1 import { Picker } from "emoji-mart";
2 import emojiShortName from "emoji-short-name";
4 BlockCommunityResponse,
23 PrivateMessageReportView,
25 RegistrationApplicationView,
29 } from "lemmy-js-client";
30 import { default as MarkdownIt } from "markdown-it";
31 import markdown_it_container from "markdown-it-container";
32 import markdown_it_emoji from "markdown-it-emoji/bare";
33 import markdown_it_footnote from "markdown-it-footnote";
34 import markdown_it_html5_embed from "markdown-it-html5-embed";
35 import markdown_it_sub from "markdown-it-sub";
36 import markdown_it_sup from "markdown-it-sup";
37 import Renderer from "markdown-it/lib/renderer";
38 import Token from "markdown-it/lib/token";
39 import moment from "moment";
40 import tippy from "tippy.js";
41 import Toastify from "toastify-js";
42 import { getHttpBase } from "./env";
43 import { i18n } from "./i18next";
44 import { CommentNodeI, DataType, IsoData, VoteType } from "./interfaces";
45 import { HttpService, UserService } from "./services";
46 import { isBrowser } from "./utils/browser/is-browser";
47 import { 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))/;
233 const tldRegex = /([a-z0-9]+\.)*[a-z0-9]+\.[a-z]+/;
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 validInstanceTLD(str: string) {
248 return tldRegex.test(str);
251 export function communityRSSUrl(actorId: string, sort: string): string {
252 const url = new URL(actorId);
253 return `${url.origin}/feeds${url.pathname}.xml?sort=${sort}`;
256 export function validEmail(email: string) {
258 /^(([^\s"(),.:;<>@[\\\]]+(\.[^\s"(),.:;<>@[\\\]]+)*)|(".+"))@((\[(?:\d{1,3}\.){3}\d{1,3}])|(([\dA-Za-z\-]+\.)+[A-Za-z]{2,}))$/;
259 return re.test(String(email).toLowerCase());
262 export function capitalizeFirstLetter(str: string): string {
263 return str.charAt(0).toUpperCase() + str.slice(1);
266 export async function getSiteMetadata(url: string) {
267 const form: GetSiteMetadata = { url };
268 const client = new LemmyHttp(getHttpBase());
269 return client.getSiteMetadata(form);
272 export function getDataTypeString(dt: DataType) {
273 return dt === DataType.Post ? "Post" : "Comment";
276 export function debounce<T extends any[], R>(
277 func: (...e: T) => R,
281 // 'private' variable for instance
282 // The returned function will be able to reference this due to closure.
283 // Each call to the returned function will share this common timer.
284 let timeout: NodeJS.Timeout | null;
286 // Calling debounce returns a new anonymous function
288 // reference the context and args for the setTimeout function
289 const args = arguments;
291 // Should the function be called now? If immediate is true
292 // and not already in a timeout then the answer is: Yes
293 const callNow = immediate && !timeout;
295 // This is the basic debounce behavior where you can call this
296 // function several times, but it will only execute once
297 // [before or after imposing a delay].
298 // Each time the returned function is called, the timer starts over.
299 clearTimeout(timeout ?? undefined);
301 // Set the new timeout
302 timeout = setTimeout(function () {
303 // Inside the timeout function, clear the timeout variable
304 // which will let the next execution run when in 'immediate' mode
307 // Check if the function already ran with the immediate flag
309 // Call the original function with apply
310 // apply lets you define the 'this' object as well as the arguments
311 // (both captured before setTimeout)
312 func.apply(this, args);
316 // Immediate mode and no wait timer? Execute the function..
317 if (callNow) func.apply(this, args);
321 export async function fetchThemeList(): Promise<string[]> {
322 return fetch("/css/themelist").then(res => res.json());
325 export async function setTheme(theme: string, forceReload = false) {
329 if (theme === "browser" && !forceReload) {
332 // This is only run on a force reload
333 if (theme == "browser") {
337 const themeList = await fetchThemeList();
339 // Unload all the other themes
340 for (var i = 0; i < themeList.length; i++) {
341 const styleSheet = document.getElementById(themeList[i]);
343 styleSheet.setAttribute("disabled", "disabled");
348 .getElementById("default-light")
349 ?.setAttribute("disabled", "disabled");
350 document.getElementById("default-dark")?.setAttribute("disabled", "disabled");
352 // Load the theme dynamically
353 const cssLoc = `/css/themes/${theme}.css`;
355 loadCss(theme, cssLoc);
356 document.getElementById(theme)?.removeAttribute("disabled");
359 export function loadCss(id: string, loc: string) {
360 if (!document.getElementById(id)) {
361 var head = document.getElementsByTagName("head")[0];
362 var link = document.createElement("link");
364 link.rel = "stylesheet";
365 link.type = "text/css";
368 head.appendChild(link);
372 export function objectFlip(obj: any) {
374 Object.keys(obj).forEach(key => {
380 export function showAvatars(
381 myUserInfo = UserService.Instance.myUserInfo
383 return myUserInfo?.local_user_view.local_user.show_avatars ?? true;
386 export function showScores(
387 myUserInfo = UserService.Instance.myUserInfo
389 return myUserInfo?.local_user_view.local_user.show_scores ?? true;
392 export function isCakeDay(published: string): boolean {
393 // moment(undefined) or moment.utc(undefined) returns the current date/time
394 // moment(null) or moment.utc(null) returns null
395 const createDate = moment.utc(published).local();
396 const currentDate = moment(new Date());
399 createDate.date() === currentDate.date() &&
400 createDate.month() === currentDate.month() &&
401 createDate.year() !== currentDate.year()
405 export function toast(text: string, background: ThemeColor = "success") {
407 const backgroundColor = `var(--${background})`;
410 backgroundColor: backgroundColor,
418 export function pictrsDeleteToast(filename: string, deleteUrl: string) {
420 const clickToDeleteText = i18n.t("click_to_delete_picture", { filename });
421 const deletePictureText = i18n.t("picture_deleted", {
424 const failedDeletePictureText = i18n.t("failed_to_delete_picture", {
428 const backgroundColor = `var(--light)`;
430 const toast = Toastify({
431 text: clickToDeleteText,
432 backgroundColor: backgroundColor,
438 fetch(deleteUrl).then(res => {
440 if (res.ok === true) {
441 alert(deletePictureText);
443 alert(failedDeletePictureText);
455 export function setupTribute() {
457 noMatchTemplate: function () {
464 menuItemTemplate: (item: any) => {
465 const shortName = `:${item.original.key}:`;
466 return `${item.original.val} ${shortName}`;
468 selectTemplate: (item: any) => {
469 const customEmoji = customEmojisLookup.get(
472 if (customEmoji == undefined) return `${item.original.val}`;
474 return `![${customEmoji.alt_text}](${customEmoji.image_url} "${customEmoji.shortcode}")`;
476 values: Object.entries(emojiShortName)
478 return { key: e[1], val: e[0] };
481 Array.from(customEmojisLookup.entries()).map(k => ({
483 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}" />`,
487 autocompleteMode: true,
489 // menuItemLimit: mentionDropdownFetchLimit,
490 menuShowMinLength: 2,
495 selectTemplate: (item: any) => {
496 const it: PersonTribute = item.original;
497 return `[${it.key}](${it.view.person.actor_id})`;
499 values: debounce(async (text: string, cb: any) => {
500 cb(await personSearch(text));
503 autocompleteMode: true,
505 // menuItemLimit: mentionDropdownFetchLimit,
506 menuShowMinLength: 2,
512 selectTemplate: (item: any) => {
513 const it: CommunityTribute = item.original;
514 return `[${it.key}](${it.view.community.actor_id})`;
516 values: debounce(async (text: string, cb: any) => {
517 cb(await communitySearch(text));
520 autocompleteMode: true,
522 // menuItemLimit: mentionDropdownFetchLimit,
523 menuShowMinLength: 2,
529 function setupEmojiDataModel(custom_emoji_views: CustomEmojiView[]) {
530 const groupedEmojis = groupBy(
532 x => x.custom_emoji.category
534 for (const [category, emojis] of Object.entries(groupedEmojis)) {
538 emojis: emojis.map(emoji => ({
539 id: emoji.custom_emoji.shortcode,
540 name: emoji.custom_emoji.shortcode,
541 keywords: emoji.keywords.map(x => x.keyword),
542 skins: [{ src: emoji.custom_emoji.image_url }],
546 customEmojisLookup = new Map(
547 custom_emoji_views.map(view => [view.custom_emoji.shortcode, view])
551 export function updateEmojiDataModel(custom_emoji_view: CustomEmojiView) {
552 const emoji: EmojiMartCustomEmoji = {
553 id: custom_emoji_view.custom_emoji.shortcode,
554 name: custom_emoji_view.custom_emoji.shortcode,
555 keywords: custom_emoji_view.keywords.map(x => x.keyword),
556 skins: [{ src: custom_emoji_view.custom_emoji.image_url }],
558 const categoryIndex = customEmojis.findIndex(
559 x => x.id == custom_emoji_view.custom_emoji.category
561 if (categoryIndex == -1) {
563 id: custom_emoji_view.custom_emoji.category,
564 name: custom_emoji_view.custom_emoji.category,
568 const emojiIndex = customEmojis[categoryIndex].emojis.findIndex(
569 x => x.id == custom_emoji_view.custom_emoji.shortcode
571 if (emojiIndex == -1) {
572 customEmojis[categoryIndex].emojis.push(emoji);
574 customEmojis[categoryIndex].emojis[emojiIndex] = emoji;
577 customEmojisLookup.set(
578 custom_emoji_view.custom_emoji.shortcode,
583 export function removeFromEmojiDataModel(id: number) {
584 let view: CustomEmojiView | undefined;
585 for (const item of customEmojisLookup.values()) {
586 if (item.custom_emoji.id === id) {
592 const categoryIndex = customEmojis.findIndex(
593 x => x.id == view?.custom_emoji.category
595 const emojiIndex = customEmojis[categoryIndex].emojis.findIndex(
596 x => x.id == view?.custom_emoji.shortcode
598 customEmojis[categoryIndex].emojis = customEmojis[
600 ].emojis.splice(emojiIndex, 1);
602 customEmojisLookup.delete(view?.custom_emoji.shortcode);
605 function setupMarkdown() {
606 const markdownItConfig: MarkdownIt.Options = {
612 const emojiDefs = Array.from(customEmojisLookup.entries()).reduce(
613 (main, [key, value]) => ({ ...main, [key]: value }),
616 md = new MarkdownIt(markdownItConfig)
617 .use(markdown_it_sub)
618 .use(markdown_it_sup)
619 .use(markdown_it_footnote)
620 .use(markdown_it_html5_embed, html5EmbedConfig)
621 .use(markdown_it_container, "spoiler", spoilerConfig)
622 .use(markdown_it_emoji, {
626 mdNoImages = new MarkdownIt(markdownItConfig)
627 .use(markdown_it_sub)
628 .use(markdown_it_sup)
629 .use(markdown_it_footnote)
630 .use(markdown_it_html5_embed, html5EmbedConfig)
631 .use(markdown_it_container, "spoiler", spoilerConfig)
632 .use(markdown_it_emoji, {
636 const defaultRenderer = md.renderer.rules.image;
637 md.renderer.rules.image = function (
640 options: MarkdownIt.Options,
644 //Provide custom renderer for our emojis to allow us to add a css class and force size dimensions on them.
645 const item = tokens[idx] as any;
646 const title = item.attrs.length >= 3 ? item.attrs[2][1] : "";
647 const src: string = item.attrs[0][1];
648 const isCustomEmoji = customEmojisLookup.get(title) != undefined;
649 if (!isCustomEmoji) {
650 return defaultRenderer?.(tokens, idx, options, env, self) ?? "";
652 const alt_text = item.content;
653 return `<img class="icon icon-emoji" src="${src}" title="${title}" alt="${alt_text}"/>`;
655 md.renderer.rules.table_open = function () {
656 return '<table class="table">';
660 export function getEmojiMart(
661 onEmojiSelect: (e: any) => void,
662 customPickerOptions: any = {}
664 const pickerOptions = {
665 ...customPickerOptions,
666 onEmojiSelect: onEmojiSelect,
667 custom: customEmojis,
669 return new Picker(pickerOptions);
672 var tippyInstance: any;
674 tippyInstance = tippy("[data-tippy-content]");
677 export function setupTippy() {
679 tippyInstance.forEach((e: any) => e.destroy());
680 tippyInstance = tippy("[data-tippy-content]", {
682 // Display on "long press"
683 touch: ["hold", 500],
688 interface PersonTribute {
693 async function personSearch(text: string): Promise<PersonTribute[]> {
694 const usersResponse = await fetchUsers(text);
696 return usersResponse.map(pv => ({
697 key: `@${pv.person.name}@${hostname(pv.person.actor_id)}`,
702 interface CommunityTribute {
707 async function communitySearch(text: string): Promise<CommunityTribute[]> {
708 const communitiesResponse = await fetchCommunities(text);
710 return communitiesResponse.map(cv => ({
711 key: `!${cv.community.name}@${hostname(cv.community.actor_id)}`,
716 export function getRecipientIdFromProps(props: any): number {
717 return props.match.params.recipient_id
718 ? Number(props.match.params.recipient_id)
722 export function getIdFromProps(props: any): number | undefined {
723 const id = props.match.params.post_id;
724 return id ? Number(id) : undefined;
727 export function getCommentIdFromProps(props: any): number | undefined {
728 const id = props.match.params.comment_id;
729 return id ? Number(id) : undefined;
732 type ImmutableListKey =
741 | "private_message_report"
742 | "registration_application";
744 function editListImmutable<
745 T extends { [key in F]: { id: number } },
746 F extends ImmutableListKey
747 >(fieldName: F, data: T, list: T[]): T[] {
749 ...list.map(c => (c[fieldName].id === data[fieldName].id ? data : c)),
753 export function editComment(
755 comments: CommentView[]
757 return editListImmutable("comment", data, comments);
760 export function editCommentReply(
761 data: CommentReplyView,
762 replies: CommentReplyView[]
763 ): CommentReplyView[] {
764 return editListImmutable("comment_reply", data, replies);
767 interface WithComment {
769 counts: CommentAggregates;
774 export function editMention(
775 data: PersonMentionView,
776 comments: PersonMentionView[]
777 ): PersonMentionView[] {
778 return editListImmutable("person_mention", data, comments);
781 export function editCommunity(
783 communities: CommunityView[]
785 return editListImmutable("community", data, communities);
788 export function editPrivateMessage(
789 data: PrivateMessageView,
790 messages: PrivateMessageView[]
791 ): PrivateMessageView[] {
792 return editListImmutable("private_message", data, messages);
795 export function editPost(data: PostView, posts: PostView[]): PostView[] {
796 return editListImmutable("post", data, posts);
799 export function editPostReport(
800 data: PostReportView,
801 reports: PostReportView[]
803 return editListImmutable("post_report", data, reports);
806 export function editCommentReport(
807 data: CommentReportView,
808 reports: CommentReportView[]
809 ): CommentReportView[] {
810 return editListImmutable("comment_report", data, reports);
813 export function editPrivateMessageReport(
814 data: PrivateMessageReportView,
815 reports: PrivateMessageReportView[]
816 ): PrivateMessageReportView[] {
817 return editListImmutable("private_message_report", data, reports);
820 export function editRegistrationApplication(
821 data: RegistrationApplicationView,
822 apps: RegistrationApplicationView[]
823 ): RegistrationApplicationView[] {
824 return editListImmutable("registration_application", data, apps);
827 export function editWith<D extends WithComment, L extends WithComment>(
828 { comment, counts, saved, my_vote }: D,
833 c.comment.id === comment.id
834 ? { ...c, comment, counts, saved, my_vote }
840 export function updatePersonBlock(
841 data: BlockPersonResponse,
842 myUserInfo: MyUserInfo | undefined = UserService.Instance.myUserInfo
846 myUserInfo.person_blocks.push({
847 person: myUserInfo.local_user_view.person,
848 target: data.person_view.person,
850 toast(`${i18n.t("blocked")} ${data.person_view.person.name}`);
852 myUserInfo.person_blocks = myUserInfo.person_blocks.filter(
853 i => i.target.id !== data.person_view.person.id
855 toast(`${i18n.t("unblocked")} ${data.person_view.person.name}`);
860 export function updateCommunityBlock(
861 data: BlockCommunityResponse,
862 myUserInfo: MyUserInfo | undefined = UserService.Instance.myUserInfo
866 myUserInfo.community_blocks.push({
867 person: myUserInfo.local_user_view.person,
868 community: data.community_view.community,
870 toast(`${i18n.t("blocked")} ${data.community_view.community.name}`);
872 myUserInfo.community_blocks = myUserInfo.community_blocks.filter(
873 i => i.community.id !== data.community_view.community.id
875 toast(`${i18n.t("unblocked")} ${data.community_view.community.name}`);
880 export function commentsToFlatNodes(comments: CommentView[]): CommentNodeI[] {
881 const nodes: CommentNodeI[] = [];
882 for (const comment of comments) {
883 nodes.push({ comment_view: comment, children: [], depth: 0 });
888 export function convertCommentSortType(sort: SortType): CommentSortType {
893 sort == "TopMonth" ||
897 } else if (sort == "New") {
899 } else if (sort == "Hot" || sort == "Active") {
906 export function buildCommentsTree(
907 comments: CommentView[],
908 parentComment: boolean
910 const map = new Map<number, CommentNodeI>();
911 const depthOffset = !parentComment
913 : getDepthFromComment(comments[0].comment) ?? 0;
915 for (const comment_view of comments) {
916 const depthI = getDepthFromComment(comment_view.comment) ?? 0;
917 const depth = depthI ? depthI - depthOffset : 0;
918 const node: CommentNodeI = {
923 map.set(comment_view.comment.id, { ...node });
926 const tree: CommentNodeI[] = [];
928 // if its a parent comment fetch, then push the first comment to the top node.
930 const cNode = map.get(comments[0].comment.id);
936 for (const comment_view of comments) {
937 const child = map.get(comment_view.comment.id);
939 const parent_id = getCommentParentId(comment_view.comment);
941 const parent = map.get(parent_id);
942 // Necessary because blocked comment might not exist
944 parent.children.push(child);
947 if (!parentComment) {
957 export function getCommentParentId(comment?: CommentI): number | undefined {
958 const split = comment?.path.split(".");
962 return split && split.length > 1
963 ? Number(split.at(split.length - 2))
967 export function getDepthFromComment(comment?: CommentI): number | undefined {
968 const len = comment?.path.split(".").length;
969 return len ? len - 2 : undefined;
972 // TODO make immutable
973 export function insertCommentIntoTree(
974 tree: CommentNodeI[],
976 parentComment: boolean
978 // Building a fake node to be used for later
979 const node: CommentNodeI = {
985 const parentId = getCommentParentId(cv.comment);
987 const parent_comment = searchCommentTree(tree, parentId);
988 if (parent_comment) {
989 node.depth = parent_comment.depth + 1;
990 parent_comment.children.unshift(node);
992 } else if (!parentComment) {
997 export function searchCommentTree(
998 tree: CommentNodeI[],
1000 ): CommentNodeI | undefined {
1001 for (const node of tree) {
1002 if (node.comment_view.comment.id === id) {
1006 for (const child of node.children) {
1007 const res = searchCommentTree([child], id);
1017 export const colorList: string[] = [
1027 function hsl(num: number) {
1028 return `hsla(${num}, 35%, 50%, 0.5)`;
1031 export function hostname(url: string): string {
1032 const cUrl = new URL(url);
1033 return cUrl.port ? `${cUrl.hostname}:${cUrl.port}` : `${cUrl.hostname}`;
1036 export function validTitle(title?: string): boolean {
1037 // Initial title is null, minimum length is taken care of by textarea's minLength={3}
1038 if (!title || title.length < 3) return true;
1040 const regex = new RegExp(/.*\S.*/, "g");
1042 return regex.test(title);
1045 export function siteBannerCss(banner: string): string {
1047 background-image: linear-gradient( rgba(0, 0, 0, 0.8), rgba(0, 0, 0, 0.8) ) ,url("${banner}"); \
1048 background-attachment: fixed; \
1049 background-position: top; \
1050 background-repeat: no-repeat; \
1051 background-size: 100% cover; \
1054 max-height: 100vh; \
1058 export function setIsoData(context: any): IsoData {
1059 // If its the browser, you need to deserialize the data from the window
1061 return window.isoData;
1062 } else return context.router.staticContext;
1065 moment.updateLocale("en", {
1086 export function saveScrollPosition(context: any) {
1087 const path: string = context.router.route.location.pathname;
1088 const y = window.scrollY;
1089 sessionStorage.setItem(`scrollPosition_${path}`, y.toString());
1092 export function restoreScrollPosition(context: any) {
1093 const path: string = context.router.route.location.pathname;
1094 const y = Number(sessionStorage.getItem(`scrollPosition_${path}`));
1095 window.scrollTo(0, y);
1098 export function showLocal(isoData: IsoData): boolean {
1099 return isoData.site_res.site_view.local_site.federation_enabled;
1102 export interface Choice {
1108 export function getUpdatedSearchId(id?: number | null, urlId?: number | null) {
1111 : ((id ?? urlId) === 0 ? undefined : id ?? urlId)?.toString();
1114 export function communityToChoice(cv: CommunityView): Choice {
1116 value: cv.community.id.toString(),
1117 label: communitySelectName(cv),
1121 export function personToChoice(pvs: PersonView): Choice {
1123 value: pvs.person.id.toString(),
1124 label: personSelectName(pvs),
1128 function fetchSearchResults(q: string, type_: SearchType) {
1129 const form: Search = {
1133 listing_type: "All",
1139 return HttpService.client.search(form);
1142 export async function fetchCommunities(q: string) {
1143 const res = await fetchSearchResults(q, "Communities");
1145 return res.state === "success" ? res.data.communities : [];
1148 export async function fetchUsers(q: string) {
1149 const res = await fetchSearchResults(q, "Users");
1151 return res.state === "success" ? res.data.users : [];
1154 export function communitySelectName(cv: CommunityView): string {
1155 return cv.community.local
1156 ? cv.community.title
1157 : `${hostname(cv.community.actor_id)}/${cv.community.title}`;
1160 export function personSelectName({
1161 person: { display_name, name, local, actor_id },
1162 }: PersonView): string {
1163 const pName = display_name ?? name;
1164 return local ? pName : `${hostname(actor_id)}/${pName}`;
1167 export function initializeSite(site?: GetSiteResponse) {
1168 UserService.Instance.myUserInfo = site?.my_user;
1169 i18n.changeLanguage();
1171 setupEmojiDataModel(site.custom_emojis ?? []);
1176 const SHORTNUM_SI_FORMAT = new Intl.NumberFormat("en-US", {
1177 maximumSignificantDigits: 3,
1179 notation: "compact",
1180 compactDisplay: "short",
1183 export function numToSI(value: number): string {
1184 return SHORTNUM_SI_FORMAT.format(value);
1187 export function myAuth(): string | undefined {
1188 return UserService.Instance.auth();
1191 export function myAuthRequired(): string {
1192 return UserService.Instance.auth(true) ?? "";
1195 export function enableDownvotes(siteRes: GetSiteResponse): boolean {
1196 return siteRes.site_view.local_site.enable_downvotes;
1199 export function enableNsfw(siteRes: GetSiteResponse): boolean {
1200 return siteRes.site_view.local_site.enable_nsfw;
1203 export function postToCommentSortType(sort: SortType): CommentSortType {
1218 export function isPostBlocked(
1220 myUserInfo: MyUserInfo | undefined = UserService.Instance.myUserInfo
1223 (myUserInfo?.community_blocks
1224 .map(c => c.community.id)
1225 .includes(pv.community.id) ||
1226 myUserInfo?.person_blocks
1227 .map(p => p.target.id)
1228 .includes(pv.creator.id)) ??
1233 /// Checks to make sure you can view NSFW posts. Returns true if you can.
1234 export function nsfwCheck(
1236 myUserInfo = UserService.Instance.myUserInfo
1238 const nsfw = pv.post.nsfw || pv.community.nsfw;
1239 const myShowNsfw = myUserInfo?.local_user_view.local_user.show_nsfw ?? false;
1240 return !nsfw || (nsfw && myShowNsfw);
1243 export function getRandomFromList<T>(list: T[]): T | undefined {
1244 return list.length == 0
1246 : list.at(Math.floor(Math.random() * list.length));
1250 * This shows what language you can select
1252 * Use showAll for the site form
1253 * Use showSite for the profile and community forms
1254 * Use false for both those to filter on your profile and site ones
1256 export function selectableLanguages(
1257 allLanguages: Language[],
1258 siteLanguages: number[],
1261 myUserInfo = UserService.Instance.myUserInfo
1263 const allLangIds = allLanguages.map(l => l.id);
1264 let myLangs = myUserInfo?.discussion_languages ?? allLangIds;
1265 myLangs = myLangs.length == 0 ? allLangIds : myLangs;
1266 const siteLangs = siteLanguages.length == 0 ? allLangIds : siteLanguages;
1269 return allLanguages;
1272 return allLanguages.filter(x => siteLangs.includes(x.id));
1275 .filter(x => siteLangs.includes(x.id))
1276 .filter(x => myLangs.includes(x.id));
1281 interface EmojiMartCategory {
1284 emojis: EmojiMartCustomEmoji[];
1287 interface EmojiMartCustomEmoji {
1291 skins: EmojiMartSkin[];
1294 interface EmojiMartSkin {
1298 export function isAuthPath(pathname: string) {
1299 return /create_.*|inbox|settings|admin|reports|registration_applications/g.test(
1304 export function newVote(voteType: VoteType, myVote?: number): number {
1305 if (voteType == VoteType.Upvote) {
1306 return myVote == 1 ? 0 : 1;
1308 return myVote == -1 ? 0 : -1;