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";
36 LocalUserSettingsView,
41 WebSocketJsonResponse,
50 } from "lemmy-js-client";
56 CommentNode as CommentNodeI,
57 } from "./interfaces";
58 import { UserService, WebSocketService } from "./services";
61 Tribute = require("tributejs");
63 import markdown_it from "markdown-it";
64 import markdown_it_sub from "markdown-it-sub";
65 import markdown_it_sup from "markdown-it-sup";
66 import markdown_it_container from "markdown-it-container";
67 import emojiShortName from "emoji-short-name";
68 import Toastify from "toastify-js";
69 import tippy from "tippy.js";
70 import moment from "moment";
71 import { Subscription } from "rxjs";
72 import { retryWhen, delay, take } from "rxjs/operators";
73 import { i18n } from "./i18next";
74 import { httpBase } from "./env";
76 export const wsClient = new LemmyWebsocket();
78 export const favIconUrl = "/static/assets/icons/favicon.svg";
79 export const favIconPngUrl = "/static/assets/icons/apple-touch-icon.png";
81 // export const defaultFavIcon = `${window.location.protocol}//${window.location.host}${favIconPngUrl}`;
82 export const repoUrl = "https://github.com/LemmyNet";
83 export const joinLemmyUrl = "https://join-lemmy.org";
84 export const supportLemmyUrl = `${joinLemmyUrl}/support`;
85 export const docsUrl = `${joinLemmyUrl}/docs/en/index.html`;
86 export const helpGuideUrl = `${joinLemmyUrl}/docs/en/about/guide.html`; // TODO find a way to redirect to the non-en folder
87 export const markdownHelpUrl = `${helpGuideUrl}#markdown-guide`;
88 export const sortingHelpUrl = `${helpGuideUrl}#sorting`;
89 export const archiveUrl = "https://archive.is";
90 export const elementUrl = "https://element.io/";
92 export const postRefetchSeconds: number = 60 * 1000;
93 export const fetchLimit = 20;
94 export const mentionDropdownFetchLimit = 10;
96 export const languages = [
133 export const themes = [
149 const DEFAULT_ALPHABET =
150 "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
152 function getRandomCharFromAlphabet(alphabet: string): string {
153 return alphabet.charAt(Math.floor(Math.random() * alphabet.length));
156 export function randomStr(
157 idDesiredLength = 20,
158 alphabet = DEFAULT_ALPHABET
161 * Create n-long array and map it to random chars from given alphabet.
162 * Then join individual chars as string
164 return Array.from({ length: idDesiredLength })
166 return getRandomCharFromAlphabet(alphabet);
171 export function wsJsonToRes<ResponseType>(
172 msg: WebSocketJsonResponse<ResponseType>
173 ): WebSocketResponse<ResponseType> {
180 export function wsUserOp(msg: any): UserOperation {
181 let opStr: string = msg.op;
182 return UserOperation[opStr];
185 export const md = new markdown_it({
190 .use(markdown_it_sub)
191 .use(markdown_it_sup)
192 .use(markdown_it_container, "spoiler", {
193 validate: function (params: any) {
194 return params.trim().match(/^spoiler\s+(.*)$/);
197 render: function (tokens: any, idx: any) {
198 var m = tokens[idx].info.trim().match(/^spoiler\s+(.*)$/);
200 if (tokens[idx].nesting === 1) {
202 return `<details><summary> ${md.utils.escapeHtml(m[1])} </summary>\n`;
205 return "</details>\n";
210 export function hotRankComment(comment_view: CommentView): number {
211 return hotRank(comment_view.counts.score, comment_view.comment.published);
214 export function hotRankActivePost(post_view: PostView): number {
215 return hotRank(post_view.counts.score, post_view.counts.newest_comment_time);
218 export function hotRankPost(post_view: PostView): number {
219 return hotRank(post_view.counts.score, post_view.post.published);
222 export function hotRank(score: number, timeStr: string): number {
223 // Rank = ScaleFactor * sign(Score) * log(1 + abs(Score)) / (Time + 2)^Gravity
224 let date: Date = new Date(timeStr + "Z"); // Add Z to convert from UTC date
225 let now: Date = new Date();
226 let hoursElapsed: number = (now.getTime() - date.getTime()) / 36e5;
229 (10000 * Math.log10(Math.max(1, 3 + score))) /
230 Math.pow(hoursElapsed + 2, 1.8);
232 // console.log(`Comment: ${comment.content}\nRank: ${rank}\nScore: ${comment.score}\nHours: ${hoursElapsed}`);
237 export function mdToHtml(text: string) {
238 return { __html: md.render(text) };
241 export function getUnixTime(text: string): number {
242 return text ? new Date(text).getTime() / 1000 : undefined;
245 export function canMod(
246 localUserView: LocalUserSettingsView,
251 // You can do moderator actions only on the mods added after you.
253 let yourIndex = modIds.findIndex(id => id == localUserView.person.id);
254 if (yourIndex == -1) {
257 // onSelf +1 on mod actions not for yourself, IE ban, remove, etc
258 modIds = modIds.slice(0, yourIndex + (onSelf ? 0 : 1));
259 return !modIds.includes(creator_id);
266 export function isMod(modIds: number[], creator_id: number): boolean {
267 return modIds.includes(creator_id);
270 const imageRegex = new RegExp(
271 /(http)?s?:?(\/\/[^"']*\.(?:jpg|jpeg|gif|png|svg|webp))/
273 const videoRegex = new RegExp(`(http)?s?:?(\/\/[^"']*\.(?:mp4))`);
275 export function isImage(url: string) {
276 return imageRegex.test(url);
279 export function isVideo(url: string) {
280 return videoRegex.test(url);
283 export function validURL(str: string) {
284 return !!new URL(str);
287 export function communityRSSUrl(actorId: string, sort: string): string {
288 let url = new URL(actorId);
289 return `${url.origin}/feeds${url.pathname}.xml?sort=${sort}`;
292 export function validEmail(email: string) {
294 /^(([^\s"(),.:;<>@[\\\]]+(\.[^\s"(),.:;<>@[\\\]]+)*)|(".+"))@((\[(?:\d{1,3}\.){3}\d{1,3}])|(([\dA-Za-z\-]+\.)+[A-Za-z]{2,}))$/;
295 return re.test(String(email).toLowerCase());
298 export function capitalizeFirstLetter(str: string): string {
299 return str.charAt(0).toUpperCase() + str.slice(1);
302 export function routeSortTypeToEnum(sort: string): SortType {
303 return SortType[sort];
306 export function listingTypeFromNum(type_: number): ListingType {
307 return Object.values(ListingType)[type_];
310 export function sortTypeFromNum(type_: number): SortType {
311 return Object.values(SortType)[type_];
314 export function routeListingTypeToEnum(type: string): ListingType {
315 return ListingType[type];
318 export function routeDataTypeToEnum(type: string): DataType {
319 return DataType[capitalizeFirstLetter(type)];
322 export function routeSearchTypeToEnum(type: string): SearchType {
323 return SearchType[type];
326 export async function getPageTitle(url: string) {
327 let res = await fetch(`/iframely/oembed?url=${url}`).then(res => res.json());
328 let title = await res.title;
332 export function debounce(func: any, wait = 1000, immediate = false) {
333 // 'private' variable for instance
334 // The returned function will be able to reference this due to closure.
335 // Each call to the returned function will share this common timer.
338 // Calling debounce returns a new anonymous function
340 // reference the context and args for the setTimeout function
341 var args = arguments;
343 // Should the function be called now? If immediate is true
344 // and not already in a timeout then the answer is: Yes
345 var callNow = immediate && !timeout;
347 // This is the basic debounce behaviour where you can call this
348 // function several times, but it will only execute once
349 // [before or after imposing a delay].
350 // Each time the returned function is called, the timer starts over.
351 clearTimeout(timeout);
353 // Set the new timeout
354 timeout = setTimeout(function () {
355 // Inside the timeout function, clear the timeout variable
356 // which will let the next execution run when in 'immediate' mode
359 // Check if the function already ran with the immediate flag
361 // Call the original function with apply
362 // apply lets you define the 'this' object as well as the arguments
363 // (both captured before setTimeout)
364 func.apply(this, args);
368 // Immediate mode and no wait timer? Execute the function..
369 if (callNow) func.apply(this, args);
374 export function getLanguage(override?: string): string {
375 let localUserView = UserService.Instance.localUserView;
378 (localUserView?.local_user.lang
379 ? localUserView.local_user.lang
382 if (lang == "browser" && isBrowser()) {
383 return getBrowserLanguage();
389 export function getBrowserLanguage(): string {
390 return navigator.language;
393 export function getMomentLanguage(): string {
394 let lang = getLanguage();
395 if (lang.startsWith("zh")) {
397 } else if (lang.startsWith("sv")) {
399 } else if (lang.startsWith("fr")) {
401 } else if (lang.startsWith("de")) {
403 } else if (lang.startsWith("ru")) {
405 } else if (lang.startsWith("es")) {
407 } else if (lang.startsWith("eo")) {
409 } else if (lang.startsWith("nl")) {
411 } else if (lang.startsWith("it")) {
413 } else if (lang.startsWith("fi")) {
415 } else if (lang.startsWith("ca")) {
417 } else if (lang.startsWith("fa")) {
419 } else if (lang.startsWith("pl")) {
421 } else if (lang.startsWith("pt")) {
423 } else if (lang.startsWith("ja")) {
425 } else if (lang.startsWith("ka")) {
427 } else if (lang.startsWith("hi")) {
429 } else if (lang.startsWith("el")) {
431 } else if (lang.startsWith("eu")) {
433 } else if (lang.startsWith("gl")) {
435 } else if (lang.startsWith("tr")) {
437 } else if (lang.startsWith("hu")) {
439 } else if (lang.startsWith("uk")) {
441 } else if (lang.startsWith("sq")) {
443 } else if (lang.startsWith("km")) {
445 } else if (lang.startsWith("ga")) {
447 } else if (lang.startsWith("sr")) {
449 } else if (lang.startsWith("ko")) {
451 } else if (lang.startsWith("da")) {
453 } else if (lang.startsWith("oc")) {
455 } else if (lang.startsWith("hr")) {
457 } else if (lang.startsWith("th")) {
459 } else if (lang.startsWith("bg")) {
467 export function setTheme(theme: string, forceReload = false) {
471 if (theme === "browser" && !forceReload) {
474 // This is only run on a force reload
475 if (theme == "browser") {
479 // Unload all the other themes
480 for (var i = 0; i < themes.length; i++) {
481 let styleSheet = document.getElementById(themes[i]);
483 styleSheet.setAttribute("disabled", "disabled");
488 .getElementById("default-light")
489 ?.setAttribute("disabled", "disabled");
490 document.getElementById("default-dark")?.setAttribute("disabled", "disabled");
492 // Load the theme dynamically
493 let cssLoc = `/static/assets/css/themes/${theme}.min.css`;
494 loadCss(theme, cssLoc);
495 document.getElementById(theme).removeAttribute("disabled");
498 export function loadCss(id: string, loc: string) {
499 if (!document.getElementById(id)) {
500 var head = document.getElementsByTagName("head")[0];
501 var link = document.createElement("link");
503 link.rel = "stylesheet";
504 link.type = "text/css";
507 head.appendChild(link);
511 export function objectFlip(obj: any) {
513 Object.keys(obj).forEach(key => {
519 export function showAvatars(): boolean {
521 UserService.Instance.localUserView?.local_user.show_avatars ||
522 !UserService.Instance.localUserView
526 export function showScores(): boolean {
528 UserService.Instance.localUserView?.local_user.show_scores ||
529 !UserService.Instance.localUserView
533 export function isCakeDay(published: string): boolean {
534 // moment(undefined) or moment.utc(undefined) returns the current date/time
535 // moment(null) or moment.utc(null) returns null
536 const createDate = moment.utc(published || null).local();
537 const currentDate = moment(new Date());
540 createDate.date() === currentDate.date() &&
541 createDate.month() === currentDate.month() &&
542 createDate.year() !== currentDate.year()
546 export function toast(text: string, background = "success") {
548 let backgroundColor = `var(--${background})`;
551 backgroundColor: backgroundColor,
558 export function pictrsDeleteToast(
559 clickToDeleteText: string,
560 deletePictureText: string,
564 let backgroundColor = `var(--light)`;
565 let toast = Toastify({
566 text: clickToDeleteText,
567 backgroundColor: backgroundColor,
573 window.location.replace(deleteUrl);
574 alert(deletePictureText);
583 interface NotifyInfo {
590 export function messageToastify(info: NotifyInfo, router: any) {
592 let htmlBody = info.body ? md.render(info.body) : "";
593 let backgroundColor = `var(--light)`;
595 let toast = Toastify({
596 text: `${htmlBody}<br />${info.name}`,
597 avatar: info.icon ? info.icon : null,
598 backgroundColor: backgroundColor,
599 className: "text-dark",
608 router.history.push(info.link);
615 export function notifyPost(post_view: PostView, router: any) {
616 let info: NotifyInfo = {
617 name: post_view.community.name,
618 icon: post_view.community.icon,
619 link: `/post/${post_view.post.id}`,
620 body: post_view.post.name,
622 notify(info, router);
625 export function notifyComment(comment_view: CommentView, router: any) {
626 let info: NotifyInfo = {
627 name: comment_view.creator.name,
628 icon: comment_view.creator.avatar,
629 link: `/post/${comment_view.post.id}/comment/${comment_view.comment.id}`,
630 body: comment_view.comment.content,
632 notify(info, router);
635 export function notifyPrivateMessage(pmv: PrivateMessageView, router: any) {
636 let info: NotifyInfo = {
637 name: pmv.creator.name,
638 icon: pmv.creator.avatar,
640 body: pmv.private_message.content,
642 notify(info, router);
645 function notify(info: NotifyInfo, router: any) {
646 messageToastify(info, router);
648 if (Notification.permission !== "granted") Notification.requestPermission();
650 var notification = new Notification(info.name, {
655 notification.onclick = (ev: Event): any => {
657 router.history.push(info.link);
662 export function setupTribute() {
664 noMatchTemplate: function () {
671 menuItemTemplate: (item: any) => {
672 let shortName = `:${item.original.key}:`;
673 return `${item.original.val} ${shortName}`;
675 selectTemplate: (item: any) => {
676 return `${item.original.val}`;
678 values: Object.entries(emojiShortName).map(e => {
679 return { key: e[1], val: e[0] };
682 autocompleteMode: true,
684 // menuItemLimit: mentionDropdownFetchLimit,
685 menuShowMinLength: 2,
690 selectTemplate: (item: any) => {
691 let it: PersonTribute = item.original;
692 return `[${it.key}](${it.view.person.actor_id})`;
694 values: (text: string, cb: (persons: PersonTribute[]) => any) => {
695 personSearch(text, (persons: PersonTribute[]) => cb(persons));
698 autocompleteMode: true,
700 // menuItemLimit: mentionDropdownFetchLimit,
701 menuShowMinLength: 2,
707 selectTemplate: (item: any) => {
708 let it: CommunityTribute = item.original;
709 return `[${it.key}](${it.view.community.actor_id})`;
711 values: (text: string, cb: any) => {
712 communitySearch(text, (communities: CommunityTribute[]) =>
717 autocompleteMode: true,
719 // menuItemLimit: mentionDropdownFetchLimit,
720 menuShowMinLength: 2,
726 var tippyInstance: any;
728 tippyInstance = tippy("[data-tippy-content]");
731 export function setupTippy() {
733 tippyInstance.forEach((e: any) => e.destroy());
734 tippyInstance = tippy("[data-tippy-content]", {
736 // Display on "long press"
737 touch: ["hold", 500],
742 interface PersonTribute {
744 view: PersonViewSafe;
747 function personSearch(text: string, cb: (persons: PersonTribute[]) => any) {
751 type_: SearchType.Users,
752 sort: SortType.TopAll,
753 listing_type: ListingType.All,
755 limit: mentionDropdownFetchLimit,
756 auth: authField(false),
759 WebSocketService.Instance.send(wsClient.search(form));
761 let personSub = WebSocketService.Instance.subject.subscribe(
763 let res = wsJsonToRes(msg);
764 if (res.op == UserOperation.Search) {
765 let data = res.data as SearchResponse;
766 let persons: PersonTribute[] = data.users.map(pv => {
767 let tribute: PersonTribute = {
768 key: `@${pv.person.name}@${hostname(pv.person.actor_id)}`,
774 personSub.unsubscribe();
777 err => console.error(err),
778 () => console.log("complete")
785 interface CommunityTribute {
790 function communitySearch(
792 cb: (communities: CommunityTribute[]) => any
797 type_: SearchType.Communities,
798 sort: SortType.TopAll,
799 listing_type: ListingType.All,
801 limit: mentionDropdownFetchLimit,
802 auth: authField(false),
805 WebSocketService.Instance.send(wsClient.search(form));
807 let communitySub = WebSocketService.Instance.subject.subscribe(
809 let res = wsJsonToRes(msg);
810 if (res.op == UserOperation.Search) {
811 let data = res.data as SearchResponse;
812 let communities: CommunityTribute[] = data.communities.map(cv => {
813 let tribute: CommunityTribute = {
814 key: `!${cv.community.name}@${hostname(cv.community.actor_id)}`,
820 communitySub.unsubscribe();
823 err => console.error(err),
824 () => console.log("complete")
831 export function getListingTypeFromProps(props: any): ListingType {
832 return props.match.params.listing_type
833 ? routeListingTypeToEnum(props.match.params.listing_type)
834 : UserService.Instance.localUserView
835 ? Object.values(ListingType)[
836 UserService.Instance.localUserView.local_user.default_listing_type
841 // TODO might need to add a user setting for this too
842 export function getDataTypeFromProps(props: any): DataType {
843 return props.match.params.data_type
844 ? routeDataTypeToEnum(props.match.params.data_type)
848 export function getSortTypeFromProps(props: any): SortType {
849 return props.match.params.sort
850 ? routeSortTypeToEnum(props.match.params.sort)
851 : UserService.Instance.localUserView
852 ? Object.values(SortType)[
853 UserService.Instance.localUserView.local_user.default_sort_type
858 export function getPageFromProps(props: any): number {
859 return props.match.params.page ? Number(props.match.params.page) : 1;
862 export function getRecipientIdFromProps(props: any): number {
863 return props.match.params.recipient_id
864 ? Number(props.match.params.recipient_id)
868 export function getIdFromProps(props: any): number {
869 return Number(props.match.params.id);
872 export function getCommentIdFromProps(props: any): number {
873 return Number(props.match.params.comment_id);
876 export function getUsernameFromProps(props: any): string {
877 return props.match.params.username;
880 export function editCommentRes(data: CommentView, comments: CommentView[]) {
881 let found = comments.find(c => c.comment.id == data.comment.id);
883 found.comment.content = data.comment.content;
884 found.comment.updated = data.comment.updated;
885 found.comment.removed = data.comment.removed;
886 found.comment.deleted = data.comment.deleted;
887 found.counts.upvotes = data.counts.upvotes;
888 found.counts.downvotes = data.counts.downvotes;
889 found.counts.score = data.counts.score;
893 export function saveCommentRes(data: CommentView, comments: CommentView[]) {
894 let found = comments.find(c => c.comment.id == data.comment.id);
896 found.saved = data.saved;
900 export function createCommentLikeRes(
902 comments: CommentView[]
904 let found = comments.find(c => c.comment.id === data.comment.id);
906 found.counts.score = data.counts.score;
907 found.counts.upvotes = data.counts.upvotes;
908 found.counts.downvotes = data.counts.downvotes;
909 if (data.my_vote !== null) {
910 found.my_vote = data.my_vote;
915 export function createPostLikeFindRes(data: PostView, posts: PostView[]) {
916 let found = posts.find(p => p.post.id == data.post.id);
918 createPostLikeRes(data, found);
922 export function createPostLikeRes(data: PostView, post_view: PostView) {
924 post_view.counts.score = data.counts.score;
925 post_view.counts.upvotes = data.counts.upvotes;
926 post_view.counts.downvotes = data.counts.downvotes;
927 if (data.my_vote !== null) {
928 post_view.my_vote = data.my_vote;
933 export function editPostFindRes(data: PostView, posts: PostView[]) {
934 let found = posts.find(p => p.post.id == data.post.id);
936 editPostRes(data, found);
940 export function editPostRes(data: PostView, post: PostView) {
942 post.post.url = data.post.url;
943 post.post.name = data.post.name;
944 post.post.nsfw = data.post.nsfw;
945 post.post.deleted = data.post.deleted;
946 post.post.removed = data.post.removed;
947 post.post.stickied = data.post.stickied;
948 post.post.body = data.post.body;
949 post.post.locked = data.post.locked;
950 post.saved = data.saved;
954 export function commentsToFlatNodes(comments: CommentView[]): CommentNodeI[] {
955 let nodes: CommentNodeI[] = [];
956 for (let comment of comments) {
957 nodes.push({ comment_view: comment });
962 function commentSort(tree: CommentNodeI[], sort: CommentSortType) {
963 // First, put removed and deleted comments at the bottom, then do your other sorts
964 if (sort == CommentSortType.Top) {
967 +a.comment_view.comment.removed - +b.comment_view.comment.removed ||
968 +a.comment_view.comment.deleted - +b.comment_view.comment.deleted ||
969 b.comment_view.counts.score - a.comment_view.counts.score
971 } else if (sort == CommentSortType.New) {
974 +a.comment_view.comment.removed - +b.comment_view.comment.removed ||
975 +a.comment_view.comment.deleted - +b.comment_view.comment.deleted ||
976 b.comment_view.comment.published.localeCompare(
977 a.comment_view.comment.published
980 } else if (sort == CommentSortType.Old) {
983 +a.comment_view.comment.removed - +b.comment_view.comment.removed ||
984 +a.comment_view.comment.deleted - +b.comment_view.comment.deleted ||
985 a.comment_view.comment.published.localeCompare(
986 b.comment_view.comment.published
989 } else if (sort == CommentSortType.Hot) {
992 +a.comment_view.comment.removed - +b.comment_view.comment.removed ||
993 +a.comment_view.comment.deleted - +b.comment_view.comment.deleted ||
994 hotRankComment(b.comment_view) - hotRankComment(a.comment_view)
998 // Go through the children recursively
999 for (let node of tree) {
1000 if (node.children) {
1001 commentSort(node.children, sort);
1006 export function commentSortSortType(tree: CommentNodeI[], sort: SortType) {
1007 commentSort(tree, convertCommentSortType(sort));
1010 function convertCommentSortType(sort: SortType): CommentSortType {
1012 sort == SortType.TopAll ||
1013 sort == SortType.TopDay ||
1014 sort == SortType.TopWeek ||
1015 sort == SortType.TopMonth ||
1016 sort == SortType.TopYear
1018 return CommentSortType.Top;
1019 } else if (sort == SortType.New) {
1020 return CommentSortType.New;
1021 } else if (sort == SortType.Hot || sort == SortType.Active) {
1022 return CommentSortType.Hot;
1024 return CommentSortType.Hot;
1028 export function buildCommentsTree(
1029 comments: CommentView[],
1030 commentSortType: CommentSortType
1032 let map = new Map<number, CommentNodeI>();
1033 for (let comment_view of comments) {
1034 let node: CommentNodeI = {
1035 comment_view: comment_view,
1038 map.set(comment_view.comment.id, { ...node });
1040 let tree: CommentNodeI[] = [];
1041 for (let comment_view of comments) {
1042 let child = map.get(comment_view.comment.id);
1043 if (comment_view.comment.parent_id) {
1044 let parent_ = map.get(comment_view.comment.parent_id);
1045 parent_.children.push(child);
1053 commentSort(tree, commentSortType);
1058 function setDepth(node: CommentNodeI, i = 0) {
1059 for (let child of node.children) {
1061 setDepth(child, i + 1);
1065 export function insertCommentIntoTree(tree: CommentNodeI[], cv: CommentView) {
1066 // Building a fake node to be used for later
1067 let node: CommentNodeI = {
1073 if (cv.comment.parent_id) {
1074 let parentComment = searchCommentTree(tree, cv.comment.parent_id);
1075 if (parentComment) {
1076 node.depth = parentComment.depth + 1;
1077 parentComment.children.unshift(node);
1084 export function searchCommentTree(
1085 tree: CommentNodeI[],
1088 for (let node of tree) {
1089 if (node.comment_view.comment.id === id) {
1093 for (const child of node.children) {
1094 const res = searchCommentTree([child], id);
1104 export const colorList: string[] = [
1113 function hsl(num: number) {
1114 return `hsla(${num}, 35%, 50%, 1)`;
1117 export function previewLines(
1126 // Use lines * 2 because markdown requires 2 lines
1127 .slice(0, maxLines * 2)
1132 export function hostname(url: string): string {
1133 let cUrl = new URL(url);
1134 return cUrl.port ? `${cUrl.hostname}:${cUrl.port}` : `${cUrl.hostname}`;
1137 export function validTitle(title?: string): boolean {
1138 // Initial title is null, minimum length is taken care of by textarea's minLength={3}
1139 if (title === null || title.length < 3) return true;
1141 const regex = new RegExp(/.*\S.*/, "g");
1143 return regex.test(title);
1146 export function siteBannerCss(banner: string): string {
1148 background-image: linear-gradient( rgba(0, 0, 0, 0.8), rgba(0, 0, 0, 0.8) ) ,url("${banner}"); \
1149 background-attachment: fixed; \
1150 background-position: top; \
1151 background-repeat: no-repeat; \
1152 background-size: 100% cover; \
1155 max-height: 100vh; \
1159 export function isBrowser() {
1160 return typeof window !== "undefined";
1163 export function setIsoData(context: any): IsoData {
1164 let isoData: IsoData = isBrowser()
1166 : context.router.staticContext;
1170 export function wsSubscribe(parseMessage: any): Subscription {
1172 return WebSocketService.Instance.subject
1173 .pipe(retryWhen(errors => errors.pipe(delay(3000), take(10))))
1175 msg => parseMessage(msg),
1176 err => console.error(err),
1177 () => console.log("complete")
1184 export function setOptionalAuth(obj: any, auth = UserService.Instance.auth) {
1190 export function authField(
1192 auth = UserService.Instance.auth
1194 if (auth == null && throwErr) {
1195 toast(i18n.t("not_logged_in"), "danger");
1196 throw "Not logged in";
1202 moment.updateLocale("en", {
1223 export function saveScrollPosition(context: any) {
1224 let path: string = context.router.route.location.pathname;
1225 let y = window.scrollY;
1226 sessionStorage.setItem(`scrollPosition_${path}`, y.toString());
1229 export function restoreScrollPosition(context: any) {
1230 let path: string = context.router.route.location.pathname;
1231 let y = Number(sessionStorage.getItem(`scrollPosition_${path}`));
1232 window.scrollTo(0, y);
1235 export function showLocal(isoData: IsoData): boolean {
1236 return isoData.site_res.federated_instances?.linked.length > 0;
1239 interface ChoicesValue {
1244 export function communityToChoice(cv: CommunityView): ChoicesValue {
1245 let choice: ChoicesValue = {
1246 value: cv.community.id.toString(),
1247 label: communitySelectName(cv),
1252 export function personToChoice(pvs: PersonViewSafe): ChoicesValue {
1253 let choice: ChoicesValue = {
1254 value: pvs.person.id.toString(),
1255 label: personSelectName(pvs),
1260 export async function fetchCommunities(q: string) {
1261 let form: Search = {
1263 type_: SearchType.Communities,
1264 sort: SortType.TopAll,
1265 listing_type: ListingType.All,
1268 auth: authField(false),
1270 let client = new LemmyHttp(httpBase);
1271 return client.search(form);
1274 export async function fetchUsers(q: string) {
1275 let form: Search = {
1277 type_: SearchType.Users,
1278 sort: SortType.TopAll,
1279 listing_type: ListingType.All,
1282 auth: authField(false),
1284 let client = new LemmyHttp(httpBase);
1285 return client.search(form);
1288 export const choicesConfig = {
1290 searchResultLimit: fetchLimit,
1292 containerOuter: "choices",
1293 containerInner: "choices__inner bg-light border-0",
1294 input: "form-control",
1295 inputCloned: "choices__input--cloned",
1296 list: "choices__list",
1297 listItems: "choices__list--multiple",
1298 listSingle: "choices__list--single",
1299 listDropdown: "choices__list--dropdown",
1300 item: "choices__item bg-light",
1301 itemSelectable: "choices__item--selectable",
1302 itemDisabled: "choices__item--disabled",
1303 itemChoice: "choices__item--choice",
1304 placeholder: "choices__placeholder",
1305 group: "choices__group",
1306 groupHeading: "choices__heading",
1307 button: "choices__button",
1308 activeState: "is-active",
1309 focusState: "is-focused",
1310 openState: "is-open",
1311 disabledState: "is-disabled",
1312 highlightedState: "text-info",
1313 selectedState: "text-info",
1314 flippedState: "is-flipped",
1315 loadingState: "is-loading",
1316 noResults: "has-no-results",
1317 noChoices: "has-no-choices",
1321 export function communitySelectName(cv: CommunityView): string {
1322 return cv.community.local
1324 : `${hostname(cv.community.actor_id)}/${cv.community.name}`;
1327 export function personSelectName(pvs: PersonViewSafe): string {
1328 return pvs.person.local
1330 : `${hostname(pvs.person.actor_id)}/${pvs.person.name}`;