Skip to content

Commit 898d278

Browse files
feat(studio): preview ruler and safe-margin toggles (#4127)
* feat(studio): preview ruler and safe-margin toggles * test(studio): cover guides placement in the preview pane and the caption band box * feat(studio): safe margins are two nested 90 and 80 percent boxes with edge ticks * fix(studio): safe box ticks centred on the line, no halo, tighter skill wording test
1 parent 14e5f57 commit 898d278

13 files changed

Lines changed: 427 additions & 5 deletions
Lines changed: 88 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,88 @@
1+
// @vitest-environment happy-dom
2+
3+
import React, { act } from "react";
4+
import { createRoot } from "react-dom/client";
5+
import { afterEach, describe, expect, it, vi } from "vitest";
6+
import { PreviewGuides } from "./PreviewGuides";
7+
import { usePreviewGuidesStore } from "./previewGuidesStore";
8+
9+
(globalThis as unknown as { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
10+
11+
const compRect = vi.hoisted(() => ({
12+
current: { left: 20, top: 20, width: 400, height: 225, scaleX: 1, scaleY: 1 },
13+
}));
14+
vi.mock("./useDomEditCompositionRect", () => ({
15+
useDomEditCompositionRect: () => compRect.current,
16+
}));
17+
18+
afterEach(() => {
19+
compRect.current = { left: 20, top: 20, width: 400, height: 225, scaleX: 1, scaleY: 1 };
20+
document.body.innerHTML = "";
21+
window.localStorage.clear();
22+
});
23+
24+
function render(rulerVisible: boolean, safeMarginsVisible: boolean) {
25+
usePreviewGuidesStore.setState({ rulerVisible, safeMarginsVisible });
26+
const host = document.createElement("div");
27+
document.body.append(host);
28+
act(() => {
29+
createRoot(host).render(<PreviewGuides iframeRef={{ current: null }} />);
30+
});
31+
return host;
32+
}
33+
34+
describe("PreviewGuides", () => {
35+
it("draws nothing when both toggles are off", () => {
36+
const host = render(false, false);
37+
expect(host.querySelector("[data-testid]")).toBeNull();
38+
});
39+
40+
it("draws the ruler with ticks 0 to 100 every 10 on both edges", () => {
41+
const host = render(true, false);
42+
const top = host.querySelector('[data-testid="preview-ruler-top"]');
43+
expect(Array.from(top?.children ?? []).map((t) => t.textContent)).toEqual(
44+
Array.from({ length: 11 }, (_, i) => String(i * 10)),
45+
);
46+
expect(host.querySelector('[data-testid="preview-ruler-left"]')).not.toBeNull();
47+
expect(host.querySelector('[data-testid="preview-safe-90"]')).toBeNull();
48+
expect(host.querySelector('[data-testid="preview-safe-80"]')).toBeNull();
49+
});
50+
51+
it("draws the 90% and 80% boxes with edge-midpoint ticks and no labels or caption band", () => {
52+
const host = render(false, true);
53+
const box = (pct: number) =>
54+
host.querySelector<HTMLElement>(`[data-testid="preview-safe-${pct}"]`);
55+
expect([box(90)?.style.left, box(90)?.style.bottom]).toEqual(["5%", "5%"]);
56+
expect([box(80)?.style.top, box(80)?.style.right]).toEqual(["10%", "10%"]);
57+
expect(box(90)?.children.length).toBe(4);
58+
expect(box(80)?.children.length).toBe(4);
59+
expect(host.textContent).toBe("");
60+
expect(host.querySelector('[data-testid="preview-ruler-top"]')).toBeNull();
61+
});
62+
63+
it("places the ruler in the gutter outside the frame", () => {
64+
const host = render(true, false);
65+
const top = host.querySelector<HTMLElement>('[data-testid="preview-ruler-top"]');
66+
const left = host.querySelector<HTMLElement>('[data-testid="preview-ruler-left"]');
67+
expect([top?.style.left, top?.style.top, top?.style.width]).toEqual(["20px", "4px", "400px"]);
68+
expect([left?.style.left, left?.style.top, left?.style.height]).toEqual([
69+
"4px",
70+
"20px",
71+
"225px",
72+
]);
73+
});
74+
75+
it("draws nothing until the composition has a size", () => {
76+
compRect.current = { left: 0, top: 0, width: 0, height: 0, scaleX: 1, scaleY: 1 };
77+
const host = render(true, true);
78+
expect(host.querySelector("[data-testid]")).toBeNull();
79+
});
80+
81+
it("draws the same boxes on a portrait composition", () => {
82+
compRect.current = { left: 20, top: 20, width: 225, height: 400, scaleX: 1, scaleY: 1 };
83+
const host = render(false, true);
84+
const box = host.querySelector<HTMLElement>('[data-testid="preview-safe-90"]');
85+
expect([box?.style.left, box?.style.top]).toEqual(["5%", "5%"]);
86+
expect(host.querySelector('[data-testid="preview-safe-80"]')).not.toBeNull();
87+
});
88+
});
Lines changed: 125 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,125 @@
1+
import { memo, useRef, type RefObject } from "react";
2+
import { useDomEditCompositionRect } from "./useDomEditCompositionRect";
3+
import { RULER_GUTTER_PX, usePreviewGuidesStore } from "./previewGuidesStore";
4+
import { SAFE_BOX_PERCENTS, safeBoxInsetPercent } from "../../utils/previewSafeMargins";
5+
6+
interface PreviewGuidesProps {
7+
iframeRef: RefObject<HTMLIFrameElement | null>;
8+
}
9+
10+
const TICKS = Array.from({ length: 11 }, (_, i) => i * 10);
11+
const INK = "rgba(255,255,255,0.7)";
12+
13+
/** Ruler and safe-margin boxes drawn over the preview pane, never inside the composition. */
14+
export const PreviewGuides = memo(function PreviewGuides({ iframeRef }: PreviewGuidesProps) {
15+
const rulerVisible = usePreviewGuidesStore((s) => s.rulerVisible);
16+
const safeMarginsVisible = usePreviewGuidesStore((s) => s.safeMarginsVisible);
17+
if (!rulerVisible && !safeMarginsVisible) return null;
18+
return (
19+
<ActiveGuides
20+
iframeRef={iframeRef}
21+
rulerVisible={rulerVisible}
22+
safeMarginsVisible={safeMarginsVisible}
23+
/>
24+
);
25+
});
26+
27+
interface ActiveGuidesProps extends PreviewGuidesProps {
28+
rulerVisible: boolean;
29+
safeMarginsVisible: boolean;
30+
}
31+
32+
/** Owns the composition-rect subscription, so it only runs while a guide is on. */
33+
function ActiveGuides({ iframeRef, rulerVisible, safeMarginsVisible }: ActiveGuidesProps) {
34+
const paneRef = useRef<HTMLDivElement>(null);
35+
const rect = useDomEditCompositionRect({ iframeRef, overlayRef: paneRef });
36+
const ready = rect.width > 0 && rect.height > 0;
37+
38+
return (
39+
<div ref={paneRef} aria-hidden="true" className="pointer-events-none absolute inset-0 z-20">
40+
{ready && rulerVisible && (
41+
<>
42+
<div
43+
data-testid="preview-ruler-top"
44+
className="absolute bg-black/70"
45+
style={{
46+
left: rect.left,
47+
top: rect.top - RULER_GUTTER_PX,
48+
width: rect.width,
49+
height: RULER_GUTTER_PX,
50+
}}
51+
>
52+
{TICKS.map((pct) => (
53+
<span
54+
key={pct}
55+
className="absolute bottom-0 border-l text-[9px] leading-none tabular-nums pl-0.5 h-2.5"
56+
style={{ left: `${pct}%`, borderColor: INK, color: INK }}
57+
>
58+
{pct}
59+
</span>
60+
))}
61+
</div>
62+
<div
63+
data-testid="preview-ruler-left"
64+
className="absolute bg-black/70"
65+
style={{
66+
left: rect.left - RULER_GUTTER_PX,
67+
top: rect.top,
68+
width: RULER_GUTTER_PX,
69+
height: rect.height,
70+
}}
71+
>
72+
{TICKS.map((pct) => (
73+
<span
74+
key={pct}
75+
className="absolute right-0 border-t text-[9px] leading-none tabular-nums pt-0.5 w-2.5"
76+
style={{ top: `${pct}%`, borderColor: INK, color: INK }}
77+
>
78+
{pct}
79+
</span>
80+
))}
81+
</div>
82+
</>
83+
)}
84+
{ready && safeMarginsVisible && (
85+
<div
86+
className="absolute"
87+
style={{ left: rect.left, top: rect.top, width: rect.width, height: rect.height }}
88+
>
89+
{SAFE_BOX_PERCENTS.map((boxPercent) => (
90+
<SafeBox key={boxPercent} boxPercent={boxPercent} />
91+
))}
92+
</div>
93+
)}
94+
</div>
95+
);
96+
}
97+
98+
const TICK_PX = 7;
99+
const EDGE_MIDPOINTS = [
100+
{ edge: "top", style: { left: "50%", top: -(TICK_PX + 1) / 2, width: 1, height: TICK_PX } },
101+
{ edge: "bottom", style: { left: "50%", bottom: -(TICK_PX + 1) / 2, width: 1, height: TICK_PX } },
102+
{ edge: "left", style: { top: "50%", left: -(TICK_PX + 1) / 2, width: TICK_PX, height: 1 } },
103+
{ edge: "right", style: { top: "50%", right: -(TICK_PX + 1) / 2, width: TICK_PX, height: 1 } },
104+
] as const;
105+
106+
/** One thin white box inset from every edge, with a tick at the midpoint of each edge. */
107+
function SafeBox({ boxPercent }: { boxPercent: number }) {
108+
const inset = `${safeBoxInsetPercent(boxPercent)}%`;
109+
return (
110+
<div
111+
data-testid={`preview-safe-${boxPercent}`}
112+
className="absolute border border-white/90"
113+
style={{
114+
left: inset,
115+
top: inset,
116+
right: inset,
117+
bottom: inset,
118+
}}
119+
>
120+
{EDGE_MIDPOINTS.map(({ edge, style }) => (
121+
<span key={edge} className="absolute bg-white/90" style={style} />
122+
))}
123+
</div>
124+
);
125+
}

‎packages/studio/src/components/editor/SnapToolbar.test.tsx‎

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@ import { usePlayerStore } from "../../player/store/playerStore";
88
import type { LeftSidebarHandle } from "../sidebar/LeftSidebar";
99
import type { DomEditSelection } from "./domEditing";
1010
import { SnapToolbar } from "./SnapToolbar";
11+
import { usePreviewGuidesStore } from "./previewGuidesStore";
1112

1213
(globalThis as unknown as { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
1314

@@ -120,3 +121,22 @@ describe("SnapToolbar keyboard shortcuts", () => {
120121
act(() => root.unmount());
121122
});
122123
});
124+
125+
describe("SnapToolbar ruler and safe-margin toggles", () => {
126+
it.each([
127+
["Toggle ruler", "rulerVisible"],
128+
["Toggle safe margins", "safeMarginsVisible"],
129+
])("%s flips %s and remembers it", (label, key) => {
130+
usePreviewGuidesStore.setState({ rulerVisible: false, safeMarginsVisible: false });
131+
const { root } = renderToolbar();
132+
const button = () => document.querySelector<HTMLButtonElement>(`[aria-label="${label}"]`);
133+
expect(button()?.getAttribute("aria-pressed")).toBe("false");
134+
135+
act(() => button()?.click());
136+
137+
expect(button()?.getAttribute("aria-pressed")).toBe("true");
138+
const stored = window.localStorage.getItem("hf-studio-ui-preferences") ?? "{}";
139+
expect(JSON.parse(stored)[key]).toBe(true);
140+
act(() => root.unmount());
141+
});
142+
});

‎packages/studio/src/components/editor/SnapToolbar.tsx‎

Lines changed: 25 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,8 @@
11
import { memo, useCallback, useEffect, useRef, useState } from "react";
2-
import { MagnetStraight, GridFour, Path } from "@phosphor-icons/react";
2+
import { MagnetStraight, GridFour, Path, Ruler, FrameCorners } from "@phosphor-icons/react";
33
import { readStudioUiPreferences, writeStudioUiPreferences } from "../../utils/studioUiPreferences";
44
import { usePlayerStore } from "../../player/store/playerStore";
5+
import { usePreviewGuidesStore } from "./previewGuidesStore";
56

67
const SNAP_DEFAULTS = {
78
snapEnabled: true,
@@ -39,6 +40,7 @@ export const SnapToolbar = memo(function SnapToolbar({ onSnapChange }: SnapToolb
3940
const motionPathCreateAvailable = usePlayerStore((s) => s.motionPathCreateAvailable);
4041
const motionPathArmed = usePlayerStore((s) => s.motionPathArmed);
4142
const setMotionPathArmed = usePlayerStore((s) => s.setMotionPathArmed);
43+
const guides = usePreviewGuidesStore();
4244
const popoverRef = useRef<HTMLDivElement>(null);
4345
const gridButtonRef = useRef<HTMLButtonElement>(null);
4446

@@ -116,6 +118,28 @@ export const SnapToolbar = memo(function SnapToolbar({ onSnapChange }: SnapToolb
116118
<Path size={16} weight={motionPathArmed ? "fill" : "regular"} />
117119
</button>
118120
)}
121+
{(
122+
[
123+
["rulerVisible", "Ruler", Ruler],
124+
["safeMarginsVisible", "Safe margins", FrameCorners],
125+
] as const
126+
).map(([key, label, Icon]) => (
127+
<button
128+
key={key}
129+
type="button"
130+
className={`rounded-md p-1.5 transition-colors active:scale-[0.95] ${
131+
guides[key]
132+
? "bg-studio-accent/20 text-studio-accent"
133+
: "bg-black/40 text-white/60 hover:bg-black/60 hover:text-white/80"
134+
}`}
135+
onClick={() => guides.toggle(key)}
136+
title={`${label} ${guides[key] ? "on" : "off"}`}
137+
aria-label={`Toggle ${label.toLowerCase()}`}
138+
aria-pressed={guides[key]}
139+
>
140+
<Icon size={16} weight={guides[key] ? "fill" : "regular"} />
141+
</button>
142+
))}
119143
<button
120144
type="button"
121145
className={`rounded-md p-1.5 transition-colors active:scale-[0.95] ${
Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
import { create } from "zustand";
2+
import { readStudioUiPreferences, writeStudioUiPreferences } from "../../utils/studioUiPreferences";
3+
4+
/** Space the preview fit reserves above and left of the frame while the ruler is on. */
5+
export const RULER_GUTTER_PX = 16;
6+
7+
type GuideKey = "rulerVisible" | "safeMarginsVisible";
8+
9+
interface PreviewGuidesState {
10+
rulerVisible: boolean;
11+
safeMarginsVisible: boolean;
12+
toggle: (key: GuideKey) => void;
13+
}
14+
15+
export const usePreviewGuidesStore = create<PreviewGuidesState>((set, get) => {
16+
const stored = readStudioUiPreferences();
17+
return {
18+
rulerVisible: stored.rulerVisible ?? false,
19+
safeMarginsVisible: stored.safeMarginsVisible ?? false,
20+
toggle: (key) => {
21+
const next = !get()[key];
22+
writeStudioUiPreferences({ [key]: next });
23+
set({ [key]: next });
24+
},
25+
};
26+
});

‎packages/studio/src/components/nle/NLEPreview.test.ts‎

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -134,6 +134,19 @@ describe("getPreviewPlayerKey", () => {
134134
});
135135

136136
describe("resolvePreviewStageSize", () => {
137+
it("reserves the ruler gutter on both sides of both axes", () => {
138+
const wide = { width: 1920, height: 1080 };
139+
const tall = { width: 1080, height: 1920 };
140+
expect(resolvePreviewStageSize(512, 402, wide, undefined, 16)).toEqual({
141+
width: 464,
142+
height: 261,
143+
});
144+
expect(resolvePreviewStageSize(512, 402, tall, undefined, 16)).toEqual({
145+
width: 199.125,
146+
height: 354,
147+
});
148+
});
149+
137150
it("fits portrait composition dimensions by height in a narrow viewport", () => {
138151
expect(resolvePreviewStageSize(512, 402, { width: 1080, height: 1920 }, undefined)).toEqual({
139152
width: 217.125,

‎packages/studio/src/components/nle/NLEPreview.tsx‎

Lines changed: 9 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@ import {
1111
toDomPrecision,
1212
type PreviewZoomState,
1313
} from "./previewZoom";
14+
import { RULER_GUTTER_PX, usePreviewGuidesStore } from "../editor/previewGuidesStore";
1415
import { readStudioUiPreferences, writeStudioUiPreferences } from "../../utils/studioUiPreferences";
1516
interface NLEPreviewProps {
1617
projectId: string;
@@ -89,9 +90,10 @@ export function resolvePreviewStageSize(
8990
viewportHeight: number,
9091
compositionSize: PreviewCompositionSize | null,
9192
portrait: boolean | undefined,
93+
gutterPx = 0,
9294
): { width: number; height: number } {
93-
const availableWidth = Math.max(0, viewportWidth - PREVIEW_STAGE_INSET_PX);
94-
const availableHeight = Math.max(0, viewportHeight - PREVIEW_STAGE_INSET_PX);
95+
const availableWidth = Math.max(0, viewportWidth - PREVIEW_STAGE_INSET_PX - 2 * gutterPx);
96+
const availableHeight = Math.max(0, viewportHeight - PREVIEW_STAGE_INSET_PX - 2 * gutterPx);
9597
const aspectRatio =
9698
compositionSize && compositionSize.width > 0 && compositionSize.height > 0
9799
? compositionSize.width / compositionSize.height
@@ -135,6 +137,7 @@ export const NLEPreview = memo(function NLEPreview({
135137
onStageRef?.(stageRef);
136138
}, [onStageRef]);
137139
const [compositionSize, setCompositionSize] = useState<PreviewCompositionSize | null>(null);
140+
const gutterPx = usePreviewGuidesStore((s) => (s.rulerVisible ? RULER_GUTTER_PX : 0));
138141
const [stageSize, setStageSize] = useState(() => resolvePreviewStageSize(0, 0, null, portrait));
139142

140143
const zoomRef = useRef<PreviewZoomState>(loadInitialZoom());
@@ -164,14 +167,16 @@ export const NLEPreview = memo(function NLEPreview({
164167

165168
const updateStageSize = () => {
166169
const rect = viewport.getBoundingClientRect();
167-
setStageSize(resolvePreviewStageSize(rect.width, rect.height, compositionSize, portrait));
170+
setStageSize(
171+
resolvePreviewStageSize(rect.width, rect.height, compositionSize, portrait, gutterPx),
172+
);
168173
};
169174

170175
updateStageSize();
171176
const observer = new ResizeObserver(updateStageSize);
172177
observer.observe(viewport);
173178
return () => observer.disconnect();
174-
}, [compositionSize, portrait]);
179+
}, [compositionSize, portrait, gutterPx]);
175180

176181
const onCompositionSizeChangeRef = useRef(onCompositionSizeChange);
177182
onCompositionSizeChangeRef.current = onCompositionSizeChange;

0 commit comments

Comments
 (0)