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 {
110 adminMatrixIds?: string[];
113 let customEmojis: EmojiMartCategory[] = [];
114 export let customEmojisLookup: Map<string, CustomEmojiView> = new Map<
119 const DEFAULT_ALPHABET =
120 "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
122 function getRandomCharFromAlphabet(alphabet: string): string {
123 return alphabet.charAt(Math.floor(Math.random() * alphabet.length));
126 export function getIdFromString(id?: string): number | undefined {
127 return id && id !== "0" && !Number.isNaN(Number(id)) ? Number(id) : undefined;
130 export function getPageFromString(page?: string): number {
131 return page && !Number.isNaN(Number(page)) ? Number(page) : 1;
134 export function randomStr(
135 idDesiredLength = 20,
136 alphabet = DEFAULT_ALPHABET
139 * Create n-long array and map it to random chars from given alphabet.
140 * Then join individual chars as string
142 return Array.from({ length: idDesiredLength })
144 return getRandomCharFromAlphabet(alphabet);
149 const html5EmbedConfig = {
151 useImageSyntax: true, // Enables video/audio embed with ![]() syntax (default)
153 audio: 'controls preload="metadata"',
154 video: 'width="100%" max-height="100%" controls loop preload="metadata"',
159 const spoilerConfig = {
160 validate: (params: string) => {
161 return params.trim().match(/^spoiler\s+(.*)$/);
164 render: (tokens: any, idx: any) => {
165 var m = tokens[idx].info.trim().match(/^spoiler\s+(.*)$/);
167 if (tokens[idx].nesting === 1) {
169 return `<details><summary> ${md.utils.escapeHtml(m[1])} </summary>\n`;
172 return "</details>\n";
177 export let md: MarkdownIt = new MarkdownIt();
179 export let mdNoImages: MarkdownIt = new MarkdownIt();
181 export function hotRankComment(comment_view: CommentView): number {
182 return hotRank(comment_view.counts.score, comment_view.comment.published);
185 export function hotRankActivePost(post_view: PostView): number {
186 return hotRank(post_view.counts.score, post_view.counts.newest_comment_time);
189 export function hotRankPost(post_view: PostView): number {
190 return hotRank(post_view.counts.score, post_view.post.published);
193 export function hotRank(score: number, timeStr: string): number {
194 // Rank = ScaleFactor * sign(Score) * log(1 + abs(Score)) / (Time + 2)^Gravity
195 let date: Date = new Date(timeStr + "Z"); // Add Z to convert from UTC date
196 let now: Date = new Date();
197 let hoursElapsed: number = (now.getTime() - date.getTime()) / 36e5;
200 (10000 * Math.log10(Math.max(1, 3 + Number(score)))) /
201 Math.pow(hoursElapsed + 2, 1.8);
203 // console.log(`Comment: ${comment.content}\nRank: ${rank}\nScore: ${comment.score}\nHours: ${hoursElapsed}`);
208 export function mdToHtml(text: string) {
209 return { __html: md.render(text) };
212 export function mdToHtmlNoImages(text: string) {
213 return { __html: mdNoImages.render(text) };
216 export function mdToHtmlInline(text: string) {
217 return { __html: md.renderInline(text) };
220 export function getUnixTime(text?: string): number | undefined {
221 return text ? new Date(text).getTime() / 1000 : undefined;
224 export function futureDaysToUnixTime(days?: number): number | undefined {
227 new Date(Date.now() + 1000 * 60 * 60 * 24 * days).getTime() / 1000
232 export function canMod(
234 mods?: CommunityModeratorView[],
235 admins?: PersonView[],
236 myUserInfo = UserService.Instance.myUserInfo,
239 // You can do moderator actions only on the mods added after you.
242 ?.map(a => a.person.id)
243 .concat(mods?.map(m => m.moderator.id) ?? []) ?? [];
246 let myIndex = adminsThenMods.findIndex(
247 id => id == myUserInfo.local_user_view.person.id
252 // onSelf +1 on mod actions not for yourself, IE ban, remove, etc
253 adminsThenMods = adminsThenMods.slice(0, myIndex + (onSelf ? 0 : 1));
254 return !adminsThenMods.includes(creator_id);
261 export function canAdmin(
263 admins?: PersonView[],
264 myUserInfo = UserService.Instance.myUserInfo,
267 return canMod(creatorId, undefined, admins, myUserInfo, onSelf);
270 export function isMod(
272 mods?: CommunityModeratorView[]
274 return mods?.map(m => m.moderator.id).includes(creatorId) ?? false;
277 export function amMod(
278 mods?: CommunityModeratorView[],
279 myUserInfo = UserService.Instance.myUserInfo
281 return myUserInfo ? isMod(myUserInfo.local_user_view.person.id, mods) : false;
284 export function isAdmin(creatorId: number, admins?: PersonView[]): boolean {
285 return admins?.map(a => a.person.id).includes(creatorId) ?? false;
288 export function amAdmin(myUserInfo = UserService.Instance.myUserInfo): boolean {
289 return myUserInfo?.local_user_view.person.admin ?? false;
292 export function amCommunityCreator(
294 mods?: CommunityModeratorView[],
295 myUserInfo = UserService.Instance.myUserInfo
297 let myId = myUserInfo?.local_user_view.person.id;
298 // Don't allow mod actions on yourself
299 return myId == mods?.at(0)?.moderator.id && myId != creator_id;
302 export function amSiteCreator(
304 admins?: PersonView[],
305 myUserInfo = UserService.Instance.myUserInfo
307 let myId = myUserInfo?.local_user_view.person.id;
308 return myId == admins?.at(0)?.person.id && myId != creator_id;
311 export function amTopMod(
312 mods: CommunityModeratorView[],
313 myUserInfo = UserService.Instance.myUserInfo
315 return mods.at(0)?.moderator.id == myUserInfo?.local_user_view.person.id;
318 const imageRegex = /(http)?s?:?(\/\/[^"']*\.(?:jpg|jpeg|gif|png|svg|webp))/;
319 const videoRegex = /(http)?s?:?(\/\/[^"']*\.(?:mp4|webm))/;
321 export function isImage(url: string) {
322 return imageRegex.test(url);
325 export function isVideo(url: string) {
326 return videoRegex.test(url);
329 export function validURL(str: string) {
330 return !!new URL(str);
333 export function communityRSSUrl(actorId: string, sort: string): string {
334 let url = new URL(actorId);
335 return `${url.origin}/feeds${url.pathname}.xml?sort=${sort}`;
338 export function validEmail(email: string) {
340 /^(([^\s"(),.:;<>@[\\\]]+(\.[^\s"(),.:;<>@[\\\]]+)*)|(".+"))@((\[(?:\d{1,3}\.){3}\d{1,3}])|(([\dA-Za-z\-]+\.)+[A-Za-z]{2,}))$/;
341 return re.test(String(email).toLowerCase());
344 export function capitalizeFirstLetter(str: string): string {
345 return str.charAt(0).toUpperCase() + str.slice(1);
348 export async function getSiteMetadata(url: string) {
349 let form: GetSiteMetadata = { url };
350 let client = new LemmyHttp(getHttpBase());
351 return client.getSiteMetadata(form);
354 export function getDataTypeString(dt: DataType) {
355 return dt === DataType.Post ? "Post" : "Comment";
358 export function debounce<T extends any[], R>(
359 func: (...e: T) => R,
363 // 'private' variable for instance
364 // The returned function will be able to reference this due to closure.
365 // Each call to the returned function will share this common timer.
366 let timeout: NodeJS.Timeout | null;
368 // Calling debounce returns a new anonymous function
370 // reference the context and args for the setTimeout function
371 const args = arguments;
373 // Should the function be called now? If immediate is true
374 // and not already in a timeout then the answer is: Yes
375 const callNow = immediate && !timeout;
377 // This is the basic debounce behavior where you can call this
378 // function several times, but it will only execute once
379 // [before or after imposing a delay].
380 // Each time the returned function is called, the timer starts over.
381 clearTimeout(timeout ?? undefined);
383 // Set the new timeout
384 timeout = setTimeout(function () {
385 // Inside the timeout function, clear the timeout variable
386 // which will let the next execution run when in 'immediate' mode
389 // Check if the function already ran with the immediate flag
391 // Call the original function with apply
392 // apply lets you define the 'this' object as well as the arguments
393 // (both captured before setTimeout)
394 func.apply(this, args);
398 // Immediate mode and no wait timer? Execute the function..
399 if (callNow) func.apply(this, args);
403 export function getLanguages(
405 myUserInfo = UserService.Instance.myUserInfo
407 let myLang = myUserInfo?.local_user_view.local_user.interface_language;
408 let lang = override || myLang || "browser";
410 if (lang == "browser" && isBrowser()) {
411 return getBrowserLanguages();
417 function getBrowserLanguages(): string[] {
418 // Intersect lemmy's langs, with the browser langs
419 let langs = languages ? languages.map(l => l.code) : ["en"];
421 // NOTE, mobile browsers seem to be missing this list, so append en
422 let allowedLangs = navigator.languages
424 .filter(v => langs.includes(v));
428 export async function fetchThemeList(): Promise<string[]> {
429 return fetch("/css/themelist").then(res => res.json());
432 export async function setTheme(theme: string, forceReload = false) {
436 if (theme === "browser" && !forceReload) {
439 // This is only run on a force reload
440 if (theme == "browser") {
444 let themeList = await fetchThemeList();
446 // Unload all the other themes
447 for (var i = 0; i < themeList.length; i++) {
448 let styleSheet = document.getElementById(themeList[i]);
450 styleSheet.setAttribute("disabled", "disabled");
455 .getElementById("default-light")
456 ?.setAttribute("disabled", "disabled");
457 document.getElementById("default-dark")?.setAttribute("disabled", "disabled");
459 // Load the theme dynamically
460 let cssLoc = `/css/themes/${theme}.css`;
462 loadCss(theme, cssLoc);
463 document.getElementById(theme)?.removeAttribute("disabled");
466 export function loadCss(id: string, loc: string) {
467 if (!document.getElementById(id)) {
468 var head = document.getElementsByTagName("head")[0];
469 var link = document.createElement("link");
471 link.rel = "stylesheet";
472 link.type = "text/css";
475 head.appendChild(link);
479 export function objectFlip(obj: any) {
481 Object.keys(obj).forEach(key => {
487 export function showAvatars(
488 myUserInfo = UserService.Instance.myUserInfo
490 return myUserInfo?.local_user_view.local_user.show_avatars ?? true;
493 export function showScores(
494 myUserInfo = UserService.Instance.myUserInfo
496 return myUserInfo?.local_user_view.local_user.show_scores ?? true;
499 export function isCakeDay(published: string): boolean {
500 // moment(undefined) or moment.utc(undefined) returns the current date/time
501 // moment(null) or moment.utc(null) returns null
502 const createDate = moment.utc(published).local();
503 const currentDate = moment(new Date());
506 createDate.date() === currentDate.date() &&
507 createDate.month() === currentDate.month() &&
508 createDate.year() !== currentDate.year()
512 export function toast(text: string, background: ThemeColor = "success") {
514 const backgroundColor = `var(--${background})`;
517 backgroundColor: backgroundColor,
525 export function pictrsDeleteToast(filename: string, deleteUrl: string) {
527 const clickToDeleteText = i18n.t("click_to_delete_picture", { filename });
528 const deletePictureText = i18n.t("picture_deleted", {
531 const failedDeletePictureText = i18n.t("failed_to_delete_picture", {
535 const backgroundColor = `var(--light)`;
537 const toast = Toastify({
538 text: clickToDeleteText,
539 backgroundColor: backgroundColor,
545 fetch(deleteUrl).then(res => {
547 if (res.ok === true) {
548 alert(deletePictureText);
550 alert(failedDeletePictureText);
562 interface NotifyInfo {
569 export function messageToastify(info: NotifyInfo, router: any) {
571 let htmlBody = info.body ? md.render(info.body) : "";
572 let backgroundColor = `var(--light)`;
574 let toast = Toastify({
575 text: `${htmlBody}<br />${info.name}`,
577 backgroundColor: backgroundColor,
578 className: "text-dark",
587 router.history.push(info.link);
595 export function notifyPost(post_view: PostView, router: any) {
596 let info: NotifyInfo = {
597 name: post_view.community.name,
598 icon: post_view.community.icon,
599 link: `/post/${post_view.post.id}`,
600 body: post_view.post.name,
602 notify(info, router);
605 export function notifyComment(comment_view: CommentView, router: any) {
606 let info: NotifyInfo = {
607 name: comment_view.creator.name,
608 icon: comment_view.creator.avatar,
609 link: `/comment/${comment_view.comment.id}`,
610 body: comment_view.comment.content,
612 notify(info, router);
615 export function notifyPrivateMessage(pmv: PrivateMessageView, router: any) {
616 let info: NotifyInfo = {
617 name: pmv.creator.name,
618 icon: pmv.creator.avatar,
620 body: pmv.private_message.content,
622 notify(info, router);
625 function notify(info: NotifyInfo, router: any) {
626 messageToastify(info, router);
628 if (Notification.permission !== "granted") Notification.requestPermission();
630 var notification = new Notification(info.name, {
631 ...{ body: info.body },
632 ...(info.icon && { icon: info.icon }),
635 notification.onclick = (ev: Event): any => {
637 router.history.push(info.link);
642 export function setupTribute() {
644 noMatchTemplate: function () {
651 menuItemTemplate: (item: any) => {
652 let shortName = `:${item.original.key}:`;
653 return `${item.original.val} ${shortName}`;
655 selectTemplate: (item: any) => {
656 let customEmoji = customEmojisLookup.get(
659 if (customEmoji == undefined) return `${item.original.val}`;
661 return `![${customEmoji.alt_text}](${customEmoji.image_url} "${customEmoji.shortcode}")`;
663 values: Object.entries(emojiShortName)
665 return { key: e[1], val: e[0] };
668 Array.from(customEmojisLookup.entries()).map(k => ({
670 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}" />`,
674 autocompleteMode: true,
676 // menuItemLimit: mentionDropdownFetchLimit,
677 menuShowMinLength: 2,
682 selectTemplate: (item: any) => {
683 let it: PersonTribute = item.original;
684 return `[${it.key}](${it.view.person.actor_id})`;
686 values: debounce(async (text: string, cb: any) => {
687 cb(await personSearch(text));
690 autocompleteMode: true,
692 // menuItemLimit: mentionDropdownFetchLimit,
693 menuShowMinLength: 2,
699 selectTemplate: (item: any) => {
700 let it: CommunityTribute = item.original;
701 return `[${it.key}](${it.view.community.actor_id})`;
703 values: debounce(async (text: string, cb: any) => {
704 cb(await communitySearch(text));
707 autocompleteMode: true,
709 // menuItemLimit: mentionDropdownFetchLimit,
710 menuShowMinLength: 2,
716 function setupEmojiDataModel(custom_emoji_views: CustomEmojiView[]) {
717 let groupedEmojis = groupBy(custom_emoji_views, x => x.custom_emoji.category);
718 for (const [category, emojis] of Object.entries(groupedEmojis)) {
722 emojis: emojis.map(emoji => ({
723 id: emoji.custom_emoji.shortcode,
724 name: emoji.custom_emoji.shortcode,
725 keywords: emoji.keywords.map(x => x.keyword),
726 skins: [{ src: emoji.custom_emoji.image_url }],
730 customEmojisLookup = new Map(
731 custom_emoji_views.map(view => [view.custom_emoji.shortcode, view])
735 export function updateEmojiDataModel(custom_emoji_view: CustomEmojiView) {
736 const emoji: EmojiMartCustomEmoji = {
737 id: custom_emoji_view.custom_emoji.shortcode,
738 name: custom_emoji_view.custom_emoji.shortcode,
739 keywords: custom_emoji_view.keywords.map(x => x.keyword),
740 skins: [{ src: custom_emoji_view.custom_emoji.image_url }],
742 let categoryIndex = customEmojis.findIndex(
743 x => x.id == custom_emoji_view.custom_emoji.category
745 if (categoryIndex == -1) {
747 id: custom_emoji_view.custom_emoji.category,
748 name: custom_emoji_view.custom_emoji.category,
752 let emojiIndex = customEmojis[categoryIndex].emojis.findIndex(
753 x => x.id == custom_emoji_view.custom_emoji.shortcode
755 if (emojiIndex == -1) {
756 customEmojis[categoryIndex].emojis.push(emoji);
758 customEmojis[categoryIndex].emojis[emojiIndex] = emoji;
761 customEmojisLookup.set(
762 custom_emoji_view.custom_emoji.shortcode,
767 export function removeFromEmojiDataModel(id: number) {
768 let view: CustomEmojiView | undefined;
769 for (let item of customEmojisLookup.values()) {
770 if (item.custom_emoji.id === id) {
776 const categoryIndex = customEmojis.findIndex(
777 x => x.id == view?.custom_emoji.category
779 const emojiIndex = customEmojis[categoryIndex].emojis.findIndex(
780 x => x.id == view?.custom_emoji.shortcode
782 customEmojis[categoryIndex].emojis = customEmojis[
784 ].emojis.splice(emojiIndex, 1);
786 customEmojisLookup.delete(view?.custom_emoji.shortcode);
789 function setupMarkdown() {
790 const markdownItConfig: MarkdownIt.Options = {
796 const emojiDefs = Array.from(customEmojisLookup.entries()).reduce(
797 (main, [key, value]) => ({ ...main, [key]: value }),
800 md = new MarkdownIt(markdownItConfig)
801 .use(markdown_it_sub)
802 .use(markdown_it_sup)
803 .use(markdown_it_footnote)
804 .use(markdown_it_html5_embed, html5EmbedConfig)
805 .use(markdown_it_container, "spoiler", spoilerConfig)
806 .use(markdown_it_emoji, {
810 mdNoImages = new MarkdownIt(markdownItConfig)
811 .use(markdown_it_sub)
812 .use(markdown_it_sup)
813 .use(markdown_it_footnote)
814 .use(markdown_it_html5_embed, html5EmbedConfig)
815 .use(markdown_it_container, "spoiler", spoilerConfig)
816 .use(markdown_it_emoji, {
820 var defaultRenderer = md.renderer.rules.image;
821 md.renderer.rules.image = function (
824 options: MarkdownIt.Options,
828 //Provide custom renderer for our emojis to allow us to add a css class and force size dimensions on them.
829 const item = tokens[idx] as any;
830 const title = item.attrs.length >= 3 ? item.attrs[2][1] : "";
831 const src: string = item.attrs[0][1];
832 const isCustomEmoji = customEmojisLookup.get(title) != undefined;
833 if (!isCustomEmoji) {
834 return defaultRenderer?.(tokens, idx, options, env, self) ?? "";
836 const alt_text = item.content;
837 return `<img class="icon icon-emoji" src="${src}" title="${title}" alt="${alt_text}"/>`;
841 export function getEmojiMart(
842 onEmojiSelect: (e: any) => void,
843 customPickerOptions: any = {}
845 const pickerOptions = {
846 ...customPickerOptions,
847 onEmojiSelect: onEmojiSelect,
848 custom: customEmojis,
850 return new Picker(pickerOptions);
853 var tippyInstance: any;
855 tippyInstance = tippy("[data-tippy-content]");
858 export function setupTippy() {
860 tippyInstance.forEach((e: any) => e.destroy());
861 tippyInstance = tippy("[data-tippy-content]", {
863 // Display on "long press"
864 touch: ["hold", 500],
869 interface PersonTribute {
874 async function personSearch(text: string): Promise<PersonTribute[]> {
875 let users = (await fetchUsers(text)).users;
876 let persons: PersonTribute[] = users.map(pv => {
877 let tribute: PersonTribute = {
878 key: `@${pv.person.name}@${hostname(pv.person.actor_id)}`,
886 interface CommunityTribute {
891 async function communitySearch(text: string): Promise<CommunityTribute[]> {
892 let comms = (await fetchCommunities(text)).communities;
893 let communities: CommunityTribute[] = comms.map(cv => {
894 let tribute: CommunityTribute = {
895 key: `!${cv.community.name}@${hostname(cv.community.actor_id)}`,
903 export function getRecipientIdFromProps(props: any): number {
904 return props.match.params.recipient_id
905 ? Number(props.match.params.recipient_id)
909 export function getIdFromProps(props: any): number | undefined {
910 let id = props.match.params.post_id;
911 return id ? Number(id) : undefined;
914 export function getCommentIdFromProps(props: any): number | undefined {
915 let id = props.match.params.comment_id;
916 return id ? Number(id) : undefined;
919 export function editCommentRes(data: CommentView, comments?: CommentView[]) {
920 let found = comments?.find(c => c.comment.id == data.comment.id);
922 found.comment.content = data.comment.content;
923 found.comment.distinguished = data.comment.distinguished;
924 found.comment.updated = data.comment.updated;
925 found.comment.removed = data.comment.removed;
926 found.comment.deleted = data.comment.deleted;
927 found.counts.upvotes = data.counts.upvotes;
928 found.counts.downvotes = data.counts.downvotes;
929 found.counts.score = data.counts.score;
933 export function saveCommentRes(data: CommentView, comments?: CommentView[]) {
934 let found = comments?.find(c => c.comment.id == data.comment.id);
936 found.saved = data.saved;
940 export function updatePersonBlock(
941 data: BlockPersonResponse,
942 myUserInfo: MyUserInfo | undefined = UserService.Instance.myUserInfo
944 let mui = myUserInfo;
947 mui.person_blocks.push({
948 person: mui.local_user_view.person,
949 target: data.person_view.person,
951 toast(`${i18n.t("blocked")} ${data.person_view.person.name}`);
953 mui.person_blocks = mui.person_blocks.filter(
954 i => i.target.id != data.person_view.person.id
956 toast(`${i18n.t("unblocked")} ${data.person_view.person.name}`);
961 export function updateCommunityBlock(
962 data: BlockCommunityResponse,
963 myUserInfo: MyUserInfo | undefined = UserService.Instance.myUserInfo
965 let mui = myUserInfo;
968 mui.community_blocks.push({
969 person: mui.local_user_view.person,
970 community: data.community_view.community,
972 toast(`${i18n.t("blocked")} ${data.community_view.community.name}`);
974 mui.community_blocks = mui.community_blocks.filter(
975 i => i.community.id != data.community_view.community.id
977 toast(`${i18n.t("unblocked")} ${data.community_view.community.name}`);
982 export function createCommentLikeRes(
984 comments?: CommentView[]
986 let found = comments?.find(c => c.comment.id === data.comment.id);
988 found.counts.score = data.counts.score;
989 found.counts.upvotes = data.counts.upvotes;
990 found.counts.downvotes = data.counts.downvotes;
991 if (data.my_vote !== null) {
992 found.my_vote = data.my_vote;
997 export function createPostLikeFindRes(data: PostView, posts?: PostView[]) {
998 let found = posts?.find(p => p.post.id == data.post.id);
1000 createPostLikeRes(data, found);
1004 export function createPostLikeRes(data: PostView, post_view?: PostView) {
1006 post_view.counts.score = data.counts.score;
1007 post_view.counts.upvotes = data.counts.upvotes;
1008 post_view.counts.downvotes = data.counts.downvotes;
1009 if (data.my_vote !== null) {
1010 post_view.my_vote = data.my_vote;
1015 export function editPostFindRes(data: PostView, posts?: PostView[]) {
1016 let found = posts?.find(p => p.post.id == data.post.id);
1018 editPostRes(data, found);
1022 export function editPostRes(data: PostView, post: PostView) {
1024 post.post.url = data.post.url;
1025 post.post.name = data.post.name;
1026 post.post.nsfw = data.post.nsfw;
1027 post.post.deleted = data.post.deleted;
1028 post.post.removed = data.post.removed;
1029 post.post.featured_community = data.post.featured_community;
1030 post.post.featured_local = data.post.featured_local;
1031 post.post.body = data.post.body;
1032 post.post.locked = data.post.locked;
1033 post.saved = data.saved;
1037 // TODO possible to make these generic?
1038 export function updatePostReportRes(
1039 data: PostReportView,
1040 reports?: PostReportView[]
1042 let found = reports?.find(p => p.post_report.id == data.post_report.id);
1044 found.post_report = data.post_report;
1048 export function updateCommentReportRes(
1049 data: CommentReportView,
1050 reports?: CommentReportView[]
1052 let found = reports?.find(c => c.comment_report.id == data.comment_report.id);
1054 found.comment_report = data.comment_report;
1058 export function updatePrivateMessageReportRes(
1059 data: PrivateMessageReportView,
1060 reports?: PrivateMessageReportView[]
1062 let found = reports?.find(
1063 c => c.private_message_report.id == data.private_message_report.id
1066 found.private_message_report = data.private_message_report;
1070 export function updateRegistrationApplicationRes(
1071 data: RegistrationApplicationView,
1072 applications?: RegistrationApplicationView[]
1074 let found = applications?.find(
1075 ra => ra.registration_application.id == data.registration_application.id
1078 found.registration_application = data.registration_application;
1079 found.admin = data.admin;
1080 found.creator_local_user = data.creator_local_user;
1084 export function commentsToFlatNodes(comments: CommentView[]): CommentNodeI[] {
1085 let nodes: CommentNodeI[] = [];
1086 for (let comment of comments) {
1087 nodes.push({ comment_view: comment, children: [], depth: 0 });
1092 export function convertCommentSortType(sort: SortType): CommentSortType {
1096 sort == "TopWeek" ||
1097 sort == "TopMonth" ||
1101 } else if (sort == "New") {
1103 } else if (sort == "Hot" || sort == "Active") {
1110 export function buildCommentsTree(
1111 comments: CommentView[],
1112 parentComment: boolean
1114 let map = new Map<number, CommentNodeI>();
1115 let depthOffset = !parentComment
1117 : getDepthFromComment(comments[0].comment) ?? 0;
1119 for (let comment_view of comments) {
1120 let depthI = getDepthFromComment(comment_view.comment) ?? 0;
1121 let depth = depthI ? depthI - depthOffset : 0;
1122 let node: CommentNodeI = {
1127 map.set(comment_view.comment.id, { ...node });
1130 let tree: CommentNodeI[] = [];
1132 // if its a parent comment fetch, then push the first comment to the top node.
1133 if (parentComment) {
1134 let cNode = map.get(comments[0].comment.id);
1140 for (let comment_view of comments) {
1141 let child = map.get(comment_view.comment.id);
1143 let parent_id = getCommentParentId(comment_view.comment);
1145 let parent = map.get(parent_id);
1146 // Necessary because blocked comment might not exist
1148 parent.children.push(child);
1151 if (!parentComment) {
1161 export function getCommentParentId(comment?: CommentI): number | undefined {
1162 let split = comment?.path.split(".");
1166 return split && split.length > 1
1167 ? Number(split.at(split.length - 2))
1171 export function getDepthFromComment(comment?: CommentI): number | undefined {
1172 let len = comment?.path.split(".").length;
1173 return len ? len - 2 : undefined;
1176 export function insertCommentIntoTree(
1177 tree: CommentNodeI[],
1179 parentComment: boolean
1181 // Building a fake node to be used for later
1182 let node: CommentNodeI = {
1188 let parentId = getCommentParentId(cv.comment);
1190 let parent_comment = searchCommentTree(tree, parentId);
1191 if (parent_comment) {
1192 node.depth = parent_comment.depth + 1;
1193 parent_comment.children.unshift(node);
1195 } else if (!parentComment) {
1200 export function searchCommentTree(
1201 tree: CommentNodeI[],
1203 ): CommentNodeI | undefined {
1204 for (let node of tree) {
1205 if (node.comment_view.comment.id === id) {
1209 for (const child of node.children) {
1210 let res = searchCommentTree([child], id);
1220 export const colorList: string[] = [
1230 function hsl(num: number) {
1231 return `hsla(${num}, 35%, 50%, 1)`;
1234 export function hostname(url: string): string {
1235 let cUrl = new URL(url);
1236 return cUrl.port ? `${cUrl.hostname}:${cUrl.port}` : `${cUrl.hostname}`;
1239 export function validTitle(title?: string): boolean {
1240 // Initial title is null, minimum length is taken care of by textarea's minLength={3}
1241 if (!title || title.length < 3) return true;
1243 const regex = new RegExp(/.*\S.*/, "g");
1245 return regex.test(title);
1248 export function siteBannerCss(banner: string): string {
1250 background-image: linear-gradient( rgba(0, 0, 0, 0.8), rgba(0, 0, 0, 0.8) ) ,url("${banner}"); \
1251 background-attachment: fixed; \
1252 background-position: top; \
1253 background-repeat: no-repeat; \
1254 background-size: 100% cover; \
1257 max-height: 100vh; \
1261 export function isBrowser() {
1262 return typeof window !== "undefined";
1265 export function setIsoData(context: any): IsoData {
1266 // If its the browser, you need to deserialize the data from the window
1268 return window.isoData;
1269 } else return context.router.staticContext;
1272 export function wsSubscribe(parseMessage: any): Subscription | undefined {
1274 return WebSocketService.Instance.subject
1275 .pipe(retryWhen(errors => errors.pipe(delay(3000), take(10))))
1277 msg => parseMessage(msg),
1278 err => console.error(err),
1279 () => console.log("complete")
1286 moment.updateLocale("en", {
1307 export function saveScrollPosition(context: any) {
1308 let path: string = context.router.route.location.pathname;
1309 let y = window.scrollY;
1310 sessionStorage.setItem(`scrollPosition_${path}`, y.toString());
1313 export function restoreScrollPosition(context: any) {
1314 let path: string = context.router.route.location.pathname;
1315 let y = Number(sessionStorage.getItem(`scrollPosition_${path}`));
1316 window.scrollTo(0, y);
1319 export function showLocal(isoData: IsoData): boolean {
1320 return isoData.site_res.site_view.local_site.federation_enabled;
1323 export interface Choice {
1329 export function getUpdatedSearchId(id?: number | null, urlId?: number | null) {
1332 : ((id ?? urlId) === 0 ? undefined : id ?? urlId)?.toString();
1335 export function communityToChoice(cv: CommunityView): Choice {
1337 value: cv.community.id.toString(),
1338 label: communitySelectName(cv),
1342 export function personToChoice(pvs: PersonView): Choice {
1344 value: pvs.person.id.toString(),
1345 label: personSelectName(pvs),
1349 export async function fetchCommunities(q: string) {
1350 let form: Search = {
1352 type_: "Communities",
1354 listing_type: "All",
1357 auth: myAuth(false),
1359 let client = new LemmyHttp(getHttpBase());
1360 return client.search(form);
1363 export async function fetchUsers(q: string) {
1364 let form: Search = {
1368 listing_type: "All",
1371 auth: myAuth(false),
1373 let client = new LemmyHttp(getHttpBase());
1374 return client.search(form);
1377 export function communitySelectName(cv: CommunityView): string {
1378 return cv.community.local
1379 ? cv.community.title
1380 : `${hostname(cv.community.actor_id)}/${cv.community.title}`;
1383 export function personSelectName({
1384 person: { display_name, name, local, actor_id },
1385 }: PersonView): string {
1386 const pName = display_name ?? name;
1387 return local ? pName : `${hostname(actor_id)}/${pName}`;
1390 export function initializeSite(site?: GetSiteResponse) {
1391 UserService.Instance.myUserInfo = site?.my_user;
1392 i18n.changeLanguage(getLanguages()[0]);
1394 setupEmojiDataModel(site.custom_emojis);
1399 const SHORTNUM_SI_FORMAT = new Intl.NumberFormat("en-US", {
1400 maximumSignificantDigits: 3,
1402 notation: "compact",
1403 compactDisplay: "short",
1406 export function numToSI(value: number): string {
1407 return SHORTNUM_SI_FORMAT.format(value);
1410 export function isBanned(ps: Person): boolean {
1411 let expires = ps.ban_expires;
1412 // Add Z to convert from UTC date
1413 // TODO this check probably isn't necessary anymore
1415 if (ps.banned && new Date(expires + "Z") > new Date()) {
1425 export function myAuth(throwErr = true): string | undefined {
1426 return UserService.Instance.auth(throwErr);
1429 export function enableDownvotes(siteRes: GetSiteResponse): boolean {
1430 return siteRes.site_view.local_site.enable_downvotes;
1433 export function enableNsfw(siteRes: GetSiteResponse): boolean {
1434 return siteRes.site_view.local_site.enable_nsfw;
1437 export function postToCommentSortType(sort: SortType): CommentSortType {
1452 export function canCreateCommunity(
1453 siteRes: GetSiteResponse,
1454 myUserInfo = UserService.Instance.myUserInfo
1456 const adminOnly = siteRes.site_view.local_site.community_creation_admin_only;
1457 // TODO: Make this check if user is logged on as well
1458 return !adminOnly || amAdmin(myUserInfo);
1461 export function isPostBlocked(
1463 myUserInfo: MyUserInfo | undefined = UserService.Instance.myUserInfo
1466 (myUserInfo?.community_blocks
1467 .map(c => c.community.id)
1468 .includes(pv.community.id) ||
1469 myUserInfo?.person_blocks
1470 .map(p => p.target.id)
1471 .includes(pv.creator.id)) ??
1476 /// Checks to make sure you can view NSFW posts. Returns true if you can.
1477 export function nsfwCheck(
1479 myUserInfo = UserService.Instance.myUserInfo
1481 let nsfw = pv.post.nsfw || pv.community.nsfw;
1482 let myShowNsfw = myUserInfo?.local_user_view.local_user.show_nsfw ?? false;
1483 return !nsfw || (nsfw && myShowNsfw);
1486 export function getRandomFromList<T>(list: T[]): T | undefined {
1487 return list.length == 0
1489 : list.at(Math.floor(Math.random() * list.length));
1493 * This shows what language you can select
1495 * Use showAll for the site form
1496 * Use showSite for the profile and community forms
1497 * Use false for both those to filter on your profile and site ones
1499 export function selectableLanguages(
1500 allLanguages: Language[],
1501 siteLanguages: number[],
1504 myUserInfo = UserService.Instance.myUserInfo
1506 let allLangIds = allLanguages.map(l => l.id);
1507 let myLangs = myUserInfo?.discussion_languages ?? allLangIds;
1508 myLangs = myLangs.length == 0 ? allLangIds : myLangs;
1509 let siteLangs = siteLanguages.length == 0 ? allLangIds : siteLanguages;
1512 return allLanguages;
1515 return allLanguages.filter(x => siteLangs.includes(x.id));
1518 .filter(x => siteLangs.includes(x.id))
1519 .filter(x => myLangs.includes(x.id));
1524 export function uploadImage(image: File): Promise<UploadImageResponse> {
1525 const client = new LemmyHttp(getHttpBase());
1527 return client.uploadImage({ image });
1530 interface EmojiMartCategory {
1533 emojis: EmojiMartCustomEmoji[];
1536 interface EmojiMartCustomEmoji {
1540 skins: EmojiMartSkin[];
1543 interface EmojiMartSkin {
1547 const groupBy = <T>(
1549 predicate: (value: T, index: number, array: T[]) => string
1551 array.reduce((acc, value, index, array) => {
1552 (acc[predicate(value, index, array)] ||= []).push(value);
1554 }, {} as { [key: string]: T[] });
1556 export type QueryParams<T extends Record<string, any>> = {
1557 [key in keyof T]?: string;
1560 export function getQueryParams<T extends Record<string, any>>(processors: {
1561 [K in keyof T]: (param: string) => T[K];
1564 const searchParams = new URLSearchParams(window.location.search);
1566 return Array.from(Object.entries(processors)).reduce(
1567 (acc, [key, process]) => ({
1569 [key]: process(searchParams.get(key)),
1578 export function getQueryString<T extends Record<string, string | undefined>>(
1581 return Object.entries(obj)
1582 .filter(([, val]) => val !== undefined && val !== null)
1584 (acc, [key, val], index) => `${acc}${index > 0 ? "&" : ""}${key}=${val}`,
1589 export function isAuthPath(pathname: string) {
1590 return /create_.*|inbox|settings|setup|admin|reports|registration_applications/g.test(