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";
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/sponsors";
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 = [
94 { code: "ca", name: "Català" },
95 { code: "en", name: "English" },
96 { code: "el", name: "Ελληνικά" },
97 { code: "eu", name: "Euskara" },
98 { code: "eo", name: "Esperanto" },
99 { code: "es", name: "Español" },
100 { code: "da", name: "Dansk" },
101 { code: "de", name: "Deutsch" },
102 { code: "ga", name: "Gaeilge" },
103 { code: "gl", name: "Galego" },
104 { code: "hr", name: "hrvatski" },
105 { code: "hu", name: "Magyar Nyelv" },
106 { code: "ka", name: "ქართული ენა" },
107 { code: "ko", name: "한국어" },
108 { code: "km", name: "ភាសាខ្មែរ" },
109 { code: "hi", name: "मानक हिन्दी" },
110 { code: "fa", name: "فارسی" },
111 { code: "ja", name: "日本語" },
112 { code: "oc", name: "Occitan" },
113 { code: "pl", name: "Polski" },
114 { code: "pt_BR", name: "Português Brasileiro" },
115 { code: "zh", name: "中文" },
116 { code: "fi", name: "Suomi" },
117 { code: "fr", name: "Français" },
118 { code: "sv", name: "Svenska" },
119 { code: "sq", name: "Shqip" },
120 { code: "sr_Latn", name: "srpski" },
121 { code: "th", name: "ภาษาไทย" },
122 { code: "tr", name: "Türkçe" },
123 { code: "uk", name: "Українська Mова" },
124 { code: "ru", name: "Русский" },
125 { code: "nl", name: "Nederlands" },
126 { code: "it", name: "Italiano" },
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 user: UserSafeSettings,
247 // You can do moderator actions only on the mods added after you.
249 let yourIndex = modIds.findIndex(id => id == user.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 user = UserService.Instance.user;
371 let lang = override || (user && user.lang ? user.lang : "browser");
373 if (lang == "browser" && isBrowser()) {
374 return getBrowserLanguage();
381 export function getBrowserLanguage(): string {
382 return navigator.language;
385 export function getMomentLanguage(): string {
386 let lang = getLanguage();
387 if (lang.startsWith("zh")) {
389 } else if (lang.startsWith("sv")) {
391 } else if (lang.startsWith("fr")) {
393 } else if (lang.startsWith("de")) {
395 } else if (lang.startsWith("ru")) {
397 } else if (lang.startsWith("es")) {
399 } else if (lang.startsWith("eo")) {
401 } else if (lang.startsWith("nl")) {
403 } else if (lang.startsWith("it")) {
405 } else if (lang.startsWith("fi")) {
407 } else if (lang.startsWith("ca")) {
409 } else if (lang.startsWith("fa")) {
411 } else if (lang.startsWith("pl")) {
413 } else if (lang.startsWith("pt")) {
415 } else if (lang.startsWith("ja")) {
417 } else if (lang.startsWith("ka")) {
419 } else if (lang.startsWith("hi")) {
421 } else if (lang.startsWith("el")) {
423 } else if (lang.startsWith("eu")) {
425 } else if (lang.startsWith("gl")) {
427 } else if (lang.startsWith("tr")) {
429 } else if (lang.startsWith("hu")) {
431 } else if (lang.startsWith("uk")) {
433 } else if (lang.startsWith("sq")) {
435 } else if (lang.startsWith("km")) {
437 } else if (lang.startsWith("ga")) {
439 } else if (lang.startsWith("sr")) {
441 } else if (lang.startsWith("ko")) {
443 } else if (lang.startsWith("da")) {
445 } else if (lang.startsWith("oc")) {
447 } else if (lang.startsWith("hr")) {
449 } else if (lang.startsWith("th")) {
457 export function setTheme(theme: string, forceReload = false) {
461 if (theme === "browser" && !forceReload) {
464 // This is only run on a force reload
465 if (theme == "browser") {
469 // Unload all the other themes
470 for (var i = 0; i < themes.length; i++) {
471 let styleSheet = document.getElementById(themes[i]);
473 styleSheet.setAttribute("disabled", "disabled");
478 .getElementById("default-light")
479 ?.setAttribute("disabled", "disabled");
480 document.getElementById("default-dark")?.setAttribute("disabled", "disabled");
482 // Load the theme dynamically
483 let cssLoc = `/static/assets/css/themes/${theme}.min.css`;
484 loadCss(theme, cssLoc);
485 document.getElementById(theme).removeAttribute("disabled");
488 export function loadCss(id: string, loc: string) {
489 if (!document.getElementById(id)) {
490 var head = document.getElementsByTagName("head")[0];
491 var link = document.createElement("link");
493 link.rel = "stylesheet";
494 link.type = "text/css";
497 head.appendChild(link);
501 export function objectFlip(obj: any) {
503 Object.keys(obj).forEach(key => {
509 export function showAvatars(): boolean {
511 (UserService.Instance.user && UserService.Instance.user.show_avatars) ||
512 !UserService.Instance.user
516 export function isCakeDay(published: string): boolean {
517 // moment(undefined) or moment.utc(undefined) returns the current date/time
518 // moment(null) or moment.utc(null) returns null
519 const userCreationDate = moment.utc(published || null).local();
520 const currentDate = moment(new Date());
523 userCreationDate.date() === currentDate.date() &&
524 userCreationDate.month() === currentDate.month() &&
525 userCreationDate.year() !== currentDate.year()
529 export function toast(text: string, background = "success") {
531 let backgroundColor = `var(--${background})`;
534 backgroundColor: backgroundColor,
541 export function pictrsDeleteToast(
542 clickToDeleteText: string,
543 deletePictureText: string,
547 let backgroundColor = `var(--light)`;
548 let toast = Toastify({
549 text: clickToDeleteText,
550 backgroundColor: backgroundColor,
556 window.location.replace(deleteUrl);
557 alert(deletePictureText);
566 interface NotifyInfo {
573 export function messageToastify(info: NotifyInfo, router: any) {
575 let htmlBody = info.body ? md.render(info.body) : "";
576 let backgroundColor = `var(--light)`;
578 let toast = Toastify({
579 text: `${htmlBody}<br />${info.name}`,
580 avatar: info.icon ? info.icon : null,
581 backgroundColor: backgroundColor,
582 className: "text-dark",
590 router.history.push(info.link);
597 export function notifyPost(post_view: PostView, router: any) {
598 let info: NotifyInfo = {
599 name: post_view.community.name,
600 icon: post_view.community.icon,
601 link: `/post/${post_view.post.id}`,
602 body: post_view.post.name,
604 notify(info, router);
607 export function notifyComment(comment_view: CommentView, router: any) {
608 let info: NotifyInfo = {
609 name: comment_view.creator.name,
610 icon: comment_view.creator.avatar,
611 link: `/post/${comment_view.post.id}/comment/${comment_view.comment.id}`,
612 body: comment_view.comment.content,
614 notify(info, router);
617 export function notifyPrivateMessage(pmv: PrivateMessageView, router: any) {
618 let info: NotifyInfo = {
619 name: pmv.creator.name,
620 icon: pmv.creator.avatar,
622 body: pmv.private_message.content,
624 notify(info, router);
627 function notify(info: NotifyInfo, router: any) {
628 messageToastify(info, router);
630 if (Notification.permission !== "granted") Notification.requestPermission();
632 var notification = new Notification(info.name, {
637 notification.onclick = (ev: Event): any => {
639 router.history.push(info.link);
644 export function setupTribute() {
646 noMatchTemplate: function () {
653 menuItemTemplate: (item: any) => {
654 let shortName = `:${item.original.key}:`;
655 return `${item.original.val} ${shortName}`;
657 selectTemplate: (item: any) => {
658 return `${item.original.val}`;
660 values: Object.entries(emojiShortName).map(e => {
661 return { key: e[1], val: e[0] };
664 autocompleteMode: true,
666 // menuItemLimit: mentionDropdownFetchLimit,
667 menuShowMinLength: 2,
672 selectTemplate: (item: any) => {
673 let it: UserTribute = item.original;
674 return `[${it.key}](${it.view.user.actor_id})`;
676 values: (text: string, cb: (users: UserTribute[]) => any) => {
677 userSearch(text, (users: UserTribute[]) => cb(users));
680 autocompleteMode: true,
682 // menuItemLimit: mentionDropdownFetchLimit,
683 menuShowMinLength: 2,
689 selectTemplate: (item: any) => {
690 let it: CommunityTribute = item.original;
691 return `[${it.key}](${it.view.community.actor_id})`;
693 values: (text: string, cb: any) => {
694 communitySearch(text, (communities: CommunityTribute[]) =>
699 autocompleteMode: true,
701 // menuItemLimit: mentionDropdownFetchLimit,
702 menuShowMinLength: 2,
708 var tippyInstance: any;
710 tippyInstance = tippy("[data-tippy-content]");
713 export function setupTippy() {
715 tippyInstance.forEach((e: any) => e.destroy());
716 tippyInstance = tippy("[data-tippy-content]", {
718 // Display on "long press"
719 touch: ["hold", 500],
724 interface UserTribute {
729 function userSearch(text: string, cb: (users: UserTribute[]) => any) {
733 type_: SearchType.Users,
734 sort: SortType.TopAll,
736 limit: mentionDropdownFetchLimit,
737 auth: authField(false),
740 WebSocketService.Instance.send(wsClient.search(form));
742 let userSub = WebSocketService.Instance.subject.subscribe(
744 let res = wsJsonToRes(msg);
745 if (res.op == UserOperation.Search) {
746 let data = res.data as SearchResponse;
747 let users: UserTribute[] = data.users.map(uv => {
748 let tribute: UserTribute = {
749 key: `@${uv.user.name}@${hostname(uv.user.actor_id)}`,
755 userSub.unsubscribe();
758 err => console.error(err),
759 () => console.log("complete")
766 interface CommunityTribute {
771 function communitySearch(
773 cb: (communities: CommunityTribute[]) => any
778 type_: SearchType.Communities,
779 sort: SortType.TopAll,
781 limit: mentionDropdownFetchLimit,
782 auth: authField(false),
785 WebSocketService.Instance.send(wsClient.search(form));
787 let communitySub = WebSocketService.Instance.subject.subscribe(
789 let res = wsJsonToRes(msg);
790 if (res.op == UserOperation.Search) {
791 let data = res.data as SearchResponse;
792 let communities: CommunityTribute[] = data.communities.map(cv => {
793 let tribute: CommunityTribute = {
794 key: `!${cv.community.name}@${hostname(cv.community.actor_id)}`,
800 communitySub.unsubscribe();
803 err => console.error(err),
804 () => console.log("complete")
811 export function getListingTypeFromProps(props: any): ListingType {
812 return props.match.params.listing_type
813 ? routeListingTypeToEnum(props.match.params.listing_type)
814 : UserService.Instance.user
815 ? Object.values(ListingType)[UserService.Instance.user.default_listing_type]
819 // TODO might need to add a user setting for this too
820 export function getDataTypeFromProps(props: any): DataType {
821 return props.match.params.data_type
822 ? routeDataTypeToEnum(props.match.params.data_type)
826 export function getSortTypeFromProps(props: any): SortType {
827 return props.match.params.sort
828 ? routeSortTypeToEnum(props.match.params.sort)
829 : UserService.Instance.user
830 ? Object.values(SortType)[UserService.Instance.user.default_sort_type]
834 export function getPageFromProps(props: any): number {
835 return props.match.params.page ? Number(props.match.params.page) : 1;
838 export function getRecipientIdFromProps(props: any): number {
839 return props.match.params.recipient_id
840 ? Number(props.match.params.recipient_id)
844 export function getIdFromProps(props: any): number {
845 return Number(props.match.params.id);
848 export function getCommentIdFromProps(props: any): number {
849 return Number(props.match.params.comment_id);
852 export function getUsernameFromProps(props: any): string {
853 return props.match.params.username;
856 export function editCommentRes(data: CommentView, comments: CommentView[]) {
857 let found = comments.find(c => c.comment.id == data.comment.id);
859 found.comment.content = data.comment.content;
860 found.comment.updated = data.comment.updated;
861 found.comment.removed = data.comment.removed;
862 found.comment.deleted = data.comment.deleted;
863 found.counts.upvotes = data.counts.upvotes;
864 found.counts.downvotes = data.counts.downvotes;
865 found.counts.score = data.counts.score;
869 export function saveCommentRes(data: CommentView, comments: CommentView[]) {
870 let found = comments.find(c => c.comment.id == data.comment.id);
872 found.saved = data.saved;
876 export function createCommentLikeRes(
878 comments: CommentView[]
880 let found = comments.find(c => c.comment.id === data.comment.id);
882 found.counts.score = data.counts.score;
883 found.counts.upvotes = data.counts.upvotes;
884 found.counts.downvotes = data.counts.downvotes;
885 if (data.my_vote !== null) {
886 found.my_vote = data.my_vote;
891 export function createPostLikeFindRes(data: PostView, posts: PostView[]) {
892 let found = posts.find(p => p.post.id == data.post.id);
894 createPostLikeRes(data, found);
898 export function createPostLikeRes(data: PostView, post_view: PostView) {
900 post_view.counts.score = data.counts.score;
901 post_view.counts.upvotes = data.counts.upvotes;
902 post_view.counts.downvotes = data.counts.downvotes;
903 if (data.my_vote !== null) {
904 post_view.my_vote = data.my_vote;
909 export function editPostFindRes(data: PostView, posts: PostView[]) {
910 let found = posts.find(p => p.post.id == data.post.id);
912 editPostRes(data, found);
916 export function editPostRes(data: PostView, post: PostView) {
918 post.post.url = data.post.url;
919 post.post.name = data.post.name;
920 post.post.nsfw = data.post.nsfw;
921 post.post.deleted = data.post.deleted;
922 post.post.removed = data.post.removed;
923 post.post.stickied = data.post.stickied;
924 post.post.body = data.post.body;
925 post.post.locked = data.post.locked;
926 post.saved = data.saved;
930 export function commentsToFlatNodes(comments: CommentView[]): CommentNodeI[] {
931 let nodes: CommentNodeI[] = [];
932 for (let comment of comments) {
933 nodes.push({ comment_view: comment });
938 function commentSort(tree: CommentNodeI[], sort: CommentSortType) {
939 // First, put removed and deleted comments at the bottom, then do your other sorts
940 if (sort == CommentSortType.Top) {
943 +a.comment_view.comment.removed - +b.comment_view.comment.removed ||
944 +a.comment_view.comment.deleted - +b.comment_view.comment.deleted ||
945 b.comment_view.counts.score - a.comment_view.counts.score
947 } else if (sort == CommentSortType.New) {
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.comment.published.localeCompare(
953 a.comment_view.comment.published
956 } else if (sort == CommentSortType.Old) {
959 +a.comment_view.comment.removed - +b.comment_view.comment.removed ||
960 +a.comment_view.comment.deleted - +b.comment_view.comment.deleted ||
961 a.comment_view.comment.published.localeCompare(
962 b.comment_view.comment.published
965 } else if (sort == CommentSortType.Hot) {
968 +a.comment_view.comment.removed - +b.comment_view.comment.removed ||
969 +a.comment_view.comment.deleted - +b.comment_view.comment.deleted ||
970 hotRankComment(b.comment_view) - hotRankComment(a.comment_view)
974 // Go through the children recursively
975 for (let node of tree) {
977 commentSort(node.children, sort);
982 export function commentSortSortType(tree: CommentNodeI[], sort: SortType) {
983 commentSort(tree, convertCommentSortType(sort));
986 function convertCommentSortType(sort: SortType): CommentSortType {
988 sort == SortType.TopAll ||
989 sort == SortType.TopDay ||
990 sort == SortType.TopWeek ||
991 sort == SortType.TopMonth ||
992 sort == SortType.TopYear
994 return CommentSortType.Top;
995 } else if (sort == SortType.New) {
996 return CommentSortType.New;
997 } else if (sort == SortType.Hot || sort == SortType.Active) {
998 return CommentSortType.Hot;
1000 return CommentSortType.Hot;
1004 export function buildCommentsTree(
1005 comments: CommentView[],
1006 commentSortType: CommentSortType
1008 let map = new Map<number, CommentNodeI>();
1009 for (let comment_view of comments) {
1010 let node: CommentNodeI = {
1011 comment_view: comment_view,
1014 map.set(comment_view.comment.id, { ...node });
1016 let tree: CommentNodeI[] = [];
1017 for (let comment_view of comments) {
1018 let child = map.get(comment_view.comment.id);
1019 if (comment_view.comment.parent_id) {
1020 let parent_ = map.get(comment_view.comment.parent_id);
1021 parent_.children.push(child);
1029 commentSort(tree, commentSortType);
1034 function setDepth(node: CommentNodeI, i = 0) {
1035 for (let child of node.children) {
1037 setDepth(child, i + 1);
1041 export function insertCommentIntoTree(tree: CommentNodeI[], cv: CommentView) {
1042 // Building a fake node to be used for later
1043 let node: CommentNodeI = {
1049 if (cv.comment.parent_id) {
1050 let parentComment = searchCommentTree(tree, cv.comment.parent_id);
1051 if (parentComment) {
1052 node.depth = parentComment.depth + 1;
1053 parentComment.children.unshift(node);
1060 export function searchCommentTree(
1061 tree: CommentNodeI[],
1064 for (let node of tree) {
1065 if (node.comment_view.comment.id === id) {
1069 for (const child of node.children) {
1070 const res = searchCommentTree([child], id);
1080 export const colorList: string[] = [
1089 function hsl(num: number) {
1090 return `hsla(${num}, 35%, 50%, 1)`;
1093 export function previewLines(
1102 // Use lines * 2 because markdown requires 2 lines
1103 .slice(0, maxLines * 2)
1108 export function hostname(url: string): string {
1109 let cUrl = new URL(url);
1110 return cUrl.port ? `${cUrl.hostname}:${cUrl.port}` : `${cUrl.hostname}`;
1113 export function validTitle(title?: string): boolean {
1114 // Initial title is null, minimum length is taken care of by textarea's minLength={3}
1115 if (title === null || title.length < 3) return true;
1117 const regex = new RegExp(/.*\S.*/, "g");
1119 return regex.test(title);
1122 export function siteBannerCss(banner: string): string {
1124 background-image: linear-gradient( rgba(0, 0, 0, 0.8), rgba(0, 0, 0, 0.8) ) ,url("${banner}"); \
1125 background-attachment: fixed; \
1126 background-position: top; \
1127 background-repeat: no-repeat; \
1128 background-size: 100% cover; \
1131 max-height: 100vh; \
1135 export function isBrowser() {
1136 return typeof window !== "undefined";
1139 export function setIsoData(context: any): IsoData {
1140 let isoData: IsoData = isBrowser()
1142 : context.router.staticContext;
1146 export function wsSubscribe(parseMessage: any): Subscription {
1148 return WebSocketService.Instance.subject
1149 .pipe(retryWhen(errors => errors.pipe(delay(3000), take(10))))
1151 msg => parseMessage(msg),
1152 err => console.error(err),
1153 () => console.log("complete")
1160 export function setOptionalAuth(obj: any, auth = UserService.Instance.auth) {
1166 export function authField(
1168 auth = UserService.Instance.auth
1170 if (auth == null && throwErr) {
1171 toast(i18n.t("not_logged_in"), "danger");
1172 throw "Not logged in";
1178 moment.updateLocale("en", {
1199 export function saveScrollPosition(context: any) {
1200 let path: string = context.router.route.location.pathname;
1201 let y = window.scrollY;
1202 sessionStorage.setItem(`scrollPosition_${path}`, y.toString());
1205 export function restoreScrollPosition(context: any) {
1206 let path: string = context.router.route.location.pathname;
1207 let y = Number(sessionStorage.getItem(`scrollPosition_${path}`));
1208 window.scrollTo(0, y);