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 = 40n;
74 export const trendingFetchLimit = 6n;
75 export const mentionDropdownFetchLimit = 10;
76 export const commentTreeMaxDepth = 8;
77 export const markdownFieldCharacterLimit = 50000;
78 export const maxUploadImages = 20n;
79 export const concurrentImageUpload = 4;
81 export const relTags = "noopener nofollow";
83 export const emDash = "\u2014";
85 export type ThemeColor =
108 let customEmojis: EmojiMartCategory[] = [];
109 export let customEmojisLookup: Map<string, CustomEmojiView> = new Map<
114 const DEFAULT_ALPHABET =
115 "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
117 function getRandomCharFromAlphabet(alphabet: string): string {
118 return alphabet.charAt(Math.floor(Math.random() * alphabet.length));
121 export function getIdFromString(id?: string): number | undefined {
122 return id && id !== "0" && !Number.isNaN(Number(id)) ? Number(id) : undefined;
125 export function getPageFromString(page?: string): bigint {
126 return page && !Number.isNaN(Number(page)) ? BigInt(page) : BigInt(1);
129 export function randomStr(
130 idDesiredLength = 20,
131 alphabet = DEFAULT_ALPHABET
134 * Create n-long array and map it to random chars from given alphabet.
135 * Then join individual chars as string
137 return Array.from({ length: idDesiredLength })
139 return getRandomCharFromAlphabet(alphabet);
144 const html5EmbedConfig = {
146 useImageSyntax: true, // Enables video/audio embed with ![]() syntax (default)
148 audio: 'controls preload="metadata"',
149 video: 'width="100%" max-height="100%" controls loop preload="metadata"',
154 const spoilerConfig = {
155 validate: (params: string) => {
156 return params.trim().match(/^spoiler\s+(.*)$/);
159 render: (tokens: any, idx: any) => {
160 var m = tokens[idx].info.trim().match(/^spoiler\s+(.*)$/);
162 if (tokens[idx].nesting === 1) {
164 return `<details><summary> ${md.utils.escapeHtml(m[1])} </summary>\n`;
167 return "</details>\n";
172 export let md: MarkdownIt = new MarkdownIt();
174 export let mdNoImages: MarkdownIt = new MarkdownIt();
176 export function hotRankComment(comment_view: CommentView): number {
177 return hotRank(comment_view.counts.score, comment_view.comment.published);
180 export function hotRankActivePost(post_view: PostView): number {
181 return hotRank(post_view.counts.score, post_view.counts.newest_comment_time);
184 export function hotRankPost(post_view: PostView): number {
185 return hotRank(post_view.counts.score, post_view.post.published);
188 export function hotRank(score: bigint, timeStr: string): number {
189 // Rank = ScaleFactor * sign(Score) * log(1 + abs(Score)) / (Time + 2)^Gravity
190 let date: Date = new Date(timeStr + "Z"); // Add Z to convert from UTC date
191 let now: Date = new Date();
192 let hoursElapsed: number = (now.getTime() - date.getTime()) / 36e5;
195 (10000 * Math.log10(Math.max(1, Number(3n + score)))) /
196 Math.pow(hoursElapsed + 2, 1.8);
198 // console.log(`Comment: ${comment.content}\nRank: ${rank}\nScore: ${comment.score}\nHours: ${hoursElapsed}`);
203 export function mdToHtml(text: string) {
204 return { __html: md.render(text) };
207 export function mdToHtmlNoImages(text: string) {
208 return { __html: mdNoImages.render(text) };
211 export function mdToHtmlInline(text: string) {
212 return { __html: md.renderInline(text) };
215 export function getUnixTime(text?: string): bigint | undefined {
216 return text ? BigInt(new Date(text).getTime() / 1000) : undefined;
219 export function futureDaysToUnixTime(days?: number): bigint | undefined {
223 new Date(Date.now() + 1000 * 60 * 60 * 24 * days).getTime() / 1000
229 export function canMod(
231 mods?: CommunityModeratorView[],
232 admins?: PersonView[],
233 myUserInfo = UserService.Instance.myUserInfo,
236 // You can do moderator actions only on the mods added after you.
239 ?.map(a => a.person.id)
240 .concat(mods?.map(m => m.moderator.id) ?? []) ?? [];
243 let myIndex = adminsThenMods.findIndex(
244 id => id == myUserInfo.local_user_view.person.id
249 // onSelf +1 on mod actions not for yourself, IE ban, remove, etc
250 adminsThenMods = adminsThenMods.slice(0, myIndex + (onSelf ? 0 : 1));
251 return !adminsThenMods.includes(creator_id);
258 export function canAdmin(
260 admins?: PersonView[],
261 myUserInfo = UserService.Instance.myUserInfo,
264 return canMod(creatorId, undefined, admins, myUserInfo, onSelf);
267 export function isMod(
269 mods?: CommunityModeratorView[]
271 return mods?.map(m => m.moderator.id).includes(creatorId) ?? false;
274 export function amMod(
275 mods?: CommunityModeratorView[],
276 myUserInfo = UserService.Instance.myUserInfo
278 return myUserInfo ? isMod(myUserInfo.local_user_view.person.id, mods) : false;
281 export function isAdmin(creatorId: number, admins?: PersonView[]): boolean {
282 return admins?.map(a => a.person.id).includes(creatorId) ?? false;
285 export function amAdmin(myUserInfo = UserService.Instance.myUserInfo): boolean {
286 return myUserInfo?.local_user_view.person.admin ?? false;
289 export function amCommunityCreator(
291 mods?: CommunityModeratorView[],
292 myUserInfo = UserService.Instance.myUserInfo
294 let myId = myUserInfo?.local_user_view.person.id;
295 // Don't allow mod actions on yourself
296 return myId == mods?.at(0)?.moderator.id && myId != creator_id;
299 export function amSiteCreator(
301 admins?: PersonView[],
302 myUserInfo = UserService.Instance.myUserInfo
304 let myId = myUserInfo?.local_user_view.person.id;
305 return myId == admins?.at(0)?.person.id && myId != creator_id;
308 export function amTopMod(
309 mods: CommunityModeratorView[],
310 myUserInfo = UserService.Instance.myUserInfo
312 return mods.at(0)?.moderator.id == myUserInfo?.local_user_view.person.id;
315 const imageRegex = /(http)?s?:?(\/\/[^"']*\.(?:jpg|jpeg|gif|png|svg|webp))/;
316 const videoRegex = /(http)?s?:?(\/\/[^"']*\.(?:mp4|webm))/;
318 export function isImage(url: string) {
319 return imageRegex.test(url);
322 export function isVideo(url: string) {
323 return videoRegex.test(url);
326 export function validURL(str: string) {
327 return !!new URL(str);
330 export function communityRSSUrl(actorId: string, sort: string): string {
331 let url = new URL(actorId);
332 return `${url.origin}/feeds${url.pathname}.xml?sort=${sort}`;
335 export function validEmail(email: string) {
337 /^(([^\s"(),.:;<>@[\\\]]+(\.[^\s"(),.:;<>@[\\\]]+)*)|(".+"))@((\[(?:\d{1,3}\.){3}\d{1,3}])|(([\dA-Za-z\-]+\.)+[A-Za-z]{2,}))$/;
338 return re.test(String(email).toLowerCase());
341 export function capitalizeFirstLetter(str: string): string {
342 return str.charAt(0).toUpperCase() + str.slice(1);
345 export async function getSiteMetadata(url: string) {
346 let form: GetSiteMetadata = { url };
347 let client = new LemmyHttp(getHttpBase());
348 return client.getSiteMetadata(form);
351 export function getDataTypeString(dt: DataType) {
352 return dt === DataType.Post ? "Post" : "Comment";
355 export function debounce<T extends any[], R>(
356 func: (...e: T) => R,
360 // 'private' variable for instance
361 // The returned function will be able to reference this due to closure.
362 // Each call to the returned function will share this common timer.
363 let timeout: NodeJS.Timeout | null;
365 // Calling debounce returns a new anonymous function
367 // reference the context and args for the setTimeout function
368 const args = arguments;
370 // Should the function be called now? If immediate is true
371 // and not already in a timeout then the answer is: Yes
372 const callNow = immediate && !timeout;
374 // This is the basic debounce behavior where you can call this
375 // function several times, but it will only execute once
376 // [before or after imposing a delay].
377 // Each time the returned function is called, the timer starts over.
378 clearTimeout(timeout ?? undefined);
380 // Set the new timeout
381 timeout = setTimeout(function () {
382 // Inside the timeout function, clear the timeout variable
383 // which will let the next execution run when in 'immediate' mode
386 // Check if the function already ran with the immediate flag
388 // Call the original function with apply
389 // apply lets you define the 'this' object as well as the arguments
390 // (both captured before setTimeout)
391 func.apply(this, args);
395 // Immediate mode and no wait timer? Execute the function..
396 if (callNow) func.apply(this, args);
400 export function getLanguages(
402 myUserInfo = UserService.Instance.myUserInfo
404 let myLang = myUserInfo?.local_user_view.local_user.interface_language;
405 let lang = override || myLang || "browser";
407 if (lang == "browser" && isBrowser()) {
408 return getBrowserLanguages();
414 function getBrowserLanguages(): string[] {
415 // Intersect lemmy's langs, with the browser langs
416 let langs = languages ? languages.map(l => l.code) : ["en"];
418 // NOTE, mobile browsers seem to be missing this list, so append en
419 let allowedLangs = navigator.languages
421 .filter(v => langs.includes(v));
425 export async function fetchThemeList(): Promise<string[]> {
426 return fetch("/css/themelist").then(res => res.json());
429 export async function setTheme(theme: string, forceReload = false) {
433 if (theme === "browser" && !forceReload) {
436 // This is only run on a force reload
437 if (theme == "browser") {
441 let themeList = await fetchThemeList();
443 // Unload all the other themes
444 for (var i = 0; i < themeList.length; i++) {
445 let styleSheet = document.getElementById(themeList[i]);
447 styleSheet.setAttribute("disabled", "disabled");
452 .getElementById("default-light")
453 ?.setAttribute("disabled", "disabled");
454 document.getElementById("default-dark")?.setAttribute("disabled", "disabled");
456 // Load the theme dynamically
457 let cssLoc = `/css/themes/${theme}.css`;
459 loadCss(theme, cssLoc);
460 document.getElementById(theme)?.removeAttribute("disabled");
463 export function loadCss(id: string, loc: string) {
464 if (!document.getElementById(id)) {
465 var head = document.getElementsByTagName("head")[0];
466 var link = document.createElement("link");
468 link.rel = "stylesheet";
469 link.type = "text/css";
472 head.appendChild(link);
476 export function objectFlip(obj: any) {
478 Object.keys(obj).forEach(key => {
484 export function showAvatars(
485 myUserInfo = UserService.Instance.myUserInfo
487 return myUserInfo?.local_user_view.local_user.show_avatars ?? true;
490 export function showScores(
491 myUserInfo = UserService.Instance.myUserInfo
493 return myUserInfo?.local_user_view.local_user.show_scores ?? true;
496 export function isCakeDay(published: string): boolean {
497 // moment(undefined) or moment.utc(undefined) returns the current date/time
498 // moment(null) or moment.utc(null) returns null
499 const createDate = moment.utc(published).local();
500 const currentDate = moment(new Date());
503 createDate.date() === currentDate.date() &&
504 createDate.month() === currentDate.month() &&
505 createDate.year() !== currentDate.year()
509 export function toast(text: string, background: ThemeColor = "success") {
511 const backgroundColor = `var(--${background})`;
514 backgroundColor: backgroundColor,
522 export function pictrsDeleteToast(filename: string, deleteUrl: string) {
524 const clickToDeleteText = i18n.t("click_to_delete_picture", { filename });
525 const deletePictureText = i18n.t("picture_deleted", {
528 const failedDeletePictureText = i18n.t("failed_to_delete_picture", {
532 const backgroundColor = `var(--light)`;
534 const toast = Toastify({
535 text: clickToDeleteText,
536 backgroundColor: backgroundColor,
542 fetch(deleteUrl).then(res => {
544 if (res.ok === true) {
545 alert(deletePictureText);
547 alert(failedDeletePictureText);
559 interface NotifyInfo {
566 export function messageToastify(info: NotifyInfo, router: any) {
568 let htmlBody = info.body ? md.render(info.body) : "";
569 let backgroundColor = `var(--light)`;
571 let toast = Toastify({
572 text: `${htmlBody}<br />${info.name}`,
574 backgroundColor: backgroundColor,
575 className: "text-dark",
584 router.history.push(info.link);
592 export function notifyPost(post_view: PostView, router: any) {
593 let info: NotifyInfo = {
594 name: post_view.community.name,
595 icon: post_view.community.icon,
596 link: `/post/${post_view.post.id}`,
597 body: post_view.post.name,
599 notify(info, router);
602 export function notifyComment(comment_view: CommentView, router: any) {
603 let info: NotifyInfo = {
604 name: comment_view.creator.name,
605 icon: comment_view.creator.avatar,
606 link: `/comment/${comment_view.comment.id}`,
607 body: comment_view.comment.content,
609 notify(info, router);
612 export function notifyPrivateMessage(pmv: PrivateMessageView, router: any) {
613 let info: NotifyInfo = {
614 name: pmv.creator.name,
615 icon: pmv.creator.avatar,
617 body: pmv.private_message.content,
619 notify(info, router);
622 function notify(info: NotifyInfo, router: any) {
623 messageToastify(info, router);
625 if (Notification.permission !== "granted") Notification.requestPermission();
627 var notification = new Notification(info.name, {
628 ...{ body: info.body },
629 ...(info.icon && { icon: info.icon }),
632 notification.onclick = (ev: Event): any => {
634 router.history.push(info.link);
639 export function setupTribute() {
641 noMatchTemplate: function () {
648 menuItemTemplate: (item: any) => {
649 let shortName = `:${item.original.key}:`;
650 return `${item.original.val} ${shortName}`;
652 selectTemplate: (item: any) => {
653 let customEmoji = customEmojisLookup.get(
656 if (customEmoji == undefined) return `${item.original.val}`;
658 return `![${customEmoji.alt_text}](${customEmoji.image_url} "${customEmoji.shortcode}")`;
660 values: Object.entries(emojiShortName)
662 return { key: e[1], val: e[0] };
665 Array.from(customEmojisLookup.entries()).map(k => ({
667 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}" />`,
671 autocompleteMode: true,
673 // menuItemLimit: mentionDropdownFetchLimit,
674 menuShowMinLength: 2,
679 selectTemplate: (item: any) => {
680 let it: PersonTribute = item.original;
681 return `[${it.key}](${it.view.person.actor_id})`;
683 values: debounce(async (text: string, cb: any) => {
684 cb(await personSearch(text));
687 autocompleteMode: true,
689 // menuItemLimit: mentionDropdownFetchLimit,
690 menuShowMinLength: 2,
696 selectTemplate: (item: any) => {
697 let it: CommunityTribute = item.original;
698 return `[${it.key}](${it.view.community.actor_id})`;
700 values: debounce(async (text: string, cb: any) => {
701 cb(await communitySearch(text));
704 autocompleteMode: true,
706 // menuItemLimit: mentionDropdownFetchLimit,
707 menuShowMinLength: 2,
713 function setupEmojiDataModel(custom_emoji_views: CustomEmojiView[]) {
714 let groupedEmojis = groupBy(custom_emoji_views, x => x.custom_emoji.category);
715 for (const [category, emojis] of Object.entries(groupedEmojis)) {
719 emojis: emojis.map(emoji => ({
720 id: emoji.custom_emoji.shortcode,
721 name: emoji.custom_emoji.shortcode,
722 keywords: emoji.keywords.map(x => x.keyword),
723 skins: [{ src: emoji.custom_emoji.image_url }],
727 customEmojisLookup = new Map(
728 custom_emoji_views.map(view => [view.custom_emoji.shortcode, view])
732 export function updateEmojiDataModel(custom_emoji_view: CustomEmojiView) {
733 const emoji: EmojiMartCustomEmoji = {
734 id: custom_emoji_view.custom_emoji.shortcode,
735 name: custom_emoji_view.custom_emoji.shortcode,
736 keywords: custom_emoji_view.keywords.map(x => x.keyword),
737 skins: [{ src: custom_emoji_view.custom_emoji.image_url }],
739 let categoryIndex = customEmojis.findIndex(
740 x => x.id == custom_emoji_view.custom_emoji.category
742 if (categoryIndex == -1) {
744 id: custom_emoji_view.custom_emoji.category,
745 name: custom_emoji_view.custom_emoji.category,
749 let emojiIndex = customEmojis[categoryIndex].emojis.findIndex(
750 x => x.id == custom_emoji_view.custom_emoji.shortcode
752 if (emojiIndex == -1) {
753 customEmojis[categoryIndex].emojis.push(emoji);
755 customEmojis[categoryIndex].emojis[emojiIndex] = emoji;
758 customEmojisLookup.set(
759 custom_emoji_view.custom_emoji.shortcode,
764 export function removeFromEmojiDataModel(id: number) {
765 let view: CustomEmojiView | undefined;
766 for (let item of customEmojisLookup.values()) {
767 if (item.custom_emoji.id === id) {
773 const categoryIndex = customEmojis.findIndex(
774 x => x.id == view?.custom_emoji.category
776 const emojiIndex = customEmojis[categoryIndex].emojis.findIndex(
777 x => x.id == view?.custom_emoji.shortcode
779 customEmojis[categoryIndex].emojis = customEmojis[
781 ].emojis.splice(emojiIndex, 1);
783 customEmojisLookup.delete(view?.custom_emoji.shortcode);
786 function setupMarkdown() {
787 const markdownItConfig: MarkdownIt.Options = {
793 const emojiDefs = Array.from(customEmojisLookup.entries()).reduce(
794 (main, [key, value]) => ({ ...main, [key]: value }),
797 md = new MarkdownIt(markdownItConfig)
798 .use(markdown_it_sub)
799 .use(markdown_it_sup)
800 .use(markdown_it_footnote)
801 .use(markdown_it_html5_embed, html5EmbedConfig)
802 .use(markdown_it_container, "spoiler", spoilerConfig)
803 .use(markdown_it_emoji, {
807 mdNoImages = new MarkdownIt(markdownItConfig)
808 .use(markdown_it_sub)
809 .use(markdown_it_sup)
810 .use(markdown_it_footnote)
811 .use(markdown_it_html5_embed, html5EmbedConfig)
812 .use(markdown_it_container, "spoiler", spoilerConfig)
813 .use(markdown_it_emoji, {
817 var defaultRenderer = md.renderer.rules.image;
818 md.renderer.rules.image = function (
821 options: MarkdownIt.Options,
825 //Provide custom renderer for our emojis to allow us to add a css class and force size dimensions on them.
826 const item = tokens[idx] as any;
827 const title = item.attrs.length >= 3 ? item.attrs[2][1] : "";
828 const src: string = item.attrs[0][1];
829 const isCustomEmoji = customEmojisLookup.get(title) != undefined;
830 if (!isCustomEmoji) {
831 return defaultRenderer?.(tokens, idx, options, env, self) ?? "";
833 const alt_text = item.content;
834 return `<img class="icon icon-emoji" src="${src}" title="${title}" alt="${alt_text}"/>`;
838 export function getEmojiMart(
839 onEmojiSelect: (e: any) => void,
840 customPickerOptions: any = {}
842 const pickerOptions = {
843 ...customPickerOptions,
844 onEmojiSelect: onEmojiSelect,
845 custom: customEmojis,
847 return new Picker(pickerOptions);
850 var tippyInstance: any;
852 tippyInstance = tippy("[data-tippy-content]");
855 export function setupTippy() {
857 tippyInstance.forEach((e: any) => e.destroy());
858 tippyInstance = tippy("[data-tippy-content]", {
860 // Display on "long press"
861 touch: ["hold", 500],
866 interface PersonTribute {
871 async function personSearch(text: string): Promise<PersonTribute[]> {
872 let users = (await fetchUsers(text)).users;
873 let persons: PersonTribute[] = users.map(pv => {
874 let tribute: PersonTribute = {
875 key: `@${pv.person.name}@${hostname(pv.person.actor_id)}`,
883 interface CommunityTribute {
888 async function communitySearch(text: string): Promise<CommunityTribute[]> {
889 let comms = (await fetchCommunities(text)).communities;
890 let communities: CommunityTribute[] = comms.map(cv => {
891 let tribute: CommunityTribute = {
892 key: `!${cv.community.name}@${hostname(cv.community.actor_id)}`,
900 export function getRecipientIdFromProps(props: any): number {
901 return props.match.params.recipient_id
902 ? Number(props.match.params.recipient_id)
906 export function getIdFromProps(props: any): number | undefined {
907 let id = props.match.params.post_id;
908 return id ? Number(id) : undefined;
911 export function getCommentIdFromProps(props: any): number | undefined {
912 let id = props.match.params.comment_id;
913 return id ? Number(id) : undefined;
916 export function editCommentRes(data: CommentView, comments?: CommentView[]) {
917 let found = comments?.find(c => c.comment.id == data.comment.id);
919 found.comment.content = data.comment.content;
920 found.comment.distinguished = data.comment.distinguished;
921 found.comment.updated = data.comment.updated;
922 found.comment.removed = data.comment.removed;
923 found.comment.deleted = data.comment.deleted;
924 found.counts.upvotes = data.counts.upvotes;
925 found.counts.downvotes = data.counts.downvotes;
926 found.counts.score = data.counts.score;
930 export function saveCommentRes(data: CommentView, comments?: CommentView[]) {
931 let found = comments?.find(c => c.comment.id == data.comment.id);
933 found.saved = data.saved;
937 export function updatePersonBlock(
938 data: BlockPersonResponse,
939 myUserInfo: MyUserInfo | undefined = UserService.Instance.myUserInfo
941 let mui = myUserInfo;
944 mui.person_blocks.push({
945 person: mui.local_user_view.person,
946 target: data.person_view.person,
948 toast(`${i18n.t("blocked")} ${data.person_view.person.name}`);
950 mui.person_blocks = mui.person_blocks.filter(
951 i => i.target.id != data.person_view.person.id
953 toast(`${i18n.t("unblocked")} ${data.person_view.person.name}`);
958 export function updateCommunityBlock(
959 data: BlockCommunityResponse,
960 myUserInfo: MyUserInfo | undefined = UserService.Instance.myUserInfo
962 let mui = myUserInfo;
965 mui.community_blocks.push({
966 person: mui.local_user_view.person,
967 community: data.community_view.community,
969 toast(`${i18n.t("blocked")} ${data.community_view.community.name}`);
971 mui.community_blocks = mui.community_blocks.filter(
972 i => i.community.id != data.community_view.community.id
974 toast(`${i18n.t("unblocked")} ${data.community_view.community.name}`);
979 export function createCommentLikeRes(
981 comments?: CommentView[]
983 let found = comments?.find(c => c.comment.id === data.comment.id);
985 found.counts.score = data.counts.score;
986 found.counts.upvotes = data.counts.upvotes;
987 found.counts.downvotes = data.counts.downvotes;
988 if (data.my_vote !== null) {
989 found.my_vote = data.my_vote;
994 export function createPostLikeFindRes(data: PostView, posts?: PostView[]) {
995 let found = posts?.find(p => p.post.id == data.post.id);
997 createPostLikeRes(data, found);
1001 export function createPostLikeRes(data: PostView, post_view?: PostView) {
1003 post_view.counts.score = data.counts.score;
1004 post_view.counts.upvotes = data.counts.upvotes;
1005 post_view.counts.downvotes = data.counts.downvotes;
1006 if (data.my_vote !== null) {
1007 post_view.my_vote = data.my_vote;
1012 export function editPostFindRes(data: PostView, posts?: PostView[]) {
1013 let found = posts?.find(p => p.post.id == data.post.id);
1015 editPostRes(data, found);
1019 export function editPostRes(data: PostView, post: PostView) {
1021 post.post.url = data.post.url;
1022 post.post.name = data.post.name;
1023 post.post.nsfw = data.post.nsfw;
1024 post.post.deleted = data.post.deleted;
1025 post.post.removed = data.post.removed;
1026 post.post.featured_community = data.post.featured_community;
1027 post.post.featured_local = data.post.featured_local;
1028 post.post.body = data.post.body;
1029 post.post.locked = data.post.locked;
1030 post.saved = data.saved;
1034 // TODO possible to make these generic?
1035 export function updatePostReportRes(
1036 data: PostReportView,
1037 reports?: PostReportView[]
1039 let found = reports?.find(p => p.post_report.id == data.post_report.id);
1041 found.post_report = data.post_report;
1045 export function updateCommentReportRes(
1046 data: CommentReportView,
1047 reports?: CommentReportView[]
1049 let found = reports?.find(c => c.comment_report.id == data.comment_report.id);
1051 found.comment_report = data.comment_report;
1055 export function updatePrivateMessageReportRes(
1056 data: PrivateMessageReportView,
1057 reports?: PrivateMessageReportView[]
1059 let found = reports?.find(
1060 c => c.private_message_report.id == data.private_message_report.id
1063 found.private_message_report = data.private_message_report;
1067 export function updateRegistrationApplicationRes(
1068 data: RegistrationApplicationView,
1069 applications?: RegistrationApplicationView[]
1071 let found = applications?.find(
1072 ra => ra.registration_application.id == data.registration_application.id
1075 found.registration_application = data.registration_application;
1076 found.admin = data.admin;
1077 found.creator_local_user = data.creator_local_user;
1081 export function commentsToFlatNodes(comments: CommentView[]): CommentNodeI[] {
1082 let nodes: CommentNodeI[] = [];
1083 for (let comment of comments) {
1084 nodes.push({ comment_view: comment, children: [], depth: 0 });
1089 export function convertCommentSortType(sort: SortType): CommentSortType {
1093 sort == "TopWeek" ||
1094 sort == "TopMonth" ||
1098 } else if (sort == "New") {
1100 } else if (sort == "Hot" || sort == "Active") {
1107 export function buildCommentsTree(
1108 comments: CommentView[],
1109 parentComment: boolean
1111 let map = new Map<number, CommentNodeI>();
1112 let depthOffset = !parentComment
1114 : getDepthFromComment(comments[0].comment) ?? 0;
1116 for (let comment_view of comments) {
1117 let depthI = getDepthFromComment(comment_view.comment) ?? 0;
1118 let depth = depthI ? depthI - depthOffset : 0;
1119 let node: CommentNodeI = {
1124 map.set(comment_view.comment.id, { ...node });
1127 let tree: CommentNodeI[] = [];
1129 // if its a parent comment fetch, then push the first comment to the top node.
1130 if (parentComment) {
1131 let cNode = map.get(comments[0].comment.id);
1137 for (let comment_view of comments) {
1138 let child = map.get(comment_view.comment.id);
1140 let parent_id = getCommentParentId(comment_view.comment);
1142 let parent = map.get(parent_id);
1143 // Necessary because blocked comment might not exist
1145 parent.children.push(child);
1148 if (!parentComment) {
1158 export function getCommentParentId(comment?: CommentI): number | undefined {
1159 let split = comment?.path.split(".");
1163 return split && split.length > 1
1164 ? Number(split.at(split.length - 2))
1168 export function getDepthFromComment(comment?: CommentI): number | undefined {
1169 let len = comment?.path.split(".").length;
1170 return len ? len - 2 : undefined;
1173 export function insertCommentIntoTree(
1174 tree: CommentNodeI[],
1176 parentComment: boolean
1178 // Building a fake node to be used for later
1179 let node: CommentNodeI = {
1185 let parentId = getCommentParentId(cv.comment);
1187 let parent_comment = searchCommentTree(tree, parentId);
1188 if (parent_comment) {
1189 node.depth = parent_comment.depth + 1;
1190 parent_comment.children.unshift(node);
1192 } else if (!parentComment) {
1197 export function searchCommentTree(
1198 tree: CommentNodeI[],
1200 ): CommentNodeI | undefined {
1201 for (let node of tree) {
1202 if (node.comment_view.comment.id === id) {
1206 for (const child of node.children) {
1207 let res = searchCommentTree([child], id);
1217 export const colorList: string[] = [
1227 function hsl(num: number) {
1228 return `hsla(${num}, 35%, 50%, 1)`;
1231 export function hostname(url: string): string {
1232 let cUrl = new URL(url);
1233 return cUrl.port ? `${cUrl.hostname}:${cUrl.port}` : `${cUrl.hostname}`;
1236 export function validTitle(title?: string): boolean {
1237 // Initial title is null, minimum length is taken care of by textarea's minLength={3}
1238 if (!title || title.length < 3) return true;
1240 const regex = new RegExp(/.*\S.*/, "g");
1242 return regex.test(title);
1245 export function siteBannerCss(banner: string): string {
1247 background-image: linear-gradient( rgba(0, 0, 0, 0.8), rgba(0, 0, 0, 0.8) ) ,url("${banner}"); \
1248 background-attachment: fixed; \
1249 background-position: top; \
1250 background-repeat: no-repeat; \
1251 background-size: 100% cover; \
1254 max-height: 100vh; \
1258 export function isBrowser() {
1259 return typeof window !== "undefined";
1262 export function setIsoData(context: any): IsoData {
1263 // If its the browser, you need to deserialize the data from the window
1265 let json = window.isoData;
1266 let routeData = json.routeData;
1267 let site_res = json.site_res;
1269 let isoData: IsoData = {
1275 } else return context.router.staticContext;
1278 export function wsSubscribe(parseMessage: any): Subscription | undefined {
1280 return WebSocketService.Instance.subject
1281 .pipe(retryWhen(errors => errors.pipe(delay(3000), take(10))))
1283 msg => parseMessage(msg),
1284 err => console.error(err),
1285 () => console.log("complete")
1292 moment.updateLocale("en", {
1313 export function saveScrollPosition(context: any) {
1314 let path: string = context.router.route.location.pathname;
1315 let y = window.scrollY;
1316 sessionStorage.setItem(`scrollPosition_${path}`, y.toString());
1319 export function restoreScrollPosition(context: any) {
1320 let path: string = context.router.route.location.pathname;
1321 let y = Number(sessionStorage.getItem(`scrollPosition_${path}`));
1322 window.scrollTo(0, y);
1325 export function showLocal(isoData: IsoData): boolean {
1326 return isoData.site_res.site_view.local_site.federation_enabled;
1329 export interface Choice {
1335 export function getUpdatedSearchId(id?: number | null, urlId?: number | null) {
1338 : ((id ?? urlId) === 0 ? undefined : id ?? urlId)?.toString();
1341 export function communityToChoice(cv: CommunityView): Choice {
1343 value: cv.community.id.toString(),
1344 label: communitySelectName(cv),
1348 export function personToChoice(pvs: PersonView): Choice {
1350 value: pvs.person.id.toString(),
1351 label: personSelectName(pvs),
1355 export async function fetchCommunities(q: string) {
1356 let form: Search = {
1358 type_: "Communities",
1360 listing_type: "All",
1363 auth: myAuth(false),
1365 let client = new LemmyHttp(getHttpBase());
1366 return client.search(form);
1369 export async function fetchUsers(q: string) {
1370 let form: Search = {
1374 listing_type: "All",
1377 auth: myAuth(false),
1379 let client = new LemmyHttp(getHttpBase());
1380 return client.search(form);
1383 export function communitySelectName(cv: CommunityView): string {
1384 return cv.community.local
1385 ? cv.community.title
1386 : `${hostname(cv.community.actor_id)}/${cv.community.title}`;
1389 export function personSelectName({
1390 person: { display_name, name, local, actor_id },
1391 }: PersonView): string {
1392 const pName = display_name ?? name;
1393 return local ? pName : `${hostname(actor_id)}/${pName}`;
1396 export function initializeSite(site: GetSiteResponse) {
1397 UserService.Instance.myUserInfo = site.my_user;
1398 i18n.changeLanguage(getLanguages()[0]);
1399 setupEmojiDataModel(site.custom_emojis);
1403 const SHORTNUM_SI_FORMAT = new Intl.NumberFormat("en-US", {
1404 maximumSignificantDigits: 3,
1406 notation: "compact",
1407 compactDisplay: "short",
1410 export function numToSI(value: bigint): string {
1411 return SHORTNUM_SI_FORMAT.format(value);
1414 export function isBanned(ps: Person): boolean {
1415 let expires = ps.ban_expires;
1416 // Add Z to convert from UTC date
1417 // TODO this check probably isn't necessary anymore
1419 if (ps.banned && new Date(expires + "Z") > new Date()) {
1429 export function myAuth(throwErr = true): string | undefined {
1430 return UserService.Instance.auth(throwErr);
1433 export function enableDownvotes(siteRes: GetSiteResponse): boolean {
1434 return siteRes.site_view.local_site.enable_downvotes;
1437 export function enableNsfw(siteRes: GetSiteResponse): boolean {
1438 return siteRes.site_view.local_site.enable_nsfw;
1441 export function postToCommentSortType(sort: SortType): CommentSortType {
1456 export function canCreateCommunity(
1457 siteRes: GetSiteResponse,
1458 myUserInfo = UserService.Instance.myUserInfo
1460 const adminOnly = siteRes.site_view.local_site.community_creation_admin_only;
1461 // TODO: Make this check if user is logged on as well
1462 return !adminOnly || amAdmin(myUserInfo);
1465 export function isPostBlocked(
1467 myUserInfo: MyUserInfo | undefined = UserService.Instance.myUserInfo
1470 (myUserInfo?.community_blocks
1471 .map(c => c.community.id)
1472 .includes(pv.community.id) ||
1473 myUserInfo?.person_blocks
1474 .map(p => p.target.id)
1475 .includes(pv.creator.id)) ??
1480 /// Checks to make sure you can view NSFW posts. Returns true if you can.
1481 export function nsfwCheck(
1483 myUserInfo = UserService.Instance.myUserInfo
1485 let nsfw = pv.post.nsfw || pv.community.nsfw;
1486 let myShowNsfw = myUserInfo?.local_user_view.local_user.show_nsfw ?? false;
1487 return !nsfw || (nsfw && myShowNsfw);
1490 export function getRandomFromList<T>(list: T[]): T | undefined {
1491 return list.length == 0
1493 : list.at(Math.floor(Math.random() * list.length));
1497 * This shows what language you can select
1499 * Use showAll for the site form
1500 * Use showSite for the profile and community forms
1501 * Use false for both those to filter on your profile and site ones
1503 export function selectableLanguages(
1504 allLanguages: Language[],
1505 siteLanguages: number[],
1508 myUserInfo = UserService.Instance.myUserInfo
1510 let allLangIds = allLanguages.map(l => l.id);
1511 let myLangs = myUserInfo?.discussion_languages ?? allLangIds;
1512 myLangs = myLangs.length == 0 ? allLangIds : myLangs;
1513 let siteLangs = siteLanguages.length == 0 ? allLangIds : siteLanguages;
1516 return allLanguages;
1519 return allLanguages.filter(x => siteLangs.includes(x.id));
1522 .filter(x => siteLangs.includes(x.id))
1523 .filter(x => myLangs.includes(x.id));
1528 export function uploadImage(image: File): Promise<UploadImageResponse> {
1529 const client = new LemmyHttp(getHttpBase());
1531 return client.uploadImage({ image });
1534 interface EmojiMartCategory {
1537 emojis: EmojiMartCustomEmoji[];
1540 interface EmojiMartCustomEmoji {
1544 skins: EmojiMartSkin[];
1547 interface EmojiMartSkin {
1551 const groupBy = <T>(
1553 predicate: (value: T, index: number, array: T[]) => string
1555 array.reduce((acc, value, index, array) => {
1556 (acc[predicate(value, index, array)] ||= []).push(value);
1558 }, {} as { [key: string]: T[] });
1560 export type QueryParams<T extends Record<string, any>> = {
1561 [key in keyof T]?: string;
1564 export function getQueryParams<T extends Record<string, any>>(processors: {
1565 [K in keyof T]: (param: string) => T[K];
1568 const searchParams = new URLSearchParams(window.location.search);
1570 return Array.from(Object.entries(processors)).reduce(
1571 (acc, [key, process]) => ({
1573 [key]: process(searchParams.get(key)),
1582 export function getQueryString<T extends Record<string, string | undefined>>(
1585 return Object.entries(obj)
1586 .filter(([, val]) => val !== undefined && val !== null)
1588 (acc, [key, val], index) => `${acc}${index > 0 ? "&" : ""}${key}=${val}`,
1593 export function isAuthPath(pathname: string) {
1594 return /create_.*|inbox|settings|setup|admin|reports|registration_applications/g.test(