1 import { Picker } from "emoji-mart";
2 import emojiShortName from "emoji-short-name";
4 BlockCommunityResponse,
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 tippy from "tippy.js";
41 import Toastify from "toastify-js";
42 import { getHttpBase } from "./env";
43 import { i18n } from "./i18next";
44 import { CommentNodeI, DataType, IsoData, VoteType } from "./interfaces";
45 import { HttpService, UserService } from "./services";
46 import { isBrowser } from "./utils/browser/is-browser";
47 import { debounce } from "./utils/helpers/debounce";
48 import { groupBy } from "./utils/helpers/group-by";
52 Tribute = require("tributejs");
55 export const favIconUrl = "/static/assets/icons/favicon.svg";
56 export const favIconPngUrl = "/static/assets/icons/apple-touch-icon.png";
58 // export const defaultFavIcon = `${window.location.protocol}//${window.location.host}${favIconPngUrl}`;
59 export const repoUrl = "https://github.com/LemmyNet";
60 export const joinLemmyUrl = "https://join-lemmy.org";
61 export const donateLemmyUrl = `${joinLemmyUrl}/donate`;
62 export const docsUrl = `${joinLemmyUrl}/docs/en/index.html`;
63 export const helpGuideUrl = `${joinLemmyUrl}/docs/en/users/01-getting-started.html`; // TODO find a way to redirect to the non-en folder
64 export const markdownHelpUrl = `${joinLemmyUrl}/docs/en/users/02-media.html`;
65 export const sortingHelpUrl = `${joinLemmyUrl}/docs/en/users/03-votes-and-ranking.html`;
66 export const archiveTodayUrl = "https://archive.today";
67 export const ghostArchiveUrl = "https://ghostarchive.org";
68 export const webArchiveUrl = "https://web.archive.org";
69 export const elementUrl = "https://element.io";
71 export const postRefetchSeconds: number = 60 * 1000;
72 export const fetchLimit = 40;
73 export const trendingFetchLimit = 6;
74 export const mentionDropdownFetchLimit = 10;
75 export const commentTreeMaxDepth = 8;
76 export const markdownFieldCharacterLimit = 50000;
77 export const maxUploadImages = 20;
78 export const concurrentImageUpload = 4;
79 export const updateUnreadCountsInterval = 30000;
81 export const relTags = "noopener nofollow";
83 export const emDash = "\u2014";
85 export type ThemeColor =
108 export interface ErrorPageData {
110 adminMatrixIds?: string[];
113 const customEmojis: EmojiMartCategory[] = [];
114 export let customEmojisLookup: Map<string, CustomEmojiView> = new Map<
119 const DEFAULT_ALPHABET =
120 "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
122 function getRandomCharFromAlphabet(alphabet: string): string {
123 return alphabet.charAt(Math.floor(Math.random() * alphabet.length));
126 export function getIdFromString(id?: string): number | undefined {
127 return id && id !== "0" && !Number.isNaN(Number(id)) ? Number(id) : undefined;
130 export function getPageFromString(page?: string): number {
131 return page && !Number.isNaN(Number(page)) ? Number(page) : 1;
134 export function randomStr(
135 idDesiredLength = 20,
136 alphabet = DEFAULT_ALPHABET
139 * Create n-long array and map it to random chars from given alphabet.
140 * Then join individual chars as string
142 return Array.from({ length: idDesiredLength })
144 return getRandomCharFromAlphabet(alphabet);
149 const html5EmbedConfig = {
151 useImageSyntax: true, // Enables video/audio embed with ![]() syntax (default)
153 audio: 'controls preload="metadata"',
154 video: 'width="100%" max-height="100%" controls loop preload="metadata"',
159 const spoilerConfig = {
160 validate: (params: string) => {
161 return params.trim().match(/^spoiler\s+(.*)$/);
164 render: (tokens: any, idx: any) => {
165 var m = tokens[idx].info.trim().match(/^spoiler\s+(.*)$/);
167 if (tokens[idx].nesting === 1) {
169 return `<details><summary> ${md.utils.escapeHtml(m[1])} </summary>\n`;
172 return "</details>\n";
177 export let md: MarkdownIt = new MarkdownIt();
179 export let mdNoImages: MarkdownIt = new MarkdownIt();
181 export function hotRankComment(comment_view: CommentView): number {
182 return hotRank(comment_view.counts.score, comment_view.comment.published);
185 export function hotRankActivePost(post_view: PostView): number {
186 return hotRank(post_view.counts.score, post_view.counts.newest_comment_time);
189 export function hotRankPost(post_view: PostView): number {
190 return hotRank(post_view.counts.score, post_view.post.published);
193 export function hotRank(score: number, timeStr: string): number {
194 // Rank = ScaleFactor * sign(Score) * log(1 + abs(Score)) / (Time + 2)^Gravity
195 const date: Date = new Date(timeStr + "Z"); // Add Z to convert from UTC date
196 const now: Date = new Date();
197 const hoursElapsed: number = (now.getTime() - date.getTime()) / 36e5;
200 (10000 * Math.log10(Math.max(1, 3 + Number(score)))) /
201 Math.pow(hoursElapsed + 2, 1.8);
203 // console.log(`Comment: ${comment.content}\nRank: ${rank}\nScore: ${comment.score}\nHours: ${hoursElapsed}`);
208 export function mdToHtml(text: string) {
209 return { __html: md.render(text) };
212 export function mdToHtmlNoImages(text: string) {
213 return { __html: mdNoImages.render(text) };
216 export function mdToHtmlInline(text: string) {
217 return { __html: md.renderInline(text) };
220 export function getUnixTime(text?: string): number | undefined {
221 return text ? new Date(text).getTime() / 1000 : undefined;
224 export function futureDaysToUnixTime(days?: number): number | undefined {
227 new Date(Date.now() + 1000 * 60 * 60 * 24 * days).getTime() / 1000
232 const imageRegex = /(http)?s?:?(\/\/[^"']*\.(?:jpg|jpeg|gif|png|svg|webp))/;
233 const videoRegex = /(http)?s?:?(\/\/[^"']*\.(?:mp4|webm))/;
234 const tldRegex = /([a-z0-9]+\.)*[a-z0-9]+\.[a-z]+/;
236 export function isImage(url: string) {
237 return imageRegex.test(url);
240 export function isVideo(url: string) {
241 return videoRegex.test(url);
244 export function validURL(str: string) {
245 return !!new URL(str);
248 export function validInstanceTLD(str: string) {
249 return tldRegex.test(str);
252 export function communityRSSUrl(actorId: string, sort: string): string {
253 const url = new URL(actorId);
254 return `${url.origin}/feeds${url.pathname}.xml?sort=${sort}`;
257 export function validEmail(email: string) {
259 /^(([^\s"(),.:;<>@[\\\]]+(\.[^\s"(),.:;<>@[\\\]]+)*)|(".+"))@((\[(?:\d{1,3}\.){3}\d{1,3}])|(([\dA-Za-z\-]+\.)+[A-Za-z]{2,}))$/;
260 return re.test(String(email).toLowerCase());
263 export function capitalizeFirstLetter(str: string): string {
264 return str.charAt(0).toUpperCase() + str.slice(1);
267 export async function getSiteMetadata(url: string) {
268 const form: GetSiteMetadata = { url };
269 const client = new LemmyHttp(getHttpBase());
270 return client.getSiteMetadata(form);
273 export function getDataTypeString(dt: DataType) {
274 return dt === DataType.Post ? "Post" : "Comment";
277 export async function fetchThemeList(): Promise<string[]> {
278 return fetch("/css/themelist").then(res => res.json());
281 export async function setTheme(theme: string, forceReload = false) {
285 if (theme === "browser" && !forceReload) {
288 // This is only run on a force reload
289 if (theme == "browser") {
293 const themeList = await fetchThemeList();
295 // Unload all the other themes
296 for (var i = 0; i < themeList.length; i++) {
297 const styleSheet = document.getElementById(themeList[i]);
299 styleSheet.setAttribute("disabled", "disabled");
304 .getElementById("default-light")
305 ?.setAttribute("disabled", "disabled");
306 document.getElementById("default-dark")?.setAttribute("disabled", "disabled");
308 // Load the theme dynamically
309 const cssLoc = `/css/themes/${theme}.css`;
311 loadCss(theme, cssLoc);
312 document.getElementById(theme)?.removeAttribute("disabled");
315 export function loadCss(id: string, loc: string) {
316 if (!document.getElementById(id)) {
317 var head = document.getElementsByTagName("head")[0];
318 var link = document.createElement("link");
320 link.rel = "stylesheet";
321 link.type = "text/css";
324 head.appendChild(link);
328 export function objectFlip(obj: any) {
330 Object.keys(obj).forEach(key => {
336 export function showAvatars(
337 myUserInfo = UserService.Instance.myUserInfo
339 return myUserInfo?.local_user_view.local_user.show_avatars ?? true;
342 export function showScores(
343 myUserInfo = UserService.Instance.myUserInfo
345 return myUserInfo?.local_user_view.local_user.show_scores ?? true;
348 export function isCakeDay(published: string): boolean {
349 // moment(undefined) or moment.utc(undefined) returns the current date/time
350 // moment(null) or moment.utc(null) returns null
351 const createDate = moment.utc(published).local();
352 const currentDate = moment(new Date());
355 createDate.date() === currentDate.date() &&
356 createDate.month() === currentDate.month() &&
357 createDate.year() !== currentDate.year()
361 export function toast(text: string, background: ThemeColor = "success") {
363 const backgroundColor = `var(--${background})`;
366 backgroundColor: backgroundColor,
374 export function pictrsDeleteToast(filename: string, deleteUrl: string) {
376 const clickToDeleteText = i18n.t("click_to_delete_picture", { filename });
377 const deletePictureText = i18n.t("picture_deleted", {
380 const failedDeletePictureText = i18n.t("failed_to_delete_picture", {
384 const backgroundColor = `var(--light)`;
386 const toast = Toastify({
387 text: clickToDeleteText,
388 backgroundColor: backgroundColor,
394 fetch(deleteUrl).then(res => {
396 if (res.ok === true) {
397 alert(deletePictureText);
399 alert(failedDeletePictureText);
411 export function setupTribute() {
413 noMatchTemplate: function () {
420 menuItemTemplate: (item: any) => {
421 const shortName = `:${item.original.key}:`;
422 return `${item.original.val} ${shortName}`;
424 selectTemplate: (item: any) => {
425 const customEmoji = customEmojisLookup.get(
428 if (customEmoji == undefined) return `${item.original.val}`;
430 return `![${customEmoji.alt_text}](${customEmoji.image_url} "${customEmoji.shortcode}")`;
432 values: Object.entries(emojiShortName)
434 return { key: e[1], val: e[0] };
437 Array.from(customEmojisLookup.entries()).map(k => ({
439 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}" />`,
443 autocompleteMode: true,
445 // menuItemLimit: mentionDropdownFetchLimit,
446 menuShowMinLength: 2,
451 selectTemplate: (item: any) => {
452 const it: PersonTribute = item.original;
453 return `[${it.key}](${it.view.person.actor_id})`;
455 values: debounce(async (text: string, cb: any) => {
456 cb(await personSearch(text));
459 autocompleteMode: true,
461 // menuItemLimit: mentionDropdownFetchLimit,
462 menuShowMinLength: 2,
468 selectTemplate: (item: any) => {
469 const it: CommunityTribute = item.original;
470 return `[${it.key}](${it.view.community.actor_id})`;
472 values: debounce(async (text: string, cb: any) => {
473 cb(await communitySearch(text));
476 autocompleteMode: true,
478 // menuItemLimit: mentionDropdownFetchLimit,
479 menuShowMinLength: 2,
485 function setupEmojiDataModel(custom_emoji_views: CustomEmojiView[]) {
486 const groupedEmojis = groupBy(
488 x => x.custom_emoji.category
490 for (const [category, emojis] of Object.entries(groupedEmojis)) {
494 emojis: emojis.map(emoji => ({
495 id: emoji.custom_emoji.shortcode,
496 name: emoji.custom_emoji.shortcode,
497 keywords: emoji.keywords.map(x => x.keyword),
498 skins: [{ src: emoji.custom_emoji.image_url }],
502 customEmojisLookup = new Map(
503 custom_emoji_views.map(view => [view.custom_emoji.shortcode, view])
507 export function updateEmojiDataModel(custom_emoji_view: CustomEmojiView) {
508 const emoji: EmojiMartCustomEmoji = {
509 id: custom_emoji_view.custom_emoji.shortcode,
510 name: custom_emoji_view.custom_emoji.shortcode,
511 keywords: custom_emoji_view.keywords.map(x => x.keyword),
512 skins: [{ src: custom_emoji_view.custom_emoji.image_url }],
514 const categoryIndex = customEmojis.findIndex(
515 x => x.id == custom_emoji_view.custom_emoji.category
517 if (categoryIndex == -1) {
519 id: custom_emoji_view.custom_emoji.category,
520 name: custom_emoji_view.custom_emoji.category,
524 const emojiIndex = customEmojis[categoryIndex].emojis.findIndex(
525 x => x.id == custom_emoji_view.custom_emoji.shortcode
527 if (emojiIndex == -1) {
528 customEmojis[categoryIndex].emojis.push(emoji);
530 customEmojis[categoryIndex].emojis[emojiIndex] = emoji;
533 customEmojisLookup.set(
534 custom_emoji_view.custom_emoji.shortcode,
539 export function removeFromEmojiDataModel(id: number) {
540 let view: CustomEmojiView | undefined;
541 for (const item of customEmojisLookup.values()) {
542 if (item.custom_emoji.id === id) {
548 const categoryIndex = customEmojis.findIndex(
549 x => x.id == view?.custom_emoji.category
551 const emojiIndex = customEmojis[categoryIndex].emojis.findIndex(
552 x => x.id == view?.custom_emoji.shortcode
554 customEmojis[categoryIndex].emojis = customEmojis[
556 ].emojis.splice(emojiIndex, 1);
558 customEmojisLookup.delete(view?.custom_emoji.shortcode);
561 function setupMarkdown() {
562 const markdownItConfig: MarkdownIt.Options = {
568 const emojiDefs = Array.from(customEmojisLookup.entries()).reduce(
569 (main, [key, value]) => ({ ...main, [key]: value }),
572 md = new MarkdownIt(markdownItConfig)
573 .use(markdown_it_sub)
574 .use(markdown_it_sup)
575 .use(markdown_it_footnote)
576 .use(markdown_it_html5_embed, html5EmbedConfig)
577 .use(markdown_it_container, "spoiler", spoilerConfig)
578 .use(markdown_it_emoji, {
582 mdNoImages = new MarkdownIt(markdownItConfig)
583 .use(markdown_it_sub)
584 .use(markdown_it_sup)
585 .use(markdown_it_footnote)
586 .use(markdown_it_html5_embed, html5EmbedConfig)
587 .use(markdown_it_container, "spoiler", spoilerConfig)
588 .use(markdown_it_emoji, {
592 var defaultRenderer = md.renderer.rules.image;
593 md.renderer.rules.image = function (
596 options: MarkdownIt.Options,
600 //Provide custom renderer for our emojis to allow us to add a css class and force size dimensions on them.
601 const item = tokens[idx] as any;
602 const title = item.attrs.length >= 3 ? item.attrs[2][1] : "";
603 const src: string = item.attrs[0][1];
604 const isCustomEmoji = customEmojisLookup.get(title) != undefined;
605 if (!isCustomEmoji) {
606 return defaultRenderer?.(tokens, idx, options, env, self) ?? "";
608 const alt_text = item.content;
609 return `<img class="icon icon-emoji" src="${src}" title="${title}" alt="${alt_text}"/>`;
613 export function getEmojiMart(
614 onEmojiSelect: (e: any) => void,
615 customPickerOptions: any = {}
617 const pickerOptions = {
618 ...customPickerOptions,
619 onEmojiSelect: onEmojiSelect,
620 custom: customEmojis,
622 return new Picker(pickerOptions);
625 var tippyInstance: any;
627 tippyInstance = tippy("[data-tippy-content]");
630 export function setupTippy() {
632 tippyInstance.forEach((e: any) => e.destroy());
633 tippyInstance = tippy("[data-tippy-content]", {
635 // Display on "long press"
636 touch: ["hold", 500],
641 interface PersonTribute {
646 async function personSearch(text: string): Promise<PersonTribute[]> {
647 const usersResponse = await fetchUsers(text);
649 return usersResponse.map(pv => ({
650 key: `@${pv.person.name}@${hostname(pv.person.actor_id)}`,
655 interface CommunityTribute {
660 async function communitySearch(text: string): Promise<CommunityTribute[]> {
661 const communitiesResponse = await fetchCommunities(text);
663 return communitiesResponse.map(cv => ({
664 key: `!${cv.community.name}@${hostname(cv.community.actor_id)}`,
669 export function getRecipientIdFromProps(props: any): number {
670 return props.match.params.recipient_id
671 ? Number(props.match.params.recipient_id)
675 export function getIdFromProps(props: any): number | undefined {
676 const id = props.match.params.post_id;
677 return id ? Number(id) : undefined;
680 export function getCommentIdFromProps(props: any): number | undefined {
681 const id = props.match.params.comment_id;
682 return id ? Number(id) : undefined;
685 type ImmutableListKey =
694 | "private_message_report"
695 | "registration_application";
697 function editListImmutable<
698 T extends { [key in F]: { id: number } },
699 F extends ImmutableListKey
700 >(fieldName: F, data: T, list: T[]): T[] {
702 ...list.map(c => (c[fieldName].id === data[fieldName].id ? data : c)),
706 export function editComment(
708 comments: CommentView[]
710 return editListImmutable("comment", data, comments);
713 export function editCommentReply(
714 data: CommentReplyView,
715 replies: CommentReplyView[]
716 ): CommentReplyView[] {
717 return editListImmutable("comment_reply", data, replies);
720 interface WithComment {
722 counts: CommentAggregates;
727 export function editMention(
728 data: PersonMentionView,
729 comments: PersonMentionView[]
730 ): PersonMentionView[] {
731 return editListImmutable("person_mention", data, comments);
734 export function editCommunity(
736 communities: CommunityView[]
738 return editListImmutable("community", data, communities);
741 export function editPrivateMessage(
742 data: PrivateMessageView,
743 messages: PrivateMessageView[]
744 ): PrivateMessageView[] {
745 return editListImmutable("private_message", data, messages);
748 export function editPost(data: PostView, posts: PostView[]): PostView[] {
749 return editListImmutable("post", data, posts);
752 export function editPostReport(
753 data: PostReportView,
754 reports: PostReportView[]
756 return editListImmutable("post_report", data, reports);
759 export function editCommentReport(
760 data: CommentReportView,
761 reports: CommentReportView[]
762 ): CommentReportView[] {
763 return editListImmutable("comment_report", data, reports);
766 export function editPrivateMessageReport(
767 data: PrivateMessageReportView,
768 reports: PrivateMessageReportView[]
769 ): PrivateMessageReportView[] {
770 return editListImmutable("private_message_report", data, reports);
773 export function editRegistrationApplication(
774 data: RegistrationApplicationView,
775 apps: RegistrationApplicationView[]
776 ): RegistrationApplicationView[] {
777 return editListImmutable("registration_application", data, apps);
780 export function editWith<D extends WithComment, L extends WithComment>(
781 { comment, counts, saved, my_vote }: D,
786 c.comment.id === comment.id
787 ? { ...c, comment, counts, saved, my_vote }
793 export function updatePersonBlock(
794 data: BlockPersonResponse,
795 myUserInfo: MyUserInfo | undefined = UserService.Instance.myUserInfo
799 myUserInfo.person_blocks.push({
800 person: myUserInfo.local_user_view.person,
801 target: data.person_view.person,
803 toast(`${i18n.t("blocked")} ${data.person_view.person.name}`);
805 myUserInfo.person_blocks = myUserInfo.person_blocks.filter(
806 i => i.target.id !== data.person_view.person.id
808 toast(`${i18n.t("unblocked")} ${data.person_view.person.name}`);
813 export function updateCommunityBlock(
814 data: BlockCommunityResponse,
815 myUserInfo: MyUserInfo | undefined = UserService.Instance.myUserInfo
819 myUserInfo.community_blocks.push({
820 person: myUserInfo.local_user_view.person,
821 community: data.community_view.community,
823 toast(`${i18n.t("blocked")} ${data.community_view.community.name}`);
825 myUserInfo.community_blocks = myUserInfo.community_blocks.filter(
826 i => i.community.id !== data.community_view.community.id
828 toast(`${i18n.t("unblocked")} ${data.community_view.community.name}`);
833 export function commentsToFlatNodes(comments: CommentView[]): CommentNodeI[] {
834 const nodes: CommentNodeI[] = [];
835 for (const comment of comments) {
836 nodes.push({ comment_view: comment, children: [], depth: 0 });
841 export function convertCommentSortType(sort: SortType): CommentSortType {
846 sort == "TopMonth" ||
850 } else if (sort == "New") {
852 } else if (sort == "Hot" || sort == "Active") {
859 export function buildCommentsTree(
860 comments: CommentView[],
861 parentComment: boolean
863 const map = new Map<number, CommentNodeI>();
864 const depthOffset = !parentComment
866 : getDepthFromComment(comments[0].comment) ?? 0;
868 for (const comment_view of comments) {
869 const depthI = getDepthFromComment(comment_view.comment) ?? 0;
870 const depth = depthI ? depthI - depthOffset : 0;
871 const node: CommentNodeI = {
876 map.set(comment_view.comment.id, { ...node });
879 const tree: CommentNodeI[] = [];
881 // if its a parent comment fetch, then push the first comment to the top node.
883 const cNode = map.get(comments[0].comment.id);
889 for (const comment_view of comments) {
890 const child = map.get(comment_view.comment.id);
892 const parent_id = getCommentParentId(comment_view.comment);
894 const parent = map.get(parent_id);
895 // Necessary because blocked comment might not exist
897 parent.children.push(child);
900 if (!parentComment) {
910 export function getCommentParentId(comment?: CommentI): number | undefined {
911 const split = comment?.path.split(".");
915 return split && split.length > 1
916 ? Number(split.at(split.length - 2))
920 export function getDepthFromComment(comment?: CommentI): number | undefined {
921 const len = comment?.path.split(".").length;
922 return len ? len - 2 : undefined;
925 // TODO make immutable
926 export function insertCommentIntoTree(
927 tree: CommentNodeI[],
929 parentComment: boolean
931 // Building a fake node to be used for later
932 const node: CommentNodeI = {
938 const parentId = getCommentParentId(cv.comment);
940 const parent_comment = searchCommentTree(tree, parentId);
941 if (parent_comment) {
942 node.depth = parent_comment.depth + 1;
943 parent_comment.children.unshift(node);
945 } else if (!parentComment) {
950 export function searchCommentTree(
951 tree: CommentNodeI[],
953 ): CommentNodeI | undefined {
954 for (const node of tree) {
955 if (node.comment_view.comment.id === id) {
959 for (const child of node.children) {
960 const res = searchCommentTree([child], id);
970 export const colorList: string[] = [
980 function hsl(num: number) {
981 return `hsla(${num}, 35%, 50%, 0.5)`;
984 export function hostname(url: string): string {
985 const cUrl = new URL(url);
986 return cUrl.port ? `${cUrl.hostname}:${cUrl.port}` : `${cUrl.hostname}`;
989 export function validTitle(title?: string): boolean {
990 // Initial title is null, minimum length is taken care of by textarea's minLength={3}
991 if (!title || title.length < 3) return true;
993 const regex = new RegExp(/.*\S.*/, "g");
995 return regex.test(title);
998 export function siteBannerCss(banner: string): string {
1000 background-image: linear-gradient( rgba(0, 0, 0, 0.8), rgba(0, 0, 0, 0.8) ) ,url("${banner}"); \
1001 background-attachment: fixed; \
1002 background-position: top; \
1003 background-repeat: no-repeat; \
1004 background-size: 100% cover; \
1007 max-height: 100vh; \
1011 export function setIsoData(context: any): IsoData {
1012 // If its the browser, you need to deserialize the data from the window
1014 return window.isoData;
1015 } else return context.router.staticContext;
1018 moment.updateLocale("en", {
1039 export function saveScrollPosition(context: any) {
1040 const path: string = context.router.route.location.pathname;
1041 const y = window.scrollY;
1042 sessionStorage.setItem(`scrollPosition_${path}`, y.toString());
1045 export function restoreScrollPosition(context: any) {
1046 const path: string = context.router.route.location.pathname;
1047 const y = Number(sessionStorage.getItem(`scrollPosition_${path}`));
1048 window.scrollTo(0, y);
1051 export function showLocal(isoData: IsoData): boolean {
1052 return isoData.site_res.site_view.local_site.federation_enabled;
1055 export interface Choice {
1061 export function getUpdatedSearchId(id?: number | null, urlId?: number | null) {
1064 : ((id ?? urlId) === 0 ? undefined : id ?? urlId)?.toString();
1067 export function communityToChoice(cv: CommunityView): Choice {
1069 value: cv.community.id.toString(),
1070 label: communitySelectName(cv),
1074 export function personToChoice(pvs: PersonView): Choice {
1076 value: pvs.person.id.toString(),
1077 label: personSelectName(pvs),
1081 function fetchSearchResults(q: string, type_: SearchType) {
1082 const form: Search = {
1086 listing_type: "All",
1092 return HttpService.client.search(form);
1095 export async function fetchCommunities(q: string) {
1096 const res = await fetchSearchResults(q, "Communities");
1098 return res.state === "success" ? res.data.communities : [];
1101 export async function fetchUsers(q: string) {
1102 const res = await fetchSearchResults(q, "Users");
1104 return res.state === "success" ? res.data.users : [];
1107 export function communitySelectName(cv: CommunityView): string {
1108 return cv.community.local
1109 ? cv.community.title
1110 : `${hostname(cv.community.actor_id)}/${cv.community.title}`;
1113 export function personSelectName({
1114 person: { display_name, name, local, actor_id },
1115 }: PersonView): string {
1116 const pName = display_name ?? name;
1117 return local ? pName : `${hostname(actor_id)}/${pName}`;
1120 export function initializeSite(site?: GetSiteResponse) {
1121 UserService.Instance.myUserInfo = site?.my_user;
1122 i18n.changeLanguage(getLanguages()[0]);
1124 setupEmojiDataModel(site.custom_emojis ?? []);
1129 const SHORTNUM_SI_FORMAT = new Intl.NumberFormat("en-US", {
1130 maximumSignificantDigits: 3,
1132 notation: "compact",
1133 compactDisplay: "short",
1136 export function numToSI(value: number): string {
1137 return SHORTNUM_SI_FORMAT.format(value);
1140 export function myAuth(): string | undefined {
1141 return UserService.Instance.auth();
1144 export function myAuthRequired(): string {
1145 return UserService.Instance.auth(true) ?? "";
1148 export function enableDownvotes(siteRes: GetSiteResponse): boolean {
1149 return siteRes.site_view.local_site.enable_downvotes;
1152 export function enableNsfw(siteRes: GetSiteResponse): boolean {
1153 return siteRes.site_view.local_site.enable_nsfw;
1156 export function postToCommentSortType(sort: SortType): CommentSortType {
1171 export function isPostBlocked(
1173 myUserInfo: MyUserInfo | undefined = UserService.Instance.myUserInfo
1176 (myUserInfo?.community_blocks
1177 .map(c => c.community.id)
1178 .includes(pv.community.id) ||
1179 myUserInfo?.person_blocks
1180 .map(p => p.target.id)
1181 .includes(pv.creator.id)) ??
1186 /// Checks to make sure you can view NSFW posts. Returns true if you can.
1187 export function nsfwCheck(
1189 myUserInfo = UserService.Instance.myUserInfo
1191 const nsfw = pv.post.nsfw || pv.community.nsfw;
1192 const myShowNsfw = myUserInfo?.local_user_view.local_user.show_nsfw ?? false;
1193 return !nsfw || (nsfw && myShowNsfw);
1196 export function getRandomFromList<T>(list: T[]): T | undefined {
1197 return list.length == 0
1199 : list.at(Math.floor(Math.random() * list.length));
1203 * This shows what language you can select
1205 * Use showAll for the site form
1206 * Use showSite for the profile and community forms
1207 * Use false for both those to filter on your profile and site ones
1209 export function selectableLanguages(
1210 allLanguages: Language[],
1211 siteLanguages: number[],
1214 myUserInfo = UserService.Instance.myUserInfo
1216 const allLangIds = allLanguages.map(l => l.id);
1217 let myLangs = myUserInfo?.discussion_languages ?? allLangIds;
1218 myLangs = myLangs.length == 0 ? allLangIds : myLangs;
1219 const siteLangs = siteLanguages.length == 0 ? allLangIds : siteLanguages;
1222 return allLanguages;
1225 return allLanguages.filter(x => siteLangs.includes(x.id));
1228 .filter(x => siteLangs.includes(x.id))
1229 .filter(x => myLangs.includes(x.id));
1234 interface EmojiMartCategory {
1237 emojis: EmojiMartCustomEmoji[];
1240 interface EmojiMartCustomEmoji {
1244 skins: EmojiMartSkin[];
1247 interface EmojiMartSkin {
1251 export function isAuthPath(pathname: string) {
1252 return /create_.*|inbox|settings|admin|reports|registration_applications/g.test(
1257 export function newVote(voteType: VoteType, myVote?: number): number {
1258 if (voteType == VoteType.Upvote) {
1259 return myVote == 1 ? 0 : 1;
1261 return myVote == -1 ? 0 : -1;