1 import emojiShortName from "emoji-short-name";
3 BlockCommunityResponse,
21 RegistrationApplicationView,
26 WebSocketJsonResponse,
28 } from "lemmy-js-client";
29 import markdown_it 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";
43 CommentNode as CommentNodeI,
47 } from "./interfaces";
48 import { UserService, WebSocketService } from "./services";
52 Tribute = require("tributejs");
55 export const wsClient = new LemmyWebsocket();
57 export const favIconUrl = "/static/assets/icons/favicon.svg";
58 export const favIconPngUrl = "/static/assets/icons/apple-touch-icon.png";
60 // export const defaultFavIcon = `${window.location.protocol}//${window.location.host}${favIconPngUrl}`;
61 export const repoUrl = "https://github.com/LemmyNet";
62 export const joinLemmyUrl = "https://join-lemmy.org";
63 export const donateLemmyUrl = `${joinLemmyUrl}/donate`;
64 export const docsUrl = `${joinLemmyUrl}/docs/en/index.html`;
65 export const helpGuideUrl = `${joinLemmyUrl}/docs/en/about/guide.html`; // TODO find a way to redirect to the non-en folder
66 export const markdownHelpUrl = `${helpGuideUrl}#using-markdown`;
67 export const sortingHelpUrl = `${helpGuideUrl}#sorting`;
68 export const archiveTodayUrl = "https://archive.today";
69 export const ghostArchiveUrl = "https://ghostarchive.org";
70 export const webArchiveUrl = "https://web.archive.org";
71 export const elementUrl = "https://element.io";
73 export const postRefetchSeconds: number = 60 * 1000;
74 export const fetchLimit = 20;
75 export const mentionDropdownFetchLimit = 10;
77 export const relTags = "noopener nofollow";
79 const DEFAULT_ALPHABET =
80 "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
82 function getRandomCharFromAlphabet(alphabet: string): string {
83 return alphabet.charAt(Math.floor(Math.random() * alphabet.length));
86 export function randomStr(
88 alphabet = DEFAULT_ALPHABET
91 * Create n-long array and map it to random chars from given alphabet.
92 * Then join individual chars as string
94 return Array.from({ length: idDesiredLength })
96 return getRandomCharFromAlphabet(alphabet);
101 export function wsJsonToRes<ResponseType>(
102 msg: WebSocketJsonResponse<ResponseType>
103 ): WebSocketResponse<ResponseType> {
110 export function wsUserOp(msg: any): UserOperation {
111 let opStr: string = msg.op;
112 return UserOperation[opStr];
115 export const md = new markdown_it({
120 .use(markdown_it_sub)
121 .use(markdown_it_sup)
122 .use(markdown_it_footnote)
123 .use(markdown_it_html5_embed, {
125 useImageSyntax: true, // Enables video/audio embed with ![]() syntax (default)
127 audio: 'controls preload="metadata"',
129 'width="100%" max-height="100%" controls loop preload="metadata"',
133 .use(markdown_it_container, "spoiler", {
134 validate: function (params: any) {
135 return params.trim().match(/^spoiler\s+(.*)$/);
138 render: function (tokens: any, idx: any) {
139 var m = tokens[idx].info.trim().match(/^spoiler\s+(.*)$/);
141 if (tokens[idx].nesting === 1) {
143 return `<details><summary> ${md.utils.escapeHtml(m[1])} </summary>\n`;
146 return "</details>\n";
151 export function hotRankComment(comment_view: CommentView): number {
152 return hotRank(comment_view.counts.score, comment_view.comment.published);
155 export function hotRankActivePost(post_view: PostView): number {
156 return hotRank(post_view.counts.score, post_view.counts.newest_comment_time);
159 export function hotRankPost(post_view: PostView): number {
160 return hotRank(post_view.counts.score, post_view.post.published);
163 export function hotRank(score: number, timeStr: string): number {
164 // Rank = ScaleFactor * sign(Score) * log(1 + abs(Score)) / (Time + 2)^Gravity
165 let date: Date = new Date(timeStr + "Z"); // Add Z to convert from UTC date
166 let now: Date = new Date();
167 let hoursElapsed: number = (now.getTime() - date.getTime()) / 36e5;
170 (10000 * Math.log10(Math.max(1, 3 + score))) /
171 Math.pow(hoursElapsed + 2, 1.8);
173 // console.log(`Comment: ${comment.content}\nRank: ${rank}\nScore: ${comment.score}\nHours: ${hoursElapsed}`);
178 export function mdToHtml(text: string) {
179 return { __html: md.render(text) };
182 export function getUnixTime(text: string): number {
183 return text ? new Date(text).getTime() / 1000 : undefined;
186 export function futureDaysToUnixTime(days: number): number {
189 new Date(Date.now() + 1000 * 60 * 60 * 24 * days).getTime() / 1000
194 export function canMod(
195 myUserInfo: MyUserInfo,
200 // You can do moderator actions only on the mods added after you.
202 let yourIndex = modIds.findIndex(
203 id => id == myUserInfo.local_user_view.person.id
205 if (yourIndex == -1) {
208 // onSelf +1 on mod actions not for yourself, IE ban, remove, etc
209 modIds = modIds.slice(0, yourIndex + (onSelf ? 0 : 1));
210 return !modIds.includes(creator_id);
217 export function isMod(modIds: number[], creator_id: number): boolean {
218 return modIds.includes(creator_id);
221 const imageRegex = /(http)?s?:?(\/\/[^"']*\.(?:jpg|jpeg|gif|png|svg|webp))/;
222 const videoRegex = /(http)?s?:?(\/\/[^"']*\.(?:mp4|webm))/;
224 export function isImage(url: string) {
225 return imageRegex.test(url);
228 export function isVideo(url: string) {
229 return videoRegex.test(url);
232 export function validURL(str: string) {
233 return !!new URL(str);
236 export function communityRSSUrl(actorId: string, sort: string): string {
237 let url = new URL(actorId);
238 return `${url.origin}/feeds${url.pathname}.xml?sort=${sort}`;
241 export function validEmail(email: string) {
243 /^(([^\s"(),.:;<>@[\\\]]+(\.[^\s"(),.:;<>@[\\\]]+)*)|(".+"))@((\[(?:\d{1,3}\.){3}\d{1,3}])|(([\dA-Za-z\-]+\.)+[A-Za-z]{2,}))$/;
244 return re.test(String(email).toLowerCase());
247 export function capitalizeFirstLetter(str: string): string {
248 return str.charAt(0).toUpperCase() + str.slice(1);
251 export function routeSortTypeToEnum(sort: string): SortType {
252 return SortType[sort];
255 export function listingTypeFromNum(type_: number): ListingType {
256 return Object.values(ListingType)[type_];
259 export function sortTypeFromNum(type_: number): SortType {
260 return Object.values(SortType)[type_];
263 export function routeListingTypeToEnum(type: string): ListingType {
264 return ListingType[type];
267 export function routeDataTypeToEnum(type: string): DataType {
268 return DataType[capitalizeFirstLetter(type)];
271 export function routeSearchTypeToEnum(type: string): SearchType {
272 return SearchType[type];
275 export async function getSiteMetadata(url: string) {
276 let form: GetSiteMetadata = {
279 let client = new LemmyHttp(httpBase);
280 return client.getSiteMetadata(form);
283 export function debounce(func: any, wait = 1000, immediate = false) {
284 // 'private' variable for instance
285 // The returned function will be able to reference this due to closure.
286 // Each call to the returned function will share this common timer.
289 // Calling debounce returns a new anonymous function
291 // reference the context and args for the setTimeout function
292 var args = arguments;
294 // Should the function be called now? If immediate is true
295 // and not already in a timeout then the answer is: Yes
296 var callNow = immediate && !timeout;
298 // This is the basic debounce behaviour where you can call this
299 // function several times, but it will only execute once
300 // [before or after imposing a delay].
301 // Each time the returned function is called, the timer starts over.
302 clearTimeout(timeout);
304 // Set the new timeout
305 timeout = setTimeout(function () {
306 // Inside the timeout function, clear the timeout variable
307 // which will let the next execution run when in 'immediate' mode
310 // Check if the function already ran with the immediate flag
312 // Call the original function with apply
313 // apply lets you define the 'this' object as well as the arguments
314 // (both captured before setTimeout)
315 func.apply(this, args);
319 // Immediate mode and no wait timer? Execute the function..
320 if (callNow) func.apply(this, args);
324 export function getLanguages(override?: string): string[] {
325 let myUserInfo = UserService.Instance.myUserInfo;
328 (myUserInfo?.local_user_view.local_user.lang
329 ? myUserInfo.local_user_view.local_user.lang
332 if (lang == "browser" && isBrowser()) {
333 return getBrowserLanguages();
339 function getBrowserLanguages(): string[] {
340 // Intersect lemmy's langs, with the browser langs
341 let langs = languages ? languages.map(l => l.code) : ["en"];
343 // NOTE, mobile browsers seem to be missing this list, so append en
344 let allowedLangs = navigator.languages
346 .filter(v => langs.includes(v));
350 export async function fetchThemeList(): Promise<string[]> {
351 return fetch("/css/themelist").then(res => res.json());
354 export async function setTheme(theme: string, forceReload = false) {
358 if (theme === "browser" && !forceReload) {
361 // This is only run on a force reload
362 if (theme == "browser") {
366 let themeList = await fetchThemeList();
368 // Unload all the other themes
369 for (var i = 0; i < themeList.length; i++) {
370 let styleSheet = document.getElementById(themeList[i]);
372 styleSheet.setAttribute("disabled", "disabled");
377 .getElementById("default-light")
378 ?.setAttribute("disabled", "disabled");
379 document.getElementById("default-dark")?.setAttribute("disabled", "disabled");
381 // Load the theme dynamically
382 let cssLoc = `/css/themes/${theme}.css`;
384 loadCss(theme, cssLoc);
385 document.getElementById(theme).removeAttribute("disabled");
388 export function loadCss(id: string, loc: string) {
389 if (!document.getElementById(id)) {
390 var head = document.getElementsByTagName("head")[0];
391 var link = document.createElement("link");
393 link.rel = "stylesheet";
394 link.type = "text/css";
397 head.appendChild(link);
401 export function objectFlip(obj: any) {
403 Object.keys(obj).forEach(key => {
409 export function showAvatars(): boolean {
411 UserService.Instance.myUserInfo?.local_user_view.local_user.show_avatars ||
412 !UserService.Instance.myUserInfo
416 export function showScores(): boolean {
418 UserService.Instance.myUserInfo?.local_user_view.local_user.show_scores ||
419 !UserService.Instance.myUserInfo
423 export function isCakeDay(published: string): boolean {
424 // moment(undefined) or moment.utc(undefined) returns the current date/time
425 // moment(null) or moment.utc(null) returns null
426 const createDate = moment.utc(published || null).local();
427 const currentDate = moment(new Date());
430 createDate.date() === currentDate.date() &&
431 createDate.month() === currentDate.month() &&
432 createDate.year() !== currentDate.year()
436 export function toast(text: string, background = "success") {
438 let backgroundColor = `var(--${background})`;
441 backgroundColor: backgroundColor,
448 export function pictrsDeleteToast(
449 clickToDeleteText: string,
450 deletePictureText: string,
454 let backgroundColor = `var(--light)`;
455 let toast = Toastify({
456 text: clickToDeleteText,
457 backgroundColor: backgroundColor,
463 window.location.replace(deleteUrl);
464 alert(deletePictureText);
473 interface NotifyInfo {
480 export function messageToastify(info: NotifyInfo, router: any) {
482 let htmlBody = info.body ? md.render(info.body) : "";
483 let backgroundColor = `var(--light)`;
485 let toast = Toastify({
486 text: `${htmlBody}<br />${info.name}`,
487 avatar: info.icon ? info.icon : null,
488 backgroundColor: backgroundColor,
489 className: "text-dark",
498 router.history.push(info.link);
505 export function notifyPost(post_view: PostView, router: any) {
506 let info: NotifyInfo = {
507 name: post_view.community.name,
508 icon: post_view.community.icon,
509 link: `/post/${post_view.post.id}`,
510 body: post_view.post.name,
512 notify(info, router);
515 export function notifyComment(comment_view: CommentView, router: any) {
516 let info: NotifyInfo = {
517 name: comment_view.creator.name,
518 icon: comment_view.creator.avatar,
519 link: `/post/${comment_view.post.id}/comment/${comment_view.comment.id}`,
520 body: comment_view.comment.content,
522 notify(info, router);
525 export function notifyPrivateMessage(pmv: PrivateMessageView, router: any) {
526 let info: NotifyInfo = {
527 name: pmv.creator.name,
528 icon: pmv.creator.avatar,
530 body: pmv.private_message.content,
532 notify(info, router);
535 function notify(info: NotifyInfo, router: any) {
536 messageToastify(info, router);
538 // TODO absolute nightmare bug, but notifs are currently broken.
539 // Notification.new will try to do a browser fetch ???
541 // if (Notification.permission !== "granted") Notification.requestPermission();
543 // var notification = new Notification(info.name, {
548 // notification.onclick = (ev: Event): any => {
549 // ev.preventDefault();
550 // router.history.push(info.link);
555 export function setupTribute() {
557 noMatchTemplate: function () {
564 menuItemTemplate: (item: any) => {
565 let shortName = `:${item.original.key}:`;
566 return `${item.original.val} ${shortName}`;
568 selectTemplate: (item: any) => {
569 return `${item.original.val}`;
571 values: Object.entries(emojiShortName).map(e => {
572 return { key: e[1], val: e[0] };
575 autocompleteMode: true,
577 // menuItemLimit: mentionDropdownFetchLimit,
578 menuShowMinLength: 2,
583 selectTemplate: (item: any) => {
584 let it: PersonTribute = item.original;
585 return `[${it.key}](${it.view.person.actor_id})`;
587 values: debounce(async (text: string, cb: any) => {
588 cb(await personSearch(text));
591 autocompleteMode: true,
593 // menuItemLimit: mentionDropdownFetchLimit,
594 menuShowMinLength: 2,
600 selectTemplate: (item: any) => {
601 let it: CommunityTribute = item.original;
602 return `[${it.key}](${it.view.community.actor_id})`;
604 values: debounce(async (text: string, cb: any) => {
605 cb(await communitySearch(text));
608 autocompleteMode: true,
610 // menuItemLimit: mentionDropdownFetchLimit,
611 menuShowMinLength: 2,
617 var tippyInstance: any;
619 tippyInstance = tippy("[data-tippy-content]");
622 export function setupTippy() {
624 tippyInstance.forEach((e: any) => e.destroy());
625 tippyInstance = tippy("[data-tippy-content]", {
627 // Display on "long press"
628 touch: ["hold", 500],
633 interface PersonTribute {
635 view: PersonViewSafe;
638 async function personSearch(text: string): Promise<PersonTribute[]> {
639 let users = (await fetchUsers(text)).users;
640 let persons: PersonTribute[] = users.map(pv => {
641 let tribute: PersonTribute = {
642 key: `@${pv.person.name}@${hostname(pv.person.actor_id)}`,
650 interface CommunityTribute {
655 async function communitySearch(text: string): Promise<CommunityTribute[]> {
656 let comms = (await fetchCommunities(text)).communities;
657 let communities: CommunityTribute[] = comms.map(cv => {
658 let tribute: CommunityTribute = {
659 key: `!${cv.community.name}@${hostname(cv.community.actor_id)}`,
667 export function getListingTypeFromProps(props: any): ListingType {
668 return props.match.params.listing_type
669 ? routeListingTypeToEnum(props.match.params.listing_type)
670 : UserService.Instance.myUserInfo
671 ? Object.values(ListingType)[
672 UserService.Instance.myUserInfo.local_user_view.local_user
673 .default_listing_type
678 export function getListingTypeFromPropsNoDefault(props: any): ListingType {
679 return props.match.params.listing_type
680 ? routeListingTypeToEnum(props.match.params.listing_type)
684 // TODO might need to add a user setting for this too
685 export function getDataTypeFromProps(props: any): DataType {
686 return props.match.params.data_type
687 ? routeDataTypeToEnum(props.match.params.data_type)
691 export function getSortTypeFromProps(props: any): SortType {
692 return props.match.params.sort
693 ? routeSortTypeToEnum(props.match.params.sort)
694 : UserService.Instance.myUserInfo
695 ? Object.values(SortType)[
696 UserService.Instance.myUserInfo.local_user_view.local_user
702 export function getPageFromProps(props: any): number {
703 return props.match.params.page ? Number(props.match.params.page) : 1;
706 export function getRecipientIdFromProps(props: any): number {
707 return props.match.params.recipient_id
708 ? Number(props.match.params.recipient_id)
712 export function getIdFromProps(props: any): number {
713 return Number(props.match.params.id);
716 export function getCommentIdFromProps(props: any): number {
717 return Number(props.match.params.comment_id);
720 export function getUsernameFromProps(props: any): string {
721 return props.match.params.username;
724 export function editCommentRes(data: CommentView, comments: CommentView[]) {
725 let found = comments.find(c => c.comment.id == data.comment.id);
727 found.comment.content = data.comment.content;
728 found.comment.updated = data.comment.updated;
729 found.comment.removed = data.comment.removed;
730 found.comment.deleted = data.comment.deleted;
731 found.counts.upvotes = data.counts.upvotes;
732 found.counts.downvotes = data.counts.downvotes;
733 found.counts.score = data.counts.score;
737 export function saveCommentRes(data: CommentView, comments: CommentView[]) {
738 let found = comments.find(c => c.comment.id == data.comment.id);
740 found.saved = data.saved;
744 export function updatePersonBlock(
745 data: BlockPersonResponse
746 ): PersonBlockView[] {
748 UserService.Instance.myUserInfo.person_blocks.push({
749 person: UserService.Instance.myUserInfo.local_user_view.person,
750 target: data.person_view.person,
752 toast(`${i18n.t("blocked")} ${data.person_view.person.name}`);
754 UserService.Instance.myUserInfo.person_blocks =
755 UserService.Instance.myUserInfo.person_blocks.filter(
756 i => i.target.id != data.person_view.person.id
758 toast(`${i18n.t("unblocked")} ${data.person_view.person.name}`);
760 return UserService.Instance.myUserInfo.person_blocks;
763 export function updateCommunityBlock(
764 data: BlockCommunityResponse
765 ): CommunityBlockView[] {
767 UserService.Instance.myUserInfo.community_blocks.push({
768 person: UserService.Instance.myUserInfo.local_user_view.person,
769 community: data.community_view.community,
771 toast(`${i18n.t("blocked")} ${data.community_view.community.name}`);
773 UserService.Instance.myUserInfo.community_blocks =
774 UserService.Instance.myUserInfo.community_blocks.filter(
775 i => i.community.id != data.community_view.community.id
777 toast(`${i18n.t("unblocked")} ${data.community_view.community.name}`);
779 return UserService.Instance.myUserInfo.community_blocks;
782 export function createCommentLikeRes(
784 comments: CommentView[]
786 let found = comments.find(c => c.comment.id === data.comment.id);
788 found.counts.score = data.counts.score;
789 found.counts.upvotes = data.counts.upvotes;
790 found.counts.downvotes = data.counts.downvotes;
791 if (data.my_vote !== null) {
792 found.my_vote = data.my_vote;
797 export function createPostLikeFindRes(data: PostView, posts: PostView[]) {
798 let found = posts.find(p => p.post.id == data.post.id);
800 createPostLikeRes(data, found);
804 export function createPostLikeRes(data: PostView, post_view: PostView) {
806 post_view.counts.score = data.counts.score;
807 post_view.counts.upvotes = data.counts.upvotes;
808 post_view.counts.downvotes = data.counts.downvotes;
809 if (data.my_vote !== null) {
810 post_view.my_vote = data.my_vote;
815 export function editPostFindRes(data: PostView, posts: PostView[]) {
816 let found = posts.find(p => p.post.id == data.post.id);
818 editPostRes(data, found);
822 export function editPostRes(data: PostView, post: PostView) {
824 post.post.url = data.post.url;
825 post.post.name = data.post.name;
826 post.post.nsfw = data.post.nsfw;
827 post.post.deleted = data.post.deleted;
828 post.post.removed = data.post.removed;
829 post.post.stickied = data.post.stickied;
830 post.post.body = data.post.body;
831 post.post.locked = data.post.locked;
832 post.saved = data.saved;
836 export function updatePostReportRes(
837 data: PostReportView,
838 reports: PostReportView[]
840 let found = reports.find(p => p.post_report.id == data.post_report.id);
842 found.post_report = data.post_report;
846 export function updateCommentReportRes(
847 data: CommentReportView,
848 reports: CommentReportView[]
850 let found = reports.find(c => c.comment_report.id == data.comment_report.id);
852 found.comment_report = data.comment_report;
856 export function updateRegistrationApplicationRes(
857 data: RegistrationApplicationView,
858 applications: RegistrationApplicationView[]
860 let found = applications.find(
861 ra => ra.registration_application.id == data.registration_application.id
864 found.registration_application = data.registration_application;
865 found.admin = data.admin;
866 found.creator_local_user = data.creator_local_user;
870 export function commentsToFlatNodes(comments: CommentView[]): CommentNodeI[] {
871 let nodes: CommentNodeI[] = [];
872 for (let comment of comments) {
873 nodes.push({ comment_view: comment });
878 function commentSort(tree: CommentNodeI[], sort: CommentSortType) {
879 // First, put removed and deleted comments at the bottom, then do your other sorts
880 if (sort == CommentSortType.Top) {
883 +a.comment_view.comment.removed - +b.comment_view.comment.removed ||
884 +a.comment_view.comment.deleted - +b.comment_view.comment.deleted ||
885 b.comment_view.counts.score - a.comment_view.counts.score
887 } else if (sort == CommentSortType.New) {
890 +a.comment_view.comment.removed - +b.comment_view.comment.removed ||
891 +a.comment_view.comment.deleted - +b.comment_view.comment.deleted ||
892 b.comment_view.comment.published.localeCompare(
893 a.comment_view.comment.published
896 } else if (sort == CommentSortType.Old) {
899 +a.comment_view.comment.removed - +b.comment_view.comment.removed ||
900 +a.comment_view.comment.deleted - +b.comment_view.comment.deleted ||
901 a.comment_view.comment.published.localeCompare(
902 b.comment_view.comment.published
905 } else if (sort == CommentSortType.Hot) {
908 +a.comment_view.comment.removed - +b.comment_view.comment.removed ||
909 +a.comment_view.comment.deleted - +b.comment_view.comment.deleted ||
910 hotRankComment(b.comment_view) - hotRankComment(a.comment_view)
914 // Go through the children recursively
915 for (let node of tree) {
917 commentSort(node.children, sort);
922 export function commentSortSortType(tree: CommentNodeI[], sort: SortType) {
923 commentSort(tree, convertCommentSortType(sort));
926 function convertCommentSortType(sort: SortType): CommentSortType {
928 sort == SortType.TopAll ||
929 sort == SortType.TopDay ||
930 sort == SortType.TopWeek ||
931 sort == SortType.TopMonth ||
932 sort == SortType.TopYear
934 return CommentSortType.Top;
935 } else if (sort == SortType.New) {
936 return CommentSortType.New;
937 } else if (sort == SortType.Hot || sort == SortType.Active) {
938 return CommentSortType.Hot;
940 return CommentSortType.Hot;
944 export function buildCommentsTree(
945 comments: CommentView[],
946 commentSortType: CommentSortType
948 let map = new Map<number, CommentNodeI>();
949 for (let comment_view of comments) {
950 let node: CommentNodeI = {
951 comment_view: comment_view,
954 map.set(comment_view.comment.id, { ...node });
956 let tree: CommentNodeI[] = [];
957 for (let comment_view of comments) {
958 let child = map.get(comment_view.comment.id);
959 let parent_id = comment_view.comment.parent_id;
961 let parent = map.get(parent_id);
962 // Necessary because blocked comment might not exist
964 parent.children.push(child);
973 commentSort(tree, commentSortType);
978 function setDepth(node: CommentNodeI, i = 0) {
979 for (let child of node.children) {
981 setDepth(child, i + 1);
985 export function insertCommentIntoTree(tree: CommentNodeI[], cv: CommentView) {
986 // Building a fake node to be used for later
987 let node: CommentNodeI = {
993 if (cv.comment.parent_id) {
994 let parentComment = searchCommentTree(tree, cv.comment.parent_id);
996 node.depth = parentComment.depth + 1;
997 parentComment.children.unshift(node);
1004 export function searchCommentTree(
1005 tree: CommentNodeI[],
1008 for (let node of tree) {
1009 if (node.comment_view.comment.id === id) {
1013 for (const child of node.children) {
1014 const res = searchCommentTree([child], id);
1024 export const colorList: string[] = [
1033 function hsl(num: number) {
1034 return `hsla(${num}, 35%, 50%, 1)`;
1037 export function previewLines(
1046 // Use lines * 2 because markdown requires 2 lines
1047 .slice(0, maxLines * 2)
1052 export function hostname(url: string): string {
1053 let cUrl = new URL(url);
1054 return cUrl.port ? `${cUrl.hostname}:${cUrl.port}` : `${cUrl.hostname}`;
1057 export function validTitle(title?: string): boolean {
1058 // Initial title is null, minimum length is taken care of by textarea's minLength={3}
1059 if (title === null || title.length < 3) return true;
1061 const regex = new RegExp(/.*\S.*/, "g");
1063 return regex.test(title);
1066 export function siteBannerCss(banner: string): string {
1068 background-image: linear-gradient( rgba(0, 0, 0, 0.8), rgba(0, 0, 0, 0.8) ) ,url("${banner}"); \
1069 background-attachment: fixed; \
1070 background-position: top; \
1071 background-repeat: no-repeat; \
1072 background-size: 100% cover; \
1075 max-height: 100vh; \
1079 export function isBrowser() {
1080 return typeof window !== "undefined";
1083 export function setIsoData(context: any): IsoData {
1084 let isoData: IsoData = isBrowser()
1086 : context.router.staticContext;
1090 export function wsSubscribe(parseMessage: any): Subscription {
1092 return WebSocketService.Instance.subject
1093 .pipe(retryWhen(errors => errors.pipe(delay(3000), take(10))))
1095 msg => parseMessage(msg),
1096 err => console.error(err),
1097 () => console.log("complete")
1104 export function setOptionalAuth(obj: any, auth = UserService.Instance.auth) {
1110 export function authField(
1112 auth = UserService.Instance.auth
1114 if (auth == null && throwErr) {
1115 toast(i18n.t("not_logged_in"), "danger");
1116 throw "Not logged in";
1122 moment.updateLocale("en", {
1143 export function saveScrollPosition(context: any) {
1144 let path: string = context.router.route.location.pathname;
1145 let y = window.scrollY;
1146 sessionStorage.setItem(`scrollPosition_${path}`, y.toString());
1149 export function restoreScrollPosition(context: any) {
1150 let path: string = context.router.route.location.pathname;
1151 let y = Number(sessionStorage.getItem(`scrollPosition_${path}`));
1152 window.scrollTo(0, y);
1155 export function showLocal(isoData: IsoData): boolean {
1156 return isoData.site_res.federated_instances?.linked.length > 0;
1159 interface ChoicesValue {
1164 export function communityToChoice(cv: CommunityView): ChoicesValue {
1165 let choice: ChoicesValue = {
1166 value: cv.community.id.toString(),
1167 label: communitySelectName(cv),
1172 export function personToChoice(pvs: PersonViewSafe): ChoicesValue {
1173 let choice: ChoicesValue = {
1174 value: pvs.person.id.toString(),
1175 label: personSelectName(pvs),
1180 export async function fetchCommunities(q: string) {
1181 let form: Search = {
1183 type_: SearchType.Communities,
1184 sort: SortType.TopAll,
1185 listing_type: ListingType.All,
1188 auth: authField(false),
1190 let client = new LemmyHttp(httpBase);
1191 return client.search(form);
1194 export async function fetchUsers(q: string) {
1195 let form: Search = {
1197 type_: SearchType.Users,
1198 sort: SortType.TopAll,
1199 listing_type: ListingType.All,
1202 auth: authField(false),
1204 let client = new LemmyHttp(httpBase);
1205 return client.search(form);
1208 export const choicesConfig = {
1210 searchResultLimit: fetchLimit,
1212 containerOuter: "choices",
1213 containerInner: "choices__inner bg-secondary border-0",
1214 input: "form-control",
1215 inputCloned: "choices__input--cloned",
1216 list: "choices__list",
1217 listItems: "choices__list--multiple",
1218 listSingle: "choices__list--single",
1219 listDropdown: "choices__list--dropdown",
1220 item: "choices__item bg-secondary",
1221 itemSelectable: "choices__item--selectable",
1222 itemDisabled: "choices__item--disabled",
1223 itemChoice: "choices__item--choice",
1224 placeholder: "choices__placeholder",
1225 group: "choices__group",
1226 groupHeading: "choices__heading",
1227 button: "choices__button",
1228 activeState: "is-active",
1229 focusState: "is-focused",
1230 openState: "is-open",
1231 disabledState: "is-disabled",
1232 highlightedState: "text-info",
1233 selectedState: "text-info",
1234 flippedState: "is-flipped",
1235 loadingState: "is-loading",
1236 noResults: "has-no-results",
1237 noChoices: "has-no-choices",
1241 export function communitySelectName(cv: CommunityView): string {
1242 return cv.community.local
1243 ? cv.community.title
1244 : `${hostname(cv.community.actor_id)}/${cv.community.title}`;
1247 export function personSelectName(pvs: PersonViewSafe): string {
1248 let pName = pvs.person.display_name || pvs.person.name;
1249 return pvs.person.local ? pName : `${hostname(pvs.person.actor_id)}/${pName}`;
1252 export function initializeSite(site: GetSiteResponse) {
1253 UserService.Instance.myUserInfo = site.my_user;
1254 i18n.changeLanguage(getLanguages()[0]);
1257 const SHORTNUM_SI_FORMAT = new Intl.NumberFormat("en-US", {
1258 maximumSignificantDigits: 3,
1260 notation: "compact",
1261 compactDisplay: "short",
1264 export function numToSI(value: number): string {
1265 return SHORTNUM_SI_FORMAT.format(value);
1268 export function isBanned(ps: PersonSafe): boolean {
1269 // Add Z to convert from UTC date
1270 if (ps.ban_expires) {
1271 if (ps.banned && new Date(ps.ban_expires + "Z") > new Date()) {
1281 export function pushNotNull(array: any[], new_item?: any) {
1283 array.push(...new_item);