-
Notifications
You must be signed in to change notification settings - Fork 42
/
codeChunk.ts
83 lines (82 loc) · 2.28 KB
/
codeChunk.ts
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
71
72
73
74
75
76
77
78
79
80
81
82
83
import { NodeSpec } from 'prosemirror-model'
/**
* Generate a `NodeSpec` to represent a Stencila `CodeChunk`
*
* Based on https://prosemirror.net/examples/codemirror/ and https://github.com/ProseMirror/prosemirror-schema-basic/blob/b5ae707ab1be98a1d8735dfdc7d1845bcd126f18/src/schema-basic.js#L59
*/
export function codeChunk(): NodeSpec {
return {
allowGapCursor: true,
atom: true,
code: true,
content: 'text*',
defining: true,
draggable: true,
inline: false,
isolating: false,
marks: '',
selectable: true,
group: 'BlockContent',
attrs: {
id: { default: '' },
itemtype: { default: '' },
programmingLanguage: { default: '' },
},
toDOM(node) {
return [
'stencila-code-chunk',
{
'active-language':
typeof node.attrs.programmingLanguage === 'string'
? node.attrs.programmingLanguage
: undefined,
},
[
'pre',
{
slot: 'text',
},
0,
],
]
},
parseDOM: [
{
tag: '[itemtype="https://schema.stenci.la/CodeChunk"]',
preserveWhitespace: 'full',
contentElement: 'code',
getAttrs(dom) {
const elem = dom as HTMLElement
return {
id: elem.getAttribute('id'),
itemtype: elem.getAttribute('itemtype'),
programmingLanguage:
elem
.querySelector('meta[itemprop="programmingLanguage"][content]')
?.getAttribute('content') ??
elem
.querySelector('code[class^="language-"]')
?.getAttribute('class')
?.substring(9),
}
},
},
{
tag: 'stencila-code-chunk',
preserveWhitespace: 'full',
contentElement: '.cm-content',
getAttrs(dom) {
const elem = dom as HTMLStencilaCodeChunkElement
return {
id: elem.getAttribute('id'),
itemtype: elem.getAttribute('itemtype'),
programmingLanguage:
elem.querySelector<HTMLSelectElement>(
'[aria-label="Programming Language"] select'
)?.value ?? elem.getAttribute('active-language'),
}
},
},
],
}
}