1 import { isBrowser } from "@utils/browser";
2 import { debounce, groupBy } from "@utils/helpers";
3 import { Picker } from "emoji-mart";
4 import emojiShortName from "emoji-short-name";
6 BlockCommunityResponse,
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 } from "./i18next";
52 } from "./interfaces";
53 import { HttpService, UserService } from "./services";
54 import { RequestState } from "./services/HttpService";
58 Tribute = require("tributejs");
61 export const favIconUrl = "/static/assets/icons/favicon.svg";
62 export const favIconPngUrl = "/static/assets/icons/apple-touch-icon.png";
64 // export const defaultFavIcon = `${window.location.protocol}//${window.location.host}${favIconPngUrl}`;
65 export const repoUrl = "https://github.com/LemmyNet";
66 export const joinLemmyUrl = "https://join-lemmy.org";
67 export const donateLemmyUrl = `${joinLemmyUrl}/donate`;
68 export const docsUrl = `${joinLemmyUrl}/docs/en/index.html`;
69 export const helpGuideUrl = `${joinLemmyUrl}/docs/en/users/01-getting-started.html`; // TODO find a way to redirect to the non-en folder
70 export const markdownHelpUrl = `${joinLemmyUrl}/docs/en/users/02-media.html`;
71 export const sortingHelpUrl = `${joinLemmyUrl}/docs/en/users/03-votes-and-ranking.html`;
72 export const archiveTodayUrl = "https://archive.today";
73 export const ghostArchiveUrl = "https://ghostarchive.org";
74 export const webArchiveUrl = "https://web.archive.org";
75 export const elementUrl = "https://element.io";
77 export const postRefetchSeconds: number = 60 * 1000;
78 export const fetchLimit = 40;
79 export const trendingFetchLimit = 6;
80 export const mentionDropdownFetchLimit = 10;
81 export const commentTreeMaxDepth = 8;
82 export const markdownFieldCharacterLimit = 50000;
83 export const maxUploadImages = 20;
84 export const concurrentImageUpload = 4;
85 export const updateUnreadCountsInterval = 30000;
87 export const relTags = "noopener nofollow";
89 export const emDash = "\u2014";
91 export type ThemeColor =
114 export interface ErrorPageData {
116 adminMatrixIds?: string[];
119 const customEmojis: EmojiMartCategory[] = [];
120 export let customEmojisLookup: Map<string, CustomEmojiView> = new Map<
125 const DEFAULT_ALPHABET =
126 "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
128 function getRandomCharFromAlphabet(alphabet: string): string {
129 return alphabet.charAt(Math.floor(Math.random() * alphabet.length));
132 export function getIdFromString(id?: string): number | undefined {
133 return id && id !== "0" && !Number.isNaN(Number(id)) ? Number(id) : undefined;
136 export function getPageFromString(page?: string): number {
137 return page && !Number.isNaN(Number(page)) ? Number(page) : 1;
140 export function randomStr(
141 idDesiredLength = 20,
142 alphabet = DEFAULT_ALPHABET
145 * Create n-long array and map it to random chars from given alphabet.
146 * Then join individual chars as string
148 return Array.from({ length: idDesiredLength })
150 return getRandomCharFromAlphabet(alphabet);
155 const html5EmbedConfig = {
157 useImageSyntax: true, // Enables video/audio embed with ![]() syntax (default)
159 audio: 'controls preload="metadata"',
160 video: 'width="100%" max-height="100%" controls loop preload="metadata"',
165 const spoilerConfig = {
166 validate: (params: string) => {
167 return params.trim().match(/^spoiler\s+(.*)$/);
170 render: (tokens: any, idx: any) => {
171 var m = tokens[idx].info.trim().match(/^spoiler\s+(.*)$/);
173 if (tokens[idx].nesting === 1) {
175 return `<details><summary> ${md.utils.escapeHtml(m[1])} </summary>\n`;
178 return "</details>\n";
183 export let md: MarkdownIt = new MarkdownIt();
185 export let mdNoImages: MarkdownIt = new MarkdownIt();
187 export function hotRankComment(comment_view: CommentView): number {
188 return hotRank(comment_view.counts.score, comment_view.comment.published);
191 export function hotRankActivePost(post_view: PostView): number {
192 return hotRank(post_view.counts.score, post_view.counts.newest_comment_time);
195 export function hotRankPost(post_view: PostView): number {
196 return hotRank(post_view.counts.score, post_view.post.published);
199 export function hotRank(score: number, timeStr: string): number {
200 // Rank = ScaleFactor * sign(Score) * log(1 + abs(Score)) / (Time + 2)^Gravity
201 const date: Date = new Date(timeStr + "Z"); // Add Z to convert from UTC date
202 const now: Date = new Date();
203 const hoursElapsed: number = (now.getTime() - date.getTime()) / 36e5;
206 (10000 * Math.log10(Math.max(1, 3 + Number(score)))) /
207 Math.pow(hoursElapsed + 2, 1.8);
209 // console.log(`Comment: ${comment.content}\nRank: ${rank}\nScore: ${comment.score}\nHours: ${hoursElapsed}`);
214 export function mdToHtml(text: string) {
215 return { __html: md.render(text) };
218 export function mdToHtmlNoImages(text: string) {
219 return { __html: mdNoImages.render(text) };
222 export function mdToHtmlInline(text: string) {
223 return { __html: md.renderInline(text) };
226 export function getUnixTime(text?: string): number | undefined {
227 return text ? new Date(text).getTime() / 1000 : undefined;
230 export function futureDaysToUnixTime(days?: number): number | undefined {
233 new Date(Date.now() + 1000 * 60 * 60 * 24 * days).getTime() / 1000
238 const imageRegex = /(http)?s?:?(\/\/[^"']*\.(?:jpg|jpeg|gif|png|svg|webp))/;
239 const videoRegex = /(http)?s?:?(\/\/[^"']*\.(?:mp4|webm))/;
240 const tldRegex = /([a-z0-9]+\.)*[a-z0-9]+\.[a-z]+/;
242 export function isImage(url: string) {
243 return imageRegex.test(url);
246 export function isVideo(url: string) {
247 return videoRegex.test(url);
250 export function validURL(str: string) {
259 export function validInstanceTLD(str: string) {
260 return tldRegex.test(str);
263 export function communityRSSUrl(actorId: string, sort: string): string {
264 const url = new URL(actorId);
265 return `${url.origin}/feeds${url.pathname}.xml?sort=${sort}`;
268 export function validEmail(email: string) {
270 /^(([^\s"(),.:;<>@[\\\]]+(\.[^\s"(),.:;<>@[\\\]]+)*)|(".+"))@((\[(?:\d{1,3}\.){3}\d{1,3}])|(([\dA-Za-z\-]+\.)+[A-Za-z]{2,}))$/;
271 return re.test(String(email).toLowerCase());
274 export function capitalizeFirstLetter(str: string): string {
275 return str.charAt(0).toUpperCase() + str.slice(1);
278 export async function getSiteMetadata(url: string) {
279 const form: GetSiteMetadata = { url };
280 const client = new LemmyHttp(getHttpBase());
281 return client.getSiteMetadata(form);
284 export function getDataTypeString(dt: DataType) {
285 return dt === DataType.Post ? "Post" : "Comment";
288 export async function fetchThemeList(): Promise<string[]> {
289 return fetch("/css/themelist").then(res => res.json());
292 export async function setTheme(theme: string, forceReload = false) {
296 if (theme === "browser" && !forceReload) {
299 // This is only run on a force reload
300 if (theme == "browser") {
304 const themeList = await fetchThemeList();
306 // Unload all the other themes
307 for (var i = 0; i < themeList.length; i++) {
308 const styleSheet = document.getElementById(themeList[i]);
310 styleSheet.setAttribute("disabled", "disabled");
315 .getElementById("default-light")
316 ?.setAttribute("disabled", "disabled");
317 document.getElementById("default-dark")?.setAttribute("disabled", "disabled");
319 // Load the theme dynamically
320 const cssLoc = `/css/themes/${theme}.css`;
322 loadCss(theme, cssLoc);
323 document.getElementById(theme)?.removeAttribute("disabled");
326 export function loadCss(id: string, loc: string) {
327 if (!document.getElementById(id)) {
328 var head = document.getElementsByTagName("head")[0];
329 var link = document.createElement("link");
331 link.rel = "stylesheet";
332 link.type = "text/css";
335 head.appendChild(link);
339 export function objectFlip(obj: any) {
341 Object.keys(obj).forEach(key => {
347 export function showAvatars(
348 myUserInfo = UserService.Instance.myUserInfo
350 return myUserInfo?.local_user_view.local_user.show_avatars ?? true;
353 export function showScores(
354 myUserInfo = UserService.Instance.myUserInfo
356 return myUserInfo?.local_user_view.local_user.show_scores ?? true;
359 export function isCakeDay(published: string): boolean {
360 // moment(undefined) or moment.utc(undefined) returns the current date/time
361 // moment(null) or moment.utc(null) returns null
362 const createDate = moment.utc(published).local();
363 const currentDate = moment(new Date());
366 createDate.date() === currentDate.date() &&
367 createDate.month() === currentDate.month() &&
368 createDate.year() !== currentDate.year()
372 export function toast(text: string, background: ThemeColor = "success") {
374 const backgroundColor = `var(--bs-${background})`;
377 backgroundColor: backgroundColor,
385 export function pictrsDeleteToast(filename: string, deleteUrl: string) {
387 const clickToDeleteText = i18n.t("click_to_delete_picture", { filename });
388 const deletePictureText = i18n.t("picture_deleted", {
391 const failedDeletePictureText = i18n.t("failed_to_delete_picture", {
395 const backgroundColor = `var(--bs-light)`;
397 const toast = Toastify({
398 text: clickToDeleteText,
399 backgroundColor: backgroundColor,
405 fetch(deleteUrl).then(res => {
407 if (res.ok === true) {
408 alert(deletePictureText);
410 alert(failedDeletePictureText);
422 export function setupTribute() {
424 noMatchTemplate: function () {
431 menuItemTemplate: (item: any) => {
432 const shortName = `:${item.original.key}:`;
433 return `${item.original.val} ${shortName}`;
435 selectTemplate: (item: any) => {
436 const customEmoji = customEmojisLookup.get(
439 if (customEmoji == undefined) return `${item.original.val}`;
441 return `![${customEmoji.alt_text}](${customEmoji.image_url} "${customEmoji.shortcode}")`;
443 values: Object.entries(emojiShortName)
445 return { key: e[1], val: e[0] };
448 Array.from(customEmojisLookup.entries()).map(k => ({
450 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}" />`,
454 autocompleteMode: true,
456 // menuItemLimit: mentionDropdownFetchLimit,
457 menuShowMinLength: 2,
462 selectTemplate: (item: any) => {
463 const it: PersonTribute = item.original;
464 return `[${it.key}](${it.view.person.actor_id})`;
466 values: debounce(async (text: string, cb: any) => {
467 cb(await personSearch(text));
470 autocompleteMode: true,
472 // menuItemLimit: mentionDropdownFetchLimit,
473 menuShowMinLength: 2,
479 selectTemplate: (item: any) => {
480 const it: CommunityTribute = item.original;
481 return `[${it.key}](${it.view.community.actor_id})`;
483 values: debounce(async (text: string, cb: any) => {
484 cb(await communitySearch(text));
487 autocompleteMode: true,
489 // menuItemLimit: mentionDropdownFetchLimit,
490 menuShowMinLength: 2,
496 function setupEmojiDataModel(custom_emoji_views: CustomEmojiView[]) {
497 const groupedEmojis = groupBy(
499 x => x.custom_emoji.category
501 for (const [category, emojis] of Object.entries(groupedEmojis)) {
505 emojis: emojis.map(emoji => ({
506 id: emoji.custom_emoji.shortcode,
507 name: emoji.custom_emoji.shortcode,
508 keywords: emoji.keywords.map(x => x.keyword),
509 skins: [{ src: emoji.custom_emoji.image_url }],
513 customEmojisLookup = new Map(
514 custom_emoji_views.map(view => [view.custom_emoji.shortcode, view])
518 export function updateEmojiDataModel(custom_emoji_view: CustomEmojiView) {
519 const emoji: EmojiMartCustomEmoji = {
520 id: custom_emoji_view.custom_emoji.shortcode,
521 name: custom_emoji_view.custom_emoji.shortcode,
522 keywords: custom_emoji_view.keywords.map(x => x.keyword),
523 skins: [{ src: custom_emoji_view.custom_emoji.image_url }],
525 const categoryIndex = customEmojis.findIndex(
526 x => x.id == custom_emoji_view.custom_emoji.category
528 if (categoryIndex == -1) {
530 id: custom_emoji_view.custom_emoji.category,
531 name: custom_emoji_view.custom_emoji.category,
535 const emojiIndex = customEmojis[categoryIndex].emojis.findIndex(
536 x => x.id == custom_emoji_view.custom_emoji.shortcode
538 if (emojiIndex == -1) {
539 customEmojis[categoryIndex].emojis.push(emoji);
541 customEmojis[categoryIndex].emojis[emojiIndex] = emoji;
544 customEmojisLookup.set(
545 custom_emoji_view.custom_emoji.shortcode,
550 export function removeFromEmojiDataModel(id: number) {
551 let view: CustomEmojiView | undefined;
552 for (const item of customEmojisLookup.values()) {
553 if (item.custom_emoji.id === id) {
559 const categoryIndex = customEmojis.findIndex(
560 x => x.id == view?.custom_emoji.category
562 const emojiIndex = customEmojis[categoryIndex].emojis.findIndex(
563 x => x.id == view?.custom_emoji.shortcode
565 customEmojis[categoryIndex].emojis = customEmojis[
567 ].emojis.splice(emojiIndex, 1);
569 customEmojisLookup.delete(view?.custom_emoji.shortcode);
572 function setupMarkdown() {
573 const markdownItConfig: MarkdownIt.Options = {
579 const emojiDefs = Array.from(customEmojisLookup.entries()).reduce(
580 (main, [key, value]) => ({ ...main, [key]: value }),
583 md = new MarkdownIt(markdownItConfig)
584 .use(markdown_it_sub)
585 .use(markdown_it_sup)
586 .use(markdown_it_footnote)
587 .use(markdown_it_html5_embed, html5EmbedConfig)
588 .use(markdown_it_container, "spoiler", spoilerConfig)
589 .use(markdown_it_emoji, {
593 mdNoImages = new MarkdownIt(markdownItConfig)
594 .use(markdown_it_sub)
595 .use(markdown_it_sup)
596 .use(markdown_it_footnote)
597 .use(markdown_it_html5_embed, html5EmbedConfig)
598 .use(markdown_it_container, "spoiler", spoilerConfig)
599 .use(markdown_it_emoji, {
603 const defaultRenderer = md.renderer.rules.image;
604 md.renderer.rules.image = function (
607 options: MarkdownIt.Options,
611 //Provide custom renderer for our emojis to allow us to add a css class and force size dimensions on them.
612 const item = tokens[idx] as any;
613 const title = item.attrs.length >= 3 ? item.attrs[2][1] : "";
614 const src: string = item.attrs[0][1];
615 const isCustomEmoji = customEmojisLookup.get(title) != undefined;
616 if (!isCustomEmoji) {
617 return defaultRenderer?.(tokens, idx, options, env, self) ?? "";
619 const alt_text = item.content;
620 return `<img class="icon icon-emoji" src="${src}" title="${title}" alt="${alt_text}"/>`;
622 md.renderer.rules.table_open = function () {
623 return '<table class="table">';
627 export function getEmojiMart(
628 onEmojiSelect: (e: any) => void,
629 customPickerOptions: any = {}
631 const pickerOptions = {
632 ...customPickerOptions,
633 onEmojiSelect: onEmojiSelect,
634 custom: customEmojis,
636 return new Picker(pickerOptions);
639 var tippyInstance: any;
641 tippyInstance = tippy("[data-tippy-content]");
644 export function setupTippy() {
646 tippyInstance.forEach((e: any) => e.destroy());
647 tippyInstance = tippy("[data-tippy-content]", {
649 // Display on "long press"
650 touch: ["hold", 500],
655 interface PersonTribute {
660 async function personSearch(text: string): Promise<PersonTribute[]> {
661 const usersResponse = await fetchUsers(text);
663 return usersResponse.map(pv => ({
664 key: `@${pv.person.name}@${hostname(pv.person.actor_id)}`,
669 interface CommunityTribute {
674 async function communitySearch(text: string): Promise<CommunityTribute[]> {
675 const communitiesResponse = await fetchCommunities(text);
677 return communitiesResponse.map(cv => ({
678 key: `!${cv.community.name}@${hostname(cv.community.actor_id)}`,
683 export function getRecipientIdFromProps(props: any): number {
684 return props.match.params.recipient_id
685 ? Number(props.match.params.recipient_id)
689 export function getIdFromProps(props: any): number | undefined {
690 const id = props.match.params.post_id;
691 return id ? Number(id) : undefined;
694 export function getCommentIdFromProps(props: any): number | undefined {
695 const id = props.match.params.comment_id;
696 return id ? Number(id) : undefined;
699 type ImmutableListKey =
708 | "private_message_report"
709 | "registration_application";
711 function editListImmutable<
712 T extends { [key in F]: { id: number } },
713 F extends ImmutableListKey
714 >(fieldName: F, data: T, list: T[]): T[] {
716 ...list.map(c => (c[fieldName].id === data[fieldName].id ? data : c)),
720 export function editComment(
722 comments: CommentView[]
724 return editListImmutable("comment", data, comments);
727 export function editCommentReply(
728 data: CommentReplyView,
729 replies: CommentReplyView[]
730 ): CommentReplyView[] {
731 return editListImmutable("comment_reply", data, replies);
734 interface WithComment {
736 counts: CommentAggregates;
741 export function editMention(
742 data: PersonMentionView,
743 comments: PersonMentionView[]
744 ): PersonMentionView[] {
745 return editListImmutable("person_mention", data, comments);
748 export function editCommunity(
750 communities: CommunityView[]
752 return editListImmutable("community", data, communities);
755 export function editPrivateMessage(
756 data: PrivateMessageView,
757 messages: PrivateMessageView[]
758 ): PrivateMessageView[] {
759 return editListImmutable("private_message", data, messages);
762 export function editPost(data: PostView, posts: PostView[]): PostView[] {
763 return editListImmutable("post", data, posts);
766 export function editPostReport(
767 data: PostReportView,
768 reports: PostReportView[]
770 return editListImmutable("post_report", data, reports);
773 export function editCommentReport(
774 data: CommentReportView,
775 reports: CommentReportView[]
776 ): CommentReportView[] {
777 return editListImmutable("comment_report", data, reports);
780 export function editPrivateMessageReport(
781 data: PrivateMessageReportView,
782 reports: PrivateMessageReportView[]
783 ): PrivateMessageReportView[] {
784 return editListImmutable("private_message_report", data, reports);
787 export function editRegistrationApplication(
788 data: RegistrationApplicationView,
789 apps: RegistrationApplicationView[]
790 ): RegistrationApplicationView[] {
791 return editListImmutable("registration_application", data, apps);
794 export function editWith<D extends WithComment, L extends WithComment>(
795 { comment, counts, saved, my_vote }: D,
800 c.comment.id === comment.id
801 ? { ...c, comment, counts, saved, my_vote }
807 export function updatePersonBlock(
808 data: BlockPersonResponse,
809 myUserInfo: MyUserInfo | undefined = UserService.Instance.myUserInfo
813 myUserInfo.person_blocks.push({
814 person: myUserInfo.local_user_view.person,
815 target: data.person_view.person,
817 toast(`${i18n.t("blocked")} ${data.person_view.person.name}`);
819 myUserInfo.person_blocks = myUserInfo.person_blocks.filter(
820 i => i.target.id !== data.person_view.person.id
822 toast(`${i18n.t("unblocked")} ${data.person_view.person.name}`);
827 export function updateCommunityBlock(
828 data: BlockCommunityResponse,
829 myUserInfo: MyUserInfo | undefined = UserService.Instance.myUserInfo
833 myUserInfo.community_blocks.push({
834 person: myUserInfo.local_user_view.person,
835 community: data.community_view.community,
837 toast(`${i18n.t("blocked")} ${data.community_view.community.name}`);
839 myUserInfo.community_blocks = myUserInfo.community_blocks.filter(
840 i => i.community.id !== data.community_view.community.id
842 toast(`${i18n.t("unblocked")} ${data.community_view.community.name}`);
847 export function commentsToFlatNodes(comments: CommentView[]): CommentNodeI[] {
848 const nodes: CommentNodeI[] = [];
849 for (const comment of comments) {
850 nodes.push({ comment_view: comment, children: [], depth: 0 });
855 export function convertCommentSortType(sort: SortType): CommentSortType {
859 sort == "TopSixHour" ||
860 sort == "TopTwelveHour" ||
863 sort == "TopMonth" ||
867 } else if (sort == "New") {
869 } else if (sort == "Hot" || sort == "Active") {
876 export function buildCommentsTree(
877 comments: CommentView[],
878 parentComment: boolean
880 const map = new Map<number, CommentNodeI>();
881 const depthOffset = !parentComment
883 : getDepthFromComment(comments[0].comment) ?? 0;
885 for (const comment_view of comments) {
886 const depthI = getDepthFromComment(comment_view.comment) ?? 0;
887 const depth = depthI ? depthI - depthOffset : 0;
888 const node: CommentNodeI = {
893 map.set(comment_view.comment.id, { ...node });
896 const tree: CommentNodeI[] = [];
898 // if its a parent comment fetch, then push the first comment to the top node.
900 const cNode = map.get(comments[0].comment.id);
906 for (const comment_view of comments) {
907 const child = map.get(comment_view.comment.id);
909 const parent_id = getCommentParentId(comment_view.comment);
911 const parent = map.get(parent_id);
912 // Necessary because blocked comment might not exist
914 parent.children.push(child);
917 if (!parentComment) {
927 export function getCommentParentId(comment?: CommentI): number | undefined {
928 const split = comment?.path.split(".");
932 return split && split.length > 1
933 ? Number(split.at(split.length - 2))
937 export function getDepthFromComment(comment?: CommentI): number | undefined {
938 const len = comment?.path.split(".").length;
939 return len ? len - 2 : undefined;
942 // TODO make immutable
943 export function insertCommentIntoTree(
944 tree: CommentNodeI[],
946 parentComment: boolean
948 // Building a fake node to be used for later
949 const node: CommentNodeI = {
955 const parentId = getCommentParentId(cv.comment);
957 const parent_comment = searchCommentTree(tree, parentId);
958 if (parent_comment) {
959 node.depth = parent_comment.depth + 1;
960 parent_comment.children.unshift(node);
962 } else if (!parentComment) {
967 export function searchCommentTree(
968 tree: CommentNodeI[],
970 ): CommentNodeI | undefined {
971 for (const node of tree) {
972 if (node.comment_view.comment.id === id) {
976 for (const child of node.children) {
977 const res = searchCommentTree([child], id);
987 export const colorList: string[] = [
997 function hsl(num: number) {
998 return `hsla(${num}, 35%, 50%, 0.5)`;
1001 export function hostname(url: string): string {
1002 const cUrl = new URL(url);
1003 return cUrl.port ? `${cUrl.hostname}:${cUrl.port}` : `${cUrl.hostname}`;
1006 export function validTitle(title?: string): boolean {
1007 // Initial title is null, minimum length is taken care of by textarea's minLength={3}
1008 if (!title || title.length < 3) return true;
1010 const regex = new RegExp(/.*\S.*/, "g");
1012 return regex.test(title);
1015 export function siteBannerCss(banner: string): string {
1017 background-image: linear-gradient( rgba(0, 0, 0, 0.8), rgba(0, 0, 0, 0.8) ) ,url("${banner}"); \
1018 background-attachment: fixed; \
1019 background-position: top; \
1020 background-repeat: no-repeat; \
1021 background-size: 100% cover; \
1024 max-height: 100vh; \
1028 export function setIsoData<T extends RouteData>(context: any): IsoData<T> {
1029 // If its the browser, you need to deserialize the data from the window
1031 return window.isoData;
1032 } else return context.router.staticContext;
1035 moment.updateLocale("en", {
1056 export function saveScrollPosition(context: any) {
1057 const path: string = context.router.route.location.pathname;
1058 const y = window.scrollY;
1059 sessionStorage.setItem(`scrollPosition_${path}`, y.toString());
1062 export function restoreScrollPosition(context: any) {
1063 const path: string = context.router.route.location.pathname;
1064 const y = Number(sessionStorage.getItem(`scrollPosition_${path}`));
1065 window.scrollTo(0, y);
1068 export function showLocal(isoData: IsoData): boolean {
1069 return isoData.site_res.site_view.local_site.federation_enabled;
1072 export interface Choice {
1078 export function getUpdatedSearchId(id?: number | null, urlId?: number | null) {
1081 : ((id ?? urlId) === 0 ? undefined : id ?? urlId)?.toString();
1084 export function communityToChoice(cv: CommunityView): Choice {
1086 value: cv.community.id.toString(),
1087 label: communitySelectName(cv),
1091 export function personToChoice(pvs: PersonView): Choice {
1093 value: pvs.person.id.toString(),
1094 label: personSelectName(pvs),
1098 function fetchSearchResults(q: string, type_: SearchType) {
1099 const form: Search = {
1103 listing_type: "All",
1109 return HttpService.client.search(form);
1112 export async function fetchCommunities(q: string) {
1113 const res = await fetchSearchResults(q, "Communities");
1115 return res.state === "success" ? res.data.communities : [];
1118 export async function fetchUsers(q: string) {
1119 const res = await fetchSearchResults(q, "Users");
1121 return res.state === "success" ? res.data.users : [];
1124 export function communitySelectName(cv: CommunityView): string {
1125 return cv.community.local
1126 ? cv.community.title
1127 : `${hostname(cv.community.actor_id)}/${cv.community.title}`;
1130 export function personSelectName({
1131 person: { display_name, name, local, actor_id },
1132 }: PersonView): string {
1133 const pName = display_name ?? name;
1134 return local ? pName : `${hostname(actor_id)}/${pName}`;
1137 export function initializeSite(site?: GetSiteResponse) {
1138 UserService.Instance.myUserInfo = site?.my_user;
1139 i18n.changeLanguage();
1141 setupEmojiDataModel(site.custom_emojis ?? []);
1146 const SHORTNUM_SI_FORMAT = new Intl.NumberFormat("en-US", {
1147 maximumSignificantDigits: 3,
1149 notation: "compact",
1150 compactDisplay: "short",
1153 export function numToSI(value: number): string {
1154 return SHORTNUM_SI_FORMAT.format(value);
1157 export function myAuth(): string | undefined {
1158 return UserService.Instance.auth();
1161 export function myAuthRequired(): string {
1162 return UserService.Instance.auth(true) ?? "";
1165 export function enableDownvotes(siteRes: GetSiteResponse): boolean {
1166 return siteRes.site_view.local_site.enable_downvotes;
1169 export function enableNsfw(siteRes: GetSiteResponse): boolean {
1170 return siteRes.site_view.local_site.enable_nsfw;
1173 export function postToCommentSortType(sort: SortType): CommentSortType {
1188 export function isPostBlocked(
1190 myUserInfo: MyUserInfo | undefined = UserService.Instance.myUserInfo
1193 (myUserInfo?.community_blocks
1194 .map(c => c.community.id)
1195 .includes(pv.community.id) ||
1196 myUserInfo?.person_blocks
1197 .map(p => p.target.id)
1198 .includes(pv.creator.id)) ??
1203 /// Checks to make sure you can view NSFW posts. Returns true if you can.
1204 export function nsfwCheck(
1206 myUserInfo = UserService.Instance.myUserInfo
1208 const nsfw = pv.post.nsfw || pv.community.nsfw;
1209 const myShowNsfw = myUserInfo?.local_user_view.local_user.show_nsfw ?? false;
1210 return !nsfw || (nsfw && myShowNsfw);
1213 export function getRandomFromList<T>(list: T[]): T | undefined {
1214 return list.length == 0
1216 : list.at(Math.floor(Math.random() * list.length));
1220 * This shows what language you can select
1222 * Use showAll for the site form
1223 * Use showSite for the profile and community forms
1224 * Use false for both those to filter on your profile and site ones
1226 export function selectableLanguages(
1227 allLanguages: Language[],
1228 siteLanguages: number[],
1231 myUserInfo = UserService.Instance.myUserInfo
1233 const allLangIds = allLanguages.map(l => l.id);
1234 let myLangs = myUserInfo?.discussion_languages ?? allLangIds;
1235 myLangs = myLangs.length == 0 ? allLangIds : myLangs;
1236 const siteLangs = siteLanguages.length == 0 ? allLangIds : siteLanguages;
1239 return allLanguages;
1242 return allLanguages.filter(x => siteLangs.includes(x.id));
1245 .filter(x => siteLangs.includes(x.id))
1246 .filter(x => myLangs.includes(x.id));
1251 interface EmojiMartCategory {
1254 emojis: EmojiMartCustomEmoji[];
1257 interface EmojiMartCustomEmoji {
1261 skins: EmojiMartSkin[];
1264 interface EmojiMartSkin {
1268 export function isAuthPath(pathname: string) {
1269 return /create_.*|inbox|settings|admin|reports|registration_applications/g.test(
1274 export function newVote(voteType: VoteType, myVote?: number): number {
1275 if (voteType == VoteType.Upvote) {
1276 return myVote == 1 ? 0 : 1;
1278 return myVote == -1 ? 0 : -1;
1282 export type RouteDataResponse<T extends Record<string, any>> = {
1283 [K in keyof T]: RequestState<T[K]>;