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/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 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();
385 export function getBrowserLanguage(): string {
386 return navigator.language;
389 export function getMomentLanguage(): string {
390 let lang = getLanguage();
391 if (lang.startsWith("zh")) {
393 } else if (lang.startsWith("sv")) {
395 } else if (lang.startsWith("fr")) {
397 } else if (lang.startsWith("de")) {
399 } else if (lang.startsWith("ru")) {
401 } else if (lang.startsWith("es")) {
403 } else if (lang.startsWith("eo")) {
405 } else if (lang.startsWith("nl")) {
407 } else if (lang.startsWith("it")) {
409 } else if (lang.startsWith("fi")) {
411 } else if (lang.startsWith("ca")) {
413 } else if (lang.startsWith("fa")) {
415 } else if (lang.startsWith("pl")) {
417 } else if (lang.startsWith("pt")) {
419 } else if (lang.startsWith("ja")) {
421 } else if (lang.startsWith("ka")) {
423 } else if (lang.startsWith("hi")) {
425 } else if (lang.startsWith("el")) {
427 } else if (lang.startsWith("eu")) {
429 } else if (lang.startsWith("gl")) {
431 } else if (lang.startsWith("tr")) {
433 } else if (lang.startsWith("hu")) {
435 } else if (lang.startsWith("uk")) {
437 } else if (lang.startsWith("sq")) {
439 } else if (lang.startsWith("km")) {
441 } else if (lang.startsWith("ga")) {
443 } else if (lang.startsWith("sr")) {
445 } else if (lang.startsWith("ko")) {
447 } else if (lang.startsWith("da")) {
449 } else if (lang.startsWith("oc")) {
451 } else if (lang.startsWith("hr")) {
453 } else if (lang.startsWith("th")) {
461 export function setTheme(theme: string, forceReload = false) {
465 if (theme === "browser" && !forceReload) {
468 // This is only run on a force reload
469 if (theme == "browser") {
473 // Unload all the other themes
474 for (var i = 0; i < themes.length; i++) {
475 let styleSheet = document.getElementById(themes[i]);
477 styleSheet.setAttribute("disabled", "disabled");
482 .getElementById("default-light")
483 ?.setAttribute("disabled", "disabled");
484 document.getElementById("default-dark")?.setAttribute("disabled", "disabled");
486 // Load the theme dynamically
487 let cssLoc = `/static/assets/css/themes/${theme}.min.css`;
488 loadCss(theme, cssLoc);
489 document.getElementById(theme).removeAttribute("disabled");
492 export function loadCss(id: string, loc: string) {
493 if (!document.getElementById(id)) {
494 var head = document.getElementsByTagName("head")[0];
495 var link = document.createElement("link");
497 link.rel = "stylesheet";
498 link.type = "text/css";
501 head.appendChild(link);
505 export function objectFlip(obj: any) {
507 Object.keys(obj).forEach(key => {
513 export function showAvatars(): boolean {
515 UserService.Instance.localUserView?.local_user.show_avatars ||
516 !UserService.Instance.localUserView
520 export function isCakeDay(published: string): boolean {
521 // moment(undefined) or moment.utc(undefined) returns the current date/time
522 // moment(null) or moment.utc(null) returns null
523 const createDate = moment.utc(published || null).local();
524 const currentDate = moment(new Date());
527 createDate.date() === currentDate.date() &&
528 createDate.month() === currentDate.month() &&
529 createDate.year() !== currentDate.year()
533 export function toast(text: string, background = "success") {
535 let backgroundColor = `var(--${background})`;
538 backgroundColor: backgroundColor,
545 export function pictrsDeleteToast(
546 clickToDeleteText: string,
547 deletePictureText: string,
551 let backgroundColor = `var(--light)`;
552 let toast = Toastify({
553 text: clickToDeleteText,
554 backgroundColor: backgroundColor,
560 window.location.replace(deleteUrl);
561 alert(deletePictureText);
570 interface NotifyInfo {
577 export function messageToastify(info: NotifyInfo, router: any) {
579 let htmlBody = info.body ? md.render(info.body) : "";
580 let backgroundColor = `var(--light)`;
582 let toast = Toastify({
583 text: `${htmlBody}<br />${info.name}`,
584 avatar: info.icon ? info.icon : null,
585 backgroundColor: backgroundColor,
586 className: "text-dark",
594 router.history.push(info.link);
601 export function notifyPost(post_view: PostView, router: any) {
602 let info: NotifyInfo = {
603 name: post_view.community.name,
604 icon: post_view.community.icon,
605 link: `/post/${post_view.post.id}`,
606 body: post_view.post.name,
608 notify(info, router);
611 export function notifyComment(comment_view: CommentView, router: any) {
612 let info: NotifyInfo = {
613 name: comment_view.creator.name,
614 icon: comment_view.creator.avatar,
615 link: `/post/${comment_view.post.id}/comment/${comment_view.comment.id}`,
616 body: comment_view.comment.content,
618 notify(info, router);
621 export function notifyPrivateMessage(pmv: PrivateMessageView, router: any) {
622 let info: NotifyInfo = {
623 name: pmv.creator.name,
624 icon: pmv.creator.avatar,
626 body: pmv.private_message.content,
628 notify(info, router);
631 function notify(info: NotifyInfo, router: any) {
632 messageToastify(info, router);
634 if (Notification.permission !== "granted") Notification.requestPermission();
636 var notification = new Notification(info.name, {
641 notification.onclick = (ev: Event): any => {
643 router.history.push(info.link);
648 export function setupTribute() {
650 noMatchTemplate: function () {
657 menuItemTemplate: (item: any) => {
658 let shortName = `:${item.original.key}:`;
659 return `${item.original.val} ${shortName}`;
661 selectTemplate: (item: any) => {
662 return `${item.original.val}`;
664 values: Object.entries(emojiShortName).map(e => {
665 return { key: e[1], val: e[0] };
668 autocompleteMode: true,
670 // menuItemLimit: mentionDropdownFetchLimit,
671 menuShowMinLength: 2,
676 selectTemplate: (item: any) => {
677 let it: PersonTribute = item.original;
678 return `[${it.key}](${it.view.person.actor_id})`;
680 values: (text: string, cb: (persons: PersonTribute[]) => any) => {
681 personSearch(text, (persons: PersonTribute[]) => cb(persons));
684 autocompleteMode: true,
686 // menuItemLimit: mentionDropdownFetchLimit,
687 menuShowMinLength: 2,
693 selectTemplate: (item: any) => {
694 let it: CommunityTribute = item.original;
695 return `[${it.key}](${it.view.community.actor_id})`;
697 values: (text: string, cb: any) => {
698 communitySearch(text, (communities: CommunityTribute[]) =>
703 autocompleteMode: true,
705 // menuItemLimit: mentionDropdownFetchLimit,
706 menuShowMinLength: 2,
712 var tippyInstance: any;
714 tippyInstance = tippy("[data-tippy-content]");
717 export function setupTippy() {
719 tippyInstance.forEach((e: any) => e.destroy());
720 tippyInstance = tippy("[data-tippy-content]", {
722 // Display on "long press"
723 touch: ["hold", 500],
728 interface PersonTribute {
730 view: PersonViewSafe;
733 function personSearch(text: string, cb: (persons: PersonTribute[]) => any) {
737 type_: SearchType.Users,
738 sort: SortType.TopAll,
740 limit: mentionDropdownFetchLimit,
741 auth: authField(false),
744 WebSocketService.Instance.send(wsClient.search(form));
746 let personSub = WebSocketService.Instance.subject.subscribe(
748 let res = wsJsonToRes(msg);
749 if (res.op == UserOperation.Search) {
750 let data = res.data as SearchResponse;
751 let persons: PersonTribute[] = data.users.map(pv => {
752 let tribute: PersonTribute = {
753 key: `@${pv.person.name}@${hostname(pv.person.actor_id)}`,
759 personSub.unsubscribe();
762 err => console.error(err),
763 () => console.log("complete")
770 interface CommunityTribute {
775 function communitySearch(
777 cb: (communities: CommunityTribute[]) => any
782 type_: SearchType.Communities,
783 sort: SortType.TopAll,
785 limit: mentionDropdownFetchLimit,
786 auth: authField(false),
789 WebSocketService.Instance.send(wsClient.search(form));
791 let communitySub = WebSocketService.Instance.subject.subscribe(
793 let res = wsJsonToRes(msg);
794 if (res.op == UserOperation.Search) {
795 let data = res.data as SearchResponse;
796 let communities: CommunityTribute[] = data.communities.map(cv => {
797 let tribute: CommunityTribute = {
798 key: `!${cv.community.name}@${hostname(cv.community.actor_id)}`,
804 communitySub.unsubscribe();
807 err => console.error(err),
808 () => console.log("complete")
815 export function getListingTypeFromProps(props: any): ListingType {
816 return props.match.params.listing_type
817 ? routeListingTypeToEnum(props.match.params.listing_type)
818 : UserService.Instance.localUserView
819 ? Object.values(ListingType)[
820 UserService.Instance.localUserView.local_user.default_listing_type
825 // TODO might need to add a user setting for this too
826 export function getDataTypeFromProps(props: any): DataType {
827 return props.match.params.data_type
828 ? routeDataTypeToEnum(props.match.params.data_type)
832 export function getSortTypeFromProps(props: any): SortType {
833 return props.match.params.sort
834 ? routeSortTypeToEnum(props.match.params.sort)
835 : UserService.Instance.localUserView
836 ? Object.values(SortType)[
837 UserService.Instance.localUserView.local_user.default_sort_type
842 export function getPageFromProps(props: any): number {
843 return props.match.params.page ? Number(props.match.params.page) : 1;
846 export function getRecipientIdFromProps(props: any): number {
847 return props.match.params.recipient_id
848 ? Number(props.match.params.recipient_id)
852 export function getIdFromProps(props: any): number {
853 return Number(props.match.params.id);
856 export function getCommentIdFromProps(props: any): number {
857 return Number(props.match.params.comment_id);
860 export function getUsernameFromProps(props: any): string {
861 return props.match.params.username;
864 export function editCommentRes(data: CommentView, comments: CommentView[]) {
865 let found = comments.find(c => c.comment.id == data.comment.id);
867 found.comment.content = data.comment.content;
868 found.comment.updated = data.comment.updated;
869 found.comment.removed = data.comment.removed;
870 found.comment.deleted = data.comment.deleted;
871 found.counts.upvotes = data.counts.upvotes;
872 found.counts.downvotes = data.counts.downvotes;
873 found.counts.score = data.counts.score;
877 export function saveCommentRes(data: CommentView, comments: CommentView[]) {
878 let found = comments.find(c => c.comment.id == data.comment.id);
880 found.saved = data.saved;
884 export function createCommentLikeRes(
886 comments: CommentView[]
888 let found = comments.find(c => c.comment.id === data.comment.id);
890 found.counts.score = data.counts.score;
891 found.counts.upvotes = data.counts.upvotes;
892 found.counts.downvotes = data.counts.downvotes;
893 if (data.my_vote !== null) {
894 found.my_vote = data.my_vote;
899 export function createPostLikeFindRes(data: PostView, posts: PostView[]) {
900 let found = posts.find(p => p.post.id == data.post.id);
902 createPostLikeRes(data, found);
906 export function createPostLikeRes(data: PostView, post_view: PostView) {
908 post_view.counts.score = data.counts.score;
909 post_view.counts.upvotes = data.counts.upvotes;
910 post_view.counts.downvotes = data.counts.downvotes;
911 if (data.my_vote !== null) {
912 post_view.my_vote = data.my_vote;
917 export function editPostFindRes(data: PostView, posts: PostView[]) {
918 let found = posts.find(p => p.post.id == data.post.id);
920 editPostRes(data, found);
924 export function editPostRes(data: PostView, post: PostView) {
926 post.post.url = data.post.url;
927 post.post.name = data.post.name;
928 post.post.nsfw = data.post.nsfw;
929 post.post.deleted = data.post.deleted;
930 post.post.removed = data.post.removed;
931 post.post.stickied = data.post.stickied;
932 post.post.body = data.post.body;
933 post.post.locked = data.post.locked;
934 post.saved = data.saved;
938 export function commentsToFlatNodes(comments: CommentView[]): CommentNodeI[] {
939 let nodes: CommentNodeI[] = [];
940 for (let comment of comments) {
941 nodes.push({ comment_view: comment });
946 function commentSort(tree: CommentNodeI[], sort: CommentSortType) {
947 // First, put removed and deleted comments at the bottom, then do your other sorts
948 if (sort == CommentSortType.Top) {
951 +a.comment_view.comment.removed - +b.comment_view.comment.removed ||
952 +a.comment_view.comment.deleted - +b.comment_view.comment.deleted ||
953 b.comment_view.counts.score - a.comment_view.counts.score
955 } else if (sort == CommentSortType.New) {
958 +a.comment_view.comment.removed - +b.comment_view.comment.removed ||
959 +a.comment_view.comment.deleted - +b.comment_view.comment.deleted ||
960 b.comment_view.comment.published.localeCompare(
961 a.comment_view.comment.published
964 } else if (sort == CommentSortType.Old) {
967 +a.comment_view.comment.removed - +b.comment_view.comment.removed ||
968 +a.comment_view.comment.deleted - +b.comment_view.comment.deleted ||
969 a.comment_view.comment.published.localeCompare(
970 b.comment_view.comment.published
973 } else if (sort == CommentSortType.Hot) {
976 +a.comment_view.comment.removed - +b.comment_view.comment.removed ||
977 +a.comment_view.comment.deleted - +b.comment_view.comment.deleted ||
978 hotRankComment(b.comment_view) - hotRankComment(a.comment_view)
982 // Go through the children recursively
983 for (let node of tree) {
985 commentSort(node.children, sort);
990 export function commentSortSortType(tree: CommentNodeI[], sort: SortType) {
991 commentSort(tree, convertCommentSortType(sort));
994 function convertCommentSortType(sort: SortType): CommentSortType {
996 sort == SortType.TopAll ||
997 sort == SortType.TopDay ||
998 sort == SortType.TopWeek ||
999 sort == SortType.TopMonth ||
1000 sort == SortType.TopYear
1002 return CommentSortType.Top;
1003 } else if (sort == SortType.New) {
1004 return CommentSortType.New;
1005 } else if (sort == SortType.Hot || sort == SortType.Active) {
1006 return CommentSortType.Hot;
1008 return CommentSortType.Hot;
1012 export function buildCommentsTree(
1013 comments: CommentView[],
1014 commentSortType: CommentSortType
1016 let map = new Map<number, CommentNodeI>();
1017 for (let comment_view of comments) {
1018 let node: CommentNodeI = {
1019 comment_view: comment_view,
1022 map.set(comment_view.comment.id, { ...node });
1024 let tree: CommentNodeI[] = [];
1025 for (let comment_view of comments) {
1026 let child = map.get(comment_view.comment.id);
1027 if (comment_view.comment.parent_id) {
1028 let parent_ = map.get(comment_view.comment.parent_id);
1029 parent_.children.push(child);
1037 commentSort(tree, commentSortType);
1042 function setDepth(node: CommentNodeI, i = 0) {
1043 for (let child of node.children) {
1045 setDepth(child, i + 1);
1049 export function insertCommentIntoTree(tree: CommentNodeI[], cv: CommentView) {
1050 // Building a fake node to be used for later
1051 let node: CommentNodeI = {
1057 if (cv.comment.parent_id) {
1058 let parentComment = searchCommentTree(tree, cv.comment.parent_id);
1059 if (parentComment) {
1060 node.depth = parentComment.depth + 1;
1061 parentComment.children.unshift(node);
1068 export function searchCommentTree(
1069 tree: CommentNodeI[],
1072 for (let node of tree) {
1073 if (node.comment_view.comment.id === id) {
1077 for (const child of node.children) {
1078 const res = searchCommentTree([child], id);
1088 export const colorList: string[] = [
1097 function hsl(num: number) {
1098 return `hsla(${num}, 35%, 50%, 1)`;
1101 export function previewLines(
1110 // Use lines * 2 because markdown requires 2 lines
1111 .slice(0, maxLines * 2)
1116 export function hostname(url: string): string {
1117 let cUrl = new URL(url);
1118 return cUrl.port ? `${cUrl.hostname}:${cUrl.port}` : `${cUrl.hostname}`;
1121 export function validTitle(title?: string): boolean {
1122 // Initial title is null, minimum length is taken care of by textarea's minLength={3}
1123 if (title === null || title.length < 3) return true;
1125 const regex = new RegExp(/.*\S.*/, "g");
1127 return regex.test(title);
1130 export function siteBannerCss(banner: string): string {
1132 background-image: linear-gradient( rgba(0, 0, 0, 0.8), rgba(0, 0, 0, 0.8) ) ,url("${banner}"); \
1133 background-attachment: fixed; \
1134 background-position: top; \
1135 background-repeat: no-repeat; \
1136 background-size: 100% cover; \
1139 max-height: 100vh; \
1143 export function isBrowser() {
1144 return typeof window !== "undefined";
1147 export function setIsoData(context: any): IsoData {
1148 let isoData: IsoData = isBrowser()
1150 : context.router.staticContext;
1154 export function wsSubscribe(parseMessage: any): Subscription {
1156 return WebSocketService.Instance.subject
1157 .pipe(retryWhen(errors => errors.pipe(delay(3000), take(10))))
1159 msg => parseMessage(msg),
1160 err => console.error(err),
1161 () => console.log("complete")
1168 export function setOptionalAuth(obj: any, auth = UserService.Instance.auth) {
1174 export function authField(
1176 auth = UserService.Instance.auth
1178 if (auth == null && throwErr) {
1179 toast(i18n.t("not_logged_in"), "danger");
1180 throw "Not logged in";
1186 moment.updateLocale("en", {
1207 export function saveScrollPosition(context: any) {
1208 let path: string = context.router.route.location.pathname;
1209 let y = window.scrollY;
1210 sessionStorage.setItem(`scrollPosition_${path}`, y.toString());
1213 export function restoreScrollPosition(context: any) {
1214 let path: string = context.router.route.location.pathname;
1215 let y = Number(sessionStorage.getItem(`scrollPosition_${path}`));
1216 window.scrollTo(0, y);