Skip to content

Record your screen, ship a demo. Free and open-source, GPU-accelerated, no watermarks, no subscriptions. Windows, macOS, Linux. Actively maintained.

18.2 KB
Raw Blame
import {
	ChevronDown,
	CircleArrowDown,
	Download,
	FolderOpen,
	FolderPlus,
	Info,
	Keyboard,
	Languages,
	Moon,
	PanelLeft,
	Redo2,
	RefreshCw,
	Save,
	Sparkles,
	Star,
	Sun,
	Undo2,
} from "lucide-react";
import { useEffect, useRef, useState } from "react";
import logoMark from "@/assets/openscreen-mark.png";
import { Tooltip } from "@/components/ui/tooltip";
import { useI18n, useScopedT } from "@/contexts/I18nContext";
import { useShortcuts } from "@/contexts/ShortcutsContext";
import { useTheme } from "@/hooks/useTheme";
import { useUpdateBadge } from "@/hooks/useUpdateBadge";
import { getAvailableLocales, getLocaleName } from "@/i18n/loader";
import { moveMenuFocus } from "@/lib/menuKeyboard";
import { formatFirstFixedBinding } from "@/lib/shortcuts";
import { StylePresetsMenu } from "../StylePresetsMenu";
import styles from "./EditorShellV4.module.css";

export type EditorMode = "media" | "edit" | "rec";

export interface TopBarActions {
	openProject: () => void;
	newProject: () => void;
	save: () => void;
	export: () => void;
	openSettings: () => void;
	renameProject: (title: string) => void;
	toggleChat: () => void;
	openProviderSettings: () => void;
	showAbout: () => void;
	checkForUpdates: () => void;
	undo: () => void;
	redo: () => void;
}

interface EditorTopBarProps {
	mode: EditorMode;
	onModeChange: (mode: EditorMode) => void;
	projectTitle: string | null;
	dirty: boolean;
	canExport: boolean;
	canUndo: boolean;
	canRedo: boolean;
	chatOpen: boolean;
	actions: TopBarActions;
}

/** The update button's click. The main process answers at once; the dialogs or the restart that
 *  follow are its own. */
function applyUpdate() {
	void window.electronAPI?.applyUpdate?.().catch(() => {
		// The main process logs and reports its own failures.
	});
}

const MODES: Array<{ id: EditorMode; labelKey: string }> = [
	{ id: "media", labelKey: "topbar.modes.media" },
	{ id: "edit", labelKey: "topbar.modes.edit" },
	{ id: "rec", labelKey: "topbar.modes.rec" },
];

export function EditorTopBar({
	mode,
	onModeChange,
	projectTitle,
	dirty,
	canExport,
	canUndo,
	canRedo,
	chatOpen,
	actions,
}: EditorTopBarProps) {
	const t = useScopedT("editor");
	const tShortcuts = useScopedT("shortcuts");
	const tCommon = useScopedT("common");
	const { isMac } = useShortcuts();
	const savedLabel = dirty ? t("topbar.unsaved") : t("topbar.saved");
	const updateBadge = useUpdateBadge();

	// ponytail: the left side panel only renders in "edit" mode (see
	// NewEditorShell body), so its toggle is meaningless in Media/Rec —
	// hide the button (and its separator) there to keep the topbar honest.
	const showChatToggle = mode === "edit";
	return (
		<header className={styles.topbar}>
			{/* Fixed-width slot: the toggle is Edit-only, and .topbarLead holds its
			    space in the other modes so nothing to the right moves. */}
			<span className={styles.topbarLead}>
				{showChatToggle ? (
					<>
						<Tooltip content={t("topbar.toggleChatPanel")}>
							<button
								type="button"
								className={`${styles.iconBtn}${chatOpen ? ` ${styles.on}` : ""}`}
								aria-label={t("topbar.toggleChatPanel")}
								aria-pressed={chatOpen}
								onClick={actions.toggleChat}
							>
								<PanelLeft size={17} />
							</button>
						</Tooltip>
						<span className={styles.sep} aria-hidden />
					</>
				) : null}
			</span>
			<AppMenu actions={actions} />
			<span className={styles.sep} aria-hidden />
			<span className={styles.projectSlot}>
				<ProjectNameField title={projectTitle} onRename={actions.renameProject} />
				{/* The saved state, as one dot right after the name it is about. Mounted with no
				    project too, hidden, so loading one moves nothing. Save itself is in the
				    OpenScreen menu, and on Ctrl+S. */}
				<span
					className={styles.saveDot}
					data-dirty={dirty}
					data-hidden={!projectTitle}
					title={savedLabel}
				>
					<span className="sr-only">{savedLabel}</span>
				</span>
			</span>

			<div className={styles.modeSwitch} role="tablist" aria-label={t("topbar.editorMode")}>
				{MODES.map((m) => (
					<button
						key={m.id}
						type="button"
						role="tab"
						aria-selected={mode === m.id}
						// Feeds the hidden bold copy that reserves the selected width — see
						// .modeSwitch button::before.
						data-label={t(m.labelKey)}
						onClick={() => onModeChange(m.id)}
					>
						<span className={styles.modeLabel}>{t(m.labelKey)}</span>
					</button>
				))}
			</div>

			{/* A preset is the whole look the right panel's panes edit — Composition, camera,
			    cursor — so its entry sits in the bar, reachable from every pane and mode,
			    rather than in any one pane's header. */}
			{/* Always mounted, disabled when there is nothing to step to: the bar keeps its width
			    and the pair reads as the history it is. Same handlers as Ctrl+Z / Ctrl+Shift+Z. */}
			{/* `aria-disabled`, not `disabled`: a natively disabled button takes no pointer events,
			    so the tooltip could never open on it. The click does nothing while it is set. */}
			<Tooltip
				content={tShortcuts("fixedActions.undo")}
				shortcut={formatFirstFixedBinding("undo", isMac)}
			>
				<button
					type="button"
					className={styles.iconBtn}
					aria-label={tShortcuts("fixedActions.undo")}
					aria-disabled={!canUndo || undefined}
					onClick={canUndo ? actions.undo : undefined}
				>
					<Undo2 size={16} />
				</button>
			</Tooltip>
			<Tooltip
				content={tShortcuts("fixedActions.redo")}
				shortcut={formatFirstFixedBinding("redo", isMac)}
			>
				<button
					type="button"
					className={styles.iconBtn}
					aria-label={tShortcuts("fixedActions.redo")}
					aria-disabled={!canRedo || undefined}
					onClick={canRedo ? actions.redo : undefined}
				>
					<Redo2 size={16} />
				</button>
			</Tooltip>
			<StylePresetsMenu />
			{updateBadge ? (
				<Tooltip content={tCommon("actions.updateTo", { version: updateBadge.version })}>
					<button
						type="button"
						className={styles.updateBtn}
						aria-label={tCommon("actions.updateTo", { version: updateBadge.version })}
						onClick={applyUpdate}
					>
						<CircleArrowDown size={15} />
						<span className={styles.updateLabel}>{tCommon("actions.update")}</span>
					</button>
				</Tooltip>
			) : null}
			<button
				type="button"
				className={styles.exportBtn}
				aria-label={t("topbar.export")}
				onClick={actions.export}
				disabled={!canExport}
			>
				<Download size={15} />
				<span className={styles.exportLabel}>{t("topbar.export")}</span>
			</button>
		</header>
	);
}

function ProjectNameField({
	title,
	onRename,
}: {
	title: string | null;
	onRename: (title: string) => void;
}) {
	const t = useScopedT("editor");
	const [editing, setEditing] = useState(false);
	const [draft, setDraft] = useState(title ?? "");

	const startEditing = () => {
		setDraft(title ?? "");
		setEditing(true);
	};

	const commit = () => {
		setEditing(false);
		const next = draft.trim();
		if (next) onRename(next);
	};

	if (editing) {
		return (
			<input
				className={styles.projectNameInput}
				autoFocus
				value={draft}
				onFocus={(e) => e.currentTarget.select()}
				onChange={(e) => setDraft(e.target.value)}
				onBlur={commit}
				onKeyDown={(e) => {
					if (e.key === "Enter") {
						e.preventDefault();
						commit();
					} else if (e.key === "Escape") {
						setEditing(false);
					}
				}}
			/>
		);
	}

	return (
		<button
			type="button"
			className={`${styles.ghostBtn} ${styles.projectNameBtn}`}
			aria-label={t("topbar.renameProject")}
			// The label is truncated to keep the slot fixed, so the full name has to
			// stay reachable on hover.
			title={title ?? undefined}
			disabled={!title}
			onClick={startEditing}
		>
			<span className={styles.projectNameLabel}>{title ?? t("topbar.noProject")}</span>
		</button>
	);
}

/** The brand doubles as the application menu.
 *
 *  Windows and Linux have no visible menu bar to put About and the update check in: this bar
 *  IS the titlebar (createEditorWindow passes titleBarStyle:"hidden"), and the native menu is
 *  behind setAutoHideMenuBar(true) — so those two items were reachable only from the tray, or
 *  by holding Alt, which is to say not reachable. Hanging them off the wordmark is what Figma,
 *  Linear and Slack do under the same constraint.
 *
 *  It costs the bar no width, which is the reason it is the wordmark and not a new button:
 *  .modeSwitch is the only flex-shrink:1 element in the topbar, so any control added here is
 *  paid for out of the mode labels, in the most verbose of 13 locales, at the 800px minimum
 *  window width.
 *
 *  No row invents a label. Each one reuses the key of the thing it opens: `common.actions.*`
 *  for the rows electron/main.ts also builds native menu items from (About, Check for
 *  Updates), and the dialog's own title key for the rows that open a dialog (`shortcuts.title`,
 *  `editor.providerSettings.title`). That is what stops this menu from drifting away from the
 *  native menu on one side and from what its rows actually open on the other — and it is why
 *  this component adds no translation work. */
/** Shared by the mount seed and the per-open refresh below. A rejection — no preload, browser
 *  mode — resolves to "no", which hides the item rather than shipping a button whose click the
 *  main process would refuse without saying so. */
async function readUpdateVeto(cancelled: () => boolean, apply: (allowed: boolean) => void) {
	try {
		const allowed = await window.electronAPI?.canCheckForUpdatesNow?.();
		if (!cancelled()) apply(allowed === true);
	} catch {
		if (!cancelled()) apply(false);
	}
}

function AppMenu({ actions }: { actions: TopBarActions }) {
	const tCommon = useScopedT("common");
	const tEditor = useScopedT("editor");
	const tShortcuts = useScopedT("shortcuts");
	const { theme, toggle: toggleTheme } = useTheme();
	const { locale, setLocale } = useI18n();
	const [open, setOpen] = useState(false);
	// The language list unfolds inside the menu rather than in a second popover: the menu is
	// anchored inline for the no-drag reason above, and a nested surface would need the same.
	const [languagesOpen, setLanguagesOpen] = useState(false);
	const [version, setVersion] = useState<string | null>(null);
	const [canUpdate, setCanUpdate] = useState(false);
	const ref = useRef<HTMLDivElement | null>(null);
	const menuRef = useRef<HTMLDivElement | null>(null);
	const triggerRef = useRef<HTMLButtonElement | null>(null);

	// At mount: the version, which never changes while the process lives, and a first read of
	// the update veto so the item does not pop in a frame late on the first open and shove the
	// row under the pointer.
	useEffect(() => {
		let cancelled = false;
		window.electronAPI
			?.getAppInfo?.()
			.then((info) => {
				if (!cancelled) setVersion(info.version);
			})
			.catch(() => {
				// Leaves the version off the About row. The row itself still works, and the tray
				// and native menu still reach the same box, so there is nothing to report.
			});
		void readUpdateVeto(() => cancelled, setCanUpdate);
		return () => {
			cancelled = true;
		};
	}, []);

	// And again on every open, unlike the version: this answer includes the transient veto —
	// no update check mid-take — so the seed above goes stale the moment a recording starts.
	// A cached "yes" would offer a check that the main process then silently refuses.
	useEffect(() => {
		if (!open) return;
		let cancelled = false;
		void readUpdateVeto(() => cancelled, setCanUpdate);
		return () => {
			cancelled = true;
		};
	}, [open]);

	useEffect(() => {
		if (!open) setLanguagesOpen(false);
	}, [open]);

	useEffect(() => {
		if (!open) return;
		const onDocMouseDown = (e: MouseEvent) => {
			if (ref.current && !ref.current.contains(e.target as Node)) setOpen(false);
		};
		// On the document, as the dialogs do (Modals.tsx), not on the menu: a press on the menu's
		// padding or a separator drops focus to <body>, where a listener on the menu never hears
		// the key (#1015). Escape hands focus back to the trigger, and goes no further, so nothing
		// else bound to it acts on the same press.
		const onDocKeyDown = (e: KeyboardEvent) => {
			if (e.key !== "Escape") return;
			e.preventDefault();
			e.stopPropagation();
			setOpen(false);
			triggerRef.current?.focus();
		};
		document.addEventListener("mousedown", onDocMouseDown);
		document.addEventListener("keydown", onDocKeyDown);
		return () => {
			document.removeEventListener("mousedown", onDocMouseDown);
			document.removeEventListener("keydown", onDocKeyDown);
		};
	}, [open]);

	// Focus the first item as the menu appears, so it is operable from the keyboard without a
	// Tab through the whole bar first.
	useEffect(() => {
		if (!open) return;
		menuRef.current?.querySelector<HTMLButtonElement>('[role="menuitem"]')?.focus();
	}, [open]);

	const run = (action: () => void) => () => {
		// Unlike Escape, a click does not hand focus back to the trigger: the pointer user did not
		// come from there, and a focus ring appearing under the cursor reads as a bug.
		setOpen(false);
		action();
	};

	return (
		<div ref={ref} className={styles.appMenuAnchor}>
			<button
				ref={triggerRef}
				type="button"
				className={`${styles.brand} ${styles.brandBtn}`}
				aria-haspopup="menu"
				aria-expanded={open}
				aria-label="OpenScreen"
				onClick={() => setOpen((v) => !v)}
			>
				{/* Decorative: the wordmark beside it already names the app — and, being the
				    button's only text, is also its accessible name. */}
				<img src={logoMark} alt="" draggable={false} />
				<span className={styles.name}>OpenScreen</span>
				<ChevronDown size={13} className={styles.brandChevron} aria-hidden />
			</button>
			{open ? (
				<div ref={menuRef} className={styles.appMenu} role="menu" onKeyDown={moveMenuFocus}>
					{/* The file actions that used to be three icons in the bar. Their labels are the
					    keys those icons carried as tooltips; Ctrl+N / Ctrl+O / Ctrl+S still reach them
					    through the native menu's accelerators. */}
					<button
						type="button"
						role="menuitem"
						className={styles.appMenuRow}
						onClick={run(actions.newProject)}
					>
						<FolderPlus size={15} />
						{tEditor("topbar.newProject")}
					</button>
					<button
						type="button"
						role="menuitem"
						className={styles.appMenuRow}
						onClick={run(actions.openProject)}
					>
						<FolderOpen size={15} />
						{tEditor("topbar.openProject")}
					</button>
					<button
						type="button"
						role="menuitem"
						className={styles.appMenuRow}
						onClick={run(actions.save)}
					>
						<Save size={15} />
						{tEditor("topbar.saveProject")}
					</button>
					<div className={styles.appMenuSep} aria-hidden />
					<button
						type="button"
						role="menuitem"
						className={styles.appMenuRow}
						onClick={run(actions.openSettings)}
					>
						<Keyboard size={15} />
						{tShortcuts("title")}
					</button>
					{/* Settings surfaces together, above the separator. Both rows are labelled with the
					    title of the dialog they open, so neither can drift from it — and unlike the AI
					    panel's own entry points, this one is reachable in Media and Rec too, which is
					    the whole reason the dialog's open state was lifted out of LeftPanel (#420). */}
					<button
						type="button"
						role="menuitem"
						className={styles.appMenuRow}
						onClick={run(actions.openProviderSettings)}
					>
						<Sparkles size={15} />
						{tEditor("providerSettings.title")}
					</button>
					<button
						type="button"
						role="menuitem"
						className={styles.appMenuRow}
						onClick={run(toggleTheme)}
					>
						{theme === "dark" ? <Sun size={15} /> : <Moon size={15} />}
						{theme === "dark"
							? tEditor("topbar.switchToLightTheme")
							: tEditor("topbar.switchToDarkTheme")}
					</button>
					<button
						type="button"
						role="menuitem"
						className={styles.appMenuRow}
						aria-expanded={languagesOpen}
						onClick={() => setLanguagesOpen((v) => !v)}
					>
						<Languages size={15} />
						{tEditor("topbar.changeLanguage")}
						<span className={styles.appMenuVersion}>{getLocaleName(locale)}</span>
						<ChevronDown size={14} className={styles.appMenuChevron} aria-hidden />
					</button>
					{languagesOpen ? (
						<div
							className={styles.appMenuSub}
							role="group"
							aria-label={tEditor("topbar.changeLanguage")}
						>
							{getAvailableLocales().map((code) => (
								<button
									key={code}
									type="button"
									role="menuitemradio"
									aria-checked={code === locale}
									className={styles.appMenuRow}
									onClick={run(() => setLocale(code))}
								>
									{getLocaleName(code)}
								</button>
							))}
						</div>
					) : null}
					<div className={styles.appMenuSep} aria-hidden />
					{/* Only the PERMANENT half of the veto is applied here. A Store/Flathub/Snap/Nix
					    copy never offers the check at all; the transient half — not during a take —
					    stays with the main process, which re-checks it on the IPC, because this
					    window is not the one that knows a recording is running. */}
					{canUpdate ? (
						<button
							type="button"
							role="menuitem"
							className={styles.appMenuRow}
							onClick={run(actions.checkForUpdates)}
						>
							<RefreshCw size={15} />
							{tCommon("actions.checkForUpdates")}
						</button>
					) : null}
					<button
						type="button"
						role="menuitem"
						className={styles.appMenuRow}
						onClick={run(actions.showAbout)}
					>
						<Info size={15} />
						{tCommon("actions.about")}
						{version ? <span className={styles.appMenuVersion}>{version}</span> : null}
					</button>
					{/* The permanent way to reach the repo, as opposed to the one-time ask after an
					    export. Unconditional: unlike the update check above, a link to the repo root
					    is safe on every channel, the Store included. Main opens the URL, so this row
					    and the export prompt can never point at different pages. */}
					<button
						type="button"
						role="menuitem"
						className={styles.appMenuRow}
						data-testid="app-menu-star-on-github"
						onClick={run(() => {
							void window.electronAPI
								?.openRepoPage?.()
								.catch((err) => console.warn("[star] could not open the repo page:", err));
						})}
					>
						<Star size={15} />
						{tCommon("actions.starOnGithub")}
					</button>
				</div>
			) : null}
		</div>
	);
}