1 import emojiShortName from "emoji-short-name";
2 import ISO6391 from "iso-639-1";
4 BlockCommunityResponse,
21 RegistrationApplicationView,
27 WebSocketJsonResponse,
29 } from "lemmy-js-client";
30 import markdown_it from "markdown-it";
31 import markdown_it_container from "markdown-it-container";
32 import markdown_it_html5_embed from "markdown-it-html5-embed";
33 import markdown_it_sub from "markdown-it-sub";
34 import markdown_it_sup from "markdown-it-sup";
35 import moment from "moment";
36 import "moment/locale/bg";
37 import "moment/locale/bn";
38 import "moment/locale/ca";
39 import "moment/locale/cs";
40 import "moment/locale/cy";
41 import "moment/locale/da";
42 import "moment/locale/de";
43 import "moment/locale/el";
44 import "moment/locale/eo";
45 import "moment/locale/es";
46 import "moment/locale/eu";
47 import "moment/locale/fa";
48 import "moment/locale/fi";
49 import "moment/locale/fr";
50 import "moment/locale/ga";
51 import "moment/locale/gl";
52 import "moment/locale/hi";
53 import "moment/locale/hr";
54 import "moment/locale/hu";
55 import "moment/locale/id";
56 import "moment/locale/it";
57 import "moment/locale/ja";
58 import "moment/locale/ka";
59 import "moment/locale/km";
60 import "moment/locale/ko";
61 import "moment/locale/ml";
62 import "moment/locale/nb";
63 import "moment/locale/nl";
64 import "moment/locale/pl";
65 import "moment/locale/pt-br";
66 import "moment/locale/ru";
67 import "moment/locale/sk";
68 import "moment/locale/sq";
69 import "moment/locale/sr";
70 import "moment/locale/sv";
71 import "moment/locale/tr";
72 import "moment/locale/uk";
73 import "moment/locale/vi";
74 import "moment/locale/zh-cn";
75 import { Subscription } from "rxjs";
76 import { delay, retryWhen, take } from "rxjs/operators";
77 import tippy from "tippy.js";
78 import Toastify from "toastify-js";
79 import { httpBase } from "./env";
80 import { i18n } from "./i18next";
82 CommentNode as CommentNodeI,
86 } from "./interfaces";
87 import { UserService, WebSocketService } from "./services";
91 Tribute = require("tributejs");
94 export const wsClient = new LemmyWebsocket();
96 export const favIconUrl = "/static/assets/icons/favicon.svg";
97 export const favIconPngUrl = "/static/assets/icons/apple-touch-icon.png";
99 // export const defaultFavIcon = `${window.location.protocol}//${window.location.host}${favIconPngUrl}`;
100 export const repoUrl = "https://github.com/LemmyNet";
101 export const joinLemmyUrl = "https://join-lemmy.org";
102 export const donateLemmyUrl = `${joinLemmyUrl}/donate`;
103 export const docsUrl = `${joinLemmyUrl}/docs/en/index.html`;
104 export const helpGuideUrl = `${joinLemmyUrl}/docs/en/about/guide.html`; // TODO find a way to redirect to the non-en folder
105 export const markdownHelpUrl = `${helpGuideUrl}#using-markdown`;
106 export const sortingHelpUrl = `${helpGuideUrl}#sorting`;
107 export const archiveTodayUrl = "https://archive.today";
108 export const ghostArchiveUrl = "https://ghostarchive.org";
109 export const webArchiveUrl = "https://web.archive.org";
110 export const elementUrl = "https://element.io";
112 export const postRefetchSeconds: number = 60 * 1000;
113 export const fetchLimit = 20;
114 export const mentionDropdownFetchLimit = 10;
116 export const languages = [
165 export const themes = [
182 const DEFAULT_ALPHABET =
183 "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
185 function getRandomCharFromAlphabet(alphabet: string): string {
186 return alphabet.charAt(Math.floor(Math.random() * alphabet.length));
189 export function randomStr(
190 idDesiredLength = 20,
191 alphabet = DEFAULT_ALPHABET
194 * Create n-long array and map it to random chars from given alphabet.
195 * Then join individual chars as string
197 return Array.from({ length: idDesiredLength })
199 return getRandomCharFromAlphabet(alphabet);
204 export function wsJsonToRes<ResponseType>(
205 msg: WebSocketJsonResponse<ResponseType>
206 ): WebSocketResponse<ResponseType> {
213 export function wsUserOp(msg: any): UserOperation {
214 let opStr: string = msg.op;
215 return UserOperation[opStr];
218 export const md = new markdown_it({
223 .use(markdown_it_sub)
224 .use(markdown_it_sup)
225 .use(markdown_it_html5_embed, {
227 useImageSyntax: true, // Enables video/audio embed with ![]() syntax (default)
229 audio: 'controls preload="metadata"',
231 'width="100%" max-height="100%" controls loop preload="metadata"',
235 .use(markdown_it_container, "spoiler", {
236 validate: function (params: any) {
237 return params.trim().match(/^spoiler\s+(.*)$/);
240 render: function (tokens: any, idx: any) {
241 var m = tokens[idx].info.trim().match(/^spoiler\s+(.*)$/);
243 if (tokens[idx].nesting === 1) {
245 return `<details><summary> ${md.utils.escapeHtml(m[1])} </summary>\n`;
248 return "</details>\n";
253 export function hotRankComment(comment_view: CommentView): number {
254 return hotRank(comment_view.counts.score, comment_view.comment.published);
257 export function hotRankActivePost(post_view: PostView): number {
258 return hotRank(post_view.counts.score, post_view.counts.newest_comment_time);
261 export function hotRankPost(post_view: PostView): number {
262 return hotRank(post_view.counts.score, post_view.post.published);
265 export function hotRank(score: number, timeStr: string): number {
266 // Rank = ScaleFactor * sign(Score) * log(1 + abs(Score)) / (Time + 2)^Gravity
267 let date: Date = new Date(timeStr + "Z"); // Add Z to convert from UTC date
268 let now: Date = new Date();
269 let hoursElapsed: number = (now.getTime() - date.getTime()) / 36e5;
272 (10000 * Math.log10(Math.max(1, 3 + score))) /
273 Math.pow(hoursElapsed + 2, 1.8);
275 // console.log(`Comment: ${comment.content}\nRank: ${rank}\nScore: ${comment.score}\nHours: ${hoursElapsed}`);
280 export function mdToHtml(text: string) {
281 return { __html: md.render(text) };
284 export function getUnixTime(text: string): number {
285 return text ? new Date(text).getTime() / 1000 : undefined;
288 export function canMod(
289 myUserInfo: MyUserInfo,
294 // You can do moderator actions only on the mods added after you.
296 let yourIndex = modIds.findIndex(
297 id => id == myUserInfo.local_user_view.person.id
299 if (yourIndex == -1) {
302 // onSelf +1 on mod actions not for yourself, IE ban, remove, etc
303 modIds = modIds.slice(0, yourIndex + (onSelf ? 0 : 1));
304 return !modIds.includes(creator_id);
311 export function isMod(modIds: number[], creator_id: number): boolean {
312 return modIds.includes(creator_id);
315 const imageRegex = new RegExp(
316 /(http)?s?:?(\/\/[^"']*\.(?:jpg|jpeg|gif|png|svg|webp))/
318 const videoRegex = new RegExp(`(http)?s?:?(\/\/[^"']*\.(?:mp4))`);
320 export function isImage(url: string) {
321 return imageRegex.test(url);
324 export function isVideo(url: string) {
325 return videoRegex.test(url);
328 export function validURL(str: string) {
329 return !!new URL(str);
332 export function communityRSSUrl(actorId: string, sort: string): string {
333 let url = new URL(actorId);
334 return `${url.origin}/feeds${url.pathname}.xml?sort=${sort}`;
337 export function validEmail(email: string) {
339 /^(([^\s"(),.:;<>@[\\\]]+(\.[^\s"(),.:;<>@[\\\]]+)*)|(".+"))@((\[(?:\d{1,3}\.){3}\d{1,3}])|(([\dA-Za-z\-]+\.)+[A-Za-z]{2,}))$/;
340 return re.test(String(email).toLowerCase());
343 export function capitalizeFirstLetter(str: string): string {
344 return str.charAt(0).toUpperCase() + str.slice(1);
347 export function routeSortTypeToEnum(sort: string): SortType {
348 return SortType[sort];
351 export function listingTypeFromNum(type_: number): ListingType {
352 return Object.values(ListingType)[type_];
355 export function sortTypeFromNum(type_: number): SortType {
356 return Object.values(SortType)[type_];
359 export function routeListingTypeToEnum(type: string): ListingType {
360 return ListingType[type];
363 export function routeDataTypeToEnum(type: string): DataType {
364 return DataType[capitalizeFirstLetter(type)];
367 export function routeSearchTypeToEnum(type: string): SearchType {
368 return SearchType[type];
371 export async function getSiteMetadata(url: string) {
372 let form: GetSiteMetadata = {
375 let client = new LemmyHttp(httpBase);
376 return client.getSiteMetadata(form);
379 export function debounce(func: any, wait = 1000, immediate = false) {
380 // 'private' variable for instance
381 // The returned function will be able to reference this due to closure.
382 // Each call to the returned function will share this common timer.
385 // Calling debounce returns a new anonymous function
387 // reference the context and args for the setTimeout function
388 var args = arguments;
390 // Should the function be called now? If immediate is true
391 // and not already in a timeout then the answer is: Yes
392 var callNow = immediate && !timeout;
394 // This is the basic debounce behaviour where you can call this
395 // function several times, but it will only execute once
396 // [before or after imposing a delay].
397 // Each time the returned function is called, the timer starts over.
398 clearTimeout(timeout);
400 // Set the new timeout
401 timeout = setTimeout(function () {
402 // Inside the timeout function, clear the timeout variable
403 // which will let the next execution run when in 'immediate' mode
406 // Check if the function already ran with the immediate flag
408 // Call the original function with apply
409 // apply lets you define the 'this' object as well as the arguments
410 // (both captured before setTimeout)
411 func.apply(this, args);
415 // Immediate mode and no wait timer? Execute the function..
416 if (callNow) func.apply(this, args);
420 export function getNativeLanguageName(code: string): string {
421 let [isoCode, qualifier] = code.split("_");
423 let native = ISO6391.getNativeName(isoCode) || code;
426 return `${native}_${qualifier}`;
433 export function getLanguage(override?: string): string {
434 let myUserInfo = UserService.Instance.myUserInfo;
437 (myUserInfo?.local_user_view.local_user.lang
438 ? myUserInfo.local_user_view.local_user.lang
441 if (lang == "browser" && isBrowser()) {
442 return getBrowserLanguage();
448 export function getBrowserLanguage(): string {
449 // Intersect lemmy's langs, with the browser langs
450 let langs = languages ? languages.map(l => l.code) : ["en"];
452 // NOTE, mobile browsers seem to be missing this list, so append en
453 let allowedLangs = navigator.languages
455 .filter(v => langs.includes(v));
456 return allowedLangs[0];
459 export function getMomentLanguage(): string {
460 let lang = getLanguage();
461 if (lang.startsWith("zh")) {
463 } else if (lang.startsWith("sv")) {
465 } else if (lang.startsWith("fr")) {
467 } else if (lang.startsWith("de")) {
469 } else if (lang.startsWith("ru")) {
471 } else if (lang.startsWith("es")) {
473 } else if (lang.startsWith("eo")) {
475 } else if (lang.startsWith("nl")) {
477 } else if (lang.startsWith("it")) {
479 } else if (lang.startsWith("fi")) {
481 } else if (lang.startsWith("ca")) {
483 } else if (lang.startsWith("fa")) {
485 } else if (lang.startsWith("pl")) {
487 } else if (lang.startsWith("pt_BR")) {
489 } else if (lang.startsWith("ja")) {
491 } else if (lang.startsWith("ka")) {
493 } else if (lang.startsWith("hi")) {
495 } else if (lang.startsWith("el")) {
497 } else if (lang.startsWith("eu")) {
499 } else if (lang.startsWith("gl")) {
501 } else if (lang.startsWith("tr")) {
503 } else if (lang.startsWith("hu")) {
505 } else if (lang.startsWith("uk")) {
507 } else if (lang.startsWith("sq")) {
509 } else if (lang.startsWith("km")) {
511 } else if (lang.startsWith("ga")) {
513 } else if (lang.startsWith("sr")) {
515 } else if (lang.startsWith("ko")) {
517 } else if (lang.startsWith("da")) {
519 } else if (lang.startsWith("oc")) {
521 } else if (lang.startsWith("hr")) {
523 } else if (lang.startsWith("th")) {
525 } else if (lang.startsWith("bg")) {
527 } else if (lang.startsWith("id")) {
529 } else if (lang.startsWith("nb")) {
531 } else if (lang.startsWith("cy")) {
533 } else if (lang.startsWith("sk")) {
535 } else if (lang.startsWith("vi")) {
537 } else if (lang.startsWith("pt")) {
539 } else if (lang.startsWith("ar")) {
541 } else if (lang.startsWith("bn")) {
543 } else if (lang.startsWith("ml")) {
545 } else if (lang.startsWith("cs")) {
553 export function setTheme(theme: string, forceReload = false) {
557 if (theme === "browser" && !forceReload) {
560 // This is only run on a force reload
561 if (theme == "browser") {
565 // Unload all the other themes
566 for (var i = 0; i < themes.length; i++) {
567 let styleSheet = document.getElementById(themes[i]);
569 styleSheet.setAttribute("disabled", "disabled");
574 .getElementById("default-light")
575 ?.setAttribute("disabled", "disabled");
576 document.getElementById("default-dark")?.setAttribute("disabled", "disabled");
578 // Load the theme dynamically
579 let cssLoc = `/static/assets/css/themes/${theme}.min.css`;
580 loadCss(theme, cssLoc);
581 document.getElementById(theme).removeAttribute("disabled");
584 export function loadCss(id: string, loc: string) {
585 if (!document.getElementById(id)) {
586 var head = document.getElementsByTagName("head")[0];
587 var link = document.createElement("link");
589 link.rel = "stylesheet";
590 link.type = "text/css";
593 head.appendChild(link);
597 export function objectFlip(obj: any) {
599 Object.keys(obj).forEach(key => {
605 export function showAvatars(): boolean {
607 UserService.Instance.myUserInfo?.local_user_view.local_user.show_avatars ||
608 !UserService.Instance.myUserInfo
612 export function showScores(): boolean {
614 UserService.Instance.myUserInfo?.local_user_view.local_user.show_scores ||
615 !UserService.Instance.myUserInfo
619 export function isCakeDay(published: string): boolean {
620 // moment(undefined) or moment.utc(undefined) returns the current date/time
621 // moment(null) or moment.utc(null) returns null
622 const createDate = moment.utc(published || null).local();
623 const currentDate = moment(new Date());
626 createDate.date() === currentDate.date() &&
627 createDate.month() === currentDate.month() &&
628 createDate.year() !== currentDate.year()
632 export function toast(text: string, background = "success") {
634 let backgroundColor = `var(--${background})`;
637 backgroundColor: backgroundColor,
644 export function pictrsDeleteToast(
645 clickToDeleteText: string,
646 deletePictureText: string,
650 let backgroundColor = `var(--light)`;
651 let toast = Toastify({
652 text: clickToDeleteText,
653 backgroundColor: backgroundColor,
659 window.location.replace(deleteUrl);
660 alert(deletePictureText);
669 interface NotifyInfo {
676 export function messageToastify(info: NotifyInfo, router: any) {
678 let htmlBody = info.body ? md.render(info.body) : "";
679 let backgroundColor = `var(--light)`;
681 let toast = Toastify({
682 text: `${htmlBody}<br />${info.name}`,
683 avatar: info.icon ? info.icon : null,
684 backgroundColor: backgroundColor,
685 className: "text-dark",
694 router.history.push(info.link);
701 export function notifyPost(post_view: PostView, router: any) {
702 let info: NotifyInfo = {
703 name: post_view.community.name,
704 icon: post_view.community.icon,
705 link: `/post/${post_view.post.id}`,
706 body: post_view.post.name,
708 notify(info, router);
711 export function notifyComment(comment_view: CommentView, router: any) {
712 let info: NotifyInfo = {
713 name: comment_view.creator.name,
714 icon: comment_view.creator.avatar,
715 link: `/post/${comment_view.post.id}/comment/${comment_view.comment.id}`,
716 body: comment_view.comment.content,
718 notify(info, router);
721 export function notifyPrivateMessage(pmv: PrivateMessageView, router: any) {
722 let info: NotifyInfo = {
723 name: pmv.creator.name,
724 icon: pmv.creator.avatar,
726 body: pmv.private_message.content,
728 notify(info, router);
731 function notify(info: NotifyInfo, router: any) {
732 messageToastify(info, router);
734 // TODO absolute nightmare bug, but notifs are currently broken.
735 // Notification.new will try to do a browser fetch ???
737 // if (Notification.permission !== "granted") Notification.requestPermission();
739 // var notification = new Notification(info.name, {
744 // notification.onclick = (ev: Event): any => {
745 // ev.preventDefault();
746 // router.history.push(info.link);
751 export function setupTribute() {
753 noMatchTemplate: function () {
760 menuItemTemplate: (item: any) => {
761 let shortName = `:${item.original.key}:`;
762 return `${item.original.val} ${shortName}`;
764 selectTemplate: (item: any) => {
765 return `${item.original.val}`;
767 values: Object.entries(emojiShortName).map(e => {
768 return { key: e[1], val: e[0] };
771 autocompleteMode: true,
773 // menuItemLimit: mentionDropdownFetchLimit,
774 menuShowMinLength: 2,
779 selectTemplate: (item: any) => {
780 let it: PersonTribute = item.original;
781 return `[${it.key}](${it.view.person.actor_id})`;
783 values: (text: string, cb: (persons: PersonTribute[]) => any) => {
784 personSearch(text, (persons: PersonTribute[]) => cb(persons));
787 autocompleteMode: true,
789 // menuItemLimit: mentionDropdownFetchLimit,
790 menuShowMinLength: 2,
796 selectTemplate: (item: any) => {
797 let it: CommunityTribute = item.original;
798 return `[${it.key}](${it.view.community.actor_id})`;
800 values: (text: string, cb: any) => {
801 communitySearch(text, (communities: CommunityTribute[]) =>
806 autocompleteMode: true,
808 // menuItemLimit: mentionDropdownFetchLimit,
809 menuShowMinLength: 2,
815 var tippyInstance: any;
817 tippyInstance = tippy("[data-tippy-content]");
820 export function setupTippy() {
822 tippyInstance.forEach((e: any) => e.destroy());
823 tippyInstance = tippy("[data-tippy-content]", {
825 // Display on "long press"
826 touch: ["hold", 500],
831 interface PersonTribute {
833 view: PersonViewSafe;
836 function personSearch(text: string, cb: (persons: PersonTribute[]) => any) {
840 type_: SearchType.Users,
841 sort: SortType.TopAll,
842 listing_type: ListingType.All,
844 limit: mentionDropdownFetchLimit,
845 auth: authField(false),
848 WebSocketService.Instance.send(wsClient.search(form));
850 let personSub = WebSocketService.Instance.subject.subscribe(
852 let res = wsJsonToRes(msg);
853 if (res.op == UserOperation.Search) {
854 let data = res.data as SearchResponse;
855 let persons: PersonTribute[] = data.users.map(pv => {
856 let tribute: PersonTribute = {
857 key: `@${pv.person.name}@${hostname(pv.person.actor_id)}`,
863 personSub.unsubscribe();
866 err => console.error(err),
867 () => console.log("complete")
874 interface CommunityTribute {
879 function communitySearch(
881 cb: (communities: CommunityTribute[]) => any
886 type_: SearchType.Communities,
887 sort: SortType.TopAll,
888 listing_type: ListingType.All,
890 limit: mentionDropdownFetchLimit,
891 auth: authField(false),
894 WebSocketService.Instance.send(wsClient.search(form));
896 let communitySub = WebSocketService.Instance.subject.subscribe(
898 let res = wsJsonToRes(msg);
899 if (res.op == UserOperation.Search) {
900 let data = res.data as SearchResponse;
901 let communities: CommunityTribute[] = data.communities.map(cv => {
902 let tribute: CommunityTribute = {
903 key: `!${cv.community.name}@${hostname(cv.community.actor_id)}`,
909 communitySub.unsubscribe();
912 err => console.error(err),
913 () => console.log("complete")
920 export function getListingTypeFromProps(props: any): ListingType {
921 return props.match.params.listing_type
922 ? routeListingTypeToEnum(props.match.params.listing_type)
923 : UserService.Instance.myUserInfo
924 ? Object.values(ListingType)[
925 UserService.Instance.myUserInfo.local_user_view.local_user
926 .default_listing_type
931 export function getListingTypeFromPropsNoDefault(props: any): ListingType {
932 return props.match.params.listing_type
933 ? routeListingTypeToEnum(props.match.params.listing_type)
937 // TODO might need to add a user setting for this too
938 export function getDataTypeFromProps(props: any): DataType {
939 return props.match.params.data_type
940 ? routeDataTypeToEnum(props.match.params.data_type)
944 export function getSortTypeFromProps(props: any): SortType {
945 return props.match.params.sort
946 ? routeSortTypeToEnum(props.match.params.sort)
947 : UserService.Instance.myUserInfo
948 ? Object.values(SortType)[
949 UserService.Instance.myUserInfo.local_user_view.local_user
955 export function getPageFromProps(props: any): number {
956 return props.match.params.page ? Number(props.match.params.page) : 1;
959 export function getRecipientIdFromProps(props: any): number {
960 return props.match.params.recipient_id
961 ? Number(props.match.params.recipient_id)
965 export function getIdFromProps(props: any): number {
966 return Number(props.match.params.id);
969 export function getCommentIdFromProps(props: any): number {
970 return Number(props.match.params.comment_id);
973 export function getUsernameFromProps(props: any): string {
974 return props.match.params.username;
977 export function editCommentRes(data: CommentView, comments: CommentView[]) {
978 let found = comments.find(c => c.comment.id == data.comment.id);
980 found.comment.content = data.comment.content;
981 found.comment.updated = data.comment.updated;
982 found.comment.removed = data.comment.removed;
983 found.comment.deleted = data.comment.deleted;
984 found.counts.upvotes = data.counts.upvotes;
985 found.counts.downvotes = data.counts.downvotes;
986 found.counts.score = data.counts.score;
990 export function saveCommentRes(data: CommentView, comments: CommentView[]) {
991 let found = comments.find(c => c.comment.id == data.comment.id);
993 found.saved = data.saved;
997 export function updatePersonBlock(
998 data: BlockPersonResponse
999 ): PersonBlockView[] {
1001 UserService.Instance.myUserInfo.person_blocks.push({
1002 person: UserService.Instance.myUserInfo.local_user_view.person,
1003 target: data.person_view.person,
1005 toast(`${i18n.t("blocked")} ${data.person_view.person.name}`);
1007 UserService.Instance.myUserInfo.person_blocks =
1008 UserService.Instance.myUserInfo.person_blocks.filter(
1009 i => i.target.id != data.person_view.person.id
1011 toast(`${i18n.t("unblocked")} ${data.person_view.person.name}`);
1013 return UserService.Instance.myUserInfo.person_blocks;
1016 export function updateCommunityBlock(
1017 data: BlockCommunityResponse
1018 ): CommunityBlockView[] {
1020 UserService.Instance.myUserInfo.community_blocks.push({
1021 person: UserService.Instance.myUserInfo.local_user_view.person,
1022 community: data.community_view.community,
1024 toast(`${i18n.t("blocked")} ${data.community_view.community.name}`);
1026 UserService.Instance.myUserInfo.community_blocks =
1027 UserService.Instance.myUserInfo.community_blocks.filter(
1028 i => i.community.id != data.community_view.community.id
1030 toast(`${i18n.t("unblocked")} ${data.community_view.community.name}`);
1032 return UserService.Instance.myUserInfo.community_blocks;
1035 export function createCommentLikeRes(
1037 comments: CommentView[]
1039 let found = comments.find(c => c.comment.id === data.comment.id);
1041 found.counts.score = data.counts.score;
1042 found.counts.upvotes = data.counts.upvotes;
1043 found.counts.downvotes = data.counts.downvotes;
1044 if (data.my_vote !== null) {
1045 found.my_vote = data.my_vote;
1050 export function createPostLikeFindRes(data: PostView, posts: PostView[]) {
1051 let found = posts.find(p => p.post.id == data.post.id);
1053 createPostLikeRes(data, found);
1057 export function createPostLikeRes(data: PostView, post_view: PostView) {
1059 post_view.counts.score = data.counts.score;
1060 post_view.counts.upvotes = data.counts.upvotes;
1061 post_view.counts.downvotes = data.counts.downvotes;
1062 if (data.my_vote !== null) {
1063 post_view.my_vote = data.my_vote;
1068 export function editPostFindRes(data: PostView, posts: PostView[]) {
1069 let found = posts.find(p => p.post.id == data.post.id);
1071 editPostRes(data, found);
1075 export function editPostRes(data: PostView, post: PostView) {
1077 post.post.url = data.post.url;
1078 post.post.name = data.post.name;
1079 post.post.nsfw = data.post.nsfw;
1080 post.post.deleted = data.post.deleted;
1081 post.post.removed = data.post.removed;
1082 post.post.stickied = data.post.stickied;
1083 post.post.body = data.post.body;
1084 post.post.locked = data.post.locked;
1085 post.saved = data.saved;
1089 export function updatePostReportRes(
1090 data: PostReportView,
1091 reports: PostReportView[]
1093 let found = reports.find(p => p.post.id == data.post.id);
1095 found.post_report = data.post_report;
1099 export function updateCommentReportRes(
1100 data: CommentReportView,
1101 reports: CommentReportView[]
1103 let found = reports.find(c => c.comment.id == data.comment.id);
1105 found.comment_report = data.comment_report;
1109 export function updateRegistrationApplicationRes(
1110 data: RegistrationApplicationView,
1111 applications: RegistrationApplicationView[]
1113 let found = applications.find(
1114 ra => ra.registration_application.id == data.registration_application.id
1117 found.registration_application = data.registration_application;
1118 found.admin = data.admin;
1119 found.creator_local_user = data.creator_local_user;
1123 export function commentsToFlatNodes(comments: CommentView[]): CommentNodeI[] {
1124 let nodes: CommentNodeI[] = [];
1125 for (let comment of comments) {
1126 nodes.push({ comment_view: comment });
1131 function commentSort(tree: CommentNodeI[], sort: CommentSortType) {
1132 // First, put removed and deleted comments at the bottom, then do your other sorts
1133 if (sort == CommentSortType.Top) {
1136 +a.comment_view.comment.removed - +b.comment_view.comment.removed ||
1137 +a.comment_view.comment.deleted - +b.comment_view.comment.deleted ||
1138 b.comment_view.counts.score - a.comment_view.counts.score
1140 } else if (sort == CommentSortType.New) {
1143 +a.comment_view.comment.removed - +b.comment_view.comment.removed ||
1144 +a.comment_view.comment.deleted - +b.comment_view.comment.deleted ||
1145 b.comment_view.comment.published.localeCompare(
1146 a.comment_view.comment.published
1149 } else if (sort == CommentSortType.Old) {
1152 +a.comment_view.comment.removed - +b.comment_view.comment.removed ||
1153 +a.comment_view.comment.deleted - +b.comment_view.comment.deleted ||
1154 a.comment_view.comment.published.localeCompare(
1155 b.comment_view.comment.published
1158 } else if (sort == CommentSortType.Hot) {
1161 +a.comment_view.comment.removed - +b.comment_view.comment.removed ||
1162 +a.comment_view.comment.deleted - +b.comment_view.comment.deleted ||
1163 hotRankComment(b.comment_view) - hotRankComment(a.comment_view)
1167 // Go through the children recursively
1168 for (let node of tree) {
1169 if (node.children) {
1170 commentSort(node.children, sort);
1175 export function commentSortSortType(tree: CommentNodeI[], sort: SortType) {
1176 commentSort(tree, convertCommentSortType(sort));
1179 function convertCommentSortType(sort: SortType): CommentSortType {
1181 sort == SortType.TopAll ||
1182 sort == SortType.TopDay ||
1183 sort == SortType.TopWeek ||
1184 sort == SortType.TopMonth ||
1185 sort == SortType.TopYear
1187 return CommentSortType.Top;
1188 } else if (sort == SortType.New) {
1189 return CommentSortType.New;
1190 } else if (sort == SortType.Hot || sort == SortType.Active) {
1191 return CommentSortType.Hot;
1193 return CommentSortType.Hot;
1197 export function buildCommentsTree(
1198 comments: CommentView[],
1199 commentSortType: CommentSortType
1201 let map = new Map<number, CommentNodeI>();
1202 for (let comment_view of comments) {
1203 let node: CommentNodeI = {
1204 comment_view: comment_view,
1207 map.set(comment_view.comment.id, { ...node });
1209 let tree: CommentNodeI[] = [];
1210 for (let comment_view of comments) {
1211 let child = map.get(comment_view.comment.id);
1212 let parent_id = comment_view.comment.parent_id;
1214 let parent = map.get(parent_id);
1215 // Necessary because blocked comment might not exist
1217 parent.children.push(child);
1226 commentSort(tree, commentSortType);
1231 function setDepth(node: CommentNodeI, i = 0) {
1232 for (let child of node.children) {
1234 setDepth(child, i + 1);
1238 export function insertCommentIntoTree(tree: CommentNodeI[], cv: CommentView) {
1239 // Building a fake node to be used for later
1240 let node: CommentNodeI = {
1246 if (cv.comment.parent_id) {
1247 let parentComment = searchCommentTree(tree, cv.comment.parent_id);
1248 if (parentComment) {
1249 node.depth = parentComment.depth + 1;
1250 parentComment.children.unshift(node);
1257 export function searchCommentTree(
1258 tree: CommentNodeI[],
1261 for (let node of tree) {
1262 if (node.comment_view.comment.id === id) {
1266 for (const child of node.children) {
1267 const res = searchCommentTree([child], id);
1277 export const colorList: string[] = [
1286 function hsl(num: number) {
1287 return `hsla(${num}, 35%, 50%, 1)`;
1290 export function previewLines(
1299 // Use lines * 2 because markdown requires 2 lines
1300 .slice(0, maxLines * 2)
1305 export function hostname(url: string): string {
1306 let cUrl = new URL(url);
1307 return cUrl.port ? `${cUrl.hostname}:${cUrl.port}` : `${cUrl.hostname}`;
1310 export function validTitle(title?: string): boolean {
1311 // Initial title is null, minimum length is taken care of by textarea's minLength={3}
1312 if (title === null || title.length < 3) return true;
1314 const regex = new RegExp(/.*\S.*/, "g");
1316 return regex.test(title);
1319 export function siteBannerCss(banner: string): string {
1321 background-image: linear-gradient( rgba(0, 0, 0, 0.8), rgba(0, 0, 0, 0.8) ) ,url("${banner}"); \
1322 background-attachment: fixed; \
1323 background-position: top; \
1324 background-repeat: no-repeat; \
1325 background-size: 100% cover; \
1328 max-height: 100vh; \
1332 export function isBrowser() {
1333 return typeof window !== "undefined";
1336 export function setIsoData(context: any): IsoData {
1337 let isoData: IsoData = isBrowser()
1339 : context.router.staticContext;
1343 export function wsSubscribe(parseMessage: any): Subscription {
1345 return WebSocketService.Instance.subject
1346 .pipe(retryWhen(errors => errors.pipe(delay(3000), take(10))))
1348 msg => parseMessage(msg),
1349 err => console.error(err),
1350 () => console.log("complete")
1357 export function setOptionalAuth(obj: any, auth = UserService.Instance.auth) {
1363 export function authField(
1365 auth = UserService.Instance.auth
1367 if (auth == null && throwErr) {
1368 toast(i18n.t("not_logged_in"), "danger");
1369 throw "Not logged in";
1375 moment.updateLocale("en", {
1396 export function saveScrollPosition(context: any) {
1397 let path: string = context.router.route.location.pathname;
1398 let y = window.scrollY;
1399 sessionStorage.setItem(`scrollPosition_${path}`, y.toString());
1402 export function restoreScrollPosition(context: any) {
1403 let path: string = context.router.route.location.pathname;
1404 let y = Number(sessionStorage.getItem(`scrollPosition_${path}`));
1405 window.scrollTo(0, y);
1408 export function showLocal(isoData: IsoData): boolean {
1409 return isoData.site_res.federated_instances?.linked.length > 0;
1412 interface ChoicesValue {
1417 export function communityToChoice(cv: CommunityView): ChoicesValue {
1418 let choice: ChoicesValue = {
1419 value: cv.community.id.toString(),
1420 label: communitySelectName(cv),
1425 export function personToChoice(pvs: PersonViewSafe): ChoicesValue {
1426 let choice: ChoicesValue = {
1427 value: pvs.person.id.toString(),
1428 label: personSelectName(pvs),
1433 export async function fetchCommunities(q: string) {
1434 let form: Search = {
1436 type_: SearchType.Communities,
1437 sort: SortType.TopAll,
1438 listing_type: ListingType.All,
1441 auth: authField(false),
1443 let client = new LemmyHttp(httpBase);
1444 return client.search(form);
1447 export async function fetchUsers(q: string) {
1448 let form: Search = {
1450 type_: SearchType.Users,
1451 sort: SortType.TopAll,
1452 listing_type: ListingType.All,
1455 auth: authField(false),
1457 let client = new LemmyHttp(httpBase);
1458 return client.search(form);
1461 export const choicesConfig = {
1463 searchResultLimit: fetchLimit,
1465 containerOuter: "choices",
1466 containerInner: "choices__inner bg-secondary border-0",
1467 input: "form-control",
1468 inputCloned: "choices__input--cloned",
1469 list: "choices__list",
1470 listItems: "choices__list--multiple",
1471 listSingle: "choices__list--single",
1472 listDropdown: "choices__list--dropdown",
1473 item: "choices__item bg-secondary",
1474 itemSelectable: "choices__item--selectable",
1475 itemDisabled: "choices__item--disabled",
1476 itemChoice: "choices__item--choice",
1477 placeholder: "choices__placeholder",
1478 group: "choices__group",
1479 groupHeading: "choices__heading",
1480 button: "choices__button",
1481 activeState: "is-active",
1482 focusState: "is-focused",
1483 openState: "is-open",
1484 disabledState: "is-disabled",
1485 highlightedState: "text-info",
1486 selectedState: "text-info",
1487 flippedState: "is-flipped",
1488 loadingState: "is-loading",
1489 noResults: "has-no-results",
1490 noChoices: "has-no-choices",
1494 export function communitySelectName(cv: CommunityView): string {
1495 return cv.community.local
1496 ? cv.community.title
1497 : `${hostname(cv.community.actor_id)}/${cv.community.title}`;
1500 export function personSelectName(pvs: PersonViewSafe): string {
1501 let pName = pvs.person.display_name || pvs.person.name;
1502 return pvs.person.local ? pName : `${hostname(pvs.person.actor_id)}/${pName}`;
1505 export function initializeSite(site: GetSiteResponse) {
1506 UserService.Instance.myUserInfo = site.my_user;
1507 i18n.changeLanguage(getLanguage());
1510 const SHORTNUM_SI_FORMAT = new Intl.NumberFormat("en-US", {
1511 maximumSignificantDigits: 3,
1513 notation: "compact",
1514 compactDisplay: "short",
1517 export function numToSI(value: number): string {
1518 return SHORTNUM_SI_FORMAT.format(value);