-
Notifications
You must be signed in to change notification settings - Fork 148
/
Copy pathremarkPlugin.ts
375 lines (356 loc) · 11.9 KB
/
remarkPlugin.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
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
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
/**
* 🚀 This plugin is used to support container directive in unified.
* Taking into account the compatibility of the VuePress/Docusaurus container directive, current remark plugin in unified ecosystem only supports the following syntax:
* ::: tip {title="foo"}
* This is a tip
* :::
* But the following syntax is not supported:
* ::: tip foo
* This is a tip
* :::
* In fact, the syntax is usually used in SSG Frameworks, such as VuePress/Docusaurus.
* So the plugin is used to solve the problem and support both syntaxes in above cases.
*/
/// <reference types="remark-directive" />
import type {
BlockContent,
Content,
Literal,
Paragraph,
Parent,
PhrasingContent,
Root,
} from 'mdast';
import type { Plugin } from 'unified';
export const DIRECTIVE_TYPES = [
'tip',
'note',
'warning',
'caution',
'danger',
'info',
'details',
] as const;
export const REGEX_BEGIN = /^\s*:::\s*(\w+)\s*(.*)?/;
export const REGEX_END = /\s*:::$/;
export const REGEX_GH_BEGIN = /^\s*\s*\[!(\w+)\]\s*(.*)?/;
export const TITLE_REGEX_IN_MD = /{\s*title=["']?(.+)}\s*/;
export const TITLE_REGEX_IN_MDX = /\s*title=["']?(.+)\s*/;
export type DirectiveType = (typeof DIRECTIVE_TYPES)[number];
const trimTailingQuote = (str: string) => str.replace(/['"]$/g, '');
const parseTitle = (rawTitle = '', isMDX = false) => {
const matched = rawTitle?.match(
isMDX ? TITLE_REGEX_IN_MDX : TITLE_REGEX_IN_MD,
);
return trimTailingQuote(matched?.[1] || rawTitle);
};
/**
* Construct the DOM structure of the container directive.
* For example:
*
* ::: tip {title="foo"}
* This is a tip
* :::
*
* will be transformed to:
*
* <div class="rspress-directive tip">
* <div class="rspress-directive-title">TIP</div>
* <div class="rspress-directive-content">
* <p>This is a tip</p>
* </div>
* </div>
*
*/
const createContainer = (
type: DirectiveType | string,
title: string | undefined,
children: BlockContent[],
): Parent => {
const isDetails = type === 'details';
const rootHName = isDetails ? 'details' : 'div';
const titleHName = isDetails ? 'summary' : 'div';
return {
type: 'containerDirective',
data: {
hName: rootHName,
hProperties: {
class: `rspress-directive ${type}`,
},
},
children: [
{
type: 'paragraph',
data: {
hName: titleHName,
hProperties: {
class: 'rspress-directive-title',
},
},
children: [{ type: 'text', value: title || type.toUpperCase() }],
},
{
type: 'paragraph',
data: {
hName: 'div',
hProperties: { class: 'rspress-directive-content' },
},
children: children as PhrasingContent[],
},
],
};
};
/**
* How the transformer works:
* 1. We get the paragraph and check if it is a container directive
* 2. If it is, crawl the next nodes, if there is a paragraph node, we need to check if it is the end of the container directive. If not, we need to push it to the children of the container directive node.
* 3. If we find the end of the container directive, we remove the visited node and insert the custom container directive node.
*/
function transformer(tree: Parent) {
let i = 0;
try {
while (i < tree.children.length) {
const node = tree.children[i];
if ('children' in node) {
transformer(node);
}
if (node.type === 'containerDirective') {
const type = node.name as DirectiveType;
if (DIRECTIVE_TYPES.includes(type)) {
tree.children.splice(
i,
1,
createContainer(
type,
node.attributes?.title ?? type.toUpperCase(),
node.children as BlockContent[],
) as Content,
);
}
} else if (
/**
* Support for Github Alerts
* > [!TIP]
* > This is a tip
*
* will be transformed to:
*
* <div class="rspress-directive tip">
* <div class="rspress-directive-title">TIP</div>
* <div class="rspress-directive-content">
* <p>This is a tip</p>
* </div>
* </div>
*/
node.type === 'blockquote' &&
node.children[0].type === 'paragraph'
) {
const initiatorTag: string =
// @ts-expect-error `value` is treated like `data`, but type expects `data`
node.children[0].children[0].value;
if (REGEX_GH_BEGIN.test(initiatorTag)) {
const match = initiatorTag.match(REGEX_GH_BEGIN);
const [, type] = match!;
if (!DIRECTIVE_TYPES.includes(type.toLowerCase() as DirectiveType)) {
i++;
continue;
}
if (
node.children.length === 1 &&
node.children[0].type === 'paragraph'
) {
// @ts-expect-error `value` is treated like `data`, but type expects `data`
node.children[0].children[0].value =
initiatorTag!.match(REGEX_GH_BEGIN)![2]! ?? '';
}
const newChild = createContainer(
type.toLowerCase(),
type.toUpperCase(),
(node.children.slice(1).length === 0
? node.children.slice(0)
: node.children.slice(1)) as BlockContent[],
);
tree.children.splice(i, 1, newChild as Content);
}
}
if (
node.type !== 'paragraph' ||
// 1. We get the paragraph and check if it is a container directive
node.children[0].type !== 'text'
) {
i++;
continue;
}
const firstTextNode = node.children[0];
const text = firstTextNode.value;
const metaText = text.split('\n')[0];
const content = text.slice(metaText.length);
const match = metaText.match(REGEX_BEGIN);
if (!match) {
i++;
continue;
}
const [, type, rawTitle] = match;
// In .md, we can get :::tip{title="foo"} in the first text node
// In .mdx, we get :::tip in first node and {title="foo"} in second node
let title = parseTitle(rawTitle);
// :::tip{title="foo"}
const titleExpressionNode =
// @ts-expect-error mdxTextExpression is not defined in mdast
node.children[1] && node.children[1].type === 'mdxTextExpression'
? node.children[1]
: null;
// Handle the case of `::: tip {title="foo"}`
if (titleExpressionNode) {
title = parseTitle((titleExpressionNode as Literal).value, true);
// {title="foo"} is not a part of the content, So we need to remove it
node.children.splice(1, 1);
}
if (!DIRECTIVE_TYPES.includes(type as DirectiveType)) {
i++;
continue;
}
// 2. If it is, we remove the paragraph and create a container directive
const wrappedChildren: BlockContent[] = [];
// 2.1 case: with no newline between `:::` and `:::`, for example
// ::: tip
// This is a tip
// :::
// Here the content is `::: tip\nThis is a tip\n:::`
if (content?.endsWith(':::')) {
wrappedChildren.push({
type: 'paragraph',
children: [
{
type: 'text',
value: content.replace(REGEX_END, ''),
},
],
});
const newChild = createContainer(type, title, wrappedChildren);
tree.children.splice(i, 1, newChild as Content);
} else {
// 2.2 case: with newline before the end of container, for example:
// ::: tip
// This is a tip
//
// :::
// Here the content is `::: tip\nThis is a tip`
const paragraphChild: Paragraph = {
type: 'paragraph',
children: [] as PhrasingContent[],
};
wrappedChildren.push(paragraphChild);
if (content.length) {
paragraphChild.children.push({
type: 'text',
value: content,
});
}
paragraphChild.children.push(...node.children.slice(1, -1));
// If the inserted paragraph is empty, we remove it
if (paragraphChild.children.length === 0) {
wrappedChildren.pop();
}
const lastChildInNode = node.children[node.children.length - 1];
// We find the end of the container directive in current paragraph
if (
lastChildInNode.type === 'text' &&
REGEX_END.test(lastChildInNode.value)
) {
const lastChildInNodeText = lastChildInNode.value;
const matchedEndContent = lastChildInNodeText.slice(0, -3).trim();
// eslint-disable-next-line max-depth
if (wrappedChildren.length) {
(wrappedChildren[0] as Paragraph).children.push({
type: 'text',
value: matchedEndContent,
});
} else if (matchedEndContent) {
wrappedChildren.push({
type: 'paragraph',
children: [
{
type: 'text',
value: matchedEndContent,
},
],
});
}
const newChild = createContainer(type, title, wrappedChildren);
tree.children.splice(i, 1, newChild as Content);
i++;
continue;
}
if (lastChildInNode !== firstTextNode && wrappedChildren.length) {
// We don't find the end of the container directive in current paragraph
(wrappedChildren[0] as Paragraph).children.push(lastChildInNode);
}
// 2.3 The final case: has newline after the start of container, for example:
// ::: tip
//
// This is a tip
// :::
// All of the above cases need to crawl the children of the container directive node.
// In other word, We look for the next paragraph nodes and collect all the content until we find the end of the container directive
let j = i + 1;
while (j < tree.children.length) {
const currentParagraph = tree.children[j];
if (currentParagraph.type !== 'paragraph') {
wrappedChildren.push(currentParagraph as BlockContent);
j++;
continue;
}
const lastChild =
currentParagraph.children[currentParagraph.children.length - 1];
// The whole paragraph doesn't arrive at the end of the container directive, we collect the whole paragraph
if (
lastChild !== firstTextNode &&
(lastChild.type !== 'text' || !REGEX_END.test(lastChild.value))
) {
wrappedChildren.push({
...currentParagraph,
children: currentParagraph.children.filter(
child => child !== firstTextNode,
),
});
j++;
} else {
// 3. We find the end of the container directive
// Then create the container directive, and remove the original paragraphs
// Finally, we insert the new container directive and break the loop
const lastChildText = lastChild.value;
const matchedEndContent = lastChildText.slice(0, -3).trim();
wrappedChildren.push(
...(currentParagraph.children.filter(
child => child !== firstTextNode && child !== lastChild,
) as BlockContent[]),
);
if (matchedEndContent) {
wrappedChildren.push({
type: 'paragraph',
children: [
{
type: 'text',
value: matchedEndContent,
},
],
});
}
const newChild = createContainer(type, title, wrappedChildren);
tree.children.splice(i, j - i + 1, newChild as Content);
break;
}
}
}
i++;
}
} catch (e) {
console.log(e);
throw e;
}
}
export const remarkPluginContainer: Plugin<[], Root> = () => {
return transformer;
};
export default remarkPluginContainer;