| import { Editor, Descendant } from 'slate' |
| import { Key } from 'slate-dom' |
| import { ChunkLeaf } from './types' |
| import { ReactEditor } from '../plugin/react-editor' |
|
|
| |
| |
| |
| |
| export class ChildrenHelper { |
| private editor: Editor |
| private children: Descendant[] |
|
|
| |
| |
| |
| |
| |
| |
| private cachedKeys: Array<Key | undefined> |
|
|
| |
| |
| |
| public pointerIndex: number |
|
|
| constructor(editor: Editor, children: Descendant[]) { |
| this.editor = editor |
| this.children = children |
| this.cachedKeys = new Array(children.length) |
| this.pointerIndex = 0 |
| } |
|
|
| |
| |
| |
| public read(n: number): Descendant[] { |
| |
| |
| if (n === 1) { |
| return [this.children[this.pointerIndex++]] |
| } |
|
|
| const slicedChildren = this.remaining(n) |
| this.pointerIndex += n |
|
|
| return slicedChildren |
| } |
|
|
| |
| |
| |
| |
| |
| public remaining(maxChildren?: number): Descendant[] { |
| if (maxChildren === undefined) { |
| return this.children.slice(this.pointerIndex) |
| } |
|
|
| return this.children.slice( |
| this.pointerIndex, |
| this.pointerIndex + maxChildren |
| ) |
| } |
|
|
| |
| |
| |
| public get reachedEnd() { |
| return this.pointerIndex >= this.children.length |
| } |
|
|
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| public lookAhead(node: Descendant, key: Key) { |
| const elementResult = this.children.indexOf(node, this.pointerIndex) |
| if (elementResult > -1) return elementResult - this.pointerIndex |
|
|
| for (let i = this.pointerIndex; i < this.children.length; i++) { |
| const candidateNode = this.children[i] |
| const candidateKey = this.findKey(candidateNode, i) |
| if (candidateKey === key) return i - this.pointerIndex |
| } |
|
|
| return -1 |
| } |
|
|
| |
| |
| |
| |
| public toChunkLeaves(nodes: Descendant[], startIndex: number): ChunkLeaf[] { |
| return nodes.map((node, i) => ({ |
| type: 'leaf', |
| node, |
| key: this.findKey(node, startIndex + i), |
| index: startIndex + i, |
| })) |
| } |
|
|
| |
| |
| |
| private findKey(node: Descendant, index: number): Key { |
| const cachedKey = this.cachedKeys[index] |
| if (cachedKey) return cachedKey |
| const key = ReactEditor.findKey(this.editor, node) |
| this.cachedKeys[index] = key |
| return key |
| } |
| } |
|
|