]> Untitled Git - lemmy-ui.git/blob - src/shared/markdown.ts
Use shorter regex in community link parser
[lemmy-ui.git] / src / shared / markdown.ts
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";
18
19 export let Tribute: any;
20
21 export let md: MarkdownIt = new MarkdownIt();
22
23 export let mdNoImages: MarkdownIt = new MarkdownIt();
24
25 export const customEmojis: EmojiMartCategory[] = [];
26
27 export let customEmojisLookup: Map<string, CustomEmojiView> = new Map<
28   string,
29   CustomEmojiView
30 >();
31
32 if (isBrowser()) {
33   Tribute = require("tributejs");
34 }
35
36 export function mdToHtml(text: string) {
37   return { __html: md.render(text) };
38 }
39
40 export function mdToHtmlNoImages(text: string) {
41   return { __html: mdNoImages.render(text) };
42 }
43
44 export function mdToHtmlInline(text: string) {
45   return { __html: md.renderInline(text) };
46 }
47
48 const spoilerConfig = {
49   validate: (params: string) => {
50     return params.trim().match(/^spoiler\s+(.*)$/);
51   },
52
53   render: (tokens: any, idx: any) => {
54     var m = tokens[idx].info.trim().match(/^spoiler\s+(.*)$/);
55
56     if (tokens[idx].nesting === 1) {
57       // opening tag
58       return `<details><summary> ${md.utils.escapeHtml(m[1])} </summary>\n`;
59     } else {
60       // closing tag
61       return "</details>\n";
62     }
63   },
64 };
65
66 const html5EmbedConfig = {
67   html5embed: {
68     useImageSyntax: true, // Enables video/audio embed with ![]() syntax (default)
69     attributes: {
70       audio: 'controls preload="metadata"',
71       video: 'width="100%" max-height="100%" controls loop preload="metadata"',
72     },
73   },
74 };
75
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") {
80         continue;
81       }
82       const inlineTokens = state.tokens[i].children;
83       for (let j = inlineTokens.length - 1; j >= 0; j--) {
84         if (
85           inlineTokens[j].type === "text" &&
86           new RegExp(instanceLinkRegex).test(inlineTokens[j].content)
87         ) {
88           const text = inlineTokens[j].content;
89           const matches = Array.from(text.matchAll(instanceLinkRegex));
90
91           let lastIndex = 0;
92           const newTokens: Token[] = [];
93
94           for (const match: RegExpMatchArray of matches) {
95             // If there is plain text before the match, add it as a separate token
96             if (match.index !== undefined && match.index > lastIndex) {
97               const textToken = new state.Token("text", "", 0);
98               textToken.content = text.slice(lastIndex, match.index);
99               newTokens.push(textToken);
100             }
101
102             // Determine the new href
103             let href;
104             if (match[0].startsWith("!")) {
105               href = "/c/" + match[0].substring(1);
106             } else if (match[0].startsWith("/m/")) {
107               href = "/c/" + match[0].substring(3);
108             } else {
109               href = match[0];
110             }
111
112             const linkOpenToken = new state.Token("link_open", "a", 1);
113             linkOpenToken.attrs = [["href", href]];
114             const textToken = new state.Token("text", "", 0);
115             textToken.content = match[0];
116             const linkCloseToken = new state.Token("link_close", "a", -1);
117
118             newTokens.push(linkOpenToken, textToken, linkCloseToken);
119
120             lastIndex =
121               (match.index !== undefined ? match.index : 0) + match[0].length;
122           }
123
124           // If there is plain text after the last match, add it as a separate token
125           if (lastIndex < text.length) {
126             const textToken = new state.Token("text", "", 0);
127             textToken.content = text.slice(lastIndex);
128             newTokens.push(textToken);
129           }
130
131           // Replace the original token with the new tokens
132           inlineTokens.splice(j, 1, ...newTokens);
133         }
134       }
135     }
136   });
137 }
138
139 export function setupMarkdown() {
140   const markdownItConfig: MarkdownIt.Options = {
141     html: false,
142     linkify: true,
143     typographer: true,
144   };
145
146   // const emojiDefs = Array.from(customEmojisLookup.entries()).reduce(
147   //   (main, [key, value]) => ({ ...main, [key]: value }),
148   //   {}
149   // );
150   md = new MarkdownIt(markdownItConfig)
151     .use(markdown_it_sub)
152     .use(markdown_it_sup)
153     .use(markdown_it_footnote)
154     .use(markdown_it_html5_embed, html5EmbedConfig)
155     .use(markdown_it_container, "spoiler", spoilerConfig)
156     .use(localCommunityLinkParser);
157   // .use(markdown_it_emoji, {
158   //   defs: emojiDefs,
159   // });
160
161   mdNoImages = new MarkdownIt(markdownItConfig)
162     .use(markdown_it_sub)
163     .use(markdown_it_sup)
164     .use(markdown_it_footnote)
165     .use(markdown_it_html5_embed, html5EmbedConfig)
166     .use(markdown_it_container, "spoiler", spoilerConfig)
167     .use(localCommunityLinkParser)
168     // .use(markdown_it_emoji, {
169     //   defs: emojiDefs,
170     // })
171     .disable("image");
172   const defaultRenderer = md.renderer.rules.image;
173   md.renderer.rules.image = function (
174     tokens: Token[],
175     idx: number,
176     options: MarkdownIt.Options,
177     env: any,
178     self: Renderer
179   ) {
180     //Provide custom renderer for our emojis to allow us to add a css class and force size dimensions on them.
181     const item = tokens[idx] as any;
182     const title = item.attrs.length >= 3 ? item.attrs[2][1] : "";
183     const src: string = item.attrs[0][1];
184     const isCustomEmoji = customEmojisLookup.get(title) != undefined;
185     if (!isCustomEmoji) {
186       return defaultRenderer?.(tokens, idx, options, env, self) ?? "";
187     }
188     const alt_text = item.content;
189     return `<img class="icon icon-emoji" src="${src}" title="${title}" alt="${alt_text}"/>`;
190   };
191   md.renderer.rules.table_open = function () {
192     return '<table class="table">';
193   };
194 }
195
196 export function setupEmojiDataModel(custom_emoji_views: CustomEmojiView[]) {
197   const groupedEmojis = groupBy(
198     custom_emoji_views,
199     x => x.custom_emoji.category
200   );
201   for (const [category, emojis] of Object.entries(groupedEmojis)) {
202     customEmojis.push({
203       id: category,
204       name: category,
205       emojis: emojis.map(emoji => ({
206         id: emoji.custom_emoji.shortcode,
207         name: emoji.custom_emoji.shortcode,
208         keywords: emoji.keywords.map(x => x.keyword),
209         skins: [{ src: emoji.custom_emoji.image_url }],
210       })),
211     });
212   }
213   customEmojisLookup = new Map(
214     custom_emoji_views.map(view => [view.custom_emoji.shortcode, view])
215   );
216 }
217
218 export function updateEmojiDataModel(custom_emoji_view: CustomEmojiView) {
219   const emoji: EmojiMartCustomEmoji = {
220     id: custom_emoji_view.custom_emoji.shortcode,
221     name: custom_emoji_view.custom_emoji.shortcode,
222     keywords: custom_emoji_view.keywords.map(x => x.keyword),
223     skins: [{ src: custom_emoji_view.custom_emoji.image_url }],
224   };
225   const categoryIndex = customEmojis.findIndex(
226     x => x.id == custom_emoji_view.custom_emoji.category
227   );
228   if (categoryIndex == -1) {
229     customEmojis.push({
230       id: custom_emoji_view.custom_emoji.category,
231       name: custom_emoji_view.custom_emoji.category,
232       emojis: [emoji],
233     });
234   } else {
235     const emojiIndex = customEmojis[categoryIndex].emojis.findIndex(
236       x => x.id == custom_emoji_view.custom_emoji.shortcode
237     );
238     if (emojiIndex == -1) {
239       customEmojis[categoryIndex].emojis.push(emoji);
240     } else {
241       customEmojis[categoryIndex].emojis[emojiIndex] = emoji;
242     }
243   }
244   customEmojisLookup.set(
245     custom_emoji_view.custom_emoji.shortcode,
246     custom_emoji_view
247   );
248 }
249
250 export function removeFromEmojiDataModel(id: number) {
251   let view: CustomEmojiView | undefined;
252   for (const item of customEmojisLookup.values()) {
253     if (item.custom_emoji.id === id) {
254       view = item;
255       break;
256     }
257   }
258   if (!view) return;
259   const categoryIndex = customEmojis.findIndex(
260     x => x.id == view?.custom_emoji.category
261   );
262   const emojiIndex = customEmojis[categoryIndex].emojis.findIndex(
263     x => x.id == view?.custom_emoji.shortcode
264   );
265   customEmojis[categoryIndex].emojis = customEmojis[
266     categoryIndex
267   ].emojis.splice(emojiIndex, 1);
268
269   customEmojisLookup.delete(view?.custom_emoji.shortcode);
270 }
271
272 export function getEmojiMart(
273   onEmojiSelect: (e: any) => void,
274   customPickerOptions: any = {}
275 ) {
276   const pickerOptions = {
277     ...customPickerOptions,
278     onEmojiSelect: onEmojiSelect,
279     custom: customEmojis,
280   };
281   return new Picker(pickerOptions);
282 }
283
284 export function setupTribute() {
285   return new Tribute({
286     noMatchTemplate: function () {
287       return "";
288     },
289     collection: [
290       // Emojis
291       {
292         trigger: ":",
293         menuItemTemplate: (item: any) => {
294           const shortName = `:${item.original.key}:`;
295           return `${item.original.val} ${shortName}`;
296         },
297         selectTemplate: (item: any) => {
298           const customEmoji = customEmojisLookup.get(
299             item.original.key
300           )?.custom_emoji;
301           if (customEmoji == undefined) return `${item.original.val}`;
302           else
303             return `![${customEmoji.alt_text}](${customEmoji.image_url} "${customEmoji.shortcode}")`;
304         },
305         values: Object.entries(emojiShortName)
306           .map(e => {
307             return { key: e[1], val: e[0] };
308           })
309           .concat(
310             Array.from(customEmojisLookup.entries()).map(k => ({
311               key: k[0],
312               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}" />`,
313             }))
314           ),
315         allowSpaces: false,
316         autocompleteMode: true,
317         // TODO
318         // menuItemLimit: mentionDropdownFetchLimit,
319         menuShowMinLength: 2,
320       },
321       // Persons
322       {
323         trigger: "@",
324         selectTemplate: (item: any) => {
325           const it: PersonTribute = item.original;
326           return `[${it.key}](${it.view.person.actor_id})`;
327         },
328         values: debounce(async (text: string, cb: any) => {
329           cb(await personSearch(text));
330         }),
331         allowSpaces: false,
332         autocompleteMode: true,
333         // TODO
334         // menuItemLimit: mentionDropdownFetchLimit,
335         menuShowMinLength: 2,
336       },
337
338       // Communities
339       {
340         trigger: "!",
341         selectTemplate: (item: any) => {
342           const it: CommunityTribute = item.original;
343           return `[${it.key}](${it.view.community.actor_id})`;
344         },
345         values: debounce(async (text: string, cb: any) => {
346           cb(await communitySearch(text));
347         }),
348         allowSpaces: false,
349         autocompleteMode: true,
350         // TODO
351         // menuItemLimit: mentionDropdownFetchLimit,
352         menuShowMinLength: 2,
353       },
354     ],
355   });
356 }
357
358 interface EmojiMartCategory {
359   id: string;
360   name: string;
361   emojis: EmojiMartCustomEmoji[];
362 }
363
364 interface EmojiMartCustomEmoji {
365   id: string;
366   name: string;
367   keywords: string[];
368   skins: EmojiMartSkin[];
369 }
370
371 interface EmojiMartSkin {
372   src: string;
373 }