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 localInstanceLinkParser(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: Token[] = 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 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);
105 if (match[0].startsWith("!")) {
106 href = "/c/" + match[0].substring(1);
107 } else if (match[0].startsWith("/m/")) {
108 href = "/c/" + match[0].substring(3);
111 if (match[0].startsWith("/u/")) {
112 linkClass = "user-link";
116 const linkOpenToken = new state.Token("link_open", "a", 1);
117 linkOpenToken.attrs = [
119 ["class", linkClass],
121 const textToken = new state.Token("text", "", 0);
122 textToken.content = match[0];
123 const linkCloseToken = new state.Token("link_close", "a", -1);
125 newTokens.push(linkOpenToken, textToken, linkCloseToken);
128 (match.index !== undefined ? match.index : 0) + match[0].length;
131 // If there is plain text after the last match, add it as a separate token
132 if (lastIndex < text.length) {
133 const textToken = new state.Token("text", "", 0);
134 textToken.content = text.slice(lastIndex);
135 newTokens.push(textToken);
138 inlineTokens.splice(j, 1, ...newTokens);
145 export function setupMarkdown() {
146 const markdownItConfig: MarkdownIt.Options = {
152 // const emojiDefs = Array.from(customEmojisLookup.entries()).reduce(
153 // (main, [key, value]) => ({ ...main, [key]: value }),
156 md = new MarkdownIt(markdownItConfig)
157 .use(markdown_it_sub)
158 .use(markdown_it_sup)
159 .use(markdown_it_footnote)
160 .use(markdown_it_html5_embed, html5EmbedConfig)
161 .use(markdown_it_container, "spoiler", spoilerConfig)
162 .use(localInstanceLinkParser);
163 // .use(markdown_it_emoji, {
167 mdNoImages = new MarkdownIt(markdownItConfig)
168 .use(markdown_it_sub)
169 .use(markdown_it_sup)
170 .use(markdown_it_footnote)
171 .use(markdown_it_html5_embed, html5EmbedConfig)
172 .use(markdown_it_container, "spoiler", spoilerConfig)
173 .use(localInstanceLinkParser)
174 // .use(markdown_it_emoji, {
178 const defaultRenderer = md.renderer.rules.image;
179 md.renderer.rules.image = function (
182 options: MarkdownIt.Options,
186 //Provide custom renderer for our emojis to allow us to add a css class and force size dimensions on them.
187 const item = tokens[idx] as any;
188 const title = item.attrs.length >= 3 ? item.attrs[2][1] : "";
189 const src: string = item.attrs[0][1];
190 const isCustomEmoji = customEmojisLookup.get(title) != undefined;
191 if (!isCustomEmoji) {
192 return defaultRenderer?.(tokens, idx, options, env, self) ?? "";
194 const alt_text = item.content;
195 return `<img class="icon icon-emoji" src="${src}" title="${title}" alt="${alt_text}"/>`;
197 md.renderer.rules.table_open = function () {
198 return '<table class="table">';
202 export function setupEmojiDataModel(custom_emoji_views: CustomEmojiView[]) {
203 const groupedEmojis = groupBy(
205 x => x.custom_emoji.category
207 for (const [category, emojis] of Object.entries(groupedEmojis)) {
211 emojis: emojis.map(emoji => ({
212 id: emoji.custom_emoji.shortcode,
213 name: emoji.custom_emoji.shortcode,
214 keywords: emoji.keywords.map(x => x.keyword),
215 skins: [{ src: emoji.custom_emoji.image_url }],
219 customEmojisLookup = new Map(
220 custom_emoji_views.map(view => [view.custom_emoji.shortcode, view])
224 export function updateEmojiDataModel(custom_emoji_view: CustomEmojiView) {
225 const emoji: EmojiMartCustomEmoji = {
226 id: custom_emoji_view.custom_emoji.shortcode,
227 name: custom_emoji_view.custom_emoji.shortcode,
228 keywords: custom_emoji_view.keywords.map(x => x.keyword),
229 skins: [{ src: custom_emoji_view.custom_emoji.image_url }],
231 const categoryIndex = customEmojis.findIndex(
232 x => x.id == custom_emoji_view.custom_emoji.category
234 if (categoryIndex == -1) {
236 id: custom_emoji_view.custom_emoji.category,
237 name: custom_emoji_view.custom_emoji.category,
241 const emojiIndex = customEmojis[categoryIndex].emojis.findIndex(
242 x => x.id == custom_emoji_view.custom_emoji.shortcode
244 if (emojiIndex == -1) {
245 customEmojis[categoryIndex].emojis.push(emoji);
247 customEmojis[categoryIndex].emojis[emojiIndex] = emoji;
250 customEmojisLookup.set(
251 custom_emoji_view.custom_emoji.shortcode,
256 export function removeFromEmojiDataModel(id: number) {
257 let view: CustomEmojiView | undefined;
258 for (const item of customEmojisLookup.values()) {
259 if (item.custom_emoji.id === id) {
265 const categoryIndex = customEmojis.findIndex(
266 x => x.id == view?.custom_emoji.category
268 const emojiIndex = customEmojis[categoryIndex].emojis.findIndex(
269 x => x.id == view?.custom_emoji.shortcode
271 customEmojis[categoryIndex].emojis = customEmojis[
273 ].emojis.splice(emojiIndex, 1);
275 customEmojisLookup.delete(view?.custom_emoji.shortcode);
278 export function getEmojiMart(
279 onEmojiSelect: (e: any) => void,
280 customPickerOptions: any = {}
282 const pickerOptions = {
283 ...customPickerOptions,
284 onEmojiSelect: onEmojiSelect,
285 custom: customEmojis,
287 return new Picker(pickerOptions);
290 export function setupTribute() {
292 noMatchTemplate: function () {
299 menuItemTemplate: (item: any) => {
300 const shortName = `:${item.original.key}:`;
301 return `${item.original.val} ${shortName}`;
303 selectTemplate: (item: any) => {
304 const customEmoji = customEmojisLookup.get(
307 if (customEmoji == undefined) return `${item.original.val}`;
309 return `![${customEmoji.alt_text}](${customEmoji.image_url} "${customEmoji.shortcode}")`;
311 values: Object.entries(emojiShortName)
313 return { key: e[1], val: e[0] };
316 Array.from(customEmojisLookup.entries()).map(k => ({
318 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}" />`,
322 autocompleteMode: true,
324 // menuItemLimit: mentionDropdownFetchLimit,
325 menuShowMinLength: 2,
330 selectTemplate: (item: any) => {
331 const it: PersonTribute = item.original;
332 return `[${it.key}](${it.view.person.actor_id})`;
334 values: debounce(async (text: string, cb: any) => {
335 cb(await personSearch(text));
338 autocompleteMode: true,
340 // menuItemLimit: mentionDropdownFetchLimit,
341 menuShowMinLength: 2,
347 selectTemplate: (item: any) => {
348 const it: CommunityTribute = item.original;
349 return `[${it.key}](${it.view.community.actor_id})`;
351 values: debounce(async (text: string, cb: any) => {
352 cb(await communitySearch(text));
355 autocompleteMode: true,
357 // menuItemLimit: mentionDropdownFetchLimit,
358 menuShowMinLength: 2,
364 interface EmojiMartCategory {
367 emojis: EmojiMartCustomEmoji[];
370 interface EmojiMartCustomEmoji {
374 skins: EmojiMartSkin[];
377 interface EmojiMartSkin {