1 import emojiShortName from "emoji-short-name";
18 WebSocketJsonResponse,
20 } from "lemmy-js-client";
21 import markdown_it from "markdown-it";
22 import markdown_it_container from "markdown-it-container";
23 import markdown_it_sub from "markdown-it-sub";
24 import markdown_it_sup from "markdown-it-sup";
25 import moment from "moment";
26 import "moment/locale/bg";
27 import "moment/locale/ca";
28 import "moment/locale/da";
29 import "moment/locale/de";
30 import "moment/locale/el";
31 import "moment/locale/eo";
32 import "moment/locale/es";
33 import "moment/locale/eu";
34 import "moment/locale/fa";
35 import "moment/locale/fi";
36 import "moment/locale/fr";
37 import "moment/locale/ga";
38 import "moment/locale/gl";
39 import "moment/locale/hi";
40 import "moment/locale/hr";
41 import "moment/locale/hu";
42 import "moment/locale/id";
43 import "moment/locale/it";
44 import "moment/locale/ja";
45 import "moment/locale/ka";
46 import "moment/locale/km";
47 import "moment/locale/ko";
48 import "moment/locale/nb";
49 import "moment/locale/nl";
50 import "moment/locale/pl";
51 import "moment/locale/pt-br";
52 import "moment/locale/ru";
53 import "moment/locale/sq";
54 import "moment/locale/sr";
55 import "moment/locale/sv";
56 import "moment/locale/tr";
57 import "moment/locale/uk";
58 import "moment/locale/zh-cn";
59 import { Subscription } from "rxjs";
60 import { delay, retryWhen, take } from "rxjs/operators";
61 import tippy from "tippy.js";
62 import Toastify from "toastify-js";
63 import { httpBase } from "./env";
64 import { i18n } from "./i18next";
66 CommentNode as CommentNodeI,
70 } from "./interfaces";
71 import { UserService, WebSocketService } from "./services";
75 Tribute = require("tributejs");
78 export const wsClient = new LemmyWebsocket();
80 export const favIconUrl = "/static/assets/icons/favicon.svg";
81 export const favIconPngUrl = "/static/assets/icons/apple-touch-icon.png";
83 // export const defaultFavIcon = `${window.location.protocol}//${window.location.host}${favIconPngUrl}`;
84 export const repoUrl = "https://github.com/LemmyNet";
85 export const joinLemmyUrl = "https://join-lemmy.org";
86 export const supportLemmyUrl = `${joinLemmyUrl}/support`;
87 export const docsUrl = `${joinLemmyUrl}/docs/en/index.html`;
88 export const helpGuideUrl = `${joinLemmyUrl}/docs/en/about/guide.html`; // TODO find a way to redirect to the non-en folder
89 export const markdownHelpUrl = `${helpGuideUrl}#markdown-guide`;
90 export const sortingHelpUrl = `${helpGuideUrl}#sorting`;
91 export const archiveUrl = "https://archive.is";
92 export const elementUrl = "https://element.io/";
94 export const postRefetchSeconds: number = 60 * 1000;
95 export const fetchLimit = 20;
96 export const mentionDropdownFetchLimit = 10;
98 export const languages = [
138 export const themes = [
154 const DEFAULT_ALPHABET =
155 "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
157 function getRandomCharFromAlphabet(alphabet: string): string {
158 return alphabet.charAt(Math.floor(Math.random() * alphabet.length));
161 export function randomStr(
162 idDesiredLength = 20,
163 alphabet = DEFAULT_ALPHABET
166 * Create n-long array and map it to random chars from given alphabet.
167 * Then join individual chars as string
169 return Array.from({ length: idDesiredLength })
171 return getRandomCharFromAlphabet(alphabet);
176 export function wsJsonToRes<ResponseType>(
177 msg: WebSocketJsonResponse<ResponseType>
178 ): WebSocketResponse<ResponseType> {
185 export function wsUserOp(msg: any): UserOperation {
186 let opStr: string = msg.op;
187 return UserOperation[opStr];
190 export const md = new markdown_it({
195 .use(markdown_it_sub)
196 .use(markdown_it_sup)
197 .use(markdown_it_container, "spoiler", {
198 validate: function (params: any) {
199 return params.trim().match(/^spoiler\s+(.*)$/);
202 render: function (tokens: any, idx: any) {
203 var m = tokens[idx].info.trim().match(/^spoiler\s+(.*)$/);
205 if (tokens[idx].nesting === 1) {
207 return `<details><summary> ${md.utils.escapeHtml(m[1])} </summary>\n`;
210 return "</details>\n";
215 export function hotRankComment(comment_view: CommentView): number {
216 return hotRank(comment_view.counts.score, comment_view.comment.published);
219 export function hotRankActivePost(post_view: PostView): number {
220 return hotRank(post_view.counts.score, post_view.counts.newest_comment_time);
223 export function hotRankPost(post_view: PostView): number {
224 return hotRank(post_view.counts.score, post_view.post.published);
227 export function hotRank(score: number, timeStr: string): number {
228 // Rank = ScaleFactor * sign(Score) * log(1 + abs(Score)) / (Time + 2)^Gravity
229 let date: Date = new Date(timeStr + "Z"); // Add Z to convert from UTC date
230 let now: Date = new Date();
231 let hoursElapsed: number = (now.getTime() - date.getTime()) / 36e5;
234 (10000 * Math.log10(Math.max(1, 3 + score))) /
235 Math.pow(hoursElapsed + 2, 1.8);
237 // console.log(`Comment: ${comment.content}\nRank: ${rank}\nScore: ${comment.score}\nHours: ${hoursElapsed}`);
242 export function mdToHtml(text: string) {
243 return { __html: md.render(text) };
246 export function getUnixTime(text: string): number {
247 return text ? new Date(text).getTime() / 1000 : undefined;
250 export function canMod(
251 localUserView: LocalUserSettingsView,
256 // You can do moderator actions only on the mods added after you.
258 let yourIndex = modIds.findIndex(id => id == localUserView.person.id);
259 if (yourIndex == -1) {
262 // onSelf +1 on mod actions not for yourself, IE ban, remove, etc
263 modIds = modIds.slice(0, yourIndex + (onSelf ? 0 : 1));
264 return !modIds.includes(creator_id);
271 export function isMod(modIds: number[], creator_id: number): boolean {
272 return modIds.includes(creator_id);
275 const imageRegex = new RegExp(
276 /(http)?s?:?(\/\/[^"']*\.(?:jpg|jpeg|gif|png|svg|webp))/
278 const videoRegex = new RegExp(`(http)?s?:?(\/\/[^"']*\.(?:mp4))`);
280 export function isImage(url: string) {
281 return imageRegex.test(url);
284 export function isVideo(url: string) {
285 return videoRegex.test(url);
288 export function validURL(str: string) {
289 return !!new URL(str);
292 export function communityRSSUrl(actorId: string, sort: string): string {
293 let url = new URL(actorId);
294 return `${url.origin}/feeds${url.pathname}.xml?sort=${sort}`;
297 export function validEmail(email: string) {
299 /^(([^\s"(),.:;<>@[\\\]]+(\.[^\s"(),.:;<>@[\\\]]+)*)|(".+"))@((\[(?:\d{1,3}\.){3}\d{1,3}])|(([\dA-Za-z\-]+\.)+[A-Za-z]{2,}))$/;
300 return re.test(String(email).toLowerCase());
303 export function capitalizeFirstLetter(str: string): string {
304 return str.charAt(0).toUpperCase() + str.slice(1);
307 export function routeSortTypeToEnum(sort: string): SortType {
308 return SortType[sort];
311 export function listingTypeFromNum(type_: number): ListingType {
312 return Object.values(ListingType)[type_];
315 export function sortTypeFromNum(type_: number): SortType {
316 return Object.values(SortType)[type_];
319 export function routeListingTypeToEnum(type: string): ListingType {
320 return ListingType[type];
323 export function routeDataTypeToEnum(type: string): DataType {
324 return DataType[capitalizeFirstLetter(type)];
327 export function routeSearchTypeToEnum(type: string): SearchType {
328 return SearchType[type];
331 export async function getPageTitle(url: string) {
332 let res = await fetch(`/iframely/oembed?url=${url}`).then(res => res.json());
333 let title = await res.title;
337 export function debounce(func: any, wait = 1000, immediate = false) {
338 // 'private' variable for instance
339 // The returned function will be able to reference this due to closure.
340 // Each call to the returned function will share this common timer.
343 // Calling debounce returns a new anonymous function
345 // reference the context and args for the setTimeout function
346 var args = arguments;
348 // Should the function be called now? If immediate is true
349 // and not already in a timeout then the answer is: Yes
350 var callNow = immediate && !timeout;
352 // This is the basic debounce behaviour where you can call this
353 // function several times, but it will only execute once
354 // [before or after imposing a delay].
355 // Each time the returned function is called, the timer starts over.
356 clearTimeout(timeout);
358 // Set the new timeout
359 timeout = setTimeout(function () {
360 // Inside the timeout function, clear the timeout variable
361 // which will let the next execution run when in 'immediate' mode
364 // Check if the function already ran with the immediate flag
366 // Call the original function with apply
367 // apply lets you define the 'this' object as well as the arguments
368 // (both captured before setTimeout)
369 func.apply(this, args);
373 // Immediate mode and no wait timer? Execute the function..
374 if (callNow) func.apply(this, args);
379 export function getLanguage(override?: string): string {
380 let localUserView = UserService.Instance.localUserView;
383 (localUserView?.local_user.lang
384 ? localUserView.local_user.lang
387 if (lang == "browser" && isBrowser()) {
388 return getBrowserLanguage();
394 export function getBrowserLanguage(): string {
395 // Intersect lemmy's langs, with the browser langs
396 let langs = languages ? languages.map(l => l.code) : ["en"];
398 // NOTE, mobile browsers seem to be missing this list, so append en
399 let allowedLangs = navigator.languages
401 .filter(v => langs.includes(v));
402 return allowedLangs[0];
405 export function getMomentLanguage(): string {
406 let lang = getLanguage();
407 if (lang.startsWith("zh")) {
409 } else if (lang.startsWith("sv")) {
411 } else if (lang.startsWith("fr")) {
413 } else if (lang.startsWith("de")) {
415 } else if (lang.startsWith("ru")) {
417 } else if (lang.startsWith("es")) {
419 } else if (lang.startsWith("eo")) {
421 } else if (lang.startsWith("nl")) {
423 } else if (lang.startsWith("it")) {
425 } else if (lang.startsWith("fi")) {
427 } else if (lang.startsWith("ca")) {
429 } else if (lang.startsWith("fa")) {
431 } else if (lang.startsWith("pl")) {
433 } else if (lang.startsWith("pt")) {
435 } else if (lang.startsWith("ja")) {
437 } else if (lang.startsWith("ka")) {
439 } else if (lang.startsWith("hi")) {
441 } else if (lang.startsWith("el")) {
443 } else if (lang.startsWith("eu")) {
445 } else if (lang.startsWith("gl")) {
447 } else if (lang.startsWith("tr")) {
449 } else if (lang.startsWith("hu")) {
451 } else if (lang.startsWith("uk")) {
453 } else if (lang.startsWith("sq")) {
455 } else if (lang.startsWith("km")) {
457 } else if (lang.startsWith("ga")) {
459 } else if (lang.startsWith("sr")) {
461 } else if (lang.startsWith("ko")) {
463 } else if (lang.startsWith("da")) {
465 } else if (lang.startsWith("oc")) {
467 } else if (lang.startsWith("hr")) {
469 } else if (lang.startsWith("th")) {
471 } else if (lang.startsWith("bg")) {
473 } else if (lang.startsWith("id")) {
475 } else if (lang.startsWith("nb")) {
483 export function setTheme(theme: string, forceReload = false) {
487 if (theme === "browser" && !forceReload) {
490 // This is only run on a force reload
491 if (theme == "browser") {
495 // Unload all the other themes
496 for (var i = 0; i < themes.length; i++) {
497 let styleSheet = document.getElementById(themes[i]);
499 styleSheet.setAttribute("disabled", "disabled");
504 .getElementById("default-light")
505 ?.setAttribute("disabled", "disabled");
506 document.getElementById("default-dark")?.setAttribute("disabled", "disabled");
508 // Load the theme dynamically
509 let cssLoc = `/static/assets/css/themes/${theme}.min.css`;
510 loadCss(theme, cssLoc);
511 document.getElementById(theme).removeAttribute("disabled");
514 export function loadCss(id: string, loc: string) {
515 if (!document.getElementById(id)) {
516 var head = document.getElementsByTagName("head")[0];
517 var link = document.createElement("link");
519 link.rel = "stylesheet";
520 link.type = "text/css";
523 head.appendChild(link);
527 export function objectFlip(obj: any) {
529 Object.keys(obj).forEach(key => {
535 export function showAvatars(): boolean {
537 UserService.Instance.localUserView?.local_user.show_avatars ||
538 !UserService.Instance.localUserView
542 export function showScores(): boolean {
544 UserService.Instance.localUserView?.local_user.show_scores ||
545 !UserService.Instance.localUserView
549 export function isCakeDay(published: string): boolean {
550 // moment(undefined) or moment.utc(undefined) returns the current date/time
551 // moment(null) or moment.utc(null) returns null
552 const createDate = moment.utc(published || null).local();
553 const currentDate = moment(new Date());
556 createDate.date() === currentDate.date() &&
557 createDate.month() === currentDate.month() &&
558 createDate.year() !== currentDate.year()
562 export function toast(text: string, background = "success") {
564 let backgroundColor = `var(--${background})`;
567 backgroundColor: backgroundColor,
574 export function pictrsDeleteToast(
575 clickToDeleteText: string,
576 deletePictureText: string,
580 let backgroundColor = `var(--light)`;
581 let toast = Toastify({
582 text: clickToDeleteText,
583 backgroundColor: backgroundColor,
589 window.location.replace(deleteUrl);
590 alert(deletePictureText);
599 interface NotifyInfo {
606 export function messageToastify(info: NotifyInfo, router: any) {
608 let htmlBody = info.body ? md.render(info.body) : "";
609 let backgroundColor = `var(--light)`;
611 let toast = Toastify({
612 text: `${htmlBody}<br />${info.name}`,
613 avatar: info.icon ? info.icon : null,
614 backgroundColor: backgroundColor,
615 className: "text-dark",
624 router.history.push(info.link);
631 export function notifyPost(post_view: PostView, router: any) {
632 let info: NotifyInfo = {
633 name: post_view.community.name,
634 icon: post_view.community.icon,
635 link: `/post/${post_view.post.id}`,
636 body: post_view.post.name,
638 notify(info, router);
641 export function notifyComment(comment_view: CommentView, router: any) {
642 let info: NotifyInfo = {
643 name: comment_view.creator.name,
644 icon: comment_view.creator.avatar,
645 link: `/post/${comment_view.post.id}/comment/${comment_view.comment.id}`,
646 body: comment_view.comment.content,
648 notify(info, router);
651 export function notifyPrivateMessage(pmv: PrivateMessageView, router: any) {
652 let info: NotifyInfo = {
653 name: pmv.creator.name,
654 icon: pmv.creator.avatar,
656 body: pmv.private_message.content,
658 notify(info, router);
661 function notify(info: NotifyInfo, router: any) {
662 messageToastify(info, router);
664 if (Notification.permission !== "granted") Notification.requestPermission();
666 var notification = new Notification(info.name, {
671 notification.onclick = (ev: Event): any => {
673 router.history.push(info.link);
678 export function setupTribute() {
680 noMatchTemplate: function () {
687 menuItemTemplate: (item: any) => {
688 let shortName = `:${item.original.key}:`;
689 return `${item.original.val} ${shortName}`;
691 selectTemplate: (item: any) => {
692 return `${item.original.val}`;
694 values: Object.entries(emojiShortName).map(e => {
695 return { key: e[1], val: e[0] };
698 autocompleteMode: true,
700 // menuItemLimit: mentionDropdownFetchLimit,
701 menuShowMinLength: 2,
706 selectTemplate: (item: any) => {
707 let it: PersonTribute = item.original;
708 return `[${it.key}](${it.view.person.actor_id})`;
710 values: (text: string, cb: (persons: PersonTribute[]) => any) => {
711 personSearch(text, (persons: PersonTribute[]) => cb(persons));
714 autocompleteMode: true,
716 // menuItemLimit: mentionDropdownFetchLimit,
717 menuShowMinLength: 2,
723 selectTemplate: (item: any) => {
724 let it: CommunityTribute = item.original;
725 return `[${it.key}](${it.view.community.actor_id})`;
727 values: (text: string, cb: any) => {
728 communitySearch(text, (communities: CommunityTribute[]) =>
733 autocompleteMode: true,
735 // menuItemLimit: mentionDropdownFetchLimit,
736 menuShowMinLength: 2,
742 var tippyInstance: any;
744 tippyInstance = tippy("[data-tippy-content]");
747 export function setupTippy() {
749 tippyInstance.forEach((e: any) => e.destroy());
750 tippyInstance = tippy("[data-tippy-content]", {
752 // Display on "long press"
753 touch: ["hold", 500],
758 interface PersonTribute {
760 view: PersonViewSafe;
763 function personSearch(text: string, cb: (persons: PersonTribute[]) => any) {
767 type_: SearchType.Users,
768 sort: SortType.TopAll,
769 listing_type: ListingType.All,
771 limit: mentionDropdownFetchLimit,
772 auth: authField(false),
775 WebSocketService.Instance.send(wsClient.search(form));
777 let personSub = WebSocketService.Instance.subject.subscribe(
779 let res = wsJsonToRes(msg);
780 if (res.op == UserOperation.Search) {
781 let data = res.data as SearchResponse;
782 let persons: PersonTribute[] = data.users.map(pv => {
783 let tribute: PersonTribute = {
784 key: `@${pv.person.name}@${hostname(pv.person.actor_id)}`,
790 personSub.unsubscribe();
793 err => console.error(err),
794 () => console.log("complete")
801 interface CommunityTribute {
806 function communitySearch(
808 cb: (communities: CommunityTribute[]) => any
813 type_: SearchType.Communities,
814 sort: SortType.TopAll,
815 listing_type: ListingType.All,
817 limit: mentionDropdownFetchLimit,
818 auth: authField(false),
821 WebSocketService.Instance.send(wsClient.search(form));
823 let communitySub = WebSocketService.Instance.subject.subscribe(
825 let res = wsJsonToRes(msg);
826 if (res.op == UserOperation.Search) {
827 let data = res.data as SearchResponse;
828 let communities: CommunityTribute[] = data.communities.map(cv => {
829 let tribute: CommunityTribute = {
830 key: `!${cv.community.name}@${hostname(cv.community.actor_id)}`,
836 communitySub.unsubscribe();
839 err => console.error(err),
840 () => console.log("complete")
847 export function getListingTypeFromProps(props: any): ListingType {
848 return props.match.params.listing_type
849 ? routeListingTypeToEnum(props.match.params.listing_type)
850 : UserService.Instance.localUserView
851 ? Object.values(ListingType)[
852 UserService.Instance.localUserView.local_user.default_listing_type
857 // TODO might need to add a user setting for this too
858 export function getDataTypeFromProps(props: any): DataType {
859 return props.match.params.data_type
860 ? routeDataTypeToEnum(props.match.params.data_type)
864 export function getSortTypeFromProps(props: any): SortType {
865 return props.match.params.sort
866 ? routeSortTypeToEnum(props.match.params.sort)
867 : UserService.Instance.localUserView
868 ? Object.values(SortType)[
869 UserService.Instance.localUserView.local_user.default_sort_type
874 export function getPageFromProps(props: any): number {
875 return props.match.params.page ? Number(props.match.params.page) : 1;
878 export function getRecipientIdFromProps(props: any): number {
879 return props.match.params.recipient_id
880 ? Number(props.match.params.recipient_id)
884 export function getIdFromProps(props: any): number {
885 return Number(props.match.params.id);
888 export function getCommentIdFromProps(props: any): number {
889 return Number(props.match.params.comment_id);
892 export function getUsernameFromProps(props: any): string {
893 return props.match.params.username;
896 export function editCommentRes(data: CommentView, comments: CommentView[]) {
897 let found = comments.find(c => c.comment.id == data.comment.id);
899 found.comment.content = data.comment.content;
900 found.comment.updated = data.comment.updated;
901 found.comment.removed = data.comment.removed;
902 found.comment.deleted = data.comment.deleted;
903 found.counts.upvotes = data.counts.upvotes;
904 found.counts.downvotes = data.counts.downvotes;
905 found.counts.score = data.counts.score;
909 export function saveCommentRes(data: CommentView, comments: CommentView[]) {
910 let found = comments.find(c => c.comment.id == data.comment.id);
912 found.saved = data.saved;
916 export function createCommentLikeRes(
918 comments: CommentView[]
920 let found = comments.find(c => c.comment.id === data.comment.id);
922 found.counts.score = data.counts.score;
923 found.counts.upvotes = data.counts.upvotes;
924 found.counts.downvotes = data.counts.downvotes;
925 if (data.my_vote !== null) {
926 found.my_vote = data.my_vote;
931 export function createPostLikeFindRes(data: PostView, posts: PostView[]) {
932 let found = posts.find(p => p.post.id == data.post.id);
934 createPostLikeRes(data, found);
938 export function createPostLikeRes(data: PostView, post_view: PostView) {
940 post_view.counts.score = data.counts.score;
941 post_view.counts.upvotes = data.counts.upvotes;
942 post_view.counts.downvotes = data.counts.downvotes;
943 if (data.my_vote !== null) {
944 post_view.my_vote = data.my_vote;
949 export function editPostFindRes(data: PostView, posts: PostView[]) {
950 let found = posts.find(p => p.post.id == data.post.id);
952 editPostRes(data, found);
956 export function editPostRes(data: PostView, post: PostView) {
958 post.post.url = data.post.url;
959 post.post.name = data.post.name;
960 post.post.nsfw = data.post.nsfw;
961 post.post.deleted = data.post.deleted;
962 post.post.removed = data.post.removed;
963 post.post.stickied = data.post.stickied;
964 post.post.body = data.post.body;
965 post.post.locked = data.post.locked;
966 post.saved = data.saved;
970 export function commentsToFlatNodes(comments: CommentView[]): CommentNodeI[] {
971 let nodes: CommentNodeI[] = [];
972 for (let comment of comments) {
973 nodes.push({ comment_view: comment });
978 function commentSort(tree: CommentNodeI[], sort: CommentSortType) {
979 // First, put removed and deleted comments at the bottom, then do your other sorts
980 if (sort == CommentSortType.Top) {
983 +a.comment_view.comment.removed - +b.comment_view.comment.removed ||
984 +a.comment_view.comment.deleted - +b.comment_view.comment.deleted ||
985 b.comment_view.counts.score - a.comment_view.counts.score
987 } else if (sort == CommentSortType.New) {
990 +a.comment_view.comment.removed - +b.comment_view.comment.removed ||
991 +a.comment_view.comment.deleted - +b.comment_view.comment.deleted ||
992 b.comment_view.comment.published.localeCompare(
993 a.comment_view.comment.published
996 } else if (sort == CommentSortType.Old) {
999 +a.comment_view.comment.removed - +b.comment_view.comment.removed ||
1000 +a.comment_view.comment.deleted - +b.comment_view.comment.deleted ||
1001 a.comment_view.comment.published.localeCompare(
1002 b.comment_view.comment.published
1005 } else if (sort == CommentSortType.Hot) {
1008 +a.comment_view.comment.removed - +b.comment_view.comment.removed ||
1009 +a.comment_view.comment.deleted - +b.comment_view.comment.deleted ||
1010 hotRankComment(b.comment_view) - hotRankComment(a.comment_view)
1014 // Go through the children recursively
1015 for (let node of tree) {
1016 if (node.children) {
1017 commentSort(node.children, sort);
1022 export function commentSortSortType(tree: CommentNodeI[], sort: SortType) {
1023 commentSort(tree, convertCommentSortType(sort));
1026 function convertCommentSortType(sort: SortType): CommentSortType {
1028 sort == SortType.TopAll ||
1029 sort == SortType.TopDay ||
1030 sort == SortType.TopWeek ||
1031 sort == SortType.TopMonth ||
1032 sort == SortType.TopYear
1034 return CommentSortType.Top;
1035 } else if (sort == SortType.New) {
1036 return CommentSortType.New;
1037 } else if (sort == SortType.Hot || sort == SortType.Active) {
1038 return CommentSortType.Hot;
1040 return CommentSortType.Hot;
1044 export function buildCommentsTree(
1045 comments: CommentView[],
1046 commentSortType: CommentSortType
1048 let map = new Map<number, CommentNodeI>();
1049 for (let comment_view of comments) {
1050 let node: CommentNodeI = {
1051 comment_view: comment_view,
1054 map.set(comment_view.comment.id, { ...node });
1056 let tree: CommentNodeI[] = [];
1057 for (let comment_view of comments) {
1058 let child = map.get(comment_view.comment.id);
1059 if (comment_view.comment.parent_id) {
1060 let parent_ = map.get(comment_view.comment.parent_id);
1061 parent_.children.push(child);
1069 commentSort(tree, commentSortType);
1074 function setDepth(node: CommentNodeI, i = 0) {
1075 for (let child of node.children) {
1077 setDepth(child, i + 1);
1081 export function insertCommentIntoTree(tree: CommentNodeI[], cv: CommentView) {
1082 // Building a fake node to be used for later
1083 let node: CommentNodeI = {
1089 if (cv.comment.parent_id) {
1090 let parentComment = searchCommentTree(tree, cv.comment.parent_id);
1091 if (parentComment) {
1092 node.depth = parentComment.depth + 1;
1093 parentComment.children.unshift(node);
1100 export function searchCommentTree(
1101 tree: CommentNodeI[],
1104 for (let node of tree) {
1105 if (node.comment_view.comment.id === id) {
1109 for (const child of node.children) {
1110 const res = searchCommentTree([child], id);
1120 export const colorList: string[] = [
1129 function hsl(num: number) {
1130 return `hsla(${num}, 35%, 50%, 1)`;
1133 export function previewLines(
1142 // Use lines * 2 because markdown requires 2 lines
1143 .slice(0, maxLines * 2)
1148 export function hostname(url: string): string {
1149 let cUrl = new URL(url);
1150 return cUrl.port ? `${cUrl.hostname}:${cUrl.port}` : `${cUrl.hostname}`;
1153 export function validTitle(title?: string): boolean {
1154 // Initial title is null, minimum length is taken care of by textarea's minLength={3}
1155 if (title === null || title.length < 3) return true;
1157 const regex = new RegExp(/.*\S.*/, "g");
1159 return regex.test(title);
1162 export function siteBannerCss(banner: string): string {
1164 background-image: linear-gradient( rgba(0, 0, 0, 0.8), rgba(0, 0, 0, 0.8) ) ,url("${banner}"); \
1165 background-attachment: fixed; \
1166 background-position: top; \
1167 background-repeat: no-repeat; \
1168 background-size: 100% cover; \
1171 max-height: 100vh; \
1175 export function isBrowser() {
1176 return typeof window !== "undefined";
1179 export function setIsoData(context: any): IsoData {
1180 let isoData: IsoData = isBrowser()
1182 : context.router.staticContext;
1186 export function wsSubscribe(parseMessage: any): Subscription {
1188 return WebSocketService.Instance.subject
1189 .pipe(retryWhen(errors => errors.pipe(delay(3000), take(10))))
1191 msg => parseMessage(msg),
1192 err => console.error(err),
1193 () => console.log("complete")
1200 export function setOptionalAuth(obj: any, auth = UserService.Instance.auth) {
1206 export function authField(
1208 auth = UserService.Instance.auth
1210 if (auth == null && throwErr) {
1211 toast(i18n.t("not_logged_in"), "danger");
1212 throw "Not logged in";
1218 moment.updateLocale("en", {
1239 export function saveScrollPosition(context: any) {
1240 let path: string = context.router.route.location.pathname;
1241 let y = window.scrollY;
1242 sessionStorage.setItem(`scrollPosition_${path}`, y.toString());
1245 export function restoreScrollPosition(context: any) {
1246 let path: string = context.router.route.location.pathname;
1247 let y = Number(sessionStorage.getItem(`scrollPosition_${path}`));
1248 window.scrollTo(0, y);
1251 export function showLocal(isoData: IsoData): boolean {
1252 return isoData.site_res.federated_instances?.linked.length > 0;
1255 interface ChoicesValue {
1260 export function communityToChoice(cv: CommunityView): ChoicesValue {
1261 let choice: ChoicesValue = {
1262 value: cv.community.id.toString(),
1263 label: communitySelectName(cv),
1268 export function personToChoice(pvs: PersonViewSafe): ChoicesValue {
1269 let choice: ChoicesValue = {
1270 value: pvs.person.id.toString(),
1271 label: personSelectName(pvs),
1276 export async function fetchCommunities(q: string) {
1277 let form: Search = {
1279 type_: SearchType.Communities,
1280 sort: SortType.TopAll,
1281 listing_type: ListingType.All,
1284 auth: authField(false),
1286 let client = new LemmyHttp(httpBase);
1287 return client.search(form);
1290 export async function fetchUsers(q: string) {
1291 let form: Search = {
1293 type_: SearchType.Users,
1294 sort: SortType.TopAll,
1295 listing_type: ListingType.All,
1298 auth: authField(false),
1300 let client = new LemmyHttp(httpBase);
1301 return client.search(form);
1304 export const choicesConfig = {
1306 searchResultLimit: fetchLimit,
1308 containerOuter: "choices",
1309 containerInner: "choices__inner bg-light border-0",
1310 input: "form-control",
1311 inputCloned: "choices__input--cloned",
1312 list: "choices__list",
1313 listItems: "choices__list--multiple",
1314 listSingle: "choices__list--single",
1315 listDropdown: "choices__list--dropdown",
1316 item: "choices__item bg-light",
1317 itemSelectable: "choices__item--selectable",
1318 itemDisabled: "choices__item--disabled",
1319 itemChoice: "choices__item--choice",
1320 placeholder: "choices__placeholder",
1321 group: "choices__group",
1322 groupHeading: "choices__heading",
1323 button: "choices__button",
1324 activeState: "is-active",
1325 focusState: "is-focused",
1326 openState: "is-open",
1327 disabledState: "is-disabled",
1328 highlightedState: "text-info",
1329 selectedState: "text-info",
1330 flippedState: "is-flipped",
1331 loadingState: "is-loading",
1332 noResults: "has-no-results",
1333 noChoices: "has-no-choices",
1337 export function communitySelectName(cv: CommunityView): string {
1338 return cv.community.local
1340 : `${hostname(cv.community.actor_id)}/${cv.community.name}`;
1343 export function personSelectName(pvs: PersonViewSafe): string {
1344 return pvs.person.local
1346 : `${hostname(pvs.person.actor_id)}/${pvs.person.name}`;
1349 export function initializeSite(site: GetSiteResponse) {
1350 UserService.Instance.localUserView = site.my_user;
1351 i18n.changeLanguage(getLanguage());