Skip to content

Commit 9a9495c

Browse files
committed
refactor: optimize linkification logic in linkifyContent utility
- Streamlined the linkification process by refining the handling of text nodes, ensuring only plain text nodes are transformed. - Improved the conditions for returning original text nodes when no links are detected, enhancing performance and maintainability. - Updated the recursive structure to better manage child nodes and their content, resulting in cleaner code.
1 parent 5bb1f94 commit 9a9495c

File tree

1 file changed

+21
-18
lines changed

1 file changed

+21
-18
lines changed

packages/ui/src/components/editor/utils/linkify-content.ts

Lines changed: 21 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -44,30 +44,33 @@ export function linkifyContent(doc: JSONContent): JSONContent {
4444
const recurse = (node: JSONContent): JSONContent => {
4545
if (!node) return node;
4646

47-
if (node.type === 'text' && typeof node.text === 'string') {
48-
// If it already has a link mark, leave as-is
49-
const hasLink = Array.isArray(node.marks) && node.marks.some((m) => m.type === 'link');
50-
if (hasLink) return node;
51-
const segments = linkifyText(node.text);
52-
// If no links detected, return original
53-
if (segments.length === 1 && segments[0].text === node.text && !segments[0].marks) {
54-
return node;
55-
}
56-
return { type: 'text', text: '', content: segments } as any; // handled by parent rewrite below
57-
}
58-
5947
if (Array.isArray(node.content)) {
6048
const newChildren: JSONContent[] = [];
6149
for (const child of node.content) {
62-
const next = recurse(child);
63-
// If a text node returned a wrapper with inline content, flatten it
64-
if (next && (next as any).content && next.type === 'text' && next.text === '') {
65-
newChildren.push(...(((next as any).content as JSONContent[]) || []));
50+
// Only transform plain text nodes here to avoid complex wrapping
51+
if (child && child.type === 'text' && typeof child.text === 'string') {
52+
const hasLink = Array.isArray(child.marks) && child.marks.some((m) => m.type === 'link');
53+
if (hasLink) {
54+
newChildren.push(child);
55+
} else {
56+
const segments = linkifyText(child.text);
57+
if (segments.length === 0) {
58+
newChildren.push(child);
59+
} else if (
60+
segments.length === 1 &&
61+
segments[0]?.text === child.text &&
62+
!segments[0]?.marks
63+
) {
64+
newChildren.push(child);
65+
} else {
66+
newChildren.push(...segments);
67+
}
68+
}
6669
} else {
67-
newChildren.push(next);
70+
newChildren.push(recurse(child as JSONContent));
6871
}
6972
}
70-
return { ...node, content: newChildren };
73+
return { ...node, content: newChildren } as JSONContent;
7174
}
7275

7376
return node;

0 commit comments

Comments
 (0)