1
0
elk/composables/content-parse.ts

130 lines
3.7 KiB
TypeScript
Raw Normal View History

2022-12-28 04:13:50 +09:00
// @unimport-disable
2022-11-21 16:14:07 +09:00
import type { Emoji } from 'masto'
import type { Node } from 'ultrahtml'
import { TEXT_NODE, parse, render, walkSync } from 'ultrahtml'
2022-12-28 05:42:58 +09:00
import createEmojiRegex from 'emoji-regex'
2022-11-21 06:21:53 +09:00
2022-12-28 05:42:58 +09:00
export const EMOJI_REGEX = createEmojiRegex()
2022-12-28 03:37:22 +09:00
const decoder = process.client ? document.createElement('textarea') : null as any as HTMLTextAreaElement
export function decodeHtml(text: string) {
2022-12-05 09:30:20 +09:00
decoder.innerHTML = text
return decoder.value
}
/**
* Parse raw HTML form Mastodon server to AST,
* with interop of custom emojis and inline Markdown syntax
*/
export function parseMastodonHTML(html: string, customEmojis: Record<string, Emoji> = {}, markdown = true) {
let processed = html
// custom emojis
2022-11-24 12:42:03 +09:00
.replace(/:([\w-]+?):/g, (_, name) => {
const emoji = customEmojis[name]
return emoji
? `<img src="${emoji.url}" alt=":${name}:" class="custom-emoji" data-emoji-id="${name}" />`
: `:${name}:`
})
2022-12-28 05:42:58 +09:00
.replace(EMOJI_REGEX, '<em-emoji native="$&" fallback="$&" />')
if (markdown) {
// handle code blocks
processed = processed
.replace(/>(```|~~~)(\w*)([\s\S]+?)\1/g, (_1, _2, lang, raw) => {
const code = htmlToText(raw)
const classes = lang ? ` class="language-${lang}"` : ''
return `><pre><code${classes}>${code}</code></pre>`
})
2022-11-24 12:42:03 +09:00
walkSync(parse(processed), (node) => {
if (node.type !== TEXT_NODE)
return
const replacements = [
[/\*\*\*(.*?)\*\*\*/g, '<b><em>$1</em></b>'],
[/\*\*(.*?)\*\*/g, '<b>$1</b>'],
[/\*(.*?)\*/g, '<em>$1</em>'],
[/~~(.*?)~~/g, '<del>$1</del>'],
[/`([^`]+?)`/g, '<code>$1</code>'],
] as any
for (const [re, replacement] of replacements) {
for (const match of node.value.matchAll(re)) {
if (node.loc) {
const start = match.index! + node.loc[0].start
const end = start + match[0].length + node.loc[0].start
processed = processed.slice(0, start) + match[0].replace(re, replacement) + processed.slice(end)
}
else {
processed = processed.replace(match[0], match[0].replace(re, replacement))
}
}
}
})
}
return parse(processed)
}
export function convertMastodonHTML(html: string, customEmojis: Record<string, Emoji> = {}) {
const tree = parseMastodonHTML(html, customEmojis)
return render(tree)
}
2022-11-26 01:17:15 +09:00
export function htmlToText(html: string) {
const tree = parse(html)
return (tree.children as Node[]).map(n => treeToText(n)).join('').trim()
2022-11-24 12:42:03 +09:00
}
2022-11-30 15:50:47 +09:00
export function treeToText(input: Node): string {
2022-11-24 12:42:03 +09:00
let pre = ''
2022-11-26 01:17:15 +09:00
let body = ''
let post = ''
2022-11-24 12:42:03 +09:00
if (input.type === TEXT_NODE)
return decodeHtml(input.value)
2022-11-24 12:42:03 +09:00
if (input.name === 'br')
2022-11-24 12:42:03 +09:00
return '\n'
if (['p', 'pre'].includes(input.name))
2022-11-24 12:42:03 +09:00
pre = '\n'
if (input.name === 'code') {
if (input.parent?.name === 'pre') {
const lang = input.attributes.class?.replace('language-', '')
2022-11-26 04:21:53 +09:00
2022-11-30 13:50:29 +09:00
pre = `\`\`\`${lang || ''}\n`
post = '\n```'
}
else {
pre = '`'
post = '`'
}
}
else if (input.name === 'b' || input.name === 'strong') {
2022-11-30 13:50:29 +09:00
pre = '**'
post = '**'
}
else if (input.name === 'i' || input.name === 'em') {
2022-11-30 13:50:29 +09:00
pre = '*'
post = '*'
2022-11-26 01:17:15 +09:00
}
else if (input.name === 'del') {
2022-11-30 15:50:47 +09:00
pre = '~~'
post = '~~'
}
2022-11-26 01:17:15 +09:00
if ('children' in input)
body = (input.children as Node[]).map(n => treeToText(n)).join('')
2022-11-24 12:42:03 +09:00
// add spaces around emoji to prevent parsing errors: 2 or more consecutive emojis will not be parsed
if (input.name === 'img' && input.attributes.class?.includes('custom-emoji'))
2022-12-28 06:08:40 +09:00
return ` :${input.attributes['data-emoji-id']}: `
2022-12-28 04:13:50 +09:00
if (input.name === 'em-emoji')
return `${input.attributes.native}`
2022-11-30 15:50:47 +09:00
2022-11-26 01:17:15 +09:00
return pre + body + post
2022-11-24 12:42:03 +09:00
}