1 import emojiShortName from "emoji-short-name";
3 BlockCommunityResponse,
6 CommentNode as CommentNodeI,
10 CommunityModeratorView,
22 PrivateMessageReportView,
24 RegistrationApplicationView,
28 } from "lemmy-js-client";
29 import { default as MarkdownIt } from "markdown-it";
30 import markdown_it_container from "markdown-it-container";
31 import markdown_it_footnote from "markdown-it-footnote";
32 import markdown_it_html5_embed from "markdown-it-html5-embed";
33 import markdown_it_sub from "markdown-it-sub";
34 import markdown_it_sup from "markdown-it-sup";
35 import moment from "moment";
36 import { Subscription } from "rxjs";
37 import { delay, retryWhen, take } from "rxjs/operators";
38 import tippy from "tippy.js";
39 import Toastify from "toastify-js";
40 import { httpBase } from "./env";
41 import { i18n, languages } from "./i18next";
42 import { DataType, IsoData } from "./interfaces";
43 import { UserService, WebSocketService } from "./services";
47 Tribute = require("tributejs");
50 export const wsClient = new LemmyWebsocket();
52 export const favIconUrl = "/static/assets/icons/favicon.svg";
53 export const favIconPngUrl = "/static/assets/icons/apple-touch-icon.png";
55 // export const defaultFavIcon = `${window.location.protocol}//${window.location.host}${favIconPngUrl}`;
56 export const repoUrl = "https://github.com/LemmyNet";
57 export const joinLemmyUrl = "https://join-lemmy.org";
58 export const donateLemmyUrl = `${joinLemmyUrl}/donate`;
59 export const docsUrl = `${joinLemmyUrl}/docs/en/index.html`;
60 export const helpGuideUrl = `${joinLemmyUrl}/docs/en/about/guide.html`; // TODO find a way to redirect to the non-en folder
61 export const markdownHelpUrl = `${helpGuideUrl}#using-markdown`;
62 export const sortingHelpUrl = `${helpGuideUrl}#sorting`;
63 export const archiveTodayUrl = "https://archive.today";
64 export const ghostArchiveUrl = "https://ghostarchive.org";
65 export const webArchiveUrl = "https://web.archive.org";
66 export const elementUrl = "https://element.io";
68 export const postRefetchSeconds: number = 60 * 1000;
69 export const fetchLimit = 40;
70 export const trendingFetchLimit = 6;
71 export const mentionDropdownFetchLimit = 10;
72 export const commentTreeMaxDepth = 8;
73 export const markdownFieldCharacterLimit = 50000;
75 export const relTags = "noopener nofollow";
77 const DEFAULT_ALPHABET =
78 "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
80 function getRandomCharFromAlphabet(alphabet: string): string {
81 return alphabet.charAt(Math.floor(Math.random() * alphabet.length));
84 export function randomStr(
86 alphabet = DEFAULT_ALPHABET
89 * Create n-long array and map it to random chars from given alphabet.
90 * Then join individual chars as string
92 return Array.from({ length: idDesiredLength })
94 return getRandomCharFromAlphabet(alphabet);
99 const html5EmbedConfig = {
101 useImageSyntax: true, // Enables video/audio embed with ![]() syntax (default)
103 audio: 'controls preload="metadata"',
104 video: 'width="100%" max-height="100%" controls loop preload="metadata"',
109 const spoilerConfig = {
110 validate: (params: string) => {
111 return params.trim().match(/^spoiler\s+(.*)$/);
114 render: (tokens: any, idx: any) => {
115 var m = tokens[idx].info.trim().match(/^spoiler\s+(.*)$/);
117 if (tokens[idx].nesting === 1) {
119 return `<details><summary> ${md.utils.escapeHtml(m[1])} </summary>\n`;
122 return "</details>\n";
127 const markdownItConfig: MarkdownIt.Options = {
133 export const md = new MarkdownIt(markdownItConfig)
134 .use(markdown_it_sub)
135 .use(markdown_it_sup)
136 .use(markdown_it_footnote)
137 .use(markdown_it_html5_embed, html5EmbedConfig)
138 .use(markdown_it_container, "spoiler", spoilerConfig);
140 export const mdNoImages = new MarkdownIt(markdownItConfig)
141 .use(markdown_it_sub)
142 .use(markdown_it_sup)
143 .use(markdown_it_footnote)
144 .use(markdown_it_html5_embed, html5EmbedConfig)
145 .use(markdown_it_container, "spoiler", spoilerConfig)
148 export function hotRankComment(comment_view: CommentView): number {
149 return hotRank(comment_view.counts.score, comment_view.comment.published);
152 export function hotRankActivePost(post_view: PostView): number {
153 return hotRank(post_view.counts.score, post_view.counts.newest_comment_time);
156 export function hotRankPost(post_view: PostView): number {
157 return hotRank(post_view.counts.score, post_view.post.published);
160 export function hotRank(score: number, timeStr: string): number {
161 // Rank = ScaleFactor * sign(Score) * log(1 + abs(Score)) / (Time + 2)^Gravity
162 let date: Date = new Date(timeStr + "Z"); // Add Z to convert from UTC date
163 let now: Date = new Date();
164 let hoursElapsed: number = (now.getTime() - date.getTime()) / 36e5;
167 (10000 * Math.log10(Math.max(1, 3 + score))) /
168 Math.pow(hoursElapsed + 2, 1.8);
170 // console.log(`Comment: ${comment.content}\nRank: ${rank}\nScore: ${comment.score}\nHours: ${hoursElapsed}`);
175 export function mdToHtml(text: string) {
176 return { __html: md.render(text) };
179 export function mdToHtmlNoImages(text: string) {
180 return { __html: mdNoImages.render(text) };
183 export function mdToHtmlInline(text: string) {
184 return { __html: md.renderInline(text) };
187 export function getUnixTime(text?: string): number | undefined {
188 return text ? new Date(text).getTime() / 1000 : undefined;
191 export function futureDaysToUnixTime(days?: number): number | undefined {
194 new Date(Date.now() + 1000 * 60 * 60 * 24 * days).getTime() / 1000
199 export function canMod(
201 mods?: CommunityModeratorView[],
202 admins?: PersonViewSafe[],
203 myUserInfo = UserService.Instance.myUserInfo,
206 // You can do moderator actions only on the mods added after you.
209 ?.map(a => a.person.id)
210 .concat(mods?.map(m => m.moderator.id) ?? []) ?? [];
213 let myIndex = adminsThenMods.findIndex(
214 id => id == myUserInfo.local_user_view.person.id
219 // onSelf +1 on mod actions not for yourself, IE ban, remove, etc
220 adminsThenMods = adminsThenMods.slice(0, myIndex + (onSelf ? 0 : 1));
221 return !adminsThenMods.includes(creator_id);
228 export function canAdmin(
230 admins?: PersonViewSafe[],
231 myUserInfo = UserService.Instance.myUserInfo,
234 return canMod(creatorId, undefined, admins, myUserInfo, onSelf);
237 export function isMod(
239 mods?: CommunityModeratorView[]
241 return mods?.map(m => m.moderator.id).includes(creatorId) ?? false;
244 export function amMod(
245 mods?: CommunityModeratorView[],
246 myUserInfo = UserService.Instance.myUserInfo
248 return myUserInfo ? isMod(myUserInfo.local_user_view.person.id, mods) : false;
251 export function isAdmin(creatorId: number, admins?: PersonViewSafe[]): boolean {
252 return admins?.map(a => a.person.id).includes(creatorId) ?? false;
255 export function amAdmin(myUserInfo = UserService.Instance.myUserInfo): boolean {
256 return myUserInfo?.local_user_view.person.admin ?? false;
259 export function amCommunityCreator(
261 mods?: CommunityModeratorView[],
262 myUserInfo = UserService.Instance.myUserInfo
264 let myId = myUserInfo?.local_user_view.person.id;
265 // Don't allow mod actions on yourself
266 return myId == mods?.at(0)?.moderator.id && myId != creator_id;
269 export function amSiteCreator(
271 admins?: PersonViewSafe[],
272 myUserInfo = UserService.Instance.myUserInfo
274 let myId = myUserInfo?.local_user_view.person.id;
275 return myId == admins?.at(0)?.person.id && myId != creator_id;
278 export function amTopMod(
279 mods: CommunityModeratorView[],
280 myUserInfo = UserService.Instance.myUserInfo
282 return mods.at(0)?.moderator.id == myUserInfo?.local_user_view.person.id;
285 const imageRegex = /(http)?s?:?(\/\/[^"']*\.(?:jpg|jpeg|gif|png|svg|webp))/;
286 const videoRegex = /(http)?s?:?(\/\/[^"']*\.(?:mp4|webm))/;
288 export function isImage(url: string) {
289 return imageRegex.test(url);
292 export function isVideo(url: string) {
293 return videoRegex.test(url);
296 export function validURL(str: string) {
297 return !!new URL(str);
300 export function communityRSSUrl(actorId: string, sort: string): string {
301 let url = new URL(actorId);
302 return `${url.origin}/feeds${url.pathname}.xml?sort=${sort}`;
305 export function validEmail(email: string) {
307 /^(([^\s"(),.:;<>@[\\\]]+(\.[^\s"(),.:;<>@[\\\]]+)*)|(".+"))@((\[(?:\d{1,3}\.){3}\d{1,3}])|(([\dA-Za-z\-]+\.)+[A-Za-z]{2,}))$/;
308 return re.test(String(email).toLowerCase());
311 export function capitalizeFirstLetter(str: string): string {
312 return str.charAt(0).toUpperCase() + str.slice(1);
315 export function routeSortTypeToEnum(sort: string): SortType {
316 return SortType[sort];
319 export function listingTypeFromNum(type_: number): ListingType {
320 return Object.values(ListingType)[type_];
323 export function sortTypeFromNum(type_: number): SortType {
324 return Object.values(SortType)[type_];
327 export function routeListingTypeToEnum(type: string): ListingType {
328 return ListingType[type];
331 export function routeDataTypeToEnum(type: string): DataType {
332 return DataType[capitalizeFirstLetter(type)];
335 export function routeSearchTypeToEnum(type: string): SearchType {
336 return SearchType[type];
339 export async function getSiteMetadata(url: string) {
340 let form: GetSiteMetadata = { url };
341 let client = new LemmyHttp(httpBase);
342 return client.getSiteMetadata(form);
345 export function debounce(func: any, wait = 1000, immediate = false) {
346 // 'private' variable for instance
347 // The returned function will be able to reference this due to closure.
348 // Each call to the returned function will share this common timer.
351 // Calling debounce returns a new anonymous function
353 // reference the context and args for the setTimeout function
354 var args = arguments;
356 // Should the function be called now? If immediate is true
357 // and not already in a timeout then the answer is: Yes
358 var callNow = immediate && !timeout;
360 // This is the basic debounce behaviour where you can call this
361 // function several times, but it will only execute once
362 // [before or after imposing a delay].
363 // Each time the returned function is called, the timer starts over.
364 clearTimeout(timeout);
366 // Set the new timeout
367 timeout = setTimeout(function () {
368 // Inside the timeout function, clear the timeout variable
369 // which will let the next execution run when in 'immediate' mode
372 // Check if the function already ran with the immediate flag
374 // Call the original function with apply
375 // apply lets you define the 'this' object as well as the arguments
376 // (both captured before setTimeout)
377 func.apply(this, args);
381 // Immediate mode and no wait timer? Execute the function..
382 if (callNow) func.apply(this, args);
386 export function getLanguages(
388 myUserInfo = UserService.Instance.myUserInfo
390 let myLang = myUserInfo?.local_user_view.local_user.interface_language;
391 let lang = override || myLang || "browser";
393 if (lang == "browser" && isBrowser()) {
394 return getBrowserLanguages();
400 function getBrowserLanguages(): string[] {
401 // Intersect lemmy's langs, with the browser langs
402 let langs = languages ? languages.map(l => l.code) : ["en"];
404 // NOTE, mobile browsers seem to be missing this list, so append en
405 let allowedLangs = navigator.languages
407 .filter(v => langs.includes(v));
411 export async function fetchThemeList(): Promise<string[]> {
412 return fetch("/css/themelist").then(res => res.json());
415 export async function setTheme(theme: string, forceReload = false) {
419 if (theme === "browser" && !forceReload) {
422 // This is only run on a force reload
423 if (theme == "browser") {
427 let themeList = await fetchThemeList();
429 // Unload all the other themes
430 for (var i = 0; i < themeList.length; i++) {
431 let styleSheet = document.getElementById(themeList[i]);
433 styleSheet.setAttribute("disabled", "disabled");
438 .getElementById("default-light")
439 ?.setAttribute("disabled", "disabled");
440 document.getElementById("default-dark")?.setAttribute("disabled", "disabled");
442 // Load the theme dynamically
443 let cssLoc = `/css/themes/${theme}.css`;
445 loadCss(theme, cssLoc);
446 document.getElementById(theme)?.removeAttribute("disabled");
449 export function loadCss(id: string, loc: string) {
450 if (!document.getElementById(id)) {
451 var head = document.getElementsByTagName("head")[0];
452 var link = document.createElement("link");
454 link.rel = "stylesheet";
455 link.type = "text/css";
458 head.appendChild(link);
462 export function objectFlip(obj: any) {
464 Object.keys(obj).forEach(key => {
470 export function showAvatars(
471 myUserInfo = UserService.Instance.myUserInfo
473 return myUserInfo?.local_user_view.local_user.show_avatars ?? true;
476 export function showScores(
477 myUserInfo = UserService.Instance.myUserInfo
479 return myUserInfo?.local_user_view.local_user.show_scores ?? true;
482 export function isCakeDay(published: string): boolean {
483 // moment(undefined) or moment.utc(undefined) returns the current date/time
484 // moment(null) or moment.utc(null) returns null
485 const createDate = moment.utc(published).local();
486 const currentDate = moment(new Date());
489 createDate.date() === currentDate.date() &&
490 createDate.month() === currentDate.month() &&
491 createDate.year() !== currentDate.year()
495 export function toast(text: string, background = "success") {
497 let backgroundColor = `var(--${background})`;
500 backgroundColor: backgroundColor,
507 export function pictrsDeleteToast(
508 clickToDeleteText: string,
509 deletePictureText: string,
510 failedDeletePictureText: string,
514 let backgroundColor = `var(--light)`;
515 let toast = Toastify({
516 text: clickToDeleteText,
517 backgroundColor: backgroundColor,
523 fetch(deleteUrl).then(res => {
525 if (res.ok === true) {
526 alert(deletePictureText);
528 alert(failedDeletePictureText);
539 interface NotifyInfo {
546 export function messageToastify(info: NotifyInfo, router: any) {
548 let htmlBody = info.body ? md.render(info.body) : "";
549 let backgroundColor = `var(--light)`;
551 let toast = Toastify({
552 text: `${htmlBody}<br />${info.name}`,
554 backgroundColor: backgroundColor,
555 className: "text-dark",
564 router.history.push(info.link);
572 export function notifyPost(post_view: PostView, router: any) {
573 let info: NotifyInfo = {
574 name: post_view.community.name,
575 icon: post_view.community.icon,
576 link: `/post/${post_view.post.id}`,
577 body: post_view.post.name,
579 notify(info, router);
582 export function notifyComment(comment_view: CommentView, router: any) {
583 let info: NotifyInfo = {
584 name: comment_view.creator.name,
585 icon: comment_view.creator.avatar,
586 link: `/comment/${comment_view.comment.id}`,
587 body: comment_view.comment.content,
589 notify(info, router);
592 export function notifyPrivateMessage(pmv: PrivateMessageView, router: any) {
593 let info: NotifyInfo = {
594 name: pmv.creator.name,
595 icon: pmv.creator.avatar,
597 body: pmv.private_message.content,
599 notify(info, router);
602 function notify(info: NotifyInfo, router: any) {
603 messageToastify(info, router);
605 if (Notification.permission !== "granted") Notification.requestPermission();
607 var notification = new Notification(info.name, {
608 ...{ body: info.body },
609 ...(info.icon && { icon: info.icon }),
612 notification.onclick = (ev: Event): any => {
614 router.history.push(info.link);
619 export function setupTribute() {
621 noMatchTemplate: function () {
628 menuItemTemplate: (item: any) => {
629 let shortName = `:${item.original.key}:`;
630 return `${item.original.val} ${shortName}`;
632 selectTemplate: (item: any) => {
633 return `${item.original.val}`;
635 values: Object.entries(emojiShortName).map(e => {
636 return { key: e[1], val: e[0] };
639 autocompleteMode: true,
641 // menuItemLimit: mentionDropdownFetchLimit,
642 menuShowMinLength: 2,
647 selectTemplate: (item: any) => {
648 let it: PersonTribute = item.original;
649 return `[${it.key}](${it.view.person.actor_id})`;
651 values: debounce(async (text: string, cb: any) => {
652 cb(await personSearch(text));
655 autocompleteMode: true,
657 // menuItemLimit: mentionDropdownFetchLimit,
658 menuShowMinLength: 2,
664 selectTemplate: (item: any) => {
665 let it: CommunityTribute = item.original;
666 return `[${it.key}](${it.view.community.actor_id})`;
668 values: debounce(async (text: string, cb: any) => {
669 cb(await communitySearch(text));
672 autocompleteMode: true,
674 // menuItemLimit: mentionDropdownFetchLimit,
675 menuShowMinLength: 2,
681 var tippyInstance: any;
683 tippyInstance = tippy("[data-tippy-content]");
686 export function setupTippy() {
688 tippyInstance.forEach((e: any) => e.destroy());
689 tippyInstance = tippy("[data-tippy-content]", {
691 // Display on "long press"
692 touch: ["hold", 500],
697 interface PersonTribute {
699 view: PersonViewSafe;
702 async function personSearch(text: string): Promise<PersonTribute[]> {
703 let users = (await fetchUsers(text)).users;
704 let persons: PersonTribute[] = users.map(pv => {
705 let tribute: PersonTribute = {
706 key: `@${pv.person.name}@${hostname(pv.person.actor_id)}`,
714 interface CommunityTribute {
719 async function communitySearch(text: string): Promise<CommunityTribute[]> {
720 let comms = (await fetchCommunities(text)).communities;
721 let communities: CommunityTribute[] = comms.map(cv => {
722 let tribute: CommunityTribute = {
723 key: `!${cv.community.name}@${hostname(cv.community.actor_id)}`,
731 export function getListingTypeFromProps(
733 defaultListingType: ListingType,
734 myUserInfo = UserService.Instance.myUserInfo
736 let myLt = myUserInfo?.local_user_view.local_user.default_listing_type;
737 return props.match.params.listing_type
738 ? routeListingTypeToEnum(props.match.params.listing_type)
740 ? Object.values(ListingType)[myLt]
741 : defaultListingType;
744 export function getListingTypeFromPropsNoDefault(props: any): ListingType {
745 return props.match.params.listing_type
746 ? routeListingTypeToEnum(props.match.params.listing_type)
750 export function getDataTypeFromProps(props: any): DataType {
751 return props.match.params.data_type
752 ? routeDataTypeToEnum(props.match.params.data_type)
756 export function getSortTypeFromProps(
758 myUserInfo = UserService.Instance.myUserInfo
760 let mySortType = myUserInfo?.local_user_view.local_user.default_sort_type;
761 return props.match.params.sort
762 ? routeSortTypeToEnum(props.match.params.sort)
764 ? Object.values(SortType)[mySortType]
768 export function getPageFromProps(props: any): number {
769 return props.match.params.page ? Number(props.match.params.page) : 1;
772 export function getRecipientIdFromProps(props: any): number {
773 return props.match.params.recipient_id
774 ? Number(props.match.params.recipient_id)
778 export function getIdFromProps(props: any): number | undefined {
779 let id = props.match.params.post_id;
780 return id ? Number(id) : undefined;
783 export function getCommentIdFromProps(props: any): number | undefined {
784 let id = props.match.params.comment_id;
785 return id ? Number(id) : undefined;
788 export function getUsernameFromProps(props: any): string {
789 return props.match.params.username;
792 export function editCommentRes(data: CommentView, comments?: CommentView[]) {
793 let found = comments?.find(c => c.comment.id == data.comment.id);
795 found.comment.content = data.comment.content;
796 found.comment.distinguished = data.comment.distinguished;
797 found.comment.updated = data.comment.updated;
798 found.comment.removed = data.comment.removed;
799 found.comment.deleted = data.comment.deleted;
800 found.counts.upvotes = data.counts.upvotes;
801 found.counts.downvotes = data.counts.downvotes;
802 found.counts.score = data.counts.score;
806 export function saveCommentRes(data: CommentView, comments?: CommentView[]) {
807 let found = comments?.find(c => c.comment.id == data.comment.id);
809 found.saved = data.saved;
813 export function updatePersonBlock(
814 data: BlockPersonResponse,
815 myUserInfo = UserService.Instance.myUserInfo
817 let mui = myUserInfo;
820 mui.person_blocks.push({
821 person: mui.local_user_view.person,
822 target: data.person_view.person,
824 toast(`${i18n.t("blocked")} ${data.person_view.person.name}`);
826 mui.person_blocks = mui.person_blocks.filter(
827 i => i.target.id != data.person_view.person.id
829 toast(`${i18n.t("unblocked")} ${data.person_view.person.name}`);
834 export function updateCommunityBlock(
835 data: BlockCommunityResponse,
836 myUserInfo = UserService.Instance.myUserInfo
838 let mui = myUserInfo;
841 mui.community_blocks.push({
842 person: mui.local_user_view.person,
843 community: data.community_view.community,
845 toast(`${i18n.t("blocked")} ${data.community_view.community.name}`);
847 mui.community_blocks = mui.community_blocks.filter(
848 i => i.community.id != data.community_view.community.id
850 toast(`${i18n.t("unblocked")} ${data.community_view.community.name}`);
855 export function createCommentLikeRes(
857 comments?: CommentView[]
859 let found = comments?.find(c => c.comment.id === data.comment.id);
861 found.counts.score = data.counts.score;
862 found.counts.upvotes = data.counts.upvotes;
863 found.counts.downvotes = data.counts.downvotes;
864 if (data.my_vote !== null) {
865 found.my_vote = data.my_vote;
870 export function createPostLikeFindRes(data: PostView, posts?: PostView[]) {
871 let found = posts?.find(p => p.post.id == data.post.id);
873 createPostLikeRes(data, found);
877 export function createPostLikeRes(data: PostView, post_view?: PostView) {
879 post_view.counts.score = data.counts.score;
880 post_view.counts.upvotes = data.counts.upvotes;
881 post_view.counts.downvotes = data.counts.downvotes;
882 if (data.my_vote !== null) {
883 post_view.my_vote = data.my_vote;
888 export function editPostFindRes(data: PostView, posts?: PostView[]) {
889 let found = posts?.find(p => p.post.id == data.post.id);
891 editPostRes(data, found);
895 export function editPostRes(data: PostView, post: PostView) {
897 post.post.url = data.post.url;
898 post.post.name = data.post.name;
899 post.post.nsfw = data.post.nsfw;
900 post.post.deleted = data.post.deleted;
901 post.post.removed = data.post.removed;
902 post.post.featured_community = data.post.featured_community;
903 post.post.featured_local = data.post.featured_local;
904 post.post.body = data.post.body;
905 post.post.locked = data.post.locked;
906 post.saved = data.saved;
910 // TODO possible to make these generic?
911 export function updatePostReportRes(
912 data: PostReportView,
913 reports?: PostReportView[]
915 let found = reports?.find(p => p.post_report.id == data.post_report.id);
917 found.post_report = data.post_report;
921 export function updateCommentReportRes(
922 data: CommentReportView,
923 reports?: CommentReportView[]
925 let found = reports?.find(c => c.comment_report.id == data.comment_report.id);
927 found.comment_report = data.comment_report;
931 export function updatePrivateMessageReportRes(
932 data: PrivateMessageReportView,
933 reports?: PrivateMessageReportView[]
935 let found = reports?.find(
936 c => c.private_message_report.id == data.private_message_report.id
939 found.private_message_report = data.private_message_report;
943 export function updateRegistrationApplicationRes(
944 data: RegistrationApplicationView,
945 applications?: RegistrationApplicationView[]
947 let found = applications?.find(
948 ra => ra.registration_application.id == data.registration_application.id
951 found.registration_application = data.registration_application;
952 found.admin = data.admin;
953 found.creator_local_user = data.creator_local_user;
957 export function commentsToFlatNodes(comments: CommentView[]): CommentNodeI[] {
958 let nodes: CommentNodeI[] = [];
959 for (let comment of comments) {
960 nodes.push({ comment_view: comment, children: [], depth: 0 });
965 export function convertCommentSortType(sort: SortType): CommentSortType {
967 sort == SortType.TopAll ||
968 sort == SortType.TopDay ||
969 sort == SortType.TopWeek ||
970 sort == SortType.TopMonth ||
971 sort == SortType.TopYear
973 return CommentSortType.Top;
974 } else if (sort == SortType.New) {
975 return CommentSortType.New;
976 } else if (sort == SortType.Hot || sort == SortType.Active) {
977 return CommentSortType.Hot;
979 return CommentSortType.Hot;
983 export function buildCommentsTree(
984 comments: CommentView[],
985 parentComment: boolean
987 let map = new Map<number, CommentNodeI>();
988 let depthOffset = !parentComment
990 : getDepthFromComment(comments[0].comment) ?? 0;
992 for (let comment_view of comments) {
993 let depthI = getDepthFromComment(comment_view.comment) ?? 0;
994 let depth = depthI ? depthI - depthOffset : 0;
995 let node: CommentNodeI = {
1000 map.set(comment_view.comment.id, { ...node });
1003 let tree: CommentNodeI[] = [];
1005 // if its a parent comment fetch, then push the first comment to the top node.
1006 if (parentComment) {
1007 let cNode = map.get(comments[0].comment.id);
1013 for (let comment_view of comments) {
1014 let child = map.get(comment_view.comment.id);
1016 let parent_id = getCommentParentId(comment_view.comment);
1018 let parent = map.get(parent_id);
1019 // Necessary because blocked comment might not exist
1021 parent.children.push(child);
1024 if (!parentComment) {
1034 export function getCommentParentId(comment?: CommentI): number | undefined {
1035 let split = comment?.path.split(".");
1039 return split && split.length > 1
1040 ? Number(split.at(split.length - 2))
1044 export function getDepthFromComment(comment?: CommentI): number | undefined {
1045 let len = comment?.path.split(".").length;
1046 return len ? len - 2 : undefined;
1049 export function insertCommentIntoTree(
1050 tree: CommentNodeI[],
1052 parentComment: boolean
1054 // Building a fake node to be used for later
1055 let node: CommentNodeI = {
1061 let parentId = getCommentParentId(cv.comment);
1063 let parent_comment = searchCommentTree(tree, parentId);
1064 if (parent_comment) {
1065 node.depth = parent_comment.depth + 1;
1066 parent_comment.children.unshift(node);
1068 } else if (!parentComment) {
1073 export function searchCommentTree(
1074 tree: CommentNodeI[],
1076 ): CommentNodeI | undefined {
1077 for (let node of tree) {
1078 if (node.comment_view.comment.id === id) {
1082 for (const child of node.children) {
1083 let res = searchCommentTree([child], id);
1093 export const colorList: string[] = [
1103 function hsl(num: number) {
1104 return `hsla(${num}, 35%, 50%, 1)`;
1107 export function hostname(url: string): string {
1108 let cUrl = new URL(url);
1109 return cUrl.port ? `${cUrl.hostname}:${cUrl.port}` : `${cUrl.hostname}`;
1112 export function validTitle(title?: string): boolean {
1113 // Initial title is null, minimum length is taken care of by textarea's minLength={3}
1114 if (!title || title.length < 3) return true;
1116 const regex = new RegExp(/.*\S.*/, "g");
1118 return regex.test(title);
1121 export function siteBannerCss(banner: string): string {
1123 background-image: linear-gradient( rgba(0, 0, 0, 0.8), rgba(0, 0, 0, 0.8) ) ,url("${banner}"); \
1124 background-attachment: fixed; \
1125 background-position: top; \
1126 background-repeat: no-repeat; \
1127 background-size: 100% cover; \
1130 max-height: 100vh; \
1134 export function isBrowser() {
1135 return typeof window !== "undefined";
1138 export function setIsoData(context: any): IsoData {
1139 // If its the browser, you need to deserialize the data from the window
1141 let json = window.isoData;
1142 let routeData = json.routeData;
1143 let site_res = json.site_res;
1145 let isoData: IsoData = {
1151 } else return context.router.staticContext;
1154 export function wsSubscribe(parseMessage: any): Subscription | undefined {
1156 return WebSocketService.Instance.subject
1157 .pipe(retryWhen(errors => errors.pipe(delay(3000), take(10))))
1159 msg => parseMessage(msg),
1160 err => console.error(err),
1161 () => console.log("complete")
1168 moment.updateLocale("en", {
1189 export function saveScrollPosition(context: any) {
1190 let path: string = context.router.route.location.pathname;
1191 let y = window.scrollY;
1192 sessionStorage.setItem(`scrollPosition_${path}`, y.toString());
1195 export function restoreScrollPosition(context: any) {
1196 let path: string = context.router.route.location.pathname;
1197 let y = Number(sessionStorage.getItem(`scrollPosition_${path}`));
1198 window.scrollTo(0, y);
1201 export function showLocal(isoData: IsoData): boolean {
1202 let linked = isoData.site_res.federated_instances?.linked;
1203 return linked ? linked.length > 0 : false;
1206 export interface ChoicesValue {
1211 export function communityToChoice(cv: CommunityView): ChoicesValue {
1212 let choice: ChoicesValue = {
1213 value: cv.community.id.toString(),
1214 label: communitySelectName(cv),
1219 export function personToChoice(pvs: PersonViewSafe): ChoicesValue {
1220 let choice: ChoicesValue = {
1221 value: pvs.person.id.toString(),
1222 label: personSelectName(pvs),
1227 export async function fetchCommunities(q: string) {
1228 let form: Search = {
1230 type_: SearchType.Communities,
1231 sort: SortType.TopAll,
1232 listing_type: ListingType.All,
1235 auth: myAuth(false),
1237 let client = new LemmyHttp(httpBase);
1238 return client.search(form);
1241 export async function fetchUsers(q: string) {
1242 let form: Search = {
1244 type_: SearchType.Users,
1245 sort: SortType.TopAll,
1246 listing_type: ListingType.All,
1249 auth: myAuth(false),
1251 let client = new LemmyHttp(httpBase);
1252 return client.search(form);
1255 export const choicesConfig = {
1257 searchResultLimit: fetchLimit,
1259 containerOuter: "choices custom-select px-0",
1261 "choices__inner bg-secondary border-0 py-0 modlog-choices-font-size",
1262 input: "form-control",
1263 inputCloned: "choices__input--cloned",
1264 list: "choices__list",
1265 listItems: "choices__list--multiple",
1266 listSingle: "choices__list--single py-0",
1267 listDropdown: "choices__list--dropdown",
1268 item: "choices__item bg-secondary",
1269 itemSelectable: "choices__item--selectable",
1270 itemDisabled: "choices__item--disabled",
1271 itemChoice: "choices__item--choice",
1272 placeholder: "choices__placeholder",
1273 group: "choices__group",
1274 groupHeading: "choices__heading",
1275 button: "choices__button",
1276 activeState: "is-active",
1277 focusState: "is-focused",
1278 openState: "is-open",
1279 disabledState: "is-disabled",
1280 highlightedState: "text-info",
1281 selectedState: "text-info",
1282 flippedState: "is-flipped",
1283 loadingState: "is-loading",
1284 noResults: "has-no-results",
1285 noChoices: "has-no-choices",
1289 export function communitySelectName(cv: CommunityView): string {
1290 return cv.community.local
1291 ? cv.community.title
1292 : `${hostname(cv.community.actor_id)}/${cv.community.title}`;
1295 export function personSelectName(pvs: PersonViewSafe): string {
1296 let pName = pvs.person.display_name ?? pvs.person.name;
1297 return pvs.person.local ? pName : `${hostname(pvs.person.actor_id)}/${pName}`;
1300 export function initializeSite(site: GetSiteResponse) {
1301 UserService.Instance.myUserInfo = site.my_user;
1302 i18n.changeLanguage(getLanguages()[0]);
1305 const SHORTNUM_SI_FORMAT = new Intl.NumberFormat("en-US", {
1306 maximumSignificantDigits: 3,
1308 notation: "compact",
1309 compactDisplay: "short",
1312 export function numToSI(value: number): string {
1313 return SHORTNUM_SI_FORMAT.format(value);
1316 export function isBanned(ps: PersonSafe): boolean {
1317 let expires = ps.ban_expires;
1318 // Add Z to convert from UTC date
1319 // TODO this check probably isn't necessary anymore
1321 if (ps.banned && new Date(expires + "Z") > new Date()) {
1331 export function pushNotNull(array: any[], new_item?: any) {
1333 array.push(...new_item);
1337 export function myAuth(throwErr = true): string | undefined {
1338 return UserService.Instance.auth(throwErr);
1341 export function enableDownvotes(siteRes: GetSiteResponse): boolean {
1342 return siteRes.site_view.local_site.enable_downvotes;
1345 export function enableNsfw(siteRes: GetSiteResponse): boolean {
1346 return siteRes.site_view.local_site.enable_nsfw;
1349 export function postToCommentSortType(sort: SortType): CommentSortType {
1350 if ([SortType.Active, SortType.Hot].includes(sort)) {
1351 return CommentSortType.Hot;
1352 } else if ([SortType.New, SortType.NewComments].includes(sort)) {
1353 return CommentSortType.New;
1354 } else if (sort == SortType.Old) {
1355 return CommentSortType.Old;
1357 return CommentSortType.Top;
1361 export function myFirstDiscussionLanguageId(
1362 allLanguages: Language[],
1363 siteLanguages: number[],
1364 myUserInfo = UserService.Instance.myUserInfo
1365 ): number | undefined {
1366 return selectableLanguages(
1375 export function canCreateCommunity(
1376 siteRes: GetSiteResponse,
1377 myUserInfo = UserService.Instance.myUserInfo
1379 let adminOnly = siteRes.site_view.local_site.community_creation_admin_only;
1380 return !adminOnly || amAdmin(myUserInfo);
1383 export function isPostBlocked(
1385 myUserInfo = UserService.Instance.myUserInfo
1388 (myUserInfo?.community_blocks
1389 .map(c => c.community.id)
1390 .includes(pv.community.id) ||
1391 myUserInfo?.person_blocks
1392 .map(p => p.target.id)
1393 .includes(pv.creator.id)) ??
1398 /// Checks to make sure you can view NSFW posts. Returns true if you can.
1399 export function nsfwCheck(
1401 myUserInfo = UserService.Instance.myUserInfo
1403 let nsfw = pv.post.nsfw || pv.community.nsfw;
1404 let myShowNsfw = myUserInfo?.local_user_view.local_user.show_nsfw ?? false;
1405 return !nsfw || (nsfw && myShowNsfw);
1408 export function getRandomFromList<T>(list?: T[]): T | undefined {
1409 return list?.at(Math.floor(Math.random() * list.length));
1413 * This shows what language you can select
1415 * Use showAll for the site form
1416 * Use showSite for the profile and community forms
1417 * Use false for both those to filter on your profile and site ones
1419 export function selectableLanguages(
1420 allLanguages: Language[],
1421 siteLanguages: number[],
1424 myUserInfo = UserService.Instance.myUserInfo
1426 let allLangIds = allLanguages.map(l => l.id);
1427 let myLangs = myUserInfo?.discussion_languages ?? allLangIds;
1428 myLangs = myLangs.length == 0 ? allLangIds : myLangs;
1429 let siteLangs = siteLanguages.length == 0 ? allLangIds : siteLanguages;
1432 return allLanguages;
1435 return allLanguages.filter(x => siteLangs.includes(x.id));
1438 .filter(x => siteLangs.includes(x.id))
1439 .filter(x => myLangs.includes(x.id));