Edit photos by describing the change, on your own GPU. A free, open-source alternative to Nano Banana and ChatGPT image editing: photos stay on your computer, no daily limit. One installer for Windows, Mac and Linux sets up the best open model (Qwen-Image 2.1). MCP server for AI agents.
TypeScript ai-photo-editorcomfyui-alternativegenerative-fillimage-editingimage-generationinpaintinglinuxlocal-aimacosmcpmcp-servernano-banana-alternativeofflinephoto-editorprivacyqwen-imageqwen-image-2-1stable-diffusion-cppvulkanwindows
ui: job-card timing and the top bar in their own modules (no change)
Gabriele Lozuponedc93921a4523
diff --git a/src/App.tsx b/src/App.tsxindex 4812deb..6b1506b 100644--- a/src/App.tsx+++ b/src/App.tsx@@ -1,95 +1,32 @@import { getCurrentWebview } from "@tauri-apps/api/webview";-import { ArrowDownToLine, CircleHelp, EyeOff, PanelLeft, Redo2, Settings, SquarePen, Star, Undo2, X } from "lucide-react";+import { Star, X } from "lucide-react";import { useEffect, useRef, useState } from "react";import { api, configure } from "./lib/api";import { native } from "./lib/native";import {- addExampleProjects, addInputs, closeStarPrompt, dismissToast, getState, initStarPrompt, isMissingModel, newProject, openModelSetup, redoVersion, refreshLoras, refreshStatus, selectItem, setPrivateMode, setState, startEvents, startTour, submitComposer, toastError, toastInfo, undoKey, undoVersion, useStore,+ addExampleProjects, addInputs, closeStarPrompt, dismissToast, getState, initStarPrompt, redoVersion, refreshLoras, refreshStatus, selectItem, setState, startEvents, startTour, submitComposer, toastError, toastInfo, undoVersion, useStore,} from "./lib/store";-import { SilkSpin } from "./components/Cocoon";import { Composer, importPaths } from "./components/Composer";import { ExpandEditor } from "./components/ExpandEditor";import { Gallery } from "./components/Gallery";import { InpaintEditor } from "./components/InpaintEditor";import { Settings as SettingsDialog } from "./components/Settings";import { Setup } from "./components/Setup";-import { ProjectTitle, Sidebar, Wordmark } from "./components/Sidebar";+import { Sidebar } from "./components/Sidebar";import { Stage } from "./components/Stage";import { Tour } from "./components/Tour";-import { IconButton } from "./components/ui";-import { shortcut } from "./lib/platform";import { PromptTips } from "./components/PromptTips";import { Shortcuts } from "./components/Shortcuts";import { WhatsNew, whatsNewDue } from "./components/WhatsNew";import { UpscalerCompare } from "./components/Upscalers";import { KokonMark, Welcome } from "./components/Welcome";-import { BareTitleBar, WindowControls } from "./components/TitleBar";-import { autoCheckForUpdate, installUpdate } from "./lib/updates";+import { BareTitleBar } from "./components/TitleBar";+import { TopBar } from "./components/TopBar";+import { autoCheckForUpdate } from "./lib/updates";const IMAGE_EXT = /\.(png|jpe?g|webp|bmp|gif|tiff?|heic|heif)$/i;const REPO_URL = "https://github.com/GabrieleLozupone/kokon";-function StatusIndicator() {- const connected = useStore((s) => s.connected);- const server = useStore((s) => s.server);- const busy = useStore((s) => Object.values(s.jobs).some((j) => !["done", "failed", "cancelled"].includes(j.status)));- let cls = "dot";- let text = "Connecting";- let title = "";- if (connected) {- switch (server.state) {- case "ready":- cls = "dot ready";- text = busy ? "Working" : "Ready";- title = server.owned ? "Model loaded" : "Using an inference server that was already running";- break;- case "starting":- cls = "dot busy";- text = "Loading model";- break;- case "error":- cls = "dot error";- text = server.error?.message ?? "Inference server error";- title = isMissingModel(server.error) ? "Find or download the missing file" : "Open Diagnostics";- break;- default:- text = "Model not loaded";- title = "Click to load the model now";- }- }- return (- <button- className="status"- title={title}- onClick={() => {- if (server.state === "error" && isMissingModel(server.error)) openModelSetup();- else if (server.state === "error") setState({ overlay: "settings" });- else if (server.state === "stopped" && connected) api.startBackend().then(refreshStatus, toastError);- }}- >- {cls === "dot busy" || (cls === "dot ready" && busy) ? <SilkSpin size={18} /> : <span className={cls} />}- <span style={{ maxWidth: 360, overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}>{text}</span>- </button>- );-}--/** Undo / Redo between versions: back to the image the current one was made from. */-function HistoryButtons() {- const canUndo = useStore((s) => undoKey(s) !== null);- const canRedo = useStore((s) => s.redo.length > 0);- if (!canUndo && !canRedo) return null;- return (- <>- <IconButton title={`Undo: back to the previous version (${shortcut("Z")})`} onClick={undoVersion} disabled={!canUndo}>- <Undo2 size={18} />- </IconButton>- <IconButton title={`Redo (${shortcut("Y")})`} onClick={redoVersion} disabled={!canRedo}>- <Redo2 size={18} />- </IconButton>- </>- );-}-/** Same breathing mark as the HTML splash in index.html, so startup looks like one step;* a line of text appears if connecting to the local service takes a while. */function BootSplash() {@@ -106,42 +43,6 @@ function BootSplash() {);}-/** "Update" pill in the top bar once a newer release is found; one click installs it. */-function UpdatePill() {- const update = useStore((s) => s.update);- if (!update) return null;- const busy = update.phase !== "available";- const click = async () => {- const running = Object.values(getState().jobs).some((j) => !["done", "failed", "cancelled"].includes(j.status));- const msg = `Install Kokon ${update.version} now? Kokon closes and restarts in a few seconds${running ? "; the images being made now are stopped" : ""}. Your images, settings and models stay.`;- if (await native.confirm(update.notes ? `${msg}--What's new:-${update.notes}` : msg, "Update Kokon")) installUpdate();- };- const label =- update.phase === "downloading" ? `Downloading${update.progress != null ? ` ${Math.round(update.progress * 100)}%` : "…"}` : update.phase === "installing" ? "Installing…" : `Update to ${update.version}`;- return (- <button className="update-pill" onClick={click} disabled={busy} title={`Kokon ${update.version} is available`}>- <ArrowDownToLine size={14} /> {label}- </button>- );-}--function PrivateToggle() {- const on = useStore((s) => s.privateMode);- const toggle = () => setPrivateMode(!on, () => native.confirm("Turn off private mode? The images made in private mode will be deleted.", "Private mode"));- return on ? (- <button className="private-pill" onClick={toggle} title="Private mode is on: images are not saved and are deleted when you turn it off or close the app. Click to turn it off.">- <EyeOff size={15} /> Private- </button>- ) : (- <IconButton title="Private mode: nothing is saved to the gallery or your Pictures folder" onClick={toggle}>- <EyeOff size={18} />- </IconButton>- );-}-function Toasts() {const toasts = useStore((s) => s.toasts);const [open, setOpen] = useState<string | null>(null);@@ -371,38 +272,7 @@ export default function App() {<div className="app">{sidebar && !needsSetup && <Sidebar />}<div className="workspace">- <div className="topbar" data-tauri-drag-region>- <div className="brand" data-tauri-drag-region>- {(!sidebar || needsSetup) && <Wordmark />}- {!sidebar && !needsSetup && (- <>- <IconButton title="Show sidebar" onClick={() => setState({ sidebar: true })}>- <PanelLeft size={18} />- </IconButton>- <IconButton title="New image" onClick={newProject}>- <SquarePen size={18} />- </IconButton>- </>- )}- {overlay === "gallery" ? <span className="project-title">All images</span> : !needsSetup && <ProjectTitle />}- </div>- <div className="toolbar" data-tauri-drag-region>- {!needsSetup && <HistoryButtons />}- <UpdatePill />- <StatusIndicator />- {!needsSetup && <PrivateToggle />}- <IconButton title="Shortcuts (?)" onClick={() => setState({ overlay: "shortcuts" })}>- <CircleHelp size={18} />- </IconButton>- {/* Settings lives at the foot of the sidebar; here only while the sidebar is hidden. */}- {(!sidebar || needsSetup) && (- <IconButton title="Settings" onClick={() => setState({ overlay: "settings" })}>- <Settings size={18} />- </IconButton>- )}- </div>- <WindowControls />- </div>+ <TopBar /><div className="main">{needsSetup ? <Setup /> : <Stage />}{overlay === "gallery" && <Gallery />}diff --git a/src/components/Cocoon.tsx b/src/components/Cocoon.tsxindex 64b8526..fe54be9 100644--- a/src/components/Cocoon.tsx+++ b/src/components/Cocoon.tsx@@ -41,7 +41,7 @@ interface MarkLayout {h: number;}-function markLayout(w: number, h: number): MarkLayout {+export function markLayout(w: number, h: number): MarkLayout {let sh = h * 0.48;sh = Math.min(sh, (w * 0.8 * STEM_H) / 1024, (w * 0.5) / STEM_RATIO);const scale = sh / STEM_H;@@ -66,7 +66,7 @@ function mapPath(d: string, f: (x: number, y: number) => [number, number]): stri}/** The mark at `left`/`top`/`scale` with its wings grown to `up`/`down` (0..1): one path. */-function markPath(left: number, top: number, scale: number, up: number, down: number): string {+export function markPath(left: number, top: number, scale: number, up: number, down: number): string {const toPx = (x: number, y: number): [number, number] => [left + x * scale, top + y * scale];const grow = (root: [number, number], k: number) => (x: number, y: number) => toPx(root[0] + (x - root[0]) * k, root[1] + (y - root[1]) * k);return mapPath(STEM, toPx) + (up > 0.001 ? mapPath(WING_UP, grow(UP_ROOT, up)) : "") + (down > 0.001 ? mapPath(WING_DOWN, grow(DOWN_ROOT, down)) : "");@@ -79,9 +79,9 @@ const easeInOut = (v: number) => (v < 0.5 ? 4 * v * v * v : 1 - Math.pow(-2 * vconst easeOutBack = (v: number) => 1 + 2.2 * Math.pow(v - 1, 3) + 1.2 * Math.pow(v - 1, 2);/** The logo forming: the stem steps left while the wings grow (ms). */-const FORM_MS = 700;+export const FORM_MS = 700;/** Shift and wing growth at `ms` after the logo started forming. */-function formingAt(ms: number) {+export function formingAt(ms: number) {return {shift: easeInOut(clamp01(ms / FORM_MS)),up: easeOutBack(clamp01((ms - 120) / (FORM_MS - 120))),@@ -102,10 +102,10 @@ function radiusAt(u: number, m: MarkLayout): number {return Math.sqrt(Math.max(0, r * r - d * d));}-interface Thread { turns: number; dir: number; phase: number; spin: number; u0: number; u1: number; birth: number; loose: number; width: number; alpha: number; born: number | null }+export interface Thread { turns: number; dir: number; phase: number; spin: number; u0: number; u1: number; birth: number; loose: number; width: number; alpha: number; born: number | null }/** Same threads on every render: a small seeded generator. */-function makeThreads(n: number): Thread[] {+export function makeThreads(n: number): Thread[] {let seed = 0x4b6f6b6f; // "Koko"const rnd = () => {seed = (seed + 0x6d2b79f5) | 0;@@ -131,9 +131,83 @@ function makeThreads(n: number): Thread[] {}));}-const THREADS = 120;+export const THREADS = 120;const POINTS = 72;+/** One frame of the cocoon on `ctx`: `t` seconds since the card appeared, `formMs` since the+ * logo started forming (null: not yet). Threads remember when they were spun in (`born`). */+export function drawCocoon(ctx: CanvasRenderingContext2D, threads: Thread[], o: { w: number; h: number; dpr: number; ink: string; t: number; pct: number; formMs: number | null; still: boolean }) {+ const { t, still, dpr, ink } = o;+ const pctNow = o.pct;+ const size = { w: o.w, h: o.h };+ const p = clamp01(pctNow / 100);+ const formed = o.formMs !== null;+ const f = !formed ? { shift: 0, up: 0, down: 0 } : still ? { shift: 1, up: 1, down: 1 } : formingAt(o.formMs!);+ // Tightness eases in: loose orbits at the start, a closed cocoon near the end; past half+ // way the silk fills in until the cocoon is the solid stem (at ~90 %, or when forming).+ const tight = 1 - Math.pow(1 - p, 1.6);+ const solid = formed ? 1 : easeInOut(clamp01((p - 0.5) / 0.4));+ const m = markLayout(size.w, size.h);+ const left = m.leftCocoon + (m.leftLogo - m.leftCocoon) * f.shift;+ const dx = left - m.leftCocoon;+ const breathe = still ? 1 : 1 + Math.sin(t * 1.3) * 0.008 * (1 - solid);+ ctx.setTransform(dpr, 0, 0, dpr, 0, 0);+ ctx.clearRect(0, 0, size.w, size.h);+ ctx.strokeStyle = ink;+ ctx.fillStyle = ink;+ ctx.lineCap = "round";++ // The body: a faint fill that thickens with the silk, solid at the end; then the wings.+ ctx.globalAlpha = 0.025 + 0.06 * tight + (1 - 0.025 - 0.06 * tight) * solid;+ ctx.fill(new Path2D(markPath(left, m.top, m.scale, f.up, f.down)));++ const threadAlpha = 1 - solid;+ if (threadAlpha > 0.01) {+ for (const th of threads) {+ if (pctNow < th.birth && !still) continue;+ if (th.born === null) th.born = t;+ const grow = still ? 1 : Math.min(1, (t - th.born) / 1.8);+ const slack = (1 - tight) * th.loose;+ const rMul = (1 + slack * 1.1) * breathe;+ const yMul = 1 + slack * 0.35;+ const front = new Path2D();+ const back = new Path2D();+ let side = 0;+ let hx = 0;+ let hy = 0;+ for (let k = 0; k <= POINTS; k++) {+ const s = (k / POINTS) * grow;+ const u = th.u0 + (th.u1 - th.u0) * s;+ const phi = th.phase + th.dir * th.turns * Math.PI * 2 * s + th.spin * t;+ const r = radiusAt(u, m) * rMul + slack * m.w * 0.15 * Math.sin(phi * 2 + th.phase);+ const x = m.cx + dx + r * Math.cos(phi);+ const y = m.cy + u * (m.h / 2) * yMul;+ const z = Math.sin(phi) >= 0 ? 1 : -1;+ const path = z > 0 ? front : back;+ if (k === 0) path.moveTo(x, y);+ else if (z !== side) path.moveTo(hx, hy); // join front and back across the edge+ path.lineTo(x, y);+ side = z;+ hx = x;+ hy = y;+ }+ ctx.lineWidth = th.width;+ ctx.globalAlpha = th.alpha * 0.35 * threadAlpha;+ ctx.stroke(back);+ ctx.globalAlpha = th.alpha * (0.7 + 0.3 * tight) * threadAlpha;+ ctx.stroke(front);+ // The spinning end of a thread still being laid: a small glint.+ if (grow < 1) {+ ctx.globalAlpha = 0.8 * threadAlpha;+ ctx.beginPath();+ ctx.arc(hx, hy, 1.4, 0, Math.PI * 2);+ ctx.fill();+ }+ }+ }+ ctx.globalAlpha = 1;+}+/** The cocoon behind a job in progress (`pct` 0..100). For an edit the source shows in black* and white inside it, coming into focus, until the silk fills in. `form` turns the filled* cocoon into the whole logo (set just before the image is ready). */@@ -175,73 +249,9 @@ export function Cocoon({ src, pct, form, dim }: { src?: string; pct: number; forlastInk = now;}const { pct: pctNow, form: formNow } = live.current;- const p = clamp01(pctNow / 100);if (formNow && formStart === null) formStart = now;- const f = formStart === null ? { shift: 0, up: 0, down: 0 } : still ? { shift: 1, up: 1, down: 1 } : formingAt(now - formStart);if (formStart !== null && now - formStart >= FORM_MS) logoFormedAt = now;- // Tightness eases in: loose orbits at the start, a closed cocoon near the end; past half- // way the silk fills in until the cocoon is the solid stem (at ~90 %, or when forming).- const tight = 1 - Math.pow(1 - p, 1.6);- const solid = formStart !== null ? 1 : easeInOut(clamp01((p - 0.5) / 0.4));- const m = markLayout(size.w, size.h);- const left = m.leftCocoon + (m.leftLogo - m.leftCocoon) * f.shift;- const dx = left - m.leftCocoon;- const breathe = still ? 1 : 1 + Math.sin(t * 1.3) * 0.008 * (1 - solid);- ctx.setTransform(dpr, 0, 0, dpr, 0, 0);- ctx.clearRect(0, 0, size.w, size.h);- ctx.strokeStyle = ink;- ctx.fillStyle = ink;- ctx.lineCap = "round";-- // The body: a faint fill that thickens with the silk, solid at the end; then the wings.- ctx.globalAlpha = 0.025 + 0.06 * tight + (1 - 0.025 - 0.06 * tight) * solid;- ctx.fill(new Path2D(markPath(left, m.top, m.scale, f.up, f.down)));-- const threadAlpha = 1 - solid;- if (threadAlpha > 0.01) {- for (const th of threads) {- if (pctNow < th.birth && !still) continue;- if (th.born === null) th.born = t;- const grow = still ? 1 : Math.min(1, (t - th.born) / 1.8);- const slack = (1 - tight) * th.loose;- const rMul = (1 + slack * 1.1) * breathe;- const yMul = 1 + slack * 0.35;- const front = new Path2D();- const back = new Path2D();- let side = 0;- let hx = 0;- let hy = 0;- for (let k = 0; k <= POINTS; k++) {- const s = (k / POINTS) * grow;- const u = th.u0 + (th.u1 - th.u0) * s;- const phi = th.phase + th.dir * th.turns * Math.PI * 2 * s + th.spin * t;- const r = radiusAt(u, m) * rMul + slack * m.w * 0.15 * Math.sin(phi * 2 + th.phase);- const x = m.cx + dx + r * Math.cos(phi);- const y = m.cy + u * (m.h / 2) * yMul;- const z = Math.sin(phi) >= 0 ? 1 : -1;- const path = z > 0 ? front : back;- if (k === 0) path.moveTo(x, y);- else if (z !== side) path.moveTo(hx, hy); // join front and back across the edge- path.lineTo(x, y);- side = z;- hx = x;- hy = y;- }- ctx.lineWidth = th.width;- ctx.globalAlpha = th.alpha * 0.35 * threadAlpha;- ctx.stroke(back);- ctx.globalAlpha = th.alpha * (0.7 + 0.3 * tight) * threadAlpha;- ctx.stroke(front);- // The spinning end of a thread still being laid: a small glint.- if (grow < 1) {- ctx.globalAlpha = 0.8 * threadAlpha;- ctx.beginPath();- ctx.arc(hx, hy, 1.4, 0, Math.PI * 2);- ctx.fill();- }- }- }- ctx.globalAlpha = 1;+ drawCocoon(ctx, threads, { w: size.w, h: size.h, dpr, ink, t, pct: pctNow, formMs: formStart === null ? null : now - formStart, still });if (!still || formStart === null) raf = requestAnimationFrame(draw);};raf = requestAnimationFrame(draw);@@ -302,7 +312,7 @@ function takeFresh(id: string): boolean {return at !== undefined && Date.now() - at < 8000;}-function clearMask(b: HTMLElement) {+export function clearMask(b: HTMLElement) {b.style.clipPath = "";b.style.filter = "";for (const p of ["mask-image", "-webkit-mask-image", "mask-size", "-webkit-mask-size", "mask-repeat", "-webkit-mask-repeat"]) b.style.removeProperty(p);@@ -313,6 +323,84 @@ const FILL_MS = 450;const HOLD_MS = 350;const ZOOM_MS = 950;+/** The parts of a hatching result frame (the markup of `Hatch`). */+export interface HatchEls {+ el: HTMLDivElement;+ body: HTMLDivElement;+ canvasBox: HTMLDivElement | null;+ veilBox: HTMLDivElement | null;+ veil: SVGSVGElement | null;+ veilPath: SVGPathElement | null;+ ink: SVGPathElement | null;+}++/** Where the hatching timeline ends (ms), when it starts `formFrom` ms into the logo forming. */+export const hatchEnd = (formFrom: number) => FORM_MS - formFrom + FILL_MS + HOLD_MS + ZOOM_MS;++/** The hatching at `tl` ms on its timeline (which waits while the image decodes), started+ * `formFrom` ms into the logo forming. The canvas is the frame's own image box, measured on+ * each call since the frame sizes itself after mounting; until then the same fit computed. The+ * mark sits on it like on the card. */+export function paintHatch(e: HatchEls, aspect: number, tl: number, formFrom: number) {+ const { el, body: b } = e;+ const W = el.clientWidth;+ const H = el.clientHeight;+ let r = { w: Math.min(W, H * aspect), h: 0, x: 0, y: 0 };+ r = { ...r, h: r.w / aspect, x: (W - r.w) / 2, y: (H - r.w / aspect) / 2 };+ const shown = b.querySelector<HTMLElement>(".image-box, .compare-box");+ if (shown && shown.offsetWidth > 0) {+ const a = shown.getBoundingClientRect();+ const o = el.getBoundingClientRect();+ r = { w: a.width, h: a.height, x: a.left - o.left, y: a.top - o.top };+ }+ const { w: iw, h: ih, x: ox, y: oy } = r;+ const m = markLayout(iw, ih);+ for (const box of [e.canvasBox, e.veilBox]) if (box) Object.assign(box.style, { left: `${ox}px`, top: `${oy}px`, width: `${iw}px`, height: `${ih}px` });+ const fillAt = FORM_MS - formFrom;+ const zoomAt = fillAt + FILL_MS + HOLD_MS;+ const f = formingAt(formFrom + tl);+ const z = easeInOut(clamp01((tl - zoomAt) / ZOOM_MS));+ const left = ox + m.leftCocoon + (m.leftLogo - m.leftCocoon) * f.shift;+ const top = oy + m.top;+ let d: string;+ if (z <= 0) {+ d = markPath(left, top, m.scale, f.up, f.down);+ b.style.clipPath = `path('${d}')`;+ } else {+ // The logo grows while drifting to the canvas centre, and the canvas around it (a veil+ // with the logo cut out) softens at the edge and fades away: the image dissolves out of+ // the logo instead of being cut by it. A path, not a mask image, so no frame waits on a+ // decode.+ const k = 1 + (ZOOM_TO - 1) * z;+ const c0x = left + 512 * m.scale;+ const c0y = top + 512 * m.scale;+ const cx = c0x + (ox + iw / 2 - c0x) * z;+ const cy = c0y + (oy + ih / 2 - c0y) * z;+ const s = m.scale * k;+ d = markPath(cx - 512 * s, cy - 512 * s, s, 1, 1);+ b.style.clipPath = "";+ const v = e.veil;+ const vp = e.veilPath;+ if (v && vp) {+ const feather = Math.min(iw, ih) * 0.05 * easeOut(z);+ const pad = feather * 3 + 2;+ const hole = markPath(cx - ox - 512 * s, cy - oy - 512 * s, s, 1, 1);+ vp.setAttribute("d", `M${-pad} ${-pad} H${iw + pad} V${ih + pad} H${-pad} Z ` + hole);+ v.style.display = "block";+ v.style.opacity = String(1 - easeInOut(clamp01((z - 0.15) / 0.85)));+ v.style.filter = feather > 0.3 ? `blur(${feather.toFixed(1)}px)` : "";+ }+ }+ // The solid logo gives way to the image inside it.+ const fill = easeOut(clamp01((tl - fillAt) / FILL_MS));+ if (e.ink) {+ e.ink.setAttribute("d", d);+ e.ink.style.opacity = String(1 - fill);+ }+ const blur = 6 * (1 - easeOut(clamp01((tl - fillAt) / (FILL_MS + HOLD_MS + ZOOM_MS * 0.5))));+ b.style.filter = blur > 0.05 ? `blur(${blur.toFixed(2)}px)` : "";+}+/** Wraps a result frame. The first time a fresh result is shown it hatches, on the canvas the* job was made on: from the solid logo (formed here first if the job ended before its card* showed it), the image appears inside the logo, then the logo grows evenly from its centre@@ -332,30 +420,9 @@ export function Hatch({ id, aspect, children }: { id?: string; aspect: number; cconst el = ref.current;const b = body.current;if (!on || !el || !b) return;- // The canvas: the frame's own image box, measured each frame since the frame sizes itself- // after mounting; until then the same fit computed. The mark sits on it like on the card.- let iw = 0, ih = 0, ox = 0, oy = 0;- let m = markLayout(1, 1);- const measure = () => {- const W = el.clientWidth;- const H = el.clientHeight;- let r = { w: Math.min(W, H * aspect), h: 0, x: 0, y: 0 };- r = { ...r, h: r.w / aspect, x: (W - r.w) / 2, y: (H - r.w / aspect) / 2 };- const shown = b.querySelector<HTMLElement>(".image-box, .compare-box");- if (shown && shown.offsetWidth > 0) {- const a = shown.getBoundingClientRect();- const o = el.getBoundingClientRect();- r = { w: a.width, h: a.height, x: a.left - o.left, y: a.top - o.top };- }- if (r.w === iw && r.h === ih && r.x === ox && r.y === oy) return;- [iw, ih, ox, oy] = [r.w, r.h, r.x, r.y];- m = markLayout(iw, ih);- for (const box of [canvasBox.current, veilBox.current]) if (box) Object.assign(box.style, { left: `${ox}px`, top: `${oy}px`, width: `${iw}px`, height: `${ih}px` });- };const formed = performance.now() - logoFormedAt < 4000;const formFrom = formed ? FORM_MS : 0;const fillAt = FORM_MS - formFrom;- const zoomAt = fillAt + FILL_MS + HOLD_MS;const start = performance.now();// The solid logo holds until the image inside it is decoded: otherwise the ink fades onto an// empty canvas and the image pops in afterwards (the logo seems to appear twice).@@ -366,53 +433,12 @@ export function Hatch({ id, aspect, children }: { id?: string; aspect: number; cconst giveUp = window.setTimeout(ready, 5000);let raf = 0;const frame = (now: number) => {- measure();const t = now - start;- const f = formingAt(formFrom + t);// The timeline after the logo has formed, paused while the image is not ready.const wait = readyAt === null ? Math.max(0, t - fillAt) : Math.max(0, readyAt - start - fillAt);const tl = t <= fillAt ? t : Math.max(fillAt, t - wait);- const z = easeInOut(clamp01((tl - zoomAt) / ZOOM_MS));- const left = ox + m.leftCocoon + (m.leftLogo - m.leftCocoon) * f.shift;- const top = oy + m.top;- let d: string;- if (z <= 0) {- d = markPath(left, top, m.scale, f.up, f.down);- b.style.clipPath = `path('${d}')`;- } else {- // The logo grows while drifting to the canvas centre, and the canvas around it (a veil- // with the logo cut out) softens at the edge and fades away: the image dissolves out of- // the logo instead of being cut by it. A path, not a mask image, so no frame waits on a- // decode.- const k = 1 + (ZOOM_TO - 1) * z;- const c0x = left + 512 * m.scale;- const c0y = top + 512 * m.scale;- const cx = c0x + (ox + iw / 2 - c0x) * z;- const cy = c0y + (oy + ih / 2 - c0y) * z;- const s = m.scale * k;- d = markPath(cx - 512 * s, cy - 512 * s, s, 1, 1);- b.style.clipPath = "";- const v = veil.current;- const vp = veilPath.current;- if (v && vp) {- const feather = Math.min(iw, ih) * 0.05 * easeOut(z);- const pad = feather * 3 + 2;- const hole = markPath(cx - ox - 512 * s, cy - oy - 512 * s, s, 1, 1);- vp.setAttribute("d", `M${-pad} ${-pad} H${iw + pad} V${ih + pad} H${-pad} Z ` + hole);- v.style.display = "block";- v.style.opacity = String(1 - easeInOut(clamp01((z - 0.15) / 0.85)));- v.style.filter = feather > 0.3 ? `blur(${feather.toFixed(1)}px)` : "";- }- }- // The solid logo gives way to the image inside it.- const fill = easeOut(clamp01((tl - fillAt) / FILL_MS));- if (ink.current) {- ink.current.setAttribute("d", d);- ink.current.style.opacity = String(1 - fill);- }- const blur = 6 * (1 - easeOut(clamp01((tl - fillAt) / (FILL_MS + HOLD_MS + ZOOM_MS * 0.5))));- b.style.filter = blur > 0.05 ? `blur(${blur.toFixed(2)}px)` : "";- if (tl < zoomAt + ZOOM_MS) raf = requestAnimationFrame(frame);+ paintHatch({ el, body: b, canvasBox: canvasBox.current, veilBox: veilBox.current, veil: veil.current, veilPath: veilPath.current, ink: ink.current }, aspect, tl, formFrom);+ if (tl < hatchEnd(formFrom)) raf = requestAnimationFrame(frame);else {clearMask(b);setRunning(false);diff --git a/src/components/Stage.tsx b/src/components/Stage.tsxindex c406399..cc1be1e 100644--- a/src/components/Stage.tsx+++ b/src/components/Stage.tsx@@ -4,7 +4,7 @@ import {import { Fragment, useEffect, useLayoutEffect, useMemo, useRef, useState } from "react";import { api, urls } from "../lib/api";import {- compareBase, composerFromRecord, formatDuration, jobLabel, jobPercent, type JobClock, lutInfo, lutLabel, MAX_UPSCALE_AREA, MAX_UPSCALE_SIDE, MODE_LABEL, pipelineSummary, remainingSeconds, sizeForWidth, upscaleRequest, arcLayout,+ compareBase, composerFromRecord, formatDuration, jobLabel, type JobClock, lutInfo, lutLabel, MAX_UPSCALE_AREA, MAX_UPSCALE_SIDE, MODE_LABEL, pipelineSummary, remainingSeconds, sizeForWidth, upscaleRequest, arcLayout,upscalerLabel, upscaleTargets, variationRequest, imageName, type LinkKind, type TimelineLink,} from "../lib/logic";import { native } from "../lib/native";@@ -12,8 +12,9 @@ import {addAsReference, addResult, cancelJob, focusPrompt, getState, itemSource, removeSessionItem, reusePrompt, selectedItem, selectItem, sessionLabels, sessionLinks, setState, submitRequest, toastError, toastInfo, useStore, type SessionItem,} from "../lib/store";import type { GenerationRecord, GenerationRequest, JobView, LutEntry, Mode, Size } from "../lib/types";-import { Cocoon, Hatch, reducedMotion } from "./Cocoon";+import { Cocoon, Hatch } from "./Cocoon";import { CompareFrame, CompareFullscreen } from "./Compare";+import { PROMPT_FADE_MS, usePromptLeave, useTypewriter, useJobPercent, wordStyle } from "./jobMotion";import { LutBar, LutButton, LutOverlay } from "./Lut";import { IconButton, Popover, useFit } from "./ui";import { Fullscreen, FullscreenButton, isTyping, ZoomImage, type ViewerNav } from "./Viewer";@@ -102,83 +103,6 @@ function Pending({ job, item, labels }: { job: JobView; item: SessionItem; label);}-/** This machine's pace for the phases the plan cannot estimate (model load, prompt enhancer),- * remembered between jobs; a per-viewer convenience, so defaults when storage is unavailable. */-const PROGRESS_KEY = "kokon.progress";-interface ProgressMemory { loadSeconds: number; enhancerSecondsPerWord: number }-function progressMemory(): ProgressMemory {- const d: ProgressMemory = { loadSeconds: 20, enhancerSecondsPerWord: 0.015 };- try {- const v = JSON.parse(localStorage.getItem(PROGRESS_KEY) || "{}");- return { loadSeconds: v.loadSeconds > 0 ? v.loadSeconds : d.loadSeconds, enhancerSecondsPerWord: v.enhancerSecondsPerWord > 0 ? v.enhancerSecondsPerWord : d.enhancerSecondsPerWord };- } catch {- return d;- }-}-function rememberProgress(m: Partial<ProgressMemory>) {- try {- localStorage.setItem(PROGRESS_KEY, JSON.stringify({ ...progressMemory(), ...m }));- } catch {- /* storage unavailable: the defaults stay */- }-}--const ENHANCED_MODES = new Set(["generate", "edit", "multi_reference"]);--/** Live percentage of a whole job (`jobPercent`), computed a few times a second, only ever going- * up, and eased so it counts up smoothly. Tracks when the job and each phase started; `learn`- * (the main card only) remembers how long the model load and the prompt enhancer took. */-function useJobPercent(job: JobView, request: GenerationRequest | null | undefined, learn = false): { pct: number; clock: JobClock } {- const enhance = !!request?.enhance && ENHANCED_MODES.has(job.plan?.mode ?? request?.mode ?? "");- const [shown, setShown] = useState<{ pct: number; clock: JobClock }>(() => ({ pct: 0, clock: { elapsed: 0, inPhase: 0, inRunning: 0, sinceStep: 0, enhance, ...progressMemory() } }));- const live = useRef({ job, enhance });- live.current = { job, enhance };- useEffect(() => {- const mem = progressMemory();- let startedAt: number | null = null;- let runningAt: number | null = null;- let phase = { key: "", at: performance.now() };- let step = { key: "", at: performance.now() };- let target = 0;- let value = 0;- const id = window.setInterval(() => {- const { job: j, enhance: e } = live.current;- const now = performance.now();- if (startedAt === null && j.status !== "queued") startedAt = now;- if (runningAt === null && j.status === "running") runningAt = now;- const key = `${j.status}|${j.stage ?? ""}`;- if (key !== phase.key) {- // Learn the phases the plan does not estimate, when they end.- const took = (now - phase.at) / 1000;- const was = phase.key.split("|")[0];- if (learn && was === "starting_backend" && took > 1) rememberProgress({ loadSeconds: took });- if (learn && was === "enhancing_prompt" && j.enhanced_prompt) {- const words = j.enhanced_prompt.split(/\s+/).filter(Boolean).length;- if (words >= 5) rememberProgress({ enhancerSecondsPerWord: took / words });- }- phase = { key, at: now };- }- const stepKey = j.step ? `${j.stage}|${j.step[0]}/${j.step[1]}` : "";- if (stepKey !== step.key) step = { key: stepKey, at: now };- const clock: JobClock = {- elapsed: startedAt === null ? 0 : (now - startedAt) / 1000,- inPhase: (now - phase.at) / 1000,- inRunning: runningAt === null ? 0 : (now - runningAt) / 1000,- sinceStep: (now - step.at) / 1000,- enhance: e,- ...mem,- };- target = Math.max(target, jobPercent(j, clock));- value += (target - value) * (reducedMotion() ? 1 : 0.18);- if (target - value < 0.05) value = target;- setShown({ pct: value, clock });- }, 60);- return () => window.clearInterval(id);- // eslint-disable-next-line react-hooks/exhaustive-deps- }, []);- return shown;-}-function ProgressPhase({ job, title, pct, clock }: { job: JobView; title: string; pct: number; clock: JobClock }) {const o = job.plan?.output;const remain = remainingSeconds(job, clock);@@ -211,9 +135,6 @@ function ProgressPhase({ job, title, pct, clock }: { job: JobView; title: string);}-/** How long the finished prompt stays on screen before the percentage takes over (ms). */-const PROMPT_HOLD_MS = 2200;-const PROMPT_FADE_MS = 700;/** The prompt enhancer's text over the whole frame, revealed word by word at a calm pace. The* model writes it in a second or two and the image starts right away, so the text keeps@@ -225,21 +146,13 @@ function PromptPhase(props: { title: string; text: string; streaming: boolean; wconst ref = useRef<HTMLDivElement>(null);const words = useMemo(() => text.split(/(\s+)/), [text]);const writing = streaming || shown < text.length;- const [leaving, setLeaving] = useState(false);- const onGone = useRef(props.onGone);- onGone.current = props.onGone;- useEffect(() => {- if (writing || !text) return;- const hold = window.setTimeout(() => setLeaving(true), PROMPT_HOLD_MS);- const gone = window.setTimeout(() => onGone.current(), PROMPT_HOLD_MS + PROMPT_FADE_MS);- return () => (window.clearTimeout(hold), window.clearTimeout(gone));- }, [writing, text]);+ const leave = usePromptLeave(writing, text, props.onGone);// Whole words up to the revealed length; each new one fades in once (stable keys).const visible: React.ReactNode[] = [];let at = 0;for (let i = 0; i < words.length && at < shown; i++) {const w = words[i];- visible.push(/^\s+$/.test(w) ? w : <span key={i} className="w">{w}</span>);+ visible.push(/^\s+$/.test(w) ? w : <span key={i} className="w" style={wordStyle(at, shown)}>{w}</span>);at += w.length;}useEffect(() => {@@ -247,7 +160,7 @@ function PromptPhase(props: { title: string; text: string; streaming: boolean; wif (el && writing) el.scrollTop = el.scrollHeight;}, [visible.length, writing]);return (- <div className={`prompt-stage ${leaving ? "leaving" : ""}`} style={{ transitionDuration: `${PROMPT_FADE_MS}ms` }}>+ <div className={`prompt-stage ${leave.leaving ? "leaving" : ""}`} style={{ transitionDuration: `${PROMPT_FADE_MS}ms`, ...leave.style }}><span className={`enhanced-label ${writing ? "shimmer" : ""}`}><WandSparkles size={13} /> {writing ? "Writing the prompt" : "The prompt"} · {props.title}</span>@@ -264,43 +177,6 @@ function PromptPhase(props: { title: string; text: string; streaming: boolean; w);}-/** Calm reading pace of the prompt (characters a second). */-const TYPE_CHARS_PER_S = 32;--/** How many characters of `text` to show now: ~32 a second, faster when needed to finish in- * 4-12 s (and in half the time a quick image takes), never past `text`. */-function useTypewriter(text: string, streaming: boolean, budget: number | null): number {- const [shown, setShown] = useState(() => (reducedMotion() ? text.length : 0));- const target = useRef({ text, streaming, budget });- target.current = { text, streaming, budget };- const start = useRef<number | null>(null);- useEffect(() => {- if (reducedMotion()) return;- let raf = 0;- let last = performance.now();- let n = 0;- const tick = (now: number) => {- const { text: t, streaming: s, budget: b } = target.current;- const dt = Math.min(0.1, (now - last) / 1000);- last = now;- if (t.length > 0 && start.current === null) start.current = now;- if (n < t.length) {- const cap = Math.max(4, Math.min(12, b ? b * 0.5 : 12));- const total = Math.min(cap, Math.max(4, t.length / TYPE_CHARS_PER_S));- const left = Math.max(0.4, total - (now - (start.current ?? now)) / 1000);- const speed = Math.max(s ? 20 : TYPE_CHARS_PER_S, (t.length - n) / left);- n = Math.min(t.length, n + speed * dt);- setShown(n);- }- // Done once everything has arrived and is on screen.- if (s || n < t.length) raf = requestAnimationFrame(tick);- };- raf = requestAnimationFrame(tick);- return () => cancelAnimationFrame(raf);- // eslint-disable-next-line react-hooks/exhaustive-deps- }, []);- return reducedMotion() ? text.length : shown;-}function Failed({ job, item }: { job: JobView; item: SessionItem }) {const [details, setDetails] = useState(false);diff --git a/src/components/TopBar.tsx b/src/components/TopBar.tsxnew file mode 100644index 0000000..7513d06--- /dev/null+++ b/src/components/TopBar.tsx@@ -0,0 +1,150 @@+// The top bar: the project's title, then undo/redo, the update pill, the status capsule,+// private mode, shortcuts and (only while the sidebar is hidden) Settings, then the window's+// buttons. Its own file so the launch video (marketing/video) shows the same bar.+import { ArrowDownToLine, CircleHelp, EyeOff, PanelLeft, Redo2, Settings, SquarePen, Undo2 } from "lucide-react";+import { api } from "../lib/api";+import { native } from "../lib/native";+import { shortcut } from "../lib/platform";+import { getState, isMissingModel, newProject, openModelSetup, redoVersion, refreshStatus, setPrivateMode, setState, toastError, undoKey, undoVersion, useStore } from "../lib/store";+import { installUpdate } from "../lib/updates";+import { SilkSpin } from "./Cocoon";+import { ProjectTitle, Wordmark } from "./Sidebar";+import { WindowControls } from "./TitleBar";+import { IconButton } from "./ui";++function StatusIndicator() {+ const connected = useStore((s) => s.connected);+ const server = useStore((s) => s.server);+ const busy = useStore((s) => Object.values(s.jobs).some((j) => !["done", "failed", "cancelled"].includes(j.status)));+ let cls = "dot";+ let text = "Connecting";+ let title = "";+ if (connected) {+ switch (server.state) {+ case "ready":+ cls = "dot ready";+ text = busy ? "Working" : "Ready";+ title = server.owned ? "Model loaded" : "Using an inference server that was already running";+ break;+ case "starting":+ cls = "dot busy";+ text = "Loading model";+ break;+ case "error":+ cls = "dot error";+ text = server.error?.message ?? "Inference server error";+ title = isMissingModel(server.error) ? "Find or download the missing file" : "Open Diagnostics";+ break;+ default:+ text = "Model not loaded";+ title = "Click to load the model now";+ }+ }+ return (+ <button+ className="status"+ title={title}+ onClick={() => {+ if (server.state === "error" && isMissingModel(server.error)) openModelSetup();+ else if (server.state === "error") setState({ overlay: "settings" });+ else if (server.state === "stopped" && connected) api.startBackend().then(refreshStatus, toastError);+ }}+ >+ {cls === "dot busy" || (cls === "dot ready" && busy) ? <SilkSpin size={18} /> : <span className={cls} />}+ <span style={{ maxWidth: 360, overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}>{text}</span>+ </button>+ );+}++/** Undo / Redo between versions: back to the image the current one was made from. */+function HistoryButtons() {+ const canUndo = useStore((s) => undoKey(s) !== null);+ const canRedo = useStore((s) => s.redo.length > 0);+ if (!canUndo && !canRedo) return null;+ return (+ <>+ <IconButton title={`Undo: back to the previous version (${shortcut("Z")})`} onClick={undoVersion} disabled={!canUndo}>+ <Undo2 size={18} />+ </IconButton>+ <IconButton title={`Redo (${shortcut("Y")})`} onClick={redoVersion} disabled={!canRedo}>+ <Redo2 size={18} />+ </IconButton>+ </>+ );+}++/** "Update" pill in the top bar once a newer release is found; one click installs it. */+function UpdatePill() {+ const update = useStore((s) => s.update);+ if (!update) return null;+ const busy = update.phase !== "available";+ const click = async () => {+ const running = Object.values(getState().jobs).some((j) => !["done", "failed", "cancelled"].includes(j.status));+ const msg = `Install Kokon ${update.version} now? Kokon closes and restarts in a few seconds${running ? "; the images being made now are stopped" : ""}. Your images, settings and models stay.`;+ if (await native.confirm(update.notes ? `${msg}++What's new:+${update.notes}` : msg, "Update Kokon")) installUpdate();+ };+ const label =+ update.phase === "downloading" ? `Downloading${update.progress != null ? ` ${Math.round(update.progress * 100)}%` : "…"}` : update.phase === "installing" ? "Installing…" : `Update to ${update.version}`;+ return (+ <button className="update-pill" onClick={click} disabled={busy} title={`Kokon ${update.version} is available`}>+ <ArrowDownToLine size={14} /> {label}+ </button>+ );+}++function PrivateToggle() {+ const on = useStore((s) => s.privateMode);+ const toggle = () => setPrivateMode(!on, () => native.confirm("Turn off private mode? The images made in private mode will be deleted.", "Private mode"));+ return on ? (+ <button className="private-pill" onClick={toggle} title="Private mode is on: images are not saved and are deleted when you turn it off or close the app. Click to turn it off.">+ <EyeOff size={15} /> Private+ </button>+ ) : (+ <IconButton title="Private mode: nothing is saved to the gallery or your Pictures folder" onClick={toggle}>+ <EyeOff size={18} />+ </IconButton>+ );+}++export function TopBar() {+ const overlay = useStore((s) => s.overlay);+ const needsSetup = useStore((s) => s.needsSetup);+ const sidebar = useStore((s) => s.sidebar);+ return (+ <div className="topbar" data-tauri-drag-region>+ <div className="brand" data-tauri-drag-region>+ {(!sidebar || needsSetup) && <Wordmark />}+ {!sidebar && !needsSetup && (+ <>+ <IconButton title="Show sidebar" onClick={() => setState({ sidebar: true })}>+ <PanelLeft size={18} />+ </IconButton>+ <IconButton title="New image" onClick={newProject}>+ <SquarePen size={18} />+ </IconButton>+ </>+ )}+ {overlay === "gallery" ? <span className="project-title">All images</span> : !needsSetup && <ProjectTitle />}+ </div>+ <div className="toolbar" data-tauri-drag-region>+ {!needsSetup && <HistoryButtons />}+ <UpdatePill />+ <StatusIndicator />+ {!needsSetup && <PrivateToggle />}+ <IconButton title="Shortcuts (?)" onClick={() => setState({ overlay: "shortcuts" })}>+ <CircleHelp size={18} />+ </IconButton>+ {/* Settings lives at the foot of the sidebar; here only while the sidebar is hidden. */}+ {(!sidebar || needsSetup) && (+ <IconButton title="Settings" onClick={() => setState({ overlay: "settings" })}>+ <Settings size={18} />+ </IconButton>+ )}+ </div>+ <WindowControls />+ </div>+ );+}diff --git a/src/components/jobMotion.ts b/src/components/jobMotion.tsnew file mode 100644index 0000000..5889adb--- /dev/null+++ b/src/components/jobMotion.ts@@ -0,0 +1,147 @@+// The timing of a job's card in the stage: the live percentage, the prompt enhancer's text+// appearing word by word, and the prompt leaving for the percentage. Kept apart from Stage.tsx+// so the launch video (marketing/video) can drive the same card from its frame clock.+import { useEffect, useRef, useState, type CSSProperties } from "react";+import { jobPercent, type JobClock } from "../lib/logic";+import type { GenerationRequest, JobView } from "../lib/types";+import { reducedMotion } from "./Cocoon";++/** This machine's pace for the phases the plan cannot estimate (model load, prompt enhancer),+ * remembered between jobs; a per-viewer convenience, so defaults when storage is unavailable. */+const PROGRESS_KEY = "kokon.progress";+interface ProgressMemory { loadSeconds: number; enhancerSecondsPerWord: number }+function progressMemory(): ProgressMemory {+ const d: ProgressMemory = { loadSeconds: 20, enhancerSecondsPerWord: 0.015 };+ try {+ const v = JSON.parse(localStorage.getItem(PROGRESS_KEY) || "{}");+ return { loadSeconds: v.loadSeconds > 0 ? v.loadSeconds : d.loadSeconds, enhancerSecondsPerWord: v.enhancerSecondsPerWord > 0 ? v.enhancerSecondsPerWord : d.enhancerSecondsPerWord };+ } catch {+ return d;+ }+}+function rememberProgress(m: Partial<ProgressMemory>) {+ try {+ localStorage.setItem(PROGRESS_KEY, JSON.stringify({ ...progressMemory(), ...m }));+ } catch {+ /* storage unavailable: the defaults stay */+ }+}++const ENHANCED_MODES = new Set(["generate", "edit", "multi_reference"]);++/** Live percentage of a whole job (`jobPercent`), computed a few times a second, only ever going+ * up, and eased so it counts up smoothly. Tracks when the job and each phase started; `learn`+ * (the main card only) remembers how long the model load and the prompt enhancer took. */+export function useJobPercent(job: JobView, request: GenerationRequest | null | undefined, learn = false): { pct: number; clock: JobClock } {+ const enhance = !!request?.enhance && ENHANCED_MODES.has(job.plan?.mode ?? request?.mode ?? "");+ const [shown, setShown] = useState<{ pct: number; clock: JobClock }>(() => ({ pct: 0, clock: { elapsed: 0, inPhase: 0, inRunning: 0, sinceStep: 0, enhance, ...progressMemory() } }));+ const live = useRef({ job, enhance });+ live.current = { job, enhance };+ useEffect(() => {+ const mem = progressMemory();+ let startedAt: number | null = null;+ let runningAt: number | null = null;+ let phase = { key: "", at: performance.now() };+ let step = { key: "", at: performance.now() };+ let target = 0;+ let value = 0;+ const id = window.setInterval(() => {+ const { job: j, enhance: e } = live.current;+ const now = performance.now();+ if (startedAt === null && j.status !== "queued") startedAt = now;+ if (runningAt === null && j.status === "running") runningAt = now;+ const key = `${j.status}|${j.stage ?? ""}`;+ if (key !== phase.key) {+ // Learn the phases the plan does not estimate, when they end.+ const took = (now - phase.at) / 1000;+ const was = phase.key.split("|")[0];+ if (learn && was === "starting_backend" && took > 1) rememberProgress({ loadSeconds: took });+ if (learn && was === "enhancing_prompt" && j.enhanced_prompt) {+ const words = j.enhanced_prompt.split(/\s+/).filter(Boolean).length;+ if (words >= 5) rememberProgress({ enhancerSecondsPerWord: took / words });+ }+ phase = { key, at: now };+ }+ const stepKey = j.step ? `${j.stage}|${j.step[0]}/${j.step[1]}` : "";+ if (stepKey !== step.key) step = { key: stepKey, at: now };+ const clock: JobClock = {+ elapsed: startedAt === null ? 0 : (now - startedAt) / 1000,+ inPhase: (now - phase.at) / 1000,+ inRunning: runningAt === null ? 0 : (now - runningAt) / 1000,+ sinceStep: (now - step.at) / 1000,+ enhance: e,+ ...mem,+ };+ target = Math.max(target, jobPercent(j, clock));+ value += (target - value) * (reducedMotion() ? 1 : 0.18);+ if (target - value < 0.05) value = target;+ setShown({ pct: value, clock });+ }, 60);+ return () => window.clearInterval(id);+ // eslint-disable-next-line react-hooks/exhaustive-deps+ }, []);+ return shown;+}++/** How long the finished prompt stays on screen before the percentage takes over (ms). */+export const PROMPT_HOLD_MS = 2200;+export const PROMPT_FADE_MS = 700;++/** Once the whole prompt is on screen it holds, then fades (`leaving`, styled by+ * `.prompt-stage.leaving`), then `onGone`. `style` is for a clock other than the browser's. */+export function usePromptLeave(writing: boolean, text: string, onGone: () => void): { leaving: boolean; style?: CSSProperties } {+ const [leaving, setLeaving] = useState(false);+ const gone = useRef(onGone);+ gone.current = onGone;+ useEffect(() => {+ if (writing || !text) return;+ const hold = window.setTimeout(() => setLeaving(true), PROMPT_HOLD_MS);+ const end = window.setTimeout(() => gone.current(), PROMPT_HOLD_MS + PROMPT_FADE_MS);+ return () => (window.clearTimeout(hold), window.clearTimeout(end));+ }, [writing, text]);+ return { leaving };+}++/** Inline style of the word starting at character `at` while `shown` characters are revealed;+ * none here, the CSS animation (`.prompt-text .w`) fades each word in when it mounts. */+export function wordStyle(_at: number, _shown: number): CSSProperties | undefined {+ return undefined;+}++/** Calm reading pace of the prompt (characters a second). */+const TYPE_CHARS_PER_S = 32;++/** How many characters of `text` to show now: ~32 a second, faster when needed to finish in+ * 4-12 s (and in half the time a quick image takes), never past `text`. */+export function useTypewriter(text: string, streaming: boolean, budget: number | null): number {+ const [shown, setShown] = useState(() => (reducedMotion() ? text.length : 0));+ const target = useRef({ text, streaming, budget });+ target.current = { text, streaming, budget };+ const start = useRef<number | null>(null);+ useEffect(() => {+ if (reducedMotion()) return;+ let raf = 0;+ let last = performance.now();+ let n = 0;+ const tick = (now: number) => {+ const { text: t, streaming: s, budget: b } = target.current;+ const dt = Math.min(0.1, (now - last) / 1000);+ last = now;+ if (t.length > 0 && start.current === null) start.current = now;+ if (n < t.length) {+ const cap = Math.max(4, Math.min(12, b ? b * 0.5 : 12));+ const total = Math.min(cap, Math.max(4, t.length / TYPE_CHARS_PER_S));+ const left = Math.max(0.4, total - (now - (start.current ?? now)) / 1000);+ const speed = Math.max(s ? 20 : TYPE_CHARS_PER_S, (t.length - n) / left);+ n = Math.min(t.length, n + speed * dt);+ setShown(n);+ }+ // Done once everything has arrived and is on screen.+ if (s || n < t.length) raf = requestAnimationFrame(tick);+ };+ raf = requestAnimationFrame(tick);+ return () => cancelAnimationFrame(raf);+ // eslint-disable-next-line react-hooks/exhaustive-deps+ }, []);+ return reducedMotion() ? text.length : shown;+}