Skip to content

Open source CapCut alternative.

TypeScript

feat(site): wear ChatGPT's theme and safe area in the card

David Lea6c91a8891b1
diff --git a/site/scripts/eval-chatgpt-widget.ts b/site/scripts/eval-chatgpt-widget.ts
index 2ad8ba96..9cf9396f 100644
--- a/site/scripts/eval-chatgpt-widget.ts
+++ b/site/scripts/eval-chatgpt-widget.ts
@@ -36,7 +36,7 @@ const server = Bun.serve({ port: 0, fetch(request) {
}
if (url.pathname === "/preview.mp4") return new Response(Bun.file(video));
if (url.pathname === "/embed" && url.searchParams.get("code") === "signed-out") return new Response('<!doctype html><div id="session"></div><script type="module" src="/session.js"></script>', { headers: { "Content-Type": "text/html" } });
- if (url.pathname === "/embed") return new Response(`<!doctype html><title>editor</title><p id="editor">Editor for ${url.searchParams.get("project")} via ${url.searchParams.get("code")}</p><p id="inset"></p><p id="mode"></p><button id="full" onclick="parent.postMessage({ type: 'donkeycut:fullscreen' }, '*')">Fullscreen</button><script>addEventListener('message', (e) => { if (e.source === parent && e.data.type === 'donkeycut:host') { document.getElementById('inset').textContent = String(e.data.insetBottom); document.getElementById('mode').textContent = e.data.displayMode; } }); parent.postMessage({ type: 'donkeycut:host?' }, '*'); setTimeout(() => parent.postMessage({ type: 'donkeycut:ready' }, '*'), parent.parent.readyMs);</script><script type="module">import { downloadFromUrl, downloadFile } from '/download.js'; window.downloadFromUrl = downloadFromUrl; window.downloadFile = downloadFile;</script>`, { headers: { "Content-Type": "text/html", "Set-Cookie": "editor-session=fixture; Path=/api/cut-cloud/; HttpOnly; SameSite=Lax" } });
+ if (url.pathname === "/embed") return new Response(`<!doctype html><title>editor</title><p id="editor">Editor for ${url.searchParams.get("project")} via ${url.searchParams.get("code")}</p><p id="inset"></p><p id="mode"></p><p id="theme"></p><button id="full" onclick="parent.postMessage({ type: 'donkeycut:fullscreen' }, '*')">Fullscreen</button><script>addEventListener('message', (e) => { if (e.source === parent && e.data.type === 'donkeycut:host') { document.getElementById('inset').textContent = String(e.data.insetBottom); document.getElementById('mode').textContent = e.data.displayMode; document.getElementById('theme').textContent = e.data.theme; } }); parent.postMessage({ type: 'donkeycut:host?' }, '*'); setTimeout(() => parent.postMessage({ type: 'donkeycut:ready' }, '*'), parent.parent.readyMs);</script><script type="module">import { downloadFromUrl, downloadFile } from '/download.js'; window.downloadFromUrl = downloadFromUrl; window.downloadFile = downloadFile;</script>`, { headers: { "Content-Type": "text/html", "Set-Cookie": "editor-session=fixture; Path=/api/cut-cloud/; HttpOnly; SameSite=Lax" } });
if (url.pathname.startsWith("/clients/chatgpt/")) return new Response(Bun.file(path.join(root, "public/clients/chatgpt", path.basename(url.pathname))));
return new Response(hostHtml, { headers: { "Content-Type": "text/html" } });
} });
@@ -116,6 +116,14 @@ try {
await app.frameLocator("iframe.editor").locator("#mode").filter({ hasText: /^fullscreen$/ }).waitFor();
await app.frameLocator("iframe.editor").locator("#inset").filter({ hasText: /^120$/ }).waitFor();
assert.deepEqual(await page.evaluate(() => (window as unknown as { modes: string[] }).modes), ["fullscreen"], "the editor's button asks for the whole window");
+ // A host in dark with a rail over the card's left edge: the card pads the
+ // rail's band, wears dark, and hands the theme to the editor.
+ await app.frameLocator("iframe.editor").locator("#theme").filter({ hasText: /^light$/ }).waitFor();
+ await page.evaluate(() => document.querySelector("iframe")!.contentWindow!.postMessage({ jsonrpc: "2.0", method: "ui/notifications/host-context-changed", params: { theme: "dark", safeAreaInsets: { top: 0, right: 0, bottom: 120, left: 72 } } }, "*"));
+ await app.frameLocator("iframe.editor").locator("#theme").filter({ hasText: /^dark$/ }).waitFor();
+ assert.equal(await app.locator("main.editing").evaluate((m) => getComputedStyle(m).paddingLeft), "72px", "the card keeps the editor out of the rail's band");
+ assert.equal(await app.locator("main.editing").evaluate((m) => getComputedStyle(m).backgroundColor), "rgb(10, 10, 10)", "the card wears the editor's dark surface");
+ assert.equal(await app.locator("iframe.editor").evaluate((f) => getComputedStyle(f).colorScheme), "dark", "the editor frame first paints in the host's scheme");
const editorFrame = page.frames().find((f) => f.url().includes("/embed?"))!;
type Downloads = { downloadFromUrl: (url: string, name: string) => void; downloadFile: (url: string, name: string) => void };
await editorFrame.waitForFunction(() => "downloadFromUrl" in window);
diff --git a/site/src/clients/chatgpt/ui/PreviewApp.tsx b/site/src/clients/chatgpt/ui/PreviewApp.tsx
index bfedb186..989c9a6d 100644
--- a/site/src/clients/chatgpt/ui/PreviewApp.tsx
+++ b/site/src/clients/chatgpt/ui/PreviewApp.tsx
@@ -1,11 +1,11 @@
import { ArtifactVideo } from "@donkeycut/artifact-player/ArtifactVideo";
import { useEffect, useRef, useState } from "react";
import { useTranslations } from "use-intl";
-import { useProjectApp } from "./useProjectApp";
+import { useProjectApp, type HostEdges, type HostTheme } from "./useProjectApp";
import "./preview.css";
export function PreviewApp() {
- const { ready, view, playback, editor, fullscreen, hostInset, error, busy, visible, run, playbackFailed, openDonkey, openFromFrame, saveFromFrame, requestFullscreen, retryEditor, createProject } = useProjectApp();
+ const { ready, view, playback, editor, fullscreen, hostInset, edges, theme, error, busy, visible, run, playbackFailed, openDonkey, openFromFrame, saveFromFrame, requestFullscreen, retryEditor, createProject } = useProjectApp();
const project = view?.project;
const preview = view?.preview;
const rendering = preview?.status === "queued" || preview?.status === "running";
@@ -18,7 +18,7 @@ export function PreviewApp() {
// home to fall back to: it says so in the editor's space and a new project
// opens there in its place.
if (view?.view === "missing") {
- return <main className="editing" data-mode={fullscreen ? "fullscreen" : "inline"} aria-busy={busy}>
+ return <main className="editing" data-mode={fullscreen ? "fullscreen" : "inline"} style={edgePadding(edges)} aria-busy={busy}>
<div className="waiting">
<p role="status">{t("deleted")}</p>
{problem && <p role="alert">{problem}</p>}
@@ -33,8 +33,8 @@ export function PreviewApp() {
// frame reports something to see.
if (view ? project && view.canEdit : !error) {
const loading = !editor || shown !== editor.url;
- return <main className="editing" data-mode={fullscreen ? "fullscreen" : "inline"} aria-busy={loading}>
- {editor && project && <EditorFrame key={editor.url} url={editor.url} name={project.name} inset={hostInset} fullscreen={fullscreen} onReady={() => setShown(editor.url)} onFullscreen={requestFullscreen} onOpen={openFromFrame} onSave={saveFromFrame} onDownloadError={setDownloadError} onReconnect={retryEditor} />}
+ return <main className="editing" data-mode={fullscreen ? "fullscreen" : "inline"} style={edgePadding(edges)} aria-busy={loading}>
+ {editor && project && <EditorFrame key={editor.url} url={editor.url} name={project.name} inset={hostInset} theme={theme} fullscreen={fullscreen} onReady={() => setShown(editor.url)} onFullscreen={requestFullscreen} onOpen={openFromFrame} onSave={saveFromFrame} onDownloadError={setDownloadError} onReconnect={retryEditor} />}
{downloadError && <div className="download-error"><p role="alert">{downloadError}</p><button onClick={() => setDownloadError(null)}>{t("dismiss")}</button></div>}
{error && project && !editor
? <div className="waiting">
@@ -76,7 +76,10 @@ export function PreviewApp() {
</main>;
}
-/** The editor's shape in its own white while it loads: the top bar, the tab
+/** Keeps the editor out of the bands the host draws over. */
+const edgePadding = (edges: HostEdges) => ({ paddingTop: edges.top, paddingRight: edges.right, paddingLeft: edges.left });
+
+/** The editor's shape in the host's theme while it loads: the top bar, the tab
* rail, the preview and the timeline, drawn as the site's skeleton slabs. */
function EditorSkeleton() {
const t = useTranslations("chatgpt.widget");
@@ -91,17 +94,17 @@ function EditorSkeleton() {
</div>;
}
-/** The editor, framed. It learns the host's display mode and how tall the
- * bottom overlay is when it loads, whenever that changes, and whenever it
+/** The editor, framed. It learns the host's display mode, its theme and how
+ * tall the bottom overlay is when it loads, whenever that changes, and whenever it
* asks; it says when it has something on screen, and its own toolbar asks
* for fullscreen, for a tab on donkeycut.com, and for the saves the sandbox
* blocks inside the frame. */
-function EditorFrame({ url, name, inset, fullscreen, onReady, onFullscreen, onOpen, onSave, onDownloadError, onReconnect }: { url: string; name: string; inset: number; fullscreen: boolean; onReady: () => void; onFullscreen: () => void; onOpen: (url: string) => void; onSave: (text: string, name: string, mimeType: string) => void; onDownloadError: (message: string | null) => void; onReconnect: () => void }) {
+function EditorFrame({ url, name, inset, theme, fullscreen, onReady, onFullscreen, onOpen, onSave, onDownloadError, onReconnect }: { url: string; name: string; inset: number; theme: HostTheme; fullscreen: boolean; onReady: () => void; onFullscreen: () => void; onOpen: (url: string) => void; onSave: (text: string, name: string, mimeType: string) => void; onDownloadError: (message: string | null) => void; onReconnect: () => void }) {
const frame = useRef<HTMLIFrameElement>(null);
const t = useTranslations("chatgpt.widget");
const origin = new URL(url).origin;
- const tell = () => frame.current?.contentWindow?.postMessage({ type: "donkeycut:host", insetBottom: inset, displayMode: fullscreen ? "fullscreen" : "inline" }, origin);
- useEffect(tell, [inset, fullscreen, origin]);
+ const tell = () => frame.current?.contentWindow?.postMessage({ type: "donkeycut:host", insetBottom: inset, theme, displayMode: fullscreen ? "fullscreen" : "inline" }, origin);
+ useEffect(tell, [inset, theme, fullscreen, origin]);
useEffect(() => {
const onMessage = (event: MessageEvent) => {
if (event.origin !== origin || event.source !== frame.current?.contentWindow) return;
diff --git a/site/src/clients/chatgpt/ui/preview.css b/site/src/clients/chatgpt/ui/preview.css
index 34d09e80..de4c7980 100644
--- a/site/src/clients/chatgpt/ui/preview.css
+++ b/site/src/clients/chatgpt/ui/preview.css
@@ -1,12 +1,15 @@
:root{font:14px/1.5 system-ui,sans-serif;color:#20201e;background:#faf9f7;color-scheme:light;--line:#dddcd6;--muted:#66645e;--panel:#fff}
:root[data-theme=dark]{color:#eeede8;background:#20201e;color-scheme:dark;--line:#45443f;--muted:#b6b3a8;--panel:#292925}
+/* The editor's own surfaces (globals.css), light and dark, so the frame and its skeleton match the editor they hold. */
+:root{--editor-bg:#fff;--editor-fg:#20201e;--editor-edge:#e5e5e5;--slab:#eaeaec;--slab-pulse:#dcdce1;--slab-highlight:#f5f5f6}
+:root[data-theme=dark]{--editor-bg:#0a0a0a;--editor-fg:#fafafa;--editor-edge:#ffffff1a;--slab:#262626;--slab-pulse:#1e1e1e;--slab-highlight:#3b3b3b}
*{box-sizing:border-box}body{margin:0}main{padding:20px;max-width:840px;margin:auto}header{display:flex;justify-content:space-between;color:var(--muted);font-size:12px}.brand{font-weight:800;font-size:16px;color:inherit}h1{font-size:22px;line-height:1.2;margin:24px 0 16px;overflow-wrap:anywhere}video{width:100%;max-height:65vh;display:block;border-radius:12px;background:#000}button{font:inherit;color:inherit;background:var(--panel);border:1px solid var(--line);border-radius:10px;padding:10px 14px;cursor:pointer}button:hover{filter:brightness(.95)}button:disabled{opacity:.5;cursor:default}button:focus-visible{outline:2px solid #5d80cc;outline-offset:3px}.primary{background:#eac36a;color:#242018;border-color:#eac36a}nav{display:flex;flex-wrap:wrap;gap:8px;margin-top:16px}.projects{display:grid;gap:8px}.projects button{display:flex;justify-content:space-between;gap:16px;text-align:left}.projects button span:first-child{overflow-wrap:anywhere;min-width:0}.muted{color:var(--muted);font-size:12px}.error{color:#ba453b}progress{width:100%;accent-color:#d8a743}p{overflow-wrap:anywhere}
-.editing{padding:0;max-width:none;position:relative;height:560px;background:#fff;color:#20201e;color-scheme:light;--line:#dddcd6;--panel:#fff}[data-mode=fullscreen].editing{height:100vh}.editor{display:block;width:100%;height:100%;border:0;background:#fff}
-.waiting,.skeleton{position:absolute;inset:0;background:#fff}.waiting{display:flex;flex-direction:column;align-items:center;justify-content:center;gap:12px;padding:20px;text-align:center}
+.editing{padding:0;max-width:none;position:relative;height:560px;background:var(--editor-bg);color:var(--editor-fg)}[data-mode=fullscreen].editing{height:100vh}.editor{display:block;width:100%;height:100%;border:0;background:var(--editor-bg)}
+.waiting,.skeleton{position:absolute;inset:0;background:var(--editor-bg)}.waiting{display:flex;flex-direction:column;align-items:center;justify-content:center;gap:12px;padding:20px;text-align:center}
.download-error{position:absolute;top:12px;left:12px;right:12px;display:flex;align-items:center;justify-content:space-between;gap:12px;padding:12px;background:var(--panel);border:1px solid var(--line);border-radius:10px}.download-error p{margin:0}
-.skeleton{display:grid;grid-template:46px minmax(0,1fr) min(272px,55%)/68px minmax(0,1fr);overflow:hidden;--edge:1px solid #e5e5e5}.bar{grid-column:1/-1;display:flex;align-items:center;gap:10px;padding:0 12px;border-bottom:var(--edge)}.bar span{flex:1}.bar .slab{height:22px;width:64px}.bar .slab:first-child{width:22px}.bar .slab:nth-child(2){width:140px}.bar .slab:last-child{width:84px}
+.skeleton{display:grid;grid-template:46px minmax(0,1fr) min(272px,55%)/68px minmax(0,1fr);overflow:hidden;--edge:1px solid var(--editor-edge)}.bar{grid-column:1/-1;display:flex;align-items:center;gap:10px;padding:0 12px;border-bottom:var(--edge)}.bar span{flex:1}.bar .slab{height:22px;width:64px}.bar .slab:first-child{width:22px}.bar .slab:nth-child(2){width:140px}.bar .slab:last-child{width:84px}
.rail{display:flex;flex-direction:column;align-items:center;gap:16px;padding-top:12px;border-right:var(--edge);overflow:hidden}.rail .slab{flex:none;width:36px;height:36px;border-radius:8px}.stage{display:grid;place-items:center;padding:16px;min-height:0}.stage .slab{height:100%;max-width:100%;aspect-ratio:16/9;border-radius:4px}
.timeline{grid-column:1/-1;display:flex;flex-direction:column;gap:10px;padding:10px 12px;border-top:var(--edge);overflow:hidden}.controls{display:flex;justify-content:center;gap:10px;margin-bottom:6px}.controls .slab{width:28px;height:22px}.track{display:flex;gap:4px;flex:none}.track .slab{height:40px;width:34%}.track .slab:last-child{width:22%}.track:nth-child(3) .slab:first-child{width:52%}.track:nth-child(4) .slab:first-child{width:18%;margin-left:12%}.track:nth-child(4) .slab:last-child{width:28%}
/* The site's skeleton (globals.css): an opaque slab breathing between two neutrals with a highlight sweeping across it. */
-.slab{display:block;position:relative;overflow:hidden;border-radius:6px;background:#eaeaec;animation:slab-pulse 1.6s ease-in-out infinite}.slab::after{content:"";position:absolute;inset:0;background:linear-gradient(90deg,#f5f5f600,#f5f5f6 50%,#f5f5f600);animation:slab-shimmer 1.6s ease-in-out infinite}
-@keyframes slab-shimmer{0%{transform:translateX(-100%)}to{transform:translateX(100%)}}@keyframes slab-pulse{0%,to{background-color:#eaeaec}50%{background-color:#dcdce1}}@media (prefers-reduced-motion:reduce){.slab,.slab::after{animation:none}}
+.slab{display:block;position:relative;overflow:hidden;border-radius:6px;background:var(--slab);animation:slab-pulse 1.6s ease-in-out infinite}.slab::after{content:"";position:absolute;inset:0;background:linear-gradient(90deg,transparent,var(--slab-highlight) 50%,transparent);animation:slab-shimmer 1.6s ease-in-out infinite}
+@keyframes slab-shimmer{0%{transform:translateX(-100%)}to{transform:translateX(100%)}}@keyframes slab-pulse{0%,to{background-color:var(--slab)}50%{background-color:var(--slab-pulse)}}@media (prefers-reduced-motion:reduce){.slab,.slab::after{animation:none}}
diff --git a/site/src/clients/chatgpt/ui/useProjectApp.ts b/site/src/clients/chatgpt/ui/useProjectApp.ts
index 0200f9a6..f2cd6166 100644
--- a/site/src/clients/chatgpt/ui/useProjectApp.ts
+++ b/site/src/clients/chatgpt/ui/useProjectApp.ts
@@ -22,6 +22,15 @@ class CardError extends Error {
}
}
+/** The host's theme, which the card and the editor it frames both wear. */
+export type HostTheme = "light" | "dark";
+
+/** The bands of the card the host draws over: its rail, its header, its
+ * composer. The card keeps the editor out of the side and top bands and hands
+ * the bottom one to the editor, which keeps its controls above it. */
+export type HostEdges = { top: number; right: number; left: number };
+const NO_EDGES: HostEdges = { top: 0, right: 0, left: 0 };
+
/** The host carries authentication; the iframe only calls the MCP Apps bridge. */
export function useProjectApp() {
const appRef = useRef<App | null>(null);
@@ -32,6 +41,8 @@ export function useProjectApp() {
const [editor, setEditor] = useState<Editor | null>(null);
const [fullscreen, setFullscreen] = useState(false);
const [hostInset, setHostInset] = useState(0);
+ const [edges, setEdges] = useState<HostEdges>(NO_EDGES);
+ const [theme, setTheme] = useState<HostTheme>("light");
const [editorRequest, setEditorRequest] = useState<string | null>(null);
const requested = useRef<string | null>(null);
const reconnecting = useRef(false);
@@ -79,12 +90,17 @@ export function useProjectApp() {
// the number and keeps its own bottom controls above the band.
const applyContext = (context: ReturnType<App["getHostContext"]>) => {
if (!context) return;
- if (context.theme) document.documentElement.dataset.theme = context.theme;
+ if (context.theme) {
+ document.documentElement.dataset.theme = context.theme;
+ setTheme(context.theme);
+ }
if (context.locale) setLocale(context.locale);
const full = context.displayMode === "fullscreen";
if (context.displayMode) setFullscreen(full);
// Measured from ChatGPT's desktop fullscreen when the host reports no inset.
setHostInset(full ? (context.safeAreaInsets?.bottom ?? 120) : 0);
+ const insets = context.safeAreaInsets;
+ setEdges(insets ? { top: insets.top, right: insets.right, left: insets.left } : NO_EDGES);
};
app.onhostcontextchanged = (context) => { applyContext({ ...app.getHostContext(), ...context }); };
void app.connect().then(() => {
@@ -197,5 +213,5 @@ export function useProjectApp() {
setHostInset(full ? (app.getHostContext()?.safeAreaInsets?.bottom ?? 120) : 0);
} catch { /* the inline card still works */ }
}, []);
- return { ready, view, playback, editor, fullscreen, hostInset, error, busy, visible, run, playbackFailed, openDonkey, openFromFrame, saveFromFrame, requestFullscreen, retryEditor, createProject };
+ return { ready, view, playback, editor, fullscreen, hostInset, edges, theme, error, busy, visible, run, playbackFailed, openDonkey, openFromFrame, saveFromFrame, requestFullscreen, retryEditor, createProject };
}
diff --git a/site/src/cut/lib/hostBridge.ts b/site/src/cut/lib/hostBridge.ts
index 37cd2676..45a823b0 100644
--- a/site/src/cut/lib/hostBridge.ts
+++ b/site/src/cut/lib/hostBridge.ts
@@ -2,14 +2,15 @@
import { useEffect, useSyncExternalStore } from "react";
import { editorHost } from "@/cut/lib/environment";
+import { wearHostTheme } from "@/lib/theme";
/**
* The ChatGPT card and the editor it frames talk over postMessage. The card
- * tells the frame which display mode the host is in and how tall the host's
- * bottom overlay is; the frame keeps its bottom controls and the timeline's
- * last rows above that band through `--host-inset-bottom`, and asks the card
- * for fullscreen from its own toolbar. Outside the card nothing is sent and
- * the variable stays unset.
+ * tells the frame which display mode and theme the host is in and how tall
+ * the host's bottom overlay is; the frame keeps its bottom controls and the
+ * timeline's last rows above that band through `--host-inset-bottom`, and
+ * asks the card for fullscreen from its own toolbar. Outside the card nothing
+ * is sent and the variable stays unset.
*
* The frame also asks the card for the two things a sandboxed frame cannot do
* itself: open a page in a tab of its own, and save a file. ChatGPT sandboxes
@@ -100,12 +101,16 @@ export function useHostBridge() {
if (editorHost() !== "chatgpt") return;
const onMessage = (event: MessageEvent) => {
if (event.source !== window.parent) return;
- const data = event.data as { type?: unknown; insetBottom?: unknown; displayMode?: unknown } | null;
+ const data = event.data as { type?: unknown; insetBottom?: unknown; theme?: unknown; displayMode?: unknown } | null;
if (data?.type !== "donkeycut:host") return;
if (typeof data.insetBottom === "number") {
const px = Math.max(0, Math.min(400, Math.round(data.insetBottom)));
document.documentElement.style.setProperty("--host-inset-bottom", `${px}px`);
}
+ // The editor wears ChatGPT's theme, so the card reads as part of it.
+ if (data.theme === "light" || data.theme === "dark") {
+ wearHostTheme(data.theme);
+ }
const mode: HostDisplayMode = data.displayMode === "fullscreen" ? "fullscreen" : "inline";
if (mode !== displayMode) { displayMode = mode; listeners.forEach((l) => l()); }
};
diff --git a/site/src/lib/theme.ts b/site/src/lib/theme.ts
index b270500c..24916184 100644
--- a/site/src/lib/theme.ts
+++ b/site/src/lib/theme.ts
@@ -38,6 +38,13 @@ function applyTheme(choice: ThemeChoice) {
}
}
+/** A host framing the page (the ChatGPT card) sets the theme for as long as
+ * the frame lives; the person's own choice stays saved for the site. */
+export function wearHostTheme(theme: "light" | "dark") {
+ applyTheme(theme);
+ listeners.forEach((l) => l());
+}
+
export function setTheme(choice: ThemeChoice) {
try {
if (isPinned(choice)) {