feat(web): enable rich text composer by default (#12160)
Co-authored-by: maria-rcks <[email protected]>
This commit is contained in:
1 parent
df466c7981
commit
d359e94cab
28 files changed
+3558
-4072
No files matched your search
@@ -23,7 +23,6 @@
|
||||
"@effect/atom-react": "catalog:",
|
||||
"@formkit/auto-animate": "^0.9.0",
|
||||
"@legendapp/list": "catalog:",
|
||||
"@lexical/react": "^0.41.0",
|
||||
"@noble/hashes": "catalog:",
|
||||
"@pierre/diffs": "catalog:",
|
||||
"@pierre/trees": "1.0.0-beta.4",
|
||||
@@ -32,6 +31,12 @@
|
||||
"@t3tools/shared": "workspace:*",
|
||||
"@tanstack/react-pacer": "^0.19.4",
|
||||
"@tanstack/react-router": "^1.160.2",
|
||||
"@tiptap/core": "^3.31.3",
|
||||
"@tiptap/extension-task-item": "^3.31.3",
|
||||
"@tiptap/extension-task-list": "^3.31.3",
|
||||
"@tiptap/pm": "^3.31.3",
|
||||
"@tiptap/react": "^3.31.3",
|
||||
"@tiptap/starter-kit": "^3.31.3",
|
||||
"class-variance-authority": "^0.7.1",
|
||||
"culori": "^4.0.2",
|
||||
"effect": "catalog:",
|
||||
@@ -41,7 +46,6 @@
|
||||
"jose": "catalog:",
|
||||
"jsonc-parser": "3.3.1",
|
||||
"jszip": "3.10.1",
|
||||
"lexical": "^0.41.0",
|
||||
"lucide-react": "^0.564.0",
|
||||
"react": "19.2.6",
|
||||
"react-dom": "19.2.6",
|
||||
|
||||
@@ -11,7 +11,11 @@ import { useLocation, useNavigate } from "@tanstack/react-router";
|
||||
|
||||
import { isElectron } from "../env";
|
||||
import { getLocalStorageItem, removeLocalStorageItem } from "../hooks/useLocalStorage";
|
||||
import { resolveShortcutCommand, shortcutLabelForCommand } from "../keybindings";
|
||||
import {
|
||||
isRichTextBoldShortcut,
|
||||
resolveShortcutCommand,
|
||||
shortcutLabelForCommand,
|
||||
} from "../keybindings";
|
||||
import { cn, isMacPlatform } from "../lib/utils";
|
||||
import { primaryServerKeybindingsAtom } from "../state/server";
|
||||
import { useEnvironmentIdentificationMode, useLegacySidebarEnabled } from "../hooks/useSettings";
|
||||
@@ -88,6 +92,15 @@ function SidebarControl() {
|
||||
) {
|
||||
return;
|
||||
}
|
||||
if (
|
||||
isRichTextBoldShortcut(event) &&
|
||||
event.target instanceof HTMLElement &&
|
||||
event.target.closest('[data-composer-rich-text="true"]')
|
||||
) {
|
||||
// The rich-text composer claims Mod+B for bold; the toggle stays
|
||||
// available everywhere else, including the plain-text composer.
|
||||
return;
|
||||
}
|
||||
if (resolveShortcutCommand(event, keybindings) !== "sidebar.toggle") return;
|
||||
|
||||
event.preventDefault();
|
||||
|
||||
@@ -1,223 +0,0 @@
|
||||
import { useLexicalComposerContext } from "@lexical/react/LexicalComposerContext";
|
||||
import type { AssistantCitation } from "@t3tools/contracts";
|
||||
import {
|
||||
serializeAssistantCitation,
|
||||
withAssistantCitationComment,
|
||||
} from "@t3tools/shared/assistantCitations";
|
||||
import {
|
||||
$applyNodeReplacement,
|
||||
$getNodeByKey,
|
||||
$getRoot,
|
||||
$isElementNode,
|
||||
DecoratorNode,
|
||||
HISTORY_PUSH_TAG,
|
||||
SKIP_DOM_SELECTION_TAG,
|
||||
type NodeKey,
|
||||
type SerializedLexicalNode,
|
||||
type Spread,
|
||||
} from "lexical";
|
||||
import { createContext, use, type ReactElement } from "react";
|
||||
import type { AssistantCitationSourceAnchor } from "~/lib/assistantTextSelection";
|
||||
|
||||
import { AssistantCitationChip } from "./chat/AssistantCitationChip";
|
||||
import { COMPOSER_INLINE_CHIP_DECORATOR_CLASS_NAME } from "./composerInlineChip";
|
||||
|
||||
type SerializedComposerCitationNode = Spread<
|
||||
{
|
||||
citation: AssistantCitation;
|
||||
source: string;
|
||||
type: "composer-citation";
|
||||
version: 1;
|
||||
},
|
||||
SerializedLexicalNode
|
||||
>;
|
||||
|
||||
export type ComposerCitationCommentRequest = {
|
||||
previousValue: string;
|
||||
value: string;
|
||||
citationStart: number;
|
||||
sourceAnchor: AssistantCitationSourceAnchor;
|
||||
};
|
||||
|
||||
export type ComposerCitationCommentTarget = {
|
||||
nodeKey: NodeKey;
|
||||
sourceAnchor?: AssistantCitationSourceAnchor;
|
||||
removeOnCancel?: boolean;
|
||||
};
|
||||
|
||||
export const ComposerCitationCommentContext = createContext<{
|
||||
openComment: ComposerCitationCommentTarget | null;
|
||||
onOpenChange: (nodeKey: NodeKey, open: boolean) => void;
|
||||
onSubmitAndSend: () => void;
|
||||
}>({ openComment: null, onOpenChange: () => {}, onSubmitAndSend: () => {} });
|
||||
|
||||
/** Consume a cite action once its controlled prompt has been committed to the editor. */
|
||||
export function $consumeComposerCitationCommentRequest(requestRef: {
|
||||
current: ComposerCitationCommentRequest | null;
|
||||
}): ComposerCitationCommentTarget | null {
|
||||
const request = requestRef.current;
|
||||
if (!request) return null;
|
||||
const root = $getRoot();
|
||||
const value = root.getTextContent();
|
||||
if (value === request.previousValue) return null;
|
||||
requestRef.current = null;
|
||||
if (value !== request.value) return null;
|
||||
|
||||
// Controlled prompts use one paragraph with inline nodes and explicit line breaks.
|
||||
const paragraph = root.getFirstChild();
|
||||
if (!$isElementNode(paragraph)) return null;
|
||||
let offset = 0;
|
||||
for (const node of paragraph.getChildren()) {
|
||||
if (offset === request.citationStart && node instanceof ComposerCitationNode) {
|
||||
return {
|
||||
nodeKey: node.getKey(),
|
||||
sourceAnchor: request.sourceAnchor,
|
||||
removeOnCancel: true,
|
||||
};
|
||||
}
|
||||
offset += node.getTextContentSize();
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
function ComposerCitationDecorator(props: { citation: AssistantCitation; nodeKey: NodeKey }) {
|
||||
const [editor] = useLexicalComposerContext();
|
||||
const commentContext = use(ComposerCitationCommentContext);
|
||||
const commentTarget =
|
||||
commentContext.openComment?.nodeKey === props.nodeKey ? commentContext.openComment : null;
|
||||
const onSaveComment = (comment: string): boolean => {
|
||||
if (!editor.isEditable()) return false;
|
||||
let accepted = false;
|
||||
editor.update(
|
||||
() => {
|
||||
const node = $getNodeByKey(props.nodeKey);
|
||||
if (node instanceof ComposerCitationNode && node.isAttached()) {
|
||||
node.setComment(comment);
|
||||
accepted = true;
|
||||
}
|
||||
},
|
||||
{ discrete: true, tag: [HISTORY_PUSH_TAG, SKIP_DOM_SELECTION_TAG] },
|
||||
);
|
||||
return accepted;
|
||||
};
|
||||
/** Cancelling a comment on a just-created citation removes the chip the cite action added. */
|
||||
const onRemove = () => {
|
||||
if (!editor.isEditable()) return;
|
||||
editor.update(
|
||||
() => {
|
||||
const node = $getNodeByKey(props.nodeKey);
|
||||
if (node instanceof ComposerCitationNode) {
|
||||
node.selectPrevious();
|
||||
node.remove();
|
||||
}
|
||||
},
|
||||
{ tag: HISTORY_PUSH_TAG },
|
||||
);
|
||||
editor.getRootElement()?.focus({ preventScroll: true });
|
||||
};
|
||||
return (
|
||||
<span
|
||||
className="inline-flex min-w-0 max-w-full"
|
||||
contentEditable={false}
|
||||
spellCheck={false}
|
||||
data-composer-citation-chip="true"
|
||||
>
|
||||
<AssistantCitationChip
|
||||
citation={props.citation}
|
||||
composer
|
||||
commentEditor={{
|
||||
open: commentTarget !== null,
|
||||
sourceAnchor: commentTarget?.sourceAnchor,
|
||||
onOpenChange: (open) => {
|
||||
if (open && !editor.isEditable()) return;
|
||||
commentContext.onOpenChange(props.nodeKey, open);
|
||||
},
|
||||
...(commentTarget?.removeOnCancel ? { onCancel: onRemove } : {}),
|
||||
onSave: onSaveComment,
|
||||
onSaveAndSend: (comment) => {
|
||||
if (!onSaveComment(comment)) return false;
|
||||
commentContext.onSubmitAndSend();
|
||||
return true;
|
||||
},
|
||||
}}
|
||||
/>
|
||||
</span>
|
||||
);
|
||||
}
|
||||
|
||||
export class ComposerCitationNode extends DecoratorNode<ReactElement> {
|
||||
__citation: AssistantCitation;
|
||||
__source: string;
|
||||
|
||||
static override getType(): string {
|
||||
return "composer-citation";
|
||||
}
|
||||
|
||||
static override clone(node: ComposerCitationNode): ComposerCitationNode {
|
||||
return new ComposerCitationNode(node.__citation, node.__source, node.__key);
|
||||
}
|
||||
|
||||
static override importJSON(serializedNode: SerializedComposerCitationNode): ComposerCitationNode {
|
||||
return $createComposerCitationNode(
|
||||
serializedNode.citation,
|
||||
serializedNode.source,
|
||||
).updateFromJSON(serializedNode);
|
||||
}
|
||||
|
||||
constructor(citation: AssistantCitation, source: string, key?: NodeKey) {
|
||||
super(key);
|
||||
this.__citation = citation;
|
||||
this.__source = source;
|
||||
}
|
||||
|
||||
override exportJSON(): SerializedComposerCitationNode {
|
||||
const node = this.getLatest();
|
||||
return {
|
||||
...super.exportJSON(),
|
||||
citation: node.__citation,
|
||||
source: node.__source,
|
||||
type: "composer-citation",
|
||||
version: 1,
|
||||
};
|
||||
}
|
||||
|
||||
override createDOM(): HTMLElement {
|
||||
const dom = document.createElement("span");
|
||||
dom.className = `${COMPOSER_INLINE_CHIP_DECORATOR_CLASS_NAME} max-w-full`;
|
||||
return dom;
|
||||
}
|
||||
|
||||
override updateDOM(): false {
|
||||
return false;
|
||||
}
|
||||
|
||||
override getTextContent(): string {
|
||||
return this.getLatest().__source;
|
||||
}
|
||||
|
||||
setComment(comment: string): this {
|
||||
const latest = this.getLatest();
|
||||
const citation = withAssistantCitationComment(latest.__citation, comment);
|
||||
if (citation.comment === latest.__citation.comment) return latest;
|
||||
const source = serializeAssistantCitation(citation);
|
||||
const writable = this.getWritable();
|
||||
writable.__citation = citation;
|
||||
writable.__source = source;
|
||||
return writable;
|
||||
}
|
||||
|
||||
override isInline(): true {
|
||||
return true;
|
||||
}
|
||||
|
||||
override decorate(): ReactElement {
|
||||
return <ComposerCitationDecorator citation={this.__citation} nodeKey={this.__key} />;
|
||||
}
|
||||
}
|
||||
|
||||
export function $createComposerCitationNode(
|
||||
citation: AssistantCitation,
|
||||
source: string,
|
||||
): ComposerCitationNode {
|
||||
return $applyNodeReplacement(new ComposerCitationNode(citation, source));
|
||||
}
|
||||
@@ -1,92 +0,0 @@
|
||||
import { describe, expect, it, vi } from "vite-plus/test";
|
||||
import { $createParagraphNode, $getRoot, $isElementNode, createEditor } from "lexical";
|
||||
|
||||
import {
|
||||
$createComposerContextReferenceNode,
|
||||
ComposerContextReferenceNode,
|
||||
} from "./ComposerContextReferenceNode";
|
||||
import { splitPromptIntoComposerSegments } from "../composer-editor-mentions";
|
||||
|
||||
vi.mock("./composerContextPresentation", () => ({
|
||||
ComposerContextReferenceChip: () => null,
|
||||
}));
|
||||
|
||||
const reference = { kind: "terminal", contextId: "ctx-1", label: "Terminal 1 lines 3-4" };
|
||||
const link = "[Terminal 1 lines 3-4](t3-context://v1/terminal/ctx-1)";
|
||||
|
||||
function createReferenceEditor() {
|
||||
const editor = createEditor({ nodes: [ComposerContextReferenceNode] });
|
||||
editor.update(
|
||||
() => {
|
||||
$getRoot().append($createParagraphNode());
|
||||
},
|
||||
{ discrete: true },
|
||||
);
|
||||
return editor;
|
||||
}
|
||||
|
||||
function $referenceNodes() {
|
||||
const paragraph = $getRoot().getFirstChildOrThrow();
|
||||
if (!$isElementNode(paragraph)) throw new Error("Expected a paragraph");
|
||||
return paragraph.getChildren().filter((node) => node instanceof ComposerContextReferenceNode);
|
||||
}
|
||||
|
||||
describe("ComposerContextReferenceNode", () => {
|
||||
it("renders its canonical link as text so the prompt carries identity", () => {
|
||||
const editor = createReferenceEditor();
|
||||
editor.update(
|
||||
() => {
|
||||
const paragraph = $getRoot().getFirstChild();
|
||||
if (!$isElementNode(paragraph)) throw new Error("Expected a paragraph");
|
||||
paragraph.append($createComposerContextReferenceNode(reference, "ref-1"));
|
||||
},
|
||||
{ discrete: true },
|
||||
);
|
||||
const text = editor.getEditorState().read(() => $getRoot().getTextContent());
|
||||
expect(text).toBe(link);
|
||||
expect(splitPromptIntoComposerSegments(text)).toEqual([
|
||||
{ type: "context-reference", ...reference, source: link },
|
||||
]);
|
||||
});
|
||||
|
||||
it("round-trips through JSON keeping the occurrence id", () => {
|
||||
const editor = createReferenceEditor();
|
||||
editor.update(
|
||||
() => {
|
||||
const paragraph = $getRoot().getFirstChild();
|
||||
if (!$isElementNode(paragraph)) throw new Error("Expected a paragraph");
|
||||
paragraph.append($createComposerContextReferenceNode(reference, "ref-1"));
|
||||
},
|
||||
{ discrete: true },
|
||||
);
|
||||
const serialized = editor.getEditorState().toJSON();
|
||||
const restored = createReferenceEditor();
|
||||
restored.setEditorState(restored.parseEditorState(serialized));
|
||||
const nodes = restored.getEditorState().read(() =>
|
||||
$referenceNodes().map((node) => ({
|
||||
referenceId: node.__referenceId,
|
||||
reference: node.getReference(),
|
||||
})),
|
||||
);
|
||||
expect(nodes).toEqual([{ referenceId: "ref-1", reference }]);
|
||||
});
|
||||
|
||||
it("mints a distinct occurrence id per created node while sharing the payload id", () => {
|
||||
const editor = createReferenceEditor();
|
||||
editor.update(
|
||||
() => {
|
||||
const paragraph = $getRoot().getFirstChild();
|
||||
if (!$isElementNode(paragraph)) throw new Error("Expected a paragraph");
|
||||
paragraph.append(
|
||||
$createComposerContextReferenceNode(reference),
|
||||
$createComposerContextReferenceNode(reference),
|
||||
);
|
||||
},
|
||||
{ discrete: true },
|
||||
);
|
||||
const nodes = editor.getEditorState().read(() => $referenceNodes());
|
||||
expect(nodes[0]!.__contextId).toBe(nodes[1]!.__contextId);
|
||||
expect(nodes[0]!.__referenceId).not.toBe(nodes[1]!.__referenceId);
|
||||
expect(nodes[0]!.__referenceId).toMatch(/^[0-9a-f-]{36}$/);
|
||||
});
|
||||
});
|
||||
@@ -1,133 +0,0 @@
|
||||
import { formatComposerContextReference } from "@t3tools/shared/composerContextReferences";
|
||||
import type { ComposerContextId } from "@t3tools/contracts";
|
||||
import {
|
||||
$applyNodeReplacement,
|
||||
DecoratorNode,
|
||||
type NodeKey,
|
||||
type SerializedLexicalNode,
|
||||
type Spread,
|
||||
} from "lexical";
|
||||
import type { ReactElement } from "react";
|
||||
|
||||
import { randomUUID } from "~/lib/utils";
|
||||
import { COMPOSER_INLINE_CHIP_DECORATOR_CLASS_NAME } from "./composerInlineChip";
|
||||
import { ComposerContextReferenceChip } from "./composerContextPresentation";
|
||||
|
||||
export interface ComposerContextReference {
|
||||
kind: string;
|
||||
contextId: string;
|
||||
label: string;
|
||||
}
|
||||
|
||||
export type SerializedComposerContextReferenceNode = Spread<
|
||||
ComposerContextReference & {
|
||||
referenceId: string;
|
||||
type: "composer-context-reference";
|
||||
version: 1;
|
||||
},
|
||||
SerializedLexicalNode
|
||||
>;
|
||||
|
||||
/**
|
||||
* One inline occurrence of a context payload. The node's text is the canonical link, so the
|
||||
* prompt string carries kind and id and rebuilding the editor from it restores the same chip.
|
||||
* `referenceId` identifies this occurrence; duplicating the node mints a new one.
|
||||
*/
|
||||
export class ComposerContextReferenceNode extends DecoratorNode<ReactElement> {
|
||||
__kind: string;
|
||||
__contextId: string;
|
||||
__label: string;
|
||||
__referenceId: string;
|
||||
|
||||
static override getType(): "composer-context-reference" {
|
||||
return "composer-context-reference";
|
||||
}
|
||||
|
||||
static override clone(node: ComposerContextReferenceNode): ComposerContextReferenceNode {
|
||||
return new ComposerContextReferenceNode(
|
||||
{ kind: node.__kind, contextId: node.__contextId, label: node.__label },
|
||||
node.__referenceId,
|
||||
node.__key,
|
||||
);
|
||||
}
|
||||
|
||||
static override importJSON(
|
||||
serializedNode: SerializedComposerContextReferenceNode,
|
||||
): ComposerContextReferenceNode {
|
||||
return $createComposerContextReferenceNode(
|
||||
{
|
||||
kind: serializedNode.kind,
|
||||
contextId: serializedNode.contextId,
|
||||
label: serializedNode.label,
|
||||
},
|
||||
serializedNode.referenceId,
|
||||
).updateFromJSON(serializedNode);
|
||||
}
|
||||
|
||||
constructor(reference: ComposerContextReference, referenceId: string, key?: NodeKey) {
|
||||
super(key);
|
||||
this.__kind = reference.kind;
|
||||
this.__contextId = reference.contextId;
|
||||
this.__label = reference.label;
|
||||
this.__referenceId = referenceId;
|
||||
}
|
||||
|
||||
override exportJSON(): SerializedComposerContextReferenceNode {
|
||||
const latest = this.getLatest();
|
||||
return {
|
||||
...super.exportJSON(),
|
||||
kind: latest.__kind,
|
||||
contextId: latest.__contextId,
|
||||
label: latest.__label,
|
||||
referenceId: latest.__referenceId,
|
||||
type: "composer-context-reference",
|
||||
version: 1,
|
||||
};
|
||||
}
|
||||
|
||||
override createDOM(): HTMLElement {
|
||||
const dom = document.createElement("span");
|
||||
dom.className = `${COMPOSER_INLINE_CHIP_DECORATOR_CLASS_NAME} max-w-full`;
|
||||
return dom;
|
||||
}
|
||||
|
||||
override updateDOM(): false {
|
||||
return false;
|
||||
}
|
||||
|
||||
override getTextContent(): string {
|
||||
const latest = this.getLatest();
|
||||
return formatComposerContextReference({
|
||||
kind: latest.__kind,
|
||||
contextId: latest.__contextId as ComposerContextId,
|
||||
label: latest.__label,
|
||||
});
|
||||
}
|
||||
|
||||
override isInline(): true {
|
||||
return true;
|
||||
}
|
||||
|
||||
getReference(): ComposerContextReference {
|
||||
const latest = this.getLatest();
|
||||
return { kind: latest.__kind, contextId: latest.__contextId, label: latest.__label };
|
||||
}
|
||||
|
||||
override decorate(): ReactElement {
|
||||
const latest = this.getLatest();
|
||||
return (
|
||||
<ComposerContextReferenceChip
|
||||
kind={latest.__kind}
|
||||
contextId={latest.__contextId}
|
||||
label={latest.__label}
|
||||
/>
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
export function $createComposerContextReferenceNode(
|
||||
reference: ComposerContextReference,
|
||||
referenceId: string = randomUUID(),
|
||||
): ComposerContextReferenceNode {
|
||||
return $applyNodeReplacement(new ComposerContextReferenceNode(reference, referenceId));
|
||||
}
|
||||
@@ -1,183 +0,0 @@
|
||||
import { useLexicalComposerContext } from "@lexical/react/LexicalComposerContext";
|
||||
import { $copyNode, $getRoot, $isElementNode, PASTE_COMMAND, type LexicalEditor } from "lexical";
|
||||
import { act, createRef } from "react";
|
||||
import { create, type ReactTestRenderer } from "react-test-renderer";
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vite-plus/test";
|
||||
|
||||
import { collapseExpandedComposerCursor } from "../composer-logic";
|
||||
import { ComposerPromptEditor, type ComposerPromptEditorHandle } from "./ComposerPromptEditor";
|
||||
|
||||
vi.mock("./chat/FileTagChip", () => ({
|
||||
FILE_TAG_CHIP_CLASS_NAME: "",
|
||||
FileTagChipContent: () => null,
|
||||
}));
|
||||
vi.mock("./chat/ComposerPendingTerminalContexts", () => ({
|
||||
ComposerPendingTerminalContextChip: () => null,
|
||||
}));
|
||||
vi.mock("./chat/AssistantCitationChip", () => ({ AssistantCitationChip: () => null }));
|
||||
|
||||
let lexicalEditor: LexicalEditor;
|
||||
// Keep the real composer, registered nodes, updates, and snapshot API. Only the
|
||||
// DOM view is omitted so Lexical runs headlessly in this component test.
|
||||
vi.mock("@lexical/react/LexicalPlainTextPlugin", () => ({
|
||||
PlainTextPlugin: function HeadlessEditor() {
|
||||
[lexicalEditor] = useLexicalComposerContext();
|
||||
return null;
|
||||
},
|
||||
}));
|
||||
|
||||
let renderer: ReactTestRenderer | undefined;
|
||||
const editorRef = createRef<ComposerPromptEditorHandle>();
|
||||
|
||||
function composer(value: string) {
|
||||
return (
|
||||
<ComposerPromptEditor
|
||||
value={value}
|
||||
cursor={collapseExpandedComposerCursor(value, value.length)}
|
||||
contextRecords={new Map()}
|
||||
skills={[]}
|
||||
disabled={false}
|
||||
placeholder="Write a prompt"
|
||||
onChange={() => {}}
|
||||
onPaste={() => {}}
|
||||
editorRef={editorRef}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
async function renderPrompt(value: string) {
|
||||
await act(() => {
|
||||
if (renderer) renderer.update(composer(value));
|
||||
else renderer = create(composer(value));
|
||||
});
|
||||
}
|
||||
|
||||
function $firstMention() {
|
||||
const paragraph = $getRoot().getFirstChildOrThrow();
|
||||
if (!$isElementNode(paragraph)) throw new Error("Expected a composer paragraph");
|
||||
const mention = paragraph.getFirstChildOrThrow();
|
||||
if (mention.getType() !== "composer-mention") throw new Error("Expected a mention");
|
||||
return mention;
|
||||
}
|
||||
|
||||
class TestClipboardEvent extends Event {
|
||||
readonly clipboardData: DataTransfer;
|
||||
|
||||
constructor(text: string) {
|
||||
super("paste", { cancelable: true });
|
||||
this.clipboardData = {
|
||||
files: [],
|
||||
getData: (type: string) => (type === "text/plain" ? text : ""),
|
||||
} as unknown as DataTransfer;
|
||||
}
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);
|
||||
vi.stubGlobal("document", { activeElement: null });
|
||||
});
|
||||
|
||||
afterEach(async () => {
|
||||
await act(() => renderer?.unmount());
|
||||
renderer = undefined;
|
||||
vi.unstubAllGlobals();
|
||||
});
|
||||
|
||||
describe("composer mention serialization", () => {
|
||||
it.each([
|
||||
"@README.md control",
|
||||
"@terminal-1:3 Explain this output\n\n<terminal_context>\n- Terminal 1 line 3:\n 3 | output\n</terminal_context>",
|
||||
'@"docs/My \\"File\\".md" please',
|
||||
'@"docs/雪 👋.md" please',
|
||||
"[README.md](README.md) control",
|
||||
"[config#draft?.json](config%23draft%3f.json) control",
|
||||
"Plain text\n Keep indentation 👋",
|
||||
])("preserves the initial prompt %s", async (prompt) => {
|
||||
await renderPrompt(prompt);
|
||||
expect(editorRef.current?.readSnapshot().value).toBe(prompt);
|
||||
});
|
||||
|
||||
it("preserves original source when replacing the controlled prompt", async () => {
|
||||
for (const prompt of ["", "@README.md control", "Older plain control", "@README.md control"]) {
|
||||
await renderPrompt(prompt);
|
||||
expect(editorRef.current?.readSnapshot()).toMatchObject({
|
||||
value: prompt,
|
||||
expandedCursor: prompt.length,
|
||||
});
|
||||
if (prompt === "@README.md control") {
|
||||
expect(lexicalEditor.getEditorState().read(() => $firstMention().isInline())).toBe(true);
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
it("preserves source when Lexical clones the mention and reloads exported state", async () => {
|
||||
const prompt = '@"docs/雪 👋.md" remains a chip';
|
||||
await renderPrompt(prompt);
|
||||
const originalKey = lexicalEditor.getEditorState().read(() => $firstMention().getKey());
|
||||
|
||||
await act(() => {
|
||||
lexicalEditor.update(
|
||||
() => {
|
||||
const mention = $firstMention();
|
||||
mention.replace($copyNode(mention));
|
||||
},
|
||||
{ discrete: true },
|
||||
);
|
||||
});
|
||||
expect(lexicalEditor.getEditorState().read(() => $firstMention().getKey())).not.toBe(
|
||||
originalKey,
|
||||
);
|
||||
expect(editorRef.current?.readSnapshot().value).toBe(prompt);
|
||||
const exportedState = lexicalEditor.getEditorState().toJSON();
|
||||
|
||||
await renderPrompt("");
|
||||
await act(() => {
|
||||
lexicalEditor.setEditorState(lexicalEditor.parseEditorState(exportedState));
|
||||
});
|
||||
expect(editorRef.current?.readSnapshot().value).toBe(prompt);
|
||||
expect(lexicalEditor.getEditorState().read(() => $firstMention().isInline())).toBe(true);
|
||||
});
|
||||
|
||||
it("keeps canonical serialization when importing legacy mention JSON without source", async () => {
|
||||
await renderPrompt("");
|
||||
await act(() => {
|
||||
lexicalEditor.setEditorState(
|
||||
lexicalEditor.parseEditorState(
|
||||
JSON.stringify({
|
||||
root: {
|
||||
type: "root",
|
||||
version: 1,
|
||||
children: [
|
||||
{
|
||||
type: "paragraph",
|
||||
version: 1,
|
||||
children: [{ type: "composer-mention", version: 1, path: "README.md" }],
|
||||
},
|
||||
],
|
||||
},
|
||||
}),
|
||||
),
|
||||
);
|
||||
});
|
||||
expect(editorRef.current?.readSnapshot().value).toBe("[README.md](README.md)");
|
||||
expect(lexicalEditor.getEditorState().read(() => $firstMention().isInline())).toBe(true);
|
||||
});
|
||||
|
||||
it("still serializes a newly inserted mention canonically", async () => {
|
||||
vi.stubGlobal("ClipboardEvent", TestClipboardEvent);
|
||||
await renderPrompt("");
|
||||
const event = new TestClipboardEvent("@README.md ");
|
||||
await act(() => {
|
||||
lexicalEditor.update(
|
||||
() => {
|
||||
$getRoot().selectEnd();
|
||||
lexicalEditor.dispatchCommand(PASTE_COMMAND, event as ClipboardEvent);
|
||||
},
|
||||
{ discrete: true },
|
||||
);
|
||||
});
|
||||
expect(event.defaultPrevented).toBe(true);
|
||||
expect(editorRef.current?.readSnapshot().value).toBe("[README.md](README.md) ");
|
||||
expect(lexicalEditor.getEditorState().read(() => $firstMention().isInline())).toBe(true);
|
||||
});
|
||||
});
|
||||
@@ -1,864 +0,0 @@
|
||||
import { upgradeLegacyContextMessage } from "@t3tools/shared/composerContextLegacy";
|
||||
import { elementContextToPreviewAnnotation } from "../lib/elementContext";
|
||||
import { previewAnnotationContextRecord } from "../lib/composerContextRecords";
|
||||
import { EnvironmentId, MessageId, ThreadId, type AssistantCitation } from "@t3tools/contracts";
|
||||
import { serializeAssistantCitation } from "@t3tools/shared/assistantCitations";
|
||||
import { afterEach, describe, expect, it, vi } from "vite-plus/test";
|
||||
import {
|
||||
$createParagraphNode,
|
||||
$createTextNode,
|
||||
$getRoot,
|
||||
$getSelection,
|
||||
$isElementNode,
|
||||
$isRangeSelection,
|
||||
COMMAND_PRIORITY_EDITOR,
|
||||
createEditor,
|
||||
PASTE_COMMAND,
|
||||
} from "lexical";
|
||||
|
||||
import {
|
||||
importPastedComposerText,
|
||||
readPastedComposerContext,
|
||||
registerComposerInlineTokenPaste,
|
||||
} from "./composerInlineTokenPaste";
|
||||
import {
|
||||
$consumeComposerCitationCommentRequest,
|
||||
$createComposerCitationNode,
|
||||
ComposerCitationNode,
|
||||
type ComposerCitationCommentRequest,
|
||||
} from "./ComposerCitationNode";
|
||||
import { splitPromptIntoComposerSegments } from "../composer-editor-mentions";
|
||||
import type { AssistantCitationSourceAnchor } from "~/lib/assistantTextSelection";
|
||||
|
||||
vi.mock("./chat/AssistantCitationChip", () => ({ AssistantCitationChip: () => null }));
|
||||
|
||||
const citation: AssistantCitation = {
|
||||
version: 1,
|
||||
environmentId: EnvironmentId.make("remote/雪"),
|
||||
threadId: ThreadId.make("thread-1"),
|
||||
messageId: MessageId.make("message-1"),
|
||||
text: 'Keep "👋", (punctuation) and @AGENTS.md.',
|
||||
start: 5,
|
||||
end: 43,
|
||||
prefix: "前: ",
|
||||
suffix: " 後",
|
||||
};
|
||||
const citationSource = serializeAssistantCitation(citation).replaceAll("+", "%20");
|
||||
|
||||
function createCitationEditor(text = "") {
|
||||
const editor = createEditor({ nodes: [ComposerCitationNode] });
|
||||
editor.update(
|
||||
() => {
|
||||
const paragraph = $createParagraphNode();
|
||||
$getRoot().append(paragraph);
|
||||
if (text) paragraph.append($createTextNode(text));
|
||||
paragraph.selectEnd();
|
||||
},
|
||||
{ discrete: true },
|
||||
);
|
||||
registerComposerInlineTokenPaste(editor, {
|
||||
createMentionNode: (path) => $createTextNode(`<mention:${path}>`),
|
||||
createCitationNode: $createComposerCitationNode,
|
||||
createContextReferenceNode: (reference) => $createTextNode(`<context:${reference.contextId}>`),
|
||||
getExpandedAbsoluteOffsetForPoint: (_node, offset) => offset,
|
||||
});
|
||||
return editor;
|
||||
}
|
||||
|
||||
function $citationNodes() {
|
||||
const paragraph = $getRoot().getFirstChildOrThrow();
|
||||
if (!$isElementNode(paragraph)) throw new Error("Expected a composer paragraph");
|
||||
return paragraph.getChildren().filter((node) => node instanceof ComposerCitationNode);
|
||||
}
|
||||
|
||||
function pasteText(editor: ReturnType<typeof createEditor>, text: string) {
|
||||
const event = new TestClipboardEvent(text);
|
||||
editor.update(
|
||||
() => {
|
||||
editor.dispatchCommand(PASTE_COMMAND, event as ClipboardEvent);
|
||||
},
|
||||
{ discrete: true },
|
||||
);
|
||||
return event;
|
||||
}
|
||||
|
||||
class TestClipboardEvent extends Event {
|
||||
readonly clipboardData: DataTransfer;
|
||||
|
||||
constructor(text: string, extra: Record<string, string> = {}) {
|
||||
super("paste", { cancelable: true });
|
||||
this.clipboardData = {
|
||||
files: [],
|
||||
getData: (type: string) => (type === "text/plain" ? text : (extra[type] ?? "")),
|
||||
} as unknown as DataTransfer;
|
||||
}
|
||||
}
|
||||
|
||||
describe("registerComposerInlineTokenPaste", () => {
|
||||
afterEach(() => {
|
||||
vi.unstubAllGlobals();
|
||||
});
|
||||
|
||||
it("handles a copied mention without also running the plain-text paste fallback", () => {
|
||||
vi.stubGlobal("ClipboardEvent", TestClipboardEvent);
|
||||
const editor = createEditor();
|
||||
const mention = "[improve-deploy-error-logging.md](.changeset/improve-deploy-error-logging.md)";
|
||||
const plainTextFallback = vi.fn(() => {
|
||||
const selection = $getSelection();
|
||||
if (!$isRangeSelection(selection)) return false;
|
||||
selection.insertText(mention);
|
||||
return true;
|
||||
});
|
||||
|
||||
editor.update(
|
||||
() => {
|
||||
const paragraph = $createParagraphNode();
|
||||
$getRoot().append(paragraph);
|
||||
paragraph.selectEnd();
|
||||
},
|
||||
{ discrete: true },
|
||||
);
|
||||
registerComposerInlineTokenPaste(editor, {
|
||||
createMentionNode: (path) => $createTextNode(`<mention:${path}>`),
|
||||
createCitationNode: $createComposerCitationNode,
|
||||
createContextReferenceNode: (reference) =>
|
||||
$createTextNode(`<context:${reference.contextId}>`),
|
||||
getExpandedAbsoluteOffsetForPoint: () => 0,
|
||||
});
|
||||
editor.registerCommand(PASTE_COMMAND, plainTextFallback, COMMAND_PRIORITY_EDITOR);
|
||||
|
||||
const event = new TestClipboardEvent(mention);
|
||||
let handled = false;
|
||||
editor.update(
|
||||
() => {
|
||||
handled = editor.dispatchCommand(PASTE_COMMAND, event as ClipboardEvent);
|
||||
},
|
||||
{ discrete: true },
|
||||
);
|
||||
|
||||
expect(handled).toBe(true);
|
||||
expect(plainTextFallback).not.toHaveBeenCalled();
|
||||
expect(event.defaultPrevented).toBe(true);
|
||||
expect(editor.getEditorState().read(() => $getRoot().getTextContent())).toBe(
|
||||
"<mention:.changeset/improve-deploy-error-logging.md> ",
|
||||
);
|
||||
});
|
||||
|
||||
it.each([
|
||||
"yarn expo install @expo/ui",
|
||||
"npm install @jane/foo.js",
|
||||
"import '@scope/pkg/sub/path'",
|
||||
])("leaves scoped package command %s to the plain-text paste fallback", (command) => {
|
||||
vi.stubGlobal("ClipboardEvent", TestClipboardEvent);
|
||||
const editor = createEditor();
|
||||
const plainTextFallback = vi.fn((event: ClipboardEvent) => {
|
||||
const selection = $getSelection();
|
||||
if (!$isRangeSelection(selection)) return false;
|
||||
selection.insertText(event.clipboardData?.getData("text/plain") ?? "");
|
||||
return true;
|
||||
});
|
||||
|
||||
editor.update(
|
||||
() => {
|
||||
const paragraph = $createParagraphNode();
|
||||
$getRoot().append(paragraph);
|
||||
paragraph.selectEnd();
|
||||
},
|
||||
{ discrete: true },
|
||||
);
|
||||
registerComposerInlineTokenPaste(editor, {
|
||||
createMentionNode: (path) => $createTextNode(`<mention:${path}>`),
|
||||
createCitationNode: $createComposerCitationNode,
|
||||
createContextReferenceNode: (reference) =>
|
||||
$createTextNode(`<context:${reference.contextId}>`),
|
||||
getExpandedAbsoluteOffsetForPoint: () => 0,
|
||||
});
|
||||
editor.registerCommand(PASTE_COMMAND, plainTextFallback, COMMAND_PRIORITY_EDITOR);
|
||||
|
||||
const event = new TestClipboardEvent(command);
|
||||
let handled = false;
|
||||
editor.update(
|
||||
() => {
|
||||
handled = editor.dispatchCommand(PASTE_COMMAND, event as ClipboardEvent);
|
||||
},
|
||||
{ discrete: true },
|
||||
);
|
||||
|
||||
expect(handled).toBe(true);
|
||||
expect(plainTextFallback).toHaveBeenCalledOnce();
|
||||
expect(editor.getEditorState().read(() => $getRoot().getTextContent())).toBe(command);
|
||||
});
|
||||
|
||||
it("pastes a canonical scoped folder link as a mention", () => {
|
||||
vi.stubGlobal("ClipboardEvent", TestClipboardEvent);
|
||||
const editor = createEditor();
|
||||
const mention = "[sub](@scope/pkg/sub)";
|
||||
const plainTextFallback = vi.fn(() => true);
|
||||
|
||||
editor.update(
|
||||
() => {
|
||||
const paragraph = $createParagraphNode();
|
||||
$getRoot().append(paragraph);
|
||||
paragraph.selectEnd();
|
||||
},
|
||||
{ discrete: true },
|
||||
);
|
||||
registerComposerInlineTokenPaste(editor, {
|
||||
createMentionNode: (path) => $createTextNode(`<mention:${path}>`),
|
||||
createCitationNode: $createComposerCitationNode,
|
||||
createContextReferenceNode: (reference) =>
|
||||
$createTextNode(`<context:${reference.contextId}>`),
|
||||
getExpandedAbsoluteOffsetForPoint: () => 0,
|
||||
});
|
||||
editor.registerCommand(PASTE_COMMAND, plainTextFallback, COMMAND_PRIORITY_EDITOR);
|
||||
|
||||
const event = new TestClipboardEvent(mention);
|
||||
let handled = false;
|
||||
editor.update(
|
||||
() => {
|
||||
handled = editor.dispatchCommand(PASTE_COMMAND, event as ClipboardEvent);
|
||||
},
|
||||
{ discrete: true },
|
||||
);
|
||||
|
||||
expect(handled).toBe(true);
|
||||
expect(plainTextFallback).not.toHaveBeenCalled();
|
||||
expect(event.defaultPrevented).toBe(true);
|
||||
expect(editor.getEditorState().read(() => $getRoot().getTextContent())).toBe(
|
||||
"<mention:@scope/pkg/sub> ",
|
||||
);
|
||||
});
|
||||
|
||||
it("restores multiple citation nodes beside punctuation and Unicode without changing their source", () => {
|
||||
vi.stubGlobal("ClipboardEvent", TestClipboardEvent);
|
||||
const editor = createCitationEditor();
|
||||
const secondSource = serializeAssistantCitation({
|
||||
...citation,
|
||||
messageId: MessageId.make("message-2"),
|
||||
text: "Another quote 👋",
|
||||
});
|
||||
const text = `前(${citationSource}),${secondSource}${citationSource}`;
|
||||
const plainTextFallback = vi.fn(() => true);
|
||||
editor.registerCommand(PASTE_COMMAND, plainTextFallback, COMMAND_PRIORITY_EDITOR);
|
||||
|
||||
const event = pasteText(editor, text);
|
||||
|
||||
expect(event.defaultPrevented).toBe(true);
|
||||
expect(plainTextFallback).not.toHaveBeenCalled();
|
||||
editor.getEditorState().read(() => {
|
||||
expect($getRoot().getTextContent()).toBe(text);
|
||||
expect($citationNodes().map((node) => node.getTextContent())).toEqual([
|
||||
citationSource,
|
||||
secondSource,
|
||||
citationSource,
|
||||
]);
|
||||
});
|
||||
});
|
||||
|
||||
it("restores citations alongside mentions and only pads a trailing mention", () => {
|
||||
vi.stubGlobal("ClipboardEvent", TestClipboardEvent);
|
||||
const editor = createCitationEditor();
|
||||
|
||||
pasteText(editor, `${citationSource}\n[AGENTS.md](AGENTS.md) ${citationSource}`);
|
||||
|
||||
editor.getEditorState().read(() => {
|
||||
expect($getRoot().getTextContent()).toBe(
|
||||
`${citationSource}\n<mention:AGENTS.md> ${citationSource}`,
|
||||
);
|
||||
expect($citationNodes()).toHaveLength(2);
|
||||
});
|
||||
|
||||
const trailingMentionEditor = createCitationEditor();
|
||||
pasteText(trailingMentionEditor, `${citationSource} [AGENTS.md](AGENTS.md)`);
|
||||
|
||||
expect(trailingMentionEditor.getEditorState().read(() => $getRoot().getTextContent())).toBe(
|
||||
`${citationSource} <mention:AGENTS.md> `,
|
||||
);
|
||||
});
|
||||
|
||||
it.each(["what do you mean??\nPlease keep the indentation:\n café 👋"])(
|
||||
"keeps the edited comment %j bound to its quote through an editor reload and paste",
|
||||
(comment) => {
|
||||
vi.stubGlobal("ClipboardEvent", TestClipboardEvent);
|
||||
const editor = createCitationEditor();
|
||||
const commentedCitation = { ...citation, comment };
|
||||
const source = serializeAssistantCitation(commentedCitation);
|
||||
pasteText(editor, `前(${citationSource})後`);
|
||||
editor.update(
|
||||
() => {
|
||||
$citationNodes()[0]!.setComment(comment);
|
||||
},
|
||||
{ discrete: true },
|
||||
);
|
||||
|
||||
editor.getEditorState().read(() => {
|
||||
expect($getRoot().getTextContent()).toBe(`前(${source})後`);
|
||||
expect($citationNodes()[0]!.exportJSON().citation).toEqual(commentedCitation);
|
||||
});
|
||||
|
||||
const restored = createCitationEditor();
|
||||
restored.setEditorState(restored.parseEditorState(editor.getEditorState().toJSON()));
|
||||
restored.update(
|
||||
() => {
|
||||
const paragraph = $getRoot().getFirstChildOrThrow();
|
||||
if (!$isElementNode(paragraph)) throw new Error("Expected a composer paragraph");
|
||||
paragraph.selectStart().insertText("About ");
|
||||
},
|
||||
{ discrete: true },
|
||||
);
|
||||
|
||||
restored.getEditorState().read(() => {
|
||||
expect($getRoot().getTextContent()).toBe(`About 前(${source})後`);
|
||||
expect($getRoot().getChildrenSize()).toBe(1);
|
||||
expect($citationNodes()[0]!.exportJSON().citation).toEqual(commentedCitation);
|
||||
});
|
||||
|
||||
const pasted = createCitationEditor();
|
||||
pasteText(
|
||||
pasted,
|
||||
restored.getEditorState().read(() => $getRoot().getTextContent()),
|
||||
);
|
||||
pasted.getEditorState().read(() => {
|
||||
expect($getRoot().getTextContent()).toBe(`About 前(${source})後`);
|
||||
expect($citationNodes()[0]!.exportJSON().citation).toEqual(commentedCitation);
|
||||
});
|
||||
},
|
||||
);
|
||||
|
||||
it("edits only one repeated quote without moving selection or mutating earlier editor states", () => {
|
||||
vi.stubGlobal("ClipboardEvent", TestClipboardEvent);
|
||||
const editor = createCitationEditor();
|
||||
const prompt = `前(${citationSource}),(${citationSource})後`;
|
||||
pasteText(editor, prompt);
|
||||
editor.update(
|
||||
() => {
|
||||
$getRoot().getAllTextNodes().at(-1)!.select(2, 1);
|
||||
},
|
||||
{ discrete: true },
|
||||
);
|
||||
const beforeEdit = editor.getEditorState();
|
||||
const selection = beforeEdit.read(() => $getSelection()!.clone());
|
||||
const node = beforeEdit.read(() => $citationNodes()[1]!);
|
||||
editor.update(() => node.setComment("First draft"), { discrete: true });
|
||||
const comment = "Use this occurrence, not the earlier quote.";
|
||||
editor.update(() => node.setComment(comment), { discrete: true });
|
||||
const afterEdit = editor.getEditorState();
|
||||
const source = serializeAssistantCitation({ ...citation, comment });
|
||||
|
||||
afterEdit.read(() => {
|
||||
expect($getRoot().getTextContent()).toBe(`前(${citationSource}),(${source})後`);
|
||||
expect($citationNodes().map((citationNode) => citationNode.exportJSON().citation)).toEqual([
|
||||
citation,
|
||||
{ ...citation, comment },
|
||||
]);
|
||||
expect($getSelection()?.is(selection)).toBe(true);
|
||||
});
|
||||
beforeEdit.read(() => {
|
||||
expect($getRoot().getTextContent()).toBe(prompt);
|
||||
expect($citationNodes().map((citationNode) => citationNode.exportJSON().citation)).toEqual([
|
||||
citation,
|
||||
citation,
|
||||
]);
|
||||
});
|
||||
|
||||
editor.setEditorState(beforeEdit);
|
||||
expect(editor.getEditorState().read(() => $getRoot().getTextContent())).toBe(prompt);
|
||||
editor.setEditorState(afterEdit);
|
||||
expect(editor.getEditorState().read(() => $getRoot().getTextContent())).toBe(
|
||||
`前(${citationSource}),(${source})後`,
|
||||
);
|
||||
});
|
||||
|
||||
it.each(["", " \n\t "])("clears a comment with %j without removing the quote", (comment) => {
|
||||
vi.stubGlobal("ClipboardEvent", TestClipboardEvent);
|
||||
const editor = createCitationEditor();
|
||||
pasteText(editor, citationSource);
|
||||
editor.update(() => $citationNodes()[0]!.setComment("Remove this comment."), {
|
||||
discrete: true,
|
||||
});
|
||||
editor.update(() => $citationNodes()[0]!.setComment(comment), { discrete: true });
|
||||
|
||||
editor.getEditorState().read(() => {
|
||||
expect($citationNodes()).toHaveLength(1);
|
||||
expect($citationNodes()[0]!.exportJSON().citation).toStrictEqual(citation);
|
||||
expect($getRoot().getTextContent()).toBe(serializeAssistantCitation(citation));
|
||||
});
|
||||
});
|
||||
|
||||
it("keeps a citation pasted after an unfinished @ restorable as a chip", () => {
|
||||
vi.stubGlobal("ClipboardEvent", TestClipboardEvent);
|
||||
const editor = createCitationEditor("@");
|
||||
|
||||
pasteText(editor, citationSource);
|
||||
|
||||
const prompt = editor.getEditorState().read(() => $getRoot().getTextContent());
|
||||
expect(splitPromptIntoComposerSegments(prompt)).toEqual([
|
||||
{ type: "text", text: "@" },
|
||||
{ type: "citation", citation, source: citationSource },
|
||||
]);
|
||||
});
|
||||
|
||||
it("copies, cuts, and pastes selected citation nodes with all source metadata intact", () => {
|
||||
vi.stubGlobal("ClipboardEvent", TestClipboardEvent);
|
||||
const editor = createCitationEditor();
|
||||
const firstCitation = { ...citation, comment: "Explain the first occurrence." };
|
||||
const secondCitation = { ...citation, comment: "Keep the second occurrence.\n café 👋" };
|
||||
const selectedText = `${serializeAssistantCitation(firstCitation)},${serializeAssistantCitation(secondCitation)}`;
|
||||
pasteText(editor, `before ${citationSource},${citationSource} after`);
|
||||
editor.update(
|
||||
() => {
|
||||
$citationNodes()[0]!.setComment(firstCitation.comment);
|
||||
$citationNodes()[1]!.setComment(secondCitation.comment);
|
||||
},
|
||||
{ discrete: true },
|
||||
);
|
||||
let copied = "";
|
||||
editor.update(
|
||||
() => {
|
||||
const paragraph = $getRoot().getFirstChildOrThrow();
|
||||
if (!$isElementNode(paragraph)) throw new Error("Expected a composer paragraph");
|
||||
paragraph.select(1, 4);
|
||||
const selection = $getSelection();
|
||||
if (!$isRangeSelection(selection)) throw new Error("Expected a range selection");
|
||||
copied = selection.getTextContent();
|
||||
selection.removeText();
|
||||
},
|
||||
{ discrete: true },
|
||||
);
|
||||
|
||||
expect(copied).toBe(selectedText);
|
||||
expect(editor.getEditorState().read(() => $getRoot().getTextContent())).toBe("before after");
|
||||
|
||||
pasteText(editor, copied);
|
||||
|
||||
editor.getEditorState().read(() => {
|
||||
expect($getRoot().getTextContent()).toBe(`before ${selectedText} after`);
|
||||
expect($citationNodes().map((node) => node.exportJSON().citation)).toEqual([
|
||||
firstCitation,
|
||||
secondCitation,
|
||||
]);
|
||||
});
|
||||
});
|
||||
|
||||
it.each([true, false])(
|
||||
"deletes a citation and its comment atomically, backwards=%s",
|
||||
(backwards) => {
|
||||
const editor = createCitationEditor();
|
||||
const commentedCitation = { ...citation, comment: "Delete this with its quote.\n café 👋" };
|
||||
const source = serializeAssistantCitation(commentedCitation);
|
||||
editor.update(
|
||||
() => {
|
||||
const paragraph = $getRoot().getFirstChildOrThrow();
|
||||
if (!$isElementNode(paragraph)) throw new Error("Expected a composer paragraph");
|
||||
const before = $createTextNode("前(");
|
||||
const after = $createTextNode(")後");
|
||||
paragraph.append(
|
||||
before,
|
||||
$createComposerCitationNode(citation, citationSource).setComment(
|
||||
commentedCitation.comment,
|
||||
),
|
||||
after,
|
||||
);
|
||||
if (backwards) {
|
||||
after.selectStart();
|
||||
} else {
|
||||
before.selectEnd();
|
||||
}
|
||||
},
|
||||
{ discrete: true },
|
||||
);
|
||||
const beforeDeletion = editor.getEditorState();
|
||||
const serialized = beforeDeletion.toJSON();
|
||||
|
||||
editor.update(
|
||||
() => {
|
||||
const selection = $getSelection();
|
||||
if (!$isRangeSelection(selection)) throw new Error("Expected a range selection");
|
||||
selection.deleteCharacter(backwards);
|
||||
},
|
||||
{ discrete: true },
|
||||
);
|
||||
|
||||
const afterDeletion = editor.getEditorState();
|
||||
expect(afterDeletion.read(() => $getRoot().getTextContent())).toBe("前()後");
|
||||
|
||||
editor.setEditorState(beforeDeletion);
|
||||
expect(editor.getEditorState().read(() => $getRoot().getTextContent())).toBe(
|
||||
`前(${source})後`,
|
||||
);
|
||||
editor.setEditorState(afterDeletion);
|
||||
expect(editor.getEditorState().read(() => $citationNodes())).toHaveLength(0);
|
||||
|
||||
editor.setEditorState(editor.parseEditorState(serialized));
|
||||
editor.getEditorState().read(() => {
|
||||
expect($getRoot().getTextContent()).toBe(`前(${source})後`);
|
||||
expect($citationNodes()[0]?.exportJSON().citation).toEqual(commentedCitation);
|
||||
});
|
||||
},
|
||||
);
|
||||
});
|
||||
|
||||
describe("context reference paste", () => {
|
||||
it.each([
|
||||
{ focus: "focused", prefix: "" },
|
||||
{ focus: "blurred", prefix: "" },
|
||||
{ focus: "focused", prefix: "log ".repeat(10_000) },
|
||||
{ focus: "blurred", prefix: "log ".repeat(10_000) },
|
||||
])(
|
||||
"imports structured paste when $focus with $prefix.length extra characters",
|
||||
({ focus, prefix }) => {
|
||||
vi.stubGlobal("ClipboardEvent", TestClipboardEvent);
|
||||
const editor = createEditor({ nodes: [ComposerCitationNode] });
|
||||
editor.update(
|
||||
() => {
|
||||
const paragraph = $createParagraphNode();
|
||||
$getRoot().append(paragraph);
|
||||
paragraph.selectEnd();
|
||||
},
|
||||
{ discrete: true },
|
||||
);
|
||||
const imported: string[] = [];
|
||||
const importFragment = (
|
||||
fragment: import("@t3tools/contracts").ComposerContextClipboardFragment,
|
||||
) => {
|
||||
imported.push(...fragment.records.map((record) => record.contextId));
|
||||
return new Map([["img-old", "img-new"]]);
|
||||
};
|
||||
registerComposerInlineTokenPaste(editor, {
|
||||
createMentionNode: (path) => $createTextNode(`<mention:${path}>`),
|
||||
createCitationNode: $createComposerCitationNode,
|
||||
createContextReferenceNode: (reference) =>
|
||||
$createTextNode(`<context:${reference.contextId}>`),
|
||||
getExpandedAbsoluteOffsetForPoint: () => 0,
|
||||
importContextFragment: importFragment,
|
||||
});
|
||||
const event = new TestClipboardEvent(
|
||||
`${prefix} and [T](t3-context://v1/terminal/ctx-t)`,
|
||||
{
|
||||
"web application/x-t3-context-fragment+json": JSON.stringify({
|
||||
version: 1,
|
||||
source: { environmentId: "env-1" },
|
||||
records: [
|
||||
{
|
||||
version: 1,
|
||||
contextId: "img-old",
|
||||
kind: "image",
|
||||
label: "shot",
|
||||
attachmentId: "a",
|
||||
name: "shot.png",
|
||||
mimeType: "image/png",
|
||||
sizeBytes: 1,
|
||||
},
|
||||
{
|
||||
version: 1,
|
||||
contextId: "ctx-t",
|
||||
kind: "terminal",
|
||||
label: "T",
|
||||
terminalId: "t",
|
||||
terminalLabel: "T",
|
||||
lineStart: 1,
|
||||
lineEnd: 1,
|
||||
text: "x",
|
||||
},
|
||||
{
|
||||
version: 1,
|
||||
contextId: "img-unrelated",
|
||||
kind: "image",
|
||||
label: "other",
|
||||
attachmentId: "b",
|
||||
name: "other.png",
|
||||
mimeType: "image/png",
|
||||
sizeBytes: 1,
|
||||
},
|
||||
],
|
||||
}),
|
||||
},
|
||||
);
|
||||
expect(
|
||||
readPastedComposerContext(event.clipboardData)?.records.map((record) => record.contextId),
|
||||
).toEqual(["img-old", "ctx-t"]);
|
||||
if (focus === "blurred") {
|
||||
expect(importPastedComposerText(event.clipboardData, importFragment)).toBe(
|
||||
`${prefix} and [T](t3-context://v1/terminal/ctx-t)`,
|
||||
);
|
||||
expect(imported).toEqual(["img-old", "ctx-t"]);
|
||||
return;
|
||||
}
|
||||
editor.update(
|
||||
() => {
|
||||
editor.dispatchCommand(PASTE_COMMAND, event as ClipboardEvent);
|
||||
},
|
||||
{ discrete: true },
|
||||
);
|
||||
expect(imported).toEqual(["img-old", "ctx-t"]);
|
||||
expect(editor.getEditorState().read(() => $getRoot().getTextContent())).toBe(
|
||||
`${prefix}<context:img-new> and <context:ctx-t>`,
|
||||
);
|
||||
},
|
||||
);
|
||||
|
||||
it("converts a copied legacy element into a sendable annotation and rewrites its link", () => {
|
||||
const copied = upgradeLegacyContextMessage(
|
||||
[
|
||||
"Fix this",
|
||||
"",
|
||||
"<element_context>",
|
||||
"- <button>:",
|
||||
" url: https://example.com",
|
||||
" selector: #save",
|
||||
" html:",
|
||||
" <button>Save</button>",
|
||||
" styles:",
|
||||
" color: red;",
|
||||
"</element_context>",
|
||||
].join("\n"),
|
||||
);
|
||||
const event = new TestClipboardEvent(copied.text, {
|
||||
"web application/x-t3-context-fragment+json": JSON.stringify({
|
||||
version: 1,
|
||||
source: { environmentId: "env-1" },
|
||||
records: copied.records,
|
||||
}),
|
||||
});
|
||||
const annotations: ReturnType<typeof previewAnnotationContextRecord>[] = [];
|
||||
const text = importPastedComposerText(event.clipboardData, (fragment) => {
|
||||
const record = fragment.records[0]!;
|
||||
if (record.kind !== "element" || "payload" in record) throw new Error("Expected element");
|
||||
const annotation = previewAnnotationContextRecord(
|
||||
elementContextToPreviewAnnotation(record, "imported", "2026-01-01T00:00:00Z"),
|
||||
);
|
||||
annotations.push(annotation);
|
||||
return new Map([[record.contextId, annotation.contextId]]);
|
||||
});
|
||||
expect(text).toContain("t3-context://v1/preview-annotation/preview-annotation_imported");
|
||||
expect(annotations[0]?.elements?.[0]).toMatchObject({
|
||||
selector: "#save",
|
||||
htmlPreview: "<button>Save</button>",
|
||||
styles: "color: red;",
|
||||
});
|
||||
});
|
||||
|
||||
it("imports an annotation's dependent screenshot when only its chip is pasted", () => {
|
||||
vi.stubGlobal("ClipboardEvent", TestClipboardEvent);
|
||||
const editor = createEditor({ nodes: [ComposerCitationNode] });
|
||||
editor.update(
|
||||
() => {
|
||||
const paragraph = $createParagraphNode();
|
||||
$getRoot().append(paragraph);
|
||||
paragraph.selectEnd();
|
||||
},
|
||||
{ discrete: true },
|
||||
);
|
||||
const imported: string[] = [];
|
||||
registerComposerInlineTokenPaste(editor, {
|
||||
createMentionNode: (path) => $createTextNode(`<mention:${path}>`),
|
||||
createCitationNode: $createComposerCitationNode,
|
||||
createContextReferenceNode: (reference) =>
|
||||
$createTextNode(`<context:${reference.contextId}>`),
|
||||
getExpandedAbsoluteOffsetForPoint: () => 0,
|
||||
importContextFragment: (fragment) => {
|
||||
imported.push(...fragment.records.map((record) => record.contextId));
|
||||
return new Map();
|
||||
},
|
||||
});
|
||||
const annotationId = "preview-annotation_ann-1";
|
||||
const screenshotId = "image_ann-1";
|
||||
const event = new TestClipboardEvent(
|
||||
`[Fix button](t3-context://v1/preview-annotation/${annotationId})`,
|
||||
{
|
||||
"web application/x-t3-context-fragment+json": JSON.stringify({
|
||||
version: 1,
|
||||
source: { environmentId: "env-1" },
|
||||
records: [
|
||||
{
|
||||
version: 1,
|
||||
contextId: annotationId,
|
||||
kind: "preview-annotation",
|
||||
label: "Fix button",
|
||||
annotationId: "ann-1",
|
||||
pageUrl: "https://example.com",
|
||||
pageTitle: "Example",
|
||||
comment: "Fix button",
|
||||
targetSummary: "1 selected element",
|
||||
styleChanges: [],
|
||||
screenshotContextId: screenshotId,
|
||||
},
|
||||
{
|
||||
version: 1,
|
||||
contextId: screenshotId,
|
||||
kind: "image",
|
||||
label: "annotation.png",
|
||||
attachmentId: "attachment-1",
|
||||
name: "annotation.png",
|
||||
mimeType: "image/png",
|
||||
sizeBytes: 10,
|
||||
},
|
||||
{
|
||||
version: 1,
|
||||
contextId: "image_unrelated",
|
||||
kind: "image",
|
||||
label: "unrelated.png",
|
||||
attachmentId: "attachment-2",
|
||||
name: "unrelated.png",
|
||||
mimeType: "image/png",
|
||||
sizeBytes: 10,
|
||||
},
|
||||
],
|
||||
}),
|
||||
},
|
||||
);
|
||||
editor.update(
|
||||
() => {
|
||||
editor.dispatchCommand(PASTE_COMMAND, event as ClipboardEvent);
|
||||
},
|
||||
{ discrete: true },
|
||||
);
|
||||
|
||||
expect(imported).toEqual([annotationId, screenshotId]);
|
||||
expect(editor.getEditorState().read(() => $getRoot().getTextContent())).toBe(
|
||||
`<context:${annotationId}>`,
|
||||
);
|
||||
});
|
||||
|
||||
it("turns pasted context links into reference nodes", () => {
|
||||
vi.stubGlobal("ClipboardEvent", TestClipboardEvent);
|
||||
const editor = createCitationEditor("see ");
|
||||
pasteText(editor, "[Terminal 1 line 4](t3-context://v1/terminal/ctx-1) now");
|
||||
expect(editor.getEditorState().read(() => $getRoot().getTextContent())).toBe(
|
||||
"see <context:ctx-1> now",
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe("citation comment opening", () => {
|
||||
const sourceAnchor: AssistantCitationSourceAnchor = {
|
||||
source: { nodeType: 1 } as HTMLElement,
|
||||
range: { collapsed: false } as Range,
|
||||
viewport: { nodeType: 1 } as HTMLElement,
|
||||
};
|
||||
afterEach(() => {
|
||||
vi.unstubAllGlobals();
|
||||
});
|
||||
|
||||
it("opens only the newly inserted occurrence after committing its exact prompt", () => {
|
||||
vi.stubGlobal("ClipboardEvent", TestClipboardEvent);
|
||||
const editor = createCitationEditor();
|
||||
const previousValue = `前 ${citationSource} middle\nbefore after ${citationSource} 後`;
|
||||
pasteText(editor, previousValue);
|
||||
const citationStart = `前 ${citationSource} middle\nbefore `.length;
|
||||
const value =
|
||||
previousValue.slice(0, citationStart) +
|
||||
`${citationSource} ` +
|
||||
previousValue.slice(citationStart);
|
||||
const request: ComposerCitationCommentRequest = {
|
||||
previousValue,
|
||||
value,
|
||||
citationStart,
|
||||
sourceAnchor,
|
||||
};
|
||||
const requestRef = { current: request as ComposerCitationCommentRequest | null };
|
||||
|
||||
editor.getEditorState().read(() => {
|
||||
expect($consumeComposerCitationCommentRequest(requestRef)).toBeNull();
|
||||
expect(requestRef.current).toBe(request);
|
||||
});
|
||||
editor.update(
|
||||
() => {
|
||||
const text = $getRoot()
|
||||
.getAllTextNodes()
|
||||
.find((node) => node.getTextContent() === "before after ");
|
||||
if (!text) throw new Error("Expected insertion text");
|
||||
text.select("before ".length, "before ".length);
|
||||
},
|
||||
{ discrete: true },
|
||||
);
|
||||
pasteText(editor, `${citationSource} `);
|
||||
|
||||
editor.getEditorState().read(() => {
|
||||
const selection = $getSelection()?.clone();
|
||||
expect($getRoot().getTextContent()).toBe(value);
|
||||
expect($citationNodes()).toHaveLength(3);
|
||||
const target = $consumeComposerCitationCommentRequest(requestRef);
|
||||
expect(target?.nodeKey).toBe($citationNodes()[1]!.getKey());
|
||||
expect(target?.sourceAnchor).toBe(sourceAnchor);
|
||||
expect($getSelection()?.is(selection!)).toBe(true);
|
||||
expect($consumeComposerCitationCommentRequest(requestRef)).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
it("does not reopen comments when an inserted citation is restored or pasted", () => {
|
||||
vi.stubGlobal("ClipboardEvent", TestClipboardEvent);
|
||||
const editor = createCitationEditor("before ");
|
||||
const previousState = editor.getEditorState();
|
||||
const value = `before ${citationSource} `;
|
||||
const requestRef: { current: ComposerCitationCommentRequest | null } = {
|
||||
current: { previousValue: "before ", value, citationStart: "before ".length, sourceAnchor },
|
||||
};
|
||||
pasteText(editor, `${citationSource} `);
|
||||
const insertedState = editor.getEditorState();
|
||||
insertedState.read(() => {
|
||||
expect($consumeComposerCitationCommentRequest(requestRef)?.nodeKey).toBe(
|
||||
$citationNodes()[0]!.getKey(),
|
||||
);
|
||||
});
|
||||
editor.update(() => $citationNodes()[0]!.setComment("Keep this attached."), {
|
||||
discrete: true,
|
||||
});
|
||||
const commentedState = editor.getEditorState();
|
||||
|
||||
for (const restoredState of [previousState, insertedState, commentedState]) {
|
||||
editor.setEditorState(restoredState);
|
||||
editor.getEditorState().read(() => {
|
||||
expect($consumeComposerCitationCommentRequest(requestRef)).toBeNull();
|
||||
});
|
||||
}
|
||||
|
||||
const reloaded = createCitationEditor();
|
||||
reloaded.setEditorState(reloaded.parseEditorState(commentedState.toJSON()));
|
||||
reloaded.getEditorState().read(() => {
|
||||
expect($consumeComposerCitationCommentRequest({ current: null })).toBeNull();
|
||||
expect($citationNodes()[0]!.exportJSON().citation.comment).toBe("Keep this attached.");
|
||||
});
|
||||
const pasted = createCitationEditor();
|
||||
pasteText(
|
||||
pasted,
|
||||
commentedState.read(() => $getRoot().getTextContent()),
|
||||
);
|
||||
pasted.getEditorState().read(() => {
|
||||
expect($consumeComposerCitationCommentRequest({ current: null })).toBeNull();
|
||||
expect($citationNodes()[0]!.exportJSON().citation.comment).toBe("Keep this attached.");
|
||||
});
|
||||
});
|
||||
|
||||
it("discards an opening request if another prompt replaces the insertion", () => {
|
||||
vi.stubGlobal("ClipboardEvent", TestClipboardEvent);
|
||||
const editor = createCitationEditor();
|
||||
const requestRef: { current: ComposerCitationCommentRequest | null } = {
|
||||
current: { previousValue: "", value: citationSource, citationStart: 0, sourceAnchor },
|
||||
};
|
||||
editor.update(
|
||||
() => {
|
||||
const selection = $getSelection();
|
||||
if (!$isRangeSelection(selection)) throw new Error("Expected an insertion point");
|
||||
selection.insertText("A different draft");
|
||||
},
|
||||
{ discrete: true },
|
||||
);
|
||||
editor.getEditorState().read(() => {
|
||||
expect($consumeComposerCitationCommentRequest(requestRef)).toBeNull();
|
||||
});
|
||||
editor.update(
|
||||
() => {
|
||||
const paragraph = $getRoot().getFirstChildOrThrow();
|
||||
if (!$isElementNode(paragraph)) throw new Error("Expected a composer paragraph");
|
||||
paragraph.clear().selectStart();
|
||||
},
|
||||
{ discrete: true },
|
||||
);
|
||||
pasteText(editor, citationSource);
|
||||
editor.getEditorState().read(() => {
|
||||
expect($getRoot().getTextContent()).toBe(citationSource);
|
||||
expect($consumeComposerCitationCommentRequest(requestRef)).toBeNull();
|
||||
});
|
||||
});
|
||||
});
|
||||
File diff suppressed because it is too large.
Load diff
File diff suppressed because it is too large.
Load diff
@@ -79,6 +79,7 @@ import {
|
||||
replaceTextRange,
|
||||
} from "../../composer-logic";
|
||||
import { DISCONNECTED_COMPOSER_PLACEHOLDER } from "../../composerPlaceholder";
|
||||
import { listContinuationForEnter, listIndentForTab } from "../../composer-list-continuation";
|
||||
import {
|
||||
deriveComposerSendState,
|
||||
getAntigravitySendBlockReason,
|
||||
@@ -3264,7 +3265,7 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
|
||||
}, [setIsComposerScrollCollapsed]);
|
||||
|
||||
/**
|
||||
* Payloads for chips the prompt no longer references. Lexical's history restores the
|
||||
* Payloads for chips the prompt no longer references. History undo restores the
|
||||
* reference text but knows nothing about the draft records behind it, so a delete keeps its
|
||||
* payload here and an undo puts it back rather than leaving a dangling chip.
|
||||
*/
|
||||
@@ -3420,6 +3421,7 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
|
||||
replacement: string,
|
||||
options?: {
|
||||
expectedText?: string;
|
||||
expandedCursorAfterReplace?: number;
|
||||
focusEditorAfterReplace?: boolean;
|
||||
citationComment?: { start: number; sourceAnchor: AssistantCitationSourceAnchor };
|
||||
},
|
||||
@@ -3440,7 +3442,10 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
|
||||
return false;
|
||||
}
|
||||
const next = replaceTextRange(promptRef.current, rangeStart, rangeEnd, replacement);
|
||||
const nextCursor = collapseExpandedComposerCursor(next.text, next.cursor);
|
||||
const nextCursor = collapseExpandedComposerCursor(
|
||||
next.text,
|
||||
options?.expandedCursorAfterReplace ?? next.cursor,
|
||||
);
|
||||
const nextExpandedCursor = expandCollapsedComposerCursor(next.text, nextCursor);
|
||||
if (options?.citationComment) {
|
||||
composerEditorRef.current?.requestCitationComment({
|
||||
@@ -3927,6 +3932,7 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
|
||||
const onComposerCommandKey = (
|
||||
key: "ArrowDown" | "ArrowUp" | "Enter" | "Tab",
|
||||
event: KeyboardEvent,
|
||||
isTaskItem = false,
|
||||
) => {
|
||||
if (key === "Tab" && event.shiftKey) {
|
||||
if (!planModeUiEnabled) return false;
|
||||
@@ -3970,6 +3976,31 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
|
||||
submitComposer(undefined, submissionIntent);
|
||||
return true;
|
||||
}
|
||||
// Native task splitting preserves marks and chips on both sides of the caret.
|
||||
if (key === "Enter" && isTaskItem) return false;
|
||||
if (!event.isComposing && (key === "Enter" || (key === "Tab" && !event.shiftKey))) {
|
||||
const selection = composerEditorRef.current?.readSelectionRange();
|
||||
const snapshot = readComposerSnapshot();
|
||||
if (selection && selection.start === selection.end && snapshot.value === promptRef.current) {
|
||||
const edit =
|
||||
key === "Enter"
|
||||
? listContinuationForEnter(snapshot.value, selection.start)
|
||||
: listIndentForTab(snapshot.value, selection.start, selection.end);
|
||||
if (
|
||||
edit &&
|
||||
applyPromptReplacement(
|
||||
edit.start,
|
||||
edit.end,
|
||||
edit.replacement,
|
||||
key === "Tab"
|
||||
? { expandedCursorAfterReplace: selection.start + edit.replacement.length }
|
||||
: undefined,
|
||||
)
|
||||
) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
}
|
||||
return false;
|
||||
};
|
||||
|
||||
@@ -6699,6 +6730,7 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
|
||||
<ComposerContextActionsContext value={composerContextActions}>
|
||||
<ComposerPromptEditor
|
||||
editorRef={composerEditorRef}
|
||||
richTextEnabled={settings.composerRichTextEnabled}
|
||||
value={
|
||||
isComposerApprovalState
|
||||
? ""
|
||||
|
||||
@@ -33,7 +33,7 @@ function stashEntrySnippet(entry: PromptStashEntry): string {
|
||||
* Attached banner listing the stashed prompts. Opened by the stash badge or ⌘S
|
||||
* when the empty composer cannot restore a single entry. Navigated with arrows,
|
||||
* restored with Enter, dismissed with Escape. The listener runs capture-phase
|
||||
* on window so it wins over the Lexical editor's handlers while the menu is open.
|
||||
* on window so it wins over the composer's handlers while the menu is open.
|
||||
*/
|
||||
export const ComposerStashMenu = memo(function ComposerStashMenu(props: {
|
||||
entries: ReadonlyArray<PromptStashEntry>;
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { ComposerContextId } from "@t3tools/contracts";
|
||||
import type { AssistantCitation, ComposerContextClipboardFragment } from "@t3tools/contracts";
|
||||
import type { ComposerContextClipboardFragment } from "@t3tools/contracts";
|
||||
import {
|
||||
COMPOSER_CONTEXT_CLIPBOARD_MIME,
|
||||
decodeComposerContextFragment,
|
||||
@@ -10,140 +10,6 @@ import {
|
||||
formatComposerContextReference,
|
||||
replaceComposerContextReferences,
|
||||
} from "@t3tools/shared/composerContextReferences";
|
||||
import {
|
||||
$createLineBreakNode,
|
||||
$createTextNode,
|
||||
$getRoot,
|
||||
$getSelection,
|
||||
$isRangeSelection,
|
||||
COMMAND_PRIORITY_HIGH,
|
||||
PASTE_COMMAND,
|
||||
type LexicalEditor,
|
||||
type LexicalNode,
|
||||
} from "lexical";
|
||||
|
||||
import { collectComposerPromptInlineTokens } from "../composer-editor-mentions";
|
||||
|
||||
interface ComposerInlineTokenPasteOptions {
|
||||
createMentionNode: (path: string) => LexicalNode;
|
||||
createCitationNode: (citation: AssistantCitation, source: string) => LexicalNode;
|
||||
createContextReferenceNode: (reference: {
|
||||
kind: string;
|
||||
contextId: string;
|
||||
label: string;
|
||||
}) => LexicalNode;
|
||||
getExpandedAbsoluteOffsetForPoint: (node: LexicalNode, pointOffset: number) => number;
|
||||
/**
|
||||
* Imports the records behind a structured paste into the draft. Returns the ids that had
|
||||
* to change (a re-attached binary gets a fresh local id) so the pasted links follow.
|
||||
*/
|
||||
importContextFragment?: (
|
||||
fragment: ComposerContextClipboardFragment,
|
||||
) => ReadonlyMap<string, string>;
|
||||
}
|
||||
|
||||
export function registerComposerInlineTokenPaste(
|
||||
editor: LexicalEditor,
|
||||
options: ComposerInlineTokenPasteOptions,
|
||||
): () => void {
|
||||
return editor.registerCommand(
|
||||
PASTE_COMMAND,
|
||||
(event) => {
|
||||
if (!(event instanceof ClipboardEvent) || event.clipboardData === null) {
|
||||
return false;
|
||||
}
|
||||
if (event.clipboardData.files.length > 0) {
|
||||
return false;
|
||||
}
|
||||
const pastedText = event.clipboardData.getData("text/plain");
|
||||
if (pastedText.length === 0) {
|
||||
return false;
|
||||
}
|
||||
const text = importPastedComposerText(event.clipboardData, options.importContextFragment);
|
||||
// Token grammar requires trailing whitespace; a virtual newline lets a
|
||||
// mention at the very end of the pasted text still parse.
|
||||
const tokens = collectComposerPromptInlineTokens(`${text}\n`).filter(
|
||||
(token) =>
|
||||
(token.type === "mention" ||
|
||||
token.type === "citation" ||
|
||||
token.type === "context-reference") &&
|
||||
token.end <= text.length,
|
||||
);
|
||||
if (tokens.length === 0) {
|
||||
return false;
|
||||
}
|
||||
|
||||
// Lexical command listeners already run inside an editor update. Starting
|
||||
// a nested update here queues the token insertion until after this
|
||||
// listener returns, which lets the plain-text paste handler run as well.
|
||||
const selection = $getSelection();
|
||||
if (!$isRangeSelection(selection)) {
|
||||
return false;
|
||||
}
|
||||
const nodes: LexicalNode[] = [];
|
||||
const appendText = (value: string) => {
|
||||
const lines = value.split("\n");
|
||||
for (let index = 0; index < lines.length; index += 1) {
|
||||
const line = lines[index] ?? "";
|
||||
if (line.length > 0) {
|
||||
nodes.push($createTextNode(line));
|
||||
}
|
||||
if (index < lines.length - 1) {
|
||||
nodes.push($createLineBreakNode());
|
||||
}
|
||||
}
|
||||
};
|
||||
const firstToken = tokens[0];
|
||||
if (firstToken?.type === "mention" && firstToken.start === 0) {
|
||||
const startPoint = selection.isBackward() ? selection.focus : selection.anchor;
|
||||
const insertionOffset = options.getExpandedAbsoluteOffsetForPoint(
|
||||
startPoint.getNode(),
|
||||
startPoint.offset,
|
||||
);
|
||||
const precedingChar = $getRoot()
|
||||
.getTextContent()
|
||||
.slice(insertionOffset - 1, insertionOffset);
|
||||
if (precedingChar.length > 0 && !/\s/.test(precedingChar)) {
|
||||
nodes.push($createTextNode(" "));
|
||||
}
|
||||
}
|
||||
let cursor = 0;
|
||||
for (const token of tokens) {
|
||||
if (token.start < cursor) {
|
||||
continue;
|
||||
}
|
||||
if (token.start > cursor) {
|
||||
appendText(text.slice(cursor, token.start));
|
||||
}
|
||||
nodes.push(
|
||||
token.type === "citation"
|
||||
? options.createCitationNode(token.citation, token.source)
|
||||
: token.type === "context-reference"
|
||||
? options.createContextReferenceNode({
|
||||
kind: token.kind,
|
||||
contextId: token.contextId,
|
||||
label: token.label,
|
||||
})
|
||||
: options.createMentionNode(token.value),
|
||||
);
|
||||
cursor = token.end;
|
||||
}
|
||||
if (cursor < text.length) {
|
||||
appendText(text.slice(cursor));
|
||||
} else if (tokens.at(-1)?.type === "mention") {
|
||||
// Keep the serialized prompt valid: mention tokens need trailing
|
||||
// whitespace, so a paste ending in a mention gets the same
|
||||
// trailing space the autocomplete inserts.
|
||||
nodes.push($createTextNode(" "));
|
||||
}
|
||||
selection.insertNodes(nodes);
|
||||
event.preventDefault();
|
||||
return true;
|
||||
},
|
||||
COMMAND_PRIORITY_HIGH,
|
||||
);
|
||||
}
|
||||
|
||||
/** Clipboard records referenced by the copied text, including dependent screenshots. */
|
||||
export function readPastedComposerContext(
|
||||
clipboardData: Pick<DataTransfer, "getData">,
|
||||
@@ -177,7 +43,9 @@ export function readPastedComposerContext(
|
||||
/** Imports the same structured clipboard payload for focused paste and paste-to-focus. */
|
||||
export function importPastedComposerText(
|
||||
clipboardData: Pick<DataTransfer, "getData">,
|
||||
importContextFragment?: ComposerInlineTokenPasteOptions["importContextFragment"],
|
||||
importContextFragment?: (
|
||||
fragment: ComposerContextClipboardFragment,
|
||||
) => ReadonlyMap<string, string>,
|
||||
): string {
|
||||
const pastedText = clipboardData.getData("text/plain");
|
||||
const fragment = importContextFragment ? readPastedComposerContext(clipboardData) : null;
|
||||
|
||||
@@ -10,7 +10,7 @@ import { PREFERRED_HIGHLIGHTER } from "../../lib/syntaxHighlighting";
|
||||
import { GhosttyTerminalSurface } from "~/terminal/ghostty/surface";
|
||||
|
||||
// The font previews are the real surfaces, not lookalikes: the composer's
|
||||
// Lexical editor, the diff panel's file diff, and the Ghostty canvas
|
||||
// Tiptap editor, the diff panel's file diff, and the Ghostty canvas
|
||||
// renderer. Each already consumes the appearance font tokens (or, for the
|
||||
// terminal, the settings passed down as props), so what the row shows is
|
||||
// exactly what the app renders.
|
||||
|
||||
@@ -579,6 +579,9 @@ export function useSettingsRestore(onRestored?: () => void) {
|
||||
...(settings.composerCollapseOnScroll !== DEFAULT_UNIFIED_SETTINGS.composerCollapseOnScroll
|
||||
? ["Collapse composer on scroll"]
|
||||
: []),
|
||||
...(settings.composerRichTextEnabled !== DEFAULT_UNIFIED_SETTINGS.composerRichTextEnabled
|
||||
? ["Rich text composer"]
|
||||
: []),
|
||||
...(settings.sendShortcut !== DEFAULT_UNIFIED_SETTINGS.sendShortcut ? ["Send shortcut"] : []),
|
||||
...(settings.followUpBehavior !== DEFAULT_UNIFIED_SETTINGS.followUpBehavior
|
||||
? ["Follow-up behavior"]
|
||||
@@ -641,6 +644,7 @@ export function useSettingsRestore(onRestored?: () => void) {
|
||||
settings.confirmThreadDelete,
|
||||
settings.confirmThreadUnpin,
|
||||
settings.composerCollapseOnScroll,
|
||||
settings.composerRichTextEnabled,
|
||||
settings.sendShortcut,
|
||||
settings.followUpBehavior,
|
||||
settings.addProjectBaseDirectory,
|
||||
@@ -755,6 +759,7 @@ export function useSettingsRestore(onRestored?: () => void) {
|
||||
proactivePanelsEnabled: DEFAULT_UNIFIED_SETTINGS.proactivePanelsEnabled,
|
||||
showSkillsInSlashMenu: DEFAULT_UNIFIED_SETTINGS.showSkillsInSlashMenu,
|
||||
composerCollapseOnScroll: DEFAULT_UNIFIED_SETTINGS.composerCollapseOnScroll,
|
||||
composerRichTextEnabled: DEFAULT_UNIFIED_SETTINGS.composerRichTextEnabled,
|
||||
sendShortcut: DEFAULT_UNIFIED_SETTINGS.sendShortcut,
|
||||
followUpBehavior: DEFAULT_UNIFIED_SETTINGS.followUpBehavior,
|
||||
contextWindowMeterEnabled: DEFAULT_UNIFIED_SETTINGS.contextWindowMeterEnabled,
|
||||
@@ -2577,6 +2582,33 @@ export function GeneralSettingsPanel() {
|
||||
}
|
||||
/>
|
||||
|
||||
<SettingsRow
|
||||
{...searchableSetting("composer-rich-text")}
|
||||
description="Show formatted Markdown as you type."
|
||||
resetAction={
|
||||
settings.composerRichTextEnabled !==
|
||||
DEFAULT_UNIFIED_SETTINGS.composerRichTextEnabled ? (
|
||||
<SettingResetButton
|
||||
label="rich text composer"
|
||||
onClick={() =>
|
||||
updateSettings({
|
||||
composerRichTextEnabled: DEFAULT_UNIFIED_SETTINGS.composerRichTextEnabled,
|
||||
})
|
||||
}
|
||||
/>
|
||||
) : null
|
||||
}
|
||||
control={
|
||||
<Switch
|
||||
checked={settings.composerRichTextEnabled}
|
||||
onCheckedChange={(checked) =>
|
||||
updateSettings({ composerRichTextEnabled: Boolean(checked) })
|
||||
}
|
||||
aria-label="Rich text composer"
|
||||
/>
|
||||
}
|
||||
/>
|
||||
|
||||
<SettingsRow
|
||||
{...searchableSetting("composer-collapse")}
|
||||
description="Rest the composer of an existing thread into a single line when you scroll the conversation. Focus the composer or start typing to expand it again."
|
||||
|
||||
@@ -292,6 +292,12 @@ export const SETTINGS_SEARCH_ITEMS = [
|
||||
to: "/settings/general",
|
||||
searchTerms: ["command menu dollar $ slash /"],
|
||||
},
|
||||
{
|
||||
id: "composer-rich-text",
|
||||
title: "Rich text composer",
|
||||
to: "/settings/general",
|
||||
searchTerms: ["composer rich text tiptap bold italic markdown styled wysiwyg"],
|
||||
},
|
||||
{
|
||||
id: "composer-collapse",
|
||||
title: "Collapse composer on scroll",
|
||||
|
||||
@@ -0,0 +1,62 @@
|
||||
import { describe, expect, it } from "vite-plus/test";
|
||||
|
||||
import { listContinuationForEnter, listIndentForTab } from "./composer-list-continuation";
|
||||
|
||||
function applyEdit(value: string, edit: { start: number; end: number; replacement: string }) {
|
||||
return value.slice(0, edit.start) + edit.replacement + value.slice(edit.end);
|
||||
}
|
||||
|
||||
describe("composer list continuation", () => {
|
||||
it("continues ordered lists with the next number", () => {
|
||||
const value = "1. foo";
|
||||
const edit = listContinuationForEnter(value, value.length);
|
||||
expect(edit).not.toBeNull();
|
||||
expect(applyEdit(value, edit!)).toBe("1. foo\n2. ");
|
||||
});
|
||||
|
||||
it("increments multi-digit and paren markers", () => {
|
||||
expect(applyEdit("12. foo", listContinuationForEnter("12. foo", 7)!)).toBe("12. foo\n13. ");
|
||||
expect(applyEdit("3) foo", listContinuationForEnter("3) foo", 6)!)).toBe("3) foo\n4) ");
|
||||
});
|
||||
|
||||
it("continues bullets and keeps indentation", () => {
|
||||
expect(applyEdit("- foo", listContinuationForEnter("- foo", 5)!)).toBe("- foo\n- ");
|
||||
expect(applyEdit(" * foo", listContinuationForEnter(" * foo", 7)!)).toBe(" * foo\n * ");
|
||||
});
|
||||
|
||||
it("continues tasks unchecked", () => {
|
||||
expect(applyEdit("- [x] done", listContinuationForEnter("- [x] done", 10)!)).toBe(
|
||||
"- [x] done\n- [ ] ",
|
||||
);
|
||||
});
|
||||
|
||||
it("splits mid-line items", () => {
|
||||
expect(applyEdit("1. foobar", listContinuationForEnter("1. foobar", 5)!)).toBe(
|
||||
"1. fo\n2. obar",
|
||||
);
|
||||
});
|
||||
|
||||
it("exits the list on an empty item", () => {
|
||||
expect(applyEdit("1. foo\n2. ", listContinuationForEnter("1. foo\n2. ", 10)!)).toBe("1. foo\n");
|
||||
expect(applyEdit("- ", listContinuationForEnter("- ", 2)!)).toBe("");
|
||||
});
|
||||
|
||||
it("ignores non-list lines and carets inside the marker", () => {
|
||||
expect(listContinuationForEnter("plain text", 5)).toBeNull();
|
||||
expect(listContinuationForEnter("1.foo no space", 3)).toBeNull();
|
||||
expect(listContinuationForEnter("-foo", 2)).toBeNull();
|
||||
expect(listContinuationForEnter("1. foo", 1)).toBeNull();
|
||||
});
|
||||
|
||||
it("refuses to split an inline chip", () => {
|
||||
const value = "1. @README.md go";
|
||||
const cursor = value.indexOf("README") + 2;
|
||||
expect(listContinuationForEnter(value, cursor)).toBeNull();
|
||||
});
|
||||
|
||||
it("indents list items on Tab", () => {
|
||||
expect(applyEdit("- foo", listIndentForTab("- foo", 2, 2)!)).toBe(" - foo");
|
||||
expect(listIndentForTab("plain", 2, 2)).toBeNull();
|
||||
expect(listIndentForTab("- foo", 1, 3)).toBeNull();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,137 @@
|
||||
import { splitPromptIntoComposerSegments } from "./composer-editor-mentions";
|
||||
|
||||
/**
|
||||
* List continuation and indentation for the composer.
|
||||
*
|
||||
* Implemented once at the ChatComposer level (store replacement), so both
|
||||
* composer modes behave identically and serialize identically:
|
||||
* Shift+Enter on a list item continues it, Enter on an empty item exits the
|
||||
* list, and Tab indents the item. Plain Markdown markers only — no real list
|
||||
* nodes anywhere.
|
||||
*/
|
||||
|
||||
export interface ComposerListEdit {
|
||||
/** Expanded (plain string) offsets into the prompt. */
|
||||
start: number;
|
||||
end: number;
|
||||
replacement: string;
|
||||
}
|
||||
|
||||
type ListMarker =
|
||||
| { kind: "ordered"; indent: string; numberText: string; delimiter: "." | ")"; space: string }
|
||||
| { kind: "task"; indent: string; space: string }
|
||||
| { kind: "bullet"; indent: string; bullet: string; space: string };
|
||||
|
||||
function parseListMarker(line: string): { marker: ListMarker; markerEnd: number } | null {
|
||||
const indent = line.match(/^[ \t]*/)?.[0] ?? "";
|
||||
const rest = line.slice(indent.length);
|
||||
const ordered = rest.match(/^(\d+)([.)])((?:[ \t]+)|\s*$)/);
|
||||
if (ordered && ordered[1] !== undefined && ordered[2] !== undefined) {
|
||||
return {
|
||||
marker: {
|
||||
kind: "ordered",
|
||||
indent,
|
||||
numberText: ordered[1],
|
||||
delimiter: ordered[2] === ")" ? ")" : ".",
|
||||
space: ordered[3] ?? "",
|
||||
},
|
||||
markerEnd: indent.length + ordered[0].length,
|
||||
};
|
||||
}
|
||||
const task = rest.match(/^-\s\[[ xX]\]((?:[ \t]+)|\s*$)/);
|
||||
if (task) {
|
||||
return {
|
||||
marker: { kind: "task", indent, space: task[1] ?? "" },
|
||||
markerEnd: indent.length + task[0].length,
|
||||
};
|
||||
}
|
||||
const bullet = rest.match(/^([-*+])((?:[ \t]+)|\s*$)/);
|
||||
if (bullet && bullet[1] !== undefined) {
|
||||
return {
|
||||
marker: { kind: "bullet", indent, bullet: bullet[1], space: bullet[2] ?? "" },
|
||||
markerEnd: indent.length + bullet[0].length,
|
||||
};
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
function nextMarkerText(marker: ListMarker): string {
|
||||
if (marker.kind === "ordered") {
|
||||
const number = Number.parseInt(marker.numberText, 10);
|
||||
const next = Number.isSafeInteger(number)
|
||||
? String(number + 1).padStart(marker.numberText.length, "0")
|
||||
: marker.numberText;
|
||||
return `${marker.indent}${next}${marker.delimiter} `;
|
||||
}
|
||||
if (marker.kind === "task") {
|
||||
return `${marker.indent}- [ ] `;
|
||||
}
|
||||
return `${marker.indent}${marker.bullet} `;
|
||||
}
|
||||
|
||||
function segmentSource(
|
||||
segment: ReturnType<typeof splitPromptIntoComposerSegments>[number],
|
||||
): string {
|
||||
if (segment.type === "text") return segment.text;
|
||||
if (segment.type === "skill") return `$${segment.name}`;
|
||||
return segment.source;
|
||||
}
|
||||
|
||||
/** True when splitting at the caret would cut an inline chip in two. */
|
||||
function isInsideInlineToken(value: string, cursor: number): boolean {
|
||||
let offset = 0;
|
||||
for (const segment of splitPromptIntoComposerSegments(value)) {
|
||||
const end = offset + segmentSource(segment).length;
|
||||
if (segment.type !== "text" && cursor > offset && cursor < end) return true;
|
||||
offset = end;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
function currentLine(value: string, cursor: number): { start: number; end: number; text: string } {
|
||||
const start = value.lastIndexOf("\n", cursor - 1) + 1;
|
||||
const endIndex = value.indexOf("\n", cursor);
|
||||
const end = endIndex === -1 ? value.length : endIndex;
|
||||
return { start, end, text: value.slice(start, end) };
|
||||
}
|
||||
|
||||
/**
|
||||
* Enter on a list item line: continue the list, or exit it when the item is
|
||||
* empty. Returns null for non-list lines, carets inside the marker, and
|
||||
* carets inside an inline chip — all fall through to a plain newline.
|
||||
*/
|
||||
export function listContinuationForEnter(value: string, cursor: number): ComposerListEdit | null {
|
||||
if (!Number.isInteger(cursor) || cursor < 0 || cursor > value.length) return null;
|
||||
const line = currentLine(value, cursor);
|
||||
const parsed = parseListMarker(line.text);
|
||||
if (!parsed) return null;
|
||||
const markerEnd = line.start + parsed.markerEnd;
|
||||
if (cursor < markerEnd) return null;
|
||||
if (isInsideInlineToken(value, cursor)) return null;
|
||||
if (value.slice(markerEnd, line.end).trim() === "") {
|
||||
// Empty item: Enter exits the list by removing the marker.
|
||||
return { start: line.start, end: Math.max(cursor, markerEnd), replacement: "" };
|
||||
}
|
||||
return {
|
||||
start: cursor,
|
||||
end: cursor,
|
||||
replacement: `\n${nextMarkerText(parsed.marker)}`,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Tab on a list item line: indent by two spaces. Ranged selections, non-list
|
||||
* lines, and carets inside an inline chip fall through (Shift+Tab stays the
|
||||
* plan-mode toggle and is handled before this is consulted).
|
||||
*/
|
||||
export function listIndentForTab(
|
||||
value: string,
|
||||
start: number,
|
||||
end: number,
|
||||
): ComposerListEdit | null {
|
||||
if (!Number.isInteger(start) || start !== end || start < 0 || start > value.length) return null;
|
||||
const line = currentLine(value, start);
|
||||
if (!parseListMarker(line.text)) return null;
|
||||
if (isInsideInlineToken(value, start)) return null;
|
||||
return { start: line.start, end: line.start, replacement: " " };
|
||||
}
|
||||
@@ -0,0 +1,344 @@
|
||||
import { getSchemaByResolvedExtensions, Node, resolveExtensions } from "@tiptap/core";
|
||||
import StarterKit from "@tiptap/starter-kit";
|
||||
import { TaskList } from "@tiptap/extension-task-list";
|
||||
import { Node as ProseMirrorNode } from "@tiptap/pm/model";
|
||||
import { describe, expect, it } from "vite-plus/test";
|
||||
|
||||
import {
|
||||
buildDocJson,
|
||||
collapsedToFlat,
|
||||
ComposerTaskItemExtension,
|
||||
flatToCollapsed,
|
||||
flatToMarkdown,
|
||||
flatToPm,
|
||||
pmToFlat,
|
||||
serializeEditorDoc,
|
||||
} from "./composer-rich-text-doc";
|
||||
|
||||
function stubAtom(name: string, attrs: Record<string, { default: unknown }>) {
|
||||
return Node.create({
|
||||
name,
|
||||
group: "inline",
|
||||
inline: true,
|
||||
atom: true,
|
||||
addAttributes: () => attrs,
|
||||
});
|
||||
}
|
||||
|
||||
const schema = getSchemaByResolvedExtensions(
|
||||
resolveExtensions([
|
||||
StarterKit.configure({
|
||||
blockquote: false,
|
||||
bulletList: false,
|
||||
codeBlock: false,
|
||||
heading: false,
|
||||
horizontalRule: false,
|
||||
listItem: false,
|
||||
orderedList: false,
|
||||
dropcursor: false,
|
||||
gapcursor: false,
|
||||
trailingNode: false,
|
||||
}),
|
||||
stubAtom("composer-mention", { path: { default: "" }, source: { default: "" } }),
|
||||
stubAtom("composer-skill", {
|
||||
skillName: { default: "" },
|
||||
skillLabel: { default: "" },
|
||||
skillDescription: { default: null },
|
||||
}),
|
||||
stubAtom("composer-citation", {
|
||||
citation: { default: null },
|
||||
source: { default: "" },
|
||||
citeKey: { default: "" },
|
||||
}),
|
||||
stubAtom("composer-context-reference", {
|
||||
kind: { default: "" },
|
||||
contextId: { default: "" },
|
||||
label: { default: "" },
|
||||
source: { default: "" },
|
||||
}),
|
||||
TaskList,
|
||||
ComposerTaskItemExtension,
|
||||
]),
|
||||
);
|
||||
|
||||
function roundTrip(value: string) {
|
||||
const json = buildDocJson(value, (name) => ({ label: name, description: null }));
|
||||
const doc = ProseMirrorNode.fromJSON(schema, json);
|
||||
return serializeEditorDoc(doc);
|
||||
}
|
||||
|
||||
// Plain mode: the same engine with the mark extensions off. Markers stay
|
||||
// literal characters and task lines stay paragraphs.
|
||||
const plainSchema = getSchemaByResolvedExtensions(
|
||||
resolveExtensions([
|
||||
StarterKit.configure({
|
||||
blockquote: false,
|
||||
bulletList: false,
|
||||
codeBlock: false,
|
||||
heading: false,
|
||||
horizontalRule: false,
|
||||
listItem: false,
|
||||
orderedList: false,
|
||||
dropcursor: false,
|
||||
gapcursor: false,
|
||||
trailingNode: false,
|
||||
bold: false,
|
||||
italic: false,
|
||||
strike: false,
|
||||
code: false,
|
||||
}),
|
||||
stubAtom("composer-mention", { path: { default: "" }, source: { default: "" } }),
|
||||
stubAtom("composer-skill", {
|
||||
skillName: { default: "" },
|
||||
skillLabel: { default: "" },
|
||||
skillDescription: { default: null },
|
||||
}),
|
||||
stubAtom("composer-citation", {
|
||||
citation: { default: null },
|
||||
source: { default: "" },
|
||||
citeKey: { default: "" },
|
||||
}),
|
||||
stubAtom("composer-context-reference", {
|
||||
kind: { default: "" },
|
||||
contextId: { default: "" },
|
||||
label: { default: "" },
|
||||
source: { default: "" },
|
||||
}),
|
||||
TaskList,
|
||||
ComposerTaskItemExtension,
|
||||
]),
|
||||
);
|
||||
|
||||
function roundTripPlain(value: string) {
|
||||
const json = buildDocJson(value, (name) => ({ label: name, description: null }), {
|
||||
styling: false,
|
||||
});
|
||||
const doc = ProseMirrorNode.fromJSON(plainSchema, json);
|
||||
return serializeEditorDoc(doc);
|
||||
}
|
||||
|
||||
describe("composer rich text document model", () => {
|
||||
it.each([
|
||||
"",
|
||||
"\n\n",
|
||||
"plain text",
|
||||
"hello **bold** world",
|
||||
"a *italic* word and `code` here",
|
||||
"struck ~~out~~ now",
|
||||
"***bold italic*** keeps nesting",
|
||||
"line one\nline two",
|
||||
"trailing newline\n",
|
||||
"1. foo\n2. asdf\n",
|
||||
"- [ ] buy milk",
|
||||
"- [ ] buy milk",
|
||||
"\t-\t[x]\t\titem",
|
||||
"- [ ] ",
|
||||
"- [ ]\n - [ ] child",
|
||||
" - [ ] first\n - [ ] second\n - [ ] child",
|
||||
"**before @README.md after**",
|
||||
"*a **b** c*",
|
||||
"*a**b***",
|
||||
"**a*b***",
|
||||
"**a *b* c**",
|
||||
"literal \uFFFC **before @README.md after**",
|
||||
"- [x] done\n- [ ] next",
|
||||
"- [ ] parent\n - [ ] child\n - [ ] sibling\n- [ ] uncle",
|
||||
"- [ ] empty task follows\n- [ ]",
|
||||
"- [ ] **bold** task with @README.md",
|
||||
"para\n- [ ] task\npara",
|
||||
"- [ ]No space stays literal",
|
||||
"-[ ] also literal",
|
||||
"@README.md explain this",
|
||||
'@"docs/My File.md" and $my-skill please',
|
||||
"snake_case stays literal",
|
||||
"unmatched ** stays literal",
|
||||
"**bold** then @README.md then *italic*",
|
||||
])("round-trips %s through a real ProseMirror document", (value) => {
|
||||
expect(roundTrip(value).value).toBe(value);
|
||||
});
|
||||
|
||||
it.each([
|
||||
"",
|
||||
"\n",
|
||||
"text\n\n",
|
||||
"- [ ]\n- [ ] next\n",
|
||||
"- [ ] parent\n - [ ] child\n- [ ]",
|
||||
"para\n- [ ] task\npara",
|
||||
"**before @README.md after**",
|
||||
])("maps editable positions in %s", (value) => {
|
||||
const doc = ProseMirrorNode.fromJSON(
|
||||
schema,
|
||||
buildDocJson(value, (name) => ({ label: name, description: null })),
|
||||
);
|
||||
const map = serializeEditorDoc(doc);
|
||||
for (let flat = 0; flat <= map.docLength; flat += 1) {
|
||||
const position = flatToPm(map, flat);
|
||||
expect(doc.resolve(position).parent.isTextblock).toBe(true);
|
||||
expect(pmToFlat(map, position)).toBe(flat);
|
||||
expect(collapsedToFlat(map, flatToCollapsed(map, flat))).toBe(flat);
|
||||
}
|
||||
});
|
||||
|
||||
it("keeps the caret after a trailing hard break inside the same paragraph", () => {
|
||||
const doc = schema.node("doc", null, [
|
||||
schema.node("paragraph", null, [schema.text("a"), schema.node("hardBreak")]),
|
||||
]);
|
||||
const map = serializeEditorDoc(doc);
|
||||
expect(flatToPm(map, map.docLength)).toBe(3);
|
||||
expect(doc.resolve(flatToPm(map, map.docLength)).parent.isTextblock).toBe(true);
|
||||
});
|
||||
|
||||
it("renders a leading task dedent as siblings and nests under the new indent", () => {
|
||||
const doc = ProseMirrorNode.fromJSON(
|
||||
schema,
|
||||
buildDocJson(" - [ ] first\n - [ ] second\n - [ ] child", (name) => ({
|
||||
label: name,
|
||||
description: null,
|
||||
})),
|
||||
);
|
||||
const list = doc.firstChild!;
|
||||
expect(list.childCount).toBe(2);
|
||||
expect(list.child(0).childCount).toBe(1);
|
||||
expect(list.child(1).child(1).firstChild!.textContent).toBe("child");
|
||||
});
|
||||
|
||||
it("applies a shared mark to text on both sides of a chip", () => {
|
||||
const doc = ProseMirrorNode.fromJSON(
|
||||
schema,
|
||||
buildDocJson("**before @README.md after**", (name) => ({ label: name, description: null })),
|
||||
);
|
||||
expect(doc.firstChild!.childCount).toBe(3);
|
||||
doc.firstChild!.forEach((child) =>
|
||||
expect(child.marks.map((mark) => mark.type.name)).toContain("bold"),
|
||||
);
|
||||
expect(serializeEditorDoc(doc).value).toBe("**before @README.md after**");
|
||||
});
|
||||
|
||||
it.each([
|
||||
[["bold"], ["bold", "italic"], ["italic"]],
|
||||
[["italic"], ["bold", "italic"], ["bold"]],
|
||||
[["bold"], ["bold", "strike"], ["strike"]],
|
||||
[["strike"], ["bold", "strike"], ["bold"]],
|
||||
])("preserves crossing mark ranges %j through controlled rebuilds", (...marks) => {
|
||||
const doc = schema.node("doc", null, [
|
||||
schema.node(
|
||||
"paragraph",
|
||||
null,
|
||||
marks.map((names, index) =>
|
||||
schema.text(
|
||||
String.fromCharCode(97 + index),
|
||||
names.map((name) => schema.mark(name)),
|
||||
),
|
||||
),
|
||||
),
|
||||
]);
|
||||
const serialized = serializeEditorDoc(doc).value;
|
||||
const rebuilt = ProseMirrorNode.fromJSON(
|
||||
schema,
|
||||
buildDocJson(serialized, (name) => ({ label: name, description: null })),
|
||||
);
|
||||
expect(rebuilt.eq(doc)).toBe(true);
|
||||
expect(serializeEditorDoc(rebuilt).value).toBe(serialized);
|
||||
});
|
||||
|
||||
it.each([
|
||||
{ parts: [{ text: "hello ", marks: ["bold"] }], expected: "**hello** " },
|
||||
{ parts: [{ text: " ", marks: ["bold"] }], expected: " " },
|
||||
{ parts: [{ text: " left ", marks: ["bold", "italic"] }], expected: " ***left*** " },
|
||||
{
|
||||
parts: [
|
||||
{ text: "one ", marks: ["bold"] },
|
||||
{ text: " two ", marks: ["bold", "italic"] },
|
||||
{ text: " three", marks: ["bold"] },
|
||||
],
|
||||
expected: "**one *two* three**",
|
||||
},
|
||||
{
|
||||
parts: [
|
||||
{ text: "hello ", marks: ["bold"] },
|
||||
{ text: "world ", marks: ["bold", "italic"] },
|
||||
],
|
||||
expected: "**hello *world*** ",
|
||||
},
|
||||
{ parts: [{ text: " hello ", marks: ["code"] }], expected: "` hello `" },
|
||||
{ parts: [{ text: " hello ", marks: ["bold", "code"] }], expected: "**` hello `**" },
|
||||
{ parts: [{ text: " ", marks: ["bold", "code"] }], expected: "**` `**" },
|
||||
])("keeps boundary whitespace outside emphasis in $expected", ({ parts, expected }) => {
|
||||
const doc = schema.node("doc", null, [
|
||||
schema.node(
|
||||
"paragraph",
|
||||
null,
|
||||
parts.map(({ text, marks }) =>
|
||||
schema.text(
|
||||
text,
|
||||
marks.map((name) => schema.mark(name)),
|
||||
),
|
||||
),
|
||||
),
|
||||
]);
|
||||
const map = serializeEditorDoc(doc);
|
||||
expect(map.value).toBe(expected);
|
||||
const rebuilt = ProseMirrorNode.fromJSON(
|
||||
schema,
|
||||
buildDocJson(map.value, (name) => ({ label: name, description: null })),
|
||||
);
|
||||
expect(rebuilt.textContent).toBe(doc.textContent);
|
||||
expect(serializeEditorDoc(rebuilt).value).toBe(map.value);
|
||||
for (let flat = 0; flat <= map.docLength; flat += 1) {
|
||||
expect(pmToFlat(map, flatToPm(map, flat))).toBe(flat);
|
||||
expect(collapsedToFlat(map, flatToCollapsed(map, flat))).toBe(flat);
|
||||
if (flat < map.docLength && !/\s/.test(doc.textContent[flat]!)) {
|
||||
expect(rebuilt.resolve(flat + 1).nodeAfter!.marks.map((mark) => mark.type.name)).toEqual(
|
||||
doc.resolve(flat + 1).nodeAfter!.marks.map((mark) => mark.type.name),
|
||||
);
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
it("keeps chip sources canonical through the document", () => {
|
||||
const map = roundTrip("explain @README.md with **care**\nsecond line *here*");
|
||||
expect(map.value).toBe("explain @README.md with **care**\nsecond line *here*");
|
||||
expect(
|
||||
map.runs.some((run) => run.kind === "token" && run.nodeName === "composer-mention"),
|
||||
).toBe(true);
|
||||
});
|
||||
|
||||
it("normalizes uppercase checkboxes to lowercase", () => {
|
||||
expect(roundTrip("- [X] done").value).toBe("- [x] done");
|
||||
});
|
||||
|
||||
it.each([
|
||||
"plain text",
|
||||
"hello **bold** stays literal",
|
||||
"a *italic* stays literal",
|
||||
"some `code` stays literal",
|
||||
"struck ~~out~~ stays literal",
|
||||
"- [ ] stays a paragraph",
|
||||
"- [x] stays a paragraph",
|
||||
"line one\nline two",
|
||||
"@README.md explain this",
|
||||
"**bold** then @README.md then *italic*",
|
||||
])("round-trips %s byte-identically in plain mode", (value) => {
|
||||
expect(roundTripPlain(value).value).toBe(value);
|
||||
});
|
||||
|
||||
it("maps every document offset through collapsed coordinates and back", () => {
|
||||
const value = "hi **bold** @README.md bye";
|
||||
const map = roundTrip(value);
|
||||
expect(map.value).toBe(value);
|
||||
for (let flat = 0; flat <= map.docLength; flat += 1) {
|
||||
expect(collapsedToFlat(map, flatToCollapsed(map, flat))).toBe(flat);
|
||||
}
|
||||
});
|
||||
|
||||
it("maps markdown offsets at styled edges onto document text", () => {
|
||||
const value = "a **bold** c";
|
||||
const map = roundTrip(value);
|
||||
expect(map.value).toBe(value);
|
||||
// document text is "a bold c" (flat), markdown has the markers.
|
||||
expect(flatToMarkdown(map, 2)).toBe(4);
|
||||
expect(flatToMarkdown(map, 6)).toBe(10);
|
||||
expect(collapsedToFlat(map, 3)).toBe(2);
|
||||
expect(collapsedToFlat(map, 9)).toBe(6);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,644 @@
|
||||
import type { Node as ProseMirrorNode } from "@tiptap/pm/model";
|
||||
import { TaskItem } from "@tiptap/extension-task-item";
|
||||
|
||||
import { splitPromptIntoComposerSegments } from "~/composer-editor-mentions";
|
||||
import { parseInlineMarkdown, RICH_TEXT_DELIMITERS, type RichTextMark } from "~/composer-rich-text";
|
||||
import { collectInlineContextIds } from "~/lib/composerContextReferences";
|
||||
|
||||
/**
|
||||
* Pure document model for the rich text (Tiptap) composer.
|
||||
*
|
||||
* The stored prompt stays markdown (`**bold**`, `@file` chips as canonical
|
||||
* links). The Tiptap document holds styled text plus inline atom chips, so
|
||||
* this module translates both ways and maps cursor offsets between the three
|
||||
* coordinate spaces the composer speaks:
|
||||
*
|
||||
* - flat document offsets (styled markers excluded, chips count 1),
|
||||
* - collapsed cursor offsets (markers literal, chips count 1 — the coordinate
|
||||
* the draft store and mention detection use),
|
||||
* - markdown offsets (markers literal, chips expand to their source).
|
||||
*
|
||||
* DOM-free on purpose: unit tests build a real ProseMirror document from the
|
||||
* JSON this produces and assert the round trip without a browser.
|
||||
*/
|
||||
|
||||
export type SkillMeta = { label: string; description: string | null };
|
||||
|
||||
/** Outermost mark first, so closers mirror openers when nested. */
|
||||
const MARK_NESTING_ORDER: RichTextMark[] = ["strike", "bold", "italic", "code"];
|
||||
|
||||
const MARK_TO_TIPTAP: Record<RichTextMark, string> = {
|
||||
bold: "bold",
|
||||
italic: "italic",
|
||||
strike: "strike",
|
||||
code: "code",
|
||||
};
|
||||
|
||||
const TIPTAP_TO_MARK: Record<string, RichTextMark> = {
|
||||
bold: "bold",
|
||||
italic: "italic",
|
||||
strike: "strike",
|
||||
code: "code",
|
||||
};
|
||||
|
||||
/**
|
||||
* Task list items keep their exact source indent in an attribute so nesting
|
||||
* round-trips byte-identically. Checkbox case (`[X]`) normalizes to `[x]` —
|
||||
* the same fixed-point deal as `__bold__` becoming `**bold**`.
|
||||
*/
|
||||
export const ComposerTaskItemExtension = TaskItem.extend({
|
||||
addAttributes() {
|
||||
return {
|
||||
...this.parent?.(),
|
||||
indent: { default: "" },
|
||||
markerSpace: { default: " " },
|
||||
contentSpace: { default: null },
|
||||
};
|
||||
},
|
||||
}).configure({ nested: true });
|
||||
|
||||
function randomNodeKey(): string {
|
||||
return `tiptap-${Math.random().toString(36).slice(2)}`;
|
||||
}
|
||||
|
||||
interface TaskLinePrefix {
|
||||
indent: string;
|
||||
checked: boolean;
|
||||
markerSpace: string;
|
||||
contentSpace: string;
|
||||
}
|
||||
|
||||
function parseTaskPrefix(head: string): { prefix: TaskLinePrefix; markerLength: number } | null {
|
||||
const match = head.match(/^([ \t]*)-([ \t]+)\[([ xX])\]([ \t]*)/);
|
||||
if (!match) return null;
|
||||
const after = head.slice(match[0].length);
|
||||
if (after.length > 0 && !match[4]) return null;
|
||||
return {
|
||||
prefix: {
|
||||
indent: match[1] ?? "",
|
||||
checked: (match[3] ?? " ").toLowerCase() === "x",
|
||||
markerSpace: match[2]!,
|
||||
contentSpace: match[4]!,
|
||||
},
|
||||
markerLength: match[0].length,
|
||||
};
|
||||
}
|
||||
|
||||
type InlineJson = Record<string, unknown>;
|
||||
|
||||
interface DocLine {
|
||||
task: TaskLinePrefix | null;
|
||||
inline: InlineJson[];
|
||||
}
|
||||
|
||||
function atomJsonForSegment(
|
||||
segment: Exclude<ReturnType<typeof splitPromptIntoComposerSegments>[number], { type: "text" }>,
|
||||
skillLabelFor: (name: string) => SkillMeta,
|
||||
): InlineJson {
|
||||
if (segment.type === "mention") {
|
||||
return {
|
||||
type: "composer-mention",
|
||||
attrs: { path: segment.path, source: segment.source },
|
||||
};
|
||||
}
|
||||
if (segment.type === "skill") {
|
||||
const meta = skillLabelFor(segment.name);
|
||||
return {
|
||||
type: "composer-skill",
|
||||
attrs: {
|
||||
skillName: segment.name,
|
||||
skillLabel: meta.label,
|
||||
skillDescription: meta.description,
|
||||
},
|
||||
};
|
||||
}
|
||||
if (segment.type === "citation") {
|
||||
return {
|
||||
type: "composer-citation",
|
||||
attrs: { citation: segment.citation, source: segment.source, citeKey: randomNodeKey() },
|
||||
};
|
||||
}
|
||||
return {
|
||||
type: "composer-context-reference",
|
||||
attrs: {
|
||||
kind: segment.kind,
|
||||
contextId: segment.contextId,
|
||||
label: segment.label,
|
||||
source: segment.source,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
interface PendingTaskItem extends TaskLinePrefix {
|
||||
content: InlineJson[];
|
||||
children: PendingTaskItem[];
|
||||
}
|
||||
|
||||
function taskListJson(items: PendingTaskItem[]): InlineJson {
|
||||
return {
|
||||
type: "taskList",
|
||||
content: items.map((item) => ({
|
||||
type: "taskItem",
|
||||
attrs: {
|
||||
checked: item.checked,
|
||||
indent: item.indent,
|
||||
markerSpace: item.markerSpace,
|
||||
contentSpace: item.contentSpace,
|
||||
},
|
||||
content: [
|
||||
{ type: "paragraph", content: item.content },
|
||||
...(item.children.length > 0 ? [taskListJson(item.children)] : []),
|
||||
],
|
||||
})),
|
||||
};
|
||||
}
|
||||
|
||||
function textJsonForSpan(text: string, marks: RichTextMark[]): Record<string, unknown> {
|
||||
const json: Record<string, unknown> = { type: "text", text };
|
||||
if (marks.length > 0) {
|
||||
json.marks = [...marks]
|
||||
.sort((a, b) => MARK_NESTING_ORDER.indexOf(a) - MARK_NESTING_ORDER.indexOf(b))
|
||||
.map((mark) => ({ type: MARK_TO_TIPTAP[mark] }));
|
||||
}
|
||||
return json;
|
||||
}
|
||||
|
||||
export function buildTiptapContent(
|
||||
value: string,
|
||||
skillLabelFor: (name: string) => SkillMeta,
|
||||
options?: { styling?: boolean },
|
||||
): Record<string, unknown>[] {
|
||||
const styling = options?.styling ?? true;
|
||||
// Hide token source from the markdown parser, then restore the atoms with
|
||||
// the marks of their surrounding text. Choose a sentinel absent from input.
|
||||
let sentinel = "\uFFFC";
|
||||
for (let codePoint = 0xe000; value.includes(sentinel); codePoint += 1) {
|
||||
sentinel = String.fromCodePoint(codePoint);
|
||||
}
|
||||
const atoms: InlineJson[] = [];
|
||||
const text = splitPromptIntoComposerSegments(value)
|
||||
.map((segment) => {
|
||||
if (segment.type === "text") return segment.text;
|
||||
atoms.push(atomJsonForSegment(segment, skillLabelFor));
|
||||
return sentinel;
|
||||
})
|
||||
.join("");
|
||||
let atomIndex = 0;
|
||||
const lines: DocLine[] = text.split("\n").map((line) => {
|
||||
const parsed = styling ? parseTaskPrefix(line) : null;
|
||||
const content = parsed ? line.slice(parsed.markerLength) : line;
|
||||
const spans = styling ? parseInlineMarkdown(content) : [{ text: content, marks: [] }];
|
||||
const inline: InlineJson[] = [];
|
||||
for (const span of spans) {
|
||||
span.text.split(sentinel).forEach((piece, index) => {
|
||||
if (index > 0) {
|
||||
const atom = atoms[atomIndex++]!;
|
||||
inline.push({ ...atom, marks: textJsonForSpan("", span.marks).marks });
|
||||
}
|
||||
if (piece) inline.push(textJsonForSpan(piece, span.marks));
|
||||
});
|
||||
}
|
||||
return { task: parsed?.prefix ?? null, inline };
|
||||
});
|
||||
|
||||
// Pass 2: consecutive task lines group into (possibly nested) task lists
|
||||
// by indent prefix; everything else stays a paragraph.
|
||||
const blocks: Record<string, unknown>[] = [];
|
||||
let stack: { indent: string; items: PendingTaskItem[] }[] = [];
|
||||
const flushTasks = () => {
|
||||
if (stack.length > 0) {
|
||||
blocks.push(taskListJson(stack[0]!.items));
|
||||
stack = [];
|
||||
}
|
||||
};
|
||||
for (const line of lines) {
|
||||
if (!line.task) {
|
||||
flushTasks();
|
||||
blocks.push({ type: "paragraph", content: line.inline });
|
||||
continue;
|
||||
}
|
||||
const item: PendingTaskItem = {
|
||||
...line.task,
|
||||
content: line.inline,
|
||||
children: [],
|
||||
};
|
||||
for (;;) {
|
||||
const top = stack[stack.length - 1];
|
||||
if (!top) {
|
||||
// A leading indented item with no parent flattens but keeps indent.
|
||||
stack.push({ indent: item.indent, items: [] });
|
||||
continue;
|
||||
}
|
||||
if (top.indent === item.indent) {
|
||||
top.items.push(item);
|
||||
break;
|
||||
}
|
||||
if (top.indent !== "" && !item.indent.startsWith(top.indent)) {
|
||||
if (stack.length > 1) {
|
||||
stack.pop();
|
||||
continue;
|
||||
}
|
||||
top.indent = item.indent;
|
||||
top.items.push(item);
|
||||
break;
|
||||
}
|
||||
const parent = top.items[top.items.length - 1];
|
||||
if (!parent) {
|
||||
top.items.push(item);
|
||||
break;
|
||||
}
|
||||
parent.children.push(item);
|
||||
stack.push({ indent: item.indent, items: parent.children });
|
||||
break;
|
||||
}
|
||||
}
|
||||
flushTasks();
|
||||
return blocks;
|
||||
}
|
||||
|
||||
export function buildDocJson(
|
||||
value: string,
|
||||
skillLabelFor: (name: string) => SkillMeta,
|
||||
options?: { styling?: boolean },
|
||||
) {
|
||||
return { type: "doc", content: buildTiptapContent(value, skillLabelFor, options) };
|
||||
}
|
||||
|
||||
export interface RichRun {
|
||||
kind: "text" | "token" | "break" | "prefix";
|
||||
/** Flat document offset (atoms count 1, markers excluded). */
|
||||
flatStart: number;
|
||||
docLen: number;
|
||||
/** Collapsed cursor length (markers literal, tokens count 1). */
|
||||
collapsedLen: number;
|
||||
/** Markdown length (tokens expand to their source). */
|
||||
mdLen: number;
|
||||
/** Marker layout inside text runs. */
|
||||
openLen: number;
|
||||
closeLen: number;
|
||||
/** ProseMirror position of the run start. */
|
||||
pmPos: number;
|
||||
mdStart: number;
|
||||
collapsedStart: number;
|
||||
nodeName?: string;
|
||||
}
|
||||
|
||||
export interface RichDocMap {
|
||||
value: string;
|
||||
runs: RichRun[];
|
||||
docLength: number;
|
||||
contextIds: string[];
|
||||
}
|
||||
|
||||
function readAtomSource(node: ProseMirrorNode): string {
|
||||
const attrs = node.attrs as Record<string, unknown>;
|
||||
switch (node.type.name) {
|
||||
case "composer-mention":
|
||||
case "composer-citation":
|
||||
case "composer-context-reference":
|
||||
return typeof attrs.source === "string" ? attrs.source : "";
|
||||
case "composer-skill": {
|
||||
const name = typeof attrs.skillName === "string" ? attrs.skillName : "";
|
||||
return name ? `$${name}` : "";
|
||||
}
|
||||
default:
|
||||
return "";
|
||||
}
|
||||
}
|
||||
|
||||
interface RichAccumulator {
|
||||
runs: RichRun[];
|
||||
value: string;
|
||||
flat: number;
|
||||
collapsed: number;
|
||||
md: number;
|
||||
}
|
||||
|
||||
function pushBreakRun(acc: RichAccumulator, position?: number): void {
|
||||
const previous = acc.runs[acc.runs.length - 1];
|
||||
const pmPos = position ?? (previous ? previous.pmPos + previous.docLen : 1);
|
||||
// Block boundary: one newline in every coordinate space.
|
||||
acc.runs.push({
|
||||
kind: "break",
|
||||
flatStart: acc.flat,
|
||||
docLen: 1,
|
||||
collapsedLen: 1,
|
||||
mdLen: 1,
|
||||
openLen: 0,
|
||||
closeLen: 0,
|
||||
pmPos,
|
||||
mdStart: acc.md,
|
||||
collapsedStart: acc.collapsed,
|
||||
});
|
||||
acc.value += "\n";
|
||||
acc.flat += 1;
|
||||
acc.collapsed += 1;
|
||||
acc.md += 1;
|
||||
}
|
||||
|
||||
function appendInlineRuns(
|
||||
container: ProseMirrorNode,
|
||||
contentStart: number,
|
||||
acc: RichAccumulator,
|
||||
): void {
|
||||
const children: ProseMirrorNode[] = [];
|
||||
container.forEach((child) => {
|
||||
if (!child.isText || child.marks.some((mark) => mark.type.name === "code")) {
|
||||
children.push(child);
|
||||
return;
|
||||
}
|
||||
// Separate boundary whitespace so delimiters can move past it without
|
||||
// changing the document offsets or marks on the visible text.
|
||||
const text = child.text!;
|
||||
const start = text.length - text.trimStart().length;
|
||||
const end = Math.max(start, text.trimEnd().length);
|
||||
let offset = 0;
|
||||
for (const boundary of [start, end, text.length]) {
|
||||
if (boundary > offset) children.push(child.cut(offset, boundary));
|
||||
offset = boundary;
|
||||
}
|
||||
});
|
||||
// Emphasis cannot open or close next to whitespace. Retain a whitespace
|
||||
// mark only when its range has visible content on both sides.
|
||||
for (const mark of MARK_NESTING_ORDER) {
|
||||
if (mark === "code") continue;
|
||||
for (const direction of [1, -1]) {
|
||||
let hasContent = false;
|
||||
for (
|
||||
let index = direction === 1 ? 0 : children.length - 1;
|
||||
index >= 0 && index < children.length;
|
||||
index += direction
|
||||
) {
|
||||
const child = children[index]!;
|
||||
if (
|
||||
child.type.name === "hardBreak" ||
|
||||
!child.marks.some((item) => item.type.name === mark)
|
||||
) {
|
||||
hasContent = false;
|
||||
} else if (
|
||||
child.isText &&
|
||||
!child.marks.some((item) => item.type.name === "code") &&
|
||||
/^\s+$/.test(child.text!)
|
||||
) {
|
||||
if (!hasContent)
|
||||
children[index] = child.mark(child.marks.filter((item) => item.type.name !== mark));
|
||||
} else {
|
||||
hasContent = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
// Longer shared marks surround shorter ones. This keeps both nested
|
||||
// formatting and formatting across chips inside a single delimiter pair.
|
||||
const markEnds = new Map<RichTextMark, number>();
|
||||
const orderedMarks: RichTextMark[][] = [];
|
||||
for (let index = children.length - 1; index >= 0; index -= 1) {
|
||||
const child = children[index]!;
|
||||
const marks =
|
||||
child.type.name === "hardBreak"
|
||||
? []
|
||||
: child.marks
|
||||
.map((mark) => TIPTAP_TO_MARK[mark.type.name])
|
||||
.filter((mark): mark is RichTextMark => Boolean(mark));
|
||||
for (const mark of MARK_NESTING_ORDER) {
|
||||
if (!marks.includes(mark)) markEnds.delete(mark);
|
||||
else if (!markEnds.has(mark)) markEnds.set(mark, index);
|
||||
}
|
||||
orderedMarks[index] = marks.sort(
|
||||
(a, b) =>
|
||||
markEnds.get(b)! - markEnds.get(a)! ||
|
||||
MARK_NESTING_ORDER.indexOf(a) - MARK_NESTING_ORDER.indexOf(b),
|
||||
);
|
||||
}
|
||||
for (let index = 1; index < orderedMarks.length; index += 1) {
|
||||
const marks = orderedMarks[index]!;
|
||||
const retained: RichTextMark[] = [];
|
||||
for (const mark of orderedMarks[index - 1]!) {
|
||||
if (!marks.includes(mark)) break;
|
||||
retained.push(mark);
|
||||
}
|
||||
orderedMarks[index] = [...retained, ...marks.filter((mark) => !retained.includes(mark))];
|
||||
}
|
||||
const commonLength = (left: RichTextMark[], right: RichTextMark[]) => {
|
||||
let index = 0;
|
||||
while (index < left.length && left[index] === right[index]) index += 1;
|
||||
return index;
|
||||
};
|
||||
let inlineOffset = 0;
|
||||
children.forEach((child, index) => {
|
||||
const pmPos = contentStart + inlineOffset;
|
||||
inlineOffset += child.nodeSize;
|
||||
if (child.type.name === "hardBreak") {
|
||||
pushBreakRun(acc, pmPos);
|
||||
return;
|
||||
}
|
||||
const marks = orderedMarks[index]!;
|
||||
const open = marks
|
||||
.slice(commonLength(marks, orderedMarks[index - 1] ?? []))
|
||||
.map((mark) => RICH_TEXT_DELIMITERS[mark])
|
||||
.join("");
|
||||
const close = marks
|
||||
.slice(commonLength(marks, orderedMarks[index + 1] ?? []))
|
||||
.toReversed()
|
||||
.map((mark) => RICH_TEXT_DELIMITERS[mark])
|
||||
.join("");
|
||||
const source = child.isText ? child.text! : readAtomSource(child);
|
||||
const docLen = child.isText ? source.length : 1;
|
||||
const mdText = open + source + close;
|
||||
const collapsedLen = open.length + docLen + close.length;
|
||||
acc.runs.push({
|
||||
kind: child.isText ? "text" : "token",
|
||||
flatStart: acc.flat,
|
||||
docLen,
|
||||
collapsedLen,
|
||||
mdLen: mdText.length,
|
||||
openLen: open.length,
|
||||
closeLen: close.length,
|
||||
pmPos,
|
||||
mdStart: acc.md,
|
||||
collapsedStart: acc.collapsed,
|
||||
...(child.isText ? {} : { nodeName: child.type.name }),
|
||||
});
|
||||
acc.value += mdText;
|
||||
acc.flat += docLen;
|
||||
acc.collapsed += collapsedLen;
|
||||
acc.md += mdText.length;
|
||||
});
|
||||
// Empty paragraphs have an editable position even though they emit no text.
|
||||
if (children.length === 0) {
|
||||
acc.runs.push({
|
||||
kind: "text",
|
||||
flatStart: acc.flat,
|
||||
docLen: 0,
|
||||
collapsedLen: 0,
|
||||
mdLen: 0,
|
||||
openLen: 0,
|
||||
closeLen: 0,
|
||||
pmPos: contentStart,
|
||||
mdStart: acc.md,
|
||||
collapsedStart: acc.collapsed,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
function walkTaskList(list: ProseMirrorNode, listStart: number, acc: RichAccumulator): void {
|
||||
let itemPos = listStart + 1;
|
||||
let firstItem = true;
|
||||
list.content.forEach((item) => {
|
||||
// Sibling items are separated by one newline in every coordinate space.
|
||||
if (!firstItem) pushBreakRun(acc);
|
||||
firstItem = false;
|
||||
const itemContentStart = itemPos + 1;
|
||||
const first = item.firstChild;
|
||||
const empty = first?.type.name === "paragraph" && first.content.childCount === 0;
|
||||
const attrs = item.attrs as Record<string, unknown>;
|
||||
const indent = typeof attrs.indent === "string" ? attrs.indent : "";
|
||||
const markerSpace = typeof attrs.markerSpace === "string" ? attrs.markerSpace : " ";
|
||||
const contentSpace =
|
||||
typeof attrs.contentSpace === "string"
|
||||
? attrs.contentSpace || (empty ? "" : " ")
|
||||
: empty
|
||||
? ""
|
||||
: " ";
|
||||
const prefix = `${indent}-${markerSpace}[${attrs.checked === true ? "x" : " "}]${contentSpace}`;
|
||||
// The checkbox owns no document characters; every prefix offset clamps
|
||||
// to the start of the item text, exactly like style markers.
|
||||
acc.runs.push({
|
||||
kind: "prefix",
|
||||
flatStart: acc.flat,
|
||||
docLen: 0,
|
||||
collapsedLen: prefix.length,
|
||||
mdLen: prefix.length,
|
||||
openLen: 0,
|
||||
closeLen: 0,
|
||||
pmPos: itemContentStart + 1,
|
||||
mdStart: acc.md,
|
||||
collapsedStart: acc.collapsed,
|
||||
});
|
||||
acc.value += prefix;
|
||||
acc.collapsed += prefix.length;
|
||||
acc.md += prefix.length;
|
||||
let childPos = itemContentStart;
|
||||
let firstBlock = true;
|
||||
item.content.forEach((child) => {
|
||||
if (!firstBlock) pushBreakRun(acc);
|
||||
firstBlock = false;
|
||||
if (child.type.name === "taskList") {
|
||||
walkTaskList(child, childPos, acc);
|
||||
} else if (child.type.name === "paragraph") {
|
||||
appendInlineRuns(child, childPos + 1, acc);
|
||||
}
|
||||
childPos += child.nodeSize;
|
||||
});
|
||||
itemPos += item.nodeSize;
|
||||
});
|
||||
}
|
||||
|
||||
export function serializeEditorDoc(doc: ProseMirrorNode): RichDocMap {
|
||||
const acc: RichAccumulator = { runs: [], value: "", flat: 0, collapsed: 0, md: 0 };
|
||||
const blocks: ProseMirrorNode[] = [];
|
||||
doc.content.forEach((node) => {
|
||||
blocks.push(node);
|
||||
});
|
||||
|
||||
let pmBlockStart = 0;
|
||||
blocks.forEach((block, blockIndex) => {
|
||||
if (blockIndex > 0) pushBreakRun(acc);
|
||||
if (block.type.name === "taskList") {
|
||||
walkTaskList(block, pmBlockStart, acc);
|
||||
} else if (block.type.name === "paragraph") {
|
||||
appendInlineRuns(block, pmBlockStart + 1, acc);
|
||||
}
|
||||
pmBlockStart += block.nodeSize;
|
||||
});
|
||||
|
||||
return {
|
||||
value: acc.value,
|
||||
runs: acc.runs,
|
||||
docLength: acc.flat,
|
||||
contextIds: Array.from(new Set(collectInlineContextIds(acc.value))),
|
||||
};
|
||||
}
|
||||
|
||||
function lastRunEnd(map: RichDocMap, space: "collapsed" | "md"): number {
|
||||
const last = map.runs[map.runs.length - 1];
|
||||
if (!last) return 0;
|
||||
return space === "collapsed"
|
||||
? last.collapsedStart + last.collapsedLen
|
||||
: last.mdStart + last.mdLen;
|
||||
}
|
||||
|
||||
export function flatToCollapsed(map: RichDocMap, flatOffset: number): number {
|
||||
const bounded = Math.max(0, Math.min(flatOffset, map.docLength));
|
||||
for (const run of map.runs) {
|
||||
if (bounded < run.flatStart + run.docLen) {
|
||||
if (run.kind === "text" || run.kind === "token") {
|
||||
return run.collapsedStart + run.openLen + (bounded - run.flatStart);
|
||||
}
|
||||
return run.collapsedStart + (bounded - run.flatStart);
|
||||
}
|
||||
}
|
||||
return lastRunEnd(map, "collapsed");
|
||||
}
|
||||
|
||||
export function flatToMarkdown(map: RichDocMap, flatOffset: number): number {
|
||||
const bounded = Math.max(0, Math.min(flatOffset, map.docLength));
|
||||
for (const run of map.runs) {
|
||||
if (bounded < run.flatStart + run.docLen) {
|
||||
if (run.kind === "text" || run.kind === "token") {
|
||||
return run.mdStart + run.openLen + (bounded - run.flatStart);
|
||||
}
|
||||
return run.mdStart + (bounded - run.flatStart);
|
||||
}
|
||||
}
|
||||
return lastRunEnd(map, "md");
|
||||
}
|
||||
|
||||
export function collapsedToFlat(map: RichDocMap, collapsedOffset: number): number {
|
||||
for (const run of map.runs) {
|
||||
if (collapsedOffset < run.collapsedStart + run.collapsedLen) {
|
||||
// Checkbox prefixes and style markers are shown, never edited: every
|
||||
// offset inside them clamps to the adjacent document position.
|
||||
if (run.kind === "prefix") return run.flatStart;
|
||||
if (run.kind === "text" || run.kind === "token") {
|
||||
const within = collapsedOffset - run.collapsedStart;
|
||||
// Marker characters clamp to the styled edge: they are shown, never edited.
|
||||
if (within <= run.openLen) return run.flatStart;
|
||||
if (within >= run.openLen + run.docLen) return run.flatStart + run.docLen;
|
||||
return run.flatStart + (within - run.openLen);
|
||||
}
|
||||
return run.flatStart + (collapsedOffset - run.collapsedStart);
|
||||
}
|
||||
}
|
||||
return map.docLength;
|
||||
}
|
||||
|
||||
export function flatToPm(map: RichDocMap, flatOffset: number): number {
|
||||
const bounded = Math.max(0, Math.min(flatOffset, map.docLength));
|
||||
for (const run of map.runs) {
|
||||
if (bounded < run.flatStart + run.docLen) {
|
||||
return run.pmPos + (bounded - run.flatStart);
|
||||
}
|
||||
}
|
||||
const last = map.runs[map.runs.length - 1];
|
||||
if (!last) return 1;
|
||||
return last.pmPos + last.docLen;
|
||||
}
|
||||
|
||||
export function pmToFlat(map: RichDocMap, pmPos: number): number {
|
||||
for (const run of map.runs) {
|
||||
if (pmPos >= run.pmPos && pmPos <= run.pmPos + run.docLen) {
|
||||
// A position on a chip's trailing edge belongs after the chip.
|
||||
if (run.kind === "token" && pmPos === run.pmPos + run.docLen) {
|
||||
return run.flatStart + run.docLen;
|
||||
}
|
||||
return run.flatStart + Math.min(pmPos - run.pmPos, run.docLen);
|
||||
}
|
||||
}
|
||||
// A paragraph boundary position belongs to the newline between paragraphs.
|
||||
let best = 0;
|
||||
for (const run of map.runs) {
|
||||
if (run.pmPos <= pmPos) best = run.flatStart + run.docLen;
|
||||
}
|
||||
return Math.max(0, Math.min(best, map.docLength));
|
||||
}
|
||||
@@ -0,0 +1,67 @@
|
||||
import { describe, expect, it } from "vite-plus/test";
|
||||
|
||||
import { parseInlineMarkdown } from "./composer-rich-text";
|
||||
|
||||
describe("composer rich text markdown", () => {
|
||||
it("parses bold markers into styled spans", () => {
|
||||
expect(parseInlineMarkdown("hello **bold** world")).toEqual([
|
||||
{ text: "hello ", marks: [] },
|
||||
{ text: "bold", marks: ["bold"] },
|
||||
{ text: " world", marks: [] },
|
||||
]);
|
||||
});
|
||||
|
||||
it("preserves unmatched markers, escaped markers, and identifiers", () => {
|
||||
for (const text of [
|
||||
"plain text",
|
||||
"snake_case",
|
||||
"unmatched **",
|
||||
"** spaced **",
|
||||
"\\*literal\\*",
|
||||
]) {
|
||||
expect(parseInlineMarkdown(text)).toEqual([{ text, marks: [] }]);
|
||||
}
|
||||
});
|
||||
|
||||
it("renders triple markers and nested styles", () => {
|
||||
expect(parseInlineMarkdown("***both***")).toEqual([
|
||||
{ text: "both", marks: ["bold", "italic"] },
|
||||
]);
|
||||
expect(parseInlineMarkdown("*a **b** c*")).toEqual([
|
||||
{ text: "a ", marks: ["italic"] },
|
||||
{ text: "b", marks: ["italic", "bold"] },
|
||||
{ text: " c", marks: ["italic"] },
|
||||
]);
|
||||
expect(parseInlineMarkdown("**a `code` c**")).toEqual([
|
||||
{ text: "a ", marks: ["bold"] },
|
||||
{ text: "code", marks: ["bold", "code"] },
|
||||
{ text: " c", marks: ["bold"] },
|
||||
]);
|
||||
});
|
||||
|
||||
it("preserves crossing italic and bold spans", () => {
|
||||
expect(parseInlineMarkdown("*a**b*****c**")).toEqual([
|
||||
{ text: "a", marks: ["italic"] },
|
||||
{ text: "b", marks: ["italic", "bold"] },
|
||||
{ text: "c", marks: ["bold"] },
|
||||
]);
|
||||
});
|
||||
|
||||
it("keeps repeated and alternate delimiters literal inside an active mark", () => {
|
||||
const repeated = "*".repeat(10_000);
|
||||
expect(parseInlineMarkdown(repeated + "text" + repeated)).toEqual([
|
||||
{ text: repeated.slice(2) + "text", marks: ["bold"] },
|
||||
{ text: repeated.slice(2), marks: [] },
|
||||
]);
|
||||
const alternate = "__".repeat(5_000);
|
||||
expect(parseInlineMarkdown("**~~" + alternate + "text" + alternate + "~~**")).toEqual([
|
||||
{ text: alternate + "text" + alternate, marks: ["bold", "strike"] },
|
||||
]);
|
||||
});
|
||||
|
||||
it("keeps code span contents literal", () => {
|
||||
expect(parseInlineMarkdown("`**not bold**`")).toEqual([
|
||||
{ text: "**not bold**", marks: ["code"] },
|
||||
]);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,131 @@
|
||||
/**
|
||||
* Inline markdown styling for the rich text composer.
|
||||
*
|
||||
* The composer's stored prompt stays plain markdown (`**bold**`), while the
|
||||
* Tiptap surface renders styled text. These helpers translate between the two:
|
||||
* parsing markdown into marked spans for the document, serializing marked
|
||||
* spans back to markdown in the document serializer.
|
||||
*
|
||||
* Deliberately small: bold, italic, strikethrough, and inline code only.
|
||||
* Unmatched markers stay literal text so nothing the user typed is ever lost.
|
||||
*/
|
||||
|
||||
export type RichTextMark = "bold" | "italic" | "strike" | "code";
|
||||
|
||||
interface RichTextSpan {
|
||||
text: string;
|
||||
marks: RichTextMark[];
|
||||
}
|
||||
|
||||
export const RICH_TEXT_DELIMITERS: Record<RichTextMark, string> = {
|
||||
bold: "**",
|
||||
italic: "*",
|
||||
strike: "~~",
|
||||
code: "`",
|
||||
};
|
||||
|
||||
function pushSpan(spans: RichTextSpan[], text: string, marks: RichTextMark[]): void {
|
||||
if (!text) return;
|
||||
const last = spans[spans.length - 1];
|
||||
if (
|
||||
last &&
|
||||
last.marks.length === marks.length &&
|
||||
last.marks.every((mark, index) => mark === marks[index])
|
||||
) {
|
||||
last.text += text;
|
||||
} else {
|
||||
spans.push({ text, marks });
|
||||
}
|
||||
}
|
||||
|
||||
/** Parse the supported inline styles, leaving unmatched and escaped markers literal. */
|
||||
export function parseInlineMarkdown(text: string): RichTextSpan[] {
|
||||
const root: RichTextSpan[] = [];
|
||||
const stack: { delimiter: string; mark: RichTextMark; spans: RichTextSpan[] }[] = [];
|
||||
const current = () => stack.at(-1)?.spans ?? root;
|
||||
let index = 0;
|
||||
while (index < text.length) {
|
||||
const char = text[index]!;
|
||||
if (char === "\\") {
|
||||
pushSpan(current(), text.slice(index, index + 2), []);
|
||||
index += 2;
|
||||
continue;
|
||||
}
|
||||
if (char === "`") {
|
||||
// Multi-backtick code stays literal; a single-backtick span owns its contents.
|
||||
const run = text.slice(index).match(/^`+/)![0];
|
||||
const close = text.indexOf(run, index + run.length);
|
||||
if (
|
||||
run.length === 1 &&
|
||||
close > index + 1 &&
|
||||
!text.slice(index, close).includes("\n") &&
|
||||
text[close + 1] !== "`"
|
||||
) {
|
||||
pushSpan(current(), text.slice(index + 1, close), ["code"]);
|
||||
index = close + 1;
|
||||
} else {
|
||||
pushSpan(current(), run, []);
|
||||
index += run.length;
|
||||
}
|
||||
continue;
|
||||
}
|
||||
if (char !== "*" && char !== "_" && char !== "~") {
|
||||
pushSpan(current(), char, []);
|
||||
index += 1;
|
||||
continue;
|
||||
}
|
||||
let end = index;
|
||||
while (text[end] === char) end += 1;
|
||||
const before = text[index - 1] ?? "";
|
||||
const after = text[end] ?? "";
|
||||
const canClose = before !== "" && !/\s/.test(before) && (char !== "_" || !/\w/.test(after));
|
||||
const canOpen = after !== "" && !/\s/.test(after) && (char !== "_" || !/\w/.test(before));
|
||||
while (index < end) {
|
||||
const top = stack.at(-1);
|
||||
// Inside italic, a double marker opens bold before closing the single
|
||||
// marker. Once bold is active, closing runs unwind both styles.
|
||||
const opensNestedBold =
|
||||
top?.mark === "italic" &&
|
||||
end - index === 2 &&
|
||||
canOpen &&
|
||||
(char === "*" || char === "_") &&
|
||||
!stack.some((frame) => frame.mark === "bold");
|
||||
if (
|
||||
!opensNestedBold &&
|
||||
canClose &&
|
||||
top &&
|
||||
text.startsWith(top.delimiter, index) &&
|
||||
index + top.delimiter.length <= end
|
||||
) {
|
||||
stack.pop();
|
||||
for (const span of top.spans) pushSpan(current(), span.text, [top.mark, ...span.marks]);
|
||||
index += top.delimiter.length;
|
||||
} else if (canOpen && (char !== "~" || end - index >= 2)) {
|
||||
const length = char === "~" || end - index >= 2 ? 2 : 1;
|
||||
const mark = char === "~" ? "strike" : length === 2 ? "bold" : "italic";
|
||||
// A mark cannot nest inside itself, including alternate delimiters.
|
||||
// This bounds the stack to the supported styles for arbitrary input.
|
||||
if (stack.some((frame) => frame.mark === mark)) {
|
||||
pushSpan(current(), text.slice(index, end), []);
|
||||
index = end;
|
||||
continue;
|
||||
}
|
||||
stack.push({
|
||||
delimiter: char.repeat(length),
|
||||
mark,
|
||||
spans: [],
|
||||
});
|
||||
index += length;
|
||||
} else {
|
||||
pushSpan(current(), text.slice(index, end), []);
|
||||
index = end;
|
||||
}
|
||||
}
|
||||
}
|
||||
while (stack.length > 0) {
|
||||
const frame = stack.pop()!;
|
||||
pushSpan(current(), frame.delimiter, []);
|
||||
for (const span of frame.spans) pushSpan(current(), span.text, span.marks);
|
||||
}
|
||||
return root;
|
||||
}
|
||||
@@ -2120,3 +2120,105 @@ code {
|
||||
visibility: visible;
|
||||
}
|
||||
}
|
||||
|
||||
/* Rich text composer (Tiptap). The stored prompt stays markdown; only the
|
||||
surface renders styled text. Markers (** * ` ~~) appear as non-editable
|
||||
widgets while the caret is on styled text. */
|
||||
.composer-tiptap {
|
||||
position: relative;
|
||||
}
|
||||
|
||||
.composer-tiptap p {
|
||||
margin: 0;
|
||||
}
|
||||
|
||||
.composer-tiptap:focus,
|
||||
.composer-tiptap .ProseMirror:focus {
|
||||
outline: none;
|
||||
}
|
||||
|
||||
.composer-tiptap code {
|
||||
font-family: var(--font-mono);
|
||||
font-size: 0.92em;
|
||||
background: color-mix(in oklab, var(--muted-foreground) 12%, transparent);
|
||||
border-radius: 0.3em;
|
||||
padding: 0.05em 0.25em;
|
||||
}
|
||||
|
||||
.composer-rich-marker {
|
||||
color: var(--muted-foreground);
|
||||
opacity: 0.75;
|
||||
font-weight: 400;
|
||||
font-style: normal;
|
||||
text-decoration: none;
|
||||
user-select: none;
|
||||
pointer-events: none;
|
||||
}
|
||||
|
||||
/* Selected chips (node selection from arrowing into or clicking a chip). */
|
||||
.composer-tiptap .ProseMirror-selectednode {
|
||||
outline: 2px solid var(--ring);
|
||||
outline-offset: 1px;
|
||||
border-radius: 6px;
|
||||
}
|
||||
|
||||
.composer-tiptap .composer-chip-range-selected {
|
||||
position: relative;
|
||||
}
|
||||
|
||||
.composer-tiptap.ProseMirror-focused .composer-chip-range-selected::after {
|
||||
content: "";
|
||||
position: absolute;
|
||||
inset: 0;
|
||||
border-radius: 6px;
|
||||
background: Highlight;
|
||||
opacity: 0.3;
|
||||
pointer-events: none;
|
||||
}
|
||||
|
||||
/* Rich-text task lists render as real checkboxes. Tiptap's TaskItem NodeView
|
||||
builds the <li> imperatively with only a data-checked attribute (no
|
||||
data-type), so items are targeted that way. Indentation comes from list
|
||||
nesting (two spaces per level from Tab), matching the stored Markdown. */
|
||||
.composer-tiptap ul[data-type="taskList"] {
|
||||
list-style: none;
|
||||
margin: 0;
|
||||
padding: 0;
|
||||
}
|
||||
|
||||
.composer-tiptap ul[data-type="taskList"] ul[data-type="taskList"] {
|
||||
padding-left: 1.375rem;
|
||||
}
|
||||
|
||||
.composer-tiptap li[data-checked] {
|
||||
display: flex;
|
||||
align-items: flex-start;
|
||||
gap: 0.5rem;
|
||||
margin: 0;
|
||||
padding: 0;
|
||||
}
|
||||
|
||||
.composer-tiptap li[data-checked] > label {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
flex: none;
|
||||
height: 1lh;
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.composer-tiptap li[data-checked] > label input[type="checkbox"] {
|
||||
display: block;
|
||||
margin: 0;
|
||||
width: 0.95rem;
|
||||
height: 0.95rem;
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.composer-tiptap li[data-checked] > div {
|
||||
flex: 1 1 auto;
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.composer-tiptap li[data-checked] > div > p {
|
||||
margin: 0;
|
||||
}
|
||||
@@ -14,6 +14,7 @@ import {
|
||||
import {
|
||||
formatShortcutLabel,
|
||||
isDiffToggleShortcut,
|
||||
isRichTextBoldShortcut,
|
||||
modelPickerJumpCommandForIndex,
|
||||
modelPickerJumpIndexFromCommand,
|
||||
isOpenFavoriteEditorShortcut,
|
||||
@@ -962,6 +963,21 @@ describe("isTerminalClearShortcut", () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe("isRichTextBoldShortcut", () => {
|
||||
it("matches Mod+B without extra modifiers", () => {
|
||||
assert.isTrue(isRichTextBoldShortcut(event({ key: "b", metaKey: true })));
|
||||
assert.isTrue(isRichTextBoldShortcut(event({ key: "B", ctrlKey: true })));
|
||||
});
|
||||
|
||||
it("ignores shifted, alted, bare, and non-keydown presses", () => {
|
||||
assert.isFalse(isRichTextBoldShortcut(event({ key: "b", metaKey: true, shiftKey: true })));
|
||||
assert.isFalse(isRichTextBoldShortcut(event({ key: "b", metaKey: true, altKey: true })));
|
||||
assert.isFalse(isRichTextBoldShortcut(event({ key: "b" })));
|
||||
assert.isFalse(isRichTextBoldShortcut(event({ key: "i", metaKey: true })));
|
||||
assert.isFalse(isRichTextBoldShortcut(event({ type: "keyup", key: "b", metaKey: true })));
|
||||
});
|
||||
});
|
||||
|
||||
describe("terminalDeleteShortcutData", () => {
|
||||
it("maps Cmd+Backspace on macOS to delete-to-line-start", () => {
|
||||
assert.strictEqual(
|
||||
|
||||
@@ -406,6 +406,23 @@ export function isOpenFavoriteEditorShortcut(
|
||||
return matchesCommandShortcut(event, keybindings, "editor.openFavorite", options);
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether the keypress is the rich-text bold chord (Mod+B without extra
|
||||
* modifiers). Tiptap binds the same chord, so app shortcuts captured ahead
|
||||
* of the editor must yield when the rich-text composer is focused.
|
||||
*/
|
||||
export function isRichTextBoldShortcut(event: ShortcutEventLike): boolean {
|
||||
if (event.type !== undefined && event.type !== "keydown") {
|
||||
return false;
|
||||
}
|
||||
return (
|
||||
event.key.toLowerCase() === "b" &&
|
||||
(event.metaKey || event.ctrlKey) &&
|
||||
!event.altKey &&
|
||||
!event.shiftKey
|
||||
);
|
||||
}
|
||||
|
||||
export function isTerminalClearShortcut(
|
||||
event: ShortcutEventLike,
|
||||
platform = navigator.platform,
|
||||
|
||||
@@ -0,0 +1,27 @@
|
||||
# Composer coordinates and serialization
|
||||
|
||||
The draft store owns Markdown, while Tiptap owns the editing document. The rich-text
|
||||
setting changes the installed extensions, so toggling it remounts the editor from the
|
||||
stored draft. Plain mode must leave formatting markers literal. Rich mode preserves
|
||||
whitespace and chip sources, but canonicalizes supported delimiters (`__` to `**`,
|
||||
`_` to `*`) and checkbox case (`[X]` to `[x]`).
|
||||
|
||||
Store cursors are not ProseMirror positions: collapsed coordinates count a chip as one
|
||||
character, expanded coordinates count its source text, and ProseMirror also counts
|
||||
block boundaries. Keep conversion in [the document model](../../apps/web/src/composer-rich-text-doc.ts).
|
||||
Empty paragraphs need real caret positions even though they contain no text. Markers
|
||||
shown beside styled text are decorations, so offsets inside them clamp to the text edge.
|
||||
|
||||
Only replace editor content when the controlled text changes. Replacing it for a cursor
|
||||
move creates undo entries and regenerates citation identities. Pending citation popovers
|
||||
must wait until the requested draft has reached the editor before locating their chip.
|
||||
|
||||
Rich tasks split through native editor commands so marks and chips survive. Literal
|
||||
lists use [store edits](../../apps/web/src/composer-list-continuation.ts). Newlines become
|
||||
paragraph splits: trailing hard breaks otherwise appear to require two presses.
|
||||
Programmatic moves must explicitly scroll the caret into view.
|
||||
|
||||
Clipboard text must come from the Markdown serializer, not DOM text: chip labels omit
|
||||
the source and marker decorations are not content. Structured context records accompany
|
||||
that text when available. Paste completes trailing chip delimiters and adds a leading
|
||||
boundary when inserting a chip directly after text.
|
||||
@@ -20,6 +20,19 @@ const decodeServerSettingsPatch = Schema.decodeUnknownSync(ServerSettingsPatch);
|
||||
const encodeServerSettings = Schema.encodeSync(ServerSettings);
|
||||
const decodeClaudeSettings = Schema.decodeUnknownSync(ClaudeSettings);
|
||||
|
||||
describe("ClientSettings rich text composer", () => {
|
||||
it("enables rich text for new and existing settings without a saved preference", () => {
|
||||
expect(decodeClientSettings({}).composerRichTextEnabled).toBe(true);
|
||||
expect(decodeClientSettings({ sendShortcut: "mod-enter" }).composerRichTextEnabled).toBe(true);
|
||||
});
|
||||
|
||||
it("preserves an explicit opt-out through patches and persistence", () => {
|
||||
const preference = { composerRichTextEnabled: false };
|
||||
expect(decodeClientSettingsPatch(preference)).toEqual(preference);
|
||||
expect(encodeClientSettings(decodeClientSettings(preference))).toMatchObject(preference);
|
||||
});
|
||||
});
|
||||
|
||||
describe("ServerSettings default permissions", () => {
|
||||
it("keeps full access for settings saved before a default was configured", () => {
|
||||
expect(decodeServerSettings({}).defaultRuntimeMode).toBe("full-access");
|
||||
|
||||
@@ -430,6 +430,8 @@ export const ClientSettingsSchema = Schema.Struct({
|
||||
// Desktop resting composer: scrolling an existing thread's conversation
|
||||
// settles the composer into its single-line layout. Losing focus never does.
|
||||
composerCollapseOnScroll: Schema.Boolean.pipe(Schema.withDecodingDefault(Effect.succeed(true))),
|
||||
// Rich text is the default; users can opt out for literal Markdown editing.
|
||||
composerRichTextEnabled: Schema.Boolean.pipe(Schema.withDecodingDefault(Effect.succeed(true))),
|
||||
sendShortcut: Schema.Literals(["enter", "mod-enter-multiline", "mod-enter"]).pipe(
|
||||
Schema.withDecodingDefault(Effect.succeed("enter")),
|
||||
),
|
||||
@@ -1505,6 +1507,7 @@ export const ClientSettingsPatch = Schema.Struct({
|
||||
planModeEnabled: Schema.optionalKey(Schema.Boolean),
|
||||
contextWindowMeterEnabled: Schema.optionalKey(Schema.Boolean),
|
||||
composerCollapseOnScroll: Schema.optionalKey(Schema.Boolean),
|
||||
composerRichTextEnabled: Schema.optionalKey(Schema.Boolean),
|
||||
sendShortcut: Schema.optionalKey(Schema.Literals(["enter", "mod-enter-multiline", "mod-enter"])),
|
||||
followUpBehavior: Schema.optionalKey(Schema.Literals(["queue", "steer"])),
|
||||
proactivePanelsEnabled: Schema.optionalKey(Schema.Boolean),
|
||||
|
||||
Generated
+505
-301
File diff suppressed because it is too large.
Load diff
Reference in new issue
Block a user