Skip to content

Commit 648b962

Browse files
committed
fix(studio): harden inline text editing
1 parent a1b1d11 commit 648b962

16 files changed

Lines changed: 234 additions & 76 deletions

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

Lines changed: 21 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -53,6 +53,13 @@ function toolbarIn(host: HTMLElement): HTMLElement | null {
5353
return host.querySelector<HTMLElement>('[data-inline-text-toolbar="true"]');
5454
}
5555

56+
function renderSelected(html = "hello world") {
57+
const { element, session, iframe } = scene(html);
58+
const { host } = render(session, iframe);
59+
selectAll(element);
60+
return { element, host };
61+
}
62+
5663
describe("InlineTextToolbar", () => {
5764
it("stays out of the way until characters are actually selected", () => {
5865
const { session, iframe } = scene("hello world");
@@ -152,15 +159,26 @@ describe("InlineTextToolbar", () => {
152159
});
153160

154161
it("styles the selected characters when a control is used", () => {
155-
const { element, session, iframe } = scene("hello world");
156-
const { host } = render(session, iframe);
157-
selectAll(element);
162+
const { element, host } = renderSelected();
158163

159164
act(() => host.querySelector<HTMLButtonElement>('[aria-label="Bold"]')!.click());
160165

161166
expect(element.innerHTML).toBe('<span style="font-weight: 700">hello world</span>');
162167
});
163168

169+
it("ignores a click when the selection disappeared before React hid the toolbar", () => {
170+
const { element, host } = renderSelected();
171+
const bold = host.querySelector<HTMLButtonElement>('[aria-label="Bold"]')!;
172+
173+
expect(() => {
174+
act(() => {
175+
document.getSelection()!.removeAllRanges();
176+
bold.click();
177+
});
178+
}).not.toThrow();
179+
expect(element.innerHTML).toBe("hello world");
180+
});
181+
164182
it("reads back the styling it applied, so the control shows the truth", () => {
165183
const { element, session, iframe } = scene('<span style="font-style: italic">words</span>');
166184
const { host } = render(session, iframe);

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

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -56,8 +56,9 @@ export function InlineTextToolbar({
5656
const apply = useCallback(
5757
(delta: Record<string, string | null>) => {
5858
const doc = session?.element.ownerDocument;
59-
const range = doc?.defaultView?.getSelection()?.getRangeAt(0);
60-
if (!range) return;
59+
const selection = doc?.defaultView?.getSelection();
60+
if (!selection || selection.rangeCount === 0) return;
61+
const range = selection.getRangeAt(0);
6162
applyInlineStyle(range, delta);
6263
refresh();
6364
},

‎packages/studio/src/components/editor/domEditInlineText.test.ts‎

Lines changed: 14 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,5 @@
1+
// @vitest-environment happy-dom
2+
13
import { describe, expect, it, vi } from "vitest";
24
import type { DomEditSelection, DomEditTextField } from "./domEditingTypes";
35

@@ -6,7 +8,7 @@ vi.mock("./domEditingLayers", () => ({
68
isTextEditableSelection: () => editable.current,
79
}));
810

9-
const { canEditTextInline } = await import("./domEditInlineText");
11+
const { canEditTextInline, isDoublePress } = await import("./domEditInlineText");
1012

1113
function field(key: string): DomEditTextField {
1214
return {
@@ -71,3 +73,14 @@ describe("canEditTextInline", () => {
7173
expect(canEditTextInline(null)).toBe(false);
7274
});
7375
});
76+
77+
describe("isDoublePress", () => {
78+
it("pairs presses only when they land on the same element", () => {
79+
const first = document.createElement("div");
80+
const second = document.createElement("div");
81+
const previous = { x: 10, y: 10, at: 100, element: first };
82+
83+
expect(isDoublePress(previous, { x: 12, y: 12, at: 200, element: first })).toBe(true);
84+
expect(isDoublePress(previous, { x: 12, y: 12, at: 200, element: second })).toBe(false);
85+
});
86+
});

‎packages/studio/src/components/editor/domEditInlineText.ts‎

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -54,11 +54,14 @@ export function canEditElementTextInline(element: HTMLElement | null): boolean {
5454
}
5555

5656
function hasOnlyFormattingChildren(element: HTMLElement): boolean {
57+
const HTMLElementClass = element.ownerDocument.defaultView?.HTMLElement;
58+
if (!HTMLElementClass) return false;
5759
for (const child of Array.from(element.children)) {
5860
if (!isRichTextFormattingTag(child.tagName)) return false;
61+
if (!(child instanceof HTMLElementClass)) return false;
5962
// Formatting nests, and a structural child hidden inside a span is still
6063
// structural.
61-
if (!hasOnlyFormattingChildren(child as HTMLElement)) return false;
64+
if (!hasOnlyFormattingChildren(child)) return false;
6265
}
6366
return true;
6467
}
@@ -68,6 +71,7 @@ export interface PressMark {
6871
x: number;
6972
y: number;
7073
at: number;
74+
element: HTMLElement | null;
7175
}
7276

7377
/** Long enough to be deliberate, short enough not to catch two separate clicks. */
@@ -86,6 +90,8 @@ const DOUBLE_PRESS_SLOP_PX = 6;
8690
export function isDoublePress(previous: PressMark | null, next: PressMark): boolean {
8791
if (!previous) return false;
8892
return (
93+
next.element !== null &&
94+
previous.element === next.element &&
8995
next.at - previous.at <= DOUBLE_PRESS_MS &&
9096
Math.abs(next.x - previous.x) <= DOUBLE_PRESS_SLOP_PX &&
9197
Math.abs(next.y - previous.y) <= DOUBLE_PRESS_SLOP_PX

‎packages/studio/src/components/editor/useDomEditNudge.ts‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,7 @@
77
*/
88
import { useCallback, useEffect, useRef, type RefObject } from "react";
99
import { useMountEffect } from "../../hooks/useMountEffect";
10-
import { isEditableTarget } from "../../utils/timelineDiscovery";
10+
import { isTypingTarget } from "../../utils/typingTarget";
1111
import { acquireCanvasNudgeKeys } from "../../utils/canvasNudgeGate";
1212
import type { DomEditSelection } from "./domEditing";
1313
import {
@@ -130,7 +130,7 @@ function resolveSingleNudgeTarget(
130130
function shouldIgnoreNudgeKey(p: UseDomEditNudgeParams, event: KeyboardEvent): boolean {
131131
if (!p.allowCanvasMovement || event.defaultPrevented) return true;
132132
if (p.gestureRef.current || p.groupGestureRef.current || p.blockedMoveRef.current) return true;
133-
return isEditableTarget(event.target);
133+
return isTypingTarget(event.target);
134134
}
135135

136136
export function useDomEditNudge(params: UseDomEditNudgeParams): { flushNudge: () => void } {

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

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -103,13 +103,13 @@ export function useInlineTextEditing(selectionRef: RefObject<DomEditSelection |
103103
return inlineText.start(target.element);
104104
},
105105
startFromPress: (event) => {
106-
const press = { x: event.clientX, y: event.clientY, at: Date.now() };
106+
if (inlineText.session) return false;
107+
const element = elementUnderPress(event);
108+
const press = { x: event.clientX, y: event.clientY, at: Date.now(), element };
107109
const paired = isDoublePress(lastPressRef.current, press);
108110
lastPressRef.current = press;
109111

110-
if (!paired || inlineText.session) return false;
111-
112-
const element = elementUnderPress(event);
112+
if (!paired) return false;
113113
if (!element || !canEditElementTextInline(element)) return false;
114114
// The caret opens where the press landed, which means mapping the point
115115
// out of Studio's coordinates and into the composition's own.

‎packages/studio/src/components/storyboard/StoryboardFrameFocus.tsx‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@ import {
1111
} from "./AgentChatMessageButton";
1212
import { FRAME_STATUS_META } from "./frameStatus";
1313
import type { CommentsSubmitState } from "./useFrameComments";
14+
import { isTypingTarget } from "../../utils/typingTarget";
1415

1516
export interface StoryboardFrameFocusProps {
1617
projectId: string;
@@ -140,8 +141,7 @@ export function StoryboardFrameFocus({
140141
useEffect(() => {
141142
// fallow-ignore-next-line complexity
142143
const onKey = (e: KeyboardEvent) => {
143-
const el = document.activeElement;
144-
if (el instanceof HTMLTextAreaElement || el instanceof HTMLInputElement) return;
144+
if (isTypingTarget(document.activeElement)) return;
145145
if (e.key === "Escape") handleBack();
146146
else if (e.key === "ArrowLeft" && frame.index > 1) handleNavigate(-1);
147147
else if (e.key === "ArrowRight" && frame.index < frameCount) handleNavigate(1);

‎packages/studio/src/components/storyboard/StoryboardViewModeGuard.test.tsx‎

Lines changed: 19 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -26,6 +26,7 @@ vi.mock("./FramePoster", () => ({
2626
}));
2727

2828
const onSelectComposition = vi.fn();
29+
const onNavigate = vi.fn();
2930

3031
function TestApp() {
3132
const viewMode = useViewModeState();
@@ -48,9 +49,9 @@ function TestApp() {
4849
narrative: "",
4950
extra: {},
5051
}}
51-
frameCount={1}
52+
frameCount={2}
5253
onBack={vi.fn()}
53-
onNavigate={vi.fn()}
54+
onNavigate={onNavigate}
5455
onSaved={vi.fn()}
5556
onSelectComposition={onSelectComposition}
5657
scriptExists={false}
@@ -109,6 +110,7 @@ beforeEach(() => {
109110
window.history.replaceState({ entry: "timeline" }, "", "/");
110111
window.history.pushState({ entry: "storyboard" }, "", "/?view=storyboard");
111112
onSelectComposition.mockReset();
113+
onNavigate.mockReset();
112114
});
113115

114116
afterEach(() => {
@@ -168,3 +170,18 @@ describe("dirty storyboard voiceover view-mode guard", () => {
168170
act(() => root.unmount());
169171
});
170172
});
173+
174+
describe("storyboard frame keyboard navigation", () => {
175+
it("leaves arrow keys with contenteditable text", () => {
176+
const { host, root } = renderApp();
177+
const editor = document.createElement("div");
178+
editor.contentEditable = "true";
179+
host.append(editor);
180+
editor.focus();
181+
182+
act(() => window.dispatchEvent(new KeyboardEvent("keydown", { key: "ArrowRight" })));
183+
184+
expect(onNavigate).not.toHaveBeenCalled();
185+
act(() => root.unmount());
186+
});
187+
});

‎packages/studio/src/hooks/useAppHotkeys.ts‎

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@ import type { TimelineElement } from "../player";
44
import type { DomEditSelection } from "../components/editor/domEditing";
55
import type { LeftSidebarHandle } from "../components/sidebar/LeftSidebar";
66
import { STUDIO_MOTION_PATH } from "../components/editor/studioMotion";
7-
import { isEditableTarget } from "../utils/timelineDiscovery";
7+
import { isTypingTarget } from "../utils/typingTarget";
88
import { shouldIgnoreHistoryShortcut } from "../utils/studioHelpers";
99
import { canSplitElement } from "../utils/timelineElementSplit";
1010
import { trackStudioEvent } from "../utils/studioTelemetry";
@@ -188,14 +188,14 @@ function dispatchModifierKey(event: KeyboardEvent, key: string, cb: HotkeyCallba
188188
return true;
189189
}
190190

191-
if (key === "g" && !event.altKey && !isEditableTarget(event.target)) {
191+
if (key === "g" && !event.altKey && !isTypingTarget(event.target)) {
192192
event.preventDefault();
193193
if (event.shiftKey) cb.onUngroupSelection?.();
194194
else cb.onGroupSelection?.();
195195
return true;
196196
}
197197

198-
if (!event.shiftKey && !event.altKey && !isEditableTarget(event.target)) {
198+
if (!event.shiftKey && !event.altKey && !isTypingTarget(event.target)) {
199199
if (key === "c") {
200200
if (cb.handleCopy()) {
201201
event.preventDefault();
@@ -454,7 +454,7 @@ export function useAppHotkeys({
454454
dispatchModifierKey(event, key, cb);
455455
return;
456456
}
457-
if (!isEditableTarget(event.target)) dispatchPlainKey(event, key, cb);
457+
if (!isTypingTarget(event.target)) dispatchPlainKey(event, key, cb);
458458
}, []);
459459

460460
// eslint-disable-next-line no-restricted-syntax

‎packages/studio/src/hooks/useDomEditCommits.test.tsx‎

Lines changed: 28 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -871,7 +871,7 @@ describe("useDomEditCommits rich-text persist handling", () => {
871871

872872
try {
873873
await act(async () => {
874-
await rendered.hook.handleDomRichTextCommit({ html, previousHtml });
874+
await rendered.hook.handleDomRichTextCommit({ element, html, previousHtml });
875875
});
876876

877877
expect(element.innerHTML).toBe(previousHtml);
@@ -884,6 +884,33 @@ describe("useDomEditCommits rich-text persist handling", () => {
884884
rendered.cleanup();
885885
}
886886
});
887+
888+
it("does not retarget a commit onto a replacement preview node", async () => {
889+
const fetchMock = stubPatchFetch({ ok: true, changed: true, matched: true });
890+
const html = '<span style="color: blue">After</span>';
891+
const { iframe, element } = createPreviewElement(`<div data-hf-id="hf-card">${html}</div>`);
892+
const rendered = renderDomEditCommits(createSelection(element), iframe);
893+
const replacement = document.createElement("div");
894+
replacement.dataset.hfId = "hf-card";
895+
replacement.innerHTML = "Reloaded elsewhere";
896+
element.replaceWith(replacement);
897+
898+
try {
899+
await act(async () => {
900+
await rendered.hook.handleDomRichTextCommit({
901+
element,
902+
html,
903+
previousHtml: "Before",
904+
});
905+
});
906+
907+
expect(replacement.innerHTML).toBe("Reloaded elsewhere");
908+
expect(fetchMock).not.toHaveBeenCalled();
909+
expect(rendered.showToast).not.toHaveBeenCalled();
910+
} finally {
911+
rendered.cleanup();
912+
}
913+
});
887914
});
888915

889916
describe("useDomEditCommits style persist handling", () => {

0 commit comments

Comments
 (0)