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 export interface ErrorPageData {
111 adminMatrixIds?: string[];
114 let customEmojis: EmojiMartCategory[] = [];
115 export let customEmojisLookup: Map<string, CustomEmojiView> = new Map<
120 const DEFAULT_ALPHABET =
121 "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
123 function getRandomCharFromAlphabet(alphabet: string): string {
124 return alphabet.charAt(Math.floor(Math.random() * alphabet.length));
127 export function getIdFromString(id?: string): number | undefined {
128 return id && id !== "0" && !Number.isNaN(Number(id)) ? Number(id) : undefined;
131 export function getPageFromString(page?: string): bigint {
132 return page && !Number.isNaN(Number(page)) ? BigInt(page) : BigInt(1);
135 export function randomStr(
136 idDesiredLength = 20,
137 alphabet = DEFAULT_ALPHABET
140 * Create n-long array and map it to random chars from given alphabet.
141 * Then join individual chars as string
143 return Array.from({ length: idDesiredLength })
145 return getRandomCharFromAlphabet(alphabet);
150 const html5EmbedConfig = {
152 useImageSyntax: true, // Enables video/audio embed with ![]() syntax (default)
154 audio: 'controls preload="metadata"',
155 video: 'width="100%" max-height="100%" controls loop preload="metadata"',
160 const spoilerConfig = {
161 validate: (params: string) => {
162 return params.trim().match(/^spoiler\s+(.*)$/);
165 render: (tokens: any, idx: any) => {
166 var m = tokens[idx].info.trim().match(/^spoiler\s+(.*)$/);
168 if (tokens[idx].nesting === 1) {
170 return `<details><summary> ${md.utils.escapeHtml(m[1])} </summary>\n`;
173 return "</details>\n";
178 export let md: MarkdownIt = new MarkdownIt();
180 export let mdNoImages: MarkdownIt = new MarkdownIt();
182 export function hotRankComment(comment_view: CommentView): number {
183 return hotRank(comment_view.counts.score, comment_view.comment.published);
186 export function hotRankActivePost(post_view: PostView): number {
187 return hotRank(post_view.counts.score, post_view.counts.newest_comment_time);
190 export function hotRankPost(post_view: PostView): number {
191 return hotRank(post_view.counts.score, post_view.post.published);
194 export function hotRank(score: bigint, timeStr: string): number {
195 // Rank = ScaleFactor * sign(Score) * log(1 + abs(Score)) / (Time + 2)^Gravity
196 let date: Date = new Date(timeStr + "Z"); // Add Z to convert from UTC date
197 let now: Date = new Date();
198 let hoursElapsed: number = (now.getTime() - date.getTime()) / 36e5;
201 (10000 * Math.log10(Math.max(1, Number(3n + score)))) /
202 Math.pow(hoursElapsed + 2, 1.8);
204 // console.log(`Comment: ${comment.content}\nRank: ${rank}\nScore: ${comment.score}\nHours: ${hoursElapsed}`);
209 export function mdToHtml(text: string) {
210 return { __html: md.render(text) };
213 export function mdToHtmlNoImages(text: string) {
214 return { __html: mdNoImages.render(text) };
217 export function mdToHtmlInline(text: string) {
218 return { __html: md.renderInline(text) };
221 export function getUnixTime(text?: string): bigint | undefined {
222 return text ? BigInt(new Date(text).getTime() / 1000) : undefined;
225 export function futureDaysToUnixTime(days?: number): bigint | undefined {
229 new Date(Date.now() + 1000 * 60 * 60 * 24 * days).getTime() / 1000
235 export function canMod(
237 mods?: CommunityModeratorView[],
238 admins?: PersonView[],
239 myUserInfo = UserService.Instance.myUserInfo,
242 // You can do moderator actions only on the mods added after you.
245 ?.map(a => a.person.id)
246 .concat(mods?.map(m => m.moderator.id) ?? []) ?? [];
249 let myIndex = adminsThenMods.findIndex(
250 id => id == myUserInfo.local_user_view.person.id
255 // onSelf +1 on mod actions not for yourself, IE ban, remove, etc
256 adminsThenMods = adminsThenMods.slice(0, myIndex + (onSelf ? 0 : 1));
257 return !adminsThenMods.includes(creator_id);
264 export function canAdmin(
266 admins?: PersonView[],
267 myUserInfo = UserService.Instance.myUserInfo,
270 return canMod(creatorId, undefined, admins, myUserInfo, onSelf);
273 export function isMod(
275 mods?: CommunityModeratorView[]
277 return mods?.map(m => m.moderator.id).includes(creatorId) ?? false;
280 export function amMod(
281 mods?: CommunityModeratorView[],
282 myUserInfo = UserService.Instance.myUserInfo
284 return myUserInfo ? isMod(myUserInfo.local_user_view.person.id, mods) : false;
287 export function isAdmin(creatorId: number, admins?: PersonView[]): boolean {
288 return admins?.map(a => a.person.id).includes(creatorId) ?? false;
291 export function amAdmin(myUserInfo = UserService.Instance.myUserInfo): boolean {
292 return myUserInfo?.local_user_view.person.admin ?? false;
295 export function amCommunityCreator(
297 mods?: CommunityModeratorView[],
298 myUserInfo = UserService.Instance.myUserInfo
300 let myId = myUserInfo?.local_user_view.person.id;
301 // Don't allow mod actions on yourself
302 return myId == mods?.at(0)?.moderator.id && myId != creator_id;
305 export function amSiteCreator(
307 admins?: PersonView[],
308 myUserInfo = UserService.Instance.myUserInfo
310 let myId = myUserInfo?.local_user_view.person.id;
311 return myId == admins?.at(0)?.person.id && myId != creator_id;
314 export function amTopMod(
315 mods: CommunityModeratorView[],
316 myUserInfo = UserService.Instance.myUserInfo
318 return mods.at(0)?.moderator.id == myUserInfo?.local_user_view.person.id;
321 const imageRegex = /(http)?s?:?(\/\/[^"']*\.(?:jpg|jpeg|gif|png|svg|webp))/;
322 const videoRegex = /(http)?s?:?(\/\/[^"']*\.(?:mp4|webm))/;
324 export function isImage(url: string) {
325 return imageRegex.test(url);
328 export function isVideo(url: string) {
329 return videoRegex.test(url);
332 export function validURL(str: string) {
333 return !!new URL(str);
336 export function communityRSSUrl(actorId: string, sort: string): string {
337 let url = new URL(actorId);
338 return `${url.origin}/feeds${url.pathname}.xml?sort=${sort}`;
341 export function validEmail(email: string) {
343 /^(([^\s"(),.:;<>@[\\\]]+(\.[^\s"(),.:;<>@[\\\]]+)*)|(".+"))@((\[(?:\d{1,3}\.){3}\d{1,3}])|(([\dA-Za-z\-]+\.)+[A-Za-z]{2,}))$/;
344 return re.test(String(email).toLowerCase());
347 export function capitalizeFirstLetter(str: string): string {
348 return str.charAt(0).toUpperCase() + str.slice(1);
351 export async function getSiteMetadata(url: string) {
352 let form: GetSiteMetadata = { url };
353 let client = new LemmyHttp(getHttpBase());
354 return client.getSiteMetadata(form);
357 export function getDataTypeString(dt: DataType) {
358 return dt === DataType.Post ? "Post" : "Comment";
361 export function debounce<T extends any[], R>(
362 func: (...e: T) => R,
366 // 'private' variable for instance
367 // The returned function will be able to reference this due to closure.
368 // Each call to the returned function will share this common timer.
369 let timeout: NodeJS.Timeout | null;
371 // Calling debounce returns a new anonymous function
373 // reference the context and args for the setTimeout function
374 const args = arguments;
376 // Should the function be called now? If immediate is true
377 // and not already in a timeout then the answer is: Yes
378 const callNow = immediate && !timeout;
380 // This is the basic debounce behavior where you can call this
381 // function several times, but it will only execute once
382 // [before or after imposing a delay].
383 // Each time the returned function is called, the timer starts over.
384 clearTimeout(timeout ?? undefined);
386 // Set the new timeout
387 timeout = setTimeout(function () {
388 // Inside the timeout function, clear the timeout variable
389 // which will let the next execution run when in 'immediate' mode
392 // Check if the function already ran with the immediate flag
394 // Call the original function with apply
395 // apply lets you define the 'this' object as well as the arguments
396 // (both captured before setTimeout)
397 func.apply(this, args);
401 // Immediate mode and no wait timer? Execute the function..
402 if (callNow) func.apply(this, args);
406 export function getLanguages(
408 myUserInfo = UserService.Instance.myUserInfo
410 let myLang = myUserInfo?.local_user_view.local_user.interface_language;
411 let lang = override || myLang || "browser";
413 if (lang == "browser" && isBrowser()) {
414 return getBrowserLanguages();
420 function getBrowserLanguages(): string[] {
421 // Intersect lemmy's langs, with the browser langs
422 let langs = languages ? languages.map(l => l.code) : ["en"];
424 // NOTE, mobile browsers seem to be missing this list, so append en
425 let allowedLangs = navigator.languages
427 .filter(v => langs.includes(v));
431 export async function fetchThemeList(): Promise<string[]> {
432 return fetch("/css/themelist").then(res => res.json());
435 export async function setTheme(theme: string, forceReload = false) {
439 if (theme === "browser" && !forceReload) {
442 // This is only run on a force reload
443 if (theme == "browser") {
447 let themeList = await fetchThemeList();
449 // Unload all the other themes
450 for (var i = 0; i < themeList.length; i++) {
451 let styleSheet = document.getElementById(themeList[i]);
453 styleSheet.setAttribute("disabled", "disabled");
458 .getElementById("default-light")
459 ?.setAttribute("disabled", "disabled");
460 document.getElementById("default-dark")?.setAttribute("disabled", "disabled");
462 // Load the theme dynamically
463 let cssLoc = `/css/themes/${theme}.css`;
465 loadCss(theme, cssLoc);
466 document.getElementById(theme)?.removeAttribute("disabled");
469 export function loadCss(id: string, loc: string) {
470 if (!document.getElementById(id)) {
471 var head = document.getElementsByTagName("head")[0];
472 var link = document.createElement("link");
474 link.rel = "stylesheet";
475 link.type = "text/css";
478 head.appendChild(link);
482 export function objectFlip(obj: any) {
484 Object.keys(obj).forEach(key => {
490 export function showAvatars(
491 myUserInfo = UserService.Instance.myUserInfo
493 return myUserInfo?.local_user_view.local_user.show_avatars ?? true;
496 export function showScores(
497 myUserInfo = UserService.Instance.myUserInfo
499 return myUserInfo?.local_user_view.local_user.show_scores ?? true;
502 export function isCakeDay(published: string): boolean {
503 // moment(undefined) or moment.utc(undefined) returns the current date/time
504 // moment(null) or moment.utc(null) returns null
505 const createDate = moment.utc(published).local();
506 const currentDate = moment(new Date());
509 createDate.date() === currentDate.date() &&
510 createDate.month() === currentDate.month() &&
511 createDate.year() !== currentDate.year()
515 export function toast(text: string, background: ThemeColor = "success") {
517 const backgroundColor = `var(--${background})`;
520 backgroundColor: backgroundColor,
528 export function pictrsDeleteToast(filename: string, deleteUrl: string) {
530 const clickToDeleteText = i18n.t("click_to_delete_picture", { filename });
531 const deletePictureText = i18n.t("picture_deleted", {
534 const failedDeletePictureText = i18n.t("failed_to_delete_picture", {
538 const backgroundColor = `var(--light)`;
540 const toast = Toastify({
541 text: clickToDeleteText,
542 backgroundColor: backgroundColor,
548 fetch(deleteUrl).then(res => {
550 if (res.ok === true) {
551 alert(deletePictureText);
553 alert(failedDeletePictureText);
565 interface NotifyInfo {
572 export function messageToastify(info: NotifyInfo, router: any) {
574 let htmlBody = info.body ? md.render(info.body) : "";
575 let backgroundColor = `var(--light)`;
577 let toast = Toastify({
578 text: `${htmlBody}<br />${info.name}`,
580 backgroundColor: backgroundColor,
581 className: "text-dark",
590 router.history.push(info.link);
598 export function notifyPost(post_view: PostView, router: any) {
599 let info: NotifyInfo = {
600 name: post_view.community.name,
601 icon: post_view.community.icon,
602 link: `/post/${post_view.post.id}`,
603 body: post_view.post.name,
605 notify(info, router);
608 export function notifyComment(comment_view: CommentView, router: any) {
609 let info: NotifyInfo = {
610 name: comment_view.creator.name,
611 icon: comment_view.creator.avatar,
612 link: `/comment/${comment_view.comment.id}`,
613 body: comment_view.comment.content,
615 notify(info, router);
618 export function notifyPrivateMessage(pmv: PrivateMessageView, router: any) {
619 let info: NotifyInfo = {
620 name: pmv.creator.name,
621 icon: pmv.creator.avatar,
623 body: pmv.private_message.content,
625 notify(info, router);
628 function notify(info: NotifyInfo, router: any) {
629 messageToastify(info, router);
631 if (Notification.permission !== "granted") Notification.requestPermission();
633 var notification = new Notification(info.name, {
634 ...{ body: info.body },
635 ...(info.icon && { icon: info.icon }),
638 notification.onclick = (ev: Event): any => {
640 router.history.push(info.link);
645 export function setupTribute() {
647 noMatchTemplate: function () {
654 menuItemTemplate: (item: any) => {
655 let shortName = `:${item.original.key}:`;
656 return `${item.original.val} ${shortName}`;
658 selectTemplate: (item: any) => {
659 let customEmoji = customEmojisLookup.get(
662 if (customEmoji == undefined) return `${item.original.val}`;
664 return `![${customEmoji.alt_text}](${customEmoji.image_url} "${customEmoji.shortcode}")`;
666 values: Object.entries(emojiShortName)
668 return { key: e[1], val: e[0] };
671 Array.from(customEmojisLookup.entries()).map(k => ({
673 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}" />`,
677 autocompleteMode: true,
679 // menuItemLimit: mentionDropdownFetchLimit,
680 menuShowMinLength: 2,
685 selectTemplate: (item: any) => {
686 let it: PersonTribute = item.original;
687 return `[${it.key}](${it.view.person.actor_id})`;
689 values: debounce(async (text: string, cb: any) => {
690 cb(await personSearch(text));
693 autocompleteMode: true,
695 // menuItemLimit: mentionDropdownFetchLimit,
696 menuShowMinLength: 2,
702 selectTemplate: (item: any) => {
703 let it: CommunityTribute = item.original;
704 return `[${it.key}](${it.view.community.actor_id})`;
706 values: debounce(async (text: string, cb: any) => {
707 cb(await communitySearch(text));
710 autocompleteMode: true,
712 // menuItemLimit: mentionDropdownFetchLimit,
713 menuShowMinLength: 2,
719 function setupEmojiDataModel(custom_emoji_views: CustomEmojiView[]) {
720 let groupedEmojis = groupBy(custom_emoji_views, 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 let 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 let 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 (let 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 let users = (await fetchUsers(text)).users;
879 let persons: PersonTribute[] = users.map(pv => {
880 let tribute: PersonTribute = {
881 key: `@${pv.person.name}@${hostname(pv.person.actor_id)}`,
889 interface CommunityTribute {
894 async function communitySearch(text: string): Promise<CommunityTribute[]> {
895 let comms = (await fetchCommunities(text)).communities;
896 let communities: CommunityTribute[] = comms.map(cv => {
897 let 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 let id = props.match.params.post_id;
914 return id ? Number(id) : undefined;
917 export function getCommentIdFromProps(props: any): number | undefined {
918 let id = props.match.params.comment_id;
919 return id ? Number(id) : undefined;
922 export function editCommentRes(data: CommentView, comments?: CommentView[]) {
923 let 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 let 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 let 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 let 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 let 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 let 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 let 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 let 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 let found = reports?.find(c => c.comment_report.id == data.comment_report.id);
1057 found.comment_report = data.comment_report;
1061 export function updatePrivateMessageReportRes(
1062 data: PrivateMessageReportView,
1063 reports?: PrivateMessageReportView[]
1065 let found = reports?.find(
1066 c => c.private_message_report.id == data.private_message_report.id
1069 found.private_message_report = data.private_message_report;
1073 export function updateRegistrationApplicationRes(
1074 data: RegistrationApplicationView,
1075 applications?: RegistrationApplicationView[]
1077 let found = applications?.find(
1078 ra => ra.registration_application.id == data.registration_application.id
1081 found.registration_application = data.registration_application;
1082 found.admin = data.admin;
1083 found.creator_local_user = data.creator_local_user;
1087 export function commentsToFlatNodes(comments: CommentView[]): CommentNodeI[] {
1088 let nodes: CommentNodeI[] = [];
1089 for (let comment of comments) {
1090 nodes.push({ comment_view: comment, children: [], depth: 0 });
1095 export function convertCommentSortType(sort: SortType): CommentSortType {
1099 sort == "TopWeek" ||
1100 sort == "TopMonth" ||
1104 } else if (sort == "New") {
1106 } else if (sort == "Hot" || sort == "Active") {
1113 export function buildCommentsTree(
1114 comments: CommentView[],
1115 parentComment: boolean
1117 let map = new Map<number, CommentNodeI>();
1118 let depthOffset = !parentComment
1120 : getDepthFromComment(comments[0].comment) ?? 0;
1122 for (let comment_view of comments) {
1123 let depthI = getDepthFromComment(comment_view.comment) ?? 0;
1124 let depth = depthI ? depthI - depthOffset : 0;
1125 let node: CommentNodeI = {
1130 map.set(comment_view.comment.id, { ...node });
1133 let tree: CommentNodeI[] = [];
1135 // if its a parent comment fetch, then push the first comment to the top node.
1136 if (parentComment) {
1137 let cNode = map.get(comments[0].comment.id);
1143 for (let comment_view of comments) {
1144 let child = map.get(comment_view.comment.id);
1146 let parent_id = getCommentParentId(comment_view.comment);
1148 let parent = map.get(parent_id);
1149 // Necessary because blocked comment might not exist
1151 parent.children.push(child);
1154 if (!parentComment) {
1164 export function getCommentParentId(comment?: CommentI): number | undefined {
1165 let split = comment?.path.split(".");
1169 return split && split.length > 1
1170 ? Number(split.at(split.length - 2))
1174 export function getDepthFromComment(comment?: CommentI): number | undefined {
1175 let len = comment?.path.split(".").length;
1176 return len ? len - 2 : undefined;
1179 export function insertCommentIntoTree(
1180 tree: CommentNodeI[],
1182 parentComment: boolean
1184 // Building a fake node to be used for later
1185 let node: CommentNodeI = {
1191 let parentId = getCommentParentId(cv.comment);
1193 let parent_comment = searchCommentTree(tree, parentId);
1194 if (parent_comment) {
1195 node.depth = parent_comment.depth + 1;
1196 parent_comment.children.unshift(node);
1198 } else if (!parentComment) {
1203 export function searchCommentTree(
1204 tree: CommentNodeI[],
1206 ): CommentNodeI | undefined {
1207 for (let node of tree) {
1208 if (node.comment_view.comment.id === id) {
1212 for (const child of node.children) {
1213 let res = searchCommentTree([child], id);
1223 export const colorList: string[] = [
1233 function hsl(num: number) {
1234 return `hsla(${num}, 35%, 50%, 1)`;
1237 export function hostname(url: string): string {
1238 let cUrl = new URL(url);
1239 return cUrl.port ? `${cUrl.hostname}:${cUrl.port}` : `${cUrl.hostname}`;
1242 export function validTitle(title?: string): boolean {
1243 // Initial title is null, minimum length is taken care of by textarea's minLength={3}
1244 if (!title || title.length < 3) return true;
1246 const regex = new RegExp(/.*\S.*/, "g");
1248 return regex.test(title);
1251 export function siteBannerCss(banner: string): string {
1253 background-image: linear-gradient( rgba(0, 0, 0, 0.8), rgba(0, 0, 0, 0.8) ) ,url("${banner}"); \
1254 background-attachment: fixed; \
1255 background-position: top; \
1256 background-repeat: no-repeat; \
1257 background-size: 100% cover; \
1260 max-height: 100vh; \
1264 export function isBrowser() {
1265 return typeof window !== "undefined";
1268 export function setIsoData(context: any): IsoData {
1269 // If its the browser, you need to deserialize the data from the window
1271 let json = window.isoData;
1272 let routeData = json.routeData;
1273 let site_res = json.site_res;
1275 let isoData: IsoData = {
1281 } else return context.router.staticContext;
1284 export function wsSubscribe(parseMessage: any): Subscription | undefined {
1286 return WebSocketService.Instance.subject
1287 .pipe(retryWhen(errors => errors.pipe(delay(3000), take(10))))
1289 msg => parseMessage(msg),
1290 err => console.error(err),
1291 () => console.log("complete")
1298 moment.updateLocale("en", {
1319 export function saveScrollPosition(context: any) {
1320 let path: string = context.router.route.location.pathname;
1321 let y = window.scrollY;
1322 sessionStorage.setItem(`scrollPosition_${path}`, y.toString());
1325 export function restoreScrollPosition(context: any) {
1326 let path: string = context.router.route.location.pathname;
1327 let y = Number(sessionStorage.getItem(`scrollPosition_${path}`));
1328 window.scrollTo(0, y);
1331 export function showLocal(isoData: IsoData): boolean {
1332 return isoData.site_res.site_view.local_site.federation_enabled;
1335 export interface Choice {
1341 export function getUpdatedSearchId(id?: number | null, urlId?: number | null) {
1344 : ((id ?? urlId) === 0 ? undefined : id ?? urlId)?.toString();
1347 export function communityToChoice(cv: CommunityView): Choice {
1349 value: cv.community.id.toString(),
1350 label: communitySelectName(cv),
1354 export function personToChoice(pvs: PersonView): Choice {
1356 value: pvs.person.id.toString(),
1357 label: personSelectName(pvs),
1361 export async function fetchCommunities(q: string) {
1362 let form: Search = {
1364 type_: "Communities",
1366 listing_type: "All",
1369 auth: myAuth(false),
1371 let client = new LemmyHttp(getHttpBase());
1372 return client.search(form);
1375 export async function fetchUsers(q: string) {
1376 let form: Search = {
1380 listing_type: "All",
1383 auth: myAuth(false),
1385 let client = new LemmyHttp(getHttpBase());
1386 return client.search(form);
1389 export function communitySelectName(cv: CommunityView): string {
1390 return cv.community.local
1391 ? cv.community.title
1392 : `${hostname(cv.community.actor_id)}/${cv.community.title}`;
1395 export function personSelectName({
1396 person: { display_name, name, local, actor_id },
1397 }: PersonView): string {
1398 const pName = display_name ?? name;
1399 return local ? pName : `${hostname(actor_id)}/${pName}`;
1402 export function initializeSite(site: GetSiteResponse) {
1403 UserService.Instance.myUserInfo = site.my_user;
1404 i18n.changeLanguage(getLanguages()[0]);
1405 setupEmojiDataModel(site.custom_emojis);
1409 const SHORTNUM_SI_FORMAT = new Intl.NumberFormat("en-US", {
1410 maximumSignificantDigits: 3,
1412 notation: "compact",
1413 compactDisplay: "short",
1416 export function numToSI(value: bigint): string {
1417 return SHORTNUM_SI_FORMAT.format(value);
1420 export function isBanned(ps: Person): boolean {
1421 let expires = ps.ban_expires;
1422 // Add Z to convert from UTC date
1423 // TODO this check probably isn't necessary anymore
1425 if (ps.banned && new Date(expires + "Z") > new Date()) {
1435 export function myAuth(throwErr = true): string | undefined {
1436 return UserService.Instance.auth(throwErr);
1439 export function enableDownvotes(siteRes: GetSiteResponse): boolean {
1440 return siteRes.site_view.local_site.enable_downvotes;
1443 export function enableNsfw(siteRes: GetSiteResponse): boolean {
1444 return siteRes.site_view.local_site.enable_nsfw;
1447 export function postToCommentSortType(sort: SortType): CommentSortType {
1462 export function myFirstDiscussionLanguageId(
1463 allLanguages: Language[],
1464 siteLanguages: number[],
1465 myUserInfo = UserService.Instance.myUserInfo
1466 ): number | undefined {
1467 return selectableLanguages(
1476 export function canCreateCommunity(
1477 siteRes: GetSiteResponse,
1478 myUserInfo = UserService.Instance.myUserInfo
1480 const adminOnly = siteRes.site_view.local_site.community_creation_admin_only;
1481 // TODO: Make this check if user is logged on as well
1482 return !adminOnly || amAdmin(myUserInfo);
1485 export function isPostBlocked(
1487 myUserInfo: MyUserInfo | undefined = UserService.Instance.myUserInfo
1490 (myUserInfo?.community_blocks
1491 .map(c => c.community.id)
1492 .includes(pv.community.id) ||
1493 myUserInfo?.person_blocks
1494 .map(p => p.target.id)
1495 .includes(pv.creator.id)) ??
1500 /// Checks to make sure you can view NSFW posts. Returns true if you can.
1501 export function nsfwCheck(
1503 myUserInfo = UserService.Instance.myUserInfo
1505 let nsfw = pv.post.nsfw || pv.community.nsfw;
1506 let myShowNsfw = myUserInfo?.local_user_view.local_user.show_nsfw ?? false;
1507 return !nsfw || (nsfw && myShowNsfw);
1510 export function getRandomFromList<T>(list: T[]): T | undefined {
1511 return list.length == 0
1513 : list.at(Math.floor(Math.random() * list.length));
1517 * This shows what language you can select
1519 * Use showAll for the site form
1520 * Use showSite for the profile and community forms
1521 * Use false for both those to filter on your profile and site ones
1523 export function selectableLanguages(
1524 allLanguages: Language[],
1525 siteLanguages: number[],
1528 myUserInfo = UserService.Instance.myUserInfo
1530 let allLangIds = allLanguages.map(l => l.id);
1531 let myLangs = myUserInfo?.discussion_languages ?? allLangIds;
1532 myLangs = myLangs.length == 0 ? allLangIds : myLangs;
1533 let siteLangs = siteLanguages.length == 0 ? allLangIds : siteLanguages;
1536 return allLanguages;
1539 return allLanguages.filter(x => siteLangs.includes(x.id));
1542 .filter(x => siteLangs.includes(x.id))
1543 .filter(x => myLangs.includes(x.id));
1548 export function uploadImage(image: File): Promise<UploadImageResponse> {
1549 const client = new LemmyHttp(getHttpBase());
1551 return client.uploadImage({ image });
1554 interface EmojiMartCategory {
1557 emojis: EmojiMartCustomEmoji[];
1560 interface EmojiMartCustomEmoji {
1564 skins: EmojiMartSkin[];
1567 interface EmojiMartSkin {
1571 const groupBy = <T>(
1573 predicate: (value: T, index: number, array: T[]) => string
1575 array.reduce((acc, value, index, array) => {
1576 (acc[predicate(value, index, array)] ||= []).push(value);
1578 }, {} as { [key: string]: T[] });
1580 export type QueryParams<T extends Record<string, any>> = {
1581 [key in keyof T]?: string;
1584 export function getQueryParams<T extends Record<string, any>>(processors: {
1585 [K in keyof T]: (param: string) => T[K];
1588 const searchParams = new URLSearchParams(window.location.search);
1590 return Array.from(Object.entries(processors)).reduce(
1591 (acc, [key, process]) => ({
1593 [key]: process(searchParams.get(key)),
1602 export function getQueryString<T extends Record<string, string | undefined>>(
1605 return Object.entries(obj)
1606 .filter(([, val]) => val !== undefined && val !== null)
1608 (acc, [key, val], index) => `${acc}${index > 0 ? "&" : ""}${key}=${val}`,
1613 export function isAuthPath(pathname: string) {
1614 return /create_.*|inbox|settings|setup|admin|reports|registration_applications/g.test(