@contentful/field-editor-rich-text 6.6.1 → 6.6.2-canary.10

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.
package/README.md CHANGED
@@ -10,6 +10,11 @@ This package contains a React `RichTextEditor` component that is used as the def
10
10
  import { RichTextEditor } from '@contentful/field-editor-rich-text';
11
11
  ```
12
12
 
13
+ Pass `withSelectionSync={true}` to opt in to synchronizing the browser caret before editing.
14
+ It defaults to `false`; the plugin is omitted when disabled. Resolve the feature flag before
15
+ mounting the editor. This setting applies when the editor is created, so later changes require
16
+ reopening or remounting the editor.
17
+
13
18
  ## ⚠️ Important: Package Configuration
14
19
 
15
20
  Plate 53.3.14 pins `slate-react` to 0.126.4. To use the latest Slate React version tested by this package (0.127.1), update existing overrides in your application as shown below. Package-manager overrides in this repository are not inherited by applications that install the published package.
@@ -84,13 +84,14 @@ function _interop_require_wildcard(obj, nodeInterop) {
84
84
  return newObj;
85
85
  }
86
86
  const ConnectedRichTextEditor = /*#__PURE__*/ _react.memo(function ConnectedRichTextEditor(props) {
87
- const { sdk, onAction, restrictedMarks, withCharValidation } = props;
87
+ const { sdk, onAction, restrictedMarks, withCharValidation, withSelectionSync } = props;
88
88
  const id = (0, _ContentfulEditorProvider.getContentfulEditorId)(sdk);
89
- const plugins = _react.useMemo(()=>(0, _plugins.getPlugins)(sdk, onAction ?? _noop.default, restrictedMarks, withCharValidation), [
89
+ const plugins = _react.useMemo(()=>(0, _plugins.getPlugins)(sdk, onAction ?? _noop.default, restrictedMarks, withCharValidation, withSelectionSync), [
90
90
  sdk,
91
91
  onAction,
92
92
  restrictedMarks,
93
- withCharValidation
93
+ withCharValidation,
94
+ withSelectionSync
94
95
  ]);
95
96
  const initialValue = (0, _usedeepcompare.useDeepCompareMemo)(()=>{
96
97
  return (0, _toSlateDoc.toSlateDoc)(props.value);
@@ -5,6 +5,7 @@ Object.defineProperty(exports, "__esModule", {
5
5
  const _richtexttypes = require("@contentful/rich-text-types");
6
6
  const _platejs = require("platejs");
7
7
  const _vitest = require("vitest");
8
+ const _plugins = require("../../plugins");
8
9
  const _Paragraph = require("../../plugins/Paragraph/Paragraph");
9
10
  const _sanitizeHTML = require("../../plugins/PasteHTML/utils/sanitizeHTML");
10
11
  const _Cell = require("../../plugins/Table/components/Cell");
@@ -199,3 +200,18 @@ const _createTestEditor = require("../../test-utils/createTestEditor");
199
200
  _richtexttypes.BLOCKS.PARAGRAPH
200
201
  ]);
201
202
  });
203
+ _vitest.it.each([
204
+ undefined,
205
+ false,
206
+ true
207
+ ])('registers caret sync only when explicitly enabled (%s)', (enabled)=>{
208
+ const sdk = {
209
+ field: {
210
+ validation: []
211
+ }
212
+ };
213
+ const { editor } = (0, _createTestEditor.createTestEditor)({
214
+ plugins: (0, _plugins.getPlugins)(sdk, _vitest.vi.fn(), undefined, undefined, enabled)
215
+ });
216
+ (0, _vitest.expect)(editor.plugins.selectionSync !== undefined).toBe(enabled === true);
217
+ });
@@ -0,0 +1,85 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", {
3
+ value: true
4
+ });
5
+ Object.defineProperty(exports, "createSelectionSyncPlugin", {
6
+ enumerable: true,
7
+ get: function() {
8
+ return createSelectionSyncPlugin;
9
+ }
10
+ });
11
+ const _ishotkey = /*#__PURE__*/ _interop_require_default(require("is-hotkey"));
12
+ const _plate = require("../internal/plate");
13
+ const _pluginAdapter = require("../internal/pluginAdapter");
14
+ function _interop_require_default(obj) {
15
+ return obj && obj.__esModule ? obj : {
16
+ default: obj
17
+ };
18
+ }
19
+ const caretKeys = [
20
+ 'ArrowLeft',
21
+ 'ArrowRight',
22
+ 'Backspace',
23
+ 'Delete',
24
+ 'Enter'
25
+ ];
26
+ const hasMatchingCaret = (editor, selection, anchorNode)=>{
27
+ const caret = editor.selection;
28
+ if (selection.rangeCount !== 1 || !selection.isCollapsed || !caret || !(0, _plate.isCollapsed)(caret) || anchorNode?.nodeType !== Node.TEXT_NODE || !anchorNode.parentElement?.hasAttribute('data-slate-string') || selection.anchorOffset !== caret.anchor.offset) return false;
29
+ const node = editor.api.node(caret.anchor.path)?.[0];
30
+ return node && 'text' in node && node.text === anchorNode.textContent && node === editor.api.toSlateNode(anchorNode);
31
+ };
32
+ const isEditorShortcut = (editor, event)=>{
33
+ if (!event.metaKey && !event.ctrlKey) return false;
34
+ return (0, _pluginAdapter.getContentfulPlugins)(editor).some(({ handlers, options })=>{
35
+ const { hotkey } = options ?? {};
36
+ return handlers?.onKeyDown && hotkey && (0, _ishotkey.default)(hotkey, event);
37
+ });
38
+ };
39
+ const syncSelection = (editor)=>{
40
+ const selection = editor.api.getWindow()?.getSelection();
41
+ if (!selection) return;
42
+ const { anchorNode, focusNode } = selection;
43
+ if (!editor.api.hasTarget(anchorNode) || focusNode !== anchorNode && !editor.api.hasTarget(focusNode)) {
44
+ return;
45
+ }
46
+ if (hasMatchingCaret(editor, selection, anchorNode)) return;
47
+ const range = editor.api.toSlateRange(selection, {
48
+ exactMatch: false,
49
+ suppressThrow: true
50
+ });
51
+ if (!range || editor.api.void({
52
+ at: range.anchor
53
+ }) || editor.api.void({
54
+ at: range.focus
55
+ })) return;
56
+ editor.tf.select(range);
57
+ };
58
+ const createSelectionSyncPlugin = ()=>({
59
+ key: 'selectionSync',
60
+ handlers: {
61
+ onMouseUp: (editor)=>()=>{
62
+ if (!editor.api.isComposing()) syncSelection(editor);
63
+ },
64
+ onKeyDown: (editor)=>(event)=>{
65
+ if (!caretKeys.includes(event.key) && !isEditorShortcut(editor, event)) return;
66
+ if (!editor.api.isFocused() && editor.selection && editor.api.void({
67
+ at: editor.selection.focus
68
+ })) return;
69
+ if (event.nativeEvent.isComposing || editor.api.isComposing()) return;
70
+ syncSelection(editor);
71
+ },
72
+ onCompositionStart: (editor)=>()=>{
73
+ if (!editor.api.isComposing()) syncSelection(editor);
74
+ },
75
+ onDOMBeforeInput: (editor)=>(event)=>{
76
+ const input = 'nativeEvent' in event ? event.nativeEvent : event;
77
+ const changesContent = [
78
+ 'insertText',
79
+ 'insertParagraph',
80
+ 'insertLineBreak'
81
+ ].includes(input.inputType) || input.inputType.startsWith('delete');
82
+ if (changesContent && !input.isComposing && !editor.api.isComposing()) syncSelection(editor);
83
+ }
84
+ }
85
+ });
@@ -12,6 +12,7 @@ const _Break = require("./Break");
12
12
  const _CharCounter = require("./CharCounter");
13
13
  const _CommandPalette = require("./CommandPalette");
14
14
  const _useCommands = require("./CommandPalette/useCommands");
15
+ const _createSelectionSyncPlugin = require("./createSelectionSyncPlugin");
15
16
  const _DeserializeDocx = require("./DeserializeDocx");
16
17
  const _DragAndDrop = require("./DragAndDrop");
17
18
  const _EmbeddedEntityBlock = require("./EmbeddedEntityBlock");
@@ -33,9 +34,12 @@ const _Text = require("./Text");
33
34
  const _Tracking = require("./Tracking");
34
35
  const _TrailingParagraph = require("./TrailingParagraph");
35
36
  const _Voids = require("./Voids");
36
- const getPlugins = (sdk, onAction, restrictedMarks, withCharValidation)=>[
37
+ const getPlugins = (sdk, onAction, restrictedMarks, withCharValidation, withSelectionSync = false)=>[
37
38
  (0, _DeserializeDocx.createDeserializeDocxPlugin)(),
38
39
  (0, _Tracking.createTrackingPlugin)(onAction),
40
+ ...withSelectionSync ? [
41
+ (0, _createSelectionSyncPlugin.createSelectionSyncPlugin)()
42
+ ] : [],
39
43
  (0, _DragAndDrop.createDragAndDropPlugin)(),
40
44
  ...Object.values((0, _useCommands.isCommandPromptPluginEnabled)(sdk)).some(Boolean) ? [
41
45
  (0, _CommandPalette.createCommandPalettePlugin)()
@@ -20,13 +20,14 @@ import { SyncEditorChanges } from './SyncEditorChanges';
20
20
  import Toolbar from './Toolbar';
21
21
  import StickyToolbarWrapper from './Toolbar/components/StickyToolbarWrapper';
22
22
  export const ConnectedRichTextEditor = /*#__PURE__*/ React.memo(function ConnectedRichTextEditor(props) {
23
- const { sdk, onAction, restrictedMarks, withCharValidation } = props;
23
+ const { sdk, onAction, restrictedMarks, withCharValidation, withSelectionSync } = props;
24
24
  const id = getContentfulEditorId(sdk);
25
- const plugins = React.useMemo(()=>getPlugins(sdk, onAction ?? noop, restrictedMarks, withCharValidation), [
25
+ const plugins = React.useMemo(()=>getPlugins(sdk, onAction ?? noop, restrictedMarks, withCharValidation, withSelectionSync), [
26
26
  sdk,
27
27
  onAction,
28
28
  restrictedMarks,
29
- withCharValidation
29
+ withCharValidation,
30
+ withSelectionSync
30
31
  ]);
31
32
  const initialValue = useDeepCompareMemo(()=>{
32
33
  return toSlateDoc(props.value);
@@ -1,6 +1,7 @@
1
1
  import { BLOCKS } from '@contentful/rich-text-types';
2
2
  import { getPluginByType, KEYS } from 'platejs';
3
3
  import { expect, it, vi } from 'vitest';
4
+ import { getPlugins } from '../../plugins';
4
5
  import { Paragraph } from '../../plugins/Paragraph/Paragraph';
5
6
  import { sanitizeHTML } from '../../plugins/PasteHTML/utils/sanitizeHTML';
6
7
  import { Cell } from '../../plugins/Table/components/Cell';
@@ -195,3 +196,18 @@ it('unwraps an empty quote on Backspace', ()=>{
195
196
  BLOCKS.PARAGRAPH
196
197
  ]);
197
198
  });
199
+ it.each([
200
+ undefined,
201
+ false,
202
+ true
203
+ ])('registers caret sync only when explicitly enabled (%s)', (enabled)=>{
204
+ const sdk = {
205
+ field: {
206
+ validation: []
207
+ }
208
+ };
209
+ const { editor } = createTestEditor({
210
+ plugins: getPlugins(sdk, vi.fn(), undefined, undefined, enabled)
211
+ });
212
+ expect(editor.plugins.selectionSync !== undefined).toBe(enabled === true);
213
+ });
@@ -0,0 +1,70 @@
1
+ import isHotkey from 'is-hotkey';
2
+ import { isCollapsed } from '../internal/plate';
3
+ import { getContentfulPlugins } from '../internal/pluginAdapter';
4
+ const caretKeys = [
5
+ 'ArrowLeft',
6
+ 'ArrowRight',
7
+ 'Backspace',
8
+ 'Delete',
9
+ 'Enter'
10
+ ];
11
+ const hasMatchingCaret = (editor, selection, anchorNode)=>{
12
+ const caret = editor.selection;
13
+ if (selection.rangeCount !== 1 || !selection.isCollapsed || !caret || !isCollapsed(caret) || anchorNode?.nodeType !== Node.TEXT_NODE || !anchorNode.parentElement?.hasAttribute('data-slate-string') || selection.anchorOffset !== caret.anchor.offset) return false;
14
+ const node = editor.api.node(caret.anchor.path)?.[0];
15
+ return node && 'text' in node && node.text === anchorNode.textContent && node === editor.api.toSlateNode(anchorNode);
16
+ };
17
+ const isEditorShortcut = (editor, event)=>{
18
+ if (!event.metaKey && !event.ctrlKey) return false;
19
+ return getContentfulPlugins(editor).some(({ handlers, options })=>{
20
+ const { hotkey } = options ?? {};
21
+ return handlers?.onKeyDown && hotkey && isHotkey(hotkey, event);
22
+ });
23
+ };
24
+ const syncSelection = (editor)=>{
25
+ const selection = editor.api.getWindow()?.getSelection();
26
+ if (!selection) return;
27
+ const { anchorNode, focusNode } = selection;
28
+ if (!editor.api.hasTarget(anchorNode) || focusNode !== anchorNode && !editor.api.hasTarget(focusNode)) {
29
+ return;
30
+ }
31
+ if (hasMatchingCaret(editor, selection, anchorNode)) return;
32
+ const range = editor.api.toSlateRange(selection, {
33
+ exactMatch: false,
34
+ suppressThrow: true
35
+ });
36
+ if (!range || editor.api.void({
37
+ at: range.anchor
38
+ }) || editor.api.void({
39
+ at: range.focus
40
+ })) return;
41
+ editor.tf.select(range);
42
+ };
43
+ export const createSelectionSyncPlugin = ()=>({
44
+ key: 'selectionSync',
45
+ handlers: {
46
+ onMouseUp: (editor)=>()=>{
47
+ if (!editor.api.isComposing()) syncSelection(editor);
48
+ },
49
+ onKeyDown: (editor)=>(event)=>{
50
+ if (!caretKeys.includes(event.key) && !isEditorShortcut(editor, event)) return;
51
+ if (!editor.api.isFocused() && editor.selection && editor.api.void({
52
+ at: editor.selection.focus
53
+ })) return;
54
+ if (event.nativeEvent.isComposing || editor.api.isComposing()) return;
55
+ syncSelection(editor);
56
+ },
57
+ onCompositionStart: (editor)=>()=>{
58
+ if (!editor.api.isComposing()) syncSelection(editor);
59
+ },
60
+ onDOMBeforeInput: (editor)=>(event)=>{
61
+ const input = 'nativeEvent' in event ? event.nativeEvent : event;
62
+ const changesContent = [
63
+ 'insertText',
64
+ 'insertParagraph',
65
+ 'insertLineBreak'
66
+ ].includes(input.inputType) || input.inputType.startsWith('delete');
67
+ if (changesContent && !input.isComposing && !editor.api.isComposing()) syncSelection(editor);
68
+ }
69
+ }
70
+ });
@@ -2,6 +2,7 @@ import { createSoftBreakPlugin, createExitBreakPlugin, createResetNodePlugin } f
2
2
  import { createCharCounterPlugin } from './CharCounter';
3
3
  import { createCommandPalettePlugin } from './CommandPalette';
4
4
  import { isCommandPromptPluginEnabled } from './CommandPalette/useCommands';
5
+ import { createSelectionSyncPlugin } from './createSelectionSyncPlugin';
5
6
  import { createDeserializeDocxPlugin } from './DeserializeDocx';
6
7
  import { createDragAndDropPlugin } from './DragAndDrop';
7
8
  import { createEmbeddedAssetBlockPlugin, createEmbeddedEntryBlockPlugin } from './EmbeddedEntityBlock';
@@ -23,9 +24,12 @@ import { createTextPlugin } from './Text';
23
24
  import { createTrackingPlugin } from './Tracking';
24
25
  import { createTrailingParagraphPlugin } from './TrailingParagraph';
25
26
  import { createVoidsPlugin } from './Voids';
26
- export const getPlugins = (sdk, onAction, restrictedMarks, withCharValidation)=>[
27
+ export const getPlugins = (sdk, onAction, restrictedMarks, withCharValidation, withSelectionSync = false)=>[
27
28
  createDeserializeDocxPlugin(),
28
29
  createTrackingPlugin(onAction),
30
+ ...withSelectionSync ? [
31
+ createSelectionSyncPlugin()
32
+ ] : [],
29
33
  createDragAndDropPlugin(),
30
34
  ...Object.values(isCommandPromptPluginEnabled(sdk)).some(Boolean) ? [
31
35
  createCommandPalettePlugin()
@@ -19,6 +19,8 @@ type RichTextProps = {
19
19
  */
20
20
  onChange?: (doc: Contentful.Document) => unknown;
21
21
  withCharValidation?: boolean;
22
+ /** Enable caret syncing at editor creation. Defaults to false; remount to change it. */
23
+ withSelectionSync?: boolean;
22
24
  queryClient?: QueryClient;
23
25
  };
24
26
  type ConnectedRichTextProps = {
@@ -34,6 +36,7 @@ type ConnectedRichTextProps = {
34
36
  actionsDisabled?: boolean;
35
37
  stickyToolbarOffset?: number;
36
38
  withCharValidation?: boolean;
39
+ withSelectionSync?: boolean;
37
40
  queryClient?: QueryClient;
38
41
  };
39
42
  export declare const ConnectedRichTextEditor: React.NamedExoticComponent<ConnectedRichTextProps>;
@@ -0,0 +1,2 @@
1
+ import { PlatePlugin } from '../internal/types';
2
+ export declare const createSelectionSyncPlugin: () => PlatePlugin;
@@ -1,4 +1,4 @@
1
1
  import { FieldAppSDK } from '@contentful/app-sdk';
2
2
  import { PlatePlugin } from '../internal/types';
3
3
  import { RichTextTrackingActionHandler } from './Tracking';
4
- export declare const getPlugins: (sdk: FieldAppSDK, onAction: RichTextTrackingActionHandler, restrictedMarks?: string[], withCharValidation?: boolean) => PlatePlugin[];
4
+ export declare const getPlugins: (sdk: FieldAppSDK, onAction: RichTextTrackingActionHandler, restrictedMarks?: string[], withCharValidation?: boolean, withSelectionSync?: boolean) => PlatePlugin[];
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@contentful/field-editor-rich-text",
3
- "version": "6.6.1",
3
+ "version": "6.6.2-canary.10+6bc1a622",
4
4
  "source": "./src/index.tsx",
5
5
  "main": "dist/cjs/index.js",
6
6
  "module": "dist/esm/index.js",
@@ -96,5 +96,5 @@
96
96
  "prettier --write"
97
97
  ]
98
98
  },
99
- "gitHead": "de96ffd473521caf9b0a67c0680e3fdd5d44b808"
99
+ "gitHead": "6bc1a6225c8280b79b8a400b15bf67af9bcffc85"
100
100
  }