Beautiful, AI-native markdown IDE and LLM wiki
TypeScript 2nd-brainagent-skillsclaudecodexcompany-braindocsknowledge-knowledge-baseknowledge-managementllmllm-wikillm-wiki-karpathymarkdownmarkdown-editormdmdxnotespkmsecond-brainskills
Keep pasted inline content in the block at the caret (#7629)
Dimitri POSTOLOV9ac22059fd1d
diff --git a/.changeset/inline-paste-stays-in-block.md b/.changeset/inline-paste-stays-in-block.mdnew file mode 100644index 000000000..b9768a232--- /dev/null+++ b/.changeset/inline-paste-stays-in-block.md@@ -0,0 +1,5 @@+---+'@inkeep/open-knowledge': patch+---++Pasted formatted text and links now stay in the bullet, heading, quote or paragraph at the cursor instead of moving to a new paragraph outside it. A link pasted right next to a word stays a link.diff --git a/packages/app/src/editor/clipboard/handle-paste.ts b/packages/app/src/editor/clipboard/handle-paste.tsindex 3545eeffc..0a1f32803 100644--- a/packages/app/src/editor/clipboard/handle-paste.ts+++ b/packages/app/src/editor/clipboard/handle-paste.ts@@ -547,6 +547,28 @@ function buildMixedSiblingSpliceTr(return tr;}+function inlineParagraphPayload(+ state: EditorState,+ docNode: ProseMirrorNode,+): ProseMirrorNode | null {+ const { $from, $to } = state.selection;+ if (docNode.childCount !== 1 || !$from.sameParent($to) || !$from.parent.isTextblock) return null;+ const paragraph = docNode.child(0);+ return paragraph.type.name === 'paragraph' ? paragraph : null;+}++function buildSiblingSpliceTr(state: EditorState, docNode: ProseMirrorNode): Transaction | null {+ try {+ return buildListSiblingSpliceTr(state, docNode) ?? buildMixedSiblingSpliceTr(state, docNode);+ } catch {+ return null;+ }+}++function replaceSelectionWithContent(state: EditorState, node: ProseMirrorNode): Transaction {+ return state.tr.replaceSelection(node.slice(0, node.content.size));+}+function applyJsonSlice(view: EditorView,json: JSONContent,@@ -556,14 +578,10 @@ function applyJsonSlice(): boolean {try {const node = view.state.schema.nodeFromJSON(json);- let spliceTr: Transaction | null = null;- try {- spliceTr =- buildListSiblingSpliceTr(view.state, node) ?? buildMixedSiblingSpliceTr(view.state, node);- } catch {- spliceTr = null;- }- const tr = spliceTr ?? view.state.tr.replaceSelection(node.slice(0, node.content.size));+ const inlineParagraph = inlineParagraphPayload(view.state, node);+ const tr = inlineParagraph+ ? replaceSelectionWithContent(view.state, inlineParagraph)+ : (buildSiblingSpliceTr(view.state, node) ?? replaceSelectionWithContent(view.state, node));view.dispatch(tr.setMeta(PREVENT_AUTOLINK_META, true).scrollIntoView());return true;} catch (err) {diff --git a/packages/app/tests/integration/clipboard-dispatcher-reorder.test.ts b/packages/app/tests/integration/clipboard-dispatcher-reorder.test.tsindex b0b2a3d4a..78bbfb186 100644--- a/packages/app/tests/integration/clipboard-dispatcher-reorder.test.ts+++ b/packages/app/tests/integration/clipboard-dispatcher-reorder.test.ts@@ -35,15 +35,18 @@ function fakeDT(data: Record<string, string>): ClipboardEvent {function fakeView() {const captured: CapturedDispatch = { branch: 'none' };+ const parent = { type: { name: 'paragraph' }, isTextblock: true };const $from = {depth: 1,- node: (_d: number) => ({ type: { name: 'paragraph' } }),+ parent,+ node: (_d: number) => parent,+ sameParent: (other: { parent: unknown }) => other.parent === parent,};return {captured,view: {state: {- selection: { $from },+ selection: { $from, $to: $from },schema,tr: {replaceSelection(slice: { content: { firstChild?: { toJSON: () => JSONContent } } }) {diff --git a/packages/app/tests/stress/paste-fidelity.e2e.ts b/packages/app/tests/stress/paste-fidelity.e2e.tsindex a10f1bffb..f4d9b0273 100644--- a/packages/app/tests/stress/paste-fidelity.e2e.ts+++ b/packages/app/tests/stress/paste-fidelity.e2e.ts@@ -6,6 +6,7 @@ import type { Page } from '@playwright/test';import {expect,selectAllAndWaitForSelection,+ selectText,simulateCopyAndRead,simulateCutAndRead,test,@@ -1604,3 +1605,95 @@ test.describe('cell-insertion gate — component paste into a table cell (persisexpect(after).not.toContain('Callout');});});++const INLINE_PASTE_SEED = '- fooo\n\n## alpha\n';++async function openNewEmptyBullet(page: Page): Promise<void> {+ await setListItemCaret(page, 0, 'end');+ await page.keyboard.press('Enter');+ await page.waitForFunction(() => {+ const editor = window.__activeEditor;+ if (!editor) return false;+ let items = 0;+ editor.state.doc.descendants((node) => {+ if (node.type.name === 'listItem') items++;+ return true;+ });+ const { $from } = editor.state.selection;+ return (+ items === 2 &&+ $from.parent.textContent === '' &&+ $from.node($from.depth - 1).type.name === 'listItem'+ );+ });+}++async function setHeadingCaret(page: Page, offset: number): Promise<void> {+ await page.evaluate((at) => {+ const editor = window.__activeEditor;+ if (!editor) throw new Error('setHeadingCaret: no active editor');+ let start = -1;+ editor.state.doc.descendants((node, pos) => {+ if (start !== -1) return false;+ if (node.type.name === 'heading') {+ start = pos + 1;+ return false;+ }+ return true;+ });+ if (start === -1) throw new Error('setHeadingCaret: heading not found');+ editor.commands.setTextSelection(start + at);+ }, offset);+ await waitForPmSelectionInNode(page, 'heading');+}++test.describe('inline paste stays in the block at the caret (persisted bytes)', () => {+ let docName: string;++ test.beforeEach(async ({ page, api }) => {+ docName = `test-paste-inline-${randomUUID().slice(0, 8)}`;+ await api.createPage(`${docName}.md`);+ await page.goto(`/#/${docName}`);+ await waitForProvider(page);+ await page.waitForSelector('.ProseMirror:not(.composer-prosemirror)');+ await api.replaceDoc(docName, INLINE_PASTE_SEED);+ await expect.poll(() => getYText(page), { timeout: 5_000 }).toContain('## alpha');+ await page.click('.ProseMirror:not(.composer-prosemirror)');+ });++ test('bold text pasted into a new empty bullet stays in that bullet', async ({ page }) => {+ await openNewEmptyBullet(page);+ await pasteWithMimes(page, { 'text/plain': 'foo', 'text/html': '<b>foo</b>' });+ await expect.poll(() => getYText(page), { timeout: 8_000 }).toContain('- fooo\n- **foo**\n');+ });++ test('a URL pasted into a new empty bullet stays in that bullet', async ({ page }) => {+ await openNewEmptyBullet(page);+ await pasteText(page, 'https://example.com');+ await expect+ .poll(() => getYText(page), { timeout: 8_000 })+ .toContain('- fooo\n- https://example.com\n');+ });++ test('a URL pasted right after a word stays in the bullet as a link', async ({ page }) => {+ await setListItemCaret(page, 0, 'end');+ await pasteText(page, 'https://example.com');+ await expect+ .poll(() => getYText(page), { timeout: 8_000 })+ .toContain('- fooo<https://example.com>\n');+ });++ test('bold text pasted over a selection inside a bullet replaces it in place', async ({+ page,+ }) => {+ await selectText(page, 'oo');+ await pasteWithMimes(page, { 'text/plain': 'foo', 'text/html': '<b>foo</b>' });+ await expect.poll(() => getYText(page), { timeout: 8_000 }).toContain('- f**foo**o\n');+ });++ test('bold text pasted inside a heading stays in the heading', async ({ page }) => {+ await setHeadingCaret(page, 2);+ await pasteWithMimes(page, { 'text/plain': 'foo', 'text/html': '<b>foo</b>' });+ await expect.poll(() => getYText(page), { timeout: 8_000 }).toContain('## al**foo**pha');+ });+});diff --git a/packages/core/src/markdown/to-markdown-handlers.ts b/packages/core/src/markdown/to-markdown-handlers.tsindex 887647988..4d54465be 100644--- a/packages/core/src/markdown/to-markdown-handlers.ts+++ b/packages/core/src/markdown/to-markdown-handlers.ts@@ -176,14 +176,20 @@ export const toMarkdownHandlers = {return value;},- link(node, _parent, state, info) {- if (node.data?.sourceStyle === 'autolink') {- return `<${node.url ?? ''}>`;+ link(node, parent, state, info) {+ if (node.data?.sourceStyle === 'autolink' && linkTextIsUrl(node)) {+ return `<${node.url}>`;}if (node.data?.sourceStyle === 'gfm-autolink') {const onlyChild = node.children?.length === 1 ? node.children[0] : null;if (onlyChild?.type === 'text' && typeof onlyChild.value === 'string') {- return onlyChild.value;+ const literal = onlyChild.value;+ const form = gfmLiteralForm(literal, node.url);+ if (form === undefined) return literal;+ if (bareGfmLiteralReadsBack(form, literalNeighborCodes(node, parent, state, info))) {+ return literal;+ }+ if (form === 'protocol' && readsBackAsAngleAutolink(literal)) return `<${literal}>`;}}const tracker = state.createTracker(info);@@ -836,6 +842,103 @@ function normalizeAttrForUpstream(return attr;}+const GFM_PROTOCOL_LITERAL_RE = /^https?:\/\//i;++const GFM_WWW_LITERAL_RE = /^www\./i;++const ANGLE_AUTOLINK_PLAIN_URL_RE = /^https?:\/\/[A-Za-z0-9./:?#@+,;()!'-]*$/i;++const WWW_LABEL_RE = /www\./i;++type GfmLiteralForm = 'protocol' | 'www' | 'email';++function gfmLiteralForm(text: string, href: string): GfmLiteralForm | undefined {+ if (text === href && GFM_PROTOCOL_LITERAL_RE.test(text)) return 'protocol';+ if (href === `http://${text}` && GFM_WWW_LITERAL_RE.test(text)) return 'www';+ if (href === `mailto:${text}`) return 'email';+ return undefined;+}++function linkTextIsUrl(node: Link): boolean {+ let text = '';+ for (const child of node.children) {+ if (child.type !== 'text') return false;+ text += child.value;+ }+ return text === node.url;+}++function isAsciiAlpha(code: number): boolean {+ return (code >= 0x41 && code <= 0x5a) || (code >= 0x61 && code <= 0x7a);+}++function isAsciiAlphanumeric(code: number): boolean {+ return isAsciiAlpha(code) || (code >= 0x30 && code <= 0x39);+}++function isEmailDomainCode(code: number): boolean {+ return code === 0x2d || code === 0x5f || isAsciiAlphanumeric(code);+}++function isEmailAtextCode(code: number): boolean {+ return code === 0x2b || code === 0x2e || isEmailDomainCode(code);+}++function emailLiteralOpensAfter(code: number): boolean {+ return code !== 0x2f && !isEmailAtextCode(code);+}++interface NeighborCodes {+ readonly before: number;+ readonly after: number;+ readonly afterNext: number;+}++function literalNeighborCodes(+ node: Link,+ parent: Parents | undefined,+ state: State,+ info: Info,+): NeighborCodes {+ const siblings: readonly Nodes[] = parent?.children ?? [];+ const index = siblings.indexOf(node);+ const previous = index > 0 ? siblings[index - 1] : undefined;+ const next = index >= 0 ? siblings[index + 1] : undefined;+ const beforeText = previous?.type === 'text' ? previous.value : info.before;+ const afterText =+ next === undefined+ ? info.after+ : state.handle(next, parent, state, {+ ...state.createTracker(info).current(),+ before: '',+ after: '',+ });+ return {+ before: beforeText.charCodeAt(beforeText.length - 1),+ after: afterText.charCodeAt(0),+ afterNext: afterText.charCodeAt(1),+ };+}++function emailDomainContinuesAt(after: number, afterNext: number): boolean {+ return isEmailDomainCode(after) || (after === 0x2e && isAsciiAlphanumeric(afterNext));+}++function bareGfmLiteralReadsBack(+ form: GfmLiteralForm,+ { before, after, afterNext }: NeighborCodes,+): boolean {+ if (form === 'email') {+ return emailLiteralOpensAfter(before) && !emailDomainContinuesAt(after, afterNext);+ }+ const opens = form === 'protocol' ? !isAsciiAlpha(before) : classifyFlank(before) !== 'other';+ return opens && classifyFlank(after) !== 'other';+}++function readsBackAsAngleAutolink(url: string): boolean {+ return ANGLE_AUTOLINK_PLAIN_URL_RE.test(url) && !WWW_LABEL_RE.test(url);+}+function emitLinkTitle(title: string,marker: 'single' | 'double' | 'paren',