1 import emojiShortName from "emoji-short-name";
3 BlockCommunityResponse,
23 WebSocketJsonResponse,
25 } from "lemmy-js-client";
26 import markdown_it from "markdown-it";
27 import markdown_it_container from "markdown-it-container";
28 import markdown_it_sub from "markdown-it-sub";
29 import markdown_it_sup from "markdown-it-sup";
30 import moment from "moment";
31 import "moment/locale/bg";
32 import "moment/locale/ca";
33 import "moment/locale/cy";
34 import "moment/locale/da";
35 import "moment/locale/de";
36 import "moment/locale/el";
37 import "moment/locale/eo";
38 import "moment/locale/es";
39 import "moment/locale/eu";
40 import "moment/locale/fa";
41 import "moment/locale/fi";
42 import "moment/locale/fr";
43 import "moment/locale/ga";
44 import "moment/locale/gl";
45 import "moment/locale/hi";
46 import "moment/locale/hr";
47 import "moment/locale/hu";
48 import "moment/locale/id";
49 import "moment/locale/it";
50 import "moment/locale/ja";
51 import "moment/locale/ka";
52 import "moment/locale/km";
53 import "moment/locale/ko";
54 import "moment/locale/nb";
55 import "moment/locale/nl";
56 import "moment/locale/pl";
57 import "moment/locale/pt-br";
58 import "moment/locale/ru";
59 import "moment/locale/sk";
60 import "moment/locale/sq";
61 import "moment/locale/sr";
62 import "moment/locale/sv";
63 import "moment/locale/tr";
64 import "moment/locale/uk";
65 import "moment/locale/vi";
66 import "moment/locale/zh-cn";
67 import { Subscription } from "rxjs";
68 import { delay, retryWhen, take } from "rxjs/operators";
69 import tippy from "tippy.js";
70 import Toastify from "toastify-js";
71 import { httpBase } from "./env";
72 import { i18n } from "./i18next";
74 CommentNode as CommentNodeI,
78 } from "./interfaces";
79 import { UserService, WebSocketService } from "./services";
83 Tribute = require("tributejs");
86 export const wsClient = new LemmyWebsocket();
88 export const favIconUrl = "/static/assets/icons/favicon.svg";
89 export const favIconPngUrl = "/static/assets/icons/apple-touch-icon.png";
91 // export const defaultFavIcon = `${window.location.protocol}//${window.location.host}${favIconPngUrl}`;
92 export const repoUrl = "https://github.com/LemmyNet";
93 export const joinLemmyUrl = "https://join-lemmy.org";
94 export const supportLemmyUrl = `${joinLemmyUrl}/support`;
95 export const docsUrl = `${joinLemmyUrl}/docs/en/index.html`;
96 export const helpGuideUrl = `${joinLemmyUrl}/docs/en/about/guide.html`; // TODO find a way to redirect to the non-en folder
97 export const markdownHelpUrl = `${helpGuideUrl}#markdown-guide`;
98 export const sortingHelpUrl = `${helpGuideUrl}#sorting`;
99 export const archiveUrl = "https://archive.is";
100 export const elementUrl = "https://element.io/";
102 export const postRefetchSeconds: number = 60 * 1000;
103 export const fetchLimit = 20;
104 export const mentionDropdownFetchLimit = 10;
106 export const languages = [
150 export const themes = [
166 const DEFAULT_ALPHABET =
167 "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
169 function getRandomCharFromAlphabet(alphabet: string): string {
170 return alphabet.charAt(Math.floor(Math.random() * alphabet.length));
173 export function randomStr(
174 idDesiredLength = 20,
175 alphabet = DEFAULT_ALPHABET
178 * Create n-long array and map it to random chars from given alphabet.
179 * Then join individual chars as string
181 return Array.from({ length: idDesiredLength })
183 return getRandomCharFromAlphabet(alphabet);
188 export function wsJsonToRes<ResponseType>(
189 msg: WebSocketJsonResponse<ResponseType>
190 ): WebSocketResponse<ResponseType> {
197 export function wsUserOp(msg: any): UserOperation {
198 let opStr: string = msg.op;
199 return UserOperation[opStr];
202 export const md = new markdown_it({
207 .use(markdown_it_sub)
208 .use(markdown_it_sup)
209 .use(markdown_it_container, "spoiler", {
210 validate: function (params: any) {
211 return params.trim().match(/^spoiler\s+(.*)$/);
214 render: function (tokens: any, idx: any) {
215 var m = tokens[idx].info.trim().match(/^spoiler\s+(.*)$/);
217 if (tokens[idx].nesting === 1) {
219 return `<details><summary> ${md.utils.escapeHtml(m[1])} </summary>\n`;
222 return "</details>\n";
227 export function hotRankComment(comment_view: CommentView): number {
228 return hotRank(comment_view.counts.score, comment_view.comment.published);
231 export function hotRankActivePost(post_view: PostView): number {
232 return hotRank(post_view.counts.score, post_view.counts.newest_comment_time);
235 export function hotRankPost(post_view: PostView): number {
236 return hotRank(post_view.counts.score, post_view.post.published);
239 export function hotRank(score: number, timeStr: string): number {
240 // Rank = ScaleFactor * sign(Score) * log(1 + abs(Score)) / (Time + 2)^Gravity
241 let date: Date = new Date(timeStr + "Z"); // Add Z to convert from UTC date
242 let now: Date = new Date();
243 let hoursElapsed: number = (now.getTime() - date.getTime()) / 36e5;
246 (10000 * Math.log10(Math.max(1, 3 + score))) /
247 Math.pow(hoursElapsed + 2, 1.8);
249 // console.log(`Comment: ${comment.content}\nRank: ${rank}\nScore: ${comment.score}\nHours: ${hoursElapsed}`);
254 export function mdToHtml(text: string) {
255 return { __html: md.render(text) };
258 export function getUnixTime(text: string): number {
259 return text ? new Date(text).getTime() / 1000 : undefined;
262 export function canMod(
263 myUserInfo: MyUserInfo,
268 // You can do moderator actions only on the mods added after you.
270 let yourIndex = modIds.findIndex(
271 id => id == myUserInfo.local_user_view.person.id
273 if (yourIndex == -1) {
276 // onSelf +1 on mod actions not for yourself, IE ban, remove, etc
277 modIds = modIds.slice(0, yourIndex + (onSelf ? 0 : 1));
278 return !modIds.includes(creator_id);
285 export function isMod(modIds: number[], creator_id: number): boolean {
286 return modIds.includes(creator_id);
289 const imageRegex = new RegExp(
290 /(http)?s?:?(\/\/[^"']*\.(?:jpg|jpeg|gif|png|svg|webp))/
292 const videoRegex = new RegExp(`(http)?s?:?(\/\/[^"']*\.(?:mp4))`);
294 export function isImage(url: string) {
295 return imageRegex.test(url);
298 export function isVideo(url: string) {
299 return videoRegex.test(url);
302 export function validURL(str: string) {
303 return !!new URL(str);
306 export function communityRSSUrl(actorId: string, sort: string): string {
307 let url = new URL(actorId);
308 return `${url.origin}/feeds${url.pathname}.xml?sort=${sort}`;
311 export function validEmail(email: string) {
313 /^(([^\s"(),.:;<>@[\\\]]+(\.[^\s"(),.:;<>@[\\\]]+)*)|(".+"))@((\[(?:\d{1,3}\.){3}\d{1,3}])|(([\dA-Za-z\-]+\.)+[A-Za-z]{2,}))$/;
314 return re.test(String(email).toLowerCase());
317 export function capitalizeFirstLetter(str: string): string {
318 return str.charAt(0).toUpperCase() + str.slice(1);
321 export function routeSortTypeToEnum(sort: string): SortType {
322 return SortType[sort];
325 export function listingTypeFromNum(type_: number): ListingType {
326 return Object.values(ListingType)[type_];
329 export function sortTypeFromNum(type_: number): SortType {
330 return Object.values(SortType)[type_];
333 export function routeListingTypeToEnum(type: string): ListingType {
334 return ListingType[type];
337 export function routeDataTypeToEnum(type: string): DataType {
338 return DataType[capitalizeFirstLetter(type)];
341 export function routeSearchTypeToEnum(type: string): SearchType {
342 return SearchType[type];
345 export async function getSiteMetadata(url: string) {
346 let form: GetSiteMetadata = {
349 let client = new LemmyHttp(httpBase);
350 return client.getSiteMetadata(form);
353 export function debounce(func: any, wait = 1000, immediate = false) {
354 // 'private' variable for instance
355 // The returned function will be able to reference this due to closure.
356 // Each call to the returned function will share this common timer.
359 // Calling debounce returns a new anonymous function
361 // reference the context and args for the setTimeout function
362 var args = arguments;
364 // Should the function be called now? If immediate is true
365 // and not already in a timeout then the answer is: Yes
366 var callNow = immediate && !timeout;
368 // This is the basic debounce behaviour where you can call this
369 // function several times, but it will only execute once
370 // [before or after imposing a delay].
371 // Each time the returned function is called, the timer starts over.
372 clearTimeout(timeout);
374 // Set the new timeout
375 timeout = setTimeout(function () {
376 // Inside the timeout function, clear the timeout variable
377 // which will let the next execution run when in 'immediate' mode
380 // Check if the function already ran with the immediate flag
382 // Call the original function with apply
383 // apply lets you define the 'this' object as well as the arguments
384 // (both captured before setTimeout)
385 func.apply(this, args);
389 // Immediate mode and no wait timer? Execute the function..
390 if (callNow) func.apply(this, args);
395 export function getLanguage(override?: string): string {
396 let myUserInfo = UserService.Instance.myUserInfo;
399 (myUserInfo?.local_user_view.local_user.lang
400 ? myUserInfo.local_user_view.local_user.lang
403 if (lang == "browser" && isBrowser()) {
404 return getBrowserLanguage();
410 export function getBrowserLanguage(): string {
411 // Intersect lemmy's langs, with the browser langs
412 let langs = languages ? languages.map(l => l.code) : ["en"];
414 // NOTE, mobile browsers seem to be missing this list, so append en
415 let allowedLangs = navigator.languages
417 .filter(v => langs.includes(v));
418 return allowedLangs[0];
421 export function getMomentLanguage(): string {
422 let lang = getLanguage();
423 if (lang.startsWith("zh")) {
425 } else if (lang.startsWith("sv")) {
427 } else if (lang.startsWith("fr")) {
429 } else if (lang.startsWith("de")) {
431 } else if (lang.startsWith("ru")) {
433 } else if (lang.startsWith("es")) {
435 } else if (lang.startsWith("eo")) {
437 } else if (lang.startsWith("nl")) {
439 } else if (lang.startsWith("it")) {
441 } else if (lang.startsWith("fi")) {
443 } else if (lang.startsWith("ca")) {
445 } else if (lang.startsWith("fa")) {
447 } else if (lang.startsWith("pl")) {
449 } else if (lang.startsWith("pt")) {
451 } else if (lang.startsWith("ja")) {
453 } else if (lang.startsWith("ka")) {
455 } else if (lang.startsWith("hi")) {
457 } else if (lang.startsWith("el")) {
459 } else if (lang.startsWith("eu")) {
461 } else if (lang.startsWith("gl")) {
463 } else if (lang.startsWith("tr")) {
465 } else if (lang.startsWith("hu")) {
467 } else if (lang.startsWith("uk")) {
469 } else if (lang.startsWith("sq")) {
471 } else if (lang.startsWith("km")) {
473 } else if (lang.startsWith("ga")) {
475 } else if (lang.startsWith("sr")) {
477 } else if (lang.startsWith("ko")) {
479 } else if (lang.startsWith("da")) {
481 } else if (lang.startsWith("oc")) {
483 } else if (lang.startsWith("hr")) {
485 } else if (lang.startsWith("th")) {
487 } else if (lang.startsWith("bg")) {
489 } else if (lang.startsWith("id")) {
491 } else if (lang.startsWith("nb")) {
493 } else if (lang.startsWith("cy")) {
495 } else if (lang.startsWith("sk")) {
497 } else if (lang.startsWith("vi")) {
505 export function setTheme(theme: string, forceReload = false) {
509 if (theme === "browser" && !forceReload) {
512 // This is only run on a force reload
513 if (theme == "browser") {
517 // Unload all the other themes
518 for (var i = 0; i < themes.length; i++) {
519 let styleSheet = document.getElementById(themes[i]);
521 styleSheet.setAttribute("disabled", "disabled");
526 .getElementById("default-light")
527 ?.setAttribute("disabled", "disabled");
528 document.getElementById("default-dark")?.setAttribute("disabled", "disabled");
530 // Load the theme dynamically
531 let cssLoc = `/static/assets/css/themes/${theme}.min.css`;
532 loadCss(theme, cssLoc);
533 document.getElementById(theme).removeAttribute("disabled");
536 export function loadCss(id: string, loc: string) {
537 if (!document.getElementById(id)) {
538 var head = document.getElementsByTagName("head")[0];
539 var link = document.createElement("link");
541 link.rel = "stylesheet";
542 link.type = "text/css";
545 head.appendChild(link);
549 export function objectFlip(obj: any) {
551 Object.keys(obj).forEach(key => {
557 export function showAvatars(): boolean {
559 UserService.Instance.myUserInfo?.local_user_view.local_user.show_avatars ||
560 !UserService.Instance.myUserInfo
564 export function showScores(): boolean {
566 UserService.Instance.myUserInfo?.local_user_view.local_user.show_scores ||
567 !UserService.Instance.myUserInfo
571 export function isCakeDay(published: string): boolean {
572 // moment(undefined) or moment.utc(undefined) returns the current date/time
573 // moment(null) or moment.utc(null) returns null
574 const createDate = moment.utc(published || null).local();
575 const currentDate = moment(new Date());
578 createDate.date() === currentDate.date() &&
579 createDate.month() === currentDate.month() &&
580 createDate.year() !== currentDate.year()
584 export function toast(text: string, background = "success") {
586 let backgroundColor = `var(--${background})`;
589 backgroundColor: backgroundColor,
596 export function pictrsDeleteToast(
597 clickToDeleteText: string,
598 deletePictureText: string,
602 let backgroundColor = `var(--light)`;
603 let toast = Toastify({
604 text: clickToDeleteText,
605 backgroundColor: backgroundColor,
611 window.location.replace(deleteUrl);
612 alert(deletePictureText);
621 interface NotifyInfo {
628 export function messageToastify(info: NotifyInfo, router: any) {
630 let htmlBody = info.body ? md.render(info.body) : "";
631 let backgroundColor = `var(--light)`;
633 let toast = Toastify({
634 text: `${htmlBody}<br />${info.name}`,
635 avatar: info.icon ? info.icon : null,
636 backgroundColor: backgroundColor,
637 className: "text-dark",
646 router.history.push(info.link);
653 export function notifyPost(post_view: PostView, router: any) {
654 let info: NotifyInfo = {
655 name: post_view.community.name,
656 icon: post_view.community.icon,
657 link: `/post/${post_view.post.id}`,
658 body: post_view.post.name,
660 notify(info, router);
663 export function notifyComment(comment_view: CommentView, router: any) {
664 let info: NotifyInfo = {
665 name: comment_view.creator.name,
666 icon: comment_view.creator.avatar,
667 link: `/post/${comment_view.post.id}/comment/${comment_view.comment.id}`,
668 body: comment_view.comment.content,
670 notify(info, router);
673 export function notifyPrivateMessage(pmv: PrivateMessageView, router: any) {
674 let info: NotifyInfo = {
675 name: pmv.creator.name,
676 icon: pmv.creator.avatar,
678 body: pmv.private_message.content,
680 notify(info, router);
683 function notify(info: NotifyInfo, router: any) {
684 messageToastify(info, router);
686 if (Notification.permission !== "granted") Notification.requestPermission();
688 var notification = new Notification(info.name, {
693 notification.onclick = (ev: Event): any => {
695 router.history.push(info.link);
700 export function setupTribute() {
702 noMatchTemplate: function () {
709 menuItemTemplate: (item: any) => {
710 let shortName = `:${item.original.key}:`;
711 return `${item.original.val} ${shortName}`;
713 selectTemplate: (item: any) => {
714 return `${item.original.val}`;
716 values: Object.entries(emojiShortName).map(e => {
717 return { key: e[1], val: e[0] };
720 autocompleteMode: true,
722 // menuItemLimit: mentionDropdownFetchLimit,
723 menuShowMinLength: 2,
728 selectTemplate: (item: any) => {
729 let it: PersonTribute = item.original;
730 return `[${it.key}](${it.view.person.actor_id})`;
732 values: (text: string, cb: (persons: PersonTribute[]) => any) => {
733 personSearch(text, (persons: PersonTribute[]) => cb(persons));
736 autocompleteMode: true,
738 // menuItemLimit: mentionDropdownFetchLimit,
739 menuShowMinLength: 2,
745 selectTemplate: (item: any) => {
746 let it: CommunityTribute = item.original;
747 return `[${it.key}](${it.view.community.actor_id})`;
749 values: (text: string, cb: any) => {
750 communitySearch(text, (communities: CommunityTribute[]) =>
755 autocompleteMode: true,
757 // menuItemLimit: mentionDropdownFetchLimit,
758 menuShowMinLength: 2,
764 var tippyInstance: any;
766 tippyInstance = tippy("[data-tippy-content]");
769 export function setupTippy() {
771 tippyInstance.forEach((e: any) => e.destroy());
772 tippyInstance = tippy("[data-tippy-content]", {
774 // Display on "long press"
775 touch: ["hold", 500],
780 interface PersonTribute {
782 view: PersonViewSafe;
785 function personSearch(text: string, cb: (persons: PersonTribute[]) => any) {
789 type_: SearchType.Users,
790 sort: SortType.TopAll,
791 listing_type: ListingType.All,
793 limit: mentionDropdownFetchLimit,
794 auth: authField(false),
797 WebSocketService.Instance.send(wsClient.search(form));
799 let personSub = WebSocketService.Instance.subject.subscribe(
801 let res = wsJsonToRes(msg);
802 if (res.op == UserOperation.Search) {
803 let data = res.data as SearchResponse;
804 let persons: PersonTribute[] = data.users.map(pv => {
805 let tribute: PersonTribute = {
806 key: `@${pv.person.name}@${hostname(pv.person.actor_id)}`,
812 personSub.unsubscribe();
815 err => console.error(err),
816 () => console.log("complete")
823 interface CommunityTribute {
828 function communitySearch(
830 cb: (communities: CommunityTribute[]) => any
835 type_: SearchType.Communities,
836 sort: SortType.TopAll,
837 listing_type: ListingType.All,
839 limit: mentionDropdownFetchLimit,
840 auth: authField(false),
843 WebSocketService.Instance.send(wsClient.search(form));
845 let communitySub = WebSocketService.Instance.subject.subscribe(
847 let res = wsJsonToRes(msg);
848 if (res.op == UserOperation.Search) {
849 let data = res.data as SearchResponse;
850 let communities: CommunityTribute[] = data.communities.map(cv => {
851 let tribute: CommunityTribute = {
852 key: `!${cv.community.name}@${hostname(cv.community.actor_id)}`,
858 communitySub.unsubscribe();
861 err => console.error(err),
862 () => console.log("complete")
869 export function getListingTypeFromProps(props: any): ListingType {
870 return props.match.params.listing_type
871 ? routeListingTypeToEnum(props.match.params.listing_type)
872 : UserService.Instance.myUserInfo
873 ? Object.values(ListingType)[
874 UserService.Instance.myUserInfo.local_user_view.local_user
875 .default_listing_type
880 export function getListingTypeFromPropsNoDefault(props: any): ListingType {
881 return props.match.params.listing_type
882 ? routeListingTypeToEnum(props.match.params.listing_type)
886 // TODO might need to add a user setting for this too
887 export function getDataTypeFromProps(props: any): DataType {
888 return props.match.params.data_type
889 ? routeDataTypeToEnum(props.match.params.data_type)
893 export function getSortTypeFromProps(props: any): SortType {
894 return props.match.params.sort
895 ? routeSortTypeToEnum(props.match.params.sort)
896 : UserService.Instance.myUserInfo
897 ? Object.values(SortType)[
898 UserService.Instance.myUserInfo.local_user_view.local_user
904 export function getPageFromProps(props: any): number {
905 return props.match.params.page ? Number(props.match.params.page) : 1;
908 export function getRecipientIdFromProps(props: any): number {
909 return props.match.params.recipient_id
910 ? Number(props.match.params.recipient_id)
914 export function getIdFromProps(props: any): number {
915 return Number(props.match.params.id);
918 export function getCommentIdFromProps(props: any): number {
919 return Number(props.match.params.comment_id);
922 export function getUsernameFromProps(props: any): string {
923 return props.match.params.username;
926 export function editCommentRes(data: CommentView, comments: CommentView[]) {
927 let found = comments.find(c => c.comment.id == data.comment.id);
929 found.comment.content = data.comment.content;
930 found.comment.updated = data.comment.updated;
931 found.comment.removed = data.comment.removed;
932 found.comment.deleted = data.comment.deleted;
933 found.counts.upvotes = data.counts.upvotes;
934 found.counts.downvotes = data.counts.downvotes;
935 found.counts.score = data.counts.score;
939 export function saveCommentRes(data: CommentView, comments: CommentView[]) {
940 let found = comments.find(c => c.comment.id == data.comment.id);
942 found.saved = data.saved;
946 export function updatePersonBlock(
947 data: BlockPersonResponse
948 ): PersonBlockView[] {
950 UserService.Instance.myUserInfo.person_blocks.push({
951 person: UserService.Instance.myUserInfo.local_user_view.person,
952 target: data.person_view.person,
954 toast(`${i18n.t("blocked")} ${data.person_view.person.name}`);
956 UserService.Instance.myUserInfo.person_blocks =
957 UserService.Instance.myUserInfo.person_blocks.filter(
958 i => i.target.id != data.person_view.person.id
960 toast(`${i18n.t("unblocked")} ${data.person_view.person.name}`);
962 return UserService.Instance.myUserInfo.person_blocks;
965 export function updateCommunityBlock(
966 data: BlockCommunityResponse
967 ): CommunityBlockView[] {
969 UserService.Instance.myUserInfo.community_blocks.push({
970 person: UserService.Instance.myUserInfo.local_user_view.person,
971 community: data.community_view.community,
973 toast(`${i18n.t("blocked")} ${data.community_view.community.name}`);
975 UserService.Instance.myUserInfo.community_blocks =
976 UserService.Instance.myUserInfo.community_blocks.filter(
977 i => i.community.id != data.community_view.community.id
979 toast(`${i18n.t("unblocked")} ${data.community_view.community.name}`);
981 return UserService.Instance.myUserInfo.community_blocks;
984 export function createCommentLikeRes(
986 comments: CommentView[]
988 let found = comments.find(c => c.comment.id === data.comment.id);
990 found.counts.score = data.counts.score;
991 found.counts.upvotes = data.counts.upvotes;
992 found.counts.downvotes = data.counts.downvotes;
993 if (data.my_vote !== null) {
994 found.my_vote = data.my_vote;
999 export function createPostLikeFindRes(data: PostView, posts: PostView[]) {
1000 let found = posts.find(p => p.post.id == data.post.id);
1002 createPostLikeRes(data, found);
1006 export function createPostLikeRes(data: PostView, post_view: PostView) {
1008 post_view.counts.score = data.counts.score;
1009 post_view.counts.upvotes = data.counts.upvotes;
1010 post_view.counts.downvotes = data.counts.downvotes;
1011 if (data.my_vote !== null) {
1012 post_view.my_vote = data.my_vote;
1017 export function editPostFindRes(data: PostView, posts: PostView[]) {
1018 let found = posts.find(p => p.post.id == data.post.id);
1020 editPostRes(data, found);
1024 export function editPostRes(data: PostView, post: PostView) {
1026 post.post.url = data.post.url;
1027 post.post.name = data.post.name;
1028 post.post.nsfw = data.post.nsfw;
1029 post.post.deleted = data.post.deleted;
1030 post.post.removed = data.post.removed;
1031 post.post.stickied = data.post.stickied;
1032 post.post.body = data.post.body;
1033 post.post.locked = data.post.locked;
1034 post.saved = data.saved;
1038 export function commentsToFlatNodes(comments: CommentView[]): CommentNodeI[] {
1039 let nodes: CommentNodeI[] = [];
1040 for (let comment of comments) {
1041 nodes.push({ comment_view: comment });
1046 function commentSort(tree: CommentNodeI[], sort: CommentSortType) {
1047 // First, put removed and deleted comments at the bottom, then do your other sorts
1048 if (sort == CommentSortType.Top) {
1051 +a.comment_view.comment.removed - +b.comment_view.comment.removed ||
1052 +a.comment_view.comment.deleted - +b.comment_view.comment.deleted ||
1053 b.comment_view.counts.score - a.comment_view.counts.score
1055 } else if (sort == CommentSortType.New) {
1058 +a.comment_view.comment.removed - +b.comment_view.comment.removed ||
1059 +a.comment_view.comment.deleted - +b.comment_view.comment.deleted ||
1060 b.comment_view.comment.published.localeCompare(
1061 a.comment_view.comment.published
1064 } else if (sort == CommentSortType.Old) {
1067 +a.comment_view.comment.removed - +b.comment_view.comment.removed ||
1068 +a.comment_view.comment.deleted - +b.comment_view.comment.deleted ||
1069 a.comment_view.comment.published.localeCompare(
1070 b.comment_view.comment.published
1073 } else if (sort == CommentSortType.Hot) {
1076 +a.comment_view.comment.removed - +b.comment_view.comment.removed ||
1077 +a.comment_view.comment.deleted - +b.comment_view.comment.deleted ||
1078 hotRankComment(b.comment_view) - hotRankComment(a.comment_view)
1082 // Go through the children recursively
1083 for (let node of tree) {
1084 if (node.children) {
1085 commentSort(node.children, sort);
1090 export function commentSortSortType(tree: CommentNodeI[], sort: SortType) {
1091 commentSort(tree, convertCommentSortType(sort));
1094 function convertCommentSortType(sort: SortType): CommentSortType {
1096 sort == SortType.TopAll ||
1097 sort == SortType.TopDay ||
1098 sort == SortType.TopWeek ||
1099 sort == SortType.TopMonth ||
1100 sort == SortType.TopYear
1102 return CommentSortType.Top;
1103 } else if (sort == SortType.New) {
1104 return CommentSortType.New;
1105 } else if (sort == SortType.Hot || sort == SortType.Active) {
1106 return CommentSortType.Hot;
1108 return CommentSortType.Hot;
1112 export function buildCommentsTree(
1113 comments: CommentView[],
1114 commentSortType: CommentSortType
1116 let map = new Map<number, CommentNodeI>();
1117 for (let comment_view of comments) {
1118 let node: CommentNodeI = {
1119 comment_view: comment_view,
1122 map.set(comment_view.comment.id, { ...node });
1124 let tree: CommentNodeI[] = [];
1125 for (let comment_view of comments) {
1126 let child = map.get(comment_view.comment.id);
1127 let parent_id = comment_view.comment.parent_id;
1129 let parent = map.get(parent_id);
1130 // Necessary because blocked comment might not exist
1132 parent.children.push(child);
1141 commentSort(tree, commentSortType);
1146 function setDepth(node: CommentNodeI, i = 0) {
1147 for (let child of node.children) {
1149 setDepth(child, i + 1);
1153 export function insertCommentIntoTree(tree: CommentNodeI[], cv: CommentView) {
1154 // Building a fake node to be used for later
1155 let node: CommentNodeI = {
1161 if (cv.comment.parent_id) {
1162 let parentComment = searchCommentTree(tree, cv.comment.parent_id);
1163 if (parentComment) {
1164 node.depth = parentComment.depth + 1;
1165 parentComment.children.unshift(node);
1172 export function searchCommentTree(
1173 tree: CommentNodeI[],
1176 for (let node of tree) {
1177 if (node.comment_view.comment.id === id) {
1181 for (const child of node.children) {
1182 const res = searchCommentTree([child], id);
1192 export const colorList: string[] = [
1201 function hsl(num: number) {
1202 return `hsla(${num}, 35%, 50%, 1)`;
1205 export function previewLines(
1214 // Use lines * 2 because markdown requires 2 lines
1215 .slice(0, maxLines * 2)
1220 export function hostname(url: string): string {
1221 let cUrl = new URL(url);
1222 return cUrl.port ? `${cUrl.hostname}:${cUrl.port}` : `${cUrl.hostname}`;
1225 export function validTitle(title?: string): boolean {
1226 // Initial title is null, minimum length is taken care of by textarea's minLength={3}
1227 if (title === null || title.length < 3) return true;
1229 const regex = new RegExp(/.*\S.*/, "g");
1231 return regex.test(title);
1234 export function siteBannerCss(banner: string): string {
1236 background-image: linear-gradient( rgba(0, 0, 0, 0.8), rgba(0, 0, 0, 0.8) ) ,url("${banner}"); \
1237 background-attachment: fixed; \
1238 background-position: top; \
1239 background-repeat: no-repeat; \
1240 background-size: 100% cover; \
1243 max-height: 100vh; \
1247 export function isBrowser() {
1248 return typeof window !== "undefined";
1251 export function setIsoData(context: any): IsoData {
1252 let isoData: IsoData = isBrowser()
1254 : context.router.staticContext;
1258 export function wsSubscribe(parseMessage: any): Subscription {
1260 return WebSocketService.Instance.subject
1261 .pipe(retryWhen(errors => errors.pipe(delay(3000), take(10))))
1263 msg => parseMessage(msg),
1264 err => console.error(err),
1265 () => console.log("complete")
1272 export function setOptionalAuth(obj: any, auth = UserService.Instance.auth) {
1278 export function authField(
1280 auth = UserService.Instance.auth
1282 if (auth == null && throwErr) {
1283 toast(i18n.t("not_logged_in"), "danger");
1284 throw "Not logged in";
1290 moment.updateLocale("en", {
1311 export function saveScrollPosition(context: any) {
1312 let path: string = context.router.route.location.pathname;
1313 let y = window.scrollY;
1314 sessionStorage.setItem(`scrollPosition_${path}`, y.toString());
1317 export function restoreScrollPosition(context: any) {
1318 let path: string = context.router.route.location.pathname;
1319 let y = Number(sessionStorage.getItem(`scrollPosition_${path}`));
1320 window.scrollTo(0, y);
1323 export function showLocal(isoData: IsoData): boolean {
1324 return isoData.site_res.federated_instances?.linked.length > 0;
1327 interface ChoicesValue {
1332 export function communityToChoice(cv: CommunityView): ChoicesValue {
1333 let choice: ChoicesValue = {
1334 value: cv.community.id.toString(),
1335 label: communitySelectName(cv),
1340 export function personToChoice(pvs: PersonViewSafe): ChoicesValue {
1341 let choice: ChoicesValue = {
1342 value: pvs.person.id.toString(),
1343 label: personSelectName(pvs),
1348 export async function fetchCommunities(q: string) {
1349 let form: Search = {
1351 type_: SearchType.Communities,
1352 sort: SortType.TopAll,
1353 listing_type: ListingType.All,
1356 auth: authField(false),
1358 let client = new LemmyHttp(httpBase);
1359 return client.search(form);
1362 export async function fetchUsers(q: string) {
1363 let form: Search = {
1365 type_: SearchType.Users,
1366 sort: SortType.TopAll,
1367 listing_type: ListingType.All,
1370 auth: authField(false),
1372 let client = new LemmyHttp(httpBase);
1373 return client.search(form);
1376 export const choicesConfig = {
1378 searchResultLimit: fetchLimit,
1380 containerOuter: "choices",
1381 containerInner: "choices__inner bg-secondary border-0",
1382 input: "form-control",
1383 inputCloned: "choices__input--cloned",
1384 list: "choices__list",
1385 listItems: "choices__list--multiple",
1386 listSingle: "choices__list--single",
1387 listDropdown: "choices__list--dropdown",
1388 item: "choices__item bg-secondary",
1389 itemSelectable: "choices__item--selectable",
1390 itemDisabled: "choices__item--disabled",
1391 itemChoice: "choices__item--choice",
1392 placeholder: "choices__placeholder",
1393 group: "choices__group",
1394 groupHeading: "choices__heading",
1395 button: "choices__button",
1396 activeState: "is-active",
1397 focusState: "is-focused",
1398 openState: "is-open",
1399 disabledState: "is-disabled",
1400 highlightedState: "text-info",
1401 selectedState: "text-info",
1402 flippedState: "is-flipped",
1403 loadingState: "is-loading",
1404 noResults: "has-no-results",
1405 noChoices: "has-no-choices",
1409 export function communitySelectName(cv: CommunityView): string {
1410 return cv.community.local
1412 : `${hostname(cv.community.actor_id)}/${cv.community.name}`;
1415 export function personSelectName(pvs: PersonViewSafe): string {
1416 return pvs.person.local
1418 : `${hostname(pvs.person.actor_id)}/${pvs.person.name}`;
1421 export function initializeSite(site: GetSiteResponse) {
1422 UserService.Instance.myUserInfo = site.my_user;
1423 i18n.changeLanguage(getLanguage());