Skip to content

Write HTML. Render video. Built for agents.

fix(slideshow): finish remaining split-PR review findings (#1594)

Vance Ingallsf05b3f9c7c07
diff --git a/packages/cli/src/utils/compositionServer.ts b/packages/cli/src/utils/compositionServer.ts
index 13b6ae4309..24c46a5036 100644
--- a/packages/cli/src/utils/compositionServer.ts
+++ b/packages/cli/src/utils/compositionServer.ts
@@ -3,6 +3,7 @@
// composition asset files, and binding to a free port.
import { existsSync } from "node:fs";
import { resolve, dirname } from "node:path";
+import { fileURLToPath } from "node:url";
/** Minimal surface of a listening server (satisfied by @hono/node-server's ServerType). */
interface PortBindable {
@@ -15,7 +16,9 @@ interface PortBindable {
}
function helperDir(): string {
- return dirname(new URL(import.meta.url).pathname);
+ // fileURLToPath (not URL.pathname) so the Windows "/D:/..." leading-slash form
+ // doesn't break the bundle-path resolution below.
+ return dirname(fileURLToPath(import.meta.url));
}
export function resolveRuntimePath(): string | null {
diff --git a/packages/core/src/lint/rules/slideshow.ts b/packages/core/src/lint/rules/slideshow.ts
index 2731a47512..80b5d8f449 100644
--- a/packages/core/src/lint/rules/slideshow.ts
+++ b/packages/core/src/lint/rules/slideshow.ts
@@ -1,20 +1,11 @@
-// fallow-ignore-file code-duplication
import type { LintContext, HyperframeLintFinding } from "../context";
import type { LintRule } from "../types";
import { readAttr } from "../utils";
import { parseSlideshowManifest, resolveSlideshow } from "../../slideshow/parseSlideshow";
+import { isSceneLikeCompositionId } from "../../slideshow/sceneId";
type Scene = { id: string; start: number; duration: number };
-/** Mirrors isSceneLikeCompositionId in packages/core/src/runtime/timeline.ts */
-function isSceneLikeCompositionId(compositionId: string): boolean {
- const normalized = compositionId.trim().toLowerCase();
- if (!normalized || normalized === "main") return false;
- if (normalized.includes("caption")) return false;
- if (normalized.includes("ambient")) return false;
- return true;
-}
-
function parseTiming(raw: string): { start: number; duration: number } | null {
const startStr = readAttr(raw, "data-start");
if (startStr === null) return null;
diff --git a/packages/core/src/runtime/timeline.ts b/packages/core/src/runtime/timeline.ts
index e6328d73a8..6f8e583818 100644
--- a/packages/core/src/runtime/timeline.ts
+++ b/packages/core/src/runtime/timeline.ts
@@ -7,6 +7,7 @@ import type {
import { swallow } from "./diagnostics";
import { readElementPlaybackRate } from "./media";
import { createRuntimeStartTimeResolver } from "./startResolver";
+import { isSceneLikeCompositionId } from "../slideshow/sceneId";
const AUTHORED_DURATION_ATTR = "data-hf-authored-duration";
const AUTHORED_END_ATTR = "data-hf-authored-end";
@@ -230,13 +231,6 @@ export function collectRuntimeTimelinePayload(params: {
}
return maxWindowEndSeconds > 0 ? maxWindowEndSeconds : null;
};
- const isSceneLikeCompositionId = (compositionId: string): boolean => {
- const normalized = compositionId.trim().toLowerCase();
- if (!normalized || normalized === "main") return false;
- if (normalized.includes("caption")) return false;
- if (normalized.includes("ambient")) return false;
- return true;
- };
const resolveNearestCompositionContext = (
node: Element,
root: Element | null,
diff --git a/packages/core/src/slideshow/parseSlideshow.test.ts b/packages/core/src/slideshow/parseSlideshow.test.ts
index d9207243fb..1633d58818 100644
--- a/packages/core/src/slideshow/parseSlideshow.test.ts
+++ b/packages/core/src/slideshow/parseSlideshow.test.ts
@@ -37,6 +37,11 @@ describe("parseSlideshowManifest", () => {
expect(() => parseSlideshowManifest(html)).toThrow();
});
+ it("rejects a non-object manifest (e.g. a JSON array)", () => {
+ const html = `<script type="application/hyperframes-slideshow+json">[42, null]</script>`;
+ expect(() => parseSlideshowManifest(html)).toThrow();
+ });
+
it("throws when a slide entry is malformed (sceneId not a string)", () => {
const html = `<script type="application/hyperframes-slideshow+json">
{ "slides": [{ "sceneId": 42 }] }
@@ -74,6 +79,18 @@ describe("resolveSlideshow", () => {
expect(errors.some((e) => e.includes("missing"))).toBe(true);
});
+ it("flags duplicate slideSequence ids instead of silently overwriting", () => {
+ const m: import("./slideshow.types").SlideshowManifest = {
+ slides: [{ sceneId: "a" }],
+ slideSequences: [
+ { id: "dup", label: "First", slides: [{ sceneId: "c" }] },
+ { id: "dup", label: "Second", slides: [{ sceneId: "c" }] },
+ ],
+ };
+ const { errors } = resolveSlideshow(m, SCENES);
+ expect(errors.some((e) => e.includes("duplicate slideSequence id"))).toBe(true);
+ });
+
it("reports an error for a fragment outside the slide range", () => {
const m: import("./slideshow.types").SlideshowManifest = {
slides: [{ sceneId: "a", fragments: [99] }],
diff --git a/packages/core/src/slideshow/parseSlideshow.ts b/packages/core/src/slideshow/parseSlideshow.ts
index ba96fc9fb0..a7583f8406 100644
--- a/packages/core/src/slideshow/parseSlideshow.ts
+++ b/packages/core/src/slideshow/parseSlideshow.ts
@@ -69,7 +69,7 @@ function isSlideSequence(v: unknown): boolean {
}
function isManifest(v: unknown): v is SlideshowManifest {
- if (typeof v !== "object" || v === null) return false;
+ if (typeof v !== "object" || v === null || Array.isArray(v)) return false;
const o = v as Record<string, unknown>;
if (!Array.isArray(o["slides"]) || !o["slides"].every(isSlideRef)) return false;
if (o["slideSequences"] !== undefined) {
@@ -158,6 +158,10 @@ export function resolveSlideshow(
const sequences: Record<string, ResolvedSlideSequence> = {};
for (const seq of manifest.slideSequences ?? []) {
+ // Flag duplicate sequence ids rather than silently overwriting the earlier one.
+ if (Object.prototype.hasOwnProperty.call(sequences, seq.id)) {
+ errors.push(`duplicate slideSequence id "${seq.id}" — only the last definition is kept`);
+ }
sequences[seq.id] = {
id: seq.id,
label: seq.label,
diff --git a/packages/core/src/slideshow/sceneId.ts b/packages/core/src/slideshow/sceneId.ts
new file mode 100644
index 0000000000..605a3cf478
--- /dev/null
+++ b/packages/core/src/slideshow/sceneId.ts
@@ -0,0 +1,15 @@
+// packages/core/src/slideshow/sceneId.ts
+
+/**
+ * Whether a composition id names a "scene-like" composition — i.e. a real slide
+ * scene, not the root timeline (`main`) or a non-scene overlay (captions, ambient
+ * layers). Shared by the runtime scene-window computation and the slideshow lint
+ * rule so the two can never drift.
+ */
+export function isSceneLikeCompositionId(compositionId: string): boolean {
+ const normalized = compositionId.trim().toLowerCase();
+ if (!normalized || normalized === "main") return false;
+ if (normalized.includes("caption")) return false;
+ if (normalized.includes("ambient")) return false;
+ return true;
+}
diff --git a/packages/player/src/slideshow/hyperframes-slideshow.test.ts b/packages/player/src/slideshow/hyperframes-slideshow.test.ts
index 2596235998..f76372153c 100644
--- a/packages/player/src/slideshow/hyperframes-slideshow.test.ts
+++ b/packages/player/src/slideshow/hyperframes-slideshow.test.ts
@@ -2,6 +2,7 @@
import { describe, it, expect, beforeEach, afterEach, vi } from "vitest";
import { handleRuntimeMessage } from "../runtime-message-handler.js";
import { dropInvalidSlides } from "./hyperframes-slideshow.js";
+import { slideshowChannelName } from "./slideshowPresenter.js";
// Dynamic import defers custom-element registration until happy-dom is active.
// (Static top-level imports execute before the test environment is set up, which
@@ -524,7 +525,7 @@ describe("<hyperframes-slideshow> presenter mode", () => {
const tick = () => new Promise<void>((r) => setTimeout(r, 0));
it("audience mode: mirrors full position (sequence + slide + fragment) via syncTo", async () => {
- const presenterChannel = new BroadcastChannel("hf-slideshow");
+ const presenterChannel = new BroadcastChannel(slideshowChannelName());
const { el, getLastSync } = makeAudienceEl();
await tick();
@@ -542,7 +543,7 @@ describe("<hyperframes-slideshow> presenter mode", () => {
});
it("audience mode: mirrors a branch position too (full sequenceId forwarded to syncTo)", async () => {
- const presenterChannel = new BroadcastChannel("hf-slideshow");
+ const presenterChannel = new BroadcastChannel(slideshowChannelName());
const { el, getLastSync } = makeAudienceEl();
await tick();
@@ -566,7 +567,7 @@ describe("<hyperframes-slideshow> presenter mode", () => {
it("presenter mode: posts position to channel on controller onChange", async () => {
const received: unknown[] = [];
- const listenerChannel = new BroadcastChannel("hf-slideshow");
+ const listenerChannel = new BroadcastChannel(slideshowChannelName());
listenerChannel.onmessage = (e: MessageEvent) => received.push(e.data);
const { el, triggerChange } = makePresenterEl();
@@ -608,7 +609,7 @@ describe("<hyperframes-slideshow> presenter mode", () => {
await tick();
const received: unknown[] = [];
- const spy = new BroadcastChannel("hf-slideshow");
+ const spy = new BroadcastChannel(slideshowChannelName());
spy.onmessage = (e: MessageEvent) => received.push(e.data);
el.remove(); // triggers disconnectedCallback
diff --git a/packages/player/src/slideshow/hyperframes-slideshow.ts b/packages/player/src/slideshow/hyperframes-slideshow.ts
index 317bd15bd0..840881141e 100644
--- a/packages/player/src/slideshow/hyperframes-slideshow.ts
+++ b/packages/player/src/slideshow/hyperframes-slideshow.ts
@@ -114,6 +114,17 @@ export class HyperframesSlideshow extends HTMLElement {
}
}
+ // Observe the attributes the component reads so runtime toggles take effect.
+ static get observedAttributes(): string[] {
+ return ["sound", "mode"];
+ }
+
+ attributeChangedCallback(): void {
+ // Re-render once bound so a flipped `sound`/`mode` is reflected (mute button,
+ // audience-vs-presenter chrome). No-op before the controller binds.
+ if (this.controller) this.render();
+ }
+
connectedCallback(): void {
this.disconnected = false;
this.initInFlight = false;
@@ -178,7 +189,9 @@ export class HyperframesSlideshow extends HTMLElement {
*/
present(): void {
const sep = location.search ? "&" : "?";
- window.open(location.href + sep + "mode=audience", "_blank");
+ // noopener,noreferrer: the audience window must not get a reference back to
+ // this window (it syncs over BroadcastChannel, not window.opener).
+ window.open(location.href + sep + "mode=audience", "_blank", "noopener,noreferrer");
this.setAttribute("data-hf-presenting", "true");
this.presenterStartMs = Date.now();
if (this.presenterInterval === null) {
@@ -278,6 +291,19 @@ export class HyperframesSlideshow extends HTMLElement {
};
this.bindController(new SlideshowController(port, cleaned));
+
+ // Slow-iframe recovery: if the scene timeline hadn't posted yet (empty
+ // scenes → sceneId-based slides were dropped), re-init once when it finally
+ // arrives so those slides resolve instead of being permanently lost.
+ if (scenes.length === 0 && manifest.slides.length > 0) {
+ playerEl.addEventListener(
+ "scenes",
+ () => {
+ if (gen === this.initGeneration) void this.init();
+ },
+ { once: true },
+ );
+ }
} finally {
this.initInFlight = false;
}
@@ -318,7 +344,10 @@ export class HyperframesSlideshow extends HTMLElement {
// Arrows act even when nothing is focused (active === body/null) so a freshly
// loaded deck responds without a click; Space/Backspace have strong page-level
// defaults (scroll / history) so they only act when the deck actually has focus.
- const ambient = focused || active === document.body || active === null;
+ // When several decks share a page, drop the unfocused-convenience so a key
+ // doesn't drive every instance at once — only the focused deck responds.
+ const multiInstance = document.querySelectorAll("hyperframes-slideshow").length > 1;
+ const ambient = focused || (!multiInstance && (active === document.body || active === null));
if (e.key === "ArrowRight") {
if (!ambient) return;
this.controller.next();
diff --git a/packages/player/src/slideshow/slideshowPresenter.ts b/packages/player/src/slideshow/slideshowPresenter.ts
index 5bee6fd3ec..6345ba0a64 100644
--- a/packages/player/src/slideshow/slideshowPresenter.ts
+++ b/packages/player/src/slideshow/slideshowPresenter.ts
@@ -27,6 +27,16 @@ function isGotoMessage(data: unknown): data is GotoMessage {
* Presenter (default) mode: posts position updates to the channel.
* Audience mode: listens for goto messages and calls the provided handler.
*/
+/**
+ * Per-deck channel name. The presenter and its audience window load the same URL
+ * (path), so keying on pathname keeps them paired while isolating other decks
+ * presenting on the same origin (which would otherwise cross-talk on a fixed name).
+ */
+export function slideshowChannelName(): string {
+ const path = typeof location !== "undefined" ? location.pathname : "";
+ return `hf-slideshow:${path}`;
+}
+
export class SlideshowChannel {
private channel: BroadcastChannel | null = null;
@@ -35,7 +45,7 @@ export class SlideshowChannel {
private readonly onGoto: (msg: GotoMessage) => void,
) {
try {
- this.channel = new BroadcastChannel("hf-slideshow");
+ this.channel = new BroadcastChannel(slideshowChannelName());
} catch {
// BroadcastChannel unavailable (e.g. unsupported env); degrade silently.
return;
diff --git a/packages/player/vitest.config.ts b/packages/player/vitest.config.ts
index 64effe32c5..5f8f7a426a 100644
--- a/packages/player/vitest.config.ts
+++ b/packages/player/vitest.config.ts
@@ -1,7 +1,10 @@
import { defineConfig } from "vitest/config";
-import { resolve } from "path";
+import { resolve } from "node:path";
+import { fileURLToPath } from "node:url";
-const coreRoot = resolve(new URL("..", import.meta.url).pathname, "core/src");
+// fileURLToPath (not URL.pathname): on Windows .pathname yields "/D:/..." with a
+// leading slash, which breaks resolve() and the alias below.
+const coreRoot = resolve(fileURLToPath(new URL("../core/src", import.meta.url)));
export default defineConfig({
resolve: {
diff --git a/packages/producer/src/utils/paths.ts b/packages/producer/src/utils/paths.ts
index ebf8688ca0..7ff314517f 100644
--- a/packages/producer/src/utils/paths.ts
+++ b/packages/producer/src/utils/paths.ts
@@ -9,6 +9,7 @@ import {
relative as nodeRelative,
isAbsolute as nodeIsAbsolute,
} from "node:path";
+import { fileURLToPath } from "node:url";
export interface RenderPaths {
absoluteProjectDir: string;
@@ -17,7 +18,9 @@ export interface RenderPaths {
const DEFAULT_RENDERS_DIR =
process.env.PRODUCER_RENDERS_DIR ??
- nodeResolve(new URL(import.meta.url).pathname, "../../..", "renders");
+ // fileURLToPath (not URL.pathname): on Windows .pathname is "/D:/..." which
+ // resolves to a bogus renders dir.
+ nodeResolve(fileURLToPath(import.meta.url), "../../..", "renders");
type PathModuleLike = {
resolve: (...segments: string[]) => string;
diff --git a/packages/studio/src/components/panels/SlideshowPanel.test.ts b/packages/studio/src/components/panels/SlideshowPanel.test.ts
index 6ea185c09c..42ca46fdea 100644
--- a/packages/studio/src/components/panels/SlideshowPanel.test.ts
+++ b/packages/studio/src/components/panels/SlideshowPanel.test.ts
@@ -2,6 +2,7 @@ import { describe, it, expect, vi, beforeEach, afterEach } from "vitest";
import {
toggleMainLineSlide,
reorderMainLineSlide,
+ reorderBranchSlide,
setSlideNotes,
addFragment,
removeFragment,
@@ -67,6 +68,29 @@ describe("reorderMainLineSlide", () => {
});
});
+// ── reorderBranchSlide ─────────────────────────────────────────────────────
+describe("reorderBranchSlide", () => {
+ const base: SlideshowManifest = {
+ slides: [{ sceneId: "x" }],
+ slideSequences: [
+ { id: "b1", label: "Branch", slides: [{ sceneId: "a" }, { sceneId: "b" }, { sceneId: "c" }] },
+ ],
+ };
+
+ it("moves a branch slide down within its sequence (main line untouched)", () => {
+ const m = reorderBranchSlide(base, "b1", "a", "down");
+ expect(m.slideSequences?.[0].slides.map((s) => s.sceneId)).toEqual(["b", "a", "c"]);
+ expect(m.slides).toEqual(base.slides);
+ });
+
+ it("is a no-op at the boundary and for an unknown branch/scene", () => {
+ expect(reorderBranchSlide(base, "b1", "a", "up").slideSequences?.[0].slides[0].sceneId).toBe(
+ "a",
+ );
+ expect(reorderBranchSlide(base, "nope", "a", "down")).toEqual(base);
+ });
+});
+
// ── setSlideNotes ──────────────────────────────────────────────────────────
describe("setSlideNotes", () => {
diff --git a/packages/studio/src/components/panels/SlideshowPanel.tsx b/packages/studio/src/components/panels/SlideshowPanel.tsx
index b04da2d40f..9d58cea9a5 100644
--- a/packages/studio/src/components/panels/SlideshowPanel.tsx
+++ b/packages/studio/src/components/panels/SlideshowPanel.tsx
@@ -32,6 +32,7 @@ import {
export {
toggleMainLineSlide,
reorderMainLineSlide,
+ reorderBranchSlide,
setSlideNotes,
addFragment,
removeFragment,
@@ -56,6 +57,7 @@ export function safeParseManifest(html: string): SlideshowManifest {
import {
toggleMainLineSlide,
reorderMainLineSlide,
+ reorderBranchSlide,
setSlideNotes,
addFragment,
removeFragment,
@@ -101,7 +103,9 @@ export function makeSlideshowNotesController(): NotesController {
const p = pending;
if (p !== null) {
pending = null;
- p.persist(p.manifest).catch(() => {});
+ p.persist(p.manifest).catch((err: unknown) => {
+ console.error("[slideshow] notes persist failed:", err);
+ });
}
}, delayMs);
return timer;
@@ -115,7 +119,9 @@ export function makeSlideshowNotesController(): NotesController {
const p = pending;
if (p !== null) {
pending = null;
- p.persist(p.manifest).catch(() => {});
+ p.persist(p.manifest).catch((err: unknown) => {
+ console.error("[slideshow] notes persist failed:", err);
+ });
}
},
@@ -215,7 +221,12 @@ export function SlideshowPanel({ scenes, onPersist, onPersistNotes }: SlideshowP
const merged = notesCtrlRef.current.mergeIntoDiscrete(next);
setManifest(merged);
manifestRef.current = merged;
- await onPersist(merged);
+ // Surface persist failures instead of swallowing them at each call site.
+ try {
+ await onPersist(merged);
+ } catch (err) {
+ console.error("[slideshow] failed to persist manifest edit:", err);
+ }
},
[onPersist],
);
@@ -282,6 +293,15 @@ export function SlideshowPanel({ scenes, onPersist, onPersistNotes }: SlideshowP
[applyManifest],
);
+ const handleReorderBranchSlide = useCallback(
+ (sequenceId: string, sceneId: string, dir: "up" | "down") => {
+ applyManifest(reorderBranchSlide(manifestRef.current, sequenceId, sceneId, dir)).catch(
+ () => {},
+ );
+ },
+ [applyManifest],
+ );
+
const handleSetNotes = useCallback(
(notes: string) => {
if (!selectedSceneId) return;
@@ -331,6 +351,16 @@ export function SlideshowPanel({ scenes, onPersist, onPersistNotes }: SlideshowP
const handleDeleteSequence = useCallback(
(id: string) => {
+ // Deleting a branch removes its slides and orphans any hotspot targeting it —
+ // confirm first to prevent accidental data loss.
+ const seq = (manifestRef.current.slideSequences ?? []).find((s) => s.id === id);
+ const count = seq?.slides.length ?? 0;
+ const label = seq?.label ?? id;
+ const ok = window.confirm(
+ `Delete branch "${label}"${count ? ` and its ${count} slide${count === 1 ? "" : "s"}` : ""}? ` +
+ `Hotspots pointing to it will no longer resolve.`,
+ );
+ if (!ok) return;
applyManifest(deleteSequence(manifestRef.current, id)).catch(() => {});
},
[applyManifest],
@@ -429,6 +459,7 @@ export function SlideshowPanel({ scenes, onPersist, onPersistNotes }: SlideshowP
selectedSceneId={selectedSceneId}
selectedSequenceId={selectedSequenceId}
onSelectBranchSlide={handleSelectBranchSlide}
+ onReorderBranchSlide={handleReorderBranchSlide}
/>
)}
diff --git a/packages/studio/src/components/panels/SlideshowSubPanels.tsx b/packages/studio/src/components/panels/SlideshowSubPanels.tsx
index 39aaa11fdc..a03c29262b 100644
--- a/packages/studio/src/components/panels/SlideshowSubPanels.tsx
+++ b/packages/studio/src/components/panels/SlideshowSubPanels.tsx
@@ -216,6 +216,7 @@ export interface BranchTreeProps {
selectedSceneId: string | null;
selectedSequenceId: string | null;
onSelectBranchSlide: (sequenceId: string, sceneId: string) => void;
+ onReorderBranchSlide: (sequenceId: string, sceneId: string, dir: "up" | "down") => void;
}
export function BranchTree({
@@ -228,6 +229,7 @@ export function BranchTree({
selectedSceneId,
selectedSequenceId,
onSelectBranchSlide,
+ onReorderBranchSlide,
}: BranchTreeProps) {
const [newLabel, setNewLabel] = useState("");
const inputId = useId();
@@ -278,6 +280,7 @@ export function BranchTree({
selectedSceneId={selectedSceneId}
selectedSequenceId={selectedSequenceId}
onSelectBranchSlide={onSelectBranchSlide}
+ onReorderBranchSlide={onReorderBranchSlide}
/>
))}
</div>
@@ -295,6 +298,7 @@ interface BranchItemProps {
selectedSceneId: string | null;
selectedSequenceId: string | null;
onSelectBranchSlide: (sequenceId: string, sceneId: string) => void;
+ onReorderBranchSlide: (sequenceId: string, sceneId: string, dir: "up" | "down") => void;
}
function BranchItem({
@@ -306,6 +310,7 @@ function BranchItem({
selectedSceneId,
selectedSequenceId,
onSelectBranchSlide,
+ onReorderBranchSlide,
}: BranchItemProps) {
const [editing, setEditing] = useState(false);
const [draft, setDraft] = useState(seq.label);
@@ -357,7 +362,8 @@ function BranchItem({
</div>
<div className="flex flex-col gap-px pl-2">
{scenes.map((scene) => {
- const assigned = seq.slides.some((s) => s.sceneId === scene.id);
+ const branchPos = seq.slides.findIndex((s) => s.sceneId === scene.id);
+ const assigned = branchPos !== -1;
const isSelected = selectedSequenceId === seq.id && selectedSceneId === scene.id;
return (
<div
@@ -372,16 +378,39 @@ function BranchItem({
className="accent-studio-accent flex-shrink-0"
/>
{assigned ? (
- <button
- type="button"
- aria-pressed={isSelected}
- className={`flex-1 text-left truncate transition-colors hover:text-neutral-200 ${
- isSelected ? "text-white" : "text-neutral-400"
- }`}
- onClick={() => onSelectBranchSlide(seq.id, scene.id)}
- >
- {scene.label || scene.id}
- </button>
+ <>
+ <button
+ type="button"
+ aria-pressed={isSelected}
+ className={`flex-1 text-left truncate transition-colors hover:text-neutral-200 ${
+ isSelected ? "text-white" : "text-neutral-400"
+ }`}
+ onClick={() => onSelectBranchSlide(seq.id, scene.id)}
+ >
+ {scene.label || scene.id}
+ </button>
+ <span className="text-[9px] text-neutral-600 tabular-nums flex-shrink-0">
+ {branchPos + 1}/{seq.slides.length}
+ </span>
+ <button
+ type="button"
+ aria-label={`Move ${scene.label || scene.id} earlier in branch ${seq.label}`}
+ disabled={branchPos <= 0}
+ className="text-[10px] text-neutral-500 hover:text-neutral-200 disabled:opacity-30 disabled:cursor-default px-0.5"
+ onClick={() => onReorderBranchSlide(seq.id, scene.id, "up")}
+ >
+ ▲
+ </button>
+ <button
+ type="button"
+ aria-label={`Move ${scene.label || scene.id} later in branch ${seq.label}`}
+ disabled={branchPos >= seq.slides.length - 1}
+ className="text-[10px] text-neutral-500 hover:text-neutral-200 disabled:opacity-30 disabled:cursor-default px-0.5"
+ onClick={() => onReorderBranchSlide(seq.id, scene.id, "down")}
+ >
+ ▼
+ </button>
+ </>
) : (
<span className="flex-1 truncate">{scene.label || scene.id}</span>
)}
diff --git a/packages/studio/src/components/panels/slideshowPanelHelpers.ts b/packages/studio/src/components/panels/slideshowPanelHelpers.ts
index 77b574fa21..9c64eb64df 100644
--- a/packages/studio/src/components/panels/slideshowPanelHelpers.ts
+++ b/packages/studio/src/components/panels/slideshowPanelHelpers.ts
@@ -30,22 +30,37 @@ export function toggleMainLineSlide(
// fallow-ignore-next-line complexity
/** Move a main-line slide up or down by one position. */
+/** Swap the slide with `sceneId` one step up/down within a slide list. */
+function swapSlide(slides: SlideRef[], sceneId: string, direction: "up" | "down"): SlideRef[] {
+ const idx = slides.findIndex((s) => s.sceneId === sceneId);
+ if (idx === -1) return slides;
+ const next = direction === "up" ? idx - 1 : idx + 1;
+ if (next < 0 || next >= slides.length) return slides;
+ const out = [...slides];
+ const a = out[idx];
+ const b = out[next];
+ if (!a || !b) return slides;
+ out[idx] = b;
+ out[next] = a;
+ return out;
+}
+
export function reorderMainLineSlide(
manifest: SlideshowManifest,
sceneId: string,
direction: "up" | "down",
): SlideshowManifest {
- const idx = manifest.slides.findIndex((s) => s.sceneId === sceneId);
- if (idx === -1) return manifest;
- const next = direction === "up" ? idx - 1 : idx + 1;
- if (next < 0 || next >= manifest.slides.length) return manifest;
- const slides = [...manifest.slides];
- const a = slides[idx];
- const b = slides[next];
- if (!a || !b) return manifest;
- slides[idx] = b;
- slides[next] = a;
- return { ...manifest, slides };
+ return mapSlidesIn(manifest, undefined, (slides) => swapSlide(slides, sceneId, direction));
+}
+
+/** Reorder a slide within a branch sequence (parallel to reorderMainLineSlide). */
+export function reorderBranchSlide(
+ manifest: SlideshowManifest,
+ sequenceId: string,
+ sceneId: string,
+ direction: "up" | "down",
+): SlideshowManifest {
+ return mapSlidesIn(manifest, sequenceId, (slides) => swapSlide(slides, sceneId, direction));
}
/** Apply fn to a branch's slide list (sequenceId) or the main line (undefined). */
diff --git a/packages/studio/src/utils/setSlideshowManifest.ts b/packages/studio/src/utils/setSlideshowManifest.ts
index 78fd11c17c..7a00593411 100644
--- a/packages/studio/src/utils/setSlideshowManifest.ts
+++ b/packages/studio/src/utils/setSlideshowManifest.ts
@@ -20,6 +20,7 @@ import type { SlideshowManifest } from "@hyperframes/core/slideshow";
import {
SLIDESHOW_ISLAND_TYPE,
SLIDESHOW_MANIFEST_VERSION,
+ parseSlideshowManifest,
slideshowIslandRegex,
} from "@hyperframes/core/slideshow";
import type { Composition } from "@hyperframes/sdk";
@@ -64,6 +65,18 @@ export async function persistSlideshowManifest(args: PersistSlideshowArgs): Prom
const { manifest, sdkSession, originalContent, targetPath, deps, label, coalesceKey } = args;
const islandHtml = buildSlideshowIslandHtml(manifest);
+
+ // Write-time validation: confirm the island we just built round-trips to a
+ // valid manifest before touching disk, so a malformed edit can't corrupt the
+ // composition. parseSlideshowManifest throws on a structurally-invalid island.
+ try {
+ if (!parseSlideshowManifest(islandHtml)) {
+ throw new Error("built island did not parse back to a manifest");
+ }
+ } catch (err) {
+ throw new Error(`refusing to persist invalid slideshow manifest: ${(err as Error).message}`);
+ }
+
const current = sdkSession.serialize();
// Strip ALL existing islands (handles the case where two stale islands
@@ -78,6 +91,10 @@ export async function persistSlideshowManifest(args: PersistSlideshowArgs): Prom
after = stripped + "\n" + islandHtml;
}
+ // No-op gate: if the rewritten HTML is byte-identical to the current serialized
+ // HTML, skip the write — avoids a spurious disk write and a no-op undo entry.
+ if (after === current) return;
+
await persistSdkSerialize(after, targetPath, originalContent, deps, {
label: label ?? "Edit slideshow",
...(coalesceKey ? { coalesceKey } : {}),