Urara-Blog/node_modules/.pnpm-store/v3/files/c8/8d7afb8fed362203991fd096f8a498a5aaf4e3d10d0c5201c6f71ccde2c60b6ec06e2b0c13a170341dd90cac4be5e7e93736518e8c8e9bf1f52618122e630d
2022-08-14 01:14:53 +08:00

73 lines
1.4 KiB
Text
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

/**
* @fileoverview
* Get the plain-text value of a hast node.
* @longdescription
* ## Use
*
* ```js
* import {h} from 'hastscript'
* import {toString} from 'hast-util-to-string'
*
* toString(h('p', 'Alpha'))
* //=> 'Alpha'
* toString(h('div', [h('b', 'Bold'), ' and ', h('i', 'italic'), '.']))
* //=> 'Bold and italic.'
* ```
*
* ## API
*
* ### `toString(node)`
*
* Transform a node to a string.
*/
/**
* @typedef {import('hast').Root} Root
* @typedef {import('hast').Element} Element
* @typedef {Root|Root['children'][number]} Node
*/
/**
* Get the plain-text value of a hast node.
*
* @param {Node} node
* @returns {string}
*/
export function toString(node) {
// “The concatenation of data of all the Text node descendants of the context
// object, in tree order.”
if ('children' in node) {
return all(node)
}
// “Context objects data.”
return 'value' in node ? node.value : ''
}
/**
* @param {Node} node
* @returns {string}
*/
function one(node) {
if (node.type === 'text') {
return node.value
}
return 'children' in node ? all(node) : ''
}
/**
* @param {Root|Element} node
* @returns {string}
*/
function all(node) {
let index = -1
/** @type {string[]} */
const result = []
while (++index < node.children.length) {
result[index] = one(node.children[index])
}
return result.join('')
}