kjelsrud.dev/node_modules/mdast-util-to-hast/lib/revert.js
2023-07-19 21:31:30 +02:00

60 lines
1.4 KiB
JavaScript

/**
* @typedef {import('hast').ElementContent} ElementContent
*
* @typedef {import('mdast').Content} Content
* @typedef {import('mdast').Reference} Reference
* @typedef {import('mdast').Root} Root
*
* @typedef {import('./state.js').State} State
*/
/**
* @typedef {Root | Content} Nodes
* @typedef {Extract<Nodes, Reference>} References
*/
// To do: next major: always return array.
/**
* Return the content of a reference without definition as plain text.
*
* @param {State} state
* Info passed around.
* @param {References} node
* Reference node (image, link).
* @returns {ElementContent | Array<ElementContent>}
* hast content.
*/
export function revert(state, node) {
const subtype = node.referenceType
let suffix = ']'
if (subtype === 'collapsed') {
suffix += '[]'
} else if (subtype === 'full') {
suffix += '[' + (node.label || node.identifier) + ']'
}
if (node.type === 'imageReference') {
return {type: 'text', value: '![' + node.alt + suffix}
}
const contents = state.all(node)
const head = contents[0]
if (head && head.type === 'text') {
head.value = '[' + head.value
} else {
contents.unshift({type: 'text', value: '['})
}
const tail = contents[contents.length - 1]
if (tail && tail.type === 'text') {
tail.value += suffix
} else {
contents.push({type: 'text', value: suffix})
}
return contents
}