2023-10-23 23:33:39 +02:00
|
|
|
import { visit } from "unist-util-visit"
|
|
|
|
import type { Plugin, Transformer } from "unified"
|
|
|
|
import type { Literal, Parent } from "unist"
|
|
|
|
import type { ElementContent } from "hast"
|
|
|
|
import type { EmojiSet } from "emoji-mart"
|
2022-01-01 20:42:25 +01:00
|
|
|
|
2023-10-23 23:33:39 +02:00
|
|
|
import { emojiRegex } from "./isStringWithOnlyOneEmoji"
|
2022-01-01 20:42:25 +01:00
|
|
|
|
2023-10-23 23:33:39 +02:00
|
|
|
export const EMOJI_SET: EmojiSet = "twitter"
|
2022-01-01 20:42:25 +01:00
|
|
|
|
|
|
|
const extractText = (
|
|
|
|
string: string,
|
|
|
|
start: number,
|
2023-10-23 23:33:39 +02:00
|
|
|
end: number,
|
2022-01-01 20:42:25 +01:00
|
|
|
): ElementContent => {
|
|
|
|
return {
|
2023-10-23 23:33:39 +02:00
|
|
|
type: "text",
|
|
|
|
value: string.slice(start, end),
|
2022-01-01 20:42:25 +01:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
export const emojiPlugin: Plugin<[], Literal<string>> = () => {
|
|
|
|
const transformer: Transformer<Literal<string>> = (tree) => {
|
|
|
|
visit<Literal<string>, string>(
|
|
|
|
tree,
|
2023-10-23 23:33:39 +02:00
|
|
|
"text",
|
2022-01-01 20:42:25 +01:00
|
|
|
(node, position, parent: Parent<ElementContent> | null) => {
|
2023-10-23 23:33:39 +02:00
|
|
|
if (typeof node.value !== "string") {
|
2022-01-01 20:42:25 +01:00
|
|
|
return
|
|
|
|
}
|
|
|
|
position = position ?? 0
|
|
|
|
const definition: ElementContent[] = []
|
|
|
|
let lastIndex = 0
|
|
|
|
const match = emojiRegex.exec(node.value)
|
|
|
|
if (match != null) {
|
|
|
|
const value = match[0]
|
|
|
|
if (match.index !== lastIndex) {
|
|
|
|
definition.push(extractText(node.value, lastIndex, match.index))
|
|
|
|
}
|
|
|
|
definition.push({
|
2023-10-23 23:33:39 +02:00
|
|
|
type: "element",
|
|
|
|
tagName: "emoji",
|
2022-01-01 20:42:25 +01:00
|
|
|
properties: { value },
|
2023-10-23 23:33:39 +02:00
|
|
|
children: [],
|
2022-01-01 20:42:25 +01:00
|
|
|
})
|
|
|
|
lastIndex = match.index + value.length
|
|
|
|
if (lastIndex !== node.value.length) {
|
|
|
|
definition.push(
|
2023-10-23 23:33:39 +02:00
|
|
|
extractText(node.value, lastIndex, node.value.length),
|
2022-01-01 20:42:25 +01:00
|
|
|
)
|
|
|
|
}
|
|
|
|
if (parent != null) {
|
|
|
|
const last = parent.children.slice(position + 1)
|
|
|
|
parent.children = parent.children.slice(0, position)
|
|
|
|
parent.children = parent.children.concat(definition)
|
|
|
|
parent.children = parent.children.concat(last)
|
|
|
|
}
|
|
|
|
}
|
2023-10-23 23:33:39 +02:00
|
|
|
},
|
2022-01-01 20:42:25 +01:00
|
|
|
)
|
|
|
|
}
|
|
|
|
return transformer
|
|
|
|
}
|
|
|
|
|
|
|
|
declare global {
|
|
|
|
namespace JSX {
|
|
|
|
interface IntrinsicElements {
|
|
|
|
emoji: { value: string }
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|