Skip to content

armgit / macro

Public Imported from GitHub
0

Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.

fix(md): defer autolink while typing through a short TLD (#8914)

Wolf Mermelstein70c825b68a53
diff --git a/apps/web/src/lib/core/component/LexicalMarkdown/component/core/browser-test/links.browser.e2e.ts b/apps/web/src/lib/core/component/LexicalMarkdown/component/core/browser-test/links.browser.e2e.ts
index 9fb00554e9..5f306a9cbb 100644
--- a/apps/web/src/lib/core/component/LexicalMarkdown/component/core/browser-test/links.browser.e2e.ts
+++ b/apps/web/src/lib/core/component/LexicalMarkdown/component/core/browser-test/links.browser.e2e.ts
@@ -77,3 +77,28 @@ test('agent URLs navigate and removed links survive save and reopen', async ({
fullPage: true,
});
});
+
+// Pasting [email protected] b and typing o after the c used to swallow the letter when
+// mailto:[email protected] autolinked mid-keystroke (.co is also the prefix of .com).
+test('typing o after [email protected] keeps the letter without wrapping mid-edit', async ({
+ page,
+}) => {
+ await page.goto(
+ '/src/lib/core/component/LexicalMarkdown/component/core/browser-test/links.html'
+ );
+ const editor = page.getByRole('textbox', { name: 'Message' });
+ await expect(editor).toBeVisible({ timeout: 30_000 });
+ await editor.click();
+ await page.keyboard.press('ControlOrMeta+A');
+ await page.keyboard.type('[email protected] b');
+ await expect(editor).toHaveText('[email protected] b');
+ await page.keyboard.press('End');
+ await page.keyboard.press('ArrowLeft');
+ await page.keyboard.press('ArrowLeft');
+ await page.keyboard.type('o');
+ await expect(editor).toHaveText('[email protected] b');
+ await expect(editor.locator('a')).toHaveCount(0);
+ await page.keyboard.type('m');
+ await expect(editor).toHaveText('[email protected] b');
+ await expect(editor.locator('a')).toHaveCount(0);
+});
diff --git a/apps/web/src/lib/core/component/LexicalMarkdown/plugins/links/linksPlugin.test.ts b/apps/web/src/lib/core/component/LexicalMarkdown/plugins/links/linksPlugin.test.ts
index 93ec91ddaf..4b55d5ab5f 100644
--- a/apps/web/src/lib/core/component/LexicalMarkdown/plugins/links/linksPlugin.test.ts
+++ b/apps/web/src/lib/core/component/LexicalMarkdown/plugins/links/linksPlugin.test.ts
@@ -1,4 +1,8 @@
-import { $isAutoLinkNode, $isLinkNode } from '@lexical/link';
+import {
+ $createAutoLinkNode,
+ $isAutoLinkNode,
+ $isLinkNode,
+} from '@lexical/link';
import {
$convertFromMarkdownString,
$convertToMarkdownString,
@@ -13,6 +17,8 @@ import {
$createParagraphNode,
$createTextNode,
$getRoot,
+ $getSelection,
+ $isRangeSelection,
createEditor,
} from 'lexical';
import { describe, expect, it } from 'vitest';
@@ -24,6 +30,35 @@ import {
UNLINK_COMMAND,
} from './linksPlugin';
+function editorWithLinks(mode: 'protocol' | 'common-tlds' = 'common-tlds') {
+ const editor = createEditor({
+ nodes: SupportedNodeTypes,
+ onError(error) {
+ throw error;
+ },
+ });
+ const cleanup = linksPlugin({ autoLinkMatchMode: mode })(editor);
+ return { editor, cleanup };
+}
+
+function textNodes(editor: ReturnType<typeof createEditor>) {
+ return editor.getEditorState().read(() =>
+ $getRoot()
+ .getAllTextNodes()
+ .map((node) => {
+ const parent = node.getParent();
+ return {
+ text: node.getTextContent(),
+ linked: $isLinkNode(parent) || $isAutoLinkNode(parent),
+ url:
+ $isLinkNode(parent) || $isAutoLinkNode(parent)
+ ? parent.getURL()
+ : undefined,
+ };
+ })
+ );
+}
+
describe('normalizeLinkUrl', () => {
it('normalizes bare hosts to HTTPS', () => {
expect(normalizeLinkUrl(' example.com/path with spaces ')).toBe(
@@ -60,6 +95,95 @@ describe('normalizeLinkUrl', () => {
});
});
+describe('typing through an incomplete email TLD', () => {
+ it('keeps o after [email protected] and does not wrap while the caret is in the match', () => {
+ const { editor, cleanup } = editorWithLinks();
+ editor.update(
+ () => {
+ const node = $createTextNode('[email protected] b');
+ $getRoot().clear().append($createParagraphNode().append(node));
+ node.select(5, 5);
+ },
+ { discrete: true }
+ );
+ editor.update(
+ () => {
+ const selection = $getSelection();
+ if ($isRangeSelection(selection)) selection.insertText('o');
+ },
+ { discrete: true }
+ );
+ expect(
+ editor.getEditorState().read(() => $getRoot().getTextContent())
+ ).toBe('[email protected] b');
+ expect(textNodes(editor)).toEqual([
+ { text: '[email protected] b', linked: false, url: undefined },
+ ]);
+ cleanup();
+ });
+
+ it('wraps mailto:[email protected] once the caret moves past the match', () => {
+ const { editor, cleanup } = editorWithLinks();
+ editor.update(
+ () => {
+ const node = $createTextNode('[email protected] b');
+ $getRoot().clear().append($createParagraphNode().append(node));
+ node.select(5, 5);
+ },
+ { discrete: true }
+ );
+ editor.update(
+ () => {
+ const selection = $getSelection();
+ if ($isRangeSelection(selection)) selection.insertText('o');
+ },
+ { discrete: true }
+ );
+ editor.update(
+ () => {
+ const node = $getRoot().getAllTextNodes()[0];
+ node.select(8, 8);
+ const selection = $getSelection();
+ if ($isRangeSelection(selection)) selection.insertText('!');
+ },
+ { discrete: true }
+ );
+ expect(
+ editor.getEditorState().read(() => $getRoot().getTextContent())
+ ).toBe('[email protected] b!');
+ expect(textNodes(editor)).toEqual([
+ { text: '[email protected]', linked: true, url: 'mailto:[email protected]' },
+ { text: ' b!', linked: false, url: undefined },
+ ]);
+ cleanup();
+ });
+
+ it('does not shrink an autolink label when the rematch is shorter', () => {
+ const { editor, cleanup } = editorWithLinks();
+ editor.update(
+ () => {
+ // Combined text rematches a short host that starts after the label
+ // (`hello)m.co` → `m.co`). Without a non-positive shift guard,
+ // substring(n<0) keeps the suffix and replaces the longer label.
+ const link = $createAutoLinkNode('https://hello.example');
+ link.append($createTextNode('hello)'));
+ const rest = $createTextNode('m.co');
+ $getRoot().clear().append($createParagraphNode().append(link, rest));
+ },
+ { discrete: true }
+ );
+ expect(
+ editor.getEditorState().read(() => $getRoot().getTextContent())
+ ).toBe('hello)m.co');
+ expect(textNodes(editor)[0]).toEqual({
+ text: 'hello)',
+ linked: true,
+ url: 'https://hello.example',
+ });
+ cleanup();
+ });
+});
+
describe('findNextAutoLinkMatch', () => {
it('requires a protocol in protocol mode', () => {
expect(findNextAutoLinkMatch('Visit example.com')).toBeNull();
diff --git a/apps/web/src/lib/core/component/LexicalMarkdown/plugins/links/linksPlugin.ts b/apps/web/src/lib/core/component/LexicalMarkdown/plugins/links/linksPlugin.ts
index ab46019198..a6afbc0557 100644
--- a/apps/web/src/lib/core/component/LexicalMarkdown/plugins/links/linksPlugin.ts
+++ b/apps/web/src/lib/core/component/LexicalMarkdown/plugins/links/linksPlugin.ts
@@ -136,20 +136,47 @@ function $handleAppendToMatch(
return;
}
- // append to the autolink node, and shift chars from the text node for each aggregate match
+ // Grow the existing autolink by shifting chars from the following text node.
+ // A non-positive shift means the rematch is not longer than the current
+ // label; applying it would shrink the label (JS substring(n<0) → 0) and can
+ // drop the character the user just typed (e.g. o after [email protected] → m.co).
const numCharsToShift = rematch.raw.length - prevText.length;
+ if (numCharsToShift <= 0) {
+ return;
+ }
textNode.setTextContent(nodeText.substring(numCharsToShift));
prevLinkTextNode.setTextContent(rematch.text);
prevSibling.setURL(rematch.url);
}
+/**
+ * True when the collapsed caret sits inside or at the end of a match in
+ * `textNode`. Wrapping then fights the keystroke that completed the URL
+ * ([email protected]| → [email protected]|), which can swallow the typed character and blocks
+ * continuing into a longer TLD like .com.
+ */
+function $isCaretInsideAutoLinkMatch(
+ textNode: TextNode,
+ matchOffset: number,
+ matchLength: number
+): boolean {
+ const selection = $getSelection();
+ if (!$isRangeSelection(selection) || !selection.isCollapsed()) {
+ return false;
+ }
+ if (selection.anchor.key !== textNode.getKey()) {
+ return false;
+ }
+ const offset = selection.anchor.offset;
+ return offset >= matchOffset && offset <= matchOffset + matchLength;
+}
+
function $matchAndCreateAutoLink(
textNode: TextNode,
autoLinkMatchMode: AutoLinkMatchMode
) {
const nodeText = textNode.getTextContent();
const matchedLink = findNextAutoLinkMatch(nodeText, autoLinkMatchMode);
- let currentNode = textNode;
if (!matchedLink) {
return;
@@ -157,12 +184,26 @@ function $matchAndCreateAutoLink(
const matchOffset = matchedLink.index;
const matchLength = matchedLink.raw.length;
- let matchedNode;
+ if ($isCaretInsideAutoLinkMatch(textNode, matchOffset, matchLength)) {
+ return;
+ }
+
+ const selection = $getSelection();
+ const restoreAfter =
+ $isRangeSelection(selection) &&
+ selection.isCollapsed() &&
+ selection.anchor.key === textNode.getKey() &&
+ selection.anchor.offset > matchOffset + matchLength
+ ? selection.anchor.offset - (matchOffset + matchLength)
+ : null;
+
+ let matchedNode: TextNode;
+ let afterNode: TextNode | undefined;
if (matchOffset === 0) {
- [matchedNode, currentNode] = currentNode.splitText(matchLength);
+ [matchedNode, afterNode] = textNode.splitText(matchLength);
} else {
- [, matchedNode, currentNode] = currentNode.splitText(
+ [, matchedNode, afterNode] = textNode.splitText(
matchOffset,
matchOffset + matchLength
);
@@ -171,6 +212,11 @@ function $matchAndCreateAutoLink(
const linkNode = $createAutoLinkNode(matchedLink.url);
matchedNode.replace(linkNode);
linkNode.append(matchedNode);
+
+ // splitText + replace can drop the caret; put it back in the trailing text.
+ if (restoreAfter !== null && afterNode) {
+ afterNode.select(restoreAfter, restoreAfter);
+ }
}
function $convertAutoLinkToLinkNode(node: AutoLinkNode): LinkNode {