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,
27 PrivateMessageReportView,
29 RegistrationApplicationView,
34 } from "lemmy-js-client";
35 import { default as MarkdownIt } from "markdown-it";
36 import markdown_it_container from "markdown-it-container";
37 import markdown_it_footnote from "markdown-it-footnote";
38 import markdown_it_html5_embed from "markdown-it-html5-embed";
39 import markdown_it_sub from "markdown-it-sub";
40 import markdown_it_sup from "markdown-it-sup";
41 import moment from "moment";
42 import { Subscription } from "rxjs";
43 import { delay, retryWhen, take } from "rxjs/operators";
44 import tippy from "tippy.js";
45 import Toastify from "toastify-js";
46 import { httpBase } from "./env";
47 import { i18n, languages } from "./i18next";
48 import { DataType, IsoData } from "./interfaces";
49 import { UserService, WebSocketService } from "./services";
53 Tribute = require("tributejs");
56 export const wsClient = new LemmyWebsocket();
58 export const favIconUrl = "/static/assets/icons/favicon.svg";
59 export const favIconPngUrl = "/static/assets/icons/apple-touch-icon.png";
61 // export const defaultFavIcon = `${window.location.protocol}//${window.location.host}${favIconPngUrl}`;
62 export const repoUrl = "https://github.com/LemmyNet";
63 export const joinLemmyUrl = "https://join-lemmy.org";
64 export const donateLemmyUrl = `${joinLemmyUrl}/donate`;
65 export const docsUrl = `${joinLemmyUrl}/docs/en/index.html`;
66 export const helpGuideUrl = `${joinLemmyUrl}/docs/en/about/guide.html`; // TODO find a way to redirect to the non-en folder
67 export const markdownHelpUrl = `${helpGuideUrl}#using-markdown`;
68 export const sortingHelpUrl = `${helpGuideUrl}#sorting`;
69 export const archiveTodayUrl = "https://archive.today";
70 export const ghostArchiveUrl = "https://ghostarchive.org";
71 export const webArchiveUrl = "https://web.archive.org";
72 export const elementUrl = "https://element.io";
74 export const postRefetchSeconds: number = 60 * 1000;
75 export const fetchLimit = 40;
76 export const trendingFetchLimit = 6;
77 export const mentionDropdownFetchLimit = 10;
78 export const commentTreeMaxDepth = 8;
79 export const markdownFieldCharacterLimit = 50000;
81 export const relTags = "noopener nofollow";
83 const DEFAULT_ALPHABET =
84 "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
86 function getRandomCharFromAlphabet(alphabet: string): string {
87 return alphabet.charAt(Math.floor(Math.random() * alphabet.length));
90 export function randomStr(
92 alphabet = DEFAULT_ALPHABET
95 * Create n-long array and map it to random chars from given alphabet.
96 * Then join individual chars as string
98 return Array.from({ length: idDesiredLength })
100 return getRandomCharFromAlphabet(alphabet);
105 const html5EmbedConfig = {
107 useImageSyntax: true, // Enables video/audio embed with ![]() syntax (default)
109 audio: 'controls preload="metadata"',
110 video: 'width="100%" max-height="100%" controls loop preload="metadata"',
115 const spoilerConfig = {
116 validate: (params: string) => {
117 return params.trim().match(/^spoiler\s+(.*)$/);
120 render: (tokens: any, idx: any) => {
121 var m = tokens[idx].info.trim().match(/^spoiler\s+(.*)$/);
123 if (tokens[idx].nesting === 1) {
125 return `<details><summary> ${md.utils.escapeHtml(m[1])} </summary>\n`;
128 return "</details>\n";
133 const markdownItConfig: MarkdownIt.Options = {
139 export const md = new MarkdownIt(markdownItConfig)
140 .use(markdown_it_sub)
141 .use(markdown_it_sup)
142 .use(markdown_it_footnote)
143 .use(markdown_it_html5_embed, html5EmbedConfig)
144 .use(markdown_it_container, "spoiler", spoilerConfig);
146 export const mdNoImages = new MarkdownIt(markdownItConfig)
147 .use(markdown_it_sub)
148 .use(markdown_it_sup)
149 .use(markdown_it_footnote)
150 .use(markdown_it_html5_embed, html5EmbedConfig)
151 .use(markdown_it_container, "spoiler", spoilerConfig)
154 export function hotRankComment(comment_view: CommentView): number {
155 return hotRank(comment_view.counts.score, comment_view.comment.published);
158 export function hotRankActivePost(post_view: PostView): number {
159 return hotRank(post_view.counts.score, post_view.counts.newest_comment_time);
162 export function hotRankPost(post_view: PostView): number {
163 return hotRank(post_view.counts.score, post_view.post.published);
166 export function hotRank(score: number, timeStr: string): number {
167 // Rank = ScaleFactor * sign(Score) * log(1 + abs(Score)) / (Time + 2)^Gravity
168 let date: Date = new Date(timeStr + "Z"); // Add Z to convert from UTC date
169 let now: Date = new Date();
170 let hoursElapsed: number = (now.getTime() - date.getTime()) / 36e5;
173 (10000 * Math.log10(Math.max(1, 3 + score))) /
174 Math.pow(hoursElapsed + 2, 1.8);
176 // console.log(`Comment: ${comment.content}\nRank: ${rank}\nScore: ${comment.score}\nHours: ${hoursElapsed}`);
181 export function mdToHtml(text: string) {
182 return { __html: md.render(text) };
185 export function mdToHtmlNoImages(text: string) {
186 return { __html: mdNoImages.render(text) };
189 export function mdToHtmlInline(text: string) {
190 return { __html: md.renderInline(text) };
193 export function getUnixTime(text: string): number {
194 return text ? new Date(text).getTime() / 1000 : undefined;
197 export function futureDaysToUnixTime(days: number): number {
200 new Date(Date.now() + 1000 * 60 * 60 * 24 * days).getTime() / 1000
205 export function canMod(
206 mods: Option<CommunityModeratorView[]>,
207 admins: Option<PersonViewSafe[]>,
209 myUserInfo = UserService.Instance.myUserInfo,
212 // You can do moderator actions only on the mods added after you.
213 let adminsThenMods = admins
215 .map(a => a.person.id)
216 .concat(mods.unwrapOr([]).map(m => m.moderator.id));
218 return myUserInfo.match({
220 let myIndex = adminsThenMods.findIndex(
221 id => id == me.local_user_view.person.id
226 // onSelf +1 on mod actions not for yourself, IE ban, remove, etc
227 adminsThenMods = adminsThenMods.slice(0, myIndex + (onSelf ? 0 : 1));
228 return !adminsThenMods.includes(creator_id);
235 export function canAdmin(
236 admins: Option<PersonViewSafe[]>,
238 myUserInfo = UserService.Instance.myUserInfo,
241 return canMod(None, admins, creator_id, myUserInfo, onSelf);
244 export function isMod(
245 mods: Option<CommunityModeratorView[]>,
249 some: mods => mods.map(m => m.moderator.id).includes(creator_id),
254 export function amMod(
255 mods: Option<CommunityModeratorView[]>,
256 myUserInfo = UserService.Instance.myUserInfo
258 return myUserInfo.match({
259 some: mui => isMod(mods, mui.local_user_view.person.id),
264 export function isAdmin(
265 admins: Option<PersonViewSafe[]>,
268 return admins.match({
269 some: admins => admins.map(a => a.person.id).includes(creator_id),
274 export function amAdmin(myUserInfo = UserService.Instance.myUserInfo): boolean {
276 .map(mui => mui.local_user_view.person.admin)
280 export function amCommunityCreator(
281 mods: Option<CommunityModeratorView[]>,
283 myUserInfo = UserService.Instance.myUserInfo
288 .map(mui => mui.local_user_view.person.id)
291 myId == mods[0].moderator.id &&
292 // Don't allow mod actions on yourself
300 export function amSiteCreator(
301 admins: Option<PersonViewSafe[]>,
303 myUserInfo = UserService.Instance.myUserInfo
305 return admins.match({
308 .map(mui => mui.local_user_view.person.id)
311 myId == admins[0].person.id &&
312 // Don't allow mod actions on yourself
320 export function amTopMod(
321 mods: Option<CommunityModeratorView[]>,
322 myUserInfo = UserService.Instance.myUserInfo
327 some: mui => mods[0].moderator.id == mui.local_user_view.person.id,
334 const imageRegex = /(http)?s?:?(\/\/[^"']*\.(?:jpg|jpeg|gif|png|svg|webp))/;
335 const videoRegex = /(http)?s?:?(\/\/[^"']*\.(?:mp4|webm))/;
337 export function isImage(url: string) {
338 return imageRegex.test(url);
341 export function isVideo(url: string) {
342 return videoRegex.test(url);
345 export function validURL(str: string) {
346 return !!new URL(str);
349 export function communityRSSUrl(actorId: string, sort: string): string {
350 let url = new URL(actorId);
351 return `${url.origin}/feeds${url.pathname}.xml?sort=${sort}`;
354 export function validEmail(email: string) {
356 /^(([^\s"(),.:;<>@[\\\]]+(\.[^\s"(),.:;<>@[\\\]]+)*)|(".+"))@((\[(?:\d{1,3}\.){3}\d{1,3}])|(([\dA-Za-z\-]+\.)+[A-Za-z]{2,}))$/;
357 return re.test(String(email).toLowerCase());
360 export function capitalizeFirstLetter(str: string): string {
361 return str.charAt(0).toUpperCase() + str.slice(1);
364 export function routeSortTypeToEnum(sort: string): SortType {
365 return SortType[sort];
368 export function listingTypeFromNum(type_: number): ListingType {
369 return Object.values(ListingType)[type_];
372 export function sortTypeFromNum(type_: number): SortType {
373 return Object.values(SortType)[type_];
376 export function routeListingTypeToEnum(type: string): ListingType {
377 return ListingType[type];
380 export function routeDataTypeToEnum(type: string): DataType {
381 return DataType[capitalizeFirstLetter(type)];
384 export function routeSearchTypeToEnum(type: string): SearchType {
385 return SearchType[type];
388 export async function getSiteMetadata(url: string) {
389 let form = new GetSiteMetadata({
392 let client = new LemmyHttp(httpBase);
393 return client.getSiteMetadata(form);
396 export function debounce(func: any, wait = 1000, immediate = false) {
397 // 'private' variable for instance
398 // The returned function will be able to reference this due to closure.
399 // Each call to the returned function will share this common timer.
402 // Calling debounce returns a new anonymous function
404 // reference the context and args for the setTimeout function
405 var args = arguments;
407 // Should the function be called now? If immediate is true
408 // and not already in a timeout then the answer is: Yes
409 var callNow = immediate && !timeout;
411 // This is the basic debounce behaviour where you can call this
412 // function several times, but it will only execute once
413 // [before or after imposing a delay].
414 // Each time the returned function is called, the timer starts over.
415 clearTimeout(timeout);
417 // Set the new timeout
418 timeout = setTimeout(function () {
419 // Inside the timeout function, clear the timeout variable
420 // which will let the next execution run when in 'immediate' mode
423 // Check if the function already ran with the immediate flag
425 // Call the original function with apply
426 // apply lets you define the 'this' object as well as the arguments
427 // (both captured before setTimeout)
428 func.apply(this, args);
432 // Immediate mode and no wait timer? Execute the function..
433 if (callNow) func.apply(this, args);
437 export function getLanguages(
439 myUserInfo = UserService.Instance.myUserInfo
441 let myLang = myUserInfo
442 .map(m => m.local_user_view.local_user.interface_language)
443 .unwrapOr("browser");
444 let lang = override || myLang;
446 if (lang == "browser" && isBrowser()) {
447 return getBrowserLanguages();
453 function getBrowserLanguages(): string[] {
454 // Intersect lemmy's langs, with the browser langs
455 let langs = languages ? languages.map(l => l.code) : ["en"];
457 // NOTE, mobile browsers seem to be missing this list, so append en
458 let allowedLangs = navigator.languages
460 .filter(v => langs.includes(v));
464 export async function fetchThemeList(): Promise<string[]> {
465 return fetch("/css/themelist").then(res => res.json());
468 export async function setTheme(theme: string, forceReload = false) {
472 if (theme === "browser" && !forceReload) {
475 // This is only run on a force reload
476 if (theme == "browser") {
480 let themeList = await fetchThemeList();
482 // Unload all the other themes
483 for (var i = 0; i < themeList.length; i++) {
484 let styleSheet = document.getElementById(themeList[i]);
486 styleSheet.setAttribute("disabled", "disabled");
491 .getElementById("default-light")
492 ?.setAttribute("disabled", "disabled");
493 document.getElementById("default-dark")?.setAttribute("disabled", "disabled");
495 // Load the theme dynamically
496 let cssLoc = `/css/themes/${theme}.css`;
498 loadCss(theme, cssLoc);
499 document.getElementById(theme).removeAttribute("disabled");
502 export function loadCss(id: string, loc: string) {
503 if (!document.getElementById(id)) {
504 var head = document.getElementsByTagName("head")[0];
505 var link = document.createElement("link");
507 link.rel = "stylesheet";
508 link.type = "text/css";
511 head.appendChild(link);
515 export function objectFlip(obj: any) {
517 Object.keys(obj).forEach(key => {
523 export function showAvatars(
524 myUserInfo: Option<MyUserInfo> = UserService.Instance.myUserInfo
527 .map(m => m.local_user_view.local_user.show_avatars)
531 export function showScores(
532 myUserInfo: Option<MyUserInfo> = UserService.Instance.myUserInfo
535 .map(m => m.local_user_view.local_user.show_scores)
539 export function isCakeDay(published: string): boolean {
540 // moment(undefined) or moment.utc(undefined) returns the current date/time
541 // moment(null) or moment.utc(null) returns null
542 const createDate = moment.utc(published).local();
543 const currentDate = moment(new Date());
546 createDate.date() === currentDate.date() &&
547 createDate.month() === currentDate.month() &&
548 createDate.year() !== currentDate.year()
552 export function toast(text: string, background = "success") {
554 let backgroundColor = `var(--${background})`;
557 backgroundColor: backgroundColor,
564 export function pictrsDeleteToast(
565 clickToDeleteText: string,
566 deletePictureText: string,
567 failedDeletePictureText: string,
571 let backgroundColor = `var(--light)`;
572 let toast = Toastify({
573 text: clickToDeleteText,
574 backgroundColor: backgroundColor,
580 fetch(deleteUrl).then(res => {
582 if (res.ok === true) {
583 alert(deletePictureText);
585 alert(failedDeletePictureText);
596 interface NotifyInfo {
598 icon: Option<string>;
603 export function messageToastify(info: NotifyInfo, router: any) {
605 let htmlBody = info.body ? md.render(info.body) : "";
606 let backgroundColor = `var(--light)`;
608 let toast = Toastify({
609 text: `${htmlBody}<br />${info.name}`,
610 avatar: toUndefined(info.icon),
611 backgroundColor: backgroundColor,
612 className: "text-dark",
621 router.history.push(info.link);
629 export function notifyPost(post_view: PostView, router: any) {
630 let info: NotifyInfo = {
631 name: post_view.community.name,
632 icon: post_view.community.icon,
633 link: `/post/${post_view.post.id}`,
634 body: post_view.post.name,
636 notify(info, router);
639 export function notifyComment(comment_view: CommentView, router: any) {
640 let info: NotifyInfo = {
641 name: comment_view.creator.name,
642 icon: comment_view.creator.avatar,
643 link: `/comment/${comment_view.comment.id}`,
644 body: comment_view.comment.content,
646 notify(info, router);
649 export function notifyPrivateMessage(pmv: PrivateMessageView, router: any) {
650 let info: NotifyInfo = {
651 name: pmv.creator.name,
652 icon: pmv.creator.avatar,
654 body: pmv.private_message.content,
656 notify(info, router);
659 function notify(info: NotifyInfo, router: any) {
660 messageToastify(info, router);
662 if (Notification.permission !== "granted") Notification.requestPermission();
664 var notification = new Notification(info.name, {
665 ...{ body: info.body },
666 ...(info.icon.isSome() && { icon: info.icon.unwrap() }),
669 notification.onclick = (ev: Event): any => {
671 router.history.push(info.link);
676 export function setupTribute() {
678 noMatchTemplate: function () {
685 menuItemTemplate: (item: any) => {
686 let shortName = `:${item.original.key}:`;
687 return `${item.original.val} ${shortName}`;
689 selectTemplate: (item: any) => {
690 return `${item.original.val}`;
692 values: Object.entries(emojiShortName).map(e => {
693 return { key: e[1], val: e[0] };
696 autocompleteMode: true,
698 // menuItemLimit: mentionDropdownFetchLimit,
699 menuShowMinLength: 2,
704 selectTemplate: (item: any) => {
705 let it: PersonTribute = item.original;
706 return `[${it.key}](${it.view.person.actor_id})`;
708 values: debounce(async (text: string, cb: any) => {
709 cb(await personSearch(text));
712 autocompleteMode: true,
714 // menuItemLimit: mentionDropdownFetchLimit,
715 menuShowMinLength: 2,
721 selectTemplate: (item: any) => {
722 let it: CommunityTribute = item.original;
723 return `[${it.key}](${it.view.community.actor_id})`;
725 values: debounce(async (text: string, cb: any) => {
726 cb(await communitySearch(text));
729 autocompleteMode: true,
731 // menuItemLimit: mentionDropdownFetchLimit,
732 menuShowMinLength: 2,
738 var tippyInstance: any;
740 tippyInstance = tippy("[data-tippy-content]");
743 export function setupTippy() {
745 tippyInstance.forEach((e: any) => e.destroy());
746 tippyInstance = tippy("[data-tippy-content]", {
748 // Display on "long press"
749 touch: ["hold", 500],
754 interface PersonTribute {
756 view: PersonViewSafe;
759 async function personSearch(text: string): Promise<PersonTribute[]> {
760 let users = (await fetchUsers(text)).users;
761 let persons: PersonTribute[] = users.map(pv => {
762 let tribute: PersonTribute = {
763 key: `@${pv.person.name}@${hostname(pv.person.actor_id)}`,
771 interface CommunityTribute {
776 async function communitySearch(text: string): Promise<CommunityTribute[]> {
777 let comms = (await fetchCommunities(text)).communities;
778 let communities: CommunityTribute[] = comms.map(cv => {
779 let tribute: CommunityTribute = {
780 key: `!${cv.community.name}@${hostname(cv.community.actor_id)}`,
788 export function getListingTypeFromProps(
790 defaultListingType: ListingType,
791 myUserInfo = UserService.Instance.myUserInfo
793 return props.match.params.listing_type
794 ? routeListingTypeToEnum(props.match.params.listing_type)
797 Object.values(ListingType)[
798 me.local_user_view.local_user.default_listing_type
800 none: defaultListingType,
804 export function getListingTypeFromPropsNoDefault(props: any): ListingType {
805 return props.match.params.listing_type
806 ? routeListingTypeToEnum(props.match.params.listing_type)
810 export function getDataTypeFromProps(props: any): DataType {
811 return props.match.params.data_type
812 ? routeDataTypeToEnum(props.match.params.data_type)
816 export function getSortTypeFromProps(
818 myUserInfo = UserService.Instance.myUserInfo
820 return props.match.params.sort
821 ? routeSortTypeToEnum(props.match.params.sort)
824 Object.values(SortType)[
825 mui.local_user_view.local_user.default_sort_type
827 none: SortType.Active,
831 export function getPageFromProps(props: any): number {
832 return props.match.params.page ? Number(props.match.params.page) : 1;
835 export function getRecipientIdFromProps(props: any): number {
836 return props.match.params.recipient_id
837 ? Number(props.match.params.recipient_id)
841 export function getIdFromProps(props: any): Option<number> {
842 let id: string = props.match.params.post_id;
843 return id ? Some(Number(id)) : None;
846 export function getCommentIdFromProps(props: any): Option<number> {
847 let id: string = props.match.params.comment_id;
848 return id ? Some(Number(id)) : None;
851 export function getUsernameFromProps(props: any): string {
852 return props.match.params.username;
855 export function editCommentRes(data: CommentView, comments: CommentView[]) {
856 let found = comments.find(c => c.comment.id == data.comment.id);
858 found.comment.content = data.comment.content;
859 found.comment.distinguished = data.comment.distinguished;
860 found.comment.updated = data.comment.updated;
861 found.comment.removed = data.comment.removed;
862 found.comment.deleted = data.comment.deleted;
863 found.counts.upvotes = data.counts.upvotes;
864 found.counts.downvotes = data.counts.downvotes;
865 found.counts.score = data.counts.score;
869 export function saveCommentRes(data: CommentView, comments: CommentView[]) {
870 let found = comments.find(c => c.comment.id == data.comment.id);
872 found.saved = data.saved;
876 // TODO Should only use the return now, no state?
877 export function updatePersonBlock(
878 data: BlockPersonResponse,
879 myUserInfo = UserService.Instance.myUserInfo
880 ): Option<PersonBlockView[]> {
881 return myUserInfo.match({
882 some: (mui: MyUserInfo) => {
884 mui.person_blocks.push({
885 person: mui.local_user_view.person,
886 target: data.person_view.person,
888 toast(`${i18n.t("blocked")} ${data.person_view.person.name}`);
890 mui.person_blocks = mui.person_blocks.filter(
891 i => i.target.id != data.person_view.person.id
893 toast(`${i18n.t("unblocked")} ${data.person_view.person.name}`);
895 return Some(mui.person_blocks);
901 export function updateCommunityBlock(
902 data: BlockCommunityResponse,
903 myUserInfo = UserService.Instance.myUserInfo
904 ): Option<CommunityBlockView[]> {
905 return myUserInfo.match({
906 some: (mui: MyUserInfo) => {
908 mui.community_blocks.push({
909 person: mui.local_user_view.person,
910 community: data.community_view.community,
912 toast(`${i18n.t("blocked")} ${data.community_view.community.name}`);
914 mui.community_blocks = mui.community_blocks.filter(
915 i => i.community.id != data.community_view.community.id
917 toast(`${i18n.t("unblocked")} ${data.community_view.community.name}`);
919 return Some(mui.community_blocks);
925 export function createCommentLikeRes(
927 comments: CommentView[]
929 let found = comments.find(c => c.comment.id === data.comment.id);
931 found.counts.score = data.counts.score;
932 found.counts.upvotes = data.counts.upvotes;
933 found.counts.downvotes = data.counts.downvotes;
934 if (data.my_vote !== null) {
935 found.my_vote = data.my_vote;
940 export function createPostLikeFindRes(data: PostView, posts: PostView[]) {
941 let found = posts.find(p => p.post.id == data.post.id);
943 createPostLikeRes(data, found);
947 export function createPostLikeRes(data: PostView, post_view: PostView) {
949 post_view.counts.score = data.counts.score;
950 post_view.counts.upvotes = data.counts.upvotes;
951 post_view.counts.downvotes = data.counts.downvotes;
952 if (data.my_vote !== null) {
953 post_view.my_vote = data.my_vote;
958 export function editPostFindRes(data: PostView, posts: PostView[]) {
959 let found = posts.find(p => p.post.id == data.post.id);
961 editPostRes(data, found);
965 export function editPostRes(data: PostView, post: PostView) {
967 post.post.url = data.post.url;
968 post.post.name = data.post.name;
969 post.post.nsfw = data.post.nsfw;
970 post.post.deleted = data.post.deleted;
971 post.post.removed = data.post.removed;
972 post.post.featured_community = data.post.featured_community;
973 post.post.featured_local = data.post.featured_local;
974 post.post.body = data.post.body;
975 post.post.locked = data.post.locked;
976 post.saved = data.saved;
980 // TODO possible to make these generic?
981 export function updatePostReportRes(
982 data: PostReportView,
983 reports: PostReportView[]
985 let found = reports.find(p => p.post_report.id == data.post_report.id);
987 found.post_report = data.post_report;
991 export function updateCommentReportRes(
992 data: CommentReportView,
993 reports: CommentReportView[]
995 let found = reports.find(c => c.comment_report.id == data.comment_report.id);
997 found.comment_report = data.comment_report;
1001 export function updatePrivateMessageReportRes(
1002 data: PrivateMessageReportView,
1003 reports: PrivateMessageReportView[]
1005 let found = reports.find(
1006 c => c.private_message_report.id == data.private_message_report.id
1009 found.private_message_report = data.private_message_report;
1013 export function updateRegistrationApplicationRes(
1014 data: RegistrationApplicationView,
1015 applications: RegistrationApplicationView[]
1017 let found = applications.find(
1018 ra => ra.registration_application.id == data.registration_application.id
1021 found.registration_application = data.registration_application;
1022 found.admin = data.admin;
1023 found.creator_local_user = data.creator_local_user;
1027 export function commentsToFlatNodes(comments: CommentView[]): CommentNodeI[] {
1028 let nodes: CommentNodeI[] = [];
1029 for (let comment of comments) {
1030 nodes.push({ comment_view: comment, children: [], depth: 0 });
1035 export function convertCommentSortType(sort: SortType): CommentSortType {
1037 sort == SortType.TopAll ||
1038 sort == SortType.TopDay ||
1039 sort == SortType.TopWeek ||
1040 sort == SortType.TopMonth ||
1041 sort == SortType.TopYear
1043 return CommentSortType.Top;
1044 } else if (sort == SortType.New) {
1045 return CommentSortType.New;
1046 } else if (sort == SortType.Hot || sort == SortType.Active) {
1047 return CommentSortType.Hot;
1049 return CommentSortType.Hot;
1053 export function buildCommentsTree(
1054 comments: CommentView[],
1055 parentComment: boolean
1057 let map = new Map<number, CommentNodeI>();
1058 let depthOffset = !parentComment
1060 : getDepthFromComment(comments[0].comment);
1062 for (let comment_view of comments) {
1063 let node: CommentNodeI = {
1064 comment_view: comment_view,
1066 depth: getDepthFromComment(comment_view.comment) - depthOffset,
1068 map.set(comment_view.comment.id, { ...node });
1071 let tree: CommentNodeI[] = [];
1073 // if its a parent comment fetch, then push the first comment to the top node.
1074 if (parentComment) {
1075 tree.push(map.get(comments[0].comment.id));
1078 for (let comment_view of comments) {
1079 let child = map.get(comment_view.comment.id);
1080 let parent_id = getCommentParentId(comment_view.comment);
1083 let parent = map.get(parentId);
1084 // Necessary because blocked comment might not exist
1086 parent.children.push(child);
1090 if (!parentComment) {
1100 export function getCommentParentId(comment: CommentI): Option<number> {
1101 let split = comment.path.split(".");
1105 if (split.length > 1) {
1106 return Some(Number(split[split.length - 2]));
1112 export function getDepthFromComment(comment: CommentI): number {
1113 return comment.path.split(".").length - 2;
1116 export function insertCommentIntoTree(
1117 tree: CommentNodeI[],
1119 parentComment: boolean
1121 // Building a fake node to be used for later
1122 let node: CommentNodeI = {
1128 getCommentParentId(cv.comment).match({
1130 let parentComment = searchCommentTree(tree, parentId);
1131 parentComment.match({
1133 node.depth = pComment.depth + 1;
1134 pComment.children.unshift(node);
1140 if (!parentComment) {
1147 export function searchCommentTree(
1148 tree: CommentNodeI[],
1150 ): Option<CommentNodeI> {
1151 for (let node of tree) {
1152 if (node.comment_view.comment.id === id) {
1156 for (const child of node.children) {
1157 let res = searchCommentTree([child], id);
1167 export const colorList: string[] = [
1177 function hsl(num: number) {
1178 return `hsla(${num}, 35%, 50%, 1)`;
1181 export function hostname(url: string): string {
1182 let cUrl = new URL(url);
1183 return cUrl.port ? `${cUrl.hostname}:${cUrl.port}` : `${cUrl.hostname}`;
1186 export function validTitle(title?: string): boolean {
1187 // Initial title is null, minimum length is taken care of by textarea's minLength={3}
1188 if (!title || title.length < 3) return true;
1190 const regex = new RegExp(/.*\S.*/, "g");
1192 return regex.test(title);
1195 export function siteBannerCss(banner: string): string {
1197 background-image: linear-gradient( rgba(0, 0, 0, 0.8), rgba(0, 0, 0, 0.8) ) ,url("${banner}"); \
1198 background-attachment: fixed; \
1199 background-position: top; \
1200 background-repeat: no-repeat; \
1201 background-size: 100% cover; \
1204 max-height: 100vh; \
1208 export function isBrowser() {
1209 return typeof window !== "undefined";
1212 export function setIsoData<Type1, Type2, Type3, Type4, Type5>(
1214 cls1?: ClassConstructor<Type1>,
1215 cls2?: ClassConstructor<Type2>,
1216 cls3?: ClassConstructor<Type3>,
1217 cls4?: ClassConstructor<Type4>,
1218 cls5?: ClassConstructor<Type5>
1220 // If its the browser, you need to deserialize the data from the window
1222 let json = window.isoData;
1223 let routeData = json.routeData;
1224 let routeDataOut: any[] = [];
1226 // Can't do array looping because of specific type constructor required
1228 routeDataOut[0] = convertWindowJson(cls1, routeData[0]);
1231 routeDataOut[1] = convertWindowJson(cls2, routeData[1]);
1234 routeDataOut[2] = convertWindowJson(cls3, routeData[2]);
1237 routeDataOut[3] = convertWindowJson(cls4, routeData[3]);
1240 routeDataOut[4] = convertWindowJson(cls5, routeData[4]);
1242 let site_res = convertWindowJson(GetSiteResponse, json.site_res);
1244 let isoData: IsoData = {
1247 routeData: routeDataOut,
1250 } else return context.router.staticContext;
1254 * Necessary since window ISOData can't store function types like Option
1256 export function convertWindowJson<T>(cls: ClassConstructor<T>, data: any): T {
1257 return deserialize(cls, serialize(data));
1260 export function wsSubscribe(parseMessage: any): Subscription {
1262 return WebSocketService.Instance.subject
1263 .pipe(retryWhen(errors => errors.pipe(delay(3000), take(10))))
1265 msg => parseMessage(msg),
1266 err => console.error(err),
1267 () => console.log("complete")
1274 moment.updateLocale("en", {
1295 export function saveScrollPosition(context: any) {
1296 let path: string = context.router.route.location.pathname;
1297 let y = window.scrollY;
1298 sessionStorage.setItem(`scrollPosition_${path}`, y.toString());
1301 export function restoreScrollPosition(context: any) {
1302 let path: string = context.router.route.location.pathname;
1303 let y = Number(sessionStorage.getItem(`scrollPosition_${path}`));
1304 window.scrollTo(0, y);
1307 export function showLocal(isoData: IsoData): boolean {
1308 return isoData.site_res.federated_instances
1309 .map(f => f.linked.length > 0)
1313 export interface ChoicesValue {
1318 export function communityToChoice(cv: CommunityView): ChoicesValue {
1319 let choice: ChoicesValue = {
1320 value: cv.community.id.toString(),
1321 label: communitySelectName(cv),
1326 export function personToChoice(pvs: PersonViewSafe): ChoicesValue {
1327 let choice: ChoicesValue = {
1328 value: pvs.person.id.toString(),
1329 label: personSelectName(pvs),
1334 export async function fetchCommunities(q: string) {
1335 let form = new Search({
1337 type_: Some(SearchType.Communities),
1338 sort: Some(SortType.TopAll),
1339 listing_type: Some(ListingType.All),
1341 limit: Some(fetchLimit),
1343 community_name: None,
1345 auth: auth(false).ok(),
1347 let client = new LemmyHttp(httpBase);
1348 return client.search(form);
1351 export async function fetchUsers(q: string) {
1352 let form = new Search({
1354 type_: Some(SearchType.Users),
1355 sort: Some(SortType.TopAll),
1356 listing_type: Some(ListingType.All),
1358 limit: Some(fetchLimit),
1360 community_name: None,
1362 auth: auth(false).ok(),
1364 let client = new LemmyHttp(httpBase);
1365 return client.search(form);
1368 export const choicesConfig = {
1370 searchResultLimit: fetchLimit,
1372 containerOuter: "choices custom-select px-0",
1374 "choices__inner bg-secondary border-0 py-0 modlog-choices-font-size",
1375 input: "form-control",
1376 inputCloned: "choices__input--cloned",
1377 list: "choices__list",
1378 listItems: "choices__list--multiple",
1379 listSingle: "choices__list--single py-0",
1380 listDropdown: "choices__list--dropdown",
1381 item: "choices__item bg-secondary",
1382 itemSelectable: "choices__item--selectable",
1383 itemDisabled: "choices__item--disabled",
1384 itemChoice: "choices__item--choice",
1385 placeholder: "choices__placeholder",
1386 group: "choices__group",
1387 groupHeading: "choices__heading",
1388 button: "choices__button",
1389 activeState: "is-active",
1390 focusState: "is-focused",
1391 openState: "is-open",
1392 disabledState: "is-disabled",
1393 highlightedState: "text-info",
1394 selectedState: "text-info",
1395 flippedState: "is-flipped",
1396 loadingState: "is-loading",
1397 noResults: "has-no-results",
1398 noChoices: "has-no-choices",
1402 export function communitySelectName(cv: CommunityView): string {
1403 return cv.community.local
1404 ? cv.community.title
1405 : `${hostname(cv.community.actor_id)}/${cv.community.title}`;
1408 export function personSelectName(pvs: PersonViewSafe): string {
1409 let pName = pvs.person.display_name.unwrapOr(pvs.person.name);
1410 return pvs.person.local ? pName : `${hostname(pvs.person.actor_id)}/${pName}`;
1413 export function initializeSite(site: GetSiteResponse) {
1414 UserService.Instance.myUserInfo = site.my_user;
1415 i18n.changeLanguage(getLanguages()[0]);
1418 const SHORTNUM_SI_FORMAT = new Intl.NumberFormat("en-US", {
1419 maximumSignificantDigits: 3,
1421 notation: "compact",
1422 compactDisplay: "short",
1425 export function numToSI(value: number): string {
1426 return SHORTNUM_SI_FORMAT.format(value);
1429 export function isBanned(ps: PersonSafe): boolean {
1430 let expires = ps.ban_expires;
1431 // Add Z to convert from UTC date
1432 // TODO this check probably isn't necessary anymore
1433 if (expires.isSome()) {
1434 if (ps.banned && new Date(expires.unwrap() + "Z") > new Date()) {
1444 export function pushNotNull(array: any[], new_item?: any) {
1446 array.push(...new_item);
1450 export function auth(throwErr = true): Result<string, string> {
1451 return UserService.Instance.auth(throwErr);
1454 export function enableDownvotes(siteRes: GetSiteResponse): boolean {
1455 return siteRes.site_view.local_site.enable_downvotes;
1458 export function enableNsfw(siteRes: GetSiteResponse): boolean {
1459 return siteRes.site_view.local_site.enable_nsfw;
1462 export function postToCommentSortType(sort: SortType): CommentSortType {
1463 if ([SortType.Active, SortType.Hot].includes(sort)) {
1464 return CommentSortType.Hot;
1465 } else if ([SortType.New, SortType.NewComments].includes(sort)) {
1466 return CommentSortType.New;
1467 } else if (sort == SortType.Old) {
1468 return CommentSortType.Old;
1470 return CommentSortType.Top;
1474 export function arrayGet<T>(arr: Array<T>, index: number): Result<T, string> {
1475 let out = arr.at(index);
1476 if (out == undefined) {
1477 return Err("Index undefined");
1483 export function myFirstDiscussionLanguageId(
1484 allLanguages: Language[],
1485 siteLanguages: number[],
1486 myUserInfo = UserService.Instance.myUserInfo
1489 selectableLanguages(allLanguages, siteLanguages, false, false, myUserInfo),
1496 export function canCreateCommunity(
1497 siteRes: GetSiteResponse,
1498 myUserInfo = UserService.Instance.myUserInfo
1500 let adminOnly = siteRes.site_view.local_site.community_creation_admin_only;
1501 return !adminOnly || amAdmin(myUserInfo);
1504 export function isPostBlocked(
1506 myUserInfo = UserService.Instance.myUserInfo
1511 mui.community_blocks
1512 .map(c => c.community.id)
1513 .includes(pv.community.id) ||
1514 mui.person_blocks.map(p => p.target.id).includes(pv.creator.id)
1519 /// Checks to make sure you can view NSFW posts. Returns true if you can.
1520 export function nsfwCheck(
1522 myUserInfo = UserService.Instance.myUserInfo
1524 let nsfw = pv.post.nsfw || pv.community.nsfw;
1529 .map(m => m.local_user_view.local_user.show_nsfw)
1534 export function getRandomFromList<T>(list: T[]): T {
1535 return list[Math.floor(Math.random() * list.length)];
1539 * This shows what language you can select
1541 * Use showAll for the site form
1542 * Use showSite for the profile and community forms
1543 * Use false for both those to filter on your profile and site ones
1545 export function selectableLanguages(
1546 allLanguages: Language[],
1547 siteLanguages: number[],
1550 myUserInfo = UserService.Instance.myUserInfo
1552 let allLangIds = allLanguages.map(l => l.id);
1553 let myLangs = myUserInfo
1554 .map(mui => mui.discussion_languages)
1555 .unwrapOr(allLangIds);
1556 myLangs = myLangs.length == 0 ? allLangIds : myLangs;
1557 let siteLangs = siteLanguages.length == 0 ? allLangIds : siteLanguages;
1560 return allLanguages;
1563 return allLanguages.filter(x => siteLangs.includes(x.id));
1566 .filter(x => siteLangs.includes(x.id))
1567 .filter(x => myLangs.includes(x.id));