1 import emojiShortName from "emoji-short-name";
3 BlockCommunityResponse,
25 WebSocketJsonResponse,
27 } from "lemmy-js-client";
28 import markdown_it from "markdown-it";
29 import markdown_it_container from "markdown-it-container";
30 import markdown_it_html5_embed from "markdown-it-html5-embed";
31 import markdown_it_sub from "markdown-it-sub";
32 import markdown_it_sup from "markdown-it-sup";
33 import moment from "moment";
34 import "moment/locale/bg";
35 import "moment/locale/ca";
36 import "moment/locale/cy";
37 import "moment/locale/da";
38 import "moment/locale/de";
39 import "moment/locale/el";
40 import "moment/locale/eo";
41 import "moment/locale/es";
42 import "moment/locale/eu";
43 import "moment/locale/fa";
44 import "moment/locale/fi";
45 import "moment/locale/fr";
46 import "moment/locale/ga";
47 import "moment/locale/gl";
48 import "moment/locale/hi";
49 import "moment/locale/hr";
50 import "moment/locale/hu";
51 import "moment/locale/id";
52 import "moment/locale/it";
53 import "moment/locale/ja";
54 import "moment/locale/ka";
55 import "moment/locale/km";
56 import "moment/locale/ko";
57 import "moment/locale/nb";
58 import "moment/locale/nl";
59 import "moment/locale/pl";
60 import "moment/locale/pt-br";
61 import "moment/locale/ru";
62 import "moment/locale/sk";
63 import "moment/locale/sq";
64 import "moment/locale/sr";
65 import "moment/locale/sv";
66 import "moment/locale/tr";
67 import "moment/locale/uk";
68 import "moment/locale/vi";
69 import "moment/locale/zh-cn";
70 import { Subscription } from "rxjs";
71 import { delay, retryWhen, take } from "rxjs/operators";
72 import tippy from "tippy.js";
73 import Toastify from "toastify-js";
74 import { httpBase } from "./env";
75 import { i18n } from "./i18next";
77 CommentNode as CommentNodeI,
81 } from "./interfaces";
82 import { UserService, WebSocketService } from "./services";
86 Tribute = require("tributejs");
89 export const wsClient = new LemmyWebsocket();
91 export const favIconUrl = "/static/assets/icons/favicon.svg";
92 export const favIconPngUrl = "/static/assets/icons/apple-touch-icon.png";
94 // export const defaultFavIcon = `${window.location.protocol}//${window.location.host}${favIconPngUrl}`;
95 export const repoUrl = "https://github.com/LemmyNet";
96 export const joinLemmyUrl = "https://join-lemmy.org";
97 export const donateLemmyUrl = `${joinLemmyUrl}/donate`;
98 export const docsUrl = `${joinLemmyUrl}/docs/en/index.html`;
99 export const helpGuideUrl = `${joinLemmyUrl}/docs/en/about/guide.html`; // TODO find a way to redirect to the non-en folder
100 export const markdownHelpUrl = `${helpGuideUrl}#markdown-guide`;
101 export const sortingHelpUrl = `${helpGuideUrl}#sorting`;
102 export const archiveUrl = "https://archive.is";
103 export const elementUrl = "https://element.io";
105 export const postRefetchSeconds: number = 60 * 1000;
106 export const fetchLimit = 20;
107 export const mentionDropdownFetchLimit = 10;
109 export const languages = [
155 export const themes = [
171 const DEFAULT_ALPHABET =
172 "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
174 function getRandomCharFromAlphabet(alphabet: string): string {
175 return alphabet.charAt(Math.floor(Math.random() * alphabet.length));
178 export function randomStr(
179 idDesiredLength = 20,
180 alphabet = DEFAULT_ALPHABET
183 * Create n-long array and map it to random chars from given alphabet.
184 * Then join individual chars as string
186 return Array.from({ length: idDesiredLength })
188 return getRandomCharFromAlphabet(alphabet);
193 export function wsJsonToRes<ResponseType>(
194 msg: WebSocketJsonResponse<ResponseType>
195 ): WebSocketResponse<ResponseType> {
202 export function wsUserOp(msg: any): UserOperation {
203 let opStr: string = msg.op;
204 return UserOperation[opStr];
207 export const md = new markdown_it({
212 .use(markdown_it_sub)
213 .use(markdown_it_sup)
214 .use(markdown_it_html5_embed, {
216 useImageSyntax: true, // Enables video/audio embed with ![]() syntax (default)
218 audio: 'controls preload="metadata"',
220 'width="100%" max-height="100%" controls loop preload="metadata"',
224 .use(markdown_it_container, "spoiler", {
225 validate: function (params: any) {
226 return params.trim().match(/^spoiler\s+(.*)$/);
229 render: function (tokens: any, idx: any) {
230 var m = tokens[idx].info.trim().match(/^spoiler\s+(.*)$/);
232 if (tokens[idx].nesting === 1) {
234 return `<details><summary> ${md.utils.escapeHtml(m[1])} </summary>\n`;
237 return "</details>\n";
242 export function hotRankComment(comment_view: CommentView): number {
243 return hotRank(comment_view.counts.score, comment_view.comment.published);
246 export function hotRankActivePost(post_view: PostView): number {
247 return hotRank(post_view.counts.score, post_view.counts.newest_comment_time);
250 export function hotRankPost(post_view: PostView): number {
251 return hotRank(post_view.counts.score, post_view.post.published);
254 export function hotRank(score: number, timeStr: string): number {
255 // Rank = ScaleFactor * sign(Score) * log(1 + abs(Score)) / (Time + 2)^Gravity
256 let date: Date = new Date(timeStr + "Z"); // Add Z to convert from UTC date
257 let now: Date = new Date();
258 let hoursElapsed: number = (now.getTime() - date.getTime()) / 36e5;
261 (10000 * Math.log10(Math.max(1, 3 + score))) /
262 Math.pow(hoursElapsed + 2, 1.8);
264 // console.log(`Comment: ${comment.content}\nRank: ${rank}\nScore: ${comment.score}\nHours: ${hoursElapsed}`);
269 export function mdToHtml(text: string) {
270 return { __html: md.render(text) };
273 export function getUnixTime(text: string): number {
274 return text ? new Date(text).getTime() / 1000 : undefined;
277 export function canMod(
278 myUserInfo: MyUserInfo,
283 // You can do moderator actions only on the mods added after you.
285 let yourIndex = modIds.findIndex(
286 id => id == myUserInfo.local_user_view.person.id
288 if (yourIndex == -1) {
291 // onSelf +1 on mod actions not for yourself, IE ban, remove, etc
292 modIds = modIds.slice(0, yourIndex + (onSelf ? 0 : 1));
293 return !modIds.includes(creator_id);
300 export function isMod(modIds: number[], creator_id: number): boolean {
301 return modIds.includes(creator_id);
304 const imageRegex = new RegExp(
305 /(http)?s?:?(\/\/[^"']*\.(?:jpg|jpeg|gif|png|svg|webp))/
307 const videoRegex = new RegExp(`(http)?s?:?(\/\/[^"']*\.(?:mp4))`);
309 export function isImage(url: string) {
310 return imageRegex.test(url);
313 export function isVideo(url: string) {
314 return videoRegex.test(url);
317 export function validURL(str: string) {
318 return !!new URL(str);
321 export function communityRSSUrl(actorId: string, sort: string): string {
322 let url = new URL(actorId);
323 return `${url.origin}/feeds${url.pathname}.xml?sort=${sort}`;
326 export function validEmail(email: string) {
328 /^(([^\s"(),.:;<>@[\\\]]+(\.[^\s"(),.:;<>@[\\\]]+)*)|(".+"))@((\[(?:\d{1,3}\.){3}\d{1,3}])|(([\dA-Za-z\-]+\.)+[A-Za-z]{2,}))$/;
329 return re.test(String(email).toLowerCase());
332 export function capitalizeFirstLetter(str: string): string {
333 return str.charAt(0).toUpperCase() + str.slice(1);
336 export function routeSortTypeToEnum(sort: string): SortType {
337 return SortType[sort];
340 export function listingTypeFromNum(type_: number): ListingType {
341 return Object.values(ListingType)[type_];
344 export function sortTypeFromNum(type_: number): SortType {
345 return Object.values(SortType)[type_];
348 export function routeListingTypeToEnum(type: string): ListingType {
349 return ListingType[type];
352 export function routeDataTypeToEnum(type: string): DataType {
353 return DataType[capitalizeFirstLetter(type)];
356 export function routeSearchTypeToEnum(type: string): SearchType {
357 return SearchType[type];
360 export async function getSiteMetadata(url: string) {
361 let form: GetSiteMetadata = {
364 let client = new LemmyHttp(httpBase);
365 return client.getSiteMetadata(form);
368 export function debounce(func: any, wait = 1000, immediate = false) {
369 // 'private' variable for instance
370 // The returned function will be able to reference this due to closure.
371 // Each call to the returned function will share this common timer.
374 // Calling debounce returns a new anonymous function
376 // reference the context and args for the setTimeout function
377 var args = arguments;
379 // Should the function be called now? If immediate is true
380 // and not already in a timeout then the answer is: Yes
381 var callNow = immediate && !timeout;
383 // This is the basic debounce behaviour where you can call this
384 // function several times, but it will only execute once
385 // [before or after imposing a delay].
386 // Each time the returned function is called, the timer starts over.
387 clearTimeout(timeout);
389 // Set the new timeout
390 timeout = setTimeout(function () {
391 // Inside the timeout function, clear the timeout variable
392 // which will let the next execution run when in 'immediate' mode
395 // Check if the function already ran with the immediate flag
397 // Call the original function with apply
398 // apply lets you define the 'this' object as well as the arguments
399 // (both captured before setTimeout)
400 func.apply(this, args);
404 // Immediate mode and no wait timer? Execute the function..
405 if (callNow) func.apply(this, args);
410 export function getLanguage(override?: string): string {
411 let myUserInfo = UserService.Instance.myUserInfo;
414 (myUserInfo?.local_user_view.local_user.lang
415 ? myUserInfo.local_user_view.local_user.lang
418 if (lang == "browser" && isBrowser()) {
419 return getBrowserLanguage();
425 export function getBrowserLanguage(): string {
426 // Intersect lemmy's langs, with the browser langs
427 let langs = languages ? languages.map(l => l.code) : ["en"];
429 // NOTE, mobile browsers seem to be missing this list, so append en
430 let allowedLangs = navigator.languages
432 .filter(v => langs.includes(v));
433 return allowedLangs[0];
436 export function getMomentLanguage(): string {
437 let lang = getLanguage();
438 if (lang.startsWith("zh")) {
440 } else if (lang.startsWith("sv")) {
442 } else if (lang.startsWith("fr")) {
444 } else if (lang.startsWith("de")) {
446 } else if (lang.startsWith("ru")) {
448 } else if (lang.startsWith("es")) {
450 } else if (lang.startsWith("eo")) {
452 } else if (lang.startsWith("nl")) {
454 } else if (lang.startsWith("it")) {
456 } else if (lang.startsWith("fi")) {
458 } else if (lang.startsWith("ca")) {
460 } else if (lang.startsWith("fa")) {
462 } else if (lang.startsWith("pl")) {
464 } else if (lang.startsWith("pt_BR")) {
466 } else if (lang.startsWith("ja")) {
468 } else if (lang.startsWith("ka")) {
470 } else if (lang.startsWith("hi")) {
472 } else if (lang.startsWith("el")) {
474 } else if (lang.startsWith("eu")) {
476 } else if (lang.startsWith("gl")) {
478 } else if (lang.startsWith("tr")) {
480 } else if (lang.startsWith("hu")) {
482 } else if (lang.startsWith("uk")) {
484 } else if (lang.startsWith("sq")) {
486 } else if (lang.startsWith("km")) {
488 } else if (lang.startsWith("ga")) {
490 } else if (lang.startsWith("sr")) {
492 } else if (lang.startsWith("ko")) {
494 } else if (lang.startsWith("da")) {
496 } else if (lang.startsWith("oc")) {
498 } else if (lang.startsWith("hr")) {
500 } else if (lang.startsWith("th")) {
502 } else if (lang.startsWith("bg")) {
504 } else if (lang.startsWith("id")) {
506 } else if (lang.startsWith("nb")) {
508 } else if (lang.startsWith("cy")) {
510 } else if (lang.startsWith("sk")) {
512 } else if (lang.startsWith("vi")) {
514 } else if (lang.startsWith("pt")) {
516 } else if (lang.startsWith("ar")) {
524 export function setTheme(theme: string, forceReload = false) {
528 if (theme === "browser" && !forceReload) {
531 // This is only run on a force reload
532 if (theme == "browser") {
536 // Unload all the other themes
537 for (var i = 0; i < themes.length; i++) {
538 let styleSheet = document.getElementById(themes[i]);
540 styleSheet.setAttribute("disabled", "disabled");
545 .getElementById("default-light")
546 ?.setAttribute("disabled", "disabled");
547 document.getElementById("default-dark")?.setAttribute("disabled", "disabled");
549 // Load the theme dynamically
550 let cssLoc = `/static/assets/css/themes/${theme}.min.css`;
551 loadCss(theme, cssLoc);
552 document.getElementById(theme).removeAttribute("disabled");
555 export function loadCss(id: string, loc: string) {
556 if (!document.getElementById(id)) {
557 var head = document.getElementsByTagName("head")[0];
558 var link = document.createElement("link");
560 link.rel = "stylesheet";
561 link.type = "text/css";
564 head.appendChild(link);
568 export function objectFlip(obj: any) {
570 Object.keys(obj).forEach(key => {
576 export function showAvatars(): boolean {
578 UserService.Instance.myUserInfo?.local_user_view.local_user.show_avatars ||
579 !UserService.Instance.myUserInfo
583 export function showScores(): boolean {
585 UserService.Instance.myUserInfo?.local_user_view.local_user.show_scores ||
586 !UserService.Instance.myUserInfo
590 export function isCakeDay(published: string): boolean {
591 // moment(undefined) or moment.utc(undefined) returns the current date/time
592 // moment(null) or moment.utc(null) returns null
593 const createDate = moment.utc(published || null).local();
594 const currentDate = moment(new Date());
597 createDate.date() === currentDate.date() &&
598 createDate.month() === currentDate.month() &&
599 createDate.year() !== currentDate.year()
603 export function toast(text: string, background = "success") {
605 let backgroundColor = `var(--${background})`;
608 backgroundColor: backgroundColor,
615 export function pictrsDeleteToast(
616 clickToDeleteText: string,
617 deletePictureText: string,
621 let backgroundColor = `var(--light)`;
622 let toast = Toastify({
623 text: clickToDeleteText,
624 backgroundColor: backgroundColor,
630 window.location.replace(deleteUrl);
631 alert(deletePictureText);
640 interface NotifyInfo {
647 export function messageToastify(info: NotifyInfo, router: any) {
649 let htmlBody = info.body ? md.render(info.body) : "";
650 let backgroundColor = `var(--light)`;
652 let toast = Toastify({
653 text: `${htmlBody}<br />${info.name}`,
654 avatar: info.icon ? info.icon : null,
655 backgroundColor: backgroundColor,
656 className: "text-dark",
665 router.history.push(info.link);
672 export function notifyPost(post_view: PostView, router: any) {
673 let info: NotifyInfo = {
674 name: post_view.community.name,
675 icon: post_view.community.icon,
676 link: `/post/${post_view.post.id}`,
677 body: post_view.post.name,
679 notify(info, router);
682 export function notifyComment(comment_view: CommentView, router: any) {
683 let info: NotifyInfo = {
684 name: comment_view.creator.name,
685 icon: comment_view.creator.avatar,
686 link: `/post/${comment_view.post.id}/comment/${comment_view.comment.id}`,
687 body: comment_view.comment.content,
689 notify(info, router);
692 export function notifyPrivateMessage(pmv: PrivateMessageView, router: any) {
693 let info: NotifyInfo = {
694 name: pmv.creator.name,
695 icon: pmv.creator.avatar,
697 body: pmv.private_message.content,
699 notify(info, router);
702 function notify(info: NotifyInfo, router: any) {
703 messageToastify(info, router);
705 // TODO absolute nightmare bug, but notifs are currently broken.
706 // Notification.new will try to do a browser fetch ???
708 // if (Notification.permission !== "granted") Notification.requestPermission();
710 // var notification = new Notification(info.name, {
715 // notification.onclick = (ev: Event): any => {
716 // ev.preventDefault();
717 // router.history.push(info.link);
722 export function setupTribute() {
724 noMatchTemplate: function () {
731 menuItemTemplate: (item: any) => {
732 let shortName = `:${item.original.key}:`;
733 return `${item.original.val} ${shortName}`;
735 selectTemplate: (item: any) => {
736 return `${item.original.val}`;
738 values: Object.entries(emojiShortName).map(e => {
739 return { key: e[1], val: e[0] };
742 autocompleteMode: true,
744 // menuItemLimit: mentionDropdownFetchLimit,
745 menuShowMinLength: 2,
750 selectTemplate: (item: any) => {
751 let it: PersonTribute = item.original;
752 return `[${it.key}](${it.view.person.actor_id})`;
754 values: (text: string, cb: (persons: PersonTribute[]) => any) => {
755 personSearch(text, (persons: PersonTribute[]) => cb(persons));
758 autocompleteMode: true,
760 // menuItemLimit: mentionDropdownFetchLimit,
761 menuShowMinLength: 2,
767 selectTemplate: (item: any) => {
768 let it: CommunityTribute = item.original;
769 return `[${it.key}](${it.view.community.actor_id})`;
771 values: (text: string, cb: any) => {
772 communitySearch(text, (communities: CommunityTribute[]) =>
777 autocompleteMode: true,
779 // menuItemLimit: mentionDropdownFetchLimit,
780 menuShowMinLength: 2,
786 var tippyInstance: any;
788 tippyInstance = tippy("[data-tippy-content]");
791 export function setupTippy() {
793 tippyInstance.forEach((e: any) => e.destroy());
794 tippyInstance = tippy("[data-tippy-content]", {
796 // Display on "long press"
797 touch: ["hold", 500],
802 interface PersonTribute {
804 view: PersonViewSafe;
807 function personSearch(text: string, cb: (persons: PersonTribute[]) => any) {
811 type_: SearchType.Users,
812 sort: SortType.TopAll,
813 listing_type: ListingType.All,
815 limit: mentionDropdownFetchLimit,
816 auth: authField(false),
819 WebSocketService.Instance.send(wsClient.search(form));
821 let personSub = WebSocketService.Instance.subject.subscribe(
823 let res = wsJsonToRes(msg);
824 if (res.op == UserOperation.Search) {
825 let data = res.data as SearchResponse;
826 let persons: PersonTribute[] = data.users.map(pv => {
827 let tribute: PersonTribute = {
828 key: `@${pv.person.name}@${hostname(pv.person.actor_id)}`,
834 personSub.unsubscribe();
837 err => console.error(err),
838 () => console.log("complete")
845 interface CommunityTribute {
850 function communitySearch(
852 cb: (communities: CommunityTribute[]) => any
857 type_: SearchType.Communities,
858 sort: SortType.TopAll,
859 listing_type: ListingType.All,
861 limit: mentionDropdownFetchLimit,
862 auth: authField(false),
865 WebSocketService.Instance.send(wsClient.search(form));
867 let communitySub = WebSocketService.Instance.subject.subscribe(
869 let res = wsJsonToRes(msg);
870 if (res.op == UserOperation.Search) {
871 let data = res.data as SearchResponse;
872 let communities: CommunityTribute[] = data.communities.map(cv => {
873 let tribute: CommunityTribute = {
874 key: `!${cv.community.name}@${hostname(cv.community.actor_id)}`,
880 communitySub.unsubscribe();
883 err => console.error(err),
884 () => console.log("complete")
891 export function getListingTypeFromProps(props: any): ListingType {
892 return props.match.params.listing_type
893 ? routeListingTypeToEnum(props.match.params.listing_type)
894 : UserService.Instance.myUserInfo
895 ? Object.values(ListingType)[
896 UserService.Instance.myUserInfo.local_user_view.local_user
897 .default_listing_type
902 export function getListingTypeFromPropsNoDefault(props: any): ListingType {
903 return props.match.params.listing_type
904 ? routeListingTypeToEnum(props.match.params.listing_type)
908 // TODO might need to add a user setting for this too
909 export function getDataTypeFromProps(props: any): DataType {
910 return props.match.params.data_type
911 ? routeDataTypeToEnum(props.match.params.data_type)
915 export function getSortTypeFromProps(props: any): SortType {
916 return props.match.params.sort
917 ? routeSortTypeToEnum(props.match.params.sort)
918 : UserService.Instance.myUserInfo
919 ? Object.values(SortType)[
920 UserService.Instance.myUserInfo.local_user_view.local_user
926 export function getPageFromProps(props: any): number {
927 return props.match.params.page ? Number(props.match.params.page) : 1;
930 export function getRecipientIdFromProps(props: any): number {
931 return props.match.params.recipient_id
932 ? Number(props.match.params.recipient_id)
936 export function getIdFromProps(props: any): number {
937 return Number(props.match.params.id);
940 export function getCommentIdFromProps(props: any): number {
941 return Number(props.match.params.comment_id);
944 export function getUsernameFromProps(props: any): string {
945 return props.match.params.username;
948 export function editCommentRes(data: CommentView, comments: CommentView[]) {
949 let found = comments.find(c => c.comment.id == data.comment.id);
951 found.comment.content = data.comment.content;
952 found.comment.updated = data.comment.updated;
953 found.comment.removed = data.comment.removed;
954 found.comment.deleted = data.comment.deleted;
955 found.counts.upvotes = data.counts.upvotes;
956 found.counts.downvotes = data.counts.downvotes;
957 found.counts.score = data.counts.score;
961 export function saveCommentRes(data: CommentView, comments: CommentView[]) {
962 let found = comments.find(c => c.comment.id == data.comment.id);
964 found.saved = data.saved;
968 export function updatePersonBlock(
969 data: BlockPersonResponse
970 ): PersonBlockView[] {
972 UserService.Instance.myUserInfo.person_blocks.push({
973 person: UserService.Instance.myUserInfo.local_user_view.person,
974 target: data.person_view.person,
976 toast(`${i18n.t("blocked")} ${data.person_view.person.name}`);
978 UserService.Instance.myUserInfo.person_blocks =
979 UserService.Instance.myUserInfo.person_blocks.filter(
980 i => i.target.id != data.person_view.person.id
982 toast(`${i18n.t("unblocked")} ${data.person_view.person.name}`);
984 return UserService.Instance.myUserInfo.person_blocks;
987 export function updateCommunityBlock(
988 data: BlockCommunityResponse
989 ): CommunityBlockView[] {
991 UserService.Instance.myUserInfo.community_blocks.push({
992 person: UserService.Instance.myUserInfo.local_user_view.person,
993 community: data.community_view.community,
995 toast(`${i18n.t("blocked")} ${data.community_view.community.name}`);
997 UserService.Instance.myUserInfo.community_blocks =
998 UserService.Instance.myUserInfo.community_blocks.filter(
999 i => i.community.id != data.community_view.community.id
1001 toast(`${i18n.t("unblocked")} ${data.community_view.community.name}`);
1003 return UserService.Instance.myUserInfo.community_blocks;
1006 export function createCommentLikeRes(
1008 comments: CommentView[]
1010 let found = comments.find(c => c.comment.id === data.comment.id);
1012 found.counts.score = data.counts.score;
1013 found.counts.upvotes = data.counts.upvotes;
1014 found.counts.downvotes = data.counts.downvotes;
1015 if (data.my_vote !== null) {
1016 found.my_vote = data.my_vote;
1021 export function createPostLikeFindRes(data: PostView, posts: PostView[]) {
1022 let found = posts.find(p => p.post.id == data.post.id);
1024 createPostLikeRes(data, found);
1028 export function createPostLikeRes(data: PostView, post_view: PostView) {
1030 post_view.counts.score = data.counts.score;
1031 post_view.counts.upvotes = data.counts.upvotes;
1032 post_view.counts.downvotes = data.counts.downvotes;
1033 if (data.my_vote !== null) {
1034 post_view.my_vote = data.my_vote;
1039 export function editPostFindRes(data: PostView, posts: PostView[]) {
1040 let found = posts.find(p => p.post.id == data.post.id);
1042 editPostRes(data, found);
1046 export function editPostRes(data: PostView, post: PostView) {
1048 post.post.url = data.post.url;
1049 post.post.name = data.post.name;
1050 post.post.nsfw = data.post.nsfw;
1051 post.post.deleted = data.post.deleted;
1052 post.post.removed = data.post.removed;
1053 post.post.stickied = data.post.stickied;
1054 post.post.body = data.post.body;
1055 post.post.locked = data.post.locked;
1056 post.saved = data.saved;
1060 export function updatePostReportRes(
1061 data: PostReportView,
1062 reports: PostReportView[]
1064 let found = reports.find(p => p.post.id == data.post.id);
1066 found.post_report = data.post_report;
1070 export function updateCommentReportRes(
1071 data: CommentReportView,
1072 reports: CommentReportView[]
1074 let found = reports.find(c => c.comment.id == data.comment.id);
1076 found.comment_report = data.comment_report;
1080 export function commentsToFlatNodes(comments: CommentView[]): CommentNodeI[] {
1081 let nodes: CommentNodeI[] = [];
1082 for (let comment of comments) {
1083 nodes.push({ comment_view: comment });
1088 function commentSort(tree: CommentNodeI[], sort: CommentSortType) {
1089 // First, put removed and deleted comments at the bottom, then do your other sorts
1090 if (sort == CommentSortType.Top) {
1093 +a.comment_view.comment.removed - +b.comment_view.comment.removed ||
1094 +a.comment_view.comment.deleted - +b.comment_view.comment.deleted ||
1095 b.comment_view.counts.score - a.comment_view.counts.score
1097 } else if (sort == CommentSortType.New) {
1100 +a.comment_view.comment.removed - +b.comment_view.comment.removed ||
1101 +a.comment_view.comment.deleted - +b.comment_view.comment.deleted ||
1102 b.comment_view.comment.published.localeCompare(
1103 a.comment_view.comment.published
1106 } else if (sort == CommentSortType.Old) {
1109 +a.comment_view.comment.removed - +b.comment_view.comment.removed ||
1110 +a.comment_view.comment.deleted - +b.comment_view.comment.deleted ||
1111 a.comment_view.comment.published.localeCompare(
1112 b.comment_view.comment.published
1115 } else if (sort == CommentSortType.Hot) {
1118 +a.comment_view.comment.removed - +b.comment_view.comment.removed ||
1119 +a.comment_view.comment.deleted - +b.comment_view.comment.deleted ||
1120 hotRankComment(b.comment_view) - hotRankComment(a.comment_view)
1124 // Go through the children recursively
1125 for (let node of tree) {
1126 if (node.children) {
1127 commentSort(node.children, sort);
1132 export function commentSortSortType(tree: CommentNodeI[], sort: SortType) {
1133 commentSort(tree, convertCommentSortType(sort));
1136 function convertCommentSortType(sort: SortType): CommentSortType {
1138 sort == SortType.TopAll ||
1139 sort == SortType.TopDay ||
1140 sort == SortType.TopWeek ||
1141 sort == SortType.TopMonth ||
1142 sort == SortType.TopYear
1144 return CommentSortType.Top;
1145 } else if (sort == SortType.New) {
1146 return CommentSortType.New;
1147 } else if (sort == SortType.Hot || sort == SortType.Active) {
1148 return CommentSortType.Hot;
1150 return CommentSortType.Hot;
1154 export function buildCommentsTree(
1155 comments: CommentView[],
1156 commentSortType: CommentSortType
1158 let map = new Map<number, CommentNodeI>();
1159 for (let comment_view of comments) {
1160 let node: CommentNodeI = {
1161 comment_view: comment_view,
1164 map.set(comment_view.comment.id, { ...node });
1166 let tree: CommentNodeI[] = [];
1167 for (let comment_view of comments) {
1168 let child = map.get(comment_view.comment.id);
1169 let parent_id = comment_view.comment.parent_id;
1171 let parent = map.get(parent_id);
1172 // Necessary because blocked comment might not exist
1174 parent.children.push(child);
1183 commentSort(tree, commentSortType);
1188 function setDepth(node: CommentNodeI, i = 0) {
1189 for (let child of node.children) {
1191 setDepth(child, i + 1);
1195 export function insertCommentIntoTree(tree: CommentNodeI[], cv: CommentView) {
1196 // Building a fake node to be used for later
1197 let node: CommentNodeI = {
1203 if (cv.comment.parent_id) {
1204 let parentComment = searchCommentTree(tree, cv.comment.parent_id);
1205 if (parentComment) {
1206 node.depth = parentComment.depth + 1;
1207 parentComment.children.unshift(node);
1214 export function searchCommentTree(
1215 tree: CommentNodeI[],
1218 for (let node of tree) {
1219 if (node.comment_view.comment.id === id) {
1223 for (const child of node.children) {
1224 const res = searchCommentTree([child], id);
1234 export const colorList: string[] = [
1243 function hsl(num: number) {
1244 return `hsla(${num}, 35%, 50%, 1)`;
1247 export function previewLines(
1256 // Use lines * 2 because markdown requires 2 lines
1257 .slice(0, maxLines * 2)
1262 export function hostname(url: string): string {
1263 let cUrl = new URL(url);
1264 return cUrl.port ? `${cUrl.hostname}:${cUrl.port}` : `${cUrl.hostname}`;
1267 export function validTitle(title?: string): boolean {
1268 // Initial title is null, minimum length is taken care of by textarea's minLength={3}
1269 if (title === null || title.length < 3) return true;
1271 const regex = new RegExp(/.*\S.*/, "g");
1273 return regex.test(title);
1276 export function siteBannerCss(banner: string): string {
1278 background-image: linear-gradient( rgba(0, 0, 0, 0.8), rgba(0, 0, 0, 0.8) ) ,url("${banner}"); \
1279 background-attachment: fixed; \
1280 background-position: top; \
1281 background-repeat: no-repeat; \
1282 background-size: 100% cover; \
1285 max-height: 100vh; \
1289 export function isBrowser() {
1290 return typeof window !== "undefined";
1293 export function setIsoData(context: any): IsoData {
1294 let isoData: IsoData = isBrowser()
1296 : context.router.staticContext;
1300 export function wsSubscribe(parseMessage: any): Subscription {
1302 return WebSocketService.Instance.subject
1303 .pipe(retryWhen(errors => errors.pipe(delay(3000), take(10))))
1305 msg => parseMessage(msg),
1306 err => console.error(err),
1307 () => console.log("complete")
1314 export function setOptionalAuth(obj: any, auth = UserService.Instance.auth) {
1320 export function authField(
1322 auth = UserService.Instance.auth
1324 if (auth == null && throwErr) {
1325 toast(i18n.t("not_logged_in"), "danger");
1326 throw "Not logged in";
1332 moment.updateLocale("en", {
1353 export function saveScrollPosition(context: any) {
1354 let path: string = context.router.route.location.pathname;
1355 let y = window.scrollY;
1356 sessionStorage.setItem(`scrollPosition_${path}`, y.toString());
1359 export function restoreScrollPosition(context: any) {
1360 let path: string = context.router.route.location.pathname;
1361 let y = Number(sessionStorage.getItem(`scrollPosition_${path}`));
1362 window.scrollTo(0, y);
1365 export function showLocal(isoData: IsoData): boolean {
1366 return isoData.site_res.federated_instances?.linked.length > 0;
1369 interface ChoicesValue {
1374 export function communityToChoice(cv: CommunityView): ChoicesValue {
1375 let choice: ChoicesValue = {
1376 value: cv.community.id.toString(),
1377 label: communitySelectName(cv),
1382 export function personToChoice(pvs: PersonViewSafe): ChoicesValue {
1383 let choice: ChoicesValue = {
1384 value: pvs.person.id.toString(),
1385 label: personSelectName(pvs),
1390 export async function fetchCommunities(q: string) {
1391 let form: Search = {
1393 type_: SearchType.Communities,
1394 sort: SortType.TopAll,
1395 listing_type: ListingType.All,
1398 auth: authField(false),
1400 let client = new LemmyHttp(httpBase);
1401 return client.search(form);
1404 export async function fetchUsers(q: string) {
1405 let form: Search = {
1407 type_: SearchType.Users,
1408 sort: SortType.TopAll,
1409 listing_type: ListingType.All,
1412 auth: authField(false),
1414 let client = new LemmyHttp(httpBase);
1415 return client.search(form);
1418 export const choicesConfig = {
1420 searchResultLimit: fetchLimit,
1422 containerOuter: "choices",
1423 containerInner: "choices__inner bg-secondary border-0",
1424 input: "form-control",
1425 inputCloned: "choices__input--cloned",
1426 list: "choices__list",
1427 listItems: "choices__list--multiple",
1428 listSingle: "choices__list--single",
1429 listDropdown: "choices__list--dropdown",
1430 item: "choices__item bg-secondary",
1431 itemSelectable: "choices__item--selectable",
1432 itemDisabled: "choices__item--disabled",
1433 itemChoice: "choices__item--choice",
1434 placeholder: "choices__placeholder",
1435 group: "choices__group",
1436 groupHeading: "choices__heading",
1437 button: "choices__button",
1438 activeState: "is-active",
1439 focusState: "is-focused",
1440 openState: "is-open",
1441 disabledState: "is-disabled",
1442 highlightedState: "text-info",
1443 selectedState: "text-info",
1444 flippedState: "is-flipped",
1445 loadingState: "is-loading",
1446 noResults: "has-no-results",
1447 noChoices: "has-no-choices",
1451 export function communitySelectName(cv: CommunityView): string {
1452 return cv.community.local
1454 : `${hostname(cv.community.actor_id)}/${cv.community.name}`;
1457 export function personSelectName(pvs: PersonViewSafe): string {
1458 return pvs.person.local
1460 : `${hostname(pvs.person.actor_id)}/${pvs.person.name}`;
1463 export function initializeSite(site: GetSiteResponse) {
1464 UserService.Instance.myUserInfo = site.my_user;
1465 i18n.changeLanguage(getLanguage());
1468 const SHORTNUM_SI_FORMAT = new Intl.NumberFormat("en-US", {
1469 maximumSignificantDigits: 3,
1471 notation: "compact",
1472 compactDisplay: "short",
1475 export function numToSI(value: number): string {
1476 return SHORTNUM_SI_FORMAT.format(value);