watch-party/frontend/lib/emojis.mjs

70 lines
2.0 KiB
JavaScript
Raw Normal View History

2022-02-15 16:42:16 -08:00
export async function emojify(text) {
2022-02-18 10:39:53 -08:00
await emojisLoaded;
2022-02-15 16:30:22 -08:00
let last = 0;
let nodes = [];
text.replace(/:([^\s:]+):/g, (match, name, index) => {
if (last <= index)
nodes.push(document.createTextNode(text.slice(last, index)));
2022-02-18 10:39:53 -08:00
let emoji = emojis[name.toLowerCase()[0]].find((e) => e[0] == name);
2022-02-16 07:48:34 -08:00
if (!emoji) {
2022-02-15 16:42:16 -08:00
nodes.push(document.createTextNode(match));
} else {
2022-02-16 07:48:34 -08:00
if (emoji[1][0] !== ":") {
nodes.push(document.createTextNode(emoji[1]));
} else {
nodes.push(
Object.assign(new Image(), {
2022-02-18 09:20:08 -08:00
src: `/emojis/${name}${emoji[2]}`,
2022-02-16 07:48:34 -08:00
className: "emoji",
alt: name,
})
);
}
2022-02-15 16:42:16 -08:00
}
2022-02-15 16:30:22 -08:00
last = index + match.length;
});
if (last < text.length) nodes.push(document.createTextNode(text.slice(last)));
return nodes;
}
2022-02-18 10:39:53 -08:00
const emojis = {};
export const emojisLoaded = Promise.all([
2022-02-16 07:30:47 -08:00
fetch("/emojis")
.then((e) => e.json())
2022-02-18 10:39:53 -08:00
.then((a) => {
for (let e of a) {
const name = e.slice(0, -4),
lower = name.toLowerCase();
emojis[lower[0]] = emojis[lower[0]] || [];
emojis[lower[0]].push([name, ":" + name + ":", e.slice(-4), lower]);
}
}),
fetch("/emojis/unicode.json")
.then((e) => e.json())
.then((a) => {
for (let e of a) {
emojis[e[0][0]] = emojis[e[0][0]] || [];
emojis[e[0][0]].push([e[0], e[1], null, e[0]]);
}
}),
]);
export async function findEmojis(search) {
await emojisLoaded;
let groups = [[], []];
if (search.length < 1) {
for (let letter in emojis)
for (let emoji of emojis[letter]) {
(emoji[1][0] === ":" ? groups[0] : groups[1]).push(emoji);
}
} else {
search = search.toLowerCase();
for (let emoji of emojis[search[0]]) {
if (search.length == 1 || emoji[3].startsWith(search)) {
(emoji[1][0] === ":" ? groups[0] : groups[1]).push(emoji);
}
}
}
return [...groups[0], ...groups[1]];
}