75 lines
1.6 KiB
JavaScript
75 lines
1.6 KiB
JavaScript
const markerRunLength = (characters, start, marker) => {
|
|
let length = 0
|
|
while (characters[start + length] === marker) length += 1
|
|
return length
|
|
}
|
|
|
|
export const renderChatMarkdownCharacters = (value) => {
|
|
const characters = Array.isArray(value) ? value : Array.from(String(value || ''))
|
|
const output = []
|
|
let bold = false
|
|
let italic = false
|
|
let code = false
|
|
let heading = false
|
|
let lineStart = true
|
|
|
|
const push = (text, key) => {
|
|
output.push({
|
|
text,
|
|
key,
|
|
bold,
|
|
italic,
|
|
code,
|
|
heading,
|
|
newline: text === '\n',
|
|
})
|
|
}
|
|
|
|
for (let index = 0; index < characters.length; index += 1) {
|
|
const character = characters[index]
|
|
|
|
if (lineStart && character === '#') {
|
|
const length = markerRunLength(characters, index, '#')
|
|
if (characters[index + length] === ' ') {
|
|
heading = true
|
|
index += length
|
|
continue
|
|
}
|
|
}
|
|
|
|
if (lineStart && (character === '-' || character === '*') && characters[index + 1] === ' ') {
|
|
push('•', `${index}-bullet`)
|
|
push(' ', `${index}-space`)
|
|
index += 1
|
|
lineStart = false
|
|
continue
|
|
}
|
|
|
|
if (!code && (character === '*' || character === '_')) {
|
|
const length = markerRunLength(characters, index, character)
|
|
if (length >= 2) {
|
|
bold = !bold
|
|
index += length - 1
|
|
continue
|
|
}
|
|
italic = !italic
|
|
continue
|
|
}
|
|
|
|
if (character === '`') {
|
|
code = !code
|
|
continue
|
|
}
|
|
|
|
push(character, index)
|
|
if (character === '\n') {
|
|
heading = false
|
|
lineStart = true
|
|
} else {
|
|
lineStart = false
|
|
}
|
|
}
|
|
|
|
return output
|
|
}
|