|
118 | 118 | * Transform an mdast node to hast.
|
119 | 119 | * @property {(node: MdastNodes) => Array<HastElementContent>} all
|
120 | 120 | * Transform the children of an mdast parent to hast.
|
| 121 | + * @property {<Type extends HastContent>(nodes: Array<Type>, loose?: boolean | null | undefined) => Array<Type | HastText>} wrap |
| 122 | + * Wrap `nodes` with line endings between each node, adds initial/final line endings when `loose`. |
121 | 123 | * @property {(left: MdastNodeWithData | PositionLike | null | undefined, right: HastElementContent) => HastElementContent} augment
|
122 | 124 | * Like `state` but lower-level and usable on non-elements.
|
123 | 125 | * Deprecated: use `patch` and `applyData`.
|
@@ -223,6 +225,7 @@ export function createState(tree, options) {
|
223 | 225 | state.applyData = applyData
|
224 | 226 | state.one = oneBound
|
225 | 227 | state.all = allBound
|
| 228 | + state.wrap = wrap |
226 | 229 | // To do: next major: remove `augment`.
|
227 | 230 | state.augment = augment
|
228 | 231 |
|
@@ -539,3 +542,36 @@ function defaultUnknownHandler(state, node) {
|
539 | 542 | state.patch(node, result)
|
540 | 543 | return state.applyData(node, result)
|
541 | 544 | }
|
| 545 | + |
| 546 | +/** |
| 547 | + * Wrap `nodes` with line endings between each node. |
| 548 | + * |
| 549 | + * @template {HastContent} Type |
| 550 | + * Node type. |
| 551 | + * @param {Array<Type>} nodes |
| 552 | + * List of nodes to wrap. |
| 553 | + * @param {boolean | null | undefined} [loose=false] |
| 554 | + * Whether to add line endings at start and end. |
| 555 | + * @returns {Array<Type | HastText>} |
| 556 | + * Wrapped nodes. |
| 557 | + */ |
| 558 | +export function wrap(nodes, loose) { |
| 559 | + /** @type {Array<Type | HastText>} */ |
| 560 | + const result = [] |
| 561 | + let index = -1 |
| 562 | + |
| 563 | + if (loose) { |
| 564 | + result.push({type: 'text', value: '\n'}) |
| 565 | + } |
| 566 | + |
| 567 | + while (++index < nodes.length) { |
| 568 | + if (index) result.push({type: 'text', value: '\n'}) |
| 569 | + result.push(nodes[index]) |
| 570 | + } |
| 571 | + |
| 572 | + if (loose && nodes.length > 0) { |
| 573 | + result.push({type: 'text', value: '\n'}) |
| 574 | + } |
| 575 | + |
| 576 | + return result |
| 577 | +} |
0 commit comments