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,
49 } from "lemmy-js-client";
55 CommentNode as CommentNodeI,
56 } from "./interfaces";
57 import { UserService, WebSocketService } from "./services";
60 Tribute = require("tributejs");
62 import markdown_it from "markdown-it";
63 import markdown_it_sub from "markdown-it-sub";
64 import markdown_it_sup from "markdown-it-sup";
65 import markdown_it_container from "markdown-it-container";
66 import emojiShortName from "emoji-short-name";
67 import Toastify from "toastify-js";
68 import tippy from "tippy.js";
69 import moment from "moment";
70 import { Subscription } from "rxjs";
71 import { retryWhen, delay, take } from "rxjs/operators";
72 import { i18n } from "./i18next";
74 export const wsClient = new LemmyWebsocket();
76 export const favIconUrl = "/static/assets/icons/favicon.svg";
77 export const favIconPngUrl = "/static/assets/icons/apple-touch-icon.png";
79 // export const defaultFavIcon = `${window.location.protocol}//${window.location.host}${favIconPngUrl}`;
80 export const repoUrl = "https://github.com/LemmyNet";
81 export const joinLemmyUrl = "https://join.lemmy.ml";
82 export const supportLemmyUrl = "https://join.lemmy.ml/support";
83 export const docsUrl = "https://join.lemmy.ml/docs/en/index.html";
84 export const helpGuideUrl = "https://join.lemmy.ml/docs/en/about/guide.html"; // TODO find a way to redirect to the non-en folder
85 export const markdownHelpUrl = `${helpGuideUrl}#markdown-guide`;
86 export const sortingHelpUrl = `${helpGuideUrl}#sorting`;
87 export const archiveUrl = "https://archive.is";
88 export const elementUrl = "https://element.io/";
90 export const postRefetchSeconds: number = 60 * 1000;
91 export const fetchLimit = 20;
92 export const mentionDropdownFetchLimit = 10;
94 export const languages = [
131 export const themes = [
147 const DEFAULT_ALPHABET =
148 "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
150 function getRandomCharFromAlphabet(alphabet: string): string {
151 return alphabet.charAt(Math.floor(Math.random() * alphabet.length));
154 export function randomStr(
155 idDesiredLength = 20,
156 alphabet = DEFAULT_ALPHABET
159 * Create n-long array and map it to random chars from given alphabet.
160 * Then join individual chars as string
162 return Array.from({ length: idDesiredLength })
164 return getRandomCharFromAlphabet(alphabet);
169 export function wsJsonToRes<ResponseType>(
170 msg: WebSocketJsonResponse<ResponseType>
171 ): WebSocketResponse<ResponseType> {
178 export function wsUserOp(msg: any): UserOperation {
179 let opStr: string = msg.op;
180 return UserOperation[opStr];
183 export const md = new markdown_it({
188 .use(markdown_it_sub)
189 .use(markdown_it_sup)
190 .use(markdown_it_container, "spoiler", {
191 validate: function (params: any) {
192 return params.trim().match(/^spoiler\s+(.*)$/);
195 render: function (tokens: any, idx: any) {
196 var m = tokens[idx].info.trim().match(/^spoiler\s+(.*)$/);
198 if (tokens[idx].nesting === 1) {
200 return `<details><summary> ${md.utils.escapeHtml(m[1])} </summary>\n`;
203 return "</details>\n";
208 export function hotRankComment(comment_view: CommentView): number {
209 return hotRank(comment_view.counts.score, comment_view.comment.published);
212 export function hotRankActivePost(post_view: PostView): number {
213 return hotRank(post_view.counts.score, post_view.counts.newest_comment_time);
216 export function hotRankPost(post_view: PostView): number {
217 return hotRank(post_view.counts.score, post_view.post.published);
220 export function hotRank(score: number, timeStr: string): number {
221 // Rank = ScaleFactor * sign(Score) * log(1 + abs(Score)) / (Time + 2)^Gravity
222 let date: Date = new Date(timeStr + "Z"); // Add Z to convert from UTC date
223 let now: Date = new Date();
224 let hoursElapsed: number = (now.getTime() - date.getTime()) / 36e5;
227 (10000 * Math.log10(Math.max(1, 3 + score))) /
228 Math.pow(hoursElapsed + 2, 1.8);
230 // console.log(`Comment: ${comment.content}\nRank: ${rank}\nScore: ${comment.score}\nHours: ${hoursElapsed}`);
235 export function mdToHtml(text: string) {
236 return { __html: md.render(text) };
239 export function getUnixTime(text: string): number {
240 return text ? new Date(text).getTime() / 1000 : undefined;
243 export function canMod(
244 localUserView: LocalUserSettingsView,
249 // You can do moderator actions only on the mods added after you.
251 let yourIndex = modIds.findIndex(id => id == localUserView.person.id);
252 if (yourIndex == -1) {
255 // onSelf +1 on mod actions not for yourself, IE ban, remove, etc
256 modIds = modIds.slice(0, yourIndex + (onSelf ? 0 : 1));
257 return !modIds.includes(creator_id);
264 export function isMod(modIds: number[], creator_id: number): boolean {
265 return modIds.includes(creator_id);
268 const imageRegex = new RegExp(
269 /(http)?s?:?(\/\/[^"']*\.(?:jpg|jpeg|gif|png|svg|webp))/
271 const videoRegex = new RegExp(`(http)?s?:?(\/\/[^"']*\.(?:mp4))`);
273 export function isImage(url: string) {
274 return imageRegex.test(url);
277 export function isVideo(url: string) {
278 return videoRegex.test(url);
281 export function validURL(str: string) {
282 return !!new URL(str);
285 export function communityRSSUrl(actorId: string, sort: string): string {
286 let url = new URL(actorId);
287 return `${url.origin}/feeds${url.pathname}.xml?sort=${sort}`;
290 export function validEmail(email: string) {
291 let re = /^(([^\s"(),.:;<>@[\\\]]+(\.[^\s"(),.:;<>@[\\\]]+)*)|(".+"))@((\[(?:\d{1,3}\.){3}\d{1,3}])|(([\dA-Za-z\-]+\.)+[A-Za-z]{2,}))$/;
292 return re.test(String(email).toLowerCase());
295 export function capitalizeFirstLetter(str: string): string {
296 return str.charAt(0).toUpperCase() + str.slice(1);
299 export function routeSortTypeToEnum(sort: string): SortType {
300 return SortType[sort];
303 export function listingTypeFromNum(type_: number): ListingType {
304 return Object.values(ListingType)[type_];
307 export function sortTypeFromNum(type_: number): SortType {
308 return Object.values(SortType)[type_];
311 export function routeListingTypeToEnum(type: string): ListingType {
312 return ListingType[type];
315 export function routeDataTypeToEnum(type: string): DataType {
316 return DataType[capitalizeFirstLetter(type)];
319 export function routeSearchTypeToEnum(type: string): SearchType {
320 return SearchType[type];
323 export async function getPageTitle(url: string) {
324 let res = await fetch(`/iframely/oembed?url=${url}`).then(res => res.json());
325 let title = await res.title;
329 export function debounce(func: any, wait = 1000, immediate = false) {
330 // 'private' variable for instance
331 // The returned function will be able to reference this due to closure.
332 // Each call to the returned function will share this common timer.
335 // Calling debounce returns a new anonymous function
337 // reference the context and args for the setTimeout function
338 var args = arguments;
340 // Should the function be called now? If immediate is true
341 // and not already in a timeout then the answer is: Yes
342 var callNow = immediate && !timeout;
344 // This is the basic debounce behaviour where you can call this
345 // function several times, but it will only execute once
346 // [before or after imposing a delay].
347 // Each time the returned function is called, the timer starts over.
348 clearTimeout(timeout);
350 // Set the new timeout
351 timeout = setTimeout(function () {
352 // Inside the timeout function, clear the timeout variable
353 // which will let the next execution run when in 'immediate' mode
356 // Check if the function already ran with the immediate flag
358 // Call the original function with apply
359 // apply lets you define the 'this' object as well as the arguments
360 // (both captured before setTimeout)
361 func.apply(this, args);
365 // Immediate mode and no wait timer? Execute the function..
366 if (callNow) func.apply(this, args);
371 export function getLanguage(override?: string): string {
372 let localUserView = UserService.Instance.localUserView;
375 (localUserView?.local_user.lang
376 ? localUserView.local_user.lang
379 if (lang == "browser" && isBrowser()) {
380 return getBrowserLanguage();
386 export function getBrowserLanguage(): string {
387 return navigator.language;
390 export function getMomentLanguage(): string {
391 let lang = getLanguage();
392 if (lang.startsWith("zh")) {
394 } else if (lang.startsWith("sv")) {
396 } else if (lang.startsWith("fr")) {
398 } else if (lang.startsWith("de")) {
400 } else if (lang.startsWith("ru")) {
402 } else if (lang.startsWith("es")) {
404 } else if (lang.startsWith("eo")) {
406 } else if (lang.startsWith("nl")) {
408 } else if (lang.startsWith("it")) {
410 } else if (lang.startsWith("fi")) {
412 } else if (lang.startsWith("ca")) {
414 } else if (lang.startsWith("fa")) {
416 } else if (lang.startsWith("pl")) {
418 } else if (lang.startsWith("pt")) {
420 } else if (lang.startsWith("ja")) {
422 } else if (lang.startsWith("ka")) {
424 } else if (lang.startsWith("hi")) {
426 } else if (lang.startsWith("el")) {
428 } else if (lang.startsWith("eu")) {
430 } else if (lang.startsWith("gl")) {
432 } else if (lang.startsWith("tr")) {
434 } else if (lang.startsWith("hu")) {
436 } else if (lang.startsWith("uk")) {
438 } else if (lang.startsWith("sq")) {
440 } else if (lang.startsWith("km")) {
442 } else if (lang.startsWith("ga")) {
444 } else if (lang.startsWith("sr")) {
446 } else if (lang.startsWith("ko")) {
448 } else if (lang.startsWith("da")) {
450 } else if (lang.startsWith("oc")) {
452 } else if (lang.startsWith("hr")) {
454 } else if (lang.startsWith("th")) {
456 } else if (lang.startsWith("bg")) {
464 export function setTheme(theme: string, forceReload = false) {
468 if (theme === "browser" && !forceReload) {
471 // This is only run on a force reload
472 if (theme == "browser") {
476 // Unload all the other themes
477 for (var i = 0; i < themes.length; i++) {
478 let styleSheet = document.getElementById(themes[i]);
480 styleSheet.setAttribute("disabled", "disabled");
485 .getElementById("default-light")
486 ?.setAttribute("disabled", "disabled");
487 document.getElementById("default-dark")?.setAttribute("disabled", "disabled");
489 // Load the theme dynamically
490 let cssLoc = `/static/assets/css/themes/${theme}.min.css`;
491 loadCss(theme, cssLoc);
492 document.getElementById(theme).removeAttribute("disabled");
495 export function loadCss(id: string, loc: string) {
496 if (!document.getElementById(id)) {
497 var head = document.getElementsByTagName("head")[0];
498 var link = document.createElement("link");
500 link.rel = "stylesheet";
501 link.type = "text/css";
504 head.appendChild(link);
508 export function objectFlip(obj: any) {
510 Object.keys(obj).forEach(key => {
516 export function showAvatars(): boolean {
518 UserService.Instance.localUserView?.local_user.show_avatars ||
519 !UserService.Instance.localUserView
523 export function isCakeDay(published: string): boolean {
524 // moment(undefined) or moment.utc(undefined) returns the current date/time
525 // moment(null) or moment.utc(null) returns null
526 const createDate = moment.utc(published || null).local();
527 const currentDate = moment(new Date());
530 createDate.date() === currentDate.date() &&
531 createDate.month() === currentDate.month() &&
532 createDate.year() !== currentDate.year()
536 export function toast(text: string, background = "success") {
538 let backgroundColor = `var(--${background})`;
541 backgroundColor: backgroundColor,
548 export function pictrsDeleteToast(
549 clickToDeleteText: string,
550 deletePictureText: string,
554 let backgroundColor = `var(--light)`;
555 let toast = Toastify({
556 text: clickToDeleteText,
557 backgroundColor: backgroundColor,
563 window.location.replace(deleteUrl);
564 alert(deletePictureText);
573 interface NotifyInfo {
580 export function messageToastify(info: NotifyInfo, router: any) {
582 let htmlBody = info.body ? md.render(info.body) : "";
583 let backgroundColor = `var(--light)`;
585 let toast = Toastify({
586 text: `${htmlBody}<br />${info.name}`,
587 avatar: info.icon ? info.icon : null,
588 backgroundColor: backgroundColor,
589 className: "text-dark",
598 router.history.push(info.link);
605 export function notifyPost(post_view: PostView, router: any) {
606 let info: NotifyInfo = {
607 name: post_view.community.name,
608 icon: post_view.community.icon,
609 link: `/post/${post_view.post.id}`,
610 body: post_view.post.name,
612 notify(info, router);
615 export function notifyComment(comment_view: CommentView, router: any) {
616 let info: NotifyInfo = {
617 name: comment_view.creator.name,
618 icon: comment_view.creator.avatar,
619 link: `/post/${comment_view.post.id}/comment/${comment_view.comment.id}`,
620 body: comment_view.comment.content,
622 notify(info, router);
625 export function notifyPrivateMessage(pmv: PrivateMessageView, router: any) {
626 let info: NotifyInfo = {
627 name: pmv.creator.name,
628 icon: pmv.creator.avatar,
630 body: pmv.private_message.content,
632 notify(info, router);
635 function notify(info: NotifyInfo, router: any) {
636 messageToastify(info, router);
638 if (Notification.permission !== "granted") Notification.requestPermission();
640 var notification = new Notification(info.name, {
645 notification.onclick = (ev: Event): any => {
647 router.history.push(info.link);
652 export function setupTribute() {
654 noMatchTemplate: function () {
661 menuItemTemplate: (item: any) => {
662 let shortName = `:${item.original.key}:`;
663 return `${item.original.val} ${shortName}`;
665 selectTemplate: (item: any) => {
666 return `${item.original.val}`;
668 values: Object.entries(emojiShortName).map(e => {
669 return { key: e[1], val: e[0] };
672 autocompleteMode: true,
674 // menuItemLimit: mentionDropdownFetchLimit,
675 menuShowMinLength: 2,
680 selectTemplate: (item: any) => {
681 let it: PersonTribute = item.original;
682 return `[${it.key}](${it.view.person.actor_id})`;
684 values: (text: string, cb: (persons: PersonTribute[]) => any) => {
685 personSearch(text, (persons: PersonTribute[]) => cb(persons));
688 autocompleteMode: true,
690 // menuItemLimit: mentionDropdownFetchLimit,
691 menuShowMinLength: 2,
697 selectTemplate: (item: any) => {
698 let it: CommunityTribute = item.original;
699 return `[${it.key}](${it.view.community.actor_id})`;
701 values: (text: string, cb: any) => {
702 communitySearch(text, (communities: CommunityTribute[]) =>
707 autocompleteMode: true,
709 // menuItemLimit: mentionDropdownFetchLimit,
710 menuShowMinLength: 2,
716 var tippyInstance: any;
718 tippyInstance = tippy("[data-tippy-content]");
721 export function setupTippy() {
723 tippyInstance.forEach((e: any) => e.destroy());
724 tippyInstance = tippy("[data-tippy-content]", {
726 // Display on "long press"
727 touch: ["hold", 500],
732 interface PersonTribute {
734 view: PersonViewSafe;
737 function personSearch(text: string, cb: (persons: PersonTribute[]) => any) {
741 type_: SearchType.Users,
742 sort: SortType.TopAll,
744 limit: mentionDropdownFetchLimit,
745 auth: authField(false),
748 WebSocketService.Instance.send(wsClient.search(form));
750 let personSub = WebSocketService.Instance.subject.subscribe(
752 let res = wsJsonToRes(msg);
753 if (res.op == UserOperation.Search) {
754 let data = res.data as SearchResponse;
755 let persons: PersonTribute[] = data.users.map(pv => {
756 let tribute: PersonTribute = {
757 key: `@${pv.person.name}@${hostname(pv.person.actor_id)}`,
763 personSub.unsubscribe();
766 err => console.error(err),
767 () => console.log("complete")
774 interface CommunityTribute {
779 function communitySearch(
781 cb: (communities: CommunityTribute[]) => any
786 type_: SearchType.Communities,
787 sort: SortType.TopAll,
789 limit: mentionDropdownFetchLimit,
790 auth: authField(false),
793 WebSocketService.Instance.send(wsClient.search(form));
795 let communitySub = WebSocketService.Instance.subject.subscribe(
797 let res = wsJsonToRes(msg);
798 if (res.op == UserOperation.Search) {
799 let data = res.data as SearchResponse;
800 let communities: CommunityTribute[] = data.communities.map(cv => {
801 let tribute: CommunityTribute = {
802 key: `!${cv.community.name}@${hostname(cv.community.actor_id)}`,
808 communitySub.unsubscribe();
811 err => console.error(err),
812 () => console.log("complete")
819 export function getListingTypeFromProps(props: any): ListingType {
820 return props.match.params.listing_type
821 ? routeListingTypeToEnum(props.match.params.listing_type)
822 : UserService.Instance.localUserView
823 ? Object.values(ListingType)[
824 UserService.Instance.localUserView.local_user.default_listing_type
829 // TODO might need to add a user setting for this too
830 export function getDataTypeFromProps(props: any): DataType {
831 return props.match.params.data_type
832 ? routeDataTypeToEnum(props.match.params.data_type)
836 export function getSortTypeFromProps(props: any): SortType {
837 return props.match.params.sort
838 ? routeSortTypeToEnum(props.match.params.sort)
839 : UserService.Instance.localUserView
840 ? Object.values(SortType)[
841 UserService.Instance.localUserView.local_user.default_sort_type
846 export function getPageFromProps(props: any): number {
847 return props.match.params.page ? Number(props.match.params.page) : 1;
850 export function getRecipientIdFromProps(props: any): number {
851 return props.match.params.recipient_id
852 ? Number(props.match.params.recipient_id)
856 export function getIdFromProps(props: any): number {
857 return Number(props.match.params.id);
860 export function getCommentIdFromProps(props: any): number {
861 return Number(props.match.params.comment_id);
864 export function getUsernameFromProps(props: any): string {
865 return props.match.params.username;
868 export function editCommentRes(data: CommentView, comments: CommentView[]) {
869 let found = comments.find(c => c.comment.id == data.comment.id);
871 found.comment.content = data.comment.content;
872 found.comment.updated = data.comment.updated;
873 found.comment.removed = data.comment.removed;
874 found.comment.deleted = data.comment.deleted;
875 found.counts.upvotes = data.counts.upvotes;
876 found.counts.downvotes = data.counts.downvotes;
877 found.counts.score = data.counts.score;
881 export function saveCommentRes(data: CommentView, comments: CommentView[]) {
882 let found = comments.find(c => c.comment.id == data.comment.id);
884 found.saved = data.saved;
888 export function createCommentLikeRes(
890 comments: CommentView[]
892 let found = comments.find(c => c.comment.id === data.comment.id);
894 found.counts.score = data.counts.score;
895 found.counts.upvotes = data.counts.upvotes;
896 found.counts.downvotes = data.counts.downvotes;
897 if (data.my_vote !== null) {
898 found.my_vote = data.my_vote;
903 export function createPostLikeFindRes(data: PostView, posts: PostView[]) {
904 let found = posts.find(p => p.post.id == data.post.id);
906 createPostLikeRes(data, found);
910 export function createPostLikeRes(data: PostView, post_view: PostView) {
912 post_view.counts.score = data.counts.score;
913 post_view.counts.upvotes = data.counts.upvotes;
914 post_view.counts.downvotes = data.counts.downvotes;
915 if (data.my_vote !== null) {
916 post_view.my_vote = data.my_vote;
921 export function editPostFindRes(data: PostView, posts: PostView[]) {
922 let found = posts.find(p => p.post.id == data.post.id);
924 editPostRes(data, found);
928 export function editPostRes(data: PostView, post: PostView) {
930 post.post.url = data.post.url;
931 post.post.name = data.post.name;
932 post.post.nsfw = data.post.nsfw;
933 post.post.deleted = data.post.deleted;
934 post.post.removed = data.post.removed;
935 post.post.stickied = data.post.stickied;
936 post.post.body = data.post.body;
937 post.post.locked = data.post.locked;
938 post.saved = data.saved;
942 export function commentsToFlatNodes(comments: CommentView[]): CommentNodeI[] {
943 let nodes: CommentNodeI[] = [];
944 for (let comment of comments) {
945 nodes.push({ comment_view: comment });
950 function commentSort(tree: CommentNodeI[], sort: CommentSortType) {
951 // First, put removed and deleted comments at the bottom, then do your other sorts
952 if (sort == CommentSortType.Top) {
955 +a.comment_view.comment.removed - +b.comment_view.comment.removed ||
956 +a.comment_view.comment.deleted - +b.comment_view.comment.deleted ||
957 b.comment_view.counts.score - a.comment_view.counts.score
959 } else if (sort == CommentSortType.New) {
962 +a.comment_view.comment.removed - +b.comment_view.comment.removed ||
963 +a.comment_view.comment.deleted - +b.comment_view.comment.deleted ||
964 b.comment_view.comment.published.localeCompare(
965 a.comment_view.comment.published
968 } else if (sort == CommentSortType.Old) {
971 +a.comment_view.comment.removed - +b.comment_view.comment.removed ||
972 +a.comment_view.comment.deleted - +b.comment_view.comment.deleted ||
973 a.comment_view.comment.published.localeCompare(
974 b.comment_view.comment.published
977 } else if (sort == CommentSortType.Hot) {
980 +a.comment_view.comment.removed - +b.comment_view.comment.removed ||
981 +a.comment_view.comment.deleted - +b.comment_view.comment.deleted ||
982 hotRankComment(b.comment_view) - hotRankComment(a.comment_view)
986 // Go through the children recursively
987 for (let node of tree) {
989 commentSort(node.children, sort);
994 export function commentSortSortType(tree: CommentNodeI[], sort: SortType) {
995 commentSort(tree, convertCommentSortType(sort));
998 function convertCommentSortType(sort: SortType): CommentSortType {
1000 sort == SortType.TopAll ||
1001 sort == SortType.TopDay ||
1002 sort == SortType.TopWeek ||
1003 sort == SortType.TopMonth ||
1004 sort == SortType.TopYear
1006 return CommentSortType.Top;
1007 } else if (sort == SortType.New) {
1008 return CommentSortType.New;
1009 } else if (sort == SortType.Hot || sort == SortType.Active) {
1010 return CommentSortType.Hot;
1012 return CommentSortType.Hot;
1016 export function buildCommentsTree(
1017 comments: CommentView[],
1018 commentSortType: CommentSortType
1020 let map = new Map<number, CommentNodeI>();
1021 for (let comment_view of comments) {
1022 let node: CommentNodeI = {
1023 comment_view: comment_view,
1026 map.set(comment_view.comment.id, { ...node });
1028 let tree: CommentNodeI[] = [];
1029 for (let comment_view of comments) {
1030 let child = map.get(comment_view.comment.id);
1031 if (comment_view.comment.parent_id) {
1032 let parent_ = map.get(comment_view.comment.parent_id);
1033 parent_.children.push(child);
1041 commentSort(tree, commentSortType);
1046 function setDepth(node: CommentNodeI, i = 0) {
1047 for (let child of node.children) {
1049 setDepth(child, i + 1);
1053 export function insertCommentIntoTree(tree: CommentNodeI[], cv: CommentView) {
1054 // Building a fake node to be used for later
1055 let node: CommentNodeI = {
1061 if (cv.comment.parent_id) {
1062 let parentComment = searchCommentTree(tree, cv.comment.parent_id);
1063 if (parentComment) {
1064 node.depth = parentComment.depth + 1;
1065 parentComment.children.unshift(node);
1072 export function searchCommentTree(
1073 tree: CommentNodeI[],
1076 for (let node of tree) {
1077 if (node.comment_view.comment.id === id) {
1081 for (const child of node.children) {
1082 const res = searchCommentTree([child], id);
1092 export const colorList: string[] = [
1101 function hsl(num: number) {
1102 return `hsla(${num}, 35%, 50%, 1)`;
1105 export function previewLines(
1114 // Use lines * 2 because markdown requires 2 lines
1115 .slice(0, maxLines * 2)
1120 export function hostname(url: string): string {
1121 let cUrl = new URL(url);
1122 return cUrl.port ? `${cUrl.hostname}:${cUrl.port}` : `${cUrl.hostname}`;
1125 export function validTitle(title?: string): boolean {
1126 // Initial title is null, minimum length is taken care of by textarea's minLength={3}
1127 if (title === null || title.length < 3) return true;
1129 const regex = new RegExp(/.*\S.*/, "g");
1131 return regex.test(title);
1134 export function siteBannerCss(banner: string): string {
1136 background-image: linear-gradient( rgba(0, 0, 0, 0.8), rgba(0, 0, 0, 0.8) ) ,url("${banner}"); \
1137 background-attachment: fixed; \
1138 background-position: top; \
1139 background-repeat: no-repeat; \
1140 background-size: 100% cover; \
1143 max-height: 100vh; \
1147 export function isBrowser() {
1148 return typeof window !== "undefined";
1151 export function setIsoData(context: any): IsoData {
1152 let isoData: IsoData = isBrowser()
1154 : context.router.staticContext;
1158 export function wsSubscribe(parseMessage: any): Subscription {
1160 return WebSocketService.Instance.subject
1161 .pipe(retryWhen(errors => errors.pipe(delay(3000), take(10))))
1163 msg => parseMessage(msg),
1164 err => console.error(err),
1165 () => console.log("complete")
1172 export function setOptionalAuth(obj: any, auth = UserService.Instance.auth) {
1178 export function authField(
1180 auth = UserService.Instance.auth
1182 if (auth == null && throwErr) {
1183 toast(i18n.t("not_logged_in"), "danger");
1184 throw "Not logged in";
1190 moment.updateLocale("en", {
1211 export function saveScrollPosition(context: any) {
1212 let path: string = context.router.route.location.pathname;
1213 let y = window.scrollY;
1214 sessionStorage.setItem(`scrollPosition_${path}`, y.toString());
1217 export function restoreScrollPosition(context: any) {
1218 let path: string = context.router.route.location.pathname;
1219 let y = Number(sessionStorage.getItem(`scrollPosition_${path}`));
1220 window.scrollTo(0, y);