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,
33 } from "lemmy-js-client";
34 import { default as MarkdownIt } from "markdown-it";
35 import markdown_it_container from "markdown-it-container";
36 import markdown_it_footnote from "markdown-it-footnote";
37 import markdown_it_html5_embed from "markdown-it-html5-embed";
38 import markdown_it_sub from "markdown-it-sub";
39 import markdown_it_sup from "markdown-it-sup";
40 import moment from "moment";
41 import { Subscription } from "rxjs";
42 import { delay, retryWhen, take } from "rxjs/operators";
43 import tippy from "tippy.js";
44 import Toastify from "toastify-js";
45 import { httpBase } from "./env";
46 import { i18n, languages } from "./i18next";
47 import { DataType, IsoData } from "./interfaces";
48 import { UserService, WebSocketService } from "./services";
52 Tribute = require("tributejs");
55 export const wsClient = new LemmyWebsocket();
57 export const favIconUrl = "/static/assets/icons/favicon.svg";
58 export const favIconPngUrl = "/static/assets/icons/apple-touch-icon.png";
60 // export const defaultFavIcon = `${window.location.protocol}//${window.location.host}${favIconPngUrl}`;
61 export const repoUrl = "https://github.com/LemmyNet";
62 export const joinLemmyUrl = "https://join-lemmy.org";
63 export const donateLemmyUrl = `${joinLemmyUrl}/donate`;
64 export const docsUrl = `${joinLemmyUrl}/docs/en/index.html`;
65 export const helpGuideUrl = `${joinLemmyUrl}/docs/en/about/guide.html`; // TODO find a way to redirect to the non-en folder
66 export const markdownHelpUrl = `${helpGuideUrl}#using-markdown`;
67 export const sortingHelpUrl = `${helpGuideUrl}#sorting`;
68 export const archiveTodayUrl = "https://archive.today";
69 export const ghostArchiveUrl = "https://ghostarchive.org";
70 export const webArchiveUrl = "https://web.archive.org";
71 export const elementUrl = "https://element.io";
73 export const postRefetchSeconds: number = 60 * 1000;
74 export const fetchLimit = 40;
75 export const trendingFetchLimit = 6;
76 export const mentionDropdownFetchLimit = 10;
77 export const commentTreeMaxDepth = 8;
78 export const markdownFieldCharacterLimit = 50000;
80 export const relTags = "noopener nofollow";
82 const DEFAULT_ALPHABET =
83 "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
85 function getRandomCharFromAlphabet(alphabet: string): string {
86 return alphabet.charAt(Math.floor(Math.random() * alphabet.length));
89 export function randomStr(
91 alphabet = DEFAULT_ALPHABET
94 * Create n-long array and map it to random chars from given alphabet.
95 * Then join individual chars as string
97 return Array.from({ length: idDesiredLength })
99 return getRandomCharFromAlphabet(alphabet);
104 const html5EmbedConfig = {
106 useImageSyntax: true, // Enables video/audio embed with ![]() syntax (default)
108 audio: 'controls preload="metadata"',
109 video: 'width="100%" max-height="100%" controls loop preload="metadata"',
114 const spoilerConfig = {
115 validate: (params: string) => {
116 return params.trim().match(/^spoiler\s+(.*)$/);
119 render: (tokens: any, idx: any) => {
120 var m = tokens[idx].info.trim().match(/^spoiler\s+(.*)$/);
122 if (tokens[idx].nesting === 1) {
124 return `<details><summary> ${md.utils.escapeHtml(m[1])} </summary>\n`;
127 return "</details>\n";
132 const markdownItConfig: MarkdownIt.Options = {
138 export const md = new MarkdownIt(markdownItConfig)
139 .use(markdown_it_sub)
140 .use(markdown_it_sup)
141 .use(markdown_it_footnote)
142 .use(markdown_it_html5_embed, html5EmbedConfig)
143 .use(markdown_it_container, "spoiler", spoilerConfig);
145 export const mdNoImages = new MarkdownIt(markdownItConfig)
146 .use(markdown_it_sub)
147 .use(markdown_it_sup)
148 .use(markdown_it_footnote)
149 .use(markdown_it_html5_embed, html5EmbedConfig)
150 .use(markdown_it_container, "spoiler", spoilerConfig)
153 export function hotRankComment(comment_view: CommentView): number {
154 return hotRank(comment_view.counts.score, comment_view.comment.published);
157 export function hotRankActivePost(post_view: PostView): number {
158 return hotRank(post_view.counts.score, post_view.counts.newest_comment_time);
161 export function hotRankPost(post_view: PostView): number {
162 return hotRank(post_view.counts.score, post_view.post.published);
165 export function hotRank(score: number, timeStr: string): number {
166 // Rank = ScaleFactor * sign(Score) * log(1 + abs(Score)) / (Time + 2)^Gravity
167 let date: Date = new Date(timeStr + "Z"); // Add Z to convert from UTC date
168 let now: Date = new Date();
169 let hoursElapsed: number = (now.getTime() - date.getTime()) / 36e5;
172 (10000 * Math.log10(Math.max(1, 3 + score))) /
173 Math.pow(hoursElapsed + 2, 1.8);
175 // console.log(`Comment: ${comment.content}\nRank: ${rank}\nScore: ${comment.score}\nHours: ${hoursElapsed}`);
180 export function mdToHtml(text: string) {
181 return { __html: md.render(text) };
184 export function mdToHtmlNoImages(text: string) {
185 return { __html: mdNoImages.render(text) };
188 export function mdToHtmlInline(text: string) {
189 return { __html: md.renderInline(text) };
192 export function getUnixTime(text: string): number {
193 return text ? new Date(text).getTime() / 1000 : undefined;
196 export function futureDaysToUnixTime(days: number): number {
199 new Date(Date.now() + 1000 * 60 * 60 * 24 * days).getTime() / 1000
204 export function canMod(
205 mods: Option<CommunityModeratorView[]>,
206 admins: Option<PersonViewSafe[]>,
208 myUserInfo = UserService.Instance.myUserInfo,
211 // You can do moderator actions only on the mods added after you.
212 let adminsThenMods = admins
214 .map(a => a.person.id)
215 .concat(mods.unwrapOr([]).map(m => m.moderator.id));
217 return myUserInfo.match({
219 let myIndex = adminsThenMods.findIndex(
220 id => id == me.local_user_view.person.id
225 // onSelf +1 on mod actions not for yourself, IE ban, remove, etc
226 adminsThenMods = adminsThenMods.slice(0, myIndex + (onSelf ? 0 : 1));
227 return !adminsThenMods.includes(creator_id);
234 export function canAdmin(
235 admins: Option<PersonViewSafe[]>,
237 myUserInfo = UserService.Instance.myUserInfo,
240 return canMod(None, admins, creator_id, myUserInfo, onSelf);
243 export function isMod(
244 mods: Option<CommunityModeratorView[]>,
248 some: mods => mods.map(m => m.moderator.id).includes(creator_id),
253 export function amMod(
254 mods: Option<CommunityModeratorView[]>,
255 myUserInfo = UserService.Instance.myUserInfo
257 return myUserInfo.match({
258 some: mui => isMod(mods, mui.local_user_view.person.id),
263 export function isAdmin(
264 admins: Option<PersonViewSafe[]>,
267 return admins.match({
268 some: admins => admins.map(a => a.person.id).includes(creator_id),
273 export function amAdmin(myUserInfo = UserService.Instance.myUserInfo): boolean {
275 .map(mui => mui.local_user_view.person.admin)
279 export function amCommunityCreator(
280 mods: Option<CommunityModeratorView[]>,
282 myUserInfo = UserService.Instance.myUserInfo
287 .map(mui => mui.local_user_view.person.id)
290 myId == mods[0].moderator.id &&
291 // Don't allow mod actions on yourself
299 export function amSiteCreator(
300 admins: Option<PersonViewSafe[]>,
302 myUserInfo = UserService.Instance.myUserInfo
304 return admins.match({
307 .map(mui => mui.local_user_view.person.id)
310 myId == admins[0].person.id &&
311 // Don't allow mod actions on yourself
319 export function amTopMod(
320 mods: Option<CommunityModeratorView[]>,
321 myUserInfo = UserService.Instance.myUserInfo
326 some: mui => mods[0].moderator.id == mui.local_user_view.person.id,
333 const imageRegex = /(http)?s?:?(\/\/[^"']*\.(?:jpg|jpeg|gif|png|svg|webp))/;
334 const videoRegex = /(http)?s?:?(\/\/[^"']*\.(?:mp4|webm))/;
336 export function isImage(url: string) {
337 return imageRegex.test(url);
340 export function isVideo(url: string) {
341 return videoRegex.test(url);
344 export function validURL(str: string) {
345 return !!new URL(str);
348 export function communityRSSUrl(actorId: string, sort: string): string {
349 let url = new URL(actorId);
350 return `${url.origin}/feeds${url.pathname}.xml?sort=${sort}`;
353 export function validEmail(email: string) {
355 /^(([^\s"(),.:;<>@[\\\]]+(\.[^\s"(),.:;<>@[\\\]]+)*)|(".+"))@((\[(?:\d{1,3}\.){3}\d{1,3}])|(([\dA-Za-z\-]+\.)+[A-Za-z]{2,}))$/;
356 return re.test(String(email).toLowerCase());
359 export function capitalizeFirstLetter(str: string): string {
360 return str.charAt(0).toUpperCase() + str.slice(1);
363 export function routeSortTypeToEnum(sort: string): SortType {
364 return SortType[sort];
367 export function listingTypeFromNum(type_: number): ListingType {
368 return Object.values(ListingType)[type_];
371 export function sortTypeFromNum(type_: number): SortType {
372 return Object.values(SortType)[type_];
375 export function routeListingTypeToEnum(type: string): ListingType {
376 return ListingType[type];
379 export function routeDataTypeToEnum(type: string): DataType {
380 return DataType[capitalizeFirstLetter(type)];
383 export function routeSearchTypeToEnum(type: string): SearchType {
384 return SearchType[type];
387 export async function getSiteMetadata(url: string) {
388 let form = new GetSiteMetadata({
391 let client = new LemmyHttp(httpBase);
392 return client.getSiteMetadata(form);
395 export function debounce(func: any, wait = 1000, immediate = false) {
396 // 'private' variable for instance
397 // The returned function will be able to reference this due to closure.
398 // Each call to the returned function will share this common timer.
401 // Calling debounce returns a new anonymous function
403 // reference the context and args for the setTimeout function
404 var args = arguments;
406 // Should the function be called now? If immediate is true
407 // and not already in a timeout then the answer is: Yes
408 var callNow = immediate && !timeout;
410 // This is the basic debounce behaviour where you can call this
411 // function several times, but it will only execute once
412 // [before or after imposing a delay].
413 // Each time the returned function is called, the timer starts over.
414 clearTimeout(timeout);
416 // Set the new timeout
417 timeout = setTimeout(function () {
418 // Inside the timeout function, clear the timeout variable
419 // which will let the next execution run when in 'immediate' mode
422 // Check if the function already ran with the immediate flag
424 // Call the original function with apply
425 // apply lets you define the 'this' object as well as the arguments
426 // (both captured before setTimeout)
427 func.apply(this, args);
431 // Immediate mode and no wait timer? Execute the function..
432 if (callNow) func.apply(this, args);
436 export function getLanguages(
438 myUserInfo = UserService.Instance.myUserInfo
440 let myLang = myUserInfo
441 .map(m => m.local_user_view.local_user.interface_language)
442 .unwrapOr("browser");
443 let lang = override || myLang;
445 if (lang == "browser" && isBrowser()) {
446 return getBrowserLanguages();
452 function getBrowserLanguages(): string[] {
453 // Intersect lemmy's langs, with the browser langs
454 let langs = languages ? languages.map(l => l.code) : ["en"];
456 // NOTE, mobile browsers seem to be missing this list, so append en
457 let allowedLangs = navigator.languages
459 .filter(v => langs.includes(v));
463 export async function fetchThemeList(): Promise<string[]> {
464 return fetch("/css/themelist").then(res => res.json());
467 export async function setTheme(theme: string, forceReload = false) {
471 if (theme === "browser" && !forceReload) {
474 // This is only run on a force reload
475 if (theme == "browser") {
479 let themeList = await fetchThemeList();
481 // Unload all the other themes
482 for (var i = 0; i < themeList.length; i++) {
483 let styleSheet = document.getElementById(themeList[i]);
485 styleSheet.setAttribute("disabled", "disabled");
490 .getElementById("default-light")
491 ?.setAttribute("disabled", "disabled");
492 document.getElementById("default-dark")?.setAttribute("disabled", "disabled");
494 // Load the theme dynamically
495 let cssLoc = `/css/themes/${theme}.css`;
497 loadCss(theme, cssLoc);
498 document.getElementById(theme).removeAttribute("disabled");
501 export function loadCss(id: string, loc: string) {
502 if (!document.getElementById(id)) {
503 var head = document.getElementsByTagName("head")[0];
504 var link = document.createElement("link");
506 link.rel = "stylesheet";
507 link.type = "text/css";
510 head.appendChild(link);
514 export function objectFlip(obj: any) {
516 Object.keys(obj).forEach(key => {
522 export function showAvatars(
523 myUserInfo: Option<MyUserInfo> = UserService.Instance.myUserInfo
526 .map(m => m.local_user_view.local_user.show_avatars)
530 export function showScores(
531 myUserInfo: Option<MyUserInfo> = UserService.Instance.myUserInfo
534 .map(m => m.local_user_view.local_user.show_scores)
538 export function isCakeDay(published: string): boolean {
539 // moment(undefined) or moment.utc(undefined) returns the current date/time
540 // moment(null) or moment.utc(null) returns null
541 const createDate = moment.utc(published).local();
542 const currentDate = moment(new Date());
545 createDate.date() === currentDate.date() &&
546 createDate.month() === currentDate.month() &&
547 createDate.year() !== currentDate.year()
551 export function toast(text: string, background = "success") {
553 let backgroundColor = `var(--${background})`;
556 backgroundColor: backgroundColor,
563 export function pictrsDeleteToast(
564 clickToDeleteText: string,
565 deletePictureText: string,
566 failedDeletePictureText: string,
570 let backgroundColor = `var(--light)`;
571 let toast = Toastify({
572 text: clickToDeleteText,
573 backgroundColor: backgroundColor,
579 fetch(deleteUrl).then(res => {
581 if (res.ok === true) {
582 alert(deletePictureText);
584 alert(failedDeletePictureText);
595 interface NotifyInfo {
597 icon: Option<string>;
602 export function messageToastify(info: NotifyInfo, router: any) {
604 let htmlBody = info.body ? md.render(info.body) : "";
605 let backgroundColor = `var(--light)`;
607 let toast = Toastify({
608 text: `${htmlBody}<br />${info.name}`,
609 avatar: toUndefined(info.icon),
610 backgroundColor: backgroundColor,
611 className: "text-dark",
620 router.history.push(info.link);
628 export function notifyPost(post_view: PostView, router: any) {
629 let info: NotifyInfo = {
630 name: post_view.community.name,
631 icon: post_view.community.icon,
632 link: `/post/${post_view.post.id}`,
633 body: post_view.post.name,
635 notify(info, router);
638 export function notifyComment(comment_view: CommentView, router: any) {
639 let info: NotifyInfo = {
640 name: comment_view.creator.name,
641 icon: comment_view.creator.avatar,
642 link: `/comment/${comment_view.comment.id}`,
643 body: comment_view.comment.content,
645 notify(info, router);
648 export function notifyPrivateMessage(pmv: PrivateMessageView, router: any) {
649 let info: NotifyInfo = {
650 name: pmv.creator.name,
651 icon: pmv.creator.avatar,
653 body: pmv.private_message.content,
655 notify(info, router);
658 function notify(info: NotifyInfo, router: any) {
659 messageToastify(info, router);
661 if (Notification.permission !== "granted") Notification.requestPermission();
663 var notification = new Notification(info.name, {
664 ...{ body: info.body },
665 ...(info.icon.isSome() && { icon: info.icon.unwrap() }),
668 notification.onclick = (ev: Event): any => {
670 router.history.push(info.link);
675 export function setupTribute() {
677 noMatchTemplate: function () {
684 menuItemTemplate: (item: any) => {
685 let shortName = `:${item.original.key}:`;
686 return `${item.original.val} ${shortName}`;
688 selectTemplate: (item: any) => {
689 return `${item.original.val}`;
691 values: Object.entries(emojiShortName).map(e => {
692 return { key: e[1], val: e[0] };
695 autocompleteMode: true,
697 // menuItemLimit: mentionDropdownFetchLimit,
698 menuShowMinLength: 2,
703 selectTemplate: (item: any) => {
704 let it: PersonTribute = item.original;
705 return `[${it.key}](${it.view.person.actor_id})`;
707 values: debounce(async (text: string, cb: any) => {
708 cb(await personSearch(text));
711 autocompleteMode: true,
713 // menuItemLimit: mentionDropdownFetchLimit,
714 menuShowMinLength: 2,
720 selectTemplate: (item: any) => {
721 let it: CommunityTribute = item.original;
722 return `[${it.key}](${it.view.community.actor_id})`;
724 values: debounce(async (text: string, cb: any) => {
725 cb(await communitySearch(text));
728 autocompleteMode: true,
730 // menuItemLimit: mentionDropdownFetchLimit,
731 menuShowMinLength: 2,
737 var tippyInstance: any;
739 tippyInstance = tippy("[data-tippy-content]");
742 export function setupTippy() {
744 tippyInstance.forEach((e: any) => e.destroy());
745 tippyInstance = tippy("[data-tippy-content]", {
747 // Display on "long press"
748 touch: ["hold", 500],
753 interface PersonTribute {
755 view: PersonViewSafe;
758 async function personSearch(text: string): Promise<PersonTribute[]> {
759 let users = (await fetchUsers(text)).users;
760 let persons: PersonTribute[] = users.map(pv => {
761 let tribute: PersonTribute = {
762 key: `@${pv.person.name}@${hostname(pv.person.actor_id)}`,
770 interface CommunityTribute {
775 async function communitySearch(text: string): Promise<CommunityTribute[]> {
776 let comms = (await fetchCommunities(text)).communities;
777 let communities: CommunityTribute[] = comms.map(cv => {
778 let tribute: CommunityTribute = {
779 key: `!${cv.community.name}@${hostname(cv.community.actor_id)}`,
787 export function getListingTypeFromProps(
789 defaultListingType: ListingType,
790 myUserInfo = UserService.Instance.myUserInfo
792 return props.match.params.listing_type
793 ? routeListingTypeToEnum(props.match.params.listing_type)
796 Object.values(ListingType)[
797 me.local_user_view.local_user.default_listing_type
799 none: defaultListingType,
803 export function getListingTypeFromPropsNoDefault(props: any): ListingType {
804 return props.match.params.listing_type
805 ? routeListingTypeToEnum(props.match.params.listing_type)
809 export function getDataTypeFromProps(props: any): DataType {
810 return props.match.params.data_type
811 ? routeDataTypeToEnum(props.match.params.data_type)
815 export function getSortTypeFromProps(
817 myUserInfo = UserService.Instance.myUserInfo
819 return props.match.params.sort
820 ? routeSortTypeToEnum(props.match.params.sort)
823 Object.values(SortType)[
824 mui.local_user_view.local_user.default_sort_type
826 none: SortType.Active,
830 export function getPageFromProps(props: any): number {
831 return props.match.params.page ? Number(props.match.params.page) : 1;
834 export function getRecipientIdFromProps(props: any): number {
835 return props.match.params.recipient_id
836 ? Number(props.match.params.recipient_id)
840 export function getIdFromProps(props: any): Option<number> {
841 let id: string = props.match.params.post_id;
842 return id ? Some(Number(id)) : None;
845 export function getCommentIdFromProps(props: any): Option<number> {
846 let id: string = props.match.params.comment_id;
847 return id ? Some(Number(id)) : None;
850 export function getUsernameFromProps(props: any): string {
851 return props.match.params.username;
854 export function editCommentRes(data: CommentView, comments: CommentView[]) {
855 let found = comments.find(c => c.comment.id == data.comment.id);
857 found.comment.content = data.comment.content;
858 found.comment.distinguished = data.comment.distinguished;
859 found.comment.updated = data.comment.updated;
860 found.comment.removed = data.comment.removed;
861 found.comment.deleted = data.comment.deleted;
862 found.counts.upvotes = data.counts.upvotes;
863 found.counts.downvotes = data.counts.downvotes;
864 found.counts.score = data.counts.score;
868 export function saveCommentRes(data: CommentView, comments: CommentView[]) {
869 let found = comments.find(c => c.comment.id == data.comment.id);
871 found.saved = data.saved;
875 // TODO Should only use the return now, no state?
876 export function updatePersonBlock(
877 data: BlockPersonResponse,
878 myUserInfo = UserService.Instance.myUserInfo
879 ): Option<PersonBlockView[]> {
880 return myUserInfo.match({
881 some: (mui: MyUserInfo) => {
883 mui.person_blocks.push({
884 person: mui.local_user_view.person,
885 target: data.person_view.person,
887 toast(`${i18n.t("blocked")} ${data.person_view.person.name}`);
889 mui.person_blocks = mui.person_blocks.filter(
890 i => i.target.id != data.person_view.person.id
892 toast(`${i18n.t("unblocked")} ${data.person_view.person.name}`);
894 return Some(mui.person_blocks);
900 export function updateCommunityBlock(
901 data: BlockCommunityResponse,
902 myUserInfo = UserService.Instance.myUserInfo
903 ): Option<CommunityBlockView[]> {
904 return myUserInfo.match({
905 some: (mui: MyUserInfo) => {
907 mui.community_blocks.push({
908 person: mui.local_user_view.person,
909 community: data.community_view.community,
911 toast(`${i18n.t("blocked")} ${data.community_view.community.name}`);
913 mui.community_blocks = mui.community_blocks.filter(
914 i => i.community.id != data.community_view.community.id
916 toast(`${i18n.t("unblocked")} ${data.community_view.community.name}`);
918 return Some(mui.community_blocks);
924 export function createCommentLikeRes(
926 comments: CommentView[]
928 let found = comments.find(c => c.comment.id === data.comment.id);
930 found.counts.score = data.counts.score;
931 found.counts.upvotes = data.counts.upvotes;
932 found.counts.downvotes = data.counts.downvotes;
933 if (data.my_vote !== null) {
934 found.my_vote = data.my_vote;
939 export function createPostLikeFindRes(data: PostView, posts: PostView[]) {
940 let found = posts.find(p => p.post.id == data.post.id);
942 createPostLikeRes(data, found);
946 export function createPostLikeRes(data: PostView, post_view: PostView) {
948 post_view.counts.score = data.counts.score;
949 post_view.counts.upvotes = data.counts.upvotes;
950 post_view.counts.downvotes = data.counts.downvotes;
951 if (data.my_vote !== null) {
952 post_view.my_vote = data.my_vote;
957 export function editPostFindRes(data: PostView, posts: PostView[]) {
958 let found = posts.find(p => p.post.id == data.post.id);
960 editPostRes(data, found);
964 export function editPostRes(data: PostView, post: PostView) {
966 post.post.url = data.post.url;
967 post.post.name = data.post.name;
968 post.post.nsfw = data.post.nsfw;
969 post.post.deleted = data.post.deleted;
970 post.post.removed = data.post.removed;
971 post.post.stickied = data.post.stickied;
972 post.post.body = data.post.body;
973 post.post.locked = data.post.locked;
974 post.saved = data.saved;
978 // TODO possible to make these generic?
979 export function updatePostReportRes(
980 data: PostReportView,
981 reports: PostReportView[]
983 let found = reports.find(p => p.post_report.id == data.post_report.id);
985 found.post_report = data.post_report;
989 export function updateCommentReportRes(
990 data: CommentReportView,
991 reports: CommentReportView[]
993 let found = reports.find(c => c.comment_report.id == data.comment_report.id);
995 found.comment_report = data.comment_report;
999 export function updatePrivateMessageReportRes(
1000 data: PrivateMessageReportView,
1001 reports: PrivateMessageReportView[]
1003 let found = reports.find(
1004 c => c.private_message_report.id == data.private_message_report.id
1007 found.private_message_report = data.private_message_report;
1011 export function updateRegistrationApplicationRes(
1012 data: RegistrationApplicationView,
1013 applications: RegistrationApplicationView[]
1015 let found = applications.find(
1016 ra => ra.registration_application.id == data.registration_application.id
1019 found.registration_application = data.registration_application;
1020 found.admin = data.admin;
1021 found.creator_local_user = data.creator_local_user;
1025 export function commentsToFlatNodes(comments: CommentView[]): CommentNodeI[] {
1026 let nodes: CommentNodeI[] = [];
1027 for (let comment of comments) {
1028 nodes.push({ comment_view: comment, children: [], depth: 0 });
1033 export function convertCommentSortType(sort: SortType): CommentSortType {
1035 sort == SortType.TopAll ||
1036 sort == SortType.TopDay ||
1037 sort == SortType.TopWeek ||
1038 sort == SortType.TopMonth ||
1039 sort == SortType.TopYear
1041 return CommentSortType.Top;
1042 } else if (sort == SortType.New) {
1043 return CommentSortType.New;
1044 } else if (sort == SortType.Hot || sort == SortType.Active) {
1045 return CommentSortType.Hot;
1047 return CommentSortType.Hot;
1051 export function buildCommentsTree(
1052 comments: CommentView[],
1053 parentComment: boolean
1055 let map = new Map<number, CommentNodeI>();
1056 let depthOffset = !parentComment
1058 : getDepthFromComment(comments[0].comment);
1060 for (let comment_view of comments) {
1061 let node: CommentNodeI = {
1062 comment_view: comment_view,
1064 depth: getDepthFromComment(comment_view.comment) - depthOffset,
1066 map.set(comment_view.comment.id, { ...node });
1069 let tree: CommentNodeI[] = [];
1071 // if its a parent comment fetch, then push the first comment to the top node.
1072 if (parentComment) {
1073 tree.push(map.get(comments[0].comment.id));
1076 for (let comment_view of comments) {
1077 let child = map.get(comment_view.comment.id);
1078 let parent_id = getCommentParentId(comment_view.comment);
1081 let parent = map.get(parentId);
1082 // Necessary because blocked comment might not exist
1084 parent.children.push(child);
1088 if (!parentComment) {
1098 export function getCommentParentId(comment: CommentI): Option<number> {
1099 let split = comment.path.split(".");
1103 if (split.length > 1) {
1104 return Some(Number(split[split.length - 2]));
1110 export function getDepthFromComment(comment: CommentI): number {
1111 return comment.path.split(".").length - 2;
1114 export function insertCommentIntoTree(
1115 tree: CommentNodeI[],
1117 parentComment: boolean
1119 // Building a fake node to be used for later
1120 let node: CommentNodeI = {
1126 getCommentParentId(cv.comment).match({
1128 let parentComment = searchCommentTree(tree, parentId);
1129 parentComment.match({
1131 node.depth = pComment.depth + 1;
1132 pComment.children.unshift(node);
1138 if (!parentComment) {
1145 export function searchCommentTree(
1146 tree: CommentNodeI[],
1148 ): Option<CommentNodeI> {
1149 for (let node of tree) {
1150 if (node.comment_view.comment.id === id) {
1154 for (const child of node.children) {
1155 let res = searchCommentTree([child], id);
1165 export const colorList: string[] = [
1175 function hsl(num: number) {
1176 return `hsla(${num}, 35%, 50%, 1)`;
1179 export function hostname(url: string): string {
1180 let cUrl = new URL(url);
1181 return cUrl.port ? `${cUrl.hostname}:${cUrl.port}` : `${cUrl.hostname}`;
1184 export function validTitle(title?: string): boolean {
1185 // Initial title is null, minimum length is taken care of by textarea's minLength={3}
1186 if (!title || title.length < 3) return true;
1188 const regex = new RegExp(/.*\S.*/, "g");
1190 return regex.test(title);
1193 export function siteBannerCss(banner: string): string {
1195 background-image: linear-gradient( rgba(0, 0, 0, 0.8), rgba(0, 0, 0, 0.8) ) ,url("${banner}"); \
1196 background-attachment: fixed; \
1197 background-position: top; \
1198 background-repeat: no-repeat; \
1199 background-size: 100% cover; \
1202 max-height: 100vh; \
1206 export function isBrowser() {
1207 return typeof window !== "undefined";
1210 export function setIsoData<Type1, Type2, Type3, Type4, Type5>(
1212 cls1?: ClassConstructor<Type1>,
1213 cls2?: ClassConstructor<Type2>,
1214 cls3?: ClassConstructor<Type3>,
1215 cls4?: ClassConstructor<Type4>,
1216 cls5?: ClassConstructor<Type5>
1218 // If its the browser, you need to deserialize the data from the window
1220 let json = window.isoData;
1221 let routeData = json.routeData;
1222 let routeDataOut: any[] = [];
1224 // Can't do array looping because of specific type constructor required
1226 routeDataOut[0] = convertWindowJson(cls1, routeData[0]);
1229 routeDataOut[1] = convertWindowJson(cls2, routeData[1]);
1232 routeDataOut[2] = convertWindowJson(cls3, routeData[2]);
1235 routeDataOut[3] = convertWindowJson(cls4, routeData[3]);
1238 routeDataOut[4] = convertWindowJson(cls5, routeData[4]);
1240 let site_res = convertWindowJson(GetSiteResponse, json.site_res);
1242 let isoData: IsoData = {
1245 routeData: routeDataOut,
1248 } else return context.router.staticContext;
1252 * Necessary since window ISOData can't store function types like Option
1254 export function convertWindowJson<T>(cls: ClassConstructor<T>, data: any): T {
1255 return deserialize(cls, serialize(data));
1258 export function wsSubscribe(parseMessage: any): Subscription {
1260 return WebSocketService.Instance.subject
1261 .pipe(retryWhen(errors => errors.pipe(delay(3000), take(10))))
1263 msg => parseMessage(msg),
1264 err => console.error(err),
1265 () => console.log("complete")
1272 moment.updateLocale("en", {
1293 export function saveScrollPosition(context: any) {
1294 let path: string = context.router.route.location.pathname;
1295 let y = window.scrollY;
1296 sessionStorage.setItem(`scrollPosition_${path}`, y.toString());
1299 export function restoreScrollPosition(context: any) {
1300 let path: string = context.router.route.location.pathname;
1301 let y = Number(sessionStorage.getItem(`scrollPosition_${path}`));
1302 window.scrollTo(0, y);
1305 export function showLocal(isoData: IsoData): boolean {
1306 return isoData.site_res.federated_instances
1307 .map(f => f.linked.length > 0)
1311 export interface ChoicesValue {
1316 export function communityToChoice(cv: CommunityView): ChoicesValue {
1317 let choice: ChoicesValue = {
1318 value: cv.community.id.toString(),
1319 label: communitySelectName(cv),
1324 export function personToChoice(pvs: PersonViewSafe): ChoicesValue {
1325 let choice: ChoicesValue = {
1326 value: pvs.person.id.toString(),
1327 label: personSelectName(pvs),
1332 export async function fetchCommunities(q: string) {
1333 let form = new Search({
1335 type_: Some(SearchType.Communities),
1336 sort: Some(SortType.TopAll),
1337 listing_type: Some(ListingType.All),
1339 limit: Some(fetchLimit),
1341 community_name: None,
1343 auth: auth(false).ok(),
1345 let client = new LemmyHttp(httpBase);
1346 return client.search(form);
1349 export async function fetchUsers(q: string) {
1350 let form = new Search({
1352 type_: Some(SearchType.Users),
1353 sort: Some(SortType.TopAll),
1354 listing_type: Some(ListingType.All),
1356 limit: Some(fetchLimit),
1358 community_name: None,
1360 auth: auth(false).ok(),
1362 let client = new LemmyHttp(httpBase);
1363 return client.search(form);
1366 export const choicesConfig = {
1368 searchResultLimit: fetchLimit,
1370 containerOuter: "choices custom-select px-0",
1372 "choices__inner bg-secondary border-0 py-0 modlog-choices-font-size",
1373 input: "form-control",
1374 inputCloned: "choices__input--cloned",
1375 list: "choices__list",
1376 listItems: "choices__list--multiple",
1377 listSingle: "choices__list--single py-0",
1378 listDropdown: "choices__list--dropdown",
1379 item: "choices__item bg-secondary",
1380 itemSelectable: "choices__item--selectable",
1381 itemDisabled: "choices__item--disabled",
1382 itemChoice: "choices__item--choice",
1383 placeholder: "choices__placeholder",
1384 group: "choices__group",
1385 groupHeading: "choices__heading",
1386 button: "choices__button",
1387 activeState: "is-active",
1388 focusState: "is-focused",
1389 openState: "is-open",
1390 disabledState: "is-disabled",
1391 highlightedState: "text-info",
1392 selectedState: "text-info",
1393 flippedState: "is-flipped",
1394 loadingState: "is-loading",
1395 noResults: "has-no-results",
1396 noChoices: "has-no-choices",
1400 export function communitySelectName(cv: CommunityView): string {
1401 return cv.community.local
1402 ? cv.community.title
1403 : `${hostname(cv.community.actor_id)}/${cv.community.title}`;
1406 export function personSelectName(pvs: PersonViewSafe): string {
1407 let pName = pvs.person.display_name.unwrapOr(pvs.person.name);
1408 return pvs.person.local ? pName : `${hostname(pvs.person.actor_id)}/${pName}`;
1411 export function initializeSite(site: GetSiteResponse) {
1412 UserService.Instance.myUserInfo = site.my_user;
1413 i18n.changeLanguage(getLanguages()[0]);
1416 const SHORTNUM_SI_FORMAT = new Intl.NumberFormat("en-US", {
1417 maximumSignificantDigits: 3,
1419 notation: "compact",
1420 compactDisplay: "short",
1423 export function numToSI(value: number): string {
1424 return SHORTNUM_SI_FORMAT.format(value);
1427 export function isBanned(ps: PersonSafe): boolean {
1428 let expires = ps.ban_expires;
1429 // Add Z to convert from UTC date
1430 // TODO this check probably isn't necessary anymore
1431 if (expires.isSome()) {
1432 if (ps.banned && new Date(expires.unwrap() + "Z") > new Date()) {
1442 export function pushNotNull(array: any[], new_item?: any) {
1444 array.push(...new_item);
1448 export function auth(throwErr = true): Result<string, string> {
1449 return UserService.Instance.auth(throwErr);
1452 export function enableDownvotes(siteRes: GetSiteResponse): boolean {
1453 return siteRes.site_view.local_site.enable_downvotes;
1456 export function enableNsfw(siteRes: GetSiteResponse): boolean {
1457 return siteRes.site_view.local_site.enable_nsfw;
1460 export function postToCommentSortType(sort: SortType): CommentSortType {
1461 if ([SortType.Active, SortType.Hot].includes(sort)) {
1462 return CommentSortType.Hot;
1463 } else if ([SortType.New, SortType.NewComments].includes(sort)) {
1464 return CommentSortType.New;
1465 } else if (sort == SortType.Old) {
1466 return CommentSortType.Old;
1468 return CommentSortType.Top;
1472 export function arrayGet<T>(arr: Array<T>, index: number): Result<T, string> {
1473 let out = arr.at(index);
1474 if (out == undefined) {
1475 return Err("Index undefined");
1481 export function myFirstDiscussionLanguageId(
1482 myUserInfo = UserService.Instance.myUserInfo
1484 return myUserInfo.andThen(mui =>
1485 arrayGet(mui.discussion_languages, 0)
1491 export function canCreateCommunity(
1492 siteRes: GetSiteResponse,
1493 myUserInfo = UserService.Instance.myUserInfo
1495 let adminOnly = siteRes.site_view.local_site.community_creation_admin_only;
1496 return !adminOnly || amAdmin(myUserInfo);
1499 export function isPostBlocked(
1501 myUserInfo = UserService.Instance.myUserInfo
1506 mui.community_blocks
1507 .map(c => c.community.id)
1508 .includes(pv.community.id) ||
1509 mui.person_blocks.map(p => p.target.id).includes(pv.creator.id)
1514 /// Checks to make sure you can view NSFW posts. Returns true if you can.
1515 export function nsfwCheck(
1517 myUserInfo = UserService.Instance.myUserInfo
1519 let nsfw = pv.post.nsfw || pv.community.nsfw;
1524 .map(m => m.local_user_view.local_user.show_nsfw)
1529 export function getRandomFromList<T>(list : T[]) : T{
1530 return list[Math.floor(Math.random() * list.length)];