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';
32 CommentNode as CommentNodeI,
42 WebSocketJsonResponse,
47 } from './interfaces';
48 import { UserService, WebSocketService } from './services';
50 import Tribute from 'tributejs/src/Tribute.js';
51 import markdown_it from 'markdown-it';
52 import markdown_it_sub from 'markdown-it-sub';
53 import markdown_it_sup from 'markdown-it-sup';
54 import markdownitEmoji from 'markdown-it-emoji/light';
55 import markdown_it_container from 'markdown-it-container';
56 import emojiShortName from 'emoji-short-name';
57 import Toastify from 'toastify-js';
58 import tippy from 'tippy.js';
59 import moment from 'moment';
61 export const favIconUrl = '/static/assets/favicon.svg';
62 export const favIconPngUrl = '/static/assets/apple-touch-icon.png';
63 export const defaultFavIcon = `${window.location.protocol}//${window.location.host}${favIconPngUrl}`;
64 export const repoUrl = 'https://github.com/LemmyNet/lemmy';
65 export const helpGuideUrl = '/docs/about_guide.html';
66 export const markdownHelpUrl = `${helpGuideUrl}#markdown-guide`;
67 export const sortingHelpUrl = `${helpGuideUrl}#sorting`;
68 export const archiveUrl = 'https://archive.is';
69 export const elementUrl = 'https://element.io/';
71 export const postRefetchSeconds: number = 60 * 1000;
72 export const fetchLimit: number = 20;
73 export const mentionDropdownFetchLimit = 10;
75 export const languages = [
76 { code: 'ca', name: 'Català' },
77 { code: 'en', name: 'English' },
78 { code: 'el', name: 'Ελληνικά' },
79 { code: 'eu', name: 'Euskara' },
80 { code: 'eo', name: 'Esperanto' },
81 { code: 'es', name: 'Español' },
82 { code: 'de', name: 'Deutsch' },
83 { code: 'ga', name: 'Gaeilge' },
84 { code: 'gl', name: 'Galego' },
85 { code: 'hu', name: 'Magyar Nyelv' },
86 { code: 'ka', name: 'ქართული ენა' },
87 { code: 'km', name: 'ភាសាខ្មែរ' },
88 { code: 'hi', name: 'मानक हिन्दी' },
89 { code: 'fa', name: 'فارسی' },
90 { code: 'ja', name: '日本語' },
91 { code: 'pl', name: 'Polski' },
92 { code: 'pt_BR', name: 'Português Brasileiro' },
93 { code: 'zh', name: '中文' },
94 { code: 'fi', name: 'Suomi' },
95 { code: 'fr', name: 'Français' },
96 { code: 'sv', name: 'Svenska' },
97 { code: 'sq', name: 'Shqip' },
98 { code: 'sr_Latn', name: 'srpski' },
99 { code: 'tr', name: 'Türkçe' },
100 { code: 'uk', name: 'Українська Mова' },
101 { code: 'ru', name: 'Русский' },
102 { code: 'nl', name: 'Nederlands' },
103 { code: 'it', name: 'Italiano' },
106 export const themes = [
122 const DEFAULT_ALPHABET =
123 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
125 function getRandomCharFromAlphabet(alphabet: string): string {
126 return alphabet.charAt(Math.floor(Math.random() * alphabet.length));
129 export function randomStr(
130 idDesiredLength: number = 20,
131 alphabet = DEFAULT_ALPHABET
134 * Create n-long array and map it to random chars from given alphabet.
135 * Then join individual chars as string
137 return Array.from({ length: idDesiredLength })
139 return getRandomCharFromAlphabet(alphabet);
144 export function wsJsonToRes(msg: WebSocketJsonResponse): WebSocketResponse {
145 let opStr: string = msg.op;
147 op: UserOperation[opStr],
152 export const md = new markdown_it({
157 .use(markdown_it_sub)
158 .use(markdown_it_sup)
159 .use(markdown_it_container, 'spoiler', {
160 validate: function (params: any) {
161 return params.trim().match(/^spoiler\s+(.*)$/);
164 render: function (tokens: any, idx: any) {
165 var m = tokens[idx].info.trim().match(/^spoiler\s+(.*)$/);
167 if (tokens[idx].nesting === 1) {
169 return `<details><summary> ${md.utils.escapeHtml(m[1])} </summary>\n`;
172 return '</details>\n';
176 .use(markdownitEmoji, {
177 defs: objectFlip(emojiShortName),
180 export function hotRankComment(comment: Comment): number {
181 return hotRank(comment.score, comment.published);
184 export function hotRankPost(post: Post): number {
185 return hotRank(post.score, post.newest_activity_time);
188 export function hotRank(score: number, timeStr: string): number {
189 // Rank = ScaleFactor * sign(Score) * log(1 + abs(Score)) / (Time + 2)^Gravity
190 let date: Date = new Date(timeStr + 'Z'); // Add Z to convert from UTC date
191 let now: Date = new Date();
192 let hoursElapsed: number = (now.getTime() - date.getTime()) / 36e5;
195 (10000 * Math.log10(Math.max(1, 3 + score))) /
196 Math.pow(hoursElapsed + 2, 1.8);
198 // console.log(`Comment: ${comment.content}\nRank: ${rank}\nScore: ${comment.score}\nHours: ${hoursElapsed}`);
203 export function mdToHtml(text: string) {
204 return { __html: md.render(text) };
207 export function getUnixTime(text: string): number {
208 return text ? new Date(text).getTime() / 1000 : undefined;
211 export function addTypeInfo<T>(
214 ): Array<{ type_: string; data: T }> {
215 return arr.map(e => {
216 return { type_: name, data: e };
220 export function canMod(
222 modIds: Array<number>,
224 onSelf: boolean = false
226 // You can do moderator actions only on the mods added after you.
228 let yourIndex = modIds.findIndex(id => id == user.id);
229 if (yourIndex == -1) {
232 // onSelf +1 on mod actions not for yourself, IE ban, remove, etc
233 modIds = modIds.slice(0, yourIndex + (onSelf ? 0 : 1));
234 return !modIds.includes(creator_id);
241 export function isMod(modIds: Array<number>, creator_id: number): boolean {
242 return modIds.includes(creator_id);
245 const imageRegex = new RegExp(
246 /(http)?s?:?(\/\/[^"']*\.(?:jpg|jpeg|gif|png|svg|webp))/
248 const videoRegex = new RegExp(`(http)?s?:?(\/\/[^"']*\.(?:mp4))`);
250 export function isImage(url: string) {
251 return imageRegex.test(url);
254 export function isVideo(url: string) {
255 return videoRegex.test(url);
258 export function validURL(str: string) {
260 return !!new URL(str);
266 export function validEmail(email: string) {
267 let re = /^(([^\s"(),.:;<>@[\\\]]+(\.[^\s"(),.:;<>@[\\\]]+)*)|(".+"))@((\[(?:\d{1,3}\.){3}\d{1,3}])|(([\dA-Za-z\-]+\.)+[A-Za-z]{2,}))$/;
268 return re.test(String(email).toLowerCase());
271 export function capitalizeFirstLetter(str: string): string {
272 return str.charAt(0).toUpperCase() + str.slice(1);
275 export function routeSortTypeToEnum(sort: string): SortType {
278 } else if (sort == 'hot') {
280 } else if (sort == 'active') {
281 return SortType.Active;
282 } else if (sort == 'topday') {
283 return SortType.TopDay;
284 } else if (sort == 'topweek') {
285 return SortType.TopWeek;
286 } else if (sort == 'topmonth') {
287 return SortType.TopMonth;
288 } else if (sort == 'topyear') {
289 return SortType.TopYear;
290 } else if (sort == 'topall') {
291 return SortType.TopAll;
295 export function routeListingTypeToEnum(type: string): ListingType {
296 return ListingType[capitalizeFirstLetter(type)];
299 export function routeDataTypeToEnum(type: string): DataType {
300 return DataType[capitalizeFirstLetter(type)];
303 export function routeSearchTypeToEnum(type: string): SearchType {
304 return SearchType[capitalizeFirstLetter(type)];
307 export async function getPageTitle(url: string) {
308 let res = await fetch(`/iframely/oembed?url=${url}`).then(res => res.json());
309 let title = await res.title;
313 export function debounce(
316 immediate: boolean = false
318 // 'private' variable for instance
319 // The returned function will be able to reference this due to closure.
320 // Each call to the returned function will share this common timer.
323 // Calling debounce returns a new anonymous function
325 // reference the context and args for the setTimeout function
329 // Should the function be called now? If immediate is true
330 // and not already in a timeout then the answer is: Yes
331 var callNow = immediate && !timeout;
333 // This is the basic debounce behaviour where you can call this
334 // function several times, but it will only execute once
335 // [before or after imposing a delay].
336 // Each time the returned function is called, the timer starts over.
337 clearTimeout(timeout);
339 // Set the new timeout
340 timeout = setTimeout(function () {
341 // Inside the timeout function, clear the timeout variable
342 // which will let the next execution run when in 'immediate' mode
345 // Check if the function already ran with the immediate flag
347 // Call the original function with apply
348 // apply lets you define the 'this' object as well as the arguments
349 // (both captured before setTimeout)
350 func.apply(context, args);
354 // Immediate mode and no wait timer? Execute the function..
355 if (callNow) func.apply(context, args);
359 export function getLanguage(override?: string): string {
360 let user = UserService.Instance.user;
361 let lang = override || (user && user.lang ? user.lang : 'browser');
363 if (lang == 'browser') {
364 return getBrowserLanguage();
370 export function getBrowserLanguage(): string {
371 return navigator.language;
374 export function getMomentLanguage(): string {
375 let lang = getLanguage();
376 if (lang.startsWith('zh')) {
378 } else if (lang.startsWith('sv')) {
380 } else if (lang.startsWith('fr')) {
382 } else if (lang.startsWith('de')) {
384 } else if (lang.startsWith('ru')) {
386 } else if (lang.startsWith('es')) {
388 } else if (lang.startsWith('eo')) {
390 } else if (lang.startsWith('nl')) {
392 } else if (lang.startsWith('it')) {
394 } else if (lang.startsWith('fi')) {
396 } else if (lang.startsWith('ca')) {
398 } else if (lang.startsWith('fa')) {
400 } else if (lang.startsWith('pl')) {
402 } else if (lang.startsWith('pt')) {
404 } else if (lang.startsWith('ja')) {
406 } else if (lang.startsWith('ka')) {
408 } else if (lang.startsWith('hi')) {
410 } else if (lang.startsWith('el')) {
412 } else if (lang.startsWith('eu')) {
414 } else if (lang.startsWith('gl')) {
416 } else if (lang.startsWith('tr')) {
418 } else if (lang.startsWith('hu')) {
420 } else if (lang.startsWith('uk')) {
422 } else if (lang.startsWith('sq')) {
424 } else if (lang.startsWith('km')) {
426 } else if (lang.startsWith('ga')) {
428 } else if (lang.startsWith('sr')) {
436 export function setTheme(theme: string = 'darkly', loggedIn: boolean = false) {
437 // unload all the other themes
438 for (var i = 0; i < themes.length; i++) {
439 let styleSheet = document.getElementById(themes[i]);
441 styleSheet.setAttribute('disabled', 'disabled');
445 // if the user is not logged in, we load the default themes and let the browser decide
447 document.getElementById('default-light').removeAttribute('disabled');
448 document.getElementById('default-dark').removeAttribute('disabled');
451 .getElementById('default-light')
452 .setAttribute('disabled', 'disabled');
454 .getElementById('default-dark')
455 .setAttribute('disabled', 'disabled');
457 // Load the theme dynamically
458 let cssLoc = `/static/assets/css/themes/${theme}.min.css`;
459 loadCss(theme, cssLoc);
460 document.getElementById(theme).removeAttribute('disabled');
464 export function loadCss(id: string, loc: string) {
465 if (!document.getElementById(id)) {
466 var head = document.getElementsByTagName('head')[0];
467 var link = document.createElement('link');
469 link.rel = 'stylesheet';
470 link.type = 'text/css';
473 head.appendChild(link);
477 export function objectFlip(obj: any) {
479 Object.keys(obj).forEach(key => {
485 export function pictrsAvatarThumbnail(src: string): string {
486 // sample url: http://localhost:8535/pictrs/image/thumbnail256/gs7xuu.jpg
487 let split = src.split('/pictrs/image');
488 let out = `${split[0]}/pictrs/image/${
489 canUseWebP() ? 'webp/' : ''
490 }thumbnail96${split[1]}`;
494 export function showAvatars(): boolean {
496 (UserService.Instance.user && UserService.Instance.user.show_avatars) ||
497 !UserService.Instance.user
501 export function isCakeDay(published: string): boolean {
502 // moment(undefined) or moment.utc(undefined) returns the current date/time
503 // moment(null) or moment.utc(null) returns null
504 const userCreationDate = moment.utc(published || null).local();
505 const currentDate = moment(new Date());
508 userCreationDate.date() === currentDate.date() &&
509 userCreationDate.month() === currentDate.month() &&
510 userCreationDate.year() !== currentDate.year()
514 // Converts to image thumbnail
515 export function pictrsImage(hash: string, thumbnail: boolean = false): string {
516 let root = `/pictrs/image`;
518 // Necessary for other servers / domains
519 if (hash.includes('pictrs')) {
520 let split = hash.split('/pictrs/image/');
521 root = `${split[0]}/pictrs/image`;
525 let out = `${root}/${canUseWebP() ? 'webp/' : ''}${
526 thumbnail ? 'thumbnail256/' : ''
531 export function isCommentType(
532 item: Comment | PrivateMessage | Post
535 (item as Comment).community_id !== undefined &&
536 (item as Comment).content !== undefined
540 export function isPostType(
541 item: Comment | PrivateMessage | Post
543 return (item as Post).stickied !== undefined;
546 export function toast(text: string, background: string = 'success') {
547 let backgroundColor = `var(--${background})`;
550 backgroundColor: backgroundColor,
556 export function pictrsDeleteToast(
557 clickToDeleteText: string,
558 deletePictureText: string,
561 let backgroundColor = `var(--light)`;
562 let toast = Toastify({
563 text: clickToDeleteText,
564 backgroundColor: backgroundColor,
570 window.location.replace(deleteUrl);
571 alert(deletePictureText);
579 interface NotifyInfo {
586 export function messageToastify(info: NotifyInfo, router: any) {
587 let htmlBody = info.body ? md.render(info.body) : '';
588 let backgroundColor = `var(--light)`;
590 let toast = Toastify({
591 text: `${htmlBody}<br />${info.name}`,
593 backgroundColor: backgroundColor,
594 className: 'text-dark',
602 router.history.push(info.link);
608 export function notifyPost(post: Post, router: any) {
609 let info: NotifyInfo = {
610 name: post.community_name,
611 icon: post.community_icon ? post.community_icon : defaultFavIcon,
612 link: `/post/${post.id}`,
615 notify(info, router);
618 export function notifyComment(comment: Comment, router: any) {
619 let info: NotifyInfo = {
620 name: comment.creator_name,
621 icon: comment.creator_avatar ? comment.creator_avatar : defaultFavIcon,
622 link: `/post/${comment.post_id}/comment/${comment.id}`,
623 body: comment.content,
625 notify(info, router);
628 export function notifyPrivateMessage(pm: PrivateMessage, router: any) {
629 let info: NotifyInfo = {
630 name: pm.creator_name,
631 icon: pm.creator_avatar ? pm.creator_avatar : defaultFavIcon,
635 notify(info, router);
638 function notify(info: NotifyInfo, router: any) {
639 messageToastify(info, router);
641 if (Notification.permission !== 'granted') Notification.requestPermission();
643 var notification = new Notification(info.name, {
648 notification.onclick = () => {
649 event.preventDefault();
650 router.history.push(info.link);
655 export function setupTribute(): Tribute {
657 noMatchTemplate: function () {
664 menuItemTemplate: (item: any) => {
665 let shortName = `:${item.original.key}:`;
666 return `${item.original.val} ${shortName}`;
668 selectTemplate: (item: any) => {
669 return `:${item.original.key}:`;
671 values: Object.entries(emojiShortName).map(e => {
672 return { key: e[1], val: e[0] };
675 autocompleteMode: true,
676 menuItemLimit: mentionDropdownFetchLimit,
677 menuShowMinLength: 2,
682 selectTemplate: (item: any) => {
683 let link = item.original.local
684 ? `[${item.original.key}](/u/${item.original.name})`
685 : `[${item.original.key}](/user/${item.original.id})`;
688 values: (text: string, cb: any) => {
689 userSearch(text, (users: any) => cb(users));
692 autocompleteMode: true,
693 menuItemLimit: mentionDropdownFetchLimit,
694 menuShowMinLength: 2,
700 selectTemplate: (item: any) => {
701 let link = item.original.local
702 ? `[${item.original.key}](/c/${item.original.name})`
703 : `[${item.original.key}](/community/${item.original.id})`;
706 values: (text: string, cb: any) => {
707 communitySearch(text, (communities: any) => cb(communities));
710 autocompleteMode: true,
711 menuItemLimit: mentionDropdownFetchLimit,
712 menuShowMinLength: 2,
718 let tippyInstance = tippy('[data-tippy-content]');
720 export function setupTippy() {
721 tippyInstance.forEach(e => e.destroy());
722 tippyInstance = tippy('[data-tippy-content]', {
724 // Display on "long press"
725 touch: ['hold', 500],
729 function userSearch(text: string, cb: any) {
731 let form: SearchForm = {
733 type_: SearchType[SearchType.Users],
734 sort: SortType[SortType.TopAll],
736 limit: mentionDropdownFetchLimit,
739 WebSocketService.Instance.search(form);
741 let userSub = WebSocketService.Instance.subject.subscribe(
743 let res = wsJsonToRes(msg);
744 if (res.op == UserOperation.Search) {
745 let data = res.data as SearchResponse;
746 let users = data.users.map(u => {
748 key: `@${u.name}@${hostname(u.actor_id)}`,
755 userSub.unsubscribe();
758 err => console.error(err),
759 () => console.log('complete')
766 function communitySearch(text: string, cb: any) {
768 let form: SearchForm = {
770 type_: SearchType[SearchType.Communities],
771 sort: SortType[SortType.TopAll],
773 limit: mentionDropdownFetchLimit,
776 WebSocketService.Instance.search(form);
778 let communitySub = WebSocketService.Instance.subject.subscribe(
780 let res = wsJsonToRes(msg);
781 if (res.op == UserOperation.Search) {
782 let data = res.data as SearchResponse;
783 let communities = data.communities.map(c => {
785 key: `!${c.name}@${hostname(c.actor_id)}`,
792 communitySub.unsubscribe();
795 err => console.error(err),
796 () => console.log('complete')
803 export function getListingTypeFromProps(props: any): ListingType {
804 return props.match.params.listing_type
805 ? routeListingTypeToEnum(props.match.params.listing_type)
806 : UserService.Instance.user
807 ? UserService.Instance.user.default_listing_type
811 // TODO might need to add a user setting for this too
812 export function getDataTypeFromProps(props: any): DataType {
813 return props.match.params.data_type
814 ? routeDataTypeToEnum(props.match.params.data_type)
818 export function getSortTypeFromProps(props: any): SortType {
819 return props.match.params.sort
820 ? routeSortTypeToEnum(props.match.params.sort)
821 : UserService.Instance.user
822 ? UserService.Instance.user.default_sort_type
826 export function getPageFromProps(props: any): number {
827 return props.match.params.page ? Number(props.match.params.page) : 1;
830 export function editCommentRes(
831 data: CommentResponse,
832 comments: Array<Comment>
834 let found = comments.find(c => c.id == data.comment.id);
836 found.content = data.comment.content;
837 found.updated = data.comment.updated;
838 found.removed = data.comment.removed;
839 found.deleted = data.comment.deleted;
840 found.upvotes = data.comment.upvotes;
841 found.downvotes = data.comment.downvotes;
842 found.score = data.comment.score;
846 export function saveCommentRes(
847 data: CommentResponse,
848 comments: Array<Comment>
850 let found = comments.find(c => c.id == data.comment.id);
852 found.saved = data.comment.saved;
856 export function createCommentLikeRes(
857 data: CommentResponse,
858 comments: Array<Comment>
860 let found: Comment = comments.find(c => c.id === data.comment.id);
862 found.score = data.comment.score;
863 found.upvotes = data.comment.upvotes;
864 found.downvotes = data.comment.downvotes;
865 if (data.comment.my_vote !== null) {
866 found.my_vote = data.comment.my_vote;
871 export function createPostLikeFindRes(data: PostResponse, posts: Array<Post>) {
872 let found = posts.find(c => c.id == data.post.id);
874 createPostLikeRes(data, found);
878 export function createPostLikeRes(data: PostResponse, post: Post) {
880 post.score = data.post.score;
881 post.upvotes = data.post.upvotes;
882 post.downvotes = data.post.downvotes;
883 if (data.post.my_vote !== null) {
884 post.my_vote = data.post.my_vote;
889 export function editPostFindRes(data: PostResponse, posts: Array<Post>) {
890 let found = posts.find(c => c.id == data.post.id);
892 editPostRes(data, found);
896 export function editPostRes(data: PostResponse, post: Post) {
898 post.url = data.post.url;
899 post.name = data.post.name;
900 post.nsfw = data.post.nsfw;
901 post.deleted = data.post.deleted;
902 post.removed = data.post.removed;
903 post.stickied = data.post.stickied;
904 post.body = data.post.body;
905 post.locked = data.post.locked;
909 export function commentsToFlatNodes(
910 comments: Array<Comment>
911 ): Array<CommentNodeI> {
912 let nodes: Array<CommentNodeI> = [];
913 for (let comment of comments) {
914 nodes.push({ comment: comment });
919 export function commentSort(tree: Array<CommentNodeI>, sort: CommentSortType) {
920 // First, put removed and deleted comments at the bottom, then do your other sorts
921 if (sort == CommentSortType.Top) {
924 +a.comment.removed - +b.comment.removed ||
925 +a.comment.deleted - +b.comment.deleted ||
926 b.comment.score - a.comment.score
928 } else if (sort == CommentSortType.New) {
931 +a.comment.removed - +b.comment.removed ||
932 +a.comment.deleted - +b.comment.deleted ||
933 b.comment.published.localeCompare(a.comment.published)
935 } else if (sort == CommentSortType.Old) {
938 +a.comment.removed - +b.comment.removed ||
939 +a.comment.deleted - +b.comment.deleted ||
940 a.comment.published.localeCompare(b.comment.published)
942 } else if (sort == CommentSortType.Hot) {
945 +a.comment.removed - +b.comment.removed ||
946 +a.comment.deleted - +b.comment.deleted ||
947 hotRankComment(b.comment) - hotRankComment(a.comment)
951 // Go through the children recursively
952 for (let node of tree) {
954 commentSort(node.children, sort);
959 export function commentSortSortType(tree: Array<CommentNodeI>, sort: SortType) {
960 commentSort(tree, convertCommentSortType(sort));
963 function convertCommentSortType(sort: SortType): CommentSortType {
965 sort == SortType.TopAll ||
966 sort == SortType.TopDay ||
967 sort == SortType.TopWeek ||
968 sort == SortType.TopMonth ||
969 sort == SortType.TopYear
971 return CommentSortType.Top;
972 } else if (sort == SortType.New) {
973 return CommentSortType.New;
974 } else if (sort == SortType.Hot || sort == SortType.Active) {
975 return CommentSortType.Hot;
977 return CommentSortType.Hot;
981 export function postSort(
984 communityType: boolean
986 // First, put removed and deleted comments at the bottom, then do your other sorts
988 sort == SortType.TopAll ||
989 sort == SortType.TopDay ||
990 sort == SortType.TopWeek ||
991 sort == SortType.TopMonth ||
992 sort == SortType.TopYear
996 +a.removed - +b.removed ||
997 +a.deleted - +b.deleted ||
998 (communityType && +b.stickied - +a.stickied) ||
1001 } else if (sort == SortType.New) {
1004 +a.removed - +b.removed ||
1005 +a.deleted - +b.deleted ||
1006 (communityType && +b.stickied - +a.stickied) ||
1007 b.published.localeCompare(a.published)
1009 } else if (sort == SortType.Hot) {
1012 +a.removed - +b.removed ||
1013 +a.deleted - +b.deleted ||
1014 (communityType && +b.stickied - +a.stickied) ||
1015 b.hot_rank - a.hot_rank
1017 } else if (sort == SortType.Active) {
1020 +a.removed - +b.removed ||
1021 +a.deleted - +b.deleted ||
1022 (communityType && +b.stickied - +a.stickied) ||
1023 b.hot_rank_active - a.hot_rank_active
1028 export const colorList: Array<string> = [
1037 function hsl(num: number) {
1038 return `hsla(${num}, 35%, 50%, 1)`;
1041 function randomHsl() {
1042 return `hsla(${Math.random() * 360}, 100%, 50%, 1)`;
1045 export function previewLines(
1047 maxChars: number = 300,
1048 maxLines: number = 1
1054 // Use lines * 2 because markdown requires 2 lines
1055 .slice(0, maxLines * 2)
1060 export function hostname(url: string): string {
1061 let cUrl = new URL(url);
1062 return window.location.port
1063 ? `${cUrl.hostname}:${cUrl.port}`
1064 : `${cUrl.hostname}`;
1067 function canUseWebP() {
1068 // TODO pictshare might have a webp conversion bug, try disabling this
1071 // var elem = document.createElement('canvas');
1072 // if (!!(elem.getContext && elem.getContext('2d'))) {
1073 // var testString = !(window.mozInnerScreenX == null) ? 'png' : 'webp';
1074 // // was able or not to get WebP representation
1076 // elem.toDataURL('image/webp').startsWith('data:image/' + testString)
1080 // // very old browser like IE 8, canvas not supported
1084 export function validTitle(title?: string): boolean {
1085 // Initial title is null, minimum length is taken care of by textarea's minLength={3}
1086 if (title === null || title.length < 3) return true;
1088 const regex = new RegExp(/.*\S.*/, 'g');
1090 return regex.test(title);
1093 export function siteBannerCss(banner: string): string {
1095 background-image: linear-gradient( rgba(0, 0, 0, 0.8), rgba(0, 0, 0, 0.8) ) ,url("${banner}"); \
1096 background-attachment: fixed; \
1097 background-position: top; \
1098 background-repeat: no-repeat; \
1099 background-size: 100% cover; \
1102 max-height: 100vh; \