Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changeset/fix-selection-after-remote-mark.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"@portabletext/editor": patch
---

fix: preserve selection after remote mark changes
111 changes: 110 additions & 1 deletion packages/editor/src/editor/sync-machine.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,10 @@
import type {Patch} from '@portabletext/patches'
import {isSpan, isTextBlock, type PortableTextBlock} from '@portabletext/schema'
import {
isSpan,
isTextBlock,
type PortableTextBlock,
type PortableTextTextBlock,
} from '@portabletext/schema'
import type {ActorRefFrom} from 'xstate'
import {
and,
Expand Down Expand Up @@ -33,8 +38,13 @@ import {start} from '../slate/editor/start'
import {withoutNormalizing} from '../slate/editor/without-normalizing'
import type {Node} from '../slate/interfaces/node'
import type {PickFromUnion} from '../type-utils'
import type {BlockOffset} from '../types/block-offset'
import type {InvalidValueResolution} from '../types/editor'
import type {PortableTextSlateEditor} from '../types/slate-editor'
import {
blockOffsetToSpanSelectionPoint,
spanSelectionPointToBlockOffset,
} from '../utils/util.block-offset'
import {isKeyedSegment} from '../utils/util.is-keyed-segment'
import type {EditorSchema} from './editor-schema'

Expand Down Expand Up @@ -976,9 +986,22 @@ function updateBlock({

if (isPureReorder || (newKeys.length > 0 && !hasSharedKeys)) {
debug.syncValue('Replacing children via set_node')

const savedBlockOffsets = saveSelectionAsBlockOffsets(
slateEditor,
oldSlateBlock,
)

applySetNode(slateEditor, {children: slateBlock.children}, [
{_key: oldSlateBlock._key},
])

restoreSelectionFromBlockOffsets(
slateEditor,
slateBlock,
savedBlockOffsets,
)

slateEditor.onChange()
return
}
Expand Down Expand Up @@ -1151,3 +1174,89 @@ function updateBlock({
})
}
}

function saveSelectionAsBlockOffsets(
slateEditor: PortableTextSlateEditor,
block: PortableTextTextBlock,
):
| {anchor: BlockOffset | undefined; focus: BlockOffset | undefined}
| undefined {
const selection = slateEditor.selection

if (!selection) {
return undefined
}

const blockKey = block._key
const context = {schema: slateEditor.schema, value: [block]}

const anchorBlockSegment = selection.anchor.path.at(0)
const anchorInBlock =
isKeyedSegment(anchorBlockSegment) && anchorBlockSegment._key === blockKey

const focusBlockSegment = selection.focus.path.at(0)
const focusInBlock =
isKeyedSegment(focusBlockSegment) && focusBlockSegment._key === blockKey

if (!anchorInBlock && !focusInBlock) {
return undefined
}

return {
anchor: anchorInBlock
? spanSelectionPointToBlockOffset({
context,
selectionPoint: selection.anchor,
})
: undefined,
focus: focusInBlock
? spanSelectionPointToBlockOffset({
context,
selectionPoint: selection.focus,
})
: undefined,
}
}

function restoreSelectionFromBlockOffsets(
slateEditor: PortableTextSlateEditor,
newBlock: PortableTextTextBlock,
savedBlockOffsets:
| {anchor: BlockOffset | undefined; focus: BlockOffset | undefined}
| undefined,
): void {
if (!savedBlockOffsets) {
return
}

const selection = slateEditor.selection

if (!selection) {
return
}

const context = {schema: slateEditor.schema, value: [newBlock]}

const restoredAnchor = savedBlockOffsets.anchor
? blockOffsetToSpanSelectionPoint({
context,
blockOffset: savedBlockOffsets.anchor,
direction: 'forward',
})
: undefined

const restoredFocus = savedBlockOffsets.focus
? blockOffsetToSpanSelectionPoint({
context,
blockOffset: savedBlockOffsets.focus,
direction: 'forward',
})
: undefined

if (restoredAnchor || restoredFocus) {
applySelect(slateEditor, {
anchor: restoredAnchor ?? selection.anchor,
focus: restoredFocus ?? selection.focus,
})
}
}
82 changes: 82 additions & 0 deletions packages/editor/tests/selection-after-remote-patches.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -547,4 +547,86 @@ describe('Feature: Selection adjustment after remote patches', () => {
expect(editor.getSnapshot().context.selection).toEqual(afterBarSelection)
})
})

test('Scenario: Remote mark on text preserves cursor position', async () => {
const keyGenerator = createTestKeyGenerator()
const b1 = keyGenerator()
const s1 = keyGenerator()

const initialValue = [
{
_type: 'block',
_key: b1,
children: [{_type: 'span', _key: s1, text: 'foobarbaz', marks: []}],
markDefs: [],
style: 'normal',
},
]

const {editor, locator} = await createTestEditor({
keyGenerator,
schemaDefinition: defineSchema({
decorators: [{name: 'strong'}],
}),
initialValue,
})

await userEvent.click(locator)
await whenTheCaretIsPutAfter(editor, 'foobarbaz')

const newSpanFoo = keyGenerator()
const newSpanBar = keyGenerator()
const newSpanBaz = keyGenerator()

editor.send({
type: 'update value',
value: [
{
_type: 'block',
_key: b1,
children: [
{_type: 'span', _key: newSpanFoo, text: 'foo', marks: []},
{
_type: 'span',
_key: newSpanBar,
text: 'bar',
marks: ['strong'],
},
{_type: 'span', _key: newSpanBaz, text: 'baz', marks: []},
],
markDefs: [],
style: 'normal',
},
],
})

await vi.waitFor(() => {
expect(editor.getSnapshot().context.value).toEqual([
{
_type: 'block',
_key: b1,
children: [
{_type: 'span', _key: newSpanFoo, text: 'foo', marks: []},
{
_type: 'span',
_key: newSpanBar,
text: 'bar',
marks: ['strong'],
},
{_type: 'span', _key: newSpanBaz, text: 'baz', marks: []},
],
markDefs: [],
style: 'normal',
},
])
})

await vi.waitFor(() => {
const expectedSelection = getSelectionAfterText(
editor.getSnapshot().context,
'baz',
)
expect(editor.getSnapshot().context.selection).toEqual(expectedSelection)
})
})
})
Loading