1 import { Picker } from "emoji-mart";
2 import emojiShortName from "emoji-short-name";
4 BlockCommunityResponse,
10 CommunityModeratorView,
23 PrivateMessageReportView,
25 RegistrationApplicationView,
29 } from "lemmy-js-client";
30 import { default as MarkdownIt } from "markdown-it";
31 import markdown_it_container from "markdown-it-container";
32 import markdown_it_emoji from "markdown-it-emoji/bare";
33 import markdown_it_footnote from "markdown-it-footnote";
34 import markdown_it_html5_embed from "markdown-it-html5-embed";
35 import markdown_it_sub from "markdown-it-sub";
36 import markdown_it_sup from "markdown-it-sup";
37 import Renderer from "markdown-it/lib/renderer";
38 import Token from "markdown-it/lib/token";
39 import moment from "moment";
40 import { Subscription } from "rxjs";
41 import { delay, retryWhen, take } from "rxjs/operators";
42 import tippy from "tippy.js";
43 import Toastify from "toastify-js";
44 import { getHttpBase } from "./env";
45 import { i18n, languages } from "./i18next";
46 import { CommentNodeI, DataType, IsoData } from "./interfaces";
47 import { UserService, WebSocketService } from "./services";
51 Tribute = require("tributejs");
54 export const wsClient = new LemmyWebsocket();
56 export const favIconUrl = "/static/assets/icons/favicon.svg";
57 export const favIconPngUrl = "/static/assets/icons/apple-touch-icon.png";
59 // export const defaultFavIcon = `${window.location.protocol}//${window.location.host}${favIconPngUrl}`;
60 export const repoUrl = "https://github.com/LemmyNet";
61 export const joinLemmyUrl = "https://join-lemmy.org";
62 export const donateLemmyUrl = `${joinLemmyUrl}/donate`;
63 export const docsUrl = `${joinLemmyUrl}/docs/en/index.html`;
64 export const helpGuideUrl = `${joinLemmyUrl}/docs/en/users/01-getting-started.html`; // TODO find a way to redirect to the non-en folder
65 export const markdownHelpUrl = `${joinLemmyUrl}/docs/en/users/02-media.html`;
66 export const sortingHelpUrl = `${helpGuideUrl}/docs/en/users/03-votes-and-ranking.html`;
67 export const archiveTodayUrl = "https://archive.today";
68 export const ghostArchiveUrl = "https://ghostarchive.org";
69 export const webArchiveUrl = "https://web.archive.org";
70 export const elementUrl = "https://element.io";
72 export const postRefetchSeconds: number = 60 * 1000;
73 export const fetchLimit = 40;
74 export const trendingFetchLimit = 6;
75 export const mentionDropdownFetchLimit = 10;
76 export const commentTreeMaxDepth = 8;
77 export const markdownFieldCharacterLimit = 50000;
78 export const maxUploadImages = 20;
79 export const concurrentImageUpload = 4;
81 export const relTags = "noopener nofollow";
83 export const emDash = "\u2014";
85 export type ThemeColor =
108 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): number {
126 return page && !Number.isNaN(Number(page)) ? Number(page) : 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: number, 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, 3 + Number(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): number | undefined {
216 return text ? new Date(text).getTime() / 1000 : undefined;
219 export function futureDaysToUnixTime(days?: number): number | undefined {
222 new Date(Date.now() + 1000 * 60 * 60 * 24 * days).getTime() / 1000
227 export function canMod(
229 mods?: CommunityModeratorView[],
230 admins?: PersonView[],
231 myUserInfo = UserService.Instance.myUserInfo,
234 // You can do moderator actions only on the mods added after you.
237 ?.map(a => a.person.id)
238 .concat(mods?.map(m => m.moderator.id) ?? []) ?? [];
241 let myIndex = adminsThenMods.findIndex(
242 id => id == myUserInfo.local_user_view.person.id
247 // onSelf +1 on mod actions not for yourself, IE ban, remove, etc
248 adminsThenMods = adminsThenMods.slice(0, myIndex + (onSelf ? 0 : 1));
249 return !adminsThenMods.includes(creator_id);
256 export function canAdmin(
258 admins?: PersonView[],
259 myUserInfo = UserService.Instance.myUserInfo,
262 return canMod(creatorId, undefined, admins, myUserInfo, onSelf);
265 export function isMod(
267 mods?: CommunityModeratorView[]
269 return mods?.map(m => m.moderator.id).includes(creatorId) ?? false;
272 export function amMod(
273 mods?: CommunityModeratorView[],
274 myUserInfo = UserService.Instance.myUserInfo
276 return myUserInfo ? isMod(myUserInfo.local_user_view.person.id, mods) : false;
279 export function isAdmin(creatorId: number, admins?: PersonView[]): boolean {
280 return admins?.map(a => a.person.id).includes(creatorId) ?? false;
283 export function amAdmin(myUserInfo = UserService.Instance.myUserInfo): boolean {
284 return myUserInfo?.local_user_view.person.admin ?? false;
287 export function amCommunityCreator(
289 mods?: CommunityModeratorView[],
290 myUserInfo = UserService.Instance.myUserInfo
292 let myId = myUserInfo?.local_user_view.person.id;
293 // Don't allow mod actions on yourself
294 return myId == mods?.at(0)?.moderator.id && myId != creator_id;
297 export function amSiteCreator(
299 admins?: PersonView[],
300 myUserInfo = UserService.Instance.myUserInfo
302 let myId = myUserInfo?.local_user_view.person.id;
303 return myId == admins?.at(0)?.person.id && myId != creator_id;
306 export function amTopMod(
307 mods: CommunityModeratorView[],
308 myUserInfo = UserService.Instance.myUserInfo
310 return mods.at(0)?.moderator.id == myUserInfo?.local_user_view.person.id;
313 const imageRegex = /(http)?s?:?(\/\/[^"']*\.(?:jpg|jpeg|gif|png|svg|webp))/;
314 const videoRegex = /(http)?s?:?(\/\/[^"']*\.(?:mp4|webm))/;
316 export function isImage(url: string) {
317 return imageRegex.test(url);
320 export function isVideo(url: string) {
321 return videoRegex.test(url);
324 export function validURL(str: string) {
325 return !!new URL(str);
328 export function communityRSSUrl(actorId: string, sort: string): string {
329 let url = new URL(actorId);
330 return `${url.origin}/feeds${url.pathname}.xml?sort=${sort}`;
333 export function validEmail(email: string) {
335 /^(([^\s"(),.:;<>@[\\\]]+(\.[^\s"(),.:;<>@[\\\]]+)*)|(".+"))@((\[(?:\d{1,3}\.){3}\d{1,3}])|(([\dA-Za-z\-]+\.)+[A-Za-z]{2,}))$/;
336 return re.test(String(email).toLowerCase());
339 export function capitalizeFirstLetter(str: string): string {
340 return str.charAt(0).toUpperCase() + str.slice(1);
343 export async function getSiteMetadata(url: string) {
344 let form: GetSiteMetadata = { url };
345 let client = new LemmyHttp(getHttpBase());
346 return client.getSiteMetadata(form);
349 export function getDataTypeString(dt: DataType) {
350 return dt === DataType.Post ? "Post" : "Comment";
353 export function debounce<T extends any[], R>(
354 func: (...e: T) => R,
358 // 'private' variable for instance
359 // The returned function will be able to reference this due to closure.
360 // Each call to the returned function will share this common timer.
361 let timeout: NodeJS.Timeout | null;
363 // Calling debounce returns a new anonymous function
365 // reference the context and args for the setTimeout function
366 const args = arguments;
368 // Should the function be called now? If immediate is true
369 // and not already in a timeout then the answer is: Yes
370 const callNow = immediate && !timeout;
372 // This is the basic debounce behavior where you can call this
373 // function several times, but it will only execute once
374 // [before or after imposing a delay].
375 // Each time the returned function is called, the timer starts over.
376 clearTimeout(timeout ?? undefined);
378 // Set the new timeout
379 timeout = setTimeout(function () {
380 // Inside the timeout function, clear the timeout variable
381 // which will let the next execution run when in 'immediate' mode
384 // Check if the function already ran with the immediate flag
386 // Call the original function with apply
387 // apply lets you define the 'this' object as well as the arguments
388 // (both captured before setTimeout)
389 func.apply(this, args);
393 // Immediate mode and no wait timer? Execute the function..
394 if (callNow) func.apply(this, args);
398 export function getLanguages(
400 myUserInfo = UserService.Instance.myUserInfo
402 let myLang = myUserInfo?.local_user_view.local_user.interface_language;
403 let lang = override || myLang || "browser";
405 if (lang == "browser" && isBrowser()) {
406 return getBrowserLanguages();
412 function getBrowserLanguages(): string[] {
413 // Intersect lemmy's langs, with the browser langs
414 let langs = languages ? languages.map(l => l.code) : ["en"];
416 // NOTE, mobile browsers seem to be missing this list, so append en
417 let allowedLangs = navigator.languages
419 .filter(v => langs.includes(v));
423 export async function fetchThemeList(): Promise<string[]> {
424 return fetch("/css/themelist").then(res => res.json());
427 export async function setTheme(theme: string, forceReload = false) {
431 if (theme === "browser" && !forceReload) {
434 // This is only run on a force reload
435 if (theme == "browser") {
439 let themeList = await fetchThemeList();
441 // Unload all the other themes
442 for (var i = 0; i < themeList.length; i++) {
443 let styleSheet = document.getElementById(themeList[i]);
445 styleSheet.setAttribute("disabled", "disabled");
450 .getElementById("default-light")
451 ?.setAttribute("disabled", "disabled");
452 document.getElementById("default-dark")?.setAttribute("disabled", "disabled");
454 // Load the theme dynamically
455 let cssLoc = `/css/themes/${theme}.css`;
457 loadCss(theme, cssLoc);
458 document.getElementById(theme)?.removeAttribute("disabled");
461 export function loadCss(id: string, loc: string) {
462 if (!document.getElementById(id)) {
463 var head = document.getElementsByTagName("head")[0];
464 var link = document.createElement("link");
466 link.rel = "stylesheet";
467 link.type = "text/css";
470 head.appendChild(link);
474 export function objectFlip(obj: any) {
476 Object.keys(obj).forEach(key => {
482 export function showAvatars(
483 myUserInfo = UserService.Instance.myUserInfo
485 return myUserInfo?.local_user_view.local_user.show_avatars ?? true;
488 export function showScores(
489 myUserInfo = UserService.Instance.myUserInfo
491 return myUserInfo?.local_user_view.local_user.show_scores ?? true;
494 export function isCakeDay(published: string): boolean {
495 // moment(undefined) or moment.utc(undefined) returns the current date/time
496 // moment(null) or moment.utc(null) returns null
497 const createDate = moment.utc(published).local();
498 const currentDate = moment(new Date());
501 createDate.date() === currentDate.date() &&
502 createDate.month() === currentDate.month() &&
503 createDate.year() !== currentDate.year()
507 export function toast(text: string, background: ThemeColor = "success") {
509 const backgroundColor = `var(--${background})`;
512 backgroundColor: backgroundColor,
520 export function pictrsDeleteToast(filename: string, deleteUrl: string) {
522 const clickToDeleteText = i18n.t("click_to_delete_picture", { filename });
523 const deletePictureText = i18n.t("picture_deleted", {
526 const failedDeletePictureText = i18n.t("failed_to_delete_picture", {
530 const backgroundColor = `var(--light)`;
532 const toast = Toastify({
533 text: clickToDeleteText,
534 backgroundColor: backgroundColor,
540 fetch(deleteUrl).then(res => {
542 if (res.ok === true) {
543 alert(deletePictureText);
545 alert(failedDeletePictureText);
557 interface NotifyInfo {
564 export function messageToastify(info: NotifyInfo, router: any) {
566 let htmlBody = info.body ? md.render(info.body) : "";
567 let backgroundColor = `var(--light)`;
569 let toast = Toastify({
570 text: `${htmlBody}<br />${info.name}`,
572 backgroundColor: backgroundColor,
573 className: "text-dark",
582 router.history.push(info.link);
590 export function notifyPost(post_view: PostView, router: any) {
591 let info: NotifyInfo = {
592 name: post_view.community.name,
593 icon: post_view.community.icon,
594 link: `/post/${post_view.post.id}`,
595 body: post_view.post.name,
597 notify(info, router);
600 export function notifyComment(comment_view: CommentView, router: any) {
601 let info: NotifyInfo = {
602 name: comment_view.creator.name,
603 icon: comment_view.creator.avatar,
604 link: `/comment/${comment_view.comment.id}`,
605 body: comment_view.comment.content,
607 notify(info, router);
610 export function notifyPrivateMessage(pmv: PrivateMessageView, router: any) {
611 let info: NotifyInfo = {
612 name: pmv.creator.name,
613 icon: pmv.creator.avatar,
615 body: pmv.private_message.content,
617 notify(info, router);
620 function notify(info: NotifyInfo, router: any) {
621 messageToastify(info, router);
623 if (Notification.permission !== "granted") Notification.requestPermission();
625 var notification = new Notification(info.name, {
626 ...{ body: info.body },
627 ...(info.icon && { icon: info.icon }),
630 notification.onclick = (ev: Event): any => {
632 router.history.push(info.link);
637 export function setupTribute() {
639 noMatchTemplate: function () {
646 menuItemTemplate: (item: any) => {
647 let shortName = `:${item.original.key}:`;
648 return `${item.original.val} ${shortName}`;
650 selectTemplate: (item: any) => {
651 let customEmoji = customEmojisLookup.get(
654 if (customEmoji == undefined) return `${item.original.val}`;
656 return `![${customEmoji.alt_text}](${customEmoji.image_url} "${customEmoji.shortcode}")`;
658 values: Object.entries(emojiShortName)
660 return { key: e[1], val: e[0] };
663 Array.from(customEmojisLookup.entries()).map(k => ({
665 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}" />`,
669 autocompleteMode: true,
671 // menuItemLimit: mentionDropdownFetchLimit,
672 menuShowMinLength: 2,
677 selectTemplate: (item: any) => {
678 let it: PersonTribute = item.original;
679 return `[${it.key}](${it.view.person.actor_id})`;
681 values: debounce(async (text: string, cb: any) => {
682 cb(await personSearch(text));
685 autocompleteMode: true,
687 // menuItemLimit: mentionDropdownFetchLimit,
688 menuShowMinLength: 2,
694 selectTemplate: (item: any) => {
695 let it: CommunityTribute = item.original;
696 return `[${it.key}](${it.view.community.actor_id})`;
698 values: debounce(async (text: string, cb: any) => {
699 cb(await communitySearch(text));
702 autocompleteMode: true,
704 // menuItemLimit: mentionDropdownFetchLimit,
705 menuShowMinLength: 2,
711 function setupEmojiDataModel(custom_emoji_views: CustomEmojiView[]) {
712 let groupedEmojis = groupBy(custom_emoji_views, x => x.custom_emoji.category);
713 for (const [category, emojis] of Object.entries(groupedEmojis)) {
717 emojis: emojis.map(emoji => ({
718 id: emoji.custom_emoji.shortcode,
719 name: emoji.custom_emoji.shortcode,
720 keywords: emoji.keywords.map(x => x.keyword),
721 skins: [{ src: emoji.custom_emoji.image_url }],
725 customEmojisLookup = new Map(
726 custom_emoji_views.map(view => [view.custom_emoji.shortcode, view])
730 export function updateEmojiDataModel(custom_emoji_view: CustomEmojiView) {
731 const emoji: EmojiMartCustomEmoji = {
732 id: custom_emoji_view.custom_emoji.shortcode,
733 name: custom_emoji_view.custom_emoji.shortcode,
734 keywords: custom_emoji_view.keywords.map(x => x.keyword),
735 skins: [{ src: custom_emoji_view.custom_emoji.image_url }],
737 let categoryIndex = customEmojis.findIndex(
738 x => x.id == custom_emoji_view.custom_emoji.category
740 if (categoryIndex == -1) {
742 id: custom_emoji_view.custom_emoji.category,
743 name: custom_emoji_view.custom_emoji.category,
747 let emojiIndex = customEmojis[categoryIndex].emojis.findIndex(
748 x => x.id == custom_emoji_view.custom_emoji.shortcode
750 if (emojiIndex == -1) {
751 customEmojis[categoryIndex].emojis.push(emoji);
753 customEmojis[categoryIndex].emojis[emojiIndex] = emoji;
756 customEmojisLookup.set(
757 custom_emoji_view.custom_emoji.shortcode,
762 export function removeFromEmojiDataModel(id: number) {
763 let view: CustomEmojiView | undefined;
764 for (let item of customEmojisLookup.values()) {
765 if (item.custom_emoji.id === id) {
771 const categoryIndex = customEmojis.findIndex(
772 x => x.id == view?.custom_emoji.category
774 const emojiIndex = customEmojis[categoryIndex].emojis.findIndex(
775 x => x.id == view?.custom_emoji.shortcode
777 customEmojis[categoryIndex].emojis = customEmojis[
779 ].emojis.splice(emojiIndex, 1);
781 customEmojisLookup.delete(view?.custom_emoji.shortcode);
784 function setupMarkdown() {
785 const markdownItConfig: MarkdownIt.Options = {
791 const emojiDefs = Array.from(customEmojisLookup.entries()).reduce(
792 (main, [key, value]) => ({ ...main, [key]: value }),
795 md = new MarkdownIt(markdownItConfig)
796 .use(markdown_it_sub)
797 .use(markdown_it_sup)
798 .use(markdown_it_footnote)
799 .use(markdown_it_html5_embed, html5EmbedConfig)
800 .use(markdown_it_container, "spoiler", spoilerConfig)
801 .use(markdown_it_emoji, {
805 mdNoImages = 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 var defaultRenderer = md.renderer.rules.image;
816 md.renderer.rules.image = function (
819 options: MarkdownIt.Options,
823 //Provide custom renderer for our emojis to allow us to add a css class and force size dimensions on them.
824 const item = tokens[idx] as any;
825 const title = item.attrs.length >= 3 ? item.attrs[2][1] : "";
826 const src: string = item.attrs[0][1];
827 const isCustomEmoji = customEmojisLookup.get(title) != undefined;
828 if (!isCustomEmoji) {
829 return defaultRenderer?.(tokens, idx, options, env, self) ?? "";
831 const alt_text = item.content;
832 return `<img class="icon icon-emoji" src="${src}" title="${title}" alt="${alt_text}"/>`;
836 export function getEmojiMart(
837 onEmojiSelect: (e: any) => void,
838 customPickerOptions: any = {}
840 const pickerOptions = {
841 ...customPickerOptions,
842 onEmojiSelect: onEmojiSelect,
843 custom: customEmojis,
845 return new Picker(pickerOptions);
848 var tippyInstance: any;
850 tippyInstance = tippy("[data-tippy-content]");
853 export function setupTippy() {
855 tippyInstance.forEach((e: any) => e.destroy());
856 tippyInstance = tippy("[data-tippy-content]", {
858 // Display on "long press"
859 touch: ["hold", 500],
864 interface PersonTribute {
869 async function personSearch(text: string): Promise<PersonTribute[]> {
870 let users = (await fetchUsers(text)).users;
871 let persons: PersonTribute[] = users.map(pv => {
872 let tribute: PersonTribute = {
873 key: `@${pv.person.name}@${hostname(pv.person.actor_id)}`,
881 interface CommunityTribute {
886 async function communitySearch(text: string): Promise<CommunityTribute[]> {
887 let comms = (await fetchCommunities(text)).communities;
888 let communities: CommunityTribute[] = comms.map(cv => {
889 let tribute: CommunityTribute = {
890 key: `!${cv.community.name}@${hostname(cv.community.actor_id)}`,
898 export function getRecipientIdFromProps(props: any): number {
899 return props.match.params.recipient_id
900 ? Number(props.match.params.recipient_id)
904 export function getIdFromProps(props: any): number | undefined {
905 let id = props.match.params.post_id;
906 return id ? Number(id) : undefined;
909 export function getCommentIdFromProps(props: any): number | undefined {
910 let id = props.match.params.comment_id;
911 return id ? Number(id) : undefined;
914 export function editCommentRes(data: CommentView, comments?: CommentView[]) {
915 let found = comments?.find(c => c.comment.id == data.comment.id);
917 found.comment.content = data.comment.content;
918 found.comment.distinguished = data.comment.distinguished;
919 found.comment.updated = data.comment.updated;
920 found.comment.removed = data.comment.removed;
921 found.comment.deleted = data.comment.deleted;
922 found.counts.upvotes = data.counts.upvotes;
923 found.counts.downvotes = data.counts.downvotes;
924 found.counts.score = data.counts.score;
928 export function saveCommentRes(data: CommentView, comments?: CommentView[]) {
929 let found = comments?.find(c => c.comment.id == data.comment.id);
931 found.saved = data.saved;
935 export function updatePersonBlock(
936 data: BlockPersonResponse,
937 myUserInfo: MyUserInfo | undefined = UserService.Instance.myUserInfo
939 let mui = myUserInfo;
942 mui.person_blocks.push({
943 person: mui.local_user_view.person,
944 target: data.person_view.person,
946 toast(`${i18n.t("blocked")} ${data.person_view.person.name}`);
948 mui.person_blocks = mui.person_blocks.filter(
949 i => i.target.id != data.person_view.person.id
951 toast(`${i18n.t("unblocked")} ${data.person_view.person.name}`);
956 export function updateCommunityBlock(
957 data: BlockCommunityResponse,
958 myUserInfo: MyUserInfo | undefined = UserService.Instance.myUserInfo
960 let mui = myUserInfo;
963 mui.community_blocks.push({
964 person: mui.local_user_view.person,
965 community: data.community_view.community,
967 toast(`${i18n.t("blocked")} ${data.community_view.community.name}`);
969 mui.community_blocks = mui.community_blocks.filter(
970 i => i.community.id != data.community_view.community.id
972 toast(`${i18n.t("unblocked")} ${data.community_view.community.name}`);
977 export function createCommentLikeRes(
979 comments?: CommentView[]
981 let found = comments?.find(c => c.comment.id === data.comment.id);
983 found.counts.score = data.counts.score;
984 found.counts.upvotes = data.counts.upvotes;
985 found.counts.downvotes = data.counts.downvotes;
986 if (data.my_vote !== null) {
987 found.my_vote = data.my_vote;
992 export function createPostLikeFindRes(data: PostView, posts?: PostView[]) {
993 let found = posts?.find(p => p.post.id == data.post.id);
995 createPostLikeRes(data, found);
999 export function createPostLikeRes(data: PostView, post_view?: PostView) {
1001 post_view.counts.score = data.counts.score;
1002 post_view.counts.upvotes = data.counts.upvotes;
1003 post_view.counts.downvotes = data.counts.downvotes;
1004 if (data.my_vote !== null) {
1005 post_view.my_vote = data.my_vote;
1010 export function editPostFindRes(data: PostView, posts?: PostView[]) {
1011 let found = posts?.find(p => p.post.id == data.post.id);
1013 editPostRes(data, found);
1017 export function editPostRes(data: PostView, post: PostView) {
1019 post.post.url = data.post.url;
1020 post.post.name = data.post.name;
1021 post.post.nsfw = data.post.nsfw;
1022 post.post.deleted = data.post.deleted;
1023 post.post.removed = data.post.removed;
1024 post.post.featured_community = data.post.featured_community;
1025 post.post.featured_local = data.post.featured_local;
1026 post.post.body = data.post.body;
1027 post.post.locked = data.post.locked;
1028 post.saved = data.saved;
1032 // TODO possible to make these generic?
1033 export function updatePostReportRes(
1034 data: PostReportView,
1035 reports?: PostReportView[]
1037 let found = reports?.find(p => p.post_report.id == data.post_report.id);
1039 found.post_report = data.post_report;
1043 export function updateCommentReportRes(
1044 data: CommentReportView,
1045 reports?: CommentReportView[]
1047 let found = reports?.find(c => c.comment_report.id == data.comment_report.id);
1049 found.comment_report = data.comment_report;
1053 export function updatePrivateMessageReportRes(
1054 data: PrivateMessageReportView,
1055 reports?: PrivateMessageReportView[]
1057 let found = reports?.find(
1058 c => c.private_message_report.id == data.private_message_report.id
1061 found.private_message_report = data.private_message_report;
1065 export function updateRegistrationApplicationRes(
1066 data: RegistrationApplicationView,
1067 applications?: RegistrationApplicationView[]
1069 let found = applications?.find(
1070 ra => ra.registration_application.id == data.registration_application.id
1073 found.registration_application = data.registration_application;
1074 found.admin = data.admin;
1075 found.creator_local_user = data.creator_local_user;
1079 export function commentsToFlatNodes(comments: CommentView[]): CommentNodeI[] {
1080 let nodes: CommentNodeI[] = [];
1081 for (let comment of comments) {
1082 nodes.push({ comment_view: comment, children: [], depth: 0 });
1087 export function convertCommentSortType(sort: SortType): CommentSortType {
1091 sort == "TopWeek" ||
1092 sort == "TopMonth" ||
1096 } else if (sort == "New") {
1098 } else if (sort == "Hot" || sort == "Active") {
1105 export function buildCommentsTree(
1106 comments: CommentView[],
1107 parentComment: boolean
1109 let map = new Map<number, CommentNodeI>();
1110 let depthOffset = !parentComment
1112 : getDepthFromComment(comments[0].comment) ?? 0;
1114 for (let comment_view of comments) {
1115 let depthI = getDepthFromComment(comment_view.comment) ?? 0;
1116 let depth = depthI ? depthI - depthOffset : 0;
1117 let node: CommentNodeI = {
1122 map.set(comment_view.comment.id, { ...node });
1125 let tree: CommentNodeI[] = [];
1127 // if its a parent comment fetch, then push the first comment to the top node.
1128 if (parentComment) {
1129 let cNode = map.get(comments[0].comment.id);
1135 for (let comment_view of comments) {
1136 let child = map.get(comment_view.comment.id);
1138 let parent_id = getCommentParentId(comment_view.comment);
1140 let parent = map.get(parent_id);
1141 // Necessary because blocked comment might not exist
1143 parent.children.push(child);
1146 if (!parentComment) {
1156 export function getCommentParentId(comment?: CommentI): number | undefined {
1157 let split = comment?.path.split(".");
1161 return split && split.length > 1
1162 ? Number(split.at(split.length - 2))
1166 export function getDepthFromComment(comment?: CommentI): number | undefined {
1167 let len = comment?.path.split(".").length;
1168 return len ? len - 2 : undefined;
1171 export function insertCommentIntoTree(
1172 tree: CommentNodeI[],
1174 parentComment: boolean
1176 // Building a fake node to be used for later
1177 let node: CommentNodeI = {
1183 let parentId = getCommentParentId(cv.comment);
1185 let parent_comment = searchCommentTree(tree, parentId);
1186 if (parent_comment) {
1187 node.depth = parent_comment.depth + 1;
1188 parent_comment.children.unshift(node);
1190 } else if (!parentComment) {
1195 export function searchCommentTree(
1196 tree: CommentNodeI[],
1198 ): CommentNodeI | undefined {
1199 for (let node of tree) {
1200 if (node.comment_view.comment.id === id) {
1204 for (const child of node.children) {
1205 let res = searchCommentTree([child], id);
1215 export const colorList: string[] = [
1225 function hsl(num: number) {
1226 return `hsla(${num}, 35%, 50%, 1)`;
1229 export function hostname(url: string): string {
1230 let cUrl = new URL(url);
1231 return cUrl.port ? `${cUrl.hostname}:${cUrl.port}` : `${cUrl.hostname}`;
1234 export function validTitle(title?: string): boolean {
1235 // Initial title is null, minimum length is taken care of by textarea's minLength={3}
1236 if (!title || title.length < 3) return true;
1238 const regex = new RegExp(/.*\S.*/, "g");
1240 return regex.test(title);
1243 export function siteBannerCss(banner: string): string {
1245 background-image: linear-gradient( rgba(0, 0, 0, 0.8), rgba(0, 0, 0, 0.8) ) ,url("${banner}"); \
1246 background-attachment: fixed; \
1247 background-position: top; \
1248 background-repeat: no-repeat; \
1249 background-size: 100% cover; \
1252 max-height: 100vh; \
1256 export function isBrowser() {
1257 return typeof window !== "undefined";
1260 export function setIsoData(context: any): IsoData {
1261 // If its the browser, you need to deserialize the data from the window
1263 let json = window.isoData;
1264 let routeData = json.routeData;
1265 let site_res = json.site_res;
1267 let isoData: IsoData = {
1273 } else return context.router.staticContext;
1276 export function wsSubscribe(parseMessage: any): Subscription | undefined {
1278 return WebSocketService.Instance.subject
1279 .pipe(retryWhen(errors => errors.pipe(delay(3000), take(10))))
1281 msg => parseMessage(msg),
1282 err => console.error(err),
1283 () => console.log("complete")
1290 moment.updateLocale("en", {
1311 export function saveScrollPosition(context: any) {
1312 let path: string = context.router.route.location.pathname;
1313 let y = window.scrollY;
1314 sessionStorage.setItem(`scrollPosition_${path}`, y.toString());
1317 export function restoreScrollPosition(context: any) {
1318 let path: string = context.router.route.location.pathname;
1319 let y = Number(sessionStorage.getItem(`scrollPosition_${path}`));
1320 window.scrollTo(0, y);
1323 export function showLocal(isoData: IsoData): boolean {
1324 return isoData.site_res.site_view.local_site.federation_enabled;
1327 export interface Choice {
1333 export function getUpdatedSearchId(id?: number | null, urlId?: number | null) {
1336 : ((id ?? urlId) === 0 ? undefined : id ?? urlId)?.toString();
1339 export function communityToChoice(cv: CommunityView): Choice {
1341 value: cv.community.id.toString(),
1342 label: communitySelectName(cv),
1346 export function personToChoice(pvs: PersonView): Choice {
1348 value: pvs.person.id.toString(),
1349 label: personSelectName(pvs),
1353 export async function fetchCommunities(q: string) {
1354 let form: Search = {
1356 type_: "Communities",
1358 listing_type: "All",
1361 auth: myAuth(false),
1363 let client = new LemmyHttp(getHttpBase());
1364 return client.search(form);
1367 export async function fetchUsers(q: string) {
1368 let form: Search = {
1372 listing_type: "All",
1375 auth: myAuth(false),
1377 let client = new LemmyHttp(getHttpBase());
1378 return client.search(form);
1381 export function communitySelectName(cv: CommunityView): string {
1382 return cv.community.local
1383 ? cv.community.title
1384 : `${hostname(cv.community.actor_id)}/${cv.community.title}`;
1387 export function personSelectName({
1388 person: { display_name, name, local, actor_id },
1389 }: PersonView): string {
1390 const pName = display_name ?? name;
1391 return local ? pName : `${hostname(actor_id)}/${pName}`;
1394 export function initializeSite(site: GetSiteResponse) {
1395 UserService.Instance.myUserInfo = site.my_user;
1396 i18n.changeLanguage(getLanguages()[0]);
1397 setupEmojiDataModel(site.custom_emojis);
1401 const SHORTNUM_SI_FORMAT = new Intl.NumberFormat("en-US", {
1402 maximumSignificantDigits: 3,
1404 notation: "compact",
1405 compactDisplay: "short",
1408 export function numToSI(value: number): string {
1409 return SHORTNUM_SI_FORMAT.format(value);
1412 export function isBanned(ps: Person): boolean {
1413 let expires = ps.ban_expires;
1414 // Add Z to convert from UTC date
1415 // TODO this check probably isn't necessary anymore
1417 if (ps.banned && new Date(expires + "Z") > new Date()) {
1427 export function myAuth(throwErr = true): string | undefined {
1428 return UserService.Instance.auth(throwErr);
1431 export function enableDownvotes(siteRes: GetSiteResponse): boolean {
1432 return siteRes.site_view.local_site.enable_downvotes;
1435 export function enableNsfw(siteRes: GetSiteResponse): boolean {
1436 return siteRes.site_view.local_site.enable_nsfw;
1439 export function postToCommentSortType(sort: SortType): CommentSortType {
1454 export function canCreateCommunity(
1455 siteRes: GetSiteResponse,
1456 myUserInfo = UserService.Instance.myUserInfo
1458 const adminOnly = siteRes.site_view.local_site.community_creation_admin_only;
1459 // TODO: Make this check if user is logged on as well
1460 return !adminOnly || amAdmin(myUserInfo);
1463 export function isPostBlocked(
1465 myUserInfo: MyUserInfo | undefined = UserService.Instance.myUserInfo
1468 (myUserInfo?.community_blocks
1469 .map(c => c.community.id)
1470 .includes(pv.community.id) ||
1471 myUserInfo?.person_blocks
1472 .map(p => p.target.id)
1473 .includes(pv.creator.id)) ??
1478 /// Checks to make sure you can view NSFW posts. Returns true if you can.
1479 export function nsfwCheck(
1481 myUserInfo = UserService.Instance.myUserInfo
1483 let nsfw = pv.post.nsfw || pv.community.nsfw;
1484 let myShowNsfw = myUserInfo?.local_user_view.local_user.show_nsfw ?? false;
1485 return !nsfw || (nsfw && myShowNsfw);
1488 export function getRandomFromList<T>(list: T[]): T | undefined {
1489 return list.length == 0
1491 : list.at(Math.floor(Math.random() * list.length));
1495 * This shows what language you can select
1497 * Use showAll for the site form
1498 * Use showSite for the profile and community forms
1499 * Use false for both those to filter on your profile and site ones
1501 export function selectableLanguages(
1502 allLanguages: Language[],
1503 siteLanguages: number[],
1506 myUserInfo = UserService.Instance.myUserInfo
1508 let allLangIds = allLanguages.map(l => l.id);
1509 let myLangs = myUserInfo?.discussion_languages ?? allLangIds;
1510 myLangs = myLangs.length == 0 ? allLangIds : myLangs;
1511 let siteLangs = siteLanguages.length == 0 ? allLangIds : siteLanguages;
1514 return allLanguages;
1517 return allLanguages.filter(x => siteLangs.includes(x.id));
1520 .filter(x => siteLangs.includes(x.id))
1521 .filter(x => myLangs.includes(x.id));
1526 export function uploadImage(image: File): Promise<UploadImageResponse> {
1527 const client = new LemmyHttp(getHttpBase());
1529 return client.uploadImage({ image });
1532 interface EmojiMartCategory {
1535 emojis: EmojiMartCustomEmoji[];
1538 interface EmojiMartCustomEmoji {
1542 skins: EmojiMartSkin[];
1545 interface EmojiMartSkin {
1549 const groupBy = <T>(
1551 predicate: (value: T, index: number, array: T[]) => string
1553 array.reduce((acc, value, index, array) => {
1554 (acc[predicate(value, index, array)] ||= []).push(value);
1556 }, {} as { [key: string]: T[] });
1558 export type QueryParams<T extends Record<string, any>> = {
1559 [key in keyof T]?: string;
1562 export function getQueryParams<T extends Record<string, any>>(processors: {
1563 [K in keyof T]: (param: string) => T[K];
1566 const searchParams = new URLSearchParams(window.location.search);
1568 return Array.from(Object.entries(processors)).reduce(
1569 (acc, [key, process]) => ({
1571 [key]: process(searchParams.get(key)),
1580 export function getQueryString<T extends Record<string, string | undefined>>(
1583 return Object.entries(obj)
1584 .filter(([, val]) => val !== undefined && val !== null)
1586 (acc, [key, val], index) => `${acc}${index > 0 ? "&" : ""}${key}=${val}`,
1591 export function isAuthPath(pathname: string) {
1592 return /create_.*|inbox|settings|setup|admin|reports|registration_applications/g.test(
1597 export function canShare() {
1598 return isBrowser() && !!navigator.canShare;
1601 export function share(shareData: ShareData) {
1603 navigator.share(shareData);