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_html5_embed from "markdown-it-html5-embed";
29 import markdown_it_sub from "markdown-it-sub";
30 import markdown_it_sup from "markdown-it-sup";
31 import moment from "moment";
32 import "moment/locale/bg";
33 import "moment/locale/ca";
34 import "moment/locale/cy";
35 import "moment/locale/da";
36 import "moment/locale/de";
37 import "moment/locale/el";
38 import "moment/locale/eo";
39 import "moment/locale/es";
40 import "moment/locale/eu";
41 import "moment/locale/fa";
42 import "moment/locale/fi";
43 import "moment/locale/fr";
44 import "moment/locale/ga";
45 import "moment/locale/gl";
46 import "moment/locale/hi";
47 import "moment/locale/hr";
48 import "moment/locale/hu";
49 import "moment/locale/id";
50 import "moment/locale/it";
51 import "moment/locale/ja";
52 import "moment/locale/ka";
53 import "moment/locale/km";
54 import "moment/locale/ko";
55 import "moment/locale/nb";
56 import "moment/locale/nl";
57 import "moment/locale/pl";
58 import "moment/locale/pt-br";
59 import "moment/locale/ru";
60 import "moment/locale/sk";
61 import "moment/locale/sq";
62 import "moment/locale/sr";
63 import "moment/locale/sv";
64 import "moment/locale/tr";
65 import "moment/locale/uk";
66 import "moment/locale/vi";
67 import "moment/locale/zh-cn";
68 import { Subscription } from "rxjs";
69 import { delay, retryWhen, take } from "rxjs/operators";
70 import tippy from "tippy.js";
71 import Toastify from "toastify-js";
72 import { httpBase } from "./env";
73 import { i18n } from "./i18next";
75 CommentNode as CommentNodeI,
79 } from "./interfaces";
80 import { UserService, WebSocketService } from "./services";
84 Tribute = require("tributejs");
87 export const wsClient = new LemmyWebsocket();
89 export const favIconUrl = "/static/assets/icons/favicon.svg";
90 export const favIconPngUrl = "/static/assets/icons/apple-touch-icon.png";
92 // export const defaultFavIcon = `${window.location.protocol}//${window.location.host}${favIconPngUrl}`;
93 export const repoUrl = "https://github.com/LemmyNet";
94 export const joinLemmyUrl = "https://join-lemmy.org";
95 export const supportLemmyUrl = `${joinLemmyUrl}/support`;
96 export const docsUrl = `${joinLemmyUrl}/docs/en/index.html`;
97 export const helpGuideUrl = `${joinLemmyUrl}/docs/en/about/guide.html`; // TODO find a way to redirect to the non-en folder
98 export const markdownHelpUrl = `${helpGuideUrl}#markdown-guide`;
99 export const sortingHelpUrl = `${helpGuideUrl}#sorting`;
100 export const archiveUrl = "https://archive.is";
101 export const elementUrl = "https://element.io/";
103 export const postRefetchSeconds: number = 60 * 1000;
104 export const fetchLimit = 20;
105 export const mentionDropdownFetchLimit = 10;
107 export const languages = [
153 export const themes = [
169 const DEFAULT_ALPHABET =
170 "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
172 function getRandomCharFromAlphabet(alphabet: string): string {
173 return alphabet.charAt(Math.floor(Math.random() * alphabet.length));
176 export function randomStr(
177 idDesiredLength = 20,
178 alphabet = DEFAULT_ALPHABET
181 * Create n-long array and map it to random chars from given alphabet.
182 * Then join individual chars as string
184 return Array.from({ length: idDesiredLength })
186 return getRandomCharFromAlphabet(alphabet);
191 export function wsJsonToRes<ResponseType>(
192 msg: WebSocketJsonResponse<ResponseType>
193 ): WebSocketResponse<ResponseType> {
200 export function wsUserOp(msg: any): UserOperation {
201 let opStr: string = msg.op;
202 return UserOperation[opStr];
205 export const md = new markdown_it({
210 .use(markdown_it_sub)
211 .use(markdown_it_sup)
212 .use(markdown_it_html5_embed, {
214 useImageSyntax: true, // Enables video/audio embed with ![]() syntax (default)
216 audio: 'controls preload="metadata"',
218 'width="100%" max-height="100%" controls loop preload="metadata"',
222 .use(markdown_it_container, "spoiler", {
223 validate: function (params: any) {
224 return params.trim().match(/^spoiler\s+(.*)$/);
227 render: function (tokens: any, idx: any) {
228 var m = tokens[idx].info.trim().match(/^spoiler\s+(.*)$/);
230 if (tokens[idx].nesting === 1) {
232 return `<details><summary> ${md.utils.escapeHtml(m[1])} </summary>\n`;
235 return "</details>\n";
240 export function hotRankComment(comment_view: CommentView): number {
241 return hotRank(comment_view.counts.score, comment_view.comment.published);
244 export function hotRankActivePost(post_view: PostView): number {
245 return hotRank(post_view.counts.score, post_view.counts.newest_comment_time);
248 export function hotRankPost(post_view: PostView): number {
249 return hotRank(post_view.counts.score, post_view.post.published);
252 export function hotRank(score: number, timeStr: string): number {
253 // Rank = ScaleFactor * sign(Score) * log(1 + abs(Score)) / (Time + 2)^Gravity
254 let date: Date = new Date(timeStr + "Z"); // Add Z to convert from UTC date
255 let now: Date = new Date();
256 let hoursElapsed: number = (now.getTime() - date.getTime()) / 36e5;
259 (10000 * Math.log10(Math.max(1, 3 + score))) /
260 Math.pow(hoursElapsed + 2, 1.8);
262 // console.log(`Comment: ${comment.content}\nRank: ${rank}\nScore: ${comment.score}\nHours: ${hoursElapsed}`);
267 export function mdToHtml(text: string) {
268 return { __html: md.render(text) };
271 export function getUnixTime(text: string): number {
272 return text ? new Date(text).getTime() / 1000 : undefined;
275 export function canMod(
276 myUserInfo: MyUserInfo,
281 // You can do moderator actions only on the mods added after you.
283 let yourIndex = modIds.findIndex(
284 id => id == myUserInfo.local_user_view.person.id
286 if (yourIndex == -1) {
289 // onSelf +1 on mod actions not for yourself, IE ban, remove, etc
290 modIds = modIds.slice(0, yourIndex + (onSelf ? 0 : 1));
291 return !modIds.includes(creator_id);
298 export function isMod(modIds: number[], creator_id: number): boolean {
299 return modIds.includes(creator_id);
302 const imageRegex = new RegExp(
303 /(http)?s?:?(\/\/[^"']*\.(?:jpg|jpeg|gif|png|svg|webp))/
305 const videoRegex = new RegExp(`(http)?s?:?(\/\/[^"']*\.(?:mp4))`);
307 export function isImage(url: string) {
308 return imageRegex.test(url);
311 export function isVideo(url: string) {
312 return videoRegex.test(url);
315 export function validURL(str: string) {
316 return !!new URL(str);
319 export function communityRSSUrl(actorId: string, sort: string): string {
320 let url = new URL(actorId);
321 return `${url.origin}/feeds${url.pathname}.xml?sort=${sort}`;
324 export function validEmail(email: string) {
326 /^(([^\s"(),.:;<>@[\\\]]+(\.[^\s"(),.:;<>@[\\\]]+)*)|(".+"))@((\[(?:\d{1,3}\.){3}\d{1,3}])|(([\dA-Za-z\-]+\.)+[A-Za-z]{2,}))$/;
327 return re.test(String(email).toLowerCase());
330 export function capitalizeFirstLetter(str: string): string {
331 return str.charAt(0).toUpperCase() + str.slice(1);
334 export function routeSortTypeToEnum(sort: string): SortType {
335 return SortType[sort];
338 export function listingTypeFromNum(type_: number): ListingType {
339 return Object.values(ListingType)[type_];
342 export function sortTypeFromNum(type_: number): SortType {
343 return Object.values(SortType)[type_];
346 export function routeListingTypeToEnum(type: string): ListingType {
347 return ListingType[type];
350 export function routeDataTypeToEnum(type: string): DataType {
351 return DataType[capitalizeFirstLetter(type)];
354 export function routeSearchTypeToEnum(type: string): SearchType {
355 return SearchType[type];
358 export async function getSiteMetadata(url: string) {
359 let form: GetSiteMetadata = {
362 let client = new LemmyHttp(httpBase);
363 return client.getSiteMetadata(form);
366 export function debounce(func: any, wait = 1000, immediate = false) {
367 // 'private' variable for instance
368 // The returned function will be able to reference this due to closure.
369 // Each call to the returned function will share this common timer.
372 // Calling debounce returns a new anonymous function
374 // reference the context and args for the setTimeout function
375 var args = arguments;
377 // Should the function be called now? If immediate is true
378 // and not already in a timeout then the answer is: Yes
379 var callNow = immediate && !timeout;
381 // This is the basic debounce behaviour where you can call this
382 // function several times, but it will only execute once
383 // [before or after imposing a delay].
384 // Each time the returned function is called, the timer starts over.
385 clearTimeout(timeout);
387 // Set the new timeout
388 timeout = setTimeout(function () {
389 // Inside the timeout function, clear the timeout variable
390 // which will let the next execution run when in 'immediate' mode
393 // Check if the function already ran with the immediate flag
395 // Call the original function with apply
396 // apply lets you define the 'this' object as well as the arguments
397 // (both captured before setTimeout)
398 func.apply(this, args);
402 // Immediate mode and no wait timer? Execute the function..
403 if (callNow) func.apply(this, args);
408 export function getLanguage(override?: string): string {
409 let myUserInfo = UserService.Instance.myUserInfo;
412 (myUserInfo?.local_user_view.local_user.lang
413 ? myUserInfo.local_user_view.local_user.lang
416 if (lang == "browser" && isBrowser()) {
417 return getBrowserLanguage();
423 export function getBrowserLanguage(): string {
424 // Intersect lemmy's langs, with the browser langs
425 let langs = languages ? languages.map(l => l.code) : ["en"];
427 // NOTE, mobile browsers seem to be missing this list, so append en
428 let allowedLangs = navigator.languages
430 .filter(v => langs.includes(v));
431 return allowedLangs[0];
434 export function getMomentLanguage(): string {
435 let lang = getLanguage();
436 if (lang.startsWith("zh")) {
438 } else if (lang.startsWith("sv")) {
440 } else if (lang.startsWith("fr")) {
442 } else if (lang.startsWith("de")) {
444 } else if (lang.startsWith("ru")) {
446 } else if (lang.startsWith("es")) {
448 } else if (lang.startsWith("eo")) {
450 } else if (lang.startsWith("nl")) {
452 } else if (lang.startsWith("it")) {
454 } else if (lang.startsWith("fi")) {
456 } else if (lang.startsWith("ca")) {
458 } else if (lang.startsWith("fa")) {
460 } else if (lang.startsWith("pl")) {
462 } else if (lang.startsWith("pt_BR")) {
464 } else if (lang.startsWith("ja")) {
466 } else if (lang.startsWith("ka")) {
468 } else if (lang.startsWith("hi")) {
470 } else if (lang.startsWith("el")) {
472 } else if (lang.startsWith("eu")) {
474 } else if (lang.startsWith("gl")) {
476 } else if (lang.startsWith("tr")) {
478 } else if (lang.startsWith("hu")) {
480 } else if (lang.startsWith("uk")) {
482 } else if (lang.startsWith("sq")) {
484 } else if (lang.startsWith("km")) {
486 } else if (lang.startsWith("ga")) {
488 } else if (lang.startsWith("sr")) {
490 } else if (lang.startsWith("ko")) {
492 } else if (lang.startsWith("da")) {
494 } else if (lang.startsWith("oc")) {
496 } else if (lang.startsWith("hr")) {
498 } else if (lang.startsWith("th")) {
500 } else if (lang.startsWith("bg")) {
502 } else if (lang.startsWith("id")) {
504 } else if (lang.startsWith("nb")) {
506 } else if (lang.startsWith("cy")) {
508 } else if (lang.startsWith("sk")) {
510 } else if (lang.startsWith("vi")) {
512 } else if (lang.startsWith("pt")) {
514 } else if (lang.startsWith("ar")) {
522 export function setTheme(theme: string, forceReload = false) {
526 if (theme === "browser" && !forceReload) {
529 // This is only run on a force reload
530 if (theme == "browser") {
534 // Unload all the other themes
535 for (var i = 0; i < themes.length; i++) {
536 let styleSheet = document.getElementById(themes[i]);
538 styleSheet.setAttribute("disabled", "disabled");
543 .getElementById("default-light")
544 ?.setAttribute("disabled", "disabled");
545 document.getElementById("default-dark")?.setAttribute("disabled", "disabled");
547 // Load the theme dynamically
548 let cssLoc = `/static/assets/css/themes/${theme}.min.css`;
549 loadCss(theme, cssLoc);
550 document.getElementById(theme).removeAttribute("disabled");
553 export function loadCss(id: string, loc: string) {
554 if (!document.getElementById(id)) {
555 var head = document.getElementsByTagName("head")[0];
556 var link = document.createElement("link");
558 link.rel = "stylesheet";
559 link.type = "text/css";
562 head.appendChild(link);
566 export function objectFlip(obj: any) {
568 Object.keys(obj).forEach(key => {
574 export function showAvatars(): boolean {
576 UserService.Instance.myUserInfo?.local_user_view.local_user.show_avatars ||
577 !UserService.Instance.myUserInfo
581 export function showScores(): boolean {
583 UserService.Instance.myUserInfo?.local_user_view.local_user.show_scores ||
584 !UserService.Instance.myUserInfo
588 export function isCakeDay(published: string): boolean {
589 // moment(undefined) or moment.utc(undefined) returns the current date/time
590 // moment(null) or moment.utc(null) returns null
591 const createDate = moment.utc(published || null).local();
592 const currentDate = moment(new Date());
595 createDate.date() === currentDate.date() &&
596 createDate.month() === currentDate.month() &&
597 createDate.year() !== currentDate.year()
601 export function toast(text: string, background = "success") {
603 let backgroundColor = `var(--${background})`;
606 backgroundColor: backgroundColor,
613 export function pictrsDeleteToast(
614 clickToDeleteText: string,
615 deletePictureText: string,
619 let backgroundColor = `var(--light)`;
620 let toast = Toastify({
621 text: clickToDeleteText,
622 backgroundColor: backgroundColor,
628 window.location.replace(deleteUrl);
629 alert(deletePictureText);
638 interface NotifyInfo {
645 export function messageToastify(info: NotifyInfo, router: any) {
647 let htmlBody = info.body ? md.render(info.body) : "";
648 let backgroundColor = `var(--light)`;
650 let toast = Toastify({
651 text: `${htmlBody}<br />${info.name}`,
652 avatar: info.icon ? info.icon : null,
653 backgroundColor: backgroundColor,
654 className: "text-dark",
663 router.history.push(info.link);
670 export function notifyPost(post_view: PostView, router: any) {
671 let info: NotifyInfo = {
672 name: post_view.community.name,
673 icon: post_view.community.icon,
674 link: `/post/${post_view.post.id}`,
675 body: post_view.post.name,
677 notify(info, router);
680 export function notifyComment(comment_view: CommentView, router: any) {
681 let info: NotifyInfo = {
682 name: comment_view.creator.name,
683 icon: comment_view.creator.avatar,
684 link: `/post/${comment_view.post.id}/comment/${comment_view.comment.id}`,
685 body: comment_view.comment.content,
687 notify(info, router);
690 export function notifyPrivateMessage(pmv: PrivateMessageView, router: any) {
691 let info: NotifyInfo = {
692 name: pmv.creator.name,
693 icon: pmv.creator.avatar,
695 body: pmv.private_message.content,
697 notify(info, router);
700 function notify(info: NotifyInfo, router: any) {
701 messageToastify(info, router);
703 // TODO absolute nightmare bug, but notifs are currently broken.
704 // Notification.new will try to do a browser fetch ???
706 // if (Notification.permission !== "granted") Notification.requestPermission();
708 // var notification = new Notification(info.name, {
713 // notification.onclick = (ev: Event): any => {
714 // ev.preventDefault();
715 // router.history.push(info.link);
720 export function setupTribute() {
722 noMatchTemplate: function () {
729 menuItemTemplate: (item: any) => {
730 let shortName = `:${item.original.key}:`;
731 return `${item.original.val} ${shortName}`;
733 selectTemplate: (item: any) => {
734 return `${item.original.val}`;
736 values: Object.entries(emojiShortName).map(e => {
737 return { key: e[1], val: e[0] };
740 autocompleteMode: true,
742 // menuItemLimit: mentionDropdownFetchLimit,
743 menuShowMinLength: 2,
748 selectTemplate: (item: any) => {
749 let it: PersonTribute = item.original;
750 return `[${it.key}](${it.view.person.actor_id})`;
752 values: (text: string, cb: (persons: PersonTribute[]) => any) => {
753 personSearch(text, (persons: PersonTribute[]) => cb(persons));
756 autocompleteMode: true,
758 // menuItemLimit: mentionDropdownFetchLimit,
759 menuShowMinLength: 2,
765 selectTemplate: (item: any) => {
766 let it: CommunityTribute = item.original;
767 return `[${it.key}](${it.view.community.actor_id})`;
769 values: (text: string, cb: any) => {
770 communitySearch(text, (communities: CommunityTribute[]) =>
775 autocompleteMode: true,
777 // menuItemLimit: mentionDropdownFetchLimit,
778 menuShowMinLength: 2,
784 var tippyInstance: any;
786 tippyInstance = tippy("[data-tippy-content]");
789 export function setupTippy() {
791 tippyInstance.forEach((e: any) => e.destroy());
792 tippyInstance = tippy("[data-tippy-content]", {
794 // Display on "long press"
795 touch: ["hold", 500],
800 interface PersonTribute {
802 view: PersonViewSafe;
805 function personSearch(text: string, cb: (persons: PersonTribute[]) => any) {
809 type_: SearchType.Users,
810 sort: SortType.TopAll,
811 listing_type: ListingType.All,
813 limit: mentionDropdownFetchLimit,
814 auth: authField(false),
817 WebSocketService.Instance.send(wsClient.search(form));
819 let personSub = WebSocketService.Instance.subject.subscribe(
821 let res = wsJsonToRes(msg);
822 if (res.op == UserOperation.Search) {
823 let data = res.data as SearchResponse;
824 let persons: PersonTribute[] = data.users.map(pv => {
825 let tribute: PersonTribute = {
826 key: `@${pv.person.name}@${hostname(pv.person.actor_id)}`,
832 personSub.unsubscribe();
835 err => console.error(err),
836 () => console.log("complete")
843 interface CommunityTribute {
848 function communitySearch(
850 cb: (communities: CommunityTribute[]) => any
855 type_: SearchType.Communities,
856 sort: SortType.TopAll,
857 listing_type: ListingType.All,
859 limit: mentionDropdownFetchLimit,
860 auth: authField(false),
863 WebSocketService.Instance.send(wsClient.search(form));
865 let communitySub = WebSocketService.Instance.subject.subscribe(
867 let res = wsJsonToRes(msg);
868 if (res.op == UserOperation.Search) {
869 let data = res.data as SearchResponse;
870 let communities: CommunityTribute[] = data.communities.map(cv => {
871 let tribute: CommunityTribute = {
872 key: `!${cv.community.name}@${hostname(cv.community.actor_id)}`,
878 communitySub.unsubscribe();
881 err => console.error(err),
882 () => console.log("complete")
889 export function getListingTypeFromProps(props: any): ListingType {
890 return props.match.params.listing_type
891 ? routeListingTypeToEnum(props.match.params.listing_type)
892 : UserService.Instance.myUserInfo
893 ? Object.values(ListingType)[
894 UserService.Instance.myUserInfo.local_user_view.local_user
895 .default_listing_type
900 export function getListingTypeFromPropsNoDefault(props: any): ListingType {
901 return props.match.params.listing_type
902 ? routeListingTypeToEnum(props.match.params.listing_type)
906 // TODO might need to add a user setting for this too
907 export function getDataTypeFromProps(props: any): DataType {
908 return props.match.params.data_type
909 ? routeDataTypeToEnum(props.match.params.data_type)
913 export function getSortTypeFromProps(props: any): SortType {
914 return props.match.params.sort
915 ? routeSortTypeToEnum(props.match.params.sort)
916 : UserService.Instance.myUserInfo
917 ? Object.values(SortType)[
918 UserService.Instance.myUserInfo.local_user_view.local_user
924 export function getPageFromProps(props: any): number {
925 return props.match.params.page ? Number(props.match.params.page) : 1;
928 export function getRecipientIdFromProps(props: any): number {
929 return props.match.params.recipient_id
930 ? Number(props.match.params.recipient_id)
934 export function getIdFromProps(props: any): number {
935 return Number(props.match.params.id);
938 export function getCommentIdFromProps(props: any): number {
939 return Number(props.match.params.comment_id);
942 export function getUsernameFromProps(props: any): string {
943 return props.match.params.username;
946 export function editCommentRes(data: CommentView, comments: CommentView[]) {
947 let found = comments.find(c => c.comment.id == data.comment.id);
949 found.comment.content = data.comment.content;
950 found.comment.updated = data.comment.updated;
951 found.comment.removed = data.comment.removed;
952 found.comment.deleted = data.comment.deleted;
953 found.counts.upvotes = data.counts.upvotes;
954 found.counts.downvotes = data.counts.downvotes;
955 found.counts.score = data.counts.score;
959 export function saveCommentRes(data: CommentView, comments: CommentView[]) {
960 let found = comments.find(c => c.comment.id == data.comment.id);
962 found.saved = data.saved;
966 export function updatePersonBlock(
967 data: BlockPersonResponse
968 ): PersonBlockView[] {
970 UserService.Instance.myUserInfo.person_blocks.push({
971 person: UserService.Instance.myUserInfo.local_user_view.person,
972 target: data.person_view.person,
974 toast(`${i18n.t("blocked")} ${data.person_view.person.name}`);
976 UserService.Instance.myUserInfo.person_blocks =
977 UserService.Instance.myUserInfo.person_blocks.filter(
978 i => i.target.id != data.person_view.person.id
980 toast(`${i18n.t("unblocked")} ${data.person_view.person.name}`);
982 return UserService.Instance.myUserInfo.person_blocks;
985 export function updateCommunityBlock(
986 data: BlockCommunityResponse
987 ): CommunityBlockView[] {
989 UserService.Instance.myUserInfo.community_blocks.push({
990 person: UserService.Instance.myUserInfo.local_user_view.person,
991 community: data.community_view.community,
993 toast(`${i18n.t("blocked")} ${data.community_view.community.name}`);
995 UserService.Instance.myUserInfo.community_blocks =
996 UserService.Instance.myUserInfo.community_blocks.filter(
997 i => i.community.id != data.community_view.community.id
999 toast(`${i18n.t("unblocked")} ${data.community_view.community.name}`);
1001 return UserService.Instance.myUserInfo.community_blocks;
1004 export function createCommentLikeRes(
1006 comments: CommentView[]
1008 let found = comments.find(c => c.comment.id === data.comment.id);
1010 found.counts.score = data.counts.score;
1011 found.counts.upvotes = data.counts.upvotes;
1012 found.counts.downvotes = data.counts.downvotes;
1013 if (data.my_vote !== null) {
1014 found.my_vote = data.my_vote;
1019 export function createPostLikeFindRes(data: PostView, posts: PostView[]) {
1020 let found = posts.find(p => p.post.id == data.post.id);
1022 createPostLikeRes(data, found);
1026 export function createPostLikeRes(data: PostView, post_view: PostView) {
1028 post_view.counts.score = data.counts.score;
1029 post_view.counts.upvotes = data.counts.upvotes;
1030 post_view.counts.downvotes = data.counts.downvotes;
1031 if (data.my_vote !== null) {
1032 post_view.my_vote = data.my_vote;
1037 export function editPostFindRes(data: PostView, posts: PostView[]) {
1038 let found = posts.find(p => p.post.id == data.post.id);
1040 editPostRes(data, found);
1044 export function editPostRes(data: PostView, post: PostView) {
1046 post.post.url = data.post.url;
1047 post.post.name = data.post.name;
1048 post.post.nsfw = data.post.nsfw;
1049 post.post.deleted = data.post.deleted;
1050 post.post.removed = data.post.removed;
1051 post.post.stickied = data.post.stickied;
1052 post.post.body = data.post.body;
1053 post.post.locked = data.post.locked;
1054 post.saved = data.saved;
1058 export function commentsToFlatNodes(comments: CommentView[]): CommentNodeI[] {
1059 let nodes: CommentNodeI[] = [];
1060 for (let comment of comments) {
1061 nodes.push({ comment_view: comment });
1066 function commentSort(tree: CommentNodeI[], sort: CommentSortType) {
1067 // First, put removed and deleted comments at the bottom, then do your other sorts
1068 if (sort == CommentSortType.Top) {
1071 +a.comment_view.comment.removed - +b.comment_view.comment.removed ||
1072 +a.comment_view.comment.deleted - +b.comment_view.comment.deleted ||
1073 b.comment_view.counts.score - a.comment_view.counts.score
1075 } else if (sort == CommentSortType.New) {
1078 +a.comment_view.comment.removed - +b.comment_view.comment.removed ||
1079 +a.comment_view.comment.deleted - +b.comment_view.comment.deleted ||
1080 b.comment_view.comment.published.localeCompare(
1081 a.comment_view.comment.published
1084 } else if (sort == CommentSortType.Old) {
1087 +a.comment_view.comment.removed - +b.comment_view.comment.removed ||
1088 +a.comment_view.comment.deleted - +b.comment_view.comment.deleted ||
1089 a.comment_view.comment.published.localeCompare(
1090 b.comment_view.comment.published
1093 } else if (sort == CommentSortType.Hot) {
1096 +a.comment_view.comment.removed - +b.comment_view.comment.removed ||
1097 +a.comment_view.comment.deleted - +b.comment_view.comment.deleted ||
1098 hotRankComment(b.comment_view) - hotRankComment(a.comment_view)
1102 // Go through the children recursively
1103 for (let node of tree) {
1104 if (node.children) {
1105 commentSort(node.children, sort);
1110 export function commentSortSortType(tree: CommentNodeI[], sort: SortType) {
1111 commentSort(tree, convertCommentSortType(sort));
1114 function convertCommentSortType(sort: SortType): CommentSortType {
1116 sort == SortType.TopAll ||
1117 sort == SortType.TopDay ||
1118 sort == SortType.TopWeek ||
1119 sort == SortType.TopMonth ||
1120 sort == SortType.TopYear
1122 return CommentSortType.Top;
1123 } else if (sort == SortType.New) {
1124 return CommentSortType.New;
1125 } else if (sort == SortType.Hot || sort == SortType.Active) {
1126 return CommentSortType.Hot;
1128 return CommentSortType.Hot;
1132 export function buildCommentsTree(
1133 comments: CommentView[],
1134 commentSortType: CommentSortType
1136 let map = new Map<number, CommentNodeI>();
1137 for (let comment_view of comments) {
1138 let node: CommentNodeI = {
1139 comment_view: comment_view,
1142 map.set(comment_view.comment.id, { ...node });
1144 let tree: CommentNodeI[] = [];
1145 for (let comment_view of comments) {
1146 let child = map.get(comment_view.comment.id);
1147 let parent_id = comment_view.comment.parent_id;
1149 let parent = map.get(parent_id);
1150 // Necessary because blocked comment might not exist
1152 parent.children.push(child);
1161 commentSort(tree, commentSortType);
1166 function setDepth(node: CommentNodeI, i = 0) {
1167 for (let child of node.children) {
1169 setDepth(child, i + 1);
1173 export function insertCommentIntoTree(tree: CommentNodeI[], cv: CommentView) {
1174 // Building a fake node to be used for later
1175 let node: CommentNodeI = {
1181 if (cv.comment.parent_id) {
1182 let parentComment = searchCommentTree(tree, cv.comment.parent_id);
1183 if (parentComment) {
1184 node.depth = parentComment.depth + 1;
1185 parentComment.children.unshift(node);
1192 export function searchCommentTree(
1193 tree: CommentNodeI[],
1196 for (let node of tree) {
1197 if (node.comment_view.comment.id === id) {
1201 for (const child of node.children) {
1202 const res = searchCommentTree([child], id);
1212 export const colorList: string[] = [
1221 function hsl(num: number) {
1222 return `hsla(${num}, 35%, 50%, 1)`;
1225 export function previewLines(
1234 // Use lines * 2 because markdown requires 2 lines
1235 .slice(0, maxLines * 2)
1240 export function hostname(url: string): string {
1241 let cUrl = new URL(url);
1242 return cUrl.port ? `${cUrl.hostname}:${cUrl.port}` : `${cUrl.hostname}`;
1245 export function validTitle(title?: string): boolean {
1246 // Initial title is null, minimum length is taken care of by textarea's minLength={3}
1247 if (title === null || title.length < 3) return true;
1249 const regex = new RegExp(/.*\S.*/, "g");
1251 return regex.test(title);
1254 export function siteBannerCss(banner: string): string {
1256 background-image: linear-gradient( rgba(0, 0, 0, 0.8), rgba(0, 0, 0, 0.8) ) ,url("${banner}"); \
1257 background-attachment: fixed; \
1258 background-position: top; \
1259 background-repeat: no-repeat; \
1260 background-size: 100% cover; \
1263 max-height: 100vh; \
1267 export function isBrowser() {
1268 return typeof window !== "undefined";
1271 export function setIsoData(context: any): IsoData {
1272 let isoData: IsoData = isBrowser()
1274 : context.router.staticContext;
1278 export function wsSubscribe(parseMessage: any): Subscription {
1280 return WebSocketService.Instance.subject
1281 .pipe(retryWhen(errors => errors.pipe(delay(3000), take(10))))
1283 msg => parseMessage(msg),
1284 err => console.error(err),
1285 () => console.log("complete")
1292 export function setOptionalAuth(obj: any, auth = UserService.Instance.auth) {
1298 export function authField(
1300 auth = UserService.Instance.auth
1302 if (auth == null && throwErr) {
1303 toast(i18n.t("not_logged_in"), "danger");
1304 throw "Not logged in";
1310 moment.updateLocale("en", {
1331 export function saveScrollPosition(context: any) {
1332 let path: string = context.router.route.location.pathname;
1333 let y = window.scrollY;
1334 sessionStorage.setItem(`scrollPosition_${path}`, y.toString());
1337 export function restoreScrollPosition(context: any) {
1338 let path: string = context.router.route.location.pathname;
1339 let y = Number(sessionStorage.getItem(`scrollPosition_${path}`));
1340 window.scrollTo(0, y);
1343 export function showLocal(isoData: IsoData): boolean {
1344 return isoData.site_res.federated_instances?.linked.length > 0;
1347 interface ChoicesValue {
1352 export function communityToChoice(cv: CommunityView): ChoicesValue {
1353 let choice: ChoicesValue = {
1354 value: cv.community.id.toString(),
1355 label: communitySelectName(cv),
1360 export function personToChoice(pvs: PersonViewSafe): ChoicesValue {
1361 let choice: ChoicesValue = {
1362 value: pvs.person.id.toString(),
1363 label: personSelectName(pvs),
1368 export async function fetchCommunities(q: string) {
1369 let form: Search = {
1371 type_: SearchType.Communities,
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 async function fetchUsers(q: string) {
1383 let form: Search = {
1385 type_: SearchType.Users,
1386 sort: SortType.TopAll,
1387 listing_type: ListingType.All,
1390 auth: authField(false),
1392 let client = new LemmyHttp(httpBase);
1393 return client.search(form);
1396 export const choicesConfig = {
1398 searchResultLimit: fetchLimit,
1400 containerOuter: "choices",
1401 containerInner: "choices__inner bg-secondary border-0",
1402 input: "form-control",
1403 inputCloned: "choices__input--cloned",
1404 list: "choices__list",
1405 listItems: "choices__list--multiple",
1406 listSingle: "choices__list--single",
1407 listDropdown: "choices__list--dropdown",
1408 item: "choices__item bg-secondary",
1409 itemSelectable: "choices__item--selectable",
1410 itemDisabled: "choices__item--disabled",
1411 itemChoice: "choices__item--choice",
1412 placeholder: "choices__placeholder",
1413 group: "choices__group",
1414 groupHeading: "choices__heading",
1415 button: "choices__button",
1416 activeState: "is-active",
1417 focusState: "is-focused",
1418 openState: "is-open",
1419 disabledState: "is-disabled",
1420 highlightedState: "text-info",
1421 selectedState: "text-info",
1422 flippedState: "is-flipped",
1423 loadingState: "is-loading",
1424 noResults: "has-no-results",
1425 noChoices: "has-no-choices",
1429 export function communitySelectName(cv: CommunityView): string {
1430 return cv.community.local
1432 : `${hostname(cv.community.actor_id)}/${cv.community.name}`;
1435 export function personSelectName(pvs: PersonViewSafe): string {
1436 return pvs.person.local
1438 : `${hostname(pvs.person.actor_id)}/${pvs.person.name}`;
1441 export function initializeSite(site: GetSiteResponse) {
1442 UserService.Instance.myUserInfo = site.my_user;
1443 i18n.changeLanguage(getLanguage());
1446 const SHORTNUM_SI_FORMAT = new Intl.NumberFormat("en-US", {
1447 maximumSignificantDigits: 3,
1449 notation: "compact",
1450 compactDisplay: "short",
1453 export function numToSI(value: number): string {
1454 return SHORTNUM_SI_FORMAT.format(value);