1 import { Picker } from "emoji-mart";
2 import emojiShortName from "emoji-short-name";
4 BlockCommunityResponse,
12 CommunityModeratorView,
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, languages } from "./i18next";
46 import { CommentNodeI, DataType, IsoData, VoteType } from "./interfaces";
47 import { HttpService, UserService } from "./services";
48 import { RequestState } from "./services/HttpService";
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;
80 export const relTags = "noopener nofollow";
82 export const emDash = "\u2014";
84 export type ThemeColor =
107 export interface ErrorPageData {
109 adminMatrixIds?: string[];
112 const customEmojis: EmojiMartCategory[] = [];
113 export let customEmojisLookup: Map<string, CustomEmojiView> = new Map<
118 const DEFAULT_ALPHABET =
119 "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
121 function getRandomCharFromAlphabet(alphabet: string): string {
122 return alphabet.charAt(Math.floor(Math.random() * alphabet.length));
125 export function getIdFromString(id?: string): number | undefined {
126 return id && id !== "0" && !Number.isNaN(Number(id)) ? Number(id) : undefined;
129 export function getPageFromString(page?: string): number {
130 return page && !Number.isNaN(Number(page)) ? Number(page) : 1;
133 export function randomStr(
134 idDesiredLength = 20,
135 alphabet = DEFAULT_ALPHABET
138 * Create n-long array and map it to random chars from given alphabet.
139 * Then join individual chars as string
141 return Array.from({ length: idDesiredLength })
143 return getRandomCharFromAlphabet(alphabet);
148 const html5EmbedConfig = {
150 useImageSyntax: true, // Enables video/audio embed with ![]() syntax (default)
152 audio: 'controls preload="metadata"',
153 video: 'width="100%" max-height="100%" controls loop preload="metadata"',
158 const spoilerConfig = {
159 validate: (params: string) => {
160 return params.trim().match(/^spoiler\s+(.*)$/);
163 render: (tokens: any, idx: any) => {
164 var m = tokens[idx].info.trim().match(/^spoiler\s+(.*)$/);
166 if (tokens[idx].nesting === 1) {
168 return `<details><summary> ${md.utils.escapeHtml(m[1])} </summary>\n`;
171 return "</details>\n";
176 export let md: MarkdownIt = new MarkdownIt();
178 export let mdNoImages: MarkdownIt = new MarkdownIt();
180 export function hotRankComment(comment_view: CommentView): number {
181 return hotRank(comment_view.counts.score, comment_view.comment.published);
184 export function hotRankActivePost(post_view: PostView): number {
185 return hotRank(post_view.counts.score, post_view.counts.newest_comment_time);
188 export function hotRankPost(post_view: PostView): number {
189 return hotRank(post_view.counts.score, post_view.post.published);
192 export function hotRank(score: number, timeStr: string): number {
193 // Rank = ScaleFactor * sign(Score) * log(1 + abs(Score)) / (Time + 2)^Gravity
194 const date: Date = new Date(timeStr + "Z"); // Add Z to convert from UTC date
195 const now: Date = new Date();
196 const hoursElapsed: number = (now.getTime() - date.getTime()) / 36e5;
199 (10000 * Math.log10(Math.max(1, 3 + Number(score)))) /
200 Math.pow(hoursElapsed + 2, 1.8);
202 // console.log(`Comment: ${comment.content}\nRank: ${rank}\nScore: ${comment.score}\nHours: ${hoursElapsed}`);
207 export function mdToHtml(text: string) {
208 return { __html: md.render(text) };
211 export function mdToHtmlNoImages(text: string) {
212 return { __html: mdNoImages.render(text) };
215 export function mdToHtmlInline(text: string) {
216 return { __html: md.renderInline(text) };
219 export function getUnixTime(text?: string): number | undefined {
220 return text ? new Date(text).getTime() / 1000 : undefined;
223 export function futureDaysToUnixTime(days?: number): number | undefined {
226 new Date(Date.now() + 1000 * 60 * 60 * 24 * days).getTime() / 1000
231 export function canMod(
233 mods?: CommunityModeratorView[],
234 admins?: PersonView[],
235 myUserInfo = UserService.Instance.myUserInfo,
238 // You can do moderator actions only on the mods added after you.
241 ?.map(a => a.person.id)
242 .concat(mods?.map(m => m.moderator.id) ?? []) ?? [];
245 const myIndex = adminsThenMods.findIndex(
246 id => id == myUserInfo.local_user_view.person.id
251 // onSelf +1 on mod actions not for yourself, IE ban, remove, etc
252 adminsThenMods = adminsThenMods.slice(0, myIndex + (onSelf ? 0 : 1));
253 return !adminsThenMods.includes(creator_id);
260 export function canAdmin(
262 admins?: PersonView[],
263 myUserInfo = UserService.Instance.myUserInfo,
266 return canMod(creatorId, undefined, admins, myUserInfo, onSelf);
269 export function isMod(
271 mods?: CommunityModeratorView[]
273 return mods?.map(m => m.moderator.id).includes(creatorId) ?? false;
276 export function amMod(
277 mods?: CommunityModeratorView[],
278 myUserInfo = UserService.Instance.myUserInfo
280 return myUserInfo ? isMod(myUserInfo.local_user_view.person.id, mods) : false;
283 export function isAdmin(creatorId: number, admins?: PersonView[]): boolean {
284 return admins?.map(a => a.person.id).includes(creatorId) ?? false;
287 export function amAdmin(myUserInfo = UserService.Instance.myUserInfo): boolean {
288 return myUserInfo?.local_user_view.person.admin ?? false;
291 export function amCommunityCreator(
293 mods?: CommunityModeratorView[],
294 myUserInfo = UserService.Instance.myUserInfo
296 const myId = myUserInfo?.local_user_view.person.id;
297 // Don't allow mod actions on yourself
298 return myId == mods?.at(0)?.moderator.id && myId != creator_id;
301 export function amSiteCreator(
303 admins?: PersonView[],
304 myUserInfo = UserService.Instance.myUserInfo
306 const myId = myUserInfo?.local_user_view.person.id;
307 return myId == admins?.at(0)?.person.id && myId != creator_id;
310 export function amTopMod(
311 mods: CommunityModeratorView[],
312 myUserInfo = UserService.Instance.myUserInfo
314 return mods.at(0)?.moderator.id == myUserInfo?.local_user_view.person.id;
317 const imageRegex = /(http)?s?:?(\/\/[^"']*\.(?:jpg|jpeg|gif|png|svg|webp))/;
318 const videoRegex = /(http)?s?:?(\/\/[^"']*\.(?:mp4|webm))/;
320 export function isImage(url: string) {
321 return imageRegex.test(url);
324 export function isVideo(url: string) {
325 return videoRegex.test(url);
328 export function validURL(str: string) {
329 return !!new URL(str);
332 export function communityRSSUrl(actorId: string, sort: string): string {
333 const url = new URL(actorId);
334 return `${url.origin}/feeds${url.pathname}.xml?sort=${sort}`;
337 export function validEmail(email: string) {
339 /^(([^\s"(),.:;<>@[\\\]]+(\.[^\s"(),.:;<>@[\\\]]+)*)|(".+"))@((\[(?:\d{1,3}\.){3}\d{1,3}])|(([\dA-Za-z\-]+\.)+[A-Za-z]{2,}))$/;
340 return re.test(String(email).toLowerCase());
343 export function capitalizeFirstLetter(str: string): string {
344 return str.charAt(0).toUpperCase() + str.slice(1);
347 export async function getSiteMetadata(url: string) {
348 const form: GetSiteMetadata = { url };
349 const client = new LemmyHttp(getHttpBase());
350 return client.getSiteMetadata(form);
353 export function getDataTypeString(dt: DataType) {
354 return dt === DataType.Post ? "Post" : "Comment";
357 export function debounce<T extends any[], R>(
358 func: (...e: T) => R,
362 // 'private' variable for instance
363 // The returned function will be able to reference this due to closure.
364 // Each call to the returned function will share this common timer.
365 let timeout: NodeJS.Timeout | null;
367 // Calling debounce returns a new anonymous function
369 // reference the context and args for the setTimeout function
370 const args = arguments;
372 // Should the function be called now? If immediate is true
373 // and not already in a timeout then the answer is: Yes
374 const callNow = immediate && !timeout;
376 // This is the basic debounce behavior where you can call this
377 // function several times, but it will only execute once
378 // [before or after imposing a delay].
379 // Each time the returned function is called, the timer starts over.
380 clearTimeout(timeout ?? undefined);
382 // Set the new timeout
383 timeout = setTimeout(function () {
384 // Inside the timeout function, clear the timeout variable
385 // which will let the next execution run when in 'immediate' mode
388 // Check if the function already ran with the immediate flag
390 // Call the original function with apply
391 // apply lets you define the 'this' object as well as the arguments
392 // (both captured before setTimeout)
393 func.apply(this, args);
397 // Immediate mode and no wait timer? Execute the function..
398 if (callNow) func.apply(this, args);
402 export function getLanguages(
404 myUserInfo = UserService.Instance.myUserInfo
406 const myLang = myUserInfo?.local_user_view.local_user.interface_language;
407 const lang = override || myLang || "browser";
409 if (lang == "browser" && isBrowser()) {
410 return getBrowserLanguages();
416 function getBrowserLanguages(): string[] {
417 // Intersect lemmy's langs, with the browser langs
418 const langs = languages ? languages.map(l => l.code) : ["en"];
420 // NOTE, mobile browsers seem to be missing this list, so append en
421 const allowedLangs = navigator.languages
423 .filter(v => langs.includes(v));
427 export async function fetchThemeList(): Promise<string[]> {
428 return fetch("/css/themelist").then(res => res.json());
431 export async function setTheme(theme: string, forceReload = false) {
435 if (theme === "browser" && !forceReload) {
438 // This is only run on a force reload
439 if (theme == "browser") {
443 const themeList = await fetchThemeList();
445 // Unload all the other themes
446 for (var i = 0; i < themeList.length; i++) {
447 const styleSheet = document.getElementById(themeList[i]);
449 styleSheet.setAttribute("disabled", "disabled");
454 .getElementById("default-light")
455 ?.setAttribute("disabled", "disabled");
456 document.getElementById("default-dark")?.setAttribute("disabled", "disabled");
458 // Load the theme dynamically
459 const cssLoc = `/css/themes/${theme}.css`;
461 loadCss(theme, cssLoc);
462 document.getElementById(theme)?.removeAttribute("disabled");
465 export function loadCss(id: string, loc: string) {
466 if (!document.getElementById(id)) {
467 var head = document.getElementsByTagName("head")[0];
468 var link = document.createElement("link");
470 link.rel = "stylesheet";
471 link.type = "text/css";
474 head.appendChild(link);
478 export function objectFlip(obj: any) {
480 Object.keys(obj).forEach(key => {
486 export function showAvatars(
487 myUserInfo = UserService.Instance.myUserInfo
489 return myUserInfo?.local_user_view.local_user.show_avatars ?? true;
492 export function showScores(
493 myUserInfo = UserService.Instance.myUserInfo
495 return myUserInfo?.local_user_view.local_user.show_scores ?? true;
498 export function isCakeDay(published: string): boolean {
499 // moment(undefined) or moment.utc(undefined) returns the current date/time
500 // moment(null) or moment.utc(null) returns null
501 const createDate = moment.utc(published).local();
502 const currentDate = moment(new Date());
505 createDate.date() === currentDate.date() &&
506 createDate.month() === currentDate.month() &&
507 createDate.year() !== currentDate.year()
511 export function toast(text: string, background: ThemeColor = "success") {
513 const backgroundColor = `var(--${background})`;
516 backgroundColor: backgroundColor,
524 export function pictrsDeleteToast(filename: string, deleteUrl: string) {
526 const clickToDeleteText = i18n.t("click_to_delete_picture", { filename });
527 const deletePictureText = i18n.t("picture_deleted", {
530 const failedDeletePictureText = i18n.t("failed_to_delete_picture", {
534 const backgroundColor = `var(--light)`;
536 const toast = Toastify({
537 text: clickToDeleteText,
538 backgroundColor: backgroundColor,
544 fetch(deleteUrl).then(res => {
546 if (res.ok === true) {
547 alert(deletePictureText);
549 alert(failedDeletePictureText);
561 export function setupTribute() {
563 noMatchTemplate: function () {
570 menuItemTemplate: (item: any) => {
571 const shortName = `:${item.original.key}:`;
572 return `${item.original.val} ${shortName}`;
574 selectTemplate: (item: any) => {
575 const customEmoji = customEmojisLookup.get(
578 if (customEmoji == undefined) return `${item.original.val}`;
580 return `![${customEmoji.alt_text}](${customEmoji.image_url} "${customEmoji.shortcode}")`;
582 values: Object.entries(emojiShortName)
584 return { key: e[1], val: e[0] };
587 Array.from(customEmojisLookup.entries()).map(k => ({
589 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}" />`,
593 autocompleteMode: true,
595 // menuItemLimit: mentionDropdownFetchLimit,
596 menuShowMinLength: 2,
601 selectTemplate: (item: any) => {
602 const it: PersonTribute = item.original;
603 return `[${it.key}](${it.view.person.actor_id})`;
605 values: debounce(async (text: string, cb: any) => {
606 cb(await personSearch(text));
609 autocompleteMode: true,
611 // menuItemLimit: mentionDropdownFetchLimit,
612 menuShowMinLength: 2,
618 selectTemplate: (item: any) => {
619 const it: CommunityTribute = item.original;
620 return `[${it.key}](${it.view.community.actor_id})`;
622 values: debounce(async (text: string, cb: any) => {
623 cb(await communitySearch(text));
626 autocompleteMode: true,
628 // menuItemLimit: mentionDropdownFetchLimit,
629 menuShowMinLength: 2,
635 function setupEmojiDataModel(custom_emoji_views: CustomEmojiView[]) {
636 const groupedEmojis = groupBy(
638 x => x.custom_emoji.category
640 for (const [category, emojis] of Object.entries(groupedEmojis)) {
644 emojis: emojis.map(emoji => ({
645 id: emoji.custom_emoji.shortcode,
646 name: emoji.custom_emoji.shortcode,
647 keywords: emoji.keywords.map(x => x.keyword),
648 skins: [{ src: emoji.custom_emoji.image_url }],
652 customEmojisLookup = new Map(
653 custom_emoji_views.map(view => [view.custom_emoji.shortcode, view])
657 export function updateEmojiDataModel(custom_emoji_view: CustomEmojiView) {
658 const emoji: EmojiMartCustomEmoji = {
659 id: custom_emoji_view.custom_emoji.shortcode,
660 name: custom_emoji_view.custom_emoji.shortcode,
661 keywords: custom_emoji_view.keywords.map(x => x.keyword),
662 skins: [{ src: custom_emoji_view.custom_emoji.image_url }],
664 const categoryIndex = customEmojis.findIndex(
665 x => x.id == custom_emoji_view.custom_emoji.category
667 if (categoryIndex == -1) {
669 id: custom_emoji_view.custom_emoji.category,
670 name: custom_emoji_view.custom_emoji.category,
674 const emojiIndex = customEmojis[categoryIndex].emojis.findIndex(
675 x => x.id == custom_emoji_view.custom_emoji.shortcode
677 if (emojiIndex == -1) {
678 customEmojis[categoryIndex].emojis.push(emoji);
680 customEmojis[categoryIndex].emojis[emojiIndex] = emoji;
683 customEmojisLookup.set(
684 custom_emoji_view.custom_emoji.shortcode,
689 export function removeFromEmojiDataModel(id: number) {
690 let view: CustomEmojiView | undefined;
691 for (const item of customEmojisLookup.values()) {
692 if (item.custom_emoji.id === id) {
698 const categoryIndex = customEmojis.findIndex(
699 x => x.id == view?.custom_emoji.category
701 const emojiIndex = customEmojis[categoryIndex].emojis.findIndex(
702 x => x.id == view?.custom_emoji.shortcode
704 customEmojis[categoryIndex].emojis = customEmojis[
706 ].emojis.splice(emojiIndex, 1);
708 customEmojisLookup.delete(view?.custom_emoji.shortcode);
711 function setupMarkdown() {
712 const markdownItConfig: MarkdownIt.Options = {
718 const emojiDefs = Array.from(customEmojisLookup.entries()).reduce(
719 (main, [key, value]) => ({ ...main, [key]: value }),
722 md = new MarkdownIt(markdownItConfig)
723 .use(markdown_it_sub)
724 .use(markdown_it_sup)
725 .use(markdown_it_footnote)
726 .use(markdown_it_html5_embed, html5EmbedConfig)
727 .use(markdown_it_container, "spoiler", spoilerConfig)
728 .use(markdown_it_emoji, {
732 mdNoImages = new MarkdownIt(markdownItConfig)
733 .use(markdown_it_sub)
734 .use(markdown_it_sup)
735 .use(markdown_it_footnote)
736 .use(markdown_it_html5_embed, html5EmbedConfig)
737 .use(markdown_it_container, "spoiler", spoilerConfig)
738 .use(markdown_it_emoji, {
742 var defaultRenderer = md.renderer.rules.image;
743 md.renderer.rules.image = function (
746 options: MarkdownIt.Options,
750 //Provide custom renderer for our emojis to allow us to add a css class and force size dimensions on them.
751 const item = tokens[idx] as any;
752 const title = item.attrs.length >= 3 ? item.attrs[2][1] : "";
753 const src: string = item.attrs[0][1];
754 const isCustomEmoji = customEmojisLookup.get(title) != undefined;
755 if (!isCustomEmoji) {
756 return defaultRenderer?.(tokens, idx, options, env, self) ?? "";
758 const alt_text = item.content;
759 return `<img class="icon icon-emoji" src="${src}" title="${title}" alt="${alt_text}"/>`;
763 export function getEmojiMart(
764 onEmojiSelect: (e: any) => void,
765 customPickerOptions: any = {}
767 const pickerOptions = {
768 ...customPickerOptions,
769 onEmojiSelect: onEmojiSelect,
770 custom: customEmojis,
772 return new Picker(pickerOptions);
775 var tippyInstance: any;
777 tippyInstance = tippy("[data-tippy-content]");
780 export function setupTippy() {
782 tippyInstance.forEach((e: any) => e.destroy());
783 tippyInstance = tippy("[data-tippy-content]", {
785 // Display on "long press"
786 touch: ["hold", 500],
791 interface PersonTribute {
796 async function personSearch(text: string): Promise<PersonTribute[]> {
797 const usersResponse = await fetchUsers(text);
799 return usersResponse.map(pv => ({
800 key: `@${pv.person.name}@${hostname(pv.person.actor_id)}`,
805 interface CommunityTribute {
810 async function communitySearch(text: string): Promise<CommunityTribute[]> {
811 const communitiesResponse = await fetchCommunities(text);
813 return communitiesResponse.map(cv => ({
814 key: `!${cv.community.name}@${hostname(cv.community.actor_id)}`,
819 export function getRecipientIdFromProps(props: any): number {
820 return props.match.params.recipient_id
821 ? Number(props.match.params.recipient_id)
825 export function getIdFromProps(props: any): number | undefined {
826 const id = props.match.params.post_id;
827 return id ? Number(id) : undefined;
830 export function getCommentIdFromProps(props: any): number | undefined {
831 const id = props.match.params.comment_id;
832 return id ? Number(id) : undefined;
835 type ImmutableListKey =
844 | "private_message_report"
845 | "registration_application";
847 function editListImmutable<
848 T extends { [key in F]: { id: number } },
849 F extends ImmutableListKey
850 >(fieldName: F, data: T, list: T[]): T[] {
852 ...list.map(c => (c[fieldName].id === data[fieldName].id ? data : c)),
856 export function editComment(
858 comments: CommentView[]
860 return editListImmutable("comment", data, comments);
863 export function editCommentReply(
864 data: CommentReplyView,
865 replies: CommentReplyView[]
866 ): CommentReplyView[] {
867 return editListImmutable("comment_reply", data, replies);
870 interface WithComment {
872 counts: CommentAggregates;
877 export function editMention(
878 data: PersonMentionView,
879 comments: PersonMentionView[]
880 ): PersonMentionView[] {
881 return editListImmutable("person_mention", data, comments);
884 export function editCommunity(
886 communities: CommunityView[]
888 return editListImmutable("community", data, communities);
891 export function editPrivateMessage(
892 data: PrivateMessageView,
893 messages: PrivateMessageView[]
894 ): PrivateMessageView[] {
895 return editListImmutable("private_message", data, messages);
898 export function editPost(data: PostView, posts: PostView[]): PostView[] {
899 return editListImmutable("post", data, posts);
902 export function editPostReport(
903 data: PostReportView,
904 reports: PostReportView[]
906 return editListImmutable("post_report", data, reports);
909 export function editCommentReport(
910 data: CommentReportView,
911 reports: CommentReportView[]
912 ): CommentReportView[] {
913 return editListImmutable("comment_report", data, reports);
916 export function editPrivateMessageReport(
917 data: PrivateMessageReportView,
918 reports: PrivateMessageReportView[]
919 ): PrivateMessageReportView[] {
920 return editListImmutable("private_message_report", data, reports);
923 export function editRegistrationApplication(
924 data: RegistrationApplicationView,
925 apps: RegistrationApplicationView[]
926 ): RegistrationApplicationView[] {
927 return editListImmutable("registration_application", data, apps);
930 export function editWith<D extends WithComment, L extends WithComment>(
931 { comment, counts, saved, my_vote }: D,
936 c.comment.id === comment.id
937 ? { ...c, comment, counts, saved, my_vote }
943 export function updatePersonBlock(
944 data: BlockPersonResponse,
945 myUserInfo: MyUserInfo | undefined = UserService.Instance.myUserInfo
949 myUserInfo.person_blocks.push({
950 person: myUserInfo.local_user_view.person,
951 target: data.person_view.person,
953 toast(`${i18n.t("blocked")} ${data.person_view.person.name}`);
955 myUserInfo.person_blocks = myUserInfo.person_blocks.filter(
956 i => i.target.id !== data.person_view.person.id
958 toast(`${i18n.t("unblocked")} ${data.person_view.person.name}`);
963 export function updateCommunityBlock(
964 data: BlockCommunityResponse,
965 myUserInfo: MyUserInfo | undefined = UserService.Instance.myUserInfo
969 myUserInfo.community_blocks.push({
970 person: myUserInfo.local_user_view.person,
971 community: data.community_view.community,
973 toast(`${i18n.t("blocked")} ${data.community_view.community.name}`);
975 myUserInfo.community_blocks = myUserInfo.community_blocks.filter(
976 i => i.community.id !== data.community_view.community.id
978 toast(`${i18n.t("unblocked")} ${data.community_view.community.name}`);
983 export function commentsToFlatNodes(comments: CommentView[]): CommentNodeI[] {
984 const nodes: CommentNodeI[] = [];
985 for (const comment of comments) {
986 nodes.push({ comment_view: comment, children: [], depth: 0 });
991 export function convertCommentSortType(sort: SortType): CommentSortType {
996 sort == "TopMonth" ||
1000 } else if (sort == "New") {
1002 } else if (sort == "Hot" || sort == "Active") {
1009 export function buildCommentsTree(
1010 comments: CommentView[],
1011 parentComment: boolean
1013 const map = new Map<number, CommentNodeI>();
1014 const depthOffset = !parentComment
1016 : getDepthFromComment(comments[0].comment) ?? 0;
1018 for (const comment_view of comments) {
1019 const depthI = getDepthFromComment(comment_view.comment) ?? 0;
1020 const depth = depthI ? depthI - depthOffset : 0;
1021 const node: CommentNodeI = {
1026 map.set(comment_view.comment.id, { ...node });
1029 const tree: CommentNodeI[] = [];
1031 // if its a parent comment fetch, then push the first comment to the top node.
1032 if (parentComment) {
1033 const cNode = map.get(comments[0].comment.id);
1039 for (const comment_view of comments) {
1040 const child = map.get(comment_view.comment.id);
1042 const parent_id = getCommentParentId(comment_view.comment);
1044 const parent = map.get(parent_id);
1045 // Necessary because blocked comment might not exist
1047 parent.children.push(child);
1050 if (!parentComment) {
1060 export function getCommentParentId(comment?: CommentI): number | undefined {
1061 const split = comment?.path.split(".");
1065 return split && split.length > 1
1066 ? Number(split.at(split.length - 2))
1070 export function getDepthFromComment(comment?: CommentI): number | undefined {
1071 const len = comment?.path.split(".").length;
1072 return len ? len - 2 : undefined;
1075 // TODO make immutable
1076 export function insertCommentIntoTree(
1077 tree: CommentNodeI[],
1079 parentComment: boolean
1081 // Building a fake node to be used for later
1082 const node: CommentNodeI = {
1088 const parentId = getCommentParentId(cv.comment);
1090 const parent_comment = searchCommentTree(tree, parentId);
1091 if (parent_comment) {
1092 node.depth = parent_comment.depth + 1;
1093 parent_comment.children.unshift(node);
1095 } else if (!parentComment) {
1100 export function searchCommentTree(
1101 tree: CommentNodeI[],
1103 ): CommentNodeI | undefined {
1104 for (const node of tree) {
1105 if (node.comment_view.comment.id === id) {
1109 for (const child of node.children) {
1110 const res = searchCommentTree([child], id);
1120 export const colorList: string[] = [
1130 function hsl(num: number) {
1131 return `hsla(${num}, 35%, 50%, 1)`;
1134 export function hostname(url: string): string {
1135 const cUrl = new URL(url);
1136 return cUrl.port ? `${cUrl.hostname}:${cUrl.port}` : `${cUrl.hostname}`;
1139 export function validTitle(title?: string): boolean {
1140 // Initial title is null, minimum length is taken care of by textarea's minLength={3}
1141 if (!title || title.length < 3) return true;
1143 const regex = new RegExp(/.*\S.*/, "g");
1145 return regex.test(title);
1148 export function siteBannerCss(banner: string): string {
1150 background-image: linear-gradient( rgba(0, 0, 0, 0.8), rgba(0, 0, 0, 0.8) ) ,url("${banner}"); \
1151 background-attachment: fixed; \
1152 background-position: top; \
1153 background-repeat: no-repeat; \
1154 background-size: 100% cover; \
1157 max-height: 100vh; \
1161 export function isBrowser() {
1162 return typeof window !== "undefined";
1165 export function setIsoData<T extends Record<string, RequestState<any>>>(
1168 // If its the browser, you need to deserialize the data from the window
1170 return window.isoData;
1171 } else return context.router.staticContext;
1174 moment.updateLocale("en", {
1195 export function saveScrollPosition(context: any) {
1196 const path: string = context.router.route.location.pathname;
1197 const y = window.scrollY;
1198 sessionStorage.setItem(`scrollPosition_${path}`, y.toString());
1201 export function restoreScrollPosition(context: any) {
1202 const path: string = context.router.route.location.pathname;
1203 const y = Number(sessionStorage.getItem(`scrollPosition_${path}`));
1204 window.scrollTo(0, y);
1207 export function showLocal(isoData: IsoData): boolean {
1208 return isoData.site_res.site_view.local_site.federation_enabled;
1211 export interface Choice {
1217 export function getUpdatedSearchId(id?: number | null, urlId?: number | null) {
1220 : ((id ?? urlId) === 0 ? undefined : id ?? urlId)?.toString();
1223 export function communityToChoice(cv: CommunityView): Choice {
1225 value: cv.community.id.toString(),
1226 label: communitySelectName(cv),
1230 export function personToChoice(pvs: PersonView): Choice {
1232 value: pvs.person.id.toString(),
1233 label: personSelectName(pvs),
1237 function fetchSearchResults(q: string, type_: SearchType) {
1238 const form: Search = {
1242 listing_type: "All",
1248 return HttpService.client.search(form);
1251 export async function fetchCommunities(q: string) {
1252 const res = await fetchSearchResults(q, "Communities");
1254 return res.state === "success" ? res.data.communities : [];
1257 export async function fetchUsers(q: string) {
1258 const res = await fetchSearchResults(q, "Users");
1260 return res.state === "success" ? res.data.users : [];
1263 export function communitySelectName(cv: CommunityView): string {
1264 return cv.community.local
1265 ? cv.community.title
1266 : `${hostname(cv.community.actor_id)}/${cv.community.title}`;
1269 export function personSelectName({
1270 person: { display_name, name, local, actor_id },
1271 }: PersonView): string {
1272 const pName = display_name ?? name;
1273 return local ? pName : `${hostname(actor_id)}/${pName}`;
1276 export function initializeSite(site?: GetSiteResponse) {
1277 UserService.Instance.myUserInfo = site?.my_user;
1278 i18n.changeLanguage(getLanguages()[0]);
1280 setupEmojiDataModel(site.custom_emojis ?? []);
1285 const SHORTNUM_SI_FORMAT = new Intl.NumberFormat("en-US", {
1286 maximumSignificantDigits: 3,
1288 notation: "compact",
1289 compactDisplay: "short",
1292 export function numToSI(value: number): string {
1293 return SHORTNUM_SI_FORMAT.format(value);
1296 export function isBanned(ps: Person): boolean {
1297 const expires = ps.ban_expires;
1298 // Add Z to convert from UTC date
1299 // TODO this check probably isn't necessary anymore
1301 if (ps.banned && new Date(expires + "Z") > new Date()) {
1311 export function myAuth(): string | undefined {
1312 return UserService.Instance.auth();
1315 export function myAuthRequired(): string {
1316 return UserService.Instance.auth(true) ?? "";
1319 export function enableDownvotes(siteRes: GetSiteResponse): boolean {
1320 return siteRes.site_view.local_site.enable_downvotes;
1323 export function enableNsfw(siteRes: GetSiteResponse): boolean {
1324 return siteRes.site_view.local_site.enable_nsfw;
1327 export function postToCommentSortType(sort: SortType): CommentSortType {
1342 export function canCreateCommunity(
1343 siteRes: GetSiteResponse,
1344 myUserInfo = UserService.Instance.myUserInfo
1346 const adminOnly = siteRes.site_view.local_site.community_creation_admin_only;
1347 // TODO: Make this check if user is logged on as well
1348 return !adminOnly || amAdmin(myUserInfo);
1351 export function isPostBlocked(
1353 myUserInfo: MyUserInfo | undefined = UserService.Instance.myUserInfo
1356 (myUserInfo?.community_blocks
1357 .map(c => c.community.id)
1358 .includes(pv.community.id) ||
1359 myUserInfo?.person_blocks
1360 .map(p => p.target.id)
1361 .includes(pv.creator.id)) ??
1366 /// Checks to make sure you can view NSFW posts. Returns true if you can.
1367 export function nsfwCheck(
1369 myUserInfo = UserService.Instance.myUserInfo
1371 const nsfw = pv.post.nsfw || pv.community.nsfw;
1372 const myShowNsfw = myUserInfo?.local_user_view.local_user.show_nsfw ?? false;
1373 return !nsfw || (nsfw && myShowNsfw);
1376 export function getRandomFromList<T>(list: T[]): T | undefined {
1377 return list.length == 0
1379 : list.at(Math.floor(Math.random() * list.length));
1383 * This shows what language you can select
1385 * Use showAll for the site form
1386 * Use showSite for the profile and community forms
1387 * Use false for both those to filter on your profile and site ones
1389 export function selectableLanguages(
1390 allLanguages: Language[],
1391 siteLanguages: number[],
1394 myUserInfo = UserService.Instance.myUserInfo
1396 const allLangIds = allLanguages.map(l => l.id);
1397 let myLangs = myUserInfo?.discussion_languages ?? allLangIds;
1398 myLangs = myLangs.length == 0 ? allLangIds : myLangs;
1399 const siteLangs = siteLanguages.length == 0 ? allLangIds : siteLanguages;
1402 return allLanguages;
1405 return allLanguages.filter(x => siteLangs.includes(x.id));
1408 .filter(x => siteLangs.includes(x.id))
1409 .filter(x => myLangs.includes(x.id));
1414 interface EmojiMartCategory {
1417 emojis: EmojiMartCustomEmoji[];
1420 interface EmojiMartCustomEmoji {
1424 skins: EmojiMartSkin[];
1427 interface EmojiMartSkin {
1431 const groupBy = <T>(
1433 predicate: (value: T, index: number, array: T[]) => string
1435 array.reduce((acc, value, index, array) => {
1436 (acc[predicate(value, index, array)] ||= []).push(value);
1438 }, {} as { [key: string]: T[] });
1440 export type QueryParams<T extends Record<string, any>> = {
1441 [key in keyof T]?: string;
1444 export function getQueryParams<T extends Record<string, any>>(processors: {
1445 [K in keyof T]: (param: string) => T[K];
1448 const searchParams = new URLSearchParams(window.location.search);
1450 return Array.from(Object.entries(processors)).reduce(
1451 (acc, [key, process]) => ({
1453 [key]: process(searchParams.get(key)),
1462 export function getQueryString<T extends Record<string, string | undefined>>(
1465 return Object.entries(obj)
1466 .filter(([, val]) => val !== undefined && val !== null)
1468 (acc, [key, val], index) => `${acc}${index > 0 ? "&" : ""}${key}=${val}`,
1473 export function isAuthPath(pathname: string) {
1474 return /create_.*|inbox|settings|admin|reports|registration_applications/g.test(
1479 export function canShare() {
1480 return isBrowser() && !!navigator.canShare;
1483 export function share(shareData: ShareData) {
1485 navigator.share(shareData);
1489 export function newVote(voteType: VoteType, myVote?: number): number {
1490 if (voteType == VoteType.Upvote) {
1491 return myVote == 1 ? 0 : 1;
1493 return myVote == -1 ? 0 : -1;
1497 export type RouteDataResponse<T extends Record<string, any>> = {
1498 [K in keyof T]: RequestState<Exclude<T[K], undefined>>;