1 import { None, Option, Result, Some } from "@sniptt/monads";
2 import { ClassConstructor, deserialize, serialize } from "class-transformer";
3 import emojiShortName from "emoji-short-name";
5 BlockCommunityResponse,
10 CommunityModeratorView,
24 RegistrationApplicationView,
28 } from "lemmy-js-client";
29 import markdown_it from "markdown-it";
30 import markdown_it_container from "markdown-it-container";
31 import markdown_it_footnote from "markdown-it-footnote";
32 import markdown_it_html5_embed from "markdown-it-html5-embed";
33 import markdown_it_sub from "markdown-it-sub";
34 import markdown_it_sup from "markdown-it-sup";
35 import moment from "moment";
36 import { Subscription } from "rxjs";
37 import { delay, retryWhen, take } from "rxjs/operators";
38 import tippy from "tippy.js";
39 import Toastify from "toastify-js";
40 import { httpBase } from "./env";
41 import { i18n, languages } from "./i18next";
43 CommentNode as CommentNodeI,
47 } from "./interfaces";
48 import { UserService, WebSocketService } from "./services";
52 Tribute = require("tributejs");
55 export const wsClient = new LemmyWebsocket();
57 export const favIconUrl = "/static/assets/icons/favicon.svg";
58 export const favIconPngUrl = "/static/assets/icons/apple-touch-icon.png";
60 // export const defaultFavIcon = `${window.location.protocol}//${window.location.host}${favIconPngUrl}`;
61 export const repoUrl = "https://github.com/LemmyNet";
62 export const joinLemmyUrl = "https://join-lemmy.org";
63 export const donateLemmyUrl = `${joinLemmyUrl}/donate`;
64 export const docsUrl = `${joinLemmyUrl}/docs/en/index.html`;
65 export const helpGuideUrl = `${joinLemmyUrl}/docs/en/about/guide.html`; // TODO find a way to redirect to the non-en folder
66 export const markdownHelpUrl = `${helpGuideUrl}#using-markdown`;
67 export const sortingHelpUrl = `${helpGuideUrl}#sorting`;
68 export const archiveTodayUrl = "https://archive.today";
69 export const ghostArchiveUrl = "https://ghostarchive.org";
70 export const webArchiveUrl = "https://web.archive.org";
71 export const elementUrl = "https://element.io";
73 export const postRefetchSeconds: number = 60 * 1000;
74 export const fetchLimit = 20;
75 export const trendingFetchLimit = 6;
76 export const mentionDropdownFetchLimit = 10;
78 export const relTags = "noopener nofollow";
80 const DEFAULT_ALPHABET =
81 "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
83 function getRandomCharFromAlphabet(alphabet: string): string {
84 return alphabet.charAt(Math.floor(Math.random() * alphabet.length));
87 export function randomStr(
89 alphabet = DEFAULT_ALPHABET
92 * Create n-long array and map it to random chars from given alphabet.
93 * Then join individual chars as string
95 return Array.from({ length: idDesiredLength })
97 return getRandomCharFromAlphabet(alphabet);
102 export const md = new markdown_it({
107 .use(markdown_it_sub)
108 .use(markdown_it_sup)
109 .use(markdown_it_footnote)
110 .use(markdown_it_html5_embed, {
112 useImageSyntax: true, // Enables video/audio embed with ![]() syntax (default)
114 audio: 'controls preload="metadata"',
116 'width="100%" max-height="100%" controls loop preload="metadata"',
120 .use(markdown_it_container, "spoiler", {
121 validate: function (params: any) {
122 return params.trim().match(/^spoiler\s+(.*)$/);
125 render: function (tokens: any, idx: any) {
126 var m = tokens[idx].info.trim().match(/^spoiler\s+(.*)$/);
128 if (tokens[idx].nesting === 1) {
130 return `<details><summary> ${md.utils.escapeHtml(m[1])} </summary>\n`;
133 return "</details>\n";
138 export function hotRankComment(comment_view: CommentView): number {
139 return hotRank(comment_view.counts.score, comment_view.comment.published);
142 export function hotRankActivePost(post_view: PostView): number {
143 return hotRank(post_view.counts.score, post_view.counts.newest_comment_time);
146 export function hotRankPost(post_view: PostView): number {
147 return hotRank(post_view.counts.score, post_view.post.published);
150 export function hotRank(score: number, timeStr: string): number {
151 // Rank = ScaleFactor * sign(Score) * log(1 + abs(Score)) / (Time + 2)^Gravity
152 let date: Date = new Date(timeStr + "Z"); // Add Z to convert from UTC date
153 let now: Date = new Date();
154 let hoursElapsed: number = (now.getTime() - date.getTime()) / 36e5;
157 (10000 * Math.log10(Math.max(1, 3 + score))) /
158 Math.pow(hoursElapsed + 2, 1.8);
160 // console.log(`Comment: ${comment.content}\nRank: ${rank}\nScore: ${comment.score}\nHours: ${hoursElapsed}`);
165 export function mdToHtml(text: string) {
166 return { __html: md.render(text) };
169 export function getUnixTime(text: string): number {
170 return text ? new Date(text).getTime() / 1000 : undefined;
173 export function futureDaysToUnixTime(days: number): number {
176 new Date(Date.now() + 1000 * 60 * 60 * 24 * days).getTime() / 1000
181 export function canMod(
182 mods: Option<CommunityModeratorView[]>,
183 admins: Option<PersonViewSafe[]>,
185 myUserInfo = UserService.Instance.myUserInfo,
188 // You can do moderator actions only on the mods added after you.
189 let adminsThenMods = admins
191 .map(a => a.person.id)
192 .concat(mods.unwrapOr([]).map(m => m.moderator.id));
194 return myUserInfo.match({
196 let myIndex = adminsThenMods.findIndex(
197 id => id == me.local_user_view.person.id
202 // onSelf +1 on mod actions not for yourself, IE ban, remove, etc
203 adminsThenMods = adminsThenMods.slice(0, myIndex + (onSelf ? 0 : 1));
204 return !adminsThenMods.includes(creator_id);
211 export function canAdmin(
212 admins: Option<PersonViewSafe[]>,
214 myUserInfo = UserService.Instance.myUserInfo
216 return canMod(None, admins, creator_id, myUserInfo);
219 export function isMod(
220 mods: Option<CommunityModeratorView[]>,
224 some: mods => mods.map(m => m.moderator.id).includes(creator_id),
229 export function amMod(
230 mods: Option<CommunityModeratorView[]>,
231 myUserInfo = UserService.Instance.myUserInfo
233 return myUserInfo.match({
234 some: mui => isMod(mods, mui.local_user_view.person.id),
239 export function isAdmin(
240 admins: Option<PersonViewSafe[]>,
243 return admins.match({
244 some: admins => admins.map(a => a.person.id).includes(creator_id),
249 export function amAdmin(
250 admins: Option<PersonViewSafe[]>,
251 myUserInfo = UserService.Instance.myUserInfo
253 return myUserInfo.match({
254 some: mui => isAdmin(admins, mui.local_user_view.person.id),
259 export function amCommunityCreator(
260 mods: Option<CommunityModeratorView[]>,
262 myUserInfo = UserService.Instance.myUserInfo
267 .map(mui => mui.local_user_view.person.id)
270 myId == mods[0].moderator.id &&
271 // Don't allow mod actions on yourself
279 export function amSiteCreator(
280 admins: Option<PersonViewSafe[]>,
282 myUserInfo = UserService.Instance.myUserInfo
284 return admins.match({
287 .map(mui => mui.local_user_view.person.id)
290 myId == admins[0].person.id &&
291 // Don't allow mod actions on yourself
299 export function amTopMod(
300 mods: Option<CommunityModeratorView[]>,
301 myUserInfo = UserService.Instance.myUserInfo
306 some: mui => mods[0].moderator.id == mui.local_user_view.person.id,
313 const imageRegex = /(http)?s?:?(\/\/[^"']*\.(?:jpg|jpeg|gif|png|svg|webp))/;
314 const videoRegex = /(http)?s?:?(\/\/[^"']*\.(?:mp4|webm))/;
316 export function isImage(url: string) {
317 return imageRegex.test(url);
320 export function isVideo(url: string) {
321 return videoRegex.test(url);
324 export function validURL(str: string) {
325 return !!new URL(str);
328 export function communityRSSUrl(actorId: string, sort: string): string {
329 let url = new URL(actorId);
330 return `${url.origin}/feeds${url.pathname}.xml?sort=${sort}`;
333 export function validEmail(email: string) {
335 /^(([^\s"(),.:;<>@[\\\]]+(\.[^\s"(),.:;<>@[\\\]]+)*)|(".+"))@((\[(?:\d{1,3}\.){3}\d{1,3}])|(([\dA-Za-z\-]+\.)+[A-Za-z]{2,}))$/;
336 return re.test(String(email).toLowerCase());
339 export function capitalizeFirstLetter(str: string): string {
340 return str.charAt(0).toUpperCase() + str.slice(1);
343 export function routeSortTypeToEnum(sort: string): SortType {
344 return SortType[sort];
347 export function listingTypeFromNum(type_: number): ListingType {
348 return Object.values(ListingType)[type_];
351 export function sortTypeFromNum(type_: number): SortType {
352 return Object.values(SortType)[type_];
355 export function routeListingTypeToEnum(type: string): ListingType {
356 return ListingType[type];
359 export function routeDataTypeToEnum(type: string): DataType {
360 return DataType[capitalizeFirstLetter(type)];
363 export function routeSearchTypeToEnum(type: string): SearchType {
364 return SearchType[type];
367 export async function getSiteMetadata(url: string) {
368 let form: GetSiteMetadata = {
371 let client = new LemmyHttp(httpBase);
372 return client.getSiteMetadata(form);
375 export function debounce(func: any, wait = 1000, immediate = false) {
376 // 'private' variable for instance
377 // The returned function will be able to reference this due to closure.
378 // Each call to the returned function will share this common timer.
381 // Calling debounce returns a new anonymous function
383 // reference the context and args for the setTimeout function
384 var args = arguments;
386 // Should the function be called now? If immediate is true
387 // and not already in a timeout then the answer is: Yes
388 var callNow = immediate && !timeout;
390 // This is the basic debounce behaviour where you can call this
391 // function several times, but it will only execute once
392 // [before or after imposing a delay].
393 // Each time the returned function is called, the timer starts over.
394 clearTimeout(timeout);
396 // Set the new timeout
397 timeout = setTimeout(function () {
398 // Inside the timeout function, clear the timeout variable
399 // which will let the next execution run when in 'immediate' mode
402 // Check if the function already ran with the immediate flag
404 // Call the original function with apply
405 // apply lets you define the 'this' object as well as the arguments
406 // (both captured before setTimeout)
407 func.apply(this, args);
411 // Immediate mode and no wait timer? Execute the function..
412 if (callNow) func.apply(this, args);
416 export function getLanguages(
418 myUserInfo = UserService.Instance.myUserInfo
420 let myLang = myUserInfo
421 .map(m => m.local_user_view.local_user.lang)
422 .unwrapOr("browser");
423 let lang = override || myLang;
425 if (lang == "browser" && isBrowser()) {
426 return getBrowserLanguages();
432 function getBrowserLanguages(): string[] {
433 // Intersect lemmy's langs, with the browser langs
434 let langs = languages ? languages.map(l => l.code) : ["en"];
436 // NOTE, mobile browsers seem to be missing this list, so append en
437 let allowedLangs = navigator.languages
439 .filter(v => langs.includes(v));
443 export async function fetchThemeList(): Promise<string[]> {
444 return fetch("/css/themelist").then(res => res.json());
447 export async function setTheme(theme: string, forceReload = false) {
451 if (theme === "browser" && !forceReload) {
454 // This is only run on a force reload
455 if (theme == "browser") {
459 let themeList = await fetchThemeList();
461 // Unload all the other themes
462 for (var i = 0; i < themeList.length; i++) {
463 let styleSheet = document.getElementById(themeList[i]);
465 styleSheet.setAttribute("disabled", "disabled");
470 .getElementById("default-light")
471 ?.setAttribute("disabled", "disabled");
472 document.getElementById("default-dark")?.setAttribute("disabled", "disabled");
474 // Load the theme dynamically
475 let cssLoc = `/css/themes/${theme}.css`;
477 loadCss(theme, cssLoc);
478 document.getElementById(theme).removeAttribute("disabled");
481 export function loadCss(id: string, loc: string) {
482 if (!document.getElementById(id)) {
483 var head = document.getElementsByTagName("head")[0];
484 var link = document.createElement("link");
486 link.rel = "stylesheet";
487 link.type = "text/css";
490 head.appendChild(link);
494 export function objectFlip(obj: any) {
496 Object.keys(obj).forEach(key => {
502 export function showAvatars(
503 myUserInfo: Option<MyUserInfo> = UserService.Instance.myUserInfo
506 .map(m => m.local_user_view.local_user.show_avatars)
510 export function showScores(
511 myUserInfo: Option<MyUserInfo> = UserService.Instance.myUserInfo
514 .map(m => m.local_user_view.local_user.show_scores)
518 export function isCakeDay(published: string): boolean {
519 // moment(undefined) or moment.utc(undefined) returns the current date/time
520 // moment(null) or moment.utc(null) returns null
521 const createDate = moment.utc(published).local();
522 const currentDate = moment(new Date());
525 createDate.date() === currentDate.date() &&
526 createDate.month() === currentDate.month() &&
527 createDate.year() !== currentDate.year()
531 export function toast(text: string, background = "success") {
533 let backgroundColor = `var(--${background})`;
536 backgroundColor: backgroundColor,
543 export function pictrsDeleteToast(
544 clickToDeleteText: string,
545 deletePictureText: string,
549 let backgroundColor = `var(--light)`;
550 let toast = Toastify({
551 text: clickToDeleteText,
552 backgroundColor: backgroundColor,
558 window.location.replace(deleteUrl);
559 alert(deletePictureText);
568 interface NotifyInfo {
570 icon: Option<string>;
575 export function messageToastify(info: NotifyInfo, router: any) {
577 let htmlBody = info.body ? md.render(info.body) : "";
578 let backgroundColor = `var(--light)`;
580 let toast = Toastify({
581 text: `${htmlBody}<br />${info.name}`,
583 backgroundColor: backgroundColor,
584 className: "text-dark",
593 router.history.push(info.link);
600 export function notifyPost(post_view: PostView, router: any) {
601 let info: NotifyInfo = {
602 name: post_view.community.name,
603 icon: post_view.community.icon,
604 link: `/post/${post_view.post.id}`,
605 body: post_view.post.name,
607 notify(info, router);
610 export function notifyComment(comment_view: CommentView, router: any) {
611 let info: NotifyInfo = {
612 name: comment_view.creator.name,
613 icon: comment_view.creator.avatar,
614 link: `/post/${comment_view.post.id}/comment/${comment_view.comment.id}`,
615 body: comment_view.comment.content,
617 notify(info, router);
620 export function notifyPrivateMessage(pmv: PrivateMessageView, router: any) {
621 let info: NotifyInfo = {
622 name: pmv.creator.name,
623 icon: pmv.creator.avatar,
625 body: pmv.private_message.content,
627 notify(info, router);
630 function notify(info: NotifyInfo, router: any) {
631 messageToastify(info, router);
633 // TODO absolute nightmare bug, but notifs are currently broken.
634 // Notification.new will try to do a browser fetch ???
636 // if (Notification.permission !== "granted") Notification.requestPermission();
638 // var notification = new Notification(info.name, {
643 // notification.onclick = (ev: Event): any => {
644 // ev.preventDefault();
645 // router.history.push(info.link);
650 export function setupTribute() {
652 noMatchTemplate: function () {
659 menuItemTemplate: (item: any) => {
660 let shortName = `:${item.original.key}:`;
661 return `${item.original.val} ${shortName}`;
663 selectTemplate: (item: any) => {
664 return `${item.original.val}`;
666 values: Object.entries(emojiShortName).map(e => {
667 return { key: e[1], val: e[0] };
670 autocompleteMode: true,
672 // menuItemLimit: mentionDropdownFetchLimit,
673 menuShowMinLength: 2,
678 selectTemplate: (item: any) => {
679 let it: PersonTribute = item.original;
680 return `[${it.key}](${it.view.person.actor_id})`;
682 values: debounce(async (text: string, cb: any) => {
683 cb(await personSearch(text));
686 autocompleteMode: true,
688 // menuItemLimit: mentionDropdownFetchLimit,
689 menuShowMinLength: 2,
695 selectTemplate: (item: any) => {
696 let it: CommunityTribute = item.original;
697 return `[${it.key}](${it.view.community.actor_id})`;
699 values: debounce(async (text: string, cb: any) => {
700 cb(await communitySearch(text));
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 async function personSearch(text: string): Promise<PersonTribute[]> {
734 let users = (await fetchUsers(text)).users;
735 let persons: PersonTribute[] = users.map(pv => {
736 let tribute: PersonTribute = {
737 key: `@${pv.person.name}@${hostname(pv.person.actor_id)}`,
745 interface CommunityTribute {
750 async function communitySearch(text: string): Promise<CommunityTribute[]> {
751 let comms = (await fetchCommunities(text)).communities;
752 let communities: CommunityTribute[] = comms.map(cv => {
753 let tribute: CommunityTribute = {
754 key: `!${cv.community.name}@${hostname(cv.community.actor_id)}`,
762 export function getListingTypeFromProps(
764 defaultListingType: ListingType,
765 myUserInfo = UserService.Instance.myUserInfo
767 return props.match.params.listing_type
768 ? routeListingTypeToEnum(props.match.params.listing_type)
771 Object.values(ListingType)[
772 me.local_user_view.local_user.default_listing_type
774 none: defaultListingType,
778 export function getListingTypeFromPropsNoDefault(props: any): ListingType {
779 return props.match.params.listing_type
780 ? routeListingTypeToEnum(props.match.params.listing_type)
784 // TODO might need to add a user setting for this too
785 export function getDataTypeFromProps(props: any): DataType {
786 return props.match.params.data_type
787 ? routeDataTypeToEnum(props.match.params.data_type)
791 export function getSortTypeFromProps(
793 myUserInfo = UserService.Instance.myUserInfo
795 return props.match.params.sort
796 ? routeSortTypeToEnum(props.match.params.sort)
799 Object.values(SortType)[
800 mui.local_user_view.local_user.default_sort_type
802 none: SortType.Active,
806 export function getPageFromProps(props: any): number {
807 return props.match.params.page ? Number(props.match.params.page) : 1;
810 export function getRecipientIdFromProps(props: any): number {
811 return props.match.params.recipient_id
812 ? Number(props.match.params.recipient_id)
816 export function getIdFromProps(props: any): number {
817 return Number(props.match.params.id);
820 export function getCommentIdFromProps(props: any): number {
821 return Number(props.match.params.comment_id);
824 export function getUsernameFromProps(props: any): string {
825 return props.match.params.username;
828 export function editCommentRes(data: CommentView, comments: CommentView[]) {
829 let found = comments.find(c => c.comment.id == data.comment.id);
831 found.comment.content = data.comment.content;
832 found.comment.updated = data.comment.updated;
833 found.comment.removed = data.comment.removed;
834 found.comment.deleted = data.comment.deleted;
835 found.counts.upvotes = data.counts.upvotes;
836 found.counts.downvotes = data.counts.downvotes;
837 found.counts.score = data.counts.score;
841 export function saveCommentRes(data: CommentView, comments: CommentView[]) {
842 let found = comments.find(c => c.comment.id == data.comment.id);
844 found.saved = data.saved;
848 // TODO Should only use the return now, no state?
849 export function updatePersonBlock(
850 data: BlockPersonResponse,
851 myUserInfo = UserService.Instance.myUserInfo
852 ): Option<PersonBlockView[]> {
853 return myUserInfo.match({
854 some: (mui: MyUserInfo) => {
856 mui.person_blocks.push({
857 person: mui.local_user_view.person,
858 target: data.person_view.person,
860 toast(`${i18n.t("blocked")} ${data.person_view.person.name}`);
862 mui.person_blocks = mui.person_blocks.filter(
863 i => i.target.id != data.person_view.person.id
865 toast(`${i18n.t("unblocked")} ${data.person_view.person.name}`);
867 return Some(mui.person_blocks);
873 export function updateCommunityBlock(
874 data: BlockCommunityResponse,
875 myUserInfo = UserService.Instance.myUserInfo
876 ): Option<CommunityBlockView[]> {
877 return myUserInfo.match({
878 some: (mui: MyUserInfo) => {
880 mui.community_blocks.push({
881 person: mui.local_user_view.person,
882 community: data.community_view.community,
884 toast(`${i18n.t("blocked")} ${data.community_view.community.name}`);
886 mui.community_blocks = mui.community_blocks.filter(
887 i => i.community.id != data.community_view.community.id
889 toast(`${i18n.t("unblocked")} ${data.community_view.community.name}`);
891 return Some(mui.community_blocks);
897 export function createCommentLikeRes(
899 comments: CommentView[]
901 let found = comments.find(c => c.comment.id === data.comment.id);
903 found.counts.score = data.counts.score;
904 found.counts.upvotes = data.counts.upvotes;
905 found.counts.downvotes = data.counts.downvotes;
906 if (data.my_vote !== null) {
907 found.my_vote = data.my_vote;
912 export function createPostLikeFindRes(data: PostView, posts: PostView[]) {
913 let found = posts.find(p => p.post.id == data.post.id);
915 createPostLikeRes(data, found);
919 export function createPostLikeRes(data: PostView, post_view: PostView) {
921 post_view.counts.score = data.counts.score;
922 post_view.counts.upvotes = data.counts.upvotes;
923 post_view.counts.downvotes = data.counts.downvotes;
924 if (data.my_vote !== null) {
925 post_view.my_vote = data.my_vote;
930 export function editPostFindRes(data: PostView, posts: PostView[]) {
931 let found = posts.find(p => p.post.id == data.post.id);
933 editPostRes(data, found);
937 export function editPostRes(data: PostView, post: PostView) {
939 post.post.url = data.post.url;
940 post.post.name = data.post.name;
941 post.post.nsfw = data.post.nsfw;
942 post.post.deleted = data.post.deleted;
943 post.post.removed = data.post.removed;
944 post.post.stickied = data.post.stickied;
945 post.post.body = data.post.body;
946 post.post.locked = data.post.locked;
947 post.saved = data.saved;
951 export function updatePostReportRes(
952 data: PostReportView,
953 reports: PostReportView[]
955 let found = reports.find(p => p.post_report.id == data.post_report.id);
957 found.post_report = data.post_report;
961 export function updateCommentReportRes(
962 data: CommentReportView,
963 reports: CommentReportView[]
965 let found = reports.find(c => c.comment_report.id == data.comment_report.id);
967 found.comment_report = data.comment_report;
971 export function updateRegistrationApplicationRes(
972 data: RegistrationApplicationView,
973 applications: RegistrationApplicationView[]
975 let found = applications.find(
976 ra => ra.registration_application.id == data.registration_application.id
979 found.registration_application = data.registration_application;
980 found.admin = data.admin;
981 found.creator_local_user = data.creator_local_user;
985 export function commentsToFlatNodes(comments: CommentView[]): CommentNodeI[] {
986 let nodes: CommentNodeI[] = [];
987 for (let comment of comments) {
988 nodes.push({ comment_view: comment });
993 function commentSort(tree: CommentNodeI[], sort: CommentSortType) {
994 // First, put removed and deleted comments at the bottom, then do your other sorts
995 if (sort == CommentSortType.Top) {
998 +a.comment_view.comment.removed - +b.comment_view.comment.removed ||
999 +a.comment_view.comment.deleted - +b.comment_view.comment.deleted ||
1000 b.comment_view.counts.score - a.comment_view.counts.score
1002 } else if (sort == CommentSortType.New) {
1005 +a.comment_view.comment.removed - +b.comment_view.comment.removed ||
1006 +a.comment_view.comment.deleted - +b.comment_view.comment.deleted ||
1007 b.comment_view.comment.published.localeCompare(
1008 a.comment_view.comment.published
1011 } else if (sort == CommentSortType.Old) {
1014 +a.comment_view.comment.removed - +b.comment_view.comment.removed ||
1015 +a.comment_view.comment.deleted - +b.comment_view.comment.deleted ||
1016 a.comment_view.comment.published.localeCompare(
1017 b.comment_view.comment.published
1020 } else if (sort == CommentSortType.Hot) {
1023 +a.comment_view.comment.removed - +b.comment_view.comment.removed ||
1024 +a.comment_view.comment.deleted - +b.comment_view.comment.deleted ||
1025 hotRankComment(b.comment_view as CommentView) -
1026 hotRankComment(a.comment_view as CommentView)
1030 // Go through the children recursively
1031 for (let node of tree) {
1032 if (node.children) {
1033 commentSort(node.children, sort);
1038 export function commentSortSortType(tree: CommentNodeI[], sort: SortType) {
1039 commentSort(tree, convertCommentSortType(sort));
1042 function convertCommentSortType(sort: SortType): CommentSortType {
1044 sort == SortType.TopAll ||
1045 sort == SortType.TopDay ||
1046 sort == SortType.TopWeek ||
1047 sort == SortType.TopMonth ||
1048 sort == SortType.TopYear
1050 return CommentSortType.Top;
1051 } else if (sort == SortType.New) {
1052 return CommentSortType.New;
1053 } else if (sort == SortType.Hot || sort == SortType.Active) {
1054 return CommentSortType.Hot;
1056 return CommentSortType.Hot;
1060 export function buildCommentsTree(
1061 comments: CommentView[],
1062 commentSortType: CommentSortType
1064 let map = new Map<number, CommentNodeI>();
1065 for (let comment_view of comments) {
1066 let node: CommentNodeI = {
1067 comment_view: comment_view,
1071 map.set(comment_view.comment.id, { ...node });
1073 let tree: CommentNodeI[] = [];
1074 for (let comment_view of comments) {
1075 let child = map.get(comment_view.comment.id);
1076 let parent_id = comment_view.comment.parent_id;
1079 let parent = map.get(parentId);
1080 // Necessary because blocked comment might not exist
1082 parent.children.push(child);
1093 commentSort(tree, commentSortType);
1098 function setDepth(node: CommentNodeI, i = 0) {
1099 for (let child of node.children) {
1101 setDepth(child, i + 1);
1105 export function insertCommentIntoTree(tree: CommentNodeI[], cv: CommentView) {
1106 // Building a fake node to be used for later
1107 let node: CommentNodeI = {
1113 cv.comment.parent_id.match({
1115 let parentComment = searchCommentTree(tree, parentId);
1116 parentComment.match({
1118 node.depth = pComment.depth + 1;
1119 pComment.children.unshift(node);
1130 export function searchCommentTree(
1131 tree: CommentNodeI[],
1133 ): Option<CommentNodeI> {
1134 for (let node of tree) {
1135 if (node.comment_view.comment.id === id) {
1139 for (const child of node.children) {
1140 let res = searchCommentTree([child], id);
1150 export const colorList: string[] = [
1159 function hsl(num: number) {
1160 return `hsla(${num}, 35%, 50%, 1)`;
1163 export function hostname(url: string): string {
1164 let cUrl = new URL(url);
1165 return cUrl.port ? `${cUrl.hostname}:${cUrl.port}` : `${cUrl.hostname}`;
1168 export function validTitle(title?: string): boolean {
1169 // Initial title is null, minimum length is taken care of by textarea's minLength={3}
1170 if (!title || title.length < 3) return true;
1172 const regex = new RegExp(/.*\S.*/, "g");
1174 return regex.test(title);
1177 export function siteBannerCss(banner: string): string {
1179 background-image: linear-gradient( rgba(0, 0, 0, 0.8), rgba(0, 0, 0, 0.8) ) ,url("${banner}"); \
1180 background-attachment: fixed; \
1181 background-position: top; \
1182 background-repeat: no-repeat; \
1183 background-size: 100% cover; \
1186 max-height: 100vh; \
1190 export function isBrowser() {
1191 return typeof window !== "undefined";
1194 export function setIsoData<Type1, Type2, Type3, Type4, Type5>(
1196 cls1?: ClassConstructor<Type1>,
1197 cls2?: ClassConstructor<Type2>,
1198 cls3?: ClassConstructor<Type3>,
1199 cls4?: ClassConstructor<Type4>,
1200 cls5?: ClassConstructor<Type5>
1202 // If its the browser, you need to deserialize the data from the window
1204 let json = window.isoData;
1205 let routeData = json.routeData;
1206 let routeDataOut: any[] = [];
1208 // Can't do array looping because of specific type constructor required
1210 routeDataOut[0] = convertWindowJson(cls1, routeData[0]);
1213 routeDataOut[1] = convertWindowJson(cls2, routeData[1]);
1216 routeDataOut[2] = convertWindowJson(cls3, routeData[2]);
1219 routeDataOut[3] = convertWindowJson(cls4, routeData[3]);
1222 routeDataOut[4] = convertWindowJson(cls5, routeData[4]);
1225 let isoData: IsoData = {
1227 site_res: convertWindowJson(GetSiteResponse, json.site_res),
1228 routeData: routeDataOut,
1231 } else return context.router.staticContext;
1235 * Necessary since window ISOData can't store function types like Option
1237 export function convertWindowJson<T>(cls: ClassConstructor<T>, data: any): T {
1238 return deserialize(cls, serialize(data));
1241 export function wsSubscribe(parseMessage: any): Subscription {
1243 return WebSocketService.Instance.subject
1244 .pipe(retryWhen(errors => errors.pipe(delay(3000), take(10))))
1246 msg => parseMessage(msg),
1247 err => console.error(err),
1248 () => console.log("complete")
1255 moment.updateLocale("en", {
1276 export function saveScrollPosition(context: any) {
1277 let path: string = context.router.route.location.pathname;
1278 let y = window.scrollY;
1279 sessionStorage.setItem(`scrollPosition_${path}`, y.toString());
1282 export function restoreScrollPosition(context: any) {
1283 let path: string = context.router.route.location.pathname;
1284 let y = Number(sessionStorage.getItem(`scrollPosition_${path}`));
1285 window.scrollTo(0, y);
1288 export function showLocal(isoData: IsoData): boolean {
1289 return isoData.site_res.federated_instances
1290 .map(f => f.linked.length > 0)
1294 interface ChoicesValue {
1299 export function communityToChoice(cv: CommunityView): ChoicesValue {
1300 let choice: ChoicesValue = {
1301 value: cv.community.id.toString(),
1302 label: communitySelectName(cv),
1307 export function personToChoice(pvs: PersonViewSafe): ChoicesValue {
1308 let choice: ChoicesValue = {
1309 value: pvs.person.id.toString(),
1310 label: personSelectName(pvs),
1315 export async function fetchCommunities(q: string) {
1316 let form: Search = {
1318 type_: Some(SearchType.Communities),
1319 sort: Some(SortType.TopAll),
1320 listing_type: Some(ListingType.All),
1322 limit: Some(fetchLimit),
1324 community_name: None,
1326 auth: auth(false).ok(),
1328 let client = new LemmyHttp(httpBase);
1329 return client.search(form);
1332 export async function fetchUsers(q: string) {
1333 let form: Search = {
1335 type_: Some(SearchType.Users),
1336 sort: Some(SortType.TopAll),
1337 listing_type: Some(ListingType.All),
1339 limit: Some(fetchLimit),
1341 community_name: None,
1343 auth: auth(false).ok(),
1345 let client = new LemmyHttp(httpBase);
1346 return client.search(form);
1349 export const choicesConfig = {
1351 searchResultLimit: fetchLimit,
1353 containerOuter: "choices",
1354 containerInner: "choices__inner bg-secondary border-0",
1355 input: "form-control",
1356 inputCloned: "choices__input--cloned",
1357 list: "choices__list",
1358 listItems: "choices__list--multiple",
1359 listSingle: "choices__list--single",
1360 listDropdown: "choices__list--dropdown",
1361 item: "choices__item bg-secondary",
1362 itemSelectable: "choices__item--selectable",
1363 itemDisabled: "choices__item--disabled",
1364 itemChoice: "choices__item--choice",
1365 placeholder: "choices__placeholder",
1366 group: "choices__group",
1367 groupHeading: "choices__heading",
1368 button: "choices__button",
1369 activeState: "is-active",
1370 focusState: "is-focused",
1371 openState: "is-open",
1372 disabledState: "is-disabled",
1373 highlightedState: "text-info",
1374 selectedState: "text-info",
1375 flippedState: "is-flipped",
1376 loadingState: "is-loading",
1377 noResults: "has-no-results",
1378 noChoices: "has-no-choices",
1382 export function communitySelectName(cv: CommunityView): string {
1383 return cv.community.local
1384 ? cv.community.title
1385 : `${hostname(cv.community.actor_id)}/${cv.community.title}`;
1388 export function personSelectName(pvs: PersonViewSafe): string {
1389 let pName = pvs.person.display_name.unwrapOr(pvs.person.name);
1390 return pvs.person.local ? pName : `${hostname(pvs.person.actor_id)}/${pName}`;
1393 export function initializeSite(site: GetSiteResponse) {
1394 UserService.Instance.myUserInfo = site.my_user;
1395 i18n.changeLanguage(getLanguages()[0]);
1398 const SHORTNUM_SI_FORMAT = new Intl.NumberFormat("en-US", {
1399 maximumSignificantDigits: 3,
1401 notation: "compact",
1402 compactDisplay: "short",
1405 export function numToSI(value: number): string {
1406 return SHORTNUM_SI_FORMAT.format(value);
1409 export function isBanned(ps: PersonSafe): boolean {
1410 let expires = ps.ban_expires;
1411 // Add Z to convert from UTC date
1412 // TODO this check probably isn't necessary anymore
1413 if (expires.isSome()) {
1414 if (ps.banned && new Date(expires.unwrap() + "Z") > new Date()) {
1424 export function pushNotNull(array: any[], new_item?: any) {
1426 array.push(...new_item);
1430 export function auth(throwErr = true): Result<string, string> {
1431 return UserService.Instance.auth(throwErr);
1434 export function enableDownvotes(siteRes: GetSiteResponse): boolean {
1435 return siteRes.site_view.map(s => s.site.enable_downvotes).unwrapOr(true);
1438 export function enableNsfw(siteRes: GetSiteResponse): boolean {
1439 return siteRes.site_view.map(s => s.site.enable_nsfw).unwrapOr(false);