feat(web): block-level Markdown in the rich text composer (#14677)

Co-authored-by: Julius Marminge <[email protected]>
Co-authored-by: Claude Opus 5.5 (1M context) <[email protected]>
Co-authored-by: Julius Marminge <[email protected]>
This commit is contained in:
authored and GitHub committed 2026-10-07 15:29:43 -07:00
1 parent 95ccbf4066
commit 300f7f9d45
21 files changed
+3800 -177

No files matched your search

+5
View File
@@ -32,7 +32,12 @@
"@tanstack/react-pacer": "^0.19.4",
"@tanstack/react-router": "^1.160.2",
"@tiptap/core": "^3.31.3",
"@tiptap/extension-blockquote": "^3.31.3",
"@tiptap/extension-code": "^3.31.3",
"@tiptap/extension-code-block": "^3.31.3",
"@tiptap/extension-heading": "^3.31.3",
"@tiptap/extension-horizontal-rule": "^3.31.3",
"@tiptap/extension-list": "^3.31.3",
"@tiptap/extension-task-item": "^3.31.3",
"@tiptap/extension-task-list": "^3.31.3",
"@tiptap/pm": "^3.31.3",
+66 -15
View File
@@ -989,6 +989,63 @@ function MarkdownDetails({
);
}
/**
* The code block frame, shared with the composer so an editable fence and a
* rendered one cannot drift apart: the wrapper, its header row with the
* language title, an optional actions slot, and the body as children. The
* composer passes Tiptap's node view wrapper as the outer element.
*/
export function MarkdownCodeBlockFrame({
as: Wrapper = "div",
language,
fenceTitle,
theme,
wrapped = true,
title,
actions,
headerProps,
children,
}: {
as?: React.ElementType;
language: string;
fenceTitle: string | null;
theme: "light" | "dark";
wrapped?: boolean;
/** Replaces the language title, as the composer does with its language picker. */
title?: React.ReactNode;
actions?: React.ReactNode;
headerProps?: React.HTMLAttributes<HTMLDivElement>;
children: React.ReactNode;
}) {
return (
<Wrapper
className="chat-markdown-codeblock my-[0.65rem] overflow-hidden rounded-lg border border-border/70 bg-secondary leading-snug dark:border-transparent dark:bg-input/32"
data-language={language}
data-wrap={wrapped ? "true" : "false"}
>
<div
{...headerProps}
className={cn(
"chat-markdown-codeblock-header flex items-center justify-between gap-2 pt-1.5 pr-1.5 pb-0 pl-3 select-none",
headerProps?.className,
)}
>
{title ?? (
<span className="inline-flex min-w-0 items-center gap-1.5 font-mono text-2xs">
<MarkdownCodeBlockTitleContent
fenceTitle={fenceTitle}
language={language}
theme={theme}
/>
</span>
)}
{actions}
</div>
{children}
</Wrapper>
);
}
/**
* Filename titles render icon + text; language-only titles render just the
* icon (redundant next to its own name) and fall back to the language text
@@ -1141,19 +1198,12 @@ function MarkdownCodeBlock({
}
return (
<div
className="chat-markdown-codeblock my-[0.65rem] overflow-hidden rounded-lg border border-border/70 bg-secondary leading-snug dark:border-transparent dark:bg-input/32"
data-language={language}
data-wrap={wrapped ? "true" : "false"}
>
<div className="chat-markdown-codeblock-header flex items-center justify-between gap-2 pt-1.5 pr-1.5 pb-0 pl-3 select-none">
<span className="inline-flex min-w-0 items-center gap-1.5 font-mono text-2xs">
<MarkdownCodeBlockTitleContent
fenceTitle={fenceTitle}
language={language}
theme={theme}
/>
</span>
<MarkdownCodeBlockFrame
language={language}
fenceTitle={fenceTitle}
theme={theme}
wrapped={wrapped}
actions={
<span className="flex items-center gap-0.5" role="toolbar" aria-label="Code block actions">
{leadingActions}
{canWrap ? (
@@ -1195,9 +1245,10 @@ function MarkdownCodeBlock({
) : null}
{copyButton}
</span>
</div>
}
>
{children}
</div>
</MarkdownCodeBlockFrame>
);
}
@@ -1,11 +1,17 @@
import { Extension, Node, wrappingInputRule, type JSONContent } from "@tiptap/core";
import { TaskList } from "@tiptap/extension-task-list";
import { Extension, InputRule, Node, wrappingInputRule, type JSONContent } from "@tiptap/core";
import { ReactNodeViewRenderer, NodeViewWrapper, type NodeViewProps } from "@tiptap/react";
import StarterKit from "@tiptap/starter-kit";
import { type Node as ProseMirrorNode } from "@tiptap/pm/model";
import { splitBlockKeepMarks } from "@tiptap/pm/commands";
import { type EditorState, Plugin, PluginKey, TextSelection } from "@tiptap/pm/state";
import { Decoration, DecorationSet } from "@tiptap/pm/view";
import { newlineInCode, splitBlockKeepMarks } from "@tiptap/pm/commands";
import {
type EditorState,
NodeSelection,
Plugin,
PluginKey,
TextSelection,
} from "@tiptap/pm/state";
import { Decoration, DecorationSet, type EditorView } from "@tiptap/pm/view";
import type { NodeType, ResolvedPos } from "@tiptap/pm/model";
import type {
AssistantCitation,
ComposerContextClipboardFragment,
@@ -45,19 +51,34 @@ import {
} from "~/composer-editor-mentions";
import {
buildDocJson,
ComposerBlockExtensions,
ComposerCodeBlockExtension,
ComposerListExtensions,
buildTiptapContent,
collapsedToFlat,
caretTakesMarksBefore,
convertBulletItemToTask,
ComposerCodeExtension,
ComposerTaskItemExtension,
ComposerTaskListExtension,
flatToCollapsed,
flatToMarkdown,
flatToPm,
pmToFlat,
serializeEditorDoc,
serializeSelection,
splitOrLiftListItem,
stepCaretAcrossStyledEdge,
type SkillMeta,
} from "~/composer-rich-text-doc";
import {
convertCodeFenceOnEnter,
exitCodeBlockOnClosingFence,
exitCodeBlockOnTrailingBlankLines,
indentCodeBlock,
indentedNewlineInCodeBlock,
selectionInOneCodeBlock,
} from "~/composer-code-block";
import {
COMPOSER_UNDO_GROUP_DELAY,
type ComposerChangeKind,
@@ -65,6 +86,7 @@ import {
markAsClipboardEdit,
} from "~/composer-undo-grouping";
import { collectInlineContextIds } from "~/lib/composerContextReferences";
import { resolveDiffThemeName } from "~/lib/diffRendering";
import { cn, isMacPlatform } from "~/lib/utils";
import { basenameOfPath } from "~/pierre-icons";
import { FileTagChipContent } from "./chat/FileTagChip";
@@ -82,6 +104,8 @@ import {
import type { AssistantCitationSourceAnchor } from "~/lib/assistantTextSelection";
import { formatProviderSkillDisplayName } from "@t3tools/client-runtime/providerSkills";
import { Tooltip, TooltipPopup, TooltipTrigger } from "./ui/tooltip";
import { ComposerCodeBlockNodeView } from "./chat/ComposerCodeBlockNodeView";
import { composerCodeBlockHighlight } from "./composerCodeBlockHighlight";
import { importPastedComposerText } from "./composerInlineTokenPaste";
import { didComposerSelectionChangeVisibly } from "./composerSelection";
import type { ComposerDraftContextRecords } from "./composerContextPresentation";
@@ -491,6 +515,9 @@ function collectStyledRanges(doc: ProseMirrorNode): StyledRange[] {
let range: StyledRange | null = null;
let openLength = 0;
for (const run of map.runs) {
// A fence is drawn as a block, not revealed a character at a time, so its
// delimiters never become marker widgets.
if (run.nodeName === "codeBlock") continue;
if (run.openLen > 0) {
range ??= { from: run.pmPos, to: run.pmPos, markers: [] };
range.markers.push({
@@ -518,6 +545,162 @@ function collectStyledRanges(doc: ProseMirrorNode): StyledRange[] {
return ranges;
}
/**
* A typed marker becomes a list item that remembers the marker it was typed
* with, so the stored Markdown keeps `*` or `3)` rather than a canonical `-`.
*
* `- ` alone is not enough for a dash: it waits for the first character after
* the space, which it carries into the new item. That is what lets the GFM
* task gesture `- [ ] ` or `- [x] ` be typed whole and reach the task rule,
* instead of being cut off by an instant bullet. A `- ` left on its own is
* still a bullet the next time the draft is rebuilt.
*/
function listMarkerInputRule(find: RegExp, listType: "bulletList" | "orderedList"): InputRule {
return new InputRule({
find,
handler: ({ state, range, match, chain }) => {
const marker = match.groups?.marker ?? "-";
const space = match.groups?.space ?? " ";
const carried = match.groups?.carried ?? "";
// Top-level paragraphs only: inside an item or a quote the new list
// would nest under a line the stored draft writes flat.
const $from = state.doc.resolve(range.from);
if ($from.parent.type.name !== "paragraph" || $from.depth !== 1) return null;
const command = chain()
.deleteRange(range)
.wrapInList(
listType,
listType === "orderedList" ? { start: Number.parseInt(marker, 10) || 1 } : {},
)
.updateAttributes("listItem", { marker, space });
(carried ? command.insertContent(carried) : command).run();
return undefined;
},
});
}
/**
* `[ ] ` at the start of an existing bullet item turns it into a task, for
* items that were already a list when the checkbox was wanted. New tasks are
* typed whole, `- [ ] `, and reach the task rule directly.
*/
const bulletToTaskInputRule = new InputRule({
find: /^\[([ xX])\] $/,
handler: ({ state, range, match, chain }) => {
const $from = state.doc.resolve(range.from);
const item = $from.node(-1);
if ($from.parent.type.name !== "paragraph" || item?.type.name !== "listItem") return null;
// Any bullet converts; the task grammar only knows `-`, so a `*` or `+`
// item comes back out as `- [ ]`.
if (!["-", "*", "+"].includes((item.attrs as { marker?: string }).marker ?? "")) return null;
const checked = (match[1] ?? " ").toLowerCase() === "x";
chain()
.command(({ tr }) => {
convertBulletItemToTask(tr, range.from, range.to, checked);
return true;
})
.run();
return undefined;
},
});
/** `- [ ] ` or `- [x] ` at a top-level paragraph, for the same reason as the list markers. */
function taskInputRule(type: NodeType): InputRule {
const rule = wrappingInputRule({
find: /^- \[([ xX])\] $/,
type,
getAttributes: (match) => ({ checked: match[1]?.toLowerCase() === "x" }),
});
return new InputRule({
find: rule.find,
handler: (props) =>
props.state.doc.resolve(props.range.from).depth === 1 ? rule.handler(props) : null,
});
}
function hasAncestor($pos: ResolvedPos, name: string): boolean {
for (let depth = $pos.depth; depth > 0; depth -= 1) {
if ($pos.node(depth).type.name === name) return true;
}
return false;
}
/**
* `> ` at the start of a top-level paragraph opens a quote. Not inside a list:
* a quote holds prose lines, and a list item is not one.
*/
const blockquoteInputRule = new InputRule({
find: /^>(\s)$/,
handler: ({ state, range, match, chain }) => {
const $from = state.doc.resolve(range.from);
if ($from.parent.type.name !== "paragraph" || $from.depth !== 1) return null;
chain()
.deleteRange(range)
.wrapIn("blockquote", { prefix: `>${match[1] ?? " "}` })
.run();
return undefined;
},
});
/**
* `---` becomes a rule as the third dash lands; `***` and `___` need a space
* after them so typing bold or an underscore is not interrupted, matching
* Tiptap's own rule. Only at a top-level paragraph: the list and quote
* serializers have no line to write a rule into. The typed characters are
* kept as the rule's source, and `setHorizontalRule` adds a paragraph after a
* rule at the end so the caret has somewhere to go.
*/
const horizontalRuleInputRule = new InputRule({
find: /^(---|\*\*\*|___)\s?$/,
handler: ({ state, range, match, chain }) => {
const source = match[0] ?? "---";
if (!source.startsWith("---") && !/\s$/.test(source)) return null;
const $from = state.doc.resolve(range.from);
if ($from.parent.type.name !== "paragraph" || $from.depth !== 1) return null;
chain()
.deleteRange(range)
.setHorizontalRule()
.command(({ tr }) => {
// The rule is the block before the caret's paragraph.
const $pos = tr.selection.$from;
const index = $pos.index(0) - 1;
if (index < 0) return true;
const rulePos = $pos.posAtIndex(index, 0);
const rule = tr.doc.nodeAt(rulePos);
if (rule?.type.name === "horizontalRule") {
tr.setNodeMarkup(rulePos, undefined, { ...rule.attrs, source });
}
return true;
})
.run();
return undefined;
},
});
/**
* `# ` through `###### ` at a top-level paragraph make a heading. The space
* is required, which is exactly what keeps `#1234` a pull request reference
* with its picker rather than a heading. Not inside lists or quotes, whose
* serializers have no line for one.
*/
const headingInputRule = new InputRule({
find: /^(#{1,6})(\s)$/,
handler: ({ state, range, match, chain }) => {
const $from = state.doc.resolve(range.from);
if ($from.parent.type.name !== "paragraph" || $from.depth !== 1) return null;
chain()
.deleteRange(range)
.setNode("heading", { level: match[1]?.length ?? 1, space: match[2] ?? " " })
.run();
return undefined;
},
});
/** Whether the caret sits inside a fenced code block. */
function isInCodeBlock(view: EditorView): boolean {
return view.state.selection.$from.parent.type.spec.code === true;
}
const MarkerPluginKey = new PluginKey("composer-rich-markers");
const ComposerMarkerPlugin = new Plugin({
@@ -766,16 +949,16 @@ function ComposerPromptEditorTiptapInner(props: ComposerPromptEditorProps) {
expandedCursor: nextExpandedCursor,
contextIds: map.contextIds,
};
const cursorAdjacentToMention =
// A fence holds no chips, so nothing in it should summon the mention or
// command menu: `@` in code is a decorator, not a file. Suppressing the
// trigger here also keeps the store from inserting a link the block can
// only show as literal text, which the store would then count as a chip.
const inCodeBlock = updated.state.selection.$from.parent.type.spec.code === true;
const suppressTrigger =
inCodeBlock ||
isCollapsedCursorAdjacentToInlineToken(nextValue, nextCursor, "left") ||
isCollapsedCursorAdjacentToInlineToken(nextValue, nextCursor, "right");
onChangeRef.current(
nextValue,
nextCursor,
nextExpandedCursor,
cursorAdjacentToMention,
map.contextIds,
);
onChangeRef.current(nextValue, nextCursor, nextExpandedCursor, suppressTrigger, map.contextIds);
}, []);
const editorAttributes = useMemo(
@@ -824,6 +1007,8 @@ function ComposerPromptEditorTiptapInner(props: ComposerPromptEditorProps) {
gapcursor: false,
trailingNode: false,
code: false,
// The list extensions handle Backspace and Delete themselves.
listKeymap: false,
undoRedo: { newGroupDelay: COMPOSER_UNDO_GROUP_DELAY },
// Plain mode has no marks: typed markers stay literal characters.
...(richText ? {} : { bold: false, italic: false, strike: false }),
@@ -837,16 +1022,78 @@ function ComposerPromptEditorTiptapInner(props: ComposerPromptEditorProps) {
...(richText
? [
ComposerCodeExtension,
TaskList,
ComposerCodeBlockExtension.extend({
addNodeView() {
return ReactNodeViewRenderer(ComposerCodeBlockNodeView, {
// The header holds the language picker. Tiptap only shields
// events aimed at the button element itself, so a click on
// its icon or label would reach ProseMirror and move the
// selection; keep every header event away from the editor.
stopEvent: ({ event }) =>
event.target instanceof Element &&
event.target.closest(".chat-markdown-codeblock-header") !== null,
});
},
// Tiptap's own ``` + space rule would open a fence inside a
// list item or quote, where the serializer has no line for
// it. Enter on a fence line covers the gesture at top level.
addInputRules() {
return [];
},
}),
composerCodeBlockHighlight({
resolveTheme: () =>
resolveDiffThemeName(
document.documentElement.classList.contains("dark") ? "dark" : "light",
),
}),
...ComposerBlockExtensions.map((extension) =>
extension.name === "blockquote"
? extension.extend({
addInputRules() {
return [blockquoteInputRule];
},
})
: extension.name === "horizontalRule"
? extension.extend({
addInputRules() {
return [horizontalRuleInputRule];
},
})
: extension.name === "heading"
? extension.extend({
addInputRules() {
return [headingInputRule];
},
})
: extension,
),
...ComposerListExtensions.map((extension) =>
extension.name === "listItem"
? extension
: extension.extend({
addInputRules() {
return this.name === "bulletList"
? [
listMarkerInputRule(/^(?<marker>[*+])(?<space>\s)$/, "bulletList"),
listMarkerInputRule(
/^(?<marker>-)(?<space>[ \t]+)(?<carried>[^\s[])$/,
"bulletList",
),
]
: [
listMarkerInputRule(
/^(?<marker>\d+[.)])(?<space>\s)$/,
"orderedList",
),
];
},
}),
),
ComposerTaskListExtension,
ComposerTaskItemExtension.extend({
addInputRules() {
return [
wrappingInputRule({
find: /^- \[([ xX])\] $/,
type: this.type,
getAttributes: (match) => ({ checked: match[1]?.toLowerCase() === "x" }),
}),
];
return [taskInputRule(this.type), bulletToTaskInputRule];
},
}),
]
@@ -982,23 +1229,71 @@ function ComposerPromptEditorTiptapInner(props: ComposerPromptEditorProps) {
event.preventDefault();
return true;
}
// Inside a fence Tab belongs to the code, not to the composer's
// focus order or its autocomplete.
if (
event.key === "Tab" &&
!event.metaKey &&
!event.ctrlKey &&
selectionInOneCodeBlock(view.state)
) {
event.preventDefault();
event.stopPropagation();
return indentCodeBlock(view.state, event.shiftKey ? "out" : "in", (tr) =>
view.dispatch(tr),
);
}
// A fence is multi-line by definition, so Enter and Shift+Enter
// belong to the code rather than to sending or splitting: inside a
// block they make a line (a generic split would cut the fence in
// two), and on a line that is only an opening fence they open the
// block. Sending from inside a fence is still Cmd/Ctrl+Enter, which
// falls through.
if (
event.key === "Enter" &&
richText &&
!event.metaKey &&
!event.ctrlKey &&
!event.isComposing
) {
if (selectionInOneCodeBlock(view.state)) {
event.preventDefault();
event.stopPropagation();
const dispatch = (tr: typeof view.state.tr) => view.dispatch(tr.scrollIntoView());
return (
exitCodeBlockOnClosingFence(view.state, dispatch) ||
exitCodeBlockOnTrailingBlankLines(view) ||
indentedNewlineInCodeBlock(view.state, dispatch) ||
newlineInCode(view.state, dispatch)
);
}
if (convertCodeFenceOnEnter(view.state, (tr) => view.dispatch(tr))) {
event.preventDefault();
event.stopPropagation();
return true;
}
}
const handler = onCommandKeyDownRef.current;
if (event.key === "Enter") {
const instance = editorHolder.current;
const isTaskItem = richText && (instance?.isActive("taskItem") ?? false);
const handled = handler?.("Enter", event, isTaskItem) ?? false;
const isListItem = richText && (instance?.isActive("listItem") ?? false);
const handled = handler?.("Enter", event, isTaskItem || isListItem) ?? false;
if (handled) {
event.preventDefault();
event.stopPropagation();
return true;
}
event.preventDefault();
if ((isTaskItem || isListItem) && instance && splitOrLiftListItem(instance)) {
return true;
}
if (
isTaskItem &&
richText &&
instance &&
(instance.commands.splitListItem("taskItem", { checked: false }) ||
(view.state.selection.$from.parent.content.size === 0 &&
instance.commands.liftListItem("taskItem")))
hasAncestor(view.state.selection.$from, "blockquote") &&
view.state.selection.$from.parent.content.size === 0 &&
instance.commands.lift("blockquote")
) {
return true;
}
@@ -1050,6 +1345,19 @@ function ComposerPromptEditorTiptapInner(props: ComposerPromptEditorProps) {
const pastedText = clipboardData.getData("text/plain");
if (!pastedText) return false;
event.preventDefault();
// A fence takes the clipboard verbatim. Running the markdown path
// here would split the block on newlines, nest a pasted fence and
// build chips the code block's schema cannot hold anyway.
if (isInCodeBlock(view)) {
const { from, to } = view.state.selection;
view.dispatch(
markAsClipboardEdit(
view.state.tr.insertText(pastedText, from, to),
"paste",
).scrollIntoView(),
);
return true;
}
const importFragment = importFragmentRef.current;
let text = importFragment
? importPastedComposerText(clipboardData, importFragment)
@@ -1073,18 +1381,44 @@ function ComposerPromptEditorTiptapInner(props: ComposerPromptEditorProps) {
}
const editorInstance = editorHolder.current;
if (editorInstance) {
insertMarkdownParagraphs(text, skillLabelFor, { styling: richText }, (content) => {
// Tagged on the same transaction insertContent builds, so the
// paste is one undo step of its own.
editorInstance
.chain()
.command(({ tr }) => {
markAsClipboardEdit(tr, "paste");
return true;
})
.insertContent(content)
.run();
});
// Inside a list item or quote, pasted block markup has nowhere to
// go: it stays literal lines the next rebuild reads back. Inline
// marks still apply.
const $paste = view.state.selection.$from;
const nested = ["listItem", "taskItem", "blockquote"].some((name) =>
hasAncestor($paste, name),
);
insertMarkdownParagraphs(
text,
skillLabelFor,
{ styling: richText, blocks: !nested },
(content) => {
// Tagged on the same transaction insertContent builds, so the
// paste is one undo step of its own.
editorInstance
.chain()
.command(({ tr }) => {
markAsClipboardEdit(tr, "paste");
return true;
})
.insertContent(content)
.command(({ tr }) => {
// A paste ending in a rule leaves the rule selected, and
// the next keystroke would replace it. The caret goes to
// the line after it, which is added when there is none.
const { selection } = tr;
if (!(selection instanceof NodeSelection) || !selection.node.isBlock) {
return true;
}
if (!tr.doc.resolve(selection.to).nodeAfter?.isTextblock) {
tr.insert(selection.to, tr.doc.type.schema.nodes.paragraph!.create());
}
tr.setSelection(TextSelection.create(tr.doc, selection.to + 1));
return true;
})
.run();
},
);
scrollTiptapCaretIntoView(editorInstance);
}
return true;
@@ -1330,15 +1664,7 @@ function ComposerPromptEditorTiptapInner(props: ComposerPromptEditorProps) {
const clipboardData = event.clipboardData;
const { from, to } = editor.state.selection;
if (from === to) return;
const { doc, schema } = editor.state;
const slice = doc.slice(from, to);
const first = slice.content.firstChild;
const content = first?.isInline
? schema.nodes.paragraph!.create(null, slice.content)
: first?.type.name === "taskItem"
? schema.nodes.taskList!.create(null, slice.content)
: slice.content;
const text = serializeEditorDoc(doc.type.create(null, content)).value;
const text = serializeSelection(editor.state.doc, from, to);
const contextIds = Array.from(new Set(collectInlineContextIds(text)));
const fragment = contextIds.length > 0 ? build?.(contextIds) : null;
event.preventDefault();
@@ -1442,7 +1768,7 @@ function ComposerPromptEditorTiptapInner(props: ComposerPromptEditorProps) {
function insertMarkdownParagraphs(
value: string,
skillLabelFor: (name: string) => SkillMeta,
options: { styling: boolean },
options: { styling: boolean; blocks?: boolean },
insertContent: (content: JSONContent[] | JSONContent) => void,
): void {
const blocks = buildTiptapContent(value, skillLabelFor, options);
@@ -0,0 +1,121 @@
import { CheckIcon, ChevronDownIcon } from "lucide-react";
import { useMemo, useState } from "react";
import {
CODE_BLOCK_LANGUAGES,
type CodeBlockLanguage,
codeLanguageEntry,
codeLanguageLabel,
} from "~/composer-code-languages";
import { syntheticFileNameForLanguageId } from "~/pierre-icons";
import { Button } from "../ui/button";
import {
Combobox,
ComboboxEmpty,
ComboboxItem,
ComboboxList,
ComboboxPopup,
ComboboxSearchInput,
ComboboxTrigger,
} from "../ui/combobox";
import { PierreEntryIcon } from "./PierreEntryIcon";
/**
* The language's file icon: plain text gets the text-file icon, and a
* language the icon set does not cover gets the default file icon, so every
* entry has one and the labels line up.
*/
function LanguageIcon(props: { language: string; theme: "light" | "dark" }) {
const fileName = props.language ? syntheticFileNameForLanguageId(props.language) : "file.txt";
return (
<PierreEntryIcon pathValue={fileName} kind="file" theme={props.theme} className="size-3.5" />
);
}
/**
* The language control in a composer fence's header: shows what the fence
* declares and switches it from a searchable list. A language typed on the
* fence line that the list does not carry is offered as its own entry, so
* the current choice is always visible and checked.
*/
export function ComposerCodeBlockLanguagePicker(props: {
language: string;
theme: "light" | "dark";
disabled: boolean;
onChange: (language: string) => void;
}) {
const [query, setQuery] = useState("");
const current = codeLanguageEntry(props.language)?.id ?? props.language;
const items = useMemo<CodeBlockLanguage[]>(
() =>
CODE_BLOCK_LANGUAGES.some((entry) => entry.id === current)
? [...CODE_BLOCK_LANGUAGES]
: [{ id: current, label: current }, ...CODE_BLOCK_LANGUAGES],
[current],
);
const filteredItems = useMemo(() => {
const needle = query.trim().toLowerCase();
if (!needle) return items;
return items.filter(
(entry) => entry.label.toLowerCase().includes(needle) || entry.id.includes(needle),
);
}, [items, query]);
const selected = items.find((entry) => entry.id === current) ?? null;
return (
// The trigger's pill pads its content by 8px (padding plus border) and the
// button pulls a leading icon back 2px; offsetting the difference lines
// the icon up with the code below while keeping the hover pill.
<span className="-ml-1.5 flex min-w-0">
<Combobox
items={items}
filteredItems={filteredItems}
autoHighlight
itemToStringLabel={(entry) => entry.label}
isItemEqualToValue={(a, b) => a.id === b.id}
value={selected}
onOpenChange={(open) => {
if (!open) setQuery("");
}}
onValueChange={(entry) => {
if (entry && entry.id !== current) props.onChange(entry.id);
}}
>
<ComboboxTrigger
render={
<Button
type="button"
variant="ghost-muted"
size="xs"
disabled={props.disabled}
aria-label={`Code language: ${codeLanguageLabel(props.language)}`}
/>
}
>
<LanguageIcon language={current} theme={props.theme} />
<span className="max-w-40 truncate">{codeLanguageLabel(props.language)}</span>
<ChevronDownIcon className="opacity-60" />
</ComboboxTrigger>
<ComboboxPopup align="start" className="w-56">
<ComboboxSearchInput
aria-label="Search languages"
placeholder="Search languages"
value={query}
onChange={(event) => setQuery(event.target.value)}
/>
<ComboboxEmpty>No matching languages.</ComboboxEmpty>
<ComboboxList>
{(entry: CodeBlockLanguage) => (
<ComboboxItem key={entry.id || "plain"} value={entry}>
<LanguageIcon language={entry.id} theme={props.theme} />
<span className="min-w-0 flex-1 truncate">{entry.label}</span>
{entry.id === current ? <CheckIcon className="ml-auto" /> : null}
</ComboboxItem>
)}
</ComboboxList>
</ComboboxPopup>
</Combobox>
</span>
);
}
@@ -0,0 +1,67 @@
import { NodeViewContent, NodeViewWrapper, type NodeViewProps } from "@tiptap/react";
import { languageOfInfoString, withInfoStringLanguage } from "~/composer-code-languages";
import { useTheme } from "../../hooks/useTheme";
import { MarkdownCodeBlockFrame } from "../ChatMarkdown";
import { ComposerCodeBlockLanguagePicker } from "./ComposerCodeBlockLanguagePicker";
/**
* Draws a composer fence in the chat view's own code block frame, so a draft
* looks like the message it is about to become, with the language title
* swapped for a picker that rewrites the fence's language in place.
*
* The chrome stops at the language. Chat's wrap and copy buttons act on text
* the reader cannot change; here the text is the draft, and both are already
* a selection away.
*/
export function ComposerCodeBlockNodeView({
node,
editor,
getPos,
updateAttributes,
}: NodeViewProps) {
const { resolvedTheme } = useTheme();
const info = typeof node.attrs.language === "string" ? node.attrs.language : "";
const language = languageOfInfoString(info);
const changeLanguage = (next: string) => {
updateAttributes({ language: withInfoStringLanguage(info, next) });
// Back into the code, at its end, the way a picker hands focus back.
const position = getPos();
if (typeof position === "number") {
editor
.chain()
.focus(position + 1 + node.content.size)
.run();
}
};
return (
<MarkdownCodeBlockFrame
as={NodeViewWrapper}
language={language || "text"}
fenceTitle={null}
theme={resolvedTheme}
headerProps={{ contentEditable: false }}
title={
<ComposerCodeBlockLanguagePicker
language={language}
theme={resolvedTheme}
disabled={!editor.isEditable}
onChange={changeLanguage}
/>
}
>
<div className="chat-markdown-shiki">
<pre className="max-w-full overflow-x-auto px-3 pt-1 pb-2">
{/* A caret needs a line to sit on even before any code is typed. */}
<NodeViewContent<"code">
as="code"
className="block min-h-[1lh] font-mono whitespace-pre-wrap text-inherit [overflow-wrap:anywhere]"
/>
</pre>
</div>
</MarkdownCodeBlockFrame>
);
}
@@ -0,0 +1,152 @@
import { Editor } from "@tiptap/core";
import type { EditorView } from "@tiptap/pm/view";
import StarterKit from "@tiptap/starter-kit";
import { afterEach, describe, expect, it, vi } from "vite-plus/test";
import { ComposerCodeBlockExtension } from "~/composer-rich-text-doc";
import type { DiffThemeName } from "~/lib/diffRendering";
import { getSyntaxHighlighterPromise } from "~/lib/syntaxHighlighting";
import {
composerCodeBlockHighlight,
MAX_HIGHLIGHTED_CODE_BLOCK_LENGTH,
shouldHighlightCodeBlock,
tokenizeBlock,
} from "./composerCodeBlockHighlight";
vi.mock("~/lib/syntaxHighlighting", () => ({ getSyntaxHighlighterPromise: vi.fn() }));
const THEME = "github-dark" as DiffThemeName;
/**
* Stands in for the Shiki highlighter so the offset arithmetic can be checked
* without loading a real grammar. Splits each line into whitespace-delimited
* tokens, which is enough shape for the flattening logic under test.
*/
function fakeHighlighter(colorFor: (content: string) => string | undefined) {
return {
codeToTokens(code: string) {
return {
tokens: code.split(/\r?\n/).map((line) =>
line
.split(/(\s+)/)
.filter((part) => part.length > 0)
.map((content) => ({ content, color: colorFor(content) })),
),
};
},
} as unknown as Parameters<typeof tokenizeBlock>[0];
}
describe("composer code block highlighting", () => {
it("maps token offsets to positions within the block text", () => {
const highlighter = fakeHighlighter((content) => (content === "const" ? "#ff0000" : undefined));
const decorations = tokenizeBlock(highlighter, "const answer = 42", "ts", THEME);
expect(decorations).toEqual([{ from: 0, to: 5, color: "#ff0000" }]);
});
it("accounts for the newline between lines", () => {
const highlighter = fakeHighlighter((content) => (content === "two" ? "#00ff00" : undefined));
const decorations = tokenizeBlock(highlighter, "one\ntwo", "ts", THEME);
// "one" is 3 characters, then the newline, so "two" starts at 4.
expect(decorations).toEqual([{ from: 4, to: 7, color: "#00ff00" }]);
});
it("accounts for both characters of a CRLF line break", () => {
const highlighter = fakeHighlighter((content) => (content === "two" ? "#00ff00" : undefined));
const decorations = tokenizeBlock(highlighter, "one\r\ntwo", "ts", THEME);
expect(decorations).toEqual([{ from: 5, to: 8, color: "#00ff00" }]);
});
it("skips whitespace-only tokens so indentation is not decorated", () => {
const highlighter = fakeHighlighter(() => "#0000ff");
const decorations = tokenizeBlock(highlighter, " indented", "ts", THEME);
expect(decorations).toEqual([{ from: 2, to: 10, color: "#0000ff" }]);
});
it("falls back to plain text when the grammar throws", () => {
const throwing = {
codeToTokens() {
throw new Error("unsupported language");
},
} as unknown as Parameters<typeof tokenizeBlock>[0];
expect(tokenizeBlock(throwing, "const answer = 42", "nope", THEME)).toEqual([]);
});
});
describe("the highlighting size cap", () => {
// Each keystroke re-tokenizes the whole fence on the main thread; past a
// few hundred lines that stalls typing, so large fences stay plain.
it("highlights a fence up to the cap", () => {
expect(shouldHighlightCodeBlock("x".repeat(MAX_HIGHLIGHTED_CODE_BLOCK_LENGTH))).toBe(true);
});
it("leaves a fence past the cap plain", () => {
expect(shouldHighlightCodeBlock("x".repeat(MAX_HIGHLIGHTED_CODE_BLOCK_LENGTH + 1))).toBe(false);
});
});
describe("a highlighter that fails to load", () => {
afterEach(() => {
vi.unstubAllGlobals();
});
/**
* Shiki can fail to initialize at all. The blocks it could not reach stay
* plain, the ones it could are still painted, and nothing is left rejected.
*/
it("still repaints the blocks whose highlighter loaded", async () => {
vi.mocked(getSyntaxHighlighterPromise).mockImplementation((language) =>
language === "ts"
? Promise.resolve(fakeHighlighter(() => "#ff0000"))
: Promise.reject(new Error("Shiki failed to initialize")),
);
const editor = new Editor({
extensions: [
StarterKit.configure({ codeBlock: false, trailingNode: false }),
ComposerCodeBlockExtension,
composerCodeBlockHighlight({ resolveTheme: () => THEME }),
],
content: {
type: "doc",
content: [
{ type: "codeBlock", attrs: { language: "ts" }, content: [{ type: "text", text: "a" }] },
{ type: "codeBlock", attrs: { language: "py" }, content: [{ type: "text", text: "b" }] },
],
},
});
// The plugin watches <html> for theme changes; the unit suite has no DOM.
vi.stubGlobal("document", { documentElement: {} });
vi.stubGlobal(
"MutationObserver",
class {
observe() {}
disconnect() {}
},
);
// ProseMirror names each plugin after its key, though it does not type it.
const plugin = editor.extensionManager.plugins.find((candidate) =>
(candidate as unknown as { key: string }).key.startsWith("composerCodeBlockHighlight"),
);
const repainted = new Promise<void>((resolve) => {
const view = {
get state() {
return editor.state;
},
dispatch: () => resolve(),
} as unknown as EditorView;
plugin?.spec.view?.(view);
});
await expect(repainted).resolves.toBeUndefined();
});
});
@@ -0,0 +1,231 @@
import { Extension } from "@tiptap/core";
import { type EditorState, Plugin, PluginKey } from "@tiptap/pm/state";
import { Decoration, DecorationSet } from "@tiptap/pm/view";
import type { Node as ProseMirrorNode } from "@tiptap/pm/model";
import type { DiffThemeName } from "~/lib/diffRendering";
import { languageOfInfoString } from "~/composer-code-languages";
import { getSyntaxHighlighterPromise } from "~/lib/syntaxHighlighting";
interface HighlightedBlock {
/** Guards against repainting a block whose text and language are unchanged. */
readonly signature: string;
readonly decorations: ReadonlyArray<{ from: number; to: number; color: string }>;
}
const composerCodeBlockHighlightKey = new PluginKey<DecorationSet>("composerCodeBlockHighlight");
/**
* Past this many characters a fence is left plain. Any edit changes a block's
* signature, so each keystroke re-tokenizes the whole block synchronously on
* the main thread: a few milliseconds for a couple of hundred lines, but ~80ms
* at a thousand, which stalls typing. 20k characters is roughly 400–500 lines
* of ordinary code; a fence that shrinks back under it is highlighted again.
*/
export const MAX_HIGHLIGHTED_CODE_BLOCK_LENGTH = 20_000;
export function shouldHighlightCodeBlock(code: string): boolean {
return code.length <= MAX_HIGHLIGHTED_CODE_BLOCK_LENGTH;
}
function blockSignature(node: ProseMirrorNode, theme: DiffThemeName): string {
// A separator that cannot occur in a language name keeps the parts distinct.
return [theme, String(node.attrs.language ?? ""), node.textContent].join("\u0000");
}
/**
* The composer's code blocks, which are always top-level: list items and
* quotes cannot hold one. Scanning only the top level keeps a keystroke in a
* long draft from walking every node in it.
*/
function collectCodeBlocks(state: EditorState): Array<{ node: ProseMirrorNode; pos: number }> {
const blocks: Array<{ node: ProseMirrorNode; pos: number }> = [];
state.doc.forEach((node, pos) => {
if (node.type.name === "codeBlock") blocks.push({ node, pos });
});
return blocks;
}
/**
* Highlights composer code blocks with the same Shiki instance the chat view
* uses, painted as inline decorations so the text nodes stay editable.
*
* Highlighting is asynchronous and per block: a keystroke re-tokenizes only the
* block that changed, and only after its highlighter has resolved. Blocks whose
* text and language are unchanged reuse their previous decorations.
*/
export function composerCodeBlockHighlight(options: {
resolveTheme: () => DiffThemeName;
}): Extension {
return Extension.create({
name: "composerCodeBlockHighlight",
addProseMirrorPlugins() {
// Every keystroke in a code block mints a new signature, so each scan
// drops the signatures the document no longer holds. The cache is then
// bounded by the document itself, and no block it holds is ever evicted.
const cache = new Map<string, HighlightedBlock>();
// The latest scan's signatures, so a tokenize that resolves after its
// block was edited away does not put it back.
let live = new Set<string>();
return [
new Plugin<DecorationSet>({
key: composerCodeBlockHighlightKey,
state: {
init: () => DecorationSet.empty,
apply(transaction, value, _oldState, newState) {
if (!transaction.docChanged && !transaction.getMeta(composerCodeBlockHighlightKey)) {
return value.map(transaction.mapping, transaction.doc);
}
return buildDecorations(newState, cache, options.resolveTheme());
},
},
props: {
decorations(state) {
return composerCodeBlockHighlightKey.getState(state);
},
},
view(view) {
let disposed = false;
let paintedTheme = options.resolveTheme();
let scannedDoc: ProseMirrorNode | null = null;
/**
* Tokenizes any block missing from the cache, then repaints once.
* Returning early when nothing is pending is what stops the
* dispatch below from re-triggering this on its own update.
*/
const refresh = () => {
const theme = options.resolveTheme();
const themeChanged = theme !== paintedTheme;
paintedTheme = theme;
// A selection change cannot alter what needs tokenizing, and
// building a signature means concatenating every block's text.
if (!themeChanged && view.state.doc === scannedDoc) return;
scannedDoc = view.state.doc;
const blocks = collectCodeBlocks(view.state);
live = new Set(blocks.map(({ node }) => blockSignature(node, theme)));
for (const signature of cache.keys()) {
if (!live.has(signature)) cache.delete(signature);
}
const pending = blocks.filter(
({ node }) =>
shouldHighlightCodeBlock(node.textContent) &&
!cache.has(blockSignature(node, theme)),
);
if (pending.length === 0) {
// A theme switch keeps every signature but changes which one
// applies, so the painted decorations still have to be rebuilt.
if (themeChanged) {
view.dispatch(view.state.tr.setMeta(composerCodeBlockHighlightKey, true));
}
return;
}
// Settled rather than all: a block whose highlighter fails to
// load stays plain, and the others are still painted.
void Promise.allSettled(
pending.map(async ({ node }) => {
// The stored info string keeps everything after the language
// (`js title=x`); Shiki wants only the name.
const language =
languageOfInfoString(String(node.attrs.language ?? "")) || "text";
const signature = blockSignature(node, theme);
const highlighter = await getSyntaxHighlighterPromise(language);
if (disposed || cache.has(signature) || !live.has(signature)) return;
cache.set(signature, {
signature,
decorations: tokenizeBlock(highlighter, node.textContent, language, theme),
});
}),
).then(() => {
if (disposed) return;
view.dispatch(view.state.tr.setMeta(composerCodeBlockHighlightKey, true));
});
};
refresh();
// The theme lives on <html>, outside the editor, so nothing would
// otherwise tell the view a repaint is due.
const themeObserver = new MutationObserver(refresh);
themeObserver.observe(document.documentElement, {
attributeFilter: ["class"],
});
return {
update: refresh,
destroy() {
disposed = true;
themeObserver.disconnect();
},
};
},
}),
];
},
});
}
type Highlighter = Awaited<ReturnType<typeof getSyntaxHighlighterPromise>>;
/** Flattens Shiki's line/token structure into offsets within the block's text. */
export function tokenizeBlock(
highlighter: Highlighter,
code: string,
language: string,
theme: DiffThemeName,
): ReadonlyArray<{ from: number; to: number; color: string }> {
let tokens;
try {
tokens = highlighter.codeToTokens(code, { lang: language, theme }).tokens;
} catch {
// An unsupported language should read as plain text, not break the editor.
return [];
}
const decorations: Array<{ from: number; to: number; color: string }> = [];
let offset = 0;
for (const [lineIndex, line] of tokens.entries()) {
// The separator between lines, which Shiki drops; CRLF is two characters.
if (lineIndex > 0) offset += code.startsWith("\r\n", offset) ? 2 : 1;
for (const token of line) {
const length = token.content.length;
if (token.color && token.content.trim()) {
decorations.push({ from: offset, to: offset + length, color: token.color });
}
offset += length;
}
}
return decorations;
}
function buildDecorations(
state: EditorState,
cache: Map<string, HighlightedBlock>,
theme: DiffThemeName,
): DecorationSet {
const decorations: Decoration[] = [];
for (const { node, pos } of collectCodeBlocks(state)) {
if (!shouldHighlightCodeBlock(node.textContent)) continue;
const highlighted = cache.get(blockSignature(node, theme));
if (!highlighted) continue;
// Token offsets index the block's text, which lines up with document
// positions only because `codeBlock` is `text*` with no marks — one
// unmarked text node, so `content.size === textContent.length`. Allowing
// marks or hard breaks in the code block would desync these silently.
if (node.content.size !== node.textContent.length) continue;
// +1 steps past the code block's opening token into its text.
const start = pos + 1;
for (const decoration of highlighted.decorations) {
decorations.push(
Decoration.inline(start + decoration.from, start + decoration.to, {
style: `color:${decoration.color}`,
}),
);
}
}
return DecorationSet.create(state.doc, decorations);
}
@@ -0,0 +1,126 @@
import { Editor } from "@tiptap/core";
import { TextSelection } from "@tiptap/pm/state";
import StarterKit from "@tiptap/starter-kit";
import { describe, expect, it } from "vite-plus/test";
import {
buildDocJson,
ComposerBlockExtensions,
ComposerCodeBlockExtension,
ComposerListExtensions,
ComposerTaskItemExtension,
ComposerTaskListExtension,
serializeEditorDoc,
} from "./composer-rich-text-doc";
// The same modifier ProseMirror's keymap reads "Mod" as.
const mac = typeof navigator !== "undefined" && /Mac|iP(hone|[oa]d)/.test(navigator.platform);
/** A key chord as the browser reports it: key, keyCode and modifiers. */
function chord(spec: string) {
const parts = spec.split("-");
const key = parts.pop()!;
const has = (name: string) => parts.includes(name);
const base = key.length === 1 ? key.toUpperCase() : key;
return {
key: has("Shift") && /^\d$/.test(key) ? "!@#$%^&*("[Number(key) - 1]! : key,
keyCode: base.length === 1 ? base.charCodeAt(0) : 0,
shiftKey: has("Shift"),
altKey: has("Alt"),
metaKey: has("Mod") && mac,
ctrlKey: has("Mod") && !mac,
preventDefault() {},
stopPropagation() {},
} as unknown as KeyboardEvent;
}
/**
* Presses `spec` with the caret inside `value`, the way the composer's
* editor would receive it, and returns the stored Markdown.
*/
function press(value: string, spec: string) {
const editor = new Editor({
extensions: [
StarterKit.configure({
blockquote: false,
bulletList: false,
codeBlock: false,
heading: false,
horizontalRule: false,
listItem: false,
orderedList: false,
trailingNode: false,
}),
ComposerCodeBlockExtension,
...ComposerBlockExtensions,
...ComposerListExtensions,
ComposerTaskListExtension,
ComposerTaskItemExtension,
],
content: buildDocJson(value, (name) => ({ label: name, description: null })),
});
editor.view.dispatch(editor.state.tr.setSelection(TextSelection.atEnd(editor.state.doc)));
// What the view's `someProp("handleKeyDown")` does, without mounting one:
// offer the key to each extension plugin in order until one handles it.
// An unmounted editor's state does not carry them yet, so they come from
// the extension manager.
const event = chord(spec);
const before = editor.state.doc;
const handled = editor.extensionManager.plugins.some((plugin) =>
plugin.props.handleKeyDown?.call(plugin, editor.view, event),
);
return {
handled,
changed: !editor.state.doc.eq(before),
value: serializeEditorDoc(editor.state.doc).value,
};
}
// Tiptap's own block shortcuts would nest a list, task list, code block or
// heading inside a quote, or restructure a list item. The serializers only
// write what the composer's grammar has, so the nested block, and the text
// in it, would vanish from the stored draft. None of these are the
// composer's shortcuts; they must do nothing.
const BLOCK_CHORDS = [
"Mod-Shift-8",
"Mod-Shift-7",
"Mod-Shift-9",
"Mod-Shift-b",
"Mod-Alt-c",
"Mod-Alt-1",
"Mod-Alt-3",
];
describe("Tiptap's block shortcuts", () => {
it.each(BLOCK_CHORDS)("leave a quote's text alone on %s", (spec) => {
expect(press("> keep this text", spec).value).toBe("> keep this text");
});
it.each(BLOCK_CHORDS)("leave a list item alone on %s", (spec) => {
expect(press("- item", spec).value).toBe("- item");
});
it.each(BLOCK_CHORDS)("leave a paragraph alone on %s", (spec) => {
expect(press("plain text", spec).value).toBe("plain text");
});
// Guards the harness itself: a chord the composer keeps must still reach
// the keymap, or every case above would pass without pressing anything.
it("still delivers the composer's own keys", () => {
expect(press("**bold**", "Mod-b").handled).toBe(true);
});
// Sinking or lifting an item moves it without touching its `indent`, so
// the stored draft keeps the old nesting and the next rebuild undoes the
// move. Nesting belongs to the composer's own Tab, which edits the source.
it.each([
["- p\n- a", "Tab"],
["- p\n - a", "Shift-Tab"],
["- [ ] p\n- [ ] a", "Tab"],
["- [ ] p\n - [ ] a", "Shift-Tab"],
])("leave the nesting of %j alone on %s", (value, spec) => {
const result = press(value, spec);
expect(result.changed).toBe(false);
expect(result.value).toBe(value);
});
});
+391
View File
@@ -0,0 +1,391 @@
import { describe, expect, it } from "vite-plus/test";
import { Editor, Node } from "@tiptap/core";
import { newlineInCode } from "@tiptap/pm/commands";
import { TextSelection } from "@tiptap/pm/state";
import {
CODE_BLOCK_INDENT,
indentCodeBlock,
indentLines,
convertCodeFenceOnEnter,
exitCodeBlockOnClosingFence,
exitCodeBlockOnTrailingBlankLines,
indentedNewlineInCodeBlock,
leadingWhitespace,
outdentLine,
} from "./composer-code-block";
import StarterKit from "@tiptap/starter-kit";
import {
ComposerCodeBlockExtension,
ComposerListExtensions,
serializeEditorDoc,
} from "./composer-rich-text-doc";
const extensions = [
StarterKit.configure({ codeBlock: false, trailingNode: false }),
ComposerCodeBlockExtension,
...ComposerListExtensions,
Node.create({
name: "composer-mention",
group: "inline",
inline: true,
atom: true,
addAttributes: () => ({ path: { default: "" }, source: { default: "" } }),
}),
];
describe("leadingWhitespace", () => {
it("reads the indent a new line should inherit", () => {
expect(leadingWhitespace(" nested()")).toBe(" ");
expect(leadingWhitespace("\tnested()")).toBe("\t");
expect(leadingWhitespace("flush()")).toBe("");
});
it("stops at the first non-space so code is never treated as indent", () => {
expect(leadingWhitespace(" a b")).toBe(" ");
});
});
describe("outdentLine", () => {
it("removes a full indent when there is one", () => {
expect(outdentLine(" deep")).toBe(" deep");
});
/** Hand-indented lines should still outdent rather than refuse to move. */
it("falls back to a single space or tab", () => {
expect(outdentLine(" odd")).toBe("odd");
expect(outdentLine("\ttabbed")).toBe("tabbed");
});
it("bottoms out instead of eating code", () => {
expect(outdentLine("flush()")).toBe("flush()");
});
});
describe("indentLines", () => {
it("indents every line it is given", () => {
expect(indentLines(["a", "b"], "in")).toEqual([
`${CODE_BLOCK_INDENT}a`,
`${CODE_BLOCK_INDENT}b`,
]);
});
/** Indenting a blank line would leave whitespace the user cannot see. */
it("leaves blank lines alone", () => {
expect(indentLines(["a", "", "b"], "in")).toEqual([
`${CODE_BLOCK_INDENT}a`,
"",
`${CODE_BLOCK_INDENT}b`,
]);
});
it("outdents every line it is given", () => {
expect(indentLines([" a", " b", "c"], "out")).toEqual([" a", "b", "c"]);
});
});
/** Builds an editor holding a single fenced block, with the caret placed by offset. */
function codeEditor(code: string, at?: { from: number; to?: number }) {
const editor = new Editor({
extensions,
content: {
type: "doc",
content: [{ type: "codeBlock", content: [{ type: "text", text: code }] }],
},
});
const start = 1;
const from = start + (at?.from ?? code.length);
const to = start + (at?.to ?? at?.from ?? code.length);
editor.view.dispatch(
editor.state.tr.setSelection(TextSelection.create(editor.state.doc, from, to)),
);
return editor;
}
const textOf = (editor: Editor) => editor.state.doc.textContent;
describe("indentedNewlineInCodeBlock", () => {
it("carries the current indentation onto the new line", () => {
const editor = codeEditor("function f() {\n body()");
const handled = indentedNewlineInCodeBlock(editor.state, (tr) => editor.view.dispatch(tr));
expect(handled).toBe(true);
expect(textOf(editor)).toBe("function f() {\n body()\n ");
});
/**
* With no indent to carry there is nothing to add, so the default newline
* should handle it and stay a single undo step.
*/
it("declines an unindented line", () => {
const editor = codeEditor("flush()");
expect(indentedNewlineInCodeBlock(editor.state, (tr) => editor.view.dispatch(tr))).toBe(false);
expect(textOf(editor)).toBe("flush()");
});
it("indents from the line the caret is on, not the last line", () => {
const editor = codeEditor(" deep()\nflush()", { from: 10 });
indentedNewlineInCodeBlock(editor.state, (tr) => editor.view.dispatch(tr));
expect(textOf(editor)).toBe(" deep()\n \nflush()");
});
it("replaces the selected text rather than keeping it", () => {
const editor = codeEditor(" keep()DROP", { from: 8, to: 12 });
indentedNewlineInCodeBlock(editor.state, (tr) => editor.view.dispatch(tr));
expect(textOf(editor)).toBe(" keep()\n ");
});
it("does nothing outside a code block", () => {
const editor = new Editor({
extensions,
content: {
type: "doc",
content: [{ type: "paragraph", content: [{ type: "text", text: " hi" }] }],
},
});
expect(indentedNewlineInCodeBlock(editor.state, (tr) => editor.view.dispatch(tr))).toBe(false);
});
});
/** Enter inside a fence, in the order the composer's key handler tries it. */
function pressEnter(editor: Editor) {
const dispatch = (tr: Parameters<typeof editor.view.dispatch>[0]) => editor.view.dispatch(tr);
return (
exitCodeBlockOnTrailingBlankLines(editor.view) ||
indentedNewlineInCodeBlock(editor.state, dispatch) ||
newlineInCode(editor.state, dispatch)
);
}
describe("exitCodeBlockOnTrailingBlankLines", () => {
it("leaves the block once two blank lines end it", () => {
const editor = codeEditor("flush()");
pressEnter(editor);
pressEnter(editor);
expect(editor.state.doc.childCount).toBe(1);
pressEnter(editor);
expect(editor.state.doc.firstChild?.textContent).toBe("flush()");
expect(editor.state.selection.$from.parent.type.name).toBe("paragraph");
});
/** Enter carries indentation, so the blank lines after nested code are not empty. */
it("counts lines holding only carried indentation as blank", () => {
const editor = codeEditor(" nested()");
pressEnter(editor);
pressEnter(editor);
expect(editor.state.doc.childCount).toBe(1);
pressEnter(editor);
expect(editor.state.doc.firstChild?.textContent).toBe(" nested()");
expect(editor.state.selection.$from.parent.type.name).toBe("paragraph");
});
/** An unclosed fence runs to the end of the draft, so leaving it must close it. */
it("closes an unclosed fence on the way out", () => {
const editor = codeEditor("flush()");
editor.view.dispatch(editor.state.tr.setNodeAttribute(0, "close", ""));
pressEnter(editor);
pressEnter(editor);
pressEnter(editor);
expect(editor.state.doc.firstChild?.attrs.close).toBe("\n```");
});
it("stays in the block when the caret is not at its end", () => {
const editor = codeEditor("a\n\n\nb", { from: 3 });
expect(exitCodeBlockOnTrailingBlankLines(editor.view)).toBe(false);
});
});
describe("exitCodeBlockOnClosingFence", () => {
const exit = (editor: Editor) =>
exitCodeBlockOnClosingFence(editor.state, (tr) => editor.view.dispatch(tr));
it("ends the block at a typed closing fence and starts a line after it", () => {
const editor = codeEditor("const a = 1\n```");
editor.view.dispatch(editor.state.tr.setNodeAttribute(0, "language", "ts"));
expect(exit(editor)).toBe(true);
editor.view.dispatch(editor.state.tr.insertText("explain this"));
expect(serializeEditorDoc(editor.state.doc).value).toBe(
"```ts\nconst a = 1\n```\nexplain this",
);
});
it("moves the lines after the fence out of the block", () => {
const editor = codeEditor("a\n```\nb", { from: "a\n```".length });
expect(exit(editor)).toBe(true);
expect(serializeEditorDoc(editor.state.doc).value).toBe("```\na\n```\n\nb");
expect(editor.state.selection.$from.parent.type.name).toBe("paragraph");
expect(editor.state.selection.$from.parent.textContent).toBe("");
});
it.each([
["a line that cannot close the fence", "a\n``", undefined],
["a caret before the end of the line", "a\n```", { from: "a\n``".length }],
])("ignores %s", (_, code, at) => {
expect(exit(codeEditor(code, at))).toBe(false);
});
});
describe("indentCodeBlock", () => {
it("inserts an indent at a collapsed caret", () => {
const editor = codeEditor("ab", { from: 1 });
expect(indentCodeBlock(editor.state, "in", (tr) => editor.view.dispatch(tr))).toBe(true);
expect(textOf(editor)).toBe(`a${CODE_BLOCK_INDENT}b`);
});
it("indents every line a selection touches", () => {
const editor = codeEditor("one\ntwo\nthree", { from: 1, to: 9 });
indentCodeBlock(editor.state, "in", (tr) => editor.view.dispatch(tr));
expect(textOf(editor)).toBe(" one\n two\n three");
});
/** A selection of whole lines ends at the start of the next one, which it does not touch. */
it("leaves the line a selection ends at the start of", () => {
const editor = codeEditor("one\ntwo", { from: 0, to: 4 });
indentCodeBlock(editor.state, "in", (tr) => editor.view.dispatch(tr));
expect(textOf(editor)).toBe(" one\ntwo");
});
it("outdents every line a selection touches", () => {
const editor = codeEditor(" one\n two", { from: 2, to: 9 });
indentCodeBlock(editor.state, "out", (tr) => editor.view.dispatch(tr));
expect(textOf(editor)).toBe("one\ntwo");
});
/** Repeated Tab presses should keep working on the same block. */
it("keeps the selection across the shifted lines", () => {
const editor = codeEditor("one\ntwo", { from: 0, to: 7 });
indentCodeBlock(editor.state, "in", (tr) => editor.view.dispatch(tr));
indentCodeBlock(editor.state, "in", (tr) => editor.view.dispatch(tr));
expect(textOf(editor)).toBe(" one\n two");
});
it("reports handled when outdenting can go no further, so Tab never escapes the editor", () => {
const editor = codeEditor("one\ntwo", { from: 0, to: 7 });
expect(indentCodeBlock(editor.state, "out", (tr) => editor.view.dispatch(tr))).toBe(true);
expect(textOf(editor)).toBe("one\ntwo");
});
it("does nothing outside a code block", () => {
const editor = new Editor({
extensions,
content: {
type: "doc",
content: [{ type: "paragraph", content: [{ type: "text", text: "hi" }] }],
},
});
expect(indentCodeBlock(editor.state, "in", (tr) => editor.view.dispatch(tr))).toBe(false);
});
});
describe("selections across two identical fences", () => {
/** Two structurally equal code blocks; the selection spans from one into the other. */
function twoBlockEditor() {
const block = { type: "codeBlock", content: [{ type: "text", text: " a" }] };
const editor = new Editor({ extensions, content: { type: "doc", content: [block, block] } });
// First block: 1..4 (text " a" occupies 1..4); second block starts at 5.
editor.view.dispatch(
editor.state.tr.setSelection(TextSelection.create(editor.state.doc, 2, 7)),
);
return editor;
}
it("leaves Tab and Enter alone rather than editing through the boundary", () => {
const editor = twoBlockEditor();
const before = editor.getJSON();
expect(indentCodeBlock(editor.state, "in", (tr) => editor.view.dispatch(tr))).toBe(false);
expect(indentedNewlineInCodeBlock(editor.state, (tr) => editor.view.dispatch(tr))).toBe(false);
expect(editor.getJSON()).toEqual(before);
});
});
describe("convertCodeFenceOnEnter", () => {
/** Builds an editor holding one paragraph with the caret at its end. */
function paragraphEditor(text: string) {
const editor = new Editor({
extensions,
content: { type: "doc", content: [{ type: "paragraph", content: [{ type: "text", text }] }] },
});
editor.view.dispatch(
editor.state.tr.setSelection(TextSelection.create(editor.state.doc, 1 + text.length)),
);
return editor;
}
it.each([
["```", "```", ""],
["```ts", "```", "ts"],
["~~~py", "~~~", "py"],
["````", "````", ""],
["```ts title=example", "```", "ts title=example"],
["``` js", "```", " js"],
])("turns %s into a code block", (text, fence, language) => {
const editor = paragraphEditor(text);
expect(convertCodeFenceOnEnter(editor.state, (tr) => editor.view.dispatch(tr))).toBe(true);
const block = editor.state.doc.firstChild!;
expect(block.type.name).toBe("codeBlock");
expect(block.attrs).toMatchObject({ fence, language, close: `\n${fence}` });
expect(block.textContent).toBe("");
// The caret belongs inside the new block, ready for the first line.
expect(editor.state.selection.from).toBe(1);
});
it.each(["``", "text ```", "```a`b"])("leaves %s alone", (text) => {
const editor = paragraphEditor(text);
expect(convertCodeFenceOnEnter(editor.state, (tr) => editor.view.dispatch(tr))).toBe(false);
});
it("refuses to open a fence inside a list item", () => {
const text = "```ts";
const editor = new Editor({
extensions,
content: {
type: "doc",
content: [
{
type: "bulletList",
content: [
{
type: "listItem",
content: [{ type: "paragraph", content: [{ type: "text", text }] }],
},
],
},
],
},
});
// Inside listItem > paragraph: position 3 is the paragraph start.
editor.view.dispatch(
editor.state.tr.setSelection(TextSelection.create(editor.state.doc, 3 + text.length)),
);
const before = editor.getJSON();
expect(convertCodeFenceOnEnter(editor.state, (tr) => editor.view.dispatch(tr))).toBe(false);
expect(editor.getJSON()).toEqual(before);
});
it("keeps a chip's source in the info string", () => {
const editor = new Editor({
extensions,
content: {
type: "doc",
content: [
{
type: "paragraph",
content: [
{ type: "text", text: "```ts " },
{ type: "composer-mention", attrs: { path: "a.md", source: "@a.md" } },
],
},
],
},
});
editor.view.dispatch(editor.state.tr.setSelection(TextSelection.atEnd(editor.state.doc)));
expect(convertCodeFenceOnEnter(editor.state, (tr) => editor.view.dispatch(tr))).toBe(true);
expect(editor.state.doc.firstChild?.attrs.language).toBe("ts @a.md");
});
it("ignores a fence with the caret before its end", () => {
const editor = paragraphEditor("```ts");
editor.view.dispatch(editor.state.tr.setSelection(TextSelection.create(editor.state.doc, 3)));
expect(convertCodeFenceOnEnter(editor.state, (tr) => editor.view.dispatch(tr))).toBe(false);
});
});
+254
View File
@@ -0,0 +1,254 @@
import { exitCode } from "@tiptap/pm/commands";
import type { EditorState, Transaction } from "@tiptap/pm/state";
import { TextSelection } from "@tiptap/pm/state";
import type { EditorView } from "@tiptap/pm/view";
import { isClosingFence, parseOpeningFence, serializeSelection } from "~/composer-rich-text-doc";
/**
* Spaces rather than a tab: the fence round-trips through Markdown on its way
* to the agent, and a literal tab there renders at whatever width the reader
* happens to use. Two matches how this repo indents its own source.
*/
export const CODE_BLOCK_INDENT = " ";
/** The leading run of spaces and tabs on a line, which Enter carries forward. */
export function leadingWhitespace(line: string): string {
return /^[ \t]*/.exec(line)?.[0] ?? "";
}
/**
* Removes one indent's worth of leading whitespace, tolerating lines that were
* indented by hand with an odd number of spaces or with tabs. A line with no
* leading whitespace is returned unchanged, so outdenting bottoms out quietly
* rather than eating the first character of code.
*/
export function outdentLine(line: string): string {
if (line.startsWith(CODE_BLOCK_INDENT)) return line.slice(CODE_BLOCK_INDENT.length);
if (line.startsWith("\t")) return line.slice(1);
if (line.startsWith(" ")) return line.slice(1);
return line;
}
/** Applies Tab/Shift+Tab to every line a selection touches, whole lines at a time. */
export function indentLines(lines: ReadonlyArray<string>, direction: "in" | "out"): string[] {
return lines.map((line) => {
// Indenting a blank line would leave trailing whitespace behind on a line
// the user cannot see the caret move on, so leave it be.
if (direction === "in") return line.length === 0 ? line : `${CODE_BLOCK_INDENT}${line}`;
return outdentLine(line);
});
}
/** Whether every endpoint of the selection sits in the same code block. */
export function selectionInOneCodeBlock(state: EditorState): boolean {
const { $from, $to } = state.selection;
return $from.parent.type.spec.code === true && $from.sameParent($to);
}
/**
* The code block containing the selection, or null when the selection is
* outside a fence or spans out of one. Both ends must sit in the same block: a
* selection that reaches past the fence belongs to the document, not to the
* code.
*/
function codeBlockRange(
state: EditorState,
): { readonly from: number; readonly to: number; readonly text: string } | null {
const { $from, $to } = state.selection;
const parent = $from.parent;
if (parent.type.spec.code !== true) return null;
// Same occurrence, not merely equal structure: two identical fences would
// otherwise let a selection across them edit through the block boundary.
if (!$from.sameParent($to)) return null;
const from = $from.start();
return { from, to: from + parent.content.size, text: parent.textContent };
}
/**
* Enter inside a fence, carrying the current line's indentation onto the new
* line. ProseMirror's default splits the text but starts the new line at column
* zero, which means re-typing the indent on every line of a nested block.
*/
export function indentedNewlineInCodeBlock(
state: EditorState,
dispatch?: (transaction: Transaction) => void,
): boolean {
const block = codeBlockRange(state);
if (!block) return false;
const { from, to } = state.selection;
const beforeCursor = block.text.slice(0, from - block.from);
const currentLine = beforeCursor.slice(beforeCursor.lastIndexOf("\n") + 1);
const indent = leadingWhitespace(currentLine);
// Nothing to carry, so let the default newline handle it and keep this path
// out of the undo history.
if (indent.length === 0) return false;
if (dispatch) {
const inserted = `\n${indent}`;
const transaction = state.tr.insertText(inserted, from, to);
const caret = from + inserted.length;
transaction.setSelection(TextSelection.create(transaction.doc, caret));
dispatch(transaction.scrollIntoView());
}
return true;
}
/**
* Two blank lines at the end of a fence leave it, the way every code editor
* does. Without this a fence at the end of the prompt is a trap: Enter only
* ever adds another line and there is no way back to prose. A line holding
* only the indentation Enter carried forward counts as blank, and is removed
* with the rest.
*/
export function exitCodeBlockOnTrailingBlankLines(view: EditorView): boolean {
const { $from, empty } = view.state.selection;
if (!empty || $from.parent.type.spec.code !== true) return false;
if ($from.parentOffset !== $from.parent.content.size) return false;
const trailing = /\n[ \t]*\n[ \t]*$/.exec($from.parent.textContent);
if (!trailing) return false;
const transaction = view.state.tr.delete($from.pos - trailing[0].length, $from.pos);
// An unclosed fence runs to the end of the draft; the prose after it would
// be read back as code, so leaving it writes the closing fence.
if (!$from.parent.attrs.close) {
transaction.setNodeAttribute($from.before(), "close", `\n${$from.parent.attrs.fence}`);
}
view.dispatch(transaction);
return exitCode(view.state, (tr) => view.dispatch(tr.scrollIntoView()));
}
/**
* Enter at the end of a line that would close the fence, such as ```` ``` ````
* typed under the code, ends the block there. That line becomes the closing
* fence, and any lines after it continue as paragraphs after a new empty one,
* which is how the stored draft reads them.
*/
export function exitCodeBlockOnClosingFence(
state: EditorState,
dispatch?: (transaction: Transaction) => void,
): boolean {
const block = codeBlockRange(state);
if (!block || !state.selection.empty) return false;
const caret = state.selection.from - block.from;
const lineStart = block.text.lastIndexOf("\n", caret - 1) + 1;
const newlineAfter = block.text.indexOf("\n", caret);
const lineEnd = newlineAfter === -1 ? block.text.length : newlineAfter;
const line = block.text.slice(lineStart, lineEnd);
const node = state.selection.$from.parent;
if (caret !== lineEnd || !isClosingFence(line, String(node.attrs.fence))) return false;
if (dispatch) {
const { schema } = state;
const paragraph = (text: string) =>
schema.nodes.paragraph!.create(null, text ? schema.text(text) : null);
const code = block.text.slice(0, Math.max(0, lineStart - 1));
const rest = newlineAfter === -1 ? [] : block.text.slice(newlineAfter + 1).split("\n");
const closed = node.type.create(
{ ...node.attrs, close: `\n${line}` },
code ? schema.text(code) : null,
);
const start = state.selection.$from.before();
const transaction = state.tr.replaceWith(start, start + node.nodeSize, [
closed,
paragraph(""),
...rest.map(paragraph),
]);
transaction.setSelection(TextSelection.create(transaction.doc, start + closed.nodeSize + 1));
dispatch(transaction.scrollIntoView());
}
return true;
}
/**
* Tab and Shift+Tab inside a fence. A collapsed cursor indents at the caret so
* Tab works mid-line the way typing does; any selection spanning text indents
* the whole lines it touches, which is what makes re-indenting a block possible.
*/
export function indentCodeBlock(
state: EditorState,
direction: "in" | "out",
dispatch?: (transaction: Transaction) => void,
): boolean {
const block = codeBlockRange(state);
if (!block) return false;
const { from, to } = state.selection;
const startOffset = from - block.from;
const endOffset = to - block.from;
if (from === to && direction === "in") {
if (dispatch) {
const transaction = state.tr.insertText(CODE_BLOCK_INDENT, from, to);
dispatch(transaction.scrollIntoView());
}
return true;
}
// Grow the range to whole lines so indenting is stable no matter where in the
// first and last lines the selection happens to start and end.
const lineStart = block.text.lastIndexOf("\n", Math.max(0, startOffset - 1)) + 1;
// A selection ending at the start of a line does not touch that line.
const newlineAfter = block.text.indexOf("\n", Math.max(startOffset, endOffset - 1));
const lineEnd = newlineAfter === -1 ? block.text.length : newlineAfter;
const originalLines = block.text.slice(lineStart, lineEnd).split("\n");
const nextLines = indentLines(originalLines, direction);
if (nextLines.join("\n") === originalLines.join("\n")) return true;
if (dispatch) {
const transaction = state.tr.insertText(
nextLines.join("\n"),
block.from + lineStart,
block.from + lineEnd,
);
// Keep the same lines selected after the shift, so repeated Tab presses
// keep indenting the block rather than collapsing the selection.
// `split` always yields at least one entry, so these stand in only for the
// compiler's benefit.
const firstDelta = (nextLines[0]?.length ?? 0) - (originalLines[0]?.length ?? 0);
const totalDelta = nextLines.join("\n").length - originalLines.join("\n").length;
const nextFrom = Math.max(block.from + lineStart, from + firstDelta);
const nextTo = Math.max(nextFrom, to + totalDelta);
transaction.setSelection(TextSelection.create(transaction.doc, nextFrom, nextTo));
dispatch(transaction.scrollIntoView());
}
return true;
}
/**
* Enter on a line that is nothing but an opening fence turns it into a code
* block. Tiptap's own input rules only fire on a space, so without this the
* gesture every markdown editor has — ```` ```ts ```` then Enter — leaves the
* fence as literal text.
*/
export function convertCodeFenceOnEnter(
state: EditorState,
dispatch?: (transaction: Transaction) => void,
): boolean {
const { $from, empty } = state.selection;
// Top-level paragraphs only: the list and quote serializers have no line
// to write a fence into, so one created inside them would vanish.
if (!empty || $from.parent.type.name !== "paragraph" || $from.depth !== 1) return false;
if ($from.parentOffset !== $from.parent.content.size) return false;
// The parser's own grammar, read from the line's stored source, so a line
// Enter turns into a fence is exactly one the stored draft reads back as a
// fence, info string and all, including any chip's source in it.
const opening = parseOpeningFence(serializeSelection(state.doc, $from.start(), $from.end()));
const codeBlock = state.schema.nodes.codeBlock;
if (!opening || !codeBlock) return false;
if (dispatch) {
const blockStart = $from.before();
const { fence, language } = opening;
const transaction = state.tr.replaceWith(
blockStart,
blockStart + $from.parent.nodeSize,
codeBlock.create({ language, fence, close: `\n${fence}` }),
);
transaction.setSelection(TextSelection.create(transaction.doc, blockStart + 1));
dispatch(transaction.scrollIntoView());
}
return true;
}
@@ -0,0 +1,59 @@
import { describe, expect, it } from "vite-plus/test";
import {
CODE_BLOCK_LANGUAGES,
codeLanguageLabel,
languageOfInfoString,
withInfoStringLanguage,
} from "./composer-code-languages";
describe("languageOfInfoString", () => {
it.each([
["", ""],
["ts", "ts"],
[" ts ", "ts"],
["js title=example", "js"],
["typescript ", "typescript"],
])("reads %j as %j", (info, language) => {
expect(languageOfInfoString(info)).toBe(language);
});
});
describe("withInfoStringLanguage", () => {
it.each([
["", "ts", "ts"],
["js", "python", "python"],
// Anything after the language belongs to the fence and stays put.
["js title=example", "ts", "ts title=example"],
["js {1,3}", "ts", "ts {1,3}"],
// Plain text clears the language...
["js", "", ""],
// ...but a bare `title=x` would read as the language, so it keeps `text`.
["js title=example", "", "text title=example"],
// Whitespace between the fence and the language is the user's formatting.
[" js title=x", "python", " python title=x"],
[" js title=x", "", " text title=x"],
[" js", "go", " go"],
[" ", "go", " go"],
])("sets %j to %j as %j", (info, language, expected) => {
expect(withInfoStringLanguage(info, language)).toBe(expected);
});
});
describe("codeLanguageLabel", () => {
it.each([
["", "Plain text"],
["text", "Plain text"],
["cpp", "C++"],
["ts", "TypeScript"],
["arduino", "arduino"],
])("labels %j as %j", (language, label) => {
expect(codeLanguageLabel(language)).toBe(label);
});
it("lists every language once, plain text first", () => {
const ids = CODE_BLOCK_LANGUAGES.map((language) => language.id);
expect(ids[0]).toBe("");
expect(new Set(ids).size).toBe(ids.length);
});
});
+97
View File
@@ -0,0 +1,97 @@
/**
* The languages a composer fence can be switched to from its header, and how
* a choice is written back into the fence's info string.
*
* Ids are the names the highlighter and the file icons both know. The list
* is curated rather than every grammar the highlighter bundles: a picker is
* for the common case, and any other language can still be typed on the
* fence line, where it shows as its own entry.
*/
export const CODE_BLOCK_LANGUAGES = [
{ id: "", label: "Plain text" },
{ id: "bash", label: "Bash" },
{ id: "c", label: "C" },
{ id: "cpp", label: "C++" },
{ id: "csharp", label: "C#" },
{ id: "css", label: "CSS" },
{ id: "dart", label: "Dart" },
{ id: "diff", label: "Diff" },
{ id: "dockerfile", label: "Dockerfile" },
{ id: "elixir", label: "Elixir" },
{ id: "go", label: "Go" },
{ id: "graphql", label: "GraphQL" },
{ id: "haskell", label: "Haskell" },
{ id: "html", label: "HTML" },
{ id: "java", label: "Java" },
{ id: "javascript", label: "JavaScript" },
{ id: "json", label: "JSON" },
{ id: "jsx", label: "JSX" },
{ id: "kotlin", label: "Kotlin" },
{ id: "lua", label: "Lua" },
{ id: "markdown", label: "Markdown" },
{ id: "php", label: "PHP" },
{ id: "powershell", label: "PowerShell" },
{ id: "python", label: "Python" },
{ id: "r", label: "R" },
{ id: "ruby", label: "Ruby" },
{ id: "rust", label: "Rust" },
{ id: "scala", label: "Scala" },
{ id: "scss", label: "SCSS" },
{ id: "sql", label: "SQL" },
{ id: "svelte", label: "Svelte" },
{ id: "swift", label: "Swift" },
{ id: "toml", label: "TOML" },
{ id: "tsx", label: "TSX" },
{ id: "typescript", label: "TypeScript" },
{ id: "vue", label: "Vue" },
{ id: "xml", label: "XML" },
{ id: "yaml", label: "YAML" },
{ id: "zig", label: "Zig" },
] as const;
export type CodeBlockLanguage = { readonly id: string; readonly label: string };
/** Short names people type on the fence line, labelled like the entry they mean. */
const LANGUAGE_ALIASES: Record<string, string> = {
cs: "csharp",
"c++": "cpp",
js: "javascript",
md: "markdown",
py: "python",
rb: "ruby",
rs: "rust",
sh: "bash",
shell: "bash",
ts: "typescript",
yml: "yaml",
};
/** The language is the info string's first word; the rest belongs to the fence. */
export function languageOfInfoString(info: string): string {
return info.trim().split(/\s+/, 1)[0] ?? "";
}
/**
* Replaces the language and keeps everything around it: the whitespace the
* fence had before it and whatever follows it. Plain text clears it, unless
* something follows: a bare `title=x` would read as the language, so that
* keeps `text` in front.
*/
export function withInfoStringLanguage(info: string, language: string): string {
const leading = /^\s*/.exec(info)![0];
// The language is the first word, so what follows it is empty or starts
// with whitespace.
const rest = info.slice(leading.length + languageOfInfoString(info).length);
if (language) return `${leading}${language}${rest}`;
return rest.trim() ? `${leading}text${rest}` : "";
}
/** The canonical entry a language names, if the picker lists it. */
export function codeLanguageEntry(language: string): CodeBlockLanguage | null {
const id = language === "text" ? "" : (LANGUAGE_ALIASES[language.toLowerCase()] ?? language);
return CODE_BLOCK_LANGUAGES.find((entry) => entry.id === id.toLowerCase()) ?? null;
}
export function codeLanguageLabel(language: string): string {
return codeLanguageEntry(language)?.label ?? language;
}
@@ -1,6 +1,10 @@
import { describe, expect, it } from "vite-plus/test";
import { listContinuationForEnter, listIndentForTab } from "./composer-list-continuation";
import {
listContinuationForEnter,
listIndentForTab,
nextOrderedMarkerText,
} 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);
@@ -66,3 +70,16 @@ describe("composer list continuation", () => {
expect(listIndentForTab("- foo", 1, 3)).toBeNull();
});
});
describe("nextOrderedMarkerText", () => {
it.each([
["1.", "2."],
["1)", "2)"],
["09.", "10."],
["001)", "002)"],
["99.", "100."],
["99999999999999999999.", "99999999999999999999."],
])("counts %s up to %s", (marker, expected) => {
expect(nextOrderedMarkerText(marker)).toBe(expected);
});
});
+16 -5
View File
@@ -55,13 +55,24 @@ function parseListMarker(line: string): { marker: ListMarker; markerEnd: number
return null;
}
/**
* The ordered marker that follows `3.` or `09)`: one higher, same delimiter,
* zero padding kept, and a number too large to count left as typed. Shared
* with the rich editor's native split so both modes count the same way.
*/
export function nextOrderedMarkerText(marker: string): string {
const numberText = marker.slice(0, -1);
const delimiter = marker.slice(-1);
const number = Number.parseInt(numberText, 10);
const next = Number.isSafeInteger(number)
? String(number + 1).padStart(numberText.length, "0")
: numberText;
return `${next}${delimiter}`;
}
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} `;
return `${marker.indent}${nextOrderedMarkerText(`${marker.numberText}${marker.delimiter}`)} `;
}
if (marker.kind === "task") {
return `${marker.indent}- [ ] `;
+265
View File
@@ -0,0 +1,265 @@
// @vitest-environment jsdom
import { Editor } from "@tiptap/core";
import { TaskList } from "@tiptap/extension-task-list";
import { TextSelection } from "@tiptap/pm/state";
import StarterKit from "@tiptap/starter-kit";
import { afterEach, describe, expect, it } from "vite-plus/test";
import {
backspaceAcrossList,
buildDocJson,
buildTiptapContent,
ComposerBlockExtensions,
ComposerCodeBlockExtension,
ComposerListExtensions,
ComposerTaskItemExtension,
convertBulletItemToTask,
deleteAcrossList,
serializeEditorDoc,
splitOrLiftListItem,
} from "./composer-rich-text-doc";
// ProseMirror's DOM observer can flush on a timer after a test ends, which
// throws once jsdom is torn down, so every editor is destroyed after its test.
const editors: Editor[] = [];
afterEach(() => {
for (const editor of editors.splice(0)) editor.destroy();
});
/**
* Splits the last item of `value` the way Shift+Enter does, types `b`, and
* returns the stored Markdown. Tiptap carries every attribute left at the
* default `keepOnSplit: true` onto the new item and merges the overrides on
* top, so the new item must keep the source marker, indent and spacing.
*/
function makeEditor(value: string) {
const editor = new Editor({
extensions: [
StarterKit.configure({
bulletList: false,
orderedList: false,
listItem: false,
codeBlock: false,
blockquote: false,
heading: false,
horizontalRule: false,
trailingNode: false,
listKeymap: false,
}),
...ComposerListExtensions,
TaskList,
ComposerTaskItemExtension,
ComposerCodeBlockExtension,
...ComposerBlockExtensions,
],
content: buildDocJson(value, (name) => ({ label: name, description: null })),
});
editors.push(editor);
return editor;
}
function splitLastItem(value: string, type: "listItem" | "taskItem", overrides: object) {
const editor = makeEditor(value);
editor.view.dispatch(editor.state.tr.setSelection(TextSelection.atEnd(editor.state.doc)));
editor.commands.splitListItem(type, overrides);
editor.view.dispatch(editor.state.tr.insertText("b"));
return serializeEditorDoc(editor.state.doc).value;
}
describe("splitting a list item", () => {
it.each([
["* a", { space: " " }, "* a\n* b"],
["+ a", { space: " " }, "+ a\n+ b"],
["- p\n - a", { space: " " }, "- p\n - a\n - b"],
["3) a", { marker: "4)", space: " " }, "3) a\n4) b"],
])("keeps the source marker and indent of %s", (value, overrides, expected) => {
expect(splitLastItem(value, "listItem", overrides)).toBe(expected);
});
it("keeps the indent of a nested task", () => {
expect(splitLastItem("- [ ] p\n - [ ] a", "taskItem", { checked: false })).toBe(
"- [ ] p\n - [ ] a\n - [ ] b",
);
});
});
/** Puts the caret `offset` characters into the first text node holding `text`. */
function placeCaret(editor: Editor, text: string, offset = 0) {
let caret = -1;
editor.state.doc.descendants((node, pos) => {
if (caret < 0 && node.isText && node.text!.includes(text)) {
caret = pos + node.text!.indexOf(text) + offset;
}
});
editor.view.dispatch(editor.state.tr.setSelection(TextSelection.create(editor.state.doc, caret)));
}
/** The stored draft, after checking a rebuild from it gives back the same document. */
function storedDraft(editor: Editor) {
const stored = serializeEditorDoc(editor.state.doc).value;
expect(makeEditor(stored).state.doc.toString()).toBe(editor.state.doc.toString());
return stored;
}
describe("Shift+Enter twice on an item", () => {
// The second Shift+Enter lifts the new empty item one level. The stored
// draft must write it at its new depth, so a rebuild from that draft gives
// back the document the user is looking at.
it.each([
["- a\n - x", "- a\n - x\n- b"],
["* a\n * x", "* a\n * x\n* b"],
["1. a\n 1. x", "1. a\n 1. x\n2. b"],
["- a\n - x\n- c", "- a\n - x\n- b\n- c"],
["- a\n - x\n - y", "- a\n - x\n- b\n - y"],
["- [ ] a\n - [ ] x", "- [ ] a\n - [ ] x\n- [ ] b"],
["- [x] a\n - [ ] x\n- [ ] c", "- [x] a\n - [ ] x\n- [ ] b\n- [ ] c"],
])("after x in %j writes %j", (value, expected) => {
const editor = makeEditor(value);
let caret = -1;
editor.state.doc.descendants((node, pos) => {
if (node.isText && node.text === "x") caret = pos + 1;
});
editor.view.dispatch(
editor.state.tr.setSelection(TextSelection.create(editor.state.doc, caret)),
);
expect(splitOrLiftListItem(editor)).toBe(true);
expect(splitOrLiftListItem(editor)).toBe(true);
editor.view.dispatch(editor.state.tr.insertText("b"));
const stored = serializeEditorDoc(editor.state.doc).value;
expect(stored).toBe(expected);
// Same nesting after a rebuild; spacing defaults may differ but write the same.
expect(makeEditor(stored).state.doc.toString()).toBe(editor.state.doc.toString());
});
});
describe("Shift+Enter in the middle of an ordered list", () => {
it.each([
["1. a\n2. x\n3. c\n4. d", "1. a\n2. x\n3. b\n4. c\n5. d"],
["1) a\n2) x\n3) c", "1) a\n2) x\n3) b\n4) c"],
["1. a\n 1. x\n 2. c\n2. d", "1. a\n 1. x\n 2. b\n 3. c\n2. d"],
])("after x in %j writes %j", (value, expected) => {
const editor = makeEditor(value);
placeCaret(editor, "x", 1);
expect(splitOrLiftListItem(editor)).toBe(true);
editor.view.dispatch(editor.state.tr.insertText("b"));
expect(storedDraft(editor)).toBe(expected);
});
});
describe("Shift+Enter on an empty task under a bullet", () => {
// There is no task list one level up to move it into, and the item cannot
// hold a second line, so the draft stays what the editor shows.
it.each(["- a\n - [ ] x", "- [ ] a\n - x"])("in %j keeps the draft honest", (value) => {
const editor = makeEditor(value);
placeCaret(editor, "x", 1);
splitOrLiftListItem(editor);
splitOrLiftListItem(editor);
storedDraft(editor);
});
});
describe("Backspace at the start of a line", () => {
it.each([
["- a\n - x", "x", "- a\n- x"],
["- a\n - x\n - y", "x", "- a\n- x\n - y"],
["- [ ] a\n - [ ] x", "x", "- [ ] a\n- [ ] x"],
["- a\n- b\n- c", "b", "- a\nb\n- c"],
// A task under a bullet has no task list to move into, so it joins up.
["- a\n - [ ] x", "x", "- ax"],
["- a\n - x\nb", "b", "- a\n - xb"],
["1. a\nb", "b", "1. ab"],
])("in %j at %s writes %j", (value, at, expected) => {
const editor = makeEditor(value);
placeCaret(editor, at);
expect(backspaceAcrossList(editor)).toBe(true);
expect(storedDraft(editor)).toBe(expected);
});
it.each([
["- a\n```\nl1\nl2\n```", "- a\nl1\nl2"],
["p\n```ts\nl1\n```", "p\nl1"],
])("removes the fence of %j rather than joining its code up", (value, expected) => {
const editor = makeEditor(value);
placeCaret(editor, "l1");
editor.commands.keyboardShortcut("Backspace");
expect(storedDraft(editor)).toBe(expected);
});
});
describe("Delete at the end of a line", () => {
it.each([
["- a\n- b", "- ab"],
["- a\n - x\n- c", "- ax\n- c"],
["- a\n\nb", "- a\nb"],
])("in %j writes %j", (value, expected) => {
const editor = makeEditor(value);
placeCaret(editor, "a", 1);
expect(deleteAcrossList(editor)).toBe(true);
expect(storedDraft(editor)).toBe(expected);
});
it.each(["- a\n```\nl1\n```", "a\n```\nl1\n```"])("leaves the fence in %j alone", (value) => {
const editor = makeEditor(value);
placeCaret(editor, "a", 1);
editor.commands.keyboardShortcut("Delete");
expect(storedDraft(editor)).toBe(value);
});
});
describe("blocks that a list item or quote cannot hold", () => {
it("puts lines pasted at the end of an item after the list", () => {
const editor = makeEditor("- a");
editor.view.dispatch(editor.state.tr.setSelection(TextSelection.atEnd(editor.state.doc)));
const lines = buildTiptapContent("one\ntwo", (name) => ({ label: name, description: null }));
editor.commands.insertContent(lines);
expect(storedDraft(editor)).toBe("- a\none\ntwo");
});
it("will not make a task list inside a quote", () => {
const editor = makeEditor("> q");
placeCaret(editor, "q");
expect(editor.commands.wrapInList("taskList")).toBe(false);
expect(storedDraft(editor)).toBe("> q");
});
});
describe("[ ] typed at the start of a bullet item", () => {
// The value holds `[ ]` already; the rule fires on the space after it.
it.each([
["* [ ]x", "- [ ] x"],
["* a\n* [ ]x\n* c", "* a\n- [ ] x\n* c"],
["- a\n * [ ]x", "- a\n - [ ] x"],
["- a\n - [ ]x\n - y", "- a\n - [ ] x\n - y"],
["- [ ]x\n - y", "- [ ] x\n - y"],
["- [ ]x", "- [ ] x"],
])("makes the item in %j a task where it stands", (value, expected) => {
const editor = makeEditor(value);
placeCaret(editor, "[ ]x");
const from = editor.state.selection.from;
editor.view.dispatch(
editor.state.tr.setSelection(TextSelection.create(editor.state.doc, from + 3)),
);
const { tr } = editor.state;
convertBulletItemToTask(tr, from, from + 3, false);
editor.view.dispatch(tr);
expect(editor.state.selection.$from.parent.textContent).toBe("x");
expect(editor.state.selection.$from.parentOffset).toBe(0);
expect(storedDraft(editor)).toBe(expected);
});
});
describe("a rule at the end of the draft", () => {
it("keeps an empty line after it to type on", () => {
const editor = makeEditor("a\n---");
// Removing the line after the rule puts one straight back.
editor.view.dispatch(
editor.state.tr.delete(editor.state.doc.content.size - 2, editor.state.doc.content.size),
);
expect(editor.state.doc.lastChild?.type.name).toBe("paragraph");
expect(storedDraft(editor)).toBe("a\n---");
editor.view.dispatch(editor.state.tr.setSelection(TextSelection.atEnd(editor.state.doc)));
editor.view.dispatch(editor.state.tr.insertText("b"));
expect(storedDraft(editor)).toBe("a\n---\nb");
});
});
+529
View File
@@ -5,9 +5,15 @@ import { Node as ProseMirrorNode } from "@tiptap/pm/model";
import { EditorState, TextSelection } from "@tiptap/pm/state";
import { describe, expect, it } from "vite-plus/test";
import { collapseExpandedComposerCursor } from "./composer-logic";
import {
buildDocJson,
buildTiptapContent,
caretTakesMarksBefore,
ComposerBlockExtensions,
ComposerCodeBlockExtension,
ComposerListExtensions,
collapsedToFlat,
ComposerCodeExtension,
ComposerTaskItemExtension,
@@ -16,6 +22,7 @@ import {
flatToPm,
pmToFlat,
serializeEditorDoc,
serializeSelection,
stepCaretAcrossStyledEdge,
} from "./composer-rich-text-doc";
@@ -64,6 +71,9 @@ const schema = getSchemaByResolvedExtensions(
}),
TaskList,
ComposerTaskItemExtension,
ComposerCodeBlockExtension,
...ComposerListExtensions,
...ComposerBlockExtensions,
]),
);
@@ -344,6 +354,437 @@ describe("composer rich text document model", () => {
expect(roundTripPlain(value).value).toBe(value);
});
it.each([
"- one\n- two",
"* star\n* star two",
"+ plus",
"* star\n+ plus",
"1. first\n2. second",
"1) paren\n2) paren",
"3. starts at three\n4. four",
"01. zero padded\n02. two",
"- parent\n - child\n - sibling\n- uncle",
"1. ordered\n - bullet child\n2. next",
"- outer\n 1. inner ordered\n 2. more\n- outer again",
"- wide space item",
"-",
"1.",
"- \n- second",
"- **bold** item with @README.md",
"- [ ] task\n- bullet after",
"- bullet\n- [x] task after",
"para\n- item\npara",
"\t- tab indented\n\t- again",
" - leading indent only",
"- item\n\n- after a blank",
"- item one\n```ts\ncode\n```\n- item two",
"-no space stays literal",
"1.no space stays literal",
"10. ten\n11. eleven",
])("round-trips the list %s through a real ProseMirror document", (value) => {
expect(roundTrip(value).value).toBe(value);
});
it.each([
"- one\n- two",
"1. first\n2. second",
"- parent\n - child",
"* star\n+ plus",
"-no space stays literal",
])("keeps the list %s literal in plain mode", (value) => {
expect(roundTripPlain(value).value).toBe(value);
});
it.each(["- one\n- two", "1. a\n - b\n2. c", "- **bold** @README.md tail", "-"])(
"maps every document offset of the list %s through collapsed coordinates and back",
(value) => {
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("clamps offsets inside a list marker to the start of the item text", () => {
const value = "- item";
const map = roundTrip(value);
// The marker owns no document characters, like a checkbox.
for (let collapsed = 0; collapsed <= "- ".length; collapsed += 1) {
expect(collapsedToFlat(map, collapsed)).toBe(0);
}
expect(collapsedToFlat(map, "- it".length)).toBe(2);
expect(flatToCollapsed(map, 0)).toBe("- ".length);
});
it.each([
"> quoted",
"> line one\n> line two",
">no space",
"> two spaces",
"> a\n>b",
">",
"> **bold** and @README.md inside",
"> - looks like a list but stays quote text",
"> > nested stays literal inside the quote",
"before\n> quoted\nafter",
"> quote\n\n> another",
"- item\n> quote after list",
])("round-trips the quote %s through a real ProseMirror document", (value) => {
expect(roundTrip(value).value).toBe(value);
});
it.each([
"---",
"***",
"___",
"- - -",
"* * *",
"-----",
"--- ",
"text\n---\nmore",
"- item\n---\n- item two",
"```\n---\n```",
"--",
"-- -",
"---text",
])("round-trips the rule %s through a real ProseMirror document", (value) => {
expect(roundTrip(value).value).toBe(value);
});
it("parses rules ahead of lists and emphasis", () => {
const json = buildDocJson("- - -\n***\n___\ntext\n---\n- item", (n) => ({
label: n,
description: null,
}));
expect(json.content.map((block) => block.type)).toEqual([
"horizontalRule",
"horizontalRule",
"horizontalRule",
"paragraph",
"horizontalRule",
"bulletList",
]);
});
it.each([
"# Heading",
"## Two",
"###### Six",
"####### seven hashes stays a paragraph",
"# two spaces",
"#\tTab",
"# Trailing hashes stay literal #",
"#1234",
"#1234 is a pull request, not a heading",
"# Heading with **bold** and @README.md",
"#",
"# ",
"text\n# Heading\ntext",
"# Heading\n- item\n> quote\n---",
])("round-trips the heading %s through a real ProseMirror document", (value) => {
expect(roundTrip(value).value).toBe(value);
});
it.each(["> quoted", "> a\n>b", "---", "- - -", "# Heading", "#1234"])(
"keeps the block %s literal in plain mode",
(value) => {
expect(roundTripPlain(value).value).toBe(value);
},
);
it("parses the blocks it renders as the right node types", () => {
const json = buildDocJson("# Title\n> quote\n---\n#1234 ref\n- - -", (n) => ({
label: n,
description: null,
}));
expect(json.content.map((block) => block.type)).toEqual([
"heading",
"blockquote",
"horizontalRule",
"paragraph",
"horizontalRule",
// The empty line a final rule keeps for the caret.
"paragraph",
]);
});
it.each([
["---", "---"],
["a\n---", "a\n---"],
// That line and a trailing newline are the same document; the newline goes.
["---\n", "---"],
])("gives the caret a line after the final rule of %j, written %j", (value, expected) => {
const map = roundTrip(value);
expect(map.value).toBe(expected);
const json = buildDocJson(value, () => ({ label: "", description: null }));
const doc = ProseMirrorNode.fromJSON(schema, json);
expect(doc.resolve(flatToPm(map, map.docLength)).parent.isTextblock).toBe(true);
});
it("parses rules ahead of lists and emphasis", () => {
const json = buildDocJson("- - -\n***\n___\ntext\n---\n- item", (n) => ({
label: n,
description: null,
}));
expect(json.content.map((block) => block.type)).toEqual([
"horizontalRule",
"horizontalRule",
"horizontalRule",
"paragraph",
"horizontalRule",
"bulletList",
]);
});
it.each([
"# Heading",
"## Two",
"###### Six",
"####### seven hashes stays a paragraph",
"# two spaces",
"#\tTab",
"# Trailing hashes stay literal #",
"#1234",
"#1234 is a pull request, not a heading",
"# Heading with **bold** and @README.md",
"#",
"# ",
"text\n# Heading\ntext",
"# Heading\n- item\n> quote\n---",
])("round-trips the heading %s through a real ProseMirror document", (value) => {
expect(roundTrip(value).value).toBe(value);
});
it.each(["> quoted", "> a\n>b", "---", "- - -", "# Heading", "#1234"])(
"keeps the block %s literal in plain mode",
(value) => {
expect(roundTripPlain(value).value).toBe(value);
},
);
it("parses a quote as a blockquote of one paragraph per line", () => {
const json = buildDocJson("> a\n> b\n>c", (n) => ({ label: n, description: null }));
expect(json.content.map((block) => block.type)).toEqual(["blockquote", "blockquote"]);
expect((json.content[0] as { content: unknown[] }).content).toHaveLength(2);
});
it.each([
"> a\n> b",
"> **q** @README.md",
"text\n---\nmore",
"---\ntext",
"# Heading text",
"## **b** @README.md",
])(
"maps every document offset of the block %s through collapsed coordinates and back",
(value) => {
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("clamps offsets inside a quote or heading marker to the start of the text", () => {
for (const [value, prefix] of [
["> quoted", "> "],
["# Heading", "# "],
] as const) {
const map = roundTrip(value);
for (let collapsed = 0; collapsed <= prefix.length; collapsed += 1) {
expect(collapsedToFlat(map, collapsed)).toBe(0);
}
expect(flatToCollapsed(map, 0)).toBe(prefix.length);
}
});
it.each([
"```\ncode\n```",
"```ts\nconst a = 1;\n```",
"```ts\nconst a = 1;\n```\n",
"before\n```ts\nconst a = 1;\n```\nafter",
"```\n```",
"```ts\nline one\nline two\nline three\n```",
"```ts\n indented\n deeper\n```",
"```js title=example\ncode\n```",
"~~~py\ncode\n~~~",
"````\n```\n````",
"```ts\ncode without a closing fence",
"```",
"```ts\n**not bold** and @README.md stay literal\n```",
"```ts\ncode\n````",
"- [ ] task\n```ts\ncode\n```\n- [ ] after",
" ```ts\nindented fence stays a paragraph\n ```",
])("round-trips the fenced block %s", (value) => {
expect(roundTrip(value).value).toBe(value);
});
it.each(["```ts\nconst a = 1;\n```", "```\n```", "before\n```ts\ncode\n```\nafter"])(
"maps every document offset of %s through collapsed coordinates and back",
(value) => {
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("reads blocks written with CRLF line endings", () => {
const value = "# Title\r\n> quote\r\n---\r\n```ts\r\nconst a = 1;\r\n```\r\nafter";
const doc = buildDocJson(value, () => ({ label: "", description: null }));
expect(doc.content.map((block) => block.type)).toEqual([
"heading",
"blockquote",
"horizontalRule",
"codeBlock",
"paragraph",
]);
expect(roundTrip(value).value).toBe(value);
});
it("keeps the end of the code inside the fence rather than after it", () => {
const value = "```ts\nfunc();\n```";
const map = roundTrip(value);
const endOfCode = "func();".length;
// Not the end of the string: the closing fence is a line of its own.
expect(flatToCollapsed(map, endOfCode)).toBe("```ts\nfunc();".length);
expect(flatToMarkdown(map, endOfCode)).toBe("```ts\nfunc();".length);
expect(collapsedToFlat(map, flatToCollapsed(map, endOfCode))).toBe(endOfCode);
});
it("keeps the caret inside an empty fence", () => {
const value = "before\n```\n```";
const map = roundTrip(value);
const inside = "before\n".length;
expect(flatToCollapsed(map, inside)).toBe("before\n```".length);
expect(collapsedToFlat(map, flatToCollapsed(map, inside))).toBe(inside);
});
it("still places the end of an inline mark after its markers", () => {
// The fence rule must not leak into inline marks, whose trailing edge is
// deliberately the position after the closing delimiter.
const map = roundTrip("a **bold** c");
expect(flatToMarkdown(map, 6)).toBe(10);
});
it("clamps offsets inside a fence to the edge of the code", () => {
const value = "```ts\nab\n```";
const map = roundTrip(value);
expect(map.value).toBe(value);
// The opening fence owns no document characters, so every offset in it
// lands on the first character of the code.
for (let collapsed = 0; collapsed <= "```ts\n".length; collapsed += 1) {
expect(collapsedToFlat(map, collapsed)).toBe(0);
}
expect(collapsedToFlat(map, "```ts\na".length)).toBe(1);
// Everything from the closing newline onwards clamps to the code's end.
for (let collapsed = "```ts\nab".length; collapsed <= value.length; collapsed += 1) {
expect(collapsedToFlat(map, collapsed)).toBe(2);
}
});
it.each([
["```\n\n```", "```\n```"],
["```\n", "```"],
])("canonicalizes the empty fence %s", (value, expected) => {
expect(roundTrip(value).value).toBe(expected);
});
it("keeps a chip in a fence info string as source and keeps later chips aligned", () => {
const value = "```@README.md\ncode\n```\n$my-skill after";
expect(roundTrip(value).value).toBe(value);
const json = buildDocJson(value, (n) => ({ label: n, description: null }));
const after = json.content[1] as {
content: { type: string; attrs?: { skillName?: string } }[];
};
expect(after.content.map((n) => n.type)).toEqual(["composer-skill", "text"]);
expect(after.content[0]?.attrs?.skillName).toBe("my-skill");
});
it("keeps chips in a fence's info string and body each in their own place", () => {
const value = "``` @a.md\nsee @b.md\n```";
expect(roundTrip(value).value).toBe(value);
const json = buildDocJson(value, (n) => ({ label: n, description: null }));
const code = json.content[0] as { attrs: { language: string } };
expect(code.attrs.language).toBe(" @a.md");
});
it.each([
["listItem", { marker: "-", space: "" }, "bulletList", "- text"],
["listItem", { marker: "1.", space: "" }, "orderedList", "1. text"],
])("gives a bare %s a space once it has text", (item, attrs, list, expected) => {
const doc = ProseMirrorNode.fromJSON(schema, {
type: "doc",
content: [
{
type: list,
content: [
{
type: item,
attrs,
content: [{ type: "paragraph", content: [{ type: "text", text: "text" }] }],
},
],
},
],
});
expect(serializeEditorDoc(doc).value).toBe(expected);
expect(roundTrip("-").value).toBe("-");
});
it("writes code holding a closing fence inside a longer fence", () => {
const doc = ProseMirrorNode.fromJSON(schema, {
type: "doc",
content: [
{
type: "codeBlock",
attrs: { fence: "```", close: "\n```" },
content: [{ type: "text", text: "initial\n```\nsecret" }],
},
],
});
const stored = serializeEditorDoc(doc).value;
expect(stored).toBe("````\ninitial\n```\nsecret\n````");
expect(buildDocJson(stored, () => ({ label: "", description: null })).content).toHaveLength(1);
expect(roundTrip(stored).value).toBe(stored);
});
it("closes an unclosed fence that has a block after it", () => {
const doc = ProseMirrorNode.fromJSON(schema, {
type: "doc",
content: [
{ type: "codeBlock", attrs: { close: "" }, content: [{ type: "text", text: "code" }] },
{ type: "paragraph", content: [{ type: "text", text: "after" }] },
],
});
expect(serializeEditorDoc(doc).value).toBe("```\ncode\n```\nafter");
// At the end of the draft it stays unclosed, as it was written.
expect(roundTrip("```\ncode").value).toBe("```\ncode");
});
it("counts a chip's source in a fence as one cursor position, as the draft store does", () => {
const value = "```\nsee @b.md now\n```\nafter";
const map = roundTrip(value);
expect(map.value).toBe(value);
for (let flat = 0; flat <= map.docLength; flat += 1) {
expect(flatToCollapsed(map, flat)).toBe(
collapseExpandedComposerCursor(value, flatToMarkdown(map, flat)),
);
}
const afterChip = "see @b.md".length;
expect(collapsedToFlat(map, flatToCollapsed(map, afterChip))).toBe(afterChip);
const end = map.docLength;
expect(collapsedToFlat(map, flatToCollapsed(map, end))).toBe(end);
});
it("keeps fences literal in plain mode", () => {
const value = "```ts\nconst a = 1;\n```";
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);
@@ -353,6 +794,37 @@ describe("composer rich text document model", () => {
}
});
// Flipping the rich text setting remounts the editor, and the caret is
// restored from the stored collapsed cursor. That only works because the
// coordinate means the same thing on both sides of the flip.
it.each([
"plain prose with no styling at all",
"a chip @README.md counts one character in both modes",
"$my-skill leads the line",
"trailing newline\n",
])("resolves a collapsed cursor identically in both modes for %s", (value) => {
const rich = roundTrip(value);
const plain = roundTripPlain(value);
expect(rich.value).toBe(value);
expect(plain.value).toBe(value);
for (let collapsed = 0; collapsed <= value.length; collapsed += 1) {
expect(flatToMarkdown(rich, collapsedToFlat(rich, collapsed))).toBe(
flatToMarkdown(plain, collapsedToFlat(plain, collapsed)),
);
}
});
it("clamps a cursor that was sitting inside a marker onto the styled text", () => {
const value = "a **bold** c";
const plain = roundTripPlain(value);
const rich = roundTrip(value);
// Between the two asterisks: a real caret position in plain mode, and no
// position at all in rich mode, where it lands on the first styled
// character instead. The flip moves the caret by a marker's width at most.
expect(flatToMarkdown(plain, collapsedToFlat(plain, 3))).toBe(3);
expect(flatToMarkdown(rich, collapsedToFlat(rich, 3))).toBe(4);
});
it("maps markdown offsets at styled edges onto document text", () => {
const value = "a **bold** c";
const map = roundTrip(value);
@@ -365,6 +837,63 @@ describe("composer rich text document model", () => {
});
});
describe("serializeSelection", () => {
/** The stored Markdown of the selection from the start of `first` to the end of `last`. */
function copy(value: string, first: string, last: string) {
const doc = ProseMirrorNode.fromJSON(
schema,
buildDocJson(value, (name) => ({ label: name, description: null })),
);
let from = -1;
let to = -1;
doc.descendants((node, pos) => {
if (!node.isText) return true;
const text = node.text ?? "";
if (from < 0 && text.includes(first)) from = pos + text.indexOf(first);
if (text.includes(last)) to = pos + text.lastIndexOf(last) + last.length;
return false;
});
return serializeSelection(doc, from, to);
}
it("keeps the markers of the list items it spans", () => {
expect(copy("- one\n- two\n- three", "one", "two")).toBe("- one\n- two");
expect(copy("3) one\n4) two", "one", "two")).toBe("3) one\n4) two");
expect(copy("- [ ] one\n- [x] two", "one", "two")).toBe("- [ ] one\n- [x] two");
});
it("keeps the nesting of an item and its children", () => {
expect(copy("- p\n - a\n - b", "p", "a")).toBe("- p\n - a");
});
it("keeps the prefix of the quote lines it spans", () => {
expect(copy("> one\n> two", "one", "two")).toBe("> one\n> two");
});
it("copies text within one block without its marker", () => {
expect(copy("- one two", "one", "one")).toBe("one");
});
it("copies across blocks as they are written", () => {
expect(copy("intro\n- one", "intro", "one")).toBe("intro\n- one");
});
});
describe("pasting into a list item or quote", () => {
it("keeps inline marks but builds no blocks", () => {
const content = buildTiptapContent(
"**bold** text\n- item\n> quote",
() => ({ label: "", description: null }),
{ styling: true, blocks: false },
);
expect(content.map((block) => block.type)).toEqual(["paragraph", "paragraph", "paragraph"]);
const first = content[0] as { content: { text: string; marks?: { type: string }[] }[] };
expect(first.content[0]).toMatchObject({ text: "bold", marks: [{ type: "bold" }] });
expect(JSON.stringify(content[1])).toContain("- item");
expect(JSON.stringify(content[2])).toContain("> quote");
});
});
describe("caret stops at styled edges", () => {
function stateAt(value: string, pmPos: number) {
const doc = ProseMirrorNode.fromJSON(
File diff suppressed because it is too large. Load diff
+55 -29
View File
@@ -1422,7 +1422,7 @@ html[data-theme-id] [data-chat-header] [data-slot="separator"] {
/* Chat code blocks join the other code surfaces on the code tokens. The
default look keeps its secondary/input tints; themed palettes tint those
surfaces with the accent, which fights syntax highlighting. */
html[data-theme-id] .chat-markdown .chat-markdown-codeblock {
html[data-theme-id] :is(.chat-markdown, .composer-tiptap) .chat-markdown-codeblock {
background-color: var(--code-background);
border-color: var(--contrast-border);
color: var(--code-foreground);
@@ -1433,11 +1433,11 @@ html[data-theme-id] .chat-markdown pre {
color: var(--code-foreground);
}
html[data-theme-id] .chat-markdown .chat-markdown-codeblock pre {
html[data-theme-id] :is(.chat-markdown, .composer-tiptap) .chat-markdown-codeblock pre {
background-color: transparent;
}
html[data-theme-id] .chat-markdown .chat-markdown-codeblock-header {
html[data-theme-id] :is(.chat-markdown, .composer-tiptap) .chat-markdown-codeblock-header {
color: color-mix(in srgb, var(--code-foreground) 72%, transparent);
}
@@ -1685,7 +1685,7 @@ code {
Inline code stays relative to its sentence so it never towers over prose;
diffs and file previews take the size through --diffs-font-size. */
.chat-markdown .chat-markdown-shiki .shiki,
.chat-markdown pre code {
:is(.chat-markdown, .composer-tiptap) pre code {
font-size: var(--font-size-code, inherit);
}
@@ -1755,45 +1755,47 @@ code {
.chat-markdown ol,
.chat-markdown blockquote,
.chat-markdown pre,
.chat-markdown .chat-markdown-table-container {
.chat-markdown .chat-markdown-table-container,
.composer-tiptap ul,
.composer-tiptap ol {
margin: 0.65rem 0;
}
.chat-markdown h1,
.chat-markdown h2,
.chat-markdown h3,
.chat-markdown h4,
.chat-markdown h5,
.chat-markdown h6 {
:is(.chat-markdown, .composer-tiptap) h1,
:is(.chat-markdown, .composer-tiptap) h2,
:is(.chat-markdown, .composer-tiptap) h3,
:is(.chat-markdown, .composer-tiptap) h4,
:is(.chat-markdown, .composer-tiptap) h5,
:is(.chat-markdown, .composer-tiptap) h6 {
margin: 1.25rem 0 0.5rem;
font-weight: 600;
line-height: 1.3;
color: var(--contrast-foreground);
}
.chat-markdown h1 {
:is(.chat-markdown, .composer-tiptap) h1 {
font-size: 1.25rem;
}
.chat-markdown h2 {
:is(.chat-markdown, .composer-tiptap) h2 {
font-size: 1.125rem;
}
.chat-markdown h3 {
:is(.chat-markdown, .composer-tiptap) h3 {
font-size: 1rem;
}
.chat-markdown h4,
.chat-markdown h5,
.chat-markdown h6 {
:is(.chat-markdown, .composer-tiptap) h4,
:is(.chat-markdown, .composer-tiptap) h5,
:is(.chat-markdown, .composer-tiptap) h6 {
font-size: 0.875rem;
}
.chat-markdown h6 {
:is(.chat-markdown, .composer-tiptap) h6 {
color: var(--contrast-muted-foreground);
}
.chat-markdown ul {
:is(.chat-markdown, .composer-tiptap) ul {
/* Reset for nested uls under a widened ol. --list-gutter is an inherited
custom property, so without this a task-list under a multi-digit ordered
list would inherit the outer gutter instead of its own default. */
@@ -1807,21 +1809,27 @@ code {
widest marker has multiple characters so it isn't clipped by list-style-position:
outside painting the marker past the padding box. Reset it here too so a
nested ol without its own widened marker doesn't inherit the outer one. */
.chat-markdown ol {
:is(.chat-markdown, .composer-tiptap) ol {
--list-gutter: 1.25rem;
padding-left: var(--list-gutter, 1.25rem);
list-style-type: decimal;
}
.chat-markdown ol > li::marker {
:is(.chat-markdown, .composer-tiptap) ol > li::marker {
font-variant-numeric: tabular-nums;
}
.chat-markdown ul ul {
/* The composer shows the marker the source has, `3)` or a nested `7.`, not the
browser counter. Browsers without ::marker content fall back to `start`. */
.composer-tiptap ol > li[data-marker]::marker {
content: attr(data-marker) " ";
}
:is(.chat-markdown, .composer-tiptap) ul ul {
list-style-type: circle;
}
.chat-markdown ul ul ul {
:is(.chat-markdown, .composer-tiptap) ul ul ul {
list-style-type: square;
}
@@ -1870,12 +1878,30 @@ code {
background-size: 4px 2px;
}
.chat-markdown blockquote {
:is(.chat-markdown, .composer-tiptap) blockquote {
border-left: 2px solid var(--contrast-border);
padding-left: 0.8rem;
color: var(--contrast-muted-foreground);
}
/* A quote in the composer is text the user is still writing; muting it reads
as disabled in an input, so the border alone carries the quote. */
.composer-tiptap blockquote {
margin: 0.65rem 0;
color: var(--foreground);
}
/* Preflight already draws the 1px rule, as it does in chat; only the block
spacing needs to match. */
.composer-tiptap hr {
margin: 0.65rem 0;
}
/* A heading at the top of a draft should not push the first line down. */
.composer-tiptap :is(h1, h2, h3, h4, h5, h6):first-child {
margin-top: 0;
}
.chat-markdown section[data-footnotes] {
margin-top: 1.25rem;
border-top: 1px solid var(--contrast-border);
@@ -1939,23 +1965,23 @@ code {
background: color-mix(in srgb, var(--contrast-border) 78%, transparent);
}
.chat-markdown .chat-markdown-codeblock-header {
:is(.chat-markdown, .composer-tiptap) .chat-markdown-codeblock-header {
color: color-mix(in srgb, var(--contrast-foreground) 72%, transparent);
}
.chat-markdown .chat-markdown-codeblock pre {
:is(.chat-markdown, .composer-tiptap) .chat-markdown-codeblock pre {
margin: 0;
border: none;
border-radius: 0;
background: transparent;
}
.chat-markdown .chat-markdown-codeblock[data-wrap="true"] pre {
:is(.chat-markdown, .composer-tiptap) .chat-markdown-codeblock[data-wrap="true"] pre {
white-space: pre-wrap;
overflow-wrap: anywhere;
}
.chat-markdown .chat-markdown-shiki .shiki {
:is(.chat-markdown, .composer-tiptap) .chat-markdown-shiki .shiki {
background: transparent !important;
}
@@ -2181,7 +2207,7 @@ code {
outline: none;
}
.composer-tiptap code {
.composer-tiptap :not(pre) > code {
font-family: var(--font-mono);
font-size: 0.92em;
background: color-mix(in oklab, var(--muted-foreground) 12%, transparent);
+15
View File
@@ -25,3 +25,18 @@ Clipboard text must come from the Markdown serializer, not DOM text: chip labels
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.
Block nodes (fences, lists, quotes, rules, headings) keep their exact Markdown
delimiters as node attributes, so the round trip is byte-identical and offsets
inside a delimiter clamp to the block's text like task and style markers. The
serializers write only what the grammar has: a quote holds paragraphs, a list
holds paragraphs and lists. So blocks may only form at a top-level paragraph.
Input rules check this, and Tiptap's own block chords (Mod-Shift-8, Mod-Alt-c,
and so on) are removed, because nesting a block the serializer cannot write
drops its text from the stored draft. The list grammar is the plain-mode
continuation's in [composer-list-continuation](../../apps/web/src/composer-list-continuation.ts);
keep the two in step.
Enter sends, so the fence handling in `handleKeyDown` must run before the send
handler: checked afterwards, a fence never opens and a newline inside one sends
the draft.
+17
View File
@@ -12,6 +12,23 @@ becomes an attachment when inserting it would exceed the message limit. On a
hardware keyboard, use `Cmd+Shift+V` on Apple devices or `Ctrl+Shift+V` elsewhere
to keep a large paste editable in the composer instead.
## Formatting
The composer writes Markdown and shows it styled as you type. Markers such as
`**` stay in the text and show beside the styled words when your cursor is on
them. Lines starting with `- `, `1. `, `- [ ] `, `> `, `# ` or `---` become lists,
task lists, quotes, headings and rules; ` ``` ` followed by Enter opens a code
block. What you typed is what the agent receives, markers and numbering
included, and `#1234` without a space still looks up a pull request.
Enter sends. In a list or quote, **Shift+Enter** continues it, and Shift+Enter
on an empty line leaves it; **Tab** nests a list item. In a code block, Enter
starts a new line at the current indentation, **Tab** and **Shift+Tab** indent
the selected lines, and a closing ` ``` ` followed by Enter, or two blank lines
at the end, leave the block. **Backspace** at the start of a code block turns it
back into plain lines. Choose the language in a code block's corner to change
it. Very large code blocks are shown without syntax highlighting.
## Attach files
Attach up to 100 files per message. Each image can be up to 10 MiB, with at most
+15
View File
@@ -687,9 +687,24 @@ importers:
'@tiptap/core':
specifier: ^3.31.3
version: 3.31.3(@tiptap/[email protected])
'@tiptap/extension-blockquote':
specifier: ^3.31.3
version: 3.31.3(@tiptap/[email protected](@tiptap/[email protected]))(@tiptap/[email protected])
'@tiptap/extension-code':
specifier: ^3.31.3
version: 3.31.3(@tiptap/[email protected](@tiptap/[email protected]))
'@tiptap/extension-code-block':
specifier: ^3.31.3
version: 3.31.3(@tiptap/[email protected](@tiptap/[email protected]))(@tiptap/[email protected])
'@tiptap/extension-heading':
specifier: ^3.31.3
version: 3.31.3(@tiptap/[email protected](@tiptap/[email protected]))
'@tiptap/extension-horizontal-rule':
specifier: ^3.31.3
version: 3.31.3(@tiptap/[email protected](@tiptap/[email protected]))(@tiptap/[email protected])
'@tiptap/extension-list':
specifier: ^3.31.3
version: 3.31.3(@tiptap/[email protected](@tiptap/[email protected]))(@tiptap/[email protected])
'@tiptap/extension-task-item':
specifier: ^3.31.3
version: 3.31.3(@tiptap/[email protected](@tiptap/[email protected](@tiptap/[email protected]))(@tiptap/[email protected]))