Skip to content

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

8.7 KB
Raw Blame
// Empty state for the editor's preview.
//
// Import video + load project + drag/drop on top of the project store: a
// "no project" branch offers `createProject` + `loadProject`, and a
// "has project, no asset" branch offers the file picker + load (for the rare
// user who already has a .openscreen project without media attached).
//
// ponytail: the actions map to project-store operations rather than the
// `nativeBridgeClient.project.*` ones, which this shell no longer uses. The
// deprecated editor and its own `EditorEmptyState` were deleted in 1320121d,
// so this is the single render path for the feature.

import { AlertCircle, Circle, Film, FolderOpen, Upload, X } from "lucide-react";
import { useCallback, useRef, useState } from "react";
import { Dialog, DialogContent, DialogHeader, DialogTitle } from "@/components/ui/dialog";
import { useScopedT } from "@/contexts/I18nContext";
import { useProjectStore } from "@/lib/ai-edition/store/projectStore";
import { importProjectFile } from "./importProjectFile";
import styles from "./NewEditorShell.module.css";

type DropError = "unsupported-format" | "load-failed" | null;

interface EditorEmptyStateProps {
	/** True when a project exists (so the copy becomes "add a video" not "no project"). */
	hasProject: boolean;
	/** Show the file dialog (Open Video) and a Load Project button when no project is loaded. */
	showLoadProjectButton?: boolean;
	/** Switches the editor to its Record mode. With it, recording leads the first-run screen, the
	 *  way it does in a screen recorder; without it (a project that only lacks media), import does. */
	onRecord?: () => void;
}

export function EditorEmptyState({
	hasProject,
	showLoadProjectButton = true,
	onRecord,
}: EditorEmptyStateProps) {
	const t = useScopedT("editor");
	const tc = useScopedT("common");
	const [isDraggingOver, setIsDraggingOver] = useState(false);
	const [dropError, setDropError] = useState<DropError>(null);
	const lastDropErrorRef = useRef<Exclude<DropError, null>>("unsupported-format");
	if (dropError !== null) {
		lastDropErrorRef.current = dropError;
	}

	const recordLeads = !hasProject && onRecord !== undefined;
	const createProject = useProjectStore((s) => s.createProject);
	const addAsset = useProjectStore((s) => s.addAsset);
	const loadProject = useProjectStore((s) => s.loadProject);

	const ensureProject = useCallback(async (): Promise<string | null> => {
		const existing = useProjectStore.getState().projectId;
		if (existing) return existing;
		const doc = await createProject(`Project ${new Date().toLocaleString()}`);
		return doc.project.id;
	}, [createProject]);

	const handleImportVideo = useCallback(async () => {
		const result = await window.electronAPI?.openVideoFilePicker?.();
		if (!result || result.canceled || !result.success || !result.path) return;
		try {
			const projectId = await ensureProject();
			if (!projectId) return;
			const label = result.name || result.path.split(/[\\/]/).pop() || "Recording";
			await addAsset(result.path, label);
		} catch (err) {
			setDropError("load-failed");
			// ponytail: surface as a console message only — the dialog above
			// already tells the user something went wrong.
			console.error("Failed to import video", err);
		}
	}, [addAsset, ensureProject]);

	// What the open-file dialog or a drop read: see importProjectFile.
	const openLoadedProject = useCallback(
		async (file: { project?: unknown; storedProjectId?: string }) => {
			const { projectId } = await importProjectFile(file.project, file.storedProjectId);
			await loadProject(projectId);
		},
		[loadProject],
	);

	const handleLoadProject = useCallback(async () => {
		try {
			const result = await window.electronAPI?.loadProjectFile?.();
			if (!result?.success || !result.project) return;
			await openLoadedProject(result);
		} catch {
			setDropError("load-failed");
		}
	}, [openLoadedProject]);

	const handleDragOver = useCallback((e: React.DragEvent) => {
		e.preventDefault();
		if (e.dataTransfer.items.length > 0) {
			setIsDraggingOver(true);
		}
	}, []);

	const handleDragLeave = useCallback((e: React.DragEvent) => {
		if (!e.currentTarget.contains(e.relatedTarget as Node)) {
			setIsDraggingOver(false);
		}
	}, []);

	const handleDrop = useCallback(
		async (e: React.DragEvent) => {
			e.preventDefault();
			setIsDraggingOver(false);
			const files = Array.from(e.dataTransfer.files);
			if (files.length === 0) return;
			const projectFile = files.find((f) => f.name.endsWith(".openscreen"));
			if (!projectFile) {
				setDropError("unsupported-format");
				return;
			}
			let filePath: string;
			try {
				filePath = window.electronAPI?.getPathForFile(projectFile) ?? "";
			} catch {
				setDropError("load-failed");
				return;
			}
			if (!filePath) {
				setDropError("load-failed");
				return;
			}
			const result = await window.electronAPI?.loadProjectFileFromPath?.(filePath);
			if (!result?.success || !result.project) {
				setDropError("load-failed");
				return;
			}
			try {
				await openLoadedProject(result);
			} catch {
				setDropError("load-failed");
			}
		},
		[openLoadedProject],
	);

	return (
		<div
			className={styles.previewEmptyDrop}
			onDragOver={handleDragOver}
			onDragLeave={handleDragLeave}
			onDrop={handleDrop}
		>
			{isDraggingOver ? (
				<div className={styles.previewEmptyDropOverlay}>
					<Upload className={styles.previewEmptyDropIcon} />
					<p className={styles.previewEmptyDropLabel}>{t("emptyState.dropOverlay")}</p>
				</div>
			) : null}

			<Dialog open={dropError !== null} onOpenChange={(open) => !open && setDropError(null)}>
				<DialogContent className={styles.previewEmptyDialog}>
					<DialogHeader className={styles.previewEmptyDialogHeader}>
						<div className={styles.previewEmptyDialogHeaderInner}>
							<img
								src="./openscreen.png"
								alt=""
								aria-hidden="true"
								className={styles.previewEmptyDialogLogo}
							/>
							<DialogTitle className={styles.previewEmptyDialogTitle}>
								{lastDropErrorRef.current === "unsupported-format"
									? t("emptyState.dropErrors.unsupportedFormatTitle")
									: t("emptyState.dropErrors.couldNotOpenTitle")}
							</DialogTitle>
						</div>
					</DialogHeader>
					<div className={styles.previewEmptyDialogBody}>
						<div className={styles.previewEmptyDialogIcon}>
							<AlertCircle className={styles.previewEmptyDialogAlertIcon} />
						</div>
						<p className={styles.previewEmptyDialogMessage}>
							{lastDropErrorRef.current === "unsupported-format"
								? t("emptyState.dropErrors.unsupportedFormatMessage")
								: t("emptyState.dropErrors.couldNotOpenMessage")}
						</p>
					</div>
					<button
						type="button"
						onClick={() => setDropError(null)}
						className={styles.previewEmptyDialogClose}
					>
						<X className={styles.previewEmptyDialogCloseIcon} />
						{tc("actions.close")}
					</button>
				</DialogContent>
			</Dialog>

			<div className={styles.previewEmptyInner}>
				<img src="./openscreen.png" alt="" aria-hidden="true" className={styles.previewEmptyLogo} />
				<div className={styles.previewEmptyHeading}>
					<h2 className={styles.previewEmptyTitle}>
						{hasProject ? t("emptyState.titleHasAsset") : t("emptyState.title")}
					</h2>
					<p className={styles.previewEmptyDescription}>
						{hasProject ? t("emptyState.descriptionHasAsset") : t("emptyState.description")}
					</p>
				</div>
				<div className={styles.previewEmptyActions}>
					{recordLeads ? (
						<button type="button" onClick={onRecord} className={styles.previewEmptyPrimaryButton}>
							<Circle className={styles.previewEmptyButtonIcon} fill="currentColor" />
							{t("emptyState.recordButton")}
						</button>
					) : null}
					<button
						type="button"
						onClick={() => void handleImportVideo()}
						className={
							recordLeads ? styles.previewEmptySecondaryButton : styles.previewEmptyPrimaryButton
						}
					>
						<Film className={styles.previewEmptyButtonIcon} />
						{hasProject ? t("emptyState.importVideoButton") : t("emptyState.newProjectButton")}
					</button>
					{showLoadProjectButton && !hasProject ? (
						// A link once recording leads: the third way in, and the rarest on a first run.
						<button
							type="button"
							onClick={() => void handleLoadProject()}
							className={
								recordLeads ? styles.previewEmptyLinkButton : styles.previewEmptySecondaryButton
							}
						>
							<FolderOpen className={styles.previewEmptyButtonIcon} />
							{t("emptyState.loadProjectButton")}
						</button>
					) : null}
				</div>
				<p className={styles.previewEmptyHint}>{t("emptyState.supportedFormats")}</p>
				<p className={styles.previewEmptyDragHint}>
					<Upload className={styles.previewEmptyDragHintIcon} />
					{t("emptyState.dragDropHint")}
				</p>
			</div>
		</div>
	);
}