]> Untitled Git - lemmy.git/blobdiff - ui/src/utils.ts
Merge branch 'dev' into federation
[lemmy.git] / ui / src / utils.ts
index 384d5c1d500ab71d56ee456fc05704f8d6aba6c8..480b41c7c313a6ffcd6403456583b4ee14fe2ee9 100644 (file)
@@ -11,11 +11,13 @@ import 'moment/locale/fi';
 import 'moment/locale/ca';
 import 'moment/locale/fa';
 import 'moment/locale/pt-br';
+import 'moment/locale/ja';
+import 'moment/locale/ka';
 
 import {
   UserOperation,
   Comment,
-  CommentNode,
+  CommentNode as CommentNodeI,
   Post,
   PrivateMessage,
   User,
@@ -40,15 +42,61 @@ import markdown_it_container from 'markdown-it-container';
 import twemoji from 'twemoji';
 import emojiShortName from 'emoji-short-name';
 import Toastify from 'toastify-js';
+import tippy from 'tippy.js';
+import EmojiButton from '@joeattardi/emoji-button';
 
-export const repoUrl = 'https://github.com/dessalines/lemmy';
-export const markdownHelpUrl = 'https://commonmark.org/help/';
+export const repoUrl = 'https://github.com/LemmyNet/lemmy';
+export const helpGuideUrl = '/docs/about_guide.html';
+export const markdownHelpUrl = `${helpGuideUrl}#markdown-guide`;
+export const sortingHelpUrl = `${helpGuideUrl}#sorting`;
 export const archiveUrl = 'https://archive.is';
 
 export const postRefetchSeconds: number = 60 * 1000;
 export const fetchLimit: number = 20;
 export const mentionDropdownFetchLimit = 10;
 
+export const languages = [
+  { code: 'ca', name: 'Català' },
+  { code: 'en', name: 'English' },
+  { code: 'eo', name: 'Esperanto' },
+  { code: 'es', name: 'Español' },
+  { code: 'de', name: 'Deutsch' },
+  { code: 'ka', name: 'ქართული ენა' },
+  { code: 'fa', name: 'فارسی' },
+  { code: 'ja', name: '日本語' },
+  { code: 'pt_BR', name: 'Português Brasileiro' },
+  { code: 'zh', name: '中文' },
+  { code: 'fi', name: 'Suomi' },
+  { code: 'fr', name: 'Français' },
+  { code: 'sv', name: 'Svenska' },
+  { code: 'ru', name: 'Русский' },
+  { code: 'nl', name: 'Nederlands' },
+  { code: 'it', name: 'Italiano' },
+];
+
+export const themes = [
+  'litera',
+  'materia',
+  'minty',
+  'solar',
+  'united',
+  'cyborg',
+  'darkly',
+  'journal',
+  'sketchy',
+  'vaporwave',
+  'vaporwave-dark',
+  'i386',
+];
+
+export const emojiPicker = new EmojiButton({
+  // Use the emojiShortName from native
+  style: 'twemoji',
+  theme: 'dark',
+  position: 'auto-start',
+  // TODO i18n
+});
+
 export function randomStr() {
   return Math.random()
     .toString(36)
@@ -70,11 +118,11 @@ export const md = new markdown_it({
   typographer: true,
 })
   .use(markdown_it_container, 'spoiler', {
-    validate: function(params: any) {
+    validate: function (params: any) {
       return params.trim().match(/^spoiler\s+(.*)$/);
     },
 
-    render: function(tokens: any, idx: any) {
+    render: function (tokens: any, idx: any) {
       var m = tokens[idx].info.trim().match(/^spoiler\s+(.*)$/);
 
       if (tokens[idx].nesting === 1) {
@@ -90,7 +138,7 @@ export const md = new markdown_it({
     defs: objectFlip(emojiShortName),
   });
 
-md.renderer.rules.emoji = function(token, idx) {
+md.renderer.rules.emoji = function (token, idx) {
   return twemoji.parse(token[idx].content);
 };
 
@@ -159,10 +207,10 @@ export function isMod(modIds: Array<number>, creator_id: number): boolean {
   return modIds.includes(creator_id);
 }
 
-var imageRegex = new RegExp(
-  `(http)?s?:?(\/\/[^"']*\.(?:png|jpg|jpeg|gif|png|svg))`
+const imageRegex = new RegExp(
+  /(http)?s?:?(\/\/[^"']*\.(?:jpg|jpeg|gif|png|svg))/
 );
-var videoRegex = new RegExp(`(http)?s?:?(\/\/[^"']*\.(?:mp4))`);
+const videoRegex = new RegExp(`(http)?s?:?(\/\/[^"']*\.(?:mp4))`);
 
 export function isImage(url: string) {
   return imageRegex.test(url);
@@ -181,7 +229,7 @@ export function validURL(str: string) {
 }
 
 export function validEmail(email: string) {
-  let re = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
+  let re = /^(([^\s"(),.:;<>@[\\\]]+(\.[^\s"(),.:;<>@[\\\]]+)*)|(".+"))@((\[(?:\d{1,3}\.){3}\d{1,3}])|(([\dA-Za-z\-]+\.)+[A-Za-z]{2,}))$/;
   return re.test(String(email).toLowerCase());
 }
 
@@ -220,9 +268,9 @@ export function routeSearchTypeToEnum(type: string): SearchType {
 }
 
 export async function getPageTitle(url: string) {
-  let res = await fetch(`https://textance.herokuapp.com/title/${url}`);
-  let data = await res.text();
-  return data;
+  let res = await fetch(`/iframely/oembed?url=${url}`).then(res => res.json());
+  let title = await res.title;
+  return title;
 }
 
 export function debounce(
@@ -236,7 +284,7 @@ export function debounce(
   let timeout: any;
 
   // Calling debounce returns a new anonymous function
-  return function() {
+  return function () {
     // reference the context and args for the setTimeout function
     var context = this,
       args = arguments;
@@ -252,7 +300,7 @@ export function debounce(
     clearTimeout(timeout);
 
     // Set the new timeout
-    timeout = setTimeout(function() {
+    timeout = setTimeout(function () {
       // Inside the timeout function, clear the timeout variable
       // which will let the next execution run when in 'immediate' mode
       timeout = null;
@@ -271,23 +319,6 @@ export function debounce(
   };
 }
 
-export const languages = [
-  { code: 'ca', name: 'Català' },
-  { code: 'en', name: 'English' },
-  { code: 'eo', name: 'Esperanto' },
-  { code: 'es', name: 'Español' },
-  { code: 'de', name: 'Deutsch' },
-  { code: 'fa', name: 'فارسی' },
-  { code: 'pt_BR', name: 'Português Brasileiro' },
-  { code: 'zh', name: '中文' },
-  { code: 'fi', name: 'Suomi' },
-  { code: 'fr', name: 'Français' },
-  { code: 'sv', name: 'Svenska' },
-  { code: 'ru', name: 'Русский' },
-  { code: 'nl', name: 'Nederlands' },
-  { code: 'it', name: 'Italiano' },
-];
-
 export function getLanguage(): string {
   let user = UserService.Instance.user;
   let lang = user && user.lang ? user.lang : 'browser';
@@ -331,27 +362,16 @@ export function getMomentLanguage(): string {
     lang = 'fa';
   } else if (lang.startsWith('pt')) {
     lang = 'pt-br';
+  } else if (lang.startsWith('ja')) {
+    lang = 'ja';
+  } else if (lang.startsWith('ka')) {
+    lang = 'ka';
   } else {
     lang = 'en';
   }
   return lang;
 }
 
-export const themes = [
-  'litera',
-  'materia',
-  'minty',
-  'solar',
-  'united',
-  'cyborg',
-  'darkly',
-  'journal',
-  'sketchy',
-  'vaporwave',
-  'vaporwave-dark',
-  'i386',
-];
-
 export function setTheme(theme: string = 'darkly') {
   // unload all the other themes
   for (var i = 0; i < themes.length; i++) {
@@ -386,7 +406,7 @@ export function objectFlip(obj: any) {
 export function pictshareAvatarThumbnail(src: string): string {
   // sample url: http://localhost:8535/pictshare/gs7xuu.jpg
   let split = src.split('pictshare');
-  let out = `${split[0]}pictshare/96x96${split[1]}`;
+  let out = `${split[0]}pictshare/96${split[1]}`;
   return out;
 }
 
@@ -397,15 +417,22 @@ export function showAvatars(): boolean {
   );
 }
 
-/// Converts to image thumbnail (only supports pictshare currently)
-export function imageThumbnailer(url: string): string {
-  let split = url.split('pictshare');
-  if (split.length > 1) {
-    let out = `${split[0]}pictshare/192x192${split[1]}`;
-    return out;
-  } else {
-    return url;
+// Converts to image thumbnail
+export function pictshareImage(
+  hash: string,
+  thumbnail: boolean = false
+): string {
+  let root = `/pictshare`;
+
+  // Necessary for other servers / domains
+  if (hash.includes('pictshare')) {
+    let split = hash.split('/pictshare/');
+    root = `${split[0]}/pictshare`;
+    hash = split[1];
   }
+
+  let out = `${root}/${thumbnail ? '192/' : ''}${hash}`;
+  return out;
 }
 
 export function isCommentType(item: Comment | PrivateMessage): item is Comment {
@@ -422,6 +449,32 @@ export function toast(text: string, background: string = 'success') {
   }).showToast();
 }
 
+export function messageToastify(
+  creator: string,
+  avatar: string,
+  body: string,
+  link: string,
+  router: any
+) {
+  let backgroundColor = `var(--light)`;
+
+  let toast = Toastify({
+    text: `${body}<br />${creator}`,
+    avatar: avatar,
+    backgroundColor: backgroundColor,
+    close: true,
+    gravity: 'top',
+    position: 'right',
+    duration: 0,
+    onClick: () => {
+      if (toast) {
+        toast.hideToast();
+        router.history.push(link);
+      }
+    },
+  }).showToast();
+}
+
 export function setupTribute(): Tribute {
   return new Tribute({
     collection: [
@@ -429,8 +482,9 @@ export function setupTribute(): Tribute {
       {
         trigger: ':',
         menuItemTemplate: (item: any) => {
-          let emoji = `:${item.original.key}:`;
-          return `${item.original.val} ${emoji}`;
+          let shortName = `:${item.original.key}:`;
+          let twemojiIcon = twemoji.parse(item.original.val);
+          return `${twemojiIcon} ${shortName}`;
         },
         selectTemplate: (item: any) => {
           return `:${item.original.key}:`;
@@ -441,6 +495,7 @@ export function setupTribute(): Tribute {
         allowSpaces: false,
         autocompleteMode: true,
         menuItemLimit: mentionDropdownFetchLimit,
+        menuShowMinLength: 2,
       },
       // Users
       {
@@ -454,6 +509,7 @@ export function setupTribute(): Tribute {
         allowSpaces: false,
         autocompleteMode: true,
         menuItemLimit: mentionDropdownFetchLimit,
+        menuShowMinLength: 2,
       },
 
       // Communities
@@ -468,11 +524,23 @@ export function setupTribute(): Tribute {
         allowSpaces: false,
         autocompleteMode: true,
         menuItemLimit: mentionDropdownFetchLimit,
+        menuShowMinLength: 2,
       },
     ],
   });
 }
 
+let tippyInstance = tippy('[data-tippy-content]');
+
+export function setupTippy() {
+  tippyInstance.forEach(e => e.destroy());
+  tippyInstance = tippy('[data-tippy-content]', {
+    delay: [500, 0],
+    // Display on "long press"
+    touch: ['hold', 500],
+  });
+}
+
 function userSearch(text: string, cb: any) {
   if (text) {
     let form: SearchForm = {
@@ -613,11 +681,13 @@ export function createPostLikeFindRes(data: PostResponse, posts: Array<Post>) {
 }
 
 export function createPostLikeRes(data: PostResponse, post: Post) {
-  post.score = data.post.score;
-  post.upvotes = data.post.upvotes;
-  post.downvotes = data.post.downvotes;
-  if (data.post.my_vote !== null) {
-    post.my_vote = data.post.my_vote;
+  if (post) {
+    post.score = data.post.score;
+    post.upvotes = data.post.upvotes;
+    post.downvotes = data.post.downvotes;
+    if (data.post.my_vote !== null) {
+      post.my_vote = data.post.my_vote;
+    }
   }
 }
 
@@ -629,22 +699,24 @@ export function editPostFindRes(data: PostResponse, posts: Array<Post>) {
 }
 
 export function editPostRes(data: PostResponse, post: Post) {
-  post.url = data.post.url;
-  post.name = data.post.name;
-  post.nsfw = data.post.nsfw;
+  if (post) {
+    post.url = data.post.url;
+    post.name = data.post.name;
+    post.nsfw = data.post.nsfw;
+  }
 }
 
 export function commentsToFlatNodes(
   comments: Array<Comment>
-): Array<CommentNode> {
-  let nodes: Array<CommentNode> = [];
+): Array<CommentNodeI> {
+  let nodes: Array<CommentNodeI> = [];
   for (let comment of comments) {
     nodes.push({ comment: comment });
   }
   return nodes;
 }
 
-export function commentSort(tree: Array<CommentNode>, sort: CommentSortType) {
+export function commentSort(tree: Array<CommentNodeI>, sort: CommentSortType) {
   // First, put removed and deleted comments at the bottom, then do your other sorts
   if (sort == CommentSortType.Top) {
     tree.sort(
@@ -684,7 +756,7 @@ export function commentSort(tree: Array<CommentNode>, sort: CommentSortType) {
   }
 }
 
-export function commentSortSortType(tree: Array<CommentNode>, sort: SortType) {
+export function commentSortSortType(tree: Array<CommentNodeI>, sort: SortType) {
   commentSort(tree, convertCommentSortType(sort));
 }
 
@@ -706,7 +778,11 @@ function convertCommentSortType(sort: SortType): CommentSortType {
   }
 }
 
-export function postSort(posts: Array<Post>, sort: SortType) {
+export function postSort(
+  posts: Array<Post>,
+  sort: SortType,
+  communityType: boolean
+) {
   // First, put removed and deleted comments at the bottom, then do your other sorts
   if (
     sort == SortType.TopAll ||
@@ -717,13 +793,17 @@ export function postSort(posts: Array<Post>, sort: SortType) {
   ) {
     posts.sort(
       (a, b) =>
-        +a.removed - +b.removed || +a.deleted - +b.deleted || b.score - a.score
+        +a.removed - +b.removed ||
+        +a.deleted - +b.deleted ||
+        (communityType && +b.stickied - +a.stickied) ||
+        b.score - a.score
     );
   } else if (sort == SortType.New) {
     posts.sort(
       (a, b) =>
         +a.removed - +b.removed ||
         +a.deleted - +b.deleted ||
+        (communityType && +b.stickied - +a.stickied) ||
         b.published.localeCompare(a.published)
     );
   } else if (sort == SortType.Hot) {
@@ -731,7 +811,37 @@ export function postSort(posts: Array<Post>, sort: SortType) {
       (a, b) =>
         +a.removed - +b.removed ||
         +a.deleted - +b.deleted ||
+        (communityType && +b.stickied - +a.stickied) ||
         hotRankPost(b) - hotRankPost(a)
     );
   }
 }
+
+export const colorList: Array<string> = [
+  hsl(0),
+  hsl(100),
+  hsl(150),
+  hsl(200),
+  hsl(250),
+  hsl(300),
+];
+
+function hsl(num: number) {
+  return `hsla(${num}, 35%, 50%, 1)`;
+}
+
+function randomHsl() {
+  return `hsla(${Math.random() * 360}, 100%, 50%, 1)`;
+}
+
+export function previewLines(text: string, lines: number = 3): string {
+  // Use lines * 2 because markdown requires 2 lines
+  return text
+    .split('\n')
+    .slice(0, lines * 2)
+    .join('\n');
+}
+
+export function hostname(url: string): string {
+  return new URL(url).hostname;
+}