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 = [
180 const DEFAULT_ALPHABET =
181 "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
183 function getRandomCharFromAlphabet(alphabet: string): string {
184 return alphabet.charAt(Math.floor(Math.random() * alphabet.length));
187 export function randomStr(
188 idDesiredLength = 20,
189 alphabet = DEFAULT_ALPHABET
192 * Create n-long array and map it to random chars from given alphabet.
193 * Then join individual chars as string
195 return Array.from({ length: idDesiredLength })
197 return getRandomCharFromAlphabet(alphabet);
202 export function wsJsonToRes<ResponseType>(
203 msg: WebSocketJsonResponse<ResponseType>
204 ): WebSocketResponse<ResponseType> {
211 export function wsUserOp(msg: any): UserOperation {
212 let opStr: string = msg.op;
213 return UserOperation[opStr];
216 export const md = new markdown_it({
221 .use(markdown_it_sub)
222 .use(markdown_it_sup)
223 .use(markdown_it_html5_embed, {
225 useImageSyntax: true, // Enables video/audio embed with ![]() syntax (default)
227 audio: 'controls preload="metadata"',
229 'width="100%" max-height="100%" controls loop preload="metadata"',
233 .use(markdown_it_container, "spoiler", {
234 validate: function (params: any) {
235 return params.trim().match(/^spoiler\s+(.*)$/);
238 render: function (tokens: any, idx: any) {
239 var m = tokens[idx].info.trim().match(/^spoiler\s+(.*)$/);
241 if (tokens[idx].nesting === 1) {
243 return `<details><summary> ${md.utils.escapeHtml(m[1])} </summary>\n`;
246 return "</details>\n";
251 export function hotRankComment(comment_view: CommentView): number {
252 return hotRank(comment_view.counts.score, comment_view.comment.published);
255 export function hotRankActivePost(post_view: PostView): number {
256 return hotRank(post_view.counts.score, post_view.counts.newest_comment_time);
259 export function hotRankPost(post_view: PostView): number {
260 return hotRank(post_view.counts.score, post_view.post.published);
263 export function hotRank(score: number, timeStr: string): number {
264 // Rank = ScaleFactor * sign(Score) * log(1 + abs(Score)) / (Time + 2)^Gravity
265 let date: Date = new Date(timeStr + "Z"); // Add Z to convert from UTC date
266 let now: Date = new Date();
267 let hoursElapsed: number = (now.getTime() - date.getTime()) / 36e5;
270 (10000 * Math.log10(Math.max(1, 3 + score))) /
271 Math.pow(hoursElapsed + 2, 1.8);
273 // console.log(`Comment: ${comment.content}\nRank: ${rank}\nScore: ${comment.score}\nHours: ${hoursElapsed}`);
278 export function mdToHtml(text: string) {
279 return { __html: md.render(text) };
282 export function getUnixTime(text: string): number {
283 return text ? new Date(text).getTime() / 1000 : undefined;
286 export function canMod(
287 myUserInfo: MyUserInfo,
292 // You can do moderator actions only on the mods added after you.
294 let yourIndex = modIds.findIndex(
295 id => id == myUserInfo.local_user_view.person.id
297 if (yourIndex == -1) {
300 // onSelf +1 on mod actions not for yourself, IE ban, remove, etc
301 modIds = modIds.slice(0, yourIndex + (onSelf ? 0 : 1));
302 return !modIds.includes(creator_id);
309 export function isMod(modIds: number[], creator_id: number): boolean {
310 return modIds.includes(creator_id);
313 const imageRegex = new RegExp(
314 /(http)?s?:?(\/\/[^"']*\.(?:jpg|jpeg|gif|png|svg|webp))/
316 const videoRegex = new RegExp(`(http)?s?:?(\/\/[^"']*\.(?:mp4))`);
318 export function isImage(url: string) {
319 return imageRegex.test(url);
322 export function isVideo(url: string) {
323 return videoRegex.test(url);
326 export function validURL(str: string) {
327 return !!new URL(str);
330 export function communityRSSUrl(actorId: string, sort: string): string {
331 let url = new URL(actorId);
332 return `${url.origin}/feeds${url.pathname}.xml?sort=${sort}`;
335 export function validEmail(email: string) {
337 /^(([^\s"(),.:;<>@[\\\]]+(\.[^\s"(),.:;<>@[\\\]]+)*)|(".+"))@((\[(?:\d{1,3}\.){3}\d{1,3}])|(([\dA-Za-z\-]+\.)+[A-Za-z]{2,}))$/;
338 return re.test(String(email).toLowerCase());
341 export function capitalizeFirstLetter(str: string): string {
342 return str.charAt(0).toUpperCase() + str.slice(1);
345 export function routeSortTypeToEnum(sort: string): SortType {
346 return SortType[sort];
349 export function listingTypeFromNum(type_: number): ListingType {
350 return Object.values(ListingType)[type_];
353 export function sortTypeFromNum(type_: number): SortType {
354 return Object.values(SortType)[type_];
357 export function routeListingTypeToEnum(type: string): ListingType {
358 return ListingType[type];
361 export function routeDataTypeToEnum(type: string): DataType {
362 return DataType[capitalizeFirstLetter(type)];
365 export function routeSearchTypeToEnum(type: string): SearchType {
366 return SearchType[type];
369 export async function getSiteMetadata(url: string) {
370 let form: GetSiteMetadata = {
373 let client = new LemmyHttp(httpBase);
374 return client.getSiteMetadata(form);
377 export function debounce(func: any, wait = 1000, immediate = false) {
378 // 'private' variable for instance
379 // The returned function will be able to reference this due to closure.
380 // Each call to the returned function will share this common timer.
383 // Calling debounce returns a new anonymous function
385 // reference the context and args for the setTimeout function
386 var args = arguments;
388 // Should the function be called now? If immediate is true
389 // and not already in a timeout then the answer is: Yes
390 var callNow = immediate && !timeout;
392 // This is the basic debounce behaviour where you can call this
393 // function several times, but it will only execute once
394 // [before or after imposing a delay].
395 // Each time the returned function is called, the timer starts over.
396 clearTimeout(timeout);
398 // Set the new timeout
399 timeout = setTimeout(function () {
400 // Inside the timeout function, clear the timeout variable
401 // which will let the next execution run when in 'immediate' mode
404 // Check if the function already ran with the immediate flag
406 // Call the original function with apply
407 // apply lets you define the 'this' object as well as the arguments
408 // (both captured before setTimeout)
409 func.apply(this, args);
413 // Immediate mode and no wait timer? Execute the function..
414 if (callNow) func.apply(this, args);
418 export function getNativeLanguageName(code: string): string {
419 let [isoCode, qualifier] = code.split("_");
421 let native = ISO6391.getNativeName(isoCode) || code;
424 return `${native}_${qualifier}`;
431 export function getLanguage(override?: string): string {
432 let myUserInfo = UserService.Instance.myUserInfo;
435 (myUserInfo?.local_user_view.local_user.lang
436 ? myUserInfo.local_user_view.local_user.lang
439 if (lang == "browser" && isBrowser()) {
440 return getBrowserLanguage();
446 export function getBrowserLanguage(): string {
447 // Intersect lemmy's langs, with the browser langs
448 let langs = languages ? languages.map(l => l.code) : ["en"];
450 // NOTE, mobile browsers seem to be missing this list, so append en
451 let allowedLangs = navigator.languages
453 .filter(v => langs.includes(v));
454 return allowedLangs[0];
457 export function getMomentLanguage(): string {
458 let lang = getLanguage();
459 if (lang.startsWith("zh")) {
461 } else if (lang.startsWith("sv")) {
463 } else if (lang.startsWith("fr")) {
465 } else if (lang.startsWith("de")) {
467 } else if (lang.startsWith("ru")) {
469 } else if (lang.startsWith("es")) {
471 } else if (lang.startsWith("eo")) {
473 } else if (lang.startsWith("nl")) {
475 } else if (lang.startsWith("it")) {
477 } else if (lang.startsWith("fi")) {
479 } else if (lang.startsWith("ca")) {
481 } else if (lang.startsWith("fa")) {
483 } else if (lang.startsWith("pl")) {
485 } else if (lang.startsWith("pt_BR")) {
487 } else if (lang.startsWith("ja")) {
489 } else if (lang.startsWith("ka")) {
491 } else if (lang.startsWith("hi")) {
493 } else if (lang.startsWith("el")) {
495 } else if (lang.startsWith("eu")) {
497 } else if (lang.startsWith("gl")) {
499 } else if (lang.startsWith("tr")) {
501 } else if (lang.startsWith("hu")) {
503 } else if (lang.startsWith("uk")) {
505 } else if (lang.startsWith("sq")) {
507 } else if (lang.startsWith("km")) {
509 } else if (lang.startsWith("ga")) {
511 } else if (lang.startsWith("sr")) {
513 } else if (lang.startsWith("ko")) {
515 } else if (lang.startsWith("da")) {
517 } else if (lang.startsWith("oc")) {
519 } else if (lang.startsWith("hr")) {
521 } else if (lang.startsWith("th")) {
523 } else if (lang.startsWith("bg")) {
525 } else if (lang.startsWith("id")) {
527 } else if (lang.startsWith("nb")) {
529 } else if (lang.startsWith("cy")) {
531 } else if (lang.startsWith("sk")) {
533 } else if (lang.startsWith("vi")) {
535 } else if (lang.startsWith("pt")) {
537 } else if (lang.startsWith("ar")) {
539 } else if (lang.startsWith("bn")) {
541 } else if (lang.startsWith("ml")) {
543 } else if (lang.startsWith("cs")) {
551 export function setTheme(theme: string, forceReload = false) {
555 if (theme === "browser" && !forceReload) {
558 // This is only run on a force reload
559 if (theme == "browser") {
563 // Unload all the other themes
564 for (var i = 0; i < themes.length; i++) {
565 let styleSheet = document.getElementById(themes[i]);
567 styleSheet.setAttribute("disabled", "disabled");
572 .getElementById("default-light")
573 ?.setAttribute("disabled", "disabled");
574 document.getElementById("default-dark")?.setAttribute("disabled", "disabled");
576 // Load the theme dynamically
577 let cssLoc = `/static/assets/css/themes/${theme}.min.css`;
578 loadCss(theme, cssLoc);
579 document.getElementById(theme).removeAttribute("disabled");
582 export function loadCss(id: string, loc: string) {
583 if (!document.getElementById(id)) {
584 var head = document.getElementsByTagName("head")[0];
585 var link = document.createElement("link");
587 link.rel = "stylesheet";
588 link.type = "text/css";
591 head.appendChild(link);
595 export function objectFlip(obj: any) {
597 Object.keys(obj).forEach(key => {
603 export function showAvatars(): boolean {
605 UserService.Instance.myUserInfo?.local_user_view.local_user.show_avatars ||
606 !UserService.Instance.myUserInfo
610 export function showScores(): boolean {
612 UserService.Instance.myUserInfo?.local_user_view.local_user.show_scores ||
613 !UserService.Instance.myUserInfo
617 export function isCakeDay(published: string): boolean {
618 // moment(undefined) or moment.utc(undefined) returns the current date/time
619 // moment(null) or moment.utc(null) returns null
620 const createDate = moment.utc(published || null).local();
621 const currentDate = moment(new Date());
624 createDate.date() === currentDate.date() &&
625 createDate.month() === currentDate.month() &&
626 createDate.year() !== currentDate.year()
630 export function toast(text: string, background = "success") {
632 let backgroundColor = `var(--${background})`;
635 backgroundColor: backgroundColor,
642 export function pictrsDeleteToast(
643 clickToDeleteText: string,
644 deletePictureText: string,
648 let backgroundColor = `var(--light)`;
649 let toast = Toastify({
650 text: clickToDeleteText,
651 backgroundColor: backgroundColor,
657 window.location.replace(deleteUrl);
658 alert(deletePictureText);
667 interface NotifyInfo {
674 export function messageToastify(info: NotifyInfo, router: any) {
676 let htmlBody = info.body ? md.render(info.body) : "";
677 let backgroundColor = `var(--light)`;
679 let toast = Toastify({
680 text: `${htmlBody}<br />${info.name}`,
681 avatar: info.icon ? info.icon : null,
682 backgroundColor: backgroundColor,
683 className: "text-dark",
692 router.history.push(info.link);
699 export function notifyPost(post_view: PostView, router: any) {
700 let info: NotifyInfo = {
701 name: post_view.community.name,
702 icon: post_view.community.icon,
703 link: `/post/${post_view.post.id}`,
704 body: post_view.post.name,
706 notify(info, router);
709 export function notifyComment(comment_view: CommentView, router: any) {
710 let info: NotifyInfo = {
711 name: comment_view.creator.name,
712 icon: comment_view.creator.avatar,
713 link: `/post/${comment_view.post.id}/comment/${comment_view.comment.id}`,
714 body: comment_view.comment.content,
716 notify(info, router);
719 export function notifyPrivateMessage(pmv: PrivateMessageView, router: any) {
720 let info: NotifyInfo = {
721 name: pmv.creator.name,
722 icon: pmv.creator.avatar,
724 body: pmv.private_message.content,
726 notify(info, router);
729 function notify(info: NotifyInfo, router: any) {
730 messageToastify(info, router);
732 // TODO absolute nightmare bug, but notifs are currently broken.
733 // Notification.new will try to do a browser fetch ???
735 // if (Notification.permission !== "granted") Notification.requestPermission();
737 // var notification = new Notification(info.name, {
742 // notification.onclick = (ev: Event): any => {
743 // ev.preventDefault();
744 // router.history.push(info.link);
749 export function setupTribute() {
751 noMatchTemplate: function () {
758 menuItemTemplate: (item: any) => {
759 let shortName = `:${item.original.key}:`;
760 return `${item.original.val} ${shortName}`;
762 selectTemplate: (item: any) => {
763 return `${item.original.val}`;
765 values: Object.entries(emojiShortName).map(e => {
766 return { key: e[1], val: e[0] };
769 autocompleteMode: true,
771 // menuItemLimit: mentionDropdownFetchLimit,
772 menuShowMinLength: 2,
777 selectTemplate: (item: any) => {
778 let it: PersonTribute = item.original;
779 return `[${it.key}](${it.view.person.actor_id})`;
781 values: (text: string, cb: (persons: PersonTribute[]) => any) => {
782 personSearch(text, (persons: PersonTribute[]) => cb(persons));
785 autocompleteMode: true,
787 // menuItemLimit: mentionDropdownFetchLimit,
788 menuShowMinLength: 2,
794 selectTemplate: (item: any) => {
795 let it: CommunityTribute = item.original;
796 return `[${it.key}](${it.view.community.actor_id})`;
798 values: (text: string, cb: any) => {
799 communitySearch(text, (communities: CommunityTribute[]) =>
804 autocompleteMode: true,
806 // menuItemLimit: mentionDropdownFetchLimit,
807 menuShowMinLength: 2,
813 var tippyInstance: any;
815 tippyInstance = tippy("[data-tippy-content]");
818 export function setupTippy() {
820 tippyInstance.forEach((e: any) => e.destroy());
821 tippyInstance = tippy("[data-tippy-content]", {
823 // Display on "long press"
824 touch: ["hold", 500],
829 interface PersonTribute {
831 view: PersonViewSafe;
834 function personSearch(text: string, cb: (persons: PersonTribute[]) => any) {
838 type_: SearchType.Users,
839 sort: SortType.TopAll,
840 listing_type: ListingType.All,
842 limit: mentionDropdownFetchLimit,
843 auth: authField(false),
846 WebSocketService.Instance.send(wsClient.search(form));
848 let personSub = WebSocketService.Instance.subject.subscribe(
850 let res = wsJsonToRes(msg);
851 if (res.op == UserOperation.Search) {
852 let data = res.data as SearchResponse;
853 let persons: PersonTribute[] = data.users.map(pv => {
854 let tribute: PersonTribute = {
855 key: `@${pv.person.name}@${hostname(pv.person.actor_id)}`,
861 personSub.unsubscribe();
864 err => console.error(err),
865 () => console.log("complete")
872 interface CommunityTribute {
877 function communitySearch(
879 cb: (communities: CommunityTribute[]) => any
884 type_: SearchType.Communities,
885 sort: SortType.TopAll,
886 listing_type: ListingType.All,
888 limit: mentionDropdownFetchLimit,
889 auth: authField(false),
892 WebSocketService.Instance.send(wsClient.search(form));
894 let communitySub = WebSocketService.Instance.subject.subscribe(
896 let res = wsJsonToRes(msg);
897 if (res.op == UserOperation.Search) {
898 let data = res.data as SearchResponse;
899 let communities: CommunityTribute[] = data.communities.map(cv => {
900 let tribute: CommunityTribute = {
901 key: `!${cv.community.name}@${hostname(cv.community.actor_id)}`,
907 communitySub.unsubscribe();
910 err => console.error(err),
911 () => console.log("complete")
918 export function getListingTypeFromProps(props: any): ListingType {
919 return props.match.params.listing_type
920 ? routeListingTypeToEnum(props.match.params.listing_type)
921 : UserService.Instance.myUserInfo
922 ? Object.values(ListingType)[
923 UserService.Instance.myUserInfo.local_user_view.local_user
924 .default_listing_type
929 export function getListingTypeFromPropsNoDefault(props: any): ListingType {
930 return props.match.params.listing_type
931 ? routeListingTypeToEnum(props.match.params.listing_type)
935 // TODO might need to add a user setting for this too
936 export function getDataTypeFromProps(props: any): DataType {
937 return props.match.params.data_type
938 ? routeDataTypeToEnum(props.match.params.data_type)
942 export function getSortTypeFromProps(props: any): SortType {
943 return props.match.params.sort
944 ? routeSortTypeToEnum(props.match.params.sort)
945 : UserService.Instance.myUserInfo
946 ? Object.values(SortType)[
947 UserService.Instance.myUserInfo.local_user_view.local_user
953 export function getPageFromProps(props: any): number {
954 return props.match.params.page ? Number(props.match.params.page) : 1;
957 export function getRecipientIdFromProps(props: any): number {
958 return props.match.params.recipient_id
959 ? Number(props.match.params.recipient_id)
963 export function getIdFromProps(props: any): number {
964 return Number(props.match.params.id);
967 export function getCommentIdFromProps(props: any): number {
968 return Number(props.match.params.comment_id);
971 export function getUsernameFromProps(props: any): string {
972 return props.match.params.username;
975 export function editCommentRes(data: CommentView, comments: CommentView[]) {
976 let found = comments.find(c => c.comment.id == data.comment.id);
978 found.comment.content = data.comment.content;
979 found.comment.updated = data.comment.updated;
980 found.comment.removed = data.comment.removed;
981 found.comment.deleted = data.comment.deleted;
982 found.counts.upvotes = data.counts.upvotes;
983 found.counts.downvotes = data.counts.downvotes;
984 found.counts.score = data.counts.score;
988 export function saveCommentRes(data: CommentView, comments: CommentView[]) {
989 let found = comments.find(c => c.comment.id == data.comment.id);
991 found.saved = data.saved;
995 export function updatePersonBlock(
996 data: BlockPersonResponse
997 ): PersonBlockView[] {
999 UserService.Instance.myUserInfo.person_blocks.push({
1000 person: UserService.Instance.myUserInfo.local_user_view.person,
1001 target: data.person_view.person,
1003 toast(`${i18n.t("blocked")} ${data.person_view.person.name}`);
1005 UserService.Instance.myUserInfo.person_blocks =
1006 UserService.Instance.myUserInfo.person_blocks.filter(
1007 i => i.target.id != data.person_view.person.id
1009 toast(`${i18n.t("unblocked")} ${data.person_view.person.name}`);
1011 return UserService.Instance.myUserInfo.person_blocks;
1014 export function updateCommunityBlock(
1015 data: BlockCommunityResponse
1016 ): CommunityBlockView[] {
1018 UserService.Instance.myUserInfo.community_blocks.push({
1019 person: UserService.Instance.myUserInfo.local_user_view.person,
1020 community: data.community_view.community,
1022 toast(`${i18n.t("blocked")} ${data.community_view.community.name}`);
1024 UserService.Instance.myUserInfo.community_blocks =
1025 UserService.Instance.myUserInfo.community_blocks.filter(
1026 i => i.community.id != data.community_view.community.id
1028 toast(`${i18n.t("unblocked")} ${data.community_view.community.name}`);
1030 return UserService.Instance.myUserInfo.community_blocks;
1033 export function createCommentLikeRes(
1035 comments: CommentView[]
1037 let found = comments.find(c => c.comment.id === data.comment.id);
1039 found.counts.score = data.counts.score;
1040 found.counts.upvotes = data.counts.upvotes;
1041 found.counts.downvotes = data.counts.downvotes;
1042 if (data.my_vote !== null) {
1043 found.my_vote = data.my_vote;
1048 export function createPostLikeFindRes(data: PostView, posts: PostView[]) {
1049 let found = posts.find(p => p.post.id == data.post.id);
1051 createPostLikeRes(data, found);
1055 export function createPostLikeRes(data: PostView, post_view: PostView) {
1057 post_view.counts.score = data.counts.score;
1058 post_view.counts.upvotes = data.counts.upvotes;
1059 post_view.counts.downvotes = data.counts.downvotes;
1060 if (data.my_vote !== null) {
1061 post_view.my_vote = data.my_vote;
1066 export function editPostFindRes(data: PostView, posts: PostView[]) {
1067 let found = posts.find(p => p.post.id == data.post.id);
1069 editPostRes(data, found);
1073 export function editPostRes(data: PostView, post: PostView) {
1075 post.post.url = data.post.url;
1076 post.post.name = data.post.name;
1077 post.post.nsfw = data.post.nsfw;
1078 post.post.deleted = data.post.deleted;
1079 post.post.removed = data.post.removed;
1080 post.post.stickied = data.post.stickied;
1081 post.post.body = data.post.body;
1082 post.post.locked = data.post.locked;
1083 post.saved = data.saved;
1087 export function updatePostReportRes(
1088 data: PostReportView,
1089 reports: PostReportView[]
1091 let found = reports.find(p => p.post.id == data.post.id);
1093 found.post_report = data.post_report;
1097 export function updateCommentReportRes(
1098 data: CommentReportView,
1099 reports: CommentReportView[]
1101 let found = reports.find(c => c.comment.id == data.comment.id);
1103 found.comment_report = data.comment_report;
1107 export function commentsToFlatNodes(comments: CommentView[]): CommentNodeI[] {
1108 let nodes: CommentNodeI[] = [];
1109 for (let comment of comments) {
1110 nodes.push({ comment_view: comment });
1115 function commentSort(tree: CommentNodeI[], sort: CommentSortType) {
1116 // First, put removed and deleted comments at the bottom, then do your other sorts
1117 if (sort == CommentSortType.Top) {
1120 +a.comment_view.comment.removed - +b.comment_view.comment.removed ||
1121 +a.comment_view.comment.deleted - +b.comment_view.comment.deleted ||
1122 b.comment_view.counts.score - a.comment_view.counts.score
1124 } else if (sort == CommentSortType.New) {
1127 +a.comment_view.comment.removed - +b.comment_view.comment.removed ||
1128 +a.comment_view.comment.deleted - +b.comment_view.comment.deleted ||
1129 b.comment_view.comment.published.localeCompare(
1130 a.comment_view.comment.published
1133 } else if (sort == CommentSortType.Old) {
1136 +a.comment_view.comment.removed - +b.comment_view.comment.removed ||
1137 +a.comment_view.comment.deleted - +b.comment_view.comment.deleted ||
1138 a.comment_view.comment.published.localeCompare(
1139 b.comment_view.comment.published
1142 } else if (sort == CommentSortType.Hot) {
1145 +a.comment_view.comment.removed - +b.comment_view.comment.removed ||
1146 +a.comment_view.comment.deleted - +b.comment_view.comment.deleted ||
1147 hotRankComment(b.comment_view) - hotRankComment(a.comment_view)
1151 // Go through the children recursively
1152 for (let node of tree) {
1153 if (node.children) {
1154 commentSort(node.children, sort);
1159 export function commentSortSortType(tree: CommentNodeI[], sort: SortType) {
1160 commentSort(tree, convertCommentSortType(sort));
1163 function convertCommentSortType(sort: SortType): CommentSortType {
1165 sort == SortType.TopAll ||
1166 sort == SortType.TopDay ||
1167 sort == SortType.TopWeek ||
1168 sort == SortType.TopMonth ||
1169 sort == SortType.TopYear
1171 return CommentSortType.Top;
1172 } else if (sort == SortType.New) {
1173 return CommentSortType.New;
1174 } else if (sort == SortType.Hot || sort == SortType.Active) {
1175 return CommentSortType.Hot;
1177 return CommentSortType.Hot;
1181 export function buildCommentsTree(
1182 comments: CommentView[],
1183 commentSortType: CommentSortType
1185 let map = new Map<number, CommentNodeI>();
1186 for (let comment_view of comments) {
1187 let node: CommentNodeI = {
1188 comment_view: comment_view,
1191 map.set(comment_view.comment.id, { ...node });
1193 let tree: CommentNodeI[] = [];
1194 for (let comment_view of comments) {
1195 let child = map.get(comment_view.comment.id);
1196 let parent_id = comment_view.comment.parent_id;
1198 let parent = map.get(parent_id);
1199 // Necessary because blocked comment might not exist
1201 parent.children.push(child);
1210 commentSort(tree, commentSortType);
1215 function setDepth(node: CommentNodeI, i = 0) {
1216 for (let child of node.children) {
1218 setDepth(child, i + 1);
1222 export function insertCommentIntoTree(tree: CommentNodeI[], cv: CommentView) {
1223 // Building a fake node to be used for later
1224 let node: CommentNodeI = {
1230 if (cv.comment.parent_id) {
1231 let parentComment = searchCommentTree(tree, cv.comment.parent_id);
1232 if (parentComment) {
1233 node.depth = parentComment.depth + 1;
1234 parentComment.children.unshift(node);
1241 export function searchCommentTree(
1242 tree: CommentNodeI[],
1245 for (let node of tree) {
1246 if (node.comment_view.comment.id === id) {
1250 for (const child of node.children) {
1251 const res = searchCommentTree([child], id);
1261 export const colorList: string[] = [
1270 function hsl(num: number) {
1271 return `hsla(${num}, 35%, 50%, 1)`;
1274 export function previewLines(
1283 // Use lines * 2 because markdown requires 2 lines
1284 .slice(0, maxLines * 2)
1289 export function hostname(url: string): string {
1290 let cUrl = new URL(url);
1291 return cUrl.port ? `${cUrl.hostname}:${cUrl.port}` : `${cUrl.hostname}`;
1294 export function validTitle(title?: string): boolean {
1295 // Initial title is null, minimum length is taken care of by textarea's minLength={3}
1296 if (title === null || title.length < 3) return true;
1298 const regex = new RegExp(/.*\S.*/, "g");
1300 return regex.test(title);
1303 export function siteBannerCss(banner: string): string {
1305 background-image: linear-gradient( rgba(0, 0, 0, 0.8), rgba(0, 0, 0, 0.8) ) ,url("${banner}"); \
1306 background-attachment: fixed; \
1307 background-position: top; \
1308 background-repeat: no-repeat; \
1309 background-size: 100% cover; \
1312 max-height: 100vh; \
1316 export function isBrowser() {
1317 return typeof window !== "undefined";
1320 export function setIsoData(context: any): IsoData {
1321 let isoData: IsoData = isBrowser()
1323 : context.router.staticContext;
1327 export function wsSubscribe(parseMessage: any): Subscription {
1329 return WebSocketService.Instance.subject
1330 .pipe(retryWhen(errors => errors.pipe(delay(3000), take(10))))
1332 msg => parseMessage(msg),
1333 err => console.error(err),
1334 () => console.log("complete")
1341 export function setOptionalAuth(obj: any, auth = UserService.Instance.auth) {
1347 export function authField(
1349 auth = UserService.Instance.auth
1351 if (auth == null && throwErr) {
1352 toast(i18n.t("not_logged_in"), "danger");
1353 throw "Not logged in";
1359 moment.updateLocale("en", {
1380 export function saveScrollPosition(context: any) {
1381 let path: string = context.router.route.location.pathname;
1382 let y = window.scrollY;
1383 sessionStorage.setItem(`scrollPosition_${path}`, y.toString());
1386 export function restoreScrollPosition(context: any) {
1387 let path: string = context.router.route.location.pathname;
1388 let y = Number(sessionStorage.getItem(`scrollPosition_${path}`));
1389 window.scrollTo(0, y);
1392 export function showLocal(isoData: IsoData): boolean {
1393 return isoData.site_res.federated_instances?.linked.length > 0;
1396 interface ChoicesValue {
1401 export function communityToChoice(cv: CommunityView): ChoicesValue {
1402 let choice: ChoicesValue = {
1403 value: cv.community.id.toString(),
1404 label: communitySelectName(cv),
1409 export function personToChoice(pvs: PersonViewSafe): ChoicesValue {
1410 let choice: ChoicesValue = {
1411 value: pvs.person.id.toString(),
1412 label: personSelectName(pvs),
1417 export async function fetchCommunities(q: string) {
1418 let form: Search = {
1420 type_: SearchType.Communities,
1421 sort: SortType.TopAll,
1422 listing_type: ListingType.All,
1425 auth: authField(false),
1427 let client = new LemmyHttp(httpBase);
1428 return client.search(form);
1431 export async function fetchUsers(q: string) {
1432 let form: Search = {
1434 type_: SearchType.Users,
1435 sort: SortType.TopAll,
1436 listing_type: ListingType.All,
1439 auth: authField(false),
1441 let client = new LemmyHttp(httpBase);
1442 return client.search(form);
1445 export const choicesConfig = {
1447 searchResultLimit: fetchLimit,
1449 containerOuter: "choices",
1450 containerInner: "choices__inner bg-secondary border-0",
1451 input: "form-control",
1452 inputCloned: "choices__input--cloned",
1453 list: "choices__list",
1454 listItems: "choices__list--multiple",
1455 listSingle: "choices__list--single",
1456 listDropdown: "choices__list--dropdown",
1457 item: "choices__item bg-secondary",
1458 itemSelectable: "choices__item--selectable",
1459 itemDisabled: "choices__item--disabled",
1460 itemChoice: "choices__item--choice",
1461 placeholder: "choices__placeholder",
1462 group: "choices__group",
1463 groupHeading: "choices__heading",
1464 button: "choices__button",
1465 activeState: "is-active",
1466 focusState: "is-focused",
1467 openState: "is-open",
1468 disabledState: "is-disabled",
1469 highlightedState: "text-info",
1470 selectedState: "text-info",
1471 flippedState: "is-flipped",
1472 loadingState: "is-loading",
1473 noResults: "has-no-results",
1474 noChoices: "has-no-choices",
1478 export function communitySelectName(cv: CommunityView): string {
1479 return cv.community.local
1480 ? cv.community.title
1481 : `${hostname(cv.community.actor_id)}/${cv.community.title}`;
1484 export function personSelectName(pvs: PersonViewSafe): string {
1485 let pName = pvs.person.display_name || pvs.person.name;
1486 return pvs.person.local ? pName : `${hostname(pvs.person.actor_id)}/${pName}`;
1489 export function initializeSite(site: GetSiteResponse) {
1490 UserService.Instance.myUserInfo = site.my_user;
1491 i18n.changeLanguage(getLanguage());
1494 const SHORTNUM_SI_FORMAT = new Intl.NumberFormat("en-US", {
1495 maximumSignificantDigits: 3,
1497 notation: "compact",
1498 compactDisplay: "short",
1501 export function numToSI(value: number): string {
1502 return SHORTNUM_SI_FORMAT.format(value);