1 import { Picker } from "emoji-mart";
2 import emojiShortName from "emoji-short-name";
4 BlockCommunityResponse,
7 CommentNode as CommentNodeI,
11 CommunityModeratorView,
24 PrivateMessageReportView,
26 RegistrationApplicationView,
31 } from "lemmy-js-client";
32 import { default as MarkdownIt } from "markdown-it";
33 import markdown_it_container from "markdown-it-container";
34 import markdown_it_emoji from "markdown-it-emoji/bare";
35 import markdown_it_footnote from "markdown-it-footnote";
36 import markdown_it_html5_embed from "markdown-it-html5-embed";
37 import markdown_it_sub from "markdown-it-sub";
38 import markdown_it_sup from "markdown-it-sup";
39 import Renderer from "markdown-it/lib/renderer";
40 import Token from "markdown-it/lib/token";
41 import moment from "moment";
42 import { Subscription } from "rxjs";
43 import { delay, retryWhen, take } from "rxjs/operators";
44 import tippy from "tippy.js";
45 import Toastify from "toastify-js";
46 import { httpBase } from "./env";
47 import { i18n, languages } from "./i18next";
48 import { DataType, IsoData } from "./interfaces";
49 import { UserService, WebSocketService } from "./services";
53 Tribute = require("tributejs");
56 export const wsClient = new LemmyWebsocket();
58 export const favIconUrl = "/static/assets/icons/favicon.svg";
59 export const favIconPngUrl = "/static/assets/icons/apple-touch-icon.png";
61 // export const defaultFavIcon = `${window.location.protocol}//${window.location.host}${favIconPngUrl}`;
62 export const repoUrl = "https://github.com/LemmyNet";
63 export const joinLemmyUrl = "https://join-lemmy.org";
64 export const donateLemmyUrl = `${joinLemmyUrl}/donate`;
65 export const docsUrl = `${joinLemmyUrl}/docs/en/index.html`;
66 export const helpGuideUrl = `${joinLemmyUrl}/docs/en/about/guide.html`; // TODO find a way to redirect to the non-en folder
67 export const markdownHelpUrl = `${helpGuideUrl}#using-markdown`;
68 export const sortingHelpUrl = `${helpGuideUrl}#sorting`;
69 export const archiveTodayUrl = "https://archive.today";
70 export const ghostArchiveUrl = "https://ghostarchive.org";
71 export const webArchiveUrl = "https://web.archive.org";
72 export const elementUrl = "https://element.io";
74 export const postRefetchSeconds: number = 60 * 1000;
75 export const fetchLimit = 40;
76 export const trendingFetchLimit = 6;
77 export const mentionDropdownFetchLimit = 10;
78 export const commentTreeMaxDepth = 8;
79 export const markdownFieldCharacterLimit = 50000;
80 export const maxUploadImages = 20;
81 export const concurrentImageUpload = 4;
83 export const relTags = "noopener nofollow";
85 export type ThemeColor =
108 let customEmojis: EmojiMartCategory[] = [];
109 export let customEmojisLookup: Map<string, CustomEmojiView> = new Map<
114 const DEFAULT_ALPHABET =
115 "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
117 function getRandomCharFromAlphabet(alphabet: string): string {
118 return alphabet.charAt(Math.floor(Math.random() * alphabet.length));
121 export function randomStr(
122 idDesiredLength = 20,
123 alphabet = DEFAULT_ALPHABET
126 * Create n-long array and map it to random chars from given alphabet.
127 * Then join individual chars as string
129 return Array.from({ length: idDesiredLength })
131 return getRandomCharFromAlphabet(alphabet);
136 const html5EmbedConfig = {
138 useImageSyntax: true, // Enables video/audio embed with ![]() syntax (default)
140 audio: 'controls preload="metadata"',
141 video: 'width="100%" max-height="100%" controls loop preload="metadata"',
146 const spoilerConfig = {
147 validate: (params: string) => {
148 return params.trim().match(/^spoiler\s+(.*)$/);
151 render: (tokens: any, idx: any) => {
152 var m = tokens[idx].info.trim().match(/^spoiler\s+(.*)$/);
154 if (tokens[idx].nesting === 1) {
156 return `<details><summary> ${md.utils.escapeHtml(m[1])} </summary>\n`;
159 return "</details>\n";
164 export let md: MarkdownIt = new MarkdownIt();
166 export let mdNoImages: MarkdownIt = new MarkdownIt();
168 export function hotRankComment(comment_view: CommentView): number {
169 return hotRank(comment_view.counts.score, comment_view.comment.published);
172 export function hotRankActivePost(post_view: PostView): number {
173 return hotRank(post_view.counts.score, post_view.counts.newest_comment_time);
176 export function hotRankPost(post_view: PostView): number {
177 return hotRank(post_view.counts.score, post_view.post.published);
180 export function hotRank(score: number, timeStr: string): number {
181 // Rank = ScaleFactor * sign(Score) * log(1 + abs(Score)) / (Time + 2)^Gravity
182 let date: Date = new Date(timeStr + "Z"); // Add Z to convert from UTC date
183 let now: Date = new Date();
184 let hoursElapsed: number = (now.getTime() - date.getTime()) / 36e5;
187 (10000 * Math.log10(Math.max(1, 3 + score))) /
188 Math.pow(hoursElapsed + 2, 1.8);
190 // console.log(`Comment: ${comment.content}\nRank: ${rank}\nScore: ${comment.score}\nHours: ${hoursElapsed}`);
195 export function mdToHtml(text: string) {
196 return { __html: md.render(text) };
199 export function mdToHtmlNoImages(text: string) {
200 return { __html: mdNoImages.render(text) };
203 export function mdToHtmlInline(text: string) {
204 return { __html: md.renderInline(text) };
207 export function getUnixTime(text?: string): number | undefined {
208 return text ? new Date(text).getTime() / 1000 : undefined;
211 export function futureDaysToUnixTime(days?: number): number | undefined {
214 new Date(Date.now() + 1000 * 60 * 60 * 24 * days).getTime() / 1000
219 export function canMod(
221 mods?: CommunityModeratorView[],
222 admins?: PersonViewSafe[],
223 myUserInfo = UserService.Instance.myUserInfo,
226 // You can do moderator actions only on the mods added after you.
229 ?.map(a => a.person.id)
230 .concat(mods?.map(m => m.moderator.id) ?? []) ?? [];
233 let myIndex = adminsThenMods.findIndex(
234 id => id == myUserInfo.local_user_view.person.id
239 // onSelf +1 on mod actions not for yourself, IE ban, remove, etc
240 adminsThenMods = adminsThenMods.slice(0, myIndex + (onSelf ? 0 : 1));
241 return !adminsThenMods.includes(creator_id);
248 export function canAdmin(
250 admins?: PersonViewSafe[],
251 myUserInfo = UserService.Instance.myUserInfo,
254 return canMod(creatorId, undefined, admins, myUserInfo, onSelf);
257 export function isMod(
259 mods?: CommunityModeratorView[]
261 return mods?.map(m => m.moderator.id).includes(creatorId) ?? false;
264 export function amMod(
265 mods?: CommunityModeratorView[],
266 myUserInfo = UserService.Instance.myUserInfo
268 return myUserInfo ? isMod(myUserInfo.local_user_view.person.id, mods) : false;
271 export function isAdmin(creatorId: number, admins?: PersonViewSafe[]): boolean {
272 return admins?.map(a => a.person.id).includes(creatorId) ?? false;
275 export function amAdmin(myUserInfo = UserService.Instance.myUserInfo): boolean {
276 return myUserInfo?.local_user_view.person.admin ?? false;
279 export function amCommunityCreator(
281 mods?: CommunityModeratorView[],
282 myUserInfo = UserService.Instance.myUserInfo
284 let myId = myUserInfo?.local_user_view.person.id;
285 // Don't allow mod actions on yourself
286 return myId == mods?.at(0)?.moderator.id && myId != creator_id;
289 export function amSiteCreator(
291 admins?: PersonViewSafe[],
292 myUserInfo = UserService.Instance.myUserInfo
294 let myId = myUserInfo?.local_user_view.person.id;
295 return myId == admins?.at(0)?.person.id && myId != creator_id;
298 export function amTopMod(
299 mods: CommunityModeratorView[],
300 myUserInfo = UserService.Instance.myUserInfo
302 return mods.at(0)?.moderator.id == myUserInfo?.local_user_view.person.id;
305 const imageRegex = /(http)?s?:?(\/\/[^"']*\.(?:jpg|jpeg|gif|png|svg|webp))/;
306 const videoRegex = /(http)?s?:?(\/\/[^"']*\.(?:mp4|webm))/;
308 export function isImage(url: string) {
309 return imageRegex.test(url);
312 export function isVideo(url: string) {
313 return videoRegex.test(url);
316 export function validURL(str: string) {
317 return !!new URL(str);
320 export function communityRSSUrl(actorId: string, sort: string): string {
321 let url = new URL(actorId);
322 return `${url.origin}/feeds${url.pathname}.xml?sort=${sort}`;
325 export function validEmail(email: string) {
327 /^(([^\s"(),.:;<>@[\\\]]+(\.[^\s"(),.:;<>@[\\\]]+)*)|(".+"))@((\[(?:\d{1,3}\.){3}\d{1,3}])|(([\dA-Za-z\-]+\.)+[A-Za-z]{2,}))$/;
328 return re.test(String(email).toLowerCase());
331 export function capitalizeFirstLetter(str: string): string {
332 return str.charAt(0).toUpperCase() + str.slice(1);
335 export function routeSortTypeToEnum(sort: string): SortType {
336 return SortType[sort];
339 export function listingTypeFromNum(type_: number): ListingType {
340 return Object.values(ListingType)[type_];
343 export function sortTypeFromNum(type_: number): SortType {
344 return Object.values(SortType)[type_];
347 export function routeListingTypeToEnum(type: string): ListingType {
348 return ListingType[type];
351 export function routeDataTypeToEnum(type: string): DataType {
352 return DataType[capitalizeFirstLetter(type)];
355 export function routeSearchTypeToEnum(type: string): SearchType {
356 return SearchType[type];
359 export async function getSiteMetadata(url: string) {
360 let form: GetSiteMetadata = { url };
361 let client = new LemmyHttp(httpBase);
362 return client.getSiteMetadata(form);
365 export function debounce(func: any, wait = 1000, immediate = false) {
366 // 'private' variable for instance
367 // The returned function will be able to reference this due to closure.
368 // Each call to the returned function will share this common timer.
371 // Calling debounce returns a new anonymous function
373 // reference the context and args for the setTimeout function
374 var args = arguments;
376 // Should the function be called now? If immediate is true
377 // and not already in a timeout then the answer is: Yes
378 var callNow = immediate && !timeout;
380 // This is the basic debounce behaviour where you can call this
381 // function several times, but it will only execute once
382 // [before or after imposing a delay].
383 // Each time the returned function is called, the timer starts over.
384 clearTimeout(timeout);
386 // Set the new timeout
387 timeout = setTimeout(function () {
388 // Inside the timeout function, clear the timeout variable
389 // which will let the next execution run when in 'immediate' mode
392 // Check if the function already ran with the immediate flag
394 // Call the original function with apply
395 // apply lets you define the 'this' object as well as the arguments
396 // (both captured before setTimeout)
397 func.apply(this, args);
401 // Immediate mode and no wait timer? Execute the function..
402 if (callNow) func.apply(this, args);
406 export function getLanguages(
408 myUserInfo = UserService.Instance.myUserInfo
410 let myLang = myUserInfo?.local_user_view.local_user.interface_language;
411 let lang = override || myLang || "browser";
413 if (lang == "browser" && isBrowser()) {
414 return getBrowserLanguages();
420 function getBrowserLanguages(): string[] {
421 // Intersect lemmy's langs, with the browser langs
422 let langs = languages ? languages.map(l => l.code) : ["en"];
424 // NOTE, mobile browsers seem to be missing this list, so append en
425 let allowedLangs = navigator.languages
427 .filter(v => langs.includes(v));
431 export async function fetchThemeList(): Promise<string[]> {
432 return fetch("/css/themelist").then(res => res.json());
435 export async function setTheme(theme: string, forceReload = false) {
439 if (theme === "browser" && !forceReload) {
442 // This is only run on a force reload
443 if (theme == "browser") {
447 let themeList = await fetchThemeList();
449 // Unload all the other themes
450 for (var i = 0; i < themeList.length; i++) {
451 let styleSheet = document.getElementById(themeList[i]);
453 styleSheet.setAttribute("disabled", "disabled");
458 .getElementById("default-light")
459 ?.setAttribute("disabled", "disabled");
460 document.getElementById("default-dark")?.setAttribute("disabled", "disabled");
462 // Load the theme dynamically
463 let cssLoc = `/css/themes/${theme}.css`;
465 loadCss(theme, cssLoc);
466 document.getElementById(theme)?.removeAttribute("disabled");
469 export function loadCss(id: string, loc: string) {
470 if (!document.getElementById(id)) {
471 var head = document.getElementsByTagName("head")[0];
472 var link = document.createElement("link");
474 link.rel = "stylesheet";
475 link.type = "text/css";
478 head.appendChild(link);
482 export function objectFlip(obj: any) {
484 Object.keys(obj).forEach(key => {
490 export function showAvatars(
491 myUserInfo = UserService.Instance.myUserInfo
493 return myUserInfo?.local_user_view.local_user.show_avatars ?? true;
496 export function showScores(
497 myUserInfo = UserService.Instance.myUserInfo
499 return myUserInfo?.local_user_view.local_user.show_scores ?? true;
502 export function isCakeDay(published: string): boolean {
503 // moment(undefined) or moment.utc(undefined) returns the current date/time
504 // moment(null) or moment.utc(null) returns null
505 const createDate = moment.utc(published).local();
506 const currentDate = moment(new Date());
509 createDate.date() === currentDate.date() &&
510 createDate.month() === currentDate.month() &&
511 createDate.year() !== currentDate.year()
515 export function toast(text: string, background: ThemeColor = "success") {
517 const backgroundColor = `var(--${background})`;
520 backgroundColor: backgroundColor,
528 export function pictrsDeleteToast(filename: string, deleteUrl: string) {
530 const clickToDeleteText = i18n.t("click_to_delete_picture", { filename });
531 const deletePictureText = i18n.t("picture_deleted", {
534 const failedDeletePictureText = i18n.t("failed_to_delete_picture", {
538 const backgroundColor = `var(--light)`;
540 const toast = Toastify({
541 text: clickToDeleteText,
542 backgroundColor: backgroundColor,
548 fetch(deleteUrl).then(res => {
550 if (res.ok === true) {
551 alert(deletePictureText);
553 alert(failedDeletePictureText);
565 interface NotifyInfo {
572 export function messageToastify(info: NotifyInfo, router: any) {
574 let htmlBody = info.body ? md.render(info.body) : "";
575 let backgroundColor = `var(--light)`;
577 let toast = Toastify({
578 text: `${htmlBody}<br />${info.name}`,
580 backgroundColor: backgroundColor,
581 className: "text-dark",
590 router.history.push(info.link);
598 export function notifyPost(post_view: PostView, router: any) {
599 let info: NotifyInfo = {
600 name: post_view.community.name,
601 icon: post_view.community.icon,
602 link: `/post/${post_view.post.id}`,
603 body: post_view.post.name,
605 notify(info, router);
608 export function notifyComment(comment_view: CommentView, router: any) {
609 let info: NotifyInfo = {
610 name: comment_view.creator.name,
611 icon: comment_view.creator.avatar,
612 link: `/comment/${comment_view.comment.id}`,
613 body: comment_view.comment.content,
615 notify(info, router);
618 export function notifyPrivateMessage(pmv: PrivateMessageView, router: any) {
619 let info: NotifyInfo = {
620 name: pmv.creator.name,
621 icon: pmv.creator.avatar,
623 body: pmv.private_message.content,
625 notify(info, router);
628 function notify(info: NotifyInfo, router: any) {
629 messageToastify(info, router);
631 if (Notification.permission !== "granted") Notification.requestPermission();
633 var notification = new Notification(info.name, {
634 ...{ body: info.body },
635 ...(info.icon && { icon: info.icon }),
638 notification.onclick = (ev: Event): any => {
640 router.history.push(info.link);
645 export function setupTribute() {
647 noMatchTemplate: function () {
654 menuItemTemplate: (item: any) => {
655 let shortName = `:${item.original.key}:`;
656 return `${item.original.val} ${shortName}`;
658 selectTemplate: (item: any) => {
659 let customEmoji = customEmojisLookup.get(
662 if (customEmoji == undefined) return `${item.original.val}`;
664 return `![${customEmoji.alt_text}](${customEmoji.image_url} "${customEmoji.shortcode}")`;
666 values: Object.entries(emojiShortName)
668 return { key: e[1], val: e[0] };
671 Array.from(customEmojisLookup.entries()).map(k => ({
673 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}" />`,
677 autocompleteMode: true,
679 // menuItemLimit: mentionDropdownFetchLimit,
680 menuShowMinLength: 2,
685 selectTemplate: (item: any) => {
686 let it: PersonTribute = item.original;
687 return `[${it.key}](${it.view.person.actor_id})`;
689 values: debounce(async (text: string, cb: any) => {
690 cb(await personSearch(text));
693 autocompleteMode: true,
695 // menuItemLimit: mentionDropdownFetchLimit,
696 menuShowMinLength: 2,
702 selectTemplate: (item: any) => {
703 let it: CommunityTribute = item.original;
704 return `[${it.key}](${it.view.community.actor_id})`;
706 values: debounce(async (text: string, cb: any) => {
707 cb(await communitySearch(text));
710 autocompleteMode: true,
712 // menuItemLimit: mentionDropdownFetchLimit,
713 menuShowMinLength: 2,
719 function setupEmojiDataModel(custom_emoji_views: CustomEmojiView[]) {
720 let groupedEmojis = groupBy(custom_emoji_views, x => x.custom_emoji.category);
721 for (const [category, emojis] of Object.entries(groupedEmojis)) {
725 emojis: emojis.map(emoji => ({
726 id: emoji.custom_emoji.shortcode,
727 name: emoji.custom_emoji.shortcode,
728 keywords: emoji.keywords.map(x => x.keyword),
729 skins: [{ src: emoji.custom_emoji.image_url }],
733 customEmojisLookup = new Map(
734 custom_emoji_views.map(view => [view.custom_emoji.shortcode, view])
738 export function updateEmojiDataModel(custom_emoji_view: CustomEmojiView) {
739 const emoji: EmojiMartCustomEmoji = {
740 id: custom_emoji_view.custom_emoji.shortcode,
741 name: custom_emoji_view.custom_emoji.shortcode,
742 keywords: custom_emoji_view.keywords.map(x => x.keyword),
743 skins: [{ src: custom_emoji_view.custom_emoji.image_url }],
745 let categoryIndex = customEmojis.findIndex(
746 x => x.id == custom_emoji_view.custom_emoji.category
748 if (categoryIndex == -1) {
750 id: custom_emoji_view.custom_emoji.category,
751 name: custom_emoji_view.custom_emoji.category,
755 let emojiIndex = customEmojis[categoryIndex].emojis.findIndex(
756 x => x.id == custom_emoji_view.custom_emoji.shortcode
758 if (emojiIndex == -1) {
759 customEmojis[categoryIndex].emojis.push(emoji);
761 customEmojis[categoryIndex].emojis[emojiIndex] = emoji;
764 customEmojisLookup.set(
765 custom_emoji_view.custom_emoji.shortcode,
770 export function removeFromEmojiDataModel(id: number) {
771 let view: CustomEmojiView | undefined;
772 for (let item of customEmojisLookup.values()) {
773 if (item.custom_emoji.id === id) {
779 const categoryIndex = customEmojis.findIndex(
780 x => x.id == view?.custom_emoji.category
782 const emojiIndex = customEmojis[categoryIndex].emojis.findIndex(
783 x => x.id == view?.custom_emoji.shortcode
785 customEmojis[categoryIndex].emojis = customEmojis[
787 ].emojis.splice(emojiIndex, 1);
789 customEmojisLookup.delete(view?.custom_emoji.shortcode);
792 function setupMarkdown() {
793 const markdownItConfig: MarkdownIt.Options = {
799 const emojiDefs = Array.from(customEmojisLookup.entries()).reduce(
800 (main, [key, value]) => ({ ...main, [key]: value }),
803 md = new MarkdownIt(markdownItConfig)
804 .use(markdown_it_sub)
805 .use(markdown_it_sup)
806 .use(markdown_it_footnote)
807 .use(markdown_it_html5_embed, html5EmbedConfig)
808 .use(markdown_it_container, "spoiler", spoilerConfig)
809 .use(markdown_it_emoji, {
813 mdNoImages = new MarkdownIt(markdownItConfig)
814 .use(markdown_it_sub)
815 .use(markdown_it_sup)
816 .use(markdown_it_footnote)
817 .use(markdown_it_html5_embed, html5EmbedConfig)
818 .use(markdown_it_container, "spoiler", spoilerConfig)
819 .use(markdown_it_emoji, {
823 var defaultRenderer = md.renderer.rules.image;
824 md.renderer.rules.image = function (
827 options: MarkdownIt.Options,
831 //Provide custom renderer for our emojis to allow us to add a css class and force size dimensions on them.
832 const item = tokens[idx] as any;
833 const title = item.attrs.length >= 3 ? item.attrs[2][1] : "";
834 const src: string = item.attrs[0][1];
835 const isCustomEmoji = customEmojisLookup.get(title) != undefined;
836 if (!isCustomEmoji) {
837 return defaultRenderer?.(tokens, idx, options, env, self) ?? "";
839 const alt_text = item.content;
840 return `<img class="icon icon-emoji" src="${src}" title="${title}" alt="${alt_text}"/>`;
844 export function getEmojiMart(
845 onEmojiSelect: (e: any) => void,
846 customPickerOptions: any = {}
848 const pickerOptions = {
849 ...customPickerOptions,
850 onEmojiSelect: onEmojiSelect,
851 custom: customEmojis,
853 return new Picker(pickerOptions);
856 var tippyInstance: any;
858 tippyInstance = tippy("[data-tippy-content]");
861 export function setupTippy() {
863 tippyInstance.forEach((e: any) => e.destroy());
864 tippyInstance = tippy("[data-tippy-content]", {
866 // Display on "long press"
867 touch: ["hold", 500],
872 interface PersonTribute {
874 view: PersonViewSafe;
877 async function personSearch(text: string): Promise<PersonTribute[]> {
878 let users = (await fetchUsers(text)).users;
879 let persons: PersonTribute[] = users.map(pv => {
880 let tribute: PersonTribute = {
881 key: `@${pv.person.name}@${hostname(pv.person.actor_id)}`,
889 interface CommunityTribute {
894 async function communitySearch(text: string): Promise<CommunityTribute[]> {
895 let comms = (await fetchCommunities(text)).communities;
896 let communities: CommunityTribute[] = comms.map(cv => {
897 let tribute: CommunityTribute = {
898 key: `!${cv.community.name}@${hostname(cv.community.actor_id)}`,
906 export function getListingTypeFromProps(
908 defaultListingType: ListingType,
909 myUserInfo = UserService.Instance.myUserInfo
911 let myLt = myUserInfo?.local_user_view.local_user.default_listing_type;
912 return props.match.params.listing_type
913 ? routeListingTypeToEnum(props.match.params.listing_type)
915 ? Object.values(ListingType)[myLt]
916 : defaultListingType;
919 export function getListingTypeFromPropsNoDefault(props: any): ListingType {
920 return props.match.params.listing_type
921 ? routeListingTypeToEnum(props.match.params.listing_type)
925 export function getDataTypeFromProps(props: any): DataType {
926 return props.match.params.data_type
927 ? routeDataTypeToEnum(props.match.params.data_type)
931 export function getSortTypeFromProps(
933 myUserInfo = UserService.Instance.myUserInfo
935 let mySortType = myUserInfo?.local_user_view.local_user.default_sort_type;
936 return props.match.params.sort
937 ? routeSortTypeToEnum(props.match.params.sort)
939 ? Object.values(SortType)[mySortType]
943 export function getPageFromProps(props: any): number {
944 return props.match.params.page ? Number(props.match.params.page) : 1;
947 export function getRecipientIdFromProps(props: any): number {
948 return props.match.params.recipient_id
949 ? Number(props.match.params.recipient_id)
953 export function getIdFromProps(props: any): number | undefined {
954 let id = props.match.params.post_id;
955 return id ? Number(id) : undefined;
958 export function getCommentIdFromProps(props: any): number | undefined {
959 let id = props.match.params.comment_id;
960 return id ? Number(id) : undefined;
963 export function getUsernameFromProps(props: any): string {
964 return props.match.params.username;
967 export function editCommentRes(data: CommentView, comments?: CommentView[]) {
968 let found = comments?.find(c => c.comment.id == data.comment.id);
970 found.comment.content = data.comment.content;
971 found.comment.distinguished = data.comment.distinguished;
972 found.comment.updated = data.comment.updated;
973 found.comment.removed = data.comment.removed;
974 found.comment.deleted = data.comment.deleted;
975 found.counts.upvotes = data.counts.upvotes;
976 found.counts.downvotes = data.counts.downvotes;
977 found.counts.score = data.counts.score;
981 export function saveCommentRes(data: CommentView, comments?: CommentView[]) {
982 let found = comments?.find(c => c.comment.id == data.comment.id);
984 found.saved = data.saved;
988 export function updatePersonBlock(
989 data: BlockPersonResponse,
990 myUserInfo = UserService.Instance.myUserInfo
992 let mui = myUserInfo;
995 mui.person_blocks.push({
996 person: mui.local_user_view.person,
997 target: data.person_view.person,
999 toast(`${i18n.t("blocked")} ${data.person_view.person.name}`);
1001 mui.person_blocks = mui.person_blocks.filter(
1002 i => i.target.id != data.person_view.person.id
1004 toast(`${i18n.t("unblocked")} ${data.person_view.person.name}`);
1009 export function updateCommunityBlock(
1010 data: BlockCommunityResponse,
1011 myUserInfo = UserService.Instance.myUserInfo
1013 let mui = myUserInfo;
1016 mui.community_blocks.push({
1017 person: mui.local_user_view.person,
1018 community: data.community_view.community,
1020 toast(`${i18n.t("blocked")} ${data.community_view.community.name}`);
1022 mui.community_blocks = mui.community_blocks.filter(
1023 i => i.community.id != data.community_view.community.id
1025 toast(`${i18n.t("unblocked")} ${data.community_view.community.name}`);
1030 export function createCommentLikeRes(
1032 comments?: CommentView[]
1034 let found = comments?.find(c => c.comment.id === data.comment.id);
1036 found.counts.score = data.counts.score;
1037 found.counts.upvotes = data.counts.upvotes;
1038 found.counts.downvotes = data.counts.downvotes;
1039 if (data.my_vote !== null) {
1040 found.my_vote = data.my_vote;
1045 export function createPostLikeFindRes(data: PostView, posts?: PostView[]) {
1046 let found = posts?.find(p => p.post.id == data.post.id);
1048 createPostLikeRes(data, found);
1052 export function createPostLikeRes(data: PostView, post_view?: PostView) {
1054 post_view.counts.score = data.counts.score;
1055 post_view.counts.upvotes = data.counts.upvotes;
1056 post_view.counts.downvotes = data.counts.downvotes;
1057 if (data.my_vote !== null) {
1058 post_view.my_vote = data.my_vote;
1063 export function editPostFindRes(data: PostView, posts?: PostView[]) {
1064 let found = posts?.find(p => p.post.id == data.post.id);
1066 editPostRes(data, found);
1070 export function editPostRes(data: PostView, post: PostView) {
1072 post.post.url = data.post.url;
1073 post.post.name = data.post.name;
1074 post.post.nsfw = data.post.nsfw;
1075 post.post.deleted = data.post.deleted;
1076 post.post.removed = data.post.removed;
1077 post.post.featured_community = data.post.featured_community;
1078 post.post.featured_local = data.post.featured_local;
1079 post.post.body = data.post.body;
1080 post.post.locked = data.post.locked;
1081 post.saved = data.saved;
1085 // TODO possible to make these generic?
1086 export function updatePostReportRes(
1087 data: PostReportView,
1088 reports?: PostReportView[]
1090 let found = reports?.find(p => p.post_report.id == data.post_report.id);
1092 found.post_report = data.post_report;
1096 export function updateCommentReportRes(
1097 data: CommentReportView,
1098 reports?: CommentReportView[]
1100 let found = reports?.find(c => c.comment_report.id == data.comment_report.id);
1102 found.comment_report = data.comment_report;
1106 export function updatePrivateMessageReportRes(
1107 data: PrivateMessageReportView,
1108 reports?: PrivateMessageReportView[]
1110 let found = reports?.find(
1111 c => c.private_message_report.id == data.private_message_report.id
1114 found.private_message_report = data.private_message_report;
1118 export function updateRegistrationApplicationRes(
1119 data: RegistrationApplicationView,
1120 applications?: RegistrationApplicationView[]
1122 let found = applications?.find(
1123 ra => ra.registration_application.id == data.registration_application.id
1126 found.registration_application = data.registration_application;
1127 found.admin = data.admin;
1128 found.creator_local_user = data.creator_local_user;
1132 export function commentsToFlatNodes(comments: CommentView[]): CommentNodeI[] {
1133 let nodes: CommentNodeI[] = [];
1134 for (let comment of comments) {
1135 nodes.push({ comment_view: comment, children: [], depth: 0 });
1140 export function convertCommentSortType(sort: SortType): CommentSortType {
1142 sort == SortType.TopAll ||
1143 sort == SortType.TopDay ||
1144 sort == SortType.TopWeek ||
1145 sort == SortType.TopMonth ||
1146 sort == SortType.TopYear
1148 return CommentSortType.Top;
1149 } else if (sort == SortType.New) {
1150 return CommentSortType.New;
1151 } else if (sort == SortType.Hot || sort == SortType.Active) {
1152 return CommentSortType.Hot;
1154 return CommentSortType.Hot;
1158 export function buildCommentsTree(
1159 comments: CommentView[],
1160 parentComment: boolean
1162 let map = new Map<number, CommentNodeI>();
1163 let depthOffset = !parentComment
1165 : getDepthFromComment(comments[0].comment) ?? 0;
1167 for (let comment_view of comments) {
1168 let depthI = getDepthFromComment(comment_view.comment) ?? 0;
1169 let depth = depthI ? depthI - depthOffset : 0;
1170 let node: CommentNodeI = {
1175 map.set(comment_view.comment.id, { ...node });
1178 let tree: CommentNodeI[] = [];
1180 // if its a parent comment fetch, then push the first comment to the top node.
1181 if (parentComment) {
1182 let cNode = map.get(comments[0].comment.id);
1188 for (let comment_view of comments) {
1189 let child = map.get(comment_view.comment.id);
1191 let parent_id = getCommentParentId(comment_view.comment);
1193 let parent = map.get(parent_id);
1194 // Necessary because blocked comment might not exist
1196 parent.children.push(child);
1199 if (!parentComment) {
1209 export function getCommentParentId(comment?: CommentI): number | undefined {
1210 let split = comment?.path.split(".");
1214 return split && split.length > 1
1215 ? Number(split.at(split.length - 2))
1219 export function getDepthFromComment(comment?: CommentI): number | undefined {
1220 let len = comment?.path.split(".").length;
1221 return len ? len - 2 : undefined;
1224 export function insertCommentIntoTree(
1225 tree: CommentNodeI[],
1227 parentComment: boolean
1229 // Building a fake node to be used for later
1230 let node: CommentNodeI = {
1236 let parentId = getCommentParentId(cv.comment);
1238 let parent_comment = searchCommentTree(tree, parentId);
1239 if (parent_comment) {
1240 node.depth = parent_comment.depth + 1;
1241 parent_comment.children.unshift(node);
1243 } else if (!parentComment) {
1248 export function searchCommentTree(
1249 tree: CommentNodeI[],
1251 ): CommentNodeI | undefined {
1252 for (let node of tree) {
1253 if (node.comment_view.comment.id === id) {
1257 for (const child of node.children) {
1258 let res = searchCommentTree([child], id);
1268 export const colorList: string[] = [
1278 function hsl(num: number) {
1279 return `hsla(${num}, 35%, 50%, 1)`;
1282 export function hostname(url: string): string {
1283 let cUrl = new URL(url);
1284 return cUrl.port ? `${cUrl.hostname}:${cUrl.port}` : `${cUrl.hostname}`;
1287 export function validTitle(title?: string): boolean {
1288 // Initial title is null, minimum length is taken care of by textarea's minLength={3}
1289 if (!title || title.length < 3) return true;
1291 const regex = new RegExp(/.*\S.*/, "g");
1293 return regex.test(title);
1296 export function siteBannerCss(banner: string): string {
1298 background-image: linear-gradient( rgba(0, 0, 0, 0.8), rgba(0, 0, 0, 0.8) ) ,url("${banner}"); \
1299 background-attachment: fixed; \
1300 background-position: top; \
1301 background-repeat: no-repeat; \
1302 background-size: 100% cover; \
1305 max-height: 100vh; \
1309 export function isBrowser() {
1310 return typeof window !== "undefined";
1313 export function setIsoData(context: any): IsoData {
1314 // If its the browser, you need to deserialize the data from the window
1316 let json = window.isoData;
1317 let routeData = json.routeData;
1318 let site_res = json.site_res;
1320 let isoData: IsoData = {
1326 } else return context.router.staticContext;
1329 export function wsSubscribe(parseMessage: any): Subscription | undefined {
1331 return WebSocketService.Instance.subject
1332 .pipe(retryWhen(errors => errors.pipe(delay(3000), take(10))))
1334 msg => parseMessage(msg),
1335 err => console.error(err),
1336 () => console.log("complete")
1343 moment.updateLocale("en", {
1364 export function saveScrollPosition(context: any) {
1365 let path: string = context.router.route.location.pathname;
1366 let y = window.scrollY;
1367 sessionStorage.setItem(`scrollPosition_${path}`, y.toString());
1370 export function restoreScrollPosition(context: any) {
1371 let path: string = context.router.route.location.pathname;
1372 let y = Number(sessionStorage.getItem(`scrollPosition_${path}`));
1373 window.scrollTo(0, y);
1376 export function showLocal(isoData: IsoData): boolean {
1377 let linked = isoData.site_res.federated_instances?.linked;
1378 return linked ? linked.length > 0 : false;
1381 export interface ChoicesValue {
1386 export function communityToChoice(cv: CommunityView): ChoicesValue {
1387 let choice: ChoicesValue = {
1388 value: cv.community.id.toString(),
1389 label: communitySelectName(cv),
1394 export function personToChoice(pvs: PersonViewSafe): ChoicesValue {
1395 let choice: ChoicesValue = {
1396 value: pvs.person.id.toString(),
1397 label: personSelectName(pvs),
1402 export async function fetchCommunities(q: string) {
1403 let form: Search = {
1405 type_: SearchType.Communities,
1406 sort: SortType.TopAll,
1407 listing_type: ListingType.All,
1410 auth: myAuth(false),
1412 let client = new LemmyHttp(httpBase);
1413 return client.search(form);
1416 export async function fetchUsers(q: string) {
1417 let form: Search = {
1419 type_: SearchType.Users,
1420 sort: SortType.TopAll,
1421 listing_type: ListingType.All,
1424 auth: myAuth(false),
1426 let client = new LemmyHttp(httpBase);
1427 return client.search(form);
1430 export const choicesConfig = {
1432 searchResultLimit: fetchLimit,
1434 containerOuter: "choices custom-select px-0",
1436 "choices__inner bg-secondary border-0 py-0 modlog-choices-font-size",
1437 input: "form-control",
1438 inputCloned: "choices__input--cloned",
1439 list: "choices__list",
1440 listItems: "choices__list--multiple",
1441 listSingle: "choices__list--single py-0",
1442 listDropdown: "choices__list--dropdown",
1443 item: "choices__item bg-secondary",
1444 itemSelectable: "choices__item--selectable",
1445 itemDisabled: "choices__item--disabled",
1446 itemChoice: "choices__item--choice",
1447 placeholder: "choices__placeholder",
1448 group: "choices__group",
1449 groupHeading: "choices__heading",
1450 button: "choices__button",
1451 activeState: "is-active",
1452 focusState: "is-focused",
1453 openState: "is-open",
1454 disabledState: "is-disabled",
1455 highlightedState: "text-info",
1456 selectedState: "text-info",
1457 flippedState: "is-flipped",
1458 loadingState: "is-loading",
1459 noResults: "has-no-results",
1460 noChoices: "has-no-choices",
1464 export function communitySelectName(cv: CommunityView): string {
1465 return cv.community.local
1466 ? cv.community.title
1467 : `${hostname(cv.community.actor_id)}/${cv.community.title}`;
1470 export function personSelectName(pvs: PersonViewSafe): string {
1471 let pName = pvs.person.display_name ?? pvs.person.name;
1472 return pvs.person.local ? pName : `${hostname(pvs.person.actor_id)}/${pName}`;
1475 export function initializeSite(site: GetSiteResponse) {
1476 UserService.Instance.myUserInfo = site.my_user;
1477 i18n.changeLanguage(getLanguages()[0]);
1478 setupEmojiDataModel(site.custom_emojis);
1482 const SHORTNUM_SI_FORMAT = new Intl.NumberFormat("en-US", {
1483 maximumSignificantDigits: 3,
1485 notation: "compact",
1486 compactDisplay: "short",
1489 export function numToSI(value: number): string {
1490 return SHORTNUM_SI_FORMAT.format(value);
1493 export function isBanned(ps: PersonSafe): boolean {
1494 let expires = ps.ban_expires;
1495 // Add Z to convert from UTC date
1496 // TODO this check probably isn't necessary anymore
1498 if (ps.banned && new Date(expires + "Z") > new Date()) {
1508 export function pushNotNull(array: any[], new_item?: any) {
1510 array.push(...new_item);
1514 export function myAuth(throwErr = true): string | undefined {
1515 return UserService.Instance.auth(throwErr);
1518 export function enableDownvotes(siteRes: GetSiteResponse): boolean {
1519 return siteRes.site_view.local_site.enable_downvotes;
1522 export function enableNsfw(siteRes: GetSiteResponse): boolean {
1523 return siteRes.site_view.local_site.enable_nsfw;
1526 export function postToCommentSortType(sort: SortType): CommentSortType {
1527 if ([SortType.Active, SortType.Hot].includes(sort)) {
1528 return CommentSortType.Hot;
1529 } else if ([SortType.New, SortType.NewComments].includes(sort)) {
1530 return CommentSortType.New;
1531 } else if (sort == SortType.Old) {
1532 return CommentSortType.Old;
1534 return CommentSortType.Top;
1538 export function myFirstDiscussionLanguageId(
1539 allLanguages: Language[],
1540 siteLanguages: number[],
1541 myUserInfo = UserService.Instance.myUserInfo
1542 ): number | undefined {
1543 return selectableLanguages(
1552 export function canCreateCommunity(
1553 siteRes: GetSiteResponse,
1554 myUserInfo = UserService.Instance.myUserInfo
1556 let adminOnly = siteRes.site_view.local_site.community_creation_admin_only;
1557 return !adminOnly || amAdmin(myUserInfo);
1560 export function isPostBlocked(
1562 myUserInfo = UserService.Instance.myUserInfo
1565 (myUserInfo?.community_blocks
1566 .map(c => c.community.id)
1567 .includes(pv.community.id) ||
1568 myUserInfo?.person_blocks
1569 .map(p => p.target.id)
1570 .includes(pv.creator.id)) ??
1575 /// Checks to make sure you can view NSFW posts. Returns true if you can.
1576 export function nsfwCheck(
1578 myUserInfo = UserService.Instance.myUserInfo
1580 let nsfw = pv.post.nsfw || pv.community.nsfw;
1581 let myShowNsfw = myUserInfo?.local_user_view.local_user.show_nsfw ?? false;
1582 return !nsfw || (nsfw && myShowNsfw);
1585 export function getRandomFromList<T>(list: T[]): T | undefined {
1586 return list.length == 0
1588 : list.at(Math.floor(Math.random() * list.length));
1592 * This shows what language you can select
1594 * Use showAll for the site form
1595 * Use showSite for the profile and community forms
1596 * Use false for both those to filter on your profile and site ones
1598 export function selectableLanguages(
1599 allLanguages: Language[],
1600 siteLanguages: number[],
1603 myUserInfo = UserService.Instance.myUserInfo
1605 let allLangIds = allLanguages.map(l => l.id);
1606 let myLangs = myUserInfo?.discussion_languages ?? allLangIds;
1607 myLangs = myLangs.length == 0 ? allLangIds : myLangs;
1608 let siteLangs = siteLanguages.length == 0 ? allLangIds : siteLanguages;
1611 return allLanguages;
1614 return allLanguages.filter(x => siteLangs.includes(x.id));
1617 .filter(x => siteLangs.includes(x.id))
1618 .filter(x => myLangs.includes(x.id));
1623 export function uploadImage(image: File): Promise<UploadImageResponse> {
1624 const client = new LemmyHttp(httpBase);
1626 return client.uploadImage({ image });
1629 interface EmojiMartCategory {
1632 emojis: EmojiMartCustomEmoji[];
1635 interface EmojiMartCustomEmoji {
1639 skins: EmojiMartSkin[];
1642 interface EmojiMartSkin {
1646 const groupBy = <T>(
1648 predicate: (value: T, index: number, array: T[]) => string
1650 array.reduce((acc, value, index, array) => {
1651 (acc[predicate(value, index, array)] ||= []).push(value);
1653 }, {} as { [key: string]: T[] });