1 import { Err, None, Ok, Option, Result, Some } from "@sniptt/monads";
2 import { ClassConstructor, deserialize, serialize } from "class-transformer";
3 import emojiShortName from "emoji-short-name";
5 BlockCommunityResponse,
8 CommentNode as CommentNodeI,
13 CommunityModeratorView,
26 PrivateMessageReportView,
28 RegistrationApplicationView,
32 } from "lemmy-js-client";
33 import markdown_it from "markdown-it";
34 import markdown_it_container from "markdown-it-container";
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 moment from "moment";
40 import { Subscription } from "rxjs";
41 import { delay, retryWhen, take } from "rxjs/operators";
42 import tippy from "tippy.js";
43 import Toastify from "toastify-js";
44 import { httpBase } from "./env";
45 import { i18n, languages } from "./i18next";
46 import { DataType, IsoData } from "./interfaces";
47 import { UserService, WebSocketService } from "./services";
51 Tribute = require("tributejs");
54 export const wsClient = new LemmyWebsocket();
56 export const favIconUrl = "/static/assets/icons/favicon.svg";
57 export const favIconPngUrl = "/static/assets/icons/apple-touch-icon.png";
59 // export const defaultFavIcon = `${window.location.protocol}//${window.location.host}${favIconPngUrl}`;
60 export const repoUrl = "https://github.com/LemmyNet";
61 export const joinLemmyUrl = "https://join-lemmy.org";
62 export const donateLemmyUrl = `${joinLemmyUrl}/donate`;
63 export const docsUrl = `${joinLemmyUrl}/docs/en/index.html`;
64 export const helpGuideUrl = `${joinLemmyUrl}/docs/en/about/guide.html`; // TODO find a way to redirect to the non-en folder
65 export const markdownHelpUrl = `${helpGuideUrl}#using-markdown`;
66 export const sortingHelpUrl = `${helpGuideUrl}#sorting`;
67 export const archiveTodayUrl = "https://archive.today";
68 export const ghostArchiveUrl = "https://ghostarchive.org";
69 export const webArchiveUrl = "https://web.archive.org";
70 export const elementUrl = "https://element.io";
72 export const postRefetchSeconds: number = 60 * 1000;
73 export const fetchLimit = 40;
74 export const trendingFetchLimit = 6;
75 export const mentionDropdownFetchLimit = 10;
76 export const commentTreeMaxDepth = 8;
77 export const markdownFieldCharacterLimit = 50000;
79 export const relTags = "noopener nofollow";
81 const DEFAULT_ALPHABET =
82 "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
84 function getRandomCharFromAlphabet(alphabet: string): string {
85 return alphabet.charAt(Math.floor(Math.random() * alphabet.length));
88 export function randomStr(
90 alphabet = DEFAULT_ALPHABET
93 * Create n-long array and map it to random chars from given alphabet.
94 * Then join individual chars as string
96 return Array.from({ length: idDesiredLength })
98 return getRandomCharFromAlphabet(alphabet);
103 export const md = new markdown_it({
108 .use(markdown_it_sub)
109 .use(markdown_it_sup)
110 .use(markdown_it_footnote)
111 .use(markdown_it_html5_embed, {
113 useImageSyntax: true, // Enables video/audio embed with ![]() syntax (default)
115 audio: 'controls preload="metadata"',
117 'width="100%" max-height="100%" controls loop preload="metadata"',
121 .use(markdown_it_container, "spoiler", {
122 validate: function (params: any) {
123 return params.trim().match(/^spoiler\s+(.*)$/);
126 render: function (tokens: any, idx: any) {
127 var m = tokens[idx].info.trim().match(/^spoiler\s+(.*)$/);
129 if (tokens[idx].nesting === 1) {
131 return `<details><summary> ${md.utils.escapeHtml(m[1])} </summary>\n`;
134 return "</details>\n";
139 export function hotRankComment(comment_view: CommentView): number {
140 return hotRank(comment_view.counts.score, comment_view.comment.published);
143 export function hotRankActivePost(post_view: PostView): number {
144 return hotRank(post_view.counts.score, post_view.counts.newest_comment_time);
147 export function hotRankPost(post_view: PostView): number {
148 return hotRank(post_view.counts.score, post_view.post.published);
151 export function hotRank(score: number, timeStr: string): number {
152 // Rank = ScaleFactor * sign(Score) * log(1 + abs(Score)) / (Time + 2)^Gravity
153 let date: Date = new Date(timeStr + "Z"); // Add Z to convert from UTC date
154 let now: Date = new Date();
155 let hoursElapsed: number = (now.getTime() - date.getTime()) / 36e5;
158 (10000 * Math.log10(Math.max(1, 3 + score))) /
159 Math.pow(hoursElapsed + 2, 1.8);
161 // console.log(`Comment: ${comment.content}\nRank: ${rank}\nScore: ${comment.score}\nHours: ${hoursElapsed}`);
166 export function mdToHtml(text: string) {
167 return { __html: md.render(text) };
170 export function mdToHtmlInline(text: string) {
171 return { __html: md.renderInline(text) };
174 export function getUnixTime(text: string): number {
175 return text ? new Date(text).getTime() / 1000 : undefined;
178 export function futureDaysToUnixTime(days: number): number {
181 new Date(Date.now() + 1000 * 60 * 60 * 24 * days).getTime() / 1000
186 export function canMod(
187 mods: Option<CommunityModeratorView[]>,
188 admins: Option<PersonViewSafe[]>,
190 myUserInfo = UserService.Instance.myUserInfo,
193 // You can do moderator actions only on the mods added after you.
194 let adminsThenMods = admins
196 .map(a => a.person.id)
197 .concat(mods.unwrapOr([]).map(m => m.moderator.id));
199 return myUserInfo.match({
201 let myIndex = adminsThenMods.findIndex(
202 id => id == me.local_user_view.person.id
207 // onSelf +1 on mod actions not for yourself, IE ban, remove, etc
208 adminsThenMods = adminsThenMods.slice(0, myIndex + (onSelf ? 0 : 1));
209 return !adminsThenMods.includes(creator_id);
216 export function canAdmin(
217 admins: Option<PersonViewSafe[]>,
219 myUserInfo = UserService.Instance.myUserInfo,
222 return canMod(None, admins, creator_id, myUserInfo, onSelf);
225 export function isMod(
226 mods: Option<CommunityModeratorView[]>,
230 some: mods => mods.map(m => m.moderator.id).includes(creator_id),
235 export function amMod(
236 mods: Option<CommunityModeratorView[]>,
237 myUserInfo = UserService.Instance.myUserInfo
239 return myUserInfo.match({
240 some: mui => isMod(mods, mui.local_user_view.person.id),
245 export function isAdmin(
246 admins: Option<PersonViewSafe[]>,
249 return admins.match({
250 some: admins => admins.map(a => a.person.id).includes(creator_id),
255 export function amAdmin(myUserInfo = UserService.Instance.myUserInfo): boolean {
257 .map(mui => mui.local_user_view.person.admin)
261 export function amCommunityCreator(
262 mods: Option<CommunityModeratorView[]>,
264 myUserInfo = UserService.Instance.myUserInfo
269 .map(mui => mui.local_user_view.person.id)
272 myId == mods[0].moderator.id &&
273 // Don't allow mod actions on yourself
281 export function amSiteCreator(
282 admins: Option<PersonViewSafe[]>,
284 myUserInfo = UserService.Instance.myUserInfo
286 return admins.match({
289 .map(mui => mui.local_user_view.person.id)
292 myId == admins[0].person.id &&
293 // Don't allow mod actions on yourself
301 export function amTopMod(
302 mods: Option<CommunityModeratorView[]>,
303 myUserInfo = UserService.Instance.myUserInfo
308 some: mui => mods[0].moderator.id == mui.local_user_view.person.id,
315 const imageRegex = /(http)?s?:?(\/\/[^"']*\.(?:jpg|jpeg|gif|png|svg|webp))/;
316 const videoRegex = /(http)?s?:?(\/\/[^"']*\.(?:mp4|webm))/;
318 export function isImage(url: string) {
319 return imageRegex.test(url);
322 export function isVideo(url: string) {
323 return videoRegex.test(url);
326 export function validURL(str: string) {
327 return !!new URL(str);
330 export function communityRSSUrl(actorId: string, sort: string): string {
331 let url = new URL(actorId);
332 return `${url.origin}/feeds${url.pathname}.xml?sort=${sort}`;
335 export function validEmail(email: string) {
337 /^(([^\s"(),.:;<>@[\\\]]+(\.[^\s"(),.:;<>@[\\\]]+)*)|(".+"))@((\[(?:\d{1,3}\.){3}\d{1,3}])|(([\dA-Za-z\-]+\.)+[A-Za-z]{2,}))$/;
338 return re.test(String(email).toLowerCase());
341 export function capitalizeFirstLetter(str: string): string {
342 return str.charAt(0).toUpperCase() + str.slice(1);
345 export function routeSortTypeToEnum(sort: string): SortType {
346 return SortType[sort];
349 export function listingTypeFromNum(type_: number): ListingType {
350 return Object.values(ListingType)[type_];
353 export function sortTypeFromNum(type_: number): SortType {
354 return Object.values(SortType)[type_];
357 export function routeListingTypeToEnum(type: string): ListingType {
358 return ListingType[type];
361 export function routeDataTypeToEnum(type: string): DataType {
362 return DataType[capitalizeFirstLetter(type)];
365 export function routeSearchTypeToEnum(type: string): SearchType {
366 return SearchType[type];
369 export async function getSiteMetadata(url: string) {
370 let form = new GetSiteMetadata({
373 let client = new LemmyHttp(httpBase);
374 return client.getSiteMetadata(form);
377 export function debounce(func: any, wait = 1000, immediate = false) {
378 // 'private' variable for instance
379 // The returned function will be able to reference this due to closure.
380 // Each call to the returned function will share this common timer.
383 // Calling debounce returns a new anonymous function
385 // reference the context and args for the setTimeout function
386 var args = arguments;
388 // Should the function be called now? If immediate is true
389 // and not already in a timeout then the answer is: Yes
390 var callNow = immediate && !timeout;
392 // This is the basic debounce behaviour where you can call this
393 // function several times, but it will only execute once
394 // [before or after imposing a delay].
395 // Each time the returned function is called, the timer starts over.
396 clearTimeout(timeout);
398 // Set the new timeout
399 timeout = setTimeout(function () {
400 // Inside the timeout function, clear the timeout variable
401 // which will let the next execution run when in 'immediate' mode
404 // Check if the function already ran with the immediate flag
406 // Call the original function with apply
407 // apply lets you define the 'this' object as well as the arguments
408 // (both captured before setTimeout)
409 func.apply(this, args);
413 // Immediate mode and no wait timer? Execute the function..
414 if (callNow) func.apply(this, args);
418 export function getLanguages(
420 myUserInfo = UserService.Instance.myUserInfo
422 let myLang = myUserInfo
423 .map(m => m.local_user_view.local_user.interface_language)
424 .unwrapOr("browser");
425 let lang = override || myLang;
427 if (lang == "browser" && isBrowser()) {
428 return getBrowserLanguages();
434 function getBrowserLanguages(): string[] {
435 // Intersect lemmy's langs, with the browser langs
436 let langs = languages ? languages.map(l => l.code) : ["en"];
438 // NOTE, mobile browsers seem to be missing this list, so append en
439 let allowedLangs = navigator.languages
441 .filter(v => langs.includes(v));
445 export async function fetchThemeList(): Promise<string[]> {
446 return fetch("/css/themelist").then(res => res.json());
449 export async function setTheme(theme: string, forceReload = false) {
453 if (theme === "browser" && !forceReload) {
456 // This is only run on a force reload
457 if (theme == "browser") {
461 let themeList = await fetchThemeList();
463 // Unload all the other themes
464 for (var i = 0; i < themeList.length; i++) {
465 let styleSheet = document.getElementById(themeList[i]);
467 styleSheet.setAttribute("disabled", "disabled");
472 .getElementById("default-light")
473 ?.setAttribute("disabled", "disabled");
474 document.getElementById("default-dark")?.setAttribute("disabled", "disabled");
476 // Load the theme dynamically
477 let cssLoc = `/css/themes/${theme}.css`;
479 loadCss(theme, cssLoc);
480 document.getElementById(theme).removeAttribute("disabled");
483 export function loadCss(id: string, loc: string) {
484 if (!document.getElementById(id)) {
485 var head = document.getElementsByTagName("head")[0];
486 var link = document.createElement("link");
488 link.rel = "stylesheet";
489 link.type = "text/css";
492 head.appendChild(link);
496 export function objectFlip(obj: any) {
498 Object.keys(obj).forEach(key => {
504 export function showAvatars(
505 myUserInfo: Option<MyUserInfo> = UserService.Instance.myUserInfo
508 .map(m => m.local_user_view.local_user.show_avatars)
512 export function showScores(
513 myUserInfo: Option<MyUserInfo> = UserService.Instance.myUserInfo
516 .map(m => m.local_user_view.local_user.show_scores)
520 export function isCakeDay(published: string): boolean {
521 // moment(undefined) or moment.utc(undefined) returns the current date/time
522 // moment(null) or moment.utc(null) returns null
523 const createDate = moment.utc(published).local();
524 const currentDate = moment(new Date());
527 createDate.date() === currentDate.date() &&
528 createDate.month() === currentDate.month() &&
529 createDate.year() !== currentDate.year()
533 export function toast(text: string, background = "success") {
535 let backgroundColor = `var(--${background})`;
538 backgroundColor: backgroundColor,
545 export function pictrsDeleteToast(
546 clickToDeleteText: string,
547 deletePictureText: string,
548 failedDeletePictureText: string,
552 let backgroundColor = `var(--light)`;
553 let toast = Toastify({
554 text: clickToDeleteText,
555 backgroundColor: backgroundColor,
561 fetch(deleteUrl).then(res => {
563 if (res.ok === true) {
564 alert(deletePictureText);
566 alert(failedDeletePictureText);
576 interface NotifyInfo {
578 icon: Option<string>;
583 export function messageToastify(info: NotifyInfo, router: any) {
585 let htmlBody = info.body ? md.render(info.body) : "";
586 let backgroundColor = `var(--light)`;
588 let toast = Toastify({
589 text: `${htmlBody}<br />${info.name}`,
591 backgroundColor: backgroundColor,
592 className: "text-dark",
601 router.history.push(info.link);
608 export function notifyPost(post_view: PostView, router: any) {
609 let info: NotifyInfo = {
610 name: post_view.community.name,
611 icon: post_view.community.icon,
612 link: `/post/${post_view.post.id}`,
613 body: post_view.post.name,
615 notify(info, router);
618 export function notifyComment(comment_view: CommentView, router: any) {
619 let info: NotifyInfo = {
620 name: comment_view.creator.name,
621 icon: comment_view.creator.avatar,
622 link: `/comment/${comment_view.comment.id}`,
623 body: comment_view.comment.content,
625 notify(info, router);
628 export function notifyPrivateMessage(pmv: PrivateMessageView, router: any) {
629 let info: NotifyInfo = {
630 name: pmv.creator.name,
631 icon: pmv.creator.avatar,
633 body: pmv.private_message.content,
635 notify(info, router);
638 function notify(info: NotifyInfo, router: any) {
639 messageToastify(info, router);
641 if (Notification.permission !== "granted") Notification.requestPermission();
643 var notification = new Notification(info.name, {
644 ...{ body: info.body },
645 ...(info.icon.isSome() && { icon: info.icon.unwrap() }),
648 notification.onclick = (ev: Event): any => {
650 router.history.push(info.link);
655 export function setupTribute() {
657 noMatchTemplate: function () {
664 menuItemTemplate: (item: any) => {
665 let shortName = `:${item.original.key}:`;
666 return `${item.original.val} ${shortName}`;
668 selectTemplate: (item: any) => {
669 return `${item.original.val}`;
671 values: Object.entries(emojiShortName).map(e => {
672 return { key: e[1], val: e[0] };
675 autocompleteMode: true,
677 // menuItemLimit: mentionDropdownFetchLimit,
678 menuShowMinLength: 2,
683 selectTemplate: (item: any) => {
684 let it: PersonTribute = item.original;
685 return `[${it.key}](${it.view.person.actor_id})`;
687 values: debounce(async (text: string, cb: any) => {
688 cb(await personSearch(text));
691 autocompleteMode: true,
693 // menuItemLimit: mentionDropdownFetchLimit,
694 menuShowMinLength: 2,
700 selectTemplate: (item: any) => {
701 let it: CommunityTribute = item.original;
702 return `[${it.key}](${it.view.community.actor_id})`;
704 values: debounce(async (text: string, cb: any) => {
705 cb(await communitySearch(text));
708 autocompleteMode: true,
710 // menuItemLimit: mentionDropdownFetchLimit,
711 menuShowMinLength: 2,
717 var tippyInstance: any;
719 tippyInstance = tippy("[data-tippy-content]");
722 export function setupTippy() {
724 tippyInstance.forEach((e: any) => e.destroy());
725 tippyInstance = tippy("[data-tippy-content]", {
727 // Display on "long press"
728 touch: ["hold", 500],
733 interface PersonTribute {
735 view: PersonViewSafe;
738 async function personSearch(text: string): Promise<PersonTribute[]> {
739 let users = (await fetchUsers(text)).users;
740 let persons: PersonTribute[] = users.map(pv => {
741 let tribute: PersonTribute = {
742 key: `@${pv.person.name}@${hostname(pv.person.actor_id)}`,
750 interface CommunityTribute {
755 async function communitySearch(text: string): Promise<CommunityTribute[]> {
756 let comms = (await fetchCommunities(text)).communities;
757 let communities: CommunityTribute[] = comms.map(cv => {
758 let tribute: CommunityTribute = {
759 key: `!${cv.community.name}@${hostname(cv.community.actor_id)}`,
767 export function getListingTypeFromProps(
769 defaultListingType: ListingType,
770 myUserInfo = UserService.Instance.myUserInfo
772 return props.match.params.listing_type
773 ? routeListingTypeToEnum(props.match.params.listing_type)
776 Object.values(ListingType)[
777 me.local_user_view.local_user.default_listing_type
779 none: defaultListingType,
783 export function getListingTypeFromPropsNoDefault(props: any): ListingType {
784 return props.match.params.listing_type
785 ? routeListingTypeToEnum(props.match.params.listing_type)
789 export function getDataTypeFromProps(props: any): DataType {
790 return props.match.params.data_type
791 ? routeDataTypeToEnum(props.match.params.data_type)
795 export function getSortTypeFromProps(
797 myUserInfo = UserService.Instance.myUserInfo
799 return props.match.params.sort
800 ? routeSortTypeToEnum(props.match.params.sort)
803 Object.values(SortType)[
804 mui.local_user_view.local_user.default_sort_type
806 none: SortType.Active,
810 export function getPageFromProps(props: any): number {
811 return props.match.params.page ? Number(props.match.params.page) : 1;
814 export function getRecipientIdFromProps(props: any): number {
815 return props.match.params.recipient_id
816 ? Number(props.match.params.recipient_id)
820 export function getIdFromProps(props: any): Option<number> {
821 let id: string = props.match.params.post_id;
822 return id ? Some(Number(id)) : None;
825 export function getCommentIdFromProps(props: any): Option<number> {
826 let id: string = props.match.params.comment_id;
827 return id ? Some(Number(id)) : None;
830 export function getUsernameFromProps(props: any): string {
831 return props.match.params.username;
834 export function editCommentRes(data: CommentView, comments: CommentView[]) {
835 let found = comments.find(c => c.comment.id == data.comment.id);
837 found.comment.content = data.comment.content;
838 found.comment.distinguished = data.comment.distinguished;
839 found.comment.updated = data.comment.updated;
840 found.comment.removed = data.comment.removed;
841 found.comment.deleted = data.comment.deleted;
842 found.counts.upvotes = data.counts.upvotes;
843 found.counts.downvotes = data.counts.downvotes;
844 found.counts.score = data.counts.score;
848 export function saveCommentRes(data: CommentView, comments: CommentView[]) {
849 let found = comments.find(c => c.comment.id == data.comment.id);
851 found.saved = data.saved;
855 // TODO Should only use the return now, no state?
856 export function updatePersonBlock(
857 data: BlockPersonResponse,
858 myUserInfo = UserService.Instance.myUserInfo
859 ): Option<PersonBlockView[]> {
860 return myUserInfo.match({
861 some: (mui: MyUserInfo) => {
863 mui.person_blocks.push({
864 person: mui.local_user_view.person,
865 target: data.person_view.person,
867 toast(`${i18n.t("blocked")} ${data.person_view.person.name}`);
869 mui.person_blocks = mui.person_blocks.filter(
870 i => i.target.id != data.person_view.person.id
872 toast(`${i18n.t("unblocked")} ${data.person_view.person.name}`);
874 return Some(mui.person_blocks);
880 export function updateCommunityBlock(
881 data: BlockCommunityResponse,
882 myUserInfo = UserService.Instance.myUserInfo
883 ): Option<CommunityBlockView[]> {
884 return myUserInfo.match({
885 some: (mui: MyUserInfo) => {
887 mui.community_blocks.push({
888 person: mui.local_user_view.person,
889 community: data.community_view.community,
891 toast(`${i18n.t("blocked")} ${data.community_view.community.name}`);
893 mui.community_blocks = mui.community_blocks.filter(
894 i => i.community.id != data.community_view.community.id
896 toast(`${i18n.t("unblocked")} ${data.community_view.community.name}`);
898 return Some(mui.community_blocks);
904 export function createCommentLikeRes(
906 comments: CommentView[]
908 let found = comments.find(c => c.comment.id === data.comment.id);
910 found.counts.score = data.counts.score;
911 found.counts.upvotes = data.counts.upvotes;
912 found.counts.downvotes = data.counts.downvotes;
913 if (data.my_vote !== null) {
914 found.my_vote = data.my_vote;
919 export function createPostLikeFindRes(data: PostView, posts: PostView[]) {
920 let found = posts.find(p => p.post.id == data.post.id);
922 createPostLikeRes(data, found);
926 export function createPostLikeRes(data: PostView, post_view: PostView) {
928 post_view.counts.score = data.counts.score;
929 post_view.counts.upvotes = data.counts.upvotes;
930 post_view.counts.downvotes = data.counts.downvotes;
931 if (data.my_vote !== null) {
932 post_view.my_vote = data.my_vote;
937 export function editPostFindRes(data: PostView, posts: PostView[]) {
938 let found = posts.find(p => p.post.id == data.post.id);
940 editPostRes(data, found);
944 export function editPostRes(data: PostView, post: PostView) {
946 post.post.url = data.post.url;
947 post.post.name = data.post.name;
948 post.post.nsfw = data.post.nsfw;
949 post.post.deleted = data.post.deleted;
950 post.post.removed = data.post.removed;
951 post.post.stickied = data.post.stickied;
952 post.post.body = data.post.body;
953 post.post.locked = data.post.locked;
954 post.saved = data.saved;
958 // TODO possible to make these generic?
959 export function updatePostReportRes(
960 data: PostReportView,
961 reports: PostReportView[]
963 let found = reports.find(p => p.post_report.id == data.post_report.id);
965 found.post_report = data.post_report;
969 export function updateCommentReportRes(
970 data: CommentReportView,
971 reports: CommentReportView[]
973 let found = reports.find(c => c.comment_report.id == data.comment_report.id);
975 found.comment_report = data.comment_report;
979 export function updatePrivateMessageReportRes(
980 data: PrivateMessageReportView,
981 reports: PrivateMessageReportView[]
983 let found = reports.find(
984 c => c.private_message_report.id == data.private_message_report.id
987 found.private_message_report = data.private_message_report;
991 export function updateRegistrationApplicationRes(
992 data: RegistrationApplicationView,
993 applications: RegistrationApplicationView[]
995 let found = applications.find(
996 ra => ra.registration_application.id == data.registration_application.id
999 found.registration_application = data.registration_application;
1000 found.admin = data.admin;
1001 found.creator_local_user = data.creator_local_user;
1005 export function commentsToFlatNodes(comments: CommentView[]): CommentNodeI[] {
1006 let nodes: CommentNodeI[] = [];
1007 for (let comment of comments) {
1008 nodes.push({ comment_view: comment, children: [], depth: 0 });
1013 export function convertCommentSortType(sort: SortType): CommentSortType {
1015 sort == SortType.TopAll ||
1016 sort == SortType.TopDay ||
1017 sort == SortType.TopWeek ||
1018 sort == SortType.TopMonth ||
1019 sort == SortType.TopYear
1021 return CommentSortType.Top;
1022 } else if (sort == SortType.New) {
1023 return CommentSortType.New;
1024 } else if (sort == SortType.Hot || sort == SortType.Active) {
1025 return CommentSortType.Hot;
1027 return CommentSortType.Hot;
1031 export function buildCommentsTree(
1032 comments: CommentView[],
1033 parentComment: boolean
1035 let map = new Map<number, CommentNodeI>();
1036 let depthOffset = !parentComment
1038 : getDepthFromComment(comments[0].comment);
1040 for (let comment_view of comments) {
1041 let node: CommentNodeI = {
1042 comment_view: comment_view,
1044 depth: getDepthFromComment(comment_view.comment) - depthOffset,
1046 map.set(comment_view.comment.id, { ...node });
1049 let tree: CommentNodeI[] = [];
1051 // if its a parent comment fetch, then push the first comment to the top node.
1052 if (parentComment) {
1053 tree.push(map.get(comments[0].comment.id));
1056 for (let comment_view of comments) {
1057 let child = map.get(comment_view.comment.id);
1058 let parent_id = getCommentParentId(comment_view.comment);
1061 let parent = map.get(parentId);
1062 // Necessary because blocked comment might not exist
1064 parent.children.push(child);
1068 if (!parentComment) {
1078 export function getCommentParentId(comment: CommentI): Option<number> {
1079 let split = comment.path.split(".");
1083 if (split.length > 1) {
1084 return Some(Number(split[split.length - 2]));
1090 export function getDepthFromComment(comment: CommentI): number {
1091 return comment.path.split(".").length - 2;
1094 export function insertCommentIntoTree(
1095 tree: CommentNodeI[],
1097 parentComment: boolean
1099 // Building a fake node to be used for later
1100 let node: CommentNodeI = {
1106 getCommentParentId(cv.comment).match({
1108 let parentComment = searchCommentTree(tree, parentId);
1109 parentComment.match({
1111 node.depth = pComment.depth + 1;
1112 pComment.children.unshift(node);
1118 if (!parentComment) {
1125 export function searchCommentTree(
1126 tree: CommentNodeI[],
1128 ): Option<CommentNodeI> {
1129 for (let node of tree) {
1130 if (node.comment_view.comment.id === id) {
1134 for (const child of node.children) {
1135 let res = searchCommentTree([child], id);
1145 export const colorList: string[] = [
1155 function hsl(num: number) {
1156 return `hsla(${num}, 35%, 50%, 1)`;
1159 export function hostname(url: string): string {
1160 let cUrl = new URL(url);
1161 return cUrl.port ? `${cUrl.hostname}:${cUrl.port}` : `${cUrl.hostname}`;
1164 export function validTitle(title?: string): boolean {
1165 // Initial title is null, minimum length is taken care of by textarea's minLength={3}
1166 if (!title || title.length < 3) return true;
1168 const regex = new RegExp(/.*\S.*/, "g");
1170 return regex.test(title);
1173 export function siteBannerCss(banner: string): string {
1175 background-image: linear-gradient( rgba(0, 0, 0, 0.8), rgba(0, 0, 0, 0.8) ) ,url("${banner}"); \
1176 background-attachment: fixed; \
1177 background-position: top; \
1178 background-repeat: no-repeat; \
1179 background-size: 100% cover; \
1182 max-height: 100vh; \
1186 export function isBrowser() {
1187 return typeof window !== "undefined";
1190 export function setIsoData<Type1, Type2, Type3, Type4, Type5>(
1192 cls1?: ClassConstructor<Type1>,
1193 cls2?: ClassConstructor<Type2>,
1194 cls3?: ClassConstructor<Type3>,
1195 cls4?: ClassConstructor<Type4>,
1196 cls5?: ClassConstructor<Type5>
1198 // If its the browser, you need to deserialize the data from the window
1200 let json = window.isoData;
1201 let routeData = json.routeData;
1202 let routeDataOut: any[] = [];
1204 // Can't do array looping because of specific type constructor required
1206 routeDataOut[0] = convertWindowJson(cls1, routeData[0]);
1209 routeDataOut[1] = convertWindowJson(cls2, routeData[1]);
1212 routeDataOut[2] = convertWindowJson(cls3, routeData[2]);
1215 routeDataOut[3] = convertWindowJson(cls4, routeData[3]);
1218 routeDataOut[4] = convertWindowJson(cls5, routeData[4]);
1220 let site_res = convertWindowJson(GetSiteResponse, json.site_res);
1222 let isoData: IsoData = {
1225 routeData: routeDataOut,
1228 } else return context.router.staticContext;
1232 * Necessary since window ISOData can't store function types like Option
1234 export function convertWindowJson<T>(cls: ClassConstructor<T>, data: any): T {
1235 return deserialize(cls, serialize(data));
1238 export function wsSubscribe(parseMessage: any): Subscription {
1240 return WebSocketService.Instance.subject
1241 .pipe(retryWhen(errors => errors.pipe(delay(3000), take(10))))
1243 msg => parseMessage(msg),
1244 err => console.error(err),
1245 () => console.log("complete")
1252 moment.updateLocale("en", {
1273 export function saveScrollPosition(context: any) {
1274 let path: string = context.router.route.location.pathname;
1275 let y = window.scrollY;
1276 sessionStorage.setItem(`scrollPosition_${path}`, y.toString());
1279 export function restoreScrollPosition(context: any) {
1280 let path: string = context.router.route.location.pathname;
1281 let y = Number(sessionStorage.getItem(`scrollPosition_${path}`));
1282 window.scrollTo(0, y);
1285 export function showLocal(isoData: IsoData): boolean {
1286 return isoData.site_res.federated_instances
1287 .map(f => f.linked.length > 0)
1291 export interface ChoicesValue {
1296 export function communityToChoice(cv: CommunityView): ChoicesValue {
1297 let choice: ChoicesValue = {
1298 value: cv.community.id.toString(),
1299 label: communitySelectName(cv),
1304 export function personToChoice(pvs: PersonViewSafe): ChoicesValue {
1305 let choice: ChoicesValue = {
1306 value: pvs.person.id.toString(),
1307 label: personSelectName(pvs),
1312 export async function fetchCommunities(q: string) {
1313 let form = new Search({
1315 type_: Some(SearchType.Communities),
1316 sort: Some(SortType.TopAll),
1317 listing_type: Some(ListingType.All),
1319 limit: Some(fetchLimit),
1321 community_name: None,
1323 auth: auth(false).ok(),
1325 let client = new LemmyHttp(httpBase);
1326 return client.search(form);
1329 export async function fetchUsers(q: string) {
1330 let form = new Search({
1332 type_: Some(SearchType.Users),
1333 sort: Some(SortType.TopAll),
1334 listing_type: Some(ListingType.All),
1336 limit: Some(fetchLimit),
1338 community_name: None,
1340 auth: auth(false).ok(),
1342 let client = new LemmyHttp(httpBase);
1343 return client.search(form);
1346 export const choicesConfig = {
1348 searchResultLimit: fetchLimit,
1350 containerOuter: "choices custom-select px-0",
1352 "choices__inner bg-secondary border-0 py-0 modlog-choices-font-size",
1353 input: "form-control",
1354 inputCloned: "choices__input--cloned",
1355 list: "choices__list",
1356 listItems: "choices__list--multiple",
1357 listSingle: "choices__list--single py-0",
1358 listDropdown: "choices__list--dropdown",
1359 item: "choices__item bg-secondary",
1360 itemSelectable: "choices__item--selectable",
1361 itemDisabled: "choices__item--disabled",
1362 itemChoice: "choices__item--choice",
1363 placeholder: "choices__placeholder",
1364 group: "choices__group",
1365 groupHeading: "choices__heading",
1366 button: "choices__button",
1367 activeState: "is-active",
1368 focusState: "is-focused",
1369 openState: "is-open",
1370 disabledState: "is-disabled",
1371 highlightedState: "text-info",
1372 selectedState: "text-info",
1373 flippedState: "is-flipped",
1374 loadingState: "is-loading",
1375 noResults: "has-no-results",
1376 noChoices: "has-no-choices",
1380 export function communitySelectName(cv: CommunityView): string {
1381 return cv.community.local
1382 ? cv.community.title
1383 : `${hostname(cv.community.actor_id)}/${cv.community.title}`;
1386 export function personSelectName(pvs: PersonViewSafe): string {
1387 let pName = pvs.person.display_name.unwrapOr(pvs.person.name);
1388 return pvs.person.local ? pName : `${hostname(pvs.person.actor_id)}/${pName}`;
1391 export function initializeSite(site: GetSiteResponse) {
1392 UserService.Instance.myUserInfo = site.my_user;
1393 i18n.changeLanguage(getLanguages()[0]);
1396 const SHORTNUM_SI_FORMAT = new Intl.NumberFormat("en-US", {
1397 maximumSignificantDigits: 3,
1399 notation: "compact",
1400 compactDisplay: "short",
1403 export function numToSI(value: number): string {
1404 return SHORTNUM_SI_FORMAT.format(value);
1407 export function isBanned(ps: PersonSafe): boolean {
1408 let expires = ps.ban_expires;
1409 // Add Z to convert from UTC date
1410 // TODO this check probably isn't necessary anymore
1411 if (expires.isSome()) {
1412 if (ps.banned && new Date(expires.unwrap() + "Z") > new Date()) {
1422 export function pushNotNull(array: any[], new_item?: any) {
1424 array.push(...new_item);
1428 export function auth(throwErr = true): Result<string, string> {
1429 return UserService.Instance.auth(throwErr);
1432 export function enableDownvotes(siteRes: GetSiteResponse): boolean {
1433 return siteRes.site_view.local_site.enable_downvotes;
1436 export function enableNsfw(siteRes: GetSiteResponse): boolean {
1437 return siteRes.site_view.local_site.enable_nsfw;
1440 export function postToCommentSortType(sort: SortType): CommentSortType {
1441 if ([SortType.Active, SortType.Hot].includes(sort)) {
1442 return CommentSortType.Hot;
1443 } else if ([SortType.New, SortType.NewComments].includes(sort)) {
1444 return CommentSortType.New;
1445 } else if (sort == SortType.Old) {
1446 return CommentSortType.Old;
1448 return CommentSortType.Top;
1452 export function arrayGet<T>(arr: Array<T>, index: number): Result<T, string> {
1453 let out = arr.at(index);
1454 if (out == undefined) {
1455 return Err("Index undefined");
1461 export function myFirstDiscussionLanguageId(
1462 myUserInfo = UserService.Instance.myUserInfo
1464 return myUserInfo.andThen(mui =>
1465 arrayGet(mui.discussion_languages, 0)
1471 export function canCreateCommunity(
1472 siteRes: GetSiteResponse,
1473 myUserInfo = UserService.Instance.myUserInfo
1475 let adminOnly = siteRes.site_view.local_site.community_creation_admin_only;
1476 return !adminOnly || amAdmin(myUserInfo);
1479 export function isPostBlocked(
1481 myUserInfo = UserService.Instance.myUserInfo
1486 mui.community_blocks
1487 .map(c => c.community.id)
1488 .includes(pv.community.id) ||
1489 mui.person_blocks.map(p => p.target.id).includes(pv.creator.id)
1494 /// Checks to make sure you can view NSFW posts. Returns true if you can.
1495 export function nsfwCheck(
1497 myUserInfo = UserService.Instance.myUserInfo
1499 let nsfw = pv.post.nsfw || pv.community.nsfw;
1504 .map(m => m.local_user_view.local_user.show_nsfw)