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";
50 } from "./interfaces";
51 import { HttpService, UserService } from "./services";
52 import { RequestState } from "./services/HttpService";
53 import isBrowser from "./utils/browser/is-browser";
54 import debounce from "./utils/helpers/debounce";
55 import { groupBy } from "./utils/helpers/group-by";
59 Tribute = require("tributejs");
62 export const favIconUrl = "/static/assets/icons/favicon.svg";
63 export const favIconPngUrl = "/static/assets/icons/apple-touch-icon.png";
65 // export const defaultFavIcon = `${window.location.protocol}//${window.location.host}${favIconPngUrl}`;
66 export const repoUrl = "https://github.com/LemmyNet";
67 export const joinLemmyUrl = "https://join-lemmy.org";
68 export const donateLemmyUrl = `${joinLemmyUrl}/donate`;
69 export const docsUrl = `${joinLemmyUrl}/docs/en/index.html`;
70 export const helpGuideUrl = `${joinLemmyUrl}/docs/en/users/01-getting-started.html`; // TODO find a way to redirect to the non-en folder
71 export const markdownHelpUrl = `${joinLemmyUrl}/docs/en/users/02-media.html`;
72 export const sortingHelpUrl = `${joinLemmyUrl}/docs/en/users/03-votes-and-ranking.html`;
73 export const archiveTodayUrl = "https://archive.today";
74 export const ghostArchiveUrl = "https://ghostarchive.org";
75 export const webArchiveUrl = "https://web.archive.org";
76 export const elementUrl = "https://element.io";
78 export const postRefetchSeconds: number = 60 * 1000;
79 export const fetchLimit = 40;
80 export const trendingFetchLimit = 6;
81 export const mentionDropdownFetchLimit = 10;
82 export const commentTreeMaxDepth = 8;
83 export const markdownFieldCharacterLimit = 50000;
84 export const maxUploadImages = 20;
85 export const concurrentImageUpload = 4;
86 export const updateUnreadCountsInterval = 30000;
88 export const relTags = "noopener nofollow";
90 export const emDash = "\u2014";
92 export type ThemeColor =
115 export interface ErrorPageData {
117 adminMatrixIds?: string[];
120 const customEmojis: EmojiMartCategory[] = [];
121 export let customEmojisLookup: Map<string, CustomEmojiView> = new Map<
126 const DEFAULT_ALPHABET =
127 "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
129 function getRandomCharFromAlphabet(alphabet: string): string {
130 return alphabet.charAt(Math.floor(Math.random() * alphabet.length));
133 export function getIdFromString(id?: string): number | undefined {
134 return id && id !== "0" && !Number.isNaN(Number(id)) ? Number(id) : undefined;
137 export function getPageFromString(page?: string): number {
138 return page && !Number.isNaN(Number(page)) ? Number(page) : 1;
141 export function randomStr(
142 idDesiredLength = 20,
143 alphabet = DEFAULT_ALPHABET
146 * Create n-long array and map it to random chars from given alphabet.
147 * Then join individual chars as string
149 return Array.from({ length: idDesiredLength })
151 return getRandomCharFromAlphabet(alphabet);
156 const html5EmbedConfig = {
158 useImageSyntax: true, // Enables video/audio embed with ![]() syntax (default)
160 audio: 'controls preload="metadata"',
161 video: 'width="100%" max-height="100%" controls loop preload="metadata"',
166 const spoilerConfig = {
167 validate: (params: string) => {
168 return params.trim().match(/^spoiler\s+(.*)$/);
171 render: (tokens: any, idx: any) => {
172 var m = tokens[idx].info.trim().match(/^spoiler\s+(.*)$/);
174 if (tokens[idx].nesting === 1) {
176 return `<details><summary> ${md.utils.escapeHtml(m[1])} </summary>\n`;
179 return "</details>\n";
184 export let md: MarkdownIt = new MarkdownIt();
186 export let mdNoImages: MarkdownIt = new MarkdownIt();
188 export function hotRankComment(comment_view: CommentView): number {
189 return hotRank(comment_view.counts.score, comment_view.comment.published);
192 export function hotRankActivePost(post_view: PostView): number {
193 return hotRank(post_view.counts.score, post_view.counts.newest_comment_time);
196 export function hotRankPost(post_view: PostView): number {
197 return hotRank(post_view.counts.score, post_view.post.published);
200 export function hotRank(score: number, timeStr: string): number {
201 // Rank = ScaleFactor * sign(Score) * log(1 + abs(Score)) / (Time + 2)^Gravity
202 const date: Date = new Date(timeStr + "Z"); // Add Z to convert from UTC date
203 const now: Date = new Date();
204 const hoursElapsed: number = (now.getTime() - date.getTime()) / 36e5;
207 (10000 * Math.log10(Math.max(1, 3 + Number(score)))) /
208 Math.pow(hoursElapsed + 2, 1.8);
210 // console.log(`Comment: ${comment.content}\nRank: ${rank}\nScore: ${comment.score}\nHours: ${hoursElapsed}`);
215 export function mdToHtml(text: string) {
216 return { __html: md.render(text) };
219 export function mdToHtmlNoImages(text: string) {
220 return { __html: mdNoImages.render(text) };
223 export function mdToHtmlInline(text: string) {
224 return { __html: md.renderInline(text) };
227 export function getUnixTime(text?: string): number | undefined {
228 return text ? new Date(text).getTime() / 1000 : undefined;
231 export function futureDaysToUnixTime(days?: number): number | undefined {
234 new Date(Date.now() + 1000 * 60 * 60 * 24 * days).getTime() / 1000
239 const imageRegex = /(http)?s?:?(\/\/[^"']*\.(?:jpg|jpeg|gif|png|svg|webp))/;
240 const videoRegex = /(http)?s?:?(\/\/[^"']*\.(?:mp4|webm))/;
241 const tldRegex = /([a-z0-9]+\.)*[a-z0-9]+\.[a-z]+/;
243 export function isImage(url: string) {
244 return imageRegex.test(url);
247 export function isVideo(url: string) {
248 return videoRegex.test(url);
251 export function validURL(str: string) {
260 export function validInstanceTLD(str: string) {
261 return tldRegex.test(str);
264 export function communityRSSUrl(actorId: string, sort: string): string {
265 const url = new URL(actorId);
266 return `${url.origin}/feeds${url.pathname}.xml?sort=${sort}`;
269 export function validEmail(email: string) {
271 /^(([^\s"(),.:;<>@[\\\]]+(\.[^\s"(),.:;<>@[\\\]]+)*)|(".+"))@((\[(?:\d{1,3}\.){3}\d{1,3}])|(([\dA-Za-z\-]+\.)+[A-Za-z]{2,}))$/;
272 return re.test(String(email).toLowerCase());
275 export function capitalizeFirstLetter(str: string): string {
276 return str.charAt(0).toUpperCase() + str.slice(1);
279 export async function getSiteMetadata(url: string) {
280 const form: GetSiteMetadata = { url };
281 const client = new LemmyHttp(getHttpBase());
282 return client.getSiteMetadata(form);
285 export function getDataTypeString(dt: DataType) {
286 return dt === DataType.Post ? "Post" : "Comment";
289 export async function fetchThemeList(): Promise<string[]> {
290 return fetch("/css/themelist").then(res => res.json());
293 export async function setTheme(theme: string, forceReload = false) {
297 if (theme === "browser" && !forceReload) {
300 // This is only run on a force reload
301 if (theme == "browser") {
305 const themeList = await fetchThemeList();
307 // Unload all the other themes
308 for (var i = 0; i < themeList.length; i++) {
309 const styleSheet = document.getElementById(themeList[i]);
311 styleSheet.setAttribute("disabled", "disabled");
316 .getElementById("default-light")
317 ?.setAttribute("disabled", "disabled");
318 document.getElementById("default-dark")?.setAttribute("disabled", "disabled");
320 // Load the theme dynamically
321 const cssLoc = `/css/themes/${theme}.css`;
323 loadCss(theme, cssLoc);
324 document.getElementById(theme)?.removeAttribute("disabled");
327 export function loadCss(id: string, loc: string) {
328 if (!document.getElementById(id)) {
329 var head = document.getElementsByTagName("head")[0];
330 var link = document.createElement("link");
332 link.rel = "stylesheet";
333 link.type = "text/css";
336 head.appendChild(link);
340 export function objectFlip(obj: any) {
342 Object.keys(obj).forEach(key => {
348 export function showAvatars(
349 myUserInfo = UserService.Instance.myUserInfo
351 return myUserInfo?.local_user_view.local_user.show_avatars ?? true;
354 export function showScores(
355 myUserInfo = UserService.Instance.myUserInfo
357 return myUserInfo?.local_user_view.local_user.show_scores ?? true;
360 export function isCakeDay(published: string): boolean {
361 // moment(undefined) or moment.utc(undefined) returns the current date/time
362 // moment(null) or moment.utc(null) returns null
363 const createDate = moment.utc(published).local();
364 const currentDate = moment(new Date());
367 createDate.date() === currentDate.date() &&
368 createDate.month() === currentDate.month() &&
369 createDate.year() !== currentDate.year()
373 export function toast(text: string, background: ThemeColor = "success") {
375 const backgroundColor = `var(--${background})`;
378 backgroundColor: backgroundColor,
386 export function pictrsDeleteToast(filename: string, deleteUrl: string) {
388 const clickToDeleteText = i18n.t("click_to_delete_picture", { filename });
389 const deletePictureText = i18n.t("picture_deleted", {
392 const failedDeletePictureText = i18n.t("failed_to_delete_picture", {
396 const backgroundColor = `var(--light)`;
398 const toast = Toastify({
399 text: clickToDeleteText,
400 backgroundColor: backgroundColor,
406 fetch(deleteUrl).then(res => {
408 if (res.ok === true) {
409 alert(deletePictureText);
411 alert(failedDeletePictureText);
423 export function setupTribute() {
425 noMatchTemplate: function () {
432 menuItemTemplate: (item: any) => {
433 const shortName = `:${item.original.key}:`;
434 return `${item.original.val} ${shortName}`;
436 selectTemplate: (item: any) => {
437 const customEmoji = customEmojisLookup.get(
440 if (customEmoji == undefined) return `${item.original.val}`;
442 return `![${customEmoji.alt_text}](${customEmoji.image_url} "${customEmoji.shortcode}")`;
444 values: Object.entries(emojiShortName)
446 return { key: e[1], val: e[0] };
449 Array.from(customEmojisLookup.entries()).map(k => ({
451 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}" />`,
455 autocompleteMode: true,
457 // menuItemLimit: mentionDropdownFetchLimit,
458 menuShowMinLength: 2,
463 selectTemplate: (item: any) => {
464 const it: PersonTribute = item.original;
465 return `[${it.key}](${it.view.person.actor_id})`;
467 values: debounce(async (text: string, cb: any) => {
468 cb(await personSearch(text));
471 autocompleteMode: true,
473 // menuItemLimit: mentionDropdownFetchLimit,
474 menuShowMinLength: 2,
480 selectTemplate: (item: any) => {
481 const it: CommunityTribute = item.original;
482 return `[${it.key}](${it.view.community.actor_id})`;
484 values: debounce(async (text: string, cb: any) => {
485 cb(await communitySearch(text));
488 autocompleteMode: true,
490 // menuItemLimit: mentionDropdownFetchLimit,
491 menuShowMinLength: 2,
497 function setupEmojiDataModel(custom_emoji_views: CustomEmojiView[]) {
498 const groupedEmojis = groupBy(
500 x => x.custom_emoji.category
502 for (const [category, emojis] of Object.entries(groupedEmojis)) {
506 emojis: emojis.map(emoji => ({
507 id: emoji.custom_emoji.shortcode,
508 name: emoji.custom_emoji.shortcode,
509 keywords: emoji.keywords.map(x => x.keyword),
510 skins: [{ src: emoji.custom_emoji.image_url }],
514 customEmojisLookup = new Map(
515 custom_emoji_views.map(view => [view.custom_emoji.shortcode, view])
519 export function updateEmojiDataModel(custom_emoji_view: CustomEmojiView) {
520 const emoji: EmojiMartCustomEmoji = {
521 id: custom_emoji_view.custom_emoji.shortcode,
522 name: custom_emoji_view.custom_emoji.shortcode,
523 keywords: custom_emoji_view.keywords.map(x => x.keyword),
524 skins: [{ src: custom_emoji_view.custom_emoji.image_url }],
526 const categoryIndex = customEmojis.findIndex(
527 x => x.id == custom_emoji_view.custom_emoji.category
529 if (categoryIndex == -1) {
531 id: custom_emoji_view.custom_emoji.category,
532 name: custom_emoji_view.custom_emoji.category,
536 const emojiIndex = customEmojis[categoryIndex].emojis.findIndex(
537 x => x.id == custom_emoji_view.custom_emoji.shortcode
539 if (emojiIndex == -1) {
540 customEmojis[categoryIndex].emojis.push(emoji);
542 customEmojis[categoryIndex].emojis[emojiIndex] = emoji;
545 customEmojisLookup.set(
546 custom_emoji_view.custom_emoji.shortcode,
551 export function removeFromEmojiDataModel(id: number) {
552 let view: CustomEmojiView | undefined;
553 for (const item of customEmojisLookup.values()) {
554 if (item.custom_emoji.id === id) {
560 const categoryIndex = customEmojis.findIndex(
561 x => x.id == view?.custom_emoji.category
563 const emojiIndex = customEmojis[categoryIndex].emojis.findIndex(
564 x => x.id == view?.custom_emoji.shortcode
566 customEmojis[categoryIndex].emojis = customEmojis[
568 ].emojis.splice(emojiIndex, 1);
570 customEmojisLookup.delete(view?.custom_emoji.shortcode);
573 function setupMarkdown() {
574 const markdownItConfig: MarkdownIt.Options = {
580 const emojiDefs = Array.from(customEmojisLookup.entries()).reduce(
581 (main, [key, value]) => ({ ...main, [key]: value }),
584 md = new MarkdownIt(markdownItConfig)
585 .use(markdown_it_sub)
586 .use(markdown_it_sup)
587 .use(markdown_it_footnote)
588 .use(markdown_it_html5_embed, html5EmbedConfig)
589 .use(markdown_it_container, "spoiler", spoilerConfig)
590 .use(markdown_it_emoji, {
594 mdNoImages = new MarkdownIt(markdownItConfig)
595 .use(markdown_it_sub)
596 .use(markdown_it_sup)
597 .use(markdown_it_footnote)
598 .use(markdown_it_html5_embed, html5EmbedConfig)
599 .use(markdown_it_container, "spoiler", spoilerConfig)
600 .use(markdown_it_emoji, {
604 const defaultRenderer = md.renderer.rules.image;
605 md.renderer.rules.image = function (
608 options: MarkdownIt.Options,
612 //Provide custom renderer for our emojis to allow us to add a css class and force size dimensions on them.
613 const item = tokens[idx] as any;
614 const title = item.attrs.length >= 3 ? item.attrs[2][1] : "";
615 const src: string = item.attrs[0][1];
616 const isCustomEmoji = customEmojisLookup.get(title) != undefined;
617 if (!isCustomEmoji) {
618 return defaultRenderer?.(tokens, idx, options, env, self) ?? "";
620 const alt_text = item.content;
621 return `<img class="icon icon-emoji" src="${src}" title="${title}" alt="${alt_text}"/>`;
623 md.renderer.rules.table_open = function () {
624 return '<table class="table">';
628 export function getEmojiMart(
629 onEmojiSelect: (e: any) => void,
630 customPickerOptions: any = {}
632 const pickerOptions = {
633 ...customPickerOptions,
634 onEmojiSelect: onEmojiSelect,
635 custom: customEmojis,
637 return new Picker(pickerOptions);
640 var tippyInstance: any;
642 tippyInstance = tippy("[data-tippy-content]");
645 export function setupTippy() {
647 tippyInstance.forEach((e: any) => e.destroy());
648 tippyInstance = tippy("[data-tippy-content]", {
650 // Display on "long press"
651 touch: ["hold", 500],
656 interface PersonTribute {
661 async function personSearch(text: string): Promise<PersonTribute[]> {
662 const usersResponse = await fetchUsers(text);
664 return usersResponse.map(pv => ({
665 key: `@${pv.person.name}@${hostname(pv.person.actor_id)}`,
670 interface CommunityTribute {
675 async function communitySearch(text: string): Promise<CommunityTribute[]> {
676 const communitiesResponse = await fetchCommunities(text);
678 return communitiesResponse.map(cv => ({
679 key: `!${cv.community.name}@${hostname(cv.community.actor_id)}`,
684 export function getRecipientIdFromProps(props: any): number {
685 return props.match.params.recipient_id
686 ? Number(props.match.params.recipient_id)
690 export function getIdFromProps(props: any): number | undefined {
691 const id = props.match.params.post_id;
692 return id ? Number(id) : undefined;
695 export function getCommentIdFromProps(props: any): number | undefined {
696 const id = props.match.params.comment_id;
697 return id ? Number(id) : undefined;
700 type ImmutableListKey =
709 | "private_message_report"
710 | "registration_application";
712 function editListImmutable<
713 T extends { [key in F]: { id: number } },
714 F extends ImmutableListKey
715 >(fieldName: F, data: T, list: T[]): T[] {
717 ...list.map(c => (c[fieldName].id === data[fieldName].id ? data : c)),
721 export function editComment(
723 comments: CommentView[]
725 return editListImmutable("comment", data, comments);
728 export function editCommentReply(
729 data: CommentReplyView,
730 replies: CommentReplyView[]
731 ): CommentReplyView[] {
732 return editListImmutable("comment_reply", data, replies);
735 interface WithComment {
737 counts: CommentAggregates;
742 export function editMention(
743 data: PersonMentionView,
744 comments: PersonMentionView[]
745 ): PersonMentionView[] {
746 return editListImmutable("person_mention", data, comments);
749 export function editCommunity(
751 communities: CommunityView[]
753 return editListImmutable("community", data, communities);
756 export function editPrivateMessage(
757 data: PrivateMessageView,
758 messages: PrivateMessageView[]
759 ): PrivateMessageView[] {
760 return editListImmutable("private_message", data, messages);
763 export function editPost(data: PostView, posts: PostView[]): PostView[] {
764 return editListImmutable("post", data, posts);
767 export function editPostReport(
768 data: PostReportView,
769 reports: PostReportView[]
771 return editListImmutable("post_report", data, reports);
774 export function editCommentReport(
775 data: CommentReportView,
776 reports: CommentReportView[]
777 ): CommentReportView[] {
778 return editListImmutable("comment_report", data, reports);
781 export function editPrivateMessageReport(
782 data: PrivateMessageReportView,
783 reports: PrivateMessageReportView[]
784 ): PrivateMessageReportView[] {
785 return editListImmutable("private_message_report", data, reports);
788 export function editRegistrationApplication(
789 data: RegistrationApplicationView,
790 apps: RegistrationApplicationView[]
791 ): RegistrationApplicationView[] {
792 return editListImmutable("registration_application", data, apps);
795 export function editWith<D extends WithComment, L extends WithComment>(
796 { comment, counts, saved, my_vote }: D,
801 c.comment.id === comment.id
802 ? { ...c, comment, counts, saved, my_vote }
808 export function updatePersonBlock(
809 data: BlockPersonResponse,
810 myUserInfo: MyUserInfo | undefined = UserService.Instance.myUserInfo
814 myUserInfo.person_blocks.push({
815 person: myUserInfo.local_user_view.person,
816 target: data.person_view.person,
818 toast(`${i18n.t("blocked")} ${data.person_view.person.name}`);
820 myUserInfo.person_blocks = myUserInfo.person_blocks.filter(
821 i => i.target.id !== data.person_view.person.id
823 toast(`${i18n.t("unblocked")} ${data.person_view.person.name}`);
828 export function updateCommunityBlock(
829 data: BlockCommunityResponse,
830 myUserInfo: MyUserInfo | undefined = UserService.Instance.myUserInfo
834 myUserInfo.community_blocks.push({
835 person: myUserInfo.local_user_view.person,
836 community: data.community_view.community,
838 toast(`${i18n.t("blocked")} ${data.community_view.community.name}`);
840 myUserInfo.community_blocks = myUserInfo.community_blocks.filter(
841 i => i.community.id !== data.community_view.community.id
843 toast(`${i18n.t("unblocked")} ${data.community_view.community.name}`);
848 export function commentsToFlatNodes(comments: CommentView[]): CommentNodeI[] {
849 const nodes: CommentNodeI[] = [];
850 for (const comment of comments) {
851 nodes.push({ comment_view: comment, children: [], depth: 0 });
856 export function convertCommentSortType(sort: SortType): CommentSortType {
861 sort == "TopMonth" ||
865 } else if (sort == "New") {
867 } else if (sort == "Hot" || sort == "Active") {
874 export function buildCommentsTree(
875 comments: CommentView[],
876 parentComment: boolean
878 const map = new Map<number, CommentNodeI>();
879 const depthOffset = !parentComment
881 : getDepthFromComment(comments[0].comment) ?? 0;
883 for (const comment_view of comments) {
884 const depthI = getDepthFromComment(comment_view.comment) ?? 0;
885 const depth = depthI ? depthI - depthOffset : 0;
886 const node: CommentNodeI = {
891 map.set(comment_view.comment.id, { ...node });
894 const tree: CommentNodeI[] = [];
896 // if its a parent comment fetch, then push the first comment to the top node.
898 const cNode = map.get(comments[0].comment.id);
904 for (const comment_view of comments) {
905 const child = map.get(comment_view.comment.id);
907 const parent_id = getCommentParentId(comment_view.comment);
909 const parent = map.get(parent_id);
910 // Necessary because blocked comment might not exist
912 parent.children.push(child);
915 if (!parentComment) {
925 export function getCommentParentId(comment?: CommentI): number | undefined {
926 const split = comment?.path.split(".");
930 return split && split.length > 1
931 ? Number(split.at(split.length - 2))
935 export function getDepthFromComment(comment?: CommentI): number | undefined {
936 const len = comment?.path.split(".").length;
937 return len ? len - 2 : undefined;
940 // TODO make immutable
941 export function insertCommentIntoTree(
942 tree: CommentNodeI[],
944 parentComment: boolean
946 // Building a fake node to be used for later
947 const node: CommentNodeI = {
953 const parentId = getCommentParentId(cv.comment);
955 const parent_comment = searchCommentTree(tree, parentId);
956 if (parent_comment) {
957 node.depth = parent_comment.depth + 1;
958 parent_comment.children.unshift(node);
960 } else if (!parentComment) {
965 export function searchCommentTree(
966 tree: CommentNodeI[],
968 ): CommentNodeI | undefined {
969 for (const node of tree) {
970 if (node.comment_view.comment.id === id) {
974 for (const child of node.children) {
975 const res = searchCommentTree([child], id);
985 export const colorList: string[] = [
995 function hsl(num: number) {
996 return `hsla(${num}, 35%, 50%, 0.5)`;
999 export function hostname(url: string): string {
1000 const cUrl = new URL(url);
1001 return cUrl.port ? `${cUrl.hostname}:${cUrl.port}` : `${cUrl.hostname}`;
1004 export function validTitle(title?: string): boolean {
1005 // Initial title is null, minimum length is taken care of by textarea's minLength={3}
1006 if (!title || title.length < 3) return true;
1008 const regex = new RegExp(/.*\S.*/, "g");
1010 return regex.test(title);
1013 export function siteBannerCss(banner: string): string {
1015 background-image: linear-gradient( rgba(0, 0, 0, 0.8), rgba(0, 0, 0, 0.8) ) ,url("${banner}"); \
1016 background-attachment: fixed; \
1017 background-position: top; \
1018 background-repeat: no-repeat; \
1019 background-size: 100% cover; \
1022 max-height: 100vh; \
1026 export function setIsoData<T extends RouteData>(context: any): IsoData<T> {
1027 // If its the browser, you need to deserialize the data from the window
1029 return window.isoData;
1030 } else return context.router.staticContext;
1033 moment.updateLocale("en", {
1054 export function saveScrollPosition(context: any) {
1055 const path: string = context.router.route.location.pathname;
1056 const y = window.scrollY;
1057 sessionStorage.setItem(`scrollPosition_${path}`, y.toString());
1060 export function restoreScrollPosition(context: any) {
1061 const path: string = context.router.route.location.pathname;
1062 const y = Number(sessionStorage.getItem(`scrollPosition_${path}`));
1063 window.scrollTo(0, y);
1066 export function showLocal(isoData: IsoData): boolean {
1067 return isoData.site_res.site_view.local_site.federation_enabled;
1070 export interface Choice {
1076 export function getUpdatedSearchId(id?: number | null, urlId?: number | null) {
1079 : ((id ?? urlId) === 0 ? undefined : id ?? urlId)?.toString();
1082 export function communityToChoice(cv: CommunityView): Choice {
1084 value: cv.community.id.toString(),
1085 label: communitySelectName(cv),
1089 export function personToChoice(pvs: PersonView): Choice {
1091 value: pvs.person.id.toString(),
1092 label: personSelectName(pvs),
1096 function fetchSearchResults(q: string, type_: SearchType) {
1097 const form: Search = {
1101 listing_type: "All",
1107 return HttpService.client.search(form);
1110 export async function fetchCommunities(q: string) {
1111 const res = await fetchSearchResults(q, "Communities");
1113 return res.state === "success" ? res.data.communities : [];
1116 export async function fetchUsers(q: string) {
1117 const res = await fetchSearchResults(q, "Users");
1119 return res.state === "success" ? res.data.users : [];
1122 export function communitySelectName(cv: CommunityView): string {
1123 return cv.community.local
1124 ? cv.community.title
1125 : `${hostname(cv.community.actor_id)}/${cv.community.title}`;
1128 export function personSelectName({
1129 person: { display_name, name, local, actor_id },
1130 }: PersonView): string {
1131 const pName = display_name ?? name;
1132 return local ? pName : `${hostname(actor_id)}/${pName}`;
1135 export function initializeSite(site?: GetSiteResponse) {
1136 UserService.Instance.myUserInfo = site?.my_user;
1137 i18n.changeLanguage();
1139 setupEmojiDataModel(site.custom_emojis ?? []);
1144 const SHORTNUM_SI_FORMAT = new Intl.NumberFormat("en-US", {
1145 maximumSignificantDigits: 3,
1147 notation: "compact",
1148 compactDisplay: "short",
1151 export function numToSI(value: number): string {
1152 return SHORTNUM_SI_FORMAT.format(value);
1155 export function myAuth(): string | undefined {
1156 return UserService.Instance.auth();
1159 export function myAuthRequired(): string {
1160 return UserService.Instance.auth(true) ?? "";
1163 export function enableDownvotes(siteRes: GetSiteResponse): boolean {
1164 return siteRes.site_view.local_site.enable_downvotes;
1167 export function enableNsfw(siteRes: GetSiteResponse): boolean {
1168 return siteRes.site_view.local_site.enable_nsfw;
1171 export function postToCommentSortType(sort: SortType): CommentSortType {
1186 export function isPostBlocked(
1188 myUserInfo: MyUserInfo | undefined = UserService.Instance.myUserInfo
1191 (myUserInfo?.community_blocks
1192 .map(c => c.community.id)
1193 .includes(pv.community.id) ||
1194 myUserInfo?.person_blocks
1195 .map(p => p.target.id)
1196 .includes(pv.creator.id)) ??
1201 /// Checks to make sure you can view NSFW posts. Returns true if you can.
1202 export function nsfwCheck(
1204 myUserInfo = UserService.Instance.myUserInfo
1206 const nsfw = pv.post.nsfw || pv.community.nsfw;
1207 const myShowNsfw = myUserInfo?.local_user_view.local_user.show_nsfw ?? false;
1208 return !nsfw || (nsfw && myShowNsfw);
1211 export function getRandomFromList<T>(list: T[]): T | undefined {
1212 return list.length == 0
1214 : list.at(Math.floor(Math.random() * list.length));
1218 * This shows what language you can select
1220 * Use showAll for the site form
1221 * Use showSite for the profile and community forms
1222 * Use false for both those to filter on your profile and site ones
1224 export function selectableLanguages(
1225 allLanguages: Language[],
1226 siteLanguages: number[],
1229 myUserInfo = UserService.Instance.myUserInfo
1231 const allLangIds = allLanguages.map(l => l.id);
1232 let myLangs = myUserInfo?.discussion_languages ?? allLangIds;
1233 myLangs = myLangs.length == 0 ? allLangIds : myLangs;
1234 const siteLangs = siteLanguages.length == 0 ? allLangIds : siteLanguages;
1237 return allLanguages;
1240 return allLanguages.filter(x => siteLangs.includes(x.id));
1243 .filter(x => siteLangs.includes(x.id))
1244 .filter(x => myLangs.includes(x.id));
1249 interface EmojiMartCategory {
1252 emojis: EmojiMartCustomEmoji[];
1255 interface EmojiMartCustomEmoji {
1259 skins: EmojiMartSkin[];
1262 interface EmojiMartSkin {
1266 export function isAuthPath(pathname: string) {
1267 return /create_.*|inbox|settings|admin|reports|registration_applications/g.test(
1272 export function newVote(voteType: VoteType, myVote?: number): number {
1273 if (voteType == VoteType.Upvote) {
1274 return myVote == 1 ? 0 : 1;
1276 return myVote == -1 ? 0 : -1;
1280 export type RouteDataResponse<T extends Record<string, any>> = {
1281 [K in keyof T]: RequestState<T[K]>;