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";
35 LocalUserSettingsView,
40 WebSocketJsonResponse,
48 } from "lemmy-js-client";
54 CommentNode as CommentNodeI,
55 } from "./interfaces";
56 import { UserService, WebSocketService } from "./services";
59 Tribute = require("tributejs");
61 import markdown_it from "markdown-it";
62 import markdown_it_sub from "markdown-it-sub";
63 import markdown_it_sup from "markdown-it-sup";
64 import markdown_it_container from "markdown-it-container";
65 import emojiShortName from "emoji-short-name";
66 import Toastify from "toastify-js";
67 import tippy from "tippy.js";
68 import moment from "moment";
69 import { Subscription } from "rxjs";
70 import { retryWhen, delay, take } from "rxjs/operators";
71 import { i18n } from "./i18next";
73 export const wsClient = new LemmyWebsocket();
75 export const favIconUrl = "/static/assets/favicon.svg";
76 export const favIconPngUrl = "/static/assets/apple-touch-icon.png";
78 // export const defaultFavIcon = `${window.location.protocol}//${window.location.host}${favIconPngUrl}`;
79 export const repoUrl = "https://github.com/LemmyNet";
80 export const joinLemmyUrl = "https://join.lemmy.ml";
81 export const supportLemmyUrl = "https://join.lemmy.ml/support";
82 export const docsUrl = "https://join.lemmy.ml/docs/en/index.html";
83 export const helpGuideUrl = "https://join.lemmy.ml/docs/en/about/guide.html"; // TODO find a way to redirect to the non-en folder
84 export const markdownHelpUrl = `${helpGuideUrl}#markdown-guide`;
85 export const sortingHelpUrl = `${helpGuideUrl}#sorting`;
86 export const archiveUrl = "https://archive.is";
87 export const elementUrl = "https://element.io/";
89 export const postRefetchSeconds: number = 60 * 1000;
90 export const fetchLimit = 20;
91 export const mentionDropdownFetchLimit = 10;
93 export const languages = [
129 export const themes = [
145 const DEFAULT_ALPHABET =
146 "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
148 function getRandomCharFromAlphabet(alphabet: string): string {
149 return alphabet.charAt(Math.floor(Math.random() * alphabet.length));
152 export function randomStr(
153 idDesiredLength = 20,
154 alphabet = DEFAULT_ALPHABET
157 * Create n-long array and map it to random chars from given alphabet.
158 * Then join individual chars as string
160 return Array.from({ length: idDesiredLength })
162 return getRandomCharFromAlphabet(alphabet);
167 export function wsJsonToRes<ResponseType>(
168 msg: WebSocketJsonResponse<ResponseType>
169 ): WebSocketResponse<ResponseType> {
176 export function wsUserOp(msg: any): UserOperation {
177 let opStr: string = msg.op;
178 return UserOperation[opStr];
181 export const md = new markdown_it({
186 .use(markdown_it_sub)
187 .use(markdown_it_sup)
188 .use(markdown_it_container, "spoiler", {
189 validate: function (params: any) {
190 return params.trim().match(/^spoiler\s+(.*)$/);
193 render: function (tokens: any, idx: any) {
194 var m = tokens[idx].info.trim().match(/^spoiler\s+(.*)$/);
196 if (tokens[idx].nesting === 1) {
198 return `<details><summary> ${md.utils.escapeHtml(m[1])} </summary>\n`;
201 return "</details>\n";
206 export function hotRankComment(comment_view: CommentView): number {
207 return hotRank(comment_view.counts.score, comment_view.comment.published);
210 export function hotRankActivePost(post_view: PostView): number {
211 return hotRank(post_view.counts.score, post_view.counts.newest_comment_time);
214 export function hotRankPost(post_view: PostView): number {
215 return hotRank(post_view.counts.score, post_view.post.published);
218 export function hotRank(score: number, timeStr: string): number {
219 // Rank = ScaleFactor * sign(Score) * log(1 + abs(Score)) / (Time + 2)^Gravity
220 let date: Date = new Date(timeStr + "Z"); // Add Z to convert from UTC date
221 let now: Date = new Date();
222 let hoursElapsed: number = (now.getTime() - date.getTime()) / 36e5;
225 (10000 * Math.log10(Math.max(1, 3 + score))) /
226 Math.pow(hoursElapsed + 2, 1.8);
228 // console.log(`Comment: ${comment.content}\nRank: ${rank}\nScore: ${comment.score}\nHours: ${hoursElapsed}`);
233 export function mdToHtml(text: string) {
234 return { __html: md.render(text) };
237 export function getUnixTime(text: string): number {
238 return text ? new Date(text).getTime() / 1000 : undefined;
241 export function canMod(
242 localUserView: LocalUserSettingsView,
247 // You can do moderator actions only on the mods added after you.
249 let yourIndex = modIds.findIndex(id => id == localUserView.person.id);
250 if (yourIndex == -1) {
253 // onSelf +1 on mod actions not for yourself, IE ban, remove, etc
254 modIds = modIds.slice(0, yourIndex + (onSelf ? 0 : 1));
255 return !modIds.includes(creator_id);
262 export function isMod(modIds: number[], creator_id: number): boolean {
263 return modIds.includes(creator_id);
266 const imageRegex = new RegExp(
267 /(http)?s?:?(\/\/[^"']*\.(?:jpg|jpeg|gif|png|svg|webp))/
269 const videoRegex = new RegExp(`(http)?s?:?(\/\/[^"']*\.(?:mp4))`);
271 export function isImage(url: string) {
272 return imageRegex.test(url);
275 export function isVideo(url: string) {
276 return videoRegex.test(url);
279 export function validURL(str: string) {
280 return !!new URL(str);
283 export function communityRSSUrl(actorId: string, sort: string): string {
284 let url = new URL(actorId);
285 return `${url.origin}/feeds${url.pathname}.xml?sort=${sort}`;
288 export function validEmail(email: string) {
289 let re = /^(([^\s"(),.:;<>@[\\\]]+(\.[^\s"(),.:;<>@[\\\]]+)*)|(".+"))@((\[(?:\d{1,3}\.){3}\d{1,3}])|(([\dA-Za-z\-]+\.)+[A-Za-z]{2,}))$/;
290 return re.test(String(email).toLowerCase());
293 export function capitalizeFirstLetter(str: string): string {
294 return str.charAt(0).toUpperCase() + str.slice(1);
297 export function routeSortTypeToEnum(sort: string): SortType {
298 return SortType[sort];
301 export function listingTypeFromNum(type_: number): ListingType {
302 return Object.values(ListingType)[type_];
305 export function sortTypeFromNum(type_: number): SortType {
306 return Object.values(SortType)[type_];
309 export function routeListingTypeToEnum(type: string): ListingType {
310 return ListingType[type];
313 export function routeDataTypeToEnum(type: string): DataType {
314 return DataType[capitalizeFirstLetter(type)];
317 export function routeSearchTypeToEnum(type: string): SearchType {
318 return SearchType[type];
321 export async function getPageTitle(url: string) {
322 let res = await fetch(`/iframely/oembed?url=${url}`).then(res => res.json());
323 let title = await res.title;
327 export function debounce(func: any, wait = 1000, immediate = false) {
328 // 'private' variable for instance
329 // The returned function will be able to reference this due to closure.
330 // Each call to the returned function will share this common timer.
333 // Calling debounce returns a new anonymous function
335 // reference the context and args for the setTimeout function
336 var args = arguments;
338 // Should the function be called now? If immediate is true
339 // and not already in a timeout then the answer is: Yes
340 var callNow = immediate && !timeout;
342 // This is the basic debounce behaviour where you can call this
343 // function several times, but it will only execute once
344 // [before or after imposing a delay].
345 // Each time the returned function is called, the timer starts over.
346 clearTimeout(timeout);
348 // Set the new timeout
349 timeout = setTimeout(function () {
350 // Inside the timeout function, clear the timeout variable
351 // which will let the next execution run when in 'immediate' mode
354 // Check if the function already ran with the immediate flag
356 // Call the original function with apply
357 // apply lets you define the 'this' object as well as the arguments
358 // (both captured before setTimeout)
359 func.apply(this, args);
363 // Immediate mode and no wait timer? Execute the function..
364 if (callNow) func.apply(this, args);
369 export function getLanguage(override?: string): string {
370 let localUserView = UserService.Instance.localUserView;
373 (localUserView?.local_user.lang
374 ? localUserView.local_user.lang
377 if (lang == "browser" && isBrowser()) {
378 return getBrowserLanguage();
384 export function getBrowserLanguage(): string {
385 return navigator.language;
388 export function getMomentLanguage(): string {
389 let lang = getLanguage();
390 if (lang.startsWith("zh")) {
392 } else if (lang.startsWith("sv")) {
394 } else if (lang.startsWith("fr")) {
396 } else if (lang.startsWith("de")) {
398 } else if (lang.startsWith("ru")) {
400 } else if (lang.startsWith("es")) {
402 } else if (lang.startsWith("eo")) {
404 } else if (lang.startsWith("nl")) {
406 } else if (lang.startsWith("it")) {
408 } else if (lang.startsWith("fi")) {
410 } else if (lang.startsWith("ca")) {
412 } else if (lang.startsWith("fa")) {
414 } else if (lang.startsWith("pl")) {
416 } else if (lang.startsWith("pt")) {
418 } else if (lang.startsWith("ja")) {
420 } else if (lang.startsWith("ka")) {
422 } else if (lang.startsWith("hi")) {
424 } else if (lang.startsWith("el")) {
426 } else if (lang.startsWith("eu")) {
428 } else if (lang.startsWith("gl")) {
430 } else if (lang.startsWith("tr")) {
432 } else if (lang.startsWith("hu")) {
434 } else if (lang.startsWith("uk")) {
436 } else if (lang.startsWith("sq")) {
438 } else if (lang.startsWith("km")) {
440 } else if (lang.startsWith("ga")) {
442 } else if (lang.startsWith("sr")) {
444 } else if (lang.startsWith("ko")) {
446 } else if (lang.startsWith("da")) {
448 } else if (lang.startsWith("oc")) {
450 } else if (lang.startsWith("hr")) {
452 } else if (lang.startsWith("th")) {
460 export function setTheme(theme: string, forceReload = false) {
464 if (theme === "browser" && !forceReload) {
467 // This is only run on a force reload
468 if (theme == "browser") {
472 // Unload all the other themes
473 for (var i = 0; i < themes.length; i++) {
474 let styleSheet = document.getElementById(themes[i]);
476 styleSheet.setAttribute("disabled", "disabled");
481 .getElementById("default-light")
482 ?.setAttribute("disabled", "disabled");
483 document.getElementById("default-dark")?.setAttribute("disabled", "disabled");
485 // Load the theme dynamically
486 let cssLoc = `/static/assets/css/themes/${theme}.min.css`;
487 loadCss(theme, cssLoc);
488 document.getElementById(theme).removeAttribute("disabled");
491 export function loadCss(id: string, loc: string) {
492 if (!document.getElementById(id)) {
493 var head = document.getElementsByTagName("head")[0];
494 var link = document.createElement("link");
496 link.rel = "stylesheet";
497 link.type = "text/css";
500 head.appendChild(link);
504 export function objectFlip(obj: any) {
506 Object.keys(obj).forEach(key => {
512 export function showAvatars(): boolean {
514 UserService.Instance.localUserView?.local_user.show_avatars ||
515 !UserService.Instance.localUserView
519 export function isCakeDay(published: string): boolean {
520 // moment(undefined) or moment.utc(undefined) returns the current date/time
521 // moment(null) or moment.utc(null) returns null
522 const createDate = moment.utc(published || null).local();
523 const currentDate = moment(new Date());
526 createDate.date() === currentDate.date() &&
527 createDate.month() === currentDate.month() &&
528 createDate.year() !== currentDate.year()
532 export function toast(text: string, background = "success") {
534 let backgroundColor = `var(--${background})`;
537 backgroundColor: backgroundColor,
544 export function pictrsDeleteToast(
545 clickToDeleteText: string,
546 deletePictureText: string,
550 let backgroundColor = `var(--light)`;
551 let toast = Toastify({
552 text: clickToDeleteText,
553 backgroundColor: backgroundColor,
559 window.location.replace(deleteUrl);
560 alert(deletePictureText);
569 interface NotifyInfo {
576 export function messageToastify(info: NotifyInfo, router: any) {
578 let htmlBody = info.body ? md.render(info.body) : "";
579 let backgroundColor = `var(--light)`;
581 let toast = Toastify({
582 text: `${htmlBody}<br />${info.name}`,
583 avatar: info.icon ? info.icon : null,
584 backgroundColor: backgroundColor,
585 className: "text-dark",
593 router.history.push(info.link);
600 export function notifyPost(post_view: PostView, router: any) {
601 let info: NotifyInfo = {
602 name: post_view.community.name,
603 icon: post_view.community.icon,
604 link: `/post/${post_view.post.id}`,
605 body: post_view.post.name,
607 notify(info, router);
610 export function notifyComment(comment_view: CommentView, router: any) {
611 let info: NotifyInfo = {
612 name: comment_view.creator.name,
613 icon: comment_view.creator.avatar,
614 link: `/post/${comment_view.post.id}/comment/${comment_view.comment.id}`,
615 body: comment_view.comment.content,
617 notify(info, router);
620 export function notifyPrivateMessage(pmv: PrivateMessageView, router: any) {
621 let info: NotifyInfo = {
622 name: pmv.creator.name,
623 icon: pmv.creator.avatar,
625 body: pmv.private_message.content,
627 notify(info, router);
630 function notify(info: NotifyInfo, router: any) {
631 messageToastify(info, router);
633 if (Notification.permission !== "granted") Notification.requestPermission();
635 var notification = new Notification(info.name, {
640 notification.onclick = (ev: Event): any => {
642 router.history.push(info.link);
647 export function setupTribute() {
649 noMatchTemplate: function () {
656 menuItemTemplate: (item: any) => {
657 let shortName = `:${item.original.key}:`;
658 return `${item.original.val} ${shortName}`;
660 selectTemplate: (item: any) => {
661 return `${item.original.val}`;
663 values: Object.entries(emojiShortName).map(e => {
664 return { key: e[1], val: e[0] };
667 autocompleteMode: true,
669 // menuItemLimit: mentionDropdownFetchLimit,
670 menuShowMinLength: 2,
675 selectTemplate: (item: any) => {
676 let it: PersonTribute = item.original;
677 return `[${it.key}](${it.view.person.actor_id})`;
679 values: (text: string, cb: (persons: PersonTribute[]) => any) => {
680 personSearch(text, (persons: PersonTribute[]) => cb(persons));
683 autocompleteMode: true,
685 // menuItemLimit: mentionDropdownFetchLimit,
686 menuShowMinLength: 2,
692 selectTemplate: (item: any) => {
693 let it: CommunityTribute = item.original;
694 return `[${it.key}](${it.view.community.actor_id})`;
696 values: (text: string, cb: any) => {
697 communitySearch(text, (communities: CommunityTribute[]) =>
702 autocompleteMode: true,
704 // menuItemLimit: mentionDropdownFetchLimit,
705 menuShowMinLength: 2,
711 var tippyInstance: any;
713 tippyInstance = tippy("[data-tippy-content]");
716 export function setupTippy() {
718 tippyInstance.forEach((e: any) => e.destroy());
719 tippyInstance = tippy("[data-tippy-content]", {
721 // Display on "long press"
722 touch: ["hold", 500],
727 interface PersonTribute {
729 view: PersonViewSafe;
732 function personSearch(text: string, cb: (persons: PersonTribute[]) => any) {
736 type_: SearchType.Users,
737 sort: SortType.TopAll,
739 limit: mentionDropdownFetchLimit,
740 auth: authField(false),
743 WebSocketService.Instance.send(wsClient.search(form));
745 let personSub = WebSocketService.Instance.subject.subscribe(
747 let res = wsJsonToRes(msg);
748 if (res.op == UserOperation.Search) {
749 let data = res.data as SearchResponse;
750 let persons: PersonTribute[] = data.users.map(pv => {
751 let tribute: PersonTribute = {
752 key: `@${pv.person.name}@${hostname(pv.person.actor_id)}`,
758 personSub.unsubscribe();
761 err => console.error(err),
762 () => console.log("complete")
769 interface CommunityTribute {
774 function communitySearch(
776 cb: (communities: CommunityTribute[]) => any
781 type_: SearchType.Communities,
782 sort: SortType.TopAll,
784 limit: mentionDropdownFetchLimit,
785 auth: authField(false),
788 WebSocketService.Instance.send(wsClient.search(form));
790 let communitySub = WebSocketService.Instance.subject.subscribe(
792 let res = wsJsonToRes(msg);
793 if (res.op == UserOperation.Search) {
794 let data = res.data as SearchResponse;
795 let communities: CommunityTribute[] = data.communities.map(cv => {
796 let tribute: CommunityTribute = {
797 key: `!${cv.community.name}@${hostname(cv.community.actor_id)}`,
803 communitySub.unsubscribe();
806 err => console.error(err),
807 () => console.log("complete")
814 export function getListingTypeFromProps(props: any): ListingType {
815 return props.match.params.listing_type
816 ? routeListingTypeToEnum(props.match.params.listing_type)
817 : UserService.Instance.localUserView
818 ? Object.values(ListingType)[
819 UserService.Instance.localUserView.local_user.default_listing_type
824 // TODO might need to add a user setting for this too
825 export function getDataTypeFromProps(props: any): DataType {
826 return props.match.params.data_type
827 ? routeDataTypeToEnum(props.match.params.data_type)
831 export function getSortTypeFromProps(props: any): SortType {
832 return props.match.params.sort
833 ? routeSortTypeToEnum(props.match.params.sort)
834 : UserService.Instance.localUserView
835 ? Object.values(SortType)[
836 UserService.Instance.localUserView.local_user.default_sort_type
841 export function getPageFromProps(props: any): number {
842 return props.match.params.page ? Number(props.match.params.page) : 1;
845 export function getRecipientIdFromProps(props: any): number {
846 return props.match.params.recipient_id
847 ? Number(props.match.params.recipient_id)
851 export function getIdFromProps(props: any): number {
852 return Number(props.match.params.id);
855 export function getCommentIdFromProps(props: any): number {
856 return Number(props.match.params.comment_id);
859 export function getUsernameFromProps(props: any): string {
860 return props.match.params.username;
863 export function editCommentRes(data: CommentView, comments: CommentView[]) {
864 let found = comments.find(c => c.comment.id == data.comment.id);
866 found.comment.content = data.comment.content;
867 found.comment.updated = data.comment.updated;
868 found.comment.removed = data.comment.removed;
869 found.comment.deleted = data.comment.deleted;
870 found.counts.upvotes = data.counts.upvotes;
871 found.counts.downvotes = data.counts.downvotes;
872 found.counts.score = data.counts.score;
876 export function saveCommentRes(data: CommentView, comments: CommentView[]) {
877 let found = comments.find(c => c.comment.id == data.comment.id);
879 found.saved = data.saved;
883 export function createCommentLikeRes(
885 comments: CommentView[]
887 let found = comments.find(c => c.comment.id === data.comment.id);
889 found.counts.score = data.counts.score;
890 found.counts.upvotes = data.counts.upvotes;
891 found.counts.downvotes = data.counts.downvotes;
892 if (data.my_vote !== null) {
893 found.my_vote = data.my_vote;
898 export function createPostLikeFindRes(data: PostView, posts: PostView[]) {
899 let found = posts.find(p => p.post.id == data.post.id);
901 createPostLikeRes(data, found);
905 export function createPostLikeRes(data: PostView, post_view: PostView) {
907 post_view.counts.score = data.counts.score;
908 post_view.counts.upvotes = data.counts.upvotes;
909 post_view.counts.downvotes = data.counts.downvotes;
910 if (data.my_vote !== null) {
911 post_view.my_vote = data.my_vote;
916 export function editPostFindRes(data: PostView, posts: PostView[]) {
917 let found = posts.find(p => p.post.id == data.post.id);
919 editPostRes(data, found);
923 export function editPostRes(data: PostView, post: PostView) {
925 post.post.url = data.post.url;
926 post.post.name = data.post.name;
927 post.post.nsfw = data.post.nsfw;
928 post.post.deleted = data.post.deleted;
929 post.post.removed = data.post.removed;
930 post.post.stickied = data.post.stickied;
931 post.post.body = data.post.body;
932 post.post.locked = data.post.locked;
933 post.saved = data.saved;
937 export function commentsToFlatNodes(comments: CommentView[]): CommentNodeI[] {
938 let nodes: CommentNodeI[] = [];
939 for (let comment of comments) {
940 nodes.push({ comment_view: comment });
945 function commentSort(tree: CommentNodeI[], sort: CommentSortType) {
946 // First, put removed and deleted comments at the bottom, then do your other sorts
947 if (sort == CommentSortType.Top) {
950 +a.comment_view.comment.removed - +b.comment_view.comment.removed ||
951 +a.comment_view.comment.deleted - +b.comment_view.comment.deleted ||
952 b.comment_view.counts.score - a.comment_view.counts.score
954 } else if (sort == CommentSortType.New) {
957 +a.comment_view.comment.removed - +b.comment_view.comment.removed ||
958 +a.comment_view.comment.deleted - +b.comment_view.comment.deleted ||
959 b.comment_view.comment.published.localeCompare(
960 a.comment_view.comment.published
963 } else if (sort == CommentSortType.Old) {
966 +a.comment_view.comment.removed - +b.comment_view.comment.removed ||
967 +a.comment_view.comment.deleted - +b.comment_view.comment.deleted ||
968 a.comment_view.comment.published.localeCompare(
969 b.comment_view.comment.published
972 } else if (sort == CommentSortType.Hot) {
975 +a.comment_view.comment.removed - +b.comment_view.comment.removed ||
976 +a.comment_view.comment.deleted - +b.comment_view.comment.deleted ||
977 hotRankComment(b.comment_view) - hotRankComment(a.comment_view)
981 // Go through the children recursively
982 for (let node of tree) {
984 commentSort(node.children, sort);
989 export function commentSortSortType(tree: CommentNodeI[], sort: SortType) {
990 commentSort(tree, convertCommentSortType(sort));
993 function convertCommentSortType(sort: SortType): CommentSortType {
995 sort == SortType.TopAll ||
996 sort == SortType.TopDay ||
997 sort == SortType.TopWeek ||
998 sort == SortType.TopMonth ||
999 sort == SortType.TopYear
1001 return CommentSortType.Top;
1002 } else if (sort == SortType.New) {
1003 return CommentSortType.New;
1004 } else if (sort == SortType.Hot || sort == SortType.Active) {
1005 return CommentSortType.Hot;
1007 return CommentSortType.Hot;
1011 export function buildCommentsTree(
1012 comments: CommentView[],
1013 commentSortType: CommentSortType
1015 let map = new Map<number, CommentNodeI>();
1016 for (let comment_view of comments) {
1017 let node: CommentNodeI = {
1018 comment_view: comment_view,
1021 map.set(comment_view.comment.id, { ...node });
1023 let tree: CommentNodeI[] = [];
1024 for (let comment_view of comments) {
1025 let child = map.get(comment_view.comment.id);
1026 if (comment_view.comment.parent_id) {
1027 let parent_ = map.get(comment_view.comment.parent_id);
1028 parent_.children.push(child);
1036 commentSort(tree, commentSortType);
1041 function setDepth(node: CommentNodeI, i = 0) {
1042 for (let child of node.children) {
1044 setDepth(child, i + 1);
1048 export function insertCommentIntoTree(tree: CommentNodeI[], cv: CommentView) {
1049 // Building a fake node to be used for later
1050 let node: CommentNodeI = {
1056 if (cv.comment.parent_id) {
1057 let parentComment = searchCommentTree(tree, cv.comment.parent_id);
1058 if (parentComment) {
1059 node.depth = parentComment.depth + 1;
1060 parentComment.children.unshift(node);
1067 export function searchCommentTree(
1068 tree: CommentNodeI[],
1071 for (let node of tree) {
1072 if (node.comment_view.comment.id === id) {
1076 for (const child of node.children) {
1077 const res = searchCommentTree([child], id);
1087 export const colorList: string[] = [
1096 function hsl(num: number) {
1097 return `hsla(${num}, 35%, 50%, 1)`;
1100 export function previewLines(
1109 // Use lines * 2 because markdown requires 2 lines
1110 .slice(0, maxLines * 2)
1115 export function hostname(url: string): string {
1116 let cUrl = new URL(url);
1117 return cUrl.port ? `${cUrl.hostname}:${cUrl.port}` : `${cUrl.hostname}`;
1120 export function validTitle(title?: string): boolean {
1121 // Initial title is null, minimum length is taken care of by textarea's minLength={3}
1122 if (title === null || title.length < 3) return true;
1124 const regex = new RegExp(/.*\S.*/, "g");
1126 return regex.test(title);
1129 export function siteBannerCss(banner: string): string {
1131 background-image: linear-gradient( rgba(0, 0, 0, 0.8), rgba(0, 0, 0, 0.8) ) ,url("${banner}"); \
1132 background-attachment: fixed; \
1133 background-position: top; \
1134 background-repeat: no-repeat; \
1135 background-size: 100% cover; \
1138 max-height: 100vh; \
1142 export function isBrowser() {
1143 return typeof window !== "undefined";
1146 export function setIsoData(context: any): IsoData {
1147 let isoData: IsoData = isBrowser()
1149 : context.router.staticContext;
1153 export function wsSubscribe(parseMessage: any): Subscription {
1155 return WebSocketService.Instance.subject
1156 .pipe(retryWhen(errors => errors.pipe(delay(3000), take(10))))
1158 msg => parseMessage(msg),
1159 err => console.error(err),
1160 () => console.log("complete")
1167 export function setOptionalAuth(obj: any, auth = UserService.Instance.auth) {
1173 export function authField(
1175 auth = UserService.Instance.auth
1177 if (auth == null && throwErr) {
1178 toast(i18n.t("not_logged_in"), "danger");
1179 throw "Not logged in";
1185 moment.updateLocale("en", {
1206 export function saveScrollPosition(context: any) {
1207 let path: string = context.router.route.location.pathname;
1208 let y = window.scrollY;
1209 sessionStorage.setItem(`scrollPosition_${path}`, y.toString());
1212 export function restoreScrollPosition(context: any) {
1213 let path: string = context.router.route.location.pathname;
1214 let y = Number(sessionStorage.getItem(`scrollPosition_${path}`));
1215 window.scrollTo(0, y);