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

51 lines
1.2 KiB
JavaScript
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.

/**
* @typedef {import('hast').Element} Element
* @typedef {import('hast').Properties} Properties
* @typedef {import('mdast').Code} Code
* @typedef {import('../state.js').State} State
*/
/**
* Turn an mdast `code` node into hast.
*
* @param {State} state
* Info passed around.
* @param {Code} node
* mdast node.
* @returns {Element}
* hast node.
*/
export function code(state, node) {
const value = node.value ? node.value + '\n' : ''
// To do: next major, use `node.lang` w/o regex, the splittings been going
// on for years in remark now.
const lang = node.lang ? node.lang.match(/^[^ \t]+(?=[ \t]|$)/) : null
/** @type {Properties} */
const properties = {}
if (lang) {
properties.className = ['language-' + lang]
}
// Create `<code>`.
/** @type {Element} */
let result = {
type: 'element',
tagName: 'code',
properties,
children: [{type: 'text', value}]
}
if (node.meta) {
result.data = {meta: node.meta}
}
state.patch(node, result)
result = state.applyData(node, result)
// Create `<pre>`.
result = {type: 'element', tagName: 'pre', properties: {}, children: [result]}
state.patch(node, result)
return result
}