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: "tr", name: "Türkçe" },
122 { code: "uk", name: "Українська Mова" },
123 { code: "ru", name: "Русский" },
124 { code: "nl", name: "Nederlands" },
125 { code: "it", name: "Italiano" },
128 export const themes = [
144 const DEFAULT_ALPHABET =
145 "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
147 function getRandomCharFromAlphabet(alphabet: string): string {
148 return alphabet.charAt(Math.floor(Math.random() * alphabet.length));
151 export function randomStr(
152 idDesiredLength = 20,
153 alphabet = DEFAULT_ALPHABET
156 * Create n-long array and map it to random chars from given alphabet.
157 * Then join individual chars as string
159 return Array.from({ length: idDesiredLength })
161 return getRandomCharFromAlphabet(alphabet);
166 export function wsJsonToRes<ResponseType>(
167 msg: WebSocketJsonResponse<ResponseType>
168 ): WebSocketResponse<ResponseType> {
175 export function wsUserOp(msg: any): UserOperation {
176 let opStr: string = msg.op;
177 return UserOperation[opStr];
180 export const md = new markdown_it({
185 .use(markdown_it_sub)
186 .use(markdown_it_sup)
187 .use(markdown_it_container, "spoiler", {
188 validate: function (params: any) {
189 return params.trim().match(/^spoiler\s+(.*)$/);
192 render: function (tokens: any, idx: any) {
193 var m = tokens[idx].info.trim().match(/^spoiler\s+(.*)$/);
195 if (tokens[idx].nesting === 1) {
197 return `<details><summary> ${md.utils.escapeHtml(m[1])} </summary>\n`;
200 return "</details>\n";
205 export function hotRankComment(comment_view: CommentView): number {
206 return hotRank(comment_view.counts.score, comment_view.comment.published);
209 export function hotRankActivePost(post_view: PostView): number {
210 return hotRank(post_view.counts.score, post_view.counts.newest_comment_time);
213 export function hotRankPost(post_view: PostView): number {
214 return hotRank(post_view.counts.score, post_view.post.published);
217 export function hotRank(score: number, timeStr: string): number {
218 // Rank = ScaleFactor * sign(Score) * log(1 + abs(Score)) / (Time + 2)^Gravity
219 let date: Date = new Date(timeStr + "Z"); // Add Z to convert from UTC date
220 let now: Date = new Date();
221 let hoursElapsed: number = (now.getTime() - date.getTime()) / 36e5;
224 (10000 * Math.log10(Math.max(1, 3 + score))) /
225 Math.pow(hoursElapsed + 2, 1.8);
227 // console.log(`Comment: ${comment.content}\nRank: ${rank}\nScore: ${comment.score}\nHours: ${hoursElapsed}`);
232 export function mdToHtml(text: string) {
233 return { __html: md.render(text) };
236 export function getUnixTime(text: string): number {
237 return text ? new Date(text).getTime() / 1000 : undefined;
240 export function canMod(
241 user: UserSafeSettings,
246 // You can do moderator actions only on the mods added after you.
248 let yourIndex = modIds.findIndex(id => id == user.id);
249 if (yourIndex == -1) {
252 // onSelf +1 on mod actions not for yourself, IE ban, remove, etc
253 modIds = modIds.slice(0, yourIndex + (onSelf ? 0 : 1));
254 return !modIds.includes(creator_id);
261 export function isMod(modIds: number[], creator_id: number): boolean {
262 return modIds.includes(creator_id);
265 const imageRegex = new RegExp(
266 /(http)?s?:?(\/\/[^"']*\.(?:jpg|jpeg|gif|png|svg|webp))/
268 const videoRegex = new RegExp(`(http)?s?:?(\/\/[^"']*\.(?:mp4))`);
270 export function isImage(url: string) {
271 return imageRegex.test(url);
274 export function isVideo(url: string) {
275 return videoRegex.test(url);
278 export function validURL(str: string) {
279 return !!new URL(str);
282 export function communityRSSUrl(actorId: string, sort: string): string {
283 let url = new URL(actorId);
284 return `${url.origin}/feeds${url.pathname}.xml?sort=${sort}`;
287 export function validEmail(email: string) {
288 let re = /^(([^\s"(),.:;<>@[\\\]]+(\.[^\s"(),.:;<>@[\\\]]+)*)|(".+"))@((\[(?:\d{1,3}\.){3}\d{1,3}])|(([\dA-Za-z\-]+\.)+[A-Za-z]{2,}))$/;
289 return re.test(String(email).toLowerCase());
292 export function capitalizeFirstLetter(str: string): string {
293 return str.charAt(0).toUpperCase() + str.slice(1);
296 export function routeSortTypeToEnum(sort: string): SortType {
297 return SortType[sort];
300 export function listingTypeFromNum(type_: number): ListingType {
301 return Object.values(ListingType)[type_];
304 export function sortTypeFromNum(type_: number): SortType {
305 return Object.values(SortType)[type_];
308 export function routeListingTypeToEnum(type: string): ListingType {
309 return ListingType[type];
312 export function routeDataTypeToEnum(type: string): DataType {
313 return DataType[capitalizeFirstLetter(type)];
316 export function routeSearchTypeToEnum(type: string): SearchType {
317 return SearchType[type];
320 export async function getPageTitle(url: string) {
321 let res = await fetch(`/iframely/oembed?url=${url}`).then(res => res.json());
322 let title = await res.title;
326 export function debounce(func: any, wait = 1000, immediate = false) {
327 // 'private' variable for instance
328 // The returned function will be able to reference this due to closure.
329 // Each call to the returned function will share this common timer.
332 // Calling debounce returns a new anonymous function
334 // reference the context and args for the setTimeout function
335 var args = arguments;
337 // Should the function be called now? If immediate is true
338 // and not already in a timeout then the answer is: Yes
339 var callNow = immediate && !timeout;
341 // This is the basic debounce behaviour where you can call this
342 // function several times, but it will only execute once
343 // [before or after imposing a delay].
344 // Each time the returned function is called, the timer starts over.
345 clearTimeout(timeout);
347 // Set the new timeout
348 timeout = setTimeout(function () {
349 // Inside the timeout function, clear the timeout variable
350 // which will let the next execution run when in 'immediate' mode
353 // Check if the function already ran with the immediate flag
355 // Call the original function with apply
356 // apply lets you define the 'this' object as well as the arguments
357 // (both captured before setTimeout)
358 func.apply(this, args);
362 // Immediate mode and no wait timer? Execute the function..
363 if (callNow) func.apply(this, args);
368 export function getLanguage(override?: string): string {
369 let user = UserService.Instance.user;
370 let lang = override || (user && user.lang ? user.lang : "browser");
372 if (lang == "browser" && isBrowser()) {
373 return getBrowserLanguage();
380 export function getBrowserLanguage(): string {
381 return navigator.language;
384 export function getMomentLanguage(): string {
385 let lang = getLanguage();
386 if (lang.startsWith("zh")) {
388 } else if (lang.startsWith("sv")) {
390 } else if (lang.startsWith("fr")) {
392 } else if (lang.startsWith("de")) {
394 } else if (lang.startsWith("ru")) {
396 } else if (lang.startsWith("es")) {
398 } else if (lang.startsWith("eo")) {
400 } else if (lang.startsWith("nl")) {
402 } else if (lang.startsWith("it")) {
404 } else if (lang.startsWith("fi")) {
406 } else if (lang.startsWith("ca")) {
408 } else if (lang.startsWith("fa")) {
410 } else if (lang.startsWith("pl")) {
412 } else if (lang.startsWith("pt")) {
414 } else if (lang.startsWith("ja")) {
416 } else if (lang.startsWith("ka")) {
418 } else if (lang.startsWith("hi")) {
420 } else if (lang.startsWith("el")) {
422 } else if (lang.startsWith("eu")) {
424 } else if (lang.startsWith("gl")) {
426 } else if (lang.startsWith("tr")) {
428 } else if (lang.startsWith("hu")) {
430 } else if (lang.startsWith("uk")) {
432 } else if (lang.startsWith("sq")) {
434 } else if (lang.startsWith("km")) {
436 } else if (lang.startsWith("ga")) {
438 } else if (lang.startsWith("sr")) {
440 } else if (lang.startsWith("ko")) {
442 } else if (lang.startsWith("da")) {
444 } else if (lang.startsWith("oc")) {
446 } else if (lang.startsWith("hr")) {
454 export function setTheme(theme: string, forceReload = false) {
458 if (theme === "browser" && !forceReload) {
461 // This is only run on a force reload
462 if (theme == "browser") {
466 // Unload all the other themes
467 for (var i = 0; i < themes.length; i++) {
468 let styleSheet = document.getElementById(themes[i]);
470 styleSheet.setAttribute("disabled", "disabled");
475 .getElementById("default-light")
476 ?.setAttribute("disabled", "disabled");
477 document.getElementById("default-dark")?.setAttribute("disabled", "disabled");
479 // Load the theme dynamically
480 let cssLoc = `/static/assets/css/themes/${theme}.min.css`;
481 loadCss(theme, cssLoc);
482 document.getElementById(theme).removeAttribute("disabled");
485 export function loadCss(id: string, loc: string) {
486 if (!document.getElementById(id)) {
487 var head = document.getElementsByTagName("head")[0];
488 var link = document.createElement("link");
490 link.rel = "stylesheet";
491 link.type = "text/css";
494 head.appendChild(link);
498 export function objectFlip(obj: any) {
500 Object.keys(obj).forEach(key => {
506 export function showAvatars(): boolean {
508 (UserService.Instance.user && UserService.Instance.user.show_avatars) ||
509 !UserService.Instance.user
513 export function isCakeDay(published: string): boolean {
514 // moment(undefined) or moment.utc(undefined) returns the current date/time
515 // moment(null) or moment.utc(null) returns null
516 const userCreationDate = moment.utc(published || null).local();
517 const currentDate = moment(new Date());
520 userCreationDate.date() === currentDate.date() &&
521 userCreationDate.month() === currentDate.month() &&
522 userCreationDate.year() !== currentDate.year()
526 export function toast(text: string, background = "success") {
528 let backgroundColor = `var(--${background})`;
531 backgroundColor: backgroundColor,
538 export function pictrsDeleteToast(
539 clickToDeleteText: string,
540 deletePictureText: string,
544 let backgroundColor = `var(--light)`;
545 let toast = Toastify({
546 text: clickToDeleteText,
547 backgroundColor: backgroundColor,
553 window.location.replace(deleteUrl);
554 alert(deletePictureText);
563 interface NotifyInfo {
570 export function messageToastify(info: NotifyInfo, router: any) {
572 let htmlBody = info.body ? md.render(info.body) : "";
573 let backgroundColor = `var(--light)`;
575 let toast = Toastify({
576 text: `${htmlBody}<br />${info.name}`,
577 avatar: info.icon ? info.icon : null,
578 backgroundColor: backgroundColor,
579 className: "text-dark",
587 router.history.push(info.link);
594 export function notifyPost(post_view: PostView, router: any) {
595 let info: NotifyInfo = {
596 name: post_view.community.name,
597 icon: post_view.community.icon,
598 link: `/post/${post_view.post.id}`,
599 body: post_view.post.name,
601 notify(info, router);
604 export function notifyComment(comment_view: CommentView, router: any) {
605 let info: NotifyInfo = {
606 name: comment_view.creator.name,
607 icon: comment_view.creator.avatar,
608 link: `/post/${comment_view.post.id}/comment/${comment_view.comment.id}`,
609 body: comment_view.comment.content,
611 notify(info, router);
614 export function notifyPrivateMessage(pmv: PrivateMessageView, router: any) {
615 let info: NotifyInfo = {
616 name: pmv.creator.name,
617 icon: pmv.creator.avatar,
619 body: pmv.private_message.content,
621 notify(info, router);
624 function notify(info: NotifyInfo, router: any) {
625 messageToastify(info, router);
627 if (Notification.permission !== "granted") Notification.requestPermission();
629 var notification = new Notification(info.name, {
634 notification.onclick = (ev: Event): any => {
636 router.history.push(info.link);
641 export function setupTribute() {
643 noMatchTemplate: function () {
650 menuItemTemplate: (item: any) => {
651 let shortName = `:${item.original.key}:`;
652 return `${item.original.val} ${shortName}`;
654 selectTemplate: (item: any) => {
655 return `${item.original.val}`;
657 values: Object.entries(emojiShortName).map(e => {
658 return { key: e[1], val: e[0] };
661 autocompleteMode: true,
663 // menuItemLimit: mentionDropdownFetchLimit,
664 menuShowMinLength: 2,
669 selectTemplate: (item: any) => {
670 let it: UserTribute = item.original;
671 return `[${it.key}](${it.view.user.actor_id})`;
673 values: (text: string, cb: (users: UserTribute[]) => any) => {
674 userSearch(text, (users: UserTribute[]) => cb(users));
677 autocompleteMode: true,
679 // menuItemLimit: mentionDropdownFetchLimit,
680 menuShowMinLength: 2,
686 selectTemplate: (item: any) => {
687 let it: CommunityTribute = item.original;
688 return `[${it.key}](${it.view.community.actor_id})`;
690 values: (text: string, cb: any) => {
691 communitySearch(text, (communities: CommunityTribute[]) =>
696 autocompleteMode: true,
698 // menuItemLimit: mentionDropdownFetchLimit,
699 menuShowMinLength: 2,
705 var tippyInstance: any;
707 tippyInstance = tippy("[data-tippy-content]");
710 export function setupTippy() {
712 tippyInstance.forEach((e: any) => e.destroy());
713 tippyInstance = tippy("[data-tippy-content]", {
715 // Display on "long press"
716 touch: ["hold", 500],
721 interface UserTribute {
726 function userSearch(text: string, cb: (users: UserTribute[]) => any) {
730 type_: SearchType.Users,
731 sort: SortType.TopAll,
733 limit: mentionDropdownFetchLimit,
734 auth: authField(false),
737 WebSocketService.Instance.send(wsClient.search(form));
739 let userSub = WebSocketService.Instance.subject.subscribe(
741 let res = wsJsonToRes(msg);
742 if (res.op == UserOperation.Search) {
743 let data = res.data as SearchResponse;
744 let users: UserTribute[] = data.users.map(uv => {
745 let tribute: UserTribute = {
746 key: `@${uv.user.name}@${hostname(uv.user.actor_id)}`,
752 userSub.unsubscribe();
755 err => console.error(err),
756 () => console.log("complete")
763 interface CommunityTribute {
768 function communitySearch(
770 cb: (communities: CommunityTribute[]) => any
775 type_: SearchType.Communities,
776 sort: SortType.TopAll,
778 limit: mentionDropdownFetchLimit,
779 auth: authField(false),
782 WebSocketService.Instance.send(wsClient.search(form));
784 let communitySub = WebSocketService.Instance.subject.subscribe(
786 let res = wsJsonToRes(msg);
787 if (res.op == UserOperation.Search) {
788 let data = res.data as SearchResponse;
789 let communities: CommunityTribute[] = data.communities.map(cv => {
790 let tribute: CommunityTribute = {
791 key: `!${cv.community.name}@${hostname(cv.community.actor_id)}`,
797 communitySub.unsubscribe();
800 err => console.error(err),
801 () => console.log("complete")
808 export function getListingTypeFromProps(props: any): ListingType {
809 return props.match.params.listing_type
810 ? routeListingTypeToEnum(props.match.params.listing_type)
811 : UserService.Instance.user
812 ? Object.values(ListingType)[UserService.Instance.user.default_listing_type]
816 // TODO might need to add a user setting for this too
817 export function getDataTypeFromProps(props: any): DataType {
818 return props.match.params.data_type
819 ? routeDataTypeToEnum(props.match.params.data_type)
823 export function getSortTypeFromProps(props: any): SortType {
824 return props.match.params.sort
825 ? routeSortTypeToEnum(props.match.params.sort)
826 : UserService.Instance.user
827 ? Object.values(SortType)[UserService.Instance.user.default_sort_type]
831 export function getPageFromProps(props: any): number {
832 return props.match.params.page ? Number(props.match.params.page) : 1;
835 export function getRecipientIdFromProps(props: any): number {
836 return props.match.params.recipient_id
837 ? Number(props.match.params.recipient_id)
841 export function getIdFromProps(props: any): number {
842 return Number(props.match.params.id);
845 export function getCommentIdFromProps(props: any): number {
846 return Number(props.match.params.comment_id);
849 export function getUsernameFromProps(props: any): string {
850 return props.match.params.username;
853 export function editCommentRes(data: CommentView, comments: CommentView[]) {
854 let found = comments.find(c => c.comment.id == data.comment.id);
856 found.comment.content = data.comment.content;
857 found.comment.updated = data.comment.updated;
858 found.comment.removed = data.comment.removed;
859 found.comment.deleted = data.comment.deleted;
860 found.counts.upvotes = data.counts.upvotes;
861 found.counts.downvotes = data.counts.downvotes;
862 found.counts.score = data.counts.score;
866 export function saveCommentRes(data: CommentView, comments: CommentView[]) {
867 let found = comments.find(c => c.comment.id == data.comment.id);
869 found.saved = data.saved;
873 export function createCommentLikeRes(
875 comments: CommentView[]
877 let found = comments.find(c => c.comment.id === data.comment.id);
879 found.counts.score = data.counts.score;
880 found.counts.upvotes = data.counts.upvotes;
881 found.counts.downvotes = data.counts.downvotes;
882 if (data.my_vote !== null) {
883 found.my_vote = data.my_vote;
888 export function createPostLikeFindRes(data: PostView, posts: PostView[]) {
889 let found = posts.find(p => p.post.id == data.post.id);
891 createPostLikeRes(data, found);
895 export function createPostLikeRes(data: PostView, post_view: PostView) {
897 post_view.counts.score = data.counts.score;
898 post_view.counts.upvotes = data.counts.upvotes;
899 post_view.counts.downvotes = data.counts.downvotes;
900 if (data.my_vote !== null) {
901 post_view.my_vote = data.my_vote;
906 export function editPostFindRes(data: PostView, posts: PostView[]) {
907 let found = posts.find(p => p.post.id == data.post.id);
909 editPostRes(data, found);
913 export function editPostRes(data: PostView, post: PostView) {
915 post.post.url = data.post.url;
916 post.post.name = data.post.name;
917 post.post.nsfw = data.post.nsfw;
918 post.post.deleted = data.post.deleted;
919 post.post.removed = data.post.removed;
920 post.post.stickied = data.post.stickied;
921 post.post.body = data.post.body;
922 post.post.locked = data.post.locked;
923 post.saved = data.saved;
927 export function commentsToFlatNodes(comments: CommentView[]): CommentNodeI[] {
928 let nodes: CommentNodeI[] = [];
929 for (let comment of comments) {
930 nodes.push({ comment_view: comment });
935 function commentSort(tree: CommentNodeI[], sort: CommentSortType) {
936 // First, put removed and deleted comments at the bottom, then do your other sorts
937 if (sort == CommentSortType.Top) {
940 +a.comment_view.comment.removed - +b.comment_view.comment.removed ||
941 +a.comment_view.comment.deleted - +b.comment_view.comment.deleted ||
942 b.comment_view.counts.score - a.comment_view.counts.score
944 } else if (sort == CommentSortType.New) {
947 +a.comment_view.comment.removed - +b.comment_view.comment.removed ||
948 +a.comment_view.comment.deleted - +b.comment_view.comment.deleted ||
949 b.comment_view.comment.published.localeCompare(
950 a.comment_view.comment.published
953 } else if (sort == CommentSortType.Old) {
956 +a.comment_view.comment.removed - +b.comment_view.comment.removed ||
957 +a.comment_view.comment.deleted - +b.comment_view.comment.deleted ||
958 a.comment_view.comment.published.localeCompare(
959 b.comment_view.comment.published
962 } else if (sort == CommentSortType.Hot) {
965 +a.comment_view.comment.removed - +b.comment_view.comment.removed ||
966 +a.comment_view.comment.deleted - +b.comment_view.comment.deleted ||
967 hotRankComment(b.comment_view) - hotRankComment(a.comment_view)
971 // Go through the children recursively
972 for (let node of tree) {
974 commentSort(node.children, sort);
979 export function commentSortSortType(tree: CommentNodeI[], sort: SortType) {
980 commentSort(tree, convertCommentSortType(sort));
983 function convertCommentSortType(sort: SortType): CommentSortType {
985 sort == SortType.TopAll ||
986 sort == SortType.TopDay ||
987 sort == SortType.TopWeek ||
988 sort == SortType.TopMonth ||
989 sort == SortType.TopYear
991 return CommentSortType.Top;
992 } else if (sort == SortType.New) {
993 return CommentSortType.New;
994 } else if (sort == SortType.Hot || sort == SortType.Active) {
995 return CommentSortType.Hot;
997 return CommentSortType.Hot;
1001 export function buildCommentsTree(
1002 comments: CommentView[],
1003 commentSortType: CommentSortType
1005 let map = new Map<number, CommentNodeI>();
1006 for (let comment_view of comments) {
1007 let node: CommentNodeI = {
1008 comment_view: comment_view,
1011 map.set(comment_view.comment.id, { ...node });
1013 let tree: CommentNodeI[] = [];
1014 for (let comment_view of comments) {
1015 let child = map.get(comment_view.comment.id);
1016 if (comment_view.comment.parent_id) {
1017 let parent_ = map.get(comment_view.comment.parent_id);
1018 parent_.children.push(child);
1026 commentSort(tree, commentSortType);
1031 function setDepth(node: CommentNodeI, i = 0) {
1032 for (let child of node.children) {
1034 setDepth(child, i + 1);
1038 export function insertCommentIntoTree(tree: CommentNodeI[], cv: CommentView) {
1039 // Building a fake node to be used for later
1040 let node: CommentNodeI = {
1046 if (cv.comment.parent_id) {
1047 let parentComment = searchCommentTree(tree, cv.comment.parent_id);
1048 if (parentComment) {
1049 node.depth = parentComment.depth + 1;
1050 parentComment.children.unshift(node);
1057 export function searchCommentTree(
1058 tree: CommentNodeI[],
1061 for (let node of tree) {
1062 if (node.comment_view.comment.id === id) {
1066 for (const child of node.children) {
1067 const res = searchCommentTree([child], id);
1077 export const colorList: string[] = [
1086 function hsl(num: number) {
1087 return `hsla(${num}, 35%, 50%, 1)`;
1090 export function previewLines(
1099 // Use lines * 2 because markdown requires 2 lines
1100 .slice(0, maxLines * 2)
1105 export function hostname(url: string): string {
1106 let cUrl = new URL(url);
1107 return cUrl.port ? `${cUrl.hostname}:${cUrl.port}` : `${cUrl.hostname}`;
1110 export function validTitle(title?: string): boolean {
1111 // Initial title is null, minimum length is taken care of by textarea's minLength={3}
1112 if (title === null || title.length < 3) return true;
1114 const regex = new RegExp(/.*\S.*/, "g");
1116 return regex.test(title);
1119 export function siteBannerCss(banner: string): string {
1121 background-image: linear-gradient( rgba(0, 0, 0, 0.8), rgba(0, 0, 0, 0.8) ) ,url("${banner}"); \
1122 background-attachment: fixed; \
1123 background-position: top; \
1124 background-repeat: no-repeat; \
1125 background-size: 100% cover; \
1128 max-height: 100vh; \
1132 export function isBrowser() {
1133 return typeof window !== "undefined";
1136 export function setIsoData(context: any): IsoData {
1137 let isoData: IsoData = isBrowser()
1139 : context.router.staticContext;
1143 export function wsSubscribe(parseMessage: any): Subscription {
1145 return WebSocketService.Instance.subject
1146 .pipe(retryWhen(errors => errors.pipe(delay(3000), take(10))))
1148 msg => parseMessage(msg),
1149 err => console.error(err),
1150 () => console.log("complete")
1157 export function setOptionalAuth(obj: any, auth = UserService.Instance.auth) {
1163 export function authField(
1165 auth = UserService.Instance.auth
1167 if (auth == null && throwErr) {
1168 toast(i18n.t("not_logged_in"), "danger");
1169 throw "Not logged in";
1175 moment.updateLocale("en", {
1196 export function saveScrollPosition(context: any) {
1197 let path: string = context.router.route.location.pathname;
1198 let y = window.scrollY;
1199 sessionStorage.setItem(`scrollPosition_${path}`, y.toString());
1202 export function restoreScrollPosition(context: any) {
1203 let path: string = context.router.route.location.pathname;
1204 let y = Number(sessionStorage.getItem(`scrollPosition_${path}`));
1205 window.scrollTo(0, y);