1 import emojiShortName from "emoji-short-name";
3 BlockCommunityResponse,
6 CommentNode as CommentNodeI,
10 CommunityModeratorView,
22 PrivateMessageReportView,
24 RegistrationApplicationView,
29 } from "lemmy-js-client";
30 import { default as MarkdownIt } from "markdown-it";
31 import markdown_it_container from "markdown-it-container";
32 import markdown_it_footnote from "markdown-it-footnote";
33 import markdown_it_html5_embed from "markdown-it-html5-embed";
34 import markdown_it_sub from "markdown-it-sub";
35 import markdown_it_sup from "markdown-it-sup";
36 import moment from "moment";
37 import { Subscription } from "rxjs";
38 import { delay, retryWhen, take } from "rxjs/operators";
39 import tippy from "tippy.js";
40 import Toastify from "toastify-js";
41 import { httpBase } from "./env";
42 import { i18n, languages } from "./i18next";
43 import { DataType, IsoData } from "./interfaces";
44 import { UserService, WebSocketService } from "./services";
48 Tribute = require("tributejs");
51 export const wsClient = new LemmyWebsocket();
53 export const favIconUrl = "/static/assets/icons/favicon.svg";
54 export const favIconPngUrl = "/static/assets/icons/apple-touch-icon.png";
56 // export const defaultFavIcon = `${window.location.protocol}//${window.location.host}${favIconPngUrl}`;
57 export const repoUrl = "https://github.com/LemmyNet";
58 export const joinLemmyUrl = "https://join-lemmy.org";
59 export const donateLemmyUrl = `${joinLemmyUrl}/donate`;
60 export const docsUrl = `${joinLemmyUrl}/docs/en/index.html`;
61 export const helpGuideUrl = `${joinLemmyUrl}/docs/en/about/guide.html`; // TODO find a way to redirect to the non-en folder
62 export const markdownHelpUrl = `${helpGuideUrl}#using-markdown`;
63 export const sortingHelpUrl = `${helpGuideUrl}#sorting`;
64 export const archiveTodayUrl = "https://archive.today";
65 export const ghostArchiveUrl = "https://ghostarchive.org";
66 export const webArchiveUrl = "https://web.archive.org";
67 export const elementUrl = "https://element.io";
69 export const postRefetchSeconds: number = 60 * 1000;
70 export const fetchLimit = 40;
71 export const trendingFetchLimit = 6;
72 export const mentionDropdownFetchLimit = 10;
73 export const commentTreeMaxDepth = 8;
74 export const markdownFieldCharacterLimit = 50000;
76 export const relTags = "noopener nofollow";
78 const DEFAULT_ALPHABET =
79 "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
81 function getRandomCharFromAlphabet(alphabet: string): string {
82 return alphabet.charAt(Math.floor(Math.random() * alphabet.length));
85 export function randomStr(
87 alphabet = DEFAULT_ALPHABET
90 * Create n-long array and map it to random chars from given alphabet.
91 * Then join individual chars as string
93 return Array.from({ length: idDesiredLength })
95 return getRandomCharFromAlphabet(alphabet);
100 const html5EmbedConfig = {
102 useImageSyntax: true, // Enables video/audio embed with ![]() syntax (default)
104 audio: 'controls preload="metadata"',
105 video: 'width="100%" max-height="100%" controls loop preload="metadata"',
110 const spoilerConfig = {
111 validate: (params: string) => {
112 return params.trim().match(/^spoiler\s+(.*)$/);
115 render: (tokens: any, idx: any) => {
116 var m = tokens[idx].info.trim().match(/^spoiler\s+(.*)$/);
118 if (tokens[idx].nesting === 1) {
120 return `<details><summary> ${md.utils.escapeHtml(m[1])} </summary>\n`;
123 return "</details>\n";
128 const markdownItConfig: MarkdownIt.Options = {
134 export const md = new MarkdownIt(markdownItConfig)
135 .use(markdown_it_sub)
136 .use(markdown_it_sup)
137 .use(markdown_it_footnote)
138 .use(markdown_it_html5_embed, html5EmbedConfig)
139 .use(markdown_it_container, "spoiler", spoilerConfig);
141 export const mdNoImages = new MarkdownIt(markdownItConfig)
142 .use(markdown_it_sub)
143 .use(markdown_it_sup)
144 .use(markdown_it_footnote)
145 .use(markdown_it_html5_embed, html5EmbedConfig)
146 .use(markdown_it_container, "spoiler", spoilerConfig)
149 export function hotRankComment(comment_view: CommentView): number {
150 return hotRank(comment_view.counts.score, comment_view.comment.published);
153 export function hotRankActivePost(post_view: PostView): number {
154 return hotRank(post_view.counts.score, post_view.counts.newest_comment_time);
157 export function hotRankPost(post_view: PostView): number {
158 return hotRank(post_view.counts.score, post_view.post.published);
161 export function hotRank(score: number, timeStr: string): number {
162 // Rank = ScaleFactor * sign(Score) * log(1 + abs(Score)) / (Time + 2)^Gravity
163 let date: Date = new Date(timeStr + "Z"); // Add Z to convert from UTC date
164 let now: Date = new Date();
165 let hoursElapsed: number = (now.getTime() - date.getTime()) / 36e5;
168 (10000 * Math.log10(Math.max(1, 3 + score))) /
169 Math.pow(hoursElapsed + 2, 1.8);
171 // console.log(`Comment: ${comment.content}\nRank: ${rank}\nScore: ${comment.score}\nHours: ${hoursElapsed}`);
176 export function mdToHtml(text: string) {
177 return { __html: md.render(text) };
180 export function mdToHtmlNoImages(text: string) {
181 return { __html: mdNoImages.render(text) };
184 export function mdToHtmlInline(text: string) {
185 return { __html: md.renderInline(text) };
188 export function getUnixTime(text?: string): number | undefined {
189 return text ? new Date(text).getTime() / 1000 : undefined;
192 export function futureDaysToUnixTime(days?: number): number | undefined {
195 new Date(Date.now() + 1000 * 60 * 60 * 24 * days).getTime() / 1000
200 export function canMod(
202 mods?: CommunityModeratorView[],
203 admins?: PersonViewSafe[],
204 myUserInfo = UserService.Instance.myUserInfo,
207 // You can do moderator actions only on the mods added after you.
210 ?.map(a => a.person.id)
211 .concat(mods?.map(m => m.moderator.id) ?? []) ?? [];
214 let myIndex = adminsThenMods.findIndex(
215 id => id == myUserInfo.local_user_view.person.id
220 // onSelf +1 on mod actions not for yourself, IE ban, remove, etc
221 adminsThenMods = adminsThenMods.slice(0, myIndex + (onSelf ? 0 : 1));
222 return !adminsThenMods.includes(creator_id);
229 export function canAdmin(
231 admins?: PersonViewSafe[],
232 myUserInfo = UserService.Instance.myUserInfo,
235 return canMod(creatorId, undefined, admins, myUserInfo, onSelf);
238 export function isMod(
240 mods?: CommunityModeratorView[]
242 return mods?.map(m => m.moderator.id).includes(creatorId) ?? false;
245 export function amMod(
246 mods?: CommunityModeratorView[],
247 myUserInfo = UserService.Instance.myUserInfo
249 return myUserInfo ? isMod(myUserInfo.local_user_view.person.id, mods) : false;
252 export function isAdmin(creatorId: number, admins?: PersonViewSafe[]): boolean {
253 return admins?.map(a => a.person.id).includes(creatorId) ?? false;
256 export function amAdmin(myUserInfo = UserService.Instance.myUserInfo): boolean {
257 return myUserInfo?.local_user_view.person.admin ?? false;
260 export function amCommunityCreator(
262 mods?: CommunityModeratorView[],
263 myUserInfo = UserService.Instance.myUserInfo
265 let myId = myUserInfo?.local_user_view.person.id;
266 // Don't allow mod actions on yourself
267 return myId == mods?.at(0)?.moderator.id && myId != creator_id;
270 export function amSiteCreator(
272 admins?: PersonViewSafe[],
273 myUserInfo = UserService.Instance.myUserInfo
275 let myId = myUserInfo?.local_user_view.person.id;
276 return myId == admins?.at(0)?.person.id && myId != creator_id;
279 export function amTopMod(
280 mods: CommunityModeratorView[],
281 myUserInfo = UserService.Instance.myUserInfo
283 return mods.at(0)?.moderator.id == myUserInfo?.local_user_view.person.id;
286 const imageRegex = /(http)?s?:?(\/\/[^"']*\.(?:jpg|jpeg|gif|png|svg|webp))/;
287 const videoRegex = /(http)?s?:?(\/\/[^"']*\.(?:mp4|webm))/;
289 export function isImage(url: string) {
290 return imageRegex.test(url);
293 export function isVideo(url: string) {
294 return videoRegex.test(url);
297 export function validURL(str: string) {
298 return !!new URL(str);
301 export function communityRSSUrl(actorId: string, sort: string): string {
302 let url = new URL(actorId);
303 return `${url.origin}/feeds${url.pathname}.xml?sort=${sort}`;
306 export function validEmail(email: string) {
308 /^(([^\s"(),.:;<>@[\\\]]+(\.[^\s"(),.:;<>@[\\\]]+)*)|(".+"))@((\[(?:\d{1,3}\.){3}\d{1,3}])|(([\dA-Za-z\-]+\.)+[A-Za-z]{2,}))$/;
309 return re.test(String(email).toLowerCase());
312 export function capitalizeFirstLetter(str: string): string {
313 return str.charAt(0).toUpperCase() + str.slice(1);
316 export function routeSortTypeToEnum(sort: string): SortType {
317 return SortType[sort];
320 export function listingTypeFromNum(type_: number): ListingType {
321 return Object.values(ListingType)[type_];
324 export function sortTypeFromNum(type_: number): SortType {
325 return Object.values(SortType)[type_];
328 export function routeListingTypeToEnum(type: string): ListingType {
329 return ListingType[type];
332 export function routeDataTypeToEnum(type: string): DataType {
333 return DataType[capitalizeFirstLetter(type)];
336 export function routeSearchTypeToEnum(type: string): SearchType {
337 return SearchType[type];
340 export async function getSiteMetadata(url: string) {
341 let form: GetSiteMetadata = { url };
342 let client = new LemmyHttp(httpBase);
343 return client.getSiteMetadata(form);
346 export function debounce(func: any, wait = 1000, immediate = false) {
347 // 'private' variable for instance
348 // The returned function will be able to reference this due to closure.
349 // Each call to the returned function will share this common timer.
352 // Calling debounce returns a new anonymous function
354 // reference the context and args for the setTimeout function
355 var args = arguments;
357 // Should the function be called now? If immediate is true
358 // and not already in a timeout then the answer is: Yes
359 var callNow = immediate && !timeout;
361 // This is the basic debounce behaviour where you can call this
362 // function several times, but it will only execute once
363 // [before or after imposing a delay].
364 // Each time the returned function is called, the timer starts over.
365 clearTimeout(timeout);
367 // Set the new timeout
368 timeout = setTimeout(function () {
369 // Inside the timeout function, clear the timeout variable
370 // which will let the next execution run when in 'immediate' mode
373 // Check if the function already ran with the immediate flag
375 // Call the original function with apply
376 // apply lets you define the 'this' object as well as the arguments
377 // (both captured before setTimeout)
378 func.apply(this, args);
382 // Immediate mode and no wait timer? Execute the function..
383 if (callNow) func.apply(this, args);
387 export function getLanguages(
389 myUserInfo = UserService.Instance.myUserInfo
391 let myLang = myUserInfo?.local_user_view.local_user.interface_language;
392 let lang = override || myLang || "browser";
394 if (lang == "browser" && isBrowser()) {
395 return getBrowserLanguages();
401 function getBrowserLanguages(): string[] {
402 // Intersect lemmy's langs, with the browser langs
403 let langs = languages ? languages.map(l => l.code) : ["en"];
405 // NOTE, mobile browsers seem to be missing this list, so append en
406 let allowedLangs = navigator.languages
408 .filter(v => langs.includes(v));
412 export async function fetchThemeList(): Promise<string[]> {
413 return fetch("/css/themelist").then(res => res.json());
416 export async function setTheme(theme: string, forceReload = false) {
420 if (theme === "browser" && !forceReload) {
423 // This is only run on a force reload
424 if (theme == "browser") {
428 let themeList = await fetchThemeList();
430 // Unload all the other themes
431 for (var i = 0; i < themeList.length; i++) {
432 let styleSheet = document.getElementById(themeList[i]);
434 styleSheet.setAttribute("disabled", "disabled");
439 .getElementById("default-light")
440 ?.setAttribute("disabled", "disabled");
441 document.getElementById("default-dark")?.setAttribute("disabled", "disabled");
443 // Load the theme dynamically
444 let cssLoc = `/css/themes/${theme}.css`;
446 loadCss(theme, cssLoc);
447 document.getElementById(theme)?.removeAttribute("disabled");
450 export function loadCss(id: string, loc: string) {
451 if (!document.getElementById(id)) {
452 var head = document.getElementsByTagName("head")[0];
453 var link = document.createElement("link");
455 link.rel = "stylesheet";
456 link.type = "text/css";
459 head.appendChild(link);
463 export function objectFlip(obj: any) {
465 Object.keys(obj).forEach(key => {
471 export function showAvatars(
472 myUserInfo = UserService.Instance.myUserInfo
474 return myUserInfo?.local_user_view.local_user.show_avatars ?? true;
477 export function showScores(
478 myUserInfo = UserService.Instance.myUserInfo
480 return myUserInfo?.local_user_view.local_user.show_scores ?? true;
483 export function isCakeDay(published: string): boolean {
484 // moment(undefined) or moment.utc(undefined) returns the current date/time
485 // moment(null) or moment.utc(null) returns null
486 const createDate = moment.utc(published).local();
487 const currentDate = moment(new Date());
490 createDate.date() === currentDate.date() &&
491 createDate.month() === currentDate.month() &&
492 createDate.year() !== currentDate.year()
496 export function toast(text: string, background = "success") {
498 let backgroundColor = `var(--${background})`;
501 backgroundColor: backgroundColor,
509 export function pictrsDeleteToast(
510 clickToDeleteText: string,
511 deletePictureText: string,
512 failedDeletePictureText: string,
516 let backgroundColor = `var(--light)`;
517 let toast = Toastify({
518 text: clickToDeleteText,
519 backgroundColor: backgroundColor,
525 fetch(deleteUrl).then(res => {
527 if (res.ok === true) {
528 alert(deletePictureText);
530 alert(failedDeletePictureText);
541 interface NotifyInfo {
548 export function messageToastify(info: NotifyInfo, router: any) {
550 let htmlBody = info.body ? md.render(info.body) : "";
551 let backgroundColor = `var(--light)`;
553 let toast = Toastify({
554 text: `${htmlBody}<br />${info.name}`,
556 backgroundColor: backgroundColor,
557 className: "text-dark",
566 router.history.push(info.link);
574 export function notifyPost(post_view: PostView, router: any) {
575 let info: NotifyInfo = {
576 name: post_view.community.name,
577 icon: post_view.community.icon,
578 link: `/post/${post_view.post.id}`,
579 body: post_view.post.name,
581 notify(info, router);
584 export function notifyComment(comment_view: CommentView, router: any) {
585 let info: NotifyInfo = {
586 name: comment_view.creator.name,
587 icon: comment_view.creator.avatar,
588 link: `/comment/${comment_view.comment.id}`,
589 body: comment_view.comment.content,
591 notify(info, router);
594 export function notifyPrivateMessage(pmv: PrivateMessageView, router: any) {
595 let info: NotifyInfo = {
596 name: pmv.creator.name,
597 icon: pmv.creator.avatar,
599 body: pmv.private_message.content,
601 notify(info, router);
604 function notify(info: NotifyInfo, router: any) {
605 messageToastify(info, router);
607 if (Notification.permission !== "granted") Notification.requestPermission();
609 var notification = new Notification(info.name, {
610 ...{ body: info.body },
611 ...(info.icon && { icon: info.icon }),
614 notification.onclick = (ev: Event): any => {
616 router.history.push(info.link);
621 export function setupTribute() {
623 noMatchTemplate: function () {
630 menuItemTemplate: (item: any) => {
631 let shortName = `:${item.original.key}:`;
632 return `${item.original.val} ${shortName}`;
634 selectTemplate: (item: any) => {
635 return `${item.original.val}`;
637 values: Object.entries(emojiShortName).map(e => {
638 return { key: e[1], val: e[0] };
641 autocompleteMode: true,
643 // menuItemLimit: mentionDropdownFetchLimit,
644 menuShowMinLength: 2,
649 selectTemplate: (item: any) => {
650 let it: PersonTribute = item.original;
651 return `[${it.key}](${it.view.person.actor_id})`;
653 values: debounce(async (text: string, cb: any) => {
654 cb(await personSearch(text));
657 autocompleteMode: true,
659 // menuItemLimit: mentionDropdownFetchLimit,
660 menuShowMinLength: 2,
666 selectTemplate: (item: any) => {
667 let it: CommunityTribute = item.original;
668 return `[${it.key}](${it.view.community.actor_id})`;
670 values: debounce(async (text: string, cb: any) => {
671 cb(await communitySearch(text));
674 autocompleteMode: true,
676 // menuItemLimit: mentionDropdownFetchLimit,
677 menuShowMinLength: 2,
683 var tippyInstance: any;
685 tippyInstance = tippy("[data-tippy-content]");
688 export function setupTippy() {
690 tippyInstance.forEach((e: any) => e.destroy());
691 tippyInstance = tippy("[data-tippy-content]", {
693 // Display on "long press"
694 touch: ["hold", 500],
699 interface PersonTribute {
701 view: PersonViewSafe;
704 async function personSearch(text: string): Promise<PersonTribute[]> {
705 let users = (await fetchUsers(text)).users;
706 let persons: PersonTribute[] = users.map(pv => {
707 let tribute: PersonTribute = {
708 key: `@${pv.person.name}@${hostname(pv.person.actor_id)}`,
716 interface CommunityTribute {
721 async function communitySearch(text: string): Promise<CommunityTribute[]> {
722 let comms = (await fetchCommunities(text)).communities;
723 let communities: CommunityTribute[] = comms.map(cv => {
724 let tribute: CommunityTribute = {
725 key: `!${cv.community.name}@${hostname(cv.community.actor_id)}`,
733 export function getListingTypeFromProps(
735 defaultListingType: ListingType,
736 myUserInfo = UserService.Instance.myUserInfo
738 let myLt = myUserInfo?.local_user_view.local_user.default_listing_type;
739 return props.match.params.listing_type
740 ? routeListingTypeToEnum(props.match.params.listing_type)
742 ? Object.values(ListingType)[myLt]
743 : defaultListingType;
746 export function getListingTypeFromPropsNoDefault(props: any): ListingType {
747 return props.match.params.listing_type
748 ? routeListingTypeToEnum(props.match.params.listing_type)
752 export function getDataTypeFromProps(props: any): DataType {
753 return props.match.params.data_type
754 ? routeDataTypeToEnum(props.match.params.data_type)
758 export function getSortTypeFromProps(
760 myUserInfo = UserService.Instance.myUserInfo
762 let mySortType = myUserInfo?.local_user_view.local_user.default_sort_type;
763 return props.match.params.sort
764 ? routeSortTypeToEnum(props.match.params.sort)
766 ? Object.values(SortType)[mySortType]
770 export function getPageFromProps(props: any): number {
771 return props.match.params.page ? Number(props.match.params.page) : 1;
774 export function getRecipientIdFromProps(props: any): number {
775 return props.match.params.recipient_id
776 ? Number(props.match.params.recipient_id)
780 export function getIdFromProps(props: any): number | undefined {
781 let id = props.match.params.post_id;
782 return id ? Number(id) : undefined;
785 export function getCommentIdFromProps(props: any): number | undefined {
786 let id = props.match.params.comment_id;
787 return id ? Number(id) : undefined;
790 export function getUsernameFromProps(props: any): string {
791 return props.match.params.username;
794 export function editCommentRes(data: CommentView, comments?: CommentView[]) {
795 let found = comments?.find(c => c.comment.id == data.comment.id);
797 found.comment.content = data.comment.content;
798 found.comment.distinguished = data.comment.distinguished;
799 found.comment.updated = data.comment.updated;
800 found.comment.removed = data.comment.removed;
801 found.comment.deleted = data.comment.deleted;
802 found.counts.upvotes = data.counts.upvotes;
803 found.counts.downvotes = data.counts.downvotes;
804 found.counts.score = data.counts.score;
808 export function saveCommentRes(data: CommentView, comments?: CommentView[]) {
809 let found = comments?.find(c => c.comment.id == data.comment.id);
811 found.saved = data.saved;
815 export function updatePersonBlock(
816 data: BlockPersonResponse,
817 myUserInfo = UserService.Instance.myUserInfo
819 let mui = myUserInfo;
822 mui.person_blocks.push({
823 person: mui.local_user_view.person,
824 target: data.person_view.person,
826 toast(`${i18n.t("blocked")} ${data.person_view.person.name}`);
828 mui.person_blocks = mui.person_blocks.filter(
829 i => i.target.id != data.person_view.person.id
831 toast(`${i18n.t("unblocked")} ${data.person_view.person.name}`);
836 export function updateCommunityBlock(
837 data: BlockCommunityResponse,
838 myUserInfo = UserService.Instance.myUserInfo
840 let mui = myUserInfo;
843 mui.community_blocks.push({
844 person: mui.local_user_view.person,
845 community: data.community_view.community,
847 toast(`${i18n.t("blocked")} ${data.community_view.community.name}`);
849 mui.community_blocks = mui.community_blocks.filter(
850 i => i.community.id != data.community_view.community.id
852 toast(`${i18n.t("unblocked")} ${data.community_view.community.name}`);
857 export function createCommentLikeRes(
859 comments?: CommentView[]
861 let found = comments?.find(c => c.comment.id === data.comment.id);
863 found.counts.score = data.counts.score;
864 found.counts.upvotes = data.counts.upvotes;
865 found.counts.downvotes = data.counts.downvotes;
866 if (data.my_vote !== null) {
867 found.my_vote = data.my_vote;
872 export function createPostLikeFindRes(data: PostView, posts?: PostView[]) {
873 let found = posts?.find(p => p.post.id == data.post.id);
875 createPostLikeRes(data, found);
879 export function createPostLikeRes(data: PostView, post_view?: PostView) {
881 post_view.counts.score = data.counts.score;
882 post_view.counts.upvotes = data.counts.upvotes;
883 post_view.counts.downvotes = data.counts.downvotes;
884 if (data.my_vote !== null) {
885 post_view.my_vote = data.my_vote;
890 export function editPostFindRes(data: PostView, posts?: PostView[]) {
891 let found = posts?.find(p => p.post.id == data.post.id);
893 editPostRes(data, found);
897 export function editPostRes(data: PostView, post: PostView) {
899 post.post.url = data.post.url;
900 post.post.name = data.post.name;
901 post.post.nsfw = data.post.nsfw;
902 post.post.deleted = data.post.deleted;
903 post.post.removed = data.post.removed;
904 post.post.featured_community = data.post.featured_community;
905 post.post.featured_local = data.post.featured_local;
906 post.post.body = data.post.body;
907 post.post.locked = data.post.locked;
908 post.saved = data.saved;
912 // TODO possible to make these generic?
913 export function updatePostReportRes(
914 data: PostReportView,
915 reports?: PostReportView[]
917 let found = reports?.find(p => p.post_report.id == data.post_report.id);
919 found.post_report = data.post_report;
923 export function updateCommentReportRes(
924 data: CommentReportView,
925 reports?: CommentReportView[]
927 let found = reports?.find(c => c.comment_report.id == data.comment_report.id);
929 found.comment_report = data.comment_report;
933 export function updatePrivateMessageReportRes(
934 data: PrivateMessageReportView,
935 reports?: PrivateMessageReportView[]
937 let found = reports?.find(
938 c => c.private_message_report.id == data.private_message_report.id
941 found.private_message_report = data.private_message_report;
945 export function updateRegistrationApplicationRes(
946 data: RegistrationApplicationView,
947 applications?: RegistrationApplicationView[]
949 let found = applications?.find(
950 ra => ra.registration_application.id == data.registration_application.id
953 found.registration_application = data.registration_application;
954 found.admin = data.admin;
955 found.creator_local_user = data.creator_local_user;
959 export function commentsToFlatNodes(comments: CommentView[]): CommentNodeI[] {
960 let nodes: CommentNodeI[] = [];
961 for (let comment of comments) {
962 nodes.push({ comment_view: comment, children: [], depth: 0 });
967 export function convertCommentSortType(sort: SortType): CommentSortType {
969 sort == SortType.TopAll ||
970 sort == SortType.TopDay ||
971 sort == SortType.TopWeek ||
972 sort == SortType.TopMonth ||
973 sort == SortType.TopYear
975 return CommentSortType.Top;
976 } else if (sort == SortType.New) {
977 return CommentSortType.New;
978 } else if (sort == SortType.Hot || sort == SortType.Active) {
979 return CommentSortType.Hot;
981 return CommentSortType.Hot;
985 export function buildCommentsTree(
986 comments: CommentView[],
987 parentComment: boolean
989 let map = new Map<number, CommentNodeI>();
990 let depthOffset = !parentComment
992 : getDepthFromComment(comments[0].comment) ?? 0;
994 for (let comment_view of comments) {
995 let depthI = getDepthFromComment(comment_view.comment) ?? 0;
996 let depth = depthI ? depthI - depthOffset : 0;
997 let node: CommentNodeI = {
1002 map.set(comment_view.comment.id, { ...node });
1005 let tree: CommentNodeI[] = [];
1007 // if its a parent comment fetch, then push the first comment to the top node.
1008 if (parentComment) {
1009 let cNode = map.get(comments[0].comment.id);
1015 for (let comment_view of comments) {
1016 let child = map.get(comment_view.comment.id);
1018 let parent_id = getCommentParentId(comment_view.comment);
1020 let parent = map.get(parent_id);
1021 // Necessary because blocked comment might not exist
1023 parent.children.push(child);
1026 if (!parentComment) {
1036 export function getCommentParentId(comment?: CommentI): number | undefined {
1037 let split = comment?.path.split(".");
1041 return split && split.length > 1
1042 ? Number(split.at(split.length - 2))
1046 export function getDepthFromComment(comment?: CommentI): number | undefined {
1047 let len = comment?.path.split(".").length;
1048 return len ? len - 2 : undefined;
1051 export function insertCommentIntoTree(
1052 tree: CommentNodeI[],
1054 parentComment: boolean
1056 // Building a fake node to be used for later
1057 let node: CommentNodeI = {
1063 let parentId = getCommentParentId(cv.comment);
1065 let parent_comment = searchCommentTree(tree, parentId);
1066 if (parent_comment) {
1067 node.depth = parent_comment.depth + 1;
1068 parent_comment.children.unshift(node);
1070 } else if (!parentComment) {
1075 export function searchCommentTree(
1076 tree: CommentNodeI[],
1078 ): CommentNodeI | undefined {
1079 for (let node of tree) {
1080 if (node.comment_view.comment.id === id) {
1084 for (const child of node.children) {
1085 let res = searchCommentTree([child], id);
1095 export const colorList: string[] = [
1105 function hsl(num: number) {
1106 return `hsla(${num}, 35%, 50%, 1)`;
1109 export function hostname(url: string): string {
1110 let cUrl = new URL(url);
1111 return cUrl.port ? `${cUrl.hostname}:${cUrl.port}` : `${cUrl.hostname}`;
1114 export function validTitle(title?: string): boolean {
1115 // Initial title is null, minimum length is taken care of by textarea's minLength={3}
1116 if (!title || title.length < 3) return true;
1118 const regex = new RegExp(/.*\S.*/, "g");
1120 return regex.test(title);
1123 export function siteBannerCss(banner: string): string {
1125 background-image: linear-gradient( rgba(0, 0, 0, 0.8), rgba(0, 0, 0, 0.8) ) ,url("${banner}"); \
1126 background-attachment: fixed; \
1127 background-position: top; \
1128 background-repeat: no-repeat; \
1129 background-size: 100% cover; \
1132 max-height: 100vh; \
1136 export function isBrowser() {
1137 return typeof window !== "undefined";
1140 export function setIsoData(context: any): IsoData {
1141 // If its the browser, you need to deserialize the data from the window
1143 let json = window.isoData;
1144 let routeData = json.routeData;
1145 let site_res = json.site_res;
1147 let isoData: IsoData = {
1153 } else return context.router.staticContext;
1156 export function wsSubscribe(parseMessage: any): Subscription | undefined {
1158 return WebSocketService.Instance.subject
1159 .pipe(retryWhen(errors => errors.pipe(delay(3000), take(10))))
1161 msg => parseMessage(msg),
1162 err => console.error(err),
1163 () => console.log("complete")
1170 moment.updateLocale("en", {
1191 export function saveScrollPosition(context: any) {
1192 let path: string = context.router.route.location.pathname;
1193 let y = window.scrollY;
1194 sessionStorage.setItem(`scrollPosition_${path}`, y.toString());
1197 export function restoreScrollPosition(context: any) {
1198 let path: string = context.router.route.location.pathname;
1199 let y = Number(sessionStorage.getItem(`scrollPosition_${path}`));
1200 window.scrollTo(0, y);
1203 export function showLocal(isoData: IsoData): boolean {
1204 let linked = isoData.site_res.federated_instances?.linked;
1205 return linked ? linked.length > 0 : false;
1208 export interface ChoicesValue {
1213 export function communityToChoice(cv: CommunityView): ChoicesValue {
1214 let choice: ChoicesValue = {
1215 value: cv.community.id.toString(),
1216 label: communitySelectName(cv),
1221 export function personToChoice(pvs: PersonViewSafe): ChoicesValue {
1222 let choice: ChoicesValue = {
1223 value: pvs.person.id.toString(),
1224 label: personSelectName(pvs),
1229 export async function fetchCommunities(q: string) {
1230 let form: Search = {
1232 type_: SearchType.Communities,
1233 sort: SortType.TopAll,
1234 listing_type: ListingType.All,
1237 auth: myAuth(false),
1239 let client = new LemmyHttp(httpBase);
1240 return client.search(form);
1243 export async function fetchUsers(q: string) {
1244 let form: Search = {
1246 type_: SearchType.Users,
1247 sort: SortType.TopAll,
1248 listing_type: ListingType.All,
1251 auth: myAuth(false),
1253 let client = new LemmyHttp(httpBase);
1254 return client.search(form);
1257 export const choicesConfig = {
1259 searchResultLimit: fetchLimit,
1261 containerOuter: "choices custom-select px-0",
1263 "choices__inner bg-secondary border-0 py-0 modlog-choices-font-size",
1264 input: "form-control",
1265 inputCloned: "choices__input--cloned",
1266 list: "choices__list",
1267 listItems: "choices__list--multiple",
1268 listSingle: "choices__list--single py-0",
1269 listDropdown: "choices__list--dropdown",
1270 item: "choices__item bg-secondary",
1271 itemSelectable: "choices__item--selectable",
1272 itemDisabled: "choices__item--disabled",
1273 itemChoice: "choices__item--choice",
1274 placeholder: "choices__placeholder",
1275 group: "choices__group",
1276 groupHeading: "choices__heading",
1277 button: "choices__button",
1278 activeState: "is-active",
1279 focusState: "is-focused",
1280 openState: "is-open",
1281 disabledState: "is-disabled",
1282 highlightedState: "text-info",
1283 selectedState: "text-info",
1284 flippedState: "is-flipped",
1285 loadingState: "is-loading",
1286 noResults: "has-no-results",
1287 noChoices: "has-no-choices",
1291 export function communitySelectName(cv: CommunityView): string {
1292 return cv.community.local
1293 ? cv.community.title
1294 : `${hostname(cv.community.actor_id)}/${cv.community.title}`;
1297 export function personSelectName(pvs: PersonViewSafe): string {
1298 let pName = pvs.person.display_name ?? pvs.person.name;
1299 return pvs.person.local ? pName : `${hostname(pvs.person.actor_id)}/${pName}`;
1302 export function initializeSite(site: GetSiteResponse) {
1303 UserService.Instance.myUserInfo = site.my_user;
1304 i18n.changeLanguage(getLanguages()[0]);
1307 const SHORTNUM_SI_FORMAT = new Intl.NumberFormat("en-US", {
1308 maximumSignificantDigits: 3,
1310 notation: "compact",
1311 compactDisplay: "short",
1314 export function numToSI(value: number): string {
1315 return SHORTNUM_SI_FORMAT.format(value);
1318 export function isBanned(ps: PersonSafe): boolean {
1319 let expires = ps.ban_expires;
1320 // Add Z to convert from UTC date
1321 // TODO this check probably isn't necessary anymore
1323 if (ps.banned && new Date(expires + "Z") > new Date()) {
1333 export function pushNotNull(array: any[], new_item?: any) {
1335 array.push(...new_item);
1339 export function myAuth(throwErr = true): string | undefined {
1340 return UserService.Instance.auth(throwErr);
1343 export function enableDownvotes(siteRes: GetSiteResponse): boolean {
1344 return siteRes.site_view.local_site.enable_downvotes;
1347 export function enableNsfw(siteRes: GetSiteResponse): boolean {
1348 return siteRes.site_view.local_site.enable_nsfw;
1351 export function postToCommentSortType(sort: SortType): CommentSortType {
1352 if ([SortType.Active, SortType.Hot].includes(sort)) {
1353 return CommentSortType.Hot;
1354 } else if ([SortType.New, SortType.NewComments].includes(sort)) {
1355 return CommentSortType.New;
1356 } else if (sort == SortType.Old) {
1357 return CommentSortType.Old;
1359 return CommentSortType.Top;
1363 export function myFirstDiscussionLanguageId(
1364 allLanguages: Language[],
1365 siteLanguages: number[],
1366 myUserInfo = UserService.Instance.myUserInfo
1367 ): number | undefined {
1368 return selectableLanguages(
1377 export function canCreateCommunity(
1378 siteRes: GetSiteResponse,
1379 myUserInfo = UserService.Instance.myUserInfo
1381 let adminOnly = siteRes.site_view.local_site.community_creation_admin_only;
1382 return !adminOnly || amAdmin(myUserInfo);
1385 export function isPostBlocked(
1387 myUserInfo = UserService.Instance.myUserInfo
1390 (myUserInfo?.community_blocks
1391 .map(c => c.community.id)
1392 .includes(pv.community.id) ||
1393 myUserInfo?.person_blocks
1394 .map(p => p.target.id)
1395 .includes(pv.creator.id)) ??
1400 /// Checks to make sure you can view NSFW posts. Returns true if you can.
1401 export function nsfwCheck(
1403 myUserInfo = UserService.Instance.myUserInfo
1405 let nsfw = pv.post.nsfw || pv.community.nsfw;
1406 let myShowNsfw = myUserInfo?.local_user_view.local_user.show_nsfw ?? false;
1407 return !nsfw || (nsfw && myShowNsfw);
1410 export function getRandomFromList<T>(list?: T[]): T | undefined {
1411 return list?.at(Math.floor(Math.random() * list.length));
1415 * This shows what language you can select
1417 * Use showAll for the site form
1418 * Use showSite for the profile and community forms
1419 * Use false for both those to filter on your profile and site ones
1421 export function selectableLanguages(
1422 allLanguages: Language[],
1423 siteLanguages: number[],
1426 myUserInfo = UserService.Instance.myUserInfo
1428 let allLangIds = allLanguages.map(l => l.id);
1429 let myLangs = myUserInfo?.discussion_languages ?? allLangIds;
1430 myLangs = myLangs.length == 0 ? allLangIds : myLangs;
1431 let siteLangs = siteLanguages.length == 0 ? allLangIds : siteLanguages;
1434 return allLanguages;
1437 return allLanguages.filter(x => siteLangs.includes(x.id));
1440 .filter(x => siteLangs.includes(x.id))
1441 .filter(x => myLangs.includes(x.id));
1446 export function uploadImage(image: File): Promise<UploadImageResponse> {
1447 const client = new LemmyHttp(httpBase);
1449 return client.uploadImage({ image });