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 themes = [
95 const DEFAULT_ALPHABET =
96 "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
98 function getRandomCharFromAlphabet(alphabet: string): string {
99 return alphabet.charAt(Math.floor(Math.random() * alphabet.length));
102 export function randomStr(
103 idDesiredLength = 20,
104 alphabet = DEFAULT_ALPHABET
107 * Create n-long array and map it to random chars from given alphabet.
108 * Then join individual chars as string
110 return Array.from({ length: idDesiredLength })
112 return getRandomCharFromAlphabet(alphabet);
117 export function wsJsonToRes<ResponseType>(
118 msg: WebSocketJsonResponse<ResponseType>
119 ): WebSocketResponse<ResponseType> {
126 export function wsUserOp(msg: any): UserOperation {
127 let opStr: string = msg.op;
128 return UserOperation[opStr];
131 export const md = new markdown_it({
136 .use(markdown_it_sub)
137 .use(markdown_it_sup)
138 .use(markdown_it_footnote)
139 .use(markdown_it_html5_embed, {
141 useImageSyntax: true, // Enables video/audio embed with ![]() syntax (default)
143 audio: 'controls preload="metadata"',
145 'width="100%" max-height="100%" controls loop preload="metadata"',
149 .use(markdown_it_container, "spoiler", {
150 validate: function (params: any) {
151 return params.trim().match(/^spoiler\s+(.*)$/);
154 render: function (tokens: any, idx: any) {
155 var m = tokens[idx].info.trim().match(/^spoiler\s+(.*)$/);
157 if (tokens[idx].nesting === 1) {
159 return `<details><summary> ${md.utils.escapeHtml(m[1])} </summary>\n`;
162 return "</details>\n";
167 export function hotRankComment(comment_view: CommentView): number {
168 return hotRank(comment_view.counts.score, comment_view.comment.published);
171 export function hotRankActivePost(post_view: PostView): number {
172 return hotRank(post_view.counts.score, post_view.counts.newest_comment_time);
175 export function hotRankPost(post_view: PostView): number {
176 return hotRank(post_view.counts.score, post_view.post.published);
179 export function hotRank(score: number, timeStr: string): number {
180 // Rank = ScaleFactor * sign(Score) * log(1 + abs(Score)) / (Time + 2)^Gravity
181 let date: Date = new Date(timeStr + "Z"); // Add Z to convert from UTC date
182 let now: Date = new Date();
183 let hoursElapsed: number = (now.getTime() - date.getTime()) / 36e5;
186 (10000 * Math.log10(Math.max(1, 3 + score))) /
187 Math.pow(hoursElapsed + 2, 1.8);
189 // console.log(`Comment: ${comment.content}\nRank: ${rank}\nScore: ${comment.score}\nHours: ${hoursElapsed}`);
194 export function mdToHtml(text: string) {
195 return { __html: md.render(text) };
198 export function getUnixTime(text: string): number {
199 return text ? new Date(text).getTime() / 1000 : undefined;
202 export function futureDaysToUnixTime(days: number): number {
205 new Date(Date.now() + 1000 * 60 * 60 * 24 * days).getTime() / 1000
210 export function canMod(
211 myUserInfo: MyUserInfo,
216 // You can do moderator actions only on the mods added after you.
218 let yourIndex = modIds.findIndex(
219 id => id == myUserInfo.local_user_view.person.id
221 if (yourIndex == -1) {
224 // onSelf +1 on mod actions not for yourself, IE ban, remove, etc
225 modIds = modIds.slice(0, yourIndex + (onSelf ? 0 : 1));
226 return !modIds.includes(creator_id);
233 export function isMod(modIds: number[], creator_id: number): boolean {
234 return modIds.includes(creator_id);
237 const imageRegex = /(http)?s?:?(\/\/[^"']*\.(?:jpg|jpeg|gif|png|svg|webp))/;
238 const videoRegex = /(http)?s?:?(\/\/[^"']*\.(?:mp4|webm))/;
240 export function isImage(url: string) {
241 return imageRegex.test(url);
244 export function isVideo(url: string) {
245 return videoRegex.test(url);
248 export function validURL(str: string) {
249 return !!new URL(str);
252 export function communityRSSUrl(actorId: string, sort: string): string {
253 let url = new URL(actorId);
254 return `${url.origin}/feeds${url.pathname}.xml?sort=${sort}`;
257 export function validEmail(email: string) {
259 /^(([^\s"(),.:;<>@[\\\]]+(\.[^\s"(),.:;<>@[\\\]]+)*)|(".+"))@((\[(?:\d{1,3}\.){3}\d{1,3}])|(([\dA-Za-z\-]+\.)+[A-Za-z]{2,}))$/;
260 return re.test(String(email).toLowerCase());
263 export function capitalizeFirstLetter(str: string): string {
264 return str.charAt(0).toUpperCase() + str.slice(1);
267 export function routeSortTypeToEnum(sort: string): SortType {
268 return SortType[sort];
271 export function listingTypeFromNum(type_: number): ListingType {
272 return Object.values(ListingType)[type_];
275 export function sortTypeFromNum(type_: number): SortType {
276 return Object.values(SortType)[type_];
279 export function routeListingTypeToEnum(type: string): ListingType {
280 return ListingType[type];
283 export function routeDataTypeToEnum(type: string): DataType {
284 return DataType[capitalizeFirstLetter(type)];
287 export function routeSearchTypeToEnum(type: string): SearchType {
288 return SearchType[type];
291 export async function getSiteMetadata(url: string) {
292 let form: GetSiteMetadata = {
295 let client = new LemmyHttp(httpBase);
296 return client.getSiteMetadata(form);
299 export function debounce(func: any, wait = 1000, immediate = false) {
300 // 'private' variable for instance
301 // The returned function will be able to reference this due to closure.
302 // Each call to the returned function will share this common timer.
305 // Calling debounce returns a new anonymous function
307 // reference the context and args for the setTimeout function
308 var args = arguments;
310 // Should the function be called now? If immediate is true
311 // and not already in a timeout then the answer is: Yes
312 var callNow = immediate && !timeout;
314 // This is the basic debounce behaviour where you can call this
315 // function several times, but it will only execute once
316 // [before or after imposing a delay].
317 // Each time the returned function is called, the timer starts over.
318 clearTimeout(timeout);
320 // Set the new timeout
321 timeout = setTimeout(function () {
322 // Inside the timeout function, clear the timeout variable
323 // which will let the next execution run when in 'immediate' mode
326 // Check if the function already ran with the immediate flag
328 // Call the original function with apply
329 // apply lets you define the 'this' object as well as the arguments
330 // (both captured before setTimeout)
331 func.apply(this, args);
335 // Immediate mode and no wait timer? Execute the function..
336 if (callNow) func.apply(this, args);
340 export function getLanguages(override?: string): string[] {
341 let myUserInfo = UserService.Instance.myUserInfo;
344 (myUserInfo?.local_user_view.local_user.lang
345 ? myUserInfo.local_user_view.local_user.lang
348 if (lang == "browser" && isBrowser()) {
349 return getBrowserLanguages();
355 function getBrowserLanguages(): string[] {
356 // Intersect lemmy's langs, with the browser langs
357 let langs = languages ? languages.map(l => l.code) : ["en"];
359 // NOTE, mobile browsers seem to be missing this list, so append en
360 let allowedLangs = navigator.languages
362 .filter(v => langs.includes(v));
366 export function setTheme(theme: string, forceReload = false) {
370 if (theme === "browser" && !forceReload) {
373 // This is only run on a force reload
374 if (theme == "browser") {
378 // Unload all the other themes
379 for (var i = 0; i < themes.length; i++) {
380 let styleSheet = document.getElementById(themes[i]);
382 styleSheet.setAttribute("disabled", "disabled");
387 .getElementById("default-light")
388 ?.setAttribute("disabled", "disabled");
389 document.getElementById("default-dark")?.setAttribute("disabled", "disabled");
391 // Load the theme dynamically
392 let cssLoc = `/static/assets/css/themes/${theme}.min.css`;
393 loadCss(theme, cssLoc);
394 document.getElementById(theme).removeAttribute("disabled");
397 export function loadCss(id: string, loc: string) {
398 if (!document.getElementById(id)) {
399 var head = document.getElementsByTagName("head")[0];
400 var link = document.createElement("link");
402 link.rel = "stylesheet";
403 link.type = "text/css";
406 head.appendChild(link);
410 export function objectFlip(obj: any) {
412 Object.keys(obj).forEach(key => {
418 export function showAvatars(): boolean {
420 UserService.Instance.myUserInfo?.local_user_view.local_user.show_avatars ||
421 !UserService.Instance.myUserInfo
425 export function showScores(): boolean {
427 UserService.Instance.myUserInfo?.local_user_view.local_user.show_scores ||
428 !UserService.Instance.myUserInfo
432 export function isCakeDay(published: string): boolean {
433 // moment(undefined) or moment.utc(undefined) returns the current date/time
434 // moment(null) or moment.utc(null) returns null
435 const createDate = moment.utc(published || null).local();
436 const currentDate = moment(new Date());
439 createDate.date() === currentDate.date() &&
440 createDate.month() === currentDate.month() &&
441 createDate.year() !== currentDate.year()
445 export function toast(text: string, background = "success") {
447 let backgroundColor = `var(--${background})`;
450 backgroundColor: backgroundColor,
457 export function pictrsDeleteToast(
458 clickToDeleteText: string,
459 deletePictureText: string,
463 let backgroundColor = `var(--light)`;
464 let toast = Toastify({
465 text: clickToDeleteText,
466 backgroundColor: backgroundColor,
472 window.location.replace(deleteUrl);
473 alert(deletePictureText);
482 interface NotifyInfo {
489 export function messageToastify(info: NotifyInfo, router: any) {
491 let htmlBody = info.body ? md.render(info.body) : "";
492 let backgroundColor = `var(--light)`;
494 let toast = Toastify({
495 text: `${htmlBody}<br />${info.name}`,
496 avatar: info.icon ? info.icon : null,
497 backgroundColor: backgroundColor,
498 className: "text-dark",
507 router.history.push(info.link);
514 export function notifyPost(post_view: PostView, router: any) {
515 let info: NotifyInfo = {
516 name: post_view.community.name,
517 icon: post_view.community.icon,
518 link: `/post/${post_view.post.id}`,
519 body: post_view.post.name,
521 notify(info, router);
524 export function notifyComment(comment_view: CommentView, router: any) {
525 let info: NotifyInfo = {
526 name: comment_view.creator.name,
527 icon: comment_view.creator.avatar,
528 link: `/post/${comment_view.post.id}/comment/${comment_view.comment.id}`,
529 body: comment_view.comment.content,
531 notify(info, router);
534 export function notifyPrivateMessage(pmv: PrivateMessageView, router: any) {
535 let info: NotifyInfo = {
536 name: pmv.creator.name,
537 icon: pmv.creator.avatar,
539 body: pmv.private_message.content,
541 notify(info, router);
544 function notify(info: NotifyInfo, router: any) {
545 messageToastify(info, router);
547 // TODO absolute nightmare bug, but notifs are currently broken.
548 // Notification.new will try to do a browser fetch ???
550 // if (Notification.permission !== "granted") Notification.requestPermission();
552 // var notification = new Notification(info.name, {
557 // notification.onclick = (ev: Event): any => {
558 // ev.preventDefault();
559 // router.history.push(info.link);
564 export function setupTribute() {
566 noMatchTemplate: function () {
573 menuItemTemplate: (item: any) => {
574 let shortName = `:${item.original.key}:`;
575 return `${item.original.val} ${shortName}`;
577 selectTemplate: (item: any) => {
578 return `${item.original.val}`;
580 values: Object.entries(emojiShortName).map(e => {
581 return { key: e[1], val: e[0] };
584 autocompleteMode: true,
586 // menuItemLimit: mentionDropdownFetchLimit,
587 menuShowMinLength: 2,
592 selectTemplate: (item: any) => {
593 let it: PersonTribute = item.original;
594 return `[${it.key}](${it.view.person.actor_id})`;
596 values: (text: string, cb: (persons: PersonTribute[]) => any) => {
597 personSearch(text, (persons: PersonTribute[]) => cb(persons));
600 autocompleteMode: true,
602 // menuItemLimit: mentionDropdownFetchLimit,
603 menuShowMinLength: 2,
609 selectTemplate: (item: any) => {
610 let it: CommunityTribute = item.original;
611 return `[${it.key}](${it.view.community.actor_id})`;
613 values: (text: string, cb: any) => {
614 communitySearch(text, (communities: CommunityTribute[]) =>
619 autocompleteMode: true,
621 // menuItemLimit: mentionDropdownFetchLimit,
622 menuShowMinLength: 2,
628 var tippyInstance: any;
630 tippyInstance = tippy("[data-tippy-content]");
633 export function setupTippy() {
635 tippyInstance.forEach((e: any) => e.destroy());
636 tippyInstance = tippy("[data-tippy-content]", {
638 // Display on "long press"
639 touch: ["hold", 500],
644 interface PersonTribute {
646 view: PersonViewSafe;
649 function personSearch(text: string, cb: (persons: PersonTribute[]) => any) {
653 type_: SearchType.Users,
654 sort: SortType.TopAll,
655 listing_type: ListingType.All,
657 limit: mentionDropdownFetchLimit,
658 auth: authField(false),
661 WebSocketService.Instance.send(wsClient.search(form));
663 let personSub = WebSocketService.Instance.subject.subscribe(
665 let res = wsJsonToRes(msg);
666 if (res.op == UserOperation.Search) {
667 let data = res.data as SearchResponse;
668 let persons: PersonTribute[] = data.users.map(pv => {
669 let tribute: PersonTribute = {
670 key: `@${pv.person.name}@${hostname(pv.person.actor_id)}`,
676 personSub.unsubscribe();
679 err => console.error(err),
680 () => console.log("complete")
687 interface CommunityTribute {
692 function communitySearch(
694 cb: (communities: CommunityTribute[]) => any
699 type_: SearchType.Communities,
700 sort: SortType.TopAll,
701 listing_type: ListingType.All,
703 limit: mentionDropdownFetchLimit,
704 auth: authField(false),
707 WebSocketService.Instance.send(wsClient.search(form));
709 let communitySub = WebSocketService.Instance.subject.subscribe(
711 let res = wsJsonToRes(msg);
712 if (res.op == UserOperation.Search) {
713 let data = res.data as SearchResponse;
714 let communities: CommunityTribute[] = data.communities.map(cv => {
715 let tribute: CommunityTribute = {
716 key: `!${cv.community.name}@${hostname(cv.community.actor_id)}`,
722 communitySub.unsubscribe();
725 err => console.error(err),
726 () => console.log("complete")
733 export function getListingTypeFromProps(props: any): ListingType {
734 return props.match.params.listing_type
735 ? routeListingTypeToEnum(props.match.params.listing_type)
736 : UserService.Instance.myUserInfo
737 ? Object.values(ListingType)[
738 UserService.Instance.myUserInfo.local_user_view.local_user
739 .default_listing_type
744 export function getListingTypeFromPropsNoDefault(props: any): ListingType {
745 return props.match.params.listing_type
746 ? routeListingTypeToEnum(props.match.params.listing_type)
750 // TODO might need to add a user setting for this too
751 export function getDataTypeFromProps(props: any): DataType {
752 return props.match.params.data_type
753 ? routeDataTypeToEnum(props.match.params.data_type)
757 export function getSortTypeFromProps(props: any): SortType {
758 return props.match.params.sort
759 ? routeSortTypeToEnum(props.match.params.sort)
760 : UserService.Instance.myUserInfo
761 ? Object.values(SortType)[
762 UserService.Instance.myUserInfo.local_user_view.local_user
768 export function getPageFromProps(props: any): number {
769 return props.match.params.page ? Number(props.match.params.page) : 1;
772 export function getRecipientIdFromProps(props: any): number {
773 return props.match.params.recipient_id
774 ? Number(props.match.params.recipient_id)
778 export function getIdFromProps(props: any): number {
779 return Number(props.match.params.id);
782 export function getCommentIdFromProps(props: any): number {
783 return Number(props.match.params.comment_id);
786 export function getUsernameFromProps(props: any): string {
787 return props.match.params.username;
790 export function editCommentRes(data: CommentView, comments: CommentView[]) {
791 let found = comments.find(c => c.comment.id == data.comment.id);
793 found.comment.content = data.comment.content;
794 found.comment.updated = data.comment.updated;
795 found.comment.removed = data.comment.removed;
796 found.comment.deleted = data.comment.deleted;
797 found.counts.upvotes = data.counts.upvotes;
798 found.counts.downvotes = data.counts.downvotes;
799 found.counts.score = data.counts.score;
803 export function saveCommentRes(data: CommentView, comments: CommentView[]) {
804 let found = comments.find(c => c.comment.id == data.comment.id);
806 found.saved = data.saved;
810 export function updatePersonBlock(
811 data: BlockPersonResponse
812 ): PersonBlockView[] {
814 UserService.Instance.myUserInfo.person_blocks.push({
815 person: UserService.Instance.myUserInfo.local_user_view.person,
816 target: data.person_view.person,
818 toast(`${i18n.t("blocked")} ${data.person_view.person.name}`);
820 UserService.Instance.myUserInfo.person_blocks =
821 UserService.Instance.myUserInfo.person_blocks.filter(
822 i => i.target.id != data.person_view.person.id
824 toast(`${i18n.t("unblocked")} ${data.person_view.person.name}`);
826 return UserService.Instance.myUserInfo.person_blocks;
829 export function updateCommunityBlock(
830 data: BlockCommunityResponse
831 ): CommunityBlockView[] {
833 UserService.Instance.myUserInfo.community_blocks.push({
834 person: UserService.Instance.myUserInfo.local_user_view.person,
835 community: data.community_view.community,
837 toast(`${i18n.t("blocked")} ${data.community_view.community.name}`);
839 UserService.Instance.myUserInfo.community_blocks =
840 UserService.Instance.myUserInfo.community_blocks.filter(
841 i => i.community.id != data.community_view.community.id
843 toast(`${i18n.t("unblocked")} ${data.community_view.community.name}`);
845 return UserService.Instance.myUserInfo.community_blocks;
848 export function createCommentLikeRes(
850 comments: CommentView[]
852 let found = comments.find(c => c.comment.id === data.comment.id);
854 found.counts.score = data.counts.score;
855 found.counts.upvotes = data.counts.upvotes;
856 found.counts.downvotes = data.counts.downvotes;
857 if (data.my_vote !== null) {
858 found.my_vote = data.my_vote;
863 export function createPostLikeFindRes(data: PostView, posts: PostView[]) {
864 let found = posts.find(p => p.post.id == data.post.id);
866 createPostLikeRes(data, found);
870 export function createPostLikeRes(data: PostView, post_view: PostView) {
872 post_view.counts.score = data.counts.score;
873 post_view.counts.upvotes = data.counts.upvotes;
874 post_view.counts.downvotes = data.counts.downvotes;
875 if (data.my_vote !== null) {
876 post_view.my_vote = data.my_vote;
881 export function editPostFindRes(data: PostView, posts: PostView[]) {
882 let found = posts.find(p => p.post.id == data.post.id);
884 editPostRes(data, found);
888 export function editPostRes(data: PostView, post: PostView) {
890 post.post.url = data.post.url;
891 post.post.name = data.post.name;
892 post.post.nsfw = data.post.nsfw;
893 post.post.deleted = data.post.deleted;
894 post.post.removed = data.post.removed;
895 post.post.stickied = data.post.stickied;
896 post.post.body = data.post.body;
897 post.post.locked = data.post.locked;
898 post.saved = data.saved;
902 export function updatePostReportRes(
903 data: PostReportView,
904 reports: PostReportView[]
906 let found = reports.find(p => p.post_report.id == data.post_report.id);
908 found.post_report = data.post_report;
912 export function updateCommentReportRes(
913 data: CommentReportView,
914 reports: CommentReportView[]
916 let found = reports.find(c => c.comment_report.id == data.comment_report.id);
918 found.comment_report = data.comment_report;
922 export function updateRegistrationApplicationRes(
923 data: RegistrationApplicationView,
924 applications: RegistrationApplicationView[]
926 let found = applications.find(
927 ra => ra.registration_application.id == data.registration_application.id
930 found.registration_application = data.registration_application;
931 found.admin = data.admin;
932 found.creator_local_user = data.creator_local_user;
936 export function commentsToFlatNodes(comments: CommentView[]): CommentNodeI[] {
937 let nodes: CommentNodeI[] = [];
938 for (let comment of comments) {
939 nodes.push({ comment_view: comment });
944 function commentSort(tree: CommentNodeI[], sort: CommentSortType) {
945 // First, put removed and deleted comments at the bottom, then do your other sorts
946 if (sort == CommentSortType.Top) {
949 +a.comment_view.comment.removed - +b.comment_view.comment.removed ||
950 +a.comment_view.comment.deleted - +b.comment_view.comment.deleted ||
951 b.comment_view.counts.score - a.comment_view.counts.score
953 } else if (sort == CommentSortType.New) {
956 +a.comment_view.comment.removed - +b.comment_view.comment.removed ||
957 +a.comment_view.comment.deleted - +b.comment_view.comment.deleted ||
958 b.comment_view.comment.published.localeCompare(
959 a.comment_view.comment.published
962 } else if (sort == CommentSortType.Old) {
965 +a.comment_view.comment.removed - +b.comment_view.comment.removed ||
966 +a.comment_view.comment.deleted - +b.comment_view.comment.deleted ||
967 a.comment_view.comment.published.localeCompare(
968 b.comment_view.comment.published
971 } else if (sort == CommentSortType.Hot) {
974 +a.comment_view.comment.removed - +b.comment_view.comment.removed ||
975 +a.comment_view.comment.deleted - +b.comment_view.comment.deleted ||
976 hotRankComment(b.comment_view) - hotRankComment(a.comment_view)
980 // Go through the children recursively
981 for (let node of tree) {
983 commentSort(node.children, sort);
988 export function commentSortSortType(tree: CommentNodeI[], sort: SortType) {
989 commentSort(tree, convertCommentSortType(sort));
992 function convertCommentSortType(sort: SortType): CommentSortType {
994 sort == SortType.TopAll ||
995 sort == SortType.TopDay ||
996 sort == SortType.TopWeek ||
997 sort == SortType.TopMonth ||
998 sort == SortType.TopYear
1000 return CommentSortType.Top;
1001 } else if (sort == SortType.New) {
1002 return CommentSortType.New;
1003 } else if (sort == SortType.Hot || sort == SortType.Active) {
1004 return CommentSortType.Hot;
1006 return CommentSortType.Hot;
1010 export function buildCommentsTree(
1011 comments: CommentView[],
1012 commentSortType: CommentSortType
1014 let map = new Map<number, CommentNodeI>();
1015 for (let comment_view of comments) {
1016 let node: CommentNodeI = {
1017 comment_view: comment_view,
1020 map.set(comment_view.comment.id, { ...node });
1022 let tree: CommentNodeI[] = [];
1023 for (let comment_view of comments) {
1024 let child = map.get(comment_view.comment.id);
1025 let parent_id = comment_view.comment.parent_id;
1027 let parent = map.get(parent_id);
1028 // Necessary because blocked comment might not exist
1030 parent.children.push(child);
1039 commentSort(tree, commentSortType);
1044 function setDepth(node: CommentNodeI, i = 0) {
1045 for (let child of node.children) {
1047 setDepth(child, i + 1);
1051 export function insertCommentIntoTree(tree: CommentNodeI[], cv: CommentView) {
1052 // Building a fake node to be used for later
1053 let node: CommentNodeI = {
1059 if (cv.comment.parent_id) {
1060 let parentComment = searchCommentTree(tree, cv.comment.parent_id);
1061 if (parentComment) {
1062 node.depth = parentComment.depth + 1;
1063 parentComment.children.unshift(node);
1070 export function searchCommentTree(
1071 tree: CommentNodeI[],
1074 for (let node of tree) {
1075 if (node.comment_view.comment.id === id) {
1079 for (const child of node.children) {
1080 const res = searchCommentTree([child], id);
1090 export const colorList: string[] = [
1099 function hsl(num: number) {
1100 return `hsla(${num}, 35%, 50%, 1)`;
1103 export function previewLines(
1112 // Use lines * 2 because markdown requires 2 lines
1113 .slice(0, maxLines * 2)
1118 export function hostname(url: string): string {
1119 let cUrl = new URL(url);
1120 return cUrl.port ? `${cUrl.hostname}:${cUrl.port}` : `${cUrl.hostname}`;
1123 export function validTitle(title?: string): boolean {
1124 // Initial title is null, minimum length is taken care of by textarea's minLength={3}
1125 if (title === null || title.length < 3) return true;
1127 const regex = new RegExp(/.*\S.*/, "g");
1129 return regex.test(title);
1132 export function siteBannerCss(banner: string): string {
1134 background-image: linear-gradient( rgba(0, 0, 0, 0.8), rgba(0, 0, 0, 0.8) ) ,url("${banner}"); \
1135 background-attachment: fixed; \
1136 background-position: top; \
1137 background-repeat: no-repeat; \
1138 background-size: 100% cover; \
1141 max-height: 100vh; \
1145 export function isBrowser() {
1146 return typeof window !== "undefined";
1149 export function setIsoData(context: any): IsoData {
1150 let isoData: IsoData = isBrowser()
1152 : context.router.staticContext;
1156 export function wsSubscribe(parseMessage: any): Subscription {
1158 return WebSocketService.Instance.subject
1159 .pipe(retryWhen(errors => errors.pipe(delay(3000), take(10))))
1161 msg => parseMessage(msg),
1162 err => console.error(err),
1163 () => console.log("complete")
1170 export function setOptionalAuth(obj: any, auth = UserService.Instance.auth) {
1176 export function authField(
1178 auth = UserService.Instance.auth
1180 if (auth == null && throwErr) {
1181 toast(i18n.t("not_logged_in"), "danger");
1182 throw "Not logged in";
1188 moment.updateLocale("en", {
1209 export function saveScrollPosition(context: any) {
1210 let path: string = context.router.route.location.pathname;
1211 let y = window.scrollY;
1212 sessionStorage.setItem(`scrollPosition_${path}`, y.toString());
1215 export function restoreScrollPosition(context: any) {
1216 let path: string = context.router.route.location.pathname;
1217 let y = Number(sessionStorage.getItem(`scrollPosition_${path}`));
1218 window.scrollTo(0, y);
1221 export function showLocal(isoData: IsoData): boolean {
1222 return isoData.site_res.federated_instances?.linked.length > 0;
1225 interface ChoicesValue {
1230 export function communityToChoice(cv: CommunityView): ChoicesValue {
1231 let choice: ChoicesValue = {
1232 value: cv.community.id.toString(),
1233 label: communitySelectName(cv),
1238 export function personToChoice(pvs: PersonViewSafe): ChoicesValue {
1239 let choice: ChoicesValue = {
1240 value: pvs.person.id.toString(),
1241 label: personSelectName(pvs),
1246 export async function fetchCommunities(q: string) {
1247 let form: Search = {
1249 type_: SearchType.Communities,
1250 sort: SortType.TopAll,
1251 listing_type: ListingType.All,
1254 auth: authField(false),
1256 let client = new LemmyHttp(httpBase);
1257 return client.search(form);
1260 export async function fetchUsers(q: string) {
1261 let form: Search = {
1263 type_: SearchType.Users,
1264 sort: SortType.TopAll,
1265 listing_type: ListingType.All,
1268 auth: authField(false),
1270 let client = new LemmyHttp(httpBase);
1271 return client.search(form);
1274 export const choicesConfig = {
1276 searchResultLimit: fetchLimit,
1278 containerOuter: "choices",
1279 containerInner: "choices__inner bg-secondary border-0",
1280 input: "form-control",
1281 inputCloned: "choices__input--cloned",
1282 list: "choices__list",
1283 listItems: "choices__list--multiple",
1284 listSingle: "choices__list--single",
1285 listDropdown: "choices__list--dropdown",
1286 item: "choices__item bg-secondary",
1287 itemSelectable: "choices__item--selectable",
1288 itemDisabled: "choices__item--disabled",
1289 itemChoice: "choices__item--choice",
1290 placeholder: "choices__placeholder",
1291 group: "choices__group",
1292 groupHeading: "choices__heading",
1293 button: "choices__button",
1294 activeState: "is-active",
1295 focusState: "is-focused",
1296 openState: "is-open",
1297 disabledState: "is-disabled",
1298 highlightedState: "text-info",
1299 selectedState: "text-info",
1300 flippedState: "is-flipped",
1301 loadingState: "is-loading",
1302 noResults: "has-no-results",
1303 noChoices: "has-no-choices",
1307 export function communitySelectName(cv: CommunityView): string {
1308 return cv.community.local
1309 ? cv.community.title
1310 : `${hostname(cv.community.actor_id)}/${cv.community.title}`;
1313 export function personSelectName(pvs: PersonViewSafe): string {
1314 let pName = pvs.person.display_name || pvs.person.name;
1315 return pvs.person.local ? pName : `${hostname(pvs.person.actor_id)}/${pName}`;
1318 export function initializeSite(site: GetSiteResponse) {
1319 UserService.Instance.myUserInfo = site.my_user;
1320 i18n.changeLanguage(getLanguages()[0]);
1323 const SHORTNUM_SI_FORMAT = new Intl.NumberFormat("en-US", {
1324 maximumSignificantDigits: 3,
1326 notation: "compact",
1327 compactDisplay: "short",
1330 export function numToSI(value: number): string {
1331 return SHORTNUM_SI_FORMAT.format(value);
1334 export function isBanned(ps: PersonSafe): boolean {
1335 // Add Z to convert from UTC date
1336 if (ps.ban_expires) {
1337 if (ps.banned && new Date(ps.ban_expires + "Z") > new Date()) {