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 export const themes = [
97 const DEFAULT_ALPHABET =
98 "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
100 function getRandomCharFromAlphabet(alphabet: string): string {
101 return alphabet.charAt(Math.floor(Math.random() * alphabet.length));
104 export function randomStr(
105 idDesiredLength = 20,
106 alphabet = DEFAULT_ALPHABET
109 * Create n-long array and map it to random chars from given alphabet.
110 * Then join individual chars as string
112 return Array.from({ length: idDesiredLength })
114 return getRandomCharFromAlphabet(alphabet);
119 export function wsJsonToRes<ResponseType>(
120 msg: WebSocketJsonResponse<ResponseType>
121 ): WebSocketResponse<ResponseType> {
128 export function wsUserOp(msg: any): UserOperation {
129 let opStr: string = msg.op;
130 return UserOperation[opStr];
133 export const md = new markdown_it({
138 .use(markdown_it_sub)
139 .use(markdown_it_sup)
140 .use(markdown_it_footnote)
141 .use(markdown_it_html5_embed, {
143 useImageSyntax: true, // Enables video/audio embed with ![]() syntax (default)
145 audio: 'controls preload="metadata"',
147 'width="100%" max-height="100%" controls loop preload="metadata"',
151 .use(markdown_it_container, "spoiler", {
152 validate: function (params: any) {
153 return params.trim().match(/^spoiler\s+(.*)$/);
156 render: function (tokens: any, idx: any) {
157 var m = tokens[idx].info.trim().match(/^spoiler\s+(.*)$/);
159 if (tokens[idx].nesting === 1) {
161 return `<details><summary> ${md.utils.escapeHtml(m[1])} </summary>\n`;
164 return "</details>\n";
169 export function hotRankComment(comment_view: CommentView): number {
170 return hotRank(comment_view.counts.score, comment_view.comment.published);
173 export function hotRankActivePost(post_view: PostView): number {
174 return hotRank(post_view.counts.score, post_view.counts.newest_comment_time);
177 export function hotRankPost(post_view: PostView): number {
178 return hotRank(post_view.counts.score, post_view.post.published);
181 export function hotRank(score: number, timeStr: string): number {
182 // Rank = ScaleFactor * sign(Score) * log(1 + abs(Score)) / (Time + 2)^Gravity
183 let date: Date = new Date(timeStr + "Z"); // Add Z to convert from UTC date
184 let now: Date = new Date();
185 let hoursElapsed: number = (now.getTime() - date.getTime()) / 36e5;
188 (10000 * Math.log10(Math.max(1, 3 + score))) /
189 Math.pow(hoursElapsed + 2, 1.8);
191 // console.log(`Comment: ${comment.content}\nRank: ${rank}\nScore: ${comment.score}\nHours: ${hoursElapsed}`);
196 export function mdToHtml(text: string) {
197 return { __html: md.render(text) };
200 export function getUnixTime(text: string): number {
201 return text ? new Date(text).getTime() / 1000 : undefined;
204 export function futureDaysToUnixTime(days: number): number {
207 new Date(Date.now() + 1000 * 60 * 60 * 24 * days).getTime() / 1000
212 export function canMod(
213 myUserInfo: MyUserInfo,
218 // You can do moderator actions only on the mods added after you.
220 let yourIndex = modIds.findIndex(
221 id => id == myUserInfo.local_user_view.person.id
223 if (yourIndex == -1) {
226 // onSelf +1 on mod actions not for yourself, IE ban, remove, etc
227 modIds = modIds.slice(0, yourIndex + (onSelf ? 0 : 1));
228 return !modIds.includes(creator_id);
235 export function isMod(modIds: number[], creator_id: number): boolean {
236 return modIds.includes(creator_id);
239 const imageRegex = /(http)?s?:?(\/\/[^"']*\.(?:jpg|jpeg|gif|png|svg|webp))/;
240 const videoRegex = /(http)?s?:?(\/\/[^"']*\.(?:mp4|webm))/;
242 export function isImage(url: string) {
243 return imageRegex.test(url);
246 export function isVideo(url: string) {
247 return videoRegex.test(url);
250 export function validURL(str: string) {
251 return !!new URL(str);
254 export function communityRSSUrl(actorId: string, sort: string): string {
255 let url = new URL(actorId);
256 return `${url.origin}/feeds${url.pathname}.xml?sort=${sort}`;
259 export function validEmail(email: string) {
261 /^(([^\s"(),.:;<>@[\\\]]+(\.[^\s"(),.:;<>@[\\\]]+)*)|(".+"))@((\[(?:\d{1,3}\.){3}\d{1,3}])|(([\dA-Za-z\-]+\.)+[A-Za-z]{2,}))$/;
262 return re.test(String(email).toLowerCase());
265 export function capitalizeFirstLetter(str: string): string {
266 return str.charAt(0).toUpperCase() + str.slice(1);
269 export function routeSortTypeToEnum(sort: string): SortType {
270 return SortType[sort];
273 export function listingTypeFromNum(type_: number): ListingType {
274 return Object.values(ListingType)[type_];
277 export function sortTypeFromNum(type_: number): SortType {
278 return Object.values(SortType)[type_];
281 export function routeListingTypeToEnum(type: string): ListingType {
282 return ListingType[type];
285 export function routeDataTypeToEnum(type: string): DataType {
286 return DataType[capitalizeFirstLetter(type)];
289 export function routeSearchTypeToEnum(type: string): SearchType {
290 return SearchType[type];
293 export async function getSiteMetadata(url: string) {
294 let form: GetSiteMetadata = {
297 let client = new LemmyHttp(httpBase);
298 return client.getSiteMetadata(form);
301 export function debounce(func: any, wait = 1000, immediate = false) {
302 // 'private' variable for instance
303 // The returned function will be able to reference this due to closure.
304 // Each call to the returned function will share this common timer.
307 // Calling debounce returns a new anonymous function
309 // reference the context and args for the setTimeout function
310 var args = arguments;
312 // Should the function be called now? If immediate is true
313 // and not already in a timeout then the answer is: Yes
314 var callNow = immediate && !timeout;
316 // This is the basic debounce behaviour where you can call this
317 // function several times, but it will only execute once
318 // [before or after imposing a delay].
319 // Each time the returned function is called, the timer starts over.
320 clearTimeout(timeout);
322 // Set the new timeout
323 timeout = setTimeout(function () {
324 // Inside the timeout function, clear the timeout variable
325 // which will let the next execution run when in 'immediate' mode
328 // Check if the function already ran with the immediate flag
330 // Call the original function with apply
331 // apply lets you define the 'this' object as well as the arguments
332 // (both captured before setTimeout)
333 func.apply(this, args);
337 // Immediate mode and no wait timer? Execute the function..
338 if (callNow) func.apply(this, args);
342 export function getLanguages(override?: string): string[] {
343 let myUserInfo = UserService.Instance.myUserInfo;
346 (myUserInfo?.local_user_view.local_user.lang
347 ? myUserInfo.local_user_view.local_user.lang
350 if (lang == "browser" && isBrowser()) {
351 return getBrowserLanguages();
357 function getBrowserLanguages(): string[] {
358 // Intersect lemmy's langs, with the browser langs
359 let langs = languages ? languages.map(l => l.code) : ["en"];
361 // NOTE, mobile browsers seem to be missing this list, so append en
362 let allowedLangs = navigator.languages
364 .filter(v => langs.includes(v));
368 export function setTheme(theme: string, forceReload = false) {
372 if (theme === "browser" && !forceReload) {
375 // This is only run on a force reload
376 if (theme == "browser") {
380 // Unload all the other themes
381 for (var i = 0; i < themes.length; i++) {
382 let styleSheet = document.getElementById(themes[i]);
384 styleSheet.setAttribute("disabled", "disabled");
389 .getElementById("default-light")
390 ?.setAttribute("disabled", "disabled");
391 document.getElementById("default-dark")?.setAttribute("disabled", "disabled");
393 // Load the theme dynamically
394 let cssLoc = `/static/assets/css/themes/${theme}.min.css`;
395 loadCss(theme, cssLoc);
396 document.getElementById(theme).removeAttribute("disabled");
399 export function loadCss(id: string, loc: string) {
400 if (!document.getElementById(id)) {
401 var head = document.getElementsByTagName("head")[0];
402 var link = document.createElement("link");
404 link.rel = "stylesheet";
405 link.type = "text/css";
408 head.appendChild(link);
412 export function objectFlip(obj: any) {
414 Object.keys(obj).forEach(key => {
420 export function showAvatars(): boolean {
422 UserService.Instance.myUserInfo?.local_user_view.local_user.show_avatars ||
423 !UserService.Instance.myUserInfo
427 export function showScores(): boolean {
429 UserService.Instance.myUserInfo?.local_user_view.local_user.show_scores ||
430 !UserService.Instance.myUserInfo
434 export function isCakeDay(published: string): boolean {
435 // moment(undefined) or moment.utc(undefined) returns the current date/time
436 // moment(null) or moment.utc(null) returns null
437 const createDate = moment.utc(published || null).local();
438 const currentDate = moment(new Date());
441 createDate.date() === currentDate.date() &&
442 createDate.month() === currentDate.month() &&
443 createDate.year() !== currentDate.year()
447 export function toast(text: string, background = "success") {
449 let backgroundColor = `var(--${background})`;
452 backgroundColor: backgroundColor,
459 export function pictrsDeleteToast(
460 clickToDeleteText: string,
461 deletePictureText: string,
465 let backgroundColor = `var(--light)`;
466 let toast = Toastify({
467 text: clickToDeleteText,
468 backgroundColor: backgroundColor,
474 window.location.replace(deleteUrl);
475 alert(deletePictureText);
484 interface NotifyInfo {
491 export function messageToastify(info: NotifyInfo, router: any) {
493 let htmlBody = info.body ? md.render(info.body) : "";
494 let backgroundColor = `var(--light)`;
496 let toast = Toastify({
497 text: `${htmlBody}<br />${info.name}`,
498 avatar: info.icon ? info.icon : null,
499 backgroundColor: backgroundColor,
500 className: "text-dark",
509 router.history.push(info.link);
516 export function notifyPost(post_view: PostView, router: any) {
517 let info: NotifyInfo = {
518 name: post_view.community.name,
519 icon: post_view.community.icon,
520 link: `/post/${post_view.post.id}`,
521 body: post_view.post.name,
523 notify(info, router);
526 export function notifyComment(comment_view: CommentView, router: any) {
527 let info: NotifyInfo = {
528 name: comment_view.creator.name,
529 icon: comment_view.creator.avatar,
530 link: `/post/${comment_view.post.id}/comment/${comment_view.comment.id}`,
531 body: comment_view.comment.content,
533 notify(info, router);
536 export function notifyPrivateMessage(pmv: PrivateMessageView, router: any) {
537 let info: NotifyInfo = {
538 name: pmv.creator.name,
539 icon: pmv.creator.avatar,
541 body: pmv.private_message.content,
543 notify(info, router);
546 function notify(info: NotifyInfo, router: any) {
547 messageToastify(info, router);
549 // TODO absolute nightmare bug, but notifs are currently broken.
550 // Notification.new will try to do a browser fetch ???
552 // if (Notification.permission !== "granted") Notification.requestPermission();
554 // var notification = new Notification(info.name, {
559 // notification.onclick = (ev: Event): any => {
560 // ev.preventDefault();
561 // router.history.push(info.link);
566 export function setupTribute() {
568 noMatchTemplate: function () {
575 menuItemTemplate: (item: any) => {
576 let shortName = `:${item.original.key}:`;
577 return `${item.original.val} ${shortName}`;
579 selectTemplate: (item: any) => {
580 return `${item.original.val}`;
582 values: Object.entries(emojiShortName).map(e => {
583 return { key: e[1], val: e[0] };
586 autocompleteMode: true,
588 // menuItemLimit: mentionDropdownFetchLimit,
589 menuShowMinLength: 2,
594 selectTemplate: (item: any) => {
595 let it: PersonTribute = item.original;
596 return `[${it.key}](${it.view.person.actor_id})`;
598 values: (text: string, cb: (persons: PersonTribute[]) => any) => {
599 personSearch(text, (persons: PersonTribute[]) => cb(persons));
602 autocompleteMode: true,
604 // menuItemLimit: mentionDropdownFetchLimit,
605 menuShowMinLength: 2,
611 selectTemplate: (item: any) => {
612 let it: CommunityTribute = item.original;
613 return `[${it.key}](${it.view.community.actor_id})`;
615 values: (text: string, cb: any) => {
616 communitySearch(text, (communities: CommunityTribute[]) =>
621 autocompleteMode: true,
623 // menuItemLimit: mentionDropdownFetchLimit,
624 menuShowMinLength: 2,
630 var tippyInstance: any;
632 tippyInstance = tippy("[data-tippy-content]");
635 export function setupTippy() {
637 tippyInstance.forEach((e: any) => e.destroy());
638 tippyInstance = tippy("[data-tippy-content]", {
640 // Display on "long press"
641 touch: ["hold", 500],
646 interface PersonTribute {
648 view: PersonViewSafe;
651 function personSearch(text: string, cb: (persons: PersonTribute[]) => any) {
655 type_: SearchType.Users,
656 sort: SortType.TopAll,
657 listing_type: ListingType.All,
659 limit: mentionDropdownFetchLimit,
660 auth: authField(false),
663 WebSocketService.Instance.send(wsClient.search(form));
665 let personSub = WebSocketService.Instance.subject.subscribe(
667 let res = wsJsonToRes(msg);
668 if (res.op == UserOperation.Search) {
669 let data = res.data as SearchResponse;
670 let persons: PersonTribute[] = data.users.map(pv => {
671 let tribute: PersonTribute = {
672 key: `@${pv.person.name}@${hostname(pv.person.actor_id)}`,
678 personSub.unsubscribe();
681 err => console.error(err),
682 () => console.log("complete")
689 interface CommunityTribute {
694 function communitySearch(
696 cb: (communities: CommunityTribute[]) => any
701 type_: SearchType.Communities,
702 sort: SortType.TopAll,
703 listing_type: ListingType.All,
705 limit: mentionDropdownFetchLimit,
706 auth: authField(false),
709 WebSocketService.Instance.send(wsClient.search(form));
711 let communitySub = WebSocketService.Instance.subject.subscribe(
713 let res = wsJsonToRes(msg);
714 if (res.op == UserOperation.Search) {
715 let data = res.data as SearchResponse;
716 let communities: CommunityTribute[] = data.communities.map(cv => {
717 let tribute: CommunityTribute = {
718 key: `!${cv.community.name}@${hostname(cv.community.actor_id)}`,
724 communitySub.unsubscribe();
727 err => console.error(err),
728 () => console.log("complete")
735 export function getListingTypeFromProps(props: any): ListingType {
736 return props.match.params.listing_type
737 ? routeListingTypeToEnum(props.match.params.listing_type)
738 : UserService.Instance.myUserInfo
739 ? Object.values(ListingType)[
740 UserService.Instance.myUserInfo.local_user_view.local_user
741 .default_listing_type
746 export function getListingTypeFromPropsNoDefault(props: any): ListingType {
747 return props.match.params.listing_type
748 ? routeListingTypeToEnum(props.match.params.listing_type)
752 // TODO might need to add a user setting for this too
753 export function getDataTypeFromProps(props: any): DataType {
754 return props.match.params.data_type
755 ? routeDataTypeToEnum(props.match.params.data_type)
759 export function getSortTypeFromProps(props: any): SortType {
760 return props.match.params.sort
761 ? routeSortTypeToEnum(props.match.params.sort)
762 : UserService.Instance.myUserInfo
763 ? Object.values(SortType)[
764 UserService.Instance.myUserInfo.local_user_view.local_user
770 export function getPageFromProps(props: any): number {
771 return props.match.params.page ? Number(props.match.params.page) : 1;
774 export function getRecipientIdFromProps(props: any): number {
775 return props.match.params.recipient_id
776 ? Number(props.match.params.recipient_id)
780 export function getIdFromProps(props: any): number {
781 return Number(props.match.params.id);
784 export function getCommentIdFromProps(props: any): number {
785 return Number(props.match.params.comment_id);
788 export function getUsernameFromProps(props: any): string {
789 return props.match.params.username;
792 export function editCommentRes(data: CommentView, comments: CommentView[]) {
793 let found = comments.find(c => c.comment.id == data.comment.id);
795 found.comment.content = data.comment.content;
796 found.comment.updated = data.comment.updated;
797 found.comment.removed = data.comment.removed;
798 found.comment.deleted = data.comment.deleted;
799 found.counts.upvotes = data.counts.upvotes;
800 found.counts.downvotes = data.counts.downvotes;
801 found.counts.score = data.counts.score;
805 export function saveCommentRes(data: CommentView, comments: CommentView[]) {
806 let found = comments.find(c => c.comment.id == data.comment.id);
808 found.saved = data.saved;
812 export function updatePersonBlock(
813 data: BlockPersonResponse
814 ): PersonBlockView[] {
816 UserService.Instance.myUserInfo.person_blocks.push({
817 person: UserService.Instance.myUserInfo.local_user_view.person,
818 target: data.person_view.person,
820 toast(`${i18n.t("blocked")} ${data.person_view.person.name}`);
822 UserService.Instance.myUserInfo.person_blocks =
823 UserService.Instance.myUserInfo.person_blocks.filter(
824 i => i.target.id != data.person_view.person.id
826 toast(`${i18n.t("unblocked")} ${data.person_view.person.name}`);
828 return UserService.Instance.myUserInfo.person_blocks;
831 export function updateCommunityBlock(
832 data: BlockCommunityResponse
833 ): CommunityBlockView[] {
835 UserService.Instance.myUserInfo.community_blocks.push({
836 person: UserService.Instance.myUserInfo.local_user_view.person,
837 community: data.community_view.community,
839 toast(`${i18n.t("blocked")} ${data.community_view.community.name}`);
841 UserService.Instance.myUserInfo.community_blocks =
842 UserService.Instance.myUserInfo.community_blocks.filter(
843 i => i.community.id != data.community_view.community.id
845 toast(`${i18n.t("unblocked")} ${data.community_view.community.name}`);
847 return UserService.Instance.myUserInfo.community_blocks;
850 export function createCommentLikeRes(
852 comments: CommentView[]
854 let found = comments.find(c => c.comment.id === data.comment.id);
856 found.counts.score = data.counts.score;
857 found.counts.upvotes = data.counts.upvotes;
858 found.counts.downvotes = data.counts.downvotes;
859 if (data.my_vote !== null) {
860 found.my_vote = data.my_vote;
865 export function createPostLikeFindRes(data: PostView, posts: PostView[]) {
866 let found = posts.find(p => p.post.id == data.post.id);
868 createPostLikeRes(data, found);
872 export function createPostLikeRes(data: PostView, post_view: PostView) {
874 post_view.counts.score = data.counts.score;
875 post_view.counts.upvotes = data.counts.upvotes;
876 post_view.counts.downvotes = data.counts.downvotes;
877 if (data.my_vote !== null) {
878 post_view.my_vote = data.my_vote;
883 export function editPostFindRes(data: PostView, posts: PostView[]) {
884 let found = posts.find(p => p.post.id == data.post.id);
886 editPostRes(data, found);
890 export function editPostRes(data: PostView, post: PostView) {
892 post.post.url = data.post.url;
893 post.post.name = data.post.name;
894 post.post.nsfw = data.post.nsfw;
895 post.post.deleted = data.post.deleted;
896 post.post.removed = data.post.removed;
897 post.post.stickied = data.post.stickied;
898 post.post.body = data.post.body;
899 post.post.locked = data.post.locked;
900 post.saved = data.saved;
904 export function updatePostReportRes(
905 data: PostReportView,
906 reports: PostReportView[]
908 let found = reports.find(p => p.post_report.id == data.post_report.id);
910 found.post_report = data.post_report;
914 export function updateCommentReportRes(
915 data: CommentReportView,
916 reports: CommentReportView[]
918 let found = reports.find(c => c.comment_report.id == data.comment_report.id);
920 found.comment_report = data.comment_report;
924 export function updateRegistrationApplicationRes(
925 data: RegistrationApplicationView,
926 applications: RegistrationApplicationView[]
928 let found = applications.find(
929 ra => ra.registration_application.id == data.registration_application.id
932 found.registration_application = data.registration_application;
933 found.admin = data.admin;
934 found.creator_local_user = data.creator_local_user;
938 export function commentsToFlatNodes(comments: CommentView[]): CommentNodeI[] {
939 let nodes: CommentNodeI[] = [];
940 for (let comment of comments) {
941 nodes.push({ comment_view: comment });
946 function commentSort(tree: CommentNodeI[], sort: CommentSortType) {
947 // First, put removed and deleted comments at the bottom, then do your other sorts
948 if (sort == CommentSortType.Top) {
951 +a.comment_view.comment.removed - +b.comment_view.comment.removed ||
952 +a.comment_view.comment.deleted - +b.comment_view.comment.deleted ||
953 b.comment_view.counts.score - a.comment_view.counts.score
955 } else if (sort == CommentSortType.New) {
958 +a.comment_view.comment.removed - +b.comment_view.comment.removed ||
959 +a.comment_view.comment.deleted - +b.comment_view.comment.deleted ||
960 b.comment_view.comment.published.localeCompare(
961 a.comment_view.comment.published
964 } else if (sort == CommentSortType.Old) {
967 +a.comment_view.comment.removed - +b.comment_view.comment.removed ||
968 +a.comment_view.comment.deleted - +b.comment_view.comment.deleted ||
969 a.comment_view.comment.published.localeCompare(
970 b.comment_view.comment.published
973 } else if (sort == CommentSortType.Hot) {
976 +a.comment_view.comment.removed - +b.comment_view.comment.removed ||
977 +a.comment_view.comment.deleted - +b.comment_view.comment.deleted ||
978 hotRankComment(b.comment_view) - hotRankComment(a.comment_view)
982 // Go through the children recursively
983 for (let node of tree) {
985 commentSort(node.children, sort);
990 export function commentSortSortType(tree: CommentNodeI[], sort: SortType) {
991 commentSort(tree, convertCommentSortType(sort));
994 function convertCommentSortType(sort: SortType): CommentSortType {
996 sort == SortType.TopAll ||
997 sort == SortType.TopDay ||
998 sort == SortType.TopWeek ||
999 sort == SortType.TopMonth ||
1000 sort == SortType.TopYear
1002 return CommentSortType.Top;
1003 } else if (sort == SortType.New) {
1004 return CommentSortType.New;
1005 } else if (sort == SortType.Hot || sort == SortType.Active) {
1006 return CommentSortType.Hot;
1008 return CommentSortType.Hot;
1012 export function buildCommentsTree(
1013 comments: CommentView[],
1014 commentSortType: CommentSortType
1016 let map = new Map<number, CommentNodeI>();
1017 for (let comment_view of comments) {
1018 let node: CommentNodeI = {
1019 comment_view: comment_view,
1022 map.set(comment_view.comment.id, { ...node });
1024 let tree: CommentNodeI[] = [];
1025 for (let comment_view of comments) {
1026 let child = map.get(comment_view.comment.id);
1027 let parent_id = comment_view.comment.parent_id;
1029 let parent = map.get(parent_id);
1030 // Necessary because blocked comment might not exist
1032 parent.children.push(child);
1041 commentSort(tree, commentSortType);
1046 function setDepth(node: CommentNodeI, i = 0) {
1047 for (let child of node.children) {
1049 setDepth(child, i + 1);
1053 export function insertCommentIntoTree(tree: CommentNodeI[], cv: CommentView) {
1054 // Building a fake node to be used for later
1055 let node: CommentNodeI = {
1061 if (cv.comment.parent_id) {
1062 let parentComment = searchCommentTree(tree, cv.comment.parent_id);
1063 if (parentComment) {
1064 node.depth = parentComment.depth + 1;
1065 parentComment.children.unshift(node);
1072 export function searchCommentTree(
1073 tree: CommentNodeI[],
1076 for (let node of tree) {
1077 if (node.comment_view.comment.id === id) {
1081 for (const child of node.children) {
1082 const res = searchCommentTree([child], id);
1092 export const colorList: string[] = [
1101 function hsl(num: number) {
1102 return `hsla(${num}, 35%, 50%, 1)`;
1105 export function previewLines(
1114 // Use lines * 2 because markdown requires 2 lines
1115 .slice(0, maxLines * 2)
1120 export function hostname(url: string): string {
1121 let cUrl = new URL(url);
1122 return cUrl.port ? `${cUrl.hostname}:${cUrl.port}` : `${cUrl.hostname}`;
1125 export function validTitle(title?: string): boolean {
1126 // Initial title is null, minimum length is taken care of by textarea's minLength={3}
1127 if (title === null || title.length < 3) return true;
1129 const regex = new RegExp(/.*\S.*/, "g");
1131 return regex.test(title);
1134 export function siteBannerCss(banner: string): string {
1136 background-image: linear-gradient( rgba(0, 0, 0, 0.8), rgba(0, 0, 0, 0.8) ) ,url("${banner}"); \
1137 background-attachment: fixed; \
1138 background-position: top; \
1139 background-repeat: no-repeat; \
1140 background-size: 100% cover; \
1143 max-height: 100vh; \
1147 export function isBrowser() {
1148 return typeof window !== "undefined";
1151 export function setIsoData(context: any): IsoData {
1152 let isoData: IsoData = isBrowser()
1154 : context.router.staticContext;
1158 export function wsSubscribe(parseMessage: any): Subscription {
1160 return WebSocketService.Instance.subject
1161 .pipe(retryWhen(errors => errors.pipe(delay(3000), take(10))))
1163 msg => parseMessage(msg),
1164 err => console.error(err),
1165 () => console.log("complete")
1172 export function setOptionalAuth(obj: any, auth = UserService.Instance.auth) {
1178 export function authField(
1180 auth = UserService.Instance.auth
1182 if (auth == null && throwErr) {
1183 toast(i18n.t("not_logged_in"), "danger");
1184 throw "Not logged in";
1190 moment.updateLocale("en", {
1211 export function saveScrollPosition(context: any) {
1212 let path: string = context.router.route.location.pathname;
1213 let y = window.scrollY;
1214 sessionStorage.setItem(`scrollPosition_${path}`, y.toString());
1217 export function restoreScrollPosition(context: any) {
1218 let path: string = context.router.route.location.pathname;
1219 let y = Number(sessionStorage.getItem(`scrollPosition_${path}`));
1220 window.scrollTo(0, y);
1223 export function showLocal(isoData: IsoData): boolean {
1224 return isoData.site_res.federated_instances?.linked.length > 0;
1227 interface ChoicesValue {
1232 export function communityToChoice(cv: CommunityView): ChoicesValue {
1233 let choice: ChoicesValue = {
1234 value: cv.community.id.toString(),
1235 label: communitySelectName(cv),
1240 export function personToChoice(pvs: PersonViewSafe): ChoicesValue {
1241 let choice: ChoicesValue = {
1242 value: pvs.person.id.toString(),
1243 label: personSelectName(pvs),
1248 export async function fetchCommunities(q: string) {
1249 let form: Search = {
1251 type_: SearchType.Communities,
1252 sort: SortType.TopAll,
1253 listing_type: ListingType.All,
1256 auth: authField(false),
1258 let client = new LemmyHttp(httpBase);
1259 return client.search(form);
1262 export async function fetchUsers(q: string) {
1263 let form: Search = {
1265 type_: SearchType.Users,
1266 sort: SortType.TopAll,
1267 listing_type: ListingType.All,
1270 auth: authField(false),
1272 let client = new LemmyHttp(httpBase);
1273 return client.search(form);
1276 export const choicesConfig = {
1278 searchResultLimit: fetchLimit,
1280 containerOuter: "choices",
1281 containerInner: "choices__inner bg-secondary border-0",
1282 input: "form-control",
1283 inputCloned: "choices__input--cloned",
1284 list: "choices__list",
1285 listItems: "choices__list--multiple",
1286 listSingle: "choices__list--single",
1287 listDropdown: "choices__list--dropdown",
1288 item: "choices__item bg-secondary",
1289 itemSelectable: "choices__item--selectable",
1290 itemDisabled: "choices__item--disabled",
1291 itemChoice: "choices__item--choice",
1292 placeholder: "choices__placeholder",
1293 group: "choices__group",
1294 groupHeading: "choices__heading",
1295 button: "choices__button",
1296 activeState: "is-active",
1297 focusState: "is-focused",
1298 openState: "is-open",
1299 disabledState: "is-disabled",
1300 highlightedState: "text-info",
1301 selectedState: "text-info",
1302 flippedState: "is-flipped",
1303 loadingState: "is-loading",
1304 noResults: "has-no-results",
1305 noChoices: "has-no-choices",
1309 export function communitySelectName(cv: CommunityView): string {
1310 return cv.community.local
1311 ? cv.community.title
1312 : `${hostname(cv.community.actor_id)}/${cv.community.title}`;
1315 export function personSelectName(pvs: PersonViewSafe): string {
1316 let pName = pvs.person.display_name || pvs.person.name;
1317 return pvs.person.local ? pName : `${hostname(pvs.person.actor_id)}/${pName}`;
1320 export function initializeSite(site: GetSiteResponse) {
1321 UserService.Instance.myUserInfo = site.my_user;
1322 i18n.changeLanguage(getLanguages()[0]);
1325 const SHORTNUM_SI_FORMAT = new Intl.NumberFormat("en-US", {
1326 maximumSignificantDigits: 3,
1328 notation: "compact",
1329 compactDisplay: "short",
1332 export function numToSI(value: number): string {
1333 return SHORTNUM_SI_FORMAT.format(value);
1336 export function isBanned(ps: PersonSafe): boolean {
1337 // Add Z to convert from UTC date
1338 if (ps.ban_expires) {
1339 if (ps.banned && new Date(ps.ban_expires + "Z") > new Date()) {