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,
508 export function pictrsDeleteToast(
509 clickToDeleteText: string,
510 deletePictureText: string,
511 failedDeletePictureText: string,
515 let backgroundColor = `var(--light)`;
516 let toast = Toastify({
517 text: clickToDeleteText,
518 backgroundColor: backgroundColor,
524 fetch(deleteUrl).then(res => {
526 if (res.ok === true) {
527 alert(deletePictureText);
529 alert(failedDeletePictureText);
540 interface NotifyInfo {
547 export function messageToastify(info: NotifyInfo, router: any) {
549 let htmlBody = info.body ? md.render(info.body) : "";
550 let backgroundColor = `var(--light)`;
552 let toast = Toastify({
553 text: `${htmlBody}<br />${info.name}`,
555 backgroundColor: backgroundColor,
556 className: "text-dark",
565 router.history.push(info.link);
573 export function notifyPost(post_view: PostView, router: any) {
574 let info: NotifyInfo = {
575 name: post_view.community.name,
576 icon: post_view.community.icon,
577 link: `/post/${post_view.post.id}`,
578 body: post_view.post.name,
580 notify(info, router);
583 export function notifyComment(comment_view: CommentView, router: any) {
584 let info: NotifyInfo = {
585 name: comment_view.creator.name,
586 icon: comment_view.creator.avatar,
587 link: `/comment/${comment_view.comment.id}`,
588 body: comment_view.comment.content,
590 notify(info, router);
593 export function notifyPrivateMessage(pmv: PrivateMessageView, router: any) {
594 let info: NotifyInfo = {
595 name: pmv.creator.name,
596 icon: pmv.creator.avatar,
598 body: pmv.private_message.content,
600 notify(info, router);
603 function notify(info: NotifyInfo, router: any) {
604 messageToastify(info, router);
606 if (Notification.permission !== "granted") Notification.requestPermission();
608 var notification = new Notification(info.name, {
609 ...{ body: info.body },
610 ...(info.icon && { icon: info.icon }),
613 notification.onclick = (ev: Event): any => {
615 router.history.push(info.link);
620 export function setupTribute() {
622 noMatchTemplate: function () {
629 menuItemTemplate: (item: any) => {
630 let shortName = `:${item.original.key}:`;
631 return `${item.original.val} ${shortName}`;
633 selectTemplate: (item: any) => {
634 return `${item.original.val}`;
636 values: Object.entries(emojiShortName).map(e => {
637 return { key: e[1], val: e[0] };
640 autocompleteMode: true,
642 // menuItemLimit: mentionDropdownFetchLimit,
643 menuShowMinLength: 2,
648 selectTemplate: (item: any) => {
649 let it: PersonTribute = item.original;
650 return `[${it.key}](${it.view.person.actor_id})`;
652 values: debounce(async (text: string, cb: any) => {
653 cb(await personSearch(text));
656 autocompleteMode: true,
658 // menuItemLimit: mentionDropdownFetchLimit,
659 menuShowMinLength: 2,
665 selectTemplate: (item: any) => {
666 let it: CommunityTribute = item.original;
667 return `[${it.key}](${it.view.community.actor_id})`;
669 values: debounce(async (text: string, cb: any) => {
670 cb(await communitySearch(text));
673 autocompleteMode: true,
675 // menuItemLimit: mentionDropdownFetchLimit,
676 menuShowMinLength: 2,
682 var tippyInstance: any;
684 tippyInstance = tippy("[data-tippy-content]");
687 export function setupTippy() {
689 tippyInstance.forEach((e: any) => e.destroy());
690 tippyInstance = tippy("[data-tippy-content]", {
692 // Display on "long press"
693 touch: ["hold", 500],
698 interface PersonTribute {
700 view: PersonViewSafe;
703 async function personSearch(text: string): Promise<PersonTribute[]> {
704 let users = (await fetchUsers(text)).users;
705 let persons: PersonTribute[] = users.map(pv => {
706 let tribute: PersonTribute = {
707 key: `@${pv.person.name}@${hostname(pv.person.actor_id)}`,
715 interface CommunityTribute {
720 async function communitySearch(text: string): Promise<CommunityTribute[]> {
721 let comms = (await fetchCommunities(text)).communities;
722 let communities: CommunityTribute[] = comms.map(cv => {
723 let tribute: CommunityTribute = {
724 key: `!${cv.community.name}@${hostname(cv.community.actor_id)}`,
732 export function getListingTypeFromProps(
734 defaultListingType: ListingType,
735 myUserInfo = UserService.Instance.myUserInfo
737 let myLt = myUserInfo?.local_user_view.local_user.default_listing_type;
738 return props.match.params.listing_type
739 ? routeListingTypeToEnum(props.match.params.listing_type)
741 ? Object.values(ListingType)[myLt]
742 : defaultListingType;
745 export function getListingTypeFromPropsNoDefault(props: any): ListingType {
746 return props.match.params.listing_type
747 ? routeListingTypeToEnum(props.match.params.listing_type)
751 export function getDataTypeFromProps(props: any): DataType {
752 return props.match.params.data_type
753 ? routeDataTypeToEnum(props.match.params.data_type)
757 export function getSortTypeFromProps(
759 myUserInfo = UserService.Instance.myUserInfo
761 let mySortType = myUserInfo?.local_user_view.local_user.default_sort_type;
762 return props.match.params.sort
763 ? routeSortTypeToEnum(props.match.params.sort)
765 ? Object.values(SortType)[mySortType]
769 export function getPageFromProps(props: any): number {
770 return props.match.params.page ? Number(props.match.params.page) : 1;
773 export function getRecipientIdFromProps(props: any): number {
774 return props.match.params.recipient_id
775 ? Number(props.match.params.recipient_id)
779 export function getIdFromProps(props: any): number | undefined {
780 let id = props.match.params.post_id;
781 return id ? Number(id) : undefined;
784 export function getCommentIdFromProps(props: any): number | undefined {
785 let id = props.match.params.comment_id;
786 return id ? Number(id) : undefined;
789 export function getUsernameFromProps(props: any): string {
790 return props.match.params.username;
793 export function editCommentRes(data: CommentView, comments?: CommentView[]) {
794 let found = comments?.find(c => c.comment.id == data.comment.id);
796 found.comment.content = data.comment.content;
797 found.comment.distinguished = data.comment.distinguished;
798 found.comment.updated = data.comment.updated;
799 found.comment.removed = data.comment.removed;
800 found.comment.deleted = data.comment.deleted;
801 found.counts.upvotes = data.counts.upvotes;
802 found.counts.downvotes = data.counts.downvotes;
803 found.counts.score = data.counts.score;
807 export function saveCommentRes(data: CommentView, comments?: CommentView[]) {
808 let found = comments?.find(c => c.comment.id == data.comment.id);
810 found.saved = data.saved;
814 export function updatePersonBlock(
815 data: BlockPersonResponse,
816 myUserInfo = UserService.Instance.myUserInfo
818 let mui = myUserInfo;
821 mui.person_blocks.push({
822 person: mui.local_user_view.person,
823 target: data.person_view.person,
825 toast(`${i18n.t("blocked")} ${data.person_view.person.name}`);
827 mui.person_blocks = mui.person_blocks.filter(
828 i => i.target.id != data.person_view.person.id
830 toast(`${i18n.t("unblocked")} ${data.person_view.person.name}`);
835 export function updateCommunityBlock(
836 data: BlockCommunityResponse,
837 myUserInfo = UserService.Instance.myUserInfo
839 let mui = myUserInfo;
842 mui.community_blocks.push({
843 person: mui.local_user_view.person,
844 community: data.community_view.community,
846 toast(`${i18n.t("blocked")} ${data.community_view.community.name}`);
848 mui.community_blocks = mui.community_blocks.filter(
849 i => i.community.id != data.community_view.community.id
851 toast(`${i18n.t("unblocked")} ${data.community_view.community.name}`);
856 export function createCommentLikeRes(
858 comments?: CommentView[]
860 let found = comments?.find(c => c.comment.id === data.comment.id);
862 found.counts.score = data.counts.score;
863 found.counts.upvotes = data.counts.upvotes;
864 found.counts.downvotes = data.counts.downvotes;
865 if (data.my_vote !== null) {
866 found.my_vote = data.my_vote;
871 export function createPostLikeFindRes(data: PostView, posts?: PostView[]) {
872 let found = posts?.find(p => p.post.id == data.post.id);
874 createPostLikeRes(data, found);
878 export function createPostLikeRes(data: PostView, post_view?: PostView) {
880 post_view.counts.score = data.counts.score;
881 post_view.counts.upvotes = data.counts.upvotes;
882 post_view.counts.downvotes = data.counts.downvotes;
883 if (data.my_vote !== null) {
884 post_view.my_vote = data.my_vote;
889 export function editPostFindRes(data: PostView, posts?: PostView[]) {
890 let found = posts?.find(p => p.post.id == data.post.id);
892 editPostRes(data, found);
896 export function editPostRes(data: PostView, post: PostView) {
898 post.post.url = data.post.url;
899 post.post.name = data.post.name;
900 post.post.nsfw = data.post.nsfw;
901 post.post.deleted = data.post.deleted;
902 post.post.removed = data.post.removed;
903 post.post.featured_community = data.post.featured_community;
904 post.post.featured_local = data.post.featured_local;
905 post.post.body = data.post.body;
906 post.post.locked = data.post.locked;
907 post.saved = data.saved;
911 // TODO possible to make these generic?
912 export function updatePostReportRes(
913 data: PostReportView,
914 reports?: PostReportView[]
916 let found = reports?.find(p => p.post_report.id == data.post_report.id);
918 found.post_report = data.post_report;
922 export function updateCommentReportRes(
923 data: CommentReportView,
924 reports?: CommentReportView[]
926 let found = reports?.find(c => c.comment_report.id == data.comment_report.id);
928 found.comment_report = data.comment_report;
932 export function updatePrivateMessageReportRes(
933 data: PrivateMessageReportView,
934 reports?: PrivateMessageReportView[]
936 let found = reports?.find(
937 c => c.private_message_report.id == data.private_message_report.id
940 found.private_message_report = data.private_message_report;
944 export function updateRegistrationApplicationRes(
945 data: RegistrationApplicationView,
946 applications?: RegistrationApplicationView[]
948 let found = applications?.find(
949 ra => ra.registration_application.id == data.registration_application.id
952 found.registration_application = data.registration_application;
953 found.admin = data.admin;
954 found.creator_local_user = data.creator_local_user;
958 export function commentsToFlatNodes(comments: CommentView[]): CommentNodeI[] {
959 let nodes: CommentNodeI[] = [];
960 for (let comment of comments) {
961 nodes.push({ comment_view: comment, children: [], depth: 0 });
966 export function convertCommentSortType(sort: SortType): CommentSortType {
968 sort == SortType.TopAll ||
969 sort == SortType.TopDay ||
970 sort == SortType.TopWeek ||
971 sort == SortType.TopMonth ||
972 sort == SortType.TopYear
974 return CommentSortType.Top;
975 } else if (sort == SortType.New) {
976 return CommentSortType.New;
977 } else if (sort == SortType.Hot || sort == SortType.Active) {
978 return CommentSortType.Hot;
980 return CommentSortType.Hot;
984 export function buildCommentsTree(
985 comments: CommentView[],
986 parentComment: boolean
988 let map = new Map<number, CommentNodeI>();
989 let depthOffset = !parentComment
991 : getDepthFromComment(comments[0].comment) ?? 0;
993 for (let comment_view of comments) {
994 let depthI = getDepthFromComment(comment_view.comment) ?? 0;
995 let depth = depthI ? depthI - depthOffset : 0;
996 let node: CommentNodeI = {
1001 map.set(comment_view.comment.id, { ...node });
1004 let tree: CommentNodeI[] = [];
1006 // if its a parent comment fetch, then push the first comment to the top node.
1007 if (parentComment) {
1008 let cNode = map.get(comments[0].comment.id);
1014 for (let comment_view of comments) {
1015 let child = map.get(comment_view.comment.id);
1017 let parent_id = getCommentParentId(comment_view.comment);
1019 let parent = map.get(parent_id);
1020 // Necessary because blocked comment might not exist
1022 parent.children.push(child);
1025 if (!parentComment) {
1035 export function getCommentParentId(comment?: CommentI): number | undefined {
1036 let split = comment?.path.split(".");
1040 return split && split.length > 1
1041 ? Number(split.at(split.length - 2))
1045 export function getDepthFromComment(comment?: CommentI): number | undefined {
1046 let len = comment?.path.split(".").length;
1047 return len ? len - 2 : undefined;
1050 export function insertCommentIntoTree(
1051 tree: CommentNodeI[],
1053 parentComment: boolean
1055 // Building a fake node to be used for later
1056 let node: CommentNodeI = {
1062 let parentId = getCommentParentId(cv.comment);
1064 let parent_comment = searchCommentTree(tree, parentId);
1065 if (parent_comment) {
1066 node.depth = parent_comment.depth + 1;
1067 parent_comment.children.unshift(node);
1069 } else if (!parentComment) {
1074 export function searchCommentTree(
1075 tree: CommentNodeI[],
1077 ): CommentNodeI | undefined {
1078 for (let node of tree) {
1079 if (node.comment_view.comment.id === id) {
1083 for (const child of node.children) {
1084 let res = searchCommentTree([child], id);
1094 export const colorList: string[] = [
1104 function hsl(num: number) {
1105 return `hsla(${num}, 35%, 50%, 1)`;
1108 export function hostname(url: string): string {
1109 let cUrl = new URL(url);
1110 return cUrl.port ? `${cUrl.hostname}:${cUrl.port}` : `${cUrl.hostname}`;
1113 export function validTitle(title?: string): boolean {
1114 // Initial title is null, minimum length is taken care of by textarea's minLength={3}
1115 if (!title || title.length < 3) return true;
1117 const regex = new RegExp(/.*\S.*/, "g");
1119 return regex.test(title);
1122 export function siteBannerCss(banner: string): string {
1124 background-image: linear-gradient( rgba(0, 0, 0, 0.8), rgba(0, 0, 0, 0.8) ) ,url("${banner}"); \
1125 background-attachment: fixed; \
1126 background-position: top; \
1127 background-repeat: no-repeat; \
1128 background-size: 100% cover; \
1131 max-height: 100vh; \
1135 export function isBrowser() {
1136 return typeof window !== "undefined";
1139 export function setIsoData(context: any): IsoData {
1140 // If its the browser, you need to deserialize the data from the window
1142 let json = window.isoData;
1143 let routeData = json.routeData;
1144 let site_res = json.site_res;
1146 let isoData: IsoData = {
1152 } else return context.router.staticContext;
1155 export function wsSubscribe(parseMessage: any): Subscription | undefined {
1157 return WebSocketService.Instance.subject
1158 .pipe(retryWhen(errors => errors.pipe(delay(3000), take(10))))
1160 msg => parseMessage(msg),
1161 err => console.error(err),
1162 () => console.log("complete")
1169 moment.updateLocale("en", {
1190 export function saveScrollPosition(context: any) {
1191 let path: string = context.router.route.location.pathname;
1192 let y = window.scrollY;
1193 sessionStorage.setItem(`scrollPosition_${path}`, y.toString());
1196 export function restoreScrollPosition(context: any) {
1197 let path: string = context.router.route.location.pathname;
1198 let y = Number(sessionStorage.getItem(`scrollPosition_${path}`));
1199 window.scrollTo(0, y);
1202 export function showLocal(isoData: IsoData): boolean {
1203 let linked = isoData.site_res.federated_instances?.linked;
1204 return linked ? linked.length > 0 : false;
1207 export interface ChoicesValue {
1212 export function communityToChoice(cv: CommunityView): ChoicesValue {
1213 let choice: ChoicesValue = {
1214 value: cv.community.id.toString(),
1215 label: communitySelectName(cv),
1220 export function personToChoice(pvs: PersonViewSafe): ChoicesValue {
1221 let choice: ChoicesValue = {
1222 value: pvs.person.id.toString(),
1223 label: personSelectName(pvs),
1228 export async function fetchCommunities(q: string) {
1229 let form: Search = {
1231 type_: SearchType.Communities,
1232 sort: SortType.TopAll,
1233 listing_type: ListingType.All,
1236 auth: myAuth(false),
1238 let client = new LemmyHttp(httpBase);
1239 return client.search(form);
1242 export async function fetchUsers(q: string) {
1243 let form: Search = {
1245 type_: SearchType.Users,
1246 sort: SortType.TopAll,
1247 listing_type: ListingType.All,
1250 auth: myAuth(false),
1252 let client = new LemmyHttp(httpBase);
1253 return client.search(form);
1256 export const choicesConfig = {
1258 searchResultLimit: fetchLimit,
1260 containerOuter: "choices custom-select px-0",
1262 "choices__inner bg-secondary border-0 py-0 modlog-choices-font-size",
1263 input: "form-control",
1264 inputCloned: "choices__input--cloned",
1265 list: "choices__list",
1266 listItems: "choices__list--multiple",
1267 listSingle: "choices__list--single py-0",
1268 listDropdown: "choices__list--dropdown",
1269 item: "choices__item bg-secondary",
1270 itemSelectable: "choices__item--selectable",
1271 itemDisabled: "choices__item--disabled",
1272 itemChoice: "choices__item--choice",
1273 placeholder: "choices__placeholder",
1274 group: "choices__group",
1275 groupHeading: "choices__heading",
1276 button: "choices__button",
1277 activeState: "is-active",
1278 focusState: "is-focused",
1279 openState: "is-open",
1280 disabledState: "is-disabled",
1281 highlightedState: "text-info",
1282 selectedState: "text-info",
1283 flippedState: "is-flipped",
1284 loadingState: "is-loading",
1285 noResults: "has-no-results",
1286 noChoices: "has-no-choices",
1290 export function communitySelectName(cv: CommunityView): string {
1291 return cv.community.local
1292 ? cv.community.title
1293 : `${hostname(cv.community.actor_id)}/${cv.community.title}`;
1296 export function personSelectName(pvs: PersonViewSafe): string {
1297 let pName = pvs.person.display_name ?? pvs.person.name;
1298 return pvs.person.local ? pName : `${hostname(pvs.person.actor_id)}/${pName}`;
1301 export function initializeSite(site: GetSiteResponse) {
1302 UserService.Instance.myUserInfo = site.my_user;
1303 i18n.changeLanguage(getLanguages()[0]);
1306 const SHORTNUM_SI_FORMAT = new Intl.NumberFormat("en-US", {
1307 maximumSignificantDigits: 3,
1309 notation: "compact",
1310 compactDisplay: "short",
1313 export function numToSI(value: number): string {
1314 return SHORTNUM_SI_FORMAT.format(value);
1317 export function isBanned(ps: PersonSafe): boolean {
1318 let expires = ps.ban_expires;
1319 // Add Z to convert from UTC date
1320 // TODO this check probably isn't necessary anymore
1322 if (ps.banned && new Date(expires + "Z") > new Date()) {
1332 export function pushNotNull(array: any[], new_item?: any) {
1334 array.push(...new_item);
1338 export function myAuth(throwErr = true): string | undefined {
1339 return UserService.Instance.auth(throwErr);
1342 export function enableDownvotes(siteRes: GetSiteResponse): boolean {
1343 return siteRes.site_view.local_site.enable_downvotes;
1346 export function enableNsfw(siteRes: GetSiteResponse): boolean {
1347 return siteRes.site_view.local_site.enable_nsfw;
1350 export function postToCommentSortType(sort: SortType): CommentSortType {
1351 if ([SortType.Active, SortType.Hot].includes(sort)) {
1352 return CommentSortType.Hot;
1353 } else if ([SortType.New, SortType.NewComments].includes(sort)) {
1354 return CommentSortType.New;
1355 } else if (sort == SortType.Old) {
1356 return CommentSortType.Old;
1358 return CommentSortType.Top;
1362 export function myFirstDiscussionLanguageId(
1363 allLanguages: Language[],
1364 siteLanguages: number[],
1365 myUserInfo = UserService.Instance.myUserInfo
1366 ): number | undefined {
1367 return selectableLanguages(
1376 export function canCreateCommunity(
1377 siteRes: GetSiteResponse,
1378 myUserInfo = UserService.Instance.myUserInfo
1380 let adminOnly = siteRes.site_view.local_site.community_creation_admin_only;
1381 return !adminOnly || amAdmin(myUserInfo);
1384 export function isPostBlocked(
1386 myUserInfo = UserService.Instance.myUserInfo
1389 (myUserInfo?.community_blocks
1390 .map(c => c.community.id)
1391 .includes(pv.community.id) ||
1392 myUserInfo?.person_blocks
1393 .map(p => p.target.id)
1394 .includes(pv.creator.id)) ??
1399 /// Checks to make sure you can view NSFW posts. Returns true if you can.
1400 export function nsfwCheck(
1402 myUserInfo = UserService.Instance.myUserInfo
1404 let nsfw = pv.post.nsfw || pv.community.nsfw;
1405 let myShowNsfw = myUserInfo?.local_user_view.local_user.show_nsfw ?? false;
1406 return !nsfw || (nsfw && myShowNsfw);
1409 export function getRandomFromList<T>(list?: T[]): T | undefined {
1410 return list?.at(Math.floor(Math.random() * list.length));
1414 * This shows what language you can select
1416 * Use showAll for the site form
1417 * Use showSite for the profile and community forms
1418 * Use false for both those to filter on your profile and site ones
1420 export function selectableLanguages(
1421 allLanguages: Language[],
1422 siteLanguages: number[],
1425 myUserInfo = UserService.Instance.myUserInfo
1427 let allLangIds = allLanguages.map(l => l.id);
1428 let myLangs = myUserInfo?.discussion_languages ?? allLangIds;
1429 myLangs = myLangs.length == 0 ? allLangIds : myLangs;
1430 let siteLangs = siteLanguages.length == 0 ? allLangIds : siteLanguages;
1433 return allLanguages;
1436 return allLanguages.filter(x => siteLangs.includes(x.id));
1439 .filter(x => siteLangs.includes(x.id))
1440 .filter(x => myLangs.includes(x.id));