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 = [
168 export const themes = [
185 const DEFAULT_ALPHABET =
186 "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
188 function getRandomCharFromAlphabet(alphabet: string): string {
189 return alphabet.charAt(Math.floor(Math.random() * alphabet.length));
192 export function randomStr(
193 idDesiredLength = 20,
194 alphabet = DEFAULT_ALPHABET
197 * Create n-long array and map it to random chars from given alphabet.
198 * Then join individual chars as string
200 return Array.from({ length: idDesiredLength })
202 return getRandomCharFromAlphabet(alphabet);
207 export function wsJsonToRes<ResponseType>(
208 msg: WebSocketJsonResponse<ResponseType>
209 ): WebSocketResponse<ResponseType> {
216 export function wsUserOp(msg: any): UserOperation {
217 let opStr: string = msg.op;
218 return UserOperation[opStr];
221 export const md = new markdown_it({
226 .use(markdown_it_sub)
227 .use(markdown_it_sup)
228 .use(markdown_it_html5_embed, {
230 useImageSyntax: true, // Enables video/audio embed with ![]() syntax (default)
232 audio: 'controls preload="metadata"',
234 'width="100%" max-height="100%" controls loop preload="metadata"',
238 .use(markdown_it_container, "spoiler", {
239 validate: function (params: any) {
240 return params.trim().match(/^spoiler\s+(.*)$/);
243 render: function (tokens: any, idx: any) {
244 var m = tokens[idx].info.trim().match(/^spoiler\s+(.*)$/);
246 if (tokens[idx].nesting === 1) {
248 return `<details><summary> ${md.utils.escapeHtml(m[1])} </summary>\n`;
251 return "</details>\n";
256 export function hotRankComment(comment_view: CommentView): number {
257 return hotRank(comment_view.counts.score, comment_view.comment.published);
260 export function hotRankActivePost(post_view: PostView): number {
261 return hotRank(post_view.counts.score, post_view.counts.newest_comment_time);
264 export function hotRankPost(post_view: PostView): number {
265 return hotRank(post_view.counts.score, post_view.post.published);
268 export function hotRank(score: number, timeStr: string): number {
269 // Rank = ScaleFactor * sign(Score) * log(1 + abs(Score)) / (Time + 2)^Gravity
270 let date: Date = new Date(timeStr + "Z"); // Add Z to convert from UTC date
271 let now: Date = new Date();
272 let hoursElapsed: number = (now.getTime() - date.getTime()) / 36e5;
275 (10000 * Math.log10(Math.max(1, 3 + score))) /
276 Math.pow(hoursElapsed + 2, 1.8);
278 // console.log(`Comment: ${comment.content}\nRank: ${rank}\nScore: ${comment.score}\nHours: ${hoursElapsed}`);
283 export function mdToHtml(text: string) {
284 return { __html: md.render(text) };
287 export function getUnixTime(text: string): number {
288 return text ? new Date(text).getTime() / 1000 : undefined;
291 export function futureDaysToUnixTime(days: number): number {
294 new Date(Date.now() + 1000 * 60 * 60 * 24 * days).getTime() / 1000
299 export function canMod(
300 myUserInfo: MyUserInfo,
305 // You can do moderator actions only on the mods added after you.
307 let yourIndex = modIds.findIndex(
308 id => id == myUserInfo.local_user_view.person.id
310 if (yourIndex == -1) {
313 // onSelf +1 on mod actions not for yourself, IE ban, remove, etc
314 modIds = modIds.slice(0, yourIndex + (onSelf ? 0 : 1));
315 return !modIds.includes(creator_id);
322 export function isMod(modIds: number[], creator_id: number): boolean {
323 return modIds.includes(creator_id);
326 const imageRegex = /(http)?s?:?(\/\/[^"']*\.(?:jpg|jpeg|gif|png|svg|webp))/;
327 const videoRegex = /(http)?s?:?(\/\/[^"']*\.(?:mp4|webm))/;
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")) {
556 } else if (lang.startsWith("as")) {
558 } else if (lang.startsWith("lt")) {
566 export function setTheme(theme: string, forceReload = false) {
570 if (theme === "browser" && !forceReload) {
573 // This is only run on a force reload
574 if (theme == "browser") {
578 // Unload all the other themes
579 for (var i = 0; i < themes.length; i++) {
580 let styleSheet = document.getElementById(themes[i]);
582 styleSheet.setAttribute("disabled", "disabled");
587 .getElementById("default-light")
588 ?.setAttribute("disabled", "disabled");
589 document.getElementById("default-dark")?.setAttribute("disabled", "disabled");
591 // Load the theme dynamically
592 let cssLoc = `/static/assets/css/themes/${theme}.min.css`;
593 loadCss(theme, cssLoc);
594 document.getElementById(theme).removeAttribute("disabled");
597 export function loadCss(id: string, loc: string) {
598 if (!document.getElementById(id)) {
599 var head = document.getElementsByTagName("head")[0];
600 var link = document.createElement("link");
602 link.rel = "stylesheet";
603 link.type = "text/css";
606 head.appendChild(link);
610 export function objectFlip(obj: any) {
612 Object.keys(obj).forEach(key => {
618 export function showAvatars(): boolean {
620 UserService.Instance.myUserInfo?.local_user_view.local_user.show_avatars ||
621 !UserService.Instance.myUserInfo
625 export function showScores(): boolean {
627 UserService.Instance.myUserInfo?.local_user_view.local_user.show_scores ||
628 !UserService.Instance.myUserInfo
632 export function isCakeDay(published: string): boolean {
633 // moment(undefined) or moment.utc(undefined) returns the current date/time
634 // moment(null) or moment.utc(null) returns null
635 const createDate = moment.utc(published || null).local();
636 const currentDate = moment(new Date());
639 createDate.date() === currentDate.date() &&
640 createDate.month() === currentDate.month() &&
641 createDate.year() !== currentDate.year()
645 export function toast(text: string, background = "success") {
647 let backgroundColor = `var(--${background})`;
650 backgroundColor: backgroundColor,
657 export function pictrsDeleteToast(
658 clickToDeleteText: string,
659 deletePictureText: string,
663 let backgroundColor = `var(--light)`;
664 let toast = Toastify({
665 text: clickToDeleteText,
666 backgroundColor: backgroundColor,
672 window.location.replace(deleteUrl);
673 alert(deletePictureText);
682 interface NotifyInfo {
689 export function messageToastify(info: NotifyInfo, router: any) {
691 let htmlBody = info.body ? md.render(info.body) : "";
692 let backgroundColor = `var(--light)`;
694 let toast = Toastify({
695 text: `${htmlBody}<br />${info.name}`,
696 avatar: info.icon ? info.icon : null,
697 backgroundColor: backgroundColor,
698 className: "text-dark",
707 router.history.push(info.link);
714 export function notifyPost(post_view: PostView, router: any) {
715 let info: NotifyInfo = {
716 name: post_view.community.name,
717 icon: post_view.community.icon,
718 link: `/post/${post_view.post.id}`,
719 body: post_view.post.name,
721 notify(info, router);
724 export function notifyComment(comment_view: CommentView, router: any) {
725 let info: NotifyInfo = {
726 name: comment_view.creator.name,
727 icon: comment_view.creator.avatar,
728 link: `/post/${comment_view.post.id}/comment/${comment_view.comment.id}`,
729 body: comment_view.comment.content,
731 notify(info, router);
734 export function notifyPrivateMessage(pmv: PrivateMessageView, router: any) {
735 let info: NotifyInfo = {
736 name: pmv.creator.name,
737 icon: pmv.creator.avatar,
739 body: pmv.private_message.content,
741 notify(info, router);
744 function notify(info: NotifyInfo, router: any) {
745 messageToastify(info, router);
747 // TODO absolute nightmare bug, but notifs are currently broken.
748 // Notification.new will try to do a browser fetch ???
750 // if (Notification.permission !== "granted") Notification.requestPermission();
752 // var notification = new Notification(info.name, {
757 // notification.onclick = (ev: Event): any => {
758 // ev.preventDefault();
759 // router.history.push(info.link);
764 export function setupTribute() {
766 noMatchTemplate: function () {
773 menuItemTemplate: (item: any) => {
774 let shortName = `:${item.original.key}:`;
775 return `${item.original.val} ${shortName}`;
777 selectTemplate: (item: any) => {
778 return `${item.original.val}`;
780 values: Object.entries(emojiShortName).map(e => {
781 return { key: e[1], val: e[0] };
784 autocompleteMode: true,
786 // menuItemLimit: mentionDropdownFetchLimit,
787 menuShowMinLength: 2,
792 selectTemplate: (item: any) => {
793 let it: PersonTribute = item.original;
794 return `[${it.key}](${it.view.person.actor_id})`;
796 values: (text: string, cb: (persons: PersonTribute[]) => any) => {
797 personSearch(text, (persons: PersonTribute[]) => cb(persons));
800 autocompleteMode: true,
802 // menuItemLimit: mentionDropdownFetchLimit,
803 menuShowMinLength: 2,
809 selectTemplate: (item: any) => {
810 let it: CommunityTribute = item.original;
811 return `[${it.key}](${it.view.community.actor_id})`;
813 values: (text: string, cb: any) => {
814 communitySearch(text, (communities: CommunityTribute[]) =>
819 autocompleteMode: true,
821 // menuItemLimit: mentionDropdownFetchLimit,
822 menuShowMinLength: 2,
828 var tippyInstance: any;
830 tippyInstance = tippy("[data-tippy-content]");
833 export function setupTippy() {
835 tippyInstance.forEach((e: any) => e.destroy());
836 tippyInstance = tippy("[data-tippy-content]", {
838 // Display on "long press"
839 touch: ["hold", 500],
844 interface PersonTribute {
846 view: PersonViewSafe;
849 function personSearch(text: string, cb: (persons: PersonTribute[]) => any) {
853 type_: SearchType.Users,
854 sort: SortType.TopAll,
855 listing_type: ListingType.All,
857 limit: mentionDropdownFetchLimit,
858 auth: authField(false),
861 WebSocketService.Instance.send(wsClient.search(form));
863 let personSub = WebSocketService.Instance.subject.subscribe(
865 let res = wsJsonToRes(msg);
866 if (res.op == UserOperation.Search) {
867 let data = res.data as SearchResponse;
868 let persons: PersonTribute[] = data.users.map(pv => {
869 let tribute: PersonTribute = {
870 key: `@${pv.person.name}@${hostname(pv.person.actor_id)}`,
876 personSub.unsubscribe();
879 err => console.error(err),
880 () => console.log("complete")
887 interface CommunityTribute {
892 function communitySearch(
894 cb: (communities: CommunityTribute[]) => any
899 type_: SearchType.Communities,
900 sort: SortType.TopAll,
901 listing_type: ListingType.All,
903 limit: mentionDropdownFetchLimit,
904 auth: authField(false),
907 WebSocketService.Instance.send(wsClient.search(form));
909 let communitySub = WebSocketService.Instance.subject.subscribe(
911 let res = wsJsonToRes(msg);
912 if (res.op == UserOperation.Search) {
913 let data = res.data as SearchResponse;
914 let communities: CommunityTribute[] = data.communities.map(cv => {
915 let tribute: CommunityTribute = {
916 key: `!${cv.community.name}@${hostname(cv.community.actor_id)}`,
922 communitySub.unsubscribe();
925 err => console.error(err),
926 () => console.log("complete")
933 export function getListingTypeFromProps(props: any): ListingType {
934 return props.match.params.listing_type
935 ? routeListingTypeToEnum(props.match.params.listing_type)
936 : UserService.Instance.myUserInfo
937 ? Object.values(ListingType)[
938 UserService.Instance.myUserInfo.local_user_view.local_user
939 .default_listing_type
944 export function getListingTypeFromPropsNoDefault(props: any): ListingType {
945 return props.match.params.listing_type
946 ? routeListingTypeToEnum(props.match.params.listing_type)
950 // TODO might need to add a user setting for this too
951 export function getDataTypeFromProps(props: any): DataType {
952 return props.match.params.data_type
953 ? routeDataTypeToEnum(props.match.params.data_type)
957 export function getSortTypeFromProps(props: any): SortType {
958 return props.match.params.sort
959 ? routeSortTypeToEnum(props.match.params.sort)
960 : UserService.Instance.myUserInfo
961 ? Object.values(SortType)[
962 UserService.Instance.myUserInfo.local_user_view.local_user
968 export function getPageFromProps(props: any): number {
969 return props.match.params.page ? Number(props.match.params.page) : 1;
972 export function getRecipientIdFromProps(props: any): number {
973 return props.match.params.recipient_id
974 ? Number(props.match.params.recipient_id)
978 export function getIdFromProps(props: any): number {
979 return Number(props.match.params.id);
982 export function getCommentIdFromProps(props: any): number {
983 return Number(props.match.params.comment_id);
986 export function getUsernameFromProps(props: any): string {
987 return props.match.params.username;
990 export function editCommentRes(data: CommentView, comments: CommentView[]) {
991 let found = comments.find(c => c.comment.id == data.comment.id);
993 found.comment.content = data.comment.content;
994 found.comment.updated = data.comment.updated;
995 found.comment.removed = data.comment.removed;
996 found.comment.deleted = data.comment.deleted;
997 found.counts.upvotes = data.counts.upvotes;
998 found.counts.downvotes = data.counts.downvotes;
999 found.counts.score = data.counts.score;
1003 export function saveCommentRes(data: CommentView, comments: CommentView[]) {
1004 let found = comments.find(c => c.comment.id == data.comment.id);
1006 found.saved = data.saved;
1010 export function updatePersonBlock(
1011 data: BlockPersonResponse
1012 ): PersonBlockView[] {
1014 UserService.Instance.myUserInfo.person_blocks.push({
1015 person: UserService.Instance.myUserInfo.local_user_view.person,
1016 target: data.person_view.person,
1018 toast(`${i18n.t("blocked")} ${data.person_view.person.name}`);
1020 UserService.Instance.myUserInfo.person_blocks =
1021 UserService.Instance.myUserInfo.person_blocks.filter(
1022 i => i.target.id != data.person_view.person.id
1024 toast(`${i18n.t("unblocked")} ${data.person_view.person.name}`);
1026 return UserService.Instance.myUserInfo.person_blocks;
1029 export function updateCommunityBlock(
1030 data: BlockCommunityResponse
1031 ): CommunityBlockView[] {
1033 UserService.Instance.myUserInfo.community_blocks.push({
1034 person: UserService.Instance.myUserInfo.local_user_view.person,
1035 community: data.community_view.community,
1037 toast(`${i18n.t("blocked")} ${data.community_view.community.name}`);
1039 UserService.Instance.myUserInfo.community_blocks =
1040 UserService.Instance.myUserInfo.community_blocks.filter(
1041 i => i.community.id != data.community_view.community.id
1043 toast(`${i18n.t("unblocked")} ${data.community_view.community.name}`);
1045 return UserService.Instance.myUserInfo.community_blocks;
1048 export function createCommentLikeRes(
1050 comments: CommentView[]
1052 let found = comments.find(c => c.comment.id === data.comment.id);
1054 found.counts.score = data.counts.score;
1055 found.counts.upvotes = data.counts.upvotes;
1056 found.counts.downvotes = data.counts.downvotes;
1057 if (data.my_vote !== null) {
1058 found.my_vote = data.my_vote;
1063 export function createPostLikeFindRes(data: PostView, posts: PostView[]) {
1064 let found = posts.find(p => p.post.id == data.post.id);
1066 createPostLikeRes(data, found);
1070 export function createPostLikeRes(data: PostView, post_view: PostView) {
1072 post_view.counts.score = data.counts.score;
1073 post_view.counts.upvotes = data.counts.upvotes;
1074 post_view.counts.downvotes = data.counts.downvotes;
1075 if (data.my_vote !== null) {
1076 post_view.my_vote = data.my_vote;
1081 export function editPostFindRes(data: PostView, posts: PostView[]) {
1082 let found = posts.find(p => p.post.id == data.post.id);
1084 editPostRes(data, found);
1088 export function editPostRes(data: PostView, post: PostView) {
1090 post.post.url = data.post.url;
1091 post.post.name = data.post.name;
1092 post.post.nsfw = data.post.nsfw;
1093 post.post.deleted = data.post.deleted;
1094 post.post.removed = data.post.removed;
1095 post.post.stickied = data.post.stickied;
1096 post.post.body = data.post.body;
1097 post.post.locked = data.post.locked;
1098 post.saved = data.saved;
1102 export function updatePostReportRes(
1103 data: PostReportView,
1104 reports: PostReportView[]
1106 let found = reports.find(p => p.post.id == data.post.id);
1108 found.post_report = data.post_report;
1112 export function updateCommentReportRes(
1113 data: CommentReportView,
1114 reports: CommentReportView[]
1116 let found = reports.find(c => c.comment.id == data.comment.id);
1118 found.comment_report = data.comment_report;
1122 export function updateRegistrationApplicationRes(
1123 data: RegistrationApplicationView,
1124 applications: RegistrationApplicationView[]
1126 let found = applications.find(
1127 ra => ra.registration_application.id == data.registration_application.id
1130 found.registration_application = data.registration_application;
1131 found.admin = data.admin;
1132 found.creator_local_user = data.creator_local_user;
1136 export function commentsToFlatNodes(comments: CommentView[]): CommentNodeI[] {
1137 let nodes: CommentNodeI[] = [];
1138 for (let comment of comments) {
1139 nodes.push({ comment_view: comment });
1144 function commentSort(tree: CommentNodeI[], sort: CommentSortType) {
1145 // First, put removed and deleted comments at the bottom, then do your other sorts
1146 if (sort == CommentSortType.Top) {
1149 +a.comment_view.comment.removed - +b.comment_view.comment.removed ||
1150 +a.comment_view.comment.deleted - +b.comment_view.comment.deleted ||
1151 b.comment_view.counts.score - a.comment_view.counts.score
1153 } else if (sort == CommentSortType.New) {
1156 +a.comment_view.comment.removed - +b.comment_view.comment.removed ||
1157 +a.comment_view.comment.deleted - +b.comment_view.comment.deleted ||
1158 b.comment_view.comment.published.localeCompare(
1159 a.comment_view.comment.published
1162 } else if (sort == CommentSortType.Old) {
1165 +a.comment_view.comment.removed - +b.comment_view.comment.removed ||
1166 +a.comment_view.comment.deleted - +b.comment_view.comment.deleted ||
1167 a.comment_view.comment.published.localeCompare(
1168 b.comment_view.comment.published
1171 } else if (sort == CommentSortType.Hot) {
1174 +a.comment_view.comment.removed - +b.comment_view.comment.removed ||
1175 +a.comment_view.comment.deleted - +b.comment_view.comment.deleted ||
1176 hotRankComment(b.comment_view) - hotRankComment(a.comment_view)
1180 // Go through the children recursively
1181 for (let node of tree) {
1182 if (node.children) {
1183 commentSort(node.children, sort);
1188 export function commentSortSortType(tree: CommentNodeI[], sort: SortType) {
1189 commentSort(tree, convertCommentSortType(sort));
1192 function convertCommentSortType(sort: SortType): CommentSortType {
1194 sort == SortType.TopAll ||
1195 sort == SortType.TopDay ||
1196 sort == SortType.TopWeek ||
1197 sort == SortType.TopMonth ||
1198 sort == SortType.TopYear
1200 return CommentSortType.Top;
1201 } else if (sort == SortType.New) {
1202 return CommentSortType.New;
1203 } else if (sort == SortType.Hot || sort == SortType.Active) {
1204 return CommentSortType.Hot;
1206 return CommentSortType.Hot;
1210 export function buildCommentsTree(
1211 comments: CommentView[],
1212 commentSortType: CommentSortType
1214 let map = new Map<number, CommentNodeI>();
1215 for (let comment_view of comments) {
1216 let node: CommentNodeI = {
1217 comment_view: comment_view,
1220 map.set(comment_view.comment.id, { ...node });
1222 let tree: CommentNodeI[] = [];
1223 for (let comment_view of comments) {
1224 let child = map.get(comment_view.comment.id);
1225 let parent_id = comment_view.comment.parent_id;
1227 let parent = map.get(parent_id);
1228 // Necessary because blocked comment might not exist
1230 parent.children.push(child);
1239 commentSort(tree, commentSortType);
1244 function setDepth(node: CommentNodeI, i = 0) {
1245 for (let child of node.children) {
1247 setDepth(child, i + 1);
1251 export function insertCommentIntoTree(tree: CommentNodeI[], cv: CommentView) {
1252 // Building a fake node to be used for later
1253 let node: CommentNodeI = {
1259 if (cv.comment.parent_id) {
1260 let parentComment = searchCommentTree(tree, cv.comment.parent_id);
1261 if (parentComment) {
1262 node.depth = parentComment.depth + 1;
1263 parentComment.children.unshift(node);
1270 export function searchCommentTree(
1271 tree: CommentNodeI[],
1274 for (let node of tree) {
1275 if (node.comment_view.comment.id === id) {
1279 for (const child of node.children) {
1280 const res = searchCommentTree([child], id);
1290 export const colorList: string[] = [
1299 function hsl(num: number) {
1300 return `hsla(${num}, 35%, 50%, 1)`;
1303 export function previewLines(
1312 // Use lines * 2 because markdown requires 2 lines
1313 .slice(0, maxLines * 2)
1318 export function hostname(url: string): string {
1319 let cUrl = new URL(url);
1320 return cUrl.port ? `${cUrl.hostname}:${cUrl.port}` : `${cUrl.hostname}`;
1323 export function validTitle(title?: string): boolean {
1324 // Initial title is null, minimum length is taken care of by textarea's minLength={3}
1325 if (title === null || title.length < 3) return true;
1327 const regex = new RegExp(/.*\S.*/, "g");
1329 return regex.test(title);
1332 export function siteBannerCss(banner: string): string {
1334 background-image: linear-gradient( rgba(0, 0, 0, 0.8), rgba(0, 0, 0, 0.8) ) ,url("${banner}"); \
1335 background-attachment: fixed; \
1336 background-position: top; \
1337 background-repeat: no-repeat; \
1338 background-size: 100% cover; \
1341 max-height: 100vh; \
1345 export function isBrowser() {
1346 return typeof window !== "undefined";
1349 export function setIsoData(context: any): IsoData {
1350 let isoData: IsoData = isBrowser()
1352 : context.router.staticContext;
1356 export function wsSubscribe(parseMessage: any): Subscription {
1358 return WebSocketService.Instance.subject
1359 .pipe(retryWhen(errors => errors.pipe(delay(3000), take(10))))
1361 msg => parseMessage(msg),
1362 err => console.error(err),
1363 () => console.log("complete")
1370 export function setOptionalAuth(obj: any, auth = UserService.Instance.auth) {
1376 export function authField(
1378 auth = UserService.Instance.auth
1380 if (auth == null && throwErr) {
1381 toast(i18n.t("not_logged_in"), "danger");
1382 throw "Not logged in";
1388 moment.updateLocale("en", {
1409 export function saveScrollPosition(context: any) {
1410 let path: string = context.router.route.location.pathname;
1411 let y = window.scrollY;
1412 sessionStorage.setItem(`scrollPosition_${path}`, y.toString());
1415 export function restoreScrollPosition(context: any) {
1416 let path: string = context.router.route.location.pathname;
1417 let y = Number(sessionStorage.getItem(`scrollPosition_${path}`));
1418 window.scrollTo(0, y);
1421 export function showLocal(isoData: IsoData): boolean {
1422 return isoData.site_res.federated_instances?.linked.length > 0;
1425 interface ChoicesValue {
1430 export function communityToChoice(cv: CommunityView): ChoicesValue {
1431 let choice: ChoicesValue = {
1432 value: cv.community.id.toString(),
1433 label: communitySelectName(cv),
1438 export function personToChoice(pvs: PersonViewSafe): ChoicesValue {
1439 let choice: ChoicesValue = {
1440 value: pvs.person.id.toString(),
1441 label: personSelectName(pvs),
1446 export async function fetchCommunities(q: string) {
1447 let form: Search = {
1449 type_: SearchType.Communities,
1450 sort: SortType.TopAll,
1451 listing_type: ListingType.All,
1454 auth: authField(false),
1456 let client = new LemmyHttp(httpBase);
1457 return client.search(form);
1460 export async function fetchUsers(q: string) {
1461 let form: Search = {
1463 type_: SearchType.Users,
1464 sort: SortType.TopAll,
1465 listing_type: ListingType.All,
1468 auth: authField(false),
1470 let client = new LemmyHttp(httpBase);
1471 return client.search(form);
1474 export const choicesConfig = {
1476 searchResultLimit: fetchLimit,
1478 containerOuter: "choices",
1479 containerInner: "choices__inner bg-secondary border-0",
1480 input: "form-control",
1481 inputCloned: "choices__input--cloned",
1482 list: "choices__list",
1483 listItems: "choices__list--multiple",
1484 listSingle: "choices__list--single",
1485 listDropdown: "choices__list--dropdown",
1486 item: "choices__item bg-secondary",
1487 itemSelectable: "choices__item--selectable",
1488 itemDisabled: "choices__item--disabled",
1489 itemChoice: "choices__item--choice",
1490 placeholder: "choices__placeholder",
1491 group: "choices__group",
1492 groupHeading: "choices__heading",
1493 button: "choices__button",
1494 activeState: "is-active",
1495 focusState: "is-focused",
1496 openState: "is-open",
1497 disabledState: "is-disabled",
1498 highlightedState: "text-info",
1499 selectedState: "text-info",
1500 flippedState: "is-flipped",
1501 loadingState: "is-loading",
1502 noResults: "has-no-results",
1503 noChoices: "has-no-choices",
1507 export function communitySelectName(cv: CommunityView): string {
1508 return cv.community.local
1509 ? cv.community.title
1510 : `${hostname(cv.community.actor_id)}/${cv.community.title}`;
1513 export function personSelectName(pvs: PersonViewSafe): string {
1514 let pName = pvs.person.display_name || pvs.person.name;
1515 return pvs.person.local ? pName : `${hostname(pvs.person.actor_id)}/${pName}`;
1518 export function initializeSite(site: GetSiteResponse) {
1519 UserService.Instance.myUserInfo = site.my_user;
1520 i18n.changeLanguage(getLanguage());
1523 const SHORTNUM_SI_FORMAT = new Intl.NumberFormat("en-US", {
1524 maximumSignificantDigits: 3,
1526 notation: "compact",
1527 compactDisplay: "short",
1530 export function numToSI(value: number): string {
1531 return SHORTNUM_SI_FORMAT.format(value);
1534 export function isBanned(ps: PersonSafe): boolean {
1535 // Add Z to convert from UTC date
1536 if (ps.ban_expires) {
1537 if (ps.banned && new Date(ps.ban_expires + "Z") > new Date()) {