MCPcopy Create free account
hub / github.com/editablejs/editable / withYCodeBlock

Function withYCodeBlock

packages/plugins/codeblock/src/plugin/yjs/index.ts:14–68  ·  view source on GitHub ↗
(
  editor: T,
  document: Y.Doc,
  awareness: Awareness,
)

Source from the content-addressed store, hash-verified

12export { YRange, ySync, ySyncFacet, YSyncConfig }
13
14export const withYCodeBlock = <T extends Editable>(
15 editor: T,
16 document: Y.Doc,
17 awareness: Awareness,
18) => {
19 if (!CodeBlockEditor.isCodeBlockEditor(editor)) {
20 throw new Error('withYCodeBlock only support CodeBlockEditor')
21 }
22
23 const { normalizeNode, apply, getCodeMirrorExtensions } = editor
24
25 const providerProtocol = withProviderProtocol(editor)
26
27 editor.getCodeMirrorExtensions = (id: string) => {
28 const yExtensionConfig = new YExtensionConfig(id, editor)
29 return [...getCodeMirrorExtensions(id), yExtensionnFacet.of(yExtensionConfig), yExtension]
30 }
31
32 editor.apply = op => {
33 if (!providerProtocol.connected()) return apply(op)
34 switch (op.type) {
35 case 'remove_node':
36 // 删除代码块时,销毁 Y.Doc
37 if (CodeBlockEditor.isCodeBlock(editor, op.node)) {
38 const docMap = document.getMap<Y.Doc>(CODEBLOCK_YJS_KEY)
39 const doc = docMap.get(op.node.id)
40 if (doc) doc.destroy()
41 docMap.delete(op.node.id)
42 }
43 break
44 }
45 apply(op)
46 }
47
48 editor.normalizeNode = entry => {
49 const [node] = entry
50 // 插入代码块时,初始化 Y.Doc
51 if (CodeBlockEditor.isCodeBlock(editor, node) && providerProtocol.connected()) {
52 const docMap = document.getMap<Y.Doc>(CODEBLOCK_YJS_KEY)
53 let doc = docMap.get(node.id)
54 if (!doc) {
55 doc = new Y.Doc({ autoLoad: true })
56 const defaultValue = node.code
57 doc.getText(CODEBLOCK_YJS_FIELD).insert(0, defaultValue)
58 docMap.set(node.id, doc)
59 }
60 }
61 normalizeNode(entry)
62 }
63
64 YJS_DOC_WEAK_MAP.set(editor, document)
65 YJS_AWARENESS_WEAK_MAP.set(editor, awareness)
66
67 return editor
68}

Callers 1

PlaygroundFunction · 0.90

Calls 3

withProviderProtocolFunction · 0.90
getMethod · 0.80
destroyMethod · 0.45

Tested by

no test coverage detected

Used in the wild real call sites across dependent graphs

searching dependent graphs…