Skip to content

Commit

Permalink
feat: generate structural obj (#101)
Browse files Browse the repository at this point in the history
  • Loading branch information
huozhi authored Jun 16, 2024
1 parent fe95f1d commit 7eeca95
Showing 1 changed file with 65 additions and 12 deletions.
77 changes: 65 additions & 12 deletions lib/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -578,20 +578,52 @@ function tokenize(code) {

/**
* @param {Array<[number, string]>} tokens
* @return {Array<string>}
* @return {Array<any>}
*/
function generate(tokens) {
const linesHtml = []
const createLine = (content) => `<span class="sh__line">${content}</span>`
const lines = []
/**
* @param {any} children
*
*/
const createLine = (children) =>
// generateType === 'html'
// ? `<span class="sh__line">${content}</span>`
({
type: 'element',
tagName: 'span',
children,
properties: {
className: 'sh__line',
},
})

/**
* @param {Array<[number, string]>} tokens
* @returns {void}
*/
function flushLine(tokens) {
linesHtml.push(createLine(
tokens.map(([type, value]) => (
`<span class="sh__token--${types[type]}" style="color: var(--sh-${types[type]})">${encode(value)}</span>`
))
.join('')
))
/** @type {Array<any>} */
const lineTokens = (
tokens
.map(([type, value]) => (
{
type: 'element',
tagName: 'span',
children: [{
type: 'text',
value: value, // to encode
}],
properties: {
className: `sh__token--${types[type]}`,
style: `color: var(--sh-${types[type]})`,
},
}
))
)
lines.push(createLine(lineTokens))
}
/** @type {Array<[number, string]>} */
const lineTokens = []
for (let i = 0; i < tokens.length; i++) {
const token = tokens[i]
Expand Down Expand Up @@ -620,7 +652,26 @@ function generate(tokens) {
if (lineTokens.length)
flushLine(lineTokens)

return linesHtml
return lines
}

function toHtml(lines) {
return lines
.map(line => {
const { tagName: lineTag } = line
const tokens = line.children
.map(child => {
const { tagName, children, properties } = child
return `<${tagName} class="${
properties.className
}" style="${
properties.style
}">${encode(children[0].value)}</${tagName}>`
})
.join('')
return `<${lineTag} class="${line.properties.className}">${tokens}</${lineTag}>`
})
.join('\n')
}

/**
Expand All @@ -630,7 +681,8 @@ function generate(tokens) {
*/
function highlight(code) {
const tokens = tokenize(code)
const output = generate(tokens).join('\n')
const lines = generate(tokens)
const output = toHtml(lines)
return output
}

Expand All @@ -642,5 +694,6 @@ const SugarHigh = /** @type {const} */ {
export {
highlight,
tokenize,
generate,
SugarHigh,
}
}

0 comments on commit 7eeca95

Please sign in to comment.