1 import "moment/locale/es";
2 import "moment/locale/el";
3 import "moment/locale/eu";
4 import "moment/locale/eo";
5 import "moment/locale/de";
6 import "moment/locale/zh-cn";
7 import "moment/locale/fr";
8 import "moment/locale/sv";
9 import "moment/locale/ru";
10 import "moment/locale/nl";
11 import "moment/locale/it";
12 import "moment/locale/fi";
13 import "moment/locale/ca";
14 import "moment/locale/fa";
15 import "moment/locale/pl";
16 import "moment/locale/pt-br";
17 import "moment/locale/ja";
18 import "moment/locale/ka";
19 import "moment/locale/hi";
20 import "moment/locale/gl";
21 import "moment/locale/tr";
22 import "moment/locale/hu";
23 import "moment/locale/uk";
24 import "moment/locale/sq";
25 import "moment/locale/km";
26 import "moment/locale/ga";
27 import "moment/locale/sr";
28 import "moment/locale/ko";
29 import "moment/locale/da";
30 import "moment/locale/hr";
31 import "moment/locale/bg";
32 import "moment/locale/id";
33 import "moment/locale/nb";
38 LocalUserSettingsView,
43 WebSocketJsonResponse,
52 } from "lemmy-js-client";
58 CommentNode as CommentNodeI,
59 } from "./interfaces";
60 import { UserService, WebSocketService } from "./services";
63 Tribute = require("tributejs");
65 import markdown_it from "markdown-it";
66 import markdown_it_sub from "markdown-it-sub";
67 import markdown_it_sup from "markdown-it-sup";
68 import markdown_it_container from "markdown-it-container";
69 import emojiShortName from "emoji-short-name";
70 import Toastify from "toastify-js";
71 import tippy from "tippy.js";
72 import moment from "moment";
73 import { Subscription } from "rxjs";
74 import { retryWhen, delay, take } from "rxjs/operators";
75 import { i18n } from "./i18next";
76 import { httpBase } from "./env";
78 export const wsClient = new LemmyWebsocket();
80 export const favIconUrl = "/static/assets/icons/favicon.svg";
81 export const favIconPngUrl = "/static/assets/icons/apple-touch-icon.png";
83 // export const defaultFavIcon = `${window.location.protocol}//${window.location.host}${favIconPngUrl}`;
84 export const repoUrl = "https://github.com/LemmyNet";
85 export const joinLemmyUrl = "https://join-lemmy.org";
86 export const supportLemmyUrl = `${joinLemmyUrl}/support`;
87 export const docsUrl = `${joinLemmyUrl}/docs/en/index.html`;
88 export const helpGuideUrl = `${joinLemmyUrl}/docs/en/about/guide.html`; // TODO find a way to redirect to the non-en folder
89 export const markdownHelpUrl = `${helpGuideUrl}#markdown-guide`;
90 export const sortingHelpUrl = `${helpGuideUrl}#sorting`;
91 export const archiveUrl = "https://archive.is";
92 export const elementUrl = "https://element.io/";
94 export const postRefetchSeconds: number = 60 * 1000;
95 export const fetchLimit = 20;
96 export const mentionDropdownFetchLimit = 10;
98 export const languages = [
138 export const themes = [
154 const DEFAULT_ALPHABET =
155 "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
157 function getRandomCharFromAlphabet(alphabet: string): string {
158 return alphabet.charAt(Math.floor(Math.random() * alphabet.length));
161 export function randomStr(
162 idDesiredLength = 20,
163 alphabet = DEFAULT_ALPHABET
166 * Create n-long array and map it to random chars from given alphabet.
167 * Then join individual chars as string
169 return Array.from({ length: idDesiredLength })
171 return getRandomCharFromAlphabet(alphabet);
176 export function wsJsonToRes<ResponseType>(
177 msg: WebSocketJsonResponse<ResponseType>
178 ): WebSocketResponse<ResponseType> {
185 export function wsUserOp(msg: any): UserOperation {
186 let opStr: string = msg.op;
187 return UserOperation[opStr];
190 export const md = new markdown_it({
195 .use(markdown_it_sub)
196 .use(markdown_it_sup)
197 .use(markdown_it_container, "spoiler", {
198 validate: function (params: any) {
199 return params.trim().match(/^spoiler\s+(.*)$/);
202 render: function (tokens: any, idx: any) {
203 var m = tokens[idx].info.trim().match(/^spoiler\s+(.*)$/);
205 if (tokens[idx].nesting === 1) {
207 return `<details><summary> ${md.utils.escapeHtml(m[1])} </summary>\n`;
210 return "</details>\n";
215 export function hotRankComment(comment_view: CommentView): number {
216 return hotRank(comment_view.counts.score, comment_view.comment.published);
219 export function hotRankActivePost(post_view: PostView): number {
220 return hotRank(post_view.counts.score, post_view.counts.newest_comment_time);
223 export function hotRankPost(post_view: PostView): number {
224 return hotRank(post_view.counts.score, post_view.post.published);
227 export function hotRank(score: number, timeStr: string): number {
228 // Rank = ScaleFactor * sign(Score) * log(1 + abs(Score)) / (Time + 2)^Gravity
229 let date: Date = new Date(timeStr + "Z"); // Add Z to convert from UTC date
230 let now: Date = new Date();
231 let hoursElapsed: number = (now.getTime() - date.getTime()) / 36e5;
234 (10000 * Math.log10(Math.max(1, 3 + score))) /
235 Math.pow(hoursElapsed + 2, 1.8);
237 // console.log(`Comment: ${comment.content}\nRank: ${rank}\nScore: ${comment.score}\nHours: ${hoursElapsed}`);
242 export function mdToHtml(text: string) {
243 return { __html: md.render(text) };
246 export function getUnixTime(text: string): number {
247 return text ? new Date(text).getTime() / 1000 : undefined;
250 export function canMod(
251 localUserView: LocalUserSettingsView,
256 // You can do moderator actions only on the mods added after you.
258 let yourIndex = modIds.findIndex(id => id == localUserView.person.id);
259 if (yourIndex == -1) {
262 // onSelf +1 on mod actions not for yourself, IE ban, remove, etc
263 modIds = modIds.slice(0, yourIndex + (onSelf ? 0 : 1));
264 return !modIds.includes(creator_id);
271 export function isMod(modIds: number[], creator_id: number): boolean {
272 return modIds.includes(creator_id);
275 const imageRegex = new RegExp(
276 /(http)?s?:?(\/\/[^"']*\.(?:jpg|jpeg|gif|png|svg|webp))/
278 const videoRegex = new RegExp(`(http)?s?:?(\/\/[^"']*\.(?:mp4))`);
280 export function isImage(url: string) {
281 return imageRegex.test(url);
284 export function isVideo(url: string) {
285 return videoRegex.test(url);
288 export function validURL(str: string) {
289 return !!new URL(str);
292 export function communityRSSUrl(actorId: string, sort: string): string {
293 let url = new URL(actorId);
294 return `${url.origin}/feeds${url.pathname}.xml?sort=${sort}`;
297 export function validEmail(email: string) {
299 /^(([^\s"(),.:;<>@[\\\]]+(\.[^\s"(),.:;<>@[\\\]]+)*)|(".+"))@((\[(?:\d{1,3}\.){3}\d{1,3}])|(([\dA-Za-z\-]+\.)+[A-Za-z]{2,}))$/;
300 return re.test(String(email).toLowerCase());
303 export function capitalizeFirstLetter(str: string): string {
304 return str.charAt(0).toUpperCase() + str.slice(1);
307 export function routeSortTypeToEnum(sort: string): SortType {
308 return SortType[sort];
311 export function listingTypeFromNum(type_: number): ListingType {
312 return Object.values(ListingType)[type_];
315 export function sortTypeFromNum(type_: number): SortType {
316 return Object.values(SortType)[type_];
319 export function routeListingTypeToEnum(type: string): ListingType {
320 return ListingType[type];
323 export function routeDataTypeToEnum(type: string): DataType {
324 return DataType[capitalizeFirstLetter(type)];
327 export function routeSearchTypeToEnum(type: string): SearchType {
328 return SearchType[type];
331 export async function getPageTitle(url: string) {
332 let res = await fetch(`/iframely/oembed?url=${url}`).then(res => res.json());
333 let title = await res.title;
337 export function debounce(func: any, wait = 1000, immediate = false) {
338 // 'private' variable for instance
339 // The returned function will be able to reference this due to closure.
340 // Each call to the returned function will share this common timer.
343 // Calling debounce returns a new anonymous function
345 // reference the context and args for the setTimeout function
346 var args = arguments;
348 // Should the function be called now? If immediate is true
349 // and not already in a timeout then the answer is: Yes
350 var callNow = immediate && !timeout;
352 // This is the basic debounce behaviour where you can call this
353 // function several times, but it will only execute once
354 // [before or after imposing a delay].
355 // Each time the returned function is called, the timer starts over.
356 clearTimeout(timeout);
358 // Set the new timeout
359 timeout = setTimeout(function () {
360 // Inside the timeout function, clear the timeout variable
361 // which will let the next execution run when in 'immediate' mode
364 // Check if the function already ran with the immediate flag
366 // Call the original function with apply
367 // apply lets you define the 'this' object as well as the arguments
368 // (both captured before setTimeout)
369 func.apply(this, args);
373 // Immediate mode and no wait timer? Execute the function..
374 if (callNow) func.apply(this, args);
379 export function getLanguage(override?: string): string {
380 let localUserView = UserService.Instance.localUserView;
383 (localUserView?.local_user.lang
384 ? localUserView.local_user.lang
387 if (lang == "browser" && isBrowser()) {
388 return getBrowserLanguage();
394 export function getBrowserLanguage(): string {
395 return navigator.language;
398 export function getMomentLanguage(): string {
399 let lang = getLanguage();
400 if (lang.startsWith("zh")) {
402 } else if (lang.startsWith("sv")) {
404 } else if (lang.startsWith("fr")) {
406 } else if (lang.startsWith("de")) {
408 } else if (lang.startsWith("ru")) {
410 } else if (lang.startsWith("es")) {
412 } else if (lang.startsWith("eo")) {
414 } else if (lang.startsWith("nl")) {
416 } else if (lang.startsWith("it")) {
418 } else if (lang.startsWith("fi")) {
420 } else if (lang.startsWith("ca")) {
422 } else if (lang.startsWith("fa")) {
424 } else if (lang.startsWith("pl")) {
426 } else if (lang.startsWith("pt")) {
428 } else if (lang.startsWith("ja")) {
430 } else if (lang.startsWith("ka")) {
432 } else if (lang.startsWith("hi")) {
434 } else if (lang.startsWith("el")) {
436 } else if (lang.startsWith("eu")) {
438 } else if (lang.startsWith("gl")) {
440 } else if (lang.startsWith("tr")) {
442 } else if (lang.startsWith("hu")) {
444 } else if (lang.startsWith("uk")) {
446 } else if (lang.startsWith("sq")) {
448 } else if (lang.startsWith("km")) {
450 } else if (lang.startsWith("ga")) {
452 } else if (lang.startsWith("sr")) {
454 } else if (lang.startsWith("ko")) {
456 } else if (lang.startsWith("da")) {
458 } else if (lang.startsWith("oc")) {
460 } else if (lang.startsWith("hr")) {
462 } else if (lang.startsWith("th")) {
464 } else if (lang.startsWith("bg")) {
466 } else if (lang.startsWith("id")) {
468 } else if (lang.startsWith("nb")) {
476 export function setTheme(theme: string, forceReload = false) {
480 if (theme === "browser" && !forceReload) {
483 // This is only run on a force reload
484 if (theme == "browser") {
488 // Unload all the other themes
489 for (var i = 0; i < themes.length; i++) {
490 let styleSheet = document.getElementById(themes[i]);
492 styleSheet.setAttribute("disabled", "disabled");
497 .getElementById("default-light")
498 ?.setAttribute("disabled", "disabled");
499 document.getElementById("default-dark")?.setAttribute("disabled", "disabled");
501 // Load the theme dynamically
502 let cssLoc = `/static/assets/css/themes/${theme}.min.css`;
503 loadCss(theme, cssLoc);
504 document.getElementById(theme).removeAttribute("disabled");
507 export function loadCss(id: string, loc: string) {
508 if (!document.getElementById(id)) {
509 var head = document.getElementsByTagName("head")[0];
510 var link = document.createElement("link");
512 link.rel = "stylesheet";
513 link.type = "text/css";
516 head.appendChild(link);
520 export function objectFlip(obj: any) {
522 Object.keys(obj).forEach(key => {
528 export function showAvatars(): boolean {
530 UserService.Instance.localUserView?.local_user.show_avatars ||
531 !UserService.Instance.localUserView
535 export function showScores(): boolean {
537 UserService.Instance.localUserView?.local_user.show_scores ||
538 !UserService.Instance.localUserView
542 export function isCakeDay(published: string): boolean {
543 // moment(undefined) or moment.utc(undefined) returns the current date/time
544 // moment(null) or moment.utc(null) returns null
545 const createDate = moment.utc(published || null).local();
546 const currentDate = moment(new Date());
549 createDate.date() === currentDate.date() &&
550 createDate.month() === currentDate.month() &&
551 createDate.year() !== currentDate.year()
555 export function toast(text: string, background = "success") {
557 let backgroundColor = `var(--${background})`;
560 backgroundColor: backgroundColor,
567 export function pictrsDeleteToast(
568 clickToDeleteText: string,
569 deletePictureText: string,
573 let backgroundColor = `var(--light)`;
574 let toast = Toastify({
575 text: clickToDeleteText,
576 backgroundColor: backgroundColor,
582 window.location.replace(deleteUrl);
583 alert(deletePictureText);
592 interface NotifyInfo {
599 export function messageToastify(info: NotifyInfo, router: any) {
601 let htmlBody = info.body ? md.render(info.body) : "";
602 let backgroundColor = `var(--light)`;
604 let toast = Toastify({
605 text: `${htmlBody}<br />${info.name}`,
606 avatar: info.icon ? info.icon : null,
607 backgroundColor: backgroundColor,
608 className: "text-dark",
617 router.history.push(info.link);
624 export function notifyPost(post_view: PostView, router: any) {
625 let info: NotifyInfo = {
626 name: post_view.community.name,
627 icon: post_view.community.icon,
628 link: `/post/${post_view.post.id}`,
629 body: post_view.post.name,
631 notify(info, router);
634 export function notifyComment(comment_view: CommentView, router: any) {
635 let info: NotifyInfo = {
636 name: comment_view.creator.name,
637 icon: comment_view.creator.avatar,
638 link: `/post/${comment_view.post.id}/comment/${comment_view.comment.id}`,
639 body: comment_view.comment.content,
641 notify(info, router);
644 export function notifyPrivateMessage(pmv: PrivateMessageView, router: any) {
645 let info: NotifyInfo = {
646 name: pmv.creator.name,
647 icon: pmv.creator.avatar,
649 body: pmv.private_message.content,
651 notify(info, router);
654 function notify(info: NotifyInfo, router: any) {
655 messageToastify(info, router);
657 if (Notification.permission !== "granted") Notification.requestPermission();
659 var notification = new Notification(info.name, {
664 notification.onclick = (ev: Event): any => {
666 router.history.push(info.link);
671 export function setupTribute() {
673 noMatchTemplate: function () {
680 menuItemTemplate: (item: any) => {
681 let shortName = `:${item.original.key}:`;
682 return `${item.original.val} ${shortName}`;
684 selectTemplate: (item: any) => {
685 return `${item.original.val}`;
687 values: Object.entries(emojiShortName).map(e => {
688 return { key: e[1], val: e[0] };
691 autocompleteMode: true,
693 // menuItemLimit: mentionDropdownFetchLimit,
694 menuShowMinLength: 2,
699 selectTemplate: (item: any) => {
700 let it: PersonTribute = item.original;
701 return `[${it.key}](${it.view.person.actor_id})`;
703 values: (text: string, cb: (persons: PersonTribute[]) => any) => {
704 personSearch(text, (persons: PersonTribute[]) => cb(persons));
707 autocompleteMode: true,
709 // menuItemLimit: mentionDropdownFetchLimit,
710 menuShowMinLength: 2,
716 selectTemplate: (item: any) => {
717 let it: CommunityTribute = item.original;
718 return `[${it.key}](${it.view.community.actor_id})`;
720 values: (text: string, cb: any) => {
721 communitySearch(text, (communities: CommunityTribute[]) =>
726 autocompleteMode: true,
728 // menuItemLimit: mentionDropdownFetchLimit,
729 menuShowMinLength: 2,
735 var tippyInstance: any;
737 tippyInstance = tippy("[data-tippy-content]");
740 export function setupTippy() {
742 tippyInstance.forEach((e: any) => e.destroy());
743 tippyInstance = tippy("[data-tippy-content]", {
745 // Display on "long press"
746 touch: ["hold", 500],
751 interface PersonTribute {
753 view: PersonViewSafe;
756 function personSearch(text: string, cb: (persons: PersonTribute[]) => any) {
760 type_: SearchType.Users,
761 sort: SortType.TopAll,
762 listing_type: ListingType.All,
764 limit: mentionDropdownFetchLimit,
765 auth: authField(false),
768 WebSocketService.Instance.send(wsClient.search(form));
770 let personSub = WebSocketService.Instance.subject.subscribe(
772 let res = wsJsonToRes(msg);
773 if (res.op == UserOperation.Search) {
774 let data = res.data as SearchResponse;
775 let persons: PersonTribute[] = data.users.map(pv => {
776 let tribute: PersonTribute = {
777 key: `@${pv.person.name}@${hostname(pv.person.actor_id)}`,
783 personSub.unsubscribe();
786 err => console.error(err),
787 () => console.log("complete")
794 interface CommunityTribute {
799 function communitySearch(
801 cb: (communities: CommunityTribute[]) => any
806 type_: SearchType.Communities,
807 sort: SortType.TopAll,
808 listing_type: ListingType.All,
810 limit: mentionDropdownFetchLimit,
811 auth: authField(false),
814 WebSocketService.Instance.send(wsClient.search(form));
816 let communitySub = WebSocketService.Instance.subject.subscribe(
818 let res = wsJsonToRes(msg);
819 if (res.op == UserOperation.Search) {
820 let data = res.data as SearchResponse;
821 let communities: CommunityTribute[] = data.communities.map(cv => {
822 let tribute: CommunityTribute = {
823 key: `!${cv.community.name}@${hostname(cv.community.actor_id)}`,
829 communitySub.unsubscribe();
832 err => console.error(err),
833 () => console.log("complete")
840 export function getListingTypeFromProps(props: any): ListingType {
841 return props.match.params.listing_type
842 ? routeListingTypeToEnum(props.match.params.listing_type)
843 : UserService.Instance.localUserView
844 ? Object.values(ListingType)[
845 UserService.Instance.localUserView.local_user.default_listing_type
850 // TODO might need to add a user setting for this too
851 export function getDataTypeFromProps(props: any): DataType {
852 return props.match.params.data_type
853 ? routeDataTypeToEnum(props.match.params.data_type)
857 export function getSortTypeFromProps(props: any): SortType {
858 return props.match.params.sort
859 ? routeSortTypeToEnum(props.match.params.sort)
860 : UserService.Instance.localUserView
861 ? Object.values(SortType)[
862 UserService.Instance.localUserView.local_user.default_sort_type
867 export function getPageFromProps(props: any): number {
868 return props.match.params.page ? Number(props.match.params.page) : 1;
871 export function getRecipientIdFromProps(props: any): number {
872 return props.match.params.recipient_id
873 ? Number(props.match.params.recipient_id)
877 export function getIdFromProps(props: any): number {
878 return Number(props.match.params.id);
881 export function getCommentIdFromProps(props: any): number {
882 return Number(props.match.params.comment_id);
885 export function getUsernameFromProps(props: any): string {
886 return props.match.params.username;
889 export function editCommentRes(data: CommentView, comments: CommentView[]) {
890 let found = comments.find(c => c.comment.id == data.comment.id);
892 found.comment.content = data.comment.content;
893 found.comment.updated = data.comment.updated;
894 found.comment.removed = data.comment.removed;
895 found.comment.deleted = data.comment.deleted;
896 found.counts.upvotes = data.counts.upvotes;
897 found.counts.downvotes = data.counts.downvotes;
898 found.counts.score = data.counts.score;
902 export function saveCommentRes(data: CommentView, comments: CommentView[]) {
903 let found = comments.find(c => c.comment.id == data.comment.id);
905 found.saved = data.saved;
909 export function createCommentLikeRes(
911 comments: CommentView[]
913 let found = comments.find(c => c.comment.id === data.comment.id);
915 found.counts.score = data.counts.score;
916 found.counts.upvotes = data.counts.upvotes;
917 found.counts.downvotes = data.counts.downvotes;
918 if (data.my_vote !== null) {
919 found.my_vote = data.my_vote;
924 export function createPostLikeFindRes(data: PostView, posts: PostView[]) {
925 let found = posts.find(p => p.post.id == data.post.id);
927 createPostLikeRes(data, found);
931 export function createPostLikeRes(data: PostView, post_view: PostView) {
933 post_view.counts.score = data.counts.score;
934 post_view.counts.upvotes = data.counts.upvotes;
935 post_view.counts.downvotes = data.counts.downvotes;
936 if (data.my_vote !== null) {
937 post_view.my_vote = data.my_vote;
942 export function editPostFindRes(data: PostView, posts: PostView[]) {
943 let found = posts.find(p => p.post.id == data.post.id);
945 editPostRes(data, found);
949 export function editPostRes(data: PostView, post: PostView) {
951 post.post.url = data.post.url;
952 post.post.name = data.post.name;
953 post.post.nsfw = data.post.nsfw;
954 post.post.deleted = data.post.deleted;
955 post.post.removed = data.post.removed;
956 post.post.stickied = data.post.stickied;
957 post.post.body = data.post.body;
958 post.post.locked = data.post.locked;
959 post.saved = data.saved;
963 export function commentsToFlatNodes(comments: CommentView[]): CommentNodeI[] {
964 let nodes: CommentNodeI[] = [];
965 for (let comment of comments) {
966 nodes.push({ comment_view: comment });
971 function commentSort(tree: CommentNodeI[], sort: CommentSortType) {
972 // First, put removed and deleted comments at the bottom, then do your other sorts
973 if (sort == CommentSortType.Top) {
976 +a.comment_view.comment.removed - +b.comment_view.comment.removed ||
977 +a.comment_view.comment.deleted - +b.comment_view.comment.deleted ||
978 b.comment_view.counts.score - a.comment_view.counts.score
980 } else if (sort == CommentSortType.New) {
983 +a.comment_view.comment.removed - +b.comment_view.comment.removed ||
984 +a.comment_view.comment.deleted - +b.comment_view.comment.deleted ||
985 b.comment_view.comment.published.localeCompare(
986 a.comment_view.comment.published
989 } else if (sort == CommentSortType.Old) {
992 +a.comment_view.comment.removed - +b.comment_view.comment.removed ||
993 +a.comment_view.comment.deleted - +b.comment_view.comment.deleted ||
994 a.comment_view.comment.published.localeCompare(
995 b.comment_view.comment.published
998 } else if (sort == CommentSortType.Hot) {
1001 +a.comment_view.comment.removed - +b.comment_view.comment.removed ||
1002 +a.comment_view.comment.deleted - +b.comment_view.comment.deleted ||
1003 hotRankComment(b.comment_view) - hotRankComment(a.comment_view)
1007 // Go through the children recursively
1008 for (let node of tree) {
1009 if (node.children) {
1010 commentSort(node.children, sort);
1015 export function commentSortSortType(tree: CommentNodeI[], sort: SortType) {
1016 commentSort(tree, convertCommentSortType(sort));
1019 function convertCommentSortType(sort: SortType): CommentSortType {
1021 sort == SortType.TopAll ||
1022 sort == SortType.TopDay ||
1023 sort == SortType.TopWeek ||
1024 sort == SortType.TopMonth ||
1025 sort == SortType.TopYear
1027 return CommentSortType.Top;
1028 } else if (sort == SortType.New) {
1029 return CommentSortType.New;
1030 } else if (sort == SortType.Hot || sort == SortType.Active) {
1031 return CommentSortType.Hot;
1033 return CommentSortType.Hot;
1037 export function buildCommentsTree(
1038 comments: CommentView[],
1039 commentSortType: CommentSortType
1041 let map = new Map<number, CommentNodeI>();
1042 for (let comment_view of comments) {
1043 let node: CommentNodeI = {
1044 comment_view: comment_view,
1047 map.set(comment_view.comment.id, { ...node });
1049 let tree: CommentNodeI[] = [];
1050 for (let comment_view of comments) {
1051 let child = map.get(comment_view.comment.id);
1052 if (comment_view.comment.parent_id) {
1053 let parent_ = map.get(comment_view.comment.parent_id);
1054 parent_.children.push(child);
1062 commentSort(tree, commentSortType);
1067 function setDepth(node: CommentNodeI, i = 0) {
1068 for (let child of node.children) {
1070 setDepth(child, i + 1);
1074 export function insertCommentIntoTree(tree: CommentNodeI[], cv: CommentView) {
1075 // Building a fake node to be used for later
1076 let node: CommentNodeI = {
1082 if (cv.comment.parent_id) {
1083 let parentComment = searchCommentTree(tree, cv.comment.parent_id);
1084 if (parentComment) {
1085 node.depth = parentComment.depth + 1;
1086 parentComment.children.unshift(node);
1093 export function searchCommentTree(
1094 tree: CommentNodeI[],
1097 for (let node of tree) {
1098 if (node.comment_view.comment.id === id) {
1102 for (const child of node.children) {
1103 const res = searchCommentTree([child], id);
1113 export const colorList: string[] = [
1122 function hsl(num: number) {
1123 return `hsla(${num}, 35%, 50%, 1)`;
1126 export function previewLines(
1135 // Use lines * 2 because markdown requires 2 lines
1136 .slice(0, maxLines * 2)
1141 export function hostname(url: string): string {
1142 let cUrl = new URL(url);
1143 return cUrl.port ? `${cUrl.hostname}:${cUrl.port}` : `${cUrl.hostname}`;
1146 export function validTitle(title?: string): boolean {
1147 // Initial title is null, minimum length is taken care of by textarea's minLength={3}
1148 if (title === null || title.length < 3) return true;
1150 const regex = new RegExp(/.*\S.*/, "g");
1152 return regex.test(title);
1155 export function siteBannerCss(banner: string): string {
1157 background-image: linear-gradient( rgba(0, 0, 0, 0.8), rgba(0, 0, 0, 0.8) ) ,url("${banner}"); \
1158 background-attachment: fixed; \
1159 background-position: top; \
1160 background-repeat: no-repeat; \
1161 background-size: 100% cover; \
1164 max-height: 100vh; \
1168 export function isBrowser() {
1169 return typeof window !== "undefined";
1172 export function setIsoData(context: any): IsoData {
1173 let isoData: IsoData = isBrowser()
1175 : context.router.staticContext;
1179 export function wsSubscribe(parseMessage: any): Subscription {
1181 return WebSocketService.Instance.subject
1182 .pipe(retryWhen(errors => errors.pipe(delay(3000), take(10))))
1184 msg => parseMessage(msg),
1185 err => console.error(err),
1186 () => console.log("complete")
1193 export function setOptionalAuth(obj: any, auth = UserService.Instance.auth) {
1199 export function authField(
1201 auth = UserService.Instance.auth
1203 if (auth == null && throwErr) {
1204 toast(i18n.t("not_logged_in"), "danger");
1205 throw "Not logged in";
1211 moment.updateLocale("en", {
1232 export function saveScrollPosition(context: any) {
1233 let path: string = context.router.route.location.pathname;
1234 let y = window.scrollY;
1235 sessionStorage.setItem(`scrollPosition_${path}`, y.toString());
1238 export function restoreScrollPosition(context: any) {
1239 let path: string = context.router.route.location.pathname;
1240 let y = Number(sessionStorage.getItem(`scrollPosition_${path}`));
1241 window.scrollTo(0, y);
1244 export function showLocal(isoData: IsoData): boolean {
1245 return isoData.site_res.federated_instances?.linked.length > 0;
1248 interface ChoicesValue {
1253 export function communityToChoice(cv: CommunityView): ChoicesValue {
1254 let choice: ChoicesValue = {
1255 value: cv.community.id.toString(),
1256 label: communitySelectName(cv),
1261 export function personToChoice(pvs: PersonViewSafe): ChoicesValue {
1262 let choice: ChoicesValue = {
1263 value: pvs.person.id.toString(),
1264 label: personSelectName(pvs),
1269 export async function fetchCommunities(q: string) {
1270 let form: Search = {
1272 type_: SearchType.Communities,
1273 sort: SortType.TopAll,
1274 listing_type: ListingType.All,
1277 auth: authField(false),
1279 let client = new LemmyHttp(httpBase);
1280 return client.search(form);
1283 export async function fetchUsers(q: string) {
1284 let form: Search = {
1286 type_: SearchType.Users,
1287 sort: SortType.TopAll,
1288 listing_type: ListingType.All,
1291 auth: authField(false),
1293 let client = new LemmyHttp(httpBase);
1294 return client.search(form);
1297 export const choicesConfig = {
1299 searchResultLimit: fetchLimit,
1301 containerOuter: "choices",
1302 containerInner: "choices__inner bg-light border-0",
1303 input: "form-control",
1304 inputCloned: "choices__input--cloned",
1305 list: "choices__list",
1306 listItems: "choices__list--multiple",
1307 listSingle: "choices__list--single",
1308 listDropdown: "choices__list--dropdown",
1309 item: "choices__item bg-light",
1310 itemSelectable: "choices__item--selectable",
1311 itemDisabled: "choices__item--disabled",
1312 itemChoice: "choices__item--choice",
1313 placeholder: "choices__placeholder",
1314 group: "choices__group",
1315 groupHeading: "choices__heading",
1316 button: "choices__button",
1317 activeState: "is-active",
1318 focusState: "is-focused",
1319 openState: "is-open",
1320 disabledState: "is-disabled",
1321 highlightedState: "text-info",
1322 selectedState: "text-info",
1323 flippedState: "is-flipped",
1324 loadingState: "is-loading",
1325 noResults: "has-no-results",
1326 noChoices: "has-no-choices",
1330 export function communitySelectName(cv: CommunityView): string {
1331 return cv.community.local
1333 : `${hostname(cv.community.actor_id)}/${cv.community.name}`;
1336 export function personSelectName(pvs: PersonViewSafe): string {
1337 return pvs.person.local
1339 : `${hostname(pvs.person.actor_id)}/${pvs.person.name}`;