-
Notifications
You must be signed in to change notification settings - Fork 42
Expand file tree
/
Copy pathindex.ts
More file actions
170 lines (154 loc) · 5.86 KB
/
index.ts
File metadata and controls
170 lines (154 loc) · 5.86 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
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
import type {ExtensionAuto, ExtensionNodeSpec} from '#core';
import {nodeTypeFactory} from 'src/utils/schema';
export const CodeBlockNodeAttr = {
Lang: 'data-language',
Markup: 'data-markup',
Line: 'data-line',
ShowLineNumbers: 'data-show-line-numbers',
} as const;
export const codeBlockNodeName = 'code_block';
export const codeBlockType = nodeTypeFactory(codeBlockNodeName);
export type LineNumbersOptions = {
/**
* Allow line numbers in codeblock.
* Available with @diplodoc/transform v4.55.0 or higher.
* @default true
*/
// TODO [MAJOR]: enable by default and remove option
enabled?: boolean;
/**
* By default, new code blocks are added with line numbers.
* @default false
*/
showByDefault?: boolean;
};
export type CodeBlockSpecsOptions = {
nodeview?: ExtensionNodeSpec['view'];
/** Configure line numbers in code block */
lineNumbers?: LineNumbersOptions;
};
const getLangOfNode = (node: Element) => {
let result = node.getAttribute(CodeBlockNodeAttr.Lang) || '';
if (!result) {
const firstElementChild = node.firstElementChild;
if (
firstElementChild &&
firstElementChild.nodeName.toLowerCase() === 'code' &&
firstElementChild.classList.contains('hljs')
) {
result = firstElementChild.getAttribute('class')?.split(' ')?.[1] || '';
}
}
return result;
};
export const CodeBlockSpecs: ExtensionAuto<CodeBlockSpecsOptions> = (builder, opts) => {
builder.addNode(codeBlockNodeName, () => ({
view: opts.nodeview,
spec: {
attrs: {
[CodeBlockNodeAttr.Lang]: {default: ''},
[CodeBlockNodeAttr.Markup]: {default: '```'},
[CodeBlockNodeAttr.Line]: {default: null},
...(opts.lineNumbers?.enabled
? {
[CodeBlockNodeAttr.ShowLineNumbers]: {
default: opts.lineNumbers.showByDefault ? 'true' : '',
},
}
: {}),
},
content: 'text*',
group: 'block',
code: true,
marks: '',
selectable: true,
allowSelection: false,
parseDOM: [
{
tag: 'pre',
preserveWhitespace: 'full',
getAttrs: (node) => {
return {
[CodeBlockNodeAttr.Lang]: getLangOfNode(node as Element),
};
},
},
],
toDOM({attrs}) {
return ['pre', attrs, ['code', 0]];
},
},
fromMd: {
tokenSpec: {
name: codeBlockNodeName,
type: 'block',
noCloseToken: true,
getAttrs: (tok) => {
return {
[CodeBlockNodeAttr.Line]: tok.attrGet('data-line'),
[CodeBlockNodeAttr.ShowLineNumbers]: tok.info.includes('showLineNumbers')
? 'true'
: '',
};
},
prepareContent: removeNewLineAtEnd, // content of code blocks contains extra \n at the end
},
},
toMd: (state, node) => {
const lang: string = node.attrs[CodeBlockNodeAttr.Lang];
const markup: string = node.attrs[CodeBlockNodeAttr.Markup];
const showLineNumbers: string = opts.lineNumbers?.enabled
? node.attrs[CodeBlockNodeAttr.ShowLineNumbers]
: '';
let info = lang;
if (showLineNumbers === 'true') {
info += ' showLineNumbers';
}
state.write(markup + info + '\n');
state.text(node.textContent, false);
// Add a newline to the current content before adding closing marker
state.write('\n');
state.write(markup);
state.closeBlock(node);
},
}));
builder.addMarkdownTokenParserSpec('fence', () => ({
name: codeBlockNodeName,
type: 'block',
noCloseToken: true,
getAttrs: (tok) => {
const attrs: Record<string, string | null> = {
[CodeBlockNodeAttr.Markup]: tok.markup,
[CodeBlockNodeAttr.Line]: tok.attrGet('data-line'),
};
if (tok.info) {
// like in markdown-it
// https://github.com/markdown-it/markdown-it/blob/d07d585b6b15aaee2bc8f7a54b994526dad4dbc5/lib/renderer.mjs#L36-L37
const parts = tok.info.split(/\s+/);
const isFirstPartForLineNumbers =
opts.lineNumbers?.enabled && parts[0] === 'showLineNumbers';
attrs[CodeBlockNodeAttr.Lang] = isFirstPartForLineNumbers ? '' : parts[0];
}
if (opts.lineNumbers?.enabled && tok.info?.includes('showLineNumbers')) {
attrs[CodeBlockNodeAttr.ShowLineNumbers] = 'true';
} else {
attrs[CodeBlockNodeAttr.ShowLineNumbers] = '';
}
return attrs;
},
prepareContent: removeNewLineAtEnd, // content of fence blocks contains extra \n at the end
}));
builder.addKeymap(() => ({
Tab: (state, dispatch) => {
const {$anchor, $head} = state.selection;
if ($anchor.sameParent($head) && $anchor.parent.type.name === codeBlockNodeName) {
dispatch?.(state.tr.replaceSelectionWith(state.schema.text('\t')).scrollIntoView());
return true;
}
return false;
},
}));
};
function removeNewLineAtEnd(content: string): string {
return content.endsWith('\n') ? content.slice(0, content.length - 1) : content;
}