1 import emojiShortName from "emoji-short-name";
2 import ISO6391 from "iso-639-1";
4 BlockCommunityResponse,
22 RegistrationApplicationView,
28 WebSocketJsonResponse,
30 } from "lemmy-js-client";
31 import markdown_it from "markdown-it";
32 import markdown_it_container from "markdown-it-container";
33 import markdown_it_html5_embed from "markdown-it-html5-embed";
34 import markdown_it_sub from "markdown-it-sub";
35 import markdown_it_sup from "markdown-it-sup";
36 import moment from "moment";
37 import "moment/locale/bg";
38 import "moment/locale/bn";
39 import "moment/locale/ca";
40 import "moment/locale/cs";
41 import "moment/locale/cy";
42 import "moment/locale/da";
43 import "moment/locale/de";
44 import "moment/locale/el";
45 import "moment/locale/eo";
46 import "moment/locale/es";
47 import "moment/locale/eu";
48 import "moment/locale/fa";
49 import "moment/locale/fi";
50 import "moment/locale/fr";
51 import "moment/locale/ga";
52 import "moment/locale/gl";
53 import "moment/locale/hi";
54 import "moment/locale/hr";
55 import "moment/locale/hu";
56 import "moment/locale/id";
57 import "moment/locale/it";
58 import "moment/locale/ja";
59 import "moment/locale/ka";
60 import "moment/locale/km";
61 import "moment/locale/ko";
62 import "moment/locale/ml";
63 import "moment/locale/nb";
64 import "moment/locale/nl";
65 import "moment/locale/pl";
66 import "moment/locale/pt-br";
67 import "moment/locale/ru";
68 import "moment/locale/sk";
69 import "moment/locale/sq";
70 import "moment/locale/sr";
71 import "moment/locale/sv";
72 import "moment/locale/tr";
73 import "moment/locale/uk";
74 import "moment/locale/vi";
75 import "moment/locale/zh-cn";
76 import { Subscription } from "rxjs";
77 import { delay, retryWhen, take } from "rxjs/operators";
78 import tippy from "tippy.js";
79 import Toastify from "toastify-js";
80 import { httpBase } from "./env";
81 import { i18n } from "./i18next";
83 CommentNode as CommentNodeI,
87 } from "./interfaces";
88 import { UserService, WebSocketService } from "./services";
92 Tribute = require("tributejs");
95 export const wsClient = new LemmyWebsocket();
97 export const favIconUrl = "/static/assets/icons/favicon.svg";
98 export const favIconPngUrl = "/static/assets/icons/apple-touch-icon.png";
100 // export const defaultFavIcon = `${window.location.protocol}//${window.location.host}${favIconPngUrl}`;
101 export const repoUrl = "https://github.com/LemmyNet";
102 export const joinLemmyUrl = "https://join-lemmy.org";
103 export const donateLemmyUrl = `${joinLemmyUrl}/donate`;
104 export const docsUrl = `${joinLemmyUrl}/docs/en/index.html`;
105 export const helpGuideUrl = `${joinLemmyUrl}/docs/en/about/guide.html`; // TODO find a way to redirect to the non-en folder
106 export const markdownHelpUrl = `${helpGuideUrl}#using-markdown`;
107 export const sortingHelpUrl = `${helpGuideUrl}#sorting`;
108 export const archiveTodayUrl = "https://archive.today";
109 export const ghostArchiveUrl = "https://ghostarchive.org";
110 export const webArchiveUrl = "https://web.archive.org";
111 export const elementUrl = "https://element.io";
113 export const postRefetchSeconds: number = 60 * 1000;
114 export const fetchLimit = 20;
115 export const mentionDropdownFetchLimit = 10;
117 export const languages = [
166 export const themes = [
183 const DEFAULT_ALPHABET =
184 "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
186 function getRandomCharFromAlphabet(alphabet: string): string {
187 return alphabet.charAt(Math.floor(Math.random() * alphabet.length));
190 export function randomStr(
191 idDesiredLength = 20,
192 alphabet = DEFAULT_ALPHABET
195 * Create n-long array and map it to random chars from given alphabet.
196 * Then join individual chars as string
198 return Array.from({ length: idDesiredLength })
200 return getRandomCharFromAlphabet(alphabet);
205 export function wsJsonToRes<ResponseType>(
206 msg: WebSocketJsonResponse<ResponseType>
207 ): WebSocketResponse<ResponseType> {
214 export function wsUserOp(msg: any): UserOperation {
215 let opStr: string = msg.op;
216 return UserOperation[opStr];
219 export const md = new markdown_it({
224 .use(markdown_it_sub)
225 .use(markdown_it_sup)
226 .use(markdown_it_html5_embed, {
228 useImageSyntax: true, // Enables video/audio embed with ![]() syntax (default)
230 audio: 'controls preload="metadata"',
232 'width="100%" max-height="100%" controls loop preload="metadata"',
236 .use(markdown_it_container, "spoiler", {
237 validate: function (params: any) {
238 return params.trim().match(/^spoiler\s+(.*)$/);
241 render: function (tokens: any, idx: any) {
242 var m = tokens[idx].info.trim().match(/^spoiler\s+(.*)$/);
244 if (tokens[idx].nesting === 1) {
246 return `<details><summary> ${md.utils.escapeHtml(m[1])} </summary>\n`;
249 return "</details>\n";
254 export function hotRankComment(comment_view: CommentView): number {
255 return hotRank(comment_view.counts.score, comment_view.comment.published);
258 export function hotRankActivePost(post_view: PostView): number {
259 return hotRank(post_view.counts.score, post_view.counts.newest_comment_time);
262 export function hotRankPost(post_view: PostView): number {
263 return hotRank(post_view.counts.score, post_view.post.published);
266 export function hotRank(score: number, timeStr: string): number {
267 // Rank = ScaleFactor * sign(Score) * log(1 + abs(Score)) / (Time + 2)^Gravity
268 let date: Date = new Date(timeStr + "Z"); // Add Z to convert from UTC date
269 let now: Date = new Date();
270 let hoursElapsed: number = (now.getTime() - date.getTime()) / 36e5;
273 (10000 * Math.log10(Math.max(1, 3 + score))) /
274 Math.pow(hoursElapsed + 2, 1.8);
276 // console.log(`Comment: ${comment.content}\nRank: ${rank}\nScore: ${comment.score}\nHours: ${hoursElapsed}`);
281 export function mdToHtml(text: string) {
282 return { __html: md.render(text) };
285 export function getUnixTime(text: string): number {
286 return text ? new Date(text).getTime() / 1000 : undefined;
289 export function futureDaysToUnixTime(days: number): number {
292 new Date(Date.now() + 1000 * 60 * 60 * 24 * days).getTime() / 1000
297 export function canMod(
298 myUserInfo: MyUserInfo,
303 // You can do moderator actions only on the mods added after you.
305 let yourIndex = modIds.findIndex(
306 id => id == myUserInfo.local_user_view.person.id
308 if (yourIndex == -1) {
311 // onSelf +1 on mod actions not for yourself, IE ban, remove, etc
312 modIds = modIds.slice(0, yourIndex + (onSelf ? 0 : 1));
313 return !modIds.includes(creator_id);
320 export function isMod(modIds: number[], creator_id: number): boolean {
321 return modIds.includes(creator_id);
324 const imageRegex = new RegExp(
325 /(http)?s?:?(\/\/[^"']*\.(?:jpg|jpeg|gif|png|svg|webp))/
327 const videoRegex = new RegExp(`(http)?s?:?(\/\/[^"']*\.(?:mp4))`);
329 export function isImage(url: string) {
330 return imageRegex.test(url);
333 export function isVideo(url: string) {
334 return videoRegex.test(url);
337 export function validURL(str: string) {
338 return !!new URL(str);
341 export function communityRSSUrl(actorId: string, sort: string): string {
342 let url = new URL(actorId);
343 return `${url.origin}/feeds${url.pathname}.xml?sort=${sort}`;
346 export function validEmail(email: string) {
348 /^(([^\s"(),.:;<>@[\\\]]+(\.[^\s"(),.:;<>@[\\\]]+)*)|(".+"))@((\[(?:\d{1,3}\.){3}\d{1,3}])|(([\dA-Za-z\-]+\.)+[A-Za-z]{2,}))$/;
349 return re.test(String(email).toLowerCase());
352 export function capitalizeFirstLetter(str: string): string {
353 return str.charAt(0).toUpperCase() + str.slice(1);
356 export function routeSortTypeToEnum(sort: string): SortType {
357 return SortType[sort];
360 export function listingTypeFromNum(type_: number): ListingType {
361 return Object.values(ListingType)[type_];
364 export function sortTypeFromNum(type_: number): SortType {
365 return Object.values(SortType)[type_];
368 export function routeListingTypeToEnum(type: string): ListingType {
369 return ListingType[type];
372 export function routeDataTypeToEnum(type: string): DataType {
373 return DataType[capitalizeFirstLetter(type)];
376 export function routeSearchTypeToEnum(type: string): SearchType {
377 return SearchType[type];
380 export async function getSiteMetadata(url: string) {
381 let form: GetSiteMetadata = {
384 let client = new LemmyHttp(httpBase);
385 return client.getSiteMetadata(form);
388 export function debounce(func: any, wait = 1000, immediate = false) {
389 // 'private' variable for instance
390 // The returned function will be able to reference this due to closure.
391 // Each call to the returned function will share this common timer.
394 // Calling debounce returns a new anonymous function
396 // reference the context and args for the setTimeout function
397 var args = arguments;
399 // Should the function be called now? If immediate is true
400 // and not already in a timeout then the answer is: Yes
401 var callNow = immediate && !timeout;
403 // This is the basic debounce behaviour where you can call this
404 // function several times, but it will only execute once
405 // [before or after imposing a delay].
406 // Each time the returned function is called, the timer starts over.
407 clearTimeout(timeout);
409 // Set the new timeout
410 timeout = setTimeout(function () {
411 // Inside the timeout function, clear the timeout variable
412 // which will let the next execution run when in 'immediate' mode
415 // Check if the function already ran with the immediate flag
417 // Call the original function with apply
418 // apply lets you define the 'this' object as well as the arguments
419 // (both captured before setTimeout)
420 func.apply(this, args);
424 // Immediate mode and no wait timer? Execute the function..
425 if (callNow) func.apply(this, args);
429 export function getNativeLanguageName(code: string): string {
430 let [isoCode, qualifier] = code.split("_");
432 let native = ISO6391.getNativeName(isoCode) || code;
435 return `${native}_${qualifier}`;
442 export function getLanguage(override?: string): string {
443 let myUserInfo = UserService.Instance.myUserInfo;
446 (myUserInfo?.local_user_view.local_user.lang
447 ? myUserInfo.local_user_view.local_user.lang
450 if (lang == "browser" && isBrowser()) {
451 return getBrowserLanguage();
457 export function getBrowserLanguage(): string {
458 // Intersect lemmy's langs, with the browser langs
459 let langs = languages ? languages.map(l => l.code) : ["en"];
461 // NOTE, mobile browsers seem to be missing this list, so append en
462 let allowedLangs = navigator.languages
464 .filter(v => langs.includes(v));
465 return allowedLangs[0];
468 export function getMomentLanguage(): string {
469 let lang = getLanguage();
470 if (lang.startsWith("zh")) {
472 } else if (lang.startsWith("sv")) {
474 } else if (lang.startsWith("fr")) {
476 } else if (lang.startsWith("de")) {
478 } else if (lang.startsWith("ru")) {
480 } else if (lang.startsWith("es")) {
482 } else if (lang.startsWith("eo")) {
484 } else if (lang.startsWith("nl")) {
486 } else if (lang.startsWith("it")) {
488 } else if (lang.startsWith("fi")) {
490 } else if (lang.startsWith("ca")) {
492 } else if (lang.startsWith("fa")) {
494 } else if (lang.startsWith("pl")) {
496 } else if (lang.startsWith("pt_BR")) {
498 } else if (lang.startsWith("ja")) {
500 } else if (lang.startsWith("ka")) {
502 } else if (lang.startsWith("hi")) {
504 } else if (lang.startsWith("el")) {
506 } else if (lang.startsWith("eu")) {
508 } else if (lang.startsWith("gl")) {
510 } else if (lang.startsWith("tr")) {
512 } else if (lang.startsWith("hu")) {
514 } else if (lang.startsWith("uk")) {
516 } else if (lang.startsWith("sq")) {
518 } else if (lang.startsWith("km")) {
520 } else if (lang.startsWith("ga")) {
522 } else if (lang.startsWith("sr")) {
524 } else if (lang.startsWith("ko")) {
526 } else if (lang.startsWith("da")) {
528 } else if (lang.startsWith("oc")) {
530 } else if (lang.startsWith("hr")) {
532 } else if (lang.startsWith("th")) {
534 } else if (lang.startsWith("bg")) {
536 } else if (lang.startsWith("id")) {
538 } else if (lang.startsWith("nb")) {
540 } else if (lang.startsWith("cy")) {
542 } else if (lang.startsWith("sk")) {
544 } else if (lang.startsWith("vi")) {
546 } else if (lang.startsWith("pt")) {
548 } else if (lang.startsWith("ar")) {
550 } else if (lang.startsWith("bn")) {
552 } else if (lang.startsWith("ml")) {
554 } else if (lang.startsWith("cs")) {
562 export function setTheme(theme: string, forceReload = false) {
566 if (theme === "browser" && !forceReload) {
569 // This is only run on a force reload
570 if (theme == "browser") {
574 // Unload all the other themes
575 for (var i = 0; i < themes.length; i++) {
576 let styleSheet = document.getElementById(themes[i]);
578 styleSheet.setAttribute("disabled", "disabled");
583 .getElementById("default-light")
584 ?.setAttribute("disabled", "disabled");
585 document.getElementById("default-dark")?.setAttribute("disabled", "disabled");
587 // Load the theme dynamically
588 let cssLoc = `/static/assets/css/themes/${theme}.min.css`;
589 loadCss(theme, cssLoc);
590 document.getElementById(theme).removeAttribute("disabled");
593 export function loadCss(id: string, loc: string) {
594 if (!document.getElementById(id)) {
595 var head = document.getElementsByTagName("head")[0];
596 var link = document.createElement("link");
598 link.rel = "stylesheet";
599 link.type = "text/css";
602 head.appendChild(link);
606 export function objectFlip(obj: any) {
608 Object.keys(obj).forEach(key => {
614 export function showAvatars(): boolean {
616 UserService.Instance.myUserInfo?.local_user_view.local_user.show_avatars ||
617 !UserService.Instance.myUserInfo
621 export function showScores(): boolean {
623 UserService.Instance.myUserInfo?.local_user_view.local_user.show_scores ||
624 !UserService.Instance.myUserInfo
628 export function isCakeDay(published: string): boolean {
629 // moment(undefined) or moment.utc(undefined) returns the current date/time
630 // moment(null) or moment.utc(null) returns null
631 const createDate = moment.utc(published || null).local();
632 const currentDate = moment(new Date());
635 createDate.date() === currentDate.date() &&
636 createDate.month() === currentDate.month() &&
637 createDate.year() !== currentDate.year()
641 export function toast(text: string, background = "success") {
643 let backgroundColor = `var(--${background})`;
646 backgroundColor: backgroundColor,
653 export function pictrsDeleteToast(
654 clickToDeleteText: string,
655 deletePictureText: string,
659 let backgroundColor = `var(--light)`;
660 let toast = Toastify({
661 text: clickToDeleteText,
662 backgroundColor: backgroundColor,
668 window.location.replace(deleteUrl);
669 alert(deletePictureText);
678 interface NotifyInfo {
685 export function messageToastify(info: NotifyInfo, router: any) {
687 let htmlBody = info.body ? md.render(info.body) : "";
688 let backgroundColor = `var(--light)`;
690 let toast = Toastify({
691 text: `${htmlBody}<br />${info.name}`,
692 avatar: info.icon ? info.icon : null,
693 backgroundColor: backgroundColor,
694 className: "text-dark",
703 router.history.push(info.link);
710 export function notifyPost(post_view: PostView, router: any) {
711 let info: NotifyInfo = {
712 name: post_view.community.name,
713 icon: post_view.community.icon,
714 link: `/post/${post_view.post.id}`,
715 body: post_view.post.name,
717 notify(info, router);
720 export function notifyComment(comment_view: CommentView, router: any) {
721 let info: NotifyInfo = {
722 name: comment_view.creator.name,
723 icon: comment_view.creator.avatar,
724 link: `/post/${comment_view.post.id}/comment/${comment_view.comment.id}`,
725 body: comment_view.comment.content,
727 notify(info, router);
730 export function notifyPrivateMessage(pmv: PrivateMessageView, router: any) {
731 let info: NotifyInfo = {
732 name: pmv.creator.name,
733 icon: pmv.creator.avatar,
735 body: pmv.private_message.content,
737 notify(info, router);
740 function notify(info: NotifyInfo, router: any) {
741 messageToastify(info, router);
743 // TODO absolute nightmare bug, but notifs are currently broken.
744 // Notification.new will try to do a browser fetch ???
746 // if (Notification.permission !== "granted") Notification.requestPermission();
748 // var notification = new Notification(info.name, {
753 // notification.onclick = (ev: Event): any => {
754 // ev.preventDefault();
755 // router.history.push(info.link);
760 export function setupTribute() {
762 noMatchTemplate: function () {
769 menuItemTemplate: (item: any) => {
770 let shortName = `:${item.original.key}:`;
771 return `${item.original.val} ${shortName}`;
773 selectTemplate: (item: any) => {
774 return `${item.original.val}`;
776 values: Object.entries(emojiShortName).map(e => {
777 return { key: e[1], val: e[0] };
780 autocompleteMode: true,
782 // menuItemLimit: mentionDropdownFetchLimit,
783 menuShowMinLength: 2,
788 selectTemplate: (item: any) => {
789 let it: PersonTribute = item.original;
790 return `[${it.key}](${it.view.person.actor_id})`;
792 values: (text: string, cb: (persons: PersonTribute[]) => any) => {
793 personSearch(text, (persons: PersonTribute[]) => cb(persons));
796 autocompleteMode: true,
798 // menuItemLimit: mentionDropdownFetchLimit,
799 menuShowMinLength: 2,
805 selectTemplate: (item: any) => {
806 let it: CommunityTribute = item.original;
807 return `[${it.key}](${it.view.community.actor_id})`;
809 values: (text: string, cb: any) => {
810 communitySearch(text, (communities: CommunityTribute[]) =>
815 autocompleteMode: true,
817 // menuItemLimit: mentionDropdownFetchLimit,
818 menuShowMinLength: 2,
824 var tippyInstance: any;
826 tippyInstance = tippy("[data-tippy-content]");
829 export function setupTippy() {
831 tippyInstance.forEach((e: any) => e.destroy());
832 tippyInstance = tippy("[data-tippy-content]", {
834 // Display on "long press"
835 touch: ["hold", 500],
840 interface PersonTribute {
842 view: PersonViewSafe;
845 function personSearch(text: string, cb: (persons: PersonTribute[]) => any) {
849 type_: SearchType.Users,
850 sort: SortType.TopAll,
851 listing_type: ListingType.All,
853 limit: mentionDropdownFetchLimit,
854 auth: authField(false),
857 WebSocketService.Instance.send(wsClient.search(form));
859 let personSub = WebSocketService.Instance.subject.subscribe(
861 let res = wsJsonToRes(msg);
862 if (res.op == UserOperation.Search) {
863 let data = res.data as SearchResponse;
864 let persons: PersonTribute[] = data.users.map(pv => {
865 let tribute: PersonTribute = {
866 key: `@${pv.person.name}@${hostname(pv.person.actor_id)}`,
872 personSub.unsubscribe();
875 err => console.error(err),
876 () => console.log("complete")
883 interface CommunityTribute {
888 function communitySearch(
890 cb: (communities: CommunityTribute[]) => any
895 type_: SearchType.Communities,
896 sort: SortType.TopAll,
897 listing_type: ListingType.All,
899 limit: mentionDropdownFetchLimit,
900 auth: authField(false),
903 WebSocketService.Instance.send(wsClient.search(form));
905 let communitySub = WebSocketService.Instance.subject.subscribe(
907 let res = wsJsonToRes(msg);
908 if (res.op == UserOperation.Search) {
909 let data = res.data as SearchResponse;
910 let communities: CommunityTribute[] = data.communities.map(cv => {
911 let tribute: CommunityTribute = {
912 key: `!${cv.community.name}@${hostname(cv.community.actor_id)}`,
918 communitySub.unsubscribe();
921 err => console.error(err),
922 () => console.log("complete")
929 export function getListingTypeFromProps(props: any): ListingType {
930 return props.match.params.listing_type
931 ? routeListingTypeToEnum(props.match.params.listing_type)
932 : UserService.Instance.myUserInfo
933 ? Object.values(ListingType)[
934 UserService.Instance.myUserInfo.local_user_view.local_user
935 .default_listing_type
940 export function getListingTypeFromPropsNoDefault(props: any): ListingType {
941 return props.match.params.listing_type
942 ? routeListingTypeToEnum(props.match.params.listing_type)
946 // TODO might need to add a user setting for this too
947 export function getDataTypeFromProps(props: any): DataType {
948 return props.match.params.data_type
949 ? routeDataTypeToEnum(props.match.params.data_type)
953 export function getSortTypeFromProps(props: any): SortType {
954 return props.match.params.sort
955 ? routeSortTypeToEnum(props.match.params.sort)
956 : UserService.Instance.myUserInfo
957 ? Object.values(SortType)[
958 UserService.Instance.myUserInfo.local_user_view.local_user
964 export function getPageFromProps(props: any): number {
965 return props.match.params.page ? Number(props.match.params.page) : 1;
968 export function getRecipientIdFromProps(props: any): number {
969 return props.match.params.recipient_id
970 ? Number(props.match.params.recipient_id)
974 export function getIdFromProps(props: any): number {
975 return Number(props.match.params.id);
978 export function getCommentIdFromProps(props: any): number {
979 return Number(props.match.params.comment_id);
982 export function getUsernameFromProps(props: any): string {
983 return props.match.params.username;
986 export function editCommentRes(data: CommentView, comments: CommentView[]) {
987 let found = comments.find(c => c.comment.id == data.comment.id);
989 found.comment.content = data.comment.content;
990 found.comment.updated = data.comment.updated;
991 found.comment.removed = data.comment.removed;
992 found.comment.deleted = data.comment.deleted;
993 found.counts.upvotes = data.counts.upvotes;
994 found.counts.downvotes = data.counts.downvotes;
995 found.counts.score = data.counts.score;
999 export function saveCommentRes(data: CommentView, comments: CommentView[]) {
1000 let found = comments.find(c => c.comment.id == data.comment.id);
1002 found.saved = data.saved;
1006 export function updatePersonBlock(
1007 data: BlockPersonResponse
1008 ): PersonBlockView[] {
1010 UserService.Instance.myUserInfo.person_blocks.push({
1011 person: UserService.Instance.myUserInfo.local_user_view.person,
1012 target: data.person_view.person,
1014 toast(`${i18n.t("blocked")} ${data.person_view.person.name}`);
1016 UserService.Instance.myUserInfo.person_blocks =
1017 UserService.Instance.myUserInfo.person_blocks.filter(
1018 i => i.target.id != data.person_view.person.id
1020 toast(`${i18n.t("unblocked")} ${data.person_view.person.name}`);
1022 return UserService.Instance.myUserInfo.person_blocks;
1025 export function updateCommunityBlock(
1026 data: BlockCommunityResponse
1027 ): CommunityBlockView[] {
1029 UserService.Instance.myUserInfo.community_blocks.push({
1030 person: UserService.Instance.myUserInfo.local_user_view.person,
1031 community: data.community_view.community,
1033 toast(`${i18n.t("blocked")} ${data.community_view.community.name}`);
1035 UserService.Instance.myUserInfo.community_blocks =
1036 UserService.Instance.myUserInfo.community_blocks.filter(
1037 i => i.community.id != data.community_view.community.id
1039 toast(`${i18n.t("unblocked")} ${data.community_view.community.name}`);
1041 return UserService.Instance.myUserInfo.community_blocks;
1044 export function createCommentLikeRes(
1046 comments: CommentView[]
1048 let found = comments.find(c => c.comment.id === data.comment.id);
1050 found.counts.score = data.counts.score;
1051 found.counts.upvotes = data.counts.upvotes;
1052 found.counts.downvotes = data.counts.downvotes;
1053 if (data.my_vote !== null) {
1054 found.my_vote = data.my_vote;
1059 export function createPostLikeFindRes(data: PostView, posts: PostView[]) {
1060 let found = posts.find(p => p.post.id == data.post.id);
1062 createPostLikeRes(data, found);
1066 export function createPostLikeRes(data: PostView, post_view: PostView) {
1068 post_view.counts.score = data.counts.score;
1069 post_view.counts.upvotes = data.counts.upvotes;
1070 post_view.counts.downvotes = data.counts.downvotes;
1071 if (data.my_vote !== null) {
1072 post_view.my_vote = data.my_vote;
1077 export function editPostFindRes(data: PostView, posts: PostView[]) {
1078 let found = posts.find(p => p.post.id == data.post.id);
1080 editPostRes(data, found);
1084 export function editPostRes(data: PostView, post: PostView) {
1086 post.post.url = data.post.url;
1087 post.post.name = data.post.name;
1088 post.post.nsfw = data.post.nsfw;
1089 post.post.deleted = data.post.deleted;
1090 post.post.removed = data.post.removed;
1091 post.post.stickied = data.post.stickied;
1092 post.post.body = data.post.body;
1093 post.post.locked = data.post.locked;
1094 post.saved = data.saved;
1098 export function updatePostReportRes(
1099 data: PostReportView,
1100 reports: PostReportView[]
1102 let found = reports.find(p => p.post.id == data.post.id);
1104 found.post_report = data.post_report;
1108 export function updateCommentReportRes(
1109 data: CommentReportView,
1110 reports: CommentReportView[]
1112 let found = reports.find(c => c.comment.id == data.comment.id);
1114 found.comment_report = data.comment_report;
1118 export function updateRegistrationApplicationRes(
1119 data: RegistrationApplicationView,
1120 applications: RegistrationApplicationView[]
1122 let found = applications.find(
1123 ra => ra.registration_application.id == data.registration_application.id
1126 found.registration_application = data.registration_application;
1127 found.admin = data.admin;
1128 found.creator_local_user = data.creator_local_user;
1132 export function commentsToFlatNodes(comments: CommentView[]): CommentNodeI[] {
1133 let nodes: CommentNodeI[] = [];
1134 for (let comment of comments) {
1135 nodes.push({ comment_view: comment });
1140 function commentSort(tree: CommentNodeI[], sort: CommentSortType) {
1141 // First, put removed and deleted comments at the bottom, then do your other sorts
1142 if (sort == CommentSortType.Top) {
1145 +a.comment_view.comment.removed - +b.comment_view.comment.removed ||
1146 +a.comment_view.comment.deleted - +b.comment_view.comment.deleted ||
1147 b.comment_view.counts.score - a.comment_view.counts.score
1149 } else if (sort == CommentSortType.New) {
1152 +a.comment_view.comment.removed - +b.comment_view.comment.removed ||
1153 +a.comment_view.comment.deleted - +b.comment_view.comment.deleted ||
1154 b.comment_view.comment.published.localeCompare(
1155 a.comment_view.comment.published
1158 } else if (sort == CommentSortType.Old) {
1161 +a.comment_view.comment.removed - +b.comment_view.comment.removed ||
1162 +a.comment_view.comment.deleted - +b.comment_view.comment.deleted ||
1163 a.comment_view.comment.published.localeCompare(
1164 b.comment_view.comment.published
1167 } else if (sort == CommentSortType.Hot) {
1170 +a.comment_view.comment.removed - +b.comment_view.comment.removed ||
1171 +a.comment_view.comment.deleted - +b.comment_view.comment.deleted ||
1172 hotRankComment(b.comment_view) - hotRankComment(a.comment_view)
1176 // Go through the children recursively
1177 for (let node of tree) {
1178 if (node.children) {
1179 commentSort(node.children, sort);
1184 export function commentSortSortType(tree: CommentNodeI[], sort: SortType) {
1185 commentSort(tree, convertCommentSortType(sort));
1188 function convertCommentSortType(sort: SortType): CommentSortType {
1190 sort == SortType.TopAll ||
1191 sort == SortType.TopDay ||
1192 sort == SortType.TopWeek ||
1193 sort == SortType.TopMonth ||
1194 sort == SortType.TopYear
1196 return CommentSortType.Top;
1197 } else if (sort == SortType.New) {
1198 return CommentSortType.New;
1199 } else if (sort == SortType.Hot || sort == SortType.Active) {
1200 return CommentSortType.Hot;
1202 return CommentSortType.Hot;
1206 export function buildCommentsTree(
1207 comments: CommentView[],
1208 commentSortType: CommentSortType
1210 let map = new Map<number, CommentNodeI>();
1211 for (let comment_view of comments) {
1212 let node: CommentNodeI = {
1213 comment_view: comment_view,
1216 map.set(comment_view.comment.id, { ...node });
1218 let tree: CommentNodeI[] = [];
1219 for (let comment_view of comments) {
1220 let child = map.get(comment_view.comment.id);
1221 let parent_id = comment_view.comment.parent_id;
1223 let parent = map.get(parent_id);
1224 // Necessary because blocked comment might not exist
1226 parent.children.push(child);
1235 commentSort(tree, commentSortType);
1240 function setDepth(node: CommentNodeI, i = 0) {
1241 for (let child of node.children) {
1243 setDepth(child, i + 1);
1247 export function insertCommentIntoTree(tree: CommentNodeI[], cv: CommentView) {
1248 // Building a fake node to be used for later
1249 let node: CommentNodeI = {
1255 if (cv.comment.parent_id) {
1256 let parentComment = searchCommentTree(tree, cv.comment.parent_id);
1257 if (parentComment) {
1258 node.depth = parentComment.depth + 1;
1259 parentComment.children.unshift(node);
1266 export function searchCommentTree(
1267 tree: CommentNodeI[],
1270 for (let node of tree) {
1271 if (node.comment_view.comment.id === id) {
1275 for (const child of node.children) {
1276 const res = searchCommentTree([child], id);
1286 export const colorList: string[] = [
1295 function hsl(num: number) {
1296 return `hsla(${num}, 35%, 50%, 1)`;
1299 export function previewLines(
1308 // Use lines * 2 because markdown requires 2 lines
1309 .slice(0, maxLines * 2)
1314 export function hostname(url: string): string {
1315 let cUrl = new URL(url);
1316 return cUrl.port ? `${cUrl.hostname}:${cUrl.port}` : `${cUrl.hostname}`;
1319 export function validTitle(title?: string): boolean {
1320 // Initial title is null, minimum length is taken care of by textarea's minLength={3}
1321 if (title === null || title.length < 3) return true;
1323 const regex = new RegExp(/.*\S.*/, "g");
1325 return regex.test(title);
1328 export function siteBannerCss(banner: string): string {
1330 background-image: linear-gradient( rgba(0, 0, 0, 0.8), rgba(0, 0, 0, 0.8) ) ,url("${banner}"); \
1331 background-attachment: fixed; \
1332 background-position: top; \
1333 background-repeat: no-repeat; \
1334 background-size: 100% cover; \
1337 max-height: 100vh; \
1341 export function isBrowser() {
1342 return typeof window !== "undefined";
1345 export function setIsoData(context: any): IsoData {
1346 let isoData: IsoData = isBrowser()
1348 : context.router.staticContext;
1352 export function wsSubscribe(parseMessage: any): Subscription {
1354 return WebSocketService.Instance.subject
1355 .pipe(retryWhen(errors => errors.pipe(delay(3000), take(10))))
1357 msg => parseMessage(msg),
1358 err => console.error(err),
1359 () => console.log("complete")
1366 export function setOptionalAuth(obj: any, auth = UserService.Instance.auth) {
1372 export function authField(
1374 auth = UserService.Instance.auth
1376 if (auth == null && throwErr) {
1377 toast(i18n.t("not_logged_in"), "danger");
1378 throw "Not logged in";
1384 moment.updateLocale("en", {
1405 export function saveScrollPosition(context: any) {
1406 let path: string = context.router.route.location.pathname;
1407 let y = window.scrollY;
1408 sessionStorage.setItem(`scrollPosition_${path}`, y.toString());
1411 export function restoreScrollPosition(context: any) {
1412 let path: string = context.router.route.location.pathname;
1413 let y = Number(sessionStorage.getItem(`scrollPosition_${path}`));
1414 window.scrollTo(0, y);
1417 export function showLocal(isoData: IsoData): boolean {
1418 return isoData.site_res.federated_instances?.linked.length > 0;
1421 interface ChoicesValue {
1426 export function communityToChoice(cv: CommunityView): ChoicesValue {
1427 let choice: ChoicesValue = {
1428 value: cv.community.id.toString(),
1429 label: communitySelectName(cv),
1434 export function personToChoice(pvs: PersonViewSafe): ChoicesValue {
1435 let choice: ChoicesValue = {
1436 value: pvs.person.id.toString(),
1437 label: personSelectName(pvs),
1442 export async function fetchCommunities(q: string) {
1443 let form: Search = {
1445 type_: SearchType.Communities,
1446 sort: SortType.TopAll,
1447 listing_type: ListingType.All,
1450 auth: authField(false),
1452 let client = new LemmyHttp(httpBase);
1453 return client.search(form);
1456 export async function fetchUsers(q: string) {
1457 let form: Search = {
1459 type_: SearchType.Users,
1460 sort: SortType.TopAll,
1461 listing_type: ListingType.All,
1464 auth: authField(false),
1466 let client = new LemmyHttp(httpBase);
1467 return client.search(form);
1470 export const choicesConfig = {
1472 searchResultLimit: fetchLimit,
1474 containerOuter: "choices",
1475 containerInner: "choices__inner bg-secondary border-0",
1476 input: "form-control",
1477 inputCloned: "choices__input--cloned",
1478 list: "choices__list",
1479 listItems: "choices__list--multiple",
1480 listSingle: "choices__list--single",
1481 listDropdown: "choices__list--dropdown",
1482 item: "choices__item bg-secondary",
1483 itemSelectable: "choices__item--selectable",
1484 itemDisabled: "choices__item--disabled",
1485 itemChoice: "choices__item--choice",
1486 placeholder: "choices__placeholder",
1487 group: "choices__group",
1488 groupHeading: "choices__heading",
1489 button: "choices__button",
1490 activeState: "is-active",
1491 focusState: "is-focused",
1492 openState: "is-open",
1493 disabledState: "is-disabled",
1494 highlightedState: "text-info",
1495 selectedState: "text-info",
1496 flippedState: "is-flipped",
1497 loadingState: "is-loading",
1498 noResults: "has-no-results",
1499 noChoices: "has-no-choices",
1503 export function communitySelectName(cv: CommunityView): string {
1504 return cv.community.local
1505 ? cv.community.title
1506 : `${hostname(cv.community.actor_id)}/${cv.community.title}`;
1509 export function personSelectName(pvs: PersonViewSafe): string {
1510 let pName = pvs.person.display_name || pvs.person.name;
1511 return pvs.person.local ? pName : `${hostname(pvs.person.actor_id)}/${pName}`;
1514 export function initializeSite(site: GetSiteResponse) {
1515 UserService.Instance.myUserInfo = site.my_user;
1516 i18n.changeLanguage(getLanguage());
1519 const SHORTNUM_SI_FORMAT = new Intl.NumberFormat("en-US", {
1520 maximumSignificantDigits: 3,
1522 notation: "compact",
1523 compactDisplay: "short",
1526 export function numToSI(value: number): string {
1527 return SHORTNUM_SI_FORMAT.format(value);
1530 export function isBanned(ps: PersonSafe): boolean {
1531 // Add Z to convert from UTC date
1532 if (ps.ban_expires) {
1533 if (ps.banned && new Date(ps.ban_expires + "Z") > new Date()) {