watch-party/frontend/lib/emojis.mjs

73 lines
2.1 KiB
JavaScript
Raw Normal View History

2022-02-16 00:42:16 +00:00
export async function emojify(text) {
2022-02-18 18:39:53 +00:00
await emojisLoaded;
2022-02-16 00:30:22 +00:00
let last = 0;
let nodes = [];
text.replace(/:([^\s:]+):/g, (match, name, index) => {
if (last <= index)
nodes.push(document.createTextNode(text.slice(last, index)));
let emoji;
try {
emoji = emojis[name.toLowerCase()[0]].find((e) => e[0] == name);
} catch (e) {}
2022-02-16 15:48:34 +00:00
if (!emoji) {
2022-02-16 00:42:16 +00:00
nodes.push(document.createTextNode(match));
} else {
2022-02-16 15:48:34 +00:00
if (emoji[1][0] !== ":") {
nodes.push(document.createTextNode(emoji[1]));
} else {
nodes.push(
Object.assign(new Image(), {
2022-02-18 17:20:08 +00:00
src: `/emojis/${name}${emoji[2]}`,
2022-02-16 15:48:34 +00:00
className: "emoji",
alt: name,
})
);
}
2022-02-16 00:42:16 +00:00
}
2022-02-16 00:30:22 +00:00
last = index + match.length;
});
if (last < text.length) nodes.push(document.createTextNode(text.slice(last)));
return nodes;
}
2022-02-18 18:39:53 +00:00
const emojis = {};
export const emojisLoaded = Promise.all([
2022-02-16 15:30:47 +00:00
fetch("/emojis")
.then((e) => e.json())
2022-02-18 18:39:53 +00: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 of Object.keys(emojis).sort())
2022-02-18 18:39:53 +00:00
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]];
}