Skip to content
Merged
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
7 changes: 7 additions & 0 deletions .changeset/pt-native-traversal.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
---
"@portabletext/editor": minor
---

feat: internal Portable Text-native node traversal

Replaces the vendored Slate traversal system with schema-driven functions that resolve children on any node type, not just `.children`. The old system hardcoded `.children` as the only child field, which blocks first-class nesting where children will live in schema-defined fields like `rows`, `cells`, or `content`.
50 changes: 28 additions & 22 deletions packages/editor/src/editor/create-editable-api.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,18 +12,21 @@ import {
slateRangeToSelection,
} from '../internal-utils/slate-utils'
import {toSlateRange} from '../internal-utils/to-slate-range'
import {getNodes} from '../node-traversal/get-nodes'
import {getTextBlockNode} from '../node-traversal/get-text-block-node'
import {getActiveAnnotationsMarks} from '../selectors/selector.get-active-annotation-marks'
import {getActiveDecorators} from '../selectors/selector.get-active-decorators'
import {getFocusBlock} from '../selectors/selector.get-focus-block'
import {getFocusSpan} from '../selectors/selector.get-focus-span'
import {getSelectedValue} from '../selectors/selector.get-selected-value'
import {isActiveAnnotation} from '../selectors/selector.is-active-annotation'
import {node as editorNode} from '../slate/editor/node'
import {nodes} from '../slate/editor/nodes'
import {path as editorPath} from '../slate/editor/path'
import {isCollapsedRange} from '../slate/range/is-collapsed-range'
import {isExpandedRange} from '../slate/range/is-expanded-range'
import {isRange} from '../slate/range/is-range'
import {rangeEnd} from '../slate/range/range-end'
import {rangeIncludes} from '../slate/range/range-includes'
import {rangeStart} from '../slate/range/range-start'
import type {
EditableAPI,
EditableAPIDeleteOptions,
Expand Down Expand Up @@ -289,13 +292,10 @@ export function createEditableAPI(
let node: Node | undefined
try {
const entry = Array.from(
nodes(editor, {
at: [],
match: (n) => n._key === element._key,
}) || [],
getNodes(editor, {match: (n) => n._key === element._key}),
)[0]
if (entry) {
const [, itemPath] = entry
const itemPath = entry.path
node = getDomNode(editor, itemPath)
}
} catch {
Expand All @@ -309,28 +309,34 @@ export function createEditableAPI(
}
try {
const activeAnnotations: PortableTextObject[] = []
const spans = nodes(editor, {
at: editor.selection,
const spans = getNodes(editor, {
from: rangeStart(editor.selection).path,
to: rangeEnd(editor.selection).path,
match: (node) =>
isSpan({schema: editor.schema}, node) &&
node.marks !== undefined &&
Array.isArray(node.marks) &&
node.marks.length > 0,
})
for (const [span, path] of spans) {
const [block] = editorNode(editor, path, {depth: 1})
if (isTextBlock({schema: editor.schema}, block)) {
block.markDefs?.forEach((def) => {
if (
isSpan({schema: editor.schema}, span) &&
span.marks &&
Array.isArray(span.marks) &&
span.marks.includes(def._key)
) {
activeAnnotations.push(def)
}
})
for (const {node: span, path: spanPath} of spans) {
const blockEntry = getTextBlockNode(
editor,
editorPath(editor, spanPath, {depth: 1}),
)
if (!blockEntry) {
continue
}
const block = blockEntry.node
block.markDefs?.forEach((def) => {
if (
isSpan({schema: editor.schema}, span) &&
span.marks &&
Array.isArray(span.marks) &&
span.marks.includes(def._key)
) {
activeAnnotations.push(def)
}
})
}
return activeAnnotations
} catch {
Expand Down
2 changes: 2 additions & 0 deletions packages/editor/src/editor/create-slate-editor.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,8 @@ export function createSlateEditor(
keyGenerator: context.keyGenerator,
})

editor.editableTypes = new Set()

editor.decoratedRanges = []
editor.decoratorState = {}
editor.blockIndexMap = new Map<string, number>()
Expand Down
71 changes: 50 additions & 21 deletions packages/editor/src/editor/editor-dom.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,10 @@
import type {BehaviorEvent} from '../behaviors/behavior.types.event'
import {getDomNode} from '../dom-traversal/get-dom-node'
import {toSlateRange} from '../internal-utils/to-slate-range'
import {getNodes} from '../node-traversal/get-nodes'
import {getSelectionEndBlock, getSelectionStartBlock} from '../selectors'
import {isEditor} from '../slate/editor/is-editor'
import {nodes} from '../slate/editor/nodes'
import {isAncestorPath} from '../slate/path/is-ancestor-path'
import {rangeEdges} from '../slate/range/range-edges'
import type {PickFromUnion} from '../type-utils'
import type {PortableTextSlateEditor} from '../types/slate-editor'
import type {EditorSnapshot} from './editor-snapshot'
Expand Down Expand Up @@ -63,16 +64,26 @@ function getBlockNodes(
}

try {
const blockEntries = Array.from(
nodes(slateEditor, {
at: range,
mode: 'highest',
match: (n) => !isEditor(n),
}),
)
const [start, end] = rangeEdges(range)
const blockEntries: Array<{node: unknown; path: Array<number>}> = []
let lastHighestPath: Array<number> | undefined

return blockEntries.flatMap(([, blockPath]) => {
const domNode = getDomNode(slateEditor, blockPath)
for (const entry of getNodes(slateEditor, {
from: start.path,
to: end.path,
})) {
const entryPath = entry.path

if (lastHighestPath && isAncestorPath(lastHighestPath, entryPath)) {
continue
}

lastHighestPath = entryPath
blockEntries.push(entry)
}

return blockEntries.flatMap((blockEntry) => {
const domNode = getDomNode(slateEditor, blockEntry.path)

if (!domNode) {
return []
Expand Down Expand Up @@ -100,16 +111,34 @@ function getChildNodes(
}

try {
const childEntries = Array.from(
nodes(slateEditor, {
at: range,
mode: 'lowest',
match: (n) => !isEditor(n),
}),
)

return childEntries.flatMap(([, childPath]) => {
const domNode = getDomNode(slateEditor, childPath)
const [start, end] = rangeEdges(range)
const childEntries: Array<{node: unknown; path: Array<number>}> = []
let buffered: {node: unknown; path: Array<number>} | undefined

for (const entry of getNodes(slateEditor, {
from: start.path,
to: end.path,
})) {
const entryPath = entry.path

if (buffered) {
if (isAncestorPath(buffered.path, entryPath)) {
buffered = entry
continue
}

childEntries.push(buffered)
}

buffered = entry
}

if (buffered) {
childEntries.push(buffered)
}

return childEntries.flatMap((childEntry) => {
const domNode = getDomNode(slateEditor, childEntry.path)

if (!domNode) {
return []
Expand Down
11 changes: 3 additions & 8 deletions packages/editor/src/editor/render.inline-object.tsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import type {PortableTextChild, PortableTextObject} from '@portabletext/schema'
import {useContext, useRef, type ReactElement} from 'react'
import {getPointBlock} from '../internal-utils/slate-utils'
import {getNode} from '../node-traversal/get-node'
import {serializePath} from '../paths/serialize-path'
import type {Path} from '../slate/interfaces/path'
import type {RenderElementProps} from '../slate/react/components/editable'
Expand Down Expand Up @@ -32,13 +32,8 @@ export function RenderInlineObject(props: {
)
}

const [block] = getPointBlock({
editor: slateEditor,
point: {
path: props.indexedPath,
offset: 0,
},
})
const blockEntry = getNode(slateEditor, props.indexedPath.slice(0, 1))
const block = blockEntry?.node

if (!block) {
console.error(
Expand Down
38 changes: 29 additions & 9 deletions packages/editor/src/editor/sync-machine.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,15 +24,15 @@ import {
import {safeStringify} from '../internal-utils/safe-json'
import {validateValue} from '../internal-utils/validateValue'
import {toSlateBlock} from '../internal-utils/values'
import {getNode} from '../node-traversal/get-node'
import {hasNode} from '../node-traversal/has-node'
import {withRemoteChanges} from '../slate-plugins/slate-plugin.remote-changes'
import {pluginWithoutHistory} from '../slate-plugins/slate-plugin.without-history'
import {withoutPatching} from '../slate-plugins/slate-plugin.without-patching'
import {deleteText} from '../slate/core/delete-text'
import {node as editorNode} from '../slate/editor/node'
import {start} from '../slate/editor/start'
import {withoutNormalizing} from '../slate/editor/without-normalizing'
import type {Node} from '../slate/interfaces/node'
import {hasNode} from '../slate/node/has-node'
import type {PickFromUnion} from '../type-utils'
import type {InvalidValueResolution} from '../types/editor'
import type {PortableTextSlateEditor} from '../types/slate-editor'
Expand Down Expand Up @@ -612,7 +612,11 @@ function clearEditor({

slateEditor.children.forEach((_, index) => {
const removePath = [childrenLength - 1 - index]
const [removeNode] = editorNode(slateEditor, removePath)
const removeEntry = getNode(slateEditor, removePath)
if (!removeEntry) {
return
}
const removeNode = removeEntry.node
slateEditor.apply({
type: 'remove_node',
path: removePath,
Expand Down Expand Up @@ -645,7 +649,11 @@ function removeExtraBlocks({

if (value.length < childrenLength) {
for (let i = childrenLength - 1; i > value.length - 1; i--) {
const [removeNode] = editorNode(slateEditor, [i])
const removeEntry2 = getNode(slateEditor, [i])
if (!removeEntry2) {
continue
}
const removeNode = removeEntry2.node
slateEditor.apply({
type: 'remove_node',
path: [i],
Expand Down Expand Up @@ -861,16 +869,20 @@ function replaceBlock({
applyDeselect(slateEditor)
}

const [oldNode] = editorNode(slateEditor, [index])
const oldNodeEntry = getNode(slateEditor, [index])
if (!oldNodeEntry) {
return
}
const oldNode = oldNodeEntry.node
slateEditor.apply({type: 'remove_node', path: [index], node: oldNode})
slateEditor.apply({type: 'insert_node', path: [index], node: slateBlock})

slateEditor.onChange()

if (
selectionFocusOnBlock &&
hasNode(slateEditor, currentSelection.anchor.path, slateEditor.schema) &&
hasNode(slateEditor, currentSelection.focus.path, slateEditor.schema)
hasNode(slateEditor, currentSelection.anchor.path) &&
hasNode(slateEditor, currentSelection.focus.path)
) {
applySelect(slateEditor, currentSelection)
}
Expand Down Expand Up @@ -945,7 +957,11 @@ function updateBlock({
if (childIndex > 0) {
debug.syncValue('Removing child')

const [childNode] = editorNode(slateEditor, [index, childIndex])
const childNodeEntry = getNode(slateEditor, [index, childIndex])
if (!childNodeEntry) {
return
}
const childNode = childNodeEntry.node
slateEditor.apply({
type: 'remove_node',
path: [index, childIndex],
Expand Down Expand Up @@ -1019,10 +1035,14 @@ function updateBlock({
} else if (oldBlockChild) {
debug.syncValue('Replacing child', currentBlockChild)

const [oldChild] = editorNode(slateEditor, [
const oldChildEntry = getNode(slateEditor, [
index,
currentBlockChildIndex,
])
if (!oldChildEntry) {
return
}
const oldChild = oldChildEntry.node
slateEditor.apply({
type: 'remove_node',
path: [index, currentBlockChildIndex],
Expand Down
21 changes: 11 additions & 10 deletions packages/editor/src/internal-utils/apply-insert-node.ts
Original file line number Diff line number Diff line change
@@ -1,15 +1,14 @@
import {isSpan} from '@portabletext/schema'
import {getNode} from '../node-traversal/get-node'
import {end} from '../slate/editor/end'
import {isEdge} from '../slate/editor/is-edge'
import {isEnd} from '../slate/editor/is-end'
import {nodes} from '../slate/editor/nodes'
import {pathRef} from '../slate/editor/path-ref'
import {withoutNormalizing} from '../slate/editor/without-normalizing'
import type {Node} from '../slate/interfaces/node'
import type {Path} from '../slate/interfaces/path'
import type {Point} from '../slate/interfaces/point'
import {extractProps} from '../slate/node/extract-props'
import {getNode} from '../slate/node/get-node'
import {isObjectNode} from '../slate/node/is-object-node'
import {nextPath} from '../slate/path/next-path'
import type {PortableTextSlateEditor} from '../types/slate-editor'
Expand Down Expand Up @@ -50,24 +49,26 @@ export function applyInsertNodeAtPoint(
isSpan({schema: editor.schema}, n) ||
isObjectNode({schema: editor.schema}, n)

const [entry] = nodes(editor, {
at: at.path,
match,
mode: 'lowest',
includeObjectNodes: false,
})
const nodeEntry = getNode(editor, at.path)
const entry = nodeEntry && match(nodeEntry.node) ? nodeEntry : undefined

if (!entry) {
return
}

const [, matchPath] = entry
const matchPath = entry.path
const ref = pathRef(editor, matchPath)
const isAtEnd = isEnd(editor, at, matchPath)

// Split the node at the point if we're not at an edge
if (!isEdge(editor, at, matchPath)) {
const textNode = getNode(editor, at.path, editor.schema)
const textNodeEntry = getNode(editor, at.path)

if (!textNodeEntry) {
return
}

const textNode = textNodeEntry.node
const properties = extractProps(textNode, editor.schema)

applySplitNode(editor, at.path, at.offset, properties)
Expand Down
10 changes: 8 additions & 2 deletions packages/editor/src/internal-utils/apply-merge-node.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
import {isSpan, isTextBlock} from '@portabletext/schema'
import {getNode} from '../node-traversal/get-node'
import {withoutNormalizing} from '../slate/editor/without-normalizing'
import type {Path} from '../slate/interfaces/path'
import type {Point} from '../slate/interfaces/point'
import type {Range} from '../slate/interfaces/range'
import {getNode} from '../slate/node/get-node'
import {isAncestorPath} from '../slate/path/is-ancestor-path'
import {pathEndsBefore} from '../slate/path/path-ends-before'
import {pathEquals} from '../slate/path/path-equals'
Expand All @@ -28,7 +28,13 @@ export function applyMergeNode(
path: Path,
position: number,
): void {
const node = getNode(editor, path, editor.schema)
const nodeEntry = getNode(editor, path)

if (!nodeEntry) {
return
}

const node = nodeEntry.node
const prevPath = previousPath(path)

// Pre-transform all refs with merge semantics
Expand Down
Loading
Loading