1 import { Picker } from "emoji-mart";
2 import emojiShortName from "emoji-short-name";
4 BlockCommunityResponse,
10 CommunityModeratorView,
23 PrivateMessageReportView,
25 RegistrationApplicationView,
29 } from "lemmy-js-client";
30 import { default as MarkdownIt } from "markdown-it";
31 import markdown_it_container from "markdown-it-container";
32 import markdown_it_emoji from "markdown-it-emoji/bare";
33 import markdown_it_footnote from "markdown-it-footnote";
34 import markdown_it_html5_embed from "markdown-it-html5-embed";
35 import markdown_it_sub from "markdown-it-sub";
36 import markdown_it_sup from "markdown-it-sup";
37 import Renderer from "markdown-it/lib/renderer";
38 import Token from "markdown-it/lib/token";
39 import moment from "moment";
40 import { Subscription } from "rxjs";
41 import { delay, retryWhen, take } from "rxjs/operators";
42 import tippy from "tippy.js";
43 import Toastify from "toastify-js";
44 import { getHttpBase } from "./env";
45 import { i18n, languages } from "./i18next";
46 import { CommentNodeI, DataType, IsoData } from "./interfaces";
47 import { UserService, WebSocketService } from "./services";
51 Tribute = require("tributejs");
54 export const wsClient = new LemmyWebsocket();
56 export const favIconUrl = "/static/assets/icons/favicon.svg";
57 export const favIconPngUrl = "/static/assets/icons/apple-touch-icon.png";
59 // export const defaultFavIcon = `${window.location.protocol}//${window.location.host}${favIconPngUrl}`;
60 export const repoUrl = "https://github.com/LemmyNet";
61 export const joinLemmyUrl = "https://join-lemmy.org";
62 export const donateLemmyUrl = `${joinLemmyUrl}/donate`;
63 export const docsUrl = `${joinLemmyUrl}/docs/en/index.html`;
64 export const helpGuideUrl = `${joinLemmyUrl}/docs/en/users/01-getting-started.html`; // TODO find a way to redirect to the non-en folder
65 export const markdownHelpUrl = `${joinLemmyUrl}/docs/en/users/02-media.html`;
66 export const sortingHelpUrl = `${helpGuideUrl}/docs/en/users/03-votes-and-ranking.html`;
67 export const archiveTodayUrl = "https://archive.today";
68 export const ghostArchiveUrl = "https://ghostarchive.org";
69 export const webArchiveUrl = "https://web.archive.org";
70 export const elementUrl = "https://element.io";
72 export const postRefetchSeconds: number = 60 * 1000;
73 export const fetchLimit = 40;
74 export const trendingFetchLimit = 6;
75 export const mentionDropdownFetchLimit = 10;
76 export const commentTreeMaxDepth = 8;
77 export const markdownFieldCharacterLimit = 50000;
78 export const maxUploadImages = 20;
79 export const concurrentImageUpload = 4;
81 export const relTags = "noopener nofollow";
83 export const emDash = "\u2014";
85 export type ThemeColor =
108 export interface ErrorPageData {
111 adminMatrixIds?: string[];
114 let customEmojis: EmojiMartCategory[] = [];
115 export let customEmojisLookup: Map<string, CustomEmojiView> = new Map<
120 const DEFAULT_ALPHABET =
121 "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
123 function getRandomCharFromAlphabet(alphabet: string): string {
124 return alphabet.charAt(Math.floor(Math.random() * alphabet.length));
127 export function getIdFromString(id?: string): number | undefined {
128 return id && id !== "0" && !Number.isNaN(Number(id)) ? Number(id) : undefined;
131 export function getPageFromString(page?: string): number {
132 return page && !Number.isNaN(Number(page)) ? Number(page) : 1;
135 export function randomStr(
136 idDesiredLength = 20,
137 alphabet = DEFAULT_ALPHABET
140 * Create n-long array and map it to random chars from given alphabet.
141 * Then join individual chars as string
143 return Array.from({ length: idDesiredLength })
145 return getRandomCharFromAlphabet(alphabet);
150 const html5EmbedConfig = {
152 useImageSyntax: true, // Enables video/audio embed with ![]() syntax (default)
154 audio: 'controls preload="metadata"',
155 video: 'width="100%" max-height="100%" controls loop preload="metadata"',
160 const spoilerConfig = {
161 validate: (params: string) => {
162 return params.trim().match(/^spoiler\s+(.*)$/);
165 render: (tokens: any, idx: any) => {
166 var m = tokens[idx].info.trim().match(/^spoiler\s+(.*)$/);
168 if (tokens[idx].nesting === 1) {
170 return `<details><summary> ${md.utils.escapeHtml(m[1])} </summary>\n`;
173 return "</details>\n";
178 export let md: MarkdownIt = new MarkdownIt();
180 export let mdNoImages: MarkdownIt = new MarkdownIt();
182 export function hotRankComment(comment_view: CommentView): number {
183 return hotRank(comment_view.counts.score, comment_view.comment.published);
186 export function hotRankActivePost(post_view: PostView): number {
187 return hotRank(post_view.counts.score, post_view.counts.newest_comment_time);
190 export function hotRankPost(post_view: PostView): number {
191 return hotRank(post_view.counts.score, post_view.post.published);
194 export function hotRank(score: number, timeStr: string): number {
195 // Rank = ScaleFactor * sign(Score) * log(1 + abs(Score)) / (Time + 2)^Gravity
196 let date: Date = new Date(timeStr + "Z"); // Add Z to convert from UTC date
197 let now: Date = new Date();
198 let hoursElapsed: number = (now.getTime() - date.getTime()) / 36e5;
201 (10000 * Math.log10(Math.max(1, 3 + Number(score)))) /
202 Math.pow(hoursElapsed + 2, 1.8);
204 // console.log(`Comment: ${comment.content}\nRank: ${rank}\nScore: ${comment.score}\nHours: ${hoursElapsed}`);
209 export function mdToHtml(text: string) {
210 return { __html: md.render(text) };
213 export function mdToHtmlNoImages(text: string) {
214 return { __html: mdNoImages.render(text) };
217 export function mdToHtmlInline(text: string) {
218 return { __html: md.renderInline(text) };
221 export function getUnixTime(text?: string): number | undefined {
222 return text ? new Date(text).getTime() / 1000 : undefined;
225 export function futureDaysToUnixTime(days?: number): number | undefined {
228 new Date(Date.now() + 1000 * 60 * 60 * 24 * days).getTime() / 1000
233 export function canMod(
235 mods?: CommunityModeratorView[],
236 admins?: PersonView[],
237 myUserInfo = UserService.Instance.myUserInfo,
240 // You can do moderator actions only on the mods added after you.
243 ?.map(a => a.person.id)
244 .concat(mods?.map(m => m.moderator.id) ?? []) ?? [];
247 let myIndex = adminsThenMods.findIndex(
248 id => id == myUserInfo.local_user_view.person.id
253 // onSelf +1 on mod actions not for yourself, IE ban, remove, etc
254 adminsThenMods = adminsThenMods.slice(0, myIndex + (onSelf ? 0 : 1));
255 return !adminsThenMods.includes(creator_id);
262 export function canAdmin(
264 admins?: PersonView[],
265 myUserInfo = UserService.Instance.myUserInfo,
268 return canMod(creatorId, undefined, admins, myUserInfo, onSelf);
271 export function isMod(
273 mods?: CommunityModeratorView[]
275 return mods?.map(m => m.moderator.id).includes(creatorId) ?? false;
278 export function amMod(
279 mods?: CommunityModeratorView[],
280 myUserInfo = UserService.Instance.myUserInfo
282 return myUserInfo ? isMod(myUserInfo.local_user_view.person.id, mods) : false;
285 export function isAdmin(creatorId: number, admins?: PersonView[]): boolean {
286 return admins?.map(a => a.person.id).includes(creatorId) ?? false;
289 export function amAdmin(myUserInfo = UserService.Instance.myUserInfo): boolean {
290 return myUserInfo?.local_user_view.person.admin ?? false;
293 export function amCommunityCreator(
295 mods?: CommunityModeratorView[],
296 myUserInfo = UserService.Instance.myUserInfo
298 let myId = myUserInfo?.local_user_view.person.id;
299 // Don't allow mod actions on yourself
300 return myId == mods?.at(0)?.moderator.id && myId != creator_id;
303 export function amSiteCreator(
305 admins?: PersonView[],
306 myUserInfo = UserService.Instance.myUserInfo
308 let myId = myUserInfo?.local_user_view.person.id;
309 return myId == admins?.at(0)?.person.id && myId != creator_id;
312 export function amTopMod(
313 mods: CommunityModeratorView[],
314 myUserInfo = UserService.Instance.myUserInfo
316 return mods.at(0)?.moderator.id == myUserInfo?.local_user_view.person.id;
319 const imageRegex = /(http)?s?:?(\/\/[^"']*\.(?:jpg|jpeg|gif|png|svg|webp))/;
320 const videoRegex = /(http)?s?:?(\/\/[^"']*\.(?:mp4|webm))/;
322 export function isImage(url: string) {
323 return imageRegex.test(url);
326 export function isVideo(url: string) {
327 return videoRegex.test(url);
330 export function validURL(str: string) {
331 return !!new URL(str);
334 export function communityRSSUrl(actorId: string, sort: string): string {
335 let url = new URL(actorId);
336 return `${url.origin}/feeds${url.pathname}.xml?sort=${sort}`;
339 export function validEmail(email: string) {
341 /^(([^\s"(),.:;<>@[\\\]]+(\.[^\s"(),.:;<>@[\\\]]+)*)|(".+"))@((\[(?:\d{1,3}\.){3}\d{1,3}])|(([\dA-Za-z\-]+\.)+[A-Za-z]{2,}))$/;
342 return re.test(String(email).toLowerCase());
345 export function capitalizeFirstLetter(str: string): string {
346 return str.charAt(0).toUpperCase() + str.slice(1);
349 export async function getSiteMetadata(url: string) {
350 let form: GetSiteMetadata = { url };
351 let client = new LemmyHttp(getHttpBase());
352 return client.getSiteMetadata(form);
355 export function getDataTypeString(dt: DataType) {
356 return dt === DataType.Post ? "Post" : "Comment";
359 export function debounce<T extends any[], R>(
360 func: (...e: T) => R,
364 // 'private' variable for instance
365 // The returned function will be able to reference this due to closure.
366 // Each call to the returned function will share this common timer.
367 let timeout: NodeJS.Timeout | null;
369 // Calling debounce returns a new anonymous function
371 // reference the context and args for the setTimeout function
372 const args = arguments;
374 // Should the function be called now? If immediate is true
375 // and not already in a timeout then the answer is: Yes
376 const callNow = immediate && !timeout;
378 // This is the basic debounce behavior where you can call this
379 // function several times, but it will only execute once
380 // [before or after imposing a delay].
381 // Each time the returned function is called, the timer starts over.
382 clearTimeout(timeout ?? undefined);
384 // Set the new timeout
385 timeout = setTimeout(function () {
386 // Inside the timeout function, clear the timeout variable
387 // which will let the next execution run when in 'immediate' mode
390 // Check if the function already ran with the immediate flag
392 // Call the original function with apply
393 // apply lets you define the 'this' object as well as the arguments
394 // (both captured before setTimeout)
395 func.apply(this, args);
399 // Immediate mode and no wait timer? Execute the function..
400 if (callNow) func.apply(this, args);
404 export function getLanguages(
406 myUserInfo = UserService.Instance.myUserInfo
408 let myLang = myUserInfo?.local_user_view.local_user.interface_language;
409 let lang = override || myLang || "browser";
411 if (lang == "browser" && isBrowser()) {
412 return getBrowserLanguages();
418 function getBrowserLanguages(): string[] {
419 // Intersect lemmy's langs, with the browser langs
420 let langs = languages ? languages.map(l => l.code) : ["en"];
422 // NOTE, mobile browsers seem to be missing this list, so append en
423 let allowedLangs = navigator.languages
425 .filter(v => langs.includes(v));
429 export async function fetchThemeList(): Promise<string[]> {
430 return fetch("/css/themelist").then(res => res.json());
433 export async function setTheme(theme: string, forceReload = false) {
437 if (theme === "browser" && !forceReload) {
440 // This is only run on a force reload
441 if (theme == "browser") {
445 let themeList = await fetchThemeList();
447 // Unload all the other themes
448 for (var i = 0; i < themeList.length; i++) {
449 let styleSheet = document.getElementById(themeList[i]);
451 styleSheet.setAttribute("disabled", "disabled");
456 .getElementById("default-light")
457 ?.setAttribute("disabled", "disabled");
458 document.getElementById("default-dark")?.setAttribute("disabled", "disabled");
460 // Load the theme dynamically
461 let cssLoc = `/css/themes/${theme}.css`;
463 loadCss(theme, cssLoc);
464 document.getElementById(theme)?.removeAttribute("disabled");
467 export function loadCss(id: string, loc: string) {
468 if (!document.getElementById(id)) {
469 var head = document.getElementsByTagName("head")[0];
470 var link = document.createElement("link");
472 link.rel = "stylesheet";
473 link.type = "text/css";
476 head.appendChild(link);
480 export function objectFlip(obj: any) {
482 Object.keys(obj).forEach(key => {
488 export function showAvatars(
489 myUserInfo = UserService.Instance.myUserInfo
491 return myUserInfo?.local_user_view.local_user.show_avatars ?? true;
494 export function showScores(
495 myUserInfo = UserService.Instance.myUserInfo
497 return myUserInfo?.local_user_view.local_user.show_scores ?? true;
500 export function isCakeDay(published: string): boolean {
501 // moment(undefined) or moment.utc(undefined) returns the current date/time
502 // moment(null) or moment.utc(null) returns null
503 const createDate = moment.utc(published).local();
504 const currentDate = moment(new Date());
507 createDate.date() === currentDate.date() &&
508 createDate.month() === currentDate.month() &&
509 createDate.year() !== currentDate.year()
513 export function toast(text: string, background: ThemeColor = "success") {
515 const backgroundColor = `var(--${background})`;
518 backgroundColor: backgroundColor,
526 export function pictrsDeleteToast(filename: string, deleteUrl: string) {
528 const clickToDeleteText = i18n.t("click_to_delete_picture", { filename });
529 const deletePictureText = i18n.t("picture_deleted", {
532 const failedDeletePictureText = i18n.t("failed_to_delete_picture", {
536 const backgroundColor = `var(--light)`;
538 const toast = Toastify({
539 text: clickToDeleteText,
540 backgroundColor: backgroundColor,
546 fetch(deleteUrl).then(res => {
548 if (res.ok === true) {
549 alert(deletePictureText);
551 alert(failedDeletePictureText);
563 interface NotifyInfo {
570 export function messageToastify(info: NotifyInfo, router: any) {
572 let htmlBody = info.body ? md.render(info.body) : "";
573 let backgroundColor = `var(--light)`;
575 let toast = Toastify({
576 text: `${htmlBody}<br />${info.name}`,
578 backgroundColor: backgroundColor,
579 className: "text-dark",
588 router.history.push(info.link);
596 export function notifyPost(post_view: PostView, router: any) {
597 let info: NotifyInfo = {
598 name: post_view.community.name,
599 icon: post_view.community.icon,
600 link: `/post/${post_view.post.id}`,
601 body: post_view.post.name,
603 notify(info, router);
606 export function notifyComment(comment_view: CommentView, router: any) {
607 let info: NotifyInfo = {
608 name: comment_view.creator.name,
609 icon: comment_view.creator.avatar,
610 link: `/comment/${comment_view.comment.id}`,
611 body: comment_view.comment.content,
613 notify(info, router);
616 export function notifyPrivateMessage(pmv: PrivateMessageView, router: any) {
617 let info: NotifyInfo = {
618 name: pmv.creator.name,
619 icon: pmv.creator.avatar,
621 body: pmv.private_message.content,
623 notify(info, router);
626 function notify(info: NotifyInfo, router: any) {
627 messageToastify(info, router);
629 if (Notification.permission !== "granted") Notification.requestPermission();
631 var notification = new Notification(info.name, {
632 ...{ body: info.body },
633 ...(info.icon && { icon: info.icon }),
636 notification.onclick = (ev: Event): any => {
638 router.history.push(info.link);
643 export function setupTribute() {
645 noMatchTemplate: function () {
652 menuItemTemplate: (item: any) => {
653 let shortName = `:${item.original.key}:`;
654 return `${item.original.val} ${shortName}`;
656 selectTemplate: (item: any) => {
657 let customEmoji = customEmojisLookup.get(
660 if (customEmoji == undefined) return `${item.original.val}`;
662 return `![${customEmoji.alt_text}](${customEmoji.image_url} "${customEmoji.shortcode}")`;
664 values: Object.entries(emojiShortName)
666 return { key: e[1], val: e[0] };
669 Array.from(customEmojisLookup.entries()).map(k => ({
671 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}" />`,
675 autocompleteMode: true,
677 // menuItemLimit: mentionDropdownFetchLimit,
678 menuShowMinLength: 2,
683 selectTemplate: (item: any) => {
684 let it: PersonTribute = item.original;
685 return `[${it.key}](${it.view.person.actor_id})`;
687 values: debounce(async (text: string, cb: any) => {
688 cb(await personSearch(text));
691 autocompleteMode: true,
693 // menuItemLimit: mentionDropdownFetchLimit,
694 menuShowMinLength: 2,
700 selectTemplate: (item: any) => {
701 let it: CommunityTribute = item.original;
702 return `[${it.key}](${it.view.community.actor_id})`;
704 values: debounce(async (text: string, cb: any) => {
705 cb(await communitySearch(text));
708 autocompleteMode: true,
710 // menuItemLimit: mentionDropdownFetchLimit,
711 menuShowMinLength: 2,
717 function setupEmojiDataModel(custom_emoji_views: CustomEmojiView[]) {
718 let groupedEmojis = groupBy(custom_emoji_views, x => x.custom_emoji.category);
719 for (const [category, emojis] of Object.entries(groupedEmojis)) {
723 emojis: emojis.map(emoji => ({
724 id: emoji.custom_emoji.shortcode,
725 name: emoji.custom_emoji.shortcode,
726 keywords: emoji.keywords.map(x => x.keyword),
727 skins: [{ src: emoji.custom_emoji.image_url }],
731 customEmojisLookup = new Map(
732 custom_emoji_views.map(view => [view.custom_emoji.shortcode, view])
736 export function updateEmojiDataModel(custom_emoji_view: CustomEmojiView) {
737 const emoji: EmojiMartCustomEmoji = {
738 id: custom_emoji_view.custom_emoji.shortcode,
739 name: custom_emoji_view.custom_emoji.shortcode,
740 keywords: custom_emoji_view.keywords.map(x => x.keyword),
741 skins: [{ src: custom_emoji_view.custom_emoji.image_url }],
743 let categoryIndex = customEmojis.findIndex(
744 x => x.id == custom_emoji_view.custom_emoji.category
746 if (categoryIndex == -1) {
748 id: custom_emoji_view.custom_emoji.category,
749 name: custom_emoji_view.custom_emoji.category,
753 let emojiIndex = customEmojis[categoryIndex].emojis.findIndex(
754 x => x.id == custom_emoji_view.custom_emoji.shortcode
756 if (emojiIndex == -1) {
757 customEmojis[categoryIndex].emojis.push(emoji);
759 customEmojis[categoryIndex].emojis[emojiIndex] = emoji;
762 customEmojisLookup.set(
763 custom_emoji_view.custom_emoji.shortcode,
768 export function removeFromEmojiDataModel(id: number) {
769 let view: CustomEmojiView | undefined;
770 for (let item of customEmojisLookup.values()) {
771 if (item.custom_emoji.id === id) {
777 const categoryIndex = customEmojis.findIndex(
778 x => x.id == view?.custom_emoji.category
780 const emojiIndex = customEmojis[categoryIndex].emojis.findIndex(
781 x => x.id == view?.custom_emoji.shortcode
783 customEmojis[categoryIndex].emojis = customEmojis[
785 ].emojis.splice(emojiIndex, 1);
787 customEmojisLookup.delete(view?.custom_emoji.shortcode);
790 function setupMarkdown() {
791 const markdownItConfig: MarkdownIt.Options = {
797 const emojiDefs = Array.from(customEmojisLookup.entries()).reduce(
798 (main, [key, value]) => ({ ...main, [key]: value }),
801 md = new MarkdownIt(markdownItConfig)
802 .use(markdown_it_sub)
803 .use(markdown_it_sup)
804 .use(markdown_it_footnote)
805 .use(markdown_it_html5_embed, html5EmbedConfig)
806 .use(markdown_it_container, "spoiler", spoilerConfig)
807 .use(markdown_it_emoji, {
811 mdNoImages = new MarkdownIt(markdownItConfig)
812 .use(markdown_it_sub)
813 .use(markdown_it_sup)
814 .use(markdown_it_footnote)
815 .use(markdown_it_html5_embed, html5EmbedConfig)
816 .use(markdown_it_container, "spoiler", spoilerConfig)
817 .use(markdown_it_emoji, {
821 var defaultRenderer = md.renderer.rules.image;
822 md.renderer.rules.image = function (
825 options: MarkdownIt.Options,
829 //Provide custom renderer for our emojis to allow us to add a css class and force size dimensions on them.
830 const item = tokens[idx] as any;
831 const title = item.attrs.length >= 3 ? item.attrs[2][1] : "";
832 const src: string = item.attrs[0][1];
833 const isCustomEmoji = customEmojisLookup.get(title) != undefined;
834 if (!isCustomEmoji) {
835 return defaultRenderer?.(tokens, idx, options, env, self) ?? "";
837 const alt_text = item.content;
838 return `<img class="icon icon-emoji" src="${src}" title="${title}" alt="${alt_text}"/>`;
842 export function getEmojiMart(
843 onEmojiSelect: (e: any) => void,
844 customPickerOptions: any = {}
846 const pickerOptions = {
847 ...customPickerOptions,
848 onEmojiSelect: onEmojiSelect,
849 custom: customEmojis,
851 return new Picker(pickerOptions);
854 var tippyInstance: any;
856 tippyInstance = tippy("[data-tippy-content]");
859 export function setupTippy() {
861 tippyInstance.forEach((e: any) => e.destroy());
862 tippyInstance = tippy("[data-tippy-content]", {
864 // Display on "long press"
865 touch: ["hold", 500],
870 interface PersonTribute {
875 async function personSearch(text: string): Promise<PersonTribute[]> {
876 let users = (await fetchUsers(text)).users;
877 let persons: PersonTribute[] = users.map(pv => {
878 let tribute: PersonTribute = {
879 key: `@${pv.person.name}@${hostname(pv.person.actor_id)}`,
887 interface CommunityTribute {
892 async function communitySearch(text: string): Promise<CommunityTribute[]> {
893 let comms = (await fetchCommunities(text)).communities;
894 let communities: CommunityTribute[] = comms.map(cv => {
895 let tribute: CommunityTribute = {
896 key: `!${cv.community.name}@${hostname(cv.community.actor_id)}`,
904 export function getRecipientIdFromProps(props: any): number {
905 return props.match.params.recipient_id
906 ? Number(props.match.params.recipient_id)
910 export function getIdFromProps(props: any): number | undefined {
911 let id = props.match.params.post_id;
912 return id ? Number(id) : undefined;
915 export function getCommentIdFromProps(props: any): number | undefined {
916 let id = props.match.params.comment_id;
917 return id ? Number(id) : undefined;
920 export function editCommentRes(data: CommentView, comments?: CommentView[]) {
921 let found = comments?.find(c => c.comment.id == data.comment.id);
923 found.comment.content = data.comment.content;
924 found.comment.distinguished = data.comment.distinguished;
925 found.comment.updated = data.comment.updated;
926 found.comment.removed = data.comment.removed;
927 found.comment.deleted = data.comment.deleted;
928 found.counts.upvotes = data.counts.upvotes;
929 found.counts.downvotes = data.counts.downvotes;
930 found.counts.score = data.counts.score;
934 export function saveCommentRes(data: CommentView, comments?: CommentView[]) {
935 let found = comments?.find(c => c.comment.id == data.comment.id);
937 found.saved = data.saved;
941 export function updatePersonBlock(
942 data: BlockPersonResponse,
943 myUserInfo: MyUserInfo | undefined = UserService.Instance.myUserInfo
945 let mui = myUserInfo;
948 mui.person_blocks.push({
949 person: mui.local_user_view.person,
950 target: data.person_view.person,
952 toast(`${i18n.t("blocked")} ${data.person_view.person.name}`);
954 mui.person_blocks = mui.person_blocks.filter(
955 i => i.target.id != data.person_view.person.id
957 toast(`${i18n.t("unblocked")} ${data.person_view.person.name}`);
962 export function updateCommunityBlock(
963 data: BlockCommunityResponse,
964 myUserInfo: MyUserInfo | undefined = UserService.Instance.myUserInfo
966 let mui = myUserInfo;
969 mui.community_blocks.push({
970 person: mui.local_user_view.person,
971 community: data.community_view.community,
973 toast(`${i18n.t("blocked")} ${data.community_view.community.name}`);
975 mui.community_blocks = mui.community_blocks.filter(
976 i => i.community.id != data.community_view.community.id
978 toast(`${i18n.t("unblocked")} ${data.community_view.community.name}`);
983 export function createCommentLikeRes(
985 comments?: CommentView[]
987 let found = comments?.find(c => c.comment.id === data.comment.id);
989 found.counts.score = data.counts.score;
990 found.counts.upvotes = data.counts.upvotes;
991 found.counts.downvotes = data.counts.downvotes;
992 if (data.my_vote !== null) {
993 found.my_vote = data.my_vote;
998 export function createPostLikeFindRes(data: PostView, posts?: PostView[]) {
999 let found = posts?.find(p => p.post.id == data.post.id);
1001 createPostLikeRes(data, found);
1005 export function createPostLikeRes(data: PostView, post_view?: PostView) {
1007 post_view.counts.score = data.counts.score;
1008 post_view.counts.upvotes = data.counts.upvotes;
1009 post_view.counts.downvotes = data.counts.downvotes;
1010 if (data.my_vote !== null) {
1011 post_view.my_vote = data.my_vote;
1016 export function editPostFindRes(data: PostView, posts?: PostView[]) {
1017 let found = posts?.find(p => p.post.id == data.post.id);
1019 editPostRes(data, found);
1023 export function editPostRes(data: PostView, post: PostView) {
1025 post.post.url = data.post.url;
1026 post.post.name = data.post.name;
1027 post.post.nsfw = data.post.nsfw;
1028 post.post.deleted = data.post.deleted;
1029 post.post.removed = data.post.removed;
1030 post.post.featured_community = data.post.featured_community;
1031 post.post.featured_local = data.post.featured_local;
1032 post.post.body = data.post.body;
1033 post.post.locked = data.post.locked;
1034 post.saved = data.saved;
1038 // TODO possible to make these generic?
1039 export function updatePostReportRes(
1040 data: PostReportView,
1041 reports?: PostReportView[]
1043 let found = reports?.find(p => p.post_report.id == data.post_report.id);
1045 found.post_report = data.post_report;
1049 export function updateCommentReportRes(
1050 data: CommentReportView,
1051 reports?: CommentReportView[]
1053 let found = reports?.find(c => c.comment_report.id == data.comment_report.id);
1055 found.comment_report = data.comment_report;
1059 export function updatePrivateMessageReportRes(
1060 data: PrivateMessageReportView,
1061 reports?: PrivateMessageReportView[]
1063 let found = reports?.find(
1064 c => c.private_message_report.id == data.private_message_report.id
1067 found.private_message_report = data.private_message_report;
1071 export function updateRegistrationApplicationRes(
1072 data: RegistrationApplicationView,
1073 applications?: RegistrationApplicationView[]
1075 let found = applications?.find(
1076 ra => ra.registration_application.id == data.registration_application.id
1079 found.registration_application = data.registration_application;
1080 found.admin = data.admin;
1081 found.creator_local_user = data.creator_local_user;
1085 export function commentsToFlatNodes(comments: CommentView[]): CommentNodeI[] {
1086 let nodes: CommentNodeI[] = [];
1087 for (let comment of comments) {
1088 nodes.push({ comment_view: comment, children: [], depth: 0 });
1093 export function convertCommentSortType(sort: SortType): CommentSortType {
1097 sort == "TopWeek" ||
1098 sort == "TopMonth" ||
1102 } else if (sort == "New") {
1104 } else if (sort == "Hot" || sort == "Active") {
1111 export function buildCommentsTree(
1112 comments: CommentView[],
1113 parentComment: boolean
1115 let map = new Map<number, CommentNodeI>();
1116 let depthOffset = !parentComment
1118 : getDepthFromComment(comments[0].comment) ?? 0;
1120 for (let comment_view of comments) {
1121 let depthI = getDepthFromComment(comment_view.comment) ?? 0;
1122 let depth = depthI ? depthI - depthOffset : 0;
1123 let node: CommentNodeI = {
1128 map.set(comment_view.comment.id, { ...node });
1131 let tree: CommentNodeI[] = [];
1133 // if its a parent comment fetch, then push the first comment to the top node.
1134 if (parentComment) {
1135 let cNode = map.get(comments[0].comment.id);
1141 for (let comment_view of comments) {
1142 let child = map.get(comment_view.comment.id);
1144 let parent_id = getCommentParentId(comment_view.comment);
1146 let parent = map.get(parent_id);
1147 // Necessary because blocked comment might not exist
1149 parent.children.push(child);
1152 if (!parentComment) {
1162 export function getCommentParentId(comment?: CommentI): number | undefined {
1163 let split = comment?.path.split(".");
1167 return split && split.length > 1
1168 ? Number(split.at(split.length - 2))
1172 export function getDepthFromComment(comment?: CommentI): number | undefined {
1173 let len = comment?.path.split(".").length;
1174 return len ? len - 2 : undefined;
1177 export function insertCommentIntoTree(
1178 tree: CommentNodeI[],
1180 parentComment: boolean
1182 // Building a fake node to be used for later
1183 let node: CommentNodeI = {
1189 let parentId = getCommentParentId(cv.comment);
1191 let parent_comment = searchCommentTree(tree, parentId);
1192 if (parent_comment) {
1193 node.depth = parent_comment.depth + 1;
1194 parent_comment.children.unshift(node);
1196 } else if (!parentComment) {
1201 export function searchCommentTree(
1202 tree: CommentNodeI[],
1204 ): CommentNodeI | undefined {
1205 for (let node of tree) {
1206 if (node.comment_view.comment.id === id) {
1210 for (const child of node.children) {
1211 let res = searchCommentTree([child], id);
1221 export const colorList: string[] = [
1231 function hsl(num: number) {
1232 return `hsla(${num}, 35%, 50%, 1)`;
1235 export function hostname(url: string): string {
1236 let cUrl = new URL(url);
1237 return cUrl.port ? `${cUrl.hostname}:${cUrl.port}` : `${cUrl.hostname}`;
1240 export function validTitle(title?: string): boolean {
1241 // Initial title is null, minimum length is taken care of by textarea's minLength={3}
1242 if (!title || title.length < 3) return true;
1244 const regex = new RegExp(/.*\S.*/, "g");
1246 return regex.test(title);
1249 export function siteBannerCss(banner: string): string {
1251 background-image: linear-gradient( rgba(0, 0, 0, 0.8), rgba(0, 0, 0, 0.8) ) ,url("${banner}"); \
1252 background-attachment: fixed; \
1253 background-position: top; \
1254 background-repeat: no-repeat; \
1255 background-size: 100% cover; \
1258 max-height: 100vh; \
1262 export function isBrowser() {
1263 return typeof window !== "undefined";
1266 export function setIsoData(context: any): IsoData {
1267 // If its the browser, you need to deserialize the data from the window
1269 let json = window.isoData;
1270 let routeData = json.routeData;
1271 let site_res = json.site_res;
1273 let isoData: IsoData = {
1279 } else return context.router.staticContext;
1282 export function wsSubscribe(parseMessage: any): Subscription | undefined {
1284 return WebSocketService.Instance.subject
1285 .pipe(retryWhen(errors => errors.pipe(delay(3000), take(10))))
1287 msg => parseMessage(msg),
1288 err => console.error(err),
1289 () => console.log("complete")
1296 moment.updateLocale("en", {
1317 export function saveScrollPosition(context: any) {
1318 let path: string = context.router.route.location.pathname;
1319 let y = window.scrollY;
1320 sessionStorage.setItem(`scrollPosition_${path}`, y.toString());
1323 export function restoreScrollPosition(context: any) {
1324 let path: string = context.router.route.location.pathname;
1325 let y = Number(sessionStorage.getItem(`scrollPosition_${path}`));
1326 window.scrollTo(0, y);
1329 export function showLocal(isoData: IsoData): boolean {
1330 return isoData.site_res.site_view.local_site.federation_enabled;
1333 export interface Choice {
1339 export function getUpdatedSearchId(id?: number | null, urlId?: number | null) {
1342 : ((id ?? urlId) === 0 ? undefined : id ?? urlId)?.toString();
1345 export function communityToChoice(cv: CommunityView): Choice {
1347 value: cv.community.id.toString(),
1348 label: communitySelectName(cv),
1352 export function personToChoice(pvs: PersonView): Choice {
1354 value: pvs.person.id.toString(),
1355 label: personSelectName(pvs),
1359 export async function fetchCommunities(q: string) {
1360 let form: Search = {
1362 type_: "Communities",
1364 listing_type: "All",
1367 auth: myAuth(false),
1369 let client = new LemmyHttp(getHttpBase());
1370 return client.search(form);
1373 export async function fetchUsers(q: string) {
1374 let form: Search = {
1378 listing_type: "All",
1381 auth: myAuth(false),
1383 let client = new LemmyHttp(getHttpBase());
1384 return client.search(form);
1387 export function communitySelectName(cv: CommunityView): string {
1388 return cv.community.local
1389 ? cv.community.title
1390 : `${hostname(cv.community.actor_id)}/${cv.community.title}`;
1393 export function personSelectName({
1394 person: { display_name, name, local, actor_id },
1395 }: PersonView): string {
1396 const pName = display_name ?? name;
1397 return local ? pName : `${hostname(actor_id)}/${pName}`;
1400 export function initializeSite(site?: GetSiteResponse) {
1401 UserService.Instance.myUserInfo = site?.my_user;
1402 i18n.changeLanguage(getLanguages()[0]);
1404 setupEmojiDataModel(site.custom_emojis);
1409 const SHORTNUM_SI_FORMAT = new Intl.NumberFormat("en-US", {
1410 maximumSignificantDigits: 3,
1412 notation: "compact",
1413 compactDisplay: "short",
1416 export function numToSI(value: number): string {
1417 return SHORTNUM_SI_FORMAT.format(value);
1420 export function isBanned(ps: Person): boolean {
1421 let expires = ps.ban_expires;
1422 // Add Z to convert from UTC date
1423 // TODO this check probably isn't necessary anymore
1425 if (ps.banned && new Date(expires + "Z") > new Date()) {
1435 export function myAuth(throwErr = true): string | undefined {
1436 return UserService.Instance.auth(throwErr);
1439 export function enableDownvotes(siteRes: GetSiteResponse): boolean {
1440 return siteRes.site_view.local_site.enable_downvotes;
1443 export function enableNsfw(siteRes: GetSiteResponse): boolean {
1444 return siteRes.site_view.local_site.enable_nsfw;
1447 export function postToCommentSortType(sort: SortType): CommentSortType {
1462 export function canCreateCommunity(
1463 siteRes: GetSiteResponse,
1464 myUserInfo = UserService.Instance.myUserInfo
1466 const adminOnly = siteRes.site_view.local_site.community_creation_admin_only;
1467 // TODO: Make this check if user is logged on as well
1468 return !adminOnly || amAdmin(myUserInfo);
1471 export function isPostBlocked(
1473 myUserInfo: MyUserInfo | undefined = UserService.Instance.myUserInfo
1476 (myUserInfo?.community_blocks
1477 .map(c => c.community.id)
1478 .includes(pv.community.id) ||
1479 myUserInfo?.person_blocks
1480 .map(p => p.target.id)
1481 .includes(pv.creator.id)) ??
1486 /// Checks to make sure you can view NSFW posts. Returns true if you can.
1487 export function nsfwCheck(
1489 myUserInfo = UserService.Instance.myUserInfo
1491 let nsfw = pv.post.nsfw || pv.community.nsfw;
1492 let myShowNsfw = myUserInfo?.local_user_view.local_user.show_nsfw ?? false;
1493 return !nsfw || (nsfw && myShowNsfw);
1496 export function getRandomFromList<T>(list: T[]): T | undefined {
1497 return list.length == 0
1499 : list.at(Math.floor(Math.random() * list.length));
1503 * This shows what language you can select
1505 * Use showAll for the site form
1506 * Use showSite for the profile and community forms
1507 * Use false for both those to filter on your profile and site ones
1509 export function selectableLanguages(
1510 allLanguages: Language[],
1511 siteLanguages: number[],
1514 myUserInfo = UserService.Instance.myUserInfo
1516 let allLangIds = allLanguages.map(l => l.id);
1517 let myLangs = myUserInfo?.discussion_languages ?? allLangIds;
1518 myLangs = myLangs.length == 0 ? allLangIds : myLangs;
1519 let siteLangs = siteLanguages.length == 0 ? allLangIds : siteLanguages;
1522 return allLanguages;
1525 return allLanguages.filter(x => siteLangs.includes(x.id));
1528 .filter(x => siteLangs.includes(x.id))
1529 .filter(x => myLangs.includes(x.id));
1534 export function uploadImage(image: File): Promise<UploadImageResponse> {
1535 const client = new LemmyHttp(getHttpBase());
1537 return client.uploadImage({ image });
1540 interface EmojiMartCategory {
1543 emojis: EmojiMartCustomEmoji[];
1546 interface EmojiMartCustomEmoji {
1550 skins: EmojiMartSkin[];
1553 interface EmojiMartSkin {
1557 const groupBy = <T>(
1559 predicate: (value: T, index: number, array: T[]) => string
1561 array.reduce((acc, value, index, array) => {
1562 (acc[predicate(value, index, array)] ||= []).push(value);
1564 }, {} as { [key: string]: T[] });
1566 export type QueryParams<T extends Record<string, any>> = {
1567 [key in keyof T]?: string;
1570 export function getQueryParams<T extends Record<string, any>>(processors: {
1571 [K in keyof T]: (param: string) => T[K];
1574 const searchParams = new URLSearchParams(window.location.search);
1576 return Array.from(Object.entries(processors)).reduce(
1577 (acc, [key, process]) => ({
1579 [key]: process(searchParams.get(key)),
1588 export function getQueryString<T extends Record<string, string | undefined>>(
1591 return Object.entries(obj)
1592 .filter(([, val]) => val !== undefined && val !== null)
1594 (acc, [key, val], index) => `${acc}${index > 0 ? "&" : ""}${key}=${val}`,
1599 export function isAuthPath(pathname: string) {
1600 return /create_.*|inbox|settings|setup|admin|reports|registration_applications/g.test(