1
0
Fork 1
mirror of https://github.com/elk-zone/elk.git synced 2024-11-02 23:19:57 +00:00
elk/composables/content.ts

79 lines
2.4 KiB
TypeScript
Raw Normal View History

2022-11-21 07:14:07 +00:00
import type { Emoji } from 'masto'
2022-11-20 21:21:53 +00:00
import type { DefaultTreeAdapterMap } from 'parse5'
2022-11-20 21:25:26 +00:00
import { parseFragment } from 'parse5'
2022-11-20 21:21:53 +00:00
import type { VNode } from 'vue'
import { Fragment, h } from 'vue'
import { RouterLink } from 'vue-router'
type Node = DefaultTreeAdapterMap['childNode']
type Element = DefaultTreeAdapterMap['element']
export function defaultHandle(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')
if (href) {
const matchUser = href.value.match(UserLinkRE)
if (matchUser) {
const [, server, username] = matchUser
// Handles need to ignore server subdomains
href.value = `/@${username}@${server.replace(/(.+\.)(.+\..+)/, '$2')}`
2022-11-20 21:21:53 +00:00
}
const matchTag = href.value.match(TagLinkRE)
if (matchTag) {
const [, , name] = matchTag
href.value = `/tags/${name}`
}
}
}
return el
}
export function contentToVNode(
content: string,
handle: (node: Element) => Element | undefined | null | void = defaultHandle,
2022-11-21 07:14:07 +00:00
customEmojis: Record<string, Emoji> = {},
2022-11-20 21:21:53 +00:00
): VNode {
2022-11-21 13:21:53 +00:00
content = content.trim().replace(/:([\w-]+?):/g, (_, name) => {
2022-11-21 07:14:07 +00:00
const emoji = customEmojis[name]
if (emoji)
return `<img src="${emoji.url}" alt="${name}" class="custom-emoji" />`
return `:${name}:`
})
2022-11-20 21:21:53 +00:00
const tree = parseFragment(content)
return h(Fragment, tree.childNodes.map(n => treeToVNode(n, handle)))
}
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)
if (node == null)
return null
const attrs = Object.fromEntries(node.attrs.map(i => [i.name, i.value]))
if (node.nodeName === 'a' && (attrs.href?.startsWith('/') || attrs.href?.startsWith('.'))) {
attrs.to = attrs.href
delete attrs.href
delete attrs.target
return h(
RouterLink as any,
attrs,
2022-11-21 06:55:31 +00:00
() => node.childNodes.map(n => treeToVNode(n, handle)),
2022-11-20 21:21:53 +00:00
)
}
return h(
node.nodeName,
attrs,
node.childNodes.map(n => treeToVNode(n, handle)),
)
}
return null
}