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 = `${joinLemmyUrl}/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 const 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 const date: Date = new Date(timeStr + "Z"); // Add Z to convert from UTC date
196 const now: Date = new Date();
197 const 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 const 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 const 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 const 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 const 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 const form: GetSiteMetadata = { url };
350 const 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 const myLang = myUserInfo?.local_user_view.local_user.interface_language;
408 const 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 const langs = languages ? languages.map(l => l.code) : ["en"];
421 // NOTE, mobile browsers seem to be missing this list, so append en
422 const 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 const themeList = await fetchThemeList();
446 // Unload all the other themes
447 for (var i = 0; i < themeList.length; i++) {
448 const 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 const 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 const htmlBody = info.body ? md.render(info.body) : "";
572 const backgroundColor = `var(--light)`;
574 const 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 const 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 const 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 const 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 const shortName = `:${item.original.key}:`;
653 return `${item.original.val} ${shortName}`;
655 selectTemplate: (item: any) => {
656 const 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 const 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 const 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 const groupedEmojis = groupBy(
719 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 const 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 const 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 (const 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 {
877 async function personSearch(text: string): Promise<PersonTribute[]> {
878 const users = (await fetchUsers(text)).users;
879 const persons: PersonTribute[] = users.map(pv => {
880 const tribute: PersonTribute = {
881 key: `@${pv.person.name}@${hostname(pv.person.actor_id)}`,
889 interface CommunityTribute {
894 async function communitySearch(text: string): Promise<CommunityTribute[]> {
895 const comms = (await fetchCommunities(text)).communities;
896 const communities: CommunityTribute[] = comms.map(cv => {
897 const tribute: CommunityTribute = {
898 key: `!${cv.community.name}@${hostname(cv.community.actor_id)}`,
906 export function getRecipientIdFromProps(props: any): number {
907 return props.match.params.recipient_id
908 ? Number(props.match.params.recipient_id)
912 export function getIdFromProps(props: any): number | undefined {
913 const id = props.match.params.post_id;
914 return id ? Number(id) : undefined;
917 export function getCommentIdFromProps(props: any): number | undefined {
918 const id = props.match.params.comment_id;
919 return id ? Number(id) : undefined;
922 export function editCommentRes(data: CommentView, comments?: CommentView[]) {
923 const found = comments?.find(c => c.comment.id == data.comment.id);
925 found.comment.content = data.comment.content;
926 found.comment.distinguished = data.comment.distinguished;
927 found.comment.updated = data.comment.updated;
928 found.comment.removed = data.comment.removed;
929 found.comment.deleted = data.comment.deleted;
930 found.counts.upvotes = data.counts.upvotes;
931 found.counts.downvotes = data.counts.downvotes;
932 found.counts.score = data.counts.score;
936 export function saveCommentRes(data: CommentView, comments?: CommentView[]) {
937 const found = comments?.find(c => c.comment.id == data.comment.id);
939 found.saved = data.saved;
943 export function updatePersonBlock(
944 data: BlockPersonResponse,
945 myUserInfo: MyUserInfo | undefined = UserService.Instance.myUserInfo
947 const mui = myUserInfo;
950 mui.person_blocks.push({
951 person: mui.local_user_view.person,
952 target: data.person_view.person,
954 toast(`${i18n.t("blocked")} ${data.person_view.person.name}`);
956 mui.person_blocks = mui.person_blocks.filter(
957 i => i.target.id != data.person_view.person.id
959 toast(`${i18n.t("unblocked")} ${data.person_view.person.name}`);
964 export function updateCommunityBlock(
965 data: BlockCommunityResponse,
966 myUserInfo: MyUserInfo | undefined = UserService.Instance.myUserInfo
968 const mui = myUserInfo;
971 mui.community_blocks.push({
972 person: mui.local_user_view.person,
973 community: data.community_view.community,
975 toast(`${i18n.t("blocked")} ${data.community_view.community.name}`);
977 mui.community_blocks = mui.community_blocks.filter(
978 i => i.community.id != data.community_view.community.id
980 toast(`${i18n.t("unblocked")} ${data.community_view.community.name}`);
985 export function createCommentLikeRes(
987 comments?: CommentView[]
989 const found = comments?.find(c => c.comment.id === data.comment.id);
991 found.counts.score = data.counts.score;
992 found.counts.upvotes = data.counts.upvotes;
993 found.counts.downvotes = data.counts.downvotes;
994 if (data.my_vote !== null) {
995 found.my_vote = data.my_vote;
1000 export function createPostLikeFindRes(data: PostView, posts?: PostView[]) {
1001 const found = posts?.find(p => p.post.id == data.post.id);
1003 createPostLikeRes(data, found);
1007 export function createPostLikeRes(data: PostView, post_view?: PostView) {
1009 post_view.counts.score = data.counts.score;
1010 post_view.counts.upvotes = data.counts.upvotes;
1011 post_view.counts.downvotes = data.counts.downvotes;
1012 if (data.my_vote !== null) {
1013 post_view.my_vote = data.my_vote;
1018 export function editPostFindRes(data: PostView, posts?: PostView[]) {
1019 const found = posts?.find(p => p.post.id == data.post.id);
1021 editPostRes(data, found);
1025 export function editPostRes(data: PostView, post: PostView) {
1027 post.post.url = data.post.url;
1028 post.post.name = data.post.name;
1029 post.post.nsfw = data.post.nsfw;
1030 post.post.deleted = data.post.deleted;
1031 post.post.removed = data.post.removed;
1032 post.post.featured_community = data.post.featured_community;
1033 post.post.featured_local = data.post.featured_local;
1034 post.post.body = data.post.body;
1035 post.post.locked = data.post.locked;
1036 post.saved = data.saved;
1040 // TODO possible to make these generic?
1041 export function updatePostReportRes(
1042 data: PostReportView,
1043 reports?: PostReportView[]
1045 const found = reports?.find(p => p.post_report.id == data.post_report.id);
1047 found.post_report = data.post_report;
1051 export function updateCommentReportRes(
1052 data: CommentReportView,
1053 reports?: CommentReportView[]
1055 const found = reports?.find(
1056 c => c.comment_report.id == data.comment_report.id
1059 found.comment_report = data.comment_report;
1063 export function updatePrivateMessageReportRes(
1064 data: PrivateMessageReportView,
1065 reports?: PrivateMessageReportView[]
1067 const found = reports?.find(
1068 c => c.private_message_report.id == data.private_message_report.id
1071 found.private_message_report = data.private_message_report;
1075 export function updateRegistrationApplicationRes(
1076 data: RegistrationApplicationView,
1077 applications?: RegistrationApplicationView[]
1079 const found = applications?.find(
1080 ra => ra.registration_application.id == data.registration_application.id
1083 found.registration_application = data.registration_application;
1084 found.admin = data.admin;
1085 found.creator_local_user = data.creator_local_user;
1089 export function commentsToFlatNodes(comments: CommentView[]): CommentNodeI[] {
1090 const nodes: CommentNodeI[] = [];
1091 for (const comment of comments) {
1092 nodes.push({ comment_view: comment, children: [], depth: 0 });
1097 export function convertCommentSortType(sort: SortType): CommentSortType {
1101 sort == "TopWeek" ||
1102 sort == "TopMonth" ||
1106 } else if (sort == "New") {
1108 } else if (sort == "Hot" || sort == "Active") {
1115 export function buildCommentsTree(
1116 comments: CommentView[],
1117 parentComment: boolean
1119 const map = new Map<number, CommentNodeI>();
1120 const depthOffset = !parentComment
1122 : getDepthFromComment(comments[0].comment) ?? 0;
1124 for (const comment_view of comments) {
1125 const depthI = getDepthFromComment(comment_view.comment) ?? 0;
1126 const depth = depthI ? depthI - depthOffset : 0;
1127 const node: CommentNodeI = {
1132 map.set(comment_view.comment.id, { ...node });
1135 const tree: CommentNodeI[] = [];
1137 // if its a parent comment fetch, then push the first comment to the top node.
1138 if (parentComment) {
1139 const cNode = map.get(comments[0].comment.id);
1145 for (const comment_view of comments) {
1146 const child = map.get(comment_view.comment.id);
1148 const parent_id = getCommentParentId(comment_view.comment);
1150 const parent = map.get(parent_id);
1151 // Necessary because blocked comment might not exist
1153 parent.children.push(child);
1156 if (!parentComment) {
1166 export function getCommentParentId(comment?: CommentI): number | undefined {
1167 const split = comment?.path.split(".");
1171 return split && split.length > 1
1172 ? Number(split.at(split.length - 2))
1176 export function getDepthFromComment(comment?: CommentI): number | undefined {
1177 const len = comment?.path.split(".").length;
1178 return len ? len - 2 : undefined;
1181 export function insertCommentIntoTree(
1182 tree: CommentNodeI[],
1184 parentComment: boolean
1186 // Building a fake node to be used for later
1187 const node: CommentNodeI = {
1193 const parentId = getCommentParentId(cv.comment);
1195 const parent_comment = searchCommentTree(tree, parentId);
1196 if (parent_comment) {
1197 node.depth = parent_comment.depth + 1;
1198 parent_comment.children.unshift(node);
1200 } else if (!parentComment) {
1205 export function searchCommentTree(
1206 tree: CommentNodeI[],
1208 ): CommentNodeI | undefined {
1209 for (const node of tree) {
1210 if (node.comment_view.comment.id === id) {
1214 for (const child of node.children) {
1215 const res = searchCommentTree([child], id);
1225 export const colorList: string[] = [
1235 function hsl(num: number) {
1236 return `hsla(${num}, 35%, 50%, 1)`;
1239 export function hostname(url: string): string {
1240 const cUrl = new URL(url);
1241 return cUrl.port ? `${cUrl.hostname}:${cUrl.port}` : `${cUrl.hostname}`;
1244 export function validTitle(title?: string): boolean {
1245 // Initial title is null, minimum length is taken care of by textarea's minLength={3}
1246 if (!title || title.length < 3) return true;
1248 const regex = new RegExp(/.*\S.*/, "g");
1250 return regex.test(title);
1253 export function siteBannerCss(banner: string): string {
1255 background-image: linear-gradient( rgba(0, 0, 0, 0.8), rgba(0, 0, 0, 0.8) ) ,url("${banner}"); \
1256 background-attachment: fixed; \
1257 background-position: top; \
1258 background-repeat: no-repeat; \
1259 background-size: 100% cover; \
1262 max-height: 100vh; \
1266 export function isBrowser() {
1267 return typeof window !== "undefined";
1270 export function setIsoData(context: any): IsoData {
1271 // If its the browser, you need to deserialize the data from the window
1273 return window.isoData;
1274 } else return context.router.staticContext;
1277 export function wsSubscribe(parseMessage: any): Subscription | undefined {
1279 return WebSocketService.Instance.subject
1280 .pipe(retryWhen(errors => errors.pipe(delay(3000), take(10))))
1282 msg => parseMessage(msg),
1283 err => console.error(err),
1284 () => console.log("complete")
1291 moment.updateLocale("en", {
1312 export function saveScrollPosition(context: any) {
1313 const path: string = context.router.route.location.pathname;
1314 const y = window.scrollY;
1315 sessionStorage.setItem(`scrollPosition_${path}`, y.toString());
1318 export function restoreScrollPosition(context: any) {
1319 const path: string = context.router.route.location.pathname;
1320 const y = Number(sessionStorage.getItem(`scrollPosition_${path}`));
1321 window.scrollTo(0, y);
1324 export function showLocal(isoData: IsoData): boolean {
1325 return isoData.site_res.site_view.local_site.federation_enabled;
1328 export interface Choice {
1334 export function getUpdatedSearchId(id?: number | null, urlId?: number | null) {
1337 : ((id ?? urlId) === 0 ? undefined : id ?? urlId)?.toString();
1340 export function communityToChoice(cv: CommunityView): Choice {
1342 value: cv.community.id.toString(),
1343 label: communitySelectName(cv),
1347 export function personToChoice(pvs: PersonView): Choice {
1349 value: pvs.person.id.toString(),
1350 label: personSelectName(pvs),
1354 export async function fetchCommunities(q: string) {
1355 const form: Search = {
1357 type_: "Communities",
1359 listing_type: "All",
1362 auth: myAuth(false),
1364 const client = new LemmyHttp(getHttpBase());
1365 return client.search(form);
1368 export async function fetchUsers(q: string) {
1369 const form: Search = {
1373 listing_type: "All",
1376 auth: myAuth(false),
1378 const client = new LemmyHttp(getHttpBase());
1379 return client.search(form);
1382 export function communitySelectName(cv: CommunityView): string {
1383 return cv.community.local
1384 ? cv.community.title
1385 : `${hostname(cv.community.actor_id)}/${cv.community.title}`;
1388 export function personSelectName({
1389 person: { display_name, name, local, actor_id },
1390 }: PersonView): string {
1391 const pName = display_name ?? name;
1392 return local ? pName : `${hostname(actor_id)}/${pName}`;
1395 export function initializeSite(site?: GetSiteResponse) {
1396 UserService.Instance.myUserInfo = site?.my_user;
1397 i18n.changeLanguage(getLanguages()[0]);
1399 setupEmojiDataModel(site.custom_emojis);
1404 const SHORTNUM_SI_FORMAT = new Intl.NumberFormat("en-US", {
1405 maximumSignificantDigits: 3,
1407 notation: "compact",
1408 compactDisplay: "short",
1411 export function numToSI(value: number): string {
1412 return SHORTNUM_SI_FORMAT.format(value);
1415 export function isBanned(ps: Person): boolean {
1416 const expires = ps.ban_expires;
1417 // Add Z to convert from UTC date
1418 // TODO this check probably isn't necessary anymore
1420 if (ps.banned && new Date(expires + "Z") > new Date()) {
1430 export function myAuth(throwErr = true): string | undefined {
1431 return UserService.Instance.auth(throwErr);
1434 export function enableDownvotes(siteRes: GetSiteResponse): boolean {
1435 return siteRes.site_view.local_site.enable_downvotes;
1438 export function enableNsfw(siteRes: GetSiteResponse): boolean {
1439 return siteRes.site_view.local_site.enable_nsfw;
1442 export function postToCommentSortType(sort: SortType): CommentSortType {
1457 export function canCreateCommunity(
1458 siteRes: GetSiteResponse,
1459 myUserInfo = UserService.Instance.myUserInfo
1461 const adminOnly = siteRes.site_view.local_site.community_creation_admin_only;
1462 // TODO: Make this check if user is logged on as well
1463 return !adminOnly || amAdmin(myUserInfo);
1466 export function isPostBlocked(
1468 myUserInfo: MyUserInfo | undefined = UserService.Instance.myUserInfo
1471 (myUserInfo?.community_blocks
1472 .map(c => c.community.id)
1473 .includes(pv.community.id) ||
1474 myUserInfo?.person_blocks
1475 .map(p => p.target.id)
1476 .includes(pv.creator.id)) ??
1481 /// Checks to make sure you can view NSFW posts. Returns true if you can.
1482 export function nsfwCheck(
1484 myUserInfo = UserService.Instance.myUserInfo
1486 const nsfw = pv.post.nsfw || pv.community.nsfw;
1487 const myShowNsfw = myUserInfo?.local_user_view.local_user.show_nsfw ?? false;
1488 return !nsfw || (nsfw && myShowNsfw);
1491 export function getRandomFromList<T>(list: T[]): T | undefined {
1492 return list.length == 0
1494 : list.at(Math.floor(Math.random() * list.length));
1498 * This shows what language you can select
1500 * Use showAll for the site form
1501 * Use showSite for the profile and community forms
1502 * Use false for both those to filter on your profile and site ones
1504 export function selectableLanguages(
1505 allLanguages: Language[],
1506 siteLanguages: number[],
1509 myUserInfo = UserService.Instance.myUserInfo
1511 const allLangIds = allLanguages.map(l => l.id);
1512 let myLangs = myUserInfo?.discussion_languages ?? allLangIds;
1513 myLangs = myLangs.length == 0 ? allLangIds : myLangs;
1514 const siteLangs = siteLanguages.length == 0 ? allLangIds : siteLanguages;
1517 return allLanguages;
1520 return allLanguages.filter(x => siteLangs.includes(x.id));
1523 .filter(x => siteLangs.includes(x.id))
1524 .filter(x => myLangs.includes(x.id));
1529 export function uploadImage(image: File): Promise<UploadImageResponse> {
1530 const client = new LemmyHttp(getHttpBase());
1532 return client.uploadImage({ image });
1535 interface EmojiMartCategory {
1538 emojis: EmojiMartCustomEmoji[];
1541 interface EmojiMartCustomEmoji {
1545 skins: EmojiMartSkin[];
1548 interface EmojiMartSkin {
1552 const groupBy = <T>(
1554 predicate: (value: T, index: number, array: T[]) => string
1556 array.reduce((acc, value, index, array) => {
1557 (acc[predicate(value, index, array)] ||= []).push(value);
1559 }, {} as { [key: string]: T[] });
1561 export type QueryParams<T extends Record<string, any>> = {
1562 [key in keyof T]?: string;
1565 export function getQueryParams<T extends Record<string, any>>(processors: {
1566 [K in keyof T]: (param: string) => T[K];
1569 const searchParams = new URLSearchParams(window.location.search);
1571 return Array.from(Object.entries(processors)).reduce(
1572 (acc, [key, process]) => ({
1574 [key]: process(searchParams.get(key)),
1583 export function getQueryString<T extends Record<string, string | undefined>>(
1586 return Object.entries(obj)
1587 .filter(([, val]) => val !== undefined && val !== null)
1589 (acc, [key, val], index) => `${acc}${index > 0 ? "&" : ""}${key}=${val}`,
1594 export function isAuthPath(pathname: string) {
1595 return /create_.*|inbox|settings|setup|admin|reports|registration_applications/g.test(
1600 export function canShare() {
1601 return isBrowser() && !!navigator.canShare;
1604 export function share(shareData: ShareData) {
1606 navigator.share(shareData);