1 import { Picker } from "emoji-mart";
2 import emojiShortName from "emoji-short-name";
4 BlockCommunityResponse,
12 CommunityModeratorView,
25 PrivateMessageReportView,
27 RegistrationApplicationView,
31 } from "lemmy-js-client";
32 import { default as MarkdownIt } from "markdown-it";
33 import markdown_it_container from "markdown-it-container";
34 import markdown_it_emoji from "markdown-it-emoji/bare";
35 import markdown_it_footnote from "markdown-it-footnote";
36 import markdown_it_html5_embed from "markdown-it-html5-embed";
37 import markdown_it_sub from "markdown-it-sub";
38 import markdown_it_sup from "markdown-it-sup";
39 import Renderer from "markdown-it/lib/renderer";
40 import Token from "markdown-it/lib/token";
41 import moment from "moment";
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, VoteType } from "./interfaces";
47 import { HttpService, UserService } from "./services";
51 Tribute = require("tributejs");
54 export const favIconUrl = "/static/assets/icons/favicon.svg";
55 export const favIconPngUrl = "/static/assets/icons/apple-touch-icon.png";
57 // export const defaultFavIcon = `${window.location.protocol}//${window.location.host}${favIconPngUrl}`;
58 export const repoUrl = "https://github.com/LemmyNet";
59 export const joinLemmyUrl = "https://join-lemmy.org";
60 export const donateLemmyUrl = `${joinLemmyUrl}/donate`;
61 export const docsUrl = `${joinLemmyUrl}/docs/en/index.html`;
62 export const helpGuideUrl = `${joinLemmyUrl}/docs/en/users/01-getting-started.html`; // TODO find a way to redirect to the non-en folder
63 export const markdownHelpUrl = `${joinLemmyUrl}/docs/en/users/02-media.html`;
64 export const sortingHelpUrl = `${joinLemmyUrl}/docs/en/users/03-votes-and-ranking.html`;
65 export const archiveTodayUrl = "https://archive.today";
66 export const ghostArchiveUrl = "https://ghostarchive.org";
67 export const webArchiveUrl = "https://web.archive.org";
68 export const elementUrl = "https://element.io";
70 export const postRefetchSeconds: number = 60 * 1000;
71 export const fetchLimit = 40;
72 export const trendingFetchLimit = 6;
73 export const mentionDropdownFetchLimit = 10;
74 export const commentTreeMaxDepth = 8;
75 export const markdownFieldCharacterLimit = 50000;
76 export const maxUploadImages = 20;
77 export const concurrentImageUpload = 4;
79 export const relTags = "noopener nofollow";
81 export const emDash = "\u2014";
83 export type ThemeColor =
106 export interface ErrorPageData {
108 adminMatrixIds?: string[];
111 const customEmojis: EmojiMartCategory[] = [];
112 export let customEmojisLookup: Map<string, CustomEmojiView> = new Map<
117 const DEFAULT_ALPHABET =
118 "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
120 function getRandomCharFromAlphabet(alphabet: string): string {
121 return alphabet.charAt(Math.floor(Math.random() * alphabet.length));
124 export function getIdFromString(id?: string): number | undefined {
125 return id && id !== "0" && !Number.isNaN(Number(id)) ? Number(id) : undefined;
128 export function getPageFromString(page?: string): number {
129 return page && !Number.isNaN(Number(page)) ? Number(page) : 1;
132 export function randomStr(
133 idDesiredLength = 20,
134 alphabet = DEFAULT_ALPHABET
137 * Create n-long array and map it to random chars from given alphabet.
138 * Then join individual chars as string
140 return Array.from({ length: idDesiredLength })
142 return getRandomCharFromAlphabet(alphabet);
147 const html5EmbedConfig = {
149 useImageSyntax: true, // Enables video/audio embed with ![]() syntax (default)
151 audio: 'controls preload="metadata"',
152 video: 'width="100%" max-height="100%" controls loop preload="metadata"',
157 const spoilerConfig = {
158 validate: (params: string) => {
159 return params.trim().match(/^spoiler\s+(.*)$/);
162 render: (tokens: any, idx: any) => {
163 var m = tokens[idx].info.trim().match(/^spoiler\s+(.*)$/);
165 if (tokens[idx].nesting === 1) {
167 return `<details><summary> ${md.utils.escapeHtml(m[1])} </summary>\n`;
170 return "</details>\n";
175 export let md: MarkdownIt = new MarkdownIt();
177 export let mdNoImages: MarkdownIt = new MarkdownIt();
179 export function hotRankComment(comment_view: CommentView): number {
180 return hotRank(comment_view.counts.score, comment_view.comment.published);
183 export function hotRankActivePost(post_view: PostView): number {
184 return hotRank(post_view.counts.score, post_view.counts.newest_comment_time);
187 export function hotRankPost(post_view: PostView): number {
188 return hotRank(post_view.counts.score, post_view.post.published);
191 export function hotRank(score: number, timeStr: string): number {
192 // Rank = ScaleFactor * sign(Score) * log(1 + abs(Score)) / (Time + 2)^Gravity
193 const date: Date = new Date(timeStr + "Z"); // Add Z to convert from UTC date
194 const now: Date = new Date();
195 const hoursElapsed: number = (now.getTime() - date.getTime()) / 36e5;
198 (10000 * Math.log10(Math.max(1, 3 + Number(score)))) /
199 Math.pow(hoursElapsed + 2, 1.8);
201 // console.log(`Comment: ${comment.content}\nRank: ${rank}\nScore: ${comment.score}\nHours: ${hoursElapsed}`);
206 export function mdToHtml(text: string) {
207 return { __html: md.render(text) };
210 export function mdToHtmlNoImages(text: string) {
211 return { __html: mdNoImages.render(text) };
214 export function mdToHtmlInline(text: string) {
215 return { __html: md.renderInline(text) };
218 export function getUnixTime(text?: string): number | undefined {
219 return text ? new Date(text).getTime() / 1000 : undefined;
222 export function futureDaysToUnixTime(days?: number): number | undefined {
225 new Date(Date.now() + 1000 * 60 * 60 * 24 * days).getTime() / 1000
230 export function canMod(
232 mods?: CommunityModeratorView[],
233 admins?: PersonView[],
234 myUserInfo = UserService.Instance.myUserInfo,
237 // You can do moderator actions only on the mods added after you.
240 ?.map(a => a.person.id)
241 .concat(mods?.map(m => m.moderator.id) ?? []) ?? [];
244 const myIndex = adminsThenMods.findIndex(
245 id => id == myUserInfo.local_user_view.person.id
250 // onSelf +1 on mod actions not for yourself, IE ban, remove, etc
251 adminsThenMods = adminsThenMods.slice(0, myIndex + (onSelf ? 0 : 1));
252 return !adminsThenMods.includes(creator_id);
259 export function canAdmin(
261 admins?: PersonView[],
262 myUserInfo = UserService.Instance.myUserInfo,
265 return canMod(creatorId, undefined, admins, myUserInfo, onSelf);
268 export function isMod(
270 mods?: CommunityModeratorView[]
272 return mods?.map(m => m.moderator.id).includes(creatorId) ?? false;
275 export function amMod(
276 mods?: CommunityModeratorView[],
277 myUserInfo = UserService.Instance.myUserInfo
279 return myUserInfo ? isMod(myUserInfo.local_user_view.person.id, mods) : false;
282 export function isAdmin(creatorId: number, admins?: PersonView[]): boolean {
283 return admins?.map(a => a.person.id).includes(creatorId) ?? false;
286 export function amAdmin(myUserInfo = UserService.Instance.myUserInfo): boolean {
287 return myUserInfo?.local_user_view.person.admin ?? false;
290 export function amCommunityCreator(
292 mods?: CommunityModeratorView[],
293 myUserInfo = UserService.Instance.myUserInfo
295 const myId = myUserInfo?.local_user_view.person.id;
296 // Don't allow mod actions on yourself
297 return myId == mods?.at(0)?.moderator.id && myId != creator_id;
300 export function amSiteCreator(
302 admins?: PersonView[],
303 myUserInfo = UserService.Instance.myUserInfo
305 const myId = myUserInfo?.local_user_view.person.id;
306 return myId == admins?.at(0)?.person.id && myId != creator_id;
309 export function amTopMod(
310 mods: CommunityModeratorView[],
311 myUserInfo = UserService.Instance.myUserInfo
313 return mods.at(0)?.moderator.id == myUserInfo?.local_user_view.person.id;
316 const imageRegex = /(http)?s?:?(\/\/[^"']*\.(?:jpg|jpeg|gif|png|svg|webp))/;
317 const videoRegex = /(http)?s?:?(\/\/[^"']*\.(?:mp4|webm))/;
319 export function isImage(url: string) {
320 return imageRegex.test(url);
323 export function isVideo(url: string) {
324 return videoRegex.test(url);
327 export function validURL(str: string) {
328 return !!new URL(str);
331 export function communityRSSUrl(actorId: string, sort: string): string {
332 const url = new URL(actorId);
333 return `${url.origin}/feeds${url.pathname}.xml?sort=${sort}`;
336 export function validEmail(email: string) {
338 /^(([^\s"(),.:;<>@[\\\]]+(\.[^\s"(),.:;<>@[\\\]]+)*)|(".+"))@((\[(?:\d{1,3}\.){3}\d{1,3}])|(([\dA-Za-z\-]+\.)+[A-Za-z]{2,}))$/;
339 return re.test(String(email).toLowerCase());
342 export function capitalizeFirstLetter(str: string): string {
343 return str.charAt(0).toUpperCase() + str.slice(1);
346 export async function getSiteMetadata(url: string) {
347 const form: GetSiteMetadata = { url };
348 const client = new LemmyHttp(getHttpBase());
349 return client.getSiteMetadata(form);
352 export function getDataTypeString(dt: DataType) {
353 return dt === DataType.Post ? "Post" : "Comment";
356 export function debounce<T extends any[], R>(
357 func: (...e: T) => R,
361 // 'private' variable for instance
362 // The returned function will be able to reference this due to closure.
363 // Each call to the returned function will share this common timer.
364 let timeout: NodeJS.Timeout | null;
366 // Calling debounce returns a new anonymous function
368 // reference the context and args for the setTimeout function
369 const args = arguments;
371 // Should the function be called now? If immediate is true
372 // and not already in a timeout then the answer is: Yes
373 const callNow = immediate && !timeout;
375 // This is the basic debounce behavior where you can call this
376 // function several times, but it will only execute once
377 // [before or after imposing a delay].
378 // Each time the returned function is called, the timer starts over.
379 clearTimeout(timeout ?? undefined);
381 // Set the new timeout
382 timeout = setTimeout(function () {
383 // Inside the timeout function, clear the timeout variable
384 // which will let the next execution run when in 'immediate' mode
387 // Check if the function already ran with the immediate flag
389 // Call the original function with apply
390 // apply lets you define the 'this' object as well as the arguments
391 // (both captured before setTimeout)
392 func.apply(this, args);
396 // Immediate mode and no wait timer? Execute the function..
397 if (callNow) func.apply(this, args);
401 export function getLanguages(
403 myUserInfo = UserService.Instance.myUserInfo
405 const myLang = myUserInfo?.local_user_view.local_user.interface_language;
406 const lang = override || myLang || "browser";
408 if (lang == "browser" && isBrowser()) {
409 return getBrowserLanguages();
415 function getBrowserLanguages(): string[] {
416 // Intersect lemmy's langs, with the browser langs
417 const langs = languages ? languages.map(l => l.code) : ["en"];
419 // NOTE, mobile browsers seem to be missing this list, so append en
420 const allowedLangs = navigator.languages
422 .filter(v => langs.includes(v));
426 export async function fetchThemeList(): Promise<string[]> {
427 return fetch("/css/themelist").then(res => res.json());
430 export async function setTheme(theme: string, forceReload = false) {
434 if (theme === "browser" && !forceReload) {
437 // This is only run on a force reload
438 if (theme == "browser") {
442 const themeList = await fetchThemeList();
444 // Unload all the other themes
445 for (var i = 0; i < themeList.length; i++) {
446 const styleSheet = document.getElementById(themeList[i]);
448 styleSheet.setAttribute("disabled", "disabled");
453 .getElementById("default-light")
454 ?.setAttribute("disabled", "disabled");
455 document.getElementById("default-dark")?.setAttribute("disabled", "disabled");
457 // Load the theme dynamically
458 const cssLoc = `/css/themes/${theme}.css`;
460 loadCss(theme, cssLoc);
461 document.getElementById(theme)?.removeAttribute("disabled");
464 export function loadCss(id: string, loc: string) {
465 if (!document.getElementById(id)) {
466 var head = document.getElementsByTagName("head")[0];
467 var link = document.createElement("link");
469 link.rel = "stylesheet";
470 link.type = "text/css";
473 head.appendChild(link);
477 export function objectFlip(obj: any) {
479 Object.keys(obj).forEach(key => {
485 export function showAvatars(
486 myUserInfo = UserService.Instance.myUserInfo
488 return myUserInfo?.local_user_view.local_user.show_avatars ?? true;
491 export function showScores(
492 myUserInfo = UserService.Instance.myUserInfo
494 return myUserInfo?.local_user_view.local_user.show_scores ?? true;
497 export function isCakeDay(published: string): boolean {
498 // moment(undefined) or moment.utc(undefined) returns the current date/time
499 // moment(null) or moment.utc(null) returns null
500 const createDate = moment.utc(published).local();
501 const currentDate = moment(new Date());
504 createDate.date() === currentDate.date() &&
505 createDate.month() === currentDate.month() &&
506 createDate.year() !== currentDate.year()
510 export function toast(text: string, background: ThemeColor = "success") {
512 const backgroundColor = `var(--${background})`;
515 backgroundColor: backgroundColor,
523 export function pictrsDeleteToast(filename: string, deleteUrl: string) {
525 const clickToDeleteText = i18n.t("click_to_delete_picture", { filename });
526 const deletePictureText = i18n.t("picture_deleted", {
529 const failedDeletePictureText = i18n.t("failed_to_delete_picture", {
533 const backgroundColor = `var(--light)`;
535 const toast = Toastify({
536 text: clickToDeleteText,
537 backgroundColor: backgroundColor,
543 fetch(deleteUrl).then(res => {
545 if (res.ok === true) {
546 alert(deletePictureText);
548 alert(failedDeletePictureText);
560 export function setupTribute() {
562 noMatchTemplate: function () {
569 menuItemTemplate: (item: any) => {
570 const shortName = `:${item.original.key}:`;
571 return `${item.original.val} ${shortName}`;
573 selectTemplate: (item: any) => {
574 const customEmoji = customEmojisLookup.get(
577 if (customEmoji == undefined) return `${item.original.val}`;
579 return `![${customEmoji.alt_text}](${customEmoji.image_url} "${customEmoji.shortcode}")`;
581 values: Object.entries(emojiShortName)
583 return { key: e[1], val: e[0] };
586 Array.from(customEmojisLookup.entries()).map(k => ({
588 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}" />`,
592 autocompleteMode: true,
594 // menuItemLimit: mentionDropdownFetchLimit,
595 menuShowMinLength: 2,
600 selectTemplate: (item: any) => {
601 const it: PersonTribute = item.original;
602 return `[${it.key}](${it.view.person.actor_id})`;
604 values: debounce(async (text: string, cb: any) => {
605 cb(await personSearch(text));
608 autocompleteMode: true,
610 // menuItemLimit: mentionDropdownFetchLimit,
611 menuShowMinLength: 2,
617 selectTemplate: (item: any) => {
618 const it: CommunityTribute = item.original;
619 return `[${it.key}](${it.view.community.actor_id})`;
621 values: debounce(async (text: string, cb: any) => {
622 cb(await communitySearch(text));
625 autocompleteMode: true,
627 // menuItemLimit: mentionDropdownFetchLimit,
628 menuShowMinLength: 2,
634 function setupEmojiDataModel(custom_emoji_views: CustomEmojiView[]) {
635 const groupedEmojis = groupBy(
637 x => x.custom_emoji.category
639 for (const [category, emojis] of Object.entries(groupedEmojis)) {
643 emojis: emojis.map(emoji => ({
644 id: emoji.custom_emoji.shortcode,
645 name: emoji.custom_emoji.shortcode,
646 keywords: emoji.keywords.map(x => x.keyword),
647 skins: [{ src: emoji.custom_emoji.image_url }],
651 customEmojisLookup = new Map(
652 custom_emoji_views.map(view => [view.custom_emoji.shortcode, view])
656 export function updateEmojiDataModel(custom_emoji_view: CustomEmojiView) {
657 const emoji: EmojiMartCustomEmoji = {
658 id: custom_emoji_view.custom_emoji.shortcode,
659 name: custom_emoji_view.custom_emoji.shortcode,
660 keywords: custom_emoji_view.keywords.map(x => x.keyword),
661 skins: [{ src: custom_emoji_view.custom_emoji.image_url }],
663 const categoryIndex = customEmojis.findIndex(
664 x => x.id == custom_emoji_view.custom_emoji.category
666 if (categoryIndex == -1) {
668 id: custom_emoji_view.custom_emoji.category,
669 name: custom_emoji_view.custom_emoji.category,
673 const emojiIndex = customEmojis[categoryIndex].emojis.findIndex(
674 x => x.id == custom_emoji_view.custom_emoji.shortcode
676 if (emojiIndex == -1) {
677 customEmojis[categoryIndex].emojis.push(emoji);
679 customEmojis[categoryIndex].emojis[emojiIndex] = emoji;
682 customEmojisLookup.set(
683 custom_emoji_view.custom_emoji.shortcode,
688 export function removeFromEmojiDataModel(id: number) {
689 let view: CustomEmojiView | undefined;
690 for (const item of customEmojisLookup.values()) {
691 if (item.custom_emoji.id === id) {
697 const categoryIndex = customEmojis.findIndex(
698 x => x.id == view?.custom_emoji.category
700 const emojiIndex = customEmojis[categoryIndex].emojis.findIndex(
701 x => x.id == view?.custom_emoji.shortcode
703 customEmojis[categoryIndex].emojis = customEmojis[
705 ].emojis.splice(emojiIndex, 1);
707 customEmojisLookup.delete(view?.custom_emoji.shortcode);
710 function setupMarkdown() {
711 const markdownItConfig: MarkdownIt.Options = {
717 const emojiDefs = Array.from(customEmojisLookup.entries()).reduce(
718 (main, [key, value]) => ({ ...main, [key]: value }),
721 md = new MarkdownIt(markdownItConfig)
722 .use(markdown_it_sub)
723 .use(markdown_it_sup)
724 .use(markdown_it_footnote)
725 .use(markdown_it_html5_embed, html5EmbedConfig)
726 .use(markdown_it_container, "spoiler", spoilerConfig)
727 .use(markdown_it_emoji, {
731 mdNoImages = new MarkdownIt(markdownItConfig)
732 .use(markdown_it_sub)
733 .use(markdown_it_sup)
734 .use(markdown_it_footnote)
735 .use(markdown_it_html5_embed, html5EmbedConfig)
736 .use(markdown_it_container, "spoiler", spoilerConfig)
737 .use(markdown_it_emoji, {
741 var defaultRenderer = md.renderer.rules.image;
742 md.renderer.rules.image = function (
745 options: MarkdownIt.Options,
749 //Provide custom renderer for our emojis to allow us to add a css class and force size dimensions on them.
750 const item = tokens[idx] as any;
751 const title = item.attrs.length >= 3 ? item.attrs[2][1] : "";
752 const src: string = item.attrs[0][1];
753 const isCustomEmoji = customEmojisLookup.get(title) != undefined;
754 if (!isCustomEmoji) {
755 return defaultRenderer?.(tokens, idx, options, env, self) ?? "";
757 const alt_text = item.content;
758 return `<img class="icon icon-emoji" src="${src}" title="${title}" alt="${alt_text}"/>`;
762 export function getEmojiMart(
763 onEmojiSelect: (e: any) => void,
764 customPickerOptions: any = {}
766 const pickerOptions = {
767 ...customPickerOptions,
768 onEmojiSelect: onEmojiSelect,
769 custom: customEmojis,
771 return new Picker(pickerOptions);
774 var tippyInstance: any;
776 tippyInstance = tippy("[data-tippy-content]");
779 export function setupTippy() {
781 tippyInstance.forEach((e: any) => e.destroy());
782 tippyInstance = tippy("[data-tippy-content]", {
784 // Display on "long press"
785 touch: ["hold", 500],
790 interface PersonTribute {
795 async function personSearch(text: string): Promise<PersonTribute[]> {
796 const usersResponse = await fetchUsers(text);
798 return usersResponse.map(pv => ({
799 key: `@${pv.person.name}@${hostname(pv.person.actor_id)}`,
804 interface CommunityTribute {
809 async function communitySearch(text: string): Promise<CommunityTribute[]> {
810 const communitiesResponse = await fetchCommunities(text);
812 return communitiesResponse.map(cv => ({
813 key: `!${cv.community.name}@${hostname(cv.community.actor_id)}`,
818 export function getRecipientIdFromProps(props: any): number {
819 return props.match.params.recipient_id
820 ? Number(props.match.params.recipient_id)
824 export function getIdFromProps(props: any): number | undefined {
825 const id = props.match.params.post_id;
826 return id ? Number(id) : undefined;
829 export function getCommentIdFromProps(props: any): number | undefined {
830 const id = props.match.params.comment_id;
831 return id ? Number(id) : undefined;
834 type ImmutableListKey =
843 | "private_message_report"
844 | "registration_application";
846 function editListImmutable<
847 T extends { [key in F]: { id: number } },
848 F extends ImmutableListKey
849 >(fieldName: F, data: T, list: T[]): T[] {
851 ...list.map(c => (c[fieldName].id === data[fieldName].id ? data : c)),
855 export function editComment(
857 comments: CommentView[]
859 return editListImmutable("comment", data, comments);
862 export function editCommentReply(
863 data: CommentReplyView,
864 replies: CommentReplyView[]
865 ): CommentReplyView[] {
866 return editListImmutable("comment_reply", data, replies);
869 interface WithComment {
871 counts: CommentAggregates;
876 export function editMention(
877 data: PersonMentionView,
878 comments: PersonMentionView[]
879 ): PersonMentionView[] {
880 return editListImmutable("person_mention", data, comments);
883 export function editCommunity(
885 communities: CommunityView[]
887 return editListImmutable("community", data, communities);
890 export function editPrivateMessage(
891 data: PrivateMessageView,
892 messages: PrivateMessageView[]
893 ): PrivateMessageView[] {
894 return editListImmutable("private_message", data, messages);
897 export function editPost(data: PostView, posts: PostView[]): PostView[] {
898 return editListImmutable("post", data, posts);
901 export function editPostReport(
902 data: PostReportView,
903 reports: PostReportView[]
905 return editListImmutable("post_report", data, reports);
908 export function editCommentReport(
909 data: CommentReportView,
910 reports: CommentReportView[]
911 ): CommentReportView[] {
912 return editListImmutable("comment_report", data, reports);
915 export function editPrivateMessageReport(
916 data: PrivateMessageReportView,
917 reports: PrivateMessageReportView[]
918 ): PrivateMessageReportView[] {
919 return editListImmutable("private_message_report", data, reports);
922 export function editRegistrationApplication(
923 data: RegistrationApplicationView,
924 apps: RegistrationApplicationView[]
925 ): RegistrationApplicationView[] {
926 return editListImmutable("registration_application", data, apps);
929 export function editWith<D extends WithComment, L extends WithComment>(
930 { comment, counts, saved, my_vote }: D,
935 c.comment.id === comment.id
936 ? { ...c, comment, counts, saved, my_vote }
942 export function updatePersonBlock(
943 data: BlockPersonResponse,
944 myUserInfo: MyUserInfo | undefined = UserService.Instance.myUserInfo
948 myUserInfo.person_blocks.push({
949 person: myUserInfo.local_user_view.person,
950 target: data.person_view.person,
952 toast(`${i18n.t("blocked")} ${data.person_view.person.name}`);
954 myUserInfo.person_blocks = myUserInfo.person_blocks.filter(
955 i => i.target.id !== data.person_view.person.id
957 toast(`${i18n.t("unblocked")} ${data.person_view.person.name}`);
962 export function updateCommunityBlock(
963 data: BlockCommunityResponse,
964 myUserInfo: MyUserInfo | undefined = UserService.Instance.myUserInfo
968 myUserInfo.community_blocks.push({
969 person: myUserInfo.local_user_view.person,
970 community: data.community_view.community,
972 toast(`${i18n.t("blocked")} ${data.community_view.community.name}`);
974 myUserInfo.community_blocks = myUserInfo.community_blocks.filter(
975 i => i.community.id !== data.community_view.community.id
977 toast(`${i18n.t("unblocked")} ${data.community_view.community.name}`);
982 export function commentsToFlatNodes(comments: CommentView[]): CommentNodeI[] {
983 const nodes: CommentNodeI[] = [];
984 for (const comment of comments) {
985 nodes.push({ comment_view: comment, children: [], depth: 0 });
990 export function convertCommentSortType(sort: SortType): CommentSortType {
995 sort == "TopMonth" ||
999 } else if (sort == "New") {
1001 } else if (sort == "Hot" || sort == "Active") {
1008 export function buildCommentsTree(
1009 comments: CommentView[],
1010 parentComment: boolean
1012 const map = new Map<number, CommentNodeI>();
1013 const depthOffset = !parentComment
1015 : getDepthFromComment(comments[0].comment) ?? 0;
1017 for (const comment_view of comments) {
1018 const depthI = getDepthFromComment(comment_view.comment) ?? 0;
1019 const depth = depthI ? depthI - depthOffset : 0;
1020 const node: CommentNodeI = {
1025 map.set(comment_view.comment.id, { ...node });
1028 const tree: CommentNodeI[] = [];
1030 // if its a parent comment fetch, then push the first comment to the top node.
1031 if (parentComment) {
1032 const cNode = map.get(comments[0].comment.id);
1038 for (const comment_view of comments) {
1039 const child = map.get(comment_view.comment.id);
1041 const parent_id = getCommentParentId(comment_view.comment);
1043 const parent = map.get(parent_id);
1044 // Necessary because blocked comment might not exist
1046 parent.children.push(child);
1049 if (!parentComment) {
1059 export function getCommentParentId(comment?: CommentI): number | undefined {
1060 const split = comment?.path.split(".");
1064 return split && split.length > 1
1065 ? Number(split.at(split.length - 2))
1069 export function getDepthFromComment(comment?: CommentI): number | undefined {
1070 const len = comment?.path.split(".").length;
1071 return len ? len - 2 : undefined;
1074 // TODO make immutable
1075 export function insertCommentIntoTree(
1076 tree: CommentNodeI[],
1078 parentComment: boolean
1080 // Building a fake node to be used for later
1081 const node: CommentNodeI = {
1087 const parentId = getCommentParentId(cv.comment);
1089 const parent_comment = searchCommentTree(tree, parentId);
1090 if (parent_comment) {
1091 node.depth = parent_comment.depth + 1;
1092 parent_comment.children.unshift(node);
1094 } else if (!parentComment) {
1099 export function searchCommentTree(
1100 tree: CommentNodeI[],
1102 ): CommentNodeI | undefined {
1103 for (const node of tree) {
1104 if (node.comment_view.comment.id === id) {
1108 for (const child of node.children) {
1109 const res = searchCommentTree([child], id);
1119 export const colorList: string[] = [
1129 function hsl(num: number) {
1130 return `hsla(${num}, 35%, 50%, 0.5)`;
1133 export function hostname(url: string): string {
1134 const cUrl = new URL(url);
1135 return cUrl.port ? `${cUrl.hostname}:${cUrl.port}` : `${cUrl.hostname}`;
1138 export function validTitle(title?: string): boolean {
1139 // Initial title is null, minimum length is taken care of by textarea's minLength={3}
1140 if (!title || title.length < 3) return true;
1142 const regex = new RegExp(/.*\S.*/, "g");
1144 return regex.test(title);
1147 export function siteBannerCss(banner: string): string {
1149 background-image: linear-gradient( rgba(0, 0, 0, 0.8), rgba(0, 0, 0, 0.8) ) ,url("${banner}"); \
1150 background-attachment: fixed; \
1151 background-position: top; \
1152 background-repeat: no-repeat; \
1153 background-size: 100% cover; \
1156 max-height: 100vh; \
1160 export function isBrowser() {
1161 return typeof window !== "undefined";
1164 export function setIsoData(context: any): IsoData {
1165 // If its the browser, you need to deserialize the data from the window
1167 return window.isoData;
1168 } else return context.router.staticContext;
1171 moment.updateLocale("en", {
1192 export function saveScrollPosition(context: any) {
1193 const path: string = context.router.route.location.pathname;
1194 const y = window.scrollY;
1195 sessionStorage.setItem(`scrollPosition_${path}`, y.toString());
1198 export function restoreScrollPosition(context: any) {
1199 const path: string = context.router.route.location.pathname;
1200 const y = Number(sessionStorage.getItem(`scrollPosition_${path}`));
1201 window.scrollTo(0, y);
1204 export function showLocal(isoData: IsoData): boolean {
1205 return isoData.site_res.site_view.local_site.federation_enabled;
1208 export interface Choice {
1214 export function getUpdatedSearchId(id?: number | null, urlId?: number | null) {
1217 : ((id ?? urlId) === 0 ? undefined : id ?? urlId)?.toString();
1220 export function communityToChoice(cv: CommunityView): Choice {
1222 value: cv.community.id.toString(),
1223 label: communitySelectName(cv),
1227 export function personToChoice(pvs: PersonView): Choice {
1229 value: pvs.person.id.toString(),
1230 label: personSelectName(pvs),
1234 function fetchSearchResults(q: string, type_: SearchType) {
1235 const form: Search = {
1239 listing_type: "All",
1245 return HttpService.client.search(form);
1248 export async function fetchCommunities(q: string) {
1249 const res = await fetchSearchResults(q, "Communities");
1251 return res.state === "success" ? res.data.communities : [];
1254 export async function fetchUsers(q: string) {
1255 const res = await fetchSearchResults(q, "Users");
1257 return res.state === "success" ? res.data.users : [];
1260 export function communitySelectName(cv: CommunityView): string {
1261 return cv.community.local
1262 ? cv.community.title
1263 : `${hostname(cv.community.actor_id)}/${cv.community.title}`;
1266 export function personSelectName({
1267 person: { display_name, name, local, actor_id },
1268 }: PersonView): string {
1269 const pName = display_name ?? name;
1270 return local ? pName : `${hostname(actor_id)}/${pName}`;
1273 export function initializeSite(site?: GetSiteResponse) {
1274 UserService.Instance.myUserInfo = site?.my_user;
1275 i18n.changeLanguage(getLanguages()[0]);
1277 setupEmojiDataModel(site.custom_emojis ?? []);
1282 const SHORTNUM_SI_FORMAT = new Intl.NumberFormat("en-US", {
1283 maximumSignificantDigits: 3,
1285 notation: "compact",
1286 compactDisplay: "short",
1289 export function numToSI(value: number): string {
1290 return SHORTNUM_SI_FORMAT.format(value);
1293 export function isBanned(ps: Person): boolean {
1294 const expires = ps.ban_expires;
1295 // Add Z to convert from UTC date
1296 // TODO this check probably isn't necessary anymore
1298 if (ps.banned && new Date(expires + "Z") > new Date()) {
1308 export function myAuth(): string | undefined {
1309 return UserService.Instance.auth();
1312 export function myAuthRequired(): string {
1313 return UserService.Instance.auth(true) ?? "";
1316 export function enableDownvotes(siteRes: GetSiteResponse): boolean {
1317 return siteRes.site_view.local_site.enable_downvotes;
1320 export function enableNsfw(siteRes: GetSiteResponse): boolean {
1321 return siteRes.site_view.local_site.enable_nsfw;
1324 export function postToCommentSortType(sort: SortType): CommentSortType {
1339 export function canCreateCommunity(
1340 siteRes: GetSiteResponse,
1341 myUserInfo = UserService.Instance.myUserInfo
1343 const adminOnly = siteRes.site_view.local_site.community_creation_admin_only;
1344 // TODO: Make this check if user is logged on as well
1345 return !adminOnly || amAdmin(myUserInfo);
1348 export function isPostBlocked(
1350 myUserInfo: MyUserInfo | undefined = UserService.Instance.myUserInfo
1353 (myUserInfo?.community_blocks
1354 .map(c => c.community.id)
1355 .includes(pv.community.id) ||
1356 myUserInfo?.person_blocks
1357 .map(p => p.target.id)
1358 .includes(pv.creator.id)) ??
1363 /// Checks to make sure you can view NSFW posts. Returns true if you can.
1364 export function nsfwCheck(
1366 myUserInfo = UserService.Instance.myUserInfo
1368 const nsfw = pv.post.nsfw || pv.community.nsfw;
1369 const myShowNsfw = myUserInfo?.local_user_view.local_user.show_nsfw ?? false;
1370 return !nsfw || (nsfw && myShowNsfw);
1373 export function getRandomFromList<T>(list: T[]): T | undefined {
1374 return list.length == 0
1376 : list.at(Math.floor(Math.random() * list.length));
1380 * This shows what language you can select
1382 * Use showAll for the site form
1383 * Use showSite for the profile and community forms
1384 * Use false for both those to filter on your profile and site ones
1386 export function selectableLanguages(
1387 allLanguages: Language[],
1388 siteLanguages: number[],
1391 myUserInfo = UserService.Instance.myUserInfo
1393 const allLangIds = allLanguages.map(l => l.id);
1394 let myLangs = myUserInfo?.discussion_languages ?? allLangIds;
1395 myLangs = myLangs.length == 0 ? allLangIds : myLangs;
1396 const siteLangs = siteLanguages.length == 0 ? allLangIds : siteLanguages;
1399 return allLanguages;
1402 return allLanguages.filter(x => siteLangs.includes(x.id));
1405 .filter(x => siteLangs.includes(x.id))
1406 .filter(x => myLangs.includes(x.id));
1411 interface EmojiMartCategory {
1414 emojis: EmojiMartCustomEmoji[];
1417 interface EmojiMartCustomEmoji {
1421 skins: EmojiMartSkin[];
1424 interface EmojiMartSkin {
1428 const groupBy = <T>(
1430 predicate: (value: T, index: number, array: T[]) => string
1432 array.reduce((acc, value, index, array) => {
1433 (acc[predicate(value, index, array)] ||= []).push(value);
1435 }, {} as { [key: string]: T[] });
1437 export type QueryParams<T extends Record<string, any>> = {
1438 [key in keyof T]?: string;
1441 export function getQueryParams<T extends Record<string, any>>(processors: {
1442 [K in keyof T]: (param: string) => T[K];
1445 const searchParams = new URLSearchParams(window.location.search);
1447 return Array.from(Object.entries(processors)).reduce(
1448 (acc, [key, process]) => ({
1450 [key]: process(searchParams.get(key)),
1459 export function getQueryString<T extends Record<string, string | undefined>>(
1462 return Object.entries(obj)
1463 .filter(([, val]) => val !== undefined && val !== null)
1465 (acc, [key, val], index) => `${acc}${index > 0 ? "&" : ""}${key}=${val}`,
1470 export function isAuthPath(pathname: string) {
1471 return /create_.*|inbox|settings|admin|reports|registration_applications/g.test(
1476 export function canShare() {
1477 return isBrowser() && !!navigator.canShare;
1480 export function share(shareData: ShareData) {
1482 navigator.share(shareData);
1486 export function newVote(voteType: VoteType, myVote?: number): number {
1487 if (voteType == VoteType.Upvote) {
1488 return myVote == 1 ? 0 : 1;
1490 return myVote == -1 ? 0 : -1;