Files
indiekit-endpoint-activitypub/lib/emoji-utils.js
Ricardo 02d449d03c feat: render custom emoji in reader (Release 1)
Extract custom emoji from ActivityPub objects (Fedify Emoji tags) and
Mastodon API (status.emojis, account.emojis). Replace :shortcode:
patterns with <img> tags in the unified processing pipeline.

Emoji rendering applies to post content, author display names, boost
attribution, and quote embed authors. Uses the shared postProcessItems()
pipeline so both reader and explore views get emoji automatically.

Bump version to 2.5.1.

Confab-Link: http://localhost:8080/sessions/e9d666ac-3c90-4298-9e92-9ac9d142bc06
2026-03-03 13:13:28 +01:00

39 lines
1.1 KiB
JavaScript

/**
* Custom emoji replacement for fediverse content.
*
* Replaces :shortcode: patterns with <img> tags for custom emoji.
* Must be called AFTER sanitizeContent() — the inserted <img> tags
* would be stripped if run through the sanitizer.
*/
/**
* Escape special regex characters in a string.
* @param {string} str
* @returns {string}
*/
function escapeRegex(str) {
return str.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
}
/**
* Replace :shortcode: patterns in HTML with custom emoji <img> tags.
*
* @param {string} html - HTML string (already sanitized)
* @param {Array<{shortcode: string, url: string}>} emojis - Custom emoji list
* @returns {string} HTML with emoji shortcodes replaced by img tags
*/
export function replaceCustomEmoji(html, emojis) {
if (!html || !emojis?.length) return html;
for (const emoji of emojis) {
if (!emoji.shortcode || !emoji.url) continue;
const pattern = new RegExp(`:${escapeRegex(emoji.shortcode)}:`, "g");
html = html.replace(
pattern,
`<img src="${emoji.url}" alt=":${emoji.shortcode}:" title=":${emoji.shortcode}:" class="ap-custom-emoji" loading="lazy">`,
);
}
return html;
}