rehype-custom-emoji-plugin/dist/index.js

37 lines
1.2 KiB
JavaScript
Raw Normal View History

2025-03-29 23:04:15 +01:00
import { findAndReplace } from "hast-util-find-and-replace";
import { h } from "hastscript";
const RE_EMOJI = /:([\w-]+):/g;
const DEFAULT_OPTIONS = {
sourceFile: "/assets/emojis.png",
hidpiSourceFile: undefined,
emojis: {},
size: 64,
2025-03-29 23:16:56 +01:00
class: "custom-emoji",
2025-03-29 23:04:15 +01:00
};
const plugin = (options) => {
const settings = Object.assign({}, DEFAULT_OPTIONS, options);
const srcset = settings.hidpiSourceFile
? `${settings.sourceFile} 1x, ${settings.hidpiSourceFile} 2x`
: undefined;
const emojiElement = (x, y, label) => {
return h("img", {
2025-03-29 23:16:56 +01:00
className: settings.class,
2025-03-29 23:04:15 +01:00
src: settings.sourceFile,
srcset,
style: `object-fit: none; object-position: -${x}px -${y}px; width: ${settings.size}px; height: ${settings.size}px`,
alt: label,
title: label,
});
};
const replaceEmoji = (_, match) => {
if (!(match in settings.emojis))
return false;
const emoji = settings.emojis[match];
return emojiElement(emoji[0], emoji[1], match);
};
return (tree) => {
findAndReplace(tree, [RE_EMOJI, replaceEmoji]);
};
};
export default plugin;