|
19 | 19 | * |
20 | 20 | * @typedef ToMarkdownOptions |
21 | 21 | * @property {'"'|"'"} [quote='"'] |
| 22 | + * Preferred quote to use around attribute values. |
| 23 | + * @property {boolean} [quoteSmart=false] |
| 24 | + * Use the other quote if that results in less bytes. |
22 | 25 | */ |
23 | 26 |
|
| 27 | +import {ccount} from 'ccount' |
24 | 28 | import {parseEntities} from 'parse-entities' |
25 | 29 | import {stringifyPosition} from 'unist-util-stringify-position' |
26 | 30 | import {VFileMessage} from 'vfile-message' |
@@ -359,7 +363,8 @@ export function mdxJsxFromMarkdown() { |
359 | 363 | * @returns {ToMarkdownExtension} |
360 | 364 | */ |
361 | 365 | export function mdxJsxToMarkdown(options = {}) { |
362 | | - const {quote = '"'} = options |
| 366 | + const {quote = '"', quoteSmart} = options |
| 367 | + const alternative = quote === '"' ? "'" : '"' |
363 | 368 |
|
364 | 369 | if (quote !== '"' && quote !== "'") { |
365 | 370 | throw new Error( |
@@ -419,16 +424,28 @@ export function mdxJsxToMarkdown(options = {}) { |
419 | 424 | throw new Error('Cannot serialize attribute w/o name') |
420 | 425 | } |
421 | 426 |
|
422 | | - result = |
423 | | - attribute.name + |
424 | | - (attribute.value === undefined || attribute.value === null |
425 | | - ? '' |
426 | | - : '=' + |
427 | | - (typeof attribute.value === 'object' |
428 | | - ? '{' + (attribute.value.value || '') + '}' |
429 | | - : quote + |
430 | | - stringifyEntitiesLight(attribute.value, {subset: [quote]}) + |
431 | | - quote)) |
| 427 | + const value = attribute.value |
| 428 | + let initializer = '' |
| 429 | + |
| 430 | + if (value === undefined || value === null) { |
| 431 | + // Empty. |
| 432 | + } else if (typeof value === 'object') { |
| 433 | + initializer = '={' + (value.value || '') + '}' |
| 434 | + } else { |
| 435 | + // If the alternative is less common than `quote`, switch. |
| 436 | + const appliedQuote = |
| 437 | + quoteSmart && ccount(value, quote) > ccount(value, alternative) |
| 438 | + ? alternative |
| 439 | + : quote |
| 440 | + |
| 441 | + initializer += |
| 442 | + '=' + |
| 443 | + appliedQuote + |
| 444 | + stringifyEntitiesLight(value, {subset: [appliedQuote]}) + |
| 445 | + appliedQuote |
| 446 | + } |
| 447 | + |
| 448 | + result = attribute.name + initializer |
432 | 449 | } |
433 | 450 |
|
434 | 451 | attributes.push((isMultiFlow ? '\n ' : ' ') + result) |
|
0 commit comments