@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.
@@ -1,9 +1,23 @@
1
1
  import type * as React from 'react';
2
2
  import type { SerializedEditorState } from 'lexical';
3
- export declare function ApplyValuePlugin({ value, incomingHash, lastEmittedHashRef, normalizedIncomingHashRef, hasNormalizedBaselineRef, }: {
3
+ import type { BaselineStatus } from './baseline-signal.js';
4
+ export declare function ApplyValuePlugin({ value, incomingHash, lastEmittedHashRef, normalizedIncomingHashRef, hasNormalizedBaselineRef, onBaselineReady, onBaselineReset, }: {
4
5
  value?: SerializedEditorState | null;
5
6
  incomingHash?: string;
6
7
  lastEmittedHashRef: React.RefObject<string | undefined>;
7
8
  normalizedIncomingHashRef: React.RefObject<string | undefined>;
8
9
  hasNormalizedBaselineRef: React.RefObject<boolean>;
10
+ /**
11
+ * Called wherever this plugin establishes the baseline for a value (sets
12
+ * `hasNormalizedBaselineRef.current = true`), with how that value fared.
13
+ * Never called for a refused or null value. Observing it changes nothing
14
+ * about emission.
15
+ */
16
+ onBaselineReady?: (status: BaselineStatus) => void;
17
+ /**
18
+ * Called wherever the editor stops holding an established baseline: a
19
+ * different value is being applied, a value is refused, or the value is
20
+ * null.
21
+ */
22
+ onBaselineReset?: () => void;
9
23
  }): React.JSX.Element | null;
@@ -6,14 +6,19 @@ import { APPLY_VALUE_TAG } from "./constants.js";
6
6
  import { useNormalizationStatus } from "./normalize/normalization-status.js";
7
7
  import { normalizeValue } from "./normalize/normalize-value.js";
8
8
  import { hashSerializedState } from "./utils/hashSerializedState.js";
9
- function ApplyValuePlugin({ value, incomingHash, lastEmittedHashRef, normalizedIncomingHashRef, hasNormalizedBaselineRef }) {
9
+ function ApplyValuePlugin({ value, incomingHash, lastEmittedHashRef, normalizedIncomingHashRef, hasNormalizedBaselineRef, onBaselineReady, onBaselineReset }) {
10
10
  const [editor] = useLexicalComposerContext();
11
11
  const { setStatus } = useNormalizationStatus();
12
12
  const lastAppliedHashRef = useRef(void 0);
13
13
  const isRefusedRef = useRef(false);
14
14
  const cancelWaiterRef = useRef(void 0);
15
+ const onBaselineReadyRef = useRef(onBaselineReady);
16
+ onBaselineReadyRef.current = onBaselineReady;
17
+ const onBaselineResetRef = useRef(onBaselineReset);
18
+ onBaselineResetRef.current = onBaselineReset;
19
+ const appliedStatusRef = useRef('ok');
15
20
  useLayoutEffect(()=>{
16
- if (null == value) return;
21
+ if (null == value) return void onBaselineResetRef.current?.();
17
22
  const nextRawHash = incomingHash;
18
23
  const refused = isRefusedRef.current;
19
24
  if (!refused && nextRawHash === lastEmittedHashRef.current) {
@@ -23,6 +28,7 @@ function ApplyValuePlugin({ value, incomingHash, lastEmittedHashRef, normalizedI
23
28
  cancelWaiterRef.current();
24
29
  cancelWaiterRef.current = void 0;
25
30
  }
31
+ onBaselineReadyRef.current?.(appliedStatusRef.current);
26
32
  }
27
33
  return;
28
34
  }
@@ -32,6 +38,7 @@ function ApplyValuePlugin({ value, incomingHash, lastEmittedHashRef, normalizedI
32
38
  cancelWaiterRef.current = void 0;
33
39
  }
34
40
  hasNormalizedBaselineRef.current = false;
41
+ onBaselineResetRef.current?.();
35
42
  const normalized = normalizeValue(value, registeredNodeTypes(editor));
36
43
  if ('refused' === normalized.status) {
37
44
  setStatus({
@@ -44,6 +51,8 @@ function ApplyValuePlugin({ value, incomingHash, lastEmittedHashRef, normalizedI
44
51
  return;
45
52
  }
46
53
  isRefusedRef.current = false;
54
+ const appliedStatus = 'adapted' === normalized.status ? 'adapted' : 'ok';
55
+ appliedStatusRef.current = appliedStatus;
47
56
  setStatus('adapted' === normalized.status ? {
48
57
  kind: 'adapted',
49
58
  convertedTypes: normalized.convertedTypes
@@ -66,6 +75,7 @@ function ApplyValuePlugin({ value, incomingHash, lastEmittedHashRef, normalizedI
66
75
  const settled = editor.getEditorState().toJSON();
67
76
  normalizedIncomingHashRef.current = hashSerializedState(settled);
68
77
  hasNormalizedBaselineRef.current = true;
78
+ onBaselineReadyRef.current?.(appliedStatus);
69
79
  });
70
80
  });
71
81
  });
@@ -0,0 +1,25 @@
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
+ /** How the value whose baseline is established fared against the editor. */
9
+ export type BaselineStatus = 'ok' | 'adapted';
10
+ /**
11
+ * Whether `ApplyValuePlugin` has established the emission baseline for the
12
+ * value the editor currently holds. `ready` is called exactly where the
13
+ * plugin sets `hasNormalizedBaselineRef.current = true`; `reset` wherever it
14
+ * starts applying a different value, refuses one, or receives null. Reading
15
+ * it leaves the emission gate unchanged.
16
+ */
17
+ export interface BaselineSignal {
18
+ /** The established baseline's status, or `null` while none is established. */
19
+ status(): BaselineStatus | null;
20
+ ready(status: BaselineStatus): void;
21
+ reset(): void;
22
+ /** Notified when a baseline becomes established. */
23
+ subscribe(listener: () => void): () => void;
24
+ }
25
+ export declare function createBaselineSignal(): BaselineSignal;
@@ -0,0 +1,23 @@
1
+ function createBaselineSignal() {
2
+ const listeners = new Set();
3
+ let current = null;
4
+ return {
5
+ status: ()=>current,
6
+ ready (status) {
7
+ current = status;
8
+ for (const listener of [
9
+ ...listeners
10
+ ])listener();
11
+ },
12
+ reset () {
13
+ current = null;
14
+ },
15
+ subscribe (listener) {
16
+ listeners.add(listener);
17
+ return ()=>{
18
+ listeners.delete(listener);
19
+ };
20
+ }
21
+ };
22
+ }
23
+ export { createBaselineSignal };
@@ -1 +1,3 @@
1
1
  export declare const APPLY_VALUE_TAG = "payload-apply-value";
2
+ /** Tags the selection-only update that puts a restored caret back after a save. */
3
+ export declare const SELECTION_RESTORE_TAG = "byline-selection-restore";
@@ -1,2 +1,3 @@
1
1
  const APPLY_VALUE_TAG = 'payload-apply-value';
2
- export { APPLY_VALUE_TAG };
2
+ const SELECTION_RESTORE_TAG = 'byline-selection-restore';
3
+ export { APPLY_VALUE_TAG, SELECTION_RESTORE_TAG };
@@ -0,0 +1,15 @@
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
+ import type { SerializedEditorState } from 'lexical';
9
+ /**
10
+ * A fingerprint of the editor's normalized content as a save would store
11
+ * it, with only the server-refreshed embed metadata above left out. Two
12
+ * states with the same fingerprint differ at most in values the save path
13
+ * itself rewrites, so a caret recorded in one fits the other.
14
+ */
15
+ export declare function contentFingerprint(state: SerializedEditorState): string;
@@ -0,0 +1,62 @@
1
+ import { hashSerializedState } from "./utils/hashSerializedState.js";
2
+ const isRecord = (value)=>null != value && 'object' == typeof value && !Array.isArray(value);
3
+ function stripEnvelope(holder, keys) {
4
+ const envelope = holder.document;
5
+ if (!isRecord(envelope)) return;
6
+ const next = {
7
+ ...envelope
8
+ };
9
+ for (const key of keys)delete next[key];
10
+ if (0 === Object.keys(next).length) delete holder.document;
11
+ else holder.document = next;
12
+ }
13
+ const hasIdentity = (relation)=>Boolean(relation.targetCollectionPath) && Boolean(relation.targetDocumentId);
14
+ function stripRefreshedMetadata(node) {
15
+ if ('inline-image' === node.type && hasIdentity(node)) {
16
+ delete node.src;
17
+ delete node.width;
18
+ delete node.height;
19
+ stripEnvelope(node, [
20
+ 'title',
21
+ 'altText',
22
+ 'image',
23
+ 'sizes',
24
+ '_resolved'
25
+ ]);
26
+ const link = node.link;
27
+ if (isRecord(link) && 'internal' === link.linkType && hasIdentity(link)) {
28
+ const next = {
29
+ ...link
30
+ };
31
+ stripEnvelope(next, [
32
+ 'title',
33
+ 'path',
34
+ '_resolved'
35
+ ]);
36
+ node.link = next;
37
+ }
38
+ }
39
+ if ('link' === node.type && isRecord(node.attributes)) {
40
+ const attributes = node.attributes;
41
+ if ('internal' === attributes.linkType && hasIdentity(attributes)) {
42
+ const next = {
43
+ ...attributes
44
+ };
45
+ stripEnvelope(next, [
46
+ 'title',
47
+ 'path',
48
+ '_resolved'
49
+ ]);
50
+ node.attributes = next;
51
+ }
52
+ }
53
+ if (Array.isArray(node.children)) {
54
+ for (const child of node.children)if (isRecord(child)) stripRefreshedMetadata(child);
55
+ }
56
+ }
57
+ function contentFingerprint(state) {
58
+ const copy = JSON.parse(JSON.stringify(state));
59
+ if (isRecord(copy.root)) stripRefreshedMetadata(copy.root);
60
+ return hashSerializedState(copy);
61
+ }
62
+ export { contentFingerprint };
@@ -9,4 +9,4 @@ import type React from 'react';
9
9
  import type { EditorFieldProps } from '../types.js';
10
10
  import './editor-component.css';
11
11
  import './themes/lexical-editor-theme.css';
12
- export declare const EditorComponent: React.MemoExoticComponent<({ name, id, label, description, required, readonly, editorConfig, defaultValue, value, onChange, minHeight, maxHeight, validate, onError: _onError, lexicalEditorProps: _lexicalEditorProps, featureBeforeEditor, featureAfterEditor, featureChildren, }: EditorFieldProps) => React.JSX.Element>;
12
+ export declare const EditorComponent: React.MemoExoticComponent<({ name, id, label, description, required, readonly, editorConfig, defaultValue, value, onChange, minHeight, maxHeight, validate, onError: _onError, lexicalEditorProps: _lexicalEditorProps, featureBeforeEditor, featureAfterEditor, featureChildren, selectionMemory, }: EditorFieldProps) => React.JSX.Element>;
@@ -5,12 +5,14 @@ import { HelpText, Label } from "@byline/ui/react";
5
5
  import { ErrorBoundary } from "react-error-boundary";
6
6
  import { richTextValidate } from "../validate/validate.js";
7
7
  import { ApplyValuePlugin } from "./apply-value-plugin.js";
8
+ import { createBaselineSignal } from "./baseline-signal.js";
8
9
  import { EditorContext } from "./editor-context.js";
10
+ import { SelectionRestorePlugin } from "./selection-restore-plugin.js";
9
11
  import { hashSerializedState } from "./utils/hashSerializedState.js";
10
12
  import "./editor-component.css";
11
13
  import "./themes/lexical-editor-theme.css";
12
14
  const baseClass = 'lexicalRichTextEditor';
13
- const editor_component_EditorComponent = /*#__PURE__*/ memo(function({ name, id, label, description, required, readonly, editorConfig, defaultValue, value, onChange, minHeight, maxHeight, validate = richTextValidate, onError: _onError, lexicalEditorProps: _lexicalEditorProps, featureBeforeEditor, featureAfterEditor, featureChildren }) {
15
+ const editor_component_EditorComponent = /*#__PURE__*/ memo(function({ name, id, label, description, required, readonly, editorConfig, defaultValue, value, onChange, minHeight, maxHeight, validate = richTextValidate, onError: _onError, lexicalEditorProps: _lexicalEditorProps, featureBeforeEditor, featureAfterEditor, featureChildren, selectionMemory }) {
14
16
  const disabled = readonly ?? false;
15
17
  const dispatchFieldUpdateTask = useRef(void 0);
16
18
  const valueRef = useRef(value);
@@ -20,6 +22,7 @@ const editor_component_EditorComponent = /*#__PURE__*/ memo(function({ name, id,
20
22
  const lastEmittedHashRef = useRef(void 0);
21
23
  const normalizedIncomingHashRef = useRef(void 0);
22
24
  const hasNormalizedBaselineRef = useRef(false);
25
+ const baselineSignal = useMemo(createBaselineSignal, []);
23
26
  useCallback((val)=>{
24
27
  if ('function' == typeof validate) return validate(val, {
25
28
  required
@@ -82,7 +85,13 @@ const editor_component_EditorComponent = /*#__PURE__*/ memo(function({ name, id,
82
85
  incomingHash: incomingHash,
83
86
  lastEmittedHashRef: lastEmittedHashRef,
84
87
  normalizedIncomingHashRef: normalizedIncomingHashRef,
85
- hasNormalizedBaselineRef: hasNormalizedBaselineRef
88
+ hasNormalizedBaselineRef: hasNormalizedBaselineRef,
89
+ onBaselineReady: selectionMemory ? baselineSignal.ready : void 0,
90
+ onBaselineReset: selectionMemory ? baselineSignal.reset : void 0
91
+ }),
92
+ selectionMemory && /*#__PURE__*/ jsx(SelectionRestorePlugin, {
93
+ memory: selectionMemory,
94
+ baseline: baselineSignal
86
95
  }),
87
96
  featureChildren
88
97
  ]
@@ -0,0 +1,33 @@
1
+ import type { RichTextSelectionMemory } from '@byline/admin/react';
2
+ import type { BaselineSignal } from './baseline-signal.js';
3
+ /**
4
+ * Records the root editor's selection while its field is the working
5
+ * target, and puts it back after a successful save. Mounted in the field's
6
+ * root editor only, and only when the form has a visit store, so nested
7
+ * editors (image captions, admonition bodies) and untracked forms never
8
+ * record.
9
+ *
10
+ * Recording reads the selection's structural points only, deferred to a
11
+ * microtask so the form has recorded the working target from the same
12
+ * input event, and only while the root's own content-editable holds focus.
13
+ * The content fingerprint is computed on demand when a save begins. An edit
14
+ * inside a nested editor, or a non-range root selection (a selected image),
15
+ * clears the recorded selection. Unmounting releases this editor's live
16
+ * selection from the visit store, which outlives it.
17
+ *
18
+ * Restoring is a rendezvous between two conditions that may arrive in
19
+ * either order: `ApplyValuePlugin` has established the baseline for the
20
+ * value the editor holds (tracked by `baseline`, and reset whenever a
21
+ * different, refused or null value arrives), and the current successful
22
+ * save's restoration has handed on a selection (`memory`). The selection is
23
+ * taken once, when both hold. The caret is placed only when the value was
24
+ * not adapted, the content fingerprint matches (only server-refreshed embed
25
+ * metadata may differ), both points resolve, and
26
+ * the control restoration focused still holds focus. The update is
27
+ * selection-only and runs outside any other update, so it never reaches the
28
+ * form's `onChange`.
29
+ */
30
+ export declare function SelectionRestorePlugin({ memory, baseline, }: {
31
+ memory: RichTextSelectionMemory;
32
+ baseline: BaselineSignal;
33
+ }): null;
@@ -0,0 +1,162 @@
1
+ "use client";
2
+ import { useEffect } from "react";
3
+ import { useLexicalComposerContext } from "@lexical/react/LexicalComposerContext";
4
+ import { $createRangeSelection, $getRoot, $getSelection, $isElementNode, $isRangeSelection, $isRootNode, $isTextNode, $setSelection, SKIP_SCROLL_INTO_VIEW_TAG } from "lexical";
5
+ import { APPLY_VALUE_TAG, SELECTION_RESTORE_TAG } from "./constants.js";
6
+ import { contentFingerprint } from "./content-fingerprint.js";
7
+ function $pathOf(node) {
8
+ const path = [];
9
+ let current = node;
10
+ while(null != current && !$isRootNode(current)){
11
+ path.unshift(current.getIndexWithinParent());
12
+ current = current.getParent();
13
+ }
14
+ return null == current ? null : path;
15
+ }
16
+ function $structuralPoint(point) {
17
+ const path = $pathOf(point.getNode());
18
+ return null == path ? null : {
19
+ path,
20
+ offset: point.offset
21
+ };
22
+ }
23
+ function $resolvePoint(point) {
24
+ let node = $getRoot();
25
+ for (const index of point.path){
26
+ if (!$isElementNode(node)) return null;
27
+ const child = node.getChildAtIndex(index);
28
+ if (null == child) return null;
29
+ node = child;
30
+ }
31
+ if (point.offset < 0) return null;
32
+ if ($isTextNode(node)) {
33
+ if (point.offset > node.getTextContentSize()) return null;
34
+ return {
35
+ key: node.getKey(),
36
+ offset: point.offset,
37
+ type: 'text'
38
+ };
39
+ }
40
+ if ($isElementNode(node)) {
41
+ if (point.offset > node.getChildrenSize()) return null;
42
+ return {
43
+ key: node.getKey(),
44
+ offset: point.offset,
45
+ type: 'element'
46
+ };
47
+ }
48
+ return null;
49
+ }
50
+ function editorFingerprint(editor) {
51
+ return contentFingerprint(editor.getEditorState().toJSON());
52
+ }
53
+ const NESTED_EDIT_EVENTS = [
54
+ 'beforeinput',
55
+ 'input',
56
+ 'paste',
57
+ 'cut',
58
+ 'drop'
59
+ ];
60
+ function SelectionRestorePlugin({ memory, baseline }) {
61
+ const [editor] = useLexicalComposerContext();
62
+ useEffect(()=>{
63
+ let disposed = false;
64
+ let scheduled = false;
65
+ const owner = {};
66
+ const fingerprint = ()=>disposed ? null : editorFingerprint(editor);
67
+ const record = ()=>{
68
+ scheduled = false;
69
+ if (disposed) return;
70
+ const rootElement = editor.getRootElement();
71
+ const selection = editor.getEditorState().read(()=>{
72
+ const current = $getSelection();
73
+ if (null == current) return;
74
+ if (!$isRangeSelection(current)) return null;
75
+ const anchor = $structuralPoint(current.anchor);
76
+ const focus = $structuralPoint(current.focus);
77
+ return anchor && focus ? {
78
+ anchor,
79
+ focus
80
+ } : void 0;
81
+ });
82
+ if (null === selection) return void memory.clear();
83
+ if (null == rootElement || rootElement.ownerDocument.activeElement !== rootElement) return;
84
+ if (void 0 !== selection) memory.record(selection, fingerprint, owner);
85
+ };
86
+ const unregisterUpdates = editor.registerUpdateListener(({ tags })=>{
87
+ if (tags.has(APPLY_VALUE_TAG) || scheduled) return;
88
+ scheduled = true;
89
+ queueMicrotask(record);
90
+ });
91
+ const onNestedEdit = (event)=>{
92
+ const target = event.target;
93
+ const element = target instanceof Element ? target : target?.parentElement ?? null;
94
+ if (element?.closest('[contenteditable]') !== editor.getRootElement()) memory.clear();
95
+ };
96
+ const unregisterRoot = editor.registerRootListener((rootElement, previous)=>{
97
+ for (const type of NESTED_EDIT_EVENTS){
98
+ previous?.removeEventListener(type, onNestedEdit, true);
99
+ rootElement?.addEventListener(type, onNestedEdit, true);
100
+ }
101
+ });
102
+ return ()=>{
103
+ disposed = true;
104
+ unregisterUpdates();
105
+ unregisterRoot();
106
+ memory.release(owner);
107
+ };
108
+ }, [
109
+ editor,
110
+ memory
111
+ ]);
112
+ useEffect(()=>{
113
+ let disposed = false;
114
+ const reconcile = ()=>{
115
+ if (disposed) return;
116
+ const status = baseline.status();
117
+ if (null == status) return;
118
+ const taken = memory.take();
119
+ if (null == taken || 'ok' !== status || !editor.isEditable()) return;
120
+ const rootElement = editor.getRootElement();
121
+ if (null == rootElement) return;
122
+ if (editorFingerprint(editor) !== taken.fingerprint) return;
123
+ const points = editor.getEditorState().read(()=>{
124
+ const anchor = $resolvePoint(taken.sel.anchor);
125
+ const focus = $resolvePoint(taken.sel.focus);
126
+ return anchor && focus ? {
127
+ anchor,
128
+ focus
129
+ } : null;
130
+ });
131
+ if (null == points) return;
132
+ rootElement.focus({
133
+ preventScroll: true
134
+ });
135
+ editor.update(()=>{
136
+ const selection = $createRangeSelection();
137
+ selection.anchor.set(points.anchor.key, points.anchor.offset, points.anchor.type);
138
+ selection.focus.set(points.focus.key, points.focus.offset, points.focus.type);
139
+ $setSelection(selection);
140
+ }, {
141
+ discrete: true,
142
+ tag: [
143
+ SELECTION_RESTORE_TAG,
144
+ SKIP_SCROLL_INTO_VIEW_TAG
145
+ ]
146
+ });
147
+ };
148
+ const unsubscribeBaseline = baseline.subscribe(reconcile);
149
+ const unsubscribeMemory = memory.subscribe(()=>queueMicrotask(reconcile));
150
+ return ()=>{
151
+ disposed = true;
152
+ unsubscribeBaseline();
153
+ unsubscribeMemory();
154
+ };
155
+ }, [
156
+ baseline,
157
+ editor,
158
+ memory
159
+ ]);
160
+ return null;
161
+ }
162
+ export { SelectionRestorePlugin };
@@ -1,5 +1,5 @@
1
1
  import { jsx, jsxs } from "react/jsx-runtime";
2
- import { LocaleBadge, useFieldError, useFieldValue } from "@byline/admin/react";
2
+ import { LocaleBadge, useFieldError, useFieldValue, useRichTextSelectionMemory } from "@byline/admin/react";
3
3
  import { ErrorText, Label } from "@byline/ui/react";
4
4
  import clsx from "clsx";
5
5
  import { defaultEditorConfig } from "./field/config/default.js";
@@ -11,6 +11,7 @@ const RichTextField = ({ field, value, defaultValue, editorConfig, readonly = fa
11
11
  const fieldPath = path ?? field.name;
12
12
  const fieldError = useFieldError(fieldPath);
13
13
  const fieldValue = useFieldValue(fieldPath);
14
+ const selectionMemory = useRichTextSelectionMemory(fieldPath);
14
15
  const incomingValue = value ?? fieldValue;
15
16
  const incomingDefault = defaultValue;
16
17
  const fieldId = instanceKey ? `${field.name}-${instanceKey}` : field.name;
@@ -52,7 +53,8 @@ const RichTextField = ({ field, value, defaultValue, editorConfig, readonly = fa
52
53
  defaultValue: incomingDefault,
53
54
  featureBeforeEditor: featureBeforeEditor,
54
55
  featureAfterEditor: featureAfterEditor,
55
- featureChildren: featureChildren
56
+ featureChildren: featureChildren,
57
+ selectionMemory: selectionMemory ?? void 0
56
58
  }, fieldId),
57
59
  fieldError && /*#__PURE__*/ jsx(ErrorText, {
58
60
  id: `${field.name}-error`,
package/dist/types.d.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
  import type { EditorConfig, EditorSettings } from './field/config/types.js';
3
4
  export interface LexicalEditorProps {
@@ -33,4 +34,9 @@ export type EditorFieldProps = {
33
34
  }) => string | boolean | Promise<string | boolean>;
34
35
  onError?: (error: Error) => void;
35
36
  lexicalEditorProps?: LexicalEditorProps;
37
+ /**
38
+ * The field's selection memory (`useRichTextSelectionMemory`). When given,
39
+ * the root editor records its selection and puts it back after a save.
40
+ */
41
+ selectionMemory?: RichTextSelectionMemory;
36
42
  };
package/package.json CHANGED
@@ -3,7 +3,7 @@
3
3
  "private": false,
4
4
  "type": "module",
5
5
  "license": "MPL-2.0",
6
- "version": "6.14.1",
6
+ "version": "6.15.0",
7
7
  "engines": {
8
8
  "node": ">=22.22.2"
9
9
  },
@@ -62,11 +62,11 @@
62
62
  }
63
63
  },
64
64
  "dependencies": {
65
- "@byline/admin": "6.14.1",
66
- "@byline/client": "6.14.1",
67
- "@byline/core": "6.14.1",
68
- "@byline/i18n": "6.14.1",
69
- "@byline/ui": "6.14.1",
65
+ "@byline/admin": "6.15.0",
66
+ "@byline/client": "6.15.0",
67
+ "@byline/core": "6.15.0",
68
+ "@byline/i18n": "6.15.0",
69
+ "@byline/ui": "6.15.0",
70
70
  "@lexical/code": "0.53.0",
71
71
  "@lexical/code-prism": "0.53.0",
72
72
  "@lexical/extension": "0.53.0",
@@ -123,7 +123,9 @@
123
123
  "typecheck": "tsc --noEmit",
124
124
  "clean": "node scripts/clean.js node_modules dist build types .turbo",
125
125
  "lint": "biome check --write --unsafe --diagnostic-level=error",
126
- "test": "vitest run --mode=node",
127
- "test:watch": "vitest --mode=node"
126
+ "test": "vitest run --mode=jsdom && vitest run --mode=node",
127
+ "test:watch": "vitest --mode=node",
128
+ "test:jsdom": "vitest run --mode=jsdom",
129
+ "test:node": "vitest run --mode=node"
128
130
  }
129
131
  }
@@ -11,6 +11,7 @@ import { APPLY_VALUE_TAG } from './constants'
11
11
  import { useNormalizationStatus } from './normalize/normalization-status'
12
12
  import { normalizeValue } from './normalize/normalize-value'
13
13
  import { hashSerializedState } from './utils/hashSerializedState'
14
+ import type { BaselineStatus } from './baseline-signal'
14
15
 
15
16
  export function ApplyValuePlugin({
16
17
  value,
@@ -18,12 +19,27 @@ export function ApplyValuePlugin({
18
19
  lastEmittedHashRef,
19
20
  normalizedIncomingHashRef,
20
21
  hasNormalizedBaselineRef,
22
+ onBaselineReady,
23
+ onBaselineReset,
21
24
  }: {
22
25
  value?: SerializedEditorState | null
23
26
  incomingHash?: string
24
27
  lastEmittedHashRef: React.RefObject<string | undefined>
25
28
  normalizedIncomingHashRef: React.RefObject<string | undefined>
26
29
  hasNormalizedBaselineRef: React.RefObject<boolean>
30
+ /**
31
+ * Called wherever this plugin establishes the baseline for a value (sets
32
+ * `hasNormalizedBaselineRef.current = true`), with how that value fared.
33
+ * Never called for a refused or null value. Observing it changes nothing
34
+ * about emission.
35
+ */
36
+ onBaselineReady?: (status: BaselineStatus) => void
37
+ /**
38
+ * Called wherever the editor stops holding an established baseline: a
39
+ * different value is being applied, a value is refused, or the value is
40
+ * null.
41
+ */
42
+ onBaselineReset?: () => void
27
43
  }): React.JSX.Element | null {
28
44
  const [editor] = useLexicalComposerContext()
29
45
  const { setStatus } = useNormalizationStatus()
@@ -32,13 +48,24 @@ export function ApplyValuePlugin({
32
48
  const isRefusedRef = useRef(false)
33
49
 
34
50
  const cancelWaiterRef = useRef<() => void>(undefined)
51
+ // Read through a ref so a new callback never re-runs the apply effect.
52
+ const onBaselineReadyRef = useRef(onBaselineReady)
53
+ onBaselineReadyRef.current = onBaselineReady
54
+ const onBaselineResetRef = useRef(onBaselineReset)
55
+ onBaselineResetRef.current = onBaselineReset
56
+ // How the value last applied fared; the echo path below re-establishes
57
+ // the baseline for that same value.
58
+ const appliedStatusRef = useRef<BaselineStatus>('ok')
35
59
 
36
60
  // A layout effect, not a passive one: this is the ONLY path by which a
37
61
  // stored value reaches the editor — the root extension deliberately
38
62
  // carries no `$initialEditorState` — so applying before paint avoids
39
63
  // showing an empty field first.
40
64
  useLayoutEffect(() => {
41
- if (value == null) return
65
+ if (value == null) {
66
+ onBaselineResetRef.current?.()
67
+ return
68
+ }
42
69
 
43
70
  const nextRawHash = incomingHash
44
71
 
@@ -57,6 +84,7 @@ export function ApplyValuePlugin({
57
84
  cancelWaiterRef.current()
58
85
  cancelWaiterRef.current = undefined
59
86
  }
87
+ onBaselineReadyRef.current?.(appliedStatusRef.current)
60
88
  }
61
89
  return
62
90
  }
@@ -76,6 +104,7 @@ export function ApplyValuePlugin({
76
104
  }
77
105
 
78
106
  hasNormalizedBaselineRef.current = false
107
+ onBaselineResetRef.current?.()
79
108
 
80
109
  // Adapt the stored value to what this editor actually accepts.
81
110
  // Lexical throws on an unregistered type and loses the text, so a
@@ -114,6 +143,8 @@ export function ApplyValuePlugin({
114
143
  }
115
144
 
116
145
  isRefusedRef.current = false
146
+ const appliedStatus: BaselineStatus = normalized.status === 'adapted' ? 'adapted' : 'ok'
147
+ appliedStatusRef.current = appliedStatus
117
148
  setStatus(
118
149
  normalized.status === 'adapted'
119
150
  ? { kind: 'adapted', convertedTypes: normalized.convertedTypes }
@@ -148,6 +179,8 @@ export function ApplyValuePlugin({
148
179
  const settled = editor.getEditorState().toJSON() as SerializedEditorState
149
180
  normalizedIncomingHashRef.current = hashSerializedState(settled)
150
181
  hasNormalizedBaselineRef.current = true
182
+ // Outside any editor update: a listener may run its own.
183
+ onBaselineReadyRef.current?.(appliedStatus)
151
184
  })
152
185
  })
153
186
  })