1 import emojiShortName from "emoji-short-name";
3 BlockCommunityResponse,
23 WebSocketJsonResponse,
25 } from "lemmy-js-client";
26 import markdown_it from "markdown-it";
27 import markdown_it_container from "markdown-it-container";
28 import markdown_it_sub from "markdown-it-sub";
29 import markdown_it_sup from "markdown-it-sup";
30 import moment from "moment";
31 import "moment/locale/bg";
32 import "moment/locale/ca";
33 import "moment/locale/cy";
34 import "moment/locale/da";
35 import "moment/locale/de";
36 import "moment/locale/el";
37 import "moment/locale/eo";
38 import "moment/locale/es";
39 import "moment/locale/eu";
40 import "moment/locale/fa";
41 import "moment/locale/fi";
42 import "moment/locale/fr";
43 import "moment/locale/ga";
44 import "moment/locale/gl";
45 import "moment/locale/hi";
46 import "moment/locale/hr";
47 import "moment/locale/hu";
48 import "moment/locale/id";
49 import "moment/locale/it";
50 import "moment/locale/ja";
51 import "moment/locale/ka";
52 import "moment/locale/km";
53 import "moment/locale/ko";
54 import "moment/locale/nb";
55 import "moment/locale/nl";
56 import "moment/locale/pl";
57 import "moment/locale/pt-br";
58 import "moment/locale/ru";
59 import "moment/locale/sk";
60 import "moment/locale/sq";
61 import "moment/locale/sr";
62 import "moment/locale/sv";
63 import "moment/locale/tr";
64 import "moment/locale/uk";
65 import "moment/locale/vi";
66 import "moment/locale/zh-cn";
67 import { Subscription } from "rxjs";
68 import { delay, retryWhen, take } from "rxjs/operators";
69 import tippy from "tippy.js";
70 import Toastify from "toastify-js";
71 import { httpBase } from "./env";
72 import { i18n } from "./i18next";
74 CommentNode as CommentNodeI,
78 } from "./interfaces";
79 import { UserService, WebSocketService } from "./services";
83 Tribute = require("tributejs");
86 export const wsClient = new LemmyWebsocket();
88 export const favIconUrl = "/static/assets/icons/favicon.svg";
89 export const favIconPngUrl = "/static/assets/icons/apple-touch-icon.png";
91 // export const defaultFavIcon = `${window.location.protocol}//${window.location.host}${favIconPngUrl}`;
92 export const repoUrl = "https://github.com/LemmyNet";
93 export const joinLemmyUrl = "https://join-lemmy.org";
94 export const supportLemmyUrl = `${joinLemmyUrl}/support`;
95 export const docsUrl = `${joinLemmyUrl}/docs/en/index.html`;
96 export const helpGuideUrl = `${joinLemmyUrl}/docs/en/about/guide.html`; // TODO find a way to redirect to the non-en folder
97 export const markdownHelpUrl = `${helpGuideUrl}#markdown-guide`;
98 export const sortingHelpUrl = `${helpGuideUrl}#sorting`;
99 export const archiveUrl = "https://archive.is";
100 export const elementUrl = "https://element.io/";
102 export const postRefetchSeconds: number = 60 * 1000;
103 export const fetchLimit = 20;
104 export const mentionDropdownFetchLimit = 10;
106 export const languages = [
151 export const themes = [
167 const DEFAULT_ALPHABET =
168 "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
170 function getRandomCharFromAlphabet(alphabet: string): string {
171 return alphabet.charAt(Math.floor(Math.random() * alphabet.length));
174 export function randomStr(
175 idDesiredLength = 20,
176 alphabet = DEFAULT_ALPHABET
179 * Create n-long array and map it to random chars from given alphabet.
180 * Then join individual chars as string
182 return Array.from({ length: idDesiredLength })
184 return getRandomCharFromAlphabet(alphabet);
189 export function wsJsonToRes<ResponseType>(
190 msg: WebSocketJsonResponse<ResponseType>
191 ): WebSocketResponse<ResponseType> {
198 export function wsUserOp(msg: any): UserOperation {
199 let opStr: string = msg.op;
200 return UserOperation[opStr];
203 export const md = new markdown_it({
208 .use(markdown_it_sub)
209 .use(markdown_it_sup)
210 .use(markdown_it_container, "spoiler", {
211 validate: function (params: any) {
212 return params.trim().match(/^spoiler\s+(.*)$/);
215 render: function (tokens: any, idx: any) {
216 var m = tokens[idx].info.trim().match(/^spoiler\s+(.*)$/);
218 if (tokens[idx].nesting === 1) {
220 return `<details><summary> ${md.utils.escapeHtml(m[1])} </summary>\n`;
223 return "</details>\n";
228 export function hotRankComment(comment_view: CommentView): number {
229 return hotRank(comment_view.counts.score, comment_view.comment.published);
232 export function hotRankActivePost(post_view: PostView): number {
233 return hotRank(post_view.counts.score, post_view.counts.newest_comment_time);
236 export function hotRankPost(post_view: PostView): number {
237 return hotRank(post_view.counts.score, post_view.post.published);
240 export function hotRank(score: number, timeStr: string): number {
241 // Rank = ScaleFactor * sign(Score) * log(1 + abs(Score)) / (Time + 2)^Gravity
242 let date: Date = new Date(timeStr + "Z"); // Add Z to convert from UTC date
243 let now: Date = new Date();
244 let hoursElapsed: number = (now.getTime() - date.getTime()) / 36e5;
247 (10000 * Math.log10(Math.max(1, 3 + score))) /
248 Math.pow(hoursElapsed + 2, 1.8);
250 // console.log(`Comment: ${comment.content}\nRank: ${rank}\nScore: ${comment.score}\nHours: ${hoursElapsed}`);
255 export function mdToHtml(text: string) {
256 return { __html: md.render(text) };
259 export function getUnixTime(text: string): number {
260 return text ? new Date(text).getTime() / 1000 : undefined;
263 export function canMod(
264 myUserInfo: MyUserInfo,
269 // You can do moderator actions only on the mods added after you.
271 let yourIndex = modIds.findIndex(
272 id => id == myUserInfo.local_user_view.person.id
274 if (yourIndex == -1) {
277 // onSelf +1 on mod actions not for yourself, IE ban, remove, etc
278 modIds = modIds.slice(0, yourIndex + (onSelf ? 0 : 1));
279 return !modIds.includes(creator_id);
286 export function isMod(modIds: number[], creator_id: number): boolean {
287 return modIds.includes(creator_id);
290 const imageRegex = new RegExp(
291 /(http)?s?:?(\/\/[^"']*\.(?:jpg|jpeg|gif|png|svg|webp))/
293 const videoRegex = new RegExp(`(http)?s?:?(\/\/[^"']*\.(?:mp4))`);
295 export function isImage(url: string) {
296 return imageRegex.test(url);
299 export function isVideo(url: string) {
300 return videoRegex.test(url);
303 export function validURL(str: string) {
304 return !!new URL(str);
307 export function communityRSSUrl(actorId: string, sort: string): string {
308 let url = new URL(actorId);
309 return `${url.origin}/feeds${url.pathname}.xml?sort=${sort}`;
312 export function validEmail(email: string) {
314 /^(([^\s"(),.:;<>@[\\\]]+(\.[^\s"(),.:;<>@[\\\]]+)*)|(".+"))@((\[(?:\d{1,3}\.){3}\d{1,3}])|(([\dA-Za-z\-]+\.)+[A-Za-z]{2,}))$/;
315 return re.test(String(email).toLowerCase());
318 export function capitalizeFirstLetter(str: string): string {
319 return str.charAt(0).toUpperCase() + str.slice(1);
322 export function routeSortTypeToEnum(sort: string): SortType {
323 return SortType[sort];
326 export function listingTypeFromNum(type_: number): ListingType {
327 return Object.values(ListingType)[type_];
330 export function sortTypeFromNum(type_: number): SortType {
331 return Object.values(SortType)[type_];
334 export function routeListingTypeToEnum(type: string): ListingType {
335 return ListingType[type];
338 export function routeDataTypeToEnum(type: string): DataType {
339 return DataType[capitalizeFirstLetter(type)];
342 export function routeSearchTypeToEnum(type: string): SearchType {
343 return SearchType[type];
346 export async function getSiteMetadata(url: string) {
347 let form: GetSiteMetadata = {
350 let client = new LemmyHttp(httpBase);
351 return client.getSiteMetadata(form);
354 export function debounce(func: any, wait = 1000, immediate = false) {
355 // 'private' variable for instance
356 // The returned function will be able to reference this due to closure.
357 // Each call to the returned function will share this common timer.
360 // Calling debounce returns a new anonymous function
362 // reference the context and args for the setTimeout function
363 var args = arguments;
365 // Should the function be called now? If immediate is true
366 // and not already in a timeout then the answer is: Yes
367 var callNow = immediate && !timeout;
369 // This is the basic debounce behaviour where you can call this
370 // function several times, but it will only execute once
371 // [before or after imposing a delay].
372 // Each time the returned function is called, the timer starts over.
373 clearTimeout(timeout);
375 // Set the new timeout
376 timeout = setTimeout(function () {
377 // Inside the timeout function, clear the timeout variable
378 // which will let the next execution run when in 'immediate' mode
381 // Check if the function already ran with the immediate flag
383 // Call the original function with apply
384 // apply lets you define the 'this' object as well as the arguments
385 // (both captured before setTimeout)
386 func.apply(this, args);
390 // Immediate mode and no wait timer? Execute the function..
391 if (callNow) func.apply(this, args);
396 export function getLanguage(override?: string): string {
397 let myUserInfo = UserService.Instance.myUserInfo;
400 (myUserInfo?.local_user_view.local_user.lang
401 ? myUserInfo.local_user_view.local_user.lang
404 if (lang == "browser" && isBrowser()) {
405 return getBrowserLanguage();
411 export function getBrowserLanguage(): string {
412 // Intersect lemmy's langs, with the browser langs
413 let langs = languages ? languages.map(l => l.code) : ["en"];
415 // NOTE, mobile browsers seem to be missing this list, so append en
416 let allowedLangs = navigator.languages
418 .filter(v => langs.includes(v));
419 return allowedLangs[0];
422 export function getMomentLanguage(): string {
423 let lang = getLanguage();
424 if (lang.startsWith("zh")) {
426 } else if (lang.startsWith("sv")) {
428 } else if (lang.startsWith("fr")) {
430 } else if (lang.startsWith("de")) {
432 } else if (lang.startsWith("ru")) {
434 } else if (lang.startsWith("es")) {
436 } else if (lang.startsWith("eo")) {
438 } else if (lang.startsWith("nl")) {
440 } else if (lang.startsWith("it")) {
442 } else if (lang.startsWith("fi")) {
444 } else if (lang.startsWith("ca")) {
446 } else if (lang.startsWith("fa")) {
448 } else if (lang.startsWith("pl")) {
450 } else if (lang.startsWith("pt_BR")) {
452 } else if (lang.startsWith("ja")) {
454 } else if (lang.startsWith("ka")) {
456 } else if (lang.startsWith("hi")) {
458 } else if (lang.startsWith("el")) {
460 } else if (lang.startsWith("eu")) {
462 } else if (lang.startsWith("gl")) {
464 } else if (lang.startsWith("tr")) {
466 } else if (lang.startsWith("hu")) {
468 } else if (lang.startsWith("uk")) {
470 } else if (lang.startsWith("sq")) {
472 } else if (lang.startsWith("km")) {
474 } else if (lang.startsWith("ga")) {
476 } else if (lang.startsWith("sr")) {
478 } else if (lang.startsWith("ko")) {
480 } else if (lang.startsWith("da")) {
482 } else if (lang.startsWith("oc")) {
484 } else if (lang.startsWith("hr")) {
486 } else if (lang.startsWith("th")) {
488 } else if (lang.startsWith("bg")) {
490 } else if (lang.startsWith("id")) {
492 } else if (lang.startsWith("nb")) {
494 } else if (lang.startsWith("cy")) {
496 } else if (lang.startsWith("sk")) {
498 } else if (lang.startsWith("vi")) {
500 } else if (lang.startsWith("pt")) {
508 export function setTheme(theme: string, forceReload = false) {
512 if (theme === "browser" && !forceReload) {
515 // This is only run on a force reload
516 if (theme == "browser") {
520 // Unload all the other themes
521 for (var i = 0; i < themes.length; i++) {
522 let styleSheet = document.getElementById(themes[i]);
524 styleSheet.setAttribute("disabled", "disabled");
529 .getElementById("default-light")
530 ?.setAttribute("disabled", "disabled");
531 document.getElementById("default-dark")?.setAttribute("disabled", "disabled");
533 // Load the theme dynamically
534 let cssLoc = `/static/assets/css/themes/${theme}.min.css`;
535 loadCss(theme, cssLoc);
536 document.getElementById(theme).removeAttribute("disabled");
539 export function loadCss(id: string, loc: string) {
540 if (!document.getElementById(id)) {
541 var head = document.getElementsByTagName("head")[0];
542 var link = document.createElement("link");
544 link.rel = "stylesheet";
545 link.type = "text/css";
548 head.appendChild(link);
552 export function objectFlip(obj: any) {
554 Object.keys(obj).forEach(key => {
560 export function showAvatars(): boolean {
562 UserService.Instance.myUserInfo?.local_user_view.local_user.show_avatars ||
563 !UserService.Instance.myUserInfo
567 export function showScores(): boolean {
569 UserService.Instance.myUserInfo?.local_user_view.local_user.show_scores ||
570 !UserService.Instance.myUserInfo
574 export function isCakeDay(published: string): boolean {
575 // moment(undefined) or moment.utc(undefined) returns the current date/time
576 // moment(null) or moment.utc(null) returns null
577 const createDate = moment.utc(published || null).local();
578 const currentDate = moment(new Date());
581 createDate.date() === currentDate.date() &&
582 createDate.month() === currentDate.month() &&
583 createDate.year() !== currentDate.year()
587 export function toast(text: string, background = "success") {
589 let backgroundColor = `var(--${background})`;
592 backgroundColor: backgroundColor,
599 export function pictrsDeleteToast(
600 clickToDeleteText: string,
601 deletePictureText: string,
605 let backgroundColor = `var(--light)`;
606 let toast = Toastify({
607 text: clickToDeleteText,
608 backgroundColor: backgroundColor,
614 window.location.replace(deleteUrl);
615 alert(deletePictureText);
624 interface NotifyInfo {
631 export function messageToastify(info: NotifyInfo, router: any) {
633 let htmlBody = info.body ? md.render(info.body) : "";
634 let backgroundColor = `var(--light)`;
636 let toast = Toastify({
637 text: `${htmlBody}<br />${info.name}`,
638 avatar: info.icon ? info.icon : null,
639 backgroundColor: backgroundColor,
640 className: "text-dark",
649 router.history.push(info.link);
656 export function notifyPost(post_view: PostView, router: any) {
657 let info: NotifyInfo = {
658 name: post_view.community.name,
659 icon: post_view.community.icon,
660 link: `/post/${post_view.post.id}`,
661 body: post_view.post.name,
663 notify(info, router);
666 export function notifyComment(comment_view: CommentView, router: any) {
667 let info: NotifyInfo = {
668 name: comment_view.creator.name,
669 icon: comment_view.creator.avatar,
670 link: `/post/${comment_view.post.id}/comment/${comment_view.comment.id}`,
671 body: comment_view.comment.content,
673 notify(info, router);
676 export function notifyPrivateMessage(pmv: PrivateMessageView, router: any) {
677 let info: NotifyInfo = {
678 name: pmv.creator.name,
679 icon: pmv.creator.avatar,
681 body: pmv.private_message.content,
683 notify(info, router);
686 function notify(info: NotifyInfo, router: any) {
687 messageToastify(info, router);
689 // TODO absolute nightmare bug, but notifs are currently broken.
690 // Notification.new will try to do a browser fetch ???
692 // if (Notification.permission !== "granted") Notification.requestPermission();
694 // var notification = new Notification(info.name, {
699 // notification.onclick = (ev: Event): any => {
700 // ev.preventDefault();
701 // router.history.push(info.link);
706 export function setupTribute() {
708 noMatchTemplate: function () {
715 menuItemTemplate: (item: any) => {
716 let shortName = `:${item.original.key}:`;
717 return `${item.original.val} ${shortName}`;
719 selectTemplate: (item: any) => {
720 return `${item.original.val}`;
722 values: Object.entries(emojiShortName).map(e => {
723 return { key: e[1], val: e[0] };
726 autocompleteMode: true,
728 // menuItemLimit: mentionDropdownFetchLimit,
729 menuShowMinLength: 2,
734 selectTemplate: (item: any) => {
735 let it: PersonTribute = item.original;
736 return `[${it.key}](${it.view.person.actor_id})`;
738 values: (text: string, cb: (persons: PersonTribute[]) => any) => {
739 personSearch(text, (persons: PersonTribute[]) => cb(persons));
742 autocompleteMode: true,
744 // menuItemLimit: mentionDropdownFetchLimit,
745 menuShowMinLength: 2,
751 selectTemplate: (item: any) => {
752 let it: CommunityTribute = item.original;
753 return `[${it.key}](${it.view.community.actor_id})`;
755 values: (text: string, cb: any) => {
756 communitySearch(text, (communities: CommunityTribute[]) =>
761 autocompleteMode: true,
763 // menuItemLimit: mentionDropdownFetchLimit,
764 menuShowMinLength: 2,
770 var tippyInstance: any;
772 tippyInstance = tippy("[data-tippy-content]");
775 export function setupTippy() {
777 tippyInstance.forEach((e: any) => e.destroy());
778 tippyInstance = tippy("[data-tippy-content]", {
780 // Display on "long press"
781 touch: ["hold", 500],
786 interface PersonTribute {
788 view: PersonViewSafe;
791 function personSearch(text: string, cb: (persons: PersonTribute[]) => any) {
795 type_: SearchType.Users,
796 sort: SortType.TopAll,
797 listing_type: ListingType.All,
799 limit: mentionDropdownFetchLimit,
800 auth: authField(false),
803 WebSocketService.Instance.send(wsClient.search(form));
805 let personSub = WebSocketService.Instance.subject.subscribe(
807 let res = wsJsonToRes(msg);
808 if (res.op == UserOperation.Search) {
809 let data = res.data as SearchResponse;
810 let persons: PersonTribute[] = data.users.map(pv => {
811 let tribute: PersonTribute = {
812 key: `@${pv.person.name}@${hostname(pv.person.actor_id)}`,
818 personSub.unsubscribe();
821 err => console.error(err),
822 () => console.log("complete")
829 interface CommunityTribute {
834 function communitySearch(
836 cb: (communities: CommunityTribute[]) => any
841 type_: SearchType.Communities,
842 sort: SortType.TopAll,
843 listing_type: ListingType.All,
845 limit: mentionDropdownFetchLimit,
846 auth: authField(false),
849 WebSocketService.Instance.send(wsClient.search(form));
851 let communitySub = WebSocketService.Instance.subject.subscribe(
853 let res = wsJsonToRes(msg);
854 if (res.op == UserOperation.Search) {
855 let data = res.data as SearchResponse;
856 let communities: CommunityTribute[] = data.communities.map(cv => {
857 let tribute: CommunityTribute = {
858 key: `!${cv.community.name}@${hostname(cv.community.actor_id)}`,
864 communitySub.unsubscribe();
867 err => console.error(err),
868 () => console.log("complete")
875 export function getListingTypeFromProps(props: any): ListingType {
876 return props.match.params.listing_type
877 ? routeListingTypeToEnum(props.match.params.listing_type)
878 : UserService.Instance.myUserInfo
879 ? Object.values(ListingType)[
880 UserService.Instance.myUserInfo.local_user_view.local_user
881 .default_listing_type
886 export function getListingTypeFromPropsNoDefault(props: any): ListingType {
887 return props.match.params.listing_type
888 ? routeListingTypeToEnum(props.match.params.listing_type)
892 // TODO might need to add a user setting for this too
893 export function getDataTypeFromProps(props: any): DataType {
894 return props.match.params.data_type
895 ? routeDataTypeToEnum(props.match.params.data_type)
899 export function getSortTypeFromProps(props: any): SortType {
900 return props.match.params.sort
901 ? routeSortTypeToEnum(props.match.params.sort)
902 : UserService.Instance.myUserInfo
903 ? Object.values(SortType)[
904 UserService.Instance.myUserInfo.local_user_view.local_user
910 export function getPageFromProps(props: any): number {
911 return props.match.params.page ? Number(props.match.params.page) : 1;
914 export function getRecipientIdFromProps(props: any): number {
915 return props.match.params.recipient_id
916 ? Number(props.match.params.recipient_id)
920 export function getIdFromProps(props: any): number {
921 return Number(props.match.params.id);
924 export function getCommentIdFromProps(props: any): number {
925 return Number(props.match.params.comment_id);
928 export function getUsernameFromProps(props: any): string {
929 return props.match.params.username;
932 export function editCommentRes(data: CommentView, comments: CommentView[]) {
933 let found = comments.find(c => c.comment.id == data.comment.id);
935 found.comment.content = data.comment.content;
936 found.comment.updated = data.comment.updated;
937 found.comment.removed = data.comment.removed;
938 found.comment.deleted = data.comment.deleted;
939 found.counts.upvotes = data.counts.upvotes;
940 found.counts.downvotes = data.counts.downvotes;
941 found.counts.score = data.counts.score;
945 export function saveCommentRes(data: CommentView, comments: CommentView[]) {
946 let found = comments.find(c => c.comment.id == data.comment.id);
948 found.saved = data.saved;
952 export function updatePersonBlock(
953 data: BlockPersonResponse
954 ): PersonBlockView[] {
956 UserService.Instance.myUserInfo.person_blocks.push({
957 person: UserService.Instance.myUserInfo.local_user_view.person,
958 target: data.person_view.person,
960 toast(`${i18n.t("blocked")} ${data.person_view.person.name}`);
962 UserService.Instance.myUserInfo.person_blocks =
963 UserService.Instance.myUserInfo.person_blocks.filter(
964 i => i.target.id != data.person_view.person.id
966 toast(`${i18n.t("unblocked")} ${data.person_view.person.name}`);
968 return UserService.Instance.myUserInfo.person_blocks;
971 export function updateCommunityBlock(
972 data: BlockCommunityResponse
973 ): CommunityBlockView[] {
975 UserService.Instance.myUserInfo.community_blocks.push({
976 person: UserService.Instance.myUserInfo.local_user_view.person,
977 community: data.community_view.community,
979 toast(`${i18n.t("blocked")} ${data.community_view.community.name}`);
981 UserService.Instance.myUserInfo.community_blocks =
982 UserService.Instance.myUserInfo.community_blocks.filter(
983 i => i.community.id != data.community_view.community.id
985 toast(`${i18n.t("unblocked")} ${data.community_view.community.name}`);
987 return UserService.Instance.myUserInfo.community_blocks;
990 export function createCommentLikeRes(
992 comments: CommentView[]
994 let found = comments.find(c => c.comment.id === data.comment.id);
996 found.counts.score = data.counts.score;
997 found.counts.upvotes = data.counts.upvotes;
998 found.counts.downvotes = data.counts.downvotes;
999 if (data.my_vote !== null) {
1000 found.my_vote = data.my_vote;
1005 export function createPostLikeFindRes(data: PostView, posts: PostView[]) {
1006 let found = posts.find(p => p.post.id == data.post.id);
1008 createPostLikeRes(data, found);
1012 export function createPostLikeRes(data: PostView, post_view: PostView) {
1014 post_view.counts.score = data.counts.score;
1015 post_view.counts.upvotes = data.counts.upvotes;
1016 post_view.counts.downvotes = data.counts.downvotes;
1017 if (data.my_vote !== null) {
1018 post_view.my_vote = data.my_vote;
1023 export function editPostFindRes(data: PostView, posts: PostView[]) {
1024 let found = posts.find(p => p.post.id == data.post.id);
1026 editPostRes(data, found);
1030 export function editPostRes(data: PostView, post: PostView) {
1032 post.post.url = data.post.url;
1033 post.post.name = data.post.name;
1034 post.post.nsfw = data.post.nsfw;
1035 post.post.deleted = data.post.deleted;
1036 post.post.removed = data.post.removed;
1037 post.post.stickied = data.post.stickied;
1038 post.post.body = data.post.body;
1039 post.post.locked = data.post.locked;
1040 post.saved = data.saved;
1044 export function commentsToFlatNodes(comments: CommentView[]): CommentNodeI[] {
1045 let nodes: CommentNodeI[] = [];
1046 for (let comment of comments) {
1047 nodes.push({ comment_view: comment });
1052 function commentSort(tree: CommentNodeI[], sort: CommentSortType) {
1053 // First, put removed and deleted comments at the bottom, then do your other sorts
1054 if (sort == CommentSortType.Top) {
1057 +a.comment_view.comment.removed - +b.comment_view.comment.removed ||
1058 +a.comment_view.comment.deleted - +b.comment_view.comment.deleted ||
1059 b.comment_view.counts.score - a.comment_view.counts.score
1061 } else if (sort == CommentSortType.New) {
1064 +a.comment_view.comment.removed - +b.comment_view.comment.removed ||
1065 +a.comment_view.comment.deleted - +b.comment_view.comment.deleted ||
1066 b.comment_view.comment.published.localeCompare(
1067 a.comment_view.comment.published
1070 } else if (sort == CommentSortType.Old) {
1073 +a.comment_view.comment.removed - +b.comment_view.comment.removed ||
1074 +a.comment_view.comment.deleted - +b.comment_view.comment.deleted ||
1075 a.comment_view.comment.published.localeCompare(
1076 b.comment_view.comment.published
1079 } else if (sort == CommentSortType.Hot) {
1082 +a.comment_view.comment.removed - +b.comment_view.comment.removed ||
1083 +a.comment_view.comment.deleted - +b.comment_view.comment.deleted ||
1084 hotRankComment(b.comment_view) - hotRankComment(a.comment_view)
1088 // Go through the children recursively
1089 for (let node of tree) {
1090 if (node.children) {
1091 commentSort(node.children, sort);
1096 export function commentSortSortType(tree: CommentNodeI[], sort: SortType) {
1097 commentSort(tree, convertCommentSortType(sort));
1100 function convertCommentSortType(sort: SortType): CommentSortType {
1102 sort == SortType.TopAll ||
1103 sort == SortType.TopDay ||
1104 sort == SortType.TopWeek ||
1105 sort == SortType.TopMonth ||
1106 sort == SortType.TopYear
1108 return CommentSortType.Top;
1109 } else if (sort == SortType.New) {
1110 return CommentSortType.New;
1111 } else if (sort == SortType.Hot || sort == SortType.Active) {
1112 return CommentSortType.Hot;
1114 return CommentSortType.Hot;
1118 export function buildCommentsTree(
1119 comments: CommentView[],
1120 commentSortType: CommentSortType
1122 let map = new Map<number, CommentNodeI>();
1123 for (let comment_view of comments) {
1124 let node: CommentNodeI = {
1125 comment_view: comment_view,
1128 map.set(comment_view.comment.id, { ...node });
1130 let tree: CommentNodeI[] = [];
1131 for (let comment_view of comments) {
1132 let child = map.get(comment_view.comment.id);
1133 let parent_id = comment_view.comment.parent_id;
1135 let parent = map.get(parent_id);
1136 // Necessary because blocked comment might not exist
1138 parent.children.push(child);
1147 commentSort(tree, commentSortType);
1152 function setDepth(node: CommentNodeI, i = 0) {
1153 for (let child of node.children) {
1155 setDepth(child, i + 1);
1159 export function insertCommentIntoTree(tree: CommentNodeI[], cv: CommentView) {
1160 // Building a fake node to be used for later
1161 let node: CommentNodeI = {
1167 if (cv.comment.parent_id) {
1168 let parentComment = searchCommentTree(tree, cv.comment.parent_id);
1169 if (parentComment) {
1170 node.depth = parentComment.depth + 1;
1171 parentComment.children.unshift(node);
1178 export function searchCommentTree(
1179 tree: CommentNodeI[],
1182 for (let node of tree) {
1183 if (node.comment_view.comment.id === id) {
1187 for (const child of node.children) {
1188 const res = searchCommentTree([child], id);
1198 export const colorList: string[] = [
1207 function hsl(num: number) {
1208 return `hsla(${num}, 35%, 50%, 1)`;
1211 export function previewLines(
1220 // Use lines * 2 because markdown requires 2 lines
1221 .slice(0, maxLines * 2)
1226 export function hostname(url: string): string {
1227 let cUrl = new URL(url);
1228 return cUrl.port ? `${cUrl.hostname}:${cUrl.port}` : `${cUrl.hostname}`;
1231 export function validTitle(title?: string): boolean {
1232 // Initial title is null, minimum length is taken care of by textarea's minLength={3}
1233 if (title === null || title.length < 3) return true;
1235 const regex = new RegExp(/.*\S.*/, "g");
1237 return regex.test(title);
1240 export function siteBannerCss(banner: string): string {
1242 background-image: linear-gradient( rgba(0, 0, 0, 0.8), rgba(0, 0, 0, 0.8) ) ,url("${banner}"); \
1243 background-attachment: fixed; \
1244 background-position: top; \
1245 background-repeat: no-repeat; \
1246 background-size: 100% cover; \
1249 max-height: 100vh; \
1253 export function isBrowser() {
1254 return typeof window !== "undefined";
1257 export function setIsoData(context: any): IsoData {
1258 let isoData: IsoData = isBrowser()
1260 : context.router.staticContext;
1264 export function wsSubscribe(parseMessage: any): Subscription {
1266 return WebSocketService.Instance.subject
1267 .pipe(retryWhen(errors => errors.pipe(delay(3000), take(10))))
1269 msg => parseMessage(msg),
1270 err => console.error(err),
1271 () => console.log("complete")
1278 export function setOptionalAuth(obj: any, auth = UserService.Instance.auth) {
1284 export function authField(
1286 auth = UserService.Instance.auth
1288 if (auth == null && throwErr) {
1289 toast(i18n.t("not_logged_in"), "danger");
1290 throw "Not logged in";
1296 moment.updateLocale("en", {
1317 export function saveScrollPosition(context: any) {
1318 let path: string = context.router.route.location.pathname;
1319 let y = window.scrollY;
1320 sessionStorage.setItem(`scrollPosition_${path}`, y.toString());
1323 export function restoreScrollPosition(context: any) {
1324 let path: string = context.router.route.location.pathname;
1325 let y = Number(sessionStorage.getItem(`scrollPosition_${path}`));
1326 window.scrollTo(0, y);
1329 export function showLocal(isoData: IsoData): boolean {
1330 return isoData.site_res.federated_instances?.linked.length > 0;
1333 interface ChoicesValue {
1338 export function communityToChoice(cv: CommunityView): ChoicesValue {
1339 let choice: ChoicesValue = {
1340 value: cv.community.id.toString(),
1341 label: communitySelectName(cv),
1346 export function personToChoice(pvs: PersonViewSafe): ChoicesValue {
1347 let choice: ChoicesValue = {
1348 value: pvs.person.id.toString(),
1349 label: personSelectName(pvs),
1354 export async function fetchCommunities(q: string) {
1355 let form: Search = {
1357 type_: SearchType.Communities,
1358 sort: SortType.TopAll,
1359 listing_type: ListingType.All,
1362 auth: authField(false),
1364 let client = new LemmyHttp(httpBase);
1365 return client.search(form);
1368 export async function fetchUsers(q: string) {
1369 let form: Search = {
1371 type_: SearchType.Users,
1372 sort: SortType.TopAll,
1373 listing_type: ListingType.All,
1376 auth: authField(false),
1378 let client = new LemmyHttp(httpBase);
1379 return client.search(form);
1382 export const choicesConfig = {
1384 searchResultLimit: fetchLimit,
1386 containerOuter: "choices",
1387 containerInner: "choices__inner bg-secondary border-0",
1388 input: "form-control",
1389 inputCloned: "choices__input--cloned",
1390 list: "choices__list",
1391 listItems: "choices__list--multiple",
1392 listSingle: "choices__list--single",
1393 listDropdown: "choices__list--dropdown",
1394 item: "choices__item bg-secondary",
1395 itemSelectable: "choices__item--selectable",
1396 itemDisabled: "choices__item--disabled",
1397 itemChoice: "choices__item--choice",
1398 placeholder: "choices__placeholder",
1399 group: "choices__group",
1400 groupHeading: "choices__heading",
1401 button: "choices__button",
1402 activeState: "is-active",
1403 focusState: "is-focused",
1404 openState: "is-open",
1405 disabledState: "is-disabled",
1406 highlightedState: "text-info",
1407 selectedState: "text-info",
1408 flippedState: "is-flipped",
1409 loadingState: "is-loading",
1410 noResults: "has-no-results",
1411 noChoices: "has-no-choices",
1415 export function communitySelectName(cv: CommunityView): string {
1416 return cv.community.local
1418 : `${hostname(cv.community.actor_id)}/${cv.community.name}`;
1421 export function personSelectName(pvs: PersonViewSafe): string {
1422 return pvs.person.local
1424 : `${hostname(pvs.person.actor_id)}/${pvs.person.name}`;
1427 export function initializeSite(site: GetSiteResponse) {
1428 UserService.Instance.myUserInfo = site.my_user;
1429 i18n.changeLanguage(getLanguage());