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 { getHttpBase } from "./env";
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) {
78 /(!\b[^@\s]+@[^@\s]+\.[^.\s]+\b)|\/c\/([^@\s]+)(@[^@\s]+\.[^.\s]+\b)?/g;
80 md.core.ruler.push("replace-text", state => {
81 const tokens = state.tokens;
83 for (let i = 0; i < tokens.length; i++) {
84 if (tokens[i].type === "inline") {
85 const token = tokens[i];
87 const originalContent = token.content;
90 originalContent.replace(
92 (match, fullDomainMatch, name, domainTld, index) => {
94 // ex: !Testing@example.com
95 if (fullDomainMatch) {
96 const [name, domain, tld] = fullDomainMatch
101 url = `${getHttpBase()}/c/${name}@${domain}.${tld}`;
103 // ex: /c/Testing or /c/Testing@example.com
104 url = `${getHttpBase()}/c/${name}${domainTld || ""}`;
107 const beforeContent = originalContent.slice(lastIndex, index);
108 lastIndex = index + match.length;
110 const beforeToken = new state.Token("text", "", 0);
111 beforeToken.content = beforeContent;
113 const linkOpenToken = new state.Token("link_open", "a", 1);
114 linkOpenToken.attrs = [["href", url]];
116 const textToken = new state.Token("text", "", 0);
117 textToken.content = match;
119 const linkCloseToken = new state.Token("link_close", "a", -1);
121 const afterContent = originalContent.slice(lastIndex);
122 const afterToken = new state.Token("text", "", 0);
123 afterToken.content = afterContent;
137 // Update i to skip the newly added tokens
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(localCommunityLinkParser);
164 // .use(markdown_it_emoji, {
168 mdNoImages = new MarkdownIt(markdownItConfig)
169 .use(markdown_it_sub)
170 .use(markdown_it_sup)
171 .use(markdown_it_footnote)
172 .use(markdown_it_html5_embed, html5EmbedConfig)
173 .use(markdown_it_container, "spoiler", spoilerConfig)
174 .use(localCommunityLinkParser)
175 // .use(markdown_it_emoji, {
179 const defaultRenderer = md.renderer.rules.image;
180 md.renderer.rules.image = function (
183 options: MarkdownIt.Options,
187 //Provide custom renderer for our emojis to allow us to add a css class and force size dimensions on them.
188 const item = tokens[idx] as any;
189 const title = item.attrs.length >= 3 ? item.attrs[2][1] : "";
190 const src: string = item.attrs[0][1];
191 const isCustomEmoji = customEmojisLookup.get(title) != undefined;
192 if (!isCustomEmoji) {
193 return defaultRenderer?.(tokens, idx, options, env, self) ?? "";
195 const alt_text = item.content;
196 return `<img class="icon icon-emoji" src="${src}" title="${title}" alt="${alt_text}"/>`;
198 md.renderer.rules.table_open = function () {
199 return '<table class="table">';
203 export function setupEmojiDataModel(custom_emoji_views: CustomEmojiView[]) {
204 const groupedEmojis = groupBy(
206 x => x.custom_emoji.category
208 for (const [category, emojis] of Object.entries(groupedEmojis)) {
212 emojis: emojis.map(emoji => ({
213 id: emoji.custom_emoji.shortcode,
214 name: emoji.custom_emoji.shortcode,
215 keywords: emoji.keywords.map(x => x.keyword),
216 skins: [{ src: emoji.custom_emoji.image_url }],
220 customEmojisLookup = new Map(
221 custom_emoji_views.map(view => [view.custom_emoji.shortcode, view])
225 export function updateEmojiDataModel(custom_emoji_view: CustomEmojiView) {
226 const emoji: EmojiMartCustomEmoji = {
227 id: custom_emoji_view.custom_emoji.shortcode,
228 name: custom_emoji_view.custom_emoji.shortcode,
229 keywords: custom_emoji_view.keywords.map(x => x.keyword),
230 skins: [{ src: custom_emoji_view.custom_emoji.image_url }],
232 const categoryIndex = customEmojis.findIndex(
233 x => x.id == custom_emoji_view.custom_emoji.category
235 if (categoryIndex == -1) {
237 id: custom_emoji_view.custom_emoji.category,
238 name: custom_emoji_view.custom_emoji.category,
242 const emojiIndex = customEmojis[categoryIndex].emojis.findIndex(
243 x => x.id == custom_emoji_view.custom_emoji.shortcode
245 if (emojiIndex == -1) {
246 customEmojis[categoryIndex].emojis.push(emoji);
248 customEmojis[categoryIndex].emojis[emojiIndex] = emoji;
251 customEmojisLookup.set(
252 custom_emoji_view.custom_emoji.shortcode,
257 export function removeFromEmojiDataModel(id: number) {
258 let view: CustomEmojiView | undefined;
259 for (const item of customEmojisLookup.values()) {
260 if (item.custom_emoji.id === id) {
266 const categoryIndex = customEmojis.findIndex(
267 x => x.id == view?.custom_emoji.category
269 const emojiIndex = customEmojis[categoryIndex].emojis.findIndex(
270 x => x.id == view?.custom_emoji.shortcode
272 customEmojis[categoryIndex].emojis = customEmojis[
274 ].emojis.splice(emojiIndex, 1);
276 customEmojisLookup.delete(view?.custom_emoji.shortcode);
279 export function getEmojiMart(
280 onEmojiSelect: (e: any) => void,
281 customPickerOptions: any = {}
283 const pickerOptions = {
284 ...customPickerOptions,
285 onEmojiSelect: onEmojiSelect,
286 custom: customEmojis,
288 return new Picker(pickerOptions);
291 export function setupTribute() {
293 noMatchTemplate: function () {
300 menuItemTemplate: (item: any) => {
301 const shortName = `:${item.original.key}:`;
302 return `${item.original.val} ${shortName}`;
304 selectTemplate: (item: any) => {
305 const customEmoji = customEmojisLookup.get(
308 if (customEmoji == undefined) return `${item.original.val}`;
310 return `![${customEmoji.alt_text}](${customEmoji.image_url} "${customEmoji.shortcode}")`;
312 values: Object.entries(emojiShortName)
314 return { key: e[1], val: e[0] };
317 Array.from(customEmojisLookup.entries()).map(k => ({
319 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}" />`,
323 autocompleteMode: true,
325 // menuItemLimit: mentionDropdownFetchLimit,
326 menuShowMinLength: 2,
331 selectTemplate: (item: any) => {
332 const it: PersonTribute = item.original;
333 return `[${it.key}](${it.view.person.actor_id})`;
335 values: debounce(async (text: string, cb: any) => {
336 cb(await personSearch(text));
339 autocompleteMode: true,
341 // menuItemLimit: mentionDropdownFetchLimit,
342 menuShowMinLength: 2,
348 selectTemplate: (item: any) => {
349 const it: CommunityTribute = item.original;
350 return `[${it.key}](${it.view.community.actor_id})`;
352 values: debounce(async (text: string, cb: any) => {
353 cb(await communitySearch(text));
356 autocompleteMode: true,
358 // menuItemLimit: mentionDropdownFetchLimit,
359 menuShowMinLength: 2,
365 interface EmojiMartCategory {
368 emojis: EmojiMartCustomEmoji[];
371 interface EmojiMartCustomEmoji {
375 skins: EmojiMartSkin[];
378 interface EmojiMartSkin {