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/da";
34 import "moment/locale/de";
35 import "moment/locale/el";
36 import "moment/locale/eo";
37 import "moment/locale/es";
38 import "moment/locale/eu";
39 import "moment/locale/fa";
40 import "moment/locale/fi";
41 import "moment/locale/fr";
42 import "moment/locale/ga";
43 import "moment/locale/gl";
44 import "moment/locale/hi";
45 import "moment/locale/hr";
46 import "moment/locale/hu";
47 import "moment/locale/id";
48 import "moment/locale/it";
49 import "moment/locale/ja";
50 import "moment/locale/ka";
51 import "moment/locale/km";
52 import "moment/locale/ko";
53 import "moment/locale/nb";
54 import "moment/locale/nl";
55 import "moment/locale/pl";
56 import "moment/locale/pt-br";
57 import "moment/locale/ru";
58 import "moment/locale/sq";
59 import "moment/locale/sr";
60 import "moment/locale/sv";
61 import "moment/locale/tr";
62 import "moment/locale/uk";
63 import "moment/locale/zh-cn";
64 import { Subscription } from "rxjs";
65 import { delay, retryWhen, take } from "rxjs/operators";
66 import tippy from "tippy.js";
67 import Toastify from "toastify-js";
68 import { httpBase } from "./env";
69 import { i18n } from "./i18next";
71 CommentNode as CommentNodeI,
75 } from "./interfaces";
76 import { UserService, WebSocketService } from "./services";
80 Tribute = require("tributejs");
83 export const wsClient = new LemmyWebsocket();
85 export const favIconUrl = "/static/assets/icons/favicon.svg";
86 export const favIconPngUrl = "/static/assets/icons/apple-touch-icon.png";
88 // export const defaultFavIcon = `${window.location.protocol}//${window.location.host}${favIconPngUrl}`;
89 export const repoUrl = "https://github.com/LemmyNet";
90 export const joinLemmyUrl = "https://join-lemmy.org";
91 export const supportLemmyUrl = `${joinLemmyUrl}/support`;
92 export const docsUrl = `${joinLemmyUrl}/docs/en/index.html`;
93 export const helpGuideUrl = `${joinLemmyUrl}/docs/en/about/guide.html`; // TODO find a way to redirect to the non-en folder
94 export const markdownHelpUrl = `${helpGuideUrl}#markdown-guide`;
95 export const sortingHelpUrl = `${helpGuideUrl}#sorting`;
96 export const archiveUrl = "https://archive.is";
97 export const elementUrl = "https://element.io/";
99 export const postRefetchSeconds: number = 60 * 1000;
100 export const fetchLimit = 20;
101 export const mentionDropdownFetchLimit = 10;
103 export const languages = [
143 export const themes = [
159 const DEFAULT_ALPHABET =
160 "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
162 function getRandomCharFromAlphabet(alphabet: string): string {
163 return alphabet.charAt(Math.floor(Math.random() * alphabet.length));
166 export function randomStr(
167 idDesiredLength = 20,
168 alphabet = DEFAULT_ALPHABET
171 * Create n-long array and map it to random chars from given alphabet.
172 * Then join individual chars as string
174 return Array.from({ length: idDesiredLength })
176 return getRandomCharFromAlphabet(alphabet);
181 export function wsJsonToRes<ResponseType>(
182 msg: WebSocketJsonResponse<ResponseType>
183 ): WebSocketResponse<ResponseType> {
190 export function wsUserOp(msg: any): UserOperation {
191 let opStr: string = msg.op;
192 return UserOperation[opStr];
195 export const md = new markdown_it({
200 .use(markdown_it_sub)
201 .use(markdown_it_sup)
202 .use(markdown_it_container, "spoiler", {
203 validate: function (params: any) {
204 return params.trim().match(/^spoiler\s+(.*)$/);
207 render: function (tokens: any, idx: any) {
208 var m = tokens[idx].info.trim().match(/^spoiler\s+(.*)$/);
210 if (tokens[idx].nesting === 1) {
212 return `<details><summary> ${md.utils.escapeHtml(m[1])} </summary>\n`;
215 return "</details>\n";
220 export function hotRankComment(comment_view: CommentView): number {
221 return hotRank(comment_view.counts.score, comment_view.comment.published);
224 export function hotRankActivePost(post_view: PostView): number {
225 return hotRank(post_view.counts.score, post_view.counts.newest_comment_time);
228 export function hotRankPost(post_view: PostView): number {
229 return hotRank(post_view.counts.score, post_view.post.published);
232 export function hotRank(score: number, timeStr: string): number {
233 // Rank = ScaleFactor * sign(Score) * log(1 + abs(Score)) / (Time + 2)^Gravity
234 let date: Date = new Date(timeStr + "Z"); // Add Z to convert from UTC date
235 let now: Date = new Date();
236 let hoursElapsed: number = (now.getTime() - date.getTime()) / 36e5;
239 (10000 * Math.log10(Math.max(1, 3 + score))) /
240 Math.pow(hoursElapsed + 2, 1.8);
242 // console.log(`Comment: ${comment.content}\nRank: ${rank}\nScore: ${comment.score}\nHours: ${hoursElapsed}`);
247 export function mdToHtml(text: string) {
248 return { __html: md.render(text) };
251 export function getUnixTime(text: string): number {
252 return text ? new Date(text).getTime() / 1000 : undefined;
255 export function canMod(
256 myUserInfo: MyUserInfo,
261 // You can do moderator actions only on the mods added after you.
263 let yourIndex = modIds.findIndex(
264 id => id == myUserInfo.local_user_view.person.id
266 if (yourIndex == -1) {
269 // onSelf +1 on mod actions not for yourself, IE ban, remove, etc
270 modIds = modIds.slice(0, yourIndex + (onSelf ? 0 : 1));
271 return !modIds.includes(creator_id);
278 export function isMod(modIds: number[], creator_id: number): boolean {
279 return modIds.includes(creator_id);
282 const imageRegex = new RegExp(
283 /(http)?s?:?(\/\/[^"']*\.(?:jpg|jpeg|gif|png|svg|webp))/
285 const videoRegex = new RegExp(`(http)?s?:?(\/\/[^"']*\.(?:mp4))`);
287 export function isImage(url: string) {
288 return imageRegex.test(url);
291 export function isVideo(url: string) {
292 return videoRegex.test(url);
295 export function validURL(str: string) {
296 return !!new URL(str);
299 export function communityRSSUrl(actorId: string, sort: string): string {
300 let url = new URL(actorId);
301 return `${url.origin}/feeds${url.pathname}.xml?sort=${sort}`;
304 export function validEmail(email: string) {
306 /^(([^\s"(),.:;<>@[\\\]]+(\.[^\s"(),.:;<>@[\\\]]+)*)|(".+"))@((\[(?:\d{1,3}\.){3}\d{1,3}])|(([\dA-Za-z\-]+\.)+[A-Za-z]{2,}))$/;
307 return re.test(String(email).toLowerCase());
310 export function capitalizeFirstLetter(str: string): string {
311 return str.charAt(0).toUpperCase() + str.slice(1);
314 export function routeSortTypeToEnum(sort: string): SortType {
315 return SortType[sort];
318 export function listingTypeFromNum(type_: number): ListingType {
319 return Object.values(ListingType)[type_];
322 export function sortTypeFromNum(type_: number): SortType {
323 return Object.values(SortType)[type_];
326 export function routeListingTypeToEnum(type: string): ListingType {
327 return ListingType[type];
330 export function routeDataTypeToEnum(type: string): DataType {
331 return DataType[capitalizeFirstLetter(type)];
334 export function routeSearchTypeToEnum(type: string): SearchType {
335 return SearchType[type];
338 export async function getSiteMetadata(url: string) {
339 let form: GetSiteMetadata = {
342 let client = new LemmyHttp(httpBase);
343 return client.getSiteMetadata(form);
346 export function debounce(func: any, wait = 1000, immediate = false) {
347 // 'private' variable for instance
348 // The returned function will be able to reference this due to closure.
349 // Each call to the returned function will share this common timer.
352 // Calling debounce returns a new anonymous function
354 // reference the context and args for the setTimeout function
355 var args = arguments;
357 // Should the function be called now? If immediate is true
358 // and not already in a timeout then the answer is: Yes
359 var callNow = immediate && !timeout;
361 // This is the basic debounce behaviour where you can call this
362 // function several times, but it will only execute once
363 // [before or after imposing a delay].
364 // Each time the returned function is called, the timer starts over.
365 clearTimeout(timeout);
367 // Set the new timeout
368 timeout = setTimeout(function () {
369 // Inside the timeout function, clear the timeout variable
370 // which will let the next execution run when in 'immediate' mode
373 // Check if the function already ran with the immediate flag
375 // Call the original function with apply
376 // apply lets you define the 'this' object as well as the arguments
377 // (both captured before setTimeout)
378 func.apply(this, args);
382 // Immediate mode and no wait timer? Execute the function..
383 if (callNow) func.apply(this, args);
388 export function getLanguage(override?: string): string {
389 let myUserInfo = UserService.Instance.myUserInfo;
392 (myUserInfo?.local_user_view.local_user.lang
393 ? myUserInfo.local_user_view.local_user.lang
396 if (lang == "browser" && isBrowser()) {
397 return getBrowserLanguage();
403 export function getBrowserLanguage(): string {
404 // Intersect lemmy's langs, with the browser langs
405 let langs = languages ? languages.map(l => l.code) : ["en"];
407 // NOTE, mobile browsers seem to be missing this list, so append en
408 let allowedLangs = navigator.languages
410 .filter(v => langs.includes(v));
411 return allowedLangs[0];
414 export function getMomentLanguage(): string {
415 let lang = getLanguage();
416 if (lang.startsWith("zh")) {
418 } else if (lang.startsWith("sv")) {
420 } else if (lang.startsWith("fr")) {
422 } else if (lang.startsWith("de")) {
424 } else if (lang.startsWith("ru")) {
426 } else if (lang.startsWith("es")) {
428 } else if (lang.startsWith("eo")) {
430 } else if (lang.startsWith("nl")) {
432 } else if (lang.startsWith("it")) {
434 } else if (lang.startsWith("fi")) {
436 } else if (lang.startsWith("ca")) {
438 } else if (lang.startsWith("fa")) {
440 } else if (lang.startsWith("pl")) {
442 } else if (lang.startsWith("pt")) {
444 } else if (lang.startsWith("ja")) {
446 } else if (lang.startsWith("ka")) {
448 } else if (lang.startsWith("hi")) {
450 } else if (lang.startsWith("el")) {
452 } else if (lang.startsWith("eu")) {
454 } else if (lang.startsWith("gl")) {
456 } else if (lang.startsWith("tr")) {
458 } else if (lang.startsWith("hu")) {
460 } else if (lang.startsWith("uk")) {
462 } else if (lang.startsWith("sq")) {
464 } else if (lang.startsWith("km")) {
466 } else if (lang.startsWith("ga")) {
468 } else if (lang.startsWith("sr")) {
470 } else if (lang.startsWith("ko")) {
472 } else if (lang.startsWith("da")) {
474 } else if (lang.startsWith("oc")) {
476 } else if (lang.startsWith("hr")) {
478 } else if (lang.startsWith("th")) {
480 } else if (lang.startsWith("bg")) {
482 } else if (lang.startsWith("id")) {
484 } else if (lang.startsWith("nb")) {
492 export function setTheme(theme: string, forceReload = false) {
496 if (theme === "browser" && !forceReload) {
499 // This is only run on a force reload
500 if (theme == "browser") {
504 // Unload all the other themes
505 for (var i = 0; i < themes.length; i++) {
506 let styleSheet = document.getElementById(themes[i]);
508 styleSheet.setAttribute("disabled", "disabled");
513 .getElementById("default-light")
514 ?.setAttribute("disabled", "disabled");
515 document.getElementById("default-dark")?.setAttribute("disabled", "disabled");
517 // Load the theme dynamically
518 let cssLoc = `/static/assets/css/themes/${theme}.min.css`;
519 loadCss(theme, cssLoc);
520 document.getElementById(theme).removeAttribute("disabled");
523 export function loadCss(id: string, loc: string) {
524 if (!document.getElementById(id)) {
525 var head = document.getElementsByTagName("head")[0];
526 var link = document.createElement("link");
528 link.rel = "stylesheet";
529 link.type = "text/css";
532 head.appendChild(link);
536 export function objectFlip(obj: any) {
538 Object.keys(obj).forEach(key => {
544 export function showAvatars(): boolean {
546 UserService.Instance.myUserInfo?.local_user_view.local_user.show_avatars ||
547 !UserService.Instance.myUserInfo
551 export function showScores(): boolean {
553 UserService.Instance.myUserInfo?.local_user_view.local_user.show_scores ||
554 !UserService.Instance.myUserInfo
558 export function isCakeDay(published: string): boolean {
559 // moment(undefined) or moment.utc(undefined) returns the current date/time
560 // moment(null) or moment.utc(null) returns null
561 const createDate = moment.utc(published || null).local();
562 const currentDate = moment(new Date());
565 createDate.date() === currentDate.date() &&
566 createDate.month() === currentDate.month() &&
567 createDate.year() !== currentDate.year()
571 export function toast(text: string, background = "success") {
573 let backgroundColor = `var(--${background})`;
576 backgroundColor: backgroundColor,
583 export function pictrsDeleteToast(
584 clickToDeleteText: string,
585 deletePictureText: string,
589 let backgroundColor = `var(--light)`;
590 let toast = Toastify({
591 text: clickToDeleteText,
592 backgroundColor: backgroundColor,
598 window.location.replace(deleteUrl);
599 alert(deletePictureText);
608 interface NotifyInfo {
615 export function messageToastify(info: NotifyInfo, router: any) {
617 let htmlBody = info.body ? md.render(info.body) : "";
618 let backgroundColor = `var(--light)`;
620 let toast = Toastify({
621 text: `${htmlBody}<br />${info.name}`,
622 avatar: info.icon ? info.icon : null,
623 backgroundColor: backgroundColor,
624 className: "text-dark",
633 router.history.push(info.link);
640 export function notifyPost(post_view: PostView, router: any) {
641 let info: NotifyInfo = {
642 name: post_view.community.name,
643 icon: post_view.community.icon,
644 link: `/post/${post_view.post.id}`,
645 body: post_view.post.name,
647 notify(info, router);
650 export function notifyComment(comment_view: CommentView, router: any) {
651 let info: NotifyInfo = {
652 name: comment_view.creator.name,
653 icon: comment_view.creator.avatar,
654 link: `/post/${comment_view.post.id}/comment/${comment_view.comment.id}`,
655 body: comment_view.comment.content,
657 notify(info, router);
660 export function notifyPrivateMessage(pmv: PrivateMessageView, router: any) {
661 let info: NotifyInfo = {
662 name: pmv.creator.name,
663 icon: pmv.creator.avatar,
665 body: pmv.private_message.content,
667 notify(info, router);
670 function notify(info: NotifyInfo, router: any) {
671 messageToastify(info, router);
673 if (Notification.permission !== "granted") Notification.requestPermission();
675 var notification = new Notification(info.name, {
680 notification.onclick = (ev: Event): any => {
682 router.history.push(info.link);
687 export function setupTribute() {
689 noMatchTemplate: function () {
696 menuItemTemplate: (item: any) => {
697 let shortName = `:${item.original.key}:`;
698 return `${item.original.val} ${shortName}`;
700 selectTemplate: (item: any) => {
701 return `${item.original.val}`;
703 values: Object.entries(emojiShortName).map(e => {
704 return { key: e[1], val: e[0] };
707 autocompleteMode: true,
709 // menuItemLimit: mentionDropdownFetchLimit,
710 menuShowMinLength: 2,
715 selectTemplate: (item: any) => {
716 let it: PersonTribute = item.original;
717 return `[${it.key}](${it.view.person.actor_id})`;
719 values: (text: string, cb: (persons: PersonTribute[]) => any) => {
720 personSearch(text, (persons: PersonTribute[]) => cb(persons));
723 autocompleteMode: true,
725 // menuItemLimit: mentionDropdownFetchLimit,
726 menuShowMinLength: 2,
732 selectTemplate: (item: any) => {
733 let it: CommunityTribute = item.original;
734 return `[${it.key}](${it.view.community.actor_id})`;
736 values: (text: string, cb: any) => {
737 communitySearch(text, (communities: CommunityTribute[]) =>
742 autocompleteMode: true,
744 // menuItemLimit: mentionDropdownFetchLimit,
745 menuShowMinLength: 2,
751 var tippyInstance: any;
753 tippyInstance = tippy("[data-tippy-content]");
756 export function setupTippy() {
758 tippyInstance.forEach((e: any) => e.destroy());
759 tippyInstance = tippy("[data-tippy-content]", {
761 // Display on "long press"
762 touch: ["hold", 500],
767 interface PersonTribute {
769 view: PersonViewSafe;
772 function personSearch(text: string, cb: (persons: PersonTribute[]) => any) {
776 type_: SearchType.Users,
777 sort: SortType.TopAll,
778 listing_type: ListingType.All,
780 limit: mentionDropdownFetchLimit,
781 auth: authField(false),
784 WebSocketService.Instance.send(wsClient.search(form));
786 let personSub = WebSocketService.Instance.subject.subscribe(
788 let res = wsJsonToRes(msg);
789 if (res.op == UserOperation.Search) {
790 let data = res.data as SearchResponse;
791 let persons: PersonTribute[] = data.users.map(pv => {
792 let tribute: PersonTribute = {
793 key: `@${pv.person.name}@${hostname(pv.person.actor_id)}`,
799 personSub.unsubscribe();
802 err => console.error(err),
803 () => console.log("complete")
810 interface CommunityTribute {
815 function communitySearch(
817 cb: (communities: CommunityTribute[]) => any
822 type_: SearchType.Communities,
823 sort: SortType.TopAll,
824 listing_type: ListingType.All,
826 limit: mentionDropdownFetchLimit,
827 auth: authField(false),
830 WebSocketService.Instance.send(wsClient.search(form));
832 let communitySub = WebSocketService.Instance.subject.subscribe(
834 let res = wsJsonToRes(msg);
835 if (res.op == UserOperation.Search) {
836 let data = res.data as SearchResponse;
837 let communities: CommunityTribute[] = data.communities.map(cv => {
838 let tribute: CommunityTribute = {
839 key: `!${cv.community.name}@${hostname(cv.community.actor_id)}`,
845 communitySub.unsubscribe();
848 err => console.error(err),
849 () => console.log("complete")
856 export function getListingTypeFromProps(props: any): ListingType {
857 return props.match.params.listing_type
858 ? routeListingTypeToEnum(props.match.params.listing_type)
859 : UserService.Instance.myUserInfo
860 ? Object.values(ListingType)[
861 UserService.Instance.myUserInfo.local_user_view.local_user
862 .default_listing_type
867 export function getListingTypeFromPropsNoDefault(props: any): ListingType {
868 return props.match.params.listing_type
869 ? routeListingTypeToEnum(props.match.params.listing_type)
873 // TODO might need to add a user setting for this too
874 export function getDataTypeFromProps(props: any): DataType {
875 return props.match.params.data_type
876 ? routeDataTypeToEnum(props.match.params.data_type)
880 export function getSortTypeFromProps(props: any): SortType {
881 return props.match.params.sort
882 ? routeSortTypeToEnum(props.match.params.sort)
883 : UserService.Instance.myUserInfo
884 ? Object.values(SortType)[
885 UserService.Instance.myUserInfo.local_user_view.local_user
891 export function getPageFromProps(props: any): number {
892 return props.match.params.page ? Number(props.match.params.page) : 1;
895 export function getRecipientIdFromProps(props: any): number {
896 return props.match.params.recipient_id
897 ? Number(props.match.params.recipient_id)
901 export function getIdFromProps(props: any): number {
902 return Number(props.match.params.id);
905 export function getCommentIdFromProps(props: any): number {
906 return Number(props.match.params.comment_id);
909 export function getUsernameFromProps(props: any): string {
910 return props.match.params.username;
913 export function editCommentRes(data: CommentView, comments: CommentView[]) {
914 let found = comments.find(c => c.comment.id == data.comment.id);
916 found.comment.content = data.comment.content;
917 found.comment.updated = data.comment.updated;
918 found.comment.removed = data.comment.removed;
919 found.comment.deleted = data.comment.deleted;
920 found.counts.upvotes = data.counts.upvotes;
921 found.counts.downvotes = data.counts.downvotes;
922 found.counts.score = data.counts.score;
926 export function saveCommentRes(data: CommentView, comments: CommentView[]) {
927 let found = comments.find(c => c.comment.id == data.comment.id);
929 found.saved = data.saved;
933 export function updatePersonBlock(
934 data: BlockPersonResponse
935 ): PersonBlockView[] {
937 UserService.Instance.myUserInfo.person_blocks.push({
938 person: UserService.Instance.myUserInfo.local_user_view.person,
939 target: data.person_view.person,
941 toast(`${i18n.t("blocked")} ${data.person_view.person.name}`);
943 UserService.Instance.myUserInfo.person_blocks =
944 UserService.Instance.myUserInfo.person_blocks.filter(
945 i => i.target.id != data.person_view.person.id
947 toast(`${i18n.t("unblocked")} ${data.person_view.person.name}`);
949 return UserService.Instance.myUserInfo.person_blocks;
952 export function updateCommunityBlock(
953 data: BlockCommunityResponse
954 ): CommunityBlockView[] {
956 UserService.Instance.myUserInfo.community_blocks.push({
957 person: UserService.Instance.myUserInfo.local_user_view.person,
958 community: data.community_view.community,
960 toast(`${i18n.t("blocked")} ${data.community_view.community.name}`);
962 UserService.Instance.myUserInfo.community_blocks =
963 UserService.Instance.myUserInfo.community_blocks.filter(
964 i => i.community.id != data.community_view.community.id
966 toast(`${i18n.t("unblocked")} ${data.community_view.community.name}`);
968 return UserService.Instance.myUserInfo.community_blocks;
971 export function createCommentLikeRes(
973 comments: CommentView[]
975 let found = comments.find(c => c.comment.id === data.comment.id);
977 found.counts.score = data.counts.score;
978 found.counts.upvotes = data.counts.upvotes;
979 found.counts.downvotes = data.counts.downvotes;
980 if (data.my_vote !== null) {
981 found.my_vote = data.my_vote;
986 export function createPostLikeFindRes(data: PostView, posts: PostView[]) {
987 let found = posts.find(p => p.post.id == data.post.id);
989 createPostLikeRes(data, found);
993 export function createPostLikeRes(data: PostView, post_view: PostView) {
995 post_view.counts.score = data.counts.score;
996 post_view.counts.upvotes = data.counts.upvotes;
997 post_view.counts.downvotes = data.counts.downvotes;
998 if (data.my_vote !== null) {
999 post_view.my_vote = data.my_vote;
1004 export function editPostFindRes(data: PostView, posts: PostView[]) {
1005 let found = posts.find(p => p.post.id == data.post.id);
1007 editPostRes(data, found);
1011 export function editPostRes(data: PostView, post: PostView) {
1013 post.post.url = data.post.url;
1014 post.post.name = data.post.name;
1015 post.post.nsfw = data.post.nsfw;
1016 post.post.deleted = data.post.deleted;
1017 post.post.removed = data.post.removed;
1018 post.post.stickied = data.post.stickied;
1019 post.post.body = data.post.body;
1020 post.post.locked = data.post.locked;
1021 post.saved = data.saved;
1025 export function commentsToFlatNodes(comments: CommentView[]): CommentNodeI[] {
1026 let nodes: CommentNodeI[] = [];
1027 for (let comment of comments) {
1028 nodes.push({ comment_view: comment });
1033 function commentSort(tree: CommentNodeI[], sort: CommentSortType) {
1034 // First, put removed and deleted comments at the bottom, then do your other sorts
1035 if (sort == CommentSortType.Top) {
1038 +a.comment_view.comment.removed - +b.comment_view.comment.removed ||
1039 +a.comment_view.comment.deleted - +b.comment_view.comment.deleted ||
1040 b.comment_view.counts.score - a.comment_view.counts.score
1042 } else if (sort == CommentSortType.New) {
1045 +a.comment_view.comment.removed - +b.comment_view.comment.removed ||
1046 +a.comment_view.comment.deleted - +b.comment_view.comment.deleted ||
1047 b.comment_view.comment.published.localeCompare(
1048 a.comment_view.comment.published
1051 } else if (sort == CommentSortType.Old) {
1054 +a.comment_view.comment.removed - +b.comment_view.comment.removed ||
1055 +a.comment_view.comment.deleted - +b.comment_view.comment.deleted ||
1056 a.comment_view.comment.published.localeCompare(
1057 b.comment_view.comment.published
1060 } else if (sort == CommentSortType.Hot) {
1063 +a.comment_view.comment.removed - +b.comment_view.comment.removed ||
1064 +a.comment_view.comment.deleted - +b.comment_view.comment.deleted ||
1065 hotRankComment(b.comment_view) - hotRankComment(a.comment_view)
1069 // Go through the children recursively
1070 for (let node of tree) {
1071 if (node.children) {
1072 commentSort(node.children, sort);
1077 export function commentSortSortType(tree: CommentNodeI[], sort: SortType) {
1078 commentSort(tree, convertCommentSortType(sort));
1081 function convertCommentSortType(sort: SortType): CommentSortType {
1083 sort == SortType.TopAll ||
1084 sort == SortType.TopDay ||
1085 sort == SortType.TopWeek ||
1086 sort == SortType.TopMonth ||
1087 sort == SortType.TopYear
1089 return CommentSortType.Top;
1090 } else if (sort == SortType.New) {
1091 return CommentSortType.New;
1092 } else if (sort == SortType.Hot || sort == SortType.Active) {
1093 return CommentSortType.Hot;
1095 return CommentSortType.Hot;
1099 export function buildCommentsTree(
1100 comments: CommentView[],
1101 commentSortType: CommentSortType
1103 let map = new Map<number, CommentNodeI>();
1104 for (let comment_view of comments) {
1105 let node: CommentNodeI = {
1106 comment_view: comment_view,
1109 map.set(comment_view.comment.id, { ...node });
1111 let tree: CommentNodeI[] = [];
1112 for (let comment_view of comments) {
1113 let child = map.get(comment_view.comment.id);
1114 let parent_id = comment_view.comment.parent_id;
1116 let parent = map.get(parent_id);
1117 // Necessary because blocked comment might not exist
1119 parent.children.push(child);
1128 commentSort(tree, commentSortType);
1133 function setDepth(node: CommentNodeI, i = 0) {
1134 for (let child of node.children) {
1136 setDepth(child, i + 1);
1140 export function insertCommentIntoTree(tree: CommentNodeI[], cv: CommentView) {
1141 // Building a fake node to be used for later
1142 let node: CommentNodeI = {
1148 if (cv.comment.parent_id) {
1149 let parentComment = searchCommentTree(tree, cv.comment.parent_id);
1150 if (parentComment) {
1151 node.depth = parentComment.depth + 1;
1152 parentComment.children.unshift(node);
1159 export function searchCommentTree(
1160 tree: CommentNodeI[],
1163 for (let node of tree) {
1164 if (node.comment_view.comment.id === id) {
1168 for (const child of node.children) {
1169 const res = searchCommentTree([child], id);
1179 export const colorList: string[] = [
1188 function hsl(num: number) {
1189 return `hsla(${num}, 35%, 50%, 1)`;
1192 export function previewLines(
1201 // Use lines * 2 because markdown requires 2 lines
1202 .slice(0, maxLines * 2)
1207 export function hostname(url: string): string {
1208 let cUrl = new URL(url);
1209 return cUrl.port ? `${cUrl.hostname}:${cUrl.port}` : `${cUrl.hostname}`;
1212 export function validTitle(title?: string): boolean {
1213 // Initial title is null, minimum length is taken care of by textarea's minLength={3}
1214 if (title === null || title.length < 3) return true;
1216 const regex = new RegExp(/.*\S.*/, "g");
1218 return regex.test(title);
1221 export function siteBannerCss(banner: string): string {
1223 background-image: linear-gradient( rgba(0, 0, 0, 0.8), rgba(0, 0, 0, 0.8) ) ,url("${banner}"); \
1224 background-attachment: fixed; \
1225 background-position: top; \
1226 background-repeat: no-repeat; \
1227 background-size: 100% cover; \
1230 max-height: 100vh; \
1234 export function isBrowser() {
1235 return typeof window !== "undefined";
1238 export function setIsoData(context: any): IsoData {
1239 let isoData: IsoData = isBrowser()
1241 : context.router.staticContext;
1245 export function wsSubscribe(parseMessage: any): Subscription {
1247 return WebSocketService.Instance.subject
1248 .pipe(retryWhen(errors => errors.pipe(delay(3000), take(10))))
1250 msg => parseMessage(msg),
1251 err => console.error(err),
1252 () => console.log("complete")
1259 export function setOptionalAuth(obj: any, auth = UserService.Instance.auth) {
1265 export function authField(
1267 auth = UserService.Instance.auth
1269 if (auth == null && throwErr) {
1270 toast(i18n.t("not_logged_in"), "danger");
1271 throw "Not logged in";
1277 moment.updateLocale("en", {
1298 export function saveScrollPosition(context: any) {
1299 let path: string = context.router.route.location.pathname;
1300 let y = window.scrollY;
1301 sessionStorage.setItem(`scrollPosition_${path}`, y.toString());
1304 export function restoreScrollPosition(context: any) {
1305 let path: string = context.router.route.location.pathname;
1306 let y = Number(sessionStorage.getItem(`scrollPosition_${path}`));
1307 window.scrollTo(0, y);
1310 export function showLocal(isoData: IsoData): boolean {
1311 return isoData.site_res.federated_instances?.linked.length > 0;
1314 interface ChoicesValue {
1319 export function communityToChoice(cv: CommunityView): ChoicesValue {
1320 let choice: ChoicesValue = {
1321 value: cv.community.id.toString(),
1322 label: communitySelectName(cv),
1327 export function personToChoice(pvs: PersonViewSafe): ChoicesValue {
1328 let choice: ChoicesValue = {
1329 value: pvs.person.id.toString(),
1330 label: personSelectName(pvs),
1335 export async function fetchCommunities(q: string) {
1336 let form: Search = {
1338 type_: SearchType.Communities,
1339 sort: SortType.TopAll,
1340 listing_type: ListingType.All,
1343 auth: authField(false),
1345 let client = new LemmyHttp(httpBase);
1346 return client.search(form);
1349 export async function fetchUsers(q: string) {
1350 let form: Search = {
1352 type_: SearchType.Users,
1353 sort: SortType.TopAll,
1354 listing_type: ListingType.All,
1357 auth: authField(false),
1359 let client = new LemmyHttp(httpBase);
1360 return client.search(form);
1363 export const choicesConfig = {
1365 searchResultLimit: fetchLimit,
1367 containerOuter: "choices",
1368 containerInner: "choices__inner bg-secondary border-0",
1369 input: "form-control",
1370 inputCloned: "choices__input--cloned",
1371 list: "choices__list",
1372 listItems: "choices__list--multiple",
1373 listSingle: "choices__list--single",
1374 listDropdown: "choices__list--dropdown",
1375 item: "choices__item bg-secondary",
1376 itemSelectable: "choices__item--selectable",
1377 itemDisabled: "choices__item--disabled",
1378 itemChoice: "choices__item--choice",
1379 placeholder: "choices__placeholder",
1380 group: "choices__group",
1381 groupHeading: "choices__heading",
1382 button: "choices__button",
1383 activeState: "is-active",
1384 focusState: "is-focused",
1385 openState: "is-open",
1386 disabledState: "is-disabled",
1387 highlightedState: "text-info",
1388 selectedState: "text-info",
1389 flippedState: "is-flipped",
1390 loadingState: "is-loading",
1391 noResults: "has-no-results",
1392 noChoices: "has-no-choices",
1396 export function communitySelectName(cv: CommunityView): string {
1397 return cv.community.local
1399 : `${hostname(cv.community.actor_id)}/${cv.community.name}`;
1402 export function personSelectName(pvs: PersonViewSafe): string {
1403 return pvs.person.local
1405 : `${hostname(pvs.person.actor_id)}/${pvs.person.name}`;
1408 export function initializeSite(site: GetSiteResponse) {
1409 UserService.Instance.myUserInfo = site.my_user;
1410 i18n.changeLanguage(getLanguage());