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