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_footnote from "markdown-it-footnote";
34 import markdown_it_html5_embed from "markdown-it-html5-embed";
35 import markdown_it_sub from "markdown-it-sub";
36 import markdown_it_sup from "markdown-it-sup";
37 import moment from "moment";
38 import "moment/locale/bg";
39 import "moment/locale/bn";
40 import "moment/locale/ca";
41 import "moment/locale/cs";
42 import "moment/locale/cy";
43 import "moment/locale/da";
44 import "moment/locale/de";
45 import "moment/locale/el";
46 import "moment/locale/eo";
47 import "moment/locale/es";
48 import "moment/locale/eu";
49 import "moment/locale/fa";
50 import "moment/locale/fi";
51 import "moment/locale/fr";
52 import "moment/locale/ga";
53 import "moment/locale/gl";
54 import "moment/locale/hi";
55 import "moment/locale/hr";
56 import "moment/locale/hu";
57 import "moment/locale/id";
58 import "moment/locale/it";
59 import "moment/locale/ja";
60 import "moment/locale/ka";
61 import "moment/locale/km";
62 import "moment/locale/ko";
63 import "moment/locale/ml";
64 import "moment/locale/nb";
65 import "moment/locale/nl";
66 import "moment/locale/pl";
67 import "moment/locale/pt-br";
68 import "moment/locale/ru";
69 import "moment/locale/sk";
70 import "moment/locale/sq";
71 import "moment/locale/sr";
72 import "moment/locale/sv";
73 import "moment/locale/tr";
74 import "moment/locale/uk";
75 import "moment/locale/vi";
76 import "moment/locale/zh-cn";
77 import { Subscription } from "rxjs";
78 import { delay, retryWhen, take } from "rxjs/operators";
79 import tippy from "tippy.js";
80 import Toastify from "toastify-js";
81 import { httpBase } from "./env";
82 import { i18n } from "./i18next";
84 CommentNode as CommentNodeI,
88 } from "./interfaces";
89 import { UserService, WebSocketService } from "./services";
93 Tribute = require("tributejs");
96 export const wsClient = new LemmyWebsocket();
98 export const favIconUrl = "/static/assets/icons/favicon.svg";
99 export const favIconPngUrl = "/static/assets/icons/apple-touch-icon.png";
101 // export const defaultFavIcon = `${window.location.protocol}//${window.location.host}${favIconPngUrl}`;
102 export const repoUrl = "https://github.com/LemmyNet";
103 export const joinLemmyUrl = "https://join-lemmy.org";
104 export const donateLemmyUrl = `${joinLemmyUrl}/donate`;
105 export const docsUrl = `${joinLemmyUrl}/docs/en/index.html`;
106 export const helpGuideUrl = `${joinLemmyUrl}/docs/en/about/guide.html`; // TODO find a way to redirect to the non-en folder
107 export const markdownHelpUrl = `${helpGuideUrl}#using-markdown`;
108 export const sortingHelpUrl = `${helpGuideUrl}#sorting`;
109 export const archiveTodayUrl = "https://archive.today";
110 export const ghostArchiveUrl = "https://ghostarchive.org";
111 export const webArchiveUrl = "https://web.archive.org";
112 export const elementUrl = "https://element.io";
114 export const postRefetchSeconds: number = 60 * 1000;
115 export const fetchLimit = 20;
116 export const mentionDropdownFetchLimit = 10;
118 export const languages = [
169 export const themes = [
186 const DEFAULT_ALPHABET =
187 "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
189 function getRandomCharFromAlphabet(alphabet: string): string {
190 return alphabet.charAt(Math.floor(Math.random() * alphabet.length));
193 export function randomStr(
194 idDesiredLength = 20,
195 alphabet = DEFAULT_ALPHABET
198 * Create n-long array and map it to random chars from given alphabet.
199 * Then join individual chars as string
201 return Array.from({ length: idDesiredLength })
203 return getRandomCharFromAlphabet(alphabet);
208 export function wsJsonToRes<ResponseType>(
209 msg: WebSocketJsonResponse<ResponseType>
210 ): WebSocketResponse<ResponseType> {
217 export function wsUserOp(msg: any): UserOperation {
218 let opStr: string = msg.op;
219 return UserOperation[opStr];
222 export const md = new markdown_it({
227 .use(markdown_it_sub)
228 .use(markdown_it_sup)
229 .use(markdown_it_footnote)
230 .use(markdown_it_html5_embed, {
232 useImageSyntax: true, // Enables video/audio embed with ![]() syntax (default)
234 audio: 'controls preload="metadata"',
236 'width="100%" max-height="100%" controls loop preload="metadata"',
240 .use(markdown_it_container, "spoiler", {
241 validate: function (params: any) {
242 return params.trim().match(/^spoiler\s+(.*)$/);
245 render: function (tokens: any, idx: any) {
246 var m = tokens[idx].info.trim().match(/^spoiler\s+(.*)$/);
248 if (tokens[idx].nesting === 1) {
250 return `<details><summary> ${md.utils.escapeHtml(m[1])} </summary>\n`;
253 return "</details>\n";
258 export function hotRankComment(comment_view: CommentView): number {
259 return hotRank(comment_view.counts.score, comment_view.comment.published);
262 export function hotRankActivePost(post_view: PostView): number {
263 return hotRank(post_view.counts.score, post_view.counts.newest_comment_time);
266 export function hotRankPost(post_view: PostView): number {
267 return hotRank(post_view.counts.score, post_view.post.published);
270 export function hotRank(score: number, timeStr: string): number {
271 // Rank = ScaleFactor * sign(Score) * log(1 + abs(Score)) / (Time + 2)^Gravity
272 let date: Date = new Date(timeStr + "Z"); // Add Z to convert from UTC date
273 let now: Date = new Date();
274 let hoursElapsed: number = (now.getTime() - date.getTime()) / 36e5;
277 (10000 * Math.log10(Math.max(1, 3 + score))) /
278 Math.pow(hoursElapsed + 2, 1.8);
280 // console.log(`Comment: ${comment.content}\nRank: ${rank}\nScore: ${comment.score}\nHours: ${hoursElapsed}`);
285 export function mdToHtml(text: string) {
286 return { __html: md.render(text) };
289 export function getUnixTime(text: string): number {
290 return text ? new Date(text).getTime() / 1000 : undefined;
293 export function futureDaysToUnixTime(days: number): number {
296 new Date(Date.now() + 1000 * 60 * 60 * 24 * days).getTime() / 1000
301 export function canMod(
302 myUserInfo: MyUserInfo,
307 // You can do moderator actions only on the mods added after you.
309 let yourIndex = modIds.findIndex(
310 id => id == myUserInfo.local_user_view.person.id
312 if (yourIndex == -1) {
315 // onSelf +1 on mod actions not for yourself, IE ban, remove, etc
316 modIds = modIds.slice(0, yourIndex + (onSelf ? 0 : 1));
317 return !modIds.includes(creator_id);
324 export function isMod(modIds: number[], creator_id: number): boolean {
325 return modIds.includes(creator_id);
328 const imageRegex = /(http)?s?:?(\/\/[^"']*\.(?:jpg|jpeg|gif|png|svg|webp))/;
329 const videoRegex = /(http)?s?:?(\/\/[^"']*\.(?:mp4|webm))/;
331 export function isImage(url: string) {
332 return imageRegex.test(url);
335 export function isVideo(url: string) {
336 return videoRegex.test(url);
339 export function validURL(str: string) {
340 return !!new URL(str);
343 export function communityRSSUrl(actorId: string, sort: string): string {
344 let url = new URL(actorId);
345 return `${url.origin}/feeds${url.pathname}.xml?sort=${sort}`;
348 export function validEmail(email: string) {
350 /^(([^\s"(),.:;<>@[\\\]]+(\.[^\s"(),.:;<>@[\\\]]+)*)|(".+"))@((\[(?:\d{1,3}\.){3}\d{1,3}])|(([\dA-Za-z\-]+\.)+[A-Za-z]{2,}))$/;
351 return re.test(String(email).toLowerCase());
354 export function capitalizeFirstLetter(str: string): string {
355 return str.charAt(0).toUpperCase() + str.slice(1);
358 export function routeSortTypeToEnum(sort: string): SortType {
359 return SortType[sort];
362 export function listingTypeFromNum(type_: number): ListingType {
363 return Object.values(ListingType)[type_];
366 export function sortTypeFromNum(type_: number): SortType {
367 return Object.values(SortType)[type_];
370 export function routeListingTypeToEnum(type: string): ListingType {
371 return ListingType[type];
374 export function routeDataTypeToEnum(type: string): DataType {
375 return DataType[capitalizeFirstLetter(type)];
378 export function routeSearchTypeToEnum(type: string): SearchType {
379 return SearchType[type];
382 export async function getSiteMetadata(url: string) {
383 let form: GetSiteMetadata = {
386 let client = new LemmyHttp(httpBase);
387 return client.getSiteMetadata(form);
390 export function debounce(func: any, wait = 1000, immediate = false) {
391 // 'private' variable for instance
392 // The returned function will be able to reference this due to closure.
393 // Each call to the returned function will share this common timer.
396 // Calling debounce returns a new anonymous function
398 // reference the context and args for the setTimeout function
399 var args = arguments;
401 // Should the function be called now? If immediate is true
402 // and not already in a timeout then the answer is: Yes
403 var callNow = immediate && !timeout;
405 // This is the basic debounce behaviour where you can call this
406 // function several times, but it will only execute once
407 // [before or after imposing a delay].
408 // Each time the returned function is called, the timer starts over.
409 clearTimeout(timeout);
411 // Set the new timeout
412 timeout = setTimeout(function () {
413 // Inside the timeout function, clear the timeout variable
414 // which will let the next execution run when in 'immediate' mode
417 // Check if the function already ran with the immediate flag
419 // Call the original function with apply
420 // apply lets you define the 'this' object as well as the arguments
421 // (both captured before setTimeout)
422 func.apply(this, args);
426 // Immediate mode and no wait timer? Execute the function..
427 if (callNow) func.apply(this, args);
431 export function getNativeLanguageName(code: string): string {
432 let [isoCode, qualifier] = code.split("_");
434 let native = ISO6391.getNativeName(isoCode) || code;
437 return `${native}_${qualifier}`;
444 export function getLanguage(override?: string): string {
445 let myUserInfo = UserService.Instance.myUserInfo;
448 (myUserInfo?.local_user_view.local_user.lang
449 ? myUserInfo.local_user_view.local_user.lang
452 if (lang == "browser" && isBrowser()) {
453 return getBrowserLanguage();
459 export function getBrowserLanguage(): string {
460 // Intersect lemmy's langs, with the browser langs
461 let langs = languages ? languages.map(l => l.code) : ["en"];
463 // NOTE, mobile browsers seem to be missing this list, so append en
464 let allowedLangs = navigator.languages
466 .filter(v => langs.includes(v));
467 return allowedLangs[0];
470 export function getMomentLanguage(): string {
471 let lang = getLanguage();
472 if (lang.startsWith("zh")) {
474 } else if (lang.startsWith("sv")) {
476 } else if (lang.startsWith("fr")) {
478 } else if (lang.startsWith("de")) {
480 } else if (lang.startsWith("ru")) {
482 } else if (lang.startsWith("es")) {
484 } else if (lang.startsWith("eo")) {
486 } else if (lang.startsWith("nl")) {
488 } else if (lang.startsWith("it")) {
490 } else if (lang.startsWith("fi")) {
492 } else if (lang.startsWith("ca")) {
494 } else if (lang.startsWith("fa")) {
496 } else if (lang.startsWith("pl")) {
498 } else if (lang.startsWith("pt_BR")) {
500 } else if (lang.startsWith("ja")) {
502 } else if (lang.startsWith("ka")) {
504 } else if (lang.startsWith("hi")) {
506 } else if (lang.startsWith("el")) {
508 } else if (lang.startsWith("eu")) {
510 } else if (lang.startsWith("gl")) {
512 } else if (lang.startsWith("tr")) {
514 } else if (lang.startsWith("hu")) {
516 } else if (lang.startsWith("uk")) {
518 } else if (lang.startsWith("sq")) {
520 } else if (lang.startsWith("km")) {
522 } else if (lang.startsWith("ga")) {
524 } else if (lang.startsWith("sr")) {
526 } else if (lang.startsWith("ko")) {
528 } else if (lang.startsWith("da")) {
530 } else if (lang.startsWith("oc")) {
532 } else if (lang.startsWith("hr")) {
534 } else if (lang.startsWith("th")) {
536 } else if (lang.startsWith("bg")) {
538 } else if (lang.startsWith("id")) {
540 } else if (lang.startsWith("nb")) {
542 } else if (lang.startsWith("cy")) {
544 } else if (lang.startsWith("sk")) {
546 } else if (lang.startsWith("vi")) {
548 } else if (lang.startsWith("pt")) {
550 } else if (lang.startsWith("ar")) {
552 } else if (lang.startsWith("bn")) {
554 } else if (lang.startsWith("ml")) {
556 } else if (lang.startsWith("cs")) {
558 } else if (lang.startsWith("as")) {
560 } else if (lang.startsWith("lt")) {
568 export function setTheme(theme: string, forceReload = false) {
572 if (theme === "browser" && !forceReload) {
575 // This is only run on a force reload
576 if (theme == "browser") {
580 // Unload all the other themes
581 for (var i = 0; i < themes.length; i++) {
582 let styleSheet = document.getElementById(themes[i]);
584 styleSheet.setAttribute("disabled", "disabled");
589 .getElementById("default-light")
590 ?.setAttribute("disabled", "disabled");
591 document.getElementById("default-dark")?.setAttribute("disabled", "disabled");
593 // Load the theme dynamically
594 let cssLoc = `/static/assets/css/themes/${theme}.min.css`;
595 loadCss(theme, cssLoc);
596 document.getElementById(theme).removeAttribute("disabled");
599 export function loadCss(id: string, loc: string) {
600 if (!document.getElementById(id)) {
601 var head = document.getElementsByTagName("head")[0];
602 var link = document.createElement("link");
604 link.rel = "stylesheet";
605 link.type = "text/css";
608 head.appendChild(link);
612 export function objectFlip(obj: any) {
614 Object.keys(obj).forEach(key => {
620 export function showAvatars(): boolean {
622 UserService.Instance.myUserInfo?.local_user_view.local_user.show_avatars ||
623 !UserService.Instance.myUserInfo
627 export function showScores(): boolean {
629 UserService.Instance.myUserInfo?.local_user_view.local_user.show_scores ||
630 !UserService.Instance.myUserInfo
634 export function isCakeDay(published: string): boolean {
635 // moment(undefined) or moment.utc(undefined) returns the current date/time
636 // moment(null) or moment.utc(null) returns null
637 const createDate = moment.utc(published || null).local();
638 const currentDate = moment(new Date());
641 createDate.date() === currentDate.date() &&
642 createDate.month() === currentDate.month() &&
643 createDate.year() !== currentDate.year()
647 export function toast(text: string, background = "success") {
649 let backgroundColor = `var(--${background})`;
652 backgroundColor: backgroundColor,
659 export function pictrsDeleteToast(
660 clickToDeleteText: string,
661 deletePictureText: string,
665 let backgroundColor = `var(--light)`;
666 let toast = Toastify({
667 text: clickToDeleteText,
668 backgroundColor: backgroundColor,
674 window.location.replace(deleteUrl);
675 alert(deletePictureText);
684 interface NotifyInfo {
691 export function messageToastify(info: NotifyInfo, router: any) {
693 let htmlBody = info.body ? md.render(info.body) : "";
694 let backgroundColor = `var(--light)`;
696 let toast = Toastify({
697 text: `${htmlBody}<br />${info.name}`,
698 avatar: info.icon ? info.icon : null,
699 backgroundColor: backgroundColor,
700 className: "text-dark",
709 router.history.push(info.link);
716 export function notifyPost(post_view: PostView, router: any) {
717 let info: NotifyInfo = {
718 name: post_view.community.name,
719 icon: post_view.community.icon,
720 link: `/post/${post_view.post.id}`,
721 body: post_view.post.name,
723 notify(info, router);
726 export function notifyComment(comment_view: CommentView, router: any) {
727 let info: NotifyInfo = {
728 name: comment_view.creator.name,
729 icon: comment_view.creator.avatar,
730 link: `/post/${comment_view.post.id}/comment/${comment_view.comment.id}`,
731 body: comment_view.comment.content,
733 notify(info, router);
736 export function notifyPrivateMessage(pmv: PrivateMessageView, router: any) {
737 let info: NotifyInfo = {
738 name: pmv.creator.name,
739 icon: pmv.creator.avatar,
741 body: pmv.private_message.content,
743 notify(info, router);
746 function notify(info: NotifyInfo, router: any) {
747 messageToastify(info, router);
749 // TODO absolute nightmare bug, but notifs are currently broken.
750 // Notification.new will try to do a browser fetch ???
752 // if (Notification.permission !== "granted") Notification.requestPermission();
754 // var notification = new Notification(info.name, {
759 // notification.onclick = (ev: Event): any => {
760 // ev.preventDefault();
761 // router.history.push(info.link);
766 export function setupTribute() {
768 noMatchTemplate: function () {
775 menuItemTemplate: (item: any) => {
776 let shortName = `:${item.original.key}:`;
777 return `${item.original.val} ${shortName}`;
779 selectTemplate: (item: any) => {
780 return `${item.original.val}`;
782 values: Object.entries(emojiShortName).map(e => {
783 return { key: e[1], val: e[0] };
786 autocompleteMode: true,
788 // menuItemLimit: mentionDropdownFetchLimit,
789 menuShowMinLength: 2,
794 selectTemplate: (item: any) => {
795 let it: PersonTribute = item.original;
796 return `[${it.key}](${it.view.person.actor_id})`;
798 values: (text: string, cb: (persons: PersonTribute[]) => any) => {
799 personSearch(text, (persons: PersonTribute[]) => cb(persons));
802 autocompleteMode: true,
804 // menuItemLimit: mentionDropdownFetchLimit,
805 menuShowMinLength: 2,
811 selectTemplate: (item: any) => {
812 let it: CommunityTribute = item.original;
813 return `[${it.key}](${it.view.community.actor_id})`;
815 values: (text: string, cb: any) => {
816 communitySearch(text, (communities: CommunityTribute[]) =>
821 autocompleteMode: true,
823 // menuItemLimit: mentionDropdownFetchLimit,
824 menuShowMinLength: 2,
830 var tippyInstance: any;
832 tippyInstance = tippy("[data-tippy-content]");
835 export function setupTippy() {
837 tippyInstance.forEach((e: any) => e.destroy());
838 tippyInstance = tippy("[data-tippy-content]", {
840 // Display on "long press"
841 touch: ["hold", 500],
846 interface PersonTribute {
848 view: PersonViewSafe;
851 function personSearch(text: string, cb: (persons: PersonTribute[]) => any) {
855 type_: SearchType.Users,
856 sort: SortType.TopAll,
857 listing_type: ListingType.All,
859 limit: mentionDropdownFetchLimit,
860 auth: authField(false),
863 WebSocketService.Instance.send(wsClient.search(form));
865 let personSub = WebSocketService.Instance.subject.subscribe(
867 let res = wsJsonToRes(msg);
868 if (res.op == UserOperation.Search) {
869 let data = res.data as SearchResponse;
870 let persons: PersonTribute[] = data.users.map(pv => {
871 let tribute: PersonTribute = {
872 key: `@${pv.person.name}@${hostname(pv.person.actor_id)}`,
878 personSub.unsubscribe();
881 err => console.error(err),
882 () => console.log("complete")
889 interface CommunityTribute {
894 function communitySearch(
896 cb: (communities: CommunityTribute[]) => any
901 type_: SearchType.Communities,
902 sort: SortType.TopAll,
903 listing_type: ListingType.All,
905 limit: mentionDropdownFetchLimit,
906 auth: authField(false),
909 WebSocketService.Instance.send(wsClient.search(form));
911 let communitySub = WebSocketService.Instance.subject.subscribe(
913 let res = wsJsonToRes(msg);
914 if (res.op == UserOperation.Search) {
915 let data = res.data as SearchResponse;
916 let communities: CommunityTribute[] = data.communities.map(cv => {
917 let tribute: CommunityTribute = {
918 key: `!${cv.community.name}@${hostname(cv.community.actor_id)}`,
924 communitySub.unsubscribe();
927 err => console.error(err),
928 () => console.log("complete")
935 export function getListingTypeFromProps(props: any): ListingType {
936 return props.match.params.listing_type
937 ? routeListingTypeToEnum(props.match.params.listing_type)
938 : UserService.Instance.myUserInfo
939 ? Object.values(ListingType)[
940 UserService.Instance.myUserInfo.local_user_view.local_user
941 .default_listing_type
946 export function getListingTypeFromPropsNoDefault(props: any): ListingType {
947 return props.match.params.listing_type
948 ? routeListingTypeToEnum(props.match.params.listing_type)
952 // TODO might need to add a user setting for this too
953 export function getDataTypeFromProps(props: any): DataType {
954 return props.match.params.data_type
955 ? routeDataTypeToEnum(props.match.params.data_type)
959 export function getSortTypeFromProps(props: any): SortType {
960 return props.match.params.sort
961 ? routeSortTypeToEnum(props.match.params.sort)
962 : UserService.Instance.myUserInfo
963 ? Object.values(SortType)[
964 UserService.Instance.myUserInfo.local_user_view.local_user
970 export function getPageFromProps(props: any): number {
971 return props.match.params.page ? Number(props.match.params.page) : 1;
974 export function getRecipientIdFromProps(props: any): number {
975 return props.match.params.recipient_id
976 ? Number(props.match.params.recipient_id)
980 export function getIdFromProps(props: any): number {
981 return Number(props.match.params.id);
984 export function getCommentIdFromProps(props: any): number {
985 return Number(props.match.params.comment_id);
988 export function getUsernameFromProps(props: any): string {
989 return props.match.params.username;
992 export function editCommentRes(data: CommentView, comments: CommentView[]) {
993 let found = comments.find(c => c.comment.id == data.comment.id);
995 found.comment.content = data.comment.content;
996 found.comment.updated = data.comment.updated;
997 found.comment.removed = data.comment.removed;
998 found.comment.deleted = data.comment.deleted;
999 found.counts.upvotes = data.counts.upvotes;
1000 found.counts.downvotes = data.counts.downvotes;
1001 found.counts.score = data.counts.score;
1005 export function saveCommentRes(data: CommentView, comments: CommentView[]) {
1006 let found = comments.find(c => c.comment.id == data.comment.id);
1008 found.saved = data.saved;
1012 export function updatePersonBlock(
1013 data: BlockPersonResponse
1014 ): PersonBlockView[] {
1016 UserService.Instance.myUserInfo.person_blocks.push({
1017 person: UserService.Instance.myUserInfo.local_user_view.person,
1018 target: data.person_view.person,
1020 toast(`${i18n.t("blocked")} ${data.person_view.person.name}`);
1022 UserService.Instance.myUserInfo.person_blocks =
1023 UserService.Instance.myUserInfo.person_blocks.filter(
1024 i => i.target.id != data.person_view.person.id
1026 toast(`${i18n.t("unblocked")} ${data.person_view.person.name}`);
1028 return UserService.Instance.myUserInfo.person_blocks;
1031 export function updateCommunityBlock(
1032 data: BlockCommunityResponse
1033 ): CommunityBlockView[] {
1035 UserService.Instance.myUserInfo.community_blocks.push({
1036 person: UserService.Instance.myUserInfo.local_user_view.person,
1037 community: data.community_view.community,
1039 toast(`${i18n.t("blocked")} ${data.community_view.community.name}`);
1041 UserService.Instance.myUserInfo.community_blocks =
1042 UserService.Instance.myUserInfo.community_blocks.filter(
1043 i => i.community.id != data.community_view.community.id
1045 toast(`${i18n.t("unblocked")} ${data.community_view.community.name}`);
1047 return UserService.Instance.myUserInfo.community_blocks;
1050 export function createCommentLikeRes(
1052 comments: CommentView[]
1054 let found = comments.find(c => c.comment.id === data.comment.id);
1056 found.counts.score = data.counts.score;
1057 found.counts.upvotes = data.counts.upvotes;
1058 found.counts.downvotes = data.counts.downvotes;
1059 if (data.my_vote !== null) {
1060 found.my_vote = data.my_vote;
1065 export function createPostLikeFindRes(data: PostView, posts: PostView[]) {
1066 let found = posts.find(p => p.post.id == data.post.id);
1068 createPostLikeRes(data, found);
1072 export function createPostLikeRes(data: PostView, post_view: PostView) {
1074 post_view.counts.score = data.counts.score;
1075 post_view.counts.upvotes = data.counts.upvotes;
1076 post_view.counts.downvotes = data.counts.downvotes;
1077 if (data.my_vote !== null) {
1078 post_view.my_vote = data.my_vote;
1083 export function editPostFindRes(data: PostView, posts: PostView[]) {
1084 let found = posts.find(p => p.post.id == data.post.id);
1086 editPostRes(data, found);
1090 export function editPostRes(data: PostView, post: PostView) {
1092 post.post.url = data.post.url;
1093 post.post.name = data.post.name;
1094 post.post.nsfw = data.post.nsfw;
1095 post.post.deleted = data.post.deleted;
1096 post.post.removed = data.post.removed;
1097 post.post.stickied = data.post.stickied;
1098 post.post.body = data.post.body;
1099 post.post.locked = data.post.locked;
1100 post.saved = data.saved;
1104 export function updatePostReportRes(
1105 data: PostReportView,
1106 reports: PostReportView[]
1108 let found = reports.find(p => p.post_report.id == data.post_report.id);
1110 found.post_report = data.post_report;
1114 export function updateCommentReportRes(
1115 data: CommentReportView,
1116 reports: CommentReportView[]
1118 let found = reports.find(c => c.comment_report.id == data.comment_report.id);
1120 found.comment_report = data.comment_report;
1124 export function updateRegistrationApplicationRes(
1125 data: RegistrationApplicationView,
1126 applications: RegistrationApplicationView[]
1128 let found = applications.find(
1129 ra => ra.registration_application.id == data.registration_application.id
1132 found.registration_application = data.registration_application;
1133 found.admin = data.admin;
1134 found.creator_local_user = data.creator_local_user;
1138 export function commentsToFlatNodes(comments: CommentView[]): CommentNodeI[] {
1139 let nodes: CommentNodeI[] = [];
1140 for (let comment of comments) {
1141 nodes.push({ comment_view: comment });
1146 function commentSort(tree: CommentNodeI[], sort: CommentSortType) {
1147 // First, put removed and deleted comments at the bottom, then do your other sorts
1148 if (sort == CommentSortType.Top) {
1151 +a.comment_view.comment.removed - +b.comment_view.comment.removed ||
1152 +a.comment_view.comment.deleted - +b.comment_view.comment.deleted ||
1153 b.comment_view.counts.score - a.comment_view.counts.score
1155 } else if (sort == CommentSortType.New) {
1158 +a.comment_view.comment.removed - +b.comment_view.comment.removed ||
1159 +a.comment_view.comment.deleted - +b.comment_view.comment.deleted ||
1160 b.comment_view.comment.published.localeCompare(
1161 a.comment_view.comment.published
1164 } else if (sort == CommentSortType.Old) {
1167 +a.comment_view.comment.removed - +b.comment_view.comment.removed ||
1168 +a.comment_view.comment.deleted - +b.comment_view.comment.deleted ||
1169 a.comment_view.comment.published.localeCompare(
1170 b.comment_view.comment.published
1173 } else if (sort == CommentSortType.Hot) {
1176 +a.comment_view.comment.removed - +b.comment_view.comment.removed ||
1177 +a.comment_view.comment.deleted - +b.comment_view.comment.deleted ||
1178 hotRankComment(b.comment_view) - hotRankComment(a.comment_view)
1182 // Go through the children recursively
1183 for (let node of tree) {
1184 if (node.children) {
1185 commentSort(node.children, sort);
1190 export function commentSortSortType(tree: CommentNodeI[], sort: SortType) {
1191 commentSort(tree, convertCommentSortType(sort));
1194 function convertCommentSortType(sort: SortType): CommentSortType {
1196 sort == SortType.TopAll ||
1197 sort == SortType.TopDay ||
1198 sort == SortType.TopWeek ||
1199 sort == SortType.TopMonth ||
1200 sort == SortType.TopYear
1202 return CommentSortType.Top;
1203 } else if (sort == SortType.New) {
1204 return CommentSortType.New;
1205 } else if (sort == SortType.Hot || sort == SortType.Active) {
1206 return CommentSortType.Hot;
1208 return CommentSortType.Hot;
1212 export function buildCommentsTree(
1213 comments: CommentView[],
1214 commentSortType: CommentSortType
1216 let map = new Map<number, CommentNodeI>();
1217 for (let comment_view of comments) {
1218 let node: CommentNodeI = {
1219 comment_view: comment_view,
1222 map.set(comment_view.comment.id, { ...node });
1224 let tree: CommentNodeI[] = [];
1225 for (let comment_view of comments) {
1226 let child = map.get(comment_view.comment.id);
1227 let parent_id = comment_view.comment.parent_id;
1229 let parent = map.get(parent_id);
1230 // Necessary because blocked comment might not exist
1232 parent.children.push(child);
1241 commentSort(tree, commentSortType);
1246 function setDepth(node: CommentNodeI, i = 0) {
1247 for (let child of node.children) {
1249 setDepth(child, i + 1);
1253 export function insertCommentIntoTree(tree: CommentNodeI[], cv: CommentView) {
1254 // Building a fake node to be used for later
1255 let node: CommentNodeI = {
1261 if (cv.comment.parent_id) {
1262 let parentComment = searchCommentTree(tree, cv.comment.parent_id);
1263 if (parentComment) {
1264 node.depth = parentComment.depth + 1;
1265 parentComment.children.unshift(node);
1272 export function searchCommentTree(
1273 tree: CommentNodeI[],
1276 for (let node of tree) {
1277 if (node.comment_view.comment.id === id) {
1281 for (const child of node.children) {
1282 const res = searchCommentTree([child], id);
1292 export const colorList: string[] = [
1301 function hsl(num: number) {
1302 return `hsla(${num}, 35%, 50%, 1)`;
1305 export function previewLines(
1314 // Use lines * 2 because markdown requires 2 lines
1315 .slice(0, maxLines * 2)
1320 export function hostname(url: string): string {
1321 let cUrl = new URL(url);
1322 return cUrl.port ? `${cUrl.hostname}:${cUrl.port}` : `${cUrl.hostname}`;
1325 export function validTitle(title?: string): boolean {
1326 // Initial title is null, minimum length is taken care of by textarea's minLength={3}
1327 if (title === null || title.length < 3) return true;
1329 const regex = new RegExp(/.*\S.*/, "g");
1331 return regex.test(title);
1334 export function siteBannerCss(banner: string): string {
1336 background-image: linear-gradient( rgba(0, 0, 0, 0.8), rgba(0, 0, 0, 0.8) ) ,url("${banner}"); \
1337 background-attachment: fixed; \
1338 background-position: top; \
1339 background-repeat: no-repeat; \
1340 background-size: 100% cover; \
1343 max-height: 100vh; \
1347 export function isBrowser() {
1348 return typeof window !== "undefined";
1351 export function setIsoData(context: any): IsoData {
1352 let isoData: IsoData = isBrowser()
1354 : context.router.staticContext;
1358 export function wsSubscribe(parseMessage: any): Subscription {
1360 return WebSocketService.Instance.subject
1361 .pipe(retryWhen(errors => errors.pipe(delay(3000), take(10))))
1363 msg => parseMessage(msg),
1364 err => console.error(err),
1365 () => console.log("complete")
1372 export function setOptionalAuth(obj: any, auth = UserService.Instance.auth) {
1378 export function authField(
1380 auth = UserService.Instance.auth
1382 if (auth == null && throwErr) {
1383 toast(i18n.t("not_logged_in"), "danger");
1384 throw "Not logged in";
1390 moment.updateLocale("en", {
1411 export function saveScrollPosition(context: any) {
1412 let path: string = context.router.route.location.pathname;
1413 let y = window.scrollY;
1414 sessionStorage.setItem(`scrollPosition_${path}`, y.toString());
1417 export function restoreScrollPosition(context: any) {
1418 let path: string = context.router.route.location.pathname;
1419 let y = Number(sessionStorage.getItem(`scrollPosition_${path}`));
1420 window.scrollTo(0, y);
1423 export function showLocal(isoData: IsoData): boolean {
1424 return isoData.site_res.federated_instances?.linked.length > 0;
1427 interface ChoicesValue {
1432 export function communityToChoice(cv: CommunityView): ChoicesValue {
1433 let choice: ChoicesValue = {
1434 value: cv.community.id.toString(),
1435 label: communitySelectName(cv),
1440 export function personToChoice(pvs: PersonViewSafe): ChoicesValue {
1441 let choice: ChoicesValue = {
1442 value: pvs.person.id.toString(),
1443 label: personSelectName(pvs),
1448 export async function fetchCommunities(q: string) {
1449 let form: Search = {
1451 type_: SearchType.Communities,
1452 sort: SortType.TopAll,
1453 listing_type: ListingType.All,
1456 auth: authField(false),
1458 let client = new LemmyHttp(httpBase);
1459 return client.search(form);
1462 export async function fetchUsers(q: string) {
1463 let form: Search = {
1465 type_: SearchType.Users,
1466 sort: SortType.TopAll,
1467 listing_type: ListingType.All,
1470 auth: authField(false),
1472 let client = new LemmyHttp(httpBase);
1473 return client.search(form);
1476 export const choicesConfig = {
1478 searchResultLimit: fetchLimit,
1480 containerOuter: "choices",
1481 containerInner: "choices__inner bg-secondary border-0",
1482 input: "form-control",
1483 inputCloned: "choices__input--cloned",
1484 list: "choices__list",
1485 listItems: "choices__list--multiple",
1486 listSingle: "choices__list--single",
1487 listDropdown: "choices__list--dropdown",
1488 item: "choices__item bg-secondary",
1489 itemSelectable: "choices__item--selectable",
1490 itemDisabled: "choices__item--disabled",
1491 itemChoice: "choices__item--choice",
1492 placeholder: "choices__placeholder",
1493 group: "choices__group",
1494 groupHeading: "choices__heading",
1495 button: "choices__button",
1496 activeState: "is-active",
1497 focusState: "is-focused",
1498 openState: "is-open",
1499 disabledState: "is-disabled",
1500 highlightedState: "text-info",
1501 selectedState: "text-info",
1502 flippedState: "is-flipped",
1503 loadingState: "is-loading",
1504 noResults: "has-no-results",
1505 noChoices: "has-no-choices",
1509 export function communitySelectName(cv: CommunityView): string {
1510 return cv.community.local
1511 ? cv.community.title
1512 : `${hostname(cv.community.actor_id)}/${cv.community.title}`;
1515 export function personSelectName(pvs: PersonViewSafe): string {
1516 let pName = pvs.person.display_name || pvs.person.name;
1517 return pvs.person.local ? pName : `${hostname(pvs.person.actor_id)}/${pName}`;
1520 export function initializeSite(site: GetSiteResponse) {
1521 UserService.Instance.myUserInfo = site.my_user;
1522 i18n.changeLanguage(getLanguage());
1525 const SHORTNUM_SI_FORMAT = new Intl.NumberFormat("en-US", {
1526 maximumSignificantDigits: 3,
1528 notation: "compact",
1529 compactDisplay: "short",
1532 export function numToSI(value: number): string {
1533 return SHORTNUM_SI_FORMAT.format(value);
1536 export function isBanned(ps: PersonSafe): boolean {
1537 // Add Z to convert from UTC date
1538 if (ps.ban_expires) {
1539 if (ps.banned && new Date(ps.ban_expires + "Z") > new Date()) {