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.ml";
84 export const supportLemmyUrl = "https://join.lemmy.ml/support";
85 export const docsUrl = "https://join.lemmy.ml/docs/en/index.html";
86 export const helpGuideUrl = "https://join.lemmy.ml/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) {
293 let re = /^(([^\s"(),.:;<>@[\\\]]+(\.[^\s"(),.:;<>@[\\\]]+)*)|(".+"))@((\[(?:\d{1,3}\.){3}\d{1,3}])|(([\dA-Za-z\-]+\.)+[A-Za-z]{2,}))$/;
294 return re.test(String(email).toLowerCase());
297 export function capitalizeFirstLetter(str: string): string {
298 return str.charAt(0).toUpperCase() + str.slice(1);
301 export function routeSortTypeToEnum(sort: string): SortType {
302 return SortType[sort];
305 export function listingTypeFromNum(type_: number): ListingType {
306 return Object.values(ListingType)[type_];
309 export function sortTypeFromNum(type_: number): SortType {
310 return Object.values(SortType)[type_];
313 export function routeListingTypeToEnum(type: string): ListingType {
314 return ListingType[type];
317 export function routeDataTypeToEnum(type: string): DataType {
318 return DataType[capitalizeFirstLetter(type)];
321 export function routeSearchTypeToEnum(type: string): SearchType {
322 return SearchType[type];
325 export async function getPageTitle(url: string) {
326 let res = await fetch(`/iframely/oembed?url=${url}`).then(res => res.json());
327 let title = await res.title;
331 export function debounce(func: any, wait = 1000, immediate = false) {
332 // 'private' variable for instance
333 // The returned function will be able to reference this due to closure.
334 // Each call to the returned function will share this common timer.
337 // Calling debounce returns a new anonymous function
339 // reference the context and args for the setTimeout function
340 var args = arguments;
342 // Should the function be called now? If immediate is true
343 // and not already in a timeout then the answer is: Yes
344 var callNow = immediate && !timeout;
346 // This is the basic debounce behaviour where you can call this
347 // function several times, but it will only execute once
348 // [before or after imposing a delay].
349 // Each time the returned function is called, the timer starts over.
350 clearTimeout(timeout);
352 // Set the new timeout
353 timeout = setTimeout(function () {
354 // Inside the timeout function, clear the timeout variable
355 // which will let the next execution run when in 'immediate' mode
358 // Check if the function already ran with the immediate flag
360 // Call the original function with apply
361 // apply lets you define the 'this' object as well as the arguments
362 // (both captured before setTimeout)
363 func.apply(this, args);
367 // Immediate mode and no wait timer? Execute the function..
368 if (callNow) func.apply(this, args);
373 export function getLanguage(override?: string): string {
374 let localUserView = UserService.Instance.localUserView;
377 (localUserView?.local_user.lang
378 ? localUserView.local_user.lang
381 if (lang == "browser" && isBrowser()) {
382 return getBrowserLanguage();
388 export function getBrowserLanguage(): string {
389 return navigator.language;
392 export function getMomentLanguage(): string {
393 let lang = getLanguage();
394 if (lang.startsWith("zh")) {
396 } else if (lang.startsWith("sv")) {
398 } else if (lang.startsWith("fr")) {
400 } else if (lang.startsWith("de")) {
402 } else if (lang.startsWith("ru")) {
404 } else if (lang.startsWith("es")) {
406 } else if (lang.startsWith("eo")) {
408 } else if (lang.startsWith("nl")) {
410 } else if (lang.startsWith("it")) {
412 } else if (lang.startsWith("fi")) {
414 } else if (lang.startsWith("ca")) {
416 } else if (lang.startsWith("fa")) {
418 } else if (lang.startsWith("pl")) {
420 } else if (lang.startsWith("pt")) {
422 } else if (lang.startsWith("ja")) {
424 } else if (lang.startsWith("ka")) {
426 } else if (lang.startsWith("hi")) {
428 } else if (lang.startsWith("el")) {
430 } else if (lang.startsWith("eu")) {
432 } else if (lang.startsWith("gl")) {
434 } else if (lang.startsWith("tr")) {
436 } else if (lang.startsWith("hu")) {
438 } else if (lang.startsWith("uk")) {
440 } else if (lang.startsWith("sq")) {
442 } else if (lang.startsWith("km")) {
444 } else if (lang.startsWith("ga")) {
446 } else if (lang.startsWith("sr")) {
448 } else if (lang.startsWith("ko")) {
450 } else if (lang.startsWith("da")) {
452 } else if (lang.startsWith("oc")) {
454 } else if (lang.startsWith("hr")) {
456 } else if (lang.startsWith("th")) {
458 } else if (lang.startsWith("bg")) {
466 export function setTheme(theme: string, forceReload = false) {
470 if (theme === "browser" && !forceReload) {
473 // This is only run on a force reload
474 if (theme == "browser") {
478 // Unload all the other themes
479 for (var i = 0; i < themes.length; i++) {
480 let styleSheet = document.getElementById(themes[i]);
482 styleSheet.setAttribute("disabled", "disabled");
487 .getElementById("default-light")
488 ?.setAttribute("disabled", "disabled");
489 document.getElementById("default-dark")?.setAttribute("disabled", "disabled");
491 // Load the theme dynamically
492 let cssLoc = `/static/assets/css/themes/${theme}.min.css`;
493 loadCss(theme, cssLoc);
494 document.getElementById(theme).removeAttribute("disabled");
497 export function loadCss(id: string, loc: string) {
498 if (!document.getElementById(id)) {
499 var head = document.getElementsByTagName("head")[0];
500 var link = document.createElement("link");
502 link.rel = "stylesheet";
503 link.type = "text/css";
506 head.appendChild(link);
510 export function objectFlip(obj: any) {
512 Object.keys(obj).forEach(key => {
518 export function showAvatars(): boolean {
520 UserService.Instance.localUserView?.local_user.show_avatars ||
521 !UserService.Instance.localUserView
525 export function showScores(): boolean {
527 UserService.Instance.localUserView?.local_user.show_scores ||
528 !UserService.Instance.localUserView
532 export function isCakeDay(published: string): boolean {
533 // moment(undefined) or moment.utc(undefined) returns the current date/time
534 // moment(null) or moment.utc(null) returns null
535 const createDate = moment.utc(published || null).local();
536 const currentDate = moment(new Date());
539 createDate.date() === currentDate.date() &&
540 createDate.month() === currentDate.month() &&
541 createDate.year() !== currentDate.year()
545 export function toast(text: string, background = "success") {
547 let backgroundColor = `var(--${background})`;
550 backgroundColor: backgroundColor,
557 export function pictrsDeleteToast(
558 clickToDeleteText: string,
559 deletePictureText: string,
563 let backgroundColor = `var(--light)`;
564 let toast = Toastify({
565 text: clickToDeleteText,
566 backgroundColor: backgroundColor,
572 window.location.replace(deleteUrl);
573 alert(deletePictureText);
582 interface NotifyInfo {
589 export function messageToastify(info: NotifyInfo, router: any) {
591 let htmlBody = info.body ? md.render(info.body) : "";
592 let backgroundColor = `var(--light)`;
594 let toast = Toastify({
595 text: `${htmlBody}<br />${info.name}`,
596 avatar: info.icon ? info.icon : null,
597 backgroundColor: backgroundColor,
598 className: "text-dark",
607 router.history.push(info.link);
614 export function notifyPost(post_view: PostView, router: any) {
615 let info: NotifyInfo = {
616 name: post_view.community.name,
617 icon: post_view.community.icon,
618 link: `/post/${post_view.post.id}`,
619 body: post_view.post.name,
621 notify(info, router);
624 export function notifyComment(comment_view: CommentView, router: any) {
625 let info: NotifyInfo = {
626 name: comment_view.creator.name,
627 icon: comment_view.creator.avatar,
628 link: `/post/${comment_view.post.id}/comment/${comment_view.comment.id}`,
629 body: comment_view.comment.content,
631 notify(info, router);
634 export function notifyPrivateMessage(pmv: PrivateMessageView, router: any) {
635 let info: NotifyInfo = {
636 name: pmv.creator.name,
637 icon: pmv.creator.avatar,
639 body: pmv.private_message.content,
641 notify(info, router);
644 function notify(info: NotifyInfo, router: any) {
645 messageToastify(info, router);
647 if (Notification.permission !== "granted") Notification.requestPermission();
649 var notification = new Notification(info.name, {
654 notification.onclick = (ev: Event): any => {
656 router.history.push(info.link);
661 export function setupTribute() {
663 noMatchTemplate: function () {
670 menuItemTemplate: (item: any) => {
671 let shortName = `:${item.original.key}:`;
672 return `${item.original.val} ${shortName}`;
674 selectTemplate: (item: any) => {
675 return `${item.original.val}`;
677 values: Object.entries(emojiShortName).map(e => {
678 return { key: e[1], val: e[0] };
681 autocompleteMode: true,
683 // menuItemLimit: mentionDropdownFetchLimit,
684 menuShowMinLength: 2,
689 selectTemplate: (item: any) => {
690 let it: PersonTribute = item.original;
691 return `[${it.key}](${it.view.person.actor_id})`;
693 values: (text: string, cb: (persons: PersonTribute[]) => any) => {
694 personSearch(text, (persons: PersonTribute[]) => cb(persons));
697 autocompleteMode: true,
699 // menuItemLimit: mentionDropdownFetchLimit,
700 menuShowMinLength: 2,
706 selectTemplate: (item: any) => {
707 let it: CommunityTribute = item.original;
708 return `[${it.key}](${it.view.community.actor_id})`;
710 values: (text: string, cb: any) => {
711 communitySearch(text, (communities: CommunityTribute[]) =>
716 autocompleteMode: true,
718 // menuItemLimit: mentionDropdownFetchLimit,
719 menuShowMinLength: 2,
725 var tippyInstance: any;
727 tippyInstance = tippy("[data-tippy-content]");
730 export function setupTippy() {
732 tippyInstance.forEach((e: any) => e.destroy());
733 tippyInstance = tippy("[data-tippy-content]", {
735 // Display on "long press"
736 touch: ["hold", 500],
741 interface PersonTribute {
743 view: PersonViewSafe;
746 function personSearch(text: string, cb: (persons: PersonTribute[]) => any) {
750 type_: SearchType.Users,
751 sort: SortType.TopAll,
752 listing_type: ListingType.All,
754 limit: mentionDropdownFetchLimit,
755 auth: authField(false),
758 WebSocketService.Instance.send(wsClient.search(form));
760 let personSub = WebSocketService.Instance.subject.subscribe(
762 let res = wsJsonToRes(msg);
763 if (res.op == UserOperation.Search) {
764 let data = res.data as SearchResponse;
765 let persons: PersonTribute[] = data.users.map(pv => {
766 let tribute: PersonTribute = {
767 key: `@${pv.person.name}@${hostname(pv.person.actor_id)}`,
773 personSub.unsubscribe();
776 err => console.error(err),
777 () => console.log("complete")
784 interface CommunityTribute {
789 function communitySearch(
791 cb: (communities: CommunityTribute[]) => any
796 type_: SearchType.Communities,
797 sort: SortType.TopAll,
798 listing_type: ListingType.All,
800 limit: mentionDropdownFetchLimit,
801 auth: authField(false),
804 WebSocketService.Instance.send(wsClient.search(form));
806 let communitySub = WebSocketService.Instance.subject.subscribe(
808 let res = wsJsonToRes(msg);
809 if (res.op == UserOperation.Search) {
810 let data = res.data as SearchResponse;
811 let communities: CommunityTribute[] = data.communities.map(cv => {
812 let tribute: CommunityTribute = {
813 key: `!${cv.community.name}@${hostname(cv.community.actor_id)}`,
819 communitySub.unsubscribe();
822 err => console.error(err),
823 () => console.log("complete")
830 export function getListingTypeFromProps(props: any): ListingType {
831 return props.match.params.listing_type
832 ? routeListingTypeToEnum(props.match.params.listing_type)
833 : UserService.Instance.localUserView
834 ? Object.values(ListingType)[
835 UserService.Instance.localUserView.local_user.default_listing_type
840 // TODO might need to add a user setting for this too
841 export function getDataTypeFromProps(props: any): DataType {
842 return props.match.params.data_type
843 ? routeDataTypeToEnum(props.match.params.data_type)
847 export function getSortTypeFromProps(props: any): SortType {
848 return props.match.params.sort
849 ? routeSortTypeToEnum(props.match.params.sort)
850 : UserService.Instance.localUserView
851 ? Object.values(SortType)[
852 UserService.Instance.localUserView.local_user.default_sort_type
857 export function getPageFromProps(props: any): number {
858 return props.match.params.page ? Number(props.match.params.page) : 1;
861 export function getRecipientIdFromProps(props: any): number {
862 return props.match.params.recipient_id
863 ? Number(props.match.params.recipient_id)
867 export function getIdFromProps(props: any): number {
868 return Number(props.match.params.id);
871 export function getCommentIdFromProps(props: any): number {
872 return Number(props.match.params.comment_id);
875 export function getUsernameFromProps(props: any): string {
876 return props.match.params.username;
879 export function editCommentRes(data: CommentView, comments: CommentView[]) {
880 let found = comments.find(c => c.comment.id == data.comment.id);
882 found.comment.content = data.comment.content;
883 found.comment.updated = data.comment.updated;
884 found.comment.removed = data.comment.removed;
885 found.comment.deleted = data.comment.deleted;
886 found.counts.upvotes = data.counts.upvotes;
887 found.counts.downvotes = data.counts.downvotes;
888 found.counts.score = data.counts.score;
892 export function saveCommentRes(data: CommentView, comments: CommentView[]) {
893 let found = comments.find(c => c.comment.id == data.comment.id);
895 found.saved = data.saved;
899 export function createCommentLikeRes(
901 comments: CommentView[]
903 let found = comments.find(c => c.comment.id === data.comment.id);
905 found.counts.score = data.counts.score;
906 found.counts.upvotes = data.counts.upvotes;
907 found.counts.downvotes = data.counts.downvotes;
908 if (data.my_vote !== null) {
909 found.my_vote = data.my_vote;
914 export function createPostLikeFindRes(data: PostView, posts: PostView[]) {
915 let found = posts.find(p => p.post.id == data.post.id);
917 createPostLikeRes(data, found);
921 export function createPostLikeRes(data: PostView, post_view: PostView) {
923 post_view.counts.score = data.counts.score;
924 post_view.counts.upvotes = data.counts.upvotes;
925 post_view.counts.downvotes = data.counts.downvotes;
926 if (data.my_vote !== null) {
927 post_view.my_vote = data.my_vote;
932 export function editPostFindRes(data: PostView, posts: PostView[]) {
933 let found = posts.find(p => p.post.id == data.post.id);
935 editPostRes(data, found);
939 export function editPostRes(data: PostView, post: PostView) {
941 post.post.url = data.post.url;
942 post.post.name = data.post.name;
943 post.post.nsfw = data.post.nsfw;
944 post.post.deleted = data.post.deleted;
945 post.post.removed = data.post.removed;
946 post.post.stickied = data.post.stickied;
947 post.post.body = data.post.body;
948 post.post.locked = data.post.locked;
949 post.saved = data.saved;
953 export function commentsToFlatNodes(comments: CommentView[]): CommentNodeI[] {
954 let nodes: CommentNodeI[] = [];
955 for (let comment of comments) {
956 nodes.push({ comment_view: comment });
961 function commentSort(tree: CommentNodeI[], sort: CommentSortType) {
962 // First, put removed and deleted comments at the bottom, then do your other sorts
963 if (sort == CommentSortType.Top) {
966 +a.comment_view.comment.removed - +b.comment_view.comment.removed ||
967 +a.comment_view.comment.deleted - +b.comment_view.comment.deleted ||
968 b.comment_view.counts.score - a.comment_view.counts.score
970 } else if (sort == CommentSortType.New) {
973 +a.comment_view.comment.removed - +b.comment_view.comment.removed ||
974 +a.comment_view.comment.deleted - +b.comment_view.comment.deleted ||
975 b.comment_view.comment.published.localeCompare(
976 a.comment_view.comment.published
979 } else if (sort == CommentSortType.Old) {
982 +a.comment_view.comment.removed - +b.comment_view.comment.removed ||
983 +a.comment_view.comment.deleted - +b.comment_view.comment.deleted ||
984 a.comment_view.comment.published.localeCompare(
985 b.comment_view.comment.published
988 } else if (sort == CommentSortType.Hot) {
991 +a.comment_view.comment.removed - +b.comment_view.comment.removed ||
992 +a.comment_view.comment.deleted - +b.comment_view.comment.deleted ||
993 hotRankComment(b.comment_view) - hotRankComment(a.comment_view)
997 // Go through the children recursively
998 for (let node of tree) {
1000 commentSort(node.children, sort);
1005 export function commentSortSortType(tree: CommentNodeI[], sort: SortType) {
1006 commentSort(tree, convertCommentSortType(sort));
1009 function convertCommentSortType(sort: SortType): CommentSortType {
1011 sort == SortType.TopAll ||
1012 sort == SortType.TopDay ||
1013 sort == SortType.TopWeek ||
1014 sort == SortType.TopMonth ||
1015 sort == SortType.TopYear
1017 return CommentSortType.Top;
1018 } else if (sort == SortType.New) {
1019 return CommentSortType.New;
1020 } else if (sort == SortType.Hot || sort == SortType.Active) {
1021 return CommentSortType.Hot;
1023 return CommentSortType.Hot;
1027 export function buildCommentsTree(
1028 comments: CommentView[],
1029 commentSortType: CommentSortType
1031 let map = new Map<number, CommentNodeI>();
1032 for (let comment_view of comments) {
1033 let node: CommentNodeI = {
1034 comment_view: comment_view,
1037 map.set(comment_view.comment.id, { ...node });
1039 let tree: CommentNodeI[] = [];
1040 for (let comment_view of comments) {
1041 let child = map.get(comment_view.comment.id);
1042 if (comment_view.comment.parent_id) {
1043 let parent_ = map.get(comment_view.comment.parent_id);
1044 parent_.children.push(child);
1052 commentSort(tree, commentSortType);
1057 function setDepth(node: CommentNodeI, i = 0) {
1058 for (let child of node.children) {
1060 setDepth(child, i + 1);
1064 export function insertCommentIntoTree(tree: CommentNodeI[], cv: CommentView) {
1065 // Building a fake node to be used for later
1066 let node: CommentNodeI = {
1072 if (cv.comment.parent_id) {
1073 let parentComment = searchCommentTree(tree, cv.comment.parent_id);
1074 if (parentComment) {
1075 node.depth = parentComment.depth + 1;
1076 parentComment.children.unshift(node);
1083 export function searchCommentTree(
1084 tree: CommentNodeI[],
1087 for (let node of tree) {
1088 if (node.comment_view.comment.id === id) {
1092 for (const child of node.children) {
1093 const res = searchCommentTree([child], id);
1103 export const colorList: string[] = [
1112 function hsl(num: number) {
1113 return `hsla(${num}, 35%, 50%, 1)`;
1116 export function previewLines(
1125 // Use lines * 2 because markdown requires 2 lines
1126 .slice(0, maxLines * 2)
1131 export function hostname(url: string): string {
1132 let cUrl = new URL(url);
1133 return cUrl.port ? `${cUrl.hostname}:${cUrl.port}` : `${cUrl.hostname}`;
1136 export function validTitle(title?: string): boolean {
1137 // Initial title is null, minimum length is taken care of by textarea's minLength={3}
1138 if (title === null || title.length < 3) return true;
1140 const regex = new RegExp(/.*\S.*/, "g");
1142 return regex.test(title);
1145 export function siteBannerCss(banner: string): string {
1147 background-image: linear-gradient( rgba(0, 0, 0, 0.8), rgba(0, 0, 0, 0.8) ) ,url("${banner}"); \
1148 background-attachment: fixed; \
1149 background-position: top; \
1150 background-repeat: no-repeat; \
1151 background-size: 100% cover; \
1154 max-height: 100vh; \
1158 export function isBrowser() {
1159 return typeof window !== "undefined";
1162 export function setIsoData(context: any): IsoData {
1163 let isoData: IsoData = isBrowser()
1165 : context.router.staticContext;
1169 export function wsSubscribe(parseMessage: any): Subscription {
1171 return WebSocketService.Instance.subject
1172 .pipe(retryWhen(errors => errors.pipe(delay(3000), take(10))))
1174 msg => parseMessage(msg),
1175 err => console.error(err),
1176 () => console.log("complete")
1183 export function setOptionalAuth(obj: any, auth = UserService.Instance.auth) {
1189 export function authField(
1191 auth = UserService.Instance.auth
1193 if (auth == null && throwErr) {
1194 toast(i18n.t("not_logged_in"), "danger");
1195 throw "Not logged in";
1201 moment.updateLocale("en", {
1222 export function saveScrollPosition(context: any) {
1223 let path: string = context.router.route.location.pathname;
1224 let y = window.scrollY;
1225 sessionStorage.setItem(`scrollPosition_${path}`, y.toString());
1228 export function restoreScrollPosition(context: any) {
1229 let path: string = context.router.route.location.pathname;
1230 let y = Number(sessionStorage.getItem(`scrollPosition_${path}`));
1231 window.scrollTo(0, y);
1234 export function showLocal(isoData: IsoData): boolean {
1235 return isoData.site_res.federated_instances?.linked.length > 0;
1238 interface ChoicesValue {
1243 export function communityToChoice(cv: CommunityView): ChoicesValue {
1244 let choice: ChoicesValue = {
1245 value: cv.community.id.toString(),
1246 label: cv.community.name,
1251 export function personToChoice(pvs: PersonViewSafe): ChoicesValue {
1252 let choice: ChoicesValue = {
1253 value: pvs.person.id.toString(),
1254 label: pvs.person.name,
1259 export async function fetchCommunities(q: string) {
1260 let form: Search = {
1262 type_: SearchType.Communities,
1263 sort: SortType.TopAll,
1264 listing_type: ListingType.All,
1267 auth: authField(false),
1269 let client = new LemmyHttp(httpBase);
1270 return client.search(form);
1273 export async function fetchUsers(q: string) {
1274 let form: Search = {
1276 type_: SearchType.Users,
1277 sort: SortType.TopAll,
1278 listing_type: ListingType.All,
1281 auth: authField(false),
1283 let client = new LemmyHttp(httpBase);
1284 return client.search(form);
1287 export const choicesConfig = {
1289 searchResultLimit: fetchLimit,
1291 containerOuter: "choices",
1292 containerInner: "choices__inner bg-light border-0",
1293 input: "form-control",
1294 inputCloned: "choices__input--cloned",
1295 list: "choices__list",
1296 listItems: "choices__list--multiple",
1297 listSingle: "choices__list--single",
1298 listDropdown: "choices__list--dropdown",
1299 item: "choices__item bg-light",
1300 itemSelectable: "choices__item--selectable",
1301 itemDisabled: "choices__item--disabled",
1302 itemChoice: "choices__item--choice",
1303 placeholder: "choices__placeholder",
1304 group: "choices__group",
1305 groupHeading: "choices__heading",
1306 button: "choices__button",
1307 activeState: "is-active",
1308 focusState: "is-focused",
1309 openState: "is-open",
1310 disabledState: "is-disabled",
1311 highlightedState: "text-info",
1312 selectedState: "text-info",
1313 flippedState: "is-flipped",
1314 loadingState: "is-loading",
1315 noResults: "has-no-results",
1316 noChoices: "has-no-choices",