Skip to content

AI media harness for planning, generating, and editing locally

TypeScript

Preserve reference chips when copying prompts

Bittiad2fe450864f
diff --git a/RELEASE_NOTES.md b/RELEASE_NOTES.md
index 47925c2..f45b337 100644
--- a/RELEASE_NOTES.md
+++ b/RELEASE_NOTES.md
@@ -4,6 +4,7 @@ This alpha update adds DMAD LoRA support, resumable model downloads, and improve
## What's new
+- Copying or cutting prompts preserves reference chips when pasted into other prompt fields.
- Choose Make Primary on an image version to show it in the main image bar and use it when creating scenes or references from that family.
- Images imported through Timeline or References, including selected video reference frames, appear in the image bar and open for editing.
- Duplicate references from their context menu, including multiple selected references with their prompts, attachments, and media settings.
diff --git a/src/components/workspace/PromptTextField.test.tsx b/src/components/workspace/PromptTextField.test.tsx
index 76b7759..016b6e3 100644
--- a/src/components/workspace/PromptTextField.test.tsx
+++ b/src/components/workspace/PromptTextField.test.tsx
@@ -34,6 +34,105 @@ const caretAt = (node: Node, offset: number) => {
fireEvent(document, new Event("selectionchange"));
};
+const selectRange = (start: Node, startOffset: number, end: Node, endOffset: number) => {
+ const range = document.createRange();
+ range.setStart(start, startOffset);
+ range.setEnd(end, endOffset);
+ document.getSelection()!.removeAllRanges();
+ document.getSelection()!.addRange(range);
+};
+const clipboard = () => {
+ const data = new Map<string, string>();
+ return { setData: (type: string, value: string) => data.set(type, value), getData: (type: string) => data.get(type) ?? "" };
+};
+
+it.each(["", "\n"])("copies multiline prompts with chip IDs into another field (ending: %j)", (ending) => {
+ const initial = `Meet @[ref:hero]\n@[ref:castle] with @[ref:hero] and @[ref:missing]${ending}`;
+ const onInsert = vi.fn();
+ let pasted = "Before after";
+ const renamed = references.map((reference) => ({ ...reference, name: `${reference.name} renamed` }));
+ function Harness() {
+ const [target, setTarget] = useState(pasted);
+ pasted = target;
+ return <>
+ <PromptTextField aria-label="Source" value={initial} onChange={vi.fn()} references={references} />
+ <PromptTextField aria-label="Target" value={target} onChange={setTarget} references={renamed} onInsertReference={onInsert} />
+ </>;
+ }
+ render(<Harness />);
+ const source = screen.getByRole("textbox", { name: "Source" });
+ const target = screen.getByRole("textbox", { name: "Target" });
+ const clipboardData = clipboard();
+ selectRange(source, 0, source, source.childNodes.length);
+ fireEvent.copy(source, { clipboardData });
+ expect(clipboardData.getData("text/plain")).toBe(initial);
+ expect(clipboardData.getData("text/plain")).not.toContain("\u200b");
+ selectRange(target.firstChild!, 7, target.firstChild!, 12);
+ fireEvent.paste(target, { clipboardData });
+ expect(pasted).toBe(`Before ${initial}`);
+ expect([...target.querySelectorAll(".prompt-chip")].map((chip) => chip.textContent)).toEqual(["Hero renamed", "Castle renamed", "Hero renamed", "Deleted reference"]);
+ expect(onInsert.mock.calls.map(([reference]) => reference.id)).toEqual(["hero", "castle"]);
+ expect(target).toHaveFocus();
+ // Further typing belongs after the inserted prompt, not before its chips.
+ fireEvent.paste(target, { clipboardData: { getData: () => " Next" } });
+ expect(pasted).toBe(`Before ${initial} Next`);
+});
+
+it("cuts only the selected text and chips and can paste them back at the cut position", () => {
+ const initial = "Before @[ref:hero] after @[ref:castle].";
+ const { field, value } = setup(initial);
+ const clipboardData = clipboard();
+ selectRange(field.firstChild!, 3, field.lastChild!, 1);
+ fireEvent.cut(field, { clipboardData });
+ expect(clipboardData.getData("text/plain")).toBe("ore @[ref:hero] after @[ref:castle].");
+ expect(value()).toBe("Bef");
+ expect(field.querySelectorAll(".prompt-chip")).toHaveLength(0);
+ fireEvent.paste(field, { clipboardData });
+ expect(value()).toBe(initial);
+ expect(field.querySelectorAll(".prompt-chip")).toHaveLength(2);
+});
+
+it("treats a partial chip-label selection as one complete reference when copying, cutting or replacing", () => {
+ const { field, value } = setup("Start @[ref:hero] end");
+ const clipboardData = clipboard();
+ const label = field.querySelector(".prompt-chip")!.firstChild!;
+ selectRange(label, 1, label, 3);
+ fireEvent.copy(field, { clipboardData });
+ expect(clipboardData.getData("text/plain")).toBe("@[ref:hero]");
+ fireEvent.cut(field, { clipboardData });
+ expect(value()).toBe("Start end");
+ fireEvent.paste(field, { clipboardData });
+ expect(value()).toBe("Start @[ref:hero] end");
+ const restoredLabel = field.querySelector(".prompt-chip")!.firstChild!;
+ selectRange(restoredLabel, 1, restoredLabel, 3);
+ fireEvent.paste(field, { clipboardData: { getData: () => "@[ref:castle]" } });
+ expect(value()).toBe("Start @[ref:castle] end");
+});
+
+it("allows copying a disabled prompt but prevents cut and paste from changing it", () => {
+ const onChange = vi.fn();
+ render(<PromptTextField aria-label="Prompt" value="@[ref:hero]" onChange={onChange} references={references} disabled />);
+ const field = screen.getByRole("textbox", { name: "Prompt" });
+ const clipboardData = clipboard();
+ selectRange(field, 0, field, field.childNodes.length);
+ fireEvent.copy(field, { clipboardData });
+ expect(clipboardData.getData("text/plain")).toBe("@[ref:hero]");
+ fireEvent.cut(field, { clipboardData });
+ fireEvent.paste(field, { clipboardData });
+ expect(onChange).not.toHaveBeenCalled();
+});
+
+it("leaves the clipboard alone when there is no selection", () => {
+ const { field, value } = setup("Hello @[ref:hero]");
+ const clipboardData = clipboard();
+ clipboardData.setData("text/plain", "Previous clipboard");
+ caretAt(field.firstChild!, 2);
+ fireEvent.copy(field, { clipboardData });
+ fireEvent.cut(field, { clipboardData });
+ expect(clipboardData.getData("text/plain")).toBe("Previous clipboard");
+ expect(value()).toBe("Hello @[ref:hero]");
+});
+
it("shows cited references as chips by name, and a deleted one as missing", () => {
const { field } = setup("@[ref:hero] walks to @[ref:tower]");
const chips = field.querySelectorAll(".prompt-chip");
diff --git a/src/components/workspace/PromptTextField.tsx b/src/components/workspace/PromptTextField.tsx
index 414db15..57a7529 100644
--- a/src/components/workspace/PromptTextField.tsx
+++ b/src/components/workspace/PromptTextField.tsx
@@ -1,4 +1,4 @@
-import { useEffect, useLayoutEffect, useRef, useState, type CSSProperties, type KeyboardEvent as ReactKeyboardEvent, type ReactNode } from "react";
+import { useEffect, useLayoutEffect, useRef, useState, type ClipboardEvent as ReactClipboardEvent, type CSSProperties, type KeyboardEvent as ReactKeyboardEvent, type ReactNode } from "react";
import { canTokenizeReference, referenceToken, splitActionText, type ActionPart } from "../../lib/project";
import { Add14, Delete14 } from "../ui/icons";
import { Flyout, TextField } from "../ui";
@@ -164,6 +164,18 @@ export function PromptTextField({ value, onChange, references, format = REFERENC
replace(range.start, range.end, "\n");
};
+ const copy = (event: ReactClipboardEvent<HTMLDivElement>, cut = false) => {
+ if (cut && disabled) { event.preventDefault(); return; }
+ const root = field.current!;
+ const range = caretRange(root, format);
+ if (!range || range.start === range.end) return;
+ // Copy the token IDs, not the chip labels the browser would put on the
+ // clipboard. Plain text also preserves citations through other text fields.
+ event.clipboardData.setData("text/plain", serialize(root, format).slice(range.start, range.end));
+ event.preventDefault();
+ if (cut) replace(range.start, range.end, "");
+ };
+
const openPicker = (anchor: HTMLElement, start: number, end: number, current: string | null) => {
if (disabled) return;
setPicking({ anchor, start, end, current });
@@ -217,13 +229,21 @@ export function PromptTextField({ value, onChange, references, format = REFERENC
style={{ "--prompt-rows": rows } as CSSProperties}
onInput={(event) => input(event.nativeEvent)}
onKeyDown={keyDown}
+ onCopy={copy}
+ onCut={(event) => copy(event, true)}
onPaste={(event) => {
// Only the characters: markup pasted from elsewhere would land as
// elements the value has no way to say.
event.preventDefault();
+ if (disabled) return;
const text = event.clipboardData.getData("text/plain").replace(/\r\n?/g, "\n");
const range = caretRange(field.current!, format) ?? { start: value.length, end: value.length };
replace(range.start, range.end, text);
+ const keys = new Set(format.split(text).filter((part) => part.kind === "reference").map((part) => part.value));
+ for (const key of keys) {
+ const reference = chips.byKey.get(key);
+ if (reference) onInsertReference?.(reference);
+ }
}}
onDrop={(event) => event.preventDefault()}
onClick={(event) => {
@@ -398,8 +418,17 @@ function offsetBefore(root: HTMLElement, node: Node, format: PromptTokenFormat):
function caretRange(root: HTMLElement, format: PromptTokenFormat): { start: number; end: number } | null {
const selection = document.getSelection();
if (!selection?.rangeCount) return null;
- const range = selection.getRangeAt(0);
+ const range = selection.getRangeAt(0).cloneRange();
if (!root.contains(range.startContainer) || !root.contains(range.endContainer)) return null;
+ // A chip is one token even when a browser selection lands inside its label.
+ // Expand nonempty selections to its edges so copy, cut and paste stay atomic.
+ if (!range.collapsed) {
+ const chipAt = (node: Node) => (node instanceof Element ? node : node.parentElement)?.closest(`[${CHIP}]`);
+ const startChip = chipAt(range.startContainer);
+ const endChip = chipAt(range.endContainer);
+ if (startChip) range.setStartBefore(startChip);
+ if (endChip) range.setEndAfter(endChip);
+ }
const measure = (container: Node, offset: number) => {
const before = document.createRange();
before.selectNodeContents(root);