fix(richtext-lexical): preserve selection in Firefox when using LexicalMenu (#10867)

Fixes #10724

The selection is never touched in an `editor.read`, but BEFORE starting
an `editor.update` it is synced with `window.selection`. Firefox for
some reason loses the editor selection, so on the next update the
selection is null.

For reference, there was a brief discussion on the Lexical Discord
server:
https://discord.com/channels/953974421008293909/1333916489870348309
This commit is contained in:
Germán Jabloñski
2025-01-29 12:18:24 -03:00
committed by GitHub
parent 3094c92ef3
commit 0e5ff246b2

View File

@@ -1,5 +1,5 @@
'use client'
import type { LexicalCommand, LexicalEditor, TextNode } from 'lexical'
import type { BaseSelection, LexicalCommand, LexicalEditor, TextNode } from 'lexical'
import type { JSX, ReactPortal, RefObject } from 'react'
import { useLexicalComposerContext } from '@lexical/react/LexicalComposerContext.js'
@@ -7,6 +7,7 @@ import { mergeRegister } from '@lexical/utils'
import {
$getSelection,
$isRangeSelection,
$setSelection,
COMMAND_PRIORITY_LOW,
createCommand,
KEY_ARROW_DOWN_COMMAND,
@@ -266,6 +267,17 @@ export function LexicalMenu({
})
setTimeout(() => {
// Needed in Firefox. See https://github.com/payloadcms/payload/issues/10724
let selection: BaseSelection | undefined
editor.read(() => {
selection = $getSelection()?.clone()
})
editor.update(() => {
if (selection) {
$setSelection(selection)
}
})
selectedItem.onSelect({
editor,
queryString: resolution.match ? resolution.match.matchingString : '',