1 import emojiShortName from "emoji-short-name";
3 BlockCommunityResponse,
21 RegistrationApplicationView,
27 WebSocketJsonResponse,
29 } from "lemmy-js-client";
30 import markdown_it from "markdown-it";
31 import markdown_it_container from "markdown-it-container";
32 import markdown_it_footnote from "markdown-it-footnote";
33 import markdown_it_html5_embed from "markdown-it-html5-embed";
34 import markdown_it_sub from "markdown-it-sub";
35 import markdown_it_sup from "markdown-it-sup";
36 import moment from "moment";
37 import { Subscription } from "rxjs";
38 import { delay, retryWhen, take } from "rxjs/operators";
39 import tippy from "tippy.js";
40 import Toastify from "toastify-js";
41 import { httpBase } from "./env";
42 import { i18n, languages } from "./i18next";
44 CommentNode as CommentNodeI,
48 } from "./interfaces";
49 import { UserService, WebSocketService } from "./services";
53 Tribute = require("tributejs");
56 export const wsClient = new LemmyWebsocket();
58 export const favIconUrl = "/static/assets/icons/favicon.svg";
59 export const favIconPngUrl = "/static/assets/icons/apple-touch-icon.png";
61 // export const defaultFavIcon = `${window.location.protocol}//${window.location.host}${favIconPngUrl}`;
62 export const repoUrl = "https://github.com/LemmyNet";
63 export const joinLemmyUrl = "https://join-lemmy.org";
64 export const donateLemmyUrl = `${joinLemmyUrl}/donate`;
65 export const docsUrl = `${joinLemmyUrl}/docs/en/index.html`;
66 export const helpGuideUrl = `${joinLemmyUrl}/docs/en/about/guide.html`; // TODO find a way to redirect to the non-en folder
67 export const markdownHelpUrl = `${helpGuideUrl}#using-markdown`;
68 export const sortingHelpUrl = `${helpGuideUrl}#sorting`;
69 export const archiveTodayUrl = "https://archive.today";
70 export const ghostArchiveUrl = "https://ghostarchive.org";
71 export const webArchiveUrl = "https://web.archive.org";
72 export const elementUrl = "https://element.io";
74 export const postRefetchSeconds: number = 60 * 1000;
75 export const fetchLimit = 20;
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 function wsJsonToRes<ResponseType>(
103 msg: WebSocketJsonResponse<ResponseType>
104 ): WebSocketResponse<ResponseType> {
111 export function wsUserOp(msg: any): UserOperation {
112 let opStr: string = msg.op;
113 return UserOperation[opStr];
116 export const md = new markdown_it({
121 .use(markdown_it_sub)
122 .use(markdown_it_sup)
123 .use(markdown_it_footnote)
124 .use(markdown_it_html5_embed, {
126 useImageSyntax: true, // Enables video/audio embed with ![]() syntax (default)
128 audio: 'controls preload="metadata"',
130 'width="100%" max-height="100%" controls loop preload="metadata"',
134 .use(markdown_it_container, "spoiler", {
135 validate: function (params: any) {
136 return params.trim().match(/^spoiler\s+(.*)$/);
139 render: function (tokens: any, idx: any) {
140 var m = tokens[idx].info.trim().match(/^spoiler\s+(.*)$/);
142 if (tokens[idx].nesting === 1) {
144 return `<details><summary> ${md.utils.escapeHtml(m[1])} </summary>\n`;
147 return "</details>\n";
152 export function hotRankComment(comment_view: CommentView): number {
153 return hotRank(comment_view.counts.score, comment_view.comment.published);
156 export function hotRankActivePost(post_view: PostView): number {
157 return hotRank(post_view.counts.score, post_view.counts.newest_comment_time);
160 export function hotRankPost(post_view: PostView): number {
161 return hotRank(post_view.counts.score, post_view.post.published);
164 export function hotRank(score: number, timeStr: string): number {
165 // Rank = ScaleFactor * sign(Score) * log(1 + abs(Score)) / (Time + 2)^Gravity
166 let date: Date = new Date(timeStr + "Z"); // Add Z to convert from UTC date
167 let now: Date = new Date();
168 let hoursElapsed: number = (now.getTime() - date.getTime()) / 36e5;
171 (10000 * Math.log10(Math.max(1, 3 + score))) /
172 Math.pow(hoursElapsed + 2, 1.8);
174 // console.log(`Comment: ${comment.content}\nRank: ${rank}\nScore: ${comment.score}\nHours: ${hoursElapsed}`);
179 export function mdToHtml(text: string) {
180 return { __html: md.render(text) };
183 export function getUnixTime(text: string): number {
184 return text ? new Date(text).getTime() / 1000 : undefined;
187 export function futureDaysToUnixTime(days: number): number {
190 new Date(Date.now() + 1000 * 60 * 60 * 24 * days).getTime() / 1000
195 export function canMod(
196 myUserInfo: MyUserInfo,
201 // You can do moderator actions only on the mods added after you.
203 let yourIndex = modIds.findIndex(
204 id => id == myUserInfo.local_user_view.person.id
206 if (yourIndex == -1) {
209 // onSelf +1 on mod actions not for yourself, IE ban, remove, etc
210 modIds = modIds.slice(0, yourIndex + (onSelf ? 0 : 1));
211 return !modIds.includes(creator_id);
218 export function isMod(modIds: number[], creator_id: number): boolean {
219 return modIds.includes(creator_id);
222 const imageRegex = /(http)?s?:?(\/\/[^"']*\.(?:jpg|jpeg|gif|png|svg|webp))/;
223 const videoRegex = /(http)?s?:?(\/\/[^"']*\.(?:mp4|webm))/;
225 export function isImage(url: string) {
226 return imageRegex.test(url);
229 export function isVideo(url: string) {
230 return videoRegex.test(url);
233 export function validURL(str: string) {
234 return !!new URL(str);
237 export function communityRSSUrl(actorId: string, sort: string): string {
238 let url = new URL(actorId);
239 return `${url.origin}/feeds${url.pathname}.xml?sort=${sort}`;
242 export function validEmail(email: string) {
244 /^(([^\s"(),.:;<>@[\\\]]+(\.[^\s"(),.:;<>@[\\\]]+)*)|(".+"))@((\[(?:\d{1,3}\.){3}\d{1,3}])|(([\dA-Za-z\-]+\.)+[A-Za-z]{2,}))$/;
245 return re.test(String(email).toLowerCase());
248 export function capitalizeFirstLetter(str: string): string {
249 return str.charAt(0).toUpperCase() + str.slice(1);
252 export function routeSortTypeToEnum(sort: string): SortType {
253 return SortType[sort];
256 export function listingTypeFromNum(type_: number): ListingType {
257 return Object.values(ListingType)[type_];
260 export function sortTypeFromNum(type_: number): SortType {
261 return Object.values(SortType)[type_];
264 export function routeListingTypeToEnum(type: string): ListingType {
265 return ListingType[type];
268 export function routeDataTypeToEnum(type: string): DataType {
269 return DataType[capitalizeFirstLetter(type)];
272 export function routeSearchTypeToEnum(type: string): SearchType {
273 return SearchType[type];
276 export async function getSiteMetadata(url: string) {
277 let form: GetSiteMetadata = {
280 let client = new LemmyHttp(httpBase);
281 return client.getSiteMetadata(form);
284 export function debounce(func: any, wait = 1000, immediate = false) {
285 // 'private' variable for instance
286 // The returned function will be able to reference this due to closure.
287 // Each call to the returned function will share this common timer.
290 // Calling debounce returns a new anonymous function
292 // reference the context and args for the setTimeout function
293 var args = arguments;
295 // Should the function be called now? If immediate is true
296 // and not already in a timeout then the answer is: Yes
297 var callNow = immediate && !timeout;
299 // This is the basic debounce behaviour where you can call this
300 // function several times, but it will only execute once
301 // [before or after imposing a delay].
302 // Each time the returned function is called, the timer starts over.
303 clearTimeout(timeout);
305 // Set the new timeout
306 timeout = setTimeout(function () {
307 // Inside the timeout function, clear the timeout variable
308 // which will let the next execution run when in 'immediate' mode
311 // Check if the function already ran with the immediate flag
313 // Call the original function with apply
314 // apply lets you define the 'this' object as well as the arguments
315 // (both captured before setTimeout)
316 func.apply(this, args);
320 // Immediate mode and no wait timer? Execute the function..
321 if (callNow) func.apply(this, args);
325 export function getLanguages(override?: string): string[] {
326 let myUserInfo = UserService.Instance.myUserInfo;
329 (myUserInfo?.local_user_view.local_user.lang
330 ? myUserInfo.local_user_view.local_user.lang
333 if (lang == "browser" && isBrowser()) {
334 return getBrowserLanguages();
340 function getBrowserLanguages(): string[] {
341 // Intersect lemmy's langs, with the browser langs
342 let langs = languages ? languages.map(l => l.code) : ["en"];
344 // NOTE, mobile browsers seem to be missing this list, so append en
345 let allowedLangs = navigator.languages
347 .filter(v => langs.includes(v));
351 export async function fetchThemeList(): Promise<string[]> {
352 return fetch("/css/themelist").then(res => res.json());
355 export async function setTheme(theme: string, forceReload = false) {
359 if (theme === "browser" && !forceReload) {
362 // This is only run on a force reload
363 if (theme == "browser") {
367 let themeList = await fetchThemeList();
369 // Unload all the other themes
370 for (var i = 0; i < themeList.length; i++) {
371 let styleSheet = document.getElementById(themeList[i]);
373 styleSheet.setAttribute("disabled", "disabled");
378 .getElementById("default-light")
379 ?.setAttribute("disabled", "disabled");
380 document.getElementById("default-dark")?.setAttribute("disabled", "disabled");
382 // Load the theme dynamically
383 let cssLoc = `/css/themes/${theme}.min.css`;
385 loadCss(theme, cssLoc);
386 document.getElementById(theme).removeAttribute("disabled");
389 export function loadCss(id: string, loc: string) {
390 if (!document.getElementById(id)) {
391 var head = document.getElementsByTagName("head")[0];
392 var link = document.createElement("link");
394 link.rel = "stylesheet";
395 link.type = "text/css";
398 head.appendChild(link);
402 export function objectFlip(obj: any) {
404 Object.keys(obj).forEach(key => {
410 export function showAvatars(): boolean {
412 UserService.Instance.myUserInfo?.local_user_view.local_user.show_avatars ||
413 !UserService.Instance.myUserInfo
417 export function showScores(): boolean {
419 UserService.Instance.myUserInfo?.local_user_view.local_user.show_scores ||
420 !UserService.Instance.myUserInfo
424 export function isCakeDay(published: string): boolean {
425 // moment(undefined) or moment.utc(undefined) returns the current date/time
426 // moment(null) or moment.utc(null) returns null
427 const createDate = moment.utc(published || null).local();
428 const currentDate = moment(new Date());
431 createDate.date() === currentDate.date() &&
432 createDate.month() === currentDate.month() &&
433 createDate.year() !== currentDate.year()
437 export function toast(text: string, background = "success") {
439 let backgroundColor = `var(--${background})`;
442 backgroundColor: backgroundColor,
449 export function pictrsDeleteToast(
450 clickToDeleteText: string,
451 deletePictureText: string,
455 let backgroundColor = `var(--light)`;
456 let toast = Toastify({
457 text: clickToDeleteText,
458 backgroundColor: backgroundColor,
464 window.location.replace(deleteUrl);
465 alert(deletePictureText);
474 interface NotifyInfo {
481 export function messageToastify(info: NotifyInfo, router: any) {
483 let htmlBody = info.body ? md.render(info.body) : "";
484 let backgroundColor = `var(--light)`;
486 let toast = Toastify({
487 text: `${htmlBody}<br />${info.name}`,
488 avatar: info.icon ? info.icon : null,
489 backgroundColor: backgroundColor,
490 className: "text-dark",
499 router.history.push(info.link);
506 export function notifyPost(post_view: PostView, router: any) {
507 let info: NotifyInfo = {
508 name: post_view.community.name,
509 icon: post_view.community.icon,
510 link: `/post/${post_view.post.id}`,
511 body: post_view.post.name,
513 notify(info, router);
516 export function notifyComment(comment_view: CommentView, router: any) {
517 let info: NotifyInfo = {
518 name: comment_view.creator.name,
519 icon: comment_view.creator.avatar,
520 link: `/post/${comment_view.post.id}/comment/${comment_view.comment.id}`,
521 body: comment_view.comment.content,
523 notify(info, router);
526 export function notifyPrivateMessage(pmv: PrivateMessageView, router: any) {
527 let info: NotifyInfo = {
528 name: pmv.creator.name,
529 icon: pmv.creator.avatar,
531 body: pmv.private_message.content,
533 notify(info, router);
536 function notify(info: NotifyInfo, router: any) {
537 messageToastify(info, router);
539 // TODO absolute nightmare bug, but notifs are currently broken.
540 // Notification.new will try to do a browser fetch ???
542 // if (Notification.permission !== "granted") Notification.requestPermission();
544 // var notification = new Notification(info.name, {
549 // notification.onclick = (ev: Event): any => {
550 // ev.preventDefault();
551 // router.history.push(info.link);
556 export function setupTribute() {
558 noMatchTemplate: function () {
565 menuItemTemplate: (item: any) => {
566 let shortName = `:${item.original.key}:`;
567 return `${item.original.val} ${shortName}`;
569 selectTemplate: (item: any) => {
570 return `${item.original.val}`;
572 values: Object.entries(emojiShortName).map(e => {
573 return { key: e[1], val: e[0] };
576 autocompleteMode: true,
578 // menuItemLimit: mentionDropdownFetchLimit,
579 menuShowMinLength: 2,
584 selectTemplate: (item: any) => {
585 let it: PersonTribute = item.original;
586 return `[${it.key}](${it.view.person.actor_id})`;
588 values: (text: string, cb: (persons: PersonTribute[]) => any) => {
589 personSearch(text, (persons: PersonTribute[]) => cb(persons));
592 autocompleteMode: true,
594 // menuItemLimit: mentionDropdownFetchLimit,
595 menuShowMinLength: 2,
601 selectTemplate: (item: any) => {
602 let it: CommunityTribute = item.original;
603 return `[${it.key}](${it.view.community.actor_id})`;
605 values: (text: string, cb: any) => {
606 communitySearch(text, (communities: CommunityTribute[]) =>
611 autocompleteMode: true,
613 // menuItemLimit: mentionDropdownFetchLimit,
614 menuShowMinLength: 2,
620 var tippyInstance: any;
622 tippyInstance = tippy("[data-tippy-content]");
625 export function setupTippy() {
627 tippyInstance.forEach((e: any) => e.destroy());
628 tippyInstance = tippy("[data-tippy-content]", {
630 // Display on "long press"
631 touch: ["hold", 500],
636 interface PersonTribute {
638 view: PersonViewSafe;
641 function personSearch(text: string, cb: (persons: PersonTribute[]) => any) {
645 type_: SearchType.Users,
646 sort: SortType.TopAll,
647 listing_type: ListingType.All,
649 limit: mentionDropdownFetchLimit,
650 auth: authField(false),
653 WebSocketService.Instance.send(wsClient.search(form));
655 let personSub = WebSocketService.Instance.subject.subscribe(
657 let res = wsJsonToRes(msg);
658 if (res.op == UserOperation.Search) {
659 let data = res.data as SearchResponse;
660 let persons: PersonTribute[] = data.users.map(pv => {
661 let tribute: PersonTribute = {
662 key: `@${pv.person.name}@${hostname(pv.person.actor_id)}`,
668 personSub.unsubscribe();
671 err => console.error(err),
672 () => console.log("complete")
679 interface CommunityTribute {
684 function communitySearch(
686 cb: (communities: CommunityTribute[]) => any
691 type_: SearchType.Communities,
692 sort: SortType.TopAll,
693 listing_type: ListingType.All,
695 limit: mentionDropdownFetchLimit,
696 auth: authField(false),
699 WebSocketService.Instance.send(wsClient.search(form));
701 let communitySub = WebSocketService.Instance.subject.subscribe(
703 let res = wsJsonToRes(msg);
704 if (res.op == UserOperation.Search) {
705 let data = res.data as SearchResponse;
706 let communities: CommunityTribute[] = data.communities.map(cv => {
707 let tribute: CommunityTribute = {
708 key: `!${cv.community.name}@${hostname(cv.community.actor_id)}`,
714 communitySub.unsubscribe();
717 err => console.error(err),
718 () => console.log("complete")
725 export function getListingTypeFromProps(props: any): ListingType {
726 return props.match.params.listing_type
727 ? routeListingTypeToEnum(props.match.params.listing_type)
728 : UserService.Instance.myUserInfo
729 ? Object.values(ListingType)[
730 UserService.Instance.myUserInfo.local_user_view.local_user
731 .default_listing_type
736 export function getListingTypeFromPropsNoDefault(props: any): ListingType {
737 return props.match.params.listing_type
738 ? routeListingTypeToEnum(props.match.params.listing_type)
742 // TODO might need to add a user setting for this too
743 export function getDataTypeFromProps(props: any): DataType {
744 return props.match.params.data_type
745 ? routeDataTypeToEnum(props.match.params.data_type)
749 export function getSortTypeFromProps(props: any): SortType {
750 return props.match.params.sort
751 ? routeSortTypeToEnum(props.match.params.sort)
752 : UserService.Instance.myUserInfo
753 ? Object.values(SortType)[
754 UserService.Instance.myUserInfo.local_user_view.local_user
760 export function getPageFromProps(props: any): number {
761 return props.match.params.page ? Number(props.match.params.page) : 1;
764 export function getRecipientIdFromProps(props: any): number {
765 return props.match.params.recipient_id
766 ? Number(props.match.params.recipient_id)
770 export function getIdFromProps(props: any): number {
771 return Number(props.match.params.id);
774 export function getCommentIdFromProps(props: any): number {
775 return Number(props.match.params.comment_id);
778 export function getUsernameFromProps(props: any): string {
779 return props.match.params.username;
782 export function editCommentRes(data: CommentView, comments: CommentView[]) {
783 let found = comments.find(c => c.comment.id == data.comment.id);
785 found.comment.content = data.comment.content;
786 found.comment.updated = data.comment.updated;
787 found.comment.removed = data.comment.removed;
788 found.comment.deleted = data.comment.deleted;
789 found.counts.upvotes = data.counts.upvotes;
790 found.counts.downvotes = data.counts.downvotes;
791 found.counts.score = data.counts.score;
795 export function saveCommentRes(data: CommentView, comments: CommentView[]) {
796 let found = comments.find(c => c.comment.id == data.comment.id);
798 found.saved = data.saved;
802 export function updatePersonBlock(
803 data: BlockPersonResponse
804 ): PersonBlockView[] {
806 UserService.Instance.myUserInfo.person_blocks.push({
807 person: UserService.Instance.myUserInfo.local_user_view.person,
808 target: data.person_view.person,
810 toast(`${i18n.t("blocked")} ${data.person_view.person.name}`);
812 UserService.Instance.myUserInfo.person_blocks =
813 UserService.Instance.myUserInfo.person_blocks.filter(
814 i => i.target.id != data.person_view.person.id
816 toast(`${i18n.t("unblocked")} ${data.person_view.person.name}`);
818 return UserService.Instance.myUserInfo.person_blocks;
821 export function updateCommunityBlock(
822 data: BlockCommunityResponse
823 ): CommunityBlockView[] {
825 UserService.Instance.myUserInfo.community_blocks.push({
826 person: UserService.Instance.myUserInfo.local_user_view.person,
827 community: data.community_view.community,
829 toast(`${i18n.t("blocked")} ${data.community_view.community.name}`);
831 UserService.Instance.myUserInfo.community_blocks =
832 UserService.Instance.myUserInfo.community_blocks.filter(
833 i => i.community.id != data.community_view.community.id
835 toast(`${i18n.t("unblocked")} ${data.community_view.community.name}`);
837 return UserService.Instance.myUserInfo.community_blocks;
840 export function createCommentLikeRes(
842 comments: CommentView[]
844 let found = comments.find(c => c.comment.id === data.comment.id);
846 found.counts.score = data.counts.score;
847 found.counts.upvotes = data.counts.upvotes;
848 found.counts.downvotes = data.counts.downvotes;
849 if (data.my_vote !== null) {
850 found.my_vote = data.my_vote;
855 export function createPostLikeFindRes(data: PostView, posts: PostView[]) {
856 let found = posts.find(p => p.post.id == data.post.id);
858 createPostLikeRes(data, found);
862 export function createPostLikeRes(data: PostView, post_view: PostView) {
864 post_view.counts.score = data.counts.score;
865 post_view.counts.upvotes = data.counts.upvotes;
866 post_view.counts.downvotes = data.counts.downvotes;
867 if (data.my_vote !== null) {
868 post_view.my_vote = data.my_vote;
873 export function editPostFindRes(data: PostView, posts: PostView[]) {
874 let found = posts.find(p => p.post.id == data.post.id);
876 editPostRes(data, found);
880 export function editPostRes(data: PostView, post: PostView) {
882 post.post.url = data.post.url;
883 post.post.name = data.post.name;
884 post.post.nsfw = data.post.nsfw;
885 post.post.deleted = data.post.deleted;
886 post.post.removed = data.post.removed;
887 post.post.stickied = data.post.stickied;
888 post.post.body = data.post.body;
889 post.post.locked = data.post.locked;
890 post.saved = data.saved;
894 export function updatePostReportRes(
895 data: PostReportView,
896 reports: PostReportView[]
898 let found = reports.find(p => p.post_report.id == data.post_report.id);
900 found.post_report = data.post_report;
904 export function updateCommentReportRes(
905 data: CommentReportView,
906 reports: CommentReportView[]
908 let found = reports.find(c => c.comment_report.id == data.comment_report.id);
910 found.comment_report = data.comment_report;
914 export function updateRegistrationApplicationRes(
915 data: RegistrationApplicationView,
916 applications: RegistrationApplicationView[]
918 let found = applications.find(
919 ra => ra.registration_application.id == data.registration_application.id
922 found.registration_application = data.registration_application;
923 found.admin = data.admin;
924 found.creator_local_user = data.creator_local_user;
928 export function commentsToFlatNodes(comments: CommentView[]): CommentNodeI[] {
929 let nodes: CommentNodeI[] = [];
930 for (let comment of comments) {
931 nodes.push({ comment_view: comment });
936 function commentSort(tree: CommentNodeI[], sort: CommentSortType) {
937 // First, put removed and deleted comments at the bottom, then do your other sorts
938 if (sort == CommentSortType.Top) {
941 +a.comment_view.comment.removed - +b.comment_view.comment.removed ||
942 +a.comment_view.comment.deleted - +b.comment_view.comment.deleted ||
943 b.comment_view.counts.score - a.comment_view.counts.score
945 } else if (sort == CommentSortType.New) {
948 +a.comment_view.comment.removed - +b.comment_view.comment.removed ||
949 +a.comment_view.comment.deleted - +b.comment_view.comment.deleted ||
950 b.comment_view.comment.published.localeCompare(
951 a.comment_view.comment.published
954 } else if (sort == CommentSortType.Old) {
957 +a.comment_view.comment.removed - +b.comment_view.comment.removed ||
958 +a.comment_view.comment.deleted - +b.comment_view.comment.deleted ||
959 a.comment_view.comment.published.localeCompare(
960 b.comment_view.comment.published
963 } else if (sort == CommentSortType.Hot) {
966 +a.comment_view.comment.removed - +b.comment_view.comment.removed ||
967 +a.comment_view.comment.deleted - +b.comment_view.comment.deleted ||
968 hotRankComment(b.comment_view) - hotRankComment(a.comment_view)
972 // Go through the children recursively
973 for (let node of tree) {
975 commentSort(node.children, sort);
980 export function commentSortSortType(tree: CommentNodeI[], sort: SortType) {
981 commentSort(tree, convertCommentSortType(sort));
984 function convertCommentSortType(sort: SortType): CommentSortType {
986 sort == SortType.TopAll ||
987 sort == SortType.TopDay ||
988 sort == SortType.TopWeek ||
989 sort == SortType.TopMonth ||
990 sort == SortType.TopYear
992 return CommentSortType.Top;
993 } else if (sort == SortType.New) {
994 return CommentSortType.New;
995 } else if (sort == SortType.Hot || sort == SortType.Active) {
996 return CommentSortType.Hot;
998 return CommentSortType.Hot;
1002 export function buildCommentsTree(
1003 comments: CommentView[],
1004 commentSortType: CommentSortType
1006 let map = new Map<number, CommentNodeI>();
1007 for (let comment_view of comments) {
1008 let node: CommentNodeI = {
1009 comment_view: comment_view,
1012 map.set(comment_view.comment.id, { ...node });
1014 let tree: CommentNodeI[] = [];
1015 for (let comment_view of comments) {
1016 let child = map.get(comment_view.comment.id);
1017 let parent_id = comment_view.comment.parent_id;
1019 let parent = map.get(parent_id);
1020 // Necessary because blocked comment might not exist
1022 parent.children.push(child);
1031 commentSort(tree, commentSortType);
1036 function setDepth(node: CommentNodeI, i = 0) {
1037 for (let child of node.children) {
1039 setDepth(child, i + 1);
1043 export function insertCommentIntoTree(tree: CommentNodeI[], cv: CommentView) {
1044 // Building a fake node to be used for later
1045 let node: CommentNodeI = {
1051 if (cv.comment.parent_id) {
1052 let parentComment = searchCommentTree(tree, cv.comment.parent_id);
1053 if (parentComment) {
1054 node.depth = parentComment.depth + 1;
1055 parentComment.children.unshift(node);
1062 export function searchCommentTree(
1063 tree: CommentNodeI[],
1066 for (let node of tree) {
1067 if (node.comment_view.comment.id === id) {
1071 for (const child of node.children) {
1072 const res = searchCommentTree([child], id);
1082 export const colorList: string[] = [
1091 function hsl(num: number) {
1092 return `hsla(${num}, 35%, 50%, 1)`;
1095 export function previewLines(
1104 // Use lines * 2 because markdown requires 2 lines
1105 .slice(0, maxLines * 2)
1110 export function hostname(url: string): string {
1111 let cUrl = new URL(url);
1112 return cUrl.port ? `${cUrl.hostname}:${cUrl.port}` : `${cUrl.hostname}`;
1115 export function validTitle(title?: string): boolean {
1116 // Initial title is null, minimum length is taken care of by textarea's minLength={3}
1117 if (title === null || title.length < 3) return true;
1119 const regex = new RegExp(/.*\S.*/, "g");
1121 return regex.test(title);
1124 export function siteBannerCss(banner: string): string {
1126 background-image: linear-gradient( rgba(0, 0, 0, 0.8), rgba(0, 0, 0, 0.8) ) ,url("${banner}"); \
1127 background-attachment: fixed; \
1128 background-position: top; \
1129 background-repeat: no-repeat; \
1130 background-size: 100% cover; \
1133 max-height: 100vh; \
1137 export function isBrowser() {
1138 return typeof window !== "undefined";
1141 export function setIsoData(context: any): IsoData {
1142 let isoData: IsoData = isBrowser()
1144 : context.router.staticContext;
1148 export function wsSubscribe(parseMessage: any): Subscription {
1150 return WebSocketService.Instance.subject
1151 .pipe(retryWhen(errors => errors.pipe(delay(3000), take(10))))
1153 msg => parseMessage(msg),
1154 err => console.error(err),
1155 () => console.log("complete")
1162 export function setOptionalAuth(obj: any, auth = UserService.Instance.auth) {
1168 export function authField(
1170 auth = UserService.Instance.auth
1172 if (auth == null && throwErr) {
1173 toast(i18n.t("not_logged_in"), "danger");
1174 throw "Not logged in";
1180 moment.updateLocale("en", {
1201 export function saveScrollPosition(context: any) {
1202 let path: string = context.router.route.location.pathname;
1203 let y = window.scrollY;
1204 sessionStorage.setItem(`scrollPosition_${path}`, y.toString());
1207 export function restoreScrollPosition(context: any) {
1208 let path: string = context.router.route.location.pathname;
1209 let y = Number(sessionStorage.getItem(`scrollPosition_${path}`));
1210 window.scrollTo(0, y);
1213 export function showLocal(isoData: IsoData): boolean {
1214 return isoData.site_res.federated_instances?.linked.length > 0;
1217 interface ChoicesValue {
1222 export function communityToChoice(cv: CommunityView): ChoicesValue {
1223 let choice: ChoicesValue = {
1224 value: cv.community.id.toString(),
1225 label: communitySelectName(cv),
1230 export function personToChoice(pvs: PersonViewSafe): ChoicesValue {
1231 let choice: ChoicesValue = {
1232 value: pvs.person.id.toString(),
1233 label: personSelectName(pvs),
1238 export async function fetchCommunities(q: string) {
1239 let form: Search = {
1241 type_: SearchType.Communities,
1242 sort: SortType.TopAll,
1243 listing_type: ListingType.All,
1246 auth: authField(false),
1248 let client = new LemmyHttp(httpBase);
1249 return client.search(form);
1252 export async function fetchUsers(q: string) {
1253 let form: Search = {
1255 type_: SearchType.Users,
1256 sort: SortType.TopAll,
1257 listing_type: ListingType.All,
1260 auth: authField(false),
1262 let client = new LemmyHttp(httpBase);
1263 return client.search(form);
1266 export const choicesConfig = {
1268 searchResultLimit: fetchLimit,
1270 containerOuter: "choices",
1271 containerInner: "choices__inner bg-secondary border-0",
1272 input: "form-control",
1273 inputCloned: "choices__input--cloned",
1274 list: "choices__list",
1275 listItems: "choices__list--multiple",
1276 listSingle: "choices__list--single",
1277 listDropdown: "choices__list--dropdown",
1278 item: "choices__item bg-secondary",
1279 itemSelectable: "choices__item--selectable",
1280 itemDisabled: "choices__item--disabled",
1281 itemChoice: "choices__item--choice",
1282 placeholder: "choices__placeholder",
1283 group: "choices__group",
1284 groupHeading: "choices__heading",
1285 button: "choices__button",
1286 activeState: "is-active",
1287 focusState: "is-focused",
1288 openState: "is-open",
1289 disabledState: "is-disabled",
1290 highlightedState: "text-info",
1291 selectedState: "text-info",
1292 flippedState: "is-flipped",
1293 loadingState: "is-loading",
1294 noResults: "has-no-results",
1295 noChoices: "has-no-choices",
1299 export function communitySelectName(cv: CommunityView): string {
1300 return cv.community.local
1301 ? cv.community.title
1302 : `${hostname(cv.community.actor_id)}/${cv.community.title}`;
1305 export function personSelectName(pvs: PersonViewSafe): string {
1306 let pName = pvs.person.display_name || pvs.person.name;
1307 return pvs.person.local ? pName : `${hostname(pvs.person.actor_id)}/${pName}`;
1310 export function initializeSite(site: GetSiteResponse) {
1311 UserService.Instance.myUserInfo = site.my_user;
1312 i18n.changeLanguage(getLanguages()[0]);
1315 const SHORTNUM_SI_FORMAT = new Intl.NumberFormat("en-US", {
1316 maximumSignificantDigits: 3,
1318 notation: "compact",
1319 compactDisplay: "short",
1322 export function numToSI(value: number): string {
1323 return SHORTNUM_SI_FORMAT.format(value);
1326 export function isBanned(ps: PersonSafe): boolean {
1327 // Add Z to convert from UTC date
1328 if (ps.ban_expires) {
1329 if (ps.banned && new Date(ps.ban_expires + "Z") > new Date()) {