1 import emojiShortName from "emoji-short-name";
2 import ISO6391 from "iso-639-1";
4 BlockCommunityResponse,
26 WebSocketJsonResponse,
28 } from "lemmy-js-client";
29 import markdown_it from "markdown-it";
30 import markdown_it_container from "markdown-it-container";
31 import markdown_it_html5_embed from "markdown-it-html5-embed";
32 import markdown_it_sub from "markdown-it-sub";
33 import markdown_it_sup from "markdown-it-sup";
34 import moment from "moment";
35 import "moment/locale/bg";
36 import "moment/locale/bn";
37 import "moment/locale/ca";
38 import "moment/locale/cs";
39 import "moment/locale/cy";
40 import "moment/locale/da";
41 import "moment/locale/de";
42 import "moment/locale/el";
43 import "moment/locale/eo";
44 import "moment/locale/es";
45 import "moment/locale/eu";
46 import "moment/locale/fa";
47 import "moment/locale/fi";
48 import "moment/locale/fr";
49 import "moment/locale/ga";
50 import "moment/locale/gl";
51 import "moment/locale/hi";
52 import "moment/locale/hr";
53 import "moment/locale/hu";
54 import "moment/locale/id";
55 import "moment/locale/it";
56 import "moment/locale/ja";
57 import "moment/locale/ka";
58 import "moment/locale/km";
59 import "moment/locale/ko";
60 import "moment/locale/ml";
61 import "moment/locale/nb";
62 import "moment/locale/nl";
63 import "moment/locale/pl";
64 import "moment/locale/pt-br";
65 import "moment/locale/ru";
66 import "moment/locale/sk";
67 import "moment/locale/sq";
68 import "moment/locale/sr";
69 import "moment/locale/sv";
70 import "moment/locale/tr";
71 import "moment/locale/uk";
72 import "moment/locale/vi";
73 import "moment/locale/zh-cn";
74 import { Subscription } from "rxjs";
75 import { delay, retryWhen, take } from "rxjs/operators";
76 import tippy from "tippy.js";
77 import Toastify from "toastify-js";
78 import { httpBase } from "./env";
79 import { i18n } from "./i18next";
81 CommentNode as CommentNodeI,
85 } from "./interfaces";
86 import { UserService, WebSocketService } from "./services";
90 Tribute = require("tributejs");
93 export const wsClient = new LemmyWebsocket();
95 export const favIconUrl = "/static/assets/icons/favicon.svg";
96 export const favIconPngUrl = "/static/assets/icons/apple-touch-icon.png";
98 // export const defaultFavIcon = `${window.location.protocol}//${window.location.host}${favIconPngUrl}`;
99 export const repoUrl = "https://github.com/LemmyNet";
100 export const joinLemmyUrl = "https://join-lemmy.org";
101 export const donateLemmyUrl = `${joinLemmyUrl}/donate`;
102 export const docsUrl = `${joinLemmyUrl}/docs/en/index.html`;
103 export const helpGuideUrl = `${joinLemmyUrl}/docs/en/about/guide.html`; // TODO find a way to redirect to the non-en folder
104 export const markdownHelpUrl = `${helpGuideUrl}#using-markdown`;
105 export const sortingHelpUrl = `${helpGuideUrl}#sorting`;
106 export const archiveTodayUrl = "https://archive.today";
107 export const ghostArchiveUrl = "https://ghostarchive.org";
108 export const webArchiveUrl = "https://web.archive.org";
109 export const elementUrl = "https://element.io";
111 export const postRefetchSeconds: number = 60 * 1000;
112 export const fetchLimit = 20;
113 export const mentionDropdownFetchLimit = 10;
115 export const languages = [
164 export const themes = [
181 const DEFAULT_ALPHABET =
182 "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
184 function getRandomCharFromAlphabet(alphabet: string): string {
185 return alphabet.charAt(Math.floor(Math.random() * alphabet.length));
188 export function randomStr(
189 idDesiredLength = 20,
190 alphabet = DEFAULT_ALPHABET
193 * Create n-long array and map it to random chars from given alphabet.
194 * Then join individual chars as string
196 return Array.from({ length: idDesiredLength })
198 return getRandomCharFromAlphabet(alphabet);
203 export function wsJsonToRes<ResponseType>(
204 msg: WebSocketJsonResponse<ResponseType>
205 ): WebSocketResponse<ResponseType> {
212 export function wsUserOp(msg: any): UserOperation {
213 let opStr: string = msg.op;
214 return UserOperation[opStr];
217 export const md = new markdown_it({
222 .use(markdown_it_sub)
223 .use(markdown_it_sup)
224 .use(markdown_it_html5_embed, {
226 useImageSyntax: true, // Enables video/audio embed with ![]() syntax (default)
228 audio: 'controls preload="metadata"',
230 'width="100%" max-height="100%" controls loop preload="metadata"',
234 .use(markdown_it_container, "spoiler", {
235 validate: function (params: any) {
236 return params.trim().match(/^spoiler\s+(.*)$/);
239 render: function (tokens: any, idx: any) {
240 var m = tokens[idx].info.trim().match(/^spoiler\s+(.*)$/);
242 if (tokens[idx].nesting === 1) {
244 return `<details><summary> ${md.utils.escapeHtml(m[1])} </summary>\n`;
247 return "</details>\n";
252 export function hotRankComment(comment_view: CommentView): number {
253 return hotRank(comment_view.counts.score, comment_view.comment.published);
256 export function hotRankActivePost(post_view: PostView): number {
257 return hotRank(post_view.counts.score, post_view.counts.newest_comment_time);
260 export function hotRankPost(post_view: PostView): number {
261 return hotRank(post_view.counts.score, post_view.post.published);
264 export function hotRank(score: number, timeStr: string): number {
265 // Rank = ScaleFactor * sign(Score) * log(1 + abs(Score)) / (Time + 2)^Gravity
266 let date: Date = new Date(timeStr + "Z"); // Add Z to convert from UTC date
267 let now: Date = new Date();
268 let hoursElapsed: number = (now.getTime() - date.getTime()) / 36e5;
271 (10000 * Math.log10(Math.max(1, 3 + score))) /
272 Math.pow(hoursElapsed + 2, 1.8);
274 // console.log(`Comment: ${comment.content}\nRank: ${rank}\nScore: ${comment.score}\nHours: ${hoursElapsed}`);
279 export function mdToHtml(text: string) {
280 return { __html: md.render(text) };
283 export function getUnixTime(text: string): number {
284 return text ? new Date(text).getTime() / 1000 : undefined;
287 export function canMod(
288 myUserInfo: MyUserInfo,
293 // You can do moderator actions only on the mods added after you.
295 let yourIndex = modIds.findIndex(
296 id => id == myUserInfo.local_user_view.person.id
298 if (yourIndex == -1) {
301 // onSelf +1 on mod actions not for yourself, IE ban, remove, etc
302 modIds = modIds.slice(0, yourIndex + (onSelf ? 0 : 1));
303 return !modIds.includes(creator_id);
310 export function isMod(modIds: number[], creator_id: number): boolean {
311 return modIds.includes(creator_id);
314 const imageRegex = new RegExp(
315 /(http)?s?:?(\/\/[^"']*\.(?:jpg|jpeg|gif|png|svg|webp))/
317 const videoRegex = new RegExp(`(http)?s?:?(\/\/[^"']*\.(?:mp4))`);
319 export function isImage(url: string) {
320 return imageRegex.test(url);
323 export function isVideo(url: string) {
324 return videoRegex.test(url);
327 export function validURL(str: string) {
328 return !!new URL(str);
331 export function communityRSSUrl(actorId: string, sort: string): string {
332 let url = new URL(actorId);
333 return `${url.origin}/feeds${url.pathname}.xml?sort=${sort}`;
336 export function validEmail(email: string) {
338 /^(([^\s"(),.:;<>@[\\\]]+(\.[^\s"(),.:;<>@[\\\]]+)*)|(".+"))@((\[(?:\d{1,3}\.){3}\d{1,3}])|(([\dA-Za-z\-]+\.)+[A-Za-z]{2,}))$/;
339 return re.test(String(email).toLowerCase());
342 export function capitalizeFirstLetter(str: string): string {
343 return str.charAt(0).toUpperCase() + str.slice(1);
346 export function routeSortTypeToEnum(sort: string): SortType {
347 return SortType[sort];
350 export function listingTypeFromNum(type_: number): ListingType {
351 return Object.values(ListingType)[type_];
354 export function sortTypeFromNum(type_: number): SortType {
355 return Object.values(SortType)[type_];
358 export function routeListingTypeToEnum(type: string): ListingType {
359 return ListingType[type];
362 export function routeDataTypeToEnum(type: string): DataType {
363 return DataType[capitalizeFirstLetter(type)];
366 export function routeSearchTypeToEnum(type: string): SearchType {
367 return SearchType[type];
370 export async function getSiteMetadata(url: string) {
371 let form: GetSiteMetadata = {
374 let client = new LemmyHttp(httpBase);
375 return client.getSiteMetadata(form);
378 export function debounce(func: any, wait = 1000, immediate = false) {
379 // 'private' variable for instance
380 // The returned function will be able to reference this due to closure.
381 // Each call to the returned function will share this common timer.
384 // Calling debounce returns a new anonymous function
386 // reference the context and args for the setTimeout function
387 var args = arguments;
389 // Should the function be called now? If immediate is true
390 // and not already in a timeout then the answer is: Yes
391 var callNow = immediate && !timeout;
393 // This is the basic debounce behaviour where you can call this
394 // function several times, but it will only execute once
395 // [before or after imposing a delay].
396 // Each time the returned function is called, the timer starts over.
397 clearTimeout(timeout);
399 // Set the new timeout
400 timeout = setTimeout(function () {
401 // Inside the timeout function, clear the timeout variable
402 // which will let the next execution run when in 'immediate' mode
405 // Check if the function already ran with the immediate flag
407 // Call the original function with apply
408 // apply lets you define the 'this' object as well as the arguments
409 // (both captured before setTimeout)
410 func.apply(this, args);
414 // Immediate mode and no wait timer? Execute the function..
415 if (callNow) func.apply(this, args);
419 export function getNativeLanguageName(code: string): string {
420 let [isoCode, qualifier] = code.split("_");
422 let native = ISO6391.getNativeName(isoCode) || code;
425 return `${native}_${qualifier}`;
432 export function getLanguage(override?: string): string {
433 let myUserInfo = UserService.Instance.myUserInfo;
436 (myUserInfo?.local_user_view.local_user.lang
437 ? myUserInfo.local_user_view.local_user.lang
440 if (lang == "browser" && isBrowser()) {
441 return getBrowserLanguage();
447 export function getBrowserLanguage(): string {
448 // Intersect lemmy's langs, with the browser langs
449 let langs = languages ? languages.map(l => l.code) : ["en"];
451 // NOTE, mobile browsers seem to be missing this list, so append en
452 let allowedLangs = navigator.languages
454 .filter(v => langs.includes(v));
455 return allowedLangs[0];
458 export function getMomentLanguage(): string {
459 let lang = getLanguage();
460 if (lang.startsWith("zh")) {
462 } else if (lang.startsWith("sv")) {
464 } else if (lang.startsWith("fr")) {
466 } else if (lang.startsWith("de")) {
468 } else if (lang.startsWith("ru")) {
470 } else if (lang.startsWith("es")) {
472 } else if (lang.startsWith("eo")) {
474 } else if (lang.startsWith("nl")) {
476 } else if (lang.startsWith("it")) {
478 } else if (lang.startsWith("fi")) {
480 } else if (lang.startsWith("ca")) {
482 } else if (lang.startsWith("fa")) {
484 } else if (lang.startsWith("pl")) {
486 } else if (lang.startsWith("pt_BR")) {
488 } else if (lang.startsWith("ja")) {
490 } else if (lang.startsWith("ka")) {
492 } else if (lang.startsWith("hi")) {
494 } else if (lang.startsWith("el")) {
496 } else if (lang.startsWith("eu")) {
498 } else if (lang.startsWith("gl")) {
500 } else if (lang.startsWith("tr")) {
502 } else if (lang.startsWith("hu")) {
504 } else if (lang.startsWith("uk")) {
506 } else if (lang.startsWith("sq")) {
508 } else if (lang.startsWith("km")) {
510 } else if (lang.startsWith("ga")) {
512 } else if (lang.startsWith("sr")) {
514 } else if (lang.startsWith("ko")) {
516 } else if (lang.startsWith("da")) {
518 } else if (lang.startsWith("oc")) {
520 } else if (lang.startsWith("hr")) {
522 } else if (lang.startsWith("th")) {
524 } else if (lang.startsWith("bg")) {
526 } else if (lang.startsWith("id")) {
528 } else if (lang.startsWith("nb")) {
530 } else if (lang.startsWith("cy")) {
532 } else if (lang.startsWith("sk")) {
534 } else if (lang.startsWith("vi")) {
536 } else if (lang.startsWith("pt")) {
538 } else if (lang.startsWith("ar")) {
540 } else if (lang.startsWith("bn")) {
542 } else if (lang.startsWith("ml")) {
544 } else if (lang.startsWith("cs")) {
552 export function setTheme(theme: string, forceReload = false) {
556 if (theme === "browser" && !forceReload) {
559 // This is only run on a force reload
560 if (theme == "browser") {
564 // Unload all the other themes
565 for (var i = 0; i < themes.length; i++) {
566 let styleSheet = document.getElementById(themes[i]);
568 styleSheet.setAttribute("disabled", "disabled");
573 .getElementById("default-light")
574 ?.setAttribute("disabled", "disabled");
575 document.getElementById("default-dark")?.setAttribute("disabled", "disabled");
577 // Load the theme dynamically
578 let cssLoc = `/static/assets/css/themes/${theme}.min.css`;
579 loadCss(theme, cssLoc);
580 document.getElementById(theme).removeAttribute("disabled");
583 export function loadCss(id: string, loc: string) {
584 if (!document.getElementById(id)) {
585 var head = document.getElementsByTagName("head")[0];
586 var link = document.createElement("link");
588 link.rel = "stylesheet";
589 link.type = "text/css";
592 head.appendChild(link);
596 export function objectFlip(obj: any) {
598 Object.keys(obj).forEach(key => {
604 export function showAvatars(): boolean {
606 UserService.Instance.myUserInfo?.local_user_view.local_user.show_avatars ||
607 !UserService.Instance.myUserInfo
611 export function showScores(): boolean {
613 UserService.Instance.myUserInfo?.local_user_view.local_user.show_scores ||
614 !UserService.Instance.myUserInfo
618 export function isCakeDay(published: string): boolean {
619 // moment(undefined) or moment.utc(undefined) returns the current date/time
620 // moment(null) or moment.utc(null) returns null
621 const createDate = moment.utc(published || null).local();
622 const currentDate = moment(new Date());
625 createDate.date() === currentDate.date() &&
626 createDate.month() === currentDate.month() &&
627 createDate.year() !== currentDate.year()
631 export function toast(text: string, background = "success") {
633 let backgroundColor = `var(--${background})`;
636 backgroundColor: backgroundColor,
643 export function pictrsDeleteToast(
644 clickToDeleteText: string,
645 deletePictureText: string,
649 let backgroundColor = `var(--light)`;
650 let toast = Toastify({
651 text: clickToDeleteText,
652 backgroundColor: backgroundColor,
658 window.location.replace(deleteUrl);
659 alert(deletePictureText);
668 interface NotifyInfo {
675 export function messageToastify(info: NotifyInfo, router: any) {
677 let htmlBody = info.body ? md.render(info.body) : "";
678 let backgroundColor = `var(--light)`;
680 let toast = Toastify({
681 text: `${htmlBody}<br />${info.name}`,
682 avatar: info.icon ? info.icon : null,
683 backgroundColor: backgroundColor,
684 className: "text-dark",
693 router.history.push(info.link);
700 export function notifyPost(post_view: PostView, router: any) {
701 let info: NotifyInfo = {
702 name: post_view.community.name,
703 icon: post_view.community.icon,
704 link: `/post/${post_view.post.id}`,
705 body: post_view.post.name,
707 notify(info, router);
710 export function notifyComment(comment_view: CommentView, router: any) {
711 let info: NotifyInfo = {
712 name: comment_view.creator.name,
713 icon: comment_view.creator.avatar,
714 link: `/post/${comment_view.post.id}/comment/${comment_view.comment.id}`,
715 body: comment_view.comment.content,
717 notify(info, router);
720 export function notifyPrivateMessage(pmv: PrivateMessageView, router: any) {
721 let info: NotifyInfo = {
722 name: pmv.creator.name,
723 icon: pmv.creator.avatar,
725 body: pmv.private_message.content,
727 notify(info, router);
730 function notify(info: NotifyInfo, router: any) {
731 messageToastify(info, router);
733 // TODO absolute nightmare bug, but notifs are currently broken.
734 // Notification.new will try to do a browser fetch ???
736 // if (Notification.permission !== "granted") Notification.requestPermission();
738 // var notification = new Notification(info.name, {
743 // notification.onclick = (ev: Event): any => {
744 // ev.preventDefault();
745 // router.history.push(info.link);
750 export function setupTribute() {
752 noMatchTemplate: function () {
759 menuItemTemplate: (item: any) => {
760 let shortName = `:${item.original.key}:`;
761 return `${item.original.val} ${shortName}`;
763 selectTemplate: (item: any) => {
764 return `${item.original.val}`;
766 values: Object.entries(emojiShortName).map(e => {
767 return { key: e[1], val: e[0] };
770 autocompleteMode: true,
772 // menuItemLimit: mentionDropdownFetchLimit,
773 menuShowMinLength: 2,
778 selectTemplate: (item: any) => {
779 let it: PersonTribute = item.original;
780 return `[${it.key}](${it.view.person.actor_id})`;
782 values: (text: string, cb: (persons: PersonTribute[]) => any) => {
783 personSearch(text, (persons: PersonTribute[]) => cb(persons));
786 autocompleteMode: true,
788 // menuItemLimit: mentionDropdownFetchLimit,
789 menuShowMinLength: 2,
795 selectTemplate: (item: any) => {
796 let it: CommunityTribute = item.original;
797 return `[${it.key}](${it.view.community.actor_id})`;
799 values: (text: string, cb: any) => {
800 communitySearch(text, (communities: CommunityTribute[]) =>
805 autocompleteMode: true,
807 // menuItemLimit: mentionDropdownFetchLimit,
808 menuShowMinLength: 2,
814 var tippyInstance: any;
816 tippyInstance = tippy("[data-tippy-content]");
819 export function setupTippy() {
821 tippyInstance.forEach((e: any) => e.destroy());
822 tippyInstance = tippy("[data-tippy-content]", {
824 // Display on "long press"
825 touch: ["hold", 500],
830 interface PersonTribute {
832 view: PersonViewSafe;
835 function personSearch(text: string, cb: (persons: PersonTribute[]) => any) {
839 type_: SearchType.Users,
840 sort: SortType.TopAll,
841 listing_type: ListingType.All,
843 limit: mentionDropdownFetchLimit,
844 auth: authField(false),
847 WebSocketService.Instance.send(wsClient.search(form));
849 let personSub = WebSocketService.Instance.subject.subscribe(
851 let res = wsJsonToRes(msg);
852 if (res.op == UserOperation.Search) {
853 let data = res.data as SearchResponse;
854 let persons: PersonTribute[] = data.users.map(pv => {
855 let tribute: PersonTribute = {
856 key: `@${pv.person.name}@${hostname(pv.person.actor_id)}`,
862 personSub.unsubscribe();
865 err => console.error(err),
866 () => console.log("complete")
873 interface CommunityTribute {
878 function communitySearch(
880 cb: (communities: CommunityTribute[]) => any
885 type_: SearchType.Communities,
886 sort: SortType.TopAll,
887 listing_type: ListingType.All,
889 limit: mentionDropdownFetchLimit,
890 auth: authField(false),
893 WebSocketService.Instance.send(wsClient.search(form));
895 let communitySub = WebSocketService.Instance.subject.subscribe(
897 let res = wsJsonToRes(msg);
898 if (res.op == UserOperation.Search) {
899 let data = res.data as SearchResponse;
900 let communities: CommunityTribute[] = data.communities.map(cv => {
901 let tribute: CommunityTribute = {
902 key: `!${cv.community.name}@${hostname(cv.community.actor_id)}`,
908 communitySub.unsubscribe();
911 err => console.error(err),
912 () => console.log("complete")
919 export function getListingTypeFromProps(props: any): ListingType {
920 return props.match.params.listing_type
921 ? routeListingTypeToEnum(props.match.params.listing_type)
922 : UserService.Instance.myUserInfo
923 ? Object.values(ListingType)[
924 UserService.Instance.myUserInfo.local_user_view.local_user
925 .default_listing_type
930 export function getListingTypeFromPropsNoDefault(props: any): ListingType {
931 return props.match.params.listing_type
932 ? routeListingTypeToEnum(props.match.params.listing_type)
936 // TODO might need to add a user setting for this too
937 export function getDataTypeFromProps(props: any): DataType {
938 return props.match.params.data_type
939 ? routeDataTypeToEnum(props.match.params.data_type)
943 export function getSortTypeFromProps(props: any): SortType {
944 return props.match.params.sort
945 ? routeSortTypeToEnum(props.match.params.sort)
946 : UserService.Instance.myUserInfo
947 ? Object.values(SortType)[
948 UserService.Instance.myUserInfo.local_user_view.local_user
954 export function getPageFromProps(props: any): number {
955 return props.match.params.page ? Number(props.match.params.page) : 1;
958 export function getRecipientIdFromProps(props: any): number {
959 return props.match.params.recipient_id
960 ? Number(props.match.params.recipient_id)
964 export function getIdFromProps(props: any): number {
965 return Number(props.match.params.id);
968 export function getCommentIdFromProps(props: any): number {
969 return Number(props.match.params.comment_id);
972 export function getUsernameFromProps(props: any): string {
973 return props.match.params.username;
976 export function editCommentRes(data: CommentView, comments: CommentView[]) {
977 let found = comments.find(c => c.comment.id == data.comment.id);
979 found.comment.content = data.comment.content;
980 found.comment.updated = data.comment.updated;
981 found.comment.removed = data.comment.removed;
982 found.comment.deleted = data.comment.deleted;
983 found.counts.upvotes = data.counts.upvotes;
984 found.counts.downvotes = data.counts.downvotes;
985 found.counts.score = data.counts.score;
989 export function saveCommentRes(data: CommentView, comments: CommentView[]) {
990 let found = comments.find(c => c.comment.id == data.comment.id);
992 found.saved = data.saved;
996 export function updatePersonBlock(
997 data: BlockPersonResponse
998 ): PersonBlockView[] {
1000 UserService.Instance.myUserInfo.person_blocks.push({
1001 person: UserService.Instance.myUserInfo.local_user_view.person,
1002 target: data.person_view.person,
1004 toast(`${i18n.t("blocked")} ${data.person_view.person.name}`);
1006 UserService.Instance.myUserInfo.person_blocks =
1007 UserService.Instance.myUserInfo.person_blocks.filter(
1008 i => i.target.id != data.person_view.person.id
1010 toast(`${i18n.t("unblocked")} ${data.person_view.person.name}`);
1012 return UserService.Instance.myUserInfo.person_blocks;
1015 export function updateCommunityBlock(
1016 data: BlockCommunityResponse
1017 ): CommunityBlockView[] {
1019 UserService.Instance.myUserInfo.community_blocks.push({
1020 person: UserService.Instance.myUserInfo.local_user_view.person,
1021 community: data.community_view.community,
1023 toast(`${i18n.t("blocked")} ${data.community_view.community.name}`);
1025 UserService.Instance.myUserInfo.community_blocks =
1026 UserService.Instance.myUserInfo.community_blocks.filter(
1027 i => i.community.id != data.community_view.community.id
1029 toast(`${i18n.t("unblocked")} ${data.community_view.community.name}`);
1031 return UserService.Instance.myUserInfo.community_blocks;
1034 export function createCommentLikeRes(
1036 comments: CommentView[]
1038 let found = comments.find(c => c.comment.id === data.comment.id);
1040 found.counts.score = data.counts.score;
1041 found.counts.upvotes = data.counts.upvotes;
1042 found.counts.downvotes = data.counts.downvotes;
1043 if (data.my_vote !== null) {
1044 found.my_vote = data.my_vote;
1049 export function createPostLikeFindRes(data: PostView, posts: PostView[]) {
1050 let found = posts.find(p => p.post.id == data.post.id);
1052 createPostLikeRes(data, found);
1056 export function createPostLikeRes(data: PostView, post_view: PostView) {
1058 post_view.counts.score = data.counts.score;
1059 post_view.counts.upvotes = data.counts.upvotes;
1060 post_view.counts.downvotes = data.counts.downvotes;
1061 if (data.my_vote !== null) {
1062 post_view.my_vote = data.my_vote;
1067 export function editPostFindRes(data: PostView, posts: PostView[]) {
1068 let found = posts.find(p => p.post.id == data.post.id);
1070 editPostRes(data, found);
1074 export function editPostRes(data: PostView, post: PostView) {
1076 post.post.url = data.post.url;
1077 post.post.name = data.post.name;
1078 post.post.nsfw = data.post.nsfw;
1079 post.post.deleted = data.post.deleted;
1080 post.post.removed = data.post.removed;
1081 post.post.stickied = data.post.stickied;
1082 post.post.body = data.post.body;
1083 post.post.locked = data.post.locked;
1084 post.saved = data.saved;
1088 export function updatePostReportRes(
1089 data: PostReportView,
1090 reports: PostReportView[]
1092 let found = reports.find(p => p.post.id == data.post.id);
1094 found.post_report = data.post_report;
1098 export function updateCommentReportRes(
1099 data: CommentReportView,
1100 reports: CommentReportView[]
1102 let found = reports.find(c => c.comment.id == data.comment.id);
1104 found.comment_report = data.comment_report;
1108 export function commentsToFlatNodes(comments: CommentView[]): CommentNodeI[] {
1109 let nodes: CommentNodeI[] = [];
1110 for (let comment of comments) {
1111 nodes.push({ comment_view: comment });
1116 function commentSort(tree: CommentNodeI[], sort: CommentSortType) {
1117 // First, put removed and deleted comments at the bottom, then do your other sorts
1118 if (sort == CommentSortType.Top) {
1121 +a.comment_view.comment.removed - +b.comment_view.comment.removed ||
1122 +a.comment_view.comment.deleted - +b.comment_view.comment.deleted ||
1123 b.comment_view.counts.score - a.comment_view.counts.score
1125 } else if (sort == CommentSortType.New) {
1128 +a.comment_view.comment.removed - +b.comment_view.comment.removed ||
1129 +a.comment_view.comment.deleted - +b.comment_view.comment.deleted ||
1130 b.comment_view.comment.published.localeCompare(
1131 a.comment_view.comment.published
1134 } else if (sort == CommentSortType.Old) {
1137 +a.comment_view.comment.removed - +b.comment_view.comment.removed ||
1138 +a.comment_view.comment.deleted - +b.comment_view.comment.deleted ||
1139 a.comment_view.comment.published.localeCompare(
1140 b.comment_view.comment.published
1143 } else if (sort == CommentSortType.Hot) {
1146 +a.comment_view.comment.removed - +b.comment_view.comment.removed ||
1147 +a.comment_view.comment.deleted - +b.comment_view.comment.deleted ||
1148 hotRankComment(b.comment_view) - hotRankComment(a.comment_view)
1152 // Go through the children recursively
1153 for (let node of tree) {
1154 if (node.children) {
1155 commentSort(node.children, sort);
1160 export function commentSortSortType(tree: CommentNodeI[], sort: SortType) {
1161 commentSort(tree, convertCommentSortType(sort));
1164 function convertCommentSortType(sort: SortType): CommentSortType {
1166 sort == SortType.TopAll ||
1167 sort == SortType.TopDay ||
1168 sort == SortType.TopWeek ||
1169 sort == SortType.TopMonth ||
1170 sort == SortType.TopYear
1172 return CommentSortType.Top;
1173 } else if (sort == SortType.New) {
1174 return CommentSortType.New;
1175 } else if (sort == SortType.Hot || sort == SortType.Active) {
1176 return CommentSortType.Hot;
1178 return CommentSortType.Hot;
1182 export function buildCommentsTree(
1183 comments: CommentView[],
1184 commentSortType: CommentSortType
1186 let map = new Map<number, CommentNodeI>();
1187 for (let comment_view of comments) {
1188 let node: CommentNodeI = {
1189 comment_view: comment_view,
1192 map.set(comment_view.comment.id, { ...node });
1194 let tree: CommentNodeI[] = [];
1195 for (let comment_view of comments) {
1196 let child = map.get(comment_view.comment.id);
1197 let parent_id = comment_view.comment.parent_id;
1199 let parent = map.get(parent_id);
1200 // Necessary because blocked comment might not exist
1202 parent.children.push(child);
1211 commentSort(tree, commentSortType);
1216 function setDepth(node: CommentNodeI, i = 0) {
1217 for (let child of node.children) {
1219 setDepth(child, i + 1);
1223 export function insertCommentIntoTree(tree: CommentNodeI[], cv: CommentView) {
1224 // Building a fake node to be used for later
1225 let node: CommentNodeI = {
1231 if (cv.comment.parent_id) {
1232 let parentComment = searchCommentTree(tree, cv.comment.parent_id);
1233 if (parentComment) {
1234 node.depth = parentComment.depth + 1;
1235 parentComment.children.unshift(node);
1242 export function searchCommentTree(
1243 tree: CommentNodeI[],
1246 for (let node of tree) {
1247 if (node.comment_view.comment.id === id) {
1251 for (const child of node.children) {
1252 const res = searchCommentTree([child], id);
1262 export const colorList: string[] = [
1271 function hsl(num: number) {
1272 return `hsla(${num}, 35%, 50%, 1)`;
1275 export function previewLines(
1284 // Use lines * 2 because markdown requires 2 lines
1285 .slice(0, maxLines * 2)
1290 export function hostname(url: string): string {
1291 let cUrl = new URL(url);
1292 return cUrl.port ? `${cUrl.hostname}:${cUrl.port}` : `${cUrl.hostname}`;
1295 export function validTitle(title?: string): boolean {
1296 // Initial title is null, minimum length is taken care of by textarea's minLength={3}
1297 if (title === null || title.length < 3) return true;
1299 const regex = new RegExp(/.*\S.*/, "g");
1301 return regex.test(title);
1304 export function siteBannerCss(banner: string): string {
1306 background-image: linear-gradient( rgba(0, 0, 0, 0.8), rgba(0, 0, 0, 0.8) ) ,url("${banner}"); \
1307 background-attachment: fixed; \
1308 background-position: top; \
1309 background-repeat: no-repeat; \
1310 background-size: 100% cover; \
1313 max-height: 100vh; \
1317 export function isBrowser() {
1318 return typeof window !== "undefined";
1321 export function setIsoData(context: any): IsoData {
1322 let isoData: IsoData = isBrowser()
1324 : context.router.staticContext;
1328 export function wsSubscribe(parseMessage: any): Subscription {
1330 return WebSocketService.Instance.subject
1331 .pipe(retryWhen(errors => errors.pipe(delay(3000), take(10))))
1333 msg => parseMessage(msg),
1334 err => console.error(err),
1335 () => console.log("complete")
1342 export function setOptionalAuth(obj: any, auth = UserService.Instance.auth) {
1348 export function authField(
1350 auth = UserService.Instance.auth
1352 if (auth == null && throwErr) {
1353 toast(i18n.t("not_logged_in"), "danger");
1354 throw "Not logged in";
1360 moment.updateLocale("en", {
1381 export function saveScrollPosition(context: any) {
1382 let path: string = context.router.route.location.pathname;
1383 let y = window.scrollY;
1384 sessionStorage.setItem(`scrollPosition_${path}`, y.toString());
1387 export function restoreScrollPosition(context: any) {
1388 let path: string = context.router.route.location.pathname;
1389 let y = Number(sessionStorage.getItem(`scrollPosition_${path}`));
1390 window.scrollTo(0, y);
1393 export function showLocal(isoData: IsoData): boolean {
1394 return isoData.site_res.federated_instances?.linked.length > 0;
1397 interface ChoicesValue {
1402 export function communityToChoice(cv: CommunityView): ChoicesValue {
1403 let choice: ChoicesValue = {
1404 value: cv.community.id.toString(),
1405 label: communitySelectName(cv),
1410 export function personToChoice(pvs: PersonViewSafe): ChoicesValue {
1411 let choice: ChoicesValue = {
1412 value: pvs.person.id.toString(),
1413 label: personSelectName(pvs),
1418 export async function fetchCommunities(q: string) {
1419 let form: Search = {
1421 type_: SearchType.Communities,
1422 sort: SortType.TopAll,
1423 listing_type: ListingType.All,
1426 auth: authField(false),
1428 let client = new LemmyHttp(httpBase);
1429 return client.search(form);
1432 export async function fetchUsers(q: string) {
1433 let form: Search = {
1435 type_: SearchType.Users,
1436 sort: SortType.TopAll,
1437 listing_type: ListingType.All,
1440 auth: authField(false),
1442 let client = new LemmyHttp(httpBase);
1443 return client.search(form);
1446 export const choicesConfig = {
1448 searchResultLimit: fetchLimit,
1450 containerOuter: "choices",
1451 containerInner: "choices__inner bg-secondary border-0",
1452 input: "form-control",
1453 inputCloned: "choices__input--cloned",
1454 list: "choices__list",
1455 listItems: "choices__list--multiple",
1456 listSingle: "choices__list--single",
1457 listDropdown: "choices__list--dropdown",
1458 item: "choices__item bg-secondary",
1459 itemSelectable: "choices__item--selectable",
1460 itemDisabled: "choices__item--disabled",
1461 itemChoice: "choices__item--choice",
1462 placeholder: "choices__placeholder",
1463 group: "choices__group",
1464 groupHeading: "choices__heading",
1465 button: "choices__button",
1466 activeState: "is-active",
1467 focusState: "is-focused",
1468 openState: "is-open",
1469 disabledState: "is-disabled",
1470 highlightedState: "text-info",
1471 selectedState: "text-info",
1472 flippedState: "is-flipped",
1473 loadingState: "is-loading",
1474 noResults: "has-no-results",
1475 noChoices: "has-no-choices",
1479 export function communitySelectName(cv: CommunityView): string {
1480 return cv.community.local
1481 ? cv.community.title
1482 : `${hostname(cv.community.actor_id)}/${cv.community.title}`;
1485 export function personSelectName(pvs: PersonViewSafe): string {
1486 let pName = pvs.person.display_name || pvs.person.name;
1487 return pvs.person.local ? pName : `${hostname(pvs.person.actor_id)}/${pName}`;
1490 export function initializeSite(site: GetSiteResponse) {
1491 UserService.Instance.myUserInfo = site.my_user;
1492 i18n.changeLanguage(getLanguage());
1495 const SHORTNUM_SI_FORMAT = new Intl.NumberFormat("en-US", {
1496 maximumSignificantDigits: 3,
1498 notation: "compact",
1499 compactDisplay: "short",
1502 export function numToSI(value: number): string {
1503 return SHORTNUM_SI_FORMAT.format(value);