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, languages } 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))/;
235 export function isImage(url: string) {
236 return imageRegex.test(url);
239 export function isVideo(url: string) {
240 return videoRegex.test(url);
243 export function validURL(str: string) {
244 return !!new URL(str);
247 export function communityRSSUrl(actorId: string, sort: string): string {
248 const url = new URL(actorId);
249 return `${url.origin}/feeds${url.pathname}.xml?sort=${sort}`;
252 export function validEmail(email: string) {
254 /^(([^\s"(),.:;<>@[\\\]]+(\.[^\s"(),.:;<>@[\\\]]+)*)|(".+"))@((\[(?:\d{1,3}\.){3}\d{1,3}])|(([\dA-Za-z\-]+\.)+[A-Za-z]{2,}))$/;
255 return re.test(String(email).toLowerCase());
258 export function capitalizeFirstLetter(str: string): string {
259 return str.charAt(0).toUpperCase() + str.slice(1);
262 export async function getSiteMetadata(url: string) {
263 const form: GetSiteMetadata = { url };
264 const client = new LemmyHttp(getHttpBase());
265 return client.getSiteMetadata(form);
268 export function getDataTypeString(dt: DataType) {
269 return dt === DataType.Post ? "Post" : "Comment";
272 export function getLanguages(
274 myUserInfo = UserService.Instance.myUserInfo
276 const myLang = myUserInfo?.local_user_view.local_user.interface_language;
277 const lang = override || myLang || "browser";
279 if (lang == "browser" && isBrowser()) {
280 return getBrowserLanguages();
286 function getBrowserLanguages(): string[] {
287 // Intersect lemmy's langs, with the browser langs
288 const langs = languages ? languages.map(l => l.code) : ["en"];
290 // NOTE, mobile browsers seem to be missing this list, so append en
291 const allowedLangs = navigator.languages
293 .filter(v => langs.includes(v));
297 export async function fetchThemeList(): Promise<string[]> {
298 return fetch("/css/themelist").then(res => res.json());
301 export async function setTheme(theme: string, forceReload = false) {
305 if (theme === "browser" && !forceReload) {
308 // This is only run on a force reload
309 if (theme == "browser") {
313 const themeList = await fetchThemeList();
315 // Unload all the other themes
316 for (var i = 0; i < themeList.length; i++) {
317 const styleSheet = document.getElementById(themeList[i]);
319 styleSheet.setAttribute("disabled", "disabled");
324 .getElementById("default-light")
325 ?.setAttribute("disabled", "disabled");
326 document.getElementById("default-dark")?.setAttribute("disabled", "disabled");
328 // Load the theme dynamically
329 const cssLoc = `/css/themes/${theme}.css`;
331 loadCss(theme, cssLoc);
332 document.getElementById(theme)?.removeAttribute("disabled");
335 export function loadCss(id: string, loc: string) {
336 if (!document.getElementById(id)) {
337 var head = document.getElementsByTagName("head")[0];
338 var link = document.createElement("link");
340 link.rel = "stylesheet";
341 link.type = "text/css";
344 head.appendChild(link);
348 export function objectFlip(obj: any) {
350 Object.keys(obj).forEach(key => {
356 export function showAvatars(
357 myUserInfo = UserService.Instance.myUserInfo
359 return myUserInfo?.local_user_view.local_user.show_avatars ?? true;
362 export function showScores(
363 myUserInfo = UserService.Instance.myUserInfo
365 return myUserInfo?.local_user_view.local_user.show_scores ?? true;
368 export function isCakeDay(published: string): boolean {
369 // moment(undefined) or moment.utc(undefined) returns the current date/time
370 // moment(null) or moment.utc(null) returns null
371 const createDate = moment.utc(published).local();
372 const currentDate = moment(new Date());
375 createDate.date() === currentDate.date() &&
376 createDate.month() === currentDate.month() &&
377 createDate.year() !== currentDate.year()
381 export function toast(text: string, background: ThemeColor = "success") {
383 const backgroundColor = `var(--${background})`;
386 backgroundColor: backgroundColor,
394 export function pictrsDeleteToast(filename: string, deleteUrl: string) {
396 const clickToDeleteText = i18n.t("click_to_delete_picture", { filename });
397 const deletePictureText = i18n.t("picture_deleted", {
400 const failedDeletePictureText = i18n.t("failed_to_delete_picture", {
404 const backgroundColor = `var(--light)`;
406 const toast = Toastify({
407 text: clickToDeleteText,
408 backgroundColor: backgroundColor,
414 fetch(deleteUrl).then(res => {
416 if (res.ok === true) {
417 alert(deletePictureText);
419 alert(failedDeletePictureText);
431 export function setupTribute() {
433 noMatchTemplate: function () {
440 menuItemTemplate: (item: any) => {
441 const shortName = `:${item.original.key}:`;
442 return `${item.original.val} ${shortName}`;
444 selectTemplate: (item: any) => {
445 const customEmoji = customEmojisLookup.get(
448 if (customEmoji == undefined) return `${item.original.val}`;
450 return `![${customEmoji.alt_text}](${customEmoji.image_url} "${customEmoji.shortcode}")`;
452 values: Object.entries(emojiShortName)
454 return { key: e[1], val: e[0] };
457 Array.from(customEmojisLookup.entries()).map(k => ({
459 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}" />`,
463 autocompleteMode: true,
465 // menuItemLimit: mentionDropdownFetchLimit,
466 menuShowMinLength: 2,
471 selectTemplate: (item: any) => {
472 const it: PersonTribute = item.original;
473 return `[${it.key}](${it.view.person.actor_id})`;
475 values: debounce(async (text: string, cb: any) => {
476 cb(await personSearch(text));
479 autocompleteMode: true,
481 // menuItemLimit: mentionDropdownFetchLimit,
482 menuShowMinLength: 2,
488 selectTemplate: (item: any) => {
489 const it: CommunityTribute = item.original;
490 return `[${it.key}](${it.view.community.actor_id})`;
492 values: debounce(async (text: string, cb: any) => {
493 cb(await communitySearch(text));
496 autocompleteMode: true,
498 // menuItemLimit: mentionDropdownFetchLimit,
499 menuShowMinLength: 2,
505 function setupEmojiDataModel(custom_emoji_views: CustomEmojiView[]) {
506 const groupedEmojis = groupBy(
508 x => x.custom_emoji.category
510 for (const [category, emojis] of Object.entries(groupedEmojis)) {
514 emojis: emojis.map(emoji => ({
515 id: emoji.custom_emoji.shortcode,
516 name: emoji.custom_emoji.shortcode,
517 keywords: emoji.keywords.map(x => x.keyword),
518 skins: [{ src: emoji.custom_emoji.image_url }],
522 customEmojisLookup = new Map(
523 custom_emoji_views.map(view => [view.custom_emoji.shortcode, view])
527 export function updateEmojiDataModel(custom_emoji_view: CustomEmojiView) {
528 const emoji: EmojiMartCustomEmoji = {
529 id: custom_emoji_view.custom_emoji.shortcode,
530 name: custom_emoji_view.custom_emoji.shortcode,
531 keywords: custom_emoji_view.keywords.map(x => x.keyword),
532 skins: [{ src: custom_emoji_view.custom_emoji.image_url }],
534 const categoryIndex = customEmojis.findIndex(
535 x => x.id == custom_emoji_view.custom_emoji.category
537 if (categoryIndex == -1) {
539 id: custom_emoji_view.custom_emoji.category,
540 name: custom_emoji_view.custom_emoji.category,
544 const emojiIndex = customEmojis[categoryIndex].emojis.findIndex(
545 x => x.id == custom_emoji_view.custom_emoji.shortcode
547 if (emojiIndex == -1) {
548 customEmojis[categoryIndex].emojis.push(emoji);
550 customEmojis[categoryIndex].emojis[emojiIndex] = emoji;
553 customEmojisLookup.set(
554 custom_emoji_view.custom_emoji.shortcode,
559 export function removeFromEmojiDataModel(id: number) {
560 let view: CustomEmojiView | undefined;
561 for (const item of customEmojisLookup.values()) {
562 if (item.custom_emoji.id === id) {
568 const categoryIndex = customEmojis.findIndex(
569 x => x.id == view?.custom_emoji.category
571 const emojiIndex = customEmojis[categoryIndex].emojis.findIndex(
572 x => x.id == view?.custom_emoji.shortcode
574 customEmojis[categoryIndex].emojis = customEmojis[
576 ].emojis.splice(emojiIndex, 1);
578 customEmojisLookup.delete(view?.custom_emoji.shortcode);
581 function setupMarkdown() {
582 const markdownItConfig: MarkdownIt.Options = {
588 const emojiDefs = Array.from(customEmojisLookup.entries()).reduce(
589 (main, [key, value]) => ({ ...main, [key]: value }),
592 md = new MarkdownIt(markdownItConfig)
593 .use(markdown_it_sub)
594 .use(markdown_it_sup)
595 .use(markdown_it_footnote)
596 .use(markdown_it_html5_embed, html5EmbedConfig)
597 .use(markdown_it_container, "spoiler", spoilerConfig)
598 .use(markdown_it_emoji, {
602 mdNoImages = new MarkdownIt(markdownItConfig)
603 .use(markdown_it_sub)
604 .use(markdown_it_sup)
605 .use(markdown_it_footnote)
606 .use(markdown_it_html5_embed, html5EmbedConfig)
607 .use(markdown_it_container, "spoiler", spoilerConfig)
608 .use(markdown_it_emoji, {
612 var defaultRenderer = md.renderer.rules.image;
613 md.renderer.rules.image = function (
616 options: MarkdownIt.Options,
620 //Provide custom renderer for our emojis to allow us to add a css class and force size dimensions on them.
621 const item = tokens[idx] as any;
622 const title = item.attrs.length >= 3 ? item.attrs[2][1] : "";
623 const src: string = item.attrs[0][1];
624 const isCustomEmoji = customEmojisLookup.get(title) != undefined;
625 if (!isCustomEmoji) {
626 return defaultRenderer?.(tokens, idx, options, env, self) ?? "";
628 const alt_text = item.content;
629 return `<img class="icon icon-emoji" src="${src}" title="${title}" alt="${alt_text}"/>`;
633 export function getEmojiMart(
634 onEmojiSelect: (e: any) => void,
635 customPickerOptions: any = {}
637 const pickerOptions = {
638 ...customPickerOptions,
639 onEmojiSelect: onEmojiSelect,
640 custom: customEmojis,
642 return new Picker(pickerOptions);
645 var tippyInstance: any;
647 tippyInstance = tippy("[data-tippy-content]");
650 export function setupTippy() {
652 tippyInstance.forEach((e: any) => e.destroy());
653 tippyInstance = tippy("[data-tippy-content]", {
655 // Display on "long press"
656 touch: ["hold", 500],
661 interface PersonTribute {
666 async function personSearch(text: string): Promise<PersonTribute[]> {
667 const usersResponse = await fetchUsers(text);
669 return usersResponse.map(pv => ({
670 key: `@${pv.person.name}@${hostname(pv.person.actor_id)}`,
675 interface CommunityTribute {
680 async function communitySearch(text: string): Promise<CommunityTribute[]> {
681 const communitiesResponse = await fetchCommunities(text);
683 return communitiesResponse.map(cv => ({
684 key: `!${cv.community.name}@${hostname(cv.community.actor_id)}`,
689 export function getRecipientIdFromProps(props: any): number {
690 return props.match.params.recipient_id
691 ? Number(props.match.params.recipient_id)
695 export function getIdFromProps(props: any): number | undefined {
696 const id = props.match.params.post_id;
697 return id ? Number(id) : undefined;
700 export function getCommentIdFromProps(props: any): number | undefined {
701 const id = props.match.params.comment_id;
702 return id ? Number(id) : undefined;
705 type ImmutableListKey =
714 | "private_message_report"
715 | "registration_application";
717 function editListImmutable<
718 T extends { [key in F]: { id: number } },
719 F extends ImmutableListKey
720 >(fieldName: F, data: T, list: T[]): T[] {
722 ...list.map(c => (c[fieldName].id === data[fieldName].id ? data : c)),
726 export function editComment(
728 comments: CommentView[]
730 return editListImmutable("comment", data, comments);
733 export function editCommentReply(
734 data: CommentReplyView,
735 replies: CommentReplyView[]
736 ): CommentReplyView[] {
737 return editListImmutable("comment_reply", data, replies);
740 interface WithComment {
742 counts: CommentAggregates;
747 export function editMention(
748 data: PersonMentionView,
749 comments: PersonMentionView[]
750 ): PersonMentionView[] {
751 return editListImmutable("person_mention", data, comments);
754 export function editCommunity(
756 communities: CommunityView[]
758 return editListImmutable("community", data, communities);
761 export function editPrivateMessage(
762 data: PrivateMessageView,
763 messages: PrivateMessageView[]
764 ): PrivateMessageView[] {
765 return editListImmutable("private_message", data, messages);
768 export function editPost(data: PostView, posts: PostView[]): PostView[] {
769 return editListImmutable("post", data, posts);
772 export function editPostReport(
773 data: PostReportView,
774 reports: PostReportView[]
776 return editListImmutable("post_report", data, reports);
779 export function editCommentReport(
780 data: CommentReportView,
781 reports: CommentReportView[]
782 ): CommentReportView[] {
783 return editListImmutable("comment_report", data, reports);
786 export function editPrivateMessageReport(
787 data: PrivateMessageReportView,
788 reports: PrivateMessageReportView[]
789 ): PrivateMessageReportView[] {
790 return editListImmutable("private_message_report", data, reports);
793 export function editRegistrationApplication(
794 data: RegistrationApplicationView,
795 apps: RegistrationApplicationView[]
796 ): RegistrationApplicationView[] {
797 return editListImmutable("registration_application", data, apps);
800 export function editWith<D extends WithComment, L extends WithComment>(
801 { comment, counts, saved, my_vote }: D,
806 c.comment.id === comment.id
807 ? { ...c, comment, counts, saved, my_vote }
813 export function updatePersonBlock(
814 data: BlockPersonResponse,
815 myUserInfo: MyUserInfo | undefined = UserService.Instance.myUserInfo
819 myUserInfo.person_blocks.push({
820 person: myUserInfo.local_user_view.person,
821 target: data.person_view.person,
823 toast(`${i18n.t("blocked")} ${data.person_view.person.name}`);
825 myUserInfo.person_blocks = myUserInfo.person_blocks.filter(
826 i => i.target.id !== data.person_view.person.id
828 toast(`${i18n.t("unblocked")} ${data.person_view.person.name}`);
833 export function updateCommunityBlock(
834 data: BlockCommunityResponse,
835 myUserInfo: MyUserInfo | undefined = UserService.Instance.myUserInfo
839 myUserInfo.community_blocks.push({
840 person: myUserInfo.local_user_view.person,
841 community: data.community_view.community,
843 toast(`${i18n.t("blocked")} ${data.community_view.community.name}`);
845 myUserInfo.community_blocks = myUserInfo.community_blocks.filter(
846 i => i.community.id !== data.community_view.community.id
848 toast(`${i18n.t("unblocked")} ${data.community_view.community.name}`);
853 export function commentsToFlatNodes(comments: CommentView[]): CommentNodeI[] {
854 const nodes: CommentNodeI[] = [];
855 for (const comment of comments) {
856 nodes.push({ comment_view: comment, children: [], depth: 0 });
861 export function convertCommentSortType(sort: SortType): CommentSortType {
866 sort == "TopMonth" ||
870 } else if (sort == "New") {
872 } else if (sort == "Hot" || sort == "Active") {
879 export function buildCommentsTree(
880 comments: CommentView[],
881 parentComment: boolean
883 const map = new Map<number, CommentNodeI>();
884 const depthOffset = !parentComment
886 : getDepthFromComment(comments[0].comment) ?? 0;
888 for (const comment_view of comments) {
889 const depthI = getDepthFromComment(comment_view.comment) ?? 0;
890 const depth = depthI ? depthI - depthOffset : 0;
891 const node: CommentNodeI = {
896 map.set(comment_view.comment.id, { ...node });
899 const tree: CommentNodeI[] = [];
901 // if its a parent comment fetch, then push the first comment to the top node.
903 const cNode = map.get(comments[0].comment.id);
909 for (const comment_view of comments) {
910 const child = map.get(comment_view.comment.id);
912 const parent_id = getCommentParentId(comment_view.comment);
914 const parent = map.get(parent_id);
915 // Necessary because blocked comment might not exist
917 parent.children.push(child);
920 if (!parentComment) {
930 export function getCommentParentId(comment?: CommentI): number | undefined {
931 const split = comment?.path.split(".");
935 return split && split.length > 1
936 ? Number(split.at(split.length - 2))
940 export function getDepthFromComment(comment?: CommentI): number | undefined {
941 const len = comment?.path.split(".").length;
942 return len ? len - 2 : undefined;
945 // TODO make immutable
946 export function insertCommentIntoTree(
947 tree: CommentNodeI[],
949 parentComment: boolean
951 // Building a fake node to be used for later
952 const node: CommentNodeI = {
958 const parentId = getCommentParentId(cv.comment);
960 const parent_comment = searchCommentTree(tree, parentId);
961 if (parent_comment) {
962 node.depth = parent_comment.depth + 1;
963 parent_comment.children.unshift(node);
965 } else if (!parentComment) {
970 export function searchCommentTree(
971 tree: CommentNodeI[],
973 ): CommentNodeI | undefined {
974 for (const node of tree) {
975 if (node.comment_view.comment.id === id) {
979 for (const child of node.children) {
980 const res = searchCommentTree([child], id);
990 export const colorList: string[] = [
1000 function hsl(num: number) {
1001 return `hsla(${num}, 35%, 50%, 0.5)`;
1004 export function hostname(url: string): string {
1005 const cUrl = new URL(url);
1006 return cUrl.port ? `${cUrl.hostname}:${cUrl.port}` : `${cUrl.hostname}`;
1009 export function validTitle(title?: string): boolean {
1010 // Initial title is null, minimum length is taken care of by textarea's minLength={3}
1011 if (!title || title.length < 3) return true;
1013 const regex = new RegExp(/.*\S.*/, "g");
1015 return regex.test(title);
1018 export function siteBannerCss(banner: string): string {
1020 background-image: linear-gradient( rgba(0, 0, 0, 0.8), rgba(0, 0, 0, 0.8) ) ,url("${banner}"); \
1021 background-attachment: fixed; \
1022 background-position: top; \
1023 background-repeat: no-repeat; \
1024 background-size: 100% cover; \
1027 max-height: 100vh; \
1031 export function setIsoData(context: any): IsoData {
1032 // If its the browser, you need to deserialize the data from the window
1034 return window.isoData;
1035 } else return context.router.staticContext;
1038 moment.updateLocale("en", {
1059 export function saveScrollPosition(context: any) {
1060 const path: string = context.router.route.location.pathname;
1061 const y = window.scrollY;
1062 sessionStorage.setItem(`scrollPosition_${path}`, y.toString());
1065 export function restoreScrollPosition(context: any) {
1066 const path: string = context.router.route.location.pathname;
1067 const y = Number(sessionStorage.getItem(`scrollPosition_${path}`));
1068 window.scrollTo(0, y);
1071 export function showLocal(isoData: IsoData): boolean {
1072 return isoData.site_res.site_view.local_site.federation_enabled;
1075 export interface Choice {
1081 export function getUpdatedSearchId(id?: number | null, urlId?: number | null) {
1084 : ((id ?? urlId) === 0 ? undefined : id ?? urlId)?.toString();
1087 export function communityToChoice(cv: CommunityView): Choice {
1089 value: cv.community.id.toString(),
1090 label: communitySelectName(cv),
1094 export function personToChoice(pvs: PersonView): Choice {
1096 value: pvs.person.id.toString(),
1097 label: personSelectName(pvs),
1101 function fetchSearchResults(q: string, type_: SearchType) {
1102 const form: Search = {
1106 listing_type: "All",
1112 return HttpService.client.search(form);
1115 export async function fetchCommunities(q: string) {
1116 const res = await fetchSearchResults(q, "Communities");
1118 return res.state === "success" ? res.data.communities : [];
1121 export async function fetchUsers(q: string) {
1122 const res = await fetchSearchResults(q, "Users");
1124 return res.state === "success" ? res.data.users : [];
1127 export function communitySelectName(cv: CommunityView): string {
1128 return cv.community.local
1129 ? cv.community.title
1130 : `${hostname(cv.community.actor_id)}/${cv.community.title}`;
1133 export function personSelectName({
1134 person: { display_name, name, local, actor_id },
1135 }: PersonView): string {
1136 const pName = display_name ?? name;
1137 return local ? pName : `${hostname(actor_id)}/${pName}`;
1140 export function initializeSite(site?: GetSiteResponse) {
1141 UserService.Instance.myUserInfo = site?.my_user;
1142 i18n.changeLanguage(getLanguages()[0]);
1144 setupEmojiDataModel(site.custom_emojis ?? []);
1149 const SHORTNUM_SI_FORMAT = new Intl.NumberFormat("en-US", {
1150 maximumSignificantDigits: 3,
1152 notation: "compact",
1153 compactDisplay: "short",
1156 export function numToSI(value: number): string {
1157 return SHORTNUM_SI_FORMAT.format(value);
1160 export function myAuth(): string | undefined {
1161 return UserService.Instance.auth();
1164 export function myAuthRequired(): string {
1165 return UserService.Instance.auth(true) ?? "";
1168 export function enableDownvotes(siteRes: GetSiteResponse): boolean {
1169 return siteRes.site_view.local_site.enable_downvotes;
1172 export function enableNsfw(siteRes: GetSiteResponse): boolean {
1173 return siteRes.site_view.local_site.enable_nsfw;
1176 export function postToCommentSortType(sort: SortType): CommentSortType {
1191 export function isPostBlocked(
1193 myUserInfo: MyUserInfo | undefined = UserService.Instance.myUserInfo
1196 (myUserInfo?.community_blocks
1197 .map(c => c.community.id)
1198 .includes(pv.community.id) ||
1199 myUserInfo?.person_blocks
1200 .map(p => p.target.id)
1201 .includes(pv.creator.id)) ??
1206 /// Checks to make sure you can view NSFW posts. Returns true if you can.
1207 export function nsfwCheck(
1209 myUserInfo = UserService.Instance.myUserInfo
1211 const nsfw = pv.post.nsfw || pv.community.nsfw;
1212 const myShowNsfw = myUserInfo?.local_user_view.local_user.show_nsfw ?? false;
1213 return !nsfw || (nsfw && myShowNsfw);
1216 export function getRandomFromList<T>(list: T[]): T | undefined {
1217 return list.length == 0
1219 : list.at(Math.floor(Math.random() * list.length));
1223 * This shows what language you can select
1225 * Use showAll for the site form
1226 * Use showSite for the profile and community forms
1227 * Use false for both those to filter on your profile and site ones
1229 export function selectableLanguages(
1230 allLanguages: Language[],
1231 siteLanguages: number[],
1234 myUserInfo = UserService.Instance.myUserInfo
1236 const allLangIds = allLanguages.map(l => l.id);
1237 let myLangs = myUserInfo?.discussion_languages ?? allLangIds;
1238 myLangs = myLangs.length == 0 ? allLangIds : myLangs;
1239 const siteLangs = siteLanguages.length == 0 ? allLangIds : siteLanguages;
1242 return allLanguages;
1245 return allLanguages.filter(x => siteLangs.includes(x.id));
1248 .filter(x => siteLangs.includes(x.id))
1249 .filter(x => myLangs.includes(x.id));
1254 interface EmojiMartCategory {
1257 emojis: EmojiMartCustomEmoji[];
1260 interface EmojiMartCustomEmoji {
1264 skins: EmojiMartSkin[];
1267 interface EmojiMartSkin {
1271 export function isAuthPath(pathname: string) {
1272 return /create_.*|inbox|settings|admin|reports|registration_applications/g.test(
1277 export function newVote(voteType: VoteType, myVote?: number): number {
1278 if (voteType == VoteType.Upvote) {
1279 return myVote == 1 ? 0 : 1;
1281 return myVote == -1 ? 0 : -1;