Repository navigation
Expand file tree
/
Copy pathdocument-link.tsx
More file actions
70 lines (69 loc) · 2.28 KB
/
Copy pathdocument-link.tsx
File metadata and controls
70 lines (69 loc) · 2.28 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
65
66
67
68
69
70
import { Editor, Element, Node, Transforms } from "slate";
import { FileText } from "lucide-react";
import { ReactEditor } from "slate-react";
import {
createAtomicInlineExtension,
type CustomElement,
type EditorPlugin,
} from "@smartdoca/slate";
import { api, type Detail } from "@web/shared/api.js";
import { workspaceDocumentId } from "@web/features/documents/internal-document-id.js";
export { internalDocumentId } from "@web/features/documents/internal-document-id.js";
import { referenceCodec } from "@core/modules/documents/codecs/rich-runtime.js";
const extension = createAtomicInlineExtension({
...referenceCodec,
decode: (data, identity) =>
referenceCodec.decode(data, identity) as CustomElement,
render: (e) => (
<span className="document-inline-reference">
<a
href={`#/r/${e.documentId}`}
target="_blank"
rel="noopener noreferrer"
onMouseDown={(event) => event.preventDefault()}
>
<FileText size={15} />
{String(e.label)}
</a>
</span>
),
});
export const documentLinkPlugin: EditorPlugin = {
...extension.plugin,
withEditor(editor) {
const e = extension.plugin.withEditor?.(editor) ?? editor;
const insertData = e.insertData;
e.insertData = (data) => {
const id = workspaceDocumentId(data.getData("text/plain").trim());
if (!id || data.files.length) return insertData(data);
const nodeId = crypto.randomUUID();
Transforms.insertNodes(e, {
type: "custom:document-reference",
id: nodeId,
documentId: id,
label: "文档链接",
children: [{ text: "" }],
});
Transforms.move(e);
void api<Detail>(`/resources/${id}`)
.then((detail) => {
if (detail.resource.kind !== "document" || ReactEditor.isReadOnly(e))
return;
const found = [
...Editor.nodes(e, {
at: [],
match: (n) => Element.isElement(n) && n.id === nodeId,
voids: true,
}),
][0];
if (found && (found[0] as any).label === "文档链接")
Transforms.setNodes(e, { label: detail.resource.title } as any, {
at: found[1],
voids: true,
});
})
.catch(() => {});
};
return e;
},
};