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 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") {
82 const inlineTokens = 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 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);
102 // Determine the new 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);
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);
118 newTokens.push(linkOpenToken, textToken, linkCloseToken);
121 (match.index !== undefined ? match.index : 0) + match[0].length;
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);
131 // Replace the original token with the new tokens
132 inlineTokens.splice(j, 1, ...newTokens);
139 export function setupMarkdown() {
140 const markdownItConfig: MarkdownIt.Options = {
146 // const emojiDefs = Array.from(customEmojisLookup.entries()).reduce(
147 // (main, [key, value]) => ({ ...main, [key]: value }),
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, {
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, {
172 const defaultRenderer = md.renderer.rules.image;
173 md.renderer.rules.image = function (
176 options: MarkdownIt.Options,
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) ?? "";
188 const alt_text = item.content;
189 return `<img class="icon icon-emoji" src="${src}" title="${title}" alt="${alt_text}"/>`;
191 md.renderer.rules.table_open = function () {
192 return '<table class="table">';
196 export function setupEmojiDataModel(custom_emoji_views: CustomEmojiView[]) {
197 const groupedEmojis = groupBy(
199 x => x.custom_emoji.category
201 for (const [category, emojis] of Object.entries(groupedEmojis)) {
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 }],
213 customEmojisLookup = new Map(
214 custom_emoji_views.map(view => [view.custom_emoji.shortcode, view])
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 }],
225 const categoryIndex = customEmojis.findIndex(
226 x => x.id == custom_emoji_view.custom_emoji.category
228 if (categoryIndex == -1) {
230 id: custom_emoji_view.custom_emoji.category,
231 name: custom_emoji_view.custom_emoji.category,
235 const emojiIndex = customEmojis[categoryIndex].emojis.findIndex(
236 x => x.id == custom_emoji_view.custom_emoji.shortcode
238 if (emojiIndex == -1) {
239 customEmojis[categoryIndex].emojis.push(emoji);
241 customEmojis[categoryIndex].emojis[emojiIndex] = emoji;
244 customEmojisLookup.set(
245 custom_emoji_view.custom_emoji.shortcode,
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) {
259 const categoryIndex = customEmojis.findIndex(
260 x => x.id == view?.custom_emoji.category
262 const emojiIndex = customEmojis[categoryIndex].emojis.findIndex(
263 x => x.id == view?.custom_emoji.shortcode
265 customEmojis[categoryIndex].emojis = customEmojis[
267 ].emojis.splice(emojiIndex, 1);
269 customEmojisLookup.delete(view?.custom_emoji.shortcode);
272 export function getEmojiMart(
273 onEmojiSelect: (e: any) => void,
274 customPickerOptions: any = {}
276 const pickerOptions = {
277 ...customPickerOptions,
278 onEmojiSelect: onEmojiSelect,
279 custom: customEmojis,
281 return new Picker(pickerOptions);
284 export function setupTribute() {
286 noMatchTemplate: function () {
293 menuItemTemplate: (item: any) => {
294 const shortName = `:${item.original.key}:`;
295 return `${item.original.val} ${shortName}`;
297 selectTemplate: (item: any) => {
298 const customEmoji = customEmojisLookup.get(
301 if (customEmoji == undefined) return `${item.original.val}`;
303 return `![${customEmoji.alt_text}](${customEmoji.image_url} "${customEmoji.shortcode}")`;
305 values: Object.entries(emojiShortName)
307 return { key: e[1], val: e[0] };
310 Array.from(customEmojisLookup.entries()).map(k => ({
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}" />`,
316 autocompleteMode: true,
318 // menuItemLimit: mentionDropdownFetchLimit,
319 menuShowMinLength: 2,
324 selectTemplate: (item: any) => {
325 const it: PersonTribute = item.original;
326 return `[${it.key}](${it.view.person.actor_id})`;
328 values: debounce(async (text: string, cb: any) => {
329 cb(await personSearch(text));
332 autocompleteMode: true,
334 // menuItemLimit: mentionDropdownFetchLimit,
335 menuShowMinLength: 2,
341 selectTemplate: (item: any) => {
342 const it: CommunityTribute = item.original;
343 return `[${it.key}](${it.view.community.actor_id})`;
345 values: debounce(async (text: string, cb: any) => {
346 cb(await communitySearch(text));
349 autocompleteMode: true,
351 // menuItemLimit: mentionDropdownFetchLimit,
352 menuShowMinLength: 2,
358 interface EmojiMartCategory {
361 emojis: EmojiMartCustomEmoji[];
364 interface EmojiMartCustomEmoji {
368 skins: EmojiMartSkin[];
371 interface EmojiMartSkin {