@portabletext/editor 2.1.10 → 2.2.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.
Files changed (29) hide show
  1. package/lib/_chunks-cjs/util.merge-text-blocks.cjs +2 -2
  2. package/lib/_chunks-cjs/util.merge-text-blocks.cjs.map +1 -1
  3. package/lib/_chunks-es/selector.is-selection-expanded.js +1 -1
  4. package/lib/_chunks-es/util.merge-text-blocks.js +2 -2
  5. package/lib/_chunks-es/util.merge-text-blocks.js.map +1 -1
  6. package/lib/index.cjs +166 -25
  7. package/lib/index.cjs.map +1 -1
  8. package/lib/index.js +169 -28
  9. package/lib/index.js.map +1 -1
  10. package/lib/plugins/index.d.cts +3 -3
  11. package/lib/utils/index.d.ts +2 -2
  12. package/package.json +7 -7
  13. package/src/behaviors/behavior.abstract.split.ts +77 -1
  14. package/src/converters/converter.portable-text.deserialize.test.ts +3 -3
  15. package/src/converters/converter.portable-text.ts +1 -1
  16. package/src/converters/converter.text-html.ts +1 -1
  17. package/src/converters/converter.text-plain.ts +1 -1
  18. package/src/editor/Editable.tsx +2 -2
  19. package/src/editor/plugins/__tests__/withPortableTextMarkModel.test.tsx +29 -35
  20. package/src/editor/plugins/createWithEditableAPI.ts +1 -1
  21. package/src/editor/plugins/createWithObjectKeys.ts +110 -1
  22. package/src/internal-utils/applyPatch.ts +1 -1
  23. package/src/internal-utils/test-editor.tsx +2 -0
  24. package/src/internal-utils/text-marks.ts +1 -1
  25. package/src/internal-utils/to-slate-range.ts +1 -1
  26. package/src/operations/behavior.operation.annotation.add.ts +1 -1
  27. package/src/operations/behavior.operation.delete.ts +31 -2
  28. package/src/operations/behavior.operation.insert.block.ts +85 -13
  29. package/src/utils/util.merge-text-blocks.ts +1 -1
@@ -1,5 +1,5 @@
1
1
  import { Behavior, Editor, EditorEmittedEvent, EditorSchema } from "../_chunks-dts/behavior.types.action.cjs";
2
- import * as react22 from "react";
2
+ import * as react21 from "react";
3
3
  import React from "react";
4
4
  /**
5
5
  * @beta
@@ -181,7 +181,7 @@ type MarkdownPluginConfig = MarkdownBehaviorsConfig & {
181
181
  */
182
182
  declare function MarkdownPlugin(props: {
183
183
  config: MarkdownPluginConfig;
184
- }): react22.JSX.Element;
184
+ }): react21.JSX.Element;
185
185
  /**
186
186
  * @beta
187
187
  * Restrict the editor to one line. The plugin takes care of blocking
@@ -192,5 +192,5 @@ declare function MarkdownPlugin(props: {
192
192
  *
193
193
  * @deprecated Install the plugin from `@portabletext/plugin-one-line`
194
194
  */
195
- declare function OneLinePlugin(): react22.JSX.Element;
195
+ declare function OneLinePlugin(): react21.JSX.Element;
196
196
  export { BehaviorPlugin, DecoratorShortcutPlugin, EditorRefPlugin, EventListenerPlugin, MarkdownPlugin, type MarkdownPluginConfig, OneLinePlugin };
@@ -1,5 +1,5 @@
1
1
  import { BlockOffset, BlockPath, ChildPath, EditorContext, EditorSelection, EditorSelectionPoint } from "../_chunks-dts/behavior.types.action.js";
2
- import * as _sanity_types8 from "@sanity/types";
2
+ import * as _sanity_types9 from "@sanity/types";
3
3
  import { KeyedSegment, PortableTextBlock, PortableTextChild, PortableTextSpan, PortableTextTextBlock } from "@sanity/types";
4
4
  /**
5
5
  * @public
@@ -150,7 +150,7 @@ declare function mergeTextBlocks({
150
150
  context: Pick<EditorContext, 'keyGenerator' | 'schema'>;
151
151
  targetBlock: PortableTextTextBlock;
152
152
  incomingBlock: PortableTextTextBlock;
153
- }): PortableTextTextBlock<_sanity_types8.PortableTextObject | _sanity_types8.PortableTextSpan>;
153
+ }): PortableTextTextBlock<_sanity_types9.PortableTextObject | _sanity_types9.PortableTextSpan>;
154
154
  /**
155
155
  * @public
156
156
  */
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@portabletext/editor",
3
- "version": "2.1.10",
3
+ "version": "2.2.0",
4
4
  "description": "Portable Text Editor made in React",
5
5
  "keywords": [
6
6
  "sanity",
@@ -78,15 +78,15 @@
78
78
  "slate": "0.118.0",
79
79
  "slate-dom": "^0.117.4",
80
80
  "slate-react": "0.117.4",
81
- "xstate": "^5.20.1",
81
+ "xstate": "^5.20.2",
82
82
  "@portabletext/block-tools": "2.0.8",
83
- "@portabletext/patches": "1.1.6",
84
- "@portabletext/keyboard-shortcuts": "1.1.1"
83
+ "@portabletext/keyboard-shortcuts": "1.1.1",
84
+ "@portabletext/patches": "1.1.6"
85
85
  },
86
86
  "devDependencies": {
87
87
  "@portabletext/toolkit": "^2.0.17",
88
88
  "@sanity/diff-match-patch": "^3.2.0",
89
- "@sanity/pkg-utils": "^7.9.21",
89
+ "@sanity/pkg-utils": "^7.11.1",
90
90
  "@sanity/schema": "^4.3.0",
91
91
  "@sanity/types": "^4.3.0",
92
92
  "@testing-library/react": "^16.3.0",
@@ -95,8 +95,8 @@
95
95
  "@types/lodash.startcase": "^4.4.9",
96
96
  "@types/react": "^19.1.9",
97
97
  "@types/react-dom": "^19.1.7",
98
- "@typescript-eslint/eslint-plugin": "^8.38.0",
99
- "@typescript-eslint/parser": "^8.38.0",
98
+ "@typescript-eslint/eslint-plugin": "^8.39.0",
99
+ "@typescript-eslint/parser": "^8.39.0",
100
100
  "@vitejs/plugin-react": "^4.7.0",
101
101
  "@vitest/browser": "^3.2.4",
102
102
  "@vitest/coverage-istanbul": "^3.2.4",
@@ -56,6 +56,79 @@ export const abstractSplitBehaviors = [
56
56
  actions: [(_, {selection}) => [raise({type: 'delete', at: selection})]],
57
57
  }),
58
58
 
59
+ defineBehavior({
60
+ on: 'split',
61
+ guard: ({snapshot}) => {
62
+ const selection = snapshot.context.selection
63
+
64
+ if (!selection || utils.isSelectionCollapsed(selection)) {
65
+ return false
66
+ }
67
+
68
+ const selectionStartBlock = selectors.getSelectionStartBlock(snapshot)
69
+ const selectionEndBlock = selectors.getSelectionEndBlock(snapshot)
70
+
71
+ if (!selectionStartBlock || !selectionEndBlock) {
72
+ return false
73
+ }
74
+
75
+ if (selectionStartBlock.node._key === selectionEndBlock.node._key) {
76
+ return false
77
+ }
78
+
79
+ const startPoint = utils.getSelectionStartPoint(selection)
80
+ const startBlockEndPoint = utils.getBlockEndPoint({
81
+ context: snapshot.context,
82
+ block: selectionStartBlock,
83
+ })
84
+ const endPoint = utils.getSelectionEndPoint(selection)
85
+ const endBlockStartPoint = utils.getBlockStartPoint({
86
+ context: snapshot.context,
87
+ block: selectionEndBlock,
88
+ })
89
+
90
+ const selectedValue = selectors.getSelectedValue(snapshot)
91
+
92
+ const blocksInBetween = selectedValue.filter(
93
+ (block) =>
94
+ block._key !== selectionStartBlock.node._key &&
95
+ block._key !== selectionEndBlock.node._key,
96
+ )
97
+
98
+ return {
99
+ startPoint,
100
+ startBlockEndPoint,
101
+ endPoint,
102
+ endBlockStartPoint,
103
+ blocksInBetween,
104
+ }
105
+ },
106
+ actions: [
107
+ (
108
+ _,
109
+ {
110
+ startPoint,
111
+ startBlockEndPoint,
112
+ endPoint,
113
+ endBlockStartPoint,
114
+ blocksInBetween,
115
+ },
116
+ ) => [
117
+ raise({
118
+ type: 'delete',
119
+ at: {anchor: startPoint, focus: startBlockEndPoint},
120
+ }),
121
+ ...blocksInBetween.map((block) =>
122
+ raise({type: 'delete.block', at: [{_key: block._key}]}),
123
+ ),
124
+ raise({
125
+ type: 'delete',
126
+ at: {anchor: endBlockStartPoint, focus: endPoint},
127
+ }),
128
+ ],
129
+ ],
130
+ }),
131
+
59
132
  defineBehavior({
60
133
  on: 'split',
61
134
  guard: ({snapshot}) => {
@@ -111,7 +184,10 @@ export const abstractSplitBehaviors = [
111
184
  block: focusTextBlock.node,
112
185
  }),
113
186
  context: snapshot.context,
114
- options: {refreshKeys: true, validateFields: true},
187
+ options: {
188
+ refreshKeys: false,
189
+ validateFields: false,
190
+ },
115
191
  })
116
192
 
117
193
  if (!newTextBlock) {
@@ -159,7 +159,7 @@ describe(converterPortableText.deserialize, () => {
159
159
  ).toMatchObject({
160
160
  data: [
161
161
  {
162
- _key: 'k0',
162
+ _key: 'b2',
163
163
  _type: 'image',
164
164
  src: 'https://example.com/image.jpg',
165
165
  },
@@ -573,7 +573,7 @@ describe(converterPortableText.deserialize, () => {
573
573
  {
574
574
  _type: 'span',
575
575
  text: 'foo',
576
- marks: ['k1'],
576
+ marks: ['b0m0'],
577
577
  },
578
578
  {
579
579
  _type: 'span',
@@ -583,7 +583,7 @@ describe(converterPortableText.deserialize, () => {
583
583
  ],
584
584
  markDefs: [
585
585
  {
586
- _key: 'k1',
586
+ _key: 'b0m0',
587
587
  _type: 'link',
588
588
  href: 'https://example.com',
589
589
  },
@@ -50,7 +50,7 @@ export const converterPortableText = defineConverter({
50
50
  context: snapshot.context,
51
51
  block,
52
52
  options: {
53
- refreshKeys: true,
53
+ refreshKeys: false,
54
54
  validateFields: false,
55
55
  },
56
56
  })
@@ -62,7 +62,7 @@ export function createConverterTextHtml(
62
62
  block,
63
63
  options: {
64
64
  refreshKeys: false,
65
- validateFields: true,
65
+ validateFields: false,
66
66
  },
67
67
  })
68
68
  return parsedBlock ? [parsedBlock] : []
@@ -85,7 +85,7 @@ export function createConverterTextPlain(
85
85
  block,
86
86
  options: {
87
87
  refreshKeys: false,
88
- validateFields: true,
88
+ validateFields: false,
89
89
  },
90
90
  })
91
91
  return parsedBlock ? [parsedBlock] : []
@@ -474,8 +474,8 @@ export const PortableTextEditable = forwardRef<
474
474
  },
475
475
  blocks: result.insert,
476
476
  options: {
477
- refreshKeys: true,
478
- validateFields: true,
477
+ refreshKeys: false,
478
+ validateFields: false,
479
479
  },
480
480
  }),
481
481
  placement: 'auto',
@@ -191,57 +191,51 @@ describe('plugin:withPortableTextMarksModel', () => {
191
191
  await waitFor(() => {
192
192
  PortableTextEditor.select(editor, sel)
193
193
  PortableTextEditor.delete(editor, sel)
194
- expect(PortableTextEditor.getValue(editor)).toMatchInlineSnapshot(`
195
- [
194
+ expect(PortableTextEditor.getValue(editor)).toEqual([
196
195
  {
197
- "_key": "5fc57af23597",
198
- "_type": "myTestBlockType",
199
- "children": [
196
+ _key: '5fc57af23597',
197
+ _type: 'myTestBlockType',
198
+ children: [
200
199
  {
201
- "_key": "be1c67c6971a",
202
- "_type": "span",
203
- "marks": [],
204
- "text": "This is a ",
200
+ _key: 'be1c67c6971a',
201
+ _type: 'span',
202
+ marks: [],
203
+ text: 'This is a ',
205
204
  },
206
205
  {
207
- "_key": "11c8c9f783a8",
208
- "_type": "span",
209
- "marks": [
210
- "fde1fd54b544",
211
- ],
212
- "text": "link",
206
+ _key: '11c8c9f783a8',
207
+ _type: 'span',
208
+ marks: ['fde1fd54b544'],
209
+ text: 'link',
213
210
  },
214
211
  {
215
- "_key": "576c748e0cd2",
216
- "_type": "span",
217
- "marks": [],
218
- "text": "This is ",
212
+ _key: '576c748e0cd2',
213
+ _type: 'span',
214
+ marks: [],
215
+ text: 'This is ',
219
216
  },
220
217
  {
221
- "_key": "f3d73d3833bf",
222
- "_type": "span",
223
- "marks": [
224
- "7b6d3d5de30c",
225
- ],
226
- "text": "another",
218
+ _key: 'f3d73d3833bf',
219
+ _type: 'span',
220
+ marks: ['7b6d3d5de30c'],
221
+ text: 'another',
227
222
  },
228
223
  ],
229
- "markDefs": [
224
+ markDefs: [
230
225
  {
231
- "_key": "fde1fd54b544",
232
- "_type": "link",
233
- "url": "1",
226
+ _key: 'fde1fd54b544',
227
+ _type: 'link',
228
+ url: '1',
234
229
  },
235
230
  {
236
- "_key": "7b6d3d5de30c",
237
- "_type": "link",
238
- "url": "2",
231
+ _key: '7b6d3d5de30c',
232
+ _type: 'link',
233
+ url: '2',
239
234
  },
240
235
  ],
241
- "style": "normal",
236
+ style: 'normal',
242
237
  },
243
- ]
244
- `)
238
+ ])
245
239
  })
246
240
  })
247
241
 
@@ -424,7 +424,7 @@ export function createEditableAPI(
424
424
  return isActiveAnnotation(annotationType)(snapshot)
425
425
  },
426
426
  addAnnotation: (type, value) => {
427
- let paths: ReturnType<EditableAPI['addAnnotation']> = undefined
427
+ let paths: ReturnType<EditableAPI['addAnnotation']>
428
428
 
429
429
  Editor.withoutNormalizing(editor, () => {
430
430
  paths = addAnnotationOperationImplementation({
@@ -1,4 +1,6 @@
1
- import {Editor, Element, Node, Transforms} from 'slate'
1
+ import {isEqual} from 'lodash'
2
+ import {Editor, Element, Node, Path, Transforms} from 'slate'
3
+ import {isSpan, isTextBlock} from '../../internal-utils/parse-blocks'
2
4
  import {isChangingRemotely} from '../../internal-utils/withChanges'
3
5
  import {isRedoing, isUndoing} from '../../internal-utils/withUndoRedo'
4
6
  import type {PortableTextSlateEditor} from '../../types/editor'
@@ -78,6 +80,113 @@ export function createWithObjectKeys(editorActor: EditorActor) {
78
80
  }
79
81
  }
80
82
 
83
+ if (operation.type === 'merge_node') {
84
+ const index = operation.path[operation.path.length - 1]
85
+ const prevPath = Path.previous(operation.path)
86
+ const prevIndex = prevPath[prevPath.length - 1]
87
+
88
+ if (operation.path.length !== 1 || prevPath.length !== 1) {
89
+ apply(operation)
90
+ return
91
+ }
92
+
93
+ const block = editor.value.at(index)
94
+ const previousBlock = editor.value.at(prevIndex)
95
+
96
+ if (!block || !previousBlock) {
97
+ apply(operation)
98
+ return
99
+ }
100
+
101
+ if (
102
+ !isTextBlock(editorActor.getSnapshot().context, block) ||
103
+ !isTextBlock(editorActor.getSnapshot().context, previousBlock)
104
+ ) {
105
+ apply(operation)
106
+ return
107
+ }
108
+
109
+ // If we are merging two text blocks, then we need to make sure there
110
+ // are no duplicate keys in the blocks. Therefore, we assign new keys
111
+ // to any child or markDef that shares key with other children or
112
+ // markDefs in the previous block.
113
+ const previousBlockChildKeys = previousBlock.children.map(
114
+ (child) => child._key,
115
+ )
116
+ const previousBlockMarkDefKeys =
117
+ previousBlock.markDefs?.map((markDef) => markDef._key) ?? []
118
+
119
+ // Assign new keys to markDefs with duplicate keys and keep track of
120
+ // the mapping between the old and new keys
121
+ const markDefKeyMap = new Map<string, string>()
122
+ const adjustedMarkDefs = block.markDefs?.map((markDef) => {
123
+ if (previousBlockMarkDefKeys.includes(markDef._key)) {
124
+ const newKey = editorActor.getSnapshot().context.keyGenerator()
125
+ markDefKeyMap.set(markDef._key, newKey)
126
+ return {
127
+ ...markDef,
128
+ _key: newKey,
129
+ }
130
+ }
131
+
132
+ return markDef
133
+ })
134
+
135
+ // Assign new keys to spans with duplicate keys and update any markDef
136
+ // key if needed
137
+ let childIndex = 0
138
+ for (const child of block.children) {
139
+ if (isSpan(editorActor.getSnapshot().context, child)) {
140
+ const marks =
141
+ child.marks?.map((mark) => {
142
+ const markDefKey = markDefKeyMap.get(mark)
143
+
144
+ if (markDefKey) {
145
+ return markDefKey
146
+ }
147
+
148
+ return mark
149
+ }) ?? []
150
+
151
+ if (!isEqual(child.marks, marks)) {
152
+ Transforms.setNodes(
153
+ editor,
154
+ {
155
+ marks,
156
+ },
157
+ {
158
+ at: [index, childIndex],
159
+ },
160
+ )
161
+ }
162
+ }
163
+
164
+ if (previousBlockChildKeys.includes(child._key)) {
165
+ Transforms.setNodes(
166
+ editor,
167
+ {
168
+ _key: editorActor.getSnapshot().context.keyGenerator(),
169
+ },
170
+ {
171
+ at: [index, childIndex],
172
+ },
173
+ )
174
+ }
175
+ childIndex++
176
+ }
177
+
178
+ apply({
179
+ ...operation,
180
+ properties: {
181
+ ...operation.properties,
182
+ // Make sure the adjusted markDefs are carried along for the merge
183
+ // operation
184
+ markDefs: adjustedMarkDefs,
185
+ },
186
+ })
187
+ return
188
+ }
189
+
81
190
  apply(operation)
82
191
  }
83
192
 
@@ -298,7 +298,7 @@ function setPatch(editor: PortableTextSlateEditor, patch: SetPatch) {
298
298
  return true
299
299
  } else if (Element.isElement(block.node) && patch.path.length === 1) {
300
300
  const {children, ...nextRest} = value as unknown as PortableTextBlock
301
- const {children: prevChildren, ...prevRest} = block.node || {
301
+ const {children: _prevChildren, ...prevRest} = block.node || {
302
302
  children: undefined,
303
303
  }
304
304
 
@@ -24,6 +24,7 @@ export async function createTestEditor(
24
24
  initialValue?: Array<PortableTextBlock>
25
25
  keyGenerator?: () => string
26
26
  schemaDefinition?: SchemaDefinition
27
+ children?: React.ReactNode
27
28
  } = {},
28
29
  ) {
29
30
  const editorRef = React.createRef<Editor>()
@@ -45,6 +46,7 @@ export async function createTestEditor(
45
46
  <InternalSlateEditorRefPlugin ref={slateRef} />
46
47
  <EventListenerPlugin on={onEvent} />
47
48
  <PortableTextEditable />
49
+ {options.children}
48
50
  </EditorProvider>,
49
51
  )
50
52
 
@@ -9,7 +9,7 @@ export function getTextMarks(
9
9
  return undefined
10
10
  }
11
11
 
12
- let marks: Array<string> | undefined = undefined
12
+ let marks: Array<string> | undefined
13
13
 
14
14
  for (const block of value) {
15
15
  if (isPortableTextBlock(block)) {
@@ -136,7 +136,7 @@ function toSlateSelectionPoint(
136
136
  let offset = spanSelectionPoint?.offset ?? selectionPoint.offset
137
137
  let childPath: Array<number> = []
138
138
  let childIndex = -1
139
- let pathChild: PortableTextSpan | PortableTextObject | undefined = undefined
139
+ let pathChild: PortableTextSpan | PortableTextObject | undefined
140
140
 
141
141
  for (const child of block.children) {
142
142
  childIndex++
@@ -46,7 +46,7 @@ export const addAnnotationOperationImplementation: BehaviorOperationImplementati
46
46
  return
47
47
  }
48
48
 
49
- let paths: AddedAnnotationPaths | undefined = undefined
49
+ let paths: AddedAnnotationPaths | undefined
50
50
  let spanPath: Path | undefined
51
51
  let markDefPath: Path | undefined
52
52
  const markDefPaths: Path[] = []
@@ -1,4 +1,4 @@
1
- import {Transforms} from 'slate'
1
+ import {deleteText, setSelection, Transforms} from 'slate'
2
2
  import {createPlaceholderBlock} from '../internal-utils/create-placeholder-block'
3
3
  import {isTextBlock} from '../internal-utils/parse-blocks'
4
4
  import {getBlockPath} from '../internal-utils/slate-utils'
@@ -11,15 +11,33 @@ export const deleteOperationImplementation: BehaviorOperationImplementation<
11
11
  > = ({context, operation}) => {
12
12
  const anchorBlockKey = getBlockKeyFromSelectionPoint(operation.at.anchor)
13
13
  const focusBlockKey = getBlockKeyFromSelectionPoint(operation.at.focus)
14
+
15
+ const startBlockKey = operation.at.backward ? focusBlockKey : anchorBlockKey
14
16
  const endBlockKey = operation.at.backward ? anchorBlockKey : focusBlockKey
15
17
  const endOffset = operation.at.backward
16
18
  ? operation.at.focus.offset
17
19
  : operation.at.anchor.offset
18
20
 
21
+ if (!startBlockKey) {
22
+ throw new Error('Failed to get start block key')
23
+ }
24
+
19
25
  if (!endBlockKey) {
20
26
  throw new Error('Failed to get end block key')
21
27
  }
22
28
 
29
+ const startBlockIndex = operation.editor.blockIndexMap.get(startBlockKey)
30
+
31
+ if (startBlockIndex === undefined) {
32
+ throw new Error('Failed to get start block index')
33
+ }
34
+
35
+ const startBlock = operation.editor.value.at(startBlockIndex)
36
+
37
+ if (!startBlock) {
38
+ throw new Error('Failed to get start block')
39
+ }
40
+
23
41
  const endBlockIndex = operation.editor.blockIndexMap.get(endBlockKey)
24
42
 
25
43
  if (endBlockIndex === undefined) {
@@ -82,10 +100,21 @@ export const deleteOperationImplementation: BehaviorOperationImplementation<
82
100
 
83
101
  const hanging = isTextBlock(context, endBlock) && endOffset === 0
84
102
 
85
- operation.editor.delete({
103
+ deleteText(operation.editor, {
86
104
  at: range,
87
105
  reverse: operation.direction === 'backward',
88
106
  unit: operation.unit,
89
107
  hanging,
90
108
  })
109
+
110
+ if (
111
+ operation.editor.selection &&
112
+ isTextBlock(context, startBlock) &&
113
+ isTextBlock(context, endBlock)
114
+ ) {
115
+ setSelection(operation.editor, {
116
+ anchor: operation.editor.selection.focus,
117
+ focus: operation.editor.selection.focus,
118
+ })
119
+ }
91
120
  }