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 { groupBy } from "./utils/helpers/group-by";
51 Tribute = require("tributejs");
54 export const favIconUrl = "/static/assets/icons/favicon.svg";
55 export const favIconPngUrl = "/static/assets/icons/apple-touch-icon.png";
57 // export const defaultFavIcon = `${window.location.protocol}//${window.location.host}${favIconPngUrl}`;
58 export const repoUrl = "https://github.com/LemmyNet";
59 export const joinLemmyUrl = "https://join-lemmy.org";
60 export const donateLemmyUrl = `${joinLemmyUrl}/donate`;
61 export const docsUrl = `${joinLemmyUrl}/docs/en/index.html`;
62 export const helpGuideUrl = `${joinLemmyUrl}/docs/en/users/01-getting-started.html`; // TODO find a way to redirect to the non-en folder
63 export const markdownHelpUrl = `${joinLemmyUrl}/docs/en/users/02-media.html`;
64 export const sortingHelpUrl = `${joinLemmyUrl}/docs/en/users/03-votes-and-ranking.html`;
65 export const archiveTodayUrl = "https://archive.today";
66 export const ghostArchiveUrl = "https://ghostarchive.org";
67 export const webArchiveUrl = "https://web.archive.org";
68 export const elementUrl = "https://element.io";
70 export const postRefetchSeconds: number = 60 * 1000;
71 export const fetchLimit = 40;
72 export const trendingFetchLimit = 6;
73 export const mentionDropdownFetchLimit = 10;
74 export const commentTreeMaxDepth = 8;
75 export const markdownFieldCharacterLimit = 50000;
76 export const maxUploadImages = 20;
77 export const concurrentImageUpload = 4;
78 export const updateUnreadCountsInterval = 30000;
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 const imageRegex = /(http)?s?:?(\/\/[^"']*\.(?:jpg|jpeg|gif|png|svg|webp))/;
232 const videoRegex = /(http)?s?:?(\/\/[^"']*\.(?:mp4|webm))/;
234 export function isImage(url: string) {
235 return imageRegex.test(url);
238 export function isVideo(url: string) {
239 return videoRegex.test(url);
242 export function validURL(str: string) {
243 return !!new URL(str);
246 export function communityRSSUrl(actorId: string, sort: string): string {
247 const url = new URL(actorId);
248 return `${url.origin}/feeds${url.pathname}.xml?sort=${sort}`;
251 export function validEmail(email: string) {
253 /^(([^\s"(),.:;<>@[\\\]]+(\.[^\s"(),.:;<>@[\\\]]+)*)|(".+"))@((\[(?:\d{1,3}\.){3}\d{1,3}])|(([\dA-Za-z\-]+\.)+[A-Za-z]{2,}))$/;
254 return re.test(String(email).toLowerCase());
257 export function capitalizeFirstLetter(str: string): string {
258 return str.charAt(0).toUpperCase() + str.slice(1);
261 export async function getSiteMetadata(url: string) {
262 const form: GetSiteMetadata = { url };
263 const client = new LemmyHttp(getHttpBase());
264 return client.getSiteMetadata(form);
267 export function getDataTypeString(dt: DataType) {
268 return dt === DataType.Post ? "Post" : "Comment";
271 export function debounce<T extends any[], R>(
272 func: (...e: T) => R,
276 // 'private' variable for instance
277 // The returned function will be able to reference this due to closure.
278 // Each call to the returned function will share this common timer.
279 let timeout: NodeJS.Timeout | null;
281 // Calling debounce returns a new anonymous function
283 // reference the context and args for the setTimeout function
284 const args = arguments;
286 // Should the function be called now? If immediate is true
287 // and not already in a timeout then the answer is: Yes
288 const callNow = immediate && !timeout;
290 // This is the basic debounce behavior where you can call this
291 // function several times, but it will only execute once
292 // [before or after imposing a delay].
293 // Each time the returned function is called, the timer starts over.
294 clearTimeout(timeout ?? undefined);
296 // Set the new timeout
297 timeout = setTimeout(function () {
298 // Inside the timeout function, clear the timeout variable
299 // which will let the next execution run when in 'immediate' mode
302 // Check if the function already ran with the immediate flag
304 // Call the original function with apply
305 // apply lets you define the 'this' object as well as the arguments
306 // (both captured before setTimeout)
307 func.apply(this, args);
311 // Immediate mode and no wait timer? Execute the function..
312 if (callNow) func.apply(this, args);
316 export function getLanguages(
318 myUserInfo = UserService.Instance.myUserInfo
320 const myLang = myUserInfo?.local_user_view.local_user.interface_language;
321 const lang = override || myLang || "browser";
323 if (lang == "browser" && isBrowser()) {
324 return getBrowserLanguages();
330 function getBrowserLanguages(): string[] {
331 // Intersect lemmy's langs, with the browser langs
332 const langs = languages ? languages.map(l => l.code) : ["en"];
334 // NOTE, mobile browsers seem to be missing this list, so append en
335 const allowedLangs = navigator.languages
337 .filter(v => langs.includes(v));
341 export async function fetchThemeList(): Promise<string[]> {
342 return fetch("/css/themelist").then(res => res.json());
345 export async function setTheme(theme: string, forceReload = false) {
349 if (theme === "browser" && !forceReload) {
352 // This is only run on a force reload
353 if (theme == "browser") {
357 const themeList = await fetchThemeList();
359 // Unload all the other themes
360 for (var i = 0; i < themeList.length; i++) {
361 const styleSheet = document.getElementById(themeList[i]);
363 styleSheet.setAttribute("disabled", "disabled");
368 .getElementById("default-light")
369 ?.setAttribute("disabled", "disabled");
370 document.getElementById("default-dark")?.setAttribute("disabled", "disabled");
372 // Load the theme dynamically
373 const cssLoc = `/css/themes/${theme}.css`;
375 loadCss(theme, cssLoc);
376 document.getElementById(theme)?.removeAttribute("disabled");
379 export function loadCss(id: string, loc: string) {
380 if (!document.getElementById(id)) {
381 var head = document.getElementsByTagName("head")[0];
382 var link = document.createElement("link");
384 link.rel = "stylesheet";
385 link.type = "text/css";
388 head.appendChild(link);
392 export function objectFlip(obj: any) {
394 Object.keys(obj).forEach(key => {
400 export function showAvatars(
401 myUserInfo = UserService.Instance.myUserInfo
403 return myUserInfo?.local_user_view.local_user.show_avatars ?? true;
406 export function showScores(
407 myUserInfo = UserService.Instance.myUserInfo
409 return myUserInfo?.local_user_view.local_user.show_scores ?? true;
412 export function isCakeDay(published: string): boolean {
413 // moment(undefined) or moment.utc(undefined) returns the current date/time
414 // moment(null) or moment.utc(null) returns null
415 const createDate = moment.utc(published).local();
416 const currentDate = moment(new Date());
419 createDate.date() === currentDate.date() &&
420 createDate.month() === currentDate.month() &&
421 createDate.year() !== currentDate.year()
425 export function toast(text: string, background: ThemeColor = "success") {
427 const backgroundColor = `var(--${background})`;
430 backgroundColor: backgroundColor,
438 export function pictrsDeleteToast(filename: string, deleteUrl: string) {
440 const clickToDeleteText = i18n.t("click_to_delete_picture", { filename });
441 const deletePictureText = i18n.t("picture_deleted", {
444 const failedDeletePictureText = i18n.t("failed_to_delete_picture", {
448 const backgroundColor = `var(--light)`;
450 const toast = Toastify({
451 text: clickToDeleteText,
452 backgroundColor: backgroundColor,
458 fetch(deleteUrl).then(res => {
460 if (res.ok === true) {
461 alert(deletePictureText);
463 alert(failedDeletePictureText);
475 export function setupTribute() {
477 noMatchTemplate: function () {
484 menuItemTemplate: (item: any) => {
485 const shortName = `:${item.original.key}:`;
486 return `${item.original.val} ${shortName}`;
488 selectTemplate: (item: any) => {
489 const customEmoji = customEmojisLookup.get(
492 if (customEmoji == undefined) return `${item.original.val}`;
494 return `![${customEmoji.alt_text}](${customEmoji.image_url} "${customEmoji.shortcode}")`;
496 values: Object.entries(emojiShortName)
498 return { key: e[1], val: e[0] };
501 Array.from(customEmojisLookup.entries()).map(k => ({
503 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}" />`,
507 autocompleteMode: true,
509 // menuItemLimit: mentionDropdownFetchLimit,
510 menuShowMinLength: 2,
515 selectTemplate: (item: any) => {
516 const it: PersonTribute = item.original;
517 return `[${it.key}](${it.view.person.actor_id})`;
519 values: debounce(async (text: string, cb: any) => {
520 cb(await personSearch(text));
523 autocompleteMode: true,
525 // menuItemLimit: mentionDropdownFetchLimit,
526 menuShowMinLength: 2,
532 selectTemplate: (item: any) => {
533 const it: CommunityTribute = item.original;
534 return `[${it.key}](${it.view.community.actor_id})`;
536 values: debounce(async (text: string, cb: any) => {
537 cb(await communitySearch(text));
540 autocompleteMode: true,
542 // menuItemLimit: mentionDropdownFetchLimit,
543 menuShowMinLength: 2,
549 function setupEmojiDataModel(custom_emoji_views: CustomEmojiView[]) {
550 const groupedEmojis = groupBy(
552 x => x.custom_emoji.category
554 for (const [category, emojis] of Object.entries(groupedEmojis)) {
558 emojis: emojis.map(emoji => ({
559 id: emoji.custom_emoji.shortcode,
560 name: emoji.custom_emoji.shortcode,
561 keywords: emoji.keywords.map(x => x.keyword),
562 skins: [{ src: emoji.custom_emoji.image_url }],
566 customEmojisLookup = new Map(
567 custom_emoji_views.map(view => [view.custom_emoji.shortcode, view])
571 export function updateEmojiDataModel(custom_emoji_view: CustomEmojiView) {
572 const emoji: EmojiMartCustomEmoji = {
573 id: custom_emoji_view.custom_emoji.shortcode,
574 name: custom_emoji_view.custom_emoji.shortcode,
575 keywords: custom_emoji_view.keywords.map(x => x.keyword),
576 skins: [{ src: custom_emoji_view.custom_emoji.image_url }],
578 const categoryIndex = customEmojis.findIndex(
579 x => x.id == custom_emoji_view.custom_emoji.category
581 if (categoryIndex == -1) {
583 id: custom_emoji_view.custom_emoji.category,
584 name: custom_emoji_view.custom_emoji.category,
588 const emojiIndex = customEmojis[categoryIndex].emojis.findIndex(
589 x => x.id == custom_emoji_view.custom_emoji.shortcode
591 if (emojiIndex == -1) {
592 customEmojis[categoryIndex].emojis.push(emoji);
594 customEmojis[categoryIndex].emojis[emojiIndex] = emoji;
597 customEmojisLookup.set(
598 custom_emoji_view.custom_emoji.shortcode,
603 export function removeFromEmojiDataModel(id: number) {
604 let view: CustomEmojiView | undefined;
605 for (const item of customEmojisLookup.values()) {
606 if (item.custom_emoji.id === id) {
612 const categoryIndex = customEmojis.findIndex(
613 x => x.id == view?.custom_emoji.category
615 const emojiIndex = customEmojis[categoryIndex].emojis.findIndex(
616 x => x.id == view?.custom_emoji.shortcode
618 customEmojis[categoryIndex].emojis = customEmojis[
620 ].emojis.splice(emojiIndex, 1);
622 customEmojisLookup.delete(view?.custom_emoji.shortcode);
625 function setupMarkdown() {
626 const markdownItConfig: MarkdownIt.Options = {
632 const emojiDefs = Array.from(customEmojisLookup.entries()).reduce(
633 (main, [key, value]) => ({ ...main, [key]: value }),
636 md = new MarkdownIt(markdownItConfig)
637 .use(markdown_it_sub)
638 .use(markdown_it_sup)
639 .use(markdown_it_footnote)
640 .use(markdown_it_html5_embed, html5EmbedConfig)
641 .use(markdown_it_container, "spoiler", spoilerConfig)
642 .use(markdown_it_emoji, {
646 mdNoImages = new MarkdownIt(markdownItConfig)
647 .use(markdown_it_sub)
648 .use(markdown_it_sup)
649 .use(markdown_it_footnote)
650 .use(markdown_it_html5_embed, html5EmbedConfig)
651 .use(markdown_it_container, "spoiler", spoilerConfig)
652 .use(markdown_it_emoji, {
656 var defaultRenderer = md.renderer.rules.image;
657 md.renderer.rules.image = function (
660 options: MarkdownIt.Options,
664 //Provide custom renderer for our emojis to allow us to add a css class and force size dimensions on them.
665 const item = tokens[idx] as any;
666 const title = item.attrs.length >= 3 ? item.attrs[2][1] : "";
667 const src: string = item.attrs[0][1];
668 const isCustomEmoji = customEmojisLookup.get(title) != undefined;
669 if (!isCustomEmoji) {
670 return defaultRenderer?.(tokens, idx, options, env, self) ?? "";
672 const alt_text = item.content;
673 return `<img class="icon icon-emoji" src="${src}" title="${title}" alt="${alt_text}"/>`;
677 export function getEmojiMart(
678 onEmojiSelect: (e: any) => void,
679 customPickerOptions: any = {}
681 const pickerOptions = {
682 ...customPickerOptions,
683 onEmojiSelect: onEmojiSelect,
684 custom: customEmojis,
686 return new Picker(pickerOptions);
689 var tippyInstance: any;
691 tippyInstance = tippy("[data-tippy-content]");
694 export function setupTippy() {
696 tippyInstance.forEach((e: any) => e.destroy());
697 tippyInstance = tippy("[data-tippy-content]", {
699 // Display on "long press"
700 touch: ["hold", 500],
705 interface PersonTribute {
710 async function personSearch(text: string): Promise<PersonTribute[]> {
711 const usersResponse = await fetchUsers(text);
713 return usersResponse.map(pv => ({
714 key: `@${pv.person.name}@${hostname(pv.person.actor_id)}`,
719 interface CommunityTribute {
724 async function communitySearch(text: string): Promise<CommunityTribute[]> {
725 const communitiesResponse = await fetchCommunities(text);
727 return communitiesResponse.map(cv => ({
728 key: `!${cv.community.name}@${hostname(cv.community.actor_id)}`,
733 export function getRecipientIdFromProps(props: any): number {
734 return props.match.params.recipient_id
735 ? Number(props.match.params.recipient_id)
739 export function getIdFromProps(props: any): number | undefined {
740 const id = props.match.params.post_id;
741 return id ? Number(id) : undefined;
744 export function getCommentIdFromProps(props: any): number | undefined {
745 const id = props.match.params.comment_id;
746 return id ? Number(id) : undefined;
749 type ImmutableListKey =
758 | "private_message_report"
759 | "registration_application";
761 function editListImmutable<
762 T extends { [key in F]: { id: number } },
763 F extends ImmutableListKey
764 >(fieldName: F, data: T, list: T[]): T[] {
766 ...list.map(c => (c[fieldName].id === data[fieldName].id ? data : c)),
770 export function editComment(
772 comments: CommentView[]
774 return editListImmutable("comment", data, comments);
777 export function editCommentReply(
778 data: CommentReplyView,
779 replies: CommentReplyView[]
780 ): CommentReplyView[] {
781 return editListImmutable("comment_reply", data, replies);
784 interface WithComment {
786 counts: CommentAggregates;
791 export function editMention(
792 data: PersonMentionView,
793 comments: PersonMentionView[]
794 ): PersonMentionView[] {
795 return editListImmutable("person_mention", data, comments);
798 export function editCommunity(
800 communities: CommunityView[]
802 return editListImmutable("community", data, communities);
805 export function editPrivateMessage(
806 data: PrivateMessageView,
807 messages: PrivateMessageView[]
808 ): PrivateMessageView[] {
809 return editListImmutable("private_message", data, messages);
812 export function editPost(data: PostView, posts: PostView[]): PostView[] {
813 return editListImmutable("post", data, posts);
816 export function editPostReport(
817 data: PostReportView,
818 reports: PostReportView[]
820 return editListImmutable("post_report", data, reports);
823 export function editCommentReport(
824 data: CommentReportView,
825 reports: CommentReportView[]
826 ): CommentReportView[] {
827 return editListImmutable("comment_report", data, reports);
830 export function editPrivateMessageReport(
831 data: PrivateMessageReportView,
832 reports: PrivateMessageReportView[]
833 ): PrivateMessageReportView[] {
834 return editListImmutable("private_message_report", data, reports);
837 export function editRegistrationApplication(
838 data: RegistrationApplicationView,
839 apps: RegistrationApplicationView[]
840 ): RegistrationApplicationView[] {
841 return editListImmutable("registration_application", data, apps);
844 export function editWith<D extends WithComment, L extends WithComment>(
845 { comment, counts, saved, my_vote }: D,
850 c.comment.id === comment.id
851 ? { ...c, comment, counts, saved, my_vote }
857 export function updatePersonBlock(
858 data: BlockPersonResponse,
859 myUserInfo: MyUserInfo | undefined = UserService.Instance.myUserInfo
863 myUserInfo.person_blocks.push({
864 person: myUserInfo.local_user_view.person,
865 target: data.person_view.person,
867 toast(`${i18n.t("blocked")} ${data.person_view.person.name}`);
869 myUserInfo.person_blocks = myUserInfo.person_blocks.filter(
870 i => i.target.id !== data.person_view.person.id
872 toast(`${i18n.t("unblocked")} ${data.person_view.person.name}`);
877 export function updateCommunityBlock(
878 data: BlockCommunityResponse,
879 myUserInfo: MyUserInfo | undefined = UserService.Instance.myUserInfo
883 myUserInfo.community_blocks.push({
884 person: myUserInfo.local_user_view.person,
885 community: data.community_view.community,
887 toast(`${i18n.t("blocked")} ${data.community_view.community.name}`);
889 myUserInfo.community_blocks = myUserInfo.community_blocks.filter(
890 i => i.community.id !== data.community_view.community.id
892 toast(`${i18n.t("unblocked")} ${data.community_view.community.name}`);
897 export function commentsToFlatNodes(comments: CommentView[]): CommentNodeI[] {
898 const nodes: CommentNodeI[] = [];
899 for (const comment of comments) {
900 nodes.push({ comment_view: comment, children: [], depth: 0 });
905 export function convertCommentSortType(sort: SortType): CommentSortType {
910 sort == "TopMonth" ||
914 } else if (sort == "New") {
916 } else if (sort == "Hot" || sort == "Active") {
923 export function buildCommentsTree(
924 comments: CommentView[],
925 parentComment: boolean
927 const map = new Map<number, CommentNodeI>();
928 const depthOffset = !parentComment
930 : getDepthFromComment(comments[0].comment) ?? 0;
932 for (const comment_view of comments) {
933 const depthI = getDepthFromComment(comment_view.comment) ?? 0;
934 const depth = depthI ? depthI - depthOffset : 0;
935 const node: CommentNodeI = {
940 map.set(comment_view.comment.id, { ...node });
943 const tree: CommentNodeI[] = [];
945 // if its a parent comment fetch, then push the first comment to the top node.
947 const cNode = map.get(comments[0].comment.id);
953 for (const comment_view of comments) {
954 const child = map.get(comment_view.comment.id);
956 const parent_id = getCommentParentId(comment_view.comment);
958 const parent = map.get(parent_id);
959 // Necessary because blocked comment might not exist
961 parent.children.push(child);
964 if (!parentComment) {
974 export function getCommentParentId(comment?: CommentI): number | undefined {
975 const split = comment?.path.split(".");
979 return split && split.length > 1
980 ? Number(split.at(split.length - 2))
984 export function getDepthFromComment(comment?: CommentI): number | undefined {
985 const len = comment?.path.split(".").length;
986 return len ? len - 2 : undefined;
989 // TODO make immutable
990 export function insertCommentIntoTree(
991 tree: CommentNodeI[],
993 parentComment: boolean
995 // Building a fake node to be used for later
996 const node: CommentNodeI = {
1002 const parentId = getCommentParentId(cv.comment);
1004 const parent_comment = searchCommentTree(tree, parentId);
1005 if (parent_comment) {
1006 node.depth = parent_comment.depth + 1;
1007 parent_comment.children.unshift(node);
1009 } else if (!parentComment) {
1014 export function searchCommentTree(
1015 tree: CommentNodeI[],
1017 ): CommentNodeI | undefined {
1018 for (const node of tree) {
1019 if (node.comment_view.comment.id === id) {
1023 for (const child of node.children) {
1024 const res = searchCommentTree([child], id);
1034 export const colorList: string[] = [
1044 function hsl(num: number) {
1045 return `hsla(${num}, 35%, 50%, 0.5)`;
1048 export function hostname(url: string): string {
1049 const cUrl = new URL(url);
1050 return cUrl.port ? `${cUrl.hostname}:${cUrl.port}` : `${cUrl.hostname}`;
1053 export function validTitle(title?: string): boolean {
1054 // Initial title is null, minimum length is taken care of by textarea's minLength={3}
1055 if (!title || title.length < 3) return true;
1057 const regex = new RegExp(/.*\S.*/, "g");
1059 return regex.test(title);
1062 export function siteBannerCss(banner: string): string {
1064 background-image: linear-gradient( rgba(0, 0, 0, 0.8), rgba(0, 0, 0, 0.8) ) ,url("${banner}"); \
1065 background-attachment: fixed; \
1066 background-position: top; \
1067 background-repeat: no-repeat; \
1068 background-size: 100% cover; \
1071 max-height: 100vh; \
1075 export function setIsoData(context: any): IsoData {
1076 // If its the browser, you need to deserialize the data from the window
1078 return window.isoData;
1079 } else return context.router.staticContext;
1082 moment.updateLocale("en", {
1103 export function saveScrollPosition(context: any) {
1104 const path: string = context.router.route.location.pathname;
1105 const y = window.scrollY;
1106 sessionStorage.setItem(`scrollPosition_${path}`, y.toString());
1109 export function restoreScrollPosition(context: any) {
1110 const path: string = context.router.route.location.pathname;
1111 const y = Number(sessionStorage.getItem(`scrollPosition_${path}`));
1112 window.scrollTo(0, y);
1115 export function showLocal(isoData: IsoData): boolean {
1116 return isoData.site_res.site_view.local_site.federation_enabled;
1119 export interface Choice {
1125 export function getUpdatedSearchId(id?: number | null, urlId?: number | null) {
1128 : ((id ?? urlId) === 0 ? undefined : id ?? urlId)?.toString();
1131 export function communityToChoice(cv: CommunityView): Choice {
1133 value: cv.community.id.toString(),
1134 label: communitySelectName(cv),
1138 export function personToChoice(pvs: PersonView): Choice {
1140 value: pvs.person.id.toString(),
1141 label: personSelectName(pvs),
1145 function fetchSearchResults(q: string, type_: SearchType) {
1146 const form: Search = {
1150 listing_type: "All",
1156 return HttpService.client.search(form);
1159 export async function fetchCommunities(q: string) {
1160 const res = await fetchSearchResults(q, "Communities");
1162 return res.state === "success" ? res.data.communities : [];
1165 export async function fetchUsers(q: string) {
1166 const res = await fetchSearchResults(q, "Users");
1168 return res.state === "success" ? res.data.users : [];
1171 export function communitySelectName(cv: CommunityView): string {
1172 return cv.community.local
1173 ? cv.community.title
1174 : `${hostname(cv.community.actor_id)}/${cv.community.title}`;
1177 export function personSelectName({
1178 person: { display_name, name, local, actor_id },
1179 }: PersonView): string {
1180 const pName = display_name ?? name;
1181 return local ? pName : `${hostname(actor_id)}/${pName}`;
1184 export function initializeSite(site?: GetSiteResponse) {
1185 UserService.Instance.myUserInfo = site?.my_user;
1186 i18n.changeLanguage(getLanguages()[0]);
1188 setupEmojiDataModel(site.custom_emojis ?? []);
1193 const SHORTNUM_SI_FORMAT = new Intl.NumberFormat("en-US", {
1194 maximumSignificantDigits: 3,
1196 notation: "compact",
1197 compactDisplay: "short",
1200 export function numToSI(value: number): string {
1201 return SHORTNUM_SI_FORMAT.format(value);
1204 export function myAuth(): string | undefined {
1205 return UserService.Instance.auth();
1208 export function myAuthRequired(): string {
1209 return UserService.Instance.auth(true) ?? "";
1212 export function enableDownvotes(siteRes: GetSiteResponse): boolean {
1213 return siteRes.site_view.local_site.enable_downvotes;
1216 export function enableNsfw(siteRes: GetSiteResponse): boolean {
1217 return siteRes.site_view.local_site.enable_nsfw;
1220 export function postToCommentSortType(sort: SortType): CommentSortType {
1235 export function isPostBlocked(
1237 myUserInfo: MyUserInfo | undefined = UserService.Instance.myUserInfo
1240 (myUserInfo?.community_blocks
1241 .map(c => c.community.id)
1242 .includes(pv.community.id) ||
1243 myUserInfo?.person_blocks
1244 .map(p => p.target.id)
1245 .includes(pv.creator.id)) ??
1250 /// Checks to make sure you can view NSFW posts. Returns true if you can.
1251 export function nsfwCheck(
1253 myUserInfo = UserService.Instance.myUserInfo
1255 const nsfw = pv.post.nsfw || pv.community.nsfw;
1256 const myShowNsfw = myUserInfo?.local_user_view.local_user.show_nsfw ?? false;
1257 return !nsfw || (nsfw && myShowNsfw);
1260 export function getRandomFromList<T>(list: T[]): T | undefined {
1261 return list.length == 0
1263 : list.at(Math.floor(Math.random() * list.length));
1267 * This shows what language you can select
1269 * Use showAll for the site form
1270 * Use showSite for the profile and community forms
1271 * Use false for both those to filter on your profile and site ones
1273 export function selectableLanguages(
1274 allLanguages: Language[],
1275 siteLanguages: number[],
1278 myUserInfo = UserService.Instance.myUserInfo
1280 const allLangIds = allLanguages.map(l => l.id);
1281 let myLangs = myUserInfo?.discussion_languages ?? allLangIds;
1282 myLangs = myLangs.length == 0 ? allLangIds : myLangs;
1283 const siteLangs = siteLanguages.length == 0 ? allLangIds : siteLanguages;
1286 return allLanguages;
1289 return allLanguages.filter(x => siteLangs.includes(x.id));
1292 .filter(x => siteLangs.includes(x.id))
1293 .filter(x => myLangs.includes(x.id));
1298 interface EmojiMartCategory {
1301 emojis: EmojiMartCustomEmoji[];
1304 interface EmojiMartCustomEmoji {
1308 skins: EmojiMartSkin[];
1311 interface EmojiMartSkin {
1315 export function isAuthPath(pathname: string) {
1316 return /create_.*|inbox|settings|admin|reports|registration_applications/g.test(
1321 export function newVote(voteType: VoteType, myVote?: number): number {
1322 if (voteType == VoteType.Upvote) {
1323 return myVote == 1 ? 0 : 1;
1325 return myVote == -1 ? 0 : -1;