Skip to content

armgit / fuobe

Public Imported from GitHub
0

The open creative studio on ComfyUI: images, video, 3D and audio on open weights, on your own GPU or the cloud. Camera motions, effects, apps, Cinema, Layers, Image to 3D and an AI agent.

Genjutsu examples: a shorter card on phones, steady labels, and kept own inputs

Adarshcc6e7990d8f0
diff --git a/public/examples/genjutsu-finish/1/show.mp4 b/public/examples/genjutsu-finish/1/show.mp4
index 242b5199..49da0be6 100644
Binary files a/public/examples/genjutsu-finish/1/show.mp4 and b/public/examples/genjutsu-finish/1/show.mp4 differ
diff --git a/public/examples/genjutsu-finish/1/show.peak.webp b/public/examples/genjutsu-finish/1/show.peak.webp
index 633bfbc7..4e9d5bce 100644
Binary files a/public/examples/genjutsu-finish/1/show.peak.webp and b/public/examples/genjutsu-finish/1/show.peak.webp differ
diff --git a/public/examples/genjutsu-finish/1/show.poster.webp b/public/examples/genjutsu-finish/1/show.poster.webp
index 8378097e..485ead16 100644
Binary files a/public/examples/genjutsu-finish/1/show.poster.webp and b/public/examples/genjutsu-finish/1/show.poster.webp differ
diff --git a/scripts/examples/publish-examples.mjs b/scripts/examples/publish-examples.mjs
index 38d15901..a69a99d0 100644
--- a/scripts/examples/publish-examples.mjs
+++ b/scripts/examples/publish-examples.mjs
@@ -15,8 +15,10 @@
* still-out a picture shown as an output: JPEG q84, 960 px at most, plus its poster (<name>.512.webp)
* clip-show a before → after loop shown as an output (a Genjutsu mode's example): "before" (the clip that went in)
* and "after" (the result) baked into one muted H.264 mp4, 1024×768, 24 fps, 1.2 MB at most, as "layout":
- * "inset" (the result fills the frame, the clip plays in a rounded window bottom-left) or "wipe" (the clip
- * for 1 s, then a thin line sweeps left to right over 1.4 s and leaves the result). Plus its first frame
+ * "inset" (the result fills the frame, the clip plays in a rounded window bottom-left) or "wipe" (a thin
+ * line splits the frame, the result on its left and the clip on its right: it holds in the middle for
+ * 1.5 s, eases to 3/4, back to 1/4 and to the middle again, so both sides always show, a subtle change
+ * is easy to see at the line, and the loop has no seam). Plus its first frame
* (<name>.poster.webp, 1024 px, so the loop starts with no jump) and the result near its end
* (<name>.peak.webp, 512 px: where a card rests, and what reduced motion shows)
* A published file is never replaced or removed (a run may name it): a copy whose file exists with other bytes stops
@@ -149,9 +151,11 @@ async function clipShow(job, dry) {
`[A1][BM]overlay=${x}:${y}:shortest=1,format=yuv420p[out]`,
].join(";");
} else {
- // 0–1 s the source; 1–2.4 s a line sweeps (ease in-out) and leaves the result on its left; then the result.
- const p = "clip((t-1)/1.4\,0\,1)";
- const X = `(${w}*if(lt(${p}\,0.5)\,2*${p}*${p}\,1-pow(-2*${p}+2\,2)/2))`;
+ // The line (the result on its left): the middle until 1.5 s, then over 1 s each (ease in-out) to 3/4, to 1/4 and
+ // back to the middle, where it holds to the end (the loop's first and last frames match).
+ const ease = (q) => `if(lt(${q},0.5),2*${q}*${q},1-pow(-2*${q}+2,2)/2)`;
+ const step = (from) => ease(`clip(t-${from},0,1)`);
+ const X = `(${w}*(0.5+0.25*${step(1.5)}-0.5*${step(2.5)}+0.25*${step(3.5)}))`;
const d = (frames / fps).toFixed(4);
inputs = ["-i", before, "-i", after];
graph = [
@@ -164,8 +168,8 @@ async function clipShow(job, dry) {
`[A][BM]overlay=0:0:shortest=1[W]`,
`[email protected]:s=8x${h}:r=${fps}:d=${d}[S]`,
`color=white:s=2x${h}:r=${fps}:d=${d}[L]`,
- `[W][S]overlay=x='${X}-4':y=0:eval=frame:enable='between(t\,1\,2.4)'[W1]`,
- `[W1][L]overlay=x='${X}-1':y=0:eval=frame:enable='between(t\,1\,2.4)',format=yuv420p[out]`,
+ `[W][S]overlay=x='${X}-4':y=0:eval=frame[W1]`,
+ `[W1][L]overlay=x='${X}-1':y=0:eval=frame,format=yuv420p[out]`,
].join(";");
}
const mp4 = path.join(dir, "show.mp4");
diff --git a/src/app/(studio)/genjutsu/page.tsx b/src/app/(studio)/genjutsu/page.tsx
index 204d1564..971a5297 100644
--- a/src/app/(studio)/genjutsu/page.tsx
+++ b/src/app/(studio)/genjutsu/page.tsx
@@ -7,5 +7,7 @@ export const metadata: Metadata = { title: "Genjutsu" };
export default function Page() {
// Which Openjutsu modes are open to everyone (two committed files, read as the page is built; the owner sees them all).
- return <GenjutsuStudio examples={exampleRow("tool:genjutsu")} modeExamples={genjutsuExamples()} live={genjutsuLive()} />;
+ const live = genjutsuLive();
+ // The page carries only the mode examples open to everyone; the owner's Genjutsu fetches the rest (/api/genjutsu/examples).
+ return <GenjutsuStudio examples={exampleRow("tool:genjutsu")} modeExamples={genjutsuExamples((f) => live[f])} live={live} />;
}
diff --git a/src/app/api/genjutsu/examples/route.ts b/src/app/api/genjutsu/examples/route.ts
new file mode 100644
index 00000000..33d38527
--- /dev/null
+++ b/src/app/api/genjutsu/examples/route.ts
@@ -0,0 +1,16 @@
+import { connection } from "next/server";
+import { genjutsuExamples } from "@/lib/examples/catalog";
+import { isOwnerRequest, sessionCookieOf } from "@/server/auth";
+
+const NO_STORE = { "Cache-Control": "no-store" };
+
+/**
+ * Every Genjutsu mode's examples, the ones still only the owner's included (their mode or a feature they need hasn't
+ * passed its GPU test yet). The page itself sends only the examples open to everyone; the owner's Genjutsu asks here
+ * for the rest. The owner only.
+ */
+export async function GET(request: Request) {
+ await connection();
+ if (!isOwnerRequest(request, sessionCookieOf(request))) return Response.json({ error: "Only the studio's owner sees these" }, { status: 403, headers: NO_STORE });
+ return Response.json({ examples: genjutsuExamples() }, { headers: NO_STORE });
+}
diff --git a/src/components/genjutsu/genjutsu-studio.tsx b/src/components/genjutsu/genjutsu-studio.tsx
index 45ac4d84..1ab2f0e6 100644
--- a/src/components/genjutsu/genjutsu-studio.tsx
+++ b/src/components/genjutsu/genjutsu-studio.tsx
@@ -1,5 +1,6 @@
"use client";
+import { useQuery } from "@tanstack/react-query";
import { Brush, Download, Info, Loader2, RotateCcw, Sparkles, Undo2, Wand2 } from "lucide-react";
import Link from "next/link";
import { useRouter, useSearchParams } from "next/navigation";
@@ -82,7 +83,7 @@ import { SetupCode } from "./setup-code";
import { useClipCuts } from "./use-cuts";
import { ModeExample, ModeExampleRow } from "./mode-example";
import { AlertDialog, AlertDialogAction, AlertDialogCancel, AlertDialogContent, AlertDialogDescription, AlertDialogFooter, AlertDialogHeader, AlertDialogTitle } from "@/components/ui/alert-dialog";
-import { exampleFor, MARKED_NOTE, partLimits, sameRecipe, toRecipe, type GenjutsuExampleCard, type ModeExamples } from "@/lib/examples/genjutsu";
+import { exampleFor, MARKED_NOTE, OWN_CHARACTER_FIELDS, partLimits, sameRecipe, toRecipe, type GenjutsuExampleCard, type ModeExamples } from "@/lib/examples/genjutsu";
/** The upload box's line: the mode's own window (Character swap: 5–15 s of one shot). */
const limits = (mode: GenjutsuMode) =>
@@ -127,6 +128,18 @@ export function GenjutsuStudio({ examples, modeExamples, live }: { examples?: Ex
const owner = useIsOwner();
const open: FeatureCheck = useCallback((f) => owner || !!live?.[f], [owner, live]);
const ownerOnly: FeatureCheck = (f) => owner && !live?.[f];
+ // The page sends only the mode examples open to everyone; the owner's are fetched (never in a visitor's page).
+ const ownerExamples = useQuery({
+ queryKey: ["genjutsu-examples"],
+ queryFn: async () => {
+ const res = await fetch("/api/genjutsu/examples");
+ if (!res.ok) throw new Error(String(res.status));
+ return ((await res.json()) as { examples: ModeExamples }).examples;
+ },
+ enabled: owner,
+ staleTime: Infinity,
+ });
+ const shownExamples = owner && ownerExamples.data ? ownerExamples.data : modeExamples;
// Genjutsu doesn't run on an account's own GPU yet (only the studios' generations do): said here, not after Generate.
const visitor = useLikelyVisitor();
const access = useModelAccess();
@@ -171,7 +184,12 @@ export function GenjutsuStudio({ examples, modeExamples, live }: { examples?: Ex
// A mode's example in the form: which one, the part's length it asks for until a clip is in, and its words that came
// from its own clip (a note under those fields).
const [exampleIn, setExampleIn] = useState<string | null>(null);
- const [pendingLength, setPendingLength] = useState<number | null>(null);
+ // The length asks for the mode (and model) it came with: another mode's part limits don't take it.
+ const [pendingLength, setPendingLength] = useState<{ length: number; mode: GenjutsuMode; model?: string } | null>(null);
+ // The mode whose seed field a pasted setup or an example filled (only that mode shows and sends it).
+ const [seedFor, setSeedFor] = useState<GenjutsuMode | null>(null);
+ // The form's words right after an example went in: words that still match it aren't the viewer's own.
+ const [exampleWords, setExampleWords] = useState("");
const [marked, setMarked] = useState<{ subject?: boolean; target?: boolean }>({});
const [askReplace, setAskReplace] = useState<GenjutsuExampleCard | null>(null);
const [dropRing, setDropRing] = useState(false);
@@ -196,6 +214,12 @@ export function GenjutsuStudio({ examples, modeExamples, live }: { examples?: Ex
const setMode = (m: GenjutsuMode) => {
setModeState(m);
+ // A seed or a length that came with another mode's setup stays with that mode.
+ if (seedFor && seedFor !== m) {
+ setSeed("");
+ setSeedFor(null);
+ }
+ if (pendingLength && pendingLength.mode !== m) setPendingLength(null);
// Character swap takes a 5–15 s part: a longer selection is cut back to its first 15 s (From picture: 15 s too).
const most = m === "character" || m === "picture" ? CHARACTER_SWAP.maxSeconds : null;
if (most && range && range.endTime - range.startTime > most + 0.05) {
@@ -258,7 +282,7 @@ export function GenjutsuStudio({ examples, modeExamples, live }: { examples?: Ex
const cut = cutWarning(partCuts);
const seedNumber = seedOf(seed);
// Modes with no seed field of their own show one once a seed is set (an example's or a pasted setup's).
- const seedShown = !isCharacter && !fresh && seed.trim() !== "";
+ const seedShown = !isCharacter && !fresh && seed.trim() !== "" && seedFor === mode;
// Character swap's H3 makers take H3's two qualities; the other makers (Recast, P-Video…) Genjutsu's own.
// A size this engine can't make worth it (your GPU's 4K) is asked as 2K, as the picker shows it.
const askedQuality = isCharacter && maker?.h3 ? (qualityOff(engine, charQuality) ? "2K" : charQuality) : quality;
@@ -410,7 +434,10 @@ export function GenjutsuStudio({ examples, modeExamples, live }: { examples?: Ex
if (s.finish) setFinish(s.finish);
if (s.references?.length) setRefs(s.references.map(asSlot));
// gj2 and examples: the seed, the part's length and the sound too (an example with no seed: a new one each time).
- if (s.seed !== undefined || example) setSeed(s.seed !== undefined ? String(s.seed) : "");
+ if (s.seed !== undefined || example) {
+ setSeed(s.seed !== undefined ? String(s.seed) : "");
+ setSeedFor(s.seed !== undefined ? s.mode : null);
+ }
if (s.originalSound) setOriginalSound(s.originalSound);
if (s.length !== undefined) partLength(s.length, s.mode, s.model);
if (!example) toast("Setup pasted", { description: clip ? "Check the references and press Generate." : "Add a clip to run it on." });
@@ -419,16 +446,16 @@ export function GenjutsuStudio({ examples, modeExamples, live }: { examples?: Ex
/** The part becomes this long from where it starts (the clip's end at most, and the mode's longest part). */
const partLength = (length: number, m: GenjutsuMode, model?: string) => {
const most = partLimits(m, model).max;
- if (!range || !duration) return setPendingLength(length);
+ if (!range || !duration) return setPendingLength({ length: Math.min(length, most), mode: m, model });
setPendingLength(null);
const end = Math.min(duration, range.startTime + Math.min(length, most));
setRange({ ...range, endTime: Math.round(end * 1000) / 1000 });
if (duration - range.startTime < length - 0.05) toast(`Your clip is ${Math.round((duration - range.startTime) * 10) / 10} s from there. The example used ${Math.round(length * 10) / 10} s.`, { id: "gj-example-length" });
};
// A clip added after an example: its part takes the example's length once the clip is read.
- if (pendingLength !== null && range && duration) {
+ if (pendingLength && range && duration) {
setPendingLength(null);
- const end = Math.min(duration, range.startTime + pendingLength);
+ const end = Math.min(duration, range.startTime + Math.min(pendingLength.length, partLimits(pendingLength.mode, pendingLength.model).max));
if (Math.abs(range.endTime - end) > 0.001) setRange({ ...range, endTime: Math.round(end * 1000) / 1000 });
}
@@ -466,7 +493,7 @@ export function GenjutsuStudio({ examples, modeExamples, live }: { examples?: Ex
}
// ?example=<id>: its mode, with the example in view (nothing is loaded until Use this example).
const ex = fresh("example");
- const exMode = ex ? GENJUTSU_MODES.find((g) => modeExamples?.[g.id]?.some((c) => c.id === ex))?.id : undefined;
+ const exMode = ex ? GENJUTSU_MODES.find((g) => shownExamples?.[g.id]?.some((c) => c.id === ex))?.id : undefined;
if (exMode && modeOpen(exMode, open)) {
setModeState(exMode);
requestAnimationFrame(() => document.querySelector("[data-mode-example]")?.scrollIntoView({ block: "center" }));
@@ -532,6 +559,7 @@ export function GenjutsuStudio({ examples, modeExamples, live }: { examples?: Ex
const reset = () => {
source.clear();
setRange(null);
+ setPendingLength(null);
clearMarks();
// The clip is gone: a later hand-off of the same video loads it again.
if (new URLSearchParams(window.location.search).has("video")) {
@@ -569,10 +597,10 @@ export function GenjutsuStudio({ examples, modeExamples, live }: { examples?: Ex
const soundLiveNow = useSoundLive(ORIGINAL_SOUND_FEATURE);
const originalSound = originalSoundOn(soundAsked ?? originalSoundDefault({ replacesPerson: isCharacter, engine: soundEngine, live: soundLiveNow }), soundEngine);
// The whole setup, as the header copies it (gj2: with the seed, the part's length and the sound) and as an example compares.
- const partNow = range ? Math.round((range.endTime - range.startTime) * 1000) / 1000 : (pendingLength ?? undefined);
+ const partNow = range ? Math.round((range.endTime - range.startTime) * 1000) / 1000 : (pendingLength?.length ?? undefined);
const fullSetup: GenjutsuSetup = { ...setup, ...(seedNumber !== undefined && !seedProblem(seedNumber) ? { seed: seedNumber } : {}), ...(partNow ? { length: partNow } : {}), originalSound };
// This mode's example for this viewer (none: no card), and whether the form still holds it.
- const example = exampleFor(modeExamples, mode, open);
+ const example = exampleFor(shownExamples, mode, open);
const exampleInUse = !!example && exampleIn === example.id && sameRecipe(toRecipe(fullSetup), example.load.recipe);
const exampleOnlyYou = !!example && owner && !example.load.needs.every((f) => !!live?.[f]);
const body: GenjutsuBody | null =
@@ -688,27 +716,41 @@ export function GenjutsuStudio({ examples, modeExamples, live }: { examples?: Ex
setTapFor(null);
};
- /** Use this example: the form's own words and seed are replaced only after a yes. */
- const ownWords = !!(prompt.trim() || subject.trim() || objectEdit.target?.trim() || objectEdit.becomes?.trim() || character.description?.trim() || picture.adjust?.trim() || words.trim() || seed.trim());
+ /**
+ * Use this example: the form's own words and seed are replaced only after a yes. Words that came with the last
+ * example loaded (and are unchanged) aren't the viewer's: switching to another example asks nothing. The character's
+ * description and who is who stay the viewer's either way, so they never count.
+ */
+ const wordsList = [prompt, subject, objectEdit.target ?? "", objectEdit.becomes ?? "", picture.adjust ?? "", words, isCharacter || fresh || seedShown ? seed : ""].map((w) => w.trim());
+ const wordsNow = wordsList.some(Boolean) ? JSON.stringify(wordsList) : "";
+ if (exampleInUse && wordsNow !== exampleWords) setExampleWords(wordsNow);
+ const ownWords = wordsNow !== "" && wordsNow !== exampleWords;
const pickExample = (card: GenjutsuExampleCard) => (ownWords && !exampleInUse ? setAskReplace(card) : loadExample(card));
const loadExample = (card: GenjutsuExampleCard) => {
- const snap = { mode, engine, tier, quality, charQuality, targets, subject, prompts, lookChoice, look, custom, words, picked, character, action, objectEdit, picture, finish, seed, range, soundAsked, pendingLength, marked, exampleIn, points, paint };
+ const snap = { mode, engine, tier, quality, charQuality, targets, subject, prompts, lookChoice, look, custom, words, picked, character, action, objectEdit, picture, finish, seed, seedFor, range, soundAsked, pendingLength, marked, exampleIn, points, paint };
const r = card.load.recipe;
apply(r, card);
- // The example's own clicks and paint never come with it; the viewer's no longer fit the new settings either.
- setPoints([]);
- setPaint(null);
+ // Who is who, the character's description and the clicks and paint describe the viewer's own clip and photos: kept.
+ if (r.mode === "character") {
+ const own = Object.fromEntries(OWN_CHARACTER_FIELDS.flatMap((k) => (character[k] !== undefined ? [[k, character[k]]] : [])));
+ setCharacter({ ...own, ...(r.character ?? {}) });
+ }
setMarked({ subject: !!r.subject, target: !!r.object?.target });
setExampleIn(card.id);
+ // What the form still needs, said as the next steps: the clip, then the photos the example used.
+ const photos = card.inputs.filter((i) => i.slot.startsWith("photo")).length;
+ const missingPhotos = Math.max(0, photos - ready(refs).length);
+ const photoWords = missingPhotos ? (r.mode === "character" ? (missingPhotos === 1 ? "a character photo" : `${missingPhotos} character photos`) : missingPhotos === 1 ? "a photo" : `${missingPhotos} photos`) : "";
+ const steps = [!clip && "your clip", photoWords].filter(Boolean).join(" and ");
toast("Example loaded", {
id: "gj-example",
- description: clip ? "Check your photos, then Generate." : "Add your clip, then Generate.",
+ description: steps ? `Add ${steps}, then Generate.` : "Check the settings, then Generate.",
duration: 10_000,
action: {
label: "Undo",
onClick: () => {
setMode(snap.mode);
- if (snap.engine !== engine && engineMode === "both") setEngine(snap.engine);
+ if (engineMode === "both") setEngine(snap.engine);
setTier(snap.tier);
setQuality(snap.quality);
setCharQuality(snap.charQuality);
@@ -726,6 +768,7 @@ export function GenjutsuStudio({ examples, modeExamples, live }: { examples?: Ex
setPicture(snap.picture);
setFinish(snap.finish);
setSeed(snap.seed);
+ setSeedFor(snap.seedFor);
if (snap.range) setRange(snap.range);
setOriginalSound(snap.soundAsked);
setPendingLength(snap.pendingLength);
@@ -736,11 +779,19 @@ export function GenjutsuStudio({ examples, modeExamples, live }: { examples?: Ex
},
},
});
- // Next: the clip (no clip yet), else the first thing still missing, else Generate.
+ // Next, with the focus there (the example's button no longer acts): the clip (no clip yet), else the photos still
+ // missing, else the first empty field, else Generate.
requestAnimationFrame(() => {
const reduce = window.matchMedia("(prefers-reduced-motion: reduce)").matches;
- const target = document.getElementById(clip ? (refs.length ? "gj-generate" : "gj-refs") : "gj-clip-drop") ?? document.getElementById("gj-generate");
- target?.scrollIntoView({ block: "center", behavior: reduce ? "auto" : "smooth" });
+ const shown = (el: Element | null): el is HTMLElement => el instanceof HTMLElement && el.getClientRects().length > 0 && !(el as HTMLButtonElement).disabled;
+ const first = (sel: string) => [...document.querySelectorAll(sel)].find(shown);
+ const emptyField = [...document.querySelectorAll<HTMLInputElement | HTMLTextAreaElement>("#gj-side input:not([type]), #gj-side input[type=text], #gj-side textarea")].find((el) => shown(el) && !el.value.trim());
+ const target = !clip
+ ? first("#gj-clip-drop button, #gj-clip-drop [role=button], #gj-clip-drop input:not([type=file])")
+ : (missingPhotos ? first("#gj-refs button") : undefined) ?? emptyField ?? first("#gj-generate");
+ const area = document.getElementById(clip ? (missingPhotos ? "gj-refs" : "gj-generate") : "gj-clip-drop");
+ (target ?? area)?.scrollIntoView({ block: "center", behavior: reduce ? "auto" : "smooth" });
+ target?.focus({ preventScroll: true });
if (!clip) {
setDropRing(true);
setTimeout(() => setDropRing(false), 2000);
@@ -761,13 +812,14 @@ export function GenjutsuStudio({ examples, modeExamples, live }: { examples?: Ex
Whole clips, shot by shot? Open in Character Swap Studio
</Link>
)}
- {visitor && <SelfHostNote className="mt-3 max-w-xl">Genjutsu isn&apos;t available here.</SelfHostNote>}
</ToolHero>
)}
{!clip && example && (
<ModeExample key={example.id} card={example} owner={!visitor} canUse={!visitor} inUse={exampleInUse} onlyYou={exampleOnlyYou} onUse={() => pickExample(example)} className="mt-6" />
)}
<div id="gj-clip-drop" className={cn("mx-auto scroll-mt-24 rounded-2xl transition-shadow", clip ? "pt-4" : "mt-8 max-w-[640px]", dropRing && "ring-2 ring-primary ring-offset-4 ring-offset-background")}>
+ {/* Said by the upload box it turns off (after the mode's example, which every viewer can watch). */}
+ {!clip && visitor && <SelfHostNote className="mb-3">Genjutsu isn&apos;t available here.</SelfHostNote>}
{!clip ? (
<ClipDrop
accept={GENJUTSU.accept}
@@ -945,7 +997,7 @@ export function GenjutsuStudio({ examples, modeExamples, live }: { examples?: Ex
)}
</div>
- <Panel className="space-y-4 lg:sticky lg:top-[calc(var(--chrome-top)+1rem)]">
+ <Panel id="gj-side" className="space-y-4 lg:sticky lg:top-[calc(var(--chrome-top)+1rem)]">
{mode === "picture" && <PictureSteps stage={pictureStage} />}
{example && !visitor && <ModeExampleRow key={example.id} card={example} owner canUse inUse={exampleInUse} onlyYou={exampleOnlyYou} onUse={() => pickExample(example)} />}
<p className="text-[13px] text-pretty text-muted-foreground">{hint}</p>
diff --git a/src/components/genjutsu/mode-example.tsx b/src/components/genjutsu/mode-example.tsx
index 25e43fae..1515104e 100644
--- a/src/components/genjutsu/mode-example.tsx
+++ b/src/components/genjutsu/mode-example.tsx
@@ -6,15 +6,15 @@ import { toast } from "sonner";
import { Button } from "@/components/ui/button";
import { Dialog, DialogContent, DialogDescription, DialogHeader, DialogTitle } from "@/components/ui/dialog";
import { copyText } from "@/lib/clipboard";
-import { encodeSetup, getMaker } from "@/lib/catalog/genjutsu";
-import type { GenjutsuExampleCard } from "@/lib/examples/genjutsu";
+import { encodeSetup } from "@/lib/catalog/genjutsu";
+import { exampleSettings, type GenjutsuExampleCard } from "@/lib/examples/genjutsu";
import { cn } from "@/lib/utils";
import { OnlyYou } from "./openjutsu-panels";
/**
* A Genjutsu mode's example, under the mode's title: one muted before → after loop (the clip that went in, then what
* came out), what went in, the settings it used, and "Use this example", which puts those settings into the form and
- * keeps the viewer's own clip and photos. Visitors, who can't run Genjutsu here, copy its setup instead.
+ * keeps the viewer's own clip and photos. Visitors, who can't run Genjutsu here, see the loop and how it was made.
*
* Loading: a still in a fixed 4:3 box first (nothing moves when the clip arrives). The clip downloads only once the
* card is at least half in view, and not at all with Save-Data or reduced motion (then the finished result shows as a
@@ -23,8 +23,6 @@ import { OnlyYou } from "./openjutsu-panels";
/** Where the clip that went in sits in an inset loop (clip-show: 308×230 at 24 px from the corner of 1024×768). */
const INSET = { left: `${(24 / 1024) * 100}%`, top: `${((768 - 24 - 230) / 768) * 100}%` };
-/** The wipe's line reaches the middle at 1.7 s: before that the frame is mostly the clip that went in. */
-const WIPE_MIDDLE = 1.7;
const reducedMotion = () => typeof window !== "undefined" && window.matchMedia("(prefers-reduced-motion: reduce)").matches;
const saveData = () => typeof navigator !== "undefined" && !!(navigator as Navigator & { connection?: { saveData?: boolean } }).connection?.saveData;
@@ -50,39 +48,43 @@ function Loop({ card }: { card: GenjutsuExampleCard }) {
const box = useRef<HTMLDivElement>(null);
const video = useRef<HTMLVideoElement>(null);
const [inView, setInView] = useState(false);
- // null: plays by itself when it can; true / false: the viewer pressed Pause or Play.
+ // null: plays by itself when it can; true / false: the viewer pressed Play or Pause.
const [chosen, setChosen] = useState<boolean | null>(null);
// Reduced motion or Save-Data: the finished result as a still, and the clip only on Play (false while the page hydrates).
const still = useSyncExternalStore(watchStill, () => reducedMotion() || saveData(), () => false);
- const [late, setLate] = useState(false);
+ // What the video itself reports (a refused play() — Low Power Mode, autoplay off — stays "not playing").
+ const [playing, setPlaying] = useState(false);
+ // The clip didn't load: the still stays, with no button that can't do anything.
+ const [failed, setFailed] = useState(false);
const out = card.output;
const rest = out.rest?.src;
useEffect(() => {
const el = box.current;
if (!el || typeof IntersectionObserver === "undefined") return;
- const io = new IntersectionObserver(([e]) => setInView(e.isIntersecting), { rootMargin: "200px 0px", threshold: 0.5 });
+ // Half of the card on screen (no margin: the ratio is of the screen itself).
+ const io = new IntersectionObserver(([e]) => setInView(e.isIntersecting), { threshold: 0.5 });
io.observe(el);
return () => io.disconnect();
}, []);
- const wanted = chosen ?? (!still && inView);
+ const wanted = !failed && (chosen ?? (!still && inView));
// The clip is fetched once it is first wanted, and kept while the mode stays (a scroll back plays at once).
const [loaded, setLoaded] = useState(false);
if (wanted && !loaded) setLoaded(true);
useEffect(() => {
const v = video.current;
- if (!v || !loaded) return;
+ if (!v || !loaded || failed) return;
const hidden = () => document.visibilityState === "hidden";
const sync = () => {
- if (wanted && inView && !hidden()) void v.play().catch(() => {});
+ if (wanted && (inView || chosen) && !hidden()) void v.play().catch(() => setPlaying(false));
else v.pause();
};
sync();
document.addEventListener("visibilitychange", sync);
return () => document.removeEventListener("visibilitychange", sync);
- }, [loaded, wanted, inView]);
+ }, [loaded, failed, wanted, inView, chosen]);
// The mode changes (this card leaves): its download stops.
useEffect(() => {
@@ -95,24 +97,13 @@ function Loop({ card }: { card: GenjutsuExampleCard }) {
};
}, [loaded]);
- // The wipe's single label follows the line: "Before" until the result has most of the frame.
- useEffect(() => {
- const v = video.current;
- if (!v || !loaded || card.load.layout !== "wipe") return;
- const tick = () => setLate(v.currentTime >= WIPE_MIDDLE);
- v.addEventListener("timeupdate", tick);
- return () => v.removeEventListener("timeupdate", tick);
- }, [loaded, card.load.layout]);
-
- const playing = loaded && wanted;
// Before the clip: the reduced-motion still is the finished result; otherwise the loop's first frame.
const poster = still && rest ? rest : (out.poster ?? rest);
- const showsResult = still && !loaded ? true : late;
return (
<div ref={box} className="relative aspect-[4/3] w-full overflow-hidden bg-muted">
{/* eslint-disable-next-line @next/next/no-img-element */}
{poster && <img src={poster} alt="" decoding="async" fetchPriority="low" className="absolute inset-0 size-full object-cover" draggable={false} />}
- {loaded && (
+ {loaded && !failed && (
<video
ref={video}
src={out.src}
@@ -124,42 +115,49 @@ function Loop({ card }: { card: GenjutsuExampleCard }) {
aria-label={card.caption}
className="absolute inset-0 size-full object-cover"
data-example-video=""
+ onPlay={() => setPlaying(true)}
+ onPause={() => setPlaying(false)}
+ onError={() => {
+ setPlaying(false);
+ setFailed(true);
+ }}
/>
)}
+ {/* The result is on the left of a wipe and fills an inset loop: "After" sits top left on both. */}
+ <Pill className="top-2 left-2">After</Pill>
{card.load.layout === "inset" ? (
- <>
- <Pill className="top-2 right-2">After</Pill>
- <Pill style={{ left: `calc(${INSET.left} + 6px)`, top: `calc(${INSET.top} + 6px)` }} className="bg-black/60 text-[11px]">
- Before
- </Pill>
- </>
+ <Pill style={{ left: `calc(${INSET.left} + 6px)`, top: `calc(${INSET.top} + 6px)` }} className="bg-black/60 text-[11px]">
+ Before
+ </Pill>
) : (
- <Pill className="top-2 left-2">{showsResult ? "After" : "Before"}</Pill>
+ <Pill className="top-2 right-2">Before</Pill>
+ )}
+ {!failed && (
+ <button
+ type="button"
+ onClick={() => setChosen(!playing)}
+ aria-label={playing ? "Pause the example" : "Play the example"}
+ className="absolute right-2 bottom-2 grid size-11 place-items-center rounded-full bg-black/55 text-white outline-none hover:bg-black/70 focus-visible:ring-2 focus-visible:ring-white"
+ >
+ {playing ? <Pause className="size-4" /> : <Play className="size-4 translate-x-px" />}
+ </button>
)}
- <button
- type="button"
- onClick={() => setChosen(!playing)}
- aria-label={playing ? "Pause the example" : "Play the example"}
- className="absolute right-2 bottom-2 grid size-11 place-items-center rounded-full bg-black/55 text-white outline-none hover:bg-black/70 focus-visible:ring-2 focus-visible:ring-white"
- >
- {playing ? <Pause className="size-4" /> : <Play className="size-4 translate-x-px" />}
- </button>
</div>
);
}
-/** Copies the example's setup as a link (a visitor pastes it into Genjutsu on their own Fuobe). */
+/** Copies the example's setup as a link (the owner pastes it into another Fuobe of theirs, or sends it on). */
async function copySetup(card: GenjutsuExampleCard) {
const link = `${window.location.origin}/genjutsu?setup=${encodeSetup(card.load.recipe)}`;
- if (await copyText(link)) toast("Setup copied", { description: "Paste it in Genjutsu on your own Fuobe." });
+ if (await copyText(link)) toast("Setup copied", { description: "Paste it in Genjutsu's Paste setup." });
else toast.error("Couldn't copy — your browser blocked the clipboard");
}
export interface ModeExampleProps {
card: GenjutsuExampleCard;
- /** The owner (or a studio of one's own): Use this example, the model's name, and Only you where it applies. */
+ /** The owner (or a studio of one's own): Use this example, the model's name, the seed, and Only you where it applies. */
owner: boolean;
- /** Genjutsu runs here: Use this example (else Copy its setup only). */
+ /** Genjutsu runs here: Use this example and Copy its setup (a visitor gets the loop and how it was made only). */
canUse: boolean;
/** The form still holds this example's settings. */
inUse: boolean;
@@ -169,24 +167,27 @@ export interface ModeExampleProps {
className?: string;
}
-/** The example card: the loop on the left (on top on a phone), what it is and what it used beside it. */
+/**
+ * The example card, as wide as the page's column (640 px): the loop beside its title on a wide screen, above it on a
+ * phone. What went in and the settings sit behind "How it was made" (on a phone the words too), so the upload box stays
+ * close.
+ */
export function ModeExample({ card, owner, canUse, inUse, onlyYou, onUse, className }: ModeExampleProps) {
- const r = card.load.recipe;
- const model = owner ? getMaker(r.model, r.engine)?.label : undefined;
- const settings = [...(model ? [model] : []), ...(card.chips ?? [])];
+ const settings = exampleSettings(card.load.recipe, { owner });
const titleId = `gj-example-${card.id.replace(/\W/g, "-")}`;
+ const words = card.words && <p className="text-[13px] leading-relaxed text-pretty text-muted-foreground">{card.words}</p>;
return (
<figure
aria-labelledby={titleId}
data-mode-example={card.id}
className={cn(
- "mx-auto grid w-full max-w-[960px] grid-cols-1 overflow-hidden rounded-2xl border bg-background text-left shadow-soft md:grid-cols-[minmax(0,1fr)_352px]",
+ "mx-auto grid w-full max-w-[640px] grid-cols-1 overflow-hidden rounded-2xl border bg-background text-left shadow-soft md:grid-cols-[minmax(0,1fr)_248px]",
inUse && "ring-2 ring-primary ring-offset-2 ring-offset-background",
className,
)}
>
<Loop card={card} />
- <figcaption className="flex min-w-0 flex-col gap-3 p-4 md:p-5">
+ <figcaption className="flex min-w-0 flex-col gap-3 p-4">
<div>
<p className="flex items-center gap-1.5 text-[11px] font-semibold text-muted-foreground">
<span className="tracking-wider uppercase">Example</span>
@@ -195,57 +196,57 @@ export function ModeExample({ card, owner, canUse, inUse, onlyYou, onUse, classN
<h3 id={titleId} className="mt-1 text-[16px] leading-snug font-semibold text-balance">
{card.caption}
</h3>
- {card.words && <p className="mt-1.5 text-[13px] leading-relaxed text-pretty text-muted-foreground">{card.words}</p>}
+ {words && <div className="mt-1.5 hidden md:block">{words}</div>}
</div>
- <div>
- <p className="text-[12px] font-medium">What went in</p>
- <div className="mt-1.5 flex items-center gap-2">
- {card.inputs.map((i) => (
- // eslint-disable-next-line @next/next/no-img-element
- <img
- key={i.slot}
- src={i.media.thumb ?? i.media.src}
- alt={i.label ?? ""}
- loading="lazy"
- decoding="async"
- className={cn("h-12 shrink-0 rounded-md bg-muted object-cover", i.slot === "clip" ? "w-16" : "w-9")}
- />
- ))}
- <span className="min-w-0 text-[13px] text-muted-foreground">{card.load.went}</span>
+ {canUse && (
+ <div className="flex gap-2">
+ <Button
+ variant={inUse ? "outline" : "default"}
+ className={cn("h-11 min-w-0 flex-1 rounded-full", inUse && "cursor-default text-foreground")}
+ onClick={inUse ? undefined : onUse}
+ aria-disabled={inUse || undefined}
+ data-use-example=""
+ >
+ {inUse ? <Check className="size-4" /> : <Sparkles className="size-4" />}
+ {inUse ? "In use" : "Use this example"}
+ </Button>
+ <Button variant="outline" className="size-11 shrink-0 rounded-full p-0" onClick={() => void copySetup(card)} aria-label="Copy its setup" title="Copy its setup">
+ <Copy className="size-4" />
+ </Button>
</div>
- </div>
- {/* The settings: open beside the loop on a wide screen, behind a tap on a phone. */}
- <div className="hidden md:block">
- <p className="text-[12px] font-medium">Settings it used</p>
- <Settings items={settings} />
- </div>
- <details className="group md:hidden">
- <summary className="flex min-h-11 cursor-pointer list-none items-center gap-1.5 text-[13px] font-medium outline-none focus-visible:ring-2 focus-visible:ring-ring [&::-webkit-details-marker]:hidden">
- <span className="inline-block transition-transform group-open:rotate-90" aria-hidden>
+ )}
+ <details className="group -mt-1">
+ <summary className="flex min-h-11 cursor-pointer list-none items-center gap-1.5 rounded-md text-[13px] font-medium outline-none focus-visible:ring-2 focus-visible:ring-ring [&::-webkit-details-marker]:hidden">
+ <span className="inline-block transition-transform group-open:rotate-90 motion-reduce:transition-none" aria-hidden>
›
</span>
- Settings it used
+ How it was made
</summary>
- <Settings items={settings} />
+ <div className="space-y-3 pt-1 pb-1">
+ {words && <div className="md:hidden">{words}</div>}
+ <div>
+ <p className="text-[12px] font-medium">What went in</p>
+ <div className="mt-1.5 flex items-center gap-2">
+ {card.inputs.map((i) => (
+ // eslint-disable-next-line @next/next/no-img-element
+ <img
+ key={i.slot}
+ src={i.media.thumb ?? i.media.src}
+ alt={i.label ?? ""}
+ loading="lazy"
+ decoding="async"
+ className={cn("h-12 shrink-0 rounded-md bg-muted object-cover", i.slot === "clip" ? "w-16" : "w-9")}
+ />
+ ))}
+ <span className="min-w-0 text-[13px] text-muted-foreground">{card.load.went}</span>
+ </div>
+ </div>
+ <div>
+ <p className="text-[12px] font-medium">Settings it used</p>
+ <Settings items={settings} />
+ </div>
+ </div>
</details>
- {/* One 44 px row for every viewer: the card keeps its height when the owner's page switches at hydration. */}
- <div className="mt-auto flex gap-2 pt-1">
- {canUse ? (
- <>
- <Button className="h-11 min-w-0 flex-1 rounded-full" onClick={onUse} disabled={inUse} data-use-example="">
- {inUse ? <Check className="size-4" /> : <Sparkles className="size-4" />}
- {inUse ? "In use" : "Use this example"}
- </Button>
- <Button variant="outline" className="size-11 shrink-0 rounded-full p-0" onClick={() => void copySetup(card)} aria-label="Copy its setup" title="Copy its setup">
- <Copy className="size-4" />
- </Button>
- </>
- ) : (
- <Button variant="outline" className="h-11 w-full rounded-full" onClick={() => void copySetup(card)}>
- <Copy className="size-4" /> Copy its setup
- </Button>
- )}
- </div>
</figcaption>
</figure>
);
diff --git a/src/components/genjutsu/setup-code.tsx b/src/components/genjutsu/setup-code.tsx
index 51bbf4ea..1064612c 100644
--- a/src/components/genjutsu/setup-code.tsx
+++ b/src/components/genjutsu/setup-code.tsx
@@ -24,13 +24,19 @@ export function SetupCode({ setup, onPaste }: { setup: GenjutsuSetup; onPaste: (
};
const paste = () => {
const s = decodeSetup(text);
- if (!s) return void toast.error("That isn't a Genjutsu setup code (they start with gj1. or gj2.)");
+ if (!s) {
+ // A later code version (gj3.…): this install is older than the one that made it.
+ const v = /gj(\d+)\./.exec(text);
+ if (v && Number(v[1]) > 2) return void toast.error("That setup comes from a newer Fuobe. Update this one to paste it.");
+ return void toast.error("That isn't a Genjutsu setup code (they start with gj1. or gj2.)");
+ }
onPaste(s);
setOpen(false);
setText("");
};
return (
- <div className="flex items-center gap-1">
+ // The same space between Copy setup, Paste setup and the engine switch after them (the ghost buttons' own padding counts).
+ <div className="mr-1 flex items-center gap-0.5">
<Button variant="ghost" size="sm" className="rounded-full" onClick={() => void copy()} aria-label="Copy setup">
<Copy className="size-3.5" />
<span className="hidden sm:inline">Copy setup</span>
diff --git a/src/components/nav/viewer-slot.tsx b/src/components/nav/viewer-slot.tsx
index 44f2ee71..f7ee12b6 100644
--- a/src/components/nav/viewer-slot.tsx
+++ b/src/components/nav/viewer-slot.tsx
@@ -17,10 +17,10 @@ import { useViewerKind } from "./nav-ui";
/**
* Fixed widths, so the placeholder and what replaces it take the same room: Log in 68 (from 1440 px), Sign up 84, the menu
- * button 40 like the bar's other items (44 on a touch screen), 6 between.
+ * button 40 like the bar's other items (44 on a touch screen), 8 between (the bar's own gap).
*/
export const VIEWER_W = {
- guest: "w-[130px] min-[1440px]:w-[204px] [@media(pointer:coarse)]:w-[134px] [@media(pointer:coarse)]:min-[1440px]:w-[208px]",
+ guest: "w-[132px] min-[1440px]:w-[208px] [@media(pointer:coarse)]:w-[136px] [@media(pointer:coarse)]:min-[1440px]:w-[212px]",
member: "w-10 [@media(pointer:coarse)]:w-11",
} as const;
@@ -76,7 +76,7 @@ export function ViewerSlot() {
</span>
);
return (
- <span data-slot="viewer" className={cn("flex shrink-0 items-center justify-end gap-1.5", VIEWER_W.guest)}>
+ <span data-slot="viewer" className={cn("flex shrink-0 items-center justify-end gap-2", VIEWER_W.guest)}>
<Suspense fallback={<GuestButtons here="/" />}>
<GuestButtonsHere />
</Suspense>
diff --git a/src/lib/catalog/genjutsu.ts b/src/lib/catalog/genjutsu.ts
index a8a780ca..3718064d 100644
--- a/src/lib/catalog/genjutsu.ts
+++ b/src/lib/catalog/genjutsu.ts
@@ -251,6 +251,9 @@ export interface FinishOptions {
soften?: number;
}
+/** Fix colours' settings when a request leaves them out (one source for the plan and an example's card). */
+export const FINISH_COLOURS_DEFAULT: Required<Pick<FinishOptions, "finish" | "strength" | "soften">> = { finish: "soft", strength: 0.4, soften: 0.33 };
+
/** The part a new maker takes (seconds): Group swap, Scene edit and From picture 2–15 s; Finish the whole clip. */
export const OPENJUTSU_LIMITS = { minSeconds: 2, maxSeconds: 15, facesMaxSeconds: 10, coloursMaxSeconds: 60, maxCharacters: 4, roleChars: 80, lightChars: 300, sceneChars: 2000 } as const;
@@ -1906,7 +1909,7 @@ function planOpenjutsu(input: GenjutsuPlanInput): GenjutsuPlan {
const settings =
m.tool === "faces"
? { faceStyle: f.faceStyle ?? "mouth", chunkSeconds: f.chunkSeconds ?? 6.5 }
- : { finish: f.finish ?? "soft", strength: f.strength ?? 0.4, soften: f.soften ?? 0.33 };
+ : { finish: f.finish ?? FINISH_COLOURS_DEFAULT.finish, strength: f.strength ?? FINISH_COLOURS_DEFAULT.strength, soften: f.soften ?? FINISH_COLOURS_DEFAULT.soften };
const step = job("fix", m.tool === "faces" ? "face-fix-video" : "tone-video", m.tool === "faces" ? "Fix the faces" : "Fix the colours", m.tool === "faces" ? input.references.slice(0, 1) : [], settings);
if (!steps.length) {
delete step.after;
@@ -2205,7 +2208,9 @@ export function encodeSetup(s: GenjutsuSetup): string {
pl: lengthOf(s.length),
os: s.originalSound,
};
- return `gj2.${toBase64Url(JSON.stringify(o))}`;
+ // gj1 while none of gj2's own fields is set: an install that reads only gj1 still pastes it.
+ const v = o.sd === undefined && o.pl === undefined && o.os === undefined ? "gj1" : "gj2";
+ return `${v}.${toBase64Url(JSON.stringify(o))}`;
}
/** A part's length as a code keeps it: 3 decimals, 1 to 60 s. */
diff --git a/src/lib/examples/catalog.ts b/src/lib/examples/catalog.ts
index 4914d556..98a92f68 100644
--- a/src/lib/examples/catalog.ts
+++ b/src/lib/examples/catalog.ts
@@ -21,7 +21,7 @@ import {
UPSCALE_STUDIO,
VIDEO_STUDIO,
} from "@/lib/studios";
-import { getMaker, GENJUTSU_MODES, requestFeatures, type GenjutsuMode } from "@/lib/catalog/genjutsu";
+import { getMaker, GENJUTSU_MODES, modeOpen, requestFeatures, type FeatureCheck, type GenjutsuMode } from "@/lib/catalog/genjutsu";
import { exampleSettings, genjutsuSurface, recipeProblem, type GenjutsuExampleCard, type ModeExamples } from "./genjutsu";
import { EXAMPLE_MEDIA, type ExampleMediaFile } from "./media.generated";
import plan from "./plan.json";
@@ -361,11 +361,16 @@ export function exampleRow(surface: ExampleSurface): ExampleRowData | null {
return borrowed.length ? { heading: MORE_HEADING, cards: borrowed, surface } : null;
}
-/** Each Genjutsu mode's examples, best first (the page picks the one a viewer may see: exampleFor in ./genjutsu). */
-export function genjutsuExamples(): ModeExamples {
+/**
+ * Each Genjutsu mode's examples, best first (the page picks the one a viewer may see: exampleFor in ./genjutsu). With
+ * `open`: only the examples whose mode and features it opens (what a page may send to every viewer).
+ */
+export function genjutsuExamples(open?: FeatureCheck): ModeExamples {
const out: ModeExamples = {};
for (const m of GENJUTSU_MODES) {
- const cards = (ALL.bySurface.get(genjutsuSurface(m.id)) ?? []) as GenjutsuExampleCard[];
+ if (open && !modeOpen(m.id, open)) continue;
+ const all = (ALL.bySurface.get(genjutsuSurface(m.id)) ?? []) as GenjutsuExampleCard[];
+ const cards = open ? all.filter((c) => c.load.needs.every(open)) : all;
if (cards.length) out[m.id] = cards;
}
return out;
diff --git a/src/lib/examples/genjutsu.ts b/src/lib/examples/genjutsu.ts
index 9a834138..3b7f52ea 100644
--- a/src/lib/examples/genjutsu.ts
+++ b/src/lib/examples/genjutsu.ts
@@ -9,6 +9,7 @@ import {
ALL_FEATURES,
decodeSetup,
encodeSetup,
+ FINISH_COLOURS_DEFAULT,
GENJUTSU,
getMaker,
lookName,
@@ -113,28 +114,29 @@ export function recipeProblem(r: GenjutsuRecipe, mode: GenjutsuMode): string | n
return null;
}
-const seconds = (n: number) => `${Math.round(n * 10) / 10} s`;
const FINISH_LABEL: Record<string, string> = { soft: "Soft film", filmic: "Filmic", rich: "Rich", off: "Off" };
-/** "Settings it used", as the form labels them (no model names: the owner's card adds the model). */
-export function exampleSettings(r: GenjutsuRecipe): string[] {
+/**
+ * "Settings it used", as the form labels them. Everyone: the size, the length in whole seconds (as "What went in" says
+ * it) and the sound. The owner's card adds the model first (not for Finish, whose finish chip already names it), the
+ * seed and the exact length. The copied setup keeps every one.
+ */
+export function exampleSettings(r: GenjutsuRecipe, opts: { owner?: boolean } = {}): string[] {
const out: string[] = [];
const maker = getMaker(r.model, r.engine);
- // The tool's own name is a model's too: the finish says which one it was.
- if (r.mode === "finish" && r.finish) {
- if (r.finish.tool === "colours") {
- out.push(`Finish: ${FINISH_LABEL[r.finish.finish ?? "soft"]}`);
- out.push(`Strength ${Math.round((r.finish.strength ?? 0.4) * 100)}%`);
- out.push(`Soften detail ${Math.round((r.finish.soften ?? 0.33) * 100)}%`);
- }
+ if (opts.owner && maker && r.mode !== "finish") out.push(maker.label);
+ if (r.mode === "finish" && r.finish?.tool === "colours") {
+ out.push(`Finish: ${FINISH_LABEL[r.finish.finish ?? FINISH_COLOURS_DEFAULT.finish]}`);
+ out.push(`Strength ${Math.round((r.finish.strength ?? FINISH_COLOURS_DEFAULT.strength) * 100)}%`);
+ out.push(`Soften detail ${Math.round((r.finish.soften ?? FINISH_COLOURS_DEFAULT.soften) * 100)}%`);
}
if (r.object) out.push(SCENE_ACTIONS.find((a) => a.id === r.object!.action)!.label);
if (r.look) out.push(`Look: ${lookName(r.look)}`);
if (r.tier) out.push(r.tier === "high" ? "High" : "Standard");
if (r.quality && maker && (maker.qualities || maker.h3)) out.push(r.quality);
- if (r.seed !== undefined) out.push(`Seed ${r.seed}`);
- out.push(`Part ${seconds(r.length)}`);
- if (r.originalSound) out.push(`Sound: ${originalSoundLabel(r.originalSound)}`);
+ out.push(opts.owner ? `${Math.round(r.length * 10) / 10} s` : `${Math.max(1, Math.round(r.length))} s`);
+ if (r.originalSound) out.push(r.originalSound === "everything" ? "Original sound" : `Sound: ${originalSoundLabel(r.originalSound)}`);
+ if (opts.owner && r.seed !== undefined) out.push(`Seed ${r.seed}`);
return out;
}
diff --git a/src/lib/examples/media.generated.ts b/src/lib/examples/media.generated.ts
index 4e0b3f7d..432d044d 100644
--- a/src/lib/examples/media.generated.ts
+++ b/src/lib/examples/media.generated.ts
@@ -6246,26 +6246,26 @@ export const EXAMPLE_MEDIA: Record<string, ExampleMediaFile> = {
"/examples/genjutsu-finish/1/show.mp4": {
"role": "show",
"type": "video/mp4",
- "bytes": 929162,
- "sha256": "5fcb43976934bb5380a9f8ce6b1a7a9dbd672ba795e6d0dbcde4c4bc82358543",
- "v": "5fcb4397",
- "poster": "/examples/genjutsu-finish/1/show.poster.webp?v=e86785a4"
+ "bytes": 994222,
+ "sha256": "70fbc6365d6cb3be84d63a6621920297fbbad5a3250f86fac5cee6080a7b1f8b",
+ "v": "70fbc636",
+ "poster": "/examples/genjutsu-finish/1/show.poster.webp?v=043b6b4f"
},
"/examples/genjutsu-finish/1/show.peak.webp": {
"role": "show",
"type": "image/webp",
- "bytes": 20826,
- "sha256": "72772e4cacbb0938f7647cb7546375ff3ff18a8e4248b43c6fb9865a126c4202",
- "v": "72772e4c",
+ "bytes": 24276,
+ "sha256": "6cec7a2fc3a3af20b7209921a11f5003fe5c35ebab3725af349434d499148228",
+ "v": "6cec7a2f",
"w": 512,
"h": 384
},
"/examples/genjutsu-finish/1/show.poster.webp": {
"role": "show",
"type": "image/webp",
- "bytes": 77530,
- "sha256": "e86785a43477f83144837904306d04ffcfb0872469ab09109a00eb2e47fce8e9",
- "v": "e86785a4",
+ "bytes": 68274,
+ "sha256": "043b6b4f591edadea151604aeac0d83095d04962210ac6278cabdbdae7dd68f8",
+ "v": "043b6b4f",
"w": 1024,
"h": 768
},
diff --git a/src/lib/examples/plan.json b/src/lib/examples/plan.json
index b1e3f180..3f4069f7 100644
--- a/src/lib/examples/plan.json
+++ b/src/lib/examples/plan.json
@@ -4766,7 +4766,10 @@
"engine": "open",
"model": "oss-fix-colours",
"finish": {
- "tool": "colours"
+ "tool": "colours",
+ "finish": "soft",
+ "strength": 0.4,
+ "soften": 0.33
},
"length": 5.166,
"originalSound": "everything"
diff --git a/tests/e2e/genjutsu-examples.mjs b/tests/e2e/genjutsu-examples.mjs
index cd18080b..bc08a462 100644
--- a/tests/e2e/genjutsu-examples.mjs
+++ b/tests/e2e/genjutsu-examples.mjs
@@ -1,12 +1,16 @@
// Genjutsu's mode examples, browser check at 390 and 1440 px, light and dark. Each mode tab: the selected mode's example
// card shows when the mode has one for this viewer (one card at most, none for a mode without one); its loop downloads
// only once the card is half in view and plays muted; nothing moves when it arrives; the pause button, the actions and
-// the settings toggle are 44 px; switching modes drops the loop. Reduced motion: the finished result as a still, no
-// download until Play. Visitors (--viewer guest | account: a studio with a password and public sign-up) see the video,
-// the settings and Copy its setup, and no Use this example, no model names, no "Only you". The owner: Use this example
-// with no clip marks the card "In use" (the form's setup equals the recipe), Undo puts the form back, and with a clip
-// and the example's kind of photos the estimate's request body equals the run that made the example
-// (tests/fixtures/genjutsu-examples/<id>.json; the clip, photos and who-is-who are the test's own).
+// "How it was made" are 44 px; switching modes drops the loop; the card is the page column's width (640 px) and on a
+// phone short enough to leave the upload box close. Reduced motion: the finished result as a still, no download until
+// Play. Visitors (--viewer guest | account: a studio with a password and public sign-up) see the video and how it was
+// made, no action row (nothing there they could run), no model names, no "Only you", and "isn't available" under the
+// card by the upload box. The owner: Use this example with no clip marks the card "In use" (the form's setup equals the
+// recipe), moves the focus to Choose a video, says what is still needed, and Undo puts the form back; a second mode's
+// example after the first asks nothing; a clip added after an example takes the example's length, and a mode change
+// drops it; with a clip and the example's kind of photos the estimate's request body equals the run that made the
+// example (tests/fixtures/genjutsu-examples/<id>.json; the clip, photos and who-is-who are the test's own, and who is who
+// typed before Use this example stays).
// Usage: node tests/e2e/genjutsu-examples.mjs [appUrl] [--viewer owner|guest|account] [--shots <dir>] Exits 1 on a failed check.
import fs from "node:fs";
import path from "node:path";
@@ -139,27 +143,34 @@ try {
}
const loopBox = await c.locator("[data-example-video]").boundingBox();
check(`${tag} ${label}: the loop is 4:3 and at least 358 px wide`, !!loopBox && loopBox.width >= 340 && Math.abs(loopBox.width / loopBox.height - 4 / 3) < 0.02, loopBox ? `${Math.round(loopBox.width)}×${Math.round(loopBox.height)}` : "none");
+ const cardBox = await c.boundingBox();
+ const dropBox = await page.locator("#gj-clip-drop").boundingBox();
if (width >= 1440) {
const side = await c.locator("figcaption").boundingBox();
- // 960 px with its 1 px border: the loop takes what the 352 px column leaves.
- check(`${tag} ${label}: 960 px card, a 352 px column beside the loop`, Math.round((await c.boundingBox()).width) === 960 && Math.round(side.width) === 352 && Math.round(loopBox.width) === 606, `${Math.round((await c.boundingBox()).width)} / ${Math.round(side.width)} / ${Math.round(loopBox.width)}`);
+ // 640 px with its 1 px border, lined up with the upload box: the loop takes what the 248 px column leaves.
+ check(`${tag} ${label}: 640 px card in the page's column, a 248 px column beside the loop`, Math.round(cardBox.width) === 640 && Math.round(side.width) === 248 && Math.round(loopBox.width) === 390 && Math.abs(cardBox.x - dropBox.x) < 1, `${Math.round(cardBox.width)} / ${Math.round(side.width)} / ${Math.round(loopBox.width)} / x ${Math.round(cardBox.x)} vs ${Math.round(dropBox.x)}`);
+ } else {
+ check(`${tag} ${label}: the phone card is short (480 px at most)`, cardBox.height <= 480, `${Math.round(cardBox.height)} px`);
}
const sizes = await c.evaluate((el) => [...el.querySelectorAll("button, summary")].filter((b) => b.getClientRects().length).map((b) => `${b.getAttribute("aria-label") ?? b.textContent?.trim()}:${Math.round(b.getBoundingClientRect().width)}x${Math.round(b.getBoundingClientRect().height)}`));
check(`${tag} ${label}: every target is 44 px or more`, sizes.every((s) => s.split(":").pop().split("x").every((d) => Number(d) >= 44) || /summary/.test(s)), JSON.stringify(sizes));
const summary = c.locator("summary");
- if (await summary.isVisible()) check(`${tag} ${label}: "Settings it used" is a 44 px toggle`, ((await summary.boundingBox())?.height ?? 0) >= 44);
+ check(`${tag} ${label}: "How it was made" is a 44 px toggle`, (await summary.innerText()).includes("How it was made") && ((await summary.boundingBox())?.height ?? 0) >= 44);
// Pause and play.
await c.getByRole("button", { name: "Pause the example" }).click();
check(`${tag} ${label}: Pause stops the loop`, !(await playing()));
await c.getByRole("button", { name: "Play the example" }).click();
check(`${tag} ${label}: Play starts it again`, await playing());
- const text = await c.innerText();
+ const text = await c.evaluate((el) => el.textContent ?? "");
check(`${tag} ${label}: "EXAMPLE", the title and "What went in"`, /example/i.test(text) && text.includes(row.caption) && text.includes("What went in") && row.caption.length <= 40);
+ if (visitor) check(`${tag} ${label}: no seed or "Part" chip for a visitor`, !/Seed \d|Part \d/.test(text), text.replace(/\s+/g, " ").slice(-120));
check(`${tag} ${label}: no test words or file paths`, !/\b(test|pass(ed)?|owner|validated|oss-|\/api\/)/i.test(text), text.replace(/\s+/g, " ").slice(0, 160));
if (visitor) {
check(`${tag} ${label}: a visitor has no Use this example`, (await c.locator("[data-use-example]").count()) === 0);
- check(`${tag} ${label}: a visitor can copy its setup`, await c.getByRole("button", { name: /Copy its setup/ }).isVisible());
+ check(`${tag} ${label}: a visitor has no action row (only Play/Pause and How it was made)`, (await c.getByRole("button", { name: /Copy its setup/ }).count()) === 0 && (await c.locator("button").count()) === 1);
check(`${tag} ${label}: no model names and no "Only you" for a visitor`, !/Group swap|Colour finish|Only you|MiniMax|H3/.test(text));
+ const noteBox = await page.getByText("Genjutsu isn't available here.").first().boundingBox();
+ check(`${tag} ${label}: "isn't available" sits under the card, by the upload box`, !!noteBox && noteBox.y > cardBox.y + cardBox.height && noteBox.y < dropBox.y + dropBox.height, noteBox ? `${Math.round(noteBox.y)}` : "none");
} else {
check(`${tag} ${label}: the owner has Use this example`, await c.locator("[data-use-example]").isVisible());
}
@@ -174,9 +185,15 @@ try {
if (!visitor && scheme === "light") {
await open(`/genjutsu?mode=${id}`);
await card().locator("[data-use-example]").click();
- await page.waitForTimeout(600);
+ await page.waitForTimeout(900);
const used = card().locator("[data-use-example]");
check(`${tag} ${label}: Use this example fills the form exactly ("In use")`, (await used.innerText()).includes("In use"), await used.innerText());
+ check(`${tag} ${label}: "In use" says so without turning off (aria-disabled, focusable)`, (await used.getAttribute("aria-disabled")) === "true" && (await used.evaluate((b) => !b.disabled)));
+ const focused = await page.evaluate(() => document.activeElement?.textContent?.trim() || document.activeElement?.tagName);
+ check(`${tag} ${label}: the focus moves to Choose a video`, focused === "Choose a video", String(focused));
+ const photos = Object.keys(row.inputs).filter((k) => k.startsWith("photo")).length;
+ const want = `Add your clip${photos ? ` and ${photos} character photos` : ""}, then Generate.`;
+ check(`${tag} ${label}: the toast says what is still needed`, await page.getByText(want).isVisible().catch(() => false), want);
check(`${tag} ${label}: it runs nothing (no run request)`, runs.length === 0);
const undo = page.getByRole("button", { name: "Undo" });
if (await undo.isVisible().catch(() => false)) {
@@ -186,6 +203,19 @@ try {
} else check(`${tag} ${label}: the toast offers Undo`, false);
}
}
+
+ // The owner: one example, then another mode's: no "Replace your settings?" (the words were the first example's).
+ const ids = Object.keys(expected);
+ if (!visitor && scheme === "light" && ids.length >= 2) {
+ await open(`/genjutsu?mode=${ids[0]}`);
+ await card().locator("[data-use-example]").click();
+ await page.waitForTimeout(600);
+ await page.getByRole("tablist", { name: "Genjutsu modes" }).getByRole("tab", { name: new RegExp(`^${MODES[ids[1]]}`) }).click();
+ await page.waitForTimeout(500);
+ await card().locator("[data-use-example]").click();
+ await page.waitForTimeout(600);
+ check(`${tag}: a second mode's example asks nothing`, (await page.getByRole("alertdialog").count()) === 0 && (await card().locator("[data-use-example]").innerText()).includes("In use"));
+ }
await context.close();
// Reduced motion: the result as a still, the loop only on Play.
@@ -242,17 +272,25 @@ try {
const rowEl = page.locator("[data-mode-example-row]");
await rowEl.waitFor({ timeout: 120_000 }).catch(() => {});
check(`owner ${width} ${row.id}: with a clip, one "Example:" row in the side panel`, (await rowEl.count()) === 1 && (await page.locator("[data-mode-example]").count()) === 0);
+ // Who is who in the example's own clip is the viewer's to give: the test gives the example's, before Use this
+ // example where the form asks for it already (it stays), else after.
+ const people = row.genjutsu.own?.character?.people ?? [];
+ const role = (i) => page.getByRole("textbox", { name: `Character ${i + 1} replaces` });
+ const typed = [];
+ for (let i = 0; i < people.length; i++) {
+ if (await role(i).isVisible().catch(() => false)) {
+ await role(i).fill(people[i].role);
+ typed.push(i);
+ }
+ }
await rowEl.getByRole("button", { name: "See it" }).click();
const dialog = page.getByRole("dialog");
await dialog.waitFor({ timeout: 10_000 });
await dialog.locator("[data-use-example]").click();
await page.waitForTimeout(800);
- // Who is who in the example's own clip is the viewer's to give: the test gives the example's.
- const people = row.genjutsu.own?.character?.people ?? [];
for (let i = 0; i < people.length; i++) {
- const field = page.getByRole("textbox", { name: `Character ${i + 1} replaces` });
- check(`owner ${width} ${row.id}: who becomes who is asked again (empty)`, (await field.inputValue()) === "");
- await field.fill(people[i].role);
+ if (typed.includes(i)) check(`owner ${width} ${row.id}: who becomes who typed before stays (${i + 1})`, (await role(i).inputValue()) === people[i].role, await role(i).inputValue());
+ else await role(i).fill(people[i].role);
}
await page.waitForTimeout(1500);
const last = bodies.at(-1);
@@ -261,7 +299,10 @@ try {
const rest = Object.fromEntries(Object.entries(b ?? {}).filter(([k]) => !["source", "references", "requestId", "frame"].includes(k)));
// Finish keeps the clip's size: its quality plays no part in the run (tests/genjutsu-examples.test.ts).
if (rest.mode === "finish") delete rest.quality;
- return JSON.stringify(Object.keys(rest).sort().reduce((o, k) => ((o[k] = rest[k]), o), {}));
+ // Fix colours' settings a run left out are the plan's defaults (FINISH_COLOURS_DEFAULT): the run used them.
+ if (rest.finish?.tool === "colours") rest.finish = { finish: "soft", strength: 0.4, soften: 0.33, ...rest.finish };
+ const sorted = (v) => (Array.isArray(v) ? v.map(sorted) : v && typeof v === "object" ? Object.keys(v).sort().reduce((o, k) => ((o[k] = sorted(v[k])), o), {}) : v);
+ return JSON.stringify(sorted(rest));
};
check(`owner ${width} ${row.id}: the form's request equals the run that made it`, !!last && strip(last) === strip(fixture), `\n form: ${strip(last)}\n run: ${strip(fixture)}`);
check(`owner ${width} ${row.id}: the photos are the viewer's own`, !!last && JSON.stringify(last.references) === JSON.stringify(refs.r ?? []));
@@ -270,6 +311,36 @@ try {
}
}
}
+
+ // The owner: an example with no clip, then a clip: the part takes the example's length; a mode change in between drops it.
+ if (!visitor && expected.finish && expected.character) {
+ for (const switchMode of [false, true]) {
+ const context = await browser.newContext({ viewport: { width: 1440, height: 900 } });
+ await context.addInitScript(() => {
+ try {
+ localStorage.setItem("fuobe.engine", "open");
+ } catch {}
+ });
+ const page = await context.newPage();
+ const bodies = [];
+ page.on("request", (r) => r.method() === "POST" && r.url().endsWith("/api/genjutsu/estimate") && bodies.push(JSON.parse(r.postData() ?? "{}")));
+ await page.goto(`${app}/genjutsu?mode=${switchMode ? "character" : "finish"}`, { waitUntil: "load", timeout: 180_000 });
+ await page.locator("[data-use-example]").first().click();
+ await page.waitForTimeout(600);
+ if (switchMode) {
+ await page.getByRole("tablist", { name: "Genjutsu modes" }).getByRole("tab", { name: /^Finish/ }).click();
+ await page.waitForTimeout(400);
+ }
+ await page.locator("#gj-clip-drop input[type=file]").setInputFiles(path.join(root, "scripts/eval/fixtures/walk-6s.mp4"));
+ await page.waitForFunction(() => !document.querySelector("#gj-clip-drop input[type=file]"), null, { timeout: 120_000 }).catch(() => {});
+ await page.waitForTimeout(6000);
+ const range = bodies.at(-1)?.range;
+ const len = range ? Math.round((range.end - range.start) * 1000) / 1000 : null;
+ const want = switchMode ? 6 : expected.finish.genjutsu.recipe.length;
+ check(`owner: ${switchMode ? "Character swap's example, then Finish, then a clip: the whole clip" : "Finish's example, then a clip: the example's length"}`, len !== null && Math.abs(len - want) < 0.01, `${len} (want ${want})`);
+ await context.close();
+ }
+ }
} finally {
await browser.close();
}
diff --git a/tests/e2e/genjutsu-openjutsu.mjs b/tests/e2e/genjutsu-openjutsu.mjs
index 4ece9538..46625011 100644
--- a/tests/e2e/genjutsu-openjutsu.mjs
+++ b/tests/e2e/genjutsu-openjutsu.mjs
@@ -1,5 +1,5 @@
// Genjutsu's Openjutsu modes, browser check. As the owner (a studio without a password): the From picture and Finish
-// tabs show and every tab is 44 px tall; Character swap with four characters shows Who becomes who, and a tap on the
+// tabs show and every tab is 44 px to tap on a phone (36 px with a mouse); Character swap with four characters shows Who becomes who, and a tap on the
// part's first frame writes where that person stands; From picture's two-step header with step 2 locked until a frame
// is used; Finish's tool switch; nothing scrolls sideways at 390 px. With --guest (a studio with a password and public
// sign-up): the five existing tabs plus the new ones whose features passed their GPU test (workflows/comfyui/gpu-tested.json
@@ -93,8 +93,17 @@ try {
await open("/genjutsu");
const t = await tabs();
check(`${width}: the owner sees From picture and Finish`, t.includes("From picture") && t.includes("Finish"), JSON.stringify(t));
- const heights = await page.evaluate(() => [...document.querySelectorAll('[role="tablist"][aria-label="Genjutsu modes"] [role="tab"]')].map((b) => Math.round(b.getBoundingClientRect().height)));
- check(`${width}: every mode tab is 44 px tall`, heights.every((h) => h >= 44), JSON.stringify(heights));
+ // The pill is 36 px; on a touch screen its tap area (::after, 4 px over and under) is 44 px (src/app/tab-row.css).
+ const heights = await page.evaluate(() =>
+ [...document.querySelectorAll('[role="tablist"][aria-label="Genjutsu modes"] [role="tab"]')].map((b) => {
+ const h = b.getBoundingClientRect().height;
+ const a = getComputedStyle(b, "::after");
+ const touch = matchMedia("(pointer: coarse)").matches && a.content !== "none" && a.position === "absolute";
+ return Math.round(touch ? h - (parseFloat(a.top) || 0) - (parseFloat(a.bottom) || 0) : h);
+ }),
+ );
+ const touch = width < 500;
+ check(`${width}: every mode tab is ${touch ? "44 px to tap" : "36 px or more"}`, heights.every((h) => h >= (touch ? 44 : 36)), JSON.stringify(heights));
// Character swap with four characters on your GPU: Who becomes who, and a tap writes the words.
await open(`/genjutsu?video=${encodeURIComponent(clip)}&setup=${code({ m: "character", e: "open", r: pics })}`);
diff --git a/tests/genjutsu-examples.test.ts b/tests/genjutsu-examples.test.ts
index 89a263f0..a5590bf9 100644
--- a/tests/genjutsu-examples.test.ts
+++ b/tests/genjutsu-examples.test.ts
@@ -5,6 +5,7 @@ import {
ALL_FEATURES,
decodeSetup,
encodeSetup,
+ FINISH_COLOURS_DEFAULT,
GENJUTSU_MODES,
getMaker,
modeOpen,
@@ -149,19 +150,35 @@ describe("Genjutsu mode examples", () => {
}
});
- it("the settings list names no model, no file and no test words", () => {
+ it("the settings list names no model, no seed, no file and no test words for a visitor", () => {
for (const r of rows) {
const list = exampleSettings(r.genjutsu!.recipe).join(" | ");
- expect(list, r.id).not.toMatch(/oss-|fuobe-|H3|Wan|test|pass|owner|\/api\//i);
- expect(list, r.id).toMatch(/Part \d/);
+ expect(list, r.id).not.toMatch(/oss-|fuobe-|H3|Wan|test|pass|owner|seed|part|\/api\//i);
+ // The length in whole seconds, as "What went in" says it.
+ expect(list, r.id).toContain(`${Math.round(r.genjutsu!.recipe.length)} s`);
+ expect((r as Row & { genjutsu: { went: string } }).genjutsu.went, r.id).toContain(`${Math.round(r.genjutsu!.recipe.length)} s`);
}
- expect(exampleSettings({ mode: "finish", engine: "open", model: "oss-fix-colours", finish: { tool: "colours" }, length: 5.166, originalSound: "everything" })).toEqual([
- "Finish: Soft film",
- "Strength 40%",
- "Soften detail 33%",
- "Part 5.2 s",
- "Sound: Everything",
- ]);
+ const finish = { mode: "finish" as const, engine: "open" as const, model: "oss-fix-colours", finish: { tool: "colours" as const }, length: 5.166, originalSound: "everything" as const };
+ // Finish's settings left out read as the plan's own defaults (FINISH_COLOURS_DEFAULT).
+ expect(exampleSettings(finish)).toEqual(["Finish: Soft film", "Strength 40%", "Soften detail 33%", "5 s", "Original sound"]);
+ // The owner: no model chip for Finish (its finish chip names it), the exact length and the seed.
+ expect(exampleSettings({ ...finish, seed: 3 }, { owner: true })).toEqual(["Finish: Soft film", "Strength 40%", "Soften detail 33%", "5.2 s", "Original sound", "Seed 3"]);
+ const character = rows.find((r) => r.id === "genjutsu-character.1")!.genjutsu!.recipe;
+ expect(exampleSettings(character)).toEqual(["720p", "5 s", "Original sound"]);
+ expect(exampleSettings(character, { owner: true })[0]).toBe(getMaker(character.model, character.engine)!.label);
+ });
+
+ it("a page sends only the examples open to everyone; the Finish recipe writes its settings out", () => {
+ expect(Object.keys(genjutsuExamples(() => false))).toEqual([]);
+ const live = genjutsuLive();
+ const open = genjutsuExamples((f) => live[f]);
+ for (const [mode, cards] of Object.entries(genjutsuExamples())) {
+ const shown = open[mode as GenjutsuMode] ?? [];
+ expect(shown.every((c) => c.load.needs.every((f) => live[f])), mode).toBe(true);
+ expect(shown.length).toBeLessThanOrEqual(cards!.length);
+ }
+ const f = rows.find((r) => r.id === "genjutsu-finish.1")!.genjutsu!.recipe.finish!;
+ expect({ finish: f.finish, strength: f.strength, soften: f.soften }).toEqual(FINISH_COLOURS_DEFAULT);
});
it("a viewer sees an example only where its mode and its model are open to them; the owner sees every one", () => {
diff --git a/tests/genjutsu-live.test.ts b/tests/genjutsu-live.test.ts
index 104a29d0..7c1c3631 100644
--- a/tests/genjutsu-live.test.ts
+++ b/tests/genjutsu-live.test.ts
@@ -49,7 +49,9 @@ describe("Genjutsu's live gate", () => {
expect(Object.keys(record.features).sort()).toEqual(["finish-colours", "group-swap"]);
expect(Object.entries(genjutsuLive()).filter(([, on]) => on).map(([k]) => k).sort()).toEqual(["finish-colours", "group-swap"]);
const page = fs.readFileSync(path.join(ROOT, "src/app/(studio)/genjutsu/page.tsx"), "utf8");
- expect(page).toMatch(/<GenjutsuStudio examples=\{exampleRow\("tool:genjutsu"\)\} modeExamples=\{genjutsuExamples\(\)\} live=\{genjutsuLive\(\)\} \/>/);
+ expect(page).toContain("const live = genjutsuLive();");
+ // The page's mode examples are only the ones open to everyone (the owner's come from an owner-only route).
+ expect(page).toMatch(/<GenjutsuStudio examples=\{exampleRow\("tool:genjutsu"\)\} modeExamples=\{genjutsuExamples\(\(f\) => live\[f\]\)\} live=\{live\} \/>/);
// The studio shows a feature when it is live or the viewer is the owner.
const studio = fs.readFileSync(path.join(ROOT, "src/components/genjutsu/genjutsu-studio.tsx"), "utf8");
expect(studio).toContain("const open: FeatureCheck = useCallback((f) => owner || !!live?.[f], [owner, live]);");
diff --git a/tests/genjutsu.test.ts b/tests/genjutsu.test.ts
index 0d150561..78cba680 100644
--- a/tests/genjutsu.test.ts
+++ b/tests/genjutsu.test.ts
@@ -534,8 +534,12 @@ describe("Genjutsu: setup codes", () => {
character: { who: "index" as const, index: 2, subject: "man in red", anchor: false, description: "a ronin", speech: "other" as const, lora: "v1" as const, windowFrames: 158 },
};
const code = encodeSetup(setup);
- expect(code).toMatch(/^gj2\.[A-Za-z0-9_-]+$/);
+ // No seed, length or sound: still a gj1 code, which an install that reads only gj1 pastes too.
+ expect(code).toMatch(/^gj1\.[A-Za-z0-9_-]+$/);
expect(decodeSetup(code)).toEqual(setup);
+ const full = { ...setup, seed: 7, length: 5.166, originalSound: "dialogue" as const };
+ expect(encodeSetup(full)).toMatch(/^gj2\.[A-Za-z0-9_-]+$/);
+ expect(decodeSetup(encodeSetup(full))).toEqual(full);
expect(decodeSetup(` http://localhost:3000/genjutsu?setup=${code} `)).toEqual(setup);
expect(decodeSetup(encodeSetup({ mode: "character", character: { dialogue: "secret words", who: "largest" } as never }))?.character).toEqual({ who: "largest" });
});
diff --git a/tests/nav-bar.test.ts b/tests/nav-bar.test.ts
index bada7777..c46a58e5 100644
--- a/tests/nav-bar.test.ts
+++ b/tests/nav-bar.test.ts
@@ -283,7 +283,7 @@ describe("the bar's shell", () => {
expect(html).not.toContain('aria-label="Search Fuobe"');
expect(html).toContain('aria-keyshortcuts="/ Meta+K Control+K"');
// The viewer's room is kept: Sign up's by default, the avatar's where an account or the owner was last.
- expect(html).toMatch(/data-slot="viewer" class="[^"]*w-\[130px\]/);
+ expect(html).toMatch(/data-slot="viewer" class="[^"]*w-\[132px\]/);
for (const w of OWNER_WORDS) expect(words(html), w).not.toContain(w.replace("&amp;", "&"));
expect(html).not.toContain("Sign up");
});