@byline/richtext-lexical 6.14.1 → 6.15.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,47 @@
1
+ /**
2
+ * This Source Code Form is subject to the terms of the Mozilla Public
3
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
4
+ * file, You can obtain one at https://mozilla.org/MPL/2.0/.
5
+ *
6
+ * Copyright (c) Infonomic Company Limited
7
+ */
8
+
9
+ /** How the value whose baseline is established fared against the editor. */
10
+ export type BaselineStatus = 'ok' | 'adapted'
11
+
12
+ /**
13
+ * Whether `ApplyValuePlugin` has established the emission baseline for the
14
+ * value the editor currently holds. `ready` is called exactly where the
15
+ * plugin sets `hasNormalizedBaselineRef.current = true`; `reset` wherever it
16
+ * starts applying a different value, refuses one, or receives null. Reading
17
+ * it leaves the emission gate unchanged.
18
+ */
19
+ export interface BaselineSignal {
20
+ /** The established baseline's status, or `null` while none is established. */
21
+ status(): BaselineStatus | null
22
+ ready(status: BaselineStatus): void
23
+ reset(): void
24
+ /** Notified when a baseline becomes established. */
25
+ subscribe(listener: () => void): () => void
26
+ }
27
+
28
+ export function createBaselineSignal(): BaselineSignal {
29
+ const listeners = new Set<() => void>()
30
+ let current: BaselineStatus | null = null
31
+ return {
32
+ status: () => current,
33
+ ready(status) {
34
+ current = status
35
+ for (const listener of [...listeners]) listener()
36
+ },
37
+ reset() {
38
+ current = null
39
+ },
40
+ subscribe(listener) {
41
+ listeners.add(listener)
42
+ return () => {
43
+ listeners.delete(listener)
44
+ }
45
+ },
46
+ }
47
+ }
@@ -1 +1,4 @@
1
1
  export const APPLY_VALUE_TAG = 'payload-apply-value'
2
+
3
+ /** Tags the selection-only update that puts a restored caret back after a save. */
4
+ export const SELECTION_RESTORE_TAG = 'byline-selection-restore'
@@ -0,0 +1,211 @@
1
+ /**
2
+ * This Source Code Form is subject to the terms of the Mozilla Public
3
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
4
+ * file, You can obtain one at https://mozilla.org/MPL/2.0/.
5
+ *
6
+ * Copyright (c) Infonomic Company Limited
7
+ */
8
+
9
+ import type { SerializedEditorState } from 'lexical'
10
+ import { describe, expect, it } from 'vitest'
11
+
12
+ import { contentFingerprint } from './content-fingerprint'
13
+
14
+ // The unchanged-content rule for rich-text caret replay: after a save, the
15
+ // caret is replayed only when the reloaded content has the same fingerprint
16
+ // as the content that was saved. Only metadata the save path itself
17
+ // refreshes on embeds may differ.
18
+
19
+ type Json = any
20
+
21
+ const text = (value: string) => ({
22
+ detail: 0,
23
+ format: 0,
24
+ mode: 'normal',
25
+ style: '',
26
+ text: value,
27
+ type: 'text',
28
+ version: 1,
29
+ })
30
+ const block = (type: string, children: unknown[], extra: Record<string, unknown> = {}) => ({
31
+ children,
32
+ direction: null,
33
+ format: '',
34
+ indent: 0,
35
+ type,
36
+ version: 1,
37
+ ...extra,
38
+ })
39
+ const content = (...children: unknown[]): Json => ({
40
+ root: { children, direction: null, format: '', indent: 0, type: 'root', version: 1 },
41
+ })
42
+ const paragraph = (value: string) => block('paragraph', [text(value)])
43
+
44
+ const internalLink = (label: string) =>
45
+ block('link', [text(label)], {
46
+ version: 2,
47
+ attributes: {
48
+ linkType: 'internal',
49
+ targetDocumentId: 'page-1',
50
+ targetCollectionId: 'pages-id',
51
+ targetCollectionPath: 'pages',
52
+ document: { title: 'A page', path: '/pages/a-page' },
53
+ },
54
+ })
55
+ const customLink = (label: string, url: string) =>
56
+ block('link', [text(label)], { version: 2, attributes: { linkType: 'custom', url } })
57
+ const embedImage = () =>
58
+ block('paragraph', [
59
+ {
60
+ type: 'inline-image',
61
+ version: 1,
62
+ targetDocumentId: 'media-1',
63
+ targetCollectionId: 'media-id',
64
+ targetCollectionPath: 'media',
65
+ document: {
66
+ title: 'Cat',
67
+ altText: 'a cat',
68
+ image: { storageUrl: '/cat.png' },
69
+ focalPoint: 'center',
70
+ },
71
+ src: '/cat.png',
72
+ position: 'full',
73
+ altText: 'an authored cat',
74
+ width: 10,
75
+ height: 10,
76
+ showCaption: true,
77
+ caption: { editorState: content(paragraph('A cat')) },
78
+ link: {
79
+ linkType: 'internal',
80
+ targetDocumentId: 'page-2',
81
+ targetCollectionId: 'pages-id',
82
+ targetCollectionPath: 'pages',
83
+ document: { title: 'Another page', path: '/pages/another' },
84
+ },
85
+ },
86
+ ])
87
+ const saved = (): Json =>
88
+ content(
89
+ block('paragraph', [
90
+ text('HelloQ world '),
91
+ internalLink('inside'),
92
+ text(' and '),
93
+ customLink('outside', 'https://example.com/a'),
94
+ ]),
95
+ embedImage()
96
+ )
97
+
98
+ /** Every node reachable through `children`, depth first. */
99
+ function* nodesOf(node: Json): Generator<Json> {
100
+ yield node
101
+ for (const child of node.children ?? []) yield* nodesOf(child)
102
+ }
103
+ const findNode = (state: Json, predicate: (node: Json) => boolean): Json => {
104
+ const found = [...nodesOf(state.root)].find(predicate)
105
+ if (found == null) throw new Error('fixture node not found')
106
+ return found
107
+ }
108
+ const imageOf = (state: Json) => findNode(state, (node) => node.type === 'inline-image')
109
+ const linkOf = (state: Json, linkType: string) =>
110
+ findNode(state, (node) => node.type === 'link' && node.attributes?.linkType === linkType)
111
+
112
+ /** The fingerprint of a copy of the saved fixture after `serverCopy` changes it. */
113
+ const reloaded = (serverCopy: (state: Json) => void) => {
114
+ const state = saved()
115
+ serverCopy(state)
116
+ return contentFingerprint(state as SerializedEditorState)
117
+ }
118
+
119
+ describe('contentFingerprint', () => {
120
+ const original = contentFingerprint(saved() as SerializedEditorState)
121
+
122
+ it.each([
123
+ ['plain unchanged content', () => {}],
124
+ [
125
+ 'the same embeds with only server-refreshed metadata',
126
+ (state: Json) => {
127
+ const image = imageOf(state)
128
+ image.src = '/media/cat-tablet.webp'
129
+ image.width = 768
130
+ image.height = 512
131
+ image.document = {
132
+ ...image.document,
133
+ title: 'Cat, renamed',
134
+ altText: 'a cat, refreshed',
135
+ image: { storageUrl: '/media/cat.webp' },
136
+ sizes: [{ name: 'tablet', url: '/media/cat-tablet.webp' }],
137
+ _resolved: true,
138
+ }
139
+ image.link.document = { title: 'Another page, renamed', path: '/pages/moved' }
140
+ linkOf(state, 'internal').attributes.document = {
141
+ title: 'A page, renamed',
142
+ path: '/pages/renamed',
143
+ }
144
+ },
145
+ ],
146
+ ])('%s: the fingerprint matches, so the caret is replayed', (_name, serverCopy) => {
147
+ expect(reloaded(serverCopy)).toBe(original)
148
+ })
149
+
150
+ it.each([
151
+ [
152
+ 'a text change',
153
+ (state: Json) => {
154
+ findNode(state, (node) => node.type === 'text').text = 'Hello world '
155
+ },
156
+ ],
157
+ [
158
+ 'a link URL change',
159
+ (state: Json) => {
160
+ linkOf(state, 'custom').attributes.url = 'https://example.com/b'
161
+ },
162
+ ],
163
+ [
164
+ 'an internal link to a different document',
165
+ (state: Json) => {
166
+ linkOf(state, 'internal').attributes.targetDocumentId = 'page-9'
167
+ },
168
+ ],
169
+ [
170
+ 'a swapped image (a different media document)',
171
+ (state: Json) => {
172
+ const image = imageOf(state)
173
+ image.targetDocumentId = 'media-2'
174
+ image.src = '/dog.png'
175
+ },
176
+ ],
177
+ [
178
+ 'a formatting change (bold toggled)',
179
+ (state: Json) => {
180
+ findNode(state, (node) => node.type === 'text').format = 1
181
+ },
182
+ ],
183
+ [
184
+ 'a changed caption',
185
+ (state: Json) => {
186
+ imageOf(state).caption.editorState.root.children[0].children[0].text = 'A dog'
187
+ },
188
+ ],
189
+ [
190
+ 'an attribute the rule does not know about',
191
+ (state: Json) => {
192
+ imageOf(state).document.focalPoint = 'top'
193
+ },
194
+ ],
195
+ [
196
+ 'an authored alt text change',
197
+ (state: Json) => {
198
+ imageOf(state).altText = 'an authored dog'
199
+ },
200
+ ],
201
+ ])('%s: the fingerprint differs, so no caret is replayed', (_name, serverCopy) => {
202
+ expect(reloaded(serverCopy)).not.toBe(original)
203
+ })
204
+
205
+ it('does not modify the state it fingerprints', () => {
206
+ const state = saved()
207
+ const before = JSON.stringify(state)
208
+ contentFingerprint(state as SerializedEditorState)
209
+ expect(JSON.stringify(state)).toBe(before)
210
+ })
211
+ })
@@ -0,0 +1,99 @@
1
+ /**
2
+ * This Source Code Form is subject to the terms of the Mozilla Public
3
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
4
+ * file, You can obtain one at https://mozilla.org/MPL/2.0/.
5
+ *
6
+ * Copyright (c) Infonomic Company Limited
7
+ */
8
+
9
+ import type { SerializedEditorState } from 'lexical'
10
+
11
+ import { hashSerializedState } from './utils/hashSerializedState'
12
+
13
+ type JsonNode = Record<string, unknown> & { children?: unknown }
14
+
15
+ const isRecord = (value: unknown): value is Record<string, unknown> =>
16
+ value != null && typeof value === 'object' && !Array.isArray(value)
17
+
18
+ /**
19
+ * Removes `keys` from the relation envelope `holder.document`, dropping the
20
+ * envelope when nothing else is left in it (the walker may create an
21
+ * envelope holding only `_resolved`).
22
+ */
23
+ function stripEnvelope(holder: Record<string, unknown>, keys: readonly string[]): void {
24
+ const envelope = holder.document
25
+ if (!isRecord(envelope)) return
26
+ const next = { ...envelope }
27
+ for (const key of keys) delete next[key]
28
+ if (Object.keys(next).length === 0) delete holder.document
29
+ else holder.document = next
30
+ }
31
+
32
+ const hasIdentity = (relation: Record<string, unknown>): boolean =>
33
+ Boolean(relation.targetCollectionPath) && Boolean(relation.targetDocumentId)
34
+
35
+ /**
36
+ * The allow-list of what the save path may rewrite on a node whose embed
37
+ * identity is unchanged, keyed by node type. Everything not listed here is
38
+ * significant: author formatting, a custom link's URL, an embed's identity
39
+ * (`targetCollectionPath` / `targetDocumentId`), an image's position and
40
+ * authored alt text, its caption and click-through link target, and any
41
+ * attribute this list does not know about.
42
+ *
43
+ * Source: the write-time embed (`packages/core/src/services/richtext-embed.ts`
44
+ * → `lexicalEditorEmbedServer` in `src/server.ts`) runs these visitors over
45
+ * the nodes reachable through `children` (`iterAllNodes` in
46
+ * `lexical-populate-shared.ts`), never into a caption's nested editor state:
47
+ *
48
+ * - `inlineImageVisitor` (`extensions/inline-image/populate.ts`), for an
49
+ * `inline-image` node with both identity fields: replaces `document.title`,
50
+ * `document.altText`, `document.image`, `document.sizes` and
51
+ * `document._resolved`, and the preview `src`, `width` and `height`.
52
+ * - `inlineImageLinkVisitor` (same file) through `createInternalLinkHydration`
53
+ * (`extensions/link/populate.ts`), for an internal click-through `link` with
54
+ * both identity fields: replaces `link.document.title`, `link.document.path`
55
+ * and `link.document._resolved`.
56
+ * - `linkVisitor` (`extensions/link/populate.ts`), for a `link` node whose
57
+ * `attributes.linkType` is `internal` with both identity fields: replaces
58
+ * `attributes.document.title`, `attributes.document.path` and
59
+ * `attributes.document._resolved`.
60
+ */
61
+ function stripRefreshedMetadata(node: JsonNode): void {
62
+ if (node.type === 'inline-image' && hasIdentity(node)) {
63
+ delete node.src
64
+ delete node.width
65
+ delete node.height
66
+ stripEnvelope(node, ['title', 'altText', 'image', 'sizes', '_resolved'])
67
+ const link = node.link
68
+ if (isRecord(link) && link.linkType === 'internal' && hasIdentity(link)) {
69
+ const next = { ...link }
70
+ stripEnvelope(next, ['title', 'path', '_resolved'])
71
+ node.link = next
72
+ }
73
+ }
74
+ if (node.type === 'link' && isRecord(node.attributes)) {
75
+ const attributes = node.attributes
76
+ if (attributes.linkType === 'internal' && hasIdentity(attributes)) {
77
+ const next = { ...attributes }
78
+ stripEnvelope(next, ['title', 'path', '_resolved'])
79
+ node.attributes = next
80
+ }
81
+ }
82
+ // Only `children` are walked, as the embed walker does: a caption's
83
+ // nested editor state stays fully significant.
84
+ if (Array.isArray(node.children)) {
85
+ for (const child of node.children) if (isRecord(child)) stripRefreshedMetadata(child)
86
+ }
87
+ }
88
+
89
+ /**
90
+ * A fingerprint of the editor's normalized content as a save would store
91
+ * it, with only the server-refreshed embed metadata above left out. Two
92
+ * states with the same fingerprint differ at most in values the save path
93
+ * itself rewrites, so a caret recorded in one fits the other.
94
+ */
95
+ export function contentFingerprint(state: SerializedEditorState): string {
96
+ const copy = JSON.parse(JSON.stringify(state)) as { root?: unknown }
97
+ if (isRecord(copy.root)) stripRefreshedMetadata(copy.root)
98
+ return hashSerializedState(copy as unknown as SerializedEditorState)
99
+ }
@@ -31,10 +31,16 @@ import { hashSerializedState } from './utils/hashSerializedState'
31
31
  // A stub with only the core types means nothing in these fixtures needs
32
32
  // converting, so the plugin's apply behaviour is what is under test here
33
33
  // rather than normalization (covered in `normalize/`).
34
+ let appliedState: unknown = null
34
35
  const mockEditor = {
35
36
  update: (fn: () => void) => fn(),
36
37
  parseEditorState: vi.fn((val) => val),
37
- setEditorState: vi.fn(),
38
+ setEditorState: vi.fn((state: unknown) => {
39
+ appliedState = state
40
+ }),
41
+ // ApplyValuePlugin reads the settled state two animation frames after it
42
+ // applies a value; without this the frame fires after the test and throws.
43
+ getEditorState: () => ({ toJSON: () => appliedState }),
38
44
  _nodes: new Map<string, unknown>([
39
45
  ['root', {}],
40
46
  ['paragraph', {}],
@@ -17,7 +17,9 @@ import { ErrorBoundary } from 'react-error-boundary'
17
17
 
18
18
  import { richTextValidate } from '../validate/validate'
19
19
  import { ApplyValuePlugin } from './apply-value-plugin'
20
+ import { createBaselineSignal } from './baseline-signal'
20
21
  import { EditorContext } from './editor-context'
22
+ import { SelectionRestorePlugin } from './selection-restore-plugin'
21
23
  import { hashSerializedState } from './utils/hashSerializedState'
22
24
  import type { EditorFieldProps } from '../types'
23
25
 
@@ -52,6 +54,7 @@ export const EditorComponent = memo(function EditorComponent({
52
54
  featureBeforeEditor,
53
55
  featureAfterEditor,
54
56
  featureChildren,
57
+ selectionMemory,
55
58
  }: EditorFieldProps): React.JSX.Element {
56
59
  const disabled = readonly ?? false
57
60
  const dispatchFieldUpdateTask = useRef<number>(undefined)
@@ -62,6 +65,7 @@ export const EditorComponent = memo(function EditorComponent({
62
65
  const lastEmittedHashRef = useRef<string | undefined>(undefined)
63
66
  const normalizedIncomingHashRef = useRef<string | undefined>(undefined)
64
67
  const hasNormalizedBaselineRef = useRef<boolean>(false)
68
+ const baselineSignal = useMemo(createBaselineSignal, [])
65
69
  // const _debugLogCountRef = useRef<number>(0)
66
70
 
67
71
  // TODO: implement validation handling (currently unused)
@@ -187,7 +191,12 @@ export const EditorComponent = memo(function EditorComponent({
187
191
  lastEmittedHashRef={lastEmittedHashRef}
188
192
  normalizedIncomingHashRef={normalizedIncomingHashRef}
189
193
  hasNormalizedBaselineRef={hasNormalizedBaselineRef}
194
+ onBaselineReady={selectionMemory ? baselineSignal.ready : undefined}
195
+ onBaselineReset={selectionMemory ? baselineSignal.reset : undefined}
190
196
  />
197
+ {selectionMemory && (
198
+ <SelectionRestorePlugin memory={selectionMemory} baseline={baselineSignal} />
199
+ )}
191
200
  {featureChildren}
192
201
  </EditorContext>
193
202
  </ErrorBoundary>
@@ -0,0 +1,236 @@
1
+ 'use client'
2
+
3
+ /**
4
+ * This Source Code Form is subject to the terms of the Mozilla Public
5
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
6
+ * file, You can obtain one at https://mozilla.org/MPL/2.0/.
7
+ *
8
+ * Copyright (c) Infonomic Company Limited
9
+ */
10
+
11
+ import { useEffect } from 'react'
12
+
13
+ import type { RichTextSelectionMemory, StructuralSelection } from '@byline/admin/react'
14
+ import { useLexicalComposerContext } from '@lexical/react/LexicalComposerContext'
15
+ import {
16
+ $createRangeSelection,
17
+ $getRoot,
18
+ $getSelection,
19
+ $isElementNode,
20
+ $isRangeSelection,
21
+ $isRootNode,
22
+ $isTextNode,
23
+ $setSelection,
24
+ type LexicalEditor,
25
+ type LexicalNode,
26
+ type PointType,
27
+ SKIP_SCROLL_INTO_VIEW_TAG,
28
+ } from 'lexical'
29
+
30
+ import { APPLY_VALUE_TAG, SELECTION_RESTORE_TAG } from './constants'
31
+ import { contentFingerprint } from './content-fingerprint'
32
+ import type { BaselineSignal } from './baseline-signal'
33
+
34
+ type StructuralPoint = StructuralSelection['anchor']
35
+
36
+ /** Child indexes from the root down to `node`; `null` when it is detached. */
37
+ function $pathOf(node: LexicalNode): number[] | null {
38
+ const path: number[] = []
39
+ let current: LexicalNode | null = node
40
+ while (current != null && !$isRootNode(current)) {
41
+ path.unshift(current.getIndexWithinParent())
42
+ current = current.getParent()
43
+ }
44
+ return current == null ? null : path
45
+ }
46
+
47
+ function $structuralPoint(point: PointType): StructuralPoint | null {
48
+ const path = $pathOf(point.getNode())
49
+ return path == null ? null : { path, offset: point.offset }
50
+ }
51
+
52
+ /** The node and point type at a structural point, or `null` when it no longer fits. */
53
+ function $resolvePoint(
54
+ point: StructuralPoint
55
+ ): { key: string; offset: number; type: 'text' | 'element' } | null {
56
+ let node: LexicalNode = $getRoot()
57
+ for (const index of point.path) {
58
+ if (!$isElementNode(node)) return null
59
+ const child = node.getChildAtIndex(index)
60
+ if (child == null) return null
61
+ node = child
62
+ }
63
+ if (point.offset < 0) return null
64
+ if ($isTextNode(node)) {
65
+ if (point.offset > node.getTextContentSize()) return null
66
+ return { key: node.getKey(), offset: point.offset, type: 'text' }
67
+ }
68
+ if ($isElementNode(node)) {
69
+ if (point.offset > node.getChildrenSize()) return null
70
+ return { key: node.getKey(), offset: point.offset, type: 'element' }
71
+ }
72
+ return null
73
+ }
74
+
75
+ /**
76
+ * The fingerprint of the content the editor holds, as a save stores it
77
+ * (`contentFingerprint`). Computed once when a save begins and once when
78
+ * the restoration compares, never per caret move.
79
+ */
80
+ function editorFingerprint(editor: LexicalEditor): string {
81
+ return contentFingerprint(editor.getEditorState().toJSON())
82
+ }
83
+
84
+ /** Edits that originate inside the root's DOM but outside its own content. */
85
+ const NESTED_EDIT_EVENTS = ['beforeinput', 'input', 'paste', 'cut', 'drop'] as const
86
+
87
+ /**
88
+ * Records the root editor's selection while its field is the working
89
+ * target, and puts it back after a successful save. Mounted in the field's
90
+ * root editor only, and only when the form has a visit store, so nested
91
+ * editors (image captions, admonition bodies) and untracked forms never
92
+ * record.
93
+ *
94
+ * Recording reads the selection's structural points only, deferred to a
95
+ * microtask so the form has recorded the working target from the same
96
+ * input event, and only while the root's own content-editable holds focus.
97
+ * The content fingerprint is computed on demand when a save begins. An edit
98
+ * inside a nested editor, or a non-range root selection (a selected image),
99
+ * clears the recorded selection. Unmounting releases this editor's live
100
+ * selection from the visit store, which outlives it.
101
+ *
102
+ * Restoring is a rendezvous between two conditions that may arrive in
103
+ * either order: `ApplyValuePlugin` has established the baseline for the
104
+ * value the editor holds (tracked by `baseline`, and reset whenever a
105
+ * different, refused or null value arrives), and the current successful
106
+ * save's restoration has handed on a selection (`memory`). The selection is
107
+ * taken once, when both hold. The caret is placed only when the value was
108
+ * not adapted, the content fingerprint matches (only server-refreshed embed
109
+ * metadata may differ), both points resolve, and
110
+ * the control restoration focused still holds focus. The update is
111
+ * selection-only and runs outside any other update, so it never reaches the
112
+ * form's `onChange`.
113
+ */
114
+ export function SelectionRestorePlugin({
115
+ memory,
116
+ baseline,
117
+ }: {
118
+ memory: RichTextSelectionMemory
119
+ baseline: BaselineSignal
120
+ }): null {
121
+ const [editor] = useLexicalComposerContext()
122
+
123
+ useEffect(() => {
124
+ let disposed = false
125
+ let scheduled = false
126
+ // Identifies this editor instance's recordings, so its teardown releases
127
+ // only what it recorded, never a newer instance's selection.
128
+ const owner = {}
129
+ // Never serializes a torn-down editor, even if a save begins before the
130
+ // release below has run.
131
+ const fingerprint = () => (disposed ? null : editorFingerprint(editor))
132
+
133
+ const record = () => {
134
+ scheduled = false
135
+ if (disposed) return
136
+ const rootElement = editor.getRootElement()
137
+ const selection = editor.getEditorState().read(() => {
138
+ const current = $getSelection()
139
+ if (current == null) return undefined
140
+ if (!$isRangeSelection(current)) return null
141
+ const anchor = $structuralPoint(current.anchor)
142
+ const focus = $structuralPoint(current.focus)
143
+ return anchor && focus ? { anchor, focus } : undefined
144
+ })
145
+ // A selected image or table cells: an older caret must not survive it.
146
+ if (selection === null) {
147
+ memory.clear()
148
+ return
149
+ }
150
+ if (rootElement == null || rootElement.ownerDocument.activeElement !== rootElement) return
151
+ if (selection !== undefined) memory.record(selection, fingerprint, owner)
152
+ }
153
+
154
+ const unregisterUpdates = editor.registerUpdateListener(({ tags }) => {
155
+ if (tags.has(APPLY_VALUE_TAG) || scheduled) return
156
+ scheduled = true
157
+ queueMicrotask(record)
158
+ })
159
+
160
+ // An edit belongs to a nested editor (or a control inside a decorator)
161
+ // when its nearest editing boundary is not the root itself. A paste can
162
+ // target a text span inside the root; that is still a root edit.
163
+ const onNestedEdit = (event: Event) => {
164
+ const target = event.target as Node | null
165
+ const element = target instanceof Element ? target : (target?.parentElement ?? null)
166
+ if (element?.closest('[contenteditable]') !== editor.getRootElement()) memory.clear()
167
+ }
168
+ const unregisterRoot = editor.registerRootListener((rootElement, previous) => {
169
+ for (const type of NESTED_EDIT_EVENTS) {
170
+ previous?.removeEventListener(type, onNestedEdit, true)
171
+ rootElement?.addEventListener(type, onNestedEdit, true)
172
+ }
173
+ })
174
+
175
+ return () => {
176
+ disposed = true
177
+ unregisterUpdates()
178
+ unregisterRoot()
179
+ // The visit store outlives this editor: drop its live selection, and
180
+ // with it the closure over the editor. A selection a save has already
181
+ // snapshotted is kept for the editor that replaces this one.
182
+ memory.release(owner)
183
+ }
184
+ }, [editor, memory])
185
+
186
+ useEffect(() => {
187
+ let disposed = false
188
+
189
+ const reconcile = () => {
190
+ if (disposed) return
191
+ const status = baseline.status()
192
+ // Without a baseline for the value the editor holds, a grant waits.
193
+ if (status == null) return
194
+ // Taken once, here: an adapted value spends the grant without a caret.
195
+ const taken = memory.take()
196
+ if (taken == null || status !== 'ok' || !editor.isEditable()) return
197
+ const rootElement = editor.getRootElement()
198
+ if (rootElement == null) return
199
+ if (editorFingerprint(editor) !== taken.fingerprint) return
200
+
201
+ const points = editor.getEditorState().read(() => {
202
+ const anchor = $resolvePoint(taken.sel.anchor)
203
+ const focus = $resolvePoint(taken.sel.focus)
204
+ return anchor && focus ? { anchor, focus } : null
205
+ })
206
+ if (points == null) return
207
+
208
+ // Focus first, so the browser's own caret placement on focus is
209
+ // superseded by the selection set synchronously below.
210
+ rootElement.focus({ preventScroll: true })
211
+ editor.update(
212
+ () => {
213
+ const selection = $createRangeSelection()
214
+ selection.anchor.set(points.anchor.key, points.anchor.offset, points.anchor.type)
215
+ selection.focus.set(points.focus.key, points.focus.offset, points.focus.type)
216
+ $setSelection(selection)
217
+ },
218
+ // Restoration has already re-anchored the scroll position.
219
+ { discrete: true, tag: [SELECTION_RESTORE_TAG, SKIP_SCROLL_INTO_VIEW_TAG] }
220
+ )
221
+ }
222
+
223
+ // A baseline is signalled from a frame or a layout effect, outside any
224
+ // editor update. Store notifications can come from anywhere, so they
225
+ // are reconciled on a microtask.
226
+ const unsubscribeBaseline = baseline.subscribe(reconcile)
227
+ const unsubscribeMemory = memory.subscribe(() => queueMicrotask(reconcile))
228
+ return () => {
229
+ disposed = true
230
+ unsubscribeBaseline()
231
+ unsubscribeMemory()
232
+ }
233
+ }, [baseline, editor, memory])
234
+
235
+ return null
236
+ }