feat: support codeblock

This commit is contained in:
Anthony Fu 2022-11-24 11:42:03 +08:00
parent 4885b165df
commit 0a8841f4f4
13 changed files with 201 additions and 52 deletions

View file

@ -1,14 +1,19 @@
import type { Emoji } from 'masto'
import type { DefaultTreeAdapterMap } from 'parse5'
import { parseFragment } from 'parse5'
import type { VNode } from 'vue'
import { Fragment, h } from 'vue'
import type { Component, VNode } from 'vue'
import { Fragment, h, isVNode } from 'vue'
import { RouterLink } from 'vue-router'
import ContentCode from '~/components/content/ContentCode.vue'
type Node = DefaultTreeAdapterMap['childNode']
type Element = DefaultTreeAdapterMap['element']
export function defaultHandle(el: Element) {
const CUSTOM_BLOCKS: Record<string, Component> = {
'custom-code': ContentCode,
}
function handleMention(el: Element) {
// Redirect mentions to the user page
if (el.tagName === 'a' && el.attrs.find(i => i.name === 'class' && i.value.includes('mention'))) {
const href = el.attrs.find(i => i.name === 'href')
@ -26,36 +31,58 @@ export function defaultHandle(el: Element) {
}
}
}
return el
return undefined
}
function handleBlocks(el: Element) {
if (el.tagName in CUSTOM_BLOCKS) {
const block = CUSTOM_BLOCKS[el.tagName]
const attrs = Object.fromEntries(el.attrs.map(i => [i.name, i.value]))
return h(block, attrs, () => el.childNodes.map(treeToVNode))
}
}
function handleNode(el: Element) {
return handleBlocks(el) || handleMention(el) || el
}
export function contentToVNode(
content: string,
handle: (node: Element) => Element | undefined | null | void = defaultHandle,
customEmojis: Record<string, Emoji> = {},
): VNode {
content = content.trim().replace(/:([\w-]+?):/g, (_, name) => {
const emoji = customEmojis[name]
if (emoji)
return `<img src="${emoji.url}" alt="${name}" class="custom-emoji" />`
return `:${name}:`
})
content = content
.trim()
// handle custom emojis
.replace(/:([\w-]+?):/g, (_, name) => {
const emoji = customEmojis[name]
if (emoji)
return `<img src="${emoji.url}" alt="${name}" class="custom-emoji" />`
return `:${name}:`
})
// handle codeblocks
.replace(/<p>(```|~~~)([\s\S]+?)\1(\s|<br\s?\/?>)*<\/p>/g, (_1, _2, raw) => {
const plain = htmlToText(`<p>${raw}</p>`).trim()
const [lang, ...rest] = plain.split(/\n/)
return `<custom-code lang="${lang || ''}" code="${encodeURIComponent(rest.join('\n'))}" />`
})
const tree = parseFragment(content)
return h(Fragment, tree.childNodes.map(n => treeToVNode(n, handle)))
return h(Fragment, tree.childNodes.map(n => treeToVNode(n)))
}
export function treeToVNode(
input: Node,
handle: (node: Element) => Element | undefined | null | void = defaultHandle,
): VNode | string | null {
if (input.nodeName === '#text')
// @ts-expect-error casing
return input.value
if ('childNodes' in input) {
const node = handle(input)
const node = handleNode(input)
if (node == null)
return null
if (isVNode(node))
return node
const attrs = Object.fromEntries(node.attrs.map(i => [i.name, i.value]))
if (node.nodeName === 'a' && (attrs.href?.startsWith('/') || attrs.href?.startsWith('.'))) {
@ -65,14 +92,38 @@ export function treeToVNode(
return h(
RouterLink as any,
attrs,
() => node.childNodes.map(n => treeToVNode(n, handle)),
() => node.childNodes.map(treeToVNode),
)
}
return h(
node.nodeName,
attrs,
node.childNodes.map(n => treeToVNode(n, handle)),
node.childNodes.map(treeToVNode),
)
}
return null
}
function htmlToText(html: string) {
const tree = parseFragment(html)
return tree.childNodes.map(n => treeToText(n)).join('')
}
function treeToText(input: Node): string {
let pre = ''
if (input.nodeName === '#text')
// @ts-expect-error casing
return input.value
if (input.nodeName === 'br')
return '\n'
if (input.nodeName === 'p')
pre = '\n'
if ('childNodes' in input)
return pre + input.childNodes.map(n => treeToText(n)).join('')
return pre
}

37
composables/shiki.ts Normal file
View file

@ -0,0 +1,37 @@
import type { Highlighter, Lang } from 'shiki'
export const shiki = ref<Highlighter>()
const registeredLang = ref(new Map<string, boolean>())
let shikiImport: Promise<void> | undefined
export function highlightCode(code: string, lang: Lang) {
if (!shikiImport) {
shikiImport = import('shiki')
.then(async (r) => {
r.setCDN('/shiki/')
shiki.value = await r.getHighlighter({
themes: [
'vitesse-dark',
'vitesse-light',
],
})
})
}
if (!shiki.value)
return code
if (!registeredLang.value.get(lang)) {
shiki.value.loadLanguage(lang)
.then(() => {
registeredLang.value.set(lang, true)
})
return code
}
return shiki.value.codeToHtml(code, {
lang,
theme: isDark.value ? 'vitesse-dark' : 'vitesse-light',
})
}

View file

@ -23,3 +23,4 @@ export function getDataUrlFromArr(arr: Uint8ClampedArray, w: number, h: number)
export function emojisArrayToObject(emojis: Emoji[]) {
return Object.fromEntries(emojis.map(i => [i.shortcode, i]))
}