1 import { communitySearch, personSearch } from "@utils/app";
2 import { isBrowser } from "@utils/browser";
3 import { debounce, groupBy } from "@utils/helpers";
4 import { CommunityTribute, PersonTribute } from "@utils/types";
5 import { Picker } from "emoji-mart";
6 import emojiShortName from "emoji-short-name";
7 import { CustomEmojiView } from "lemmy-js-client";
8 import { default as MarkdownIt } from "markdown-it";
9 import markdown_it_container from "markdown-it-container";
10 // import markdown_it_emoji from "markdown-it-emoji/bare";
11 import markdown_it_footnote from "markdown-it-footnote";
12 import markdown_it_html5_embed from "markdown-it-html5-embed";
13 import markdown_it_sub from "markdown-it-sub";
14 import markdown_it_sup from "markdown-it-sup";
15 import Renderer from "markdown-it/lib/renderer";
16 import Token from "markdown-it/lib/token";
17 import { instanceLinkRegex } from "./config";
19 export let Tribute: any;
21 export let md: MarkdownIt = new MarkdownIt();
23 export let mdNoImages: MarkdownIt = new MarkdownIt();
25 export const customEmojis: EmojiMartCategory[] = [];
27 export let customEmojisLookup: Map<string, CustomEmojiView> = new Map<
33 Tribute = require("tributejs");
36 export function mdToHtml(text: string) {
37 return { __html: md.render(text) };
40 export function mdToHtmlNoImages(text: string) {
41 return { __html: mdNoImages.render(text) };
44 export function mdToHtmlInline(text: string) {
45 return { __html: md.renderInline(text) };
48 const spoilerConfig = {
49 validate: (params: string) => {
50 return params.trim().match(/^spoiler\s+(.*)$/);
53 render: (tokens: any, idx: any) => {
54 var m = tokens[idx].info.trim().match(/^spoiler\s+(.*)$/);
56 if (tokens[idx].nesting === 1) {
58 return `<details><summary> ${md.utils.escapeHtml(m[1])} </summary>\n`;
61 return "</details>\n";
66 const html5EmbedConfig = {
68 useImageSyntax: true, // Enables video/audio embed with ![]() syntax (default)
70 audio: 'controls preload="metadata"',
71 video: 'width="100%" max-height="100%" controls loop preload="metadata"',
76 function localCommunityLinkParser(md: MarkdownIt) {
77 md.core.ruler.push("replace-text", state => {
78 for (let i = 0; i < state.tokens.length; i++) {
79 if (state.tokens[i].type !== "inline") {
82 const inlineTokens = state.tokens[i].children;
83 for (let j = inlineTokens.length - 1; j >= 0; j--) {
85 inlineTokens[j].type === "text" &&
86 new RegExp(instanceLinkRegex).test(inlineTokens[j].content)
88 const text = inlineTokens[j].content;
89 const matches = Array.from(text.matchAll(instanceLinkRegex));
92 const newTokens: Token[] = [];
94 let linkClass = "community-link";
96 for (const match: RegExpMatchArray of matches) {
97 // If there is plain text before the match, add it as a separate token
98 if (match.index !== undefined && match.index > lastIndex) {
99 const textToken = new state.Token("text", "", 0);
100 textToken.content = text.slice(lastIndex, match.index);
101 newTokens.push(textToken);
104 // Determine the new href
106 if (match[0].startsWith("!")) {
107 href = "/c/" + match[0].substring(1);
108 } else if (match[0].startsWith("/m/")) {
109 href = "/c/" + match[0].substring(3);
114 if (match[0].startsWith("/u/")) {
115 linkClass = "user-link";
118 const linkOpenToken = new state.Token("link_open", "a", 1);
119 linkOpenToken.attrs = [
121 ["class", linkClass],
123 const textToken = new state.Token("text", "", 0);
124 textToken.content = match[0];
125 const linkCloseToken = new state.Token("link_close", "a", -1);
127 newTokens.push(linkOpenToken, textToken, linkCloseToken);
130 (match.index !== undefined ? match.index : 0) + match[0].length;
133 // If there is plain text after the last match, add it as a separate token
134 if (lastIndex < text.length) {
135 const textToken = new state.Token("text", "", 0);
136 textToken.content = text.slice(lastIndex);
137 newTokens.push(textToken);
140 // Replace the original token with the new tokens
141 inlineTokens.splice(j, 1, ...newTokens);
148 export function setupMarkdown() {
149 const markdownItConfig: MarkdownIt.Options = {
155 // const emojiDefs = Array.from(customEmojisLookup.entries()).reduce(
156 // (main, [key, value]) => ({ ...main, [key]: value }),
159 md = new MarkdownIt(markdownItConfig)
160 .use(markdown_it_sub)
161 .use(markdown_it_sup)
162 .use(markdown_it_footnote)
163 .use(markdown_it_html5_embed, html5EmbedConfig)
164 .use(markdown_it_container, "spoiler", spoilerConfig)
165 .use(localCommunityLinkParser);
166 // .use(markdown_it_emoji, {
170 mdNoImages = new MarkdownIt(markdownItConfig)
171 .use(markdown_it_sub)
172 .use(markdown_it_sup)
173 .use(markdown_it_footnote)
174 .use(markdown_it_html5_embed, html5EmbedConfig)
175 .use(markdown_it_container, "spoiler", spoilerConfig)
176 .use(localCommunityLinkParser)
177 // .use(markdown_it_emoji, {
181 const defaultRenderer = md.renderer.rules.image;
182 md.renderer.rules.image = function (
185 options: MarkdownIt.Options,
189 //Provide custom renderer for our emojis to allow us to add a css class and force size dimensions on them.
190 const item = tokens[idx] as any;
191 const title = item.attrs.length >= 3 ? item.attrs[2][1] : "";
192 const src: string = item.attrs[0][1];
193 const isCustomEmoji = customEmojisLookup.get(title) != undefined;
194 if (!isCustomEmoji) {
195 return defaultRenderer?.(tokens, idx, options, env, self) ?? "";
197 const alt_text = item.content;
198 return `<img class="icon icon-emoji" src="${src}" title="${title}" alt="${alt_text}"/>`;
200 md.renderer.rules.table_open = function () {
201 return '<table class="table">';
205 export function setupEmojiDataModel(custom_emoji_views: CustomEmojiView[]) {
206 const groupedEmojis = groupBy(
208 x => x.custom_emoji.category
210 for (const [category, emojis] of Object.entries(groupedEmojis)) {
214 emojis: emojis.map(emoji => ({
215 id: emoji.custom_emoji.shortcode,
216 name: emoji.custom_emoji.shortcode,
217 keywords: emoji.keywords.map(x => x.keyword),
218 skins: [{ src: emoji.custom_emoji.image_url }],
222 customEmojisLookup = new Map(
223 custom_emoji_views.map(view => [view.custom_emoji.shortcode, view])
227 export function updateEmojiDataModel(custom_emoji_view: CustomEmojiView) {
228 const emoji: EmojiMartCustomEmoji = {
229 id: custom_emoji_view.custom_emoji.shortcode,
230 name: custom_emoji_view.custom_emoji.shortcode,
231 keywords: custom_emoji_view.keywords.map(x => x.keyword),
232 skins: [{ src: custom_emoji_view.custom_emoji.image_url }],
234 const categoryIndex = customEmojis.findIndex(
235 x => x.id == custom_emoji_view.custom_emoji.category
237 if (categoryIndex == -1) {
239 id: custom_emoji_view.custom_emoji.category,
240 name: custom_emoji_view.custom_emoji.category,
244 const emojiIndex = customEmojis[categoryIndex].emojis.findIndex(
245 x => x.id == custom_emoji_view.custom_emoji.shortcode
247 if (emojiIndex == -1) {
248 customEmojis[categoryIndex].emojis.push(emoji);
250 customEmojis[categoryIndex].emojis[emojiIndex] = emoji;
253 customEmojisLookup.set(
254 custom_emoji_view.custom_emoji.shortcode,
259 export function removeFromEmojiDataModel(id: number) {
260 let view: CustomEmojiView | undefined;
261 for (const item of customEmojisLookup.values()) {
262 if (item.custom_emoji.id === id) {
268 const categoryIndex = customEmojis.findIndex(
269 x => x.id == view?.custom_emoji.category
271 const emojiIndex = customEmojis[categoryIndex].emojis.findIndex(
272 x => x.id == view?.custom_emoji.shortcode
274 customEmojis[categoryIndex].emojis = customEmojis[
276 ].emojis.splice(emojiIndex, 1);
278 customEmojisLookup.delete(view?.custom_emoji.shortcode);
281 export function getEmojiMart(
282 onEmojiSelect: (e: any) => void,
283 customPickerOptions: any = {}
285 const pickerOptions = {
286 ...customPickerOptions,
287 onEmojiSelect: onEmojiSelect,
288 custom: customEmojis,
290 return new Picker(pickerOptions);
293 export function setupTribute() {
295 noMatchTemplate: function () {
302 menuItemTemplate: (item: any) => {
303 const shortName = `:${item.original.key}:`;
304 return `${item.original.val} ${shortName}`;
306 selectTemplate: (item: any) => {
307 const customEmoji = customEmojisLookup.get(
310 if (customEmoji == undefined) return `${item.original.val}`;
312 return `![${customEmoji.alt_text}](${customEmoji.image_url} "${customEmoji.shortcode}")`;
314 values: Object.entries(emojiShortName)
316 return { key: e[1], val: e[0] };
319 Array.from(customEmojisLookup.entries()).map(k => ({
321 val: `<img class="icon icon-emoji" src="${k[1].custom_emoji.image_url}" title="${k[1].custom_emoji.shortcode}" alt="${k[1].custom_emoji.alt_text}" />`,
325 autocompleteMode: true,
327 // menuItemLimit: mentionDropdownFetchLimit,
328 menuShowMinLength: 2,
333 selectTemplate: (item: any) => {
334 const it: PersonTribute = item.original;
335 return `[${it.key}](${it.view.person.actor_id})`;
337 values: debounce(async (text: string, cb: any) => {
338 cb(await personSearch(text));
341 autocompleteMode: true,
343 // menuItemLimit: mentionDropdownFetchLimit,
344 menuShowMinLength: 2,
350 selectTemplate: (item: any) => {
351 const it: CommunityTribute = item.original;
352 return `[${it.key}](${it.view.community.actor_id})`;
354 values: debounce(async (text: string, cb: any) => {
355 cb(await communitySearch(text));
358 autocompleteMode: true,
360 // menuItemLimit: mentionDropdownFetchLimit,
361 menuShowMinLength: 2,
367 interface EmojiMartCategory {
370 emojis: EmojiMartCustomEmoji[];
373 interface EmojiMartCustomEmoji {
377 skins: EmojiMartSkin[];
380 interface EmojiMartSkin {