1 import 'moment/locale/es';
2 import 'moment/locale/el';
3 import 'moment/locale/eu';
4 import 'moment/locale/eo';
5 import 'moment/locale/de';
6 import 'moment/locale/zh-cn';
7 import 'moment/locale/fr';
8 import 'moment/locale/sv';
9 import 'moment/locale/ru';
10 import 'moment/locale/nl';
11 import 'moment/locale/it';
12 import 'moment/locale/fi';
13 import 'moment/locale/ca';
14 import 'moment/locale/fa';
15 import 'moment/locale/pl';
16 import 'moment/locale/pt-br';
17 import 'moment/locale/ja';
18 import 'moment/locale/ka';
19 import 'moment/locale/hi';
20 import 'moment/locale/gl';
21 import 'moment/locale/tr';
22 import 'moment/locale/hu';
23 import 'moment/locale/uk';
24 import 'moment/locale/sq';
25 import 'moment/locale/km';
26 import 'moment/locale/ga';
27 import 'moment/locale/sr';
28 import 'moment/locale/ko';
33 CommentNode as CommentNodeI,
41 WebSocketJsonResponse,
46 } from 'lemmy-js-client';
48 import { CommentSortType, DataType } from './interfaces';
49 import { UserService, WebSocketService } from './services';
51 import Tribute from 'tributejs/src/Tribute.js';
52 import markdown_it from 'markdown-it';
53 import markdown_it_sub from 'markdown-it-sub';
54 import markdown_it_sup from 'markdown-it-sup';
55 import markdownitEmoji from 'markdown-it-emoji/light';
56 import markdown_it_container from 'markdown-it-container';
57 import emojiShortName from 'emoji-short-name';
58 import Toastify from 'toastify-js';
59 import tippy from 'tippy.js';
60 import moment from 'moment';
62 export const favIconUrl = '/static/assets/favicon.svg';
63 export const favIconPngUrl = '/static/assets/apple-touch-icon.png';
64 export const defaultFavIcon = `${window.location.protocol}//${window.location.host}${favIconPngUrl}`;
65 export const repoUrl = 'https://github.com/LemmyNet/lemmy';
66 export const helpGuideUrl = '/docs/about_guide.html';
67 export const markdownHelpUrl = `${helpGuideUrl}#markdown-guide`;
68 export const sortingHelpUrl = `${helpGuideUrl}#sorting`;
69 export const archiveUrl = 'https://archive.is';
70 export const elementUrl = 'https://element.io/';
72 export const postRefetchSeconds: number = 60 * 1000;
73 export const fetchLimit: number = 20;
74 export const mentionDropdownFetchLimit = 10;
76 export const languages = [
77 { code: 'ca', name: 'Català' },
78 { code: 'en', name: 'English' },
79 { code: 'el', name: 'Ελληνικά' },
80 { code: 'eu', name: 'Euskara' },
81 { code: 'eo', name: 'Esperanto' },
82 { code: 'es', name: 'Español' },
83 { code: 'de', name: 'Deutsch' },
84 { code: 'ga', name: 'Gaeilge' },
85 { code: 'gl', name: 'Galego' },
86 { code: 'hu', name: 'Magyar Nyelv' },
87 { code: 'ka', name: 'ქართული ენა' },
88 { code: 'ko', name: '한국어' },
89 { code: 'km', name: 'ភាសាខ្មែរ' },
90 { code: 'hi', name: 'मानक हिन्दी' },
91 { code: 'fa', name: 'فارسی' },
92 { code: 'ja', name: '日本語' },
93 { code: 'pl', name: 'Polski' },
94 { code: 'pt_BR', name: 'Português Brasileiro' },
95 { code: 'zh', name: '中文' },
96 { code: 'fi', name: 'Suomi' },
97 { code: 'fr', name: 'Français' },
98 { code: 'sv', name: 'Svenska' },
99 { code: 'sq', name: 'Shqip' },
100 { code: 'sr_Latn', name: 'srpski' },
101 { code: 'tr', name: 'Türkçe' },
102 { code: 'uk', name: 'Українська Mова' },
103 { code: 'ru', name: 'Русский' },
104 { code: 'nl', name: 'Nederlands' },
105 { code: 'it', name: 'Italiano' },
108 export const themes = [
124 const DEFAULT_ALPHABET =
125 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
127 function getRandomCharFromAlphabet(alphabet: string): string {
128 return alphabet.charAt(Math.floor(Math.random() * alphabet.length));
131 export function randomStr(
132 idDesiredLength: number = 20,
133 alphabet = DEFAULT_ALPHABET
136 * Create n-long array and map it to random chars from given alphabet.
137 * Then join individual chars as string
139 return Array.from({ length: idDesiredLength })
141 return getRandomCharFromAlphabet(alphabet);
146 export function wsJsonToRes(msg: WebSocketJsonResponse): WebSocketResponse {
147 let opStr: string = msg.op;
149 op: UserOperation[opStr],
154 export const md = new markdown_it({
159 .use(markdown_it_sub)
160 .use(markdown_it_sup)
161 .use(markdown_it_container, 'spoiler', {
162 validate: function (params: any) {
163 return params.trim().match(/^spoiler\s+(.*)$/);
166 render: function (tokens: any, idx: any) {
167 var m = tokens[idx].info.trim().match(/^spoiler\s+(.*)$/);
169 if (tokens[idx].nesting === 1) {
171 return `<details><summary> ${md.utils.escapeHtml(m[1])} </summary>\n`;
174 return '</details>\n';
178 .use(markdownitEmoji, {
179 defs: objectFlip(emojiShortName),
182 export function hotRankComment(comment: Comment): number {
183 return hotRank(comment.score, comment.published);
186 export function hotRankPost(post: Post): number {
187 return hotRank(post.score, post.newest_activity_time);
190 export function hotRank(score: number, timeStr: string): number {
191 // Rank = ScaleFactor * sign(Score) * log(1 + abs(Score)) / (Time + 2)^Gravity
192 let date: Date = new Date(timeStr + 'Z'); // Add Z to convert from UTC date
193 let now: Date = new Date();
194 let hoursElapsed: number = (now.getTime() - date.getTime()) / 36e5;
197 (10000 * Math.log10(Math.max(1, 3 + score))) /
198 Math.pow(hoursElapsed + 2, 1.8);
200 // console.log(`Comment: ${comment.content}\nRank: ${rank}\nScore: ${comment.score}\nHours: ${hoursElapsed}`);
205 export function mdToHtml(text: string) {
206 return { __html: md.render(text) };
209 export function getUnixTime(text: string): number {
210 return text ? new Date(text).getTime() / 1000 : undefined;
213 export function addTypeInfo<T>(
216 ): Array<{ type_: string; data: T }> {
217 return arr.map(e => {
218 return { type_: name, data: e };
222 export function canMod(
224 modIds: Array<number>,
226 onSelf: boolean = false
228 // You can do moderator actions only on the mods added after you.
230 let yourIndex = modIds.findIndex(id => id == user.id);
231 if (yourIndex == -1) {
234 // onSelf +1 on mod actions not for yourself, IE ban, remove, etc
235 modIds = modIds.slice(0, yourIndex + (onSelf ? 0 : 1));
236 return !modIds.includes(creator_id);
243 export function isMod(modIds: Array<number>, creator_id: number): boolean {
244 return modIds.includes(creator_id);
247 const imageRegex = new RegExp(
248 /(http)?s?:?(\/\/[^"']*\.(?:jpg|jpeg|gif|png|svg|webp))/
250 const videoRegex = new RegExp(`(http)?s?:?(\/\/[^"']*\.(?:mp4))`);
252 export function isImage(url: string) {
253 return imageRegex.test(url);
256 export function isVideo(url: string) {
257 return videoRegex.test(url);
260 export function validURL(str: string) {
262 return !!new URL(str);
268 export function validEmail(email: string) {
269 let re = /^(([^\s"(),.:;<>@[\\\]]+(\.[^\s"(),.:;<>@[\\\]]+)*)|(".+"))@((\[(?:\d{1,3}\.){3}\d{1,3}])|(([\dA-Za-z\-]+\.)+[A-Za-z]{2,}))$/;
270 return re.test(String(email).toLowerCase());
273 export function capitalizeFirstLetter(str: string): string {
274 return str.charAt(0).toUpperCase() + str.slice(1);
277 export function routeSortTypeToEnum(sort: string): SortType {
278 return SortType[sort];
281 export function routeListingTypeToEnum(type: string): ListingType {
282 return ListingType[type];
285 export function routeDataTypeToEnum(type: string): DataType {
286 return DataType[capitalizeFirstLetter(type)];
289 export function routeSearchTypeToEnum(type: string): SearchType {
290 return SearchType[capitalizeFirstLetter(type)];
293 export async function getPageTitle(url: string) {
294 let res = await fetch(`/iframely/oembed?url=${url}`).then(res => res.json());
295 let title = await res.title;
299 export function debounce(
302 immediate: boolean = false
304 // 'private' variable for instance
305 // The returned function will be able to reference this due to closure.
306 // Each call to the returned function will share this common timer.
309 // Calling debounce returns a new anonymous function
311 // reference the context and args for the setTimeout function
315 // Should the function be called now? If immediate is true
316 // and not already in a timeout then the answer is: Yes
317 var callNow = immediate && !timeout;
319 // This is the basic debounce behaviour where you can call this
320 // function several times, but it will only execute once
321 // [before or after imposing a delay].
322 // Each time the returned function is called, the timer starts over.
323 clearTimeout(timeout);
325 // Set the new timeout
326 timeout = setTimeout(function () {
327 // Inside the timeout function, clear the timeout variable
328 // which will let the next execution run when in 'immediate' mode
331 // Check if the function already ran with the immediate flag
333 // Call the original function with apply
334 // apply lets you define the 'this' object as well as the arguments
335 // (both captured before setTimeout)
336 func.apply(context, args);
340 // Immediate mode and no wait timer? Execute the function..
341 if (callNow) func.apply(context, args);
345 export function getLanguage(override?: string): string {
346 let user = UserService.Instance.user;
347 let lang = override || (user && user.lang ? user.lang : 'browser');
349 if (lang == 'browser') {
350 return getBrowserLanguage();
356 export function getBrowserLanguage(): string {
357 return navigator.language;
360 export function getMomentLanguage(): string {
361 let lang = getLanguage();
362 if (lang.startsWith('zh')) {
364 } else if (lang.startsWith('sv')) {
366 } else if (lang.startsWith('fr')) {
368 } else if (lang.startsWith('de')) {
370 } else if (lang.startsWith('ru')) {
372 } else if (lang.startsWith('es')) {
374 } else if (lang.startsWith('eo')) {
376 } else if (lang.startsWith('nl')) {
378 } else if (lang.startsWith('it')) {
380 } else if (lang.startsWith('fi')) {
382 } else if (lang.startsWith('ca')) {
384 } else if (lang.startsWith('fa')) {
386 } else if (lang.startsWith('pl')) {
388 } else if (lang.startsWith('pt')) {
390 } else if (lang.startsWith('ja')) {
392 } else if (lang.startsWith('ka')) {
394 } else if (lang.startsWith('hi')) {
396 } else if (lang.startsWith('el')) {
398 } else if (lang.startsWith('eu')) {
400 } else if (lang.startsWith('gl')) {
402 } else if (lang.startsWith('tr')) {
404 } else if (lang.startsWith('hu')) {
406 } else if (lang.startsWith('uk')) {
408 } else if (lang.startsWith('sq')) {
410 } else if (lang.startsWith('km')) {
412 } else if (lang.startsWith('ga')) {
414 } else if (lang.startsWith('sr')) {
416 } else if (lang.startsWith('ko')) {
424 export function setTheme(theme: string = 'darkly', loggedIn: boolean = false) {
425 // unload all the other themes
426 for (var i = 0; i < themes.length; i++) {
427 let styleSheet = document.getElementById(themes[i]);
429 styleSheet.setAttribute('disabled', 'disabled');
433 // if the user is not logged in, we load the default themes and let the browser decide
435 document.getElementById('default-light').removeAttribute('disabled');
436 document.getElementById('default-dark').removeAttribute('disabled');
439 .getElementById('default-light')
440 .setAttribute('disabled', 'disabled');
442 .getElementById('default-dark')
443 .setAttribute('disabled', 'disabled');
445 // Load the theme dynamically
446 let cssLoc = `/static/assets/css/themes/${theme}.min.css`;
447 loadCss(theme, cssLoc);
448 document.getElementById(theme).removeAttribute('disabled');
452 export function loadCss(id: string, loc: string) {
453 if (!document.getElementById(id)) {
454 var head = document.getElementsByTagName('head')[0];
455 var link = document.createElement('link');
457 link.rel = 'stylesheet';
458 link.type = 'text/css';
461 head.appendChild(link);
465 export function objectFlip(obj: any) {
467 Object.keys(obj).forEach(key => {
473 export function pictrsAvatarThumbnail(src: string): string {
474 // sample url: http://localhost:8535/pictrs/image/thumbnail256/gs7xuu.jpg
475 let split = src.split('/pictrs/image');
476 let out = `${split[0]}/pictrs/image/${
477 canUseWebP() ? 'webp/' : ''
478 }thumbnail96${split[1]}`;
482 export function showAvatars(): boolean {
484 (UserService.Instance.user && UserService.Instance.user.show_avatars) ||
485 !UserService.Instance.user
489 export function isCakeDay(published: string): boolean {
490 // moment(undefined) or moment.utc(undefined) returns the current date/time
491 // moment(null) or moment.utc(null) returns null
492 const userCreationDate = moment.utc(published || null).local();
493 const currentDate = moment(new Date());
496 userCreationDate.date() === currentDate.date() &&
497 userCreationDate.month() === currentDate.month() &&
498 userCreationDate.year() !== currentDate.year()
502 // Converts to image thumbnail
503 export function pictrsImage(hash: string, thumbnail: boolean = false): string {
504 let root = `/pictrs/image`;
506 // Necessary for other servers / domains
507 if (hash.includes('pictrs')) {
508 let split = hash.split('/pictrs/image/');
509 root = `${split[0]}/pictrs/image`;
513 let out = `${root}/${canUseWebP() ? 'webp/' : ''}${
514 thumbnail ? 'thumbnail256/' : ''
519 export function isCommentType(
520 item: Comment | PrivateMessage | Post
523 (item as Comment).community_id !== undefined &&
524 (item as Comment).content !== undefined
528 export function isPostType(
529 item: Comment | PrivateMessage | Post
531 return (item as Post).stickied !== undefined;
534 export function toast(text: string, background: string = 'success') {
535 let backgroundColor = `var(--${background})`;
538 backgroundColor: backgroundColor,
544 export function pictrsDeleteToast(
545 clickToDeleteText: string,
546 deletePictureText: string,
549 let backgroundColor = `var(--light)`;
550 let toast = Toastify({
551 text: clickToDeleteText,
552 backgroundColor: backgroundColor,
558 window.location.replace(deleteUrl);
559 alert(deletePictureText);
567 interface NotifyInfo {
574 export function messageToastify(info: NotifyInfo, router: any) {
575 let htmlBody = info.body ? md.render(info.body) : '';
576 let backgroundColor = `var(--light)`;
578 let toast = Toastify({
579 text: `${htmlBody}<br />${info.name}`,
581 backgroundColor: backgroundColor,
582 className: 'text-dark',
590 router.history.push(info.link);
596 export function notifyPost(post: Post, router: any) {
597 let info: NotifyInfo = {
598 name: post.community_name,
599 icon: post.community_icon ? post.community_icon : defaultFavIcon,
600 link: `/post/${post.id}`,
603 notify(info, router);
606 export function notifyComment(comment: Comment, router: any) {
607 let info: NotifyInfo = {
608 name: comment.creator_name,
609 icon: comment.creator_avatar ? comment.creator_avatar : defaultFavIcon,
610 link: `/post/${comment.post_id}/comment/${comment.id}`,
611 body: comment.content,
613 notify(info, router);
616 export function notifyPrivateMessage(pm: PrivateMessage, router: any) {
617 let info: NotifyInfo = {
618 name: pm.creator_name,
619 icon: pm.creator_avatar ? pm.creator_avatar : defaultFavIcon,
623 notify(info, router);
626 function notify(info: NotifyInfo, router: any) {
627 messageToastify(info, router);
629 if (Notification.permission !== 'granted') Notification.requestPermission();
631 var notification = new Notification(info.name, {
636 notification.onclick = () => {
637 event.preventDefault();
638 router.history.push(info.link);
643 export function setupTribute(): Tribute {
645 noMatchTemplate: function () {
652 menuItemTemplate: (item: any) => {
653 let shortName = `:${item.original.key}:`;
654 return `${item.original.val} ${shortName}`;
656 selectTemplate: (item: any) => {
657 return `:${item.original.key}:`;
659 values: Object.entries(emojiShortName).map(e => {
660 return { key: e[1], val: e[0] };
663 autocompleteMode: true,
664 menuItemLimit: mentionDropdownFetchLimit,
665 menuShowMinLength: 2,
670 selectTemplate: (item: any) => {
671 let link = item.original.local
672 ? `[${item.original.key}](/u/${item.original.name})`
673 : `[${item.original.key}](/user/${item.original.id})`;
676 values: (text: string, cb: any) => {
677 userSearch(text, (users: any) => cb(users));
680 autocompleteMode: true,
681 menuItemLimit: mentionDropdownFetchLimit,
682 menuShowMinLength: 2,
688 selectTemplate: (item: any) => {
689 let link = item.original.local
690 ? `[${item.original.key}](/c/${item.original.name})`
691 : `[${item.original.key}](/community/${item.original.id})`;
694 values: (text: string, cb: any) => {
695 communitySearch(text, (communities: any) => cb(communities));
698 autocompleteMode: true,
699 menuItemLimit: mentionDropdownFetchLimit,
700 menuShowMinLength: 2,
706 let tippyInstance = tippy('[data-tippy-content]');
708 export function setupTippy() {
709 tippyInstance.forEach(e => e.destroy());
710 tippyInstance = tippy('[data-tippy-content]', {
712 // Display on "long press"
713 touch: ['hold', 500],
717 function userSearch(text: string, cb: any) {
719 let form: SearchForm = {
721 type_: SearchType.Users,
722 sort: SortType.TopAll,
724 limit: mentionDropdownFetchLimit,
727 WebSocketService.Instance.search(form);
729 let userSub = WebSocketService.Instance.subject.subscribe(
731 let res = wsJsonToRes(msg);
732 if (res.op == UserOperation.Search) {
733 let data = res.data as SearchResponse;
734 let users = data.users.map(u => {
736 key: `@${u.name}@${hostname(u.actor_id)}`,
743 userSub.unsubscribe();
746 err => console.error(err),
747 () => console.log('complete')
754 function communitySearch(text: string, cb: any) {
756 let form: SearchForm = {
758 type_: SearchType.Communities,
759 sort: SortType.TopAll,
761 limit: mentionDropdownFetchLimit,
764 WebSocketService.Instance.search(form);
766 let communitySub = WebSocketService.Instance.subject.subscribe(
768 let res = wsJsonToRes(msg);
769 if (res.op == UserOperation.Search) {
770 let data = res.data as SearchResponse;
771 let communities = data.communities.map(c => {
773 key: `!${c.name}@${hostname(c.actor_id)}`,
780 communitySub.unsubscribe();
783 err => console.error(err),
784 () => console.log('complete')
791 export function getListingTypeFromProps(props: any): ListingType {
792 return props.match.params.listing_type
793 ? routeListingTypeToEnum(props.match.params.listing_type)
794 : UserService.Instance.user
795 ? Object.values(ListingType)[UserService.Instance.user.default_listing_type]
799 // TODO might need to add a user setting for this too
800 export function getDataTypeFromProps(props: any): DataType {
801 return props.match.params.data_type
802 ? routeDataTypeToEnum(props.match.params.data_type)
806 export function getSortTypeFromProps(props: any): SortType {
807 return props.match.params.sort
808 ? routeSortTypeToEnum(props.match.params.sort)
809 : UserService.Instance.user
810 ? Object.values(SortType)[UserService.Instance.user.default_sort_type]
814 export function getPageFromProps(props: any): number {
815 return props.match.params.page ? Number(props.match.params.page) : 1;
818 export function editCommentRes(
819 data: CommentResponse,
820 comments: Array<Comment>
822 let found = comments.find(c => c.id == data.comment.id);
824 found.content = data.comment.content;
825 found.updated = data.comment.updated;
826 found.removed = data.comment.removed;
827 found.deleted = data.comment.deleted;
828 found.upvotes = data.comment.upvotes;
829 found.downvotes = data.comment.downvotes;
830 found.score = data.comment.score;
834 export function saveCommentRes(
835 data: CommentResponse,
836 comments: Array<Comment>
838 let found = comments.find(c => c.id == data.comment.id);
840 found.saved = data.comment.saved;
844 export function createCommentLikeRes(
845 data: CommentResponse,
846 comments: Array<Comment>
848 let found: Comment = comments.find(c => c.id === data.comment.id);
850 found.score = data.comment.score;
851 found.upvotes = data.comment.upvotes;
852 found.downvotes = data.comment.downvotes;
853 if (data.comment.my_vote !== null) {
854 found.my_vote = data.comment.my_vote;
859 export function createPostLikeFindRes(data: PostResponse, posts: Array<Post>) {
860 let found = posts.find(c => c.id == data.post.id);
862 createPostLikeRes(data, found);
866 export function createPostLikeRes(data: PostResponse, post: Post) {
868 post.score = data.post.score;
869 post.upvotes = data.post.upvotes;
870 post.downvotes = data.post.downvotes;
871 if (data.post.my_vote !== null) {
872 post.my_vote = data.post.my_vote;
877 export function editPostFindRes(data: PostResponse, posts: Array<Post>) {
878 let found = posts.find(c => c.id == data.post.id);
880 editPostRes(data, found);
884 export function editPostRes(data: PostResponse, post: Post) {
886 post.url = data.post.url;
887 post.name = data.post.name;
888 post.nsfw = data.post.nsfw;
889 post.deleted = data.post.deleted;
890 post.removed = data.post.removed;
891 post.stickied = data.post.stickied;
892 post.body = data.post.body;
893 post.locked = data.post.locked;
897 export function commentsToFlatNodes(
898 comments: Array<Comment>
899 ): Array<CommentNodeI> {
900 let nodes: Array<CommentNodeI> = [];
901 for (let comment of comments) {
902 nodes.push({ comment: comment });
907 export function commentSort(tree: Array<CommentNodeI>, sort: CommentSortType) {
908 // First, put removed and deleted comments at the bottom, then do your other sorts
909 if (sort == CommentSortType.Top) {
912 +a.comment.removed - +b.comment.removed ||
913 +a.comment.deleted - +b.comment.deleted ||
914 b.comment.score - a.comment.score
916 } else if (sort == CommentSortType.New) {
919 +a.comment.removed - +b.comment.removed ||
920 +a.comment.deleted - +b.comment.deleted ||
921 b.comment.published.localeCompare(a.comment.published)
923 } else if (sort == CommentSortType.Old) {
926 +a.comment.removed - +b.comment.removed ||
927 +a.comment.deleted - +b.comment.deleted ||
928 a.comment.published.localeCompare(b.comment.published)
930 } else if (sort == CommentSortType.Hot) {
933 +a.comment.removed - +b.comment.removed ||
934 +a.comment.deleted - +b.comment.deleted ||
935 hotRankComment(b.comment) - hotRankComment(a.comment)
939 // Go through the children recursively
940 for (let node of tree) {
942 commentSort(node.children, sort);
947 export function commentSortSortType(tree: Array<CommentNodeI>, sort: SortType) {
948 commentSort(tree, convertCommentSortType(sort));
951 function convertCommentSortType(sort: SortType): CommentSortType {
953 sort == SortType.TopAll ||
954 sort == SortType.TopDay ||
955 sort == SortType.TopWeek ||
956 sort == SortType.TopMonth ||
957 sort == SortType.TopYear
959 return CommentSortType.Top;
960 } else if (sort == SortType.New) {
961 return CommentSortType.New;
962 } else if (sort == SortType.Hot || sort == SortType.Active) {
963 return CommentSortType.Hot;
965 return CommentSortType.Hot;
969 export function postSort(
972 communityType: boolean
974 // First, put removed and deleted comments at the bottom, then do your other sorts
976 sort == SortType.TopAll ||
977 sort == SortType.TopDay ||
978 sort == SortType.TopWeek ||
979 sort == SortType.TopMonth ||
980 sort == SortType.TopYear
984 +a.removed - +b.removed ||
985 +a.deleted - +b.deleted ||
986 (communityType && +b.stickied - +a.stickied) ||
989 } else if (sort == SortType.New) {
992 +a.removed - +b.removed ||
993 +a.deleted - +b.deleted ||
994 (communityType && +b.stickied - +a.stickied) ||
995 b.published.localeCompare(a.published)
997 } else if (sort == SortType.Hot) {
1000 +a.removed - +b.removed ||
1001 +a.deleted - +b.deleted ||
1002 (communityType && +b.stickied - +a.stickied) ||
1003 b.hot_rank - a.hot_rank
1005 } else if (sort == SortType.Active) {
1008 +a.removed - +b.removed ||
1009 +a.deleted - +b.deleted ||
1010 (communityType && +b.stickied - +a.stickied) ||
1011 b.hot_rank_active - a.hot_rank_active
1016 export const colorList: Array<string> = [
1025 function hsl(num: number) {
1026 return `hsla(${num}, 35%, 50%, 1)`;
1029 function randomHsl() {
1030 return `hsla(${Math.random() * 360}, 100%, 50%, 1)`;
1033 export function previewLines(
1035 maxChars: number = 300,
1036 maxLines: number = 1
1042 // Use lines * 2 because markdown requires 2 lines
1043 .slice(0, maxLines * 2)
1048 export function hostname(url: string): string {
1049 let cUrl = new URL(url);
1050 return window.location.port
1051 ? `${cUrl.hostname}:${cUrl.port}`
1052 : `${cUrl.hostname}`;
1055 function canUseWebP() {
1056 // TODO pictshare might have a webp conversion bug, try disabling this
1059 // var elem = document.createElement('canvas');
1060 // if (!!(elem.getContext && elem.getContext('2d'))) {
1061 // var testString = !(window.mozInnerScreenX == null) ? 'png' : 'webp';
1062 // // was able or not to get WebP representation
1064 // elem.toDataURL('image/webp').startsWith('data:image/' + testString)
1068 // // very old browser like IE 8, canvas not supported
1072 export function validTitle(title?: string): boolean {
1073 // Initial title is null, minimum length is taken care of by textarea's minLength={3}
1074 if (title === null || title.length < 3) return true;
1076 const regex = new RegExp(/.*\S.*/, 'g');
1078 return regex.test(title);
1081 export function siteBannerCss(banner: string): string {
1083 background-image: linear-gradient( rgba(0, 0, 0, 0.8), rgba(0, 0, 0, 0.8) ) ,url("${banner}"); \
1084 background-attachment: fixed; \
1085 background-position: top; \
1086 background-repeat: no-repeat; \
1087 background-size: 100% cover; \
1090 max-height: 100vh; \