Skip to content

Commit

Permalink
fix(editor): handle edge case with deleting empty text blocks next to…
Browse files Browse the repository at this point in the history
… block objects
  • Loading branch information
christianhg committed Oct 31, 2024
1 parent 65f8704 commit 3e7e815
Showing 1 changed file with 95 additions and 2 deletions.
97 changes: 95 additions & 2 deletions packages/editor/src/editor/behavior/behavior.core.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,13 @@
import {isPortableTextTextBlock} from '@sanity/types'
import {defineBehavior} from './behavior.types'
import {getFocusBlockObject} from './behavior.utils'
import {
getFocusBlockObject,
getFocusTextBlock,
getNextBlock,
getPreviousBlock,
isEmptyTextBlock,
selectionIsCollapsed,
} from './behavior.utils'

const softReturn = defineBehavior({
on: 'insert soft break',
Expand All @@ -16,4 +24,89 @@ const breakingVoidBlock = defineBehavior({
actions: [() => [{type: 'insert text block', decorators: []}]],
})

export const coreBehaviors = [softReturn, breakingVoidBlock]
const deletingEmptyTextBlockAfterBlockObject = defineBehavior({
on: 'delete backward',
guard: ({context}) => {
const focusTextBlock = getFocusTextBlock(context)
const selectionCollapsed = selectionIsCollapsed(context)
const previousBlock = getPreviousBlock(context)

if (!focusTextBlock || !selectionCollapsed || !previousBlock) {
return false
}

if (
isEmptyTextBlock(focusTextBlock.node) &&
!isPortableTextTextBlock(previousBlock.node)
) {
return {focusTextBlock, previousBlock}
}

return false
},
actions: [
(_, {focusTextBlock, previousBlock}) => [
{
type: 'delete',
selection: {
anchor: {path: focusTextBlock.path, offset: 0},
focus: {path: focusTextBlock.path, offset: 0},
},
},
{
type: 'select',
selection: {
anchor: {path: previousBlock.path, offset: 0},
focus: {path: previousBlock.path, offset: 0},
},
},
],
],
})

const deletingEmptyTextBlockBeforeBlockObject = defineBehavior({
on: 'delete forward',
guard: ({context}) => {
const focusTextBlock = getFocusTextBlock(context)
const selectionCollapsed = selectionIsCollapsed(context)
const nextBlock = getNextBlock(context)

if (!focusTextBlock || !selectionCollapsed || !nextBlock) {
return false
}

if (
isEmptyTextBlock(focusTextBlock.node) &&
!isPortableTextTextBlock(nextBlock.node)
) {
return {focusTextBlock, nextBlock}
}

return false
},
actions: [
(_, {focusTextBlock, nextBlock}) => [
{
type: 'delete',
selection: {
anchor: {path: focusTextBlock.path, offset: 0},
focus: {path: focusTextBlock.path, offset: 0},
},
},
{
type: 'select',
selection: {
anchor: {path: nextBlock.path, offset: 0},
focus: {path: nextBlock.path, offset: 0},
},
},
],
],
})

export const coreBehaviors = [
softReturn,
breakingVoidBlock,
deletingEmptyTextBlockAfterBlockObject,
deletingEmptyTextBlockBeforeBlockObject,
]

0 comments on commit 3e7e815

Please sign in to comment.