forked from CopilotKit/CopilotKit
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy patheditor-to-text.ts
More file actions
64 lines (56 loc) · 1.74 KB
/
Copy patheditor-to-text.ts
File metadata and controls
64 lines (56 loc) · 1.74 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
import { BaseEditor, Descendant, Element } from "slate";
import { HistoryEditor } from "slate-history";
import { ReactEditor } from "slate-react";
import { SuggestionAwareText } from "../types/base/custom-editor";
function nodeChildrenToTextComponents(
editor: BaseEditor & ReactEditor & HistoryEditor,
nodes: Descendant[],
): SuggestionAwareText[] {
// find inlineable elements
const indeciesOfInlineElements = new Set(
nodes
.map((node, index) => {
if (Element.isElement(node) && editor.isInline(node)) {
return index;
}
return -1;
})
.filter((index) => index !== -1),
);
// ignorable elements = inline elements,
// or neighbors of inline elements that are {text: ""}
const nonIgnorableItems = nodes.filter((node, index) => {
const isInline = indeciesOfInlineElements.has(index);
if (isInline) {
return false;
}
const isNeighbourOfInline =
indeciesOfInlineElements.has(index - 1) ||
indeciesOfInlineElements.has(index + 1);
if (isNeighbourOfInline) {
return (node as any).text !== "";
}
return true;
});
return nonIgnorableItems
.map((node) => {
if (Element.isElement(node)) {
switch (node.type) {
case "paragraph":
return nodeChildrenToTextComponents(editor, node.children);
case "suggestion":
return [];
}
} else {
return [node];
}
})
.reduce((acc, val) => acc.concat(val), []);
}
export const editorToText = (
editor: BaseEditor & ReactEditor & HistoryEditor,
) => {
const flattened = nodeChildrenToTextComponents(editor, editor.children);
const text = flattened.map((textComponent) => textComponent.text).join("\n");
return text;
};