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 const 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}"/>`;
611 md.renderer.rules.table_open = function () {
612 return '<table class="table">';
616 export function getEmojiMart(
617 onEmojiSelect: (e: any) => void,
618 customPickerOptions: any = {}
620 const pickerOptions = {
621 ...customPickerOptions,
622 onEmojiSelect: onEmojiSelect,
623 custom: customEmojis,
625 return new Picker(pickerOptions);
628 var tippyInstance: any;
630 tippyInstance = tippy("[data-tippy-content]");
633 export function setupTippy() {
635 tippyInstance.forEach((e: any) => e.destroy());
636 tippyInstance = tippy("[data-tippy-content]", {
638 // Display on "long press"
639 touch: ["hold", 500],
644 interface PersonTribute {
649 async function personSearch(text: string): Promise<PersonTribute[]> {
650 const usersResponse = await fetchUsers(text);
652 return usersResponse.map(pv => ({
653 key: `@${pv.person.name}@${hostname(pv.person.actor_id)}`,
658 interface CommunityTribute {
663 async function communitySearch(text: string): Promise<CommunityTribute[]> {
664 const communitiesResponse = await fetchCommunities(text);
666 return communitiesResponse.map(cv => ({
667 key: `!${cv.community.name}@${hostname(cv.community.actor_id)}`,
672 export function getRecipientIdFromProps(props: any): number {
673 return props.match.params.recipient_id
674 ? Number(props.match.params.recipient_id)
678 export function getIdFromProps(props: any): number | undefined {
679 const id = props.match.params.post_id;
680 return id ? Number(id) : undefined;
683 export function getCommentIdFromProps(props: any): number | undefined {
684 const id = props.match.params.comment_id;
685 return id ? Number(id) : undefined;
688 type ImmutableListKey =
697 | "private_message_report"
698 | "registration_application";
700 function editListImmutable<
701 T extends { [key in F]: { id: number } },
702 F extends ImmutableListKey
703 >(fieldName: F, data: T, list: T[]): T[] {
705 ...list.map(c => (c[fieldName].id === data[fieldName].id ? data : c)),
709 export function editComment(
711 comments: CommentView[]
713 return editListImmutable("comment", data, comments);
716 export function editCommentReply(
717 data: CommentReplyView,
718 replies: CommentReplyView[]
719 ): CommentReplyView[] {
720 return editListImmutable("comment_reply", data, replies);
723 interface WithComment {
725 counts: CommentAggregates;
730 export function editMention(
731 data: PersonMentionView,
732 comments: PersonMentionView[]
733 ): PersonMentionView[] {
734 return editListImmutable("person_mention", data, comments);
737 export function editCommunity(
739 communities: CommunityView[]
741 return editListImmutable("community", data, communities);
744 export function editPrivateMessage(
745 data: PrivateMessageView,
746 messages: PrivateMessageView[]
747 ): PrivateMessageView[] {
748 return editListImmutable("private_message", data, messages);
751 export function editPost(data: PostView, posts: PostView[]): PostView[] {
752 return editListImmutable("post", data, posts);
755 export function editPostReport(
756 data: PostReportView,
757 reports: PostReportView[]
759 return editListImmutable("post_report", data, reports);
762 export function editCommentReport(
763 data: CommentReportView,
764 reports: CommentReportView[]
765 ): CommentReportView[] {
766 return editListImmutable("comment_report", data, reports);
769 export function editPrivateMessageReport(
770 data: PrivateMessageReportView,
771 reports: PrivateMessageReportView[]
772 ): PrivateMessageReportView[] {
773 return editListImmutable("private_message_report", data, reports);
776 export function editRegistrationApplication(
777 data: RegistrationApplicationView,
778 apps: RegistrationApplicationView[]
779 ): RegistrationApplicationView[] {
780 return editListImmutable("registration_application", data, apps);
783 export function editWith<D extends WithComment, L extends WithComment>(
784 { comment, counts, saved, my_vote }: D,
789 c.comment.id === comment.id
790 ? { ...c, comment, counts, saved, my_vote }
796 export function updatePersonBlock(
797 data: BlockPersonResponse,
798 myUserInfo: MyUserInfo | undefined = UserService.Instance.myUserInfo
802 myUserInfo.person_blocks.push({
803 person: myUserInfo.local_user_view.person,
804 target: data.person_view.person,
806 toast(`${i18n.t("blocked")} ${data.person_view.person.name}`);
808 myUserInfo.person_blocks = myUserInfo.person_blocks.filter(
809 i => i.target.id !== data.person_view.person.id
811 toast(`${i18n.t("unblocked")} ${data.person_view.person.name}`);
816 export function updateCommunityBlock(
817 data: BlockCommunityResponse,
818 myUserInfo: MyUserInfo | undefined = UserService.Instance.myUserInfo
822 myUserInfo.community_blocks.push({
823 person: myUserInfo.local_user_view.person,
824 community: data.community_view.community,
826 toast(`${i18n.t("blocked")} ${data.community_view.community.name}`);
828 myUserInfo.community_blocks = myUserInfo.community_blocks.filter(
829 i => i.community.id !== data.community_view.community.id
831 toast(`${i18n.t("unblocked")} ${data.community_view.community.name}`);
836 export function commentsToFlatNodes(comments: CommentView[]): CommentNodeI[] {
837 const nodes: CommentNodeI[] = [];
838 for (const comment of comments) {
839 nodes.push({ comment_view: comment, children: [], depth: 0 });
844 export function convertCommentSortType(sort: SortType): CommentSortType {
849 sort == "TopMonth" ||
853 } else if (sort == "New") {
855 } else if (sort == "Hot" || sort == "Active") {
862 export function buildCommentsTree(
863 comments: CommentView[],
864 parentComment: boolean
866 const map = new Map<number, CommentNodeI>();
867 const depthOffset = !parentComment
869 : getDepthFromComment(comments[0].comment) ?? 0;
871 for (const comment_view of comments) {
872 const depthI = getDepthFromComment(comment_view.comment) ?? 0;
873 const depth = depthI ? depthI - depthOffset : 0;
874 const node: CommentNodeI = {
879 map.set(comment_view.comment.id, { ...node });
882 const tree: CommentNodeI[] = [];
884 // if its a parent comment fetch, then push the first comment to the top node.
886 const cNode = map.get(comments[0].comment.id);
892 for (const comment_view of comments) {
893 const child = map.get(comment_view.comment.id);
895 const parent_id = getCommentParentId(comment_view.comment);
897 const parent = map.get(parent_id);
898 // Necessary because blocked comment might not exist
900 parent.children.push(child);
903 if (!parentComment) {
913 export function getCommentParentId(comment?: CommentI): number | undefined {
914 const split = comment?.path.split(".");
918 return split && split.length > 1
919 ? Number(split.at(split.length - 2))
923 export function getDepthFromComment(comment?: CommentI): number | undefined {
924 const len = comment?.path.split(".").length;
925 return len ? len - 2 : undefined;
928 // TODO make immutable
929 export function insertCommentIntoTree(
930 tree: CommentNodeI[],
932 parentComment: boolean
934 // Building a fake node to be used for later
935 const node: CommentNodeI = {
941 const parentId = getCommentParentId(cv.comment);
943 const parent_comment = searchCommentTree(tree, parentId);
944 if (parent_comment) {
945 node.depth = parent_comment.depth + 1;
946 parent_comment.children.unshift(node);
948 } else if (!parentComment) {
953 export function searchCommentTree(
954 tree: CommentNodeI[],
956 ): CommentNodeI | undefined {
957 for (const node of tree) {
958 if (node.comment_view.comment.id === id) {
962 for (const child of node.children) {
963 const res = searchCommentTree([child], id);
973 export const colorList: string[] = [
983 function hsl(num: number) {
984 return `hsla(${num}, 35%, 50%, 0.5)`;
987 export function hostname(url: string): string {
988 const cUrl = new URL(url);
989 return cUrl.port ? `${cUrl.hostname}:${cUrl.port}` : `${cUrl.hostname}`;
992 export function validTitle(title?: string): boolean {
993 // Initial title is null, minimum length is taken care of by textarea's minLength={3}
994 if (!title || title.length < 3) return true;
996 const regex = new RegExp(/.*\S.*/, "g");
998 return regex.test(title);
1001 export function siteBannerCss(banner: string): string {
1003 background-image: linear-gradient( rgba(0, 0, 0, 0.8), rgba(0, 0, 0, 0.8) ) ,url("${banner}"); \
1004 background-attachment: fixed; \
1005 background-position: top; \
1006 background-repeat: no-repeat; \
1007 background-size: 100% cover; \
1010 max-height: 100vh; \
1014 export function setIsoData(context: any): IsoData {
1015 // If its the browser, you need to deserialize the data from the window
1017 return window.isoData;
1018 } else return context.router.staticContext;
1021 moment.updateLocale("en", {
1042 export function saveScrollPosition(context: any) {
1043 const path: string = context.router.route.location.pathname;
1044 const y = window.scrollY;
1045 sessionStorage.setItem(`scrollPosition_${path}`, y.toString());
1048 export function restoreScrollPosition(context: any) {
1049 const path: string = context.router.route.location.pathname;
1050 const y = Number(sessionStorage.getItem(`scrollPosition_${path}`));
1051 window.scrollTo(0, y);
1054 export function showLocal(isoData: IsoData): boolean {
1055 return isoData.site_res.site_view.local_site.federation_enabled;
1058 export interface Choice {
1064 export function getUpdatedSearchId(id?: number | null, urlId?: number | null) {
1067 : ((id ?? urlId) === 0 ? undefined : id ?? urlId)?.toString();
1070 export function communityToChoice(cv: CommunityView): Choice {
1072 value: cv.community.id.toString(),
1073 label: communitySelectName(cv),
1077 export function personToChoice(pvs: PersonView): Choice {
1079 value: pvs.person.id.toString(),
1080 label: personSelectName(pvs),
1084 function fetchSearchResults(q: string, type_: SearchType) {
1085 const form: Search = {
1089 listing_type: "All",
1095 return HttpService.client.search(form);
1098 export async function fetchCommunities(q: string) {
1099 const res = await fetchSearchResults(q, "Communities");
1101 return res.state === "success" ? res.data.communities : [];
1104 export async function fetchUsers(q: string) {
1105 const res = await fetchSearchResults(q, "Users");
1107 return res.state === "success" ? res.data.users : [];
1110 export function communitySelectName(cv: CommunityView): string {
1111 return cv.community.local
1112 ? cv.community.title
1113 : `${hostname(cv.community.actor_id)}/${cv.community.title}`;
1116 export function personSelectName({
1117 person: { display_name, name, local, actor_id },
1118 }: PersonView): string {
1119 const pName = display_name ?? name;
1120 return local ? pName : `${hostname(actor_id)}/${pName}`;
1123 export function initializeSite(site?: GetSiteResponse) {
1124 UserService.Instance.myUserInfo = site?.my_user;
1125 i18n.changeLanguage();
1127 setupEmojiDataModel(site.custom_emojis ?? []);
1132 const SHORTNUM_SI_FORMAT = new Intl.NumberFormat("en-US", {
1133 maximumSignificantDigits: 3,
1135 notation: "compact",
1136 compactDisplay: "short",
1139 export function numToSI(value: number): string {
1140 return SHORTNUM_SI_FORMAT.format(value);
1143 export function myAuth(): string | undefined {
1144 return UserService.Instance.auth();
1147 export function myAuthRequired(): string {
1148 return UserService.Instance.auth(true) ?? "";
1151 export function enableDownvotes(siteRes: GetSiteResponse): boolean {
1152 return siteRes.site_view.local_site.enable_downvotes;
1155 export function enableNsfw(siteRes: GetSiteResponse): boolean {
1156 return siteRes.site_view.local_site.enable_nsfw;
1159 export function postToCommentSortType(sort: SortType): CommentSortType {
1174 export function isPostBlocked(
1176 myUserInfo: MyUserInfo | undefined = UserService.Instance.myUserInfo
1179 (myUserInfo?.community_blocks
1180 .map(c => c.community.id)
1181 .includes(pv.community.id) ||
1182 myUserInfo?.person_blocks
1183 .map(p => p.target.id)
1184 .includes(pv.creator.id)) ??
1189 /// Checks to make sure you can view NSFW posts. Returns true if you can.
1190 export function nsfwCheck(
1192 myUserInfo = UserService.Instance.myUserInfo
1194 const nsfw = pv.post.nsfw || pv.community.nsfw;
1195 const myShowNsfw = myUserInfo?.local_user_view.local_user.show_nsfw ?? false;
1196 return !nsfw || (nsfw && myShowNsfw);
1199 export function getRandomFromList<T>(list: T[]): T | undefined {
1200 return list.length == 0
1202 : list.at(Math.floor(Math.random() * list.length));
1206 * This shows what language you can select
1208 * Use showAll for the site form
1209 * Use showSite for the profile and community forms
1210 * Use false for both those to filter on your profile and site ones
1212 export function selectableLanguages(
1213 allLanguages: Language[],
1214 siteLanguages: number[],
1217 myUserInfo = UserService.Instance.myUserInfo
1219 const allLangIds = allLanguages.map(l => l.id);
1220 let myLangs = myUserInfo?.discussion_languages ?? allLangIds;
1221 myLangs = myLangs.length == 0 ? allLangIds : myLangs;
1222 const siteLangs = siteLanguages.length == 0 ? allLangIds : siteLanguages;
1225 return allLanguages;
1228 return allLanguages.filter(x => siteLangs.includes(x.id));
1231 .filter(x => siteLangs.includes(x.id))
1232 .filter(x => myLangs.includes(x.id));
1237 interface EmojiMartCategory {
1240 emojis: EmojiMartCustomEmoji[];
1243 interface EmojiMartCustomEmoji {
1247 skins: EmojiMartSkin[];
1250 interface EmojiMartSkin {
1254 export function isAuthPath(pathname: string) {
1255 return /create_.*|inbox|settings|admin|reports|registration_applications/g.test(
1260 export function newVote(voteType: VoteType, myVote?: number): number {
1261 if (voteType == VoteType.Upvote) {
1262 return myVote == 1 ? 0 : 1;
1264 return myVote == -1 ? 0 : -1;