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 if (Notification.permission !== "granted") Notification.requestPermission();
691 var notification = new Notification(info.name, {
692 ...{body: info.body},
693 ...(info.icon && {icon: info.icon})
696 notification.onclick = (ev: Event): any => {
698 router.history.push(info.link);
703 export function setupTribute() {
705 noMatchTemplate: function () {
712 menuItemTemplate: (item: any) => {
713 let shortName = `:${item.original.key}:`;
714 return `${item.original.val} ${shortName}`;
716 selectTemplate: (item: any) => {
717 return `${item.original.val}`;
719 values: Object.entries(emojiShortName).map(e => {
720 return { key: e[1], val: e[0] };
723 autocompleteMode: true,
725 // menuItemLimit: mentionDropdownFetchLimit,
726 menuShowMinLength: 2,
731 selectTemplate: (item: any) => {
732 let it: PersonTribute = item.original;
733 return `[${it.key}](${it.view.person.actor_id})`;
735 values: (text: string, cb: (persons: PersonTribute[]) => any) => {
736 personSearch(text, (persons: PersonTribute[]) => cb(persons));
739 autocompleteMode: true,
741 // menuItemLimit: mentionDropdownFetchLimit,
742 menuShowMinLength: 2,
748 selectTemplate: (item: any) => {
749 let it: CommunityTribute = item.original;
750 return `[${it.key}](${it.view.community.actor_id})`;
752 values: (text: string, cb: any) => {
753 communitySearch(text, (communities: CommunityTribute[]) =>
758 autocompleteMode: true,
760 // menuItemLimit: mentionDropdownFetchLimit,
761 menuShowMinLength: 2,
767 var tippyInstance: any;
769 tippyInstance = tippy("[data-tippy-content]");
772 export function setupTippy() {
774 tippyInstance.forEach((e: any) => e.destroy());
775 tippyInstance = tippy("[data-tippy-content]", {
777 // Display on "long press"
778 touch: ["hold", 500],
783 interface PersonTribute {
785 view: PersonViewSafe;
788 function personSearch(text: string, cb: (persons: PersonTribute[]) => any) {
792 type_: SearchType.Users,
793 sort: SortType.TopAll,
794 listing_type: ListingType.All,
796 limit: mentionDropdownFetchLimit,
797 auth: authField(false),
800 WebSocketService.Instance.send(wsClient.search(form));
802 let personSub = WebSocketService.Instance.subject.subscribe(
804 let res = wsJsonToRes(msg);
805 if (res.op == UserOperation.Search) {
806 let data = res.data as SearchResponse;
807 let persons: PersonTribute[] = data.users.map(pv => {
808 let tribute: PersonTribute = {
809 key: `@${pv.person.name}@${hostname(pv.person.actor_id)}`,
815 personSub.unsubscribe();
818 err => console.error(err),
819 () => console.log("complete")
826 interface CommunityTribute {
831 function communitySearch(
833 cb: (communities: CommunityTribute[]) => any
838 type_: SearchType.Communities,
839 sort: SortType.TopAll,
840 listing_type: ListingType.All,
842 limit: mentionDropdownFetchLimit,
843 auth: authField(false),
846 WebSocketService.Instance.send(wsClient.search(form));
848 let communitySub = WebSocketService.Instance.subject.subscribe(
850 let res = wsJsonToRes(msg);
851 if (res.op == UserOperation.Search) {
852 let data = res.data as SearchResponse;
853 let communities: CommunityTribute[] = data.communities.map(cv => {
854 let tribute: CommunityTribute = {
855 key: `!${cv.community.name}@${hostname(cv.community.actor_id)}`,
861 communitySub.unsubscribe();
864 err => console.error(err),
865 () => console.log("complete")
872 export function getListingTypeFromProps(props: any): ListingType {
873 return props.match.params.listing_type
874 ? routeListingTypeToEnum(props.match.params.listing_type)
875 : UserService.Instance.myUserInfo
876 ? Object.values(ListingType)[
877 UserService.Instance.myUserInfo.local_user_view.local_user
878 .default_listing_type
883 export function getListingTypeFromPropsNoDefault(props: any): ListingType {
884 return props.match.params.listing_type
885 ? routeListingTypeToEnum(props.match.params.listing_type)
889 // TODO might need to add a user setting for this too
890 export function getDataTypeFromProps(props: any): DataType {
891 return props.match.params.data_type
892 ? routeDataTypeToEnum(props.match.params.data_type)
896 export function getSortTypeFromProps(props: any): SortType {
897 return props.match.params.sort
898 ? routeSortTypeToEnum(props.match.params.sort)
899 : UserService.Instance.myUserInfo
900 ? Object.values(SortType)[
901 UserService.Instance.myUserInfo.local_user_view.local_user
907 export function getPageFromProps(props: any): number {
908 return props.match.params.page ? Number(props.match.params.page) : 1;
911 export function getRecipientIdFromProps(props: any): number {
912 return props.match.params.recipient_id
913 ? Number(props.match.params.recipient_id)
917 export function getIdFromProps(props: any): number {
918 return Number(props.match.params.id);
921 export function getCommentIdFromProps(props: any): number {
922 return Number(props.match.params.comment_id);
925 export function getUsernameFromProps(props: any): string {
926 return props.match.params.username;
929 export function editCommentRes(data: CommentView, comments: CommentView[]) {
930 let found = comments.find(c => c.comment.id == data.comment.id);
932 found.comment.content = data.comment.content;
933 found.comment.updated = data.comment.updated;
934 found.comment.removed = data.comment.removed;
935 found.comment.deleted = data.comment.deleted;
936 found.counts.upvotes = data.counts.upvotes;
937 found.counts.downvotes = data.counts.downvotes;
938 found.counts.score = data.counts.score;
942 export function saveCommentRes(data: CommentView, comments: CommentView[]) {
943 let found = comments.find(c => c.comment.id == data.comment.id);
945 found.saved = data.saved;
949 export function updatePersonBlock(
950 data: BlockPersonResponse
951 ): PersonBlockView[] {
953 UserService.Instance.myUserInfo.person_blocks.push({
954 person: UserService.Instance.myUserInfo.local_user_view.person,
955 target: data.person_view.person,
957 toast(`${i18n.t("blocked")} ${data.person_view.person.name}`);
959 UserService.Instance.myUserInfo.person_blocks =
960 UserService.Instance.myUserInfo.person_blocks.filter(
961 i => i.target.id != data.person_view.person.id
963 toast(`${i18n.t("unblocked")} ${data.person_view.person.name}`);
965 return UserService.Instance.myUserInfo.person_blocks;
968 export function updateCommunityBlock(
969 data: BlockCommunityResponse
970 ): CommunityBlockView[] {
972 UserService.Instance.myUserInfo.community_blocks.push({
973 person: UserService.Instance.myUserInfo.local_user_view.person,
974 community: data.community_view.community,
976 toast(`${i18n.t("blocked")} ${data.community_view.community.name}`);
978 UserService.Instance.myUserInfo.community_blocks =
979 UserService.Instance.myUserInfo.community_blocks.filter(
980 i => i.community.id != data.community_view.community.id
982 toast(`${i18n.t("unblocked")} ${data.community_view.community.name}`);
984 return UserService.Instance.myUserInfo.community_blocks;
987 export function createCommentLikeRes(
989 comments: CommentView[]
991 let found = comments.find(c => c.comment.id === data.comment.id);
993 found.counts.score = data.counts.score;
994 found.counts.upvotes = data.counts.upvotes;
995 found.counts.downvotes = data.counts.downvotes;
996 if (data.my_vote !== null) {
997 found.my_vote = data.my_vote;
1002 export function createPostLikeFindRes(data: PostView, posts: PostView[]) {
1003 let found = posts.find(p => p.post.id == data.post.id);
1005 createPostLikeRes(data, found);
1009 export function createPostLikeRes(data: PostView, post_view: PostView) {
1011 post_view.counts.score = data.counts.score;
1012 post_view.counts.upvotes = data.counts.upvotes;
1013 post_view.counts.downvotes = data.counts.downvotes;
1014 if (data.my_vote !== null) {
1015 post_view.my_vote = data.my_vote;
1020 export function editPostFindRes(data: PostView, posts: PostView[]) {
1021 let found = posts.find(p => p.post.id == data.post.id);
1023 editPostRes(data, found);
1027 export function editPostRes(data: PostView, post: PostView) {
1029 post.post.url = data.post.url;
1030 post.post.name = data.post.name;
1031 post.post.nsfw = data.post.nsfw;
1032 post.post.deleted = data.post.deleted;
1033 post.post.removed = data.post.removed;
1034 post.post.stickied = data.post.stickied;
1035 post.post.body = data.post.body;
1036 post.post.locked = data.post.locked;
1037 post.saved = data.saved;
1041 export function commentsToFlatNodes(comments: CommentView[]): CommentNodeI[] {
1042 let nodes: CommentNodeI[] = [];
1043 for (let comment of comments) {
1044 nodes.push({ comment_view: comment });
1049 function commentSort(tree: CommentNodeI[], sort: CommentSortType) {
1050 // First, put removed and deleted comments at the bottom, then do your other sorts
1051 if (sort == CommentSortType.Top) {
1054 +a.comment_view.comment.removed - +b.comment_view.comment.removed ||
1055 +a.comment_view.comment.deleted - +b.comment_view.comment.deleted ||
1056 b.comment_view.counts.score - a.comment_view.counts.score
1058 } else if (sort == CommentSortType.New) {
1061 +a.comment_view.comment.removed - +b.comment_view.comment.removed ||
1062 +a.comment_view.comment.deleted - +b.comment_view.comment.deleted ||
1063 b.comment_view.comment.published.localeCompare(
1064 a.comment_view.comment.published
1067 } else if (sort == CommentSortType.Old) {
1070 +a.comment_view.comment.removed - +b.comment_view.comment.removed ||
1071 +a.comment_view.comment.deleted - +b.comment_view.comment.deleted ||
1072 a.comment_view.comment.published.localeCompare(
1073 b.comment_view.comment.published
1076 } else if (sort == CommentSortType.Hot) {
1079 +a.comment_view.comment.removed - +b.comment_view.comment.removed ||
1080 +a.comment_view.comment.deleted - +b.comment_view.comment.deleted ||
1081 hotRankComment(b.comment_view) - hotRankComment(a.comment_view)
1085 // Go through the children recursively
1086 for (let node of tree) {
1087 if (node.children) {
1088 commentSort(node.children, sort);
1093 export function commentSortSortType(tree: CommentNodeI[], sort: SortType) {
1094 commentSort(tree, convertCommentSortType(sort));
1097 function convertCommentSortType(sort: SortType): CommentSortType {
1099 sort == SortType.TopAll ||
1100 sort == SortType.TopDay ||
1101 sort == SortType.TopWeek ||
1102 sort == SortType.TopMonth ||
1103 sort == SortType.TopYear
1105 return CommentSortType.Top;
1106 } else if (sort == SortType.New) {
1107 return CommentSortType.New;
1108 } else if (sort == SortType.Hot || sort == SortType.Active) {
1109 return CommentSortType.Hot;
1111 return CommentSortType.Hot;
1115 export function buildCommentsTree(
1116 comments: CommentView[],
1117 commentSortType: CommentSortType
1119 let map = new Map<number, CommentNodeI>();
1120 for (let comment_view of comments) {
1121 let node: CommentNodeI = {
1122 comment_view: comment_view,
1125 map.set(comment_view.comment.id, { ...node });
1127 let tree: CommentNodeI[] = [];
1128 for (let comment_view of comments) {
1129 let child = map.get(comment_view.comment.id);
1130 let parent_id = comment_view.comment.parent_id;
1132 let parent = map.get(parent_id);
1133 // Necessary because blocked comment might not exist
1135 parent.children.push(child);
1144 commentSort(tree, commentSortType);
1149 function setDepth(node: CommentNodeI, i = 0) {
1150 for (let child of node.children) {
1152 setDepth(child, i + 1);
1156 export function insertCommentIntoTree(tree: CommentNodeI[], cv: CommentView) {
1157 // Building a fake node to be used for later
1158 let node: CommentNodeI = {
1164 if (cv.comment.parent_id) {
1165 let parentComment = searchCommentTree(tree, cv.comment.parent_id);
1166 if (parentComment) {
1167 node.depth = parentComment.depth + 1;
1168 parentComment.children.unshift(node);
1175 export function searchCommentTree(
1176 tree: CommentNodeI[],
1179 for (let node of tree) {
1180 if (node.comment_view.comment.id === id) {
1184 for (const child of node.children) {
1185 const res = searchCommentTree([child], id);
1195 export const colorList: string[] = [
1204 function hsl(num: number) {
1205 return `hsla(${num}, 35%, 50%, 1)`;
1208 export function previewLines(
1217 // Use lines * 2 because markdown requires 2 lines
1218 .slice(0, maxLines * 2)
1223 export function hostname(url: string): string {
1224 let cUrl = new URL(url);
1225 return cUrl.port ? `${cUrl.hostname}:${cUrl.port}` : `${cUrl.hostname}`;
1228 export function validTitle(title?: string): boolean {
1229 // Initial title is null, minimum length is taken care of by textarea's minLength={3}
1230 if (title === null || title.length < 3) return true;
1232 const regex = new RegExp(/.*\S.*/, "g");
1234 return regex.test(title);
1237 export function siteBannerCss(banner: string): string {
1239 background-image: linear-gradient( rgba(0, 0, 0, 0.8), rgba(0, 0, 0, 0.8) ) ,url("${banner}"); \
1240 background-attachment: fixed; \
1241 background-position: top; \
1242 background-repeat: no-repeat; \
1243 background-size: 100% cover; \
1246 max-height: 100vh; \
1250 export function isBrowser() {
1251 return typeof window !== "undefined";
1254 export function setIsoData(context: any): IsoData {
1255 let isoData: IsoData = isBrowser()
1257 : context.router.staticContext;
1261 export function wsSubscribe(parseMessage: any): Subscription {
1263 return WebSocketService.Instance.subject
1264 .pipe(retryWhen(errors => errors.pipe(delay(3000), take(10))))
1266 msg => parseMessage(msg),
1267 err => console.error(err),
1268 () => console.log("complete")
1275 export function setOptionalAuth(obj: any, auth = UserService.Instance.auth) {
1281 export function authField(
1283 auth = UserService.Instance.auth
1285 if (auth == null && throwErr) {
1286 toast(i18n.t("not_logged_in"), "danger");
1287 throw "Not logged in";
1293 moment.updateLocale("en", {
1314 export function saveScrollPosition(context: any) {
1315 let path: string = context.router.route.location.pathname;
1316 let y = window.scrollY;
1317 sessionStorage.setItem(`scrollPosition_${path}`, y.toString());
1320 export function restoreScrollPosition(context: any) {
1321 let path: string = context.router.route.location.pathname;
1322 let y = Number(sessionStorage.getItem(`scrollPosition_${path}`));
1323 window.scrollTo(0, y);
1326 export function showLocal(isoData: IsoData): boolean {
1327 return isoData.site_res.federated_instances?.linked.length > 0;
1330 interface ChoicesValue {
1335 export function communityToChoice(cv: CommunityView): ChoicesValue {
1336 let choice: ChoicesValue = {
1337 value: cv.community.id.toString(),
1338 label: communitySelectName(cv),
1343 export function personToChoice(pvs: PersonViewSafe): ChoicesValue {
1344 let choice: ChoicesValue = {
1345 value: pvs.person.id.toString(),
1346 label: personSelectName(pvs),
1351 export async function fetchCommunities(q: string) {
1352 let form: Search = {
1354 type_: SearchType.Communities,
1355 sort: SortType.TopAll,
1356 listing_type: ListingType.All,
1359 auth: authField(false),
1361 let client = new LemmyHttp(httpBase);
1362 return client.search(form);
1365 export async function fetchUsers(q: string) {
1366 let form: Search = {
1368 type_: SearchType.Users,
1369 sort: SortType.TopAll,
1370 listing_type: ListingType.All,
1373 auth: authField(false),
1375 let client = new LemmyHttp(httpBase);
1376 return client.search(form);
1379 export const choicesConfig = {
1381 searchResultLimit: fetchLimit,
1383 containerOuter: "choices",
1384 containerInner: "choices__inner bg-secondary border-0",
1385 input: "form-control",
1386 inputCloned: "choices__input--cloned",
1387 list: "choices__list",
1388 listItems: "choices__list--multiple",
1389 listSingle: "choices__list--single",
1390 listDropdown: "choices__list--dropdown",
1391 item: "choices__item bg-secondary",
1392 itemSelectable: "choices__item--selectable",
1393 itemDisabled: "choices__item--disabled",
1394 itemChoice: "choices__item--choice",
1395 placeholder: "choices__placeholder",
1396 group: "choices__group",
1397 groupHeading: "choices__heading",
1398 button: "choices__button",
1399 activeState: "is-active",
1400 focusState: "is-focused",
1401 openState: "is-open",
1402 disabledState: "is-disabled",
1403 highlightedState: "text-info",
1404 selectedState: "text-info",
1405 flippedState: "is-flipped",
1406 loadingState: "is-loading",
1407 noResults: "has-no-results",
1408 noChoices: "has-no-choices",
1412 export function communitySelectName(cv: CommunityView): string {
1413 return cv.community.local
1415 : `${hostname(cv.community.actor_id)}/${cv.community.name}`;
1418 export function personSelectName(pvs: PersonViewSafe): string {
1419 return pvs.person.local
1421 : `${hostname(pvs.person.actor_id)}/${pvs.person.name}`;
1424 export function initializeSite(site: GetSiteResponse) {
1425 UserService.Instance.myUserInfo = site.my_user;
1426 i18n.changeLanguage(getLanguage());