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 // restore '>' character to fix quotes
210 return { __html: md.render(text.split(">").join(">")) };
213 export function mdToHtmlNoImages(text: string) {
214 // restore '>' character to fix quotes
215 return { __html: mdNoImages.render(text.split(">").join(">")) };
218 export function mdToHtmlInline(text: string) {
219 return { __html: md.renderInline(text) };
222 export function getUnixTime(text?: string): number | undefined {
223 return text ? new Date(text).getTime() / 1000 : undefined;
226 export function futureDaysToUnixTime(days?: number): number | undefined {
229 new Date(Date.now() + 1000 * 60 * 60 * 24 * days).getTime() / 1000
234 export function canMod(
236 mods?: CommunityModeratorView[],
237 admins?: PersonView[],
238 myUserInfo = UserService.Instance.myUserInfo,
241 // You can do moderator actions only on the mods added after you.
244 ?.map(a => a.person.id)
245 .concat(mods?.map(m => m.moderator.id) ?? []) ?? [];
248 const myIndex = adminsThenMods.findIndex(
249 id => id == myUserInfo.local_user_view.person.id
254 // onSelf +1 on mod actions not for yourself, IE ban, remove, etc
255 adminsThenMods = adminsThenMods.slice(0, myIndex + (onSelf ? 0 : 1));
256 return !adminsThenMods.includes(creator_id);
263 export function canAdmin(
265 admins?: PersonView[],
266 myUserInfo = UserService.Instance.myUserInfo,
269 return canMod(creatorId, undefined, admins, myUserInfo, onSelf);
272 export function isMod(
274 mods?: CommunityModeratorView[]
276 return mods?.map(m => m.moderator.id).includes(creatorId) ?? false;
279 export function amMod(
280 mods?: CommunityModeratorView[],
281 myUserInfo = UserService.Instance.myUserInfo
283 return myUserInfo ? isMod(myUserInfo.local_user_view.person.id, mods) : false;
286 export function isAdmin(creatorId: number, admins?: PersonView[]): boolean {
287 return admins?.map(a => a.person.id).includes(creatorId) ?? false;
290 export function amAdmin(myUserInfo = UserService.Instance.myUserInfo): boolean {
291 return myUserInfo?.local_user_view.person.admin ?? false;
294 export function amCommunityCreator(
296 mods?: CommunityModeratorView[],
297 myUserInfo = UserService.Instance.myUserInfo
299 const myId = myUserInfo?.local_user_view.person.id;
300 // Don't allow mod actions on yourself
301 return myId == mods?.at(0)?.moderator.id && myId != creator_id;
304 export function amSiteCreator(
306 admins?: PersonView[],
307 myUserInfo = UserService.Instance.myUserInfo
309 const myId = myUserInfo?.local_user_view.person.id;
310 return myId == admins?.at(0)?.person.id && myId != creator_id;
313 export function amTopMod(
314 mods: CommunityModeratorView[],
315 myUserInfo = UserService.Instance.myUserInfo
317 return mods.at(0)?.moderator.id == myUserInfo?.local_user_view.person.id;
320 const imageRegex = /(http)?s?:?(\/\/[^"']*\.(?:jpg|jpeg|gif|png|svg|webp))/;
321 const videoRegex = /(http)?s?:?(\/\/[^"']*\.(?:mp4|webm))/;
323 export function isImage(url: string) {
324 return imageRegex.test(url);
327 export function isVideo(url: string) {
328 return videoRegex.test(url);
331 export function validURL(str: string) {
332 return !!new URL(str);
335 export function communityRSSUrl(actorId: string, sort: string): string {
336 const url = new URL(actorId);
337 return `${url.origin}/feeds${url.pathname}.xml?sort=${sort}`;
340 export function validEmail(email: string) {
342 /^(([^\s"(),.:;<>@[\\\]]+(\.[^\s"(),.:;<>@[\\\]]+)*)|(".+"))@((\[(?:\d{1,3}\.){3}\d{1,3}])|(([\dA-Za-z\-]+\.)+[A-Za-z]{2,}))$/;
343 return re.test(String(email).toLowerCase());
346 export function capitalizeFirstLetter(str: string): string {
347 return str.charAt(0).toUpperCase() + str.slice(1);
350 export async function getSiteMetadata(url: string) {
351 const form: GetSiteMetadata = { url };
352 const client = new LemmyHttp(getHttpBase());
353 return client.getSiteMetadata(form);
356 export function getDataTypeString(dt: DataType) {
357 return dt === DataType.Post ? "Post" : "Comment";
360 export function debounce<T extends any[], R>(
361 func: (...e: T) => R,
365 // 'private' variable for instance
366 // The returned function will be able to reference this due to closure.
367 // Each call to the returned function will share this common timer.
368 let timeout: NodeJS.Timeout | null;
370 // Calling debounce returns a new anonymous function
372 // reference the context and args for the setTimeout function
373 const args = arguments;
375 // Should the function be called now? If immediate is true
376 // and not already in a timeout then the answer is: Yes
377 const callNow = immediate && !timeout;
379 // This is the basic debounce behavior where you can call this
380 // function several times, but it will only execute once
381 // [before or after imposing a delay].
382 // Each time the returned function is called, the timer starts over.
383 clearTimeout(timeout ?? undefined);
385 // Set the new timeout
386 timeout = setTimeout(function () {
387 // Inside the timeout function, clear the timeout variable
388 // which will let the next execution run when in 'immediate' mode
391 // Check if the function already ran with the immediate flag
393 // Call the original function with apply
394 // apply lets you define the 'this' object as well as the arguments
395 // (both captured before setTimeout)
396 func.apply(this, args);
400 // Immediate mode and no wait timer? Execute the function..
401 if (callNow) func.apply(this, args);
405 export function getLanguages(
407 myUserInfo = UserService.Instance.myUserInfo
409 const myLang = myUserInfo?.local_user_view.local_user.interface_language;
410 const lang = override || myLang || "browser";
412 if (lang == "browser" && isBrowser()) {
413 return getBrowserLanguages();
419 function getBrowserLanguages(): string[] {
420 // Intersect lemmy's langs, with the browser langs
421 const langs = languages ? languages.map(l => l.code) : ["en"];
423 // NOTE, mobile browsers seem to be missing this list, so append en
424 const allowedLangs = navigator.languages
426 .filter(v => langs.includes(v));
430 export async function fetchThemeList(): Promise<string[]> {
431 return fetch("/css/themelist").then(res => res.json());
434 export async function setTheme(theme: string, forceReload = false) {
438 if (theme === "browser" && !forceReload) {
441 // This is only run on a force reload
442 if (theme == "browser") {
446 const themeList = await fetchThemeList();
448 // Unload all the other themes
449 for (var i = 0; i < themeList.length; i++) {
450 const styleSheet = document.getElementById(themeList[i]);
452 styleSheet.setAttribute("disabled", "disabled");
457 .getElementById("default-light")
458 ?.setAttribute("disabled", "disabled");
459 document.getElementById("default-dark")?.setAttribute("disabled", "disabled");
461 // Load the theme dynamically
462 const cssLoc = `/css/themes/${theme}.css`;
464 loadCss(theme, cssLoc);
465 document.getElementById(theme)?.removeAttribute("disabled");
468 export function loadCss(id: string, loc: string) {
469 if (!document.getElementById(id)) {
470 var head = document.getElementsByTagName("head")[0];
471 var link = document.createElement("link");
473 link.rel = "stylesheet";
474 link.type = "text/css";
477 head.appendChild(link);
481 export function objectFlip(obj: any) {
483 Object.keys(obj).forEach(key => {
489 export function showAvatars(
490 myUserInfo = UserService.Instance.myUserInfo
492 return myUserInfo?.local_user_view.local_user.show_avatars ?? true;
495 export function showScores(
496 myUserInfo = UserService.Instance.myUserInfo
498 return myUserInfo?.local_user_view.local_user.show_scores ?? true;
501 export function isCakeDay(published: string): boolean {
502 // moment(undefined) or moment.utc(undefined) returns the current date/time
503 // moment(null) or moment.utc(null) returns null
504 const createDate = moment.utc(published).local();
505 const currentDate = moment(new Date());
508 createDate.date() === currentDate.date() &&
509 createDate.month() === currentDate.month() &&
510 createDate.year() !== currentDate.year()
514 export function toast(text: string, background: ThemeColor = "success") {
516 const backgroundColor = `var(--${background})`;
519 backgroundColor: backgroundColor,
527 export function pictrsDeleteToast(filename: string, deleteUrl: string) {
529 const clickToDeleteText = i18n.t("click_to_delete_picture", { filename });
530 const deletePictureText = i18n.t("picture_deleted", {
533 const failedDeletePictureText = i18n.t("failed_to_delete_picture", {
537 const backgroundColor = `var(--light)`;
539 const toast = Toastify({
540 text: clickToDeleteText,
541 backgroundColor: backgroundColor,
547 fetch(deleteUrl).then(res => {
549 if (res.ok === true) {
550 alert(deletePictureText);
552 alert(failedDeletePictureText);
564 interface NotifyInfo {
571 export function messageToastify(info: NotifyInfo, router: any) {
573 const htmlBody = info.body ? md.render(info.body) : "";
574 const backgroundColor = `var(--light)`;
576 const toast = Toastify({
577 text: `${htmlBody}<br />${info.name}`,
579 backgroundColor: backgroundColor,
580 className: "text-dark",
589 router.history.push(info.link);
597 export function notifyPost(post_view: PostView, router: any) {
598 const info: NotifyInfo = {
599 name: post_view.community.name,
600 icon: post_view.community.icon,
601 link: `/post/${post_view.post.id}`,
602 body: post_view.post.name,
604 notify(info, router);
607 export function notifyComment(comment_view: CommentView, router: any) {
608 const info: NotifyInfo = {
609 name: comment_view.creator.name,
610 icon: comment_view.creator.avatar,
611 link: `/comment/${comment_view.comment.id}`,
612 body: comment_view.comment.content,
614 notify(info, router);
617 export function notifyPrivateMessage(pmv: PrivateMessageView, router: any) {
618 const info: NotifyInfo = {
619 name: pmv.creator.name,
620 icon: pmv.creator.avatar,
622 body: pmv.private_message.content,
624 notify(info, router);
627 function notify(info: NotifyInfo, router: any) {
628 messageToastify(info, router);
630 if (Notification.permission !== "granted") Notification.requestPermission();
632 var notification = new Notification(info.name, {
633 ...{ body: info.body },
634 ...(info.icon && { icon: info.icon }),
637 notification.onclick = (ev: Event): any => {
639 router.history.push(info.link);
644 export function setupTribute() {
646 noMatchTemplate: function () {
653 menuItemTemplate: (item: any) => {
654 const shortName = `:${item.original.key}:`;
655 return `${item.original.val} ${shortName}`;
657 selectTemplate: (item: any) => {
658 const customEmoji = customEmojisLookup.get(
661 if (customEmoji == undefined) return `${item.original.val}`;
663 return `![${customEmoji.alt_text}](${customEmoji.image_url} "${customEmoji.shortcode}")`;
665 values: Object.entries(emojiShortName)
667 return { key: e[1], val: e[0] };
670 Array.from(customEmojisLookup.entries()).map(k => ({
672 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}" />`,
676 autocompleteMode: true,
678 // menuItemLimit: mentionDropdownFetchLimit,
679 menuShowMinLength: 2,
684 selectTemplate: (item: any) => {
685 const it: PersonTribute = item.original;
686 return `[${it.key}](${it.view.person.actor_id})`;
688 values: debounce(async (text: string, cb: any) => {
689 cb(await personSearch(text));
692 autocompleteMode: true,
694 // menuItemLimit: mentionDropdownFetchLimit,
695 menuShowMinLength: 2,
701 selectTemplate: (item: any) => {
702 const it: CommunityTribute = item.original;
703 return `[${it.key}](${it.view.community.actor_id})`;
705 values: debounce(async (text: string, cb: any) => {
706 cb(await communitySearch(text));
709 autocompleteMode: true,
711 // menuItemLimit: mentionDropdownFetchLimit,
712 menuShowMinLength: 2,
718 function setupEmojiDataModel(custom_emoji_views: CustomEmojiView[]) {
719 const groupedEmojis = groupBy(
721 x => x.custom_emoji.category
723 for (const [category, emojis] of Object.entries(groupedEmojis)) {
727 emojis: emojis.map(emoji => ({
728 id: emoji.custom_emoji.shortcode,
729 name: emoji.custom_emoji.shortcode,
730 keywords: emoji.keywords.map(x => x.keyword),
731 skins: [{ src: emoji.custom_emoji.image_url }],
735 customEmojisLookup = new Map(
736 custom_emoji_views.map(view => [view.custom_emoji.shortcode, view])
740 export function updateEmojiDataModel(custom_emoji_view: CustomEmojiView) {
741 const emoji: EmojiMartCustomEmoji = {
742 id: custom_emoji_view.custom_emoji.shortcode,
743 name: custom_emoji_view.custom_emoji.shortcode,
744 keywords: custom_emoji_view.keywords.map(x => x.keyword),
745 skins: [{ src: custom_emoji_view.custom_emoji.image_url }],
747 const categoryIndex = customEmojis.findIndex(
748 x => x.id == custom_emoji_view.custom_emoji.category
750 if (categoryIndex == -1) {
752 id: custom_emoji_view.custom_emoji.category,
753 name: custom_emoji_view.custom_emoji.category,
757 const emojiIndex = customEmojis[categoryIndex].emojis.findIndex(
758 x => x.id == custom_emoji_view.custom_emoji.shortcode
760 if (emojiIndex == -1) {
761 customEmojis[categoryIndex].emojis.push(emoji);
763 customEmojis[categoryIndex].emojis[emojiIndex] = emoji;
766 customEmojisLookup.set(
767 custom_emoji_view.custom_emoji.shortcode,
772 export function removeFromEmojiDataModel(id: number) {
773 let view: CustomEmojiView | undefined;
774 for (const item of customEmojisLookup.values()) {
775 if (item.custom_emoji.id === id) {
781 const categoryIndex = customEmojis.findIndex(
782 x => x.id == view?.custom_emoji.category
784 const emojiIndex = customEmojis[categoryIndex].emojis.findIndex(
785 x => x.id == view?.custom_emoji.shortcode
787 customEmojis[categoryIndex].emojis = customEmojis[
789 ].emojis.splice(emojiIndex, 1);
791 customEmojisLookup.delete(view?.custom_emoji.shortcode);
794 function setupMarkdown() {
795 const markdownItConfig: MarkdownIt.Options = {
801 const emojiDefs = Array.from(customEmojisLookup.entries()).reduce(
802 (main, [key, value]) => ({ ...main, [key]: value }),
805 md = new MarkdownIt(markdownItConfig)
806 .use(markdown_it_sub)
807 .use(markdown_it_sup)
808 .use(markdown_it_footnote)
809 .use(markdown_it_html5_embed, html5EmbedConfig)
810 .use(markdown_it_container, "spoiler", spoilerConfig)
811 .use(markdown_it_emoji, {
815 mdNoImages = new MarkdownIt(markdownItConfig)
816 .use(markdown_it_sub)
817 .use(markdown_it_sup)
818 .use(markdown_it_footnote)
819 .use(markdown_it_html5_embed, html5EmbedConfig)
820 .use(markdown_it_container, "spoiler", spoilerConfig)
821 .use(markdown_it_emoji, {
825 var defaultRenderer = md.renderer.rules.image;
826 md.renderer.rules.image = function (
829 options: MarkdownIt.Options,
833 //Provide custom renderer for our emojis to allow us to add a css class and force size dimensions on them.
834 const item = tokens[idx] as any;
835 const title = item.attrs.length >= 3 ? item.attrs[2][1] : "";
836 const src: string = item.attrs[0][1];
837 const isCustomEmoji = customEmojisLookup.get(title) != undefined;
838 if (!isCustomEmoji) {
839 return defaultRenderer?.(tokens, idx, options, env, self) ?? "";
841 const alt_text = item.content;
842 return `<img class="icon icon-emoji" src="${src}" title="${title}" alt="${alt_text}"/>`;
846 export function getEmojiMart(
847 onEmojiSelect: (e: any) => void,
848 customPickerOptions: any = {}
850 const pickerOptions = {
851 ...customPickerOptions,
852 onEmojiSelect: onEmojiSelect,
853 custom: customEmojis,
855 return new Picker(pickerOptions);
858 var tippyInstance: any;
860 tippyInstance = tippy("[data-tippy-content]");
863 export function setupTippy() {
865 tippyInstance.forEach((e: any) => e.destroy());
866 tippyInstance = tippy("[data-tippy-content]", {
868 // Display on "long press"
869 touch: ["hold", 500],
874 interface PersonTribute {
879 async function personSearch(text: string): Promise<PersonTribute[]> {
880 const users = (await fetchUsers(text)).users;
881 const persons: PersonTribute[] = users.map(pv => {
882 const tribute: PersonTribute = {
883 key: `@${pv.person.name}@${hostname(pv.person.actor_id)}`,
891 interface CommunityTribute {
896 async function communitySearch(text: string): Promise<CommunityTribute[]> {
897 const comms = (await fetchCommunities(text)).communities;
898 const communities: CommunityTribute[] = comms.map(cv => {
899 const tribute: CommunityTribute = {
900 key: `!${cv.community.name}@${hostname(cv.community.actor_id)}`,
908 export function getRecipientIdFromProps(props: any): number {
909 return props.match.params.recipient_id
910 ? Number(props.match.params.recipient_id)
914 export function getIdFromProps(props: any): number | undefined {
915 const id = props.match.params.post_id;
916 return id ? Number(id) : undefined;
919 export function getCommentIdFromProps(props: any): number | undefined {
920 const id = props.match.params.comment_id;
921 return id ? Number(id) : undefined;
924 export function editCommentRes(data: CommentView, comments?: CommentView[]) {
925 const found = comments?.find(c => c.comment.id == data.comment.id);
927 found.comment.content = data.comment.content;
928 found.comment.distinguished = data.comment.distinguished;
929 found.comment.updated = data.comment.updated;
930 found.comment.removed = data.comment.removed;
931 found.comment.deleted = data.comment.deleted;
932 found.counts.upvotes = data.counts.upvotes;
933 found.counts.downvotes = data.counts.downvotes;
934 found.counts.score = data.counts.score;
938 export function saveCommentRes(data: CommentView, comments?: CommentView[]) {
939 const found = comments?.find(c => c.comment.id == data.comment.id);
941 found.saved = data.saved;
945 export function updatePersonBlock(
946 data: BlockPersonResponse,
947 myUserInfo: MyUserInfo | undefined = UserService.Instance.myUserInfo
949 const mui = myUserInfo;
952 mui.person_blocks.push({
953 person: mui.local_user_view.person,
954 target: data.person_view.person,
956 toast(`${i18n.t("blocked")} ${data.person_view.person.name}`);
958 mui.person_blocks = mui.person_blocks.filter(
959 i => i.target.id != data.person_view.person.id
961 toast(`${i18n.t("unblocked")} ${data.person_view.person.name}`);
966 export function updateCommunityBlock(
967 data: BlockCommunityResponse,
968 myUserInfo: MyUserInfo | undefined = UserService.Instance.myUserInfo
970 const mui = myUserInfo;
973 mui.community_blocks.push({
974 person: mui.local_user_view.person,
975 community: data.community_view.community,
977 toast(`${i18n.t("blocked")} ${data.community_view.community.name}`);
979 mui.community_blocks = mui.community_blocks.filter(
980 i => i.community.id != data.community_view.community.id
982 toast(`${i18n.t("unblocked")} ${data.community_view.community.name}`);
987 export function createCommentLikeRes(
989 comments?: CommentView[]
991 const found = comments?.find(c => c.comment.id === data.comment.id);
993 found.counts.score = data.counts.score;
994 found.counts.upvotes = data.counts.upvotes;
995 found.counts.downvotes = data.counts.downvotes;
996 if (data.my_vote !== null) {
997 found.my_vote = data.my_vote;
1002 export function createPostLikeFindRes(data: PostView, posts?: PostView[]) {
1003 const found = posts?.find(p => p.post.id == data.post.id);
1005 createPostLikeRes(data, found);
1009 export function createPostLikeRes(data: PostView, post_view?: PostView) {
1011 post_view.counts.score = data.counts.score;
1012 post_view.counts.upvotes = data.counts.upvotes;
1013 post_view.counts.downvotes = data.counts.downvotes;
1014 if (data.my_vote !== null) {
1015 post_view.my_vote = data.my_vote;
1020 export function editPostFindRes(data: PostView, posts?: PostView[]) {
1021 const found = posts?.find(p => p.post.id == data.post.id);
1023 editPostRes(data, found);
1027 export function editPostRes(data: PostView, post: PostView) {
1029 post.post.url = data.post.url;
1030 post.post.name = data.post.name;
1031 post.post.nsfw = data.post.nsfw;
1032 post.post.deleted = data.post.deleted;
1033 post.post.removed = data.post.removed;
1034 post.post.featured_community = data.post.featured_community;
1035 post.post.featured_local = data.post.featured_local;
1036 post.post.body = data.post.body;
1037 post.post.locked = data.post.locked;
1038 post.saved = data.saved;
1042 // TODO possible to make these generic?
1043 export function updatePostReportRes(
1044 data: PostReportView,
1045 reports?: PostReportView[]
1047 const found = reports?.find(p => p.post_report.id == data.post_report.id);
1049 found.post_report = data.post_report;
1053 export function updateCommentReportRes(
1054 data: CommentReportView,
1055 reports?: CommentReportView[]
1057 const found = reports?.find(
1058 c => c.comment_report.id == data.comment_report.id
1061 found.comment_report = data.comment_report;
1065 export function updatePrivateMessageReportRes(
1066 data: PrivateMessageReportView,
1067 reports?: PrivateMessageReportView[]
1069 const found = reports?.find(
1070 c => c.private_message_report.id == data.private_message_report.id
1073 found.private_message_report = data.private_message_report;
1077 export function updateRegistrationApplicationRes(
1078 data: RegistrationApplicationView,
1079 applications?: RegistrationApplicationView[]
1081 const found = applications?.find(
1082 ra => ra.registration_application.id == data.registration_application.id
1085 found.registration_application = data.registration_application;
1086 found.admin = data.admin;
1087 found.creator_local_user = data.creator_local_user;
1091 export function commentsToFlatNodes(comments: CommentView[]): CommentNodeI[] {
1092 const nodes: CommentNodeI[] = [];
1093 for (const comment of comments) {
1094 nodes.push({ comment_view: comment, children: [], depth: 0 });
1099 export function convertCommentSortType(sort: SortType): CommentSortType {
1103 sort == "TopWeek" ||
1104 sort == "TopMonth" ||
1108 } else if (sort == "New") {
1110 } else if (sort == "Hot" || sort == "Active") {
1117 export function buildCommentsTree(
1118 comments: CommentView[],
1119 parentComment: boolean
1121 const map = new Map<number, CommentNodeI>();
1122 const depthOffset = !parentComment
1124 : getDepthFromComment(comments[0].comment) ?? 0;
1126 for (const comment_view of comments) {
1127 const depthI = getDepthFromComment(comment_view.comment) ?? 0;
1128 const depth = depthI ? depthI - depthOffset : 0;
1129 const node: CommentNodeI = {
1134 map.set(comment_view.comment.id, { ...node });
1137 const tree: CommentNodeI[] = [];
1139 // if its a parent comment fetch, then push the first comment to the top node.
1140 if (parentComment) {
1141 const cNode = map.get(comments[0].comment.id);
1147 for (const comment_view of comments) {
1148 const child = map.get(comment_view.comment.id);
1150 const parent_id = getCommentParentId(comment_view.comment);
1152 const parent = map.get(parent_id);
1153 // Necessary because blocked comment might not exist
1155 parent.children.push(child);
1158 if (!parentComment) {
1168 export function getCommentParentId(comment?: CommentI): number | undefined {
1169 const split = comment?.path.split(".");
1173 return split && split.length > 1
1174 ? Number(split.at(split.length - 2))
1178 export function getDepthFromComment(comment?: CommentI): number | undefined {
1179 const len = comment?.path.split(".").length;
1180 return len ? len - 2 : undefined;
1183 export function insertCommentIntoTree(
1184 tree: CommentNodeI[],
1186 parentComment: boolean
1188 // Building a fake node to be used for later
1189 const node: CommentNodeI = {
1195 const parentId = getCommentParentId(cv.comment);
1197 const parent_comment = searchCommentTree(tree, parentId);
1198 if (parent_comment) {
1199 node.depth = parent_comment.depth + 1;
1200 parent_comment.children.unshift(node);
1202 } else if (!parentComment) {
1207 export function searchCommentTree(
1208 tree: CommentNodeI[],
1210 ): CommentNodeI | undefined {
1211 for (const node of tree) {
1212 if (node.comment_view.comment.id === id) {
1216 for (const child of node.children) {
1217 const res = searchCommentTree([child], id);
1227 export const colorList: string[] = [
1237 function hsl(num: number) {
1238 return `hsla(${num}, 35%, 50%, 1)`;
1241 export function hostname(url: string): string {
1242 const cUrl = new URL(url);
1243 return cUrl.port ? `${cUrl.hostname}:${cUrl.port}` : `${cUrl.hostname}`;
1246 export function validTitle(title?: string): boolean {
1247 // Initial title is null, minimum length is taken care of by textarea's minLength={3}
1248 if (!title || title.length < 3) return true;
1250 const regex = new RegExp(/.*\S.*/, "g");
1252 return regex.test(title);
1255 export function siteBannerCss(banner: string): string {
1257 background-image: linear-gradient( rgba(0, 0, 0, 0.8), rgba(0, 0, 0, 0.8) ) ,url("${banner}"); \
1258 background-attachment: fixed; \
1259 background-position: top; \
1260 background-repeat: no-repeat; \
1261 background-size: 100% cover; \
1264 max-height: 100vh; \
1268 export function isBrowser() {
1269 return typeof window !== "undefined";
1272 export function setIsoData(context: any): IsoData {
1273 // If its the browser, you need to deserialize the data from the window
1275 return window.isoData;
1276 } else return context.router.staticContext;
1279 export function wsSubscribe(parseMessage: any): Subscription | undefined {
1281 return WebSocketService.Instance.subject
1282 .pipe(retryWhen(errors => errors.pipe(delay(3000), take(10))))
1284 msg => parseMessage(msg),
1285 err => console.error(err),
1286 () => console.log("complete")
1293 moment.updateLocale("en", {
1314 export function saveScrollPosition(context: any) {
1315 const path: string = context.router.route.location.pathname;
1316 const y = window.scrollY;
1317 sessionStorage.setItem(`scrollPosition_${path}`, y.toString());
1320 export function restoreScrollPosition(context: any) {
1321 const path: string = context.router.route.location.pathname;
1322 const y = Number(sessionStorage.getItem(`scrollPosition_${path}`));
1323 window.scrollTo(0, y);
1326 export function showLocal(isoData: IsoData): boolean {
1327 return isoData.site_res.site_view.local_site.federation_enabled;
1330 export interface Choice {
1336 export function getUpdatedSearchId(id?: number | null, urlId?: number | null) {
1339 : ((id ?? urlId) === 0 ? undefined : id ?? urlId)?.toString();
1342 export function communityToChoice(cv: CommunityView): Choice {
1344 value: cv.community.id.toString(),
1345 label: communitySelectName(cv),
1349 export function personToChoice(pvs: PersonView): Choice {
1351 value: pvs.person.id.toString(),
1352 label: personSelectName(pvs),
1356 export async function fetchCommunities(q: string) {
1357 const form: Search = {
1359 type_: "Communities",
1361 listing_type: "All",
1364 auth: myAuth(false),
1366 const client = new LemmyHttp(getHttpBase());
1367 return client.search(form);
1370 export async function fetchUsers(q: string) {
1371 const form: Search = {
1375 listing_type: "All",
1378 auth: myAuth(false),
1380 const client = new LemmyHttp(getHttpBase());
1381 return client.search(form);
1384 export function communitySelectName(cv: CommunityView): string {
1385 return cv.community.local
1386 ? cv.community.title
1387 : `${hostname(cv.community.actor_id)}/${cv.community.title}`;
1390 export function personSelectName({
1391 person: { display_name, name, local, actor_id },
1392 }: PersonView): string {
1393 const pName = display_name ?? name;
1394 return local ? pName : `${hostname(actor_id)}/${pName}`;
1397 export function initializeSite(site?: GetSiteResponse) {
1398 UserService.Instance.myUserInfo = site?.my_user;
1399 i18n.changeLanguage(getLanguages()[0]);
1401 setupEmojiDataModel(site.custom_emojis);
1406 const SHORTNUM_SI_FORMAT = new Intl.NumberFormat("en-US", {
1407 maximumSignificantDigits: 3,
1409 notation: "compact",
1410 compactDisplay: "short",
1413 export function numToSI(value: number): string {
1414 return SHORTNUM_SI_FORMAT.format(value);
1417 export function isBanned(ps: Person): boolean {
1418 const expires = ps.ban_expires;
1419 // Add Z to convert from UTC date
1420 // TODO this check probably isn't necessary anymore
1422 if (ps.banned && new Date(expires + "Z") > new Date()) {
1432 export function myAuth(throwErr = true): string | undefined {
1433 return UserService.Instance.auth(throwErr);
1436 export function enableDownvotes(siteRes: GetSiteResponse): boolean {
1437 return siteRes.site_view.local_site.enable_downvotes;
1440 export function enableNsfw(siteRes: GetSiteResponse): boolean {
1441 return siteRes.site_view.local_site.enable_nsfw;
1444 export function postToCommentSortType(sort: SortType): CommentSortType {
1459 export function canCreateCommunity(
1460 siteRes: GetSiteResponse,
1461 myUserInfo = UserService.Instance.myUserInfo
1463 const adminOnly = siteRes.site_view.local_site.community_creation_admin_only;
1464 // TODO: Make this check if user is logged on as well
1465 return !adminOnly || amAdmin(myUserInfo);
1468 export function isPostBlocked(
1470 myUserInfo: MyUserInfo | undefined = UserService.Instance.myUserInfo
1473 (myUserInfo?.community_blocks
1474 .map(c => c.community.id)
1475 .includes(pv.community.id) ||
1476 myUserInfo?.person_blocks
1477 .map(p => p.target.id)
1478 .includes(pv.creator.id)) ??
1483 /// Checks to make sure you can view NSFW posts. Returns true if you can.
1484 export function nsfwCheck(
1486 myUserInfo = UserService.Instance.myUserInfo
1488 const nsfw = pv.post.nsfw || pv.community.nsfw;
1489 const myShowNsfw = myUserInfo?.local_user_view.local_user.show_nsfw ?? false;
1490 return !nsfw || (nsfw && myShowNsfw);
1493 export function getRandomFromList<T>(list: T[]): T | undefined {
1494 return list.length == 0
1496 : list.at(Math.floor(Math.random() * list.length));
1500 * This shows what language you can select
1502 * Use showAll for the site form
1503 * Use showSite for the profile and community forms
1504 * Use false for both those to filter on your profile and site ones
1506 export function selectableLanguages(
1507 allLanguages: Language[],
1508 siteLanguages: number[],
1511 myUserInfo = UserService.Instance.myUserInfo
1513 const allLangIds = allLanguages.map(l => l.id);
1514 let myLangs = myUserInfo?.discussion_languages ?? allLangIds;
1515 myLangs = myLangs.length == 0 ? allLangIds : myLangs;
1516 const siteLangs = siteLanguages.length == 0 ? allLangIds : siteLanguages;
1519 return allLanguages;
1522 return allLanguages.filter(x => siteLangs.includes(x.id));
1525 .filter(x => siteLangs.includes(x.id))
1526 .filter(x => myLangs.includes(x.id));
1531 export function uploadImage(image: File): Promise<UploadImageResponse> {
1532 const client = new LemmyHttp(getHttpBase());
1534 return client.uploadImage({ image });
1537 interface EmojiMartCategory {
1540 emojis: EmojiMartCustomEmoji[];
1543 interface EmojiMartCustomEmoji {
1547 skins: EmojiMartSkin[];
1550 interface EmojiMartSkin {
1554 const groupBy = <T>(
1556 predicate: (value: T, index: number, array: T[]) => string
1558 array.reduce((acc, value, index, array) => {
1559 (acc[predicate(value, index, array)] ||= []).push(value);
1561 }, {} as { [key: string]: T[] });
1563 export type QueryParams<T extends Record<string, any>> = {
1564 [key in keyof T]?: string;
1567 export function getQueryParams<T extends Record<string, any>>(processors: {
1568 [K in keyof T]: (param: string) => T[K];
1571 const searchParams = new URLSearchParams(window.location.search);
1573 return Array.from(Object.entries(processors)).reduce(
1574 (acc, [key, process]) => ({
1576 [key]: process(searchParams.get(key)),
1585 export function getQueryString<T extends Record<string, string | undefined>>(
1588 return Object.entries(obj)
1589 .filter(([, val]) => val !== undefined && val !== null)
1591 (acc, [key, val], index) => `${acc}${index > 0 ? "&" : ""}${key}=${val}`,
1596 export function isAuthPath(pathname: string) {
1597 return /create_.*|inbox|settings|setup|admin|reports|registration_applications/g.test(
1602 export function canShare() {
1603 return isBrowser() && !!navigator.canShare;
1606 export function share(shareData: ShareData) {
1608 navigator.share(shareData);