Open source CapCut alternative.
TypeScript
"use client";
import { useQueryClient } from "@tanstack/react-query";
import { CHAT_RUNTIME } from "@/cut/lib/chatRuntime";
import { useHostReady } from "@/cut/lib/hostBridge";
import { useCutMode } from "@/cut/lib/backend/hooks";
import { usePhoneInbox } from "@/cut/hooks/usePhoneInbox";
import { useTabTitle } from "@/cut/hooks/useTabTitle";
import { useHostCommands } from "@/cut/lib/hostCommands";
import { useEnvironment } from "@/cut/lib/environment";
import { useCallback, useEffect, useRef, useState } from "react";
import Link from "next/link";
import { Clapperboard, Laptop, Loader2, X } from "lucide-react";
import { useTranslations } from "next-intl";
import { useDescribeError } from "@/i18n/describeError";
import { Button } from "@/components/ui/button";
import {
apiFetch,
bindCutMode,
getBackend,
hasLocalCompute,
releaseCutMode,
subscribeCutMode,
} from "@/cut/lib/backend";
import { knownDocVersion } from "@/cut/lib/backend/cloud";
import { loadedDocVersion } from "@/cut/lib/backend/shared";
import { flushCachedDocWrites, writeCachedDoc, writeCachedDocDirty } from "@/cut/lib/docCache";
import { refreshProjectPreviews } from "@/cut/lib/exportClient";
import { captureRenderSnapshot, renderDoc, type ExportDoc } from "@/cut/lib/renderSnapshot";
import { projectOperation, type ProjectOperation } from "@/cut/lib/projectOperation";
import { createPreviewQueue } from "@/cut/lib/previewQueue";
import { EMPTY_LIBRARY, fileZoneAt, hasRefDrag, parseMentions, refCandidatesOf } from "@/cut/lib/assetRef";
import { placeRefAtPlayhead } from "@/cut/lib/refPlace";
import { copyTimelineSelection, pasteCutPayload, payloadFromHtml } from "@/cut/lib/cutClipboard";
import { useLibrary } from "@/cut/lib/queries";
import { copyableRefs } from "@/cut/lib/refCopy";
import { startUpload } from "@/cut/lib/importQueue";
import { checkImportRoom } from "@/cut/lib/importRoom";
import { enrichAsset, importFileToProject, isMediaFile, prepareImport } from "@/cut/lib/media";
import { isLinkedFile, uploadLinkedFile } from "@/cut/lib/linkedLibrary";
import { copiedFrameFile, hasCopiedFrame } from "@/cut/lib/stageFrame";
// Side-effect import: registers the brief-to-video resume subscription, so a
// persisted run resumes on project load even when the AI panel never mounts.
import "@/cut/lib/genScene";
// Side-effect import: registers the bundled Google font families (build-time
// self-hosted) into the shared font registry before any text renders.
import "@/cut/lib/googleFonts";
import { syncFontAssets } from "@/cut/lib/fontAssets";
import { syncLinkedLibrary } from "@/cut/lib/linkedLibrary";
import { reportActivity } from "@/cut/lib/tabActivity";
import { TabStatus } from "./TabStatus";
import { installDevHooks } from "@/cut/lib/devHooks";
import { startPerfLog, stopPerfLog } from "@/cut/lib/perfLog";
import { meterMainThread, meterPerf, stopMainThreadMeter, stopMeter } from "@/cut/lib/perfTrace";
import { isDragActive } from "@/cut/lib/drag";
import { track } from "@/lib/analytics";
import { ensureCloudThreads } from "@/cut/lib/chatCloud";
import { nextSyncMs } from "@/cut/lib/syncCadence";
import { registerEditorSave, editorChatActive, editorToolsActive, finishEditorWork, holdEditorLoad } from "@/cut/lib/editorWork";
import { noteProjectRevision, projectRevision } from "@/cut/lib/projectRevision";
import { readProjectThreads, writeActiveChat } from "@/cut/lib/chatThreads";
import { backTarget, useCutBase } from "@/cut/lib/nav";
import { useOnboardingCover } from "@/cut/lib/onboarding";
import { onboardingStage } from "@/lib/onboarding/stage";
import { onboardingQueryKey, type OnboardingState } from "@/queries/onboarding";
import { requestSidePanel } from "@/cut/lib/panelRequest";
import { reportSwallowed } from "@/cut/lib/report";
import { resolveProjectPlacement } from "@/cut/lib/residency";
import {
dialogOnTop,
isDeleteKey,
isPasteTarget,
isTyping,
noteKey,
reportDecline,
shortcutDecline,
shortcutReached,
} from "@/cut/lib/shortcutGate";
import { docFieldsEdited, projectDuration, serializeDoc, storedAssets, timelineHMax, useEditor, clipLen, type VideoTrackPlacement } from "@/cut/lib/store";
import { fileLandingAt } from "@/cut/lib/timelineDrop";
import { landOnRow } from "@/cut/lib/laneTracks";
import { playheadAt, previewAt, skimAt, stepFrame } from "@/cut/lib/playhead";
import type { MediaAsset } from "@/cut/lib/types";
import { AiPanel } from "./AiPanel";
import type { ChatStatus } from "./ChatStatusBadge";
import { EmbeddedNewProject } from "./EmbeddedNewProject";
import { ExportDialog } from "./ExportDialog";
import { StarterTour } from "./onboarding/StarterTour";
import { Inspector, useHasInspector } from "./Inspector";
import { Lightbox } from "./Lightbox";
import { Preview } from "./Preview";
import { SidePanel } from "./SidePanel";
import { SpeedCurveStrip } from "./SpeedCurveStrip";
import { Timeline } from "./Timeline";
import { StorageUpgradeDialog } from "./StorageUpgradeDialog";
import { UpgradeDialog } from "./UpgradeDialog";
import { TopBar } from "./TopBar";
import { ViewerTopBar } from "./ViewerTopBar";
/** Bounds on the viewer's change poll. The server picks the interval inside
* this range from how long the owner has been idle; the floor keeps a live
* edit feeling live, the ceiling keeps a hidden tab or a settled project from
* polling forever. */
const VIEWER_POLL_MIN_MS = 5_000;
const VIEWER_POLL_MAX_MS = 300_000;
/** Floor between hover-proxy rebuilds. The proxy is a full render of the whole
* cut, so a session spent flipping between tabs must not spend the render pool
* on it. */
const PROXY_MIN_GAP_MS = 60_000;
export function Editor({
projectId,
from,
folder,
viewer = false,
}: {
projectId: string;
from?: string | null;
folder?: string | null;
/** Read-only share view: the share page bound the shared backend and put
* the store in read-only mode before mounting. */
viewer?: boolean;
}) {
const t = useTranslations("editor.editor");
const describeError = useDescribeError();
const [chatActivity, setChatActivity] = useState<{ projectId: string; status: ChatStatus } | null>(null);
const onChatStatusChange = useCallback((id: string, status: ChatStatus) => {
setChatActivity((current) => current?.projectId === id && current.status === status
? current : { projectId: id, status });
}, []);
const chatStatus = chatActivity?.projectId === projectId ? chatActivity.status : null;
useEffect(() => installDevHooks(), []);
// Diagnostics: the engine counts what its frames did, the main thread
// reports the frames it was blocked in — with the script that ran them —
// and a local log keeps those frames. All of it is a handful of counters
// and a browser-side observer, so it runs from the first frame for every
// account, which is what catches a freeze on open. What leaves the machine
// is perfLog's decision: a session that saw trouble, and a small random
// sample for the baseline.
useEffect(() => {
startPerfLog((batch) => track("cut_perf_log", batch));
meterPerf((sample) => track("cut_preview_perf", sample));
meterMainThread(
(sample) => track("cut_main_thread", sample),
() => {
const st = useEditor.getState();
return {
activity: st.playing ? "playing" : isDragActive() ? "dragging" : "idle",
clips: st.clips.length,
audioClips: st.audioClips.length,
overlays: st.overlays.length,
assets: st.assets.length,
};
}
);
return () => {
stopMeter();
stopMainThreadMeter();
stopPerfLog();
};
}, []);
const back = backTarget(useCutBase(), from, folder);
const loaded = useEditor((s) => s.loaded);
const loadError = useEditor((s) => s.loadFailure ?? s.loadError);
// The tab is the open project, so it wears the project's name — through
// renames too.
useTabTitle(useEditor((s) => s.projectName));
// Until loadProject runs, the store still holds the previously open project;
// rendering the editor against it would leak that project's state (chat,
// clips, selection) into this route.
const stale = useEditor((s) => s.projectId) !== projectId;
// This mount earns its first paint once its own document load begins.
const [opened, setOpened] = useState(false);
const exportOpen = useEditor((s) => s.exportOpen);
const aiOpen = useEditor((s) => s.aiOpen);
const timelineOpen = useEditor((s) => s.timelineOpen);
const sharedFeatures = useEditor((s) => s.sharedFeatures);
// The timeline's height is bounded by the window, and the window changes
// size under it: a browser resize, or the ChatGPT card leaving fullscreen.
// The clamp is for this window only, so the height the user chose stays
// saved and comes back when the window grows again.
useEffect(() => {
const clamp = () => {
const max = timelineHMax();
if (useEditor.getState().timelineH > max) useEditor.setState({ timelineH: max });
};
window.addEventListener("resize", clamp);
return () => window.removeEventListener("resize", clamp);
}, []);
const { chatgpt } = useEnvironment();
const queryClient = useQueryClient();
const cutMode = useCutMode();
// ChatGPT's edits run in this editor while it is the card.
useHostCommands(projectId, chatgpt && cutMode === "cloud");
const hasInspector = useHasInspector();
// A card is the width of a chat message: the files panel, the preview and
// the inspector do not fit side by side, and the row would spill past the
// frame's edge with nothing to scroll it back. Selecting something gives the
// inspector that room, and the rail brings the panel back.
useEffect(() => {
if (chatgpt && hasInspector) requestSidePanel(null);
}, [chatgpt, hasInspector]);
const [importing, setImporting] = useState(0);
// Files being probed and named, plus the ones already placed whose bytes are
// still going out — both are work the save indicator reports. A library file
// copying shelf-side is reported as the copy it is.
const sending = useEditor((s) =>
s.assets.reduce((n, a) => (a.upload && !a.upload.error && !a.upload.server ? n + 1 : n), 0)
);
const copying = useEditor((s) =>
s.assets.reduce((n, a) => (a.upload && !a.upload.error && a.upload.server ? n + 1 : n), 0)
);
// Bytes moving into the project are work the tab should show.
useEffect(() => {
reportActivity("import", importing + sending + copying > 0);
}, [importing, sending, copying]);
// Uploaded fonts become live FontFaces the moment their assets exist (and
// drop out when deleted), so titles set in them never measure a fallback.
const assetsForFonts = useEditor((s) => s.assets);
useEffect(() => void syncFontAssets(assetsForFonts), [assetsForFonts]);
// What the Library lends rather than copies — the account's own typefaces
// today — is in reach whichever project is open.
useEffect(() => void syncLinkedLibrary(), []);
const [conflictReloaded, setConflictReloaded] = useState(false);
const [shareGone, setShareGone] = useState(false);
// This project lives on this Mac and the Donkey app isn't answering. Nothing
// to load, and nothing to guess at either: say where it is and wait.
const [needsApp, setNeedsApp] = useState(false);
// The card holds its skeleton until one of this editor's screens is up.
useHostReady(needsApp || (!stale && (Boolean(loadError) || (opened && loaded))));
const dragDepth = useRef(0);
// Load the project document, then enrich assets (thumbs/waveforms) lazily.
// Residency is a fact about the project, not the link: resolve where the id
// lives (residency.ts) and pin the backend before anything else fetches.
// Pinning, rather than setting the ambient mode, is what makes this stick —
// the ConnectGate's engine probe finishes on its own schedule and would
// otherwise flip an open cloud project onto the engine. It is also what
// raises the gate's banner over a local project the app isn't answering for:
// the banner follows the open project's residency.
// A share view skips that — its page pinned the shared backend already.
useEffect(() => {
let alive = true;
let waiting: (() => void) | undefined;
const open = async () => {
const release = await holdEditorLoad();
if (!alive) { release(); return; }
const bind = viewer
? Promise.resolve({ mode: "shared" as const, reachable: true })
: resolveProjectPlacement(projectId).then((placement) => {
if (alive) bindCutMode(placement.mode);
return placement;
});
void bind.then(async (placement) => {
if (!alive) return;
if (placement.reachable) {
setNeedsApp(false);
setOpened(true);
await useEditor.getState().loadProject(projectId, { viewer });
return;
}
// The project is on this Mac with no app answering. The gate keeps
// probing behind its banner, so wait for that rather than retrying:
// the moment the app is back, this opens the project as if the user
// had just clicked it. Waiting on the engine here — rather than
// re-running on it — is what keeps an open cloud project from being
// re-resolved out from under its own pinned backend.
waiting = subscribeCutMode(() => {
if (!alive || !hasLocalCompute()) return;
waiting?.();
waiting = undefined;
open();
});
// The gate's probe may have reached the engine while the placement
// above was resolving — its announcement fired before this
// subscription existed. Subscribing first and then reading the
// current answer closes that gap in both orders.
if (hasLocalCompute()) {
waiting();
waiting = undefined;
open();
return;
}
setNeedsApp(true);
}).finally(release);
};
open();
// An export still rendering after a reload rejoins on its own: the app-wide
// exports dock polls the engine's job feed, so it reappears with no per-
// project reconnect here.
return () => {
alive = false;
waiting?.();
};
}, [projectId, viewer]);
// A doc that carries `firstOpen` presents itself on its first open in this
// browser: the editor reads the block and follows it — which side-panel tab
// shows (null folds the panel to its rail), whether chat opens on the
// newest saved thread, whether playback starts. Playback is held while the
// welcome slides still cover the editor, so it starts the moment they hand
// over. Applied once per browser; after this the layout is the user's own
// to keep. The seeded starter template is what ships the block today.
useEffect(() => {
if (!loaded || viewer) return;
const intro = useEditor.getState().firstOpen;
if (!intro) return;
const seenKey = `cut-first-open-${projectId}`;
if (localStorage.getItem(seenKey)) return;
localStorage.setItem(seenKey, "1");
let alive = true;
const cleanups: (() => void)[] = [];
if (intro.sidePanel !== undefined) requestSidePanel(intro.sidePanel);
if (intro.chat === true) {
// No thread named: the panel opens on a fresh empty chat.
useEditor.getState().setAiOpen(true);
} else if (intro.chat) {
// Point the chat at the named thread before the panel mounts, so it
// opens the seeded conversation rather than a blank one.
const wantedId = intro.chat;
void ensureCloudThreads(projectId).then(() => {
if (!alive) return;
const threads = readProjectThreads(projectId);
const wanted = threads.find((t) => t.id === wantedId) ?? threads[0];
if (wanted) writeActiveChat(projectId, wanted.id);
useEditor.getState().setAiOpen(true);
});
}
if (intro.play) {
// The starter tour's first step is pressing play, so playback waits for
// the person while the tour is owed.
const play = () => {
const onboarding = queryClient.getQueryData<OnboardingState>(onboardingQueryKey);
if (!chatgpt && onboardingStage(onboarding) === "tour") {
return;
}
useEditor.getState().setPlaying(true);
};
if (!useOnboardingCover.getState().up) {
play();
} else {
const unsub = useOnboardingCover.subscribe((s) => {
if (s.up) return;
unsub();
play();
});
cleanups.push(unsub);
}
}
return () => {
alive = false;
cleanups.forEach((fn) => fn());
};
}, [loaded, viewer, projectId, chatgpt, queryClient]);
// Delayed follow of the owner's edits: poll the doc version and reload on
// change, keeping the playhead. A 401/403/404 means the share was revoked or
// narrowed — stop and say so.
//
// The server sets the pace (x-cut-poll-after), because it knows how long the
// owner has been idle: an actively edited project answers in seconds, a
// settled one stretches to minutes so a shared link that a crowd is watching
// costs a handful of requests instead of six per viewer per minute. The
// response is cached at the edge for that same interval, so the poll usually
// never reaches the origin at all.
useEffect(() => {
let stopped = false;
let polling = false;
let timer: ReturnType<typeof setTimeout> | null = null;
// The owner's wait between re-reads: it widens while the stored version
// holds still and snaps back on a change, on focus, and while this tab is
// busy with its own edits, playback or chat.
let ownerMs: number = CHAT_RUNTIME.syncIntervalMs;
const tick = async () => {
if (stopped || polling) return;
polling = true;
let nextIn = document.hidden ? VIEWER_POLL_MAX_MS : (viewer ? VIEWER_POLL_MIN_MS : ownerMs);
try {
const current = useEditor.getState();
if (!document.hidden && current.projectId === projectId && current.loaded &&
!current.playing && !editorToolsActive() && !editorChatActive(projectId) && (viewer || current.saveState === "saved")) {
const res = await apiFetch(`/api/cut/projects/${projectId}`, { method: "HEAD" });
const latest = useEditor.getState();
if (stopped || latest.projectId !== projectId || !latest.loaded || latest.playing) return;
if ([401, 403, 404].includes(res.status)) {
stopped = true;
setShareGone(true);
return;
}
if (res.ok) {
const after = Number(res.headers.get("x-cut-poll-after"));
if (Number.isFinite(after) && after > 0) {
nextIn = Math.min(VIEWER_POLL_MAX_MS, Math.max(VIEWER_POLL_MIN_MS, after * 1000));
}
// Compare against the version the loaded doc reported, so a doc
// still coming from cache is fetched again on the next tick
// instead of the viewer settling on an older cut.
const version = res.headers.get("x-cut-doc-version");
const showing = viewer ? loadedDocVersion(projectId) : projectRevision(projectId);
const moved = !!version && !!showing && version !== showing;
if (!viewer) {
ownerMs = nextSyncMs(ownerMs, moved ? "moved" : "still");
nextIn = ownerMs;
}
if (moved) {
if (!viewer && (useEditor.getState().saveState !== "saved" || editorToolsActive() || editorChatActive(projectId))) return;
const at = playheadAt();
await useEditor.getState().loadProject(projectId, { inPlace: true, viewer });
if (!stopped && useEditor.getState().projectId === projectId) useEditor.getState().seek(at);
}
}
} else if (!viewer && !document.hidden) {
// Busy with its own work: the first quiet tick re-reads at the floor.
ownerMs = CHAT_RUNTIME.syncIntervalMs;
nextIn = ownerMs;
}
} catch {
// Transient network failure — the next tick retries.
} finally {
polling = false;
if (!stopped) timer = setTimeout(() => void tick(), nextIn);
}
};
const focus = () => {
if (document.hidden) return;
if (timer) clearTimeout(timer);
ownerMs = CHAT_RUNTIME.syncIntervalMs;
void tick();
};
document.addEventListener("visibilitychange", focus);
window.addEventListener("focus", focus);
timer = setTimeout(() => void tick(), viewer ? VIEWER_POLL_MIN_MS : CHAT_RUNTIME.syncIntervalMs);
return () => {
stopped = true;
document.removeEventListener("visibilitychange", focus);
window.removeEventListener("focus", focus);
if (timer) clearTimeout(timer);
};
}, [viewer, projectId]);
// A cloud save hit a newer stored version (another session's edits won).
// Take the newer doc through the ordinary load path — the GET returns it and
// rebinds the driver's version — and say so.
useEffect(() => {
if (viewer) return;
const onConflict = (e: Event) => {
const detail = (e as CustomEvent<{ projectId: string }>).detail;
if (!detail || detail.projectId !== projectId) return;
void useEditor.getState().loadProject(projectId, { inPlace: true, viewer });
setConflictReloaded(true);
};
window.addEventListener("cut-cloud-doc-conflict", onConflict);
return () => window.removeEventListener("cut-cloud-doc-conflict", onConflict);
}, [projectId, viewer]);
// Keep the project card's hover proxy — and a shared project's link-preview
// card — following the cut. Both are full renders of the whole project on the
// same worker pool the exports run on, so they wait for a lull instead of
// firing while the user is still working: every change stashes the cut as it
// stands, and it renders when the editor closes or the tab goes to the
// background. Rebuilding on each settle instead meant a session of editing
// spent most of the pool on artwork nobody was waiting for, with the user's
// own export queued behind it.
useEffect(() => {
if (viewer) return;
let closing = false;
let browserRender: AbortController | null = null;
const queue = createPreviewQueue<{ operation: ProjectOperation; doc: ExportDoc }, void>(
async ({ operation, doc }) => {
// Browser encoding yields to visible editing and ends with its page.
if (operation.residency === "browser" && (closing || document.visibilityState !== "hidden")) return;
const controller = operation.residency === "browser" ? new AbortController() : null;
browserRender = controller;
try {
await refreshProjectPreviews(captureRenderSnapshot(operation, doc), controller?.signal);
} finally {
if (browserRender === controller) browserRender = null;
}
},
PROXY_MIN_GAP_MS
);
const flush = queue.flush;
// Backgrounding the tab is the reliable signal that the user has stepped
// away — it fires on a tab switch, a window blur, and on the way out of the
// page, where an unmount alone never runs.
const onVisibility = () => {
if (document.visibilityState === "hidden") void flush();
else { closing = false; browserRender?.abort(); }
};
const onPageHide = () => { closing = true; browserRender?.abort(); void flush(true); };
document.addEventListener("visibilitychange", onVisibility);
window.addEventListener("pagehide", onPageHide);
let last: {
assets: unknown;
clips: unknown;
audioClips: unknown;
overlays: unknown;
subtitles: unknown;
aspect: string;
background: string;
} | null = null;
const unsub = useEditor.subscribe((s) => {
if (!s.loaded || s.projectId !== projectId) return;
const changed =
last !== null &&
(s.assets !== last.assets ||
s.clips !== last.clips ||
s.audioClips !== last.audioClips ||
s.overlays !== last.overlays ||
s.subtitles !== last.subtitles ||
s.aspect !== last.aspect ||
s.background !== last.background);
last = {
assets: s.assets,
clips: s.clips,
audioClips: s.audioClips,
overlays: s.overlays,
subtitles: s.subtitles,
aspect: s.aspect,
background: s.background,
};
if (!changed) return; // first tick just primes the baseline
// A cut of titles and shapes over the background has a picture to show;
// only an empty project has nothing to render a card from.
if (projectDuration(s) <= 0) return;
queue.stage({ operation: projectOperation(projectId), doc: renderDoc(s) });
});
return () => {
unsub();
document.removeEventListener("visibilitychange", onVisibility);
window.removeEventListener("pagehide", onPageHide);
closing = true;
browserRender?.abort();
void flush(true);
};
}, [projectId, viewer]);
// Autosave: debounce document changes into PUT /api/cut/projects/<id>.
useEffect(() => {
if (viewer) return () => {
useEditor.getState().closeProject(projectId);
releaseCutMode();
};
let timer: ReturnType<typeof setTimeout> | null = null;
let last = serializeDoc(useEditor.getState());
// serializeDoc copies the bars, so the store's array is the baseline: a
// parked bar changes no clip field, and comparing the copies would never
// see it.
let lastBars = useEditor.getState().transitions;
// Transient failures (the network coming back up after a laptop wake, a
// 5xx) retry on a capped backoff so unsaved work never parks on a dead
// link; 4xx (e.g. a version conflict, which has its own recovery event)
// waits for the next edit as before.
let failures = 0;
const retry = () => {
failures = Math.min(failures + 1, 5);
if (timer) clearTimeout(timer);
timer = setTimeout(() => void save(), 2000 * 2 ** (failures - 1));
};
// One save on the wire at a time: an edit landing mid-save queues one
// trailing save that captures the state as it stands then, instead of
// racing a second PUT alongside the first — the engine would apply the
// two in whichever order they arrive, and the cloud would answer the
// second with a conflict against this same session's write.
let inFlight: Promise<void> | null = null;
let queued = false;
let editSeq = 0;
const save = (): Promise<void> => {
if (inFlight) {
queued = true;
return inFlight;
}
inFlight = (async () => {
do {
queued = false;
await putDoc();
} while (queued);
})().finally(() => { inFlight = null; });
return inFlight;
};
const putDoc = async () => {
const s = useEditor.getState();
if (!s.loaded || s.projectId !== projectId) return;
s.setSaveState("saving");
const doc = serializeDoc(s);
const seqAtSend = editSeq;
try {
const res = await apiFetch(`/api/cut/projects/${projectId}`, {
method: "PUT",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(doc),
});
if (res.ok) {
const saved = await res.clone().json() as { revision?: string; version?: number; updatedAt?: number };
const revision = saved.revision ?? saved.version ?? saved.updatedAt;
if (revision !== undefined && useEditor.getState().projectId === projectId)
noteProjectRevision(projectId, String(revision));
failures = 0;
if (useEditor.getState().projectId === projectId && useEditor.getState().loadEpoch === s.loadEpoch)
useEditor.getState().setSaveState(editSeq === seqAtSend ? "saved" : "dirty");
// The snapshot the next open paints from is whatever this browser
// last put on the server, so it tracks every save.
if (editSeq === seqAtSend) writeCachedDoc(projectId, doc);
return;
}
useEditor.getState().setSaveState("error");
if (res.status >= 500) retry();
} catch {
useEditor.getState().setSaveState("error");
retry();
}
};
const unregisterSave = registerEditorSave(projectId, async () => {
if (timer) clearTimeout(timer);
if (inFlight || useEditor.getState().saveState !== "saved") await save();
const current = useEditor.getState();
if (current.projectId === projectId && (!current.loaded || current.saveState !== "saved"))
throw new Error("Save the project before continuing the video run.");
});
// Re-baselined every time a document is hydrated — the snapshot an open
// paints, the live document that replaces it, a conflict reload — so a
// document that came from the server is never saved straight back to it.
let primedEpoch = -1;
// Assets change identity on runtime enrichment (thumbs, peaks) too, so a
// new reference compares by its stored projection: field edits like an
// origin change ("Add to Media", chat tagging) must save, enrichment not.
let lastAssetsRef = useEditor.getState().assets;
let lastAssetsJson = JSON.stringify(storedAssets(lastAssetsRef));
const assetsChanged = (assets: MediaAsset[]): boolean => {
if (assets === lastAssetsRef) return false;
const json = JSON.stringify(storedAssets(assets));
const changed = json !== lastAssetsJson;
lastAssetsRef = assets;
lastAssetsJson = json;
return changed;
};
const unsub = useEditor.subscribe((s) => {
if (!s.loaded || s.projectId !== projectId) return;
if (s.loadEpoch !== primedEpoch) {
// First tick after a hydration: snapshot the freshly loaded doc so
// arriving at one never counts as an edit.
primedEpoch = s.loadEpoch;
last = serializeDoc(s);
lastBars = s.transitions;
assetsChanged(s.assets);
return;
}
// The open resumed unsaved edits from the dirty disk snapshot: the
// document on screen is already ahead of the server, so push it up
// without waiting for a fresh edit.
if (s.resumePush) {
useEditor.setState({ resumePush: false });
if (timer) clearTimeout(timer);
timer = setTimeout(() => void save(), 800);
return;
}
// Evaluated every tick (not short-circuited) so the asset baseline
// advances even when another slice triggered this save.
const assetsDirty = assetsChanged(s.assets);
const changed = assetsDirty || docFieldsEdited(s, last, lastBars);
if (!changed) return;
last = serializeDoc(s);
lastBars = s.transitions;
editSeq++;
// Every edit lands on disk marked dirty before it lands on the server,
// with the version it was edited on top of: a crash or a closed tab
// inside the debounce window resumes on the next open instead of
// losing the edit.
writeCachedDocDirty(projectId, last, knownDocVersion(projectId));
if (inFlight) queued = true;
if (s.saveState !== "saving") s.setSaveState("dirty");
if (timer) clearTimeout(timer);
timer = setTimeout(() => void save(), 800);
});
// Coalesced dirty writes land now or not at all when the page goes away.
const onPageHide = () => flushCachedDocWrites();
window.addEventListener("pagehide", onPageHide);
return () => {
if (timer) clearTimeout(timer);
window.removeEventListener("pagehide", onPageHide);
void finishEditorWork(async () => {
try {
if (useEditor.getState().projectId !== projectId) return;
if (inFlight || useEditor.getState().saveState !== "saved") await save();
useEditor.getState().closeProject(projectId);
releaseCutMode();
} finally {
unregisterSave();
unsub();
if (timer) clearTimeout(timer);
flushCachedDocWrites();
}
}).catch((error) => console.error("Could not finish saving the project:", error));
};
}, [projectId, viewer]);
// Hand the keyboard back to the editor shell. Work that finishes on its own
// — an import landing — never interrupts a sentence, so a field being typed
// in keeps the keyboard here.
const shellRef = useRef<HTMLDivElement>(null);
const focusShell = useCallback(() => {
const active = document.activeElement as HTMLElement | null;
if (isTyping(active)) return;
active?.blur();
shellRef.current?.focus({ preventScroll: true });
}, []);
// A press on the timeline is different: the editor's keys are hostage to
// whatever holds focus, and a field typed in once would hold space, ⌫ and ⌘B
// for the rest of the session — the lane gestures call preventDefault, which
// stops the browser moving focus on its own. Reaching for the timeline is
// that person leaving the field, so the shell takes the keyboard back. Only
// the timeline: everywhere else a press may well belong to the field it sits
// beside (a composer's send button, an inspector's stepper). Capture, to
// land before the gesture that swallows the press.
useEffect(() => {
const onDown = (e: PointerEvent) => {
const shell = shellRef.current;
const target = e.target;
if (!shell || !(target instanceof Element) || !target.closest("[data-tl-scroll]")) return;
const active = document.activeElement;
if (isTyping(target) || !isTyping(active) || !(active instanceof HTMLElement)) return;
active.blur();
shell.focus({ preventScroll: true });
};
window.addEventListener("pointerdown", onDown, true);
return () => window.removeEventListener("pointerdown", onDown, true);
}, []);
const importFiles = useCallback(
async (
files: FileList | File[],
opts?: {
at?: number;
origin?: MediaAsset["origin"];
mediaOnly?: boolean;
/** Display name for the asset, when the file's own name is a storage
* detail (a copied frame). */
name?: string;
/** Land at `at` itself on the first row with room, opening a new row
* when every one of them is busy there — what a paste means by "here".
* Without it the file takes track 0's next free slot. */
atFirstFit?: boolean;
/** The video row a timeline drop resolved to: the row under the
* pointer, or a new track past the stack. Clip media inserts there at
* `at`, rippling the row's later clips right, each file after the
* last; without it the file takes track 0's next free slot. */
place?: VideoTrackPlacement;
/** The audio display row a timeline drop resolved to, one past
* either edge for a new lane. Sound lands there at `at`, each file
* after the last; without it the file takes lane 0. */
audioRow?: number;
/** Media folder the import files into — the one open in the Media
* panel when the upload started. */
folderId?: string;
/** Called once per file with what became of it. A caller that holds the
* only other copy of the bytes — the phone link, whose clip is staged on
* this Mac until an editor has it — reads this to know whether it may
* let that copy go. Failure here is quiet by design for a drag and drop;
* it is not for something waiting on the answer. */
onOutcome?: (result: { file: File; assetId: string } | { file: File; failed: true }) => void;
}
) => {
// A font or a LUT dropped on the editor goes on the Library shelf, the
// way a paste of one does: it has no place on the timeline.
const linked = Array.from(files).filter(isLinkedFile);
for (const file of linked) {
void uploadLinkedFile(file)
.then(() => opts?.onOutcome?.({ file, assetId: "" }))
.catch((err) => {
reportSwallowed("[cut] shelving failed", err, file.name);
opts?.onOutcome?.({ file, failed: true });
});
}
const list = Array.from(files).filter((f) => !isLinkedFile(f));
// A run of files lands in order, each after the last; a new track is
// opened by the first and the rest join it.
let at = opts?.at;
let place = opts?.place;
let audioRow = opts?.audioRow;
// The keyboard comes back to the editor. An import is started from a
// panel control — an Upload button, a library tile, a file input the OS
// dialog hands focus back to — and whichever one it was keeps focus
// afterwards, so the first Space after an import went to that control.
// Typing is never interrupted: a focused text field keeps the keyboard.
focusShell();
// A drop that won't fit the account's cloud storage says so once, up
// front; the files still land here.
checkImportRoom(list);
setImporting((n) => n + list.length);
// What landed, by kind, for the one import report after the run.
const kinds = new Set<MediaAsset["type"]>();
let landed = 0;
// Files are probed one at a time, so a run lands in drop order. Their
// bytes go out in parallel, from the upload queue.
for (const file of list) {
try {
// The file is probed from its own header and placed now; the claim,
// the copy and the upload run behind the editor. Footage this
// browser cannot decode goes the plain way: the project converts it
// first, and the asset is built from what comes back.
const pending = await prepareImport(projectId, file);
const asset = pending?.asset ?? (await importFileToProject(projectId, file, getBackend(), "caller"));
if (!asset) {
opts?.onOutcome?.({ file, failed: true });
continue;
}
// Recordings are created media: tag them so they land on the timeline
// but never in the Media panel (reserved for user imports).
if (opts?.origin) asset.origin = opts.origin;
if (opts?.name) asset.name = opts.name;
if (opts?.folderId) asset.folderId = opts.folderId;
const s = useEditor.getState();
// Probing, naming and (for a pasted frame) rendering all outlive a
// project switch. The asset was prepared against `projectId` and its
// bytes live in that project's storage, so filing it into whatever
// document is open now would point the new project at the old one's
// media.
if (s.projectId !== projectId) {
opts?.onOutcome?.({ file, failed: true });
continue;
}
s.addAsset(asset);
// mediaOnly stocks the Media panel and leaves the timeline alone
// (drops that land outside the timeline); placement is up to the user.
if (!opts?.mediaOnly) {
if (opts?.atFirstFit) {
s.addAssetAtPlayhead(asset.id, at);
} else if (asset.type === "video" || asset.type === "image") {
if (place && at !== undefined) {
// A timeline drop inserts at the pointer on the row it was
// released over, the way every media drag lands.
const from = at;
s.addVideoFromAsset(asset.id, place, from);
const placed = useEditor.getState().clips.find((c) => c.assetId === asset.id && c.start >= from - 1e-6);
if (placed) {
at = placed.start + clipLen(placed);
place = { kind: "track", track: placed.track };
}
} else {
// An upload appends at the end. A still rides track 0 like
// footage.
s.addClipFromAsset(asset.id, at);
}
} else if (audioRow !== undefined && at !== undefined) {
// A timeline drop lands on the row it was released over, the
// way every sound drag lands, each file after the last.
const from = at;
landOnRow("audio", audioRow, (lane) =>
useEditor.getState().addAudioFromAsset(asset.id, from, { lane })
);
const next = useEditor.getState();
const placed = next.audioClips.find((c) => c.assetId === asset.id && c.start >= from - 1e-6);
if (placed) {
at = placed.start + clipLen(placed);
const used = [...new Set(next.audioClips.map((c) => c.lane ?? 0))].sort((a, b) => a - b);
audioRow = used.indexOf(placed.lane ?? 0);
}
} else {
// An upload drops at the playhead (the store slides it right
// only if that spot is taken).
s.addAudioFromAsset(asset.id, at);
}
}
// A pending import already holds its bytes, so the filmstrip is
// drawn from those rather than downloaded back from storage.
void enrichAsset(asset, pending?.localUrl);
if (pending) startUpload(projectId, pending);
kinds.add(asset.type);
landed += 1;
opts?.onOutcome?.({ file, assetId: asset.id });
} catch (err) {
reportSwallowed("[cut] import failed", err, file.name);
opts?.onOutcome?.({ file, failed: true });
} finally {
setImporting((n) => n - 1);
}
}
// The person's own files only: a recording or a copied frame carries
// an origin and is media the editor made.
if (opts?.origin || !list.length) {
return;
}
track("media_imported", {
count: landed,
failed: list.length - landed,
kinds: [...kinds],
target: opts?.mediaOnly ? "media" : "timeline",
});
},
[projectId, focusShell]
);
// Whole-window drag & drop for OS files. Chrome tags native <img> drags
// with `Files` too, so internal drags — which always carry the ref MIME —
// are filtered out; dragging a stock tile never lights the drop hints.
useEffect(() => {
if (viewer) return;
const isFileDrag = (e: DragEvent) =>
!!e.dataTransfer?.types.includes("Files") && !hasRefDrag(e);
// "media" when the drag carries at least one video/audio/image (the
// timeline is a valid target); text-only drags only concern the chat.
// Items that hide their MIME type during the drag count as media.
const dragKind = (e: DragEvent): "media" | "other" => {
const items = Array.from(e.dataTransfer?.items ?? []).filter((i) => i.kind === "file");
return items.length === 0 ||
items.some((i) => !i.type || /^(video|audio|image)\//.test(i.type))
? "media"
: "other";
};
// The video canvas joins the timeline as a place that adds to the cut: a
// drop there appends, since the canvas has no time under the pointer.
const overCanvas = (e: DragEvent) => {
const pane = document.querySelector(".preview-pane");
if (!pane) return false;
const r = pane.getBoundingClientRect();
return (
e.clientX >= r.left && e.clientX <= r.right && e.clientY >= r.top && e.clientY <= r.bottom
);
};
// The hint tracks where the files would land. Over a panel that takes them
// itself — Media, Library, a composer — nothing global lights up; that zone
// lights itself. The timeline lights only over the timeline or the canvas,
// the two places a drop joins the cut; elsewhere the drag still hints the
// chat as a target ("other").
const hintKind = (e: DragEvent): "media" | "other" | null => {
if (fileZoneAt(e.clientX, e.clientY)) return null;
if (dragKind(e) !== "media") return "other";
// The timeline says whether the point lands on it, with the same
// resolution the drop uses.
return fileLandingAt(e.clientX, e.clientY) != null || overCanvas(e) ? "media" : "other";
};
const setHint = (kind: "media" | "other" | null) => {
if (useEditor.getState().dropActive !== kind) useEditor.getState().setDropActive(kind);
};
const enter = (e: DragEvent) => {
if (!isFileDrag(e)) return;
e.preventDefault();
dragDepth.current++;
setHint(hintKind(e));
};
// Crossing between panels mid-drag fires no `dragenter` on the window, so
// the hint follows the pointer here.
const over = (e: DragEvent) => {
if (!isFileDrag(e)) return;
e.preventDefault();
setHint(hintKind(e));
};
const leave = (e: DragEvent) => {
if (!isFileDrag(e)) return;
dragDepth.current = Math.max(0, dragDepth.current - 1);
if (dragDepth.current === 0) useEditor.getState().setDropActive(null);
};
const drop = (e: DragEvent) => {
if (hasRefDrag(e) || !e.dataTransfer?.files.length) return;
e.preventDefault();
dragDepth.current = 0;
useEditor.getState().setDropActive(null);
// Files land where they were dropped: a file-taking panel (Media,
// Library, a composer) keeps them; the timeline places at the pointer;
// the canvas appends to the cut; anywhere else imports into the project
// and leaves the timeline alone.
const zone = fileZoneAt(e.clientX, e.clientY);
if (zone) {
zone(Array.from(e.dataTransfer.files));
return;
}
const landing = fileLandingAt(e.clientX, e.clientY);
if (landing) {
// The first drop on an empty timeline starts the cut at 0: a lone
// clip floating at the pointer time reads as broken.
const s = useEditor.getState();
const empty = s.clips.length === 0 && s.audioClips.length === 0;
void importFiles(e.dataTransfer.files, {
at: empty ? 0 : landing.at,
place: landing.place,
audioRow: landing.audioRow,
});
return;
}
void importFiles(e.dataTransfer.files, { mediaOnly: !overCanvas(e) });
};
window.addEventListener("dragenter", enter);
window.addEventListener("dragover", over);
window.addEventListener("dragleave", leave);
window.addEventListener("drop", drop);
return () => {
window.removeEventListener("dragenter", enter);
window.removeEventListener("dragover", over);
window.removeEventListener("dragleave", leave);
window.removeEventListener("drop", drop);
};
}, [importFiles, viewer]);
// The editor's own copies: the timeline clipboard first, then a frame
// copied off the preview canvas, which lands as a still under the
// indicator. Where it lands is read at the keystroke, so a still that waits
// on its draw or its upload still arrives where the paste was aimed. True
// when something of ours was pasted.
const pasteOwn = useCallback(
(at: number): boolean => {
if (useEditor.getState().paste()) return true;
if (!hasCopiedFrame()) return false;
void copiedFrameFile()
.then((grab) => {
if (grab) {
return importFiles([grab.file], { at, atFirstFit: true, origin: "freeze", name: grab.name });
}
})
.catch((err) => reportSwallowed("[cut] paste frame failed", err));
return true;
},
[importFiles]
);
// ⌘V is decided at the paste event, the one place the system clipboard can
// be read, so the newest copy wins whichever app made it: a recording
// copied out of Voice Memos, a screenshot, a video file from the Finder, a
// frame copied off the preview, or a timeline selection. A file that Cut
// imports lands under the indicator, on the first row with room for it. A
// composer marks its own paste handled, so this only ever sees the pastes
// nobody else wanted. The keystroke keeps its default so the event fires.
// The shelf listing a pasted mention token can name, read at the paste. The
// rest of the candidates come off the store at that moment too: nothing
// here subscribes to the timeline, so a drag on a clip never re-renders
// the editor for a paste that may never come.
const library = useLibrary({ enabled: !viewer }).data ?? EMPTY_LIBRARY;
const libraryRef = useRef(library);
useEffect(() => {
libraryRef.current = library;
}, [library]);
useEffect(() => {
if (viewer) return;
const onPaste = (e: ClipboardEvent) => {
const s = useEditor.getState();
if (e.defaultPrevented || s.readOnly) return;
// A dialog on top owns the paste, the same way it owns the shortcuts.
if (s.exportOpen || dialogOnTop()) return;
if (isPasteTarget(e.target)) return;
const at = Math.max(0, previewAt());
const pasted = Array.from(e.clipboardData?.files ?? []);
// A font or a LUT is no media for the timeline: it goes on the shelf
// and lights up in its menu, the way the Library panel takes a dropped
// one.
const linked = pasted.filter(isLinkedFile);
if (linked.length > 0) {
e.preventDefault();
for (const file of linked) {
void uploadLinkedFile(file).catch((err) =>
reportSwallowed("[cut] paste failed", err, file.name)
);
}
}
const files = pasted.filter((f) => isMediaFile(f) && !isLinkedFile(f));
if (files.length === 0) {
if (linked.length > 0) return;
// A copy made in Cut — this tab, another tab, another project — rides
// the HTML flavor whole. It is the newest copy whichever tab made it,
// so it goes ahead of this tab's own timeline clipboard; a card copy
// from this same project falls through to its tokens below.
const payload = payloadFromHtml(e.clipboardData?.getData("text/html"));
const projectId = s.projectId;
if (payload && projectId && (payload.projectId !== projectId || payload.items.length > 0)) {
e.preventDefault();
void pasteCutPayload(payload, { projectId, at, library: libraryRef.current }).catch((err) =>
reportSwallowed("[cut] paste from another project failed", err)
);
return;
}
if (pasteOwn(at)) {
e.preventDefault();
return;
}
// A ⌘C on a tile — a media card, a library card, a stock sound, a
// sticker, an effect, a shape, a transition, a template — put its
// mention token here; each one lands the way the tile's add action
// lands it. Imports run behind the editor; a run lands in copy order.
const library = libraryRef.current;
const candidates = refCandidatesOf(s, library);
const refs = parseMentions(e.clipboardData?.getData("text/plain") ?? "", candidates).refs;
if (refs.length === 0 || !projectId) return;
e.preventDefault();
void (async () => {
for (const ref of refs) {
try {
await placeRefAtPlayhead(ref, { projectId, library, at });
} catch (err) {
reportSwallowed("[cut] paste failed", err, ref.name);
}
}
})();
return;
}
e.preventDefault();
// The frame the preview copied went out to the system clipboard as a
// PNG, so it comes back here as a file like any other. It is told apart
// by its bytes and keeps its freeze origin and its name; any other file
// is a newer copy from elsewhere.
void copiedFrameFile()
.then((grab) => {
const own =
grab !== null &&
files.length === 1 &&
files[0].type === grab.file.type &&
files[0].size === grab.file.size;
return own
? importFiles([grab.file], { at, atFirstFit: true, origin: "freeze", name: grab.name })
: importFiles(files, { at, atFirstFit: true });
})
.catch((err) => reportSwallowed("[cut] paste failed", err));
};
window.addEventListener("paste", onPaste);
return () => window.removeEventListener("paste", onPaste);
}, [importFiles, pasteOwn, viewer]);
// Keyboard shortcuts.
useEffect(() => {
const onKey = (e: KeyboardEvent) => {
noteKey();
const target = e.target instanceof HTMLElement ? e.target : null;
const inputType = (target as HTMLInputElement | null)?.type;
const s = useEditor.getState();
const declined = shortcutDecline(e, { exportOpen: s.exportOpen });
if (declined) {
reportDecline(declined, e);
return;
}
// Let native toggle/slider behavior win for focused controls.
const controlFocused =
target?.tagName === "INPUT" ||
target?.closest('[role="switch"],[role="slider"]') != null;
// Space is narrower: a checkbox or a switch flips on it, so it keeps the
// key. A slider does not — it moves on the arrows — and neither does a
// scrub bar, so focus left on one of those (the transport, the zoom
// control, the seek bar the pointer last touched) must not swallow the
// one key the whole editor is played with.
const spaceTaken =
(!!inputType && ["checkbox", "radio"].includes(inputType)) ||
target?.closest('[role="switch"],[role="checkbox"]') != null;
// A read-only view keeps playback keys; everything that edits is out.
if (s.readOnly) {
const allowed =
e.code === "Space" ||
e.key === "ArrowLeft" ||
e.key === "ArrowRight" ||
e.key === "Escape" ||
((e.metaKey || e.ctrlKey) &&
e.key.toLowerCase() === "j" &&
s.sharedFeatures?.chat === true);
if (!allowed) {
reportDecline("read-only", e);
return;
}
}
shortcutReached();
// ⌘ on a Mac, Ctrl elsewhere — and never with Alt down: a Brazilian or
// European layout types its extra characters on AltGr, which Windows
// sends as ctrl+alt, so ⌘C on one of those keyboards is really ₢.
const mod = (e.metaKey || e.ctrlKey) && !e.altKey;
if (e.code === "Space" && !spaceTaken) {
e.preventDefault();
if (!s.playing && playheadAt() >= projectDuration(s) - 0.01) s.seek(0);
s.setPlaying(!s.playing);
} else if (isDeleteKey(e)) {
e.preventDefault();
s.deleteSelection();
} else if (mod && e.key.toLowerCase() === "z") {
e.preventDefault();
if (e.shiftKey) s.redo();
else s.undo();
} else if (mod && e.key.toLowerCase() === "c") {
// Selected page text keeps native ⌘C. Otherwise, alongside the
// internal copy (for ⌘V back onto the timeline), the selection's
// mention tokens go to the system clipboard, so a copied clip,
// element, transition, cue, or keyframe pastes into the chat
// composer as a reference.
if (!window.getSelection()?.toString()) {
// A card or tile under the pointer is the more deliberate pick, and
// the shared ⌘C path (lib/refCopy.ts) has already copied it off the
// same keystroke. The timeline clipboard keeps its last timeline
// copy, so ⌘V still pastes what was copied for the timeline.
if (copyableRefs().length > 0) return;
if (copyTimelineSelection()) e.preventDefault();
}
} else if (mod && e.key.toLowerCase() === "g") {
e.preventDefault();
if (e.shiftKey) s.ungroupSelection();
else s.groupSelection();
} else if (mod && e.key.toLowerCase() === "j") {
e.preventDefault();
s.setAiOpen(!s.aiOpen);
} else if (mod && e.key.toLowerCase() === "b") {
e.preventDefault();
// Cut at the skimmer when the mouse is over the timeline.
s.splitAtPlayhead(skimAt() ?? undefined);
} else if (e.key.toLowerCase() === "s" && !e.metaKey && !e.ctrlKey && !e.altKey) {
s.splitAtPlayhead(skimAt() ?? undefined);
} else if (mod && e.key === ";") {
e.preventDefault();
s.toggleGuidesShown();
} else if (e.key.toLowerCase() === "t" && !e.metaKey && !e.ctrlKey && !e.altKey) {
s.addOverlay();
} else if ((e.key === "ArrowLeft" || e.key === "ArrowRight") && !controlFocused) {
e.preventDefault();
// While playing, arrows skip in 1s jumps and playback rolls on (seek
// never pauses); paused, they step a frame — 1s with Shift — for
// precise editing.
const dir = e.key === "ArrowLeft" ? -1 : 1;
s.seek(s.playing || e.shiftKey ? playheadAt() + dir : stepFrame(playheadAt(), dir));
} else if (e.key === "Escape") {
s.select(null);
}
};
window.addEventListener("keydown", onKey);
return () => window.removeEventListener("keydown", onKey);
}, [importFiles, t]);
// Takes shot on a paired phone land in this project's media as they arrive.
usePhoneInbox(importFiles);
// The way out of a project that can't open. On the web it is the home tab
// the project was opened from; the card has no home behind it, so a new
// project opens in its place.
const leave = chatgpt ? (
<EmbeddedNewProject />
) : (
<Button
variant="outline"
nativeButton={false}
render={<Link href={back.href}>{t("backTo", { tab: back.tab })}</Link>}
/>
);
// The project is here, on this Mac — it just can't be opened without the app
// that holds it. The gate's banner sits above this with the recovery steps,
// and the moment the app answers this screen loads the project itself.
if (needsApp) {
return (
<div className="grid h-full place-items-center">
<div className="flex max-w-sm flex-col items-center gap-3 text-center">
<Laptop className="size-7 text-muted-foreground" />
<p className="text-sm text-muted-foreground">
{t("needsApp")}
</p>
{leave}
</div>
</div>
);
}
if (loadError && !stale) {
return (
<div className="grid h-full place-items-center">
<div className="flex flex-col items-center gap-3 text-center">
<Clapperboard className="size-7 text-muted-foreground" />
<p className="text-sm text-muted-foreground">{describeError(loadError)}</p>
{leave}
</div>
</div>
);
}
if (!opened || !loaded || stale) {
// The spinner waits a beat before showing: a snapshot open lands within a
// few frames, and a spinner that blinks in and out for those frames reads
// as flicker, not progress.
return (
<div className="grid h-full place-items-center text-muted-foreground">
<div className="animate-in fade-in [animation-delay:300ms] [animation-fill-mode:backwards]">
<Loader2 className="size-5 animate-spin" />
</div>
</div>
);
}
return (
// The shell tracks the window rather than flooring at a width the window
// has to scroll to reach. A floor moved the problem instead of solving it:
// the editor kept its full size and the page scrolled sideways, so the
// preview ran off the edge, the top bar measured a header wider than the
// screen and never folded its buttons away, and the chat panel opened into
// space that was not there. Shrinking, each of those resolves on its own —
// the panels give up width, the top bar collapses to a menu, and the
// timeline scrolls inside itself as it always has.
<div ref={shellRef} tabIndex={-1} className="flex h-full min-w-0 overflow-hidden outline-none">
{/* The tab wears whatever is still running here. */}
<TabStatus />
<div className="grid min-w-0 flex-1 grid-rows-[46px_minmax(0,1fr)_auto]">
{viewer ? (
<ViewerTopBar chatStatus={chatStatus} />
) : (
<TopBar
chatStatus={chatStatus}
onImport={importFiles}
from={from}
folder={folder}
uploading={importing + sending}
copying={copying}
/>
)}
{/* The inspector floats over this row rather than taking a column of
it, so the preview keeps the full width and runs under the panel. */}
<div className="relative grid min-h-0 grid-cols-[auto_minmax(0,1fr)]">
<SidePanel projectId={projectId} onImport={importFiles} importing={importing > 0} />
<div className="grid min-h-0 min-w-0">
<Preview />
</div>
<Inspector />
</div>
{/* The strip anchors to the timeline's top edge and floats over the
row above it. */}
{timelineOpen && (
<div className="relative min-w-0">
<SpeedCurveStrip />
<Timeline />
</div>
)}
</div>
{(!viewer || sharedFeatures?.chat) && !chatgpt && (
<AiPanel
key={projectId}
projectId={projectId}
visible={aiOpen}
onStatusChange={onChatStatusChange}
onClose={() => useEditor.getState().setAiOpen(false)}
/>
)}
{!viewer && !chatgpt && <StarterTour projectId={projectId} />}
{exportOpen && <ExportDialog />}
{shareGone && (
<div className="fixed top-14 left-1/2 z-50 max-w-[calc(100%-2rem)] -translate-x-1/2 rounded-full bg-foreground/90 px-3.5 py-1.5 text-center text-xs font-medium text-background shadow-lg">
{t("shareGone")}
</div>
)}
{conflictReloaded && (
<div className="fixed top-14 left-1/2 z-50 flex max-w-[calc(100%-2rem)] -translate-x-1/2 items-center gap-1.5 rounded-full bg-foreground/90 py-1.5 pr-1.5 pl-3.5 text-background shadow-lg">
<span className="text-xs font-medium">{t("conflictReloaded")}</span>
<Button
variant="ghost"
size="icon-sm"
aria-label={t("dismiss")}
className="rounded-full text-background hover:bg-background/15 hover:text-background"
onClick={() => setConflictReloaded(false)}
>
<X />
</Button>
</div>
)}
{!chatgpt && <StorageUpgradeDialog surface="editor" />}
{!chatgpt && <UpgradeDialog />}
<Lightbox />
</div>
);
}