-
-
Notifications
You must be signed in to change notification settings - Fork 5
/
index.js
783 lines (697 loc) · 22.5 KB
/
index.js
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
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
/**
* @import {CompileContext, Extension as FromMarkdownExtension, Handle as FromMarkdownHandle, OnEnterError, OnExitError, Token} from 'mdast-util-from-markdown'
* @import {Handle as ToMarkdownHandle, Options as ToMarkdownExtension, State, Tracker} from 'mdast-util-to-markdown'
* @import {Point} from 'unist'
* @import {MdxJsxAttribute, MdxJsxAttributeValueExpression, MdxJsxExpressionAttribute, MdxJsxFlowElement, MdxJsxTextElement} from '../index.js'
*/
/**
* @typedef Tag
* Single tag.
* @property {string | undefined} name
* Name of tag, or `undefined` for fragment.
*
* > 👉 **Note**: `null` is used in the AST for fragments, as it serializes in
* > JSON.
* @property {Array<MdxJsxAttribute | MdxJsxExpressionAttribute>} attributes
* Attributes.
* @property {boolean} close
* Whether the tag is closing (`</x>`).
* @property {boolean} selfClosing
* Whether the tag is self-closing (`<x/>`).
* @property {Token['start']} start
* Start point.
* @property {Token['start']} end
* End point.
*
* @typedef ToMarkdownOptions
* Configuration.
* @property {'"' | "'" | null | undefined} [quote='"']
* Preferred quote to use around attribute values (default: `'"'`).
* @property {boolean | null | undefined} [quoteSmart=false]
* Use the other quote if that results in less bytes (default: `false`).
* @property {boolean | null | undefined} [tightSelfClosing=false]
* Do not use an extra space when closing self-closing elements: `<img/>`
* instead of `<img />` (default: `false`).
* @property {number | null | undefined} [printWidth=Infinity]
* Try and wrap syntax at this width (default: `Infinity`).
*
* When set to a finite number (say, `80`), the formatter will print
* attributes on separate lines when a tag doesn’t fit on one line.
* The normal behavior is to print attributes with spaces between them
* instead of line endings.
*/
import {ccount} from 'ccount'
import {ok as assert} from 'devlop'
import {parseEntities} from 'parse-entities'
import {stringifyEntitiesLight} from 'stringify-entities'
import {stringifyPosition} from 'unist-util-stringify-position'
import {VFileMessage} from 'vfile-message'
const indent = ' '
/**
* Create an extension for `mdast-util-from-markdown` to enable MDX JSX.
*
* @returns {FromMarkdownExtension}
* Extension for `mdast-util-from-markdown` to enable MDX JSX.
*
* When using the syntax extension with `addResult`, nodes will have a
* `data.estree` field set to an ESTree `Program` node.
*/
export function mdxJsxFromMarkdown() {
return {
canContainEols: ['mdxJsxTextElement'],
enter: {
mdxJsxFlowTag: enterMdxJsxTag,
mdxJsxFlowTagClosingMarker: enterMdxJsxTagClosingMarker,
mdxJsxFlowTagAttribute: enterMdxJsxTagAttribute,
mdxJsxFlowTagExpressionAttribute: enterMdxJsxTagExpressionAttribute,
mdxJsxFlowTagAttributeValueLiteral: buffer,
mdxJsxFlowTagAttributeValueExpression: buffer,
mdxJsxFlowTagSelfClosingMarker: enterMdxJsxTagSelfClosingMarker,
mdxJsxTextTag: enterMdxJsxTag,
mdxJsxTextTagClosingMarker: enterMdxJsxTagClosingMarker,
mdxJsxTextTagAttribute: enterMdxJsxTagAttribute,
mdxJsxTextTagExpressionAttribute: enterMdxJsxTagExpressionAttribute,
mdxJsxTextTagAttributeValueLiteral: buffer,
mdxJsxTextTagAttributeValueExpression: buffer,
mdxJsxTextTagSelfClosingMarker: enterMdxJsxTagSelfClosingMarker
},
exit: {
mdxJsxFlowTagClosingMarker: exitMdxJsxTagClosingMarker,
mdxJsxFlowTagNamePrimary: exitMdxJsxTagNamePrimary,
mdxJsxFlowTagNameMember: exitMdxJsxTagNameMember,
mdxJsxFlowTagNameLocal: exitMdxJsxTagNameLocal,
mdxJsxFlowTagExpressionAttribute: exitMdxJsxTagExpressionAttribute,
mdxJsxFlowTagExpressionAttributeValue: data,
mdxJsxFlowTagAttributeNamePrimary: exitMdxJsxTagAttributeNamePrimary,
mdxJsxFlowTagAttributeNameLocal: exitMdxJsxTagAttributeNameLocal,
mdxJsxFlowTagAttributeValueLiteral: exitMdxJsxTagAttributeValueLiteral,
mdxJsxFlowTagAttributeValueLiteralValue: data,
mdxJsxFlowTagAttributeValueExpression:
exitMdxJsxTagAttributeValueExpression,
mdxJsxFlowTagAttributeValueExpressionValue: data,
mdxJsxFlowTagSelfClosingMarker: exitMdxJsxTagSelfClosingMarker,
mdxJsxFlowTag: exitMdxJsxTag,
mdxJsxTextTagClosingMarker: exitMdxJsxTagClosingMarker,
mdxJsxTextTagNamePrimary: exitMdxJsxTagNamePrimary,
mdxJsxTextTagNameMember: exitMdxJsxTagNameMember,
mdxJsxTextTagNameLocal: exitMdxJsxTagNameLocal,
mdxJsxTextTagExpressionAttribute: exitMdxJsxTagExpressionAttribute,
mdxJsxTextTagExpressionAttributeValue: data,
mdxJsxTextTagAttributeNamePrimary: exitMdxJsxTagAttributeNamePrimary,
mdxJsxTextTagAttributeNameLocal: exitMdxJsxTagAttributeNameLocal,
mdxJsxTextTagAttributeValueLiteral: exitMdxJsxTagAttributeValueLiteral,
mdxJsxTextTagAttributeValueLiteralValue: data,
mdxJsxTextTagAttributeValueExpression:
exitMdxJsxTagAttributeValueExpression,
mdxJsxTextTagAttributeValueExpressionValue: data,
mdxJsxTextTagSelfClosingMarker: exitMdxJsxTagSelfClosingMarker,
mdxJsxTextTag: exitMdxJsxTag
}
}
/**
* @this {CompileContext}
* @type {FromMarkdownHandle}
*/
function buffer() {
this.buffer()
}
/**
* Copy a point-like value.
*
* @param {Point} d
* Point-like value.
* @returns {Point}
* unist point.
*/
function point(d) {
return {line: d.line, column: d.column, offset: d.offset}
}
/**
* @this {CompileContext}
* @type {FromMarkdownHandle}
*/
function data(token) {
this.config.enter.data.call(this, token)
this.config.exit.data.call(this, token)
}
/**
* @this {CompileContext}
* @type {FromMarkdownHandle}
*/
function enterMdxJsxTag(token) {
/** @type {Tag} */
const tag = {
name: undefined,
attributes: [],
close: false,
selfClosing: false,
start: token.start,
end: token.end
}
if (!this.data.mdxJsxTagStack) this.data.mdxJsxTagStack = []
this.data.mdxJsxTag = tag
this.buffer()
}
/**
* @this {CompileContext}
* @type {FromMarkdownHandle}
*/
function enterMdxJsxTagClosingMarker(token) {
const stack = this.data.mdxJsxTagStack
assert(stack, 'expected `mdxJsxTagStack`')
if (stack.length === 0) {
throw new VFileMessage(
'Unexpected closing slash `/` in tag, expected an open tag first',
{start: token.start, end: token.end},
'mdast-util-mdx-jsx:unexpected-closing-slash'
)
}
}
/**
* @this {CompileContext}
* @type {FromMarkdownHandle}
*/
function enterMdxJsxTagAnyAttribute(token) {
const tag = this.data.mdxJsxTag
assert(tag, 'expected `mdxJsxTag`')
if (tag.close) {
throw new VFileMessage(
'Unexpected attribute in closing tag, expected the end of the tag',
{start: token.start, end: token.end},
'mdast-util-mdx-jsx:unexpected-attribute'
)
}
}
/**
* @this {CompileContext}
* @type {FromMarkdownHandle}
*/
function enterMdxJsxTagSelfClosingMarker(token) {
const tag = this.data.mdxJsxTag
assert(tag, 'expected `mdxJsxTag`')
if (tag.close) {
throw new VFileMessage(
'Unexpected self-closing slash `/` in closing tag, expected the end of the tag',
{start: token.start, end: token.end},
'mdast-util-mdx-jsx:unexpected-self-closing-slash'
)
}
}
/**
* @this {CompileContext}
* @type {FromMarkdownHandle}
*/
function exitMdxJsxTagClosingMarker() {
const tag = this.data.mdxJsxTag
assert(tag, 'expected `mdxJsxTag`')
tag.close = true
}
/**
* @this {CompileContext}
* @type {FromMarkdownHandle}
*/
function exitMdxJsxTagNamePrimary(token) {
const tag = this.data.mdxJsxTag
assert(tag, 'expected `mdxJsxTag`')
tag.name = this.sliceSerialize(token)
}
/**
* @this {CompileContext}
* @type {FromMarkdownHandle}
*/
function exitMdxJsxTagNameMember(token) {
const tag = this.data.mdxJsxTag
assert(tag, 'expected `mdxJsxTag`')
tag.name += '.' + this.sliceSerialize(token)
}
/**
* @this {CompileContext}
* @type {FromMarkdownHandle}
*/
function exitMdxJsxTagNameLocal(token) {
const tag = this.data.mdxJsxTag
assert(tag, 'expected `mdxJsxTag`')
tag.name += ':' + this.sliceSerialize(token)
}
/**
* @this {CompileContext}
* @type {FromMarkdownHandle}
*/
function enterMdxJsxTagAttribute(token) {
const tag = this.data.mdxJsxTag
assert(tag, 'expected `mdxJsxTag`')
enterMdxJsxTagAnyAttribute.call(this, token)
tag.attributes.push({
type: 'mdxJsxAttribute',
name: '',
value: null,
position: {
start: point(token.start),
// @ts-expect-error: `end` will be patched later.
end: undefined
}
})
}
/**
* @this {CompileContext}
* @type {FromMarkdownHandle}
*/
function enterMdxJsxTagExpressionAttribute(token) {
const tag = this.data.mdxJsxTag
assert(tag, 'expected `mdxJsxTag`')
enterMdxJsxTagAnyAttribute.call(this, token)
tag.attributes.push({type: 'mdxJsxExpressionAttribute', value: ''})
this.buffer()
}
/**
* @this {CompileContext}
* @type {FromMarkdownHandle}
*/
function exitMdxJsxTagExpressionAttribute(token) {
const tag = this.data.mdxJsxTag
assert(tag, 'expected `mdxJsxTag`')
const tail = tag.attributes[tag.attributes.length - 1]
assert(tail.type === 'mdxJsxExpressionAttribute')
const estree = token.estree
tail.value = this.resume()
if (estree) {
tail.data = {estree}
}
}
/**
* @this {CompileContext}
* @type {FromMarkdownHandle}
*/
function exitMdxJsxTagAttributeNamePrimary(token) {
const tag = this.data.mdxJsxTag
assert(tag, 'expected `mdxJsxTag`')
const node = tag.attributes[tag.attributes.length - 1]
assert(node.type === 'mdxJsxAttribute')
node.name = this.sliceSerialize(token)
assert(node.position !== undefined)
node.position.end = point(token.end)
}
/**
* @this {CompileContext}
* @type {FromMarkdownHandle}
*/
function exitMdxJsxTagAttributeNameLocal(token) {
const tag = this.data.mdxJsxTag
assert(tag, 'expected `mdxJsxTag`')
const node = tag.attributes[tag.attributes.length - 1]
assert(node.type === 'mdxJsxAttribute')
node.name += ':' + this.sliceSerialize(token)
assert(node.position !== undefined)
node.position.end = point(token.end)
}
/**
* @this {CompileContext}
* @type {FromMarkdownHandle}
*/
function exitMdxJsxTagAttributeValueLiteral(token) {
const tag = this.data.mdxJsxTag
assert(tag, 'expected `mdxJsxTag`')
const node = tag.attributes[tag.attributes.length - 1]
node.value = parseEntities(this.resume(), {nonTerminated: false})
assert(node.position !== undefined)
node.position.end = point(token.end)
}
/**
* @this {CompileContext}
* @type {FromMarkdownHandle}
*/
function exitMdxJsxTagAttributeValueExpression(token) {
const tag = this.data.mdxJsxTag
assert(tag, 'expected `mdxJsxTag`')
const tail = tag.attributes[tag.attributes.length - 1]
assert(tail.type === 'mdxJsxAttribute')
/** @type {MdxJsxAttributeValueExpression} */
const node = {type: 'mdxJsxAttributeValueExpression', value: this.resume()}
const estree = token.estree
if (estree) {
node.data = {estree}
}
tail.value = node
assert(tail.position !== undefined)
tail.position.end = point(token.end)
}
/**
* @this {CompileContext}
* @type {FromMarkdownHandle}
*/
function exitMdxJsxTagSelfClosingMarker() {
const tag = this.data.mdxJsxTag
assert(tag, 'expected `mdxJsxTag`')
tag.selfClosing = true
}
/**
* @this {CompileContext}
* @type {FromMarkdownHandle}
*/
function exitMdxJsxTag(token) {
const tag = this.data.mdxJsxTag
assert(tag, 'expected `mdxJsxTag`')
const stack = this.data.mdxJsxTagStack
assert(stack, 'expected `mdxJsxTagStack`')
const tail = stack[stack.length - 1]
if (tag.close && tail.name !== tag.name) {
throw new VFileMessage(
'Unexpected closing tag `' +
serializeAbbreviatedTag(tag) +
'`, expected corresponding closing tag for `' +
serializeAbbreviatedTag(tail) +
'` (' +
stringifyPosition(tail) +
')',
{start: token.start, end: token.end},
'mdast-util-mdx-jsx:end-tag-mismatch'
)
}
// End of a tag, so drop the buffer.
this.resume()
if (tag.close) {
stack.pop()
} else {
this.enter(
{
type:
token.type === 'mdxJsxTextTag'
? 'mdxJsxTextElement'
: 'mdxJsxFlowElement',
name: tag.name || null,
attributes: tag.attributes,
children: []
},
token,
onErrorRightIsTag
)
}
if (tag.selfClosing || tag.close) {
this.exit(token, onErrorLeftIsTag)
} else {
stack.push(tag)
}
}
/**
* @this {CompileContext}
* @type {OnEnterError}
*/
function onErrorRightIsTag(closing, open) {
const stack = this.data.mdxJsxTagStack
assert(stack, 'expected `mdxJsxTagStack`')
const tag = stack[stack.length - 1]
assert(tag, 'expected `mdxJsxTag`')
const place = closing ? ' before the end of `' + closing.type + '`' : ''
const position = closing
? {start: closing.start, end: closing.end}
: undefined
throw new VFileMessage(
'Expected a closing tag for `' +
serializeAbbreviatedTag(tag) +
'` (' +
stringifyPosition({start: open.start, end: open.end}) +
')' +
place,
position,
'mdast-util-mdx-jsx:end-tag-mismatch'
)
}
/**
* @this {CompileContext}
* @type {OnExitError}
*/
function onErrorLeftIsTag(a, b) {
const tag = this.data.mdxJsxTag
assert(tag, 'expected `mdxJsxTag`')
throw new VFileMessage(
'Expected the closing tag `' +
serializeAbbreviatedTag(tag) +
'` either after the end of `' +
b.type +
'` (' +
stringifyPosition(b.end) +
') or another opening tag after the start of `' +
b.type +
'` (' +
stringifyPosition(b.start) +
')',
{start: a.start, end: a.end},
'mdast-util-mdx-jsx:end-tag-mismatch'
)
}
/**
* Serialize a tag, excluding attributes.
* `self-closing` is not supported, because we don’t need it yet.
*
* @param {Tag} tag
* @returns {string}
*/
function serializeAbbreviatedTag(tag) {
return '<' + (tag.close ? '/' : '') + (tag.name || '') + '>'
}
}
/**
* Create an extension for `mdast-util-to-markdown` to enable MDX JSX.
*
* This extension configures `mdast-util-to-markdown` with
* `options.fences: true` and `options.resourceLink: true` too, do not
* overwrite them!
*
* @param {ToMarkdownOptions | null | undefined} [options]
* Configuration (optional).
* @returns {ToMarkdownExtension}
* Extension for `mdast-util-to-markdown` to enable MDX JSX.
*/
export function mdxJsxToMarkdown(options) {
const options_ = options || {}
const quote = options_.quote || '"'
const quoteSmart = options_.quoteSmart || false
const tightSelfClosing = options_.tightSelfClosing || false
const printWidth = options_.printWidth || Number.POSITIVE_INFINITY
const alternative = quote === '"' ? "'" : '"'
if (quote !== '"' && quote !== "'") {
throw new Error(
'Cannot serialize attribute values with `' +
quote +
'` for `options.quote`, expected `"`, or `\'`'
)
}
mdxElement.peek = peekElement
return {
handlers: {
mdxJsxFlowElement: mdxElement,
mdxJsxTextElement: mdxElement
},
unsafe: [
{character: '<', inConstruct: ['phrasing']},
{atBreak: true, character: '<'}
],
// Always generate fenced code (never indented code).
fences: true,
// Always generate links with resources (never autolinks).
resourceLink: true
}
/**
* @type {ToMarkdownHandle}
* @param {MdxJsxFlowElement | MdxJsxTextElement} node
*/
// eslint-disable-next-line complexity
function mdxElement(node, _, state, info) {
const flow = node.type === 'mdxJsxFlowElement'
const selfClosing = node.name
? !node.children || node.children.length === 0
: false
const depth = inferDepth(state)
const currentIndent = createIndent(depth)
const trackerOneLine = state.createTracker(info)
const trackerMultiLine = state.createTracker(info)
/** @type {Array<string>} */
const serializedAttributes = []
const prefix = (flow ? currentIndent : '') + '<' + (node.name || '')
const exit = state.enter(node.type)
trackerOneLine.move(prefix)
trackerMultiLine.move(prefix)
// None.
if (node.attributes && node.attributes.length > 0) {
if (!node.name) {
throw new Error('Cannot serialize fragment w/ attributes')
}
let index = -1
while (++index < node.attributes.length) {
const attribute = node.attributes[index]
/** @type {string} */
let result
if (attribute.type === 'mdxJsxExpressionAttribute') {
result = '{' + (attribute.value || '') + '}'
} else {
if (!attribute.name) {
throw new Error('Cannot serialize attribute w/o name')
}
const value = attribute.value
const left = attribute.name
/** @type {string} */
let right = ''
if (value === null || value === undefined) {
// Empty.
} else if (typeof value === 'object') {
right = '{' + (value.value || '') + '}'
} else {
// If the alternative is less common than `quote`, switch.
const appliedQuote =
quoteSmart && ccount(value, quote) > ccount(value, alternative)
? alternative
: quote
right =
appliedQuote +
stringifyEntitiesLight(value, {subset: [appliedQuote]}) +
appliedQuote
}
result = left + (right ? '=' : '') + right
}
serializedAttributes.push(result)
}
}
let attributesOnTheirOwnLine = false
const attributesOnOneLine = serializedAttributes.join(' ')
if (
// Block:
flow &&
// Including a line ending (expressions).
(/\r?\n|\r/.test(attributesOnOneLine) ||
// Current position (including `<tag`).
trackerOneLine.current().now.column +
// -1 because columns, +1 for ` ` before attributes.
// Attributes joined by spaces.
attributesOnOneLine.length +
// ` />`.
(selfClosing ? (tightSelfClosing ? 2 : 3) : 1) >
printWidth)
) {
attributesOnTheirOwnLine = true
}
let tracker = trackerOneLine
let value = prefix
if (attributesOnTheirOwnLine) {
tracker = trackerMultiLine
let index = -1
while (++index < serializedAttributes.length) {
// Only indent first line of of attributes, we can’t indent attribute
// values.
serializedAttributes[index] =
currentIndent + indent + serializedAttributes[index]
}
value += tracker.move(
'\n' + serializedAttributes.join('\n') + '\n' + currentIndent
)
} else if (attributesOnOneLine) {
value += tracker.move(' ' + attributesOnOneLine)
}
if (selfClosing) {
value += tracker.move(
(tightSelfClosing || attributesOnTheirOwnLine ? '' : ' ') + '/'
)
}
value += tracker.move('>')
if (node.children && node.children.length > 0) {
if (node.type === 'mdxJsxTextElement') {
value += tracker.move(
// @ts-expect-error: `containerPhrasing` is typed correctly, but TS
// generates *hardcoded* types, which means that our dynamically added
// directives are not present.
// At some point, TS should fix that, and `from-markdown` should be fine.
state.containerPhrasing(node, {
...tracker.current(),
before: '>',
after: '<'
})
)
} else {
tracker.shift(2)
value += tracker.move('\n')
value += tracker.move(containerFlow(node, state, tracker.current()))
value += tracker.move('\n')
}
}
if (!selfClosing) {
value += tracker.move(
(flow ? currentIndent : '') + '</' + (node.name || '') + '>'
)
}
exit()
return value
}
}
// Modified copy of:
// <https://github.com/syntax-tree/mdast-util-to-markdown/blob/a381cbc/lib/util/container-flow.js>.
//
// To do: add `indent` support to `mdast-util-to-markdown`.
// As indents are only used for JSX, it’s fine for now, but perhaps better
// there.
/**
* @param {MdxJsxFlowElement} parent
* Parent of flow nodes.
* @param {State} state
* Info passed around about the current state.
* @param {ReturnType<Tracker['current']>} info
* Info on where we are in the document we are generating.
* @returns {string}
* Serialized children, joined by (blank) lines.
*/
function containerFlow(parent, state, info) {
const indexStack = state.indexStack
const children = parent.children
const tracker = state.createTracker(info)
const currentIndent = createIndent(inferDepth(state))
/** @type {Array<string>} */
const results = []
let index = -1
indexStack.push(-1)
while (++index < children.length) {
const child = children[index]
indexStack[indexStack.length - 1] = index
const childInfo = {before: '\n', after: '\n', ...tracker.current()}
const result = state.handle(child, parent, state, childInfo)
const serializedChild =
child.type === 'mdxJsxFlowElement'
? result
: state.indentLines(result, function (line, _, blank) {
return (blank ? '' : currentIndent) + line
})
results.push(tracker.move(serializedChild))
if (child.type !== 'list') {
state.bulletLastUsed = undefined
}
if (index < children.length - 1) {
results.push(tracker.move('\n\n'))
}
}
indexStack.pop()
return results.join('')
}
/**
* @param {State} state
* @returns {number}
*/
function inferDepth(state) {
let depth = 0
let index = state.stack.length
while (--index > -1) {
const name = state.stack[index]
if (name === 'blockquote' || name === 'listItem') break
if (name === 'mdxJsxFlowElement') depth++
}
return depth
}
/**
* @param {number} depth
* @returns {string}
*/
function createIndent(depth) {
return indent.repeat(depth)
}
/**
* @type {ToMarkdownHandle}
*/
function peekElement() {
return '<'
}