@byline/richtext-lexical 6.14.0 → 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,328 @@
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 { act } from 'react'
10
+
11
+ import {
12
+ BylineFieldServicesProvider,
13
+ claimSaveAttempt,
14
+ createEditorViewStateStore,
15
+ type EditorViewStateStore,
16
+ FormRenderer,
17
+ type RichTextSelectionMemory,
18
+ useRichTextSelectionMemory,
19
+ } from '@byline/admin/react'
20
+ import { defineAdminConfig, type RichTextEditorComponent } from '@byline/core'
21
+ import { adminTranslations } from '@byline/i18n/admin'
22
+ import { I18nProvider } from '@byline/i18n/react'
23
+ import {
24
+ $getRoot,
25
+ $getSelection,
26
+ $isRangeSelection,
27
+ $isTextNode,
28
+ type LexicalEditor,
29
+ type SerializedEditorState,
30
+ } from 'lexical'
31
+ import { createRoot, type Root } from 'react-dom/client'
32
+ import { afterEach, beforeAll, beforeEach, describe, expect, it, vi } from 'vitest'
33
+
34
+ import { RichTextField } from '../richtext-field'
35
+ import { defaultClientEditorConfig } from './config/default-extensions'
36
+ import { installFrameControl } from './test-support/frame-control'
37
+
38
+ ;(globalThis as any).IS_REACT_ACT_ENVIRONMENT = true
39
+
40
+ const counters = vi.hoisted(() => ({ pluginRenders: 0 }))
41
+
42
+ // Counts the selection plugin's renders, so a test can prove an untracked
43
+ // form never mounts it.
44
+ vi.mock('./selection-restore-plugin', async (importOriginal) => {
45
+ const actual = await importOriginal<typeof import('./selection-restore-plugin')>()
46
+ return {
47
+ SelectionRestorePlugin: (props: Parameters<typeof actual.SelectionRestorePlugin>[0]) => {
48
+ counters.pluginRenders++
49
+ return actual.SelectionRestorePlugin(props)
50
+ },
51
+ }
52
+ })
53
+
54
+ /** The field's selection memory, as the editor itself sees it. */
55
+ const probe: { memory: RichTextSelectionMemory | null } = { memory: null }
56
+
57
+ const TestEditor: RichTextEditorComponent = (props) => {
58
+ probe.memory = useRichTextSelectionMemory(props.path ?? props.field.name)
59
+ return <RichTextField {...props} editorConfig={defaultClientEditorConfig} />
60
+ }
61
+
62
+ defineAdminConfig({
63
+ i18n: {
64
+ admin: { defaultLocale: 'en', locales: ['en'] },
65
+ content: { defaultLocale: 'en', locales: ['en'] },
66
+ },
67
+ collections: [
68
+ {
69
+ path: 'pages',
70
+ labels: { singular: 'Page', plural: 'Pages' },
71
+ fields: [{ name: 'title', label: 'Title', type: 'text' }],
72
+ },
73
+ ],
74
+ fields: { richText: { editor: TestEditor } },
75
+ })
76
+
77
+ const fields = [
78
+ { name: 'title', label: 'Title', type: 'text' as const, optional: true },
79
+ { name: 'body', label: 'Body', type: 'richText' as const, optional: true },
80
+ ]
81
+
82
+ const text = (value: string) => ({
83
+ detail: 0,
84
+ format: 0,
85
+ mode: 'normal',
86
+ style: '',
87
+ text: value,
88
+ type: 'text',
89
+ version: 1,
90
+ })
91
+ const block = (type: string, children: unknown[], extra: Record<string, unknown> = {}) => ({
92
+ children,
93
+ direction: null,
94
+ format: '',
95
+ indent: 0,
96
+ type,
97
+ version: 1,
98
+ textFormat: 0,
99
+ textStyle: '',
100
+ ...extra,
101
+ })
102
+ const content = (...children: unknown[]): any => ({
103
+ root: { children, direction: null, format: '', indent: 0, type: 'root', version: 1 },
104
+ })
105
+ const paragraph = (value: string) => block('paragraph', [text(value)])
106
+ const doc = (revision: number, body: SerializedEditorState, versionId = `v${revision}`) => ({
107
+ id: 'doc',
108
+ versionId,
109
+ revision,
110
+ status: 'draft',
111
+ fields: { title: 'Title', body },
112
+ })
113
+
114
+ // jsdom lays nothing out, and implements no range geometry at all; Lexical
115
+ // measures the caret to scroll it into view.
116
+ Range.prototype.getBoundingClientRect ??= () =>
117
+ DOMRect.fromRect({ x: 0, y: 0, width: 0, height: 0 })
118
+ Range.prototype.getClientRects ??= () => [] as unknown as DOMRectList
119
+
120
+ // The field loads the editor with React `lazy()`. Importing it once here
121
+ // keeps the cold import out of the renders; `render` still awaits the lazy
122
+ // boundary and fails loudly if the editor did not mount.
123
+ beforeAll(async () => {
124
+ await import('./editor-component')
125
+ })
126
+
127
+ let frames: ReturnType<typeof installFrameControl>
128
+ let container: HTMLDivElement
129
+ let root: Root
130
+
131
+ beforeEach(() => {
132
+ frames = installFrameControl()
133
+ probe.memory = null
134
+ counters.pluginRenders = 0
135
+ container = document.createElement('div')
136
+ document.body.append(container)
137
+ root = createRoot(container)
138
+ })
139
+
140
+ afterEach(async () => {
141
+ await act(async () => {
142
+ root.unmount()
143
+ })
144
+ container.remove()
145
+ frames.restore()
146
+ vi.restoreAllMocks()
147
+ })
148
+
149
+ /** Renders the form, waits for the lazy editor to mount and settle, and returns its root. */
150
+ const render = async (
151
+ store: EditorViewStateStore | null,
152
+ data: Record<string, unknown>,
153
+ onSubmit: () => Promise<void>
154
+ ): Promise<HTMLElement> => {
155
+ await act(async () => {
156
+ root.render(
157
+ <I18nProvider
158
+ bundle={adminTranslations({ locales: ['en'] })}
159
+ activeLocale="en"
160
+ defaultLocale="en"
161
+ localeDefinitions={[{ code: 'en', nativeName: 'English' }]}
162
+ >
163
+ <BylineFieldServicesProvider
164
+ services={
165
+ {
166
+ getCollectionDocuments: async () => ({ docs: [], total: 0 }),
167
+ uploadField: async () => ({}),
168
+ } as never
169
+ }
170
+ >
171
+ <FormRenderer
172
+ mode="edit"
173
+ fields={fields as never}
174
+ initialLocale="en"
175
+ initialData={data}
176
+ collectionPath="pages"
177
+ viewState={store}
178
+ onSubmit={onSubmit}
179
+ onCancel={() => {}}
180
+ />
181
+ </BylineFieldServicesProvider>
182
+ </I18nProvider>
183
+ )
184
+ // Resolve the lazy boundary inside the same act, so React commits the
185
+ // editor before act returns.
186
+ await import('./editor-component')
187
+ })
188
+ const element = editorRoot()
189
+ if (element == null) throw new Error('rich-text editor did not mount')
190
+ await act(async () => {
191
+ await frames.settleBaseline()
192
+ })
193
+ return element
194
+ }
195
+
196
+ /** The root editor's content-editable element; nested editors sit inside it. */
197
+ const editorRoot = () =>
198
+ container
199
+ .querySelector('[data-byline-target="body"]')
200
+ ?.querySelector<HTMLElement>('[contenteditable]') ?? null
201
+
202
+ const editorOf = (element: HTMLElement | null): LexicalEditor => {
203
+ const editor = (element as any)?.__lexicalEditor as LexicalEditor | undefined
204
+ if (editor == null) throw new Error('editor not mounted')
205
+ return editor
206
+ }
207
+
208
+ const saveButton = () => {
209
+ const button = container.querySelector<HTMLButtonElement>('button[type="submit"]')
210
+ if (button == null) throw new Error('save button not found')
211
+ return button
212
+ }
213
+
214
+ /** A host-shaped submit: claims the attempt and records the receipt's revision. */
215
+ const hostSubmit = (store: EditorViewStateStore, revision: number) =>
216
+ vi.fn(async () => {
217
+ claimSaveAttempt(store).expectRefresh({ revision })
218
+ })
219
+
220
+ const clickSave = async () => {
221
+ act(() => saveButton().focus())
222
+ await act(async () => {
223
+ saveButton().click()
224
+ })
225
+ }
226
+
227
+ /** Emissions are deferred through idle callbacks; deliver them. */
228
+ const flushEmission = async () => {
229
+ await act(async () => {
230
+ frames.flushIdle()
231
+ })
232
+ }
233
+
234
+ /**
235
+ * An edit as the browser delivers it: a `beforeinput` the form records the
236
+ * working target from, then the editor's own update.
237
+ */
238
+ const edit = async (element: HTMLElement, update: () => void) => {
239
+ await act(async () => {
240
+ element.focus()
241
+ element.dispatchEvent(new InputEvent('beforeinput', { bubbles: true, inputType: 'insertText' }))
242
+ editorOf(element).update(update, { discrete: true })
243
+ })
244
+ await flushEmission()
245
+ }
246
+
247
+ /** Puts the caret at `offset` in the first text node and types `value` there. */
248
+ const insertAt = (offset: number, value: string) => () => {
249
+ const first = $getRoot().getFirstDescendant()
250
+ if (!$isTextNode(first)) throw new Error('no text node')
251
+ first.select(offset, offset)
252
+ const selection = $getSelection()
253
+ if ($isRangeSelection(selection)) selection.insertText(value)
254
+ }
255
+
256
+ /** The root editor's collapsed caret as [text, offset], or null without one. */
257
+ const caretOf = (editor: LexicalEditor): [string, number] | null =>
258
+ editor.getEditorState().read(() => {
259
+ const selection = $getSelection()
260
+ if (!$isRangeSelection(selection) || !selection.isCollapsed()) return null
261
+ return [selection.anchor.getNode().getTextContent(), selection.anchor.offset]
262
+ })
263
+
264
+ /**
265
+ * The ordinary flow: types "," after "Hello", which leaves the caret there,
266
+ * delivers the deferred change, and saves with no further selection update.
267
+ * A later caret move would recreate a selection that a faulty deferred
268
+ * callback had erased, and hide the fault.
269
+ */
270
+ const typeAndSave = async (
271
+ store: EditorViewStateStore,
272
+ onSubmit: () => Promise<void>
273
+ ): Promise<HTMLElement> => {
274
+ const element = await render(store, doc(1, content(paragraph('Hello world'))), onSubmit)
275
+ await edit(element, insertAt(5, ','))
276
+ expect(saveButton().disabled).toBe(false)
277
+ await clickSave()
278
+ expect(onSubmit).toHaveBeenCalledTimes(1)
279
+ return element
280
+ }
281
+
282
+ // Smoke tests: they check that the form, the view-state store, the field's
283
+ // selection memory and the editor are connected. jsdom has no layout, focus
284
+ // model or native selection, so where the caret and focus actually land is
285
+ // verified by hand in a browser; the unchanged-content rule itself is covered
286
+ // by `content-fingerprint.test.node.ts`.
287
+ describe('rich-text caret restoration wiring', () => {
288
+ it('a successful save of unchanged content hands the caret to the reloaded editor without dirtying the form', async () => {
289
+ const store = createEditorViewStateStore()
290
+ const onSubmit = hostSubmit(store, 2)
291
+ const before = await typeAndSave(store, onSubmit)
292
+
293
+ const after = await render(store, doc(2, content(paragraph('Hello, world'))), onSubmit)
294
+ await flushEmission()
295
+ expect(after).not.toBe(before)
296
+ expect(caretOf(editorOf(after))).toEqual(['Hello, world', 6])
297
+ // The caret is view state: no patch, no dirty form.
298
+ expect(saveButton().disabled).toBe(true)
299
+ })
300
+
301
+ it('content changed by the server: the reloaded editor gets no caret', async () => {
302
+ const store = createEditorViewStateStore()
303
+ const onSubmit = hostSubmit(store, 2)
304
+ await typeAndSave(store, onSubmit)
305
+
306
+ const after = await render(store, doc(2, content(paragraph('Hello, world!'))), onSubmit)
307
+ expect(caretOf(editorOf(after))).toBeNull()
308
+ })
309
+
310
+ it('a failed save grants no caret and leaves the form dirty', async () => {
311
+ const store = createEditorViewStateStore()
312
+ const grantSelection = vi.spyOn(store, 'grantSelection')
313
+ const onSubmit = vi.fn(async () => {
314
+ throw new Error('save failed')
315
+ })
316
+ await typeAndSave(store, onSubmit)
317
+ expect(saveButton().disabled).toBe(false)
318
+ expect(grantSelection).not.toHaveBeenCalled()
319
+ expect(probe.memory?.take()).toBeNull()
320
+ })
321
+
322
+ it('a form without a view-state store mounts no selection tracking', async () => {
323
+ const element = await render(null, doc(1, content(paragraph('Hello world'))), async () => {})
324
+ await edit(element, insertAt(5, ','))
325
+ expect(probe.memory).toBeNull()
326
+ expect(counters.pluginRenders).toBe(0)
327
+ })
328
+ })
@@ -8,7 +8,12 @@
8
8
 
9
9
  import type React from 'react'
10
10
 
11
- import { LocaleBadge, useFieldError, useFieldValue } from '@byline/admin/react'
11
+ import {
12
+ LocaleBadge,
13
+ useFieldError,
14
+ useFieldValue,
15
+ useRichTextSelectionMemory,
16
+ } from '@byline/admin/react'
12
17
  import type { RichTextField as FieldType } from '@byline/core'
13
18
  import { ErrorText, Label } from '@byline/ui/react'
14
19
  import cx from 'clsx'
@@ -66,6 +71,9 @@ export const RichTextField = ({
66
71
  const fieldPath = path ?? field.name
67
72
  const fieldError = useFieldError(fieldPath)
68
73
  const fieldValue = useFieldValue<any>(fieldPath)
74
+ // Root-editor selection only; nested editors never receive it, and a form
75
+ // without a visit store gets none, so it does no selection work.
76
+ const selectionMemory = useRichTextSelectionMemory(fieldPath)
69
77
  const incomingValue = value ?? fieldValue
70
78
  const incomingDefault = defaultValue
71
79
 
@@ -129,6 +137,7 @@ export const RichTextField = ({
129
137
  featureBeforeEditor={featureBeforeEditor}
130
138
  featureAfterEditor={featureAfterEditor}
131
139
  featureChildren={featureChildren}
140
+ selectionMemory={selectionMemory ?? undefined}
132
141
  // Ensure React fully remounts when instanceKey changes
133
142
  key={fieldId}
134
143
  />
package/src/types.ts CHANGED
@@ -1,3 +1,4 @@
1
+ import type { RichTextSelectionMemory } from '@byline/admin/react'
1
2
  import type { EditorConfig as LexicalEditorConfig, SerializedEditorState } from 'lexical'
2
3
 
3
4
  import type { EditorConfig, EditorSettings } from './field/config/types'
@@ -40,4 +41,9 @@ export type EditorFieldProps = {
40
41
  ) => string | boolean | Promise<string | boolean>
41
42
  onError?: (error: Error) => void
42
43
  lexicalEditorProps?: LexicalEditorProps
44
+ /**
45
+ * The field's selection memory (`useRichTextSelectionMemory`). When given,
46
+ * the root editor records its selection and puts it back after a save.
47
+ */
48
+ selectionMemory?: RichTextSelectionMemory
43
49
  }