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_ruby from "markdown-it-ruby";
14 import markdown_it_sub from "markdown-it-sub";
15 import markdown_it_sup from "markdown-it-sup";
16 import Renderer from "markdown-it/lib/renderer";
17 import Token from "markdown-it/lib/token";
18 import { instanceLinkRegex } from "./config";
20 export let Tribute: any;
22 export let md: MarkdownIt = new MarkdownIt();
24 export let mdNoImages: MarkdownIt = new MarkdownIt();
26 export const customEmojis: EmojiMartCategory[] = [];
28 export let customEmojisLookup: Map<string, CustomEmojiView> = new Map<
34 Tribute = require("tributejs");
37 export function mdToHtml(text: string) {
38 return { __html: md.render(text) };
41 export function mdToHtmlNoImages(text: string) {
42 return { __html: mdNoImages.render(text) };
45 export function mdToHtmlInline(text: string) {
46 return { __html: md.renderInline(text) };
49 const spoilerConfig = {
50 validate: (params: string) => {
51 return params.trim().match(/^spoiler\s+(.*)$/);
54 render: (tokens: any, idx: any) => {
55 var m = tokens[idx].info.trim().match(/^spoiler\s+(.*)$/);
57 if (tokens[idx].nesting === 1) {
59 return `<details><summary> ${md.utils.escapeHtml(m[1])} </summary>\n`;
62 return "</details>\n";
67 const html5EmbedConfig = {
69 useImageSyntax: true, // Enables video/audio embed with ![]() syntax (default)
71 audio: 'controls preload="metadata"',
72 video: 'width="100%" max-height="100%" controls loop preload="metadata"',
77 function localInstanceLinkParser(md: MarkdownIt) {
78 md.core.ruler.push("replace-text", state => {
79 for (let i = 0; i < state.tokens.length; i++) {
80 if (state.tokens[i].type !== "inline") {
83 const inlineTokens: Token[] = state.tokens[i].children || [];
84 for (let j = inlineTokens.length - 1; j >= 0; j--) {
86 inlineTokens[j].type === "text" &&
87 new RegExp(instanceLinkRegex).test(inlineTokens[j].content)
89 const text = inlineTokens[j].content;
90 const matches = Array.from(text.matchAll(instanceLinkRegex));
93 const newTokens: Token[] = [];
95 let linkClass = "community-link";
97 for (const match of matches) {
98 // If there is plain text before the match, add it as a separate token
99 if (match.index !== undefined && match.index > lastIndex) {
100 const textToken = new state.Token("text", "", 0);
101 textToken.content = text.slice(lastIndex, match.index);
102 newTokens.push(textToken);
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);
112 if (match[0].startsWith("/u/")) {
113 linkClass = "user-link";
117 const linkOpenToken = new state.Token("link_open", "a", 1);
118 linkOpenToken.attrs = [
120 ["class", linkClass],
122 const textToken = new state.Token("text", "", 0);
123 textToken.content = match[0];
124 const linkCloseToken = new state.Token("link_close", "a", -1);
126 newTokens.push(linkOpenToken, textToken, linkCloseToken);
129 (match.index !== undefined ? match.index : 0) + match[0].length;
132 // If there is plain text after the last match, add it as a separate token
133 if (lastIndex < text.length) {
134 const textToken = new state.Token("text", "", 0);
135 textToken.content = text.slice(lastIndex);
136 newTokens.push(textToken);
139 inlineTokens.splice(j, 1, ...newTokens);
146 export function setupMarkdown() {
147 const markdownItConfig: MarkdownIt.Options = {
153 // const emojiDefs = Array.from(customEmojisLookup.entries()).reduce(
154 // (main, [key, value]) => ({ ...main, [key]: value }),
157 md = new MarkdownIt(markdownItConfig)
158 .use(markdown_it_sub)
159 .use(markdown_it_sup)
160 .use(markdown_it_footnote)
161 .use(markdown_it_html5_embed, html5EmbedConfig)
162 .use(markdown_it_container, "spoiler", spoilerConfig)
163 .use(markdown_it_ruby)
164 .use(localInstanceLinkParser);
165 // .use(markdown_it_emoji, {
169 mdNoImages = new MarkdownIt(markdownItConfig)
170 .use(markdown_it_sub)
171 .use(markdown_it_sup)
172 .use(markdown_it_footnote)
173 .use(markdown_it_html5_embed, html5EmbedConfig)
174 .use(markdown_it_container, "spoiler", spoilerConfig)
175 .use(localInstanceLinkParser)
176 // .use(markdown_it_emoji, {
180 const defaultRenderer = md.renderer.rules.image;
181 md.renderer.rules.image = function (
184 options: MarkdownIt.Options,
188 //Provide custom renderer for our emojis to allow us to add a css class and force size dimensions on them.
189 const item = tokens[idx] as any;
190 const title = item.attrs.length >= 3 ? item.attrs[2][1] : "";
191 const src: string = item.attrs[0][1];
192 const isCustomEmoji = customEmojisLookup.get(title) != undefined;
193 if (!isCustomEmoji) {
194 return defaultRenderer?.(tokens, idx, options, env, self) ?? "";
196 const alt_text = item.content;
197 return `<img class="icon icon-emoji" src="${src}" title="${title}" alt="${alt_text}"/>`;
199 md.renderer.rules.table_open = function () {
200 return '<table class="table">';
204 export function setupEmojiDataModel(custom_emoji_views: CustomEmojiView[]) {
205 const groupedEmojis = groupBy(
207 x => x.custom_emoji.category
209 for (const [category, emojis] of Object.entries(groupedEmojis)) {
213 emojis: emojis.map(emoji => ({
214 id: emoji.custom_emoji.shortcode,
215 name: emoji.custom_emoji.shortcode,
216 keywords: emoji.keywords.map(x => x.keyword),
217 skins: [{ src: emoji.custom_emoji.image_url }],
221 customEmojisLookup = new Map(
222 custom_emoji_views.map(view => [view.custom_emoji.shortcode, view])
226 export function updateEmojiDataModel(custom_emoji_view: CustomEmojiView) {
227 const emoji: EmojiMartCustomEmoji = {
228 id: custom_emoji_view.custom_emoji.shortcode,
229 name: custom_emoji_view.custom_emoji.shortcode,
230 keywords: custom_emoji_view.keywords.map(x => x.keyword),
231 skins: [{ src: custom_emoji_view.custom_emoji.image_url }],
233 const categoryIndex = customEmojis.findIndex(
234 x => x.id == custom_emoji_view.custom_emoji.category
236 if (categoryIndex == -1) {
238 id: custom_emoji_view.custom_emoji.category,
239 name: custom_emoji_view.custom_emoji.category,
243 const emojiIndex = customEmojis[categoryIndex].emojis.findIndex(
244 x => x.id == custom_emoji_view.custom_emoji.shortcode
246 if (emojiIndex == -1) {
247 customEmojis[categoryIndex].emojis.push(emoji);
249 customEmojis[categoryIndex].emojis[emojiIndex] = emoji;
252 customEmojisLookup.set(
253 custom_emoji_view.custom_emoji.shortcode,
258 export function removeFromEmojiDataModel(id: number) {
259 let view: CustomEmojiView | undefined;
260 for (const item of customEmojisLookup.values()) {
261 if (item.custom_emoji.id === id) {
267 const categoryIndex = customEmojis.findIndex(
268 x => x.id == view?.custom_emoji.category
270 const emojiIndex = customEmojis[categoryIndex].emojis.findIndex(
271 x => x.id == view?.custom_emoji.shortcode
273 customEmojis[categoryIndex].emojis = customEmojis[
275 ].emojis.splice(emojiIndex, 1);
277 customEmojisLookup.delete(view?.custom_emoji.shortcode);
280 export function getEmojiMart(
281 onEmojiSelect: (e: any) => void,
282 customPickerOptions: any = {}
284 const pickerOptions = {
285 ...customPickerOptions,
286 onEmojiSelect: onEmojiSelect,
287 custom: customEmojis,
289 return new Picker(pickerOptions);
292 export function setupTribute() {
294 noMatchTemplate: function () {
301 menuItemTemplate: (item: any) => {
302 const shortName = `:${item.original.key}:`;
303 return `${item.original.val} ${shortName}`;
305 selectTemplate: (item: any) => {
306 const customEmoji = customEmojisLookup.get(
309 if (customEmoji == undefined) return `${item.original.val}`;
311 return `![${customEmoji.alt_text}](${customEmoji.image_url} "${customEmoji.shortcode}")`;
313 values: Object.entries(emojiShortName)
315 return { key: e[1], val: e[0] };
318 Array.from(customEmojisLookup.entries()).map(k => ({
320 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}" />`,
324 autocompleteMode: true,
326 // menuItemLimit: mentionDropdownFetchLimit,
327 menuShowMinLength: 2,
332 selectTemplate: (item: any) => {
333 const it: PersonTribute = item.original;
334 return `[${it.key}](${it.view.person.actor_id})`;
336 values: debounce(async (text: string, cb: any) => {
337 cb(await personSearch(text));
340 autocompleteMode: true,
342 // menuItemLimit: mentionDropdownFetchLimit,
343 menuShowMinLength: 2,
349 selectTemplate: (item: any) => {
350 const it: CommunityTribute = item.original;
351 return `[${it.key}](${it.view.community.actor_id})`;
353 values: debounce(async (text: string, cb: any) => {
354 cb(await communitySearch(text));
357 autocompleteMode: true,
359 // menuItemLimit: mentionDropdownFetchLimit,
360 menuShowMinLength: 2,
366 interface EmojiMartCategory {
369 emojis: EmojiMartCustomEmoji[];
372 interface EmojiMartCustomEmoji {
376 skins: EmojiMartSkin[];
379 interface EmojiMartSkin {