返回 presentation-ai
sibling-index.ts
1 import {
2 NodeApi,
3 PathApi,
4 type NodeEntry,
5 type Path,
6 type TElement,
7 } from "platejs";
8 import { type PlateEditor } from "platejs/react";
9
10 type ElementWithOptionalId = TElement & {
11 id?: unknown;
12 };
13
14 function findCurrentElementPath(
15 editor: PlateEditor,
16 element: TElement,
17 ): Path | undefined {
18 const elementId = (element as ElementWithOptionalId).id;
19
20 if (typeof elementId === "string") {
21 const entry = editor.api.node({
22 id: elementId,
23 at: [],
24 }) as NodeEntry<TElement> | undefined;
25
26 if (entry) return entry[1];
27 }
28
29 return editor.api.findPath(element);
30 }
31
32 export function getSiblingIndexContext<TParentElement extends TElement>(
33 editor: PlateEditor,
34 element: TElement,
35 fallbackPath: Path,
36 ) {
37 const elementPath = findCurrentElementPath(editor, element) ?? fallbackPath;
38 const parentPath = PathApi.parent(elementPath);
39 const parentElement = NodeApi.get(editor, parentPath) as
40 | TParentElement
41 | undefined;
42 const index = elementPath.at(-1) ?? fallbackPath.at(-1) ?? 0;
43
44 return {
45 elementPath,
46 index,
47 parentElement,
48 parentPath,
49 };
50 }
51
51 lines TYPESCRIPT