Repository navigation
[lexical-link] Bug Fix: $toggleLink inside an autolink makes it a link with the URL set - #9822
Conversation
…Link on an autolink being replaced on the next edit ## Description `$toggleLink(url)` inside an `AutoLinkNode` sets the autolink's URL in place and leaves it an `AutoLinkNode`; `AutoLinkExtension` re-derives an autolink's URL from its text on the next transform of its text node, so the URL the user set is lost (#9821). New cell, `test.fails`. Test only. ## Test plan ### After ``` $ pnpm exec vitest run --project unit packages/lexical-link/src/__tests__/unit/ToggleLinkOnAutoLink.test.ts Tests 1 expected fail (1) ``` With `test.fails` turned into `test` (main 7487820): ``` × keeps the URL it set after an edit of the text AssertionError: expected 'https://al.test/t30z' to be 'https://u1.test' // Object.is equality Tests 1 failed (1) ```
|
The latest updates on your projects. Learn more about Vercel for GitHub.
|
lexical
@lexical/a11y
@lexical/clipboard
@lexical/code
@lexical/code-core
@lexical/code-prism
@lexical/code-shiki
@lexical/compiler
@lexical/devtools-core
@lexical/dragon
@lexical/eslint-plugin
@lexical/extension
@lexical/fast-check
@lexical/file
@lexical/hashtag
@lexical/headless
@lexical/history
@lexical/html
@lexical/internal
@lexical/link
@lexical/list
@lexical/mark
@lexical/markdown
@lexical/mdast
@lexical/offset
@lexical/overflow
@lexical/plain-text
@lexical/react
@lexical/rich-text
@lexical/selection
@lexical/table
@lexical/tailwind
@lexical/text
@lexical/utils
@lexical/y
@lexical/yjs
commit: |
|
AI review status for this pull request.
|
…k with the URL set ## Description `$toggleLink(url)` with a selection inside an `AutoLinkNode` set that autolink's URL in place and left it an `AutoLinkNode`; `AutoLinkExtension` re-derives an autolink's URL from its text on the next transform of its text node (any edit of the link's text, or a load), so the URL the user set was lost (#9821). `updateLinkNode` now replaces an `AutoLinkNode` with a `LinkNode` carrying the URL, target, rel and title, with the same children (as the multi-node path already unwraps an autolink rather than updating it). AutoLink leaves text inside a link alone, so it stays a link. Closes #9821 ## Test plan ### Before `pnpm exec vitest run --project unit packages/lexical-link/src/__tests__/unit/ToggleLinkOnAutoLink.test.ts` with the cell as a plain test, on the previous commit: ``` × keeps the URL it set after an edit of the text AssertionError: expected 'https://al.test/t30z' to be 'https://u1.test' // Object.is equality Tests 1 failed (1) ``` ### After ``` $ pnpm exec vitest run --project unit packages/lexical-link Test Files 13 passed (13) Tests 288 passed (288) $ pnpm exec vitest run --project unit Test Files 887 passed | 6 skipped (893) Tests 33425 passed | 366 expected fail | 160 skipped (33951) ```
There was a problem hiding this comment.
Thanks, this looks good. Replacing the AutoLinkNode with a LinkNode in updateLinkNode (packages/lexical-link/src/LexicalLinkNode.ts:916-923) fixes the lost URL from #9821, and the new unit test fails without the fix and passes with it. Everything below is optional and non-blocking.
-
Keep the autolink's
targetandtitlewhen the call leaves them out (LexicalLinkNode.ts:920). For a regular link,$toggleLink(url)keeps the existingtargetandtitleunless new ones are passed (LexicalLinkNode.ts:927-935), but the new branch turnsundefinedintonull. Matchers can returnattributessuch astarget: '_blank'(LinkMatcherResult.attributesinLexicalAutoLinkExtension.ts, and the example inpackages/lexical-website/docs/react/plugins.md), so editing the URL of such an autolink now gives a link that opens in the same tab. Carrying them over matches the in-place path:const replacement = $createLinkNode(url, { rel, target: target !== undefined ? target : linkNode.getTarget(), title: title !== undefined ? title : linkNode.getTitle(), });
-
"Link removed" is announced.
AutoLinkExtensiondepends onAutoLinkAnnounceExtension, which only watchesAutoLinkNodemutations (packages/lexical-link/src/AutoLinkAnnounceExtension.ts:72-103). The replace destroys an autolink without creating one, so a screen-reader user who sets a URL on an autolink hears "Link removed" even though the text is still a link. Treating an autolink replaced by aLinkNodein the same update as a rebuild (or tagging this update with$addUpdateTagand skipping tagged updates in the announcer) would keep it quiet. -
Cover the other changed paths. A partial selection inside the autolink and a selection that starts in plain text and ends inside it both go through the changed
updateLinkNode, and both now behave differently from before. One cell each, plus a matcher withattributes, in the same unit file (the// @vitest-environment nodetier described in AGENTS.md) would pin them. -
Changeset
Verify:(.changeset/lexical-link-toggle-link-on-autolink.md:7). The playground's link editor already turned the autolink into a link before this change (packages/lexical-playground/src/plugins/FloatingLinkEditorPlugin/index.tsx:325-336), so checking there shows no difference. CONTRIBUTING.md asksVerify:to say what to test, and a directTOGGLE_LINK_COMMANDor$toggleLinkcall shows the fix. -
Nits: that playground branch is now redundant and could be removed. The autolink's NodeState is not carried to the new link; that is probably fine, since AutoLink rebuilds autolinks as you type, but a comment saying it is deliberate would help. The Test plan's Before output comes from the earlier version of the test: at this head the test fails one assertion earlier on the old code (
ToggleLinkOnAutoLink.test.ts:87).
| // An autolink's URL follows its text (AutoLinkExtension sets it again | ||
| // on the next transform of its text): a URL set by the user makes it a | ||
| // link of its own, with the same children. | ||
| const replacement = $createLinkNode(url, {rel, target, title}); |
There was a problem hiding this comment.
Optional: for a regular link $toggleLink(url) keeps the existing target/title when the call leaves them undefined (lines 927-935), but here undefined becomes null, so an autolink whose matcher set target: '_blank' loses it when its URL is edited. Carrying them over matches the in-place path:
const replacement = $createLinkNode(url, {
rel,
target: target !== undefined ? target : linkNode.getTarget(),
title: title !== undefined ? title : linkNode.getTitle(),
});| // link of its own, with the same children. | ||
| const replacement = $createLinkNode(url, {rel, target, title}); | ||
| updatedNodes.add(replacement.getKey()); | ||
| linkNode.replace(replacement, true); |
There was a problem hiding this comment.
Optional: AutoLinkExtension depends on AutoLinkAnnounceExtension, which only watches AutoLinkNode mutations (AutoLinkAnnounceExtension.ts:72-103). This replace destroys an autolink without creating one, so it now announces "Link removed" when a URL is set on an autolink, although the text is still a link. The announcer could treat an autolink replaced by a LinkNode in the same update as a rebuild, or this branch could tag the update ($addUpdateTag) for the announcer to skip.
|
|
||
| [fix] `$toggleLink(url)` inside an autolink makes it a link with that URL: it set the autolink's URL in place, and AutoLink set it back from the text on the next edit (or load), losing the URL the user chose | ||
|
|
||
| Verify: with `AutoLinkExtension`, select text inside an autolink and set a link URL (`$toggleLink`, the link editor of the playground); edit the link's text or reload: the link keeps the URL you set and is no longer an autolink. Removing a link (`$toggleLink(null)`) and setting a URL on a regular link are unchanged. |
There was a problem hiding this comment.
Nit: the playground's link editor already replaced the autolink with a LinkNode before this change (FloatingLinkEditorPlugin/index.tsx:325-336), so following this step there shows no difference. A direct TOGGLE_LINK_COMMAND or $toggleLink call would show the fix.
…gleLink makes it a link
## Description
Review: the link replacing an autolink took only the attributes `$toggleLink` was given, so an autolink's matcher target and title (and those the playground's link editor copies over) were reset, where the in-place update kept them. `$replaceAutoLink` now uses the autolink's own rel, target and title where none is given; given ones (including null) still apply. The node-selection path also makes an autolink around a selected node a link instead of wrapping the node in a new link inside it.
## Test plan
### Before
The new cell on the previous commit:
```
× keeps the target and title of the autolink unless it sets them
Tests 1 failed | 1 skipped (2)
```
### After
```
$ pnpm exec vitest run --project unit packages/lexical-link
Tests 289 passed (289)
```
… when $toggleLink makes it a link
## Description
Review: with the autolink itself in a node selection, replacing it with a link left the selection holding a removed key (nothing selected), where the selection held the autolink before. The selection now holds the link's children (the link itself may still merge into a neighbouring link with the same attributes, which removes its key; its children keep theirs), so the same text stays selected. New cells: the autolink selected alone, and next to a link with the same URL.
## Test plan
### Before
The new cells on the previous commit:
```
× with the autolink itself selected, keeps what it holds selected
```
### After
```
$ pnpm exec vitest run --project unit packages/lexical-link
Tests 291 passed (291)
```
…ggleLink makes the selected autolink a link
## Description
Review: holding the link's children in the node selection still lost them when the new link merged into a neighbouring one with the same attributes and its text coalesced with the neighbour's (Lexical's normalization moves only range points along). With the autolink itself in a node selection, its text is now selected as a range, which survives those merges. The neighbour cell now gives the neighbour the attributes `$toggleLink` sets, so the links do merge (one link, text coalesced), and checks the selected text.
## Test plan
### Before
The changed cell on the previous commit:
```
× with the autolink itself selected next to the same link, keeps its text selected
AssertionError: expected [ 1, 'see t30z now', '' ] to deeply equal [ 1, 'see t30z now', 't30z' ]
```
### After
```
$ pnpm exec vitest run --project unit packages/lexical-link
Tests 291 passed (291)
```
There was a problem hiding this comment.
Thanks, this looks good: replacing the AutoLinkNode with a LinkNode in $toggleLink fixes the reset URL from #9821, keeps the autolink's target and title when the call leaves them out, and undoes in one step. The suggestions below are optional and non-blocking.
-
"Link removed" is announced when a URL is set on an autolink (
packages/lexical-link/src/LexicalLinkNode.ts:810).AutoLinkExtensiondepends onAutoLinkAnnounceExtension, which counts onlyAutoLinkNodemutations (packages/lexical-link/src/AutoLinkAnnounceExtension.ts:72-103). This replace destroys an autolink without creating one, so a screen-reader user hears "Link removed" although the text is still a link. Tagging this update with$addUpdateTagand skipping tagged updates in the announcer, or not counting an autolink replaced by aLinkNodein the same update, would keep it quiet. -
Pin the other changed paths in
ToggleLinkOnAutoLink.test.ts. Only the first cell fails against the previous implementation; cells 2-4 pass onmainunchanged. Cell 3 (lines 197-207) passes onmainbecause there the node-selection path wraps the autolink in a newLinkNode(a link inside a link) and$link()finds the outer one; addingexpect(editor.read(() => $link().getChildren().every($isTextNode))).toBe(true), as cell 1 does, would pin the fix. A selection that starts in plain text and ends inside the autolink has no cell (onmain:link("see ")beside an autolink that gets reset; here: onelink("see t30z")), nor does a partial selection inside the autolink. Both fit the// @vitest-environment nodeunit tier described in AGENTS.md. -
Changeset
Verify:(.changeset/lexical-link-toggle-link-on-autolink.md:7). The playground's link editor already replaced the autolink itself after dispatchingTOGGLE_LINK_COMMAND(packages/lexical-playground/src/plugins/FloatingLinkEditorPlugin/index.tsx:325-336), so following this step there shows the same result before and after the change. CONTRIBUTING.md asksVerify:to say what to test; naming a directTOGGLE_LINK_COMMANDor$toggleLinkcall withAutoLinkExtensionwould show the fix. That playground branch is now redundant and could go in a follow-up. -
Test plan. AGENTS.md asks the Test plan to carry the real Before and After output of the command that was run. The Before output comes from the first version of the cell, which failed at the URL assertion; with the current cell,
mainfails earlier, atToggleLinkOnAutoLink.test.ts:91, and the package now has 291 tests rather than 288.
| const selection = $getSelection(); | ||
| const selected = | ||
| $isNodeSelection(selection) && selection.has(autoLink.getKey()); | ||
| autoLink.replace(replacement, true); |
There was a problem hiding this comment.
Optional: this replace destroys an AutoLinkNode without creating one, so the default AutoLinkAnnounceExtension (a dependency of AutoLinkExtension that counts only AutoLinkNode mutations, AutoLinkAnnounceExtension.ts:72-103) announces "Link removed" while the text is still a link. Tagging this update with $addUpdateTag(...) and skipping tagged updates in the announcer, or not counting an autolink replaced by a LinkNode in the same update, would keep it quiet.
| expect( | ||
| editor.read(() => { | ||
| const link = $link(); | ||
| const selection = $getSelection(); | ||
| return [ | ||
| $isAutoLinkNode(link), | ||
| link.getURL(), | ||
| selection === null ? null : selection.getTextContent(), | ||
| ]; | ||
| }), | ||
| ).toEqual([false, 'https://u1.test', 't30z']); |
There was a problem hiding this comment.
Optional: this cell also passes against the previous $toggleLink. There the node-selection path wraps the autolink in a new LinkNode (a link around the autolink), and $link() finds the outer link, so [false, 'https://u1.test', 't30z'] holds on both. Checking the link's children, as the first cell does, fails before the fix and passes after it:
expect(editor.read(() => $link().getChildren().every($isTextNode))).toBe(true);…es an autolink a link
## Description
Review: `AutoLinkAnnounceExtension` counts `AutoLinkNode` mutations, so replacing an autolink with a link (setting a URL on it) announced "Link removed" although the text is still a link. A destroyed autolink whose children are still in the document, in a link, is no longer counted. Also from the review: the node-selection cell now checks that the link holds the text (on `main` the node-selection path wrapped the autolink in a new link), new cells cover a selection from plain text into the autolink and one in part of it, and the changeset's `Verify:` names a direct `$toggleLink` / `TOGGLE_LINK_COMMAND` call (the playground's link editor already replaced the autolink).
## Test plan
### Before
On `main`'s `LexicalLinkNode.ts` (the target/title and neighbour cells guard behaviour `main` already has):
```
× keeps the URL it set after an edit of the text
✓ keeps the target and title of the autolink unless it sets them
× with the autolink itself selected, keeps what it holds selected
✓ with the autolink itself selected next to the same link, keeps its text selected
× with a selection from plain text into the autolink, makes it a link and keeps the URL
× with a selection in part of the autolink, makes it a link and keeps the URL
```
The announcer cell on the previous `AutoLinkAnnounceExtension.ts`:
```
× stays silent when $toggleLink makes the link a link of its own
AssertionError: expected 'Link removed' to be '' // Object.is equality
```
### After
```
$ pnpm exec vitest run --project unit packages/lexical-link
Tests 294 passed (294)
```
There was a problem hiding this comment.
This looks good to me. Replacing the AutoLinkNode with a LinkNode inside $toggleLink fixes the URL that AutoLinkExtension re-derived on the next edit (#9821), in one undo step, and the new cells fail against main's sources and pass here. As a bonus, an edited autolink now exports to Markdown as [t30z](https://u1.test) instead of bare text.
A few optional, non-blocking suggestions:
madeLinkalso matches a rebuilt autolink (packages/lexical-link/src/AutoLinkAnnounceExtension.ts:43).$isLinkNodeis true forAutoLinkNodetoo. When AutoLink rebuilds an autolink that holds more than one text node (part of the address bold, the stateAutoLinks.spec.mjscovers in "Can convert url-like text with formatting into links"),$createAutoLinkNode_moves the later text nodes into the new autolink by key, so the destruction is skipped, the creation is counted alone, and extending such an address announces "Link" wheremainstays silent. I reproduced it withwww.exaplus boldmple.co, then a boldmtyped after the link. Requiring a regular link keeps every new cell green:A cell for that rebuild would pin it. Relatedly, undoing the replacement restores the autolink asconst parent = node === null ? null : node.getParent(); return $isLinkNode(parent) && !$isAutoLinkNode(parent);
createdand announces "Link"; a matching check oncreated(its children were in a link inprevEditorState) would keep that quiet too.relnever falls back to the autolink's (packages/lexical-link/src/LexicalLinkNode.ts:803).$toggleLinkdefaultsrelto'noreferrer'at line 854, so it is neverundefinedthere. The behaviour matches regular links; the JSDoc and the description could say thatreldefaults tonoreferrer.- Changeset
Verify:(CONTRIBUTING.md, "Changesets"):$toggleLink(url)inside an autolink the user unlinked (isUnlinked, rendered as a<span>) now produces a real<a>, which is worth a sentence there. - Nits: AGENTS.md ("Reconciliation and Updates") prefers
editor.read('latest', ...)overeditor.getEditorState().read(...)in new code (AutoLinkAnnounceExtension.ts:40). The replacement also does not carry the autolink's element fields or NodeState (the playground's own replacement doesn't either), which may deserve a line in$replaceAutoLink's JSDoc. The Test plan's Before for the announcer cell shows the output with only the announcer taken frommain; with both files frommainit fails earlier, on the$isAutoLinkNodeassertion.
| editor.getEditorState().read(() => | ||
| children.some(child => { | ||
| const node = $getNodeByKey(child); | ||
| return node !== null && $isLinkNode(node.getParent()); |
There was a problem hiding this comment.
Optional: $isLinkNode is also true for an AutoLinkNode, so this matches a rebuilt autolink too. When AutoLink rebuilds an autolink that holds more than one text node (part of the address bold), $createAutoLinkNode_ moves the later text nodes into the new autolink by key, the destruction is skipped and the creation is counted alone, and extending the address announces "Link" where main stays silent (reproduced with www.exa plus bold mple.co, then a bold m typed after the link). Requiring a regular link keeps all the new cells green:
const parent = node === null ? null : node.getParent();
return $isLinkNode(parent) && !$isAutoLinkNode(parent);| title: null | string | undefined, | ||
| ): NodeKey { | ||
| const replacement = $createLinkNode(url, { | ||
| rel: rel !== undefined ? rel : autoLink.getRel(), |
There was a problem hiding this comment.
Nit: rel is never undefined here ($toggleLink defaults it to 'noreferrer' at line 854), so this fallback cannot be reached and the replacement always gets noreferrer or the caller's value, as a regular link does. Dropping the branch, or saying in the JSDoc above that rel defaults to noreferrer, would match what happens.
…s $toggleLink made links
## Description
Review: deciding from the document whether a destroyed autolink was made a link (a child of it still in a link) announced an autolink rebuilt with the same children as a new link, stayed silent when an autolink was removed after its text moved into another link, and announced "Link removed" when the new link merged into a neighbour and its text coalesced. `$toggleLink` now records the autolinks it makes links, per editor, and the announcer leaves out exactly those (`takeMadeLink`, internal, forgets each as it is seen). New cells: the merge into a neighbour (silent), a conversion beside two removals (`2 links removed`), and text moved into another link before the autolink is removed (`Link removed`).
## Test plan
### Before
The announcer cells on the previous commit:
```
× stays silent when the link $toggleLink makes merges into its neighbour
AssertionError: expected 'Link removed' to be '' // Object.is equality
× still announces a link removed after its text moved into another link
AssertionError: expected '' to be 'Link removed' // Object.is equality
```
### After
```
$ pnpm exec vitest run --project unit packages/lexical-link
Tests 297 passed (297)
```
… links to the state its update commits
## Description
Review: the record was per editor, by key, kept until the announcer saw the key destroyed, so it outlived the update that made it: with no announcer (or one disabled at the time) every conversion stayed in it, and a later real removal of an autolink with the same key (brought back by an undo, a restored state, or an update that threw) was not announced. The record is now kept for the editor state the update builds (its pending state, which its commit makes the editor's), weakly: an update that does not commit, and any later state, have none, and nothing outlives the state. New cell: an update that made the link a link threw, and the autolink is then removed (`Link removed`); and one for the removal after an undo.
## Test plan
### Before
The new cells on the previous commit:
```
× announces a link removed after an update that made it a link threw
```
### After
```
$ pnpm exec vitest run --project unit packages/lexical-link
Tests 299 passed (299)
```
There was a problem hiding this comment.
Thanks, this looks good. $toggleLink(url) now replaces an autolink it would update with a regular LinkNode, so the URL survives AutoLink's next pass over the text. The new cells in ToggleLinkOnAutoLink.test.ts and AutoLinkAnnounceExtension.test.ts fail without the fix and pass with it. The changeset follows CONTRIBUTING.md: a patch entry with a [fix] first line and a Verify: paragraph.
Two optional, non-blocking suggestions:
- Carry the autolink's NodeState (
packages/lexical-link/src/LexicalLinkNode.ts:822).$replaceAutoLinkcreates a freshLinkNodeand moves only the children, so NodeState an application set on the autolink is lost. Before this change the autolink itself stayed, so a URL toggle kept that state. Core's internal$carryNodeState(packages/lexical/src/LexicalNodeState.ts:1320) already does this for core's own type swaps. Exporting it, or adding an equivalent here, would keep that data across the conversion. AGENTS.md points ad-hoc node data to NodeState, so applications may expect it to survive. - The
relfallback is unreachable (packages/lexical-link/src/LexicalLinkNode.ts:823).$toggleLinkdefaultsrelto'noreferrer'(line 883), soautoLink.getRel()is never used, although the JSDoc above says attributes that are not given come from the autolink. Dropping the branch, or noting thenoreferrerdefault in the JSDoc, would match the behaviour.
| target: null | string | undefined, | ||
| title: null | string | undefined, | ||
| ): NodeKey { | ||
| const replacement = $createLinkNode(url, { |
There was a problem hiding this comment.
Optional: the new LinkNode gets only the children, so NodeState an app set on the autolink is lost. Before, the autolink stayed and kept it. Core's internal $carryNodeState (packages/lexical/src/LexicalNodeState.ts:1320, used at LexicalSelection.ts:460) does this for its own type swaps. Calling it, once exported, or an in-package equivalent before the replace would keep that data:
$carryNodeState(autoLink, replacement);
autoLink.replace(replacement, true);Excluding AutoLinkNode from the collapsed-selection guard also made $toggleLink(url) a no-op inside an autolink, which since meta#9822 replaces it with a LinkNode to the new URL, as the floating link editor relies on. Return early only when the caret is in no link at all. Say in the JSDoc and the changeset that a collapsed selection outside a link is left alone, and remove a duplicate expect import from the e2e spec left by the rebase. Co-authored-by: Ved Thakar <111605341+Vedthakar@users.noreply.github.com> Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Description
$toggleLink(url)with a selection inside anAutoLinkNodeset that autolink's URL in place and left it anAutoLinkNode;AutoLinkExtensionre-derives an autolink's URL from its text on the next transform of its text node (any edit of the link's text, or a load), so the URL the user set was lost (#9821).$toggleLinknow replaces anAutoLinkNodeit would update with aLinkNodeholding the same children, with the URL, and the rel, target and title it was given or, where not given, the autolink's own (so a matcher's target and title, and those the playground's link editor copies over, are kept). This covers the range-selection paths and the node-selection path (an autolink around a selected node). AutoLink leaves text inside a link alone, so it stays a link.AutoLinkAnnounceExtensionno longer announces "Link removed" for an autolink made a link this way:$toggleLinkrecords the autolinks it makes links for the editor state its update commits (weakly; an update that does not commit, and later states, have none), and the announcer leaves those out. Known limit: a redo (or a restored state) of such an update announces "Link removed", as the restored state is a clone without the record.Selection: a range selection inside the autolink is unchanged. With the autolink itself in a node selection, its text is selected as a range, which follows the new link if it merges into a neighbouring link with the same attributes and their text coalesces (Lexical's normalization moves only range points along). Known limit: a node selection holding the autolink and another node, where the new link then merges into such a neighbour, loses the autolink's part (a node selection drops nodes that merge away, and a multi-node selection cannot become a range); on
mainthe autolink is never replaced there, which is what loses the URL.Closes #9821
Test plan
Before
pnpm exec vitest run --project unit packages/lexical-link/src/__tests__/unit/ToggleLinkOnAutoLink.test.ts packages/lexical-link/src/__tests__/unit/AutoLinkAnnounceExtension.test.tsonmain'sLexicalLinkNode.tsandAutoLinkAnnounceExtension.ts(the target/title and neighbour cells guard behaviourmainalready has):After
(The full unit run is from the first fix commit; the later commits change only
$toggleLink's autolink path and its cells.) Each later commit's message shows its new cells failing before it.