Skip to content

Open source CapCut alternative.

TypeScript

feat(chatgpt): the editor card opens on a white skeleton until the editor is on screen

David Leff0d78bcb9eb
diff --git a/site/scripts/eval-chatgpt-widget.ts b/site/scripts/eval-chatgpt-widget.ts
index 1cf3f4b0..2aba6357 100644
--- a/site/scripts/eval-chatgpt-widget.ts
+++ b/site/scripts/eval-chatgpt-widget.ts
@@ -14,7 +14,7 @@ const server = Bun.serve({ port: 0, fetch(request) {
const url = new URL(request.url);
if (url.pathname === "/widget") return new Response(widgetHtml(url.origin), { headers: { "Content-Type": "text/html" } });
if (url.pathname === "/preview.mp4") return new Response(Bun.file(video));
- 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?' }, '*');</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>`, { headers: { "Content-Type": "text/html" } });
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" } });
} });
@@ -22,7 +22,7 @@ const hostHtml = `<!doctype html><html><body><iframe title="Donkey Cut preview"
const frame = document.querySelector('iframe');
const project = {id:'project',name:'Launch film',revision:'cloud:2',url:'https://donkeycut.com/app/p/project'};
let count = 0, renewals = 0;
-window.calls = []; window.links = []; window.modes = []; window.editable = false; window.holdMs = 0; window.freshCard = false;
+window.calls = []; window.links = []; window.modes = []; window.editable = false; window.holdMs = 0; window.readyMs = 0; window.freshCard = false;
const view = (selected, preview = null) => ({view:selected?'project':'projects',projects:selected?[]:[project],nextCursor:null,project:selected?project:null,preview,canRender:true,canEdit:window.editable,export:null,job:null,results:[],changed:false,account:null});
// ChatGPT's sandbox drops null-valued keys before the widget sees a result.
const dropNulls = (value) => Array.isArray(value) ? value.map(dropNulls) : value && typeof value === 'object' ? Object.fromEntries(Object.entries(value).filter(([, v]) => v !== null).map(([k, v]) => [k, dropNulls(v)])) : value;
@@ -82,6 +82,7 @@ try {
await page.evaluate(() => { (window as unknown as { editable: boolean }).editable = true; });
await app.getByRole("button", { name: "Launch film" }).click();
await app.frameLocator("iframe.editor").locator("#editor").waitFor();
+ await app.locator(".skeleton").waitFor({ state: "detached" });
assert.deepEqual(await page.evaluate(() => (window as unknown as { modes: string[] }).modes), [], "an opened editor stays inline");
assert.equal(await app.locator("button").count(), 0, "the editor card has no controls of its own");
await app.frameLocator("iframe.editor").locator("#inset").filter({ hasText: /^0$/ }).waitFor();
@@ -94,26 +95,30 @@ try {
// A card rehydrated with a spent link holds the editor's space, inline and
// without controls, while it mints a fresh link. The held reply outlasts the
// stale playback's one-second renewal, so a poll would show up in the calls.
- type Host = { calls: string[]; modes: string[]; holdMs: number; freshCard: boolean };
+ type Host = { calls: string[]; modes: string[]; holdMs: number; readyMs: number; freshCard: boolean };
await page.evaluate(() => { const host = window as unknown as Host; host.calls = []; host.holdMs = 1500; });
await frame.evaluate(() => { location.reload(); });
await page.waitForFunction(() => (window as unknown as Host).calls.length === 1);
- await app.locator("div.editor").waitFor();
+ await app.locator(".skeleton").waitFor();
assert.equal(await app.locator("button").count(), 0, "a waking editor card shows no controls");
assert.equal(await app.getByText("Render preview").count(), 0, "a waking editor card shows no preview card");
await app.frameLocator("iframe.editor").locator("#editor").filter({ hasText: "one-use" }).waitFor();
await app.frameLocator("iframe.editor").locator("#mode").filter({ hasText: /^inline$/ }).waitFor();
assert.deepEqual(await page.evaluate(() => (window as unknown as Host).calls), ["open_project"], "the rehydrated card mints one fresh link and polls nothing");
assert.deepEqual(await page.evaluate(() => (window as unknown as Host).modes), ["fullscreen"], "a card that wakes up stays inline");
- // A card whose own result carries a live link opens with it, inline.
- await page.evaluate(() => { const host = window as unknown as Host; host.calls = []; host.holdMs = 0; host.freshCard = true; });
+ // A card whose own result carries a live link opens with it, inline, and
+ // its skeleton covers the frame until the editor says it is on screen.
+ await page.evaluate(() => { const host = window as unknown as Host; host.calls = []; host.holdMs = 0; host.readyMs = 1000; host.freshCard = true; });
await frame.evaluate(() => { location.reload(); });
await app.frameLocator("iframe.editor").locator("#editor").filter({ hasText: "via card" }).waitFor();
+ assert.equal(await app.locator(".skeleton").count(), 1, "the skeleton holds until the editor is ready");
+ await page.screenshot({ path: "/tmp/donkey-chatgpt-widget-skeleton.png" });
+ await app.locator(".skeleton").waitFor({ state: "detached" });
await app.frameLocator("iframe.editor").locator("#mode").filter({ hasText: /^inline$/ }).waitFor();
assert.deepEqual(await page.evaluate(() => (window as unknown as Host).modes), ["fullscreen"], "a newly opened card opens inline");
assert.deepEqual(await page.evaluate(() => (window as unknown as Host).calls), [], "a live link needs no second call");
assert.deepEqual(errors, []);
- console.log("PASS: project selection, repeated polling, native playback, URL recovery, hidden pause, Open in Donkey Cut, editor in the card, waking editor card, decoder teardown, lazy HLS.");
+ console.log("PASS: project selection, repeated polling, native playback, URL recovery, hidden pause, Open in Donkey Cut, editor in the card, skeleton until ready, waking editor card, decoder teardown, lazy HLS.");
} finally {
await browser.close(); server.stop(true); await rm(scratch, { recursive: true, force: true });
}
diff --git a/site/src/clients/chatgpt/server/embed.ts b/site/src/clients/chatgpt/server/embed.ts
index d0c1eaec..837f8fb5 100644
--- a/site/src/clients/chatgpt/server/embed.ts
+++ b/site/src/clients/chatgpt/server/embed.ts
@@ -1,6 +1,5 @@
import { serializeSignedCookie } from "better-call";
import { auth } from "@/lib/auth";
-import { rateLimitResponse } from "@/lib/inference/rate-limit";
import { chatgptConfig } from "@/clients/chatgpt/server/config";
import {
enforceOAuthUserLimit,
@@ -11,6 +10,25 @@ import { recordEditorSession, redeemEditorCode } from "@/clients/chatgpt/server/
const NO_STORE_HEADERS = { "Cache-Control": "no-store", Pragma: "no-cache" };
+/**
+ * A page the frame shows in place of the editor. The card draws the editor's
+ * skeleton over the frame until the frame says it has something to show, so
+ * every answer here is either the editor or a page that says so.
+ */
+function refusal(message: string, status: number, retryAfter?: string) {
+ const page = `<!doctype html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>Donkey Cut</title></head><body style="margin:0;min-height:100vh;display:grid;place-items:center;padding:24px;box-sizing:border-box;background:#fff;color:#737373;font:14px/1.5 system-ui,sans-serif;text-align:center"><p>${message}</p><script>parent.postMessage({ type: "donkeycut:ready" }, "*")</script></body></html>`;
+ return new Response(page, {
+ status,
+ headers: {
+ ...NO_STORE_HEADERS,
+ ...(retryAfter && { "Retry-After": retryAfter }),
+ "Content-Type": "text/html; charset=utf-8",
+ },
+ });
+}
+
+const TOO_MANY = "Too many requests. Try again in a minute.";
+
/**
* GET /api/chatgpt/embed?code=…&project=…: the card's frame redeems its one-use
* code for a session and lands on the editor. The session cookie is
@@ -18,29 +36,29 @@ const NO_STORE_HEADERS = { "Cache-Control": "no-store", Pragma: "no-cache" };
* own sign-in never crosses into the frame, and the frame's never leaves it.
*/
export async function embedEndpoint(request: Request) {
- const config = await chatgptConfig();
- if (!config.enabled) {
- return new Response("ChatGPT connection is not enabled.", { status: 503, headers: NO_STORE_HEADERS });
+ try {
+ return await redeem(request);
+ } catch (error) {
+ console.error("[chatgpt] embed redeem failed", error);
+ return refusal("Donkey Cut could not open the editor. Open the project again from ChatGPT.", 500);
}
+}
+
+async function redeem(request: Request) {
+ const config = await chatgptConfig();
+ if (!config.enabled) return refusal("ChatGPT connection is not enabled.", 503);
const limited = limitOAuthSource(request, "embed", config.oauthRequestsPerIpMinute);
- if (limited) return limited;
+ if (limited) return refusal(TOO_MANY, 429, limited.headers.get("Retry-After") ?? undefined);
const params = new URL(request.url).searchParams;
const project = params.get("project") ?? "";
- if (!/^[A-Za-z0-9_-]{1,128}$/.test(project)) {
- return new Response("Bad request.", { status: 400, headers: NO_STORE_HEADERS });
- }
+ if (!/^[A-Za-z0-9_-]{1,128}$/.test(project)) return refusal("Bad request.", 400);
const redeemed = await redeemEditorCode(params.get("code") ?? "", config);
- if (!redeemed) {
- return new Response("This editor link has expired. Open the project again from ChatGPT.", {
- status: 403,
- headers: { ...NO_STORE_HEADERS, "Content-Type": "text/plain; charset=utf-8" },
- });
- }
+ if (!redeemed) return refusal("This editor link has expired. Open the project again from ChatGPT.", 403);
try {
enforceOAuthUserLimit(redeemed.userId, "embed", config.requestsPerMinute);
} catch (error) {
- if (error instanceof OAuthRateLimitError) return rateLimitResponse(error.retryAfterSeconds);
+ if (error instanceof OAuthRateLimitError) return refusal(TOO_MANY, 429, String(error.retryAfterSeconds));
throw error;
}
diff --git a/site/src/clients/chatgpt/ui/PreviewApp.tsx b/site/src/clients/chatgpt/ui/PreviewApp.tsx
index 067cb069..9a21b3f8 100644
--- a/site/src/clients/chatgpt/ui/PreviewApp.tsx
+++ b/site/src/clients/chatgpt/ui/PreviewApp.tsx
@@ -1,5 +1,5 @@
import { ArtifactVideo } from "@donkeycut/artifact-player/ArtifactVideo";
-import { useEffect, useRef } from "react";
+import { useEffect, useRef, useState } from "react";
import { useProjectApp } from "./useProjectApp";
import "./preview.css";
@@ -8,18 +8,25 @@ export function PreviewApp() {
const project = view?.project;
const preview = view?.preview;
const rendering = preview?.status === "queued" || preview?.status === "running";
+ // The frame whose editor has said it is on screen.
+ const [shown, setShown] = useState<string | null>(null);
// An editable project is the editor, and its own chrome carries every
// control. The card holds the editor's inline space from the first paint,
// so a card ChatGPT shows again after a reload is the editor while it
- // fetches a fresh link.
- if (view ? project && view.canEdit : !error) return <main className="editing" data-mode={fullscreen ? "fullscreen" : "inline"} aria-busy={!editor}>
- {editor && project
- ? <EditorFrame url={editor.url} name={project.name} inset={hostInset} fullscreen={fullscreen} onFullscreen={requestFullscreen} onOpen={openFromFrame} onSave={saveFromFrame} />
- : <div className="editor waiting">{error && project && <>
- <p role="alert">{error}</p>
- <button disabled={busy || !ready} onClick={retryEditor}>Try again</button>
- </>}</div>}
- </main>;
+ // fetches a fresh link. The editor's skeleton covers the frame until the
+ // 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} />}
+ {error && project && !editor
+ ? <div className="waiting">
+ <p role="alert">{error}</p>
+ <button disabled={busy || !ready} onClick={retryEditor}>Try again</button>
+ </div>
+ : loading && <EditorSkeleton />}
+ </main>;
+ }
return <main aria-busy={busy}>
<header><span className="brand">Donkey Cut</span><span>Cloud projects</span></header>
{error && <p role="alert" className="error">{error}</p>}
@@ -52,11 +59,26 @@ export function PreviewApp() {
</main>;
}
+/** The editor's shape in its own white while it loads: the top bar, the tab
+ * rail, the preview and the timeline, drawn as the site's skeleton slabs. */
+function EditorSkeleton() {
+ return <div className="skeleton" role="status" aria-label="Opening the editor">
+ <div className="bar"><i className="slab" /><i className="slab" /><span /><i className="slab" /><i className="slab" /></div>
+ <div className="rail">{[0, 1, 2, 3, 4].map((i) => <i key={i} className="slab" />)}</div>
+ <div className="stage"><i className="slab" /></div>
+ <div className="timeline">
+ <div className="controls"><i className="slab" /><i className="slab" /><i className="slab" /></div>
+ {[0, 1, 2].map((i) => <div key={i} className="track"><i className="slab" /><i className="slab" /></div>)}
+ </div>
+ </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
- * asks; 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, onFullscreen, onOpen, onSave }: { url: string; name: string; inset: number; fullscreen: boolean; onFullscreen: () => void; onOpen: (url: string) => void; onSave: (text: string, name: string, mimeType: string) => void }) {
+ * 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 }: { url: string; name: string; inset: number; fullscreen: boolean; onReady: () => void; onFullscreen: () => void; onOpen: (url: string) => void; onSave: (text: string, name: string, mimeType: string) => void }) {
const frame = useRef<HTMLIFrameElement>(null);
const origin = new URL(url).origin;
const tell = () => frame.current?.contentWindow?.postMessage({ type: "donkeycut:host", insetBottom: inset, displayMode: fullscreen ? "fullscreen" : "inline" }, origin);
@@ -65,6 +87,7 @@ function EditorFrame({ url, name, inset, fullscreen, onFullscreen, onOpen, onSav
const onMessage = (event: MessageEvent) => {
if (event.origin !== origin || event.source !== frame.current?.contentWindow) return;
if (event.data?.type === "donkeycut:host?") tell();
+ if (event.data?.type === "donkeycut:ready") onReady();
if (event.data?.type === "donkeycut:fullscreen") onFullscreen();
// The frame is the editor on this origin, so what it asks to open is
// the editor's own link — a project page, an export, the post a clip
diff --git a/site/src/clients/chatgpt/ui/preview.css b/site/src/clients/chatgpt/ui/preview.css
index 0a6dd33c..0e899635 100644
--- a/site/src/clients/chatgpt/ui/preview.css
+++ b/site/src/clients/chatgpt/ui/preview.css
@@ -1,5 +1,11 @@
: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}
*{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}.editor{display:block;width:100%;height:560px;border:0;background:#000}[data-mode=fullscreen] .editor{height:100vh}
-.waiting{--panel:#292925;--line:#45443f;color:#eeede8;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:#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}
+.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}
+.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}}
diff --git a/site/src/cut/components/Editor.tsx b/site/src/cut/components/Editor.tsx
index aa3fd5d9..fd5b75d9 100644
--- a/site/src/cut/components/Editor.tsx
+++ b/site/src/cut/components/Editor.tsx
@@ -1,7 +1,7 @@
"use client";
import { chatRuntime } from "@/cut/lib/chatRuntime";
-import { useHostBridge } from "@/cut/lib/hostBridge";
+import { useHostBridge, useHostReady } from "@/cut/lib/hostBridge";
import { useCutMode } from "@/cut/lib/backend/hooks";
import { usePhoneInbox } from "@/cut/hooks/usePhoneInbox";
import { useHostCommands } from "@/cut/lib/hostCommands";
@@ -222,6 +222,8 @@ export function Editor({
// 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.
diff --git a/site/src/cut/components/RequireSession.tsx b/site/src/cut/components/RequireSession.tsx
index 64920011..cac7efa6 100644
--- a/site/src/cut/components/RequireSession.tsx
+++ b/site/src/cut/components/RequireSession.tsx
@@ -3,7 +3,7 @@ import { bindChatRuntime, bindCutClip, bindCutJudge } from "@/cut/lib/chatRuntim
import { useEffect, type ReactNode } from "react";
import { useEnvironment } from "@/cut/lib/environment";
-import { openExternal, projectPageUrl } from "@/cut/lib/hostBridge";
+import { openExternal, projectPageUrl, useHostReady } from "@/cut/lib/hostBridge";
import { authHrefFor } from "@/app/_components/landing/useAppEntryHref";
import {
@@ -75,9 +75,12 @@ export function RequireSession({ children }: { children: ReactNode }) {
return <>{children}</>;
}
+// Above the app's loading cover, which waits on an account this frame never
+// gets.
function EmbeddedSignInFallback() {
+ useHostReady(true);
return (
- <div className="fixed inset-0 z-50 grid place-items-center bg-background p-6 text-center">
+ <div className="fixed inset-0 z-[60] grid place-items-center bg-background p-6 text-center">
<div className="max-w-sm space-y-3">
<p className="text-sm text-muted-foreground">
This browser keeps the editor signed out inside ChatGPT.
diff --git a/site/src/cut/lib/hostBridge.ts b/site/src/cut/lib/hostBridge.ts
index 6e990338..b33c10f0 100644
--- a/site/src/cut/lib/hostBridge.ts
+++ b/site/src/cut/lib/hostBridge.ts
@@ -60,6 +60,21 @@ export function saveThroughHost(text: string, name: string, mimeType: string): b
return true;
}
+/**
+ * The card draws the editor's skeleton over the frame until the frame says
+ * there is something to see: the editor, or why it cannot open. A crash
+ * reaches the page as an uncaught error and replaces whatever was loading, so
+ * it shows the frame too.
+ */
+const announceReady = () => window.parent.postMessage({ type: "donkeycut:ready" }, "*");
+if (typeof window !== "undefined" && editorHost() === "chatgpt") window.addEventListener("error", announceReady);
+
+export function useHostReady(ready: boolean) {
+ useEffect(() => {
+ if (ready && editorHost() === "chatgpt") announceReady();
+ }, [ready]);
+}
+
/** The project on donkeycut.com: this page without the frame's embed flag. */
export function projectPageUrl(): string {
const url = new URL(window.location.href);