]> Untitled Git - lemmy-ui.git/commitdiff
Merge branch 'LemmyNet:main' into breakout-role-utils
authorAlec Armbruster <35377827+alectrocute@users.noreply.github.com>
Fri, 16 Jun 2023 22:57:20 +0000 (18:57 -0400)
committerGitHub <noreply@github.com>
Fri, 16 Jun 2023 22:57:20 +0000 (18:57 -0400)
54 files changed:
.github/CODEOWNERS
.github/ISSUE_TEMPLATE/BUG_REPORT.yml
.github/ISSUE_TEMPLATE/FEATURE_REQUEST.yml
Dockerfile
dev.dockerfile
package.json
src/assets/css/main.css
src/client/index.tsx
src/shared/components/app/navbar.tsx
src/shared/components/comment/comment-node.tsx
src/shared/components/common/html-tags.tsx
src/shared/components/common/markdown-textarea.tsx
src/shared/components/common/moment-time.tsx
src/shared/components/community/communities.tsx
src/shared/components/community/community.tsx
src/shared/components/community/sidebar.tsx
src/shared/components/home/home.tsx
src/shared/components/home/login.tsx
src/shared/components/home/signup.tsx
src/shared/components/modlog.tsx
src/shared/components/person/profile.tsx
src/shared/components/person/reports.tsx
src/shared/components/person/settings.tsx
src/shared/components/post/create-post.tsx
src/shared/components/post/post-form.tsx
src/shared/components/post/post-listing.tsx
src/shared/components/post/post.tsx
src/shared/components/search.tsx
src/shared/env.ts
src/shared/i18next.ts
src/shared/services/UserService.ts
src/shared/utils.ts
src/shared/utils/browser/can-share.ts [new file with mode: 0644]
src/shared/utils/browser/is-browser.ts [new file with mode: 0644]
src/shared/utils/browser/share.ts [new file with mode: 0644]
src/shared/utils/helpers/debounce.ts [new file with mode: 0644]
src/shared/utils/helpers/get-query-params.ts [new file with mode: 0644]
src/shared/utils/helpers/get-query-string.ts [new file with mode: 0644]
src/shared/utils/helpers/group-by.ts [new file with mode: 0644]
src/shared/utils/helpers/poll.ts [new file with mode: 0644]
src/shared/utils/helpers/sleep.ts [new file with mode: 0644]
src/shared/utils/roles/am-admin.ts [new file with mode: 0644]
src/shared/utils/roles/am-community-creator.ts [new file with mode: 0644]
src/shared/utils/roles/am-mod.ts [new file with mode: 0644]
src/shared/utils/roles/am-site-creator.ts [new file with mode: 0644]
src/shared/utils/roles/am-top-mod.ts [new file with mode: 0644]
src/shared/utils/roles/can-admin.ts [new file with mode: 0644]
src/shared/utils/roles/can-create-community.ts [new file with mode: 0644]
src/shared/utils/roles/can-mod.ts [new file with mode: 0644]
src/shared/utils/roles/is-admin.ts [new file with mode: 0644]
src/shared/utils/roles/is-banned.ts [new file with mode: 0644]
src/shared/utils/roles/is-mod.ts [new file with mode: 0644]
src/shared/utils/types/query-params.ts [new file with mode: 0644]
yarn.lock

index 76916e604aeda28ef62a8e3bbd4ab7f8d13a8e82..6df17d57c4f6b962bb01c55f4aadaed0f6756774 100644 (file)
@@ -1 +1 @@
-* @dessalines @SleeplessOne1917 @alectrocute
+* @dessalines @SleeplessOne1917
index ae2d4e51f0a74a9ffb498c83f10a0f8acced7bfc..2273a13823ab59f49a6b8bc70dbd5ffbf2d93e3a 100644 (file)
@@ -21,7 +21,7 @@ body:
         - label: Is this only a single bug? Do not put multiple bugs in one issue.
           required: true
         - label: Is this a server side (not related to the UI) issue? Use the [Lemmy back end](https://github.com/LemmyNet/lemmy) repo.
-          required: false
+          required: true
   - type: textarea
     id: summary
     attributes:
index 3c75050ab8a964b03a93030ba90821c505ef5de4..2f6f3fc1f9dae8cc7bc265ade72d3ef93f140605 100644 (file)
@@ -19,7 +19,7 @@ body:
         - label: Is this only a feature request? Do not put multiple feature requests in one issue.
           required: true
         - label: Is this a server side (not related to the UI) issue? Use the [Lemmy back end](https://github.com/LemmyNet/lemmy) repo.
-          required: false
+          required: true
   - type: textarea
     id: problem
     attributes:
index 2b36581d28d6ceebe2a891d35abe15fb9da410a3..3d6d6212d8dc4401373873cf3d9bb67cf5cfbecb 100644 (file)
@@ -1,4 +1,4 @@
-FROM node:20.2-alpine as builder\r
+FROM node:alpine as builder\r
 RUN apk update && apk add curl yarn python3 build-base gcc wget git --no-cache\r
 RUN curl -sf https://gobinaries.com/tj/node-prune | sh\r
 \r
index 3bfc10daed7f14b92853e908e5e16c488f45e1e3..0e925c0a90dfca99dceb40c7186bc82e79fb757d 100644 (file)
@@ -1,4 +1,4 @@
-FROM node:20.2-alpine as builder\r
+FROM node:alpine as builder\r
 RUN apk update && apk add curl yarn python3 build-base gcc wget git --no-cache\r
 \r
 WORKDIR /usr/src/app\r
index b7c48c79b070276ac94f7e6c5d536b9abaf393c1..2298d9e140c6e40705f39fd9caf0e5173bc698ae 100644 (file)
@@ -54,7 +54,7 @@
     "inferno-server": "^8.1.1",
     "isomorphic-cookie": "^1.2.4",
     "jwt-decode": "^3.1.2",
-    "lemmy-js-client": "0.18.0-rc.1",
+    "lemmy-js-client": "0.17.2-rc.24",
     "lodash": "^4.17.21",
     "markdown-it": "^13.0.1",
     "markdown-it-container": "^3.0.0",
index 82f8433e89d063fd4c514dc9e5a09664fdbece4d..e1adfc53e1fde6077b34e16b552c8a6604b73825 100644 (file)
   overflow-x: auto;
 }
 
+.md-div table {
+  border-collapse: collapse;
+  width: 100%;
+  margin-bottom: 1rem;
+  border: 1px solid var(--dark);
+}
+
+.md-div table th,
+.md-div table td {
+  padding: 0.3rem;
+  vertical-align: top;
+  border-top: 1px solid var(--dark);
+  border: 1px solid var(--dark);
+}
+
+.md-div table thead th {
+  vertical-align: bottom;
+  border-bottom: 2px solid var(--dark);
+}
+
+.md-div table tbody + tbody {
+  border-top: 2px solid var(--dark);
+}
+
 .vote-bar {
   margin-top: -6.5px;
 }
index 7b6b6b1cd662932736a83e4daca2b355d77f2196..860c07565dbad01861283893d209de7aad2099a4 100644 (file)
@@ -1,14 +1,13 @@
 import { hydrate } from "inferno-hydrate";
 import { Router } from "inferno-router";
 import { App } from "../shared/components/app/app";
+import { HistoryService } from "../shared/services/HistoryService";
 import { initializeSite } from "../shared/utils";
 
 import "bootstrap/js/dist/collapse";
 import "bootstrap/js/dist/dropdown";
-import { HistoryService } from "../shared/services/HistoryService";
 
-const site = window.isoData.site_res;
-initializeSite(site);
+initializeSite(window.isoData.site_res);
 
 const wrapper = (
   <Router history={HistoryService.history}>
@@ -17,6 +16,7 @@ const wrapper = (
 );
 
 const root = document.getElementById("root");
+
 if (root) {
   hydrate(wrapper, root);
 }
index c17837c9a03936ca121a05f02db9a172e91abd54..6a57659b0e564f0434195778282e3a6c5571e7df 100644 (file)
@@ -10,17 +10,17 @@ import { i18n } from "../../i18next";
 import { UserService } from "../../services";
 import { HttpService, RequestState } from "../../services/HttpService";
 import {
-  amAdmin,
-  canCreateCommunity,
   donateLemmyUrl,
-  isBrowser,
   myAuth,
   numToSI,
-  poll,
   showAvatars,
   toast,
   updateUnreadCountsInterval,
 } from "../../utils";
+import { isBrowser } from "../../utils/browser/is-browser";
+import { poll } from "../../utils/helpers/poll";
+import { amAdmin } from "../../utils/roles/am-admin";
+import { canCreateCommunity } from "../../utils/roles/can-create-community";
 import { Icon } from "../common/icon";
 import { PictrsImage } from "../common/pictrs-image";
 
index 806d2c2f8e78faec10909bd5ee27769e133b1fda..ebf7cb2e0ffc4c1fd548e7192e53961f8fb05357 100644 (file)
@@ -40,16 +40,10 @@ import {
 } from "../../interfaces";
 import { UserService } from "../../services";
 import {
-  amCommunityCreator,
-  canAdmin,
-  canMod,
   colorList,
   commentTreeMaxDepth,
   futureDaysToUnixTime,
   getCommentParentId,
-  isAdmin,
-  isBanned,
-  isMod,
   mdToHtml,
   mdToHtmlNoImages,
   myAuth,
@@ -59,6 +53,12 @@ import {
   setupTippy,
   showScores,
 } from "../../utils";
+import { amCommunityCreator } from "../../utils/roles/am-community-creator";
+import { canAdmin } from "../../utils/roles/can-admin";
+import { canMod } from "../../utils/roles/can-mod";
+import { isAdmin } from "../../utils/roles/is-admin";
+import { isBanned } from "../../utils/roles/is-banned";
+import { isMod } from "../../utils/roles/is-mod";
 import { Icon, PurgeWarning, Spinner } from "../common/icon";
 import { MomentTime } from "../common/moment-time";
 import { CommunityLink } from "../community/community-link";
index f32b0fc048a04687102fc740f08912c7fb0701c3..0e6cb2d03ad381528ed3f78447e0c0bc18d2b1bf 100644 (file)
@@ -2,8 +2,7 @@ import { htmlToText } from "html-to-text";
 import { Component } from "inferno";
 import { Helmet } from "inferno-helmet";
 import { httpExternalPath } from "../../env";
-import { i18n } from "../../i18next";
-import { md } from "../../utils";
+import { getLanguages, md } from "../../utils";
 
 interface HtmlTagsProps {
   title: string;
@@ -18,10 +17,11 @@ export class HtmlTags extends Component<HtmlTagsProps, any> {
     const url = httpExternalPath(this.props.path);
     const desc = this.props.description;
     const image = this.props.image;
+    const lang = getLanguages()[0];
 
     return (
       <Helmet title={this.props.title}>
-        <html lang={i18n.resolvedLanguage} />
+        <html lang={lang == "browser" ? "en" : lang} />
 
         {["title", "og:title", "twitter:title"].map(t => (
           <meta key={t} property={t} content={this.props.title} />
index a3a9cbde61d624eb370fb425447723ade8bb3444..36f6283d4b615cb485a918a6c5a33ca7e2745ce2 100644 (file)
@@ -7,7 +7,6 @@ import { HttpService, UserService } from "../../services";
 import {
   concurrentImageUpload,
   customEmojisLookup,
-  isBrowser,
   markdownFieldCharacterLimit,
   markdownHelpUrl,
   maxUploadImages,
@@ -20,12 +19,12 @@ import {
   setupTribute,
   toast,
 } from "../../utils";
+import { isBrowser } from "../../utils/browser/is-browser";
 import { EmojiPicker } from "./emoji-picker";
 import { Icon, Spinner } from "./icon";
 import { LanguageSelect } from "./language-select";
 import NavigationPrompt from "./navigation-prompt";
 import ProgressBar from "./progress-bar";
-
 interface MarkdownTextAreaProps {
   initialContent?: string;
   initialLanguageId?: number;
@@ -185,6 +184,53 @@ export class MarkdownTextArea extends Component<
         </div>
         <div className="row">
           <div className="col-sm-12 d-flex flex-wrap">
+            {this.props.buttonTitle && (
+              <button
+                type="submit"
+                className="btn btn-sm btn-secondary mr-2"
+                disabled={this.isDisabled}
+              >
+                {this.state.loading ? (
+                  <Spinner />
+                ) : (
+                  <span>{this.props.buttonTitle}</span>
+                )}
+              </button>
+            )}
+            {this.props.replyType && (
+              <button
+                type="button"
+                className="btn btn-sm btn-secondary mr-2"
+                onClick={linkEvent(this, this.handleReplyCancel)}
+              >
+                {i18n.t("cancel")}
+              </button>
+            )}
+            {this.state.content && (
+              <button
+                className={`btn btn-sm btn-secondary mr-2 ${
+                  this.state.previewMode && "active"
+                }`}
+                onClick={linkEvent(this, this.handlePreviewToggle)}
+              >
+                {this.state.previewMode ? i18n.t("edit") : i18n.t("preview")}
+              </button>
+            )}
+            {/* A flex expander */}
+            <div className="flex-grow-1"></div>
+
+            {this.props.showLanguage && (
+              <LanguageSelect
+                iconVersion
+                allLanguages={this.props.allLanguages}
+                selectedLanguageIds={
+                  languageId ? Array.of(languageId) : undefined
+                }
+                siteLanguages={this.props.siteLanguages}
+                onChange={this.handleLanguageChange}
+                disabled={this.isDisabled}
+              />
+            )}
             {this.getFormatButton("bold", this.handleInsertBold)}
             {this.getFormatButton("italic", this.handleInsertItalic)}
             {this.getFormatButton("link", this.handleInsertLink)}
@@ -237,57 +283,6 @@ export class MarkdownTextArea extends Component<
               <Icon icon="help-circle" classes="icon-inline" />
             </a>
           </div>
-
-          <div className="col-sm-12 d-flex align-items-center flex-wrap">
-            {this.props.showLanguage && (
-              <LanguageSelect
-                iconVersion
-                allLanguages={this.props.allLanguages}
-                selectedLanguageIds={
-                  languageId ? Array.of(languageId) : undefined
-                }
-                siteLanguages={this.props.siteLanguages}
-                onChange={this.handleLanguageChange}
-                disabled={this.isDisabled}
-              />
-            )}
-
-            {/* A flex expander */}
-            <div className="flex-grow-1"></div>
-
-            {this.props.buttonTitle && (
-              <button
-                type="submit"
-                className="btn btn-sm btn-secondary mr-2"
-                disabled={this.isDisabled}
-              >
-                {this.state.loading ? (
-                  <Spinner />
-                ) : (
-                  <span>{this.props.buttonTitle}</span>
-                )}
-              </button>
-            )}
-            {this.props.replyType && (
-              <button
-                type="button"
-                className="btn btn-sm btn-secondary mr-2"
-                onClick={linkEvent(this, this.handleReplyCancel)}
-              >
-                {i18n.t("cancel")}
-              </button>
-            )}
-            {this.state.content && (
-              <button
-                className={`btn btn-sm btn-secondary mr-2 ${
-                  this.state.previewMode && "active"
-                }`}
-                onClick={linkEvent(this, this.handlePreviewToggle)}
-              >
-                {this.state.previewMode ? i18n.t("edit") : i18n.t("preview")}
-              </button>
-            )}
-          </div>
         </div>
       </form>
     );
index 30c1682c9eaaf6d7980768b35036bfd0e8a060df..10714f5bb48fea50e3b18766ac608f3f44fb521b 100644 (file)
@@ -1,7 +1,7 @@
 import { Component } from "inferno";
 import moment from "moment";
 import { i18n } from "../../i18next";
-import { capitalizeFirstLetter } from "../../utils";
+import { capitalizeFirstLetter, getLanguages } from "../../utils";
 import { Icon } from "./icon";
 
 interface MomentTimeProps {
@@ -15,7 +15,9 @@ export class MomentTime extends Component<MomentTimeProps, any> {
   constructor(props: any, context: any) {
     super(props, context);
 
-    moment.locale([...i18n.languages]);
+    const lang = getLanguages();
+
+    moment.locale(lang);
   }
 
   createdAndModifiedTimes() {
index 623269439f8642444aad0fcaa6cb8cdb0649d02d..b98bf251ca76852e88c9908294bdc773a2db7143 100644 (file)
@@ -11,17 +11,17 @@ import { InitialFetchRequest } from "../../interfaces";
 import { FirstLoadService } from "../../services/FirstLoadService";
 import { HttpService, RequestState } from "../../services/HttpService";
 import {
-  QueryParams,
   editCommunity,
   getPageFromString,
-  getQueryParams,
-  getQueryString,
   myAuth,
   myAuthRequired,
   numToSI,
   setIsoData,
   showLocal,
 } from "../../utils";
+import { getQueryParams } from "../../utils/helpers/get-query-params";
+import { getQueryString } from "../../utils/helpers/get-query-string";
+import type { QueryParams } from "../../utils/types/query-params";
 import { HtmlTags } from "../common/html-tags";
 import { Spinner } from "../common/icon";
 import { ListingTypeSelect } from "../common/listing-type-select";
index f2d7ad729a8e492b2944205314ae6e47e88c8dca..58b330f448ed9cbb6eae89edf415077b47125ad9 100644 (file)
@@ -62,7 +62,6 @@ import { UserService } from "../../services";
 import { FirstLoadService } from "../../services/FirstLoadService";
 import { HttpService, RequestState } from "../../services/HttpService";
 import {
-  QueryParams,
   commentsToFlatNodes,
   communityRSSUrl,
   editComment,
@@ -74,8 +73,6 @@ import {
   getCommentParentId,
   getDataTypeString,
   getPageFromString,
-  getQueryParams,
-  getQueryString,
   myAuth,
   postToCommentSortType,
   relTags,
@@ -88,6 +85,9 @@ import {
   updateCommunityBlock,
   updatePersonBlock,
 } from "../../utils";
+import { getQueryParams } from "../../utils/helpers/get-query-params";
+import { getQueryString } from "../../utils/helpers/get-query-string";
+import type { QueryParams } from "../../utils/types/query-params";
 import { CommentNodes } from "../comment/comment-nodes";
 import { BannerIconHeader } from "../common/banner-icon-header";
 import { DataTypeSelect } from "../common/data-type-select";
@@ -99,7 +99,6 @@ import { Sidebar } from "../community/sidebar";
 import { SiteSidebar } from "../home/site-sidebar";
 import { PostListings } from "../post/post-listings";
 import { CommunityLink } from "./community-link";
-
 interface State {
   communityRes: RequestState<GetCommunityResponse>;
   postsRes: RequestState<GetPostsResponse>;
index f4c74528bd74a6b3ae57e0cb129d8903d46647b1..997fe11ad71dad96de7ecf9b2e893ee5069a1681 100644 (file)
@@ -17,15 +17,15 @@ import {
 import { i18n } from "../../i18next";
 import { UserService } from "../../services";
 import {
-  amAdmin,
-  amMod,
-  amTopMod,
   getUnixTime,
   hostname,
   mdToHtml,
   myAuthRequired,
   numToSI,
 } from "../../utils";
+import { amAdmin } from "../../utils/roles/am-admin";
+import { amMod } from "../../utils/roles/am-mod";
+import { amTopMod } from "../../utils/roles/am-top-mod";
 import { BannerIconHeader } from "../common/banner-icon-header";
 import { Icon, PurgeWarning, Spinner } from "../common/icon";
 import { CommunityForm } from "../community/community-form";
index 870eb76cfe4017f0674bc576517ef00210445c47..9f7c322f720ce07d01f0505312364f4f0576d07c 100644 (file)
@@ -57,7 +57,6 @@ import { UserService } from "../../services";
 import { FirstLoadService } from "../../services/FirstLoadService";
 import { HttpService, RequestState } from "../../services/HttpService";
 import {
-  canCreateCommunity,
   commentsToFlatNodes,
   editComment,
   editPost,
@@ -68,13 +67,10 @@ import {
   getCommentParentId,
   getDataTypeString,
   getPageFromString,
-  getQueryParams,
-  getQueryString,
   getRandomFromList,
   mdToHtml,
   myAuth,
   postToCommentSortType,
-  QueryParams,
   relTags,
   restoreScrollPosition,
   saveScrollPosition,
@@ -85,6 +81,10 @@ import {
   trendingFetchLimit,
   updatePersonBlock,
 } from "../../utils";
+import { getQueryParams } from "../../utils/helpers/get-query-params";
+import { getQueryString } from "../../utils/helpers/get-query-string";
+import { canCreateCommunity } from "../../utils/roles/can-create-community";
+import type { QueryParams } from "../../utils/types/query-params";
 import { CommentNodes } from "../comment/comment-nodes";
 import { DataTypeSelect } from "../common/data-type-select";
 import { HtmlTags } from "../common/html-tags";
index 841a3d2b2c59f32bc134183f0860eaaa576305f2..6a270899d6c5acf67e3030eba22bde83b4c1e29c 100644 (file)
@@ -3,7 +3,8 @@ import { GetSiteResponse, LoginResponse } from "lemmy-js-client";
 import { i18n } from "../../i18next";
 import { UserService } from "../../services";
 import { HttpService, RequestState } from "../../services/HttpService";
-import { isBrowser, myAuth, setIsoData, toast, validEmail } from "../../utils";
+import { myAuth, setIsoData, toast, validEmail } from "../../utils";
+import { isBrowser } from "../../utils/browser/is-browser";
 import { HtmlTags } from "../common/html-tags";
 import { Spinner } from "../common/icon";
 
index 16a3cc6d3eef61dbb4624a6acdefaf90429b3009..192393db98bee758eaab96cdc050ff13936d87df 100644 (file)
@@ -13,7 +13,6 @@ import { i18n } from "../../i18next";
 import { UserService } from "../../services";
 import { HttpService, RequestState } from "../../services/HttpService";
 import {
-  isBrowser,
   joinLemmyUrl,
   mdToHtml,
   myAuth,
@@ -21,6 +20,7 @@ import {
   toast,
   validEmail,
 } from "../../utils";
+import { isBrowser } from "../../utils/browser/is-browser";
 import { HtmlTags } from "../common/html-tags";
 import { Icon, Spinner } from "../common/icon";
 import { MarkdownTextArea } from "../common/markdown-textarea";
index d917f5f35ed675842e43169fa6da129b696335b6..99f15e501204b474886512b3cf2c0c5833684bf8 100644 (file)
@@ -33,21 +33,21 @@ import { FirstLoadService } from "../services/FirstLoadService";
 import { HttpService, RequestState } from "../services/HttpService";
 import {
   Choice,
-  QueryParams,
-  amAdmin,
-  amMod,
-  debounce,
   fetchLimit,
   fetchUsers,
   getIdFromString,
   getPageFromString,
-  getQueryParams,
-  getQueryString,
   getUpdatedSearchId,
   myAuth,
   personToChoice,
   setIsoData,
 } from "../utils";
+import { debounce } from "../utils/helpers/debounce";
+import { getQueryParams } from "../utils/helpers/get-query-params";
+import { getQueryString } from "../utils/helpers/get-query-string";
+import { amAdmin } from "../utils/roles/am-admin";
+import { amMod } from "../utils/roles/am-mod";
+import type { QueryParams } from "../utils/types/query-params";
 import { HtmlTags } from "./common/html-tags";
 import { Icon, Spinner } from "./common/icon";
 import { MomentTime } from "./common/moment-time";
index f80d5b907a2f7f1972dc0b62d1bebb51d06df1fe..c12114bc8f3d8e4fa2ccfb32dfdfb897b7dbad37 100644 (file)
@@ -53,8 +53,6 @@ import { UserService } from "../../services";
 import { FirstLoadService } from "../../services/FirstLoadService";
 import { HttpService, RequestState } from "../../services/HttpService";
 import {
-  QueryParams,
-  canMod,
   capitalizeFirstLetter,
   editComment,
   editPost,
@@ -65,10 +63,6 @@ import {
   futureDaysToUnixTime,
   getCommentParentId,
   getPageFromString,
-  getQueryParams,
-  getQueryString,
-  isAdmin,
-  isBanned,
   mdToHtml,
   myAuth,
   myAuthRequired,
@@ -81,6 +75,12 @@ import {
   toast,
   updatePersonBlock,
 } from "../../utils";
+import { getQueryParams } from "../../utils/helpers/get-query-params";
+import { getQueryString } from "../../utils/helpers/get-query-string";
+import { canMod } from "../../utils/roles/can-mod";
+import { isAdmin } from "../../utils/roles/is-admin";
+import { isBanned } from "../../utils/roles/is-banned";
+import type { QueryParams } from "../../utils/types/query-params";
 import { BannerIconHeader } from "../common/banner-icon-header";
 import { HtmlTags } from "../common/html-tags";
 import { Icon, Spinner } from "../common/icon";
index 29daa3ff6c92dbad9d621d8c2ed9be2e6945985c..187fe4c2e0e06d71548793e49df30728e62ec2ce 100644 (file)
@@ -23,7 +23,6 @@ import { HttpService, UserService } from "../../services";
 import { FirstLoadService } from "../../services/FirstLoadService";
 import { RequestState } from "../../services/HttpService";
 import {
-  amAdmin,
   editCommentReport,
   editPostReport,
   editPrivateMessageReport,
@@ -31,6 +30,7 @@ import {
   myAuthRequired,
   setIsoData,
 } from "../../utils";
+import { amAdmin } from "../../utils/roles/am-admin";
 import { CommentReport } from "../comment/comment-report";
 import { HtmlTags } from "../common/html-tags";
 import { Spinner } from "../common/icon";
index 56d57a7a56850778c7e1a65923d36b4b38e2e0e9..3c8e9fcdd743444b24ace411615d5aa7746d208c 100644 (file)
@@ -18,7 +18,6 @@ import {
   Choice,
   capitalizeFirstLetter,
   communityToChoice,
-  debounce,
   elementUrl,
   emDash,
   enableNsfw,
@@ -37,6 +36,7 @@ import {
   updateCommunityBlock,
   updatePersonBlock,
 } from "../../utils";
+import { debounce } from "../../utils/helpers/debounce";
 import { HtmlTags } from "../common/html-tags";
 import { Icon, Spinner } from "../common/icon";
 import { ImageUploadForm } from "../common/image-upload-form";
index baa7b45ff3f778f3815af9853f24787889e9722c..63ee390f8ad0d85e36b5a040bef25b80c16460a5 100644 (file)
@@ -16,14 +16,14 @@ import {
 } from "../../services/HttpService";
 import {
   Choice,
-  QueryParams,
   enableDownvotes,
   enableNsfw,
   getIdFromString,
-  getQueryParams,
   myAuth,
   setIsoData,
 } from "../../utils";
+import { getQueryParams } from "../../utils/helpers/get-query-params";
+import type { QueryParams } from "../../utils/types/query-params";
 import { HtmlTags } from "../common/html-tags";
 import { Spinner } from "../common/icon";
 import { PostForm } from "./post-form";
index 4640922d022e4b0e214421fc1c12b4fa8113ee3b..c21a6e2b8e7c189e654f232fa3b4662f8f6cdb26 100644 (file)
@@ -18,7 +18,6 @@ import {
   archiveTodayUrl,
   capitalizeFirstLetter,
   communityToChoice,
-  debounce,
   fetchCommunities,
   getIdFromString,
   ghostArchiveUrl,
@@ -33,6 +32,7 @@ import {
   validURL,
   webArchiveUrl,
 } from "../../utils";
+import { debounce } from "../../utils/helpers/debounce";
 import { Icon, Spinner } from "../common/icon";
 import { LanguageSelect } from "../common/language-select";
 import { MarkdownTextArea } from "../common/markdown-textarea";
index e170a3321b973c606617d70598162bee7391f8f8..e4d5f77267137e0f4034b36354d848079d62365e 100644 (file)
@@ -28,18 +28,9 @@ import { i18n } from "../../i18next";
 import { BanType, PostFormParams, PurgeType, VoteType } from "../../interfaces";
 import { UserService } from "../../services";
 import {
-  amAdmin,
-  amCommunityCreator,
-  amMod,
-  canAdmin,
-  canMod,
-  canShare,
   futureDaysToUnixTime,
   hostname,
-  isAdmin,
-  isBanned,
   isImage,
-  isMod,
   isVideo,
   mdNoImages,
   mdToHtml,
@@ -49,9 +40,18 @@ import {
   numToSI,
   relTags,
   setupTippy,
-  share,
   showScores,
 } from "../../utils";
+import { canShare } from "../../utils/browser/can-share";
+import { share } from "../../utils/browser/share";
+import { amAdmin } from "../../utils/roles/am-admin";
+import { amCommunityCreator } from "../../utils/roles/am-community-creator";
+import { amMod } from "../../utils/roles/am-mod";
+import { canAdmin } from "../../utils/roles/can-admin";
+import { canMod } from "../../utils/roles/can-mod";
+import { isAdmin } from "../../utils/roles/is-admin";
+import { isBanned } from "../../utils/roles/is-banned";
+import { isMod } from "../../utils/roles/is-mod";
 import { Icon, PurgeWarning, Spinner } from "../common/icon";
 import { MomentTime } from "../common/moment-time";
 import { PictrsImage } from "../common/pictrs-image";
index 25fd1b3f18215d58aba3aa1dfb9600f43346de9e..1c4b6816baaef582a17c1253e2aa172331ba3076 100644 (file)
@@ -64,7 +64,6 @@ import {
   buildCommentsTree,
   commentsToFlatNodes,
   commentTreeMaxDepth,
-  debounce,
   editComment,
   editWith,
   enableDownvotes,
@@ -73,7 +72,6 @@ import {
   getCommentParentId,
   getDepthFromComment,
   getIdFromProps,
-  isBrowser,
   isImage,
   myAuth,
   restoreScrollPosition,
@@ -84,6 +82,8 @@ import {
   updateCommunityBlock,
   updatePersonBlock,
 } from "../../utils";
+import { isBrowser } from "../../utils/browser/is-browser";
+import { debounce } from "../../utils/helpers/debounce";
 import { CommentForm } from "../comment/comment-form";
 import { CommentNodes } from "../comment/comment-nodes";
 import { HtmlTags } from "../common/html-tags";
index 8097dbde433b7ac7ef3811e47cc44cd6d4ffe76b..d32e408755de63e2f6b23f98c18a677e4d927b4a 100644 (file)
@@ -26,11 +26,9 @@ import { FirstLoadService } from "../services/FirstLoadService";
 import { HttpService, RequestState } from "../services/HttpService";
 import {
   Choice,
-  QueryParams,
   capitalizeFirstLetter,
   commentsToFlatNodes,
   communityToChoice,
-  debounce,
   enableDownvotes,
   enableNsfw,
   fetchCommunities,
@@ -38,8 +36,6 @@ import {
   fetchUsers,
   getIdFromString,
   getPageFromString,
-  getQueryParams,
-  getQueryString,
   getUpdatedSearchId,
   myAuth,
   numToSI,
@@ -49,6 +45,10 @@ import {
   setIsoData,
   showLocal,
 } from "../utils";
+import { debounce } from "../utils/helpers/debounce";
+import { getQueryParams } from "../utils/helpers/get-query-params";
+import { getQueryString } from "../utils/helpers/get-query-string";
+import type { QueryParams } from "../utils/types/query-params";
 import { CommentNodes } from "./comment/comment-nodes";
 import { HtmlTags } from "./common/html-tags";
 import { Spinner } from "./common/icon";
index 576c6c58e916f9d9274bd40200555a9892a8b19c..969f8761241d22e6d80141e4ff133a31434bb7aa 100644 (file)
@@ -1,4 +1,4 @@
-import { isBrowser } from "./utils";
+import { isBrowser } from "./utils/browser/is-browser";
 
 const testHost = "0.0.0.0:8536";
 
index 47ca6501542b536b0a2eead58434f2c1f59eda4f..eaedbbf817b4fada361b862b4c7d7c33c26b3083 100644 (file)
@@ -1,5 +1,4 @@
 import i18next, { i18nTyped, Resource } from "i18next";
-import { UserService } from "./services";
 import { ar } from "./translations/ar";
 import { bg } from "./translations/bg";
 import { ca } from "./translations/ca";
@@ -31,7 +30,7 @@ import { sv } from "./translations/sv";
 import { vi } from "./translations/vi";
 import { zh } from "./translations/zh";
 import { zh_Hant } from "./translations/zh_Hant";
-import { isBrowser } from "./utils";
+import { getLanguages } from "./utils";
 
 export const languages = [
   { resource: ar, code: "ar", name: "العربية" },
@@ -74,31 +73,12 @@ function format(value: any, format: any): any {
   return format === "uppercase" ? value.toUpperCase() : value;
 }
 
-class LanguageDetector {
-  static readonly type = "languageDetector";
-
-  detect() {
-    const langs: string[] = [];
-
-    const myLang =
-      UserService.Instance.myUserInfo?.local_user_view.local_user
-        .interface_language ?? "browser";
-
-    if (myLang !== "browser") langs.push(myLang);
-
-    if (isBrowser()) langs.push(...navigator.languages);
-
-    return langs;
-  }
-}
-
-i18next.use(LanguageDetector).init({
+i18next.init({
   debug: false,
   compatibilityJSON: "v3",
-  supportedLngs: languages.map(l => l.code),
-  nonExplicitSupportedLngs: true,
   // load: 'languageOnly',
   // initImmediate: false,
+  lng: getLanguages()[0],
   fallbackLng: "en",
   resources,
   interpolation: { format },
index 57c8aecf710c4717f58de4b3b1adeffe84957adb..8f553aba2395aa1c57c8985c225a36b6ce6240a3 100644 (file)
@@ -4,7 +4,8 @@ import jwt_decode from "jwt-decode";
 import { LoginResponse, MyUserInfo } from "lemmy-js-client";
 import { isHttps } from "../env";
 import { i18n } from "../i18next";
-import { isAuthPath, isBrowser, toast } from "../utils";
+import { isAuthPath, toast } from "../utils";
+import { isBrowser } from "../utils/browser/is-browser";
 
 interface Claims {
   sub: number;
index df7673a47b6a1e8e860a41b764bf70c58745b464..c0caad88a385d10e3996b9248888d6efa19430dd 100644 (file)
@@ -9,7 +9,6 @@ import {
   CommentReportView,
   CommentSortType,
   CommentView,
-  CommunityModeratorView,
   CommunityView,
   CustomEmojiView,
   GetSiteMetadata,
@@ -17,7 +16,6 @@ import {
   Language,
   LemmyHttp,
   MyUserInfo,
-  Person,
   PersonMentionView,
   PersonView,
   PostReportView,
@@ -42,9 +40,12 @@ import moment from "moment";
 import tippy from "tippy.js";
 import Toastify from "toastify-js";
 import { getHttpBase } from "./env";
-import { i18n } from "./i18next";
+import { i18n, languages } from "./i18next";
 import { CommentNodeI, DataType, IsoData, VoteType } from "./interfaces";
 import { HttpService, UserService } from "./services";
+import { isBrowser } from "./utils/browser/is-browser";
+import { debounce } from "./utils/helpers/debounce";
+import { groupBy } from "./utils/helpers/group-by";
 
 let Tribute: any;
 if (isBrowser()) {
@@ -228,95 +229,8 @@ export function futureDaysToUnixTime(days?: number): number | undefined {
     : undefined;
 }
 
-export function canMod(
-  creator_id: number,
-  mods?: CommunityModeratorView[],
-  admins?: PersonView[],
-  myUserInfo = UserService.Instance.myUserInfo,
-  onSelf = false
-): boolean {
-  // You can do moderator actions only on the mods added after you.
-  let adminsThenMods =
-    admins
-      ?.map(a => a.person.id)
-      .concat(mods?.map(m => m.moderator.id) ?? []) ?? [];
-
-  if (myUserInfo) {
-    const myIndex = adminsThenMods.findIndex(
-      id => id == myUserInfo.local_user_view.person.id
-    );
-    if (myIndex == -1) {
-      return false;
-    } else {
-      // onSelf +1 on mod actions not for yourself, IE ban, remove, etc
-      adminsThenMods = adminsThenMods.slice(0, myIndex + (onSelf ? 0 : 1));
-      return !adminsThenMods.includes(creator_id);
-    }
-  } else {
-    return false;
-  }
-}
-
-export function canAdmin(
-  creatorId: number,
-  admins?: PersonView[],
-  myUserInfo = UserService.Instance.myUserInfo,
-  onSelf = false
-): boolean {
-  return canMod(creatorId, undefined, admins, myUserInfo, onSelf);
-}
-
-export function isMod(
-  creatorId: number,
-  mods?: CommunityModeratorView[]
-): boolean {
-  return mods?.map(m => m.moderator.id).includes(creatorId) ?? false;
-}
-
-export function amMod(
-  mods?: CommunityModeratorView[],
-  myUserInfo = UserService.Instance.myUserInfo
-): boolean {
-  return myUserInfo ? isMod(myUserInfo.local_user_view.person.id, mods) : false;
-}
-
-export function isAdmin(creatorId: number, admins?: PersonView[]): boolean {
-  return admins?.map(a => a.person.id).includes(creatorId) ?? false;
-}
-
-export function amAdmin(myUserInfo = UserService.Instance.myUserInfo): boolean {
-  return myUserInfo?.local_user_view.person.admin ?? false;
-}
-
-export function amCommunityCreator(
-  creator_id: number,
-  mods?: CommunityModeratorView[],
-  myUserInfo = UserService.Instance.myUserInfo
-): boolean {
-  const myId = myUserInfo?.local_user_view.person.id;
-  // Don't allow mod actions on yourself
-  return myId == mods?.at(0)?.moderator.id && myId != creator_id;
-}
-
-export function amSiteCreator(
-  creator_id: number,
-  admins?: PersonView[],
-  myUserInfo = UserService.Instance.myUserInfo
-): boolean {
-  const myId = myUserInfo?.local_user_view.person.id;
-  return myId == admins?.at(0)?.person.id && myId != creator_id;
-}
-
-export function amTopMod(
-  mods: CommunityModeratorView[],
-  myUserInfo = UserService.Instance.myUserInfo
-): boolean {
-  return mods.at(0)?.moderator.id == myUserInfo?.local_user_view.person.id;
-}
-
 const imageRegex = /(http)?s?:?(\/\/[^"']*\.(?:jpg|jpeg|gif|png|svg|webp))/;
 const videoRegex = /(http)?s?:?(\/\/[^"']*\.(?:mp4|webm))/;
-const tldRegex = /([a-z0-9]+\.)*[a-z0-9]+\.[a-z]+/;
 
 export function isImage(url: string) {
   return imageRegex.test(url);
@@ -330,10 +244,6 @@ export function validURL(str: string) {
   return !!new URL(str);
 }
 
-export function validInstanceTLD(str: string) {
-  return tldRegex.test(str);
-}
-
 export function communityRSSUrl(actorId: string, sort: string): string {
   const url = new URL(actorId);
   return `${url.origin}/feeds${url.pathname}.xml?sort=${sort}`;
@@ -359,49 +269,29 @@ export function getDataTypeString(dt: DataType) {
   return dt === DataType.Post ? "Post" : "Comment";
 }
 
-export function debounce<T extends any[], R>(
-  func: (...e: T) => R,
-  wait = 1000,
-  immediate = false
-) {
-  // 'private' variable for instance
-  // The returned function will be able to reference this due to closure.
-  // Each call to the returned function will share this common timer.
-  let timeout: NodeJS.Timeout | null;
-
-  // Calling debounce returns a new anonymous function
-  return function () {
-    // reference the context and args for the setTimeout function
-    const args = arguments;
-
-    // Should the function be called now? If immediate is true
-    //   and not already in a timeout then the answer is: Yes
-    const callNow = immediate && !timeout;
-
-    // This is the basic debounce behavior where you can call this
-    //   function several times, but it will only execute once
-    //   [before or after imposing a delay].
-    //   Each time the returned function is called, the timer starts over.
-    clearTimeout(timeout ?? undefined);
-
-    // Set the new timeout
-    timeout = setTimeout(function () {
-      // Inside the timeout function, clear the timeout variable
-      // which will let the next execution run when in 'immediate' mode
-      timeout = null;
-
-      // Check if the function already ran with the immediate flag
-      if (!immediate) {
-        // Call the original function with apply
-        // apply lets you define the 'this' object as well as the arguments
-        //    (both captured before setTimeout)
-        func.apply(this, args);
-      }
-    }, wait);
+export function getLanguages(
+  override?: string,
+  myUserInfo = UserService.Instance.myUserInfo
+): string[] {
+  const myLang = myUserInfo?.local_user_view.local_user.interface_language;
+  const lang = override || myLang || "browser";
 
-    // Immediate mode and no wait timer? Execute the function..
-    if (callNow) func.apply(this, args);
-  } as (...e: T) => R;
+  if (lang == "browser" && isBrowser()) {
+    return getBrowserLanguages();
+  } else {
+    return [lang];
+  }
+}
+
+function getBrowserLanguages(): string[] {
+  // Intersect lemmy's langs, with the browser langs
+  const langs = languages ? languages.map(l => l.code) : ["en"];
+
+  // NOTE, mobile browsers seem to be missing this list, so append en
+  const allowedLangs = navigator.languages
+    .concat("en")
+    .filter(v => langs.includes(v));
+  return allowedLangs;
 }
 
 export async function fetchThemeList(): Promise<string[]> {
@@ -719,7 +609,7 @@ function setupMarkdown() {
       defs: emojiDefs,
     })
     .disable("image");
-  const defaultRenderer = md.renderer.rules.image;
+  var defaultRenderer = md.renderer.rules.image;
   md.renderer.rules.image = function (
     tokens: Token[],
     idx: number,
@@ -738,9 +628,6 @@ function setupMarkdown() {
     const alt_text = item.content;
     return `<img class="icon icon-emoji" src="${src}" title="${title}" alt="${alt_text}"/>`;
   };
-  md.renderer.rules.table_open = function () {
-    return '<table class="table">';
-  };
 }
 
 export function getEmojiMart(
@@ -1141,10 +1028,6 @@ export function siteBannerCss(banner: string): string {
     `;
 }
 
-export function isBrowser() {
-  return typeof window !== "undefined";
-}
-
 export function setIsoData(context: any): IsoData {
   // If its the browser, you need to deserialize the data from the window
   if (isBrowser()) {
@@ -1256,7 +1139,7 @@ export function personSelectName({
 
 export function initializeSite(site?: GetSiteResponse) {
   UserService.Instance.myUserInfo = site?.my_user;
-  i18n.changeLanguage();
+  i18n.changeLanguage(getLanguages()[0]);
   if (site) {
     setupEmojiDataModel(site.custom_emojis ?? []);
   }
@@ -1274,21 +1157,6 @@ export function numToSI(value: number): string {
   return SHORTNUM_SI_FORMAT.format(value);
 }
 
-export function isBanned(ps: Person): boolean {
-  const expires = ps.ban_expires;
-  // Add Z to convert from UTC date
-  // TODO this check probably isn't necessary anymore
-  if (expires) {
-    if (ps.banned && new Date(expires + "Z") > new Date()) {
-      return true;
-    } else {
-      return false;
-    }
-  } else {
-    return ps.banned;
-  }
-}
-
 export function myAuth(): string | undefined {
   return UserService.Instance.auth();
 }
@@ -1320,15 +1188,6 @@ export function postToCommentSortType(sort: SortType): CommentSortType {
   }
 }
 
-export function canCreateCommunity(
-  siteRes: GetSiteResponse,
-  myUserInfo = UserService.Instance.myUserInfo
-): boolean {
-  const adminOnly = siteRes.site_view.local_site.community_creation_admin_only;
-  // TODO: Make this check if user is logged on as well
-  return !adminOnly || amAdmin(myUserInfo);
-}
-
 export function isPostBlocked(
   pv: PostView,
   myUserInfo: MyUserInfo | undefined = UserService.Instance.myUserInfo
@@ -1409,64 +1268,12 @@ interface EmojiMartSkin {
   src: string;
 }
 
-const groupBy = <T>(
-  array: T[],
-  predicate: (value: T, index: number, array: T[]) => string
-) =>
-  array.reduce((acc, value, index, array) => {
-    (acc[predicate(value, index, array)] ||= []).push(value);
-    return acc;
-  }, {} as { [key: string]: T[] });
-
-export type QueryParams<T extends Record<string, any>> = {
-  [key in keyof T]?: string;
-};
-
-export function getQueryParams<T extends Record<string, any>>(processors: {
-  [K in keyof T]: (param: string) => T[K];
-}): T {
-  if (isBrowser()) {
-    const searchParams = new URLSearchParams(window.location.search);
-
-    return Array.from(Object.entries(processors)).reduce(
-      (acc, [key, process]) => ({
-        ...acc,
-        [key]: process(searchParams.get(key)),
-      }),
-      {} as T
-    );
-  }
-
-  return {} as T;
-}
-
-export function getQueryString<T extends Record<string, string | undefined>>(
-  obj: T
-) {
-  return Object.entries(obj)
-    .filter(([, val]) => val !== undefined && val !== null)
-    .reduce(
-      (acc, [key, val], index) => `${acc}${index > 0 ? "&" : ""}${key}=${val}`,
-      "?"
-    );
-}
-
 export function isAuthPath(pathname: string) {
   return /create_.*|inbox|settings|admin|reports|registration_applications/g.test(
     pathname
   );
 }
 
-export function canShare() {
-  return isBrowser() && !!navigator.canShare;
-}
-
-export function share(shareData: ShareData) {
-  if (isBrowser()) {
-    navigator.share(shareData);
-  }
-}
-
 export function newVote(voteType: VoteType, myVote?: number): number {
   if (voteType == VoteType.Upvote) {
     return myVote == 1 ? 0 : 1;
@@ -1474,18 +1281,3 @@ export function newVote(voteType: VoteType, myVote?: number): number {
     return myVote == -1 ? 0 : -1;
   }
 }
-
-function sleep(millis: number): Promise<void> {
-  return new Promise(resolve => setTimeout(resolve, millis));
-}
-
-/**
- * Polls / repeatedly runs a promise, every X milliseconds
- */
-export async function poll(promiseFn: any, millis: number) {
-  if (window.document.visibilityState !== "hidden") {
-    await promiseFn();
-  }
-  await sleep(millis);
-  return poll(promiseFn, millis);
-}
diff --git a/src/shared/utils/browser/can-share.ts b/src/shared/utils/browser/can-share.ts
new file mode 100644 (file)
index 0000000..bec7e80
--- /dev/null
@@ -0,0 +1,5 @@
+import { isBrowser } from "./is-browser";
+
+export function canShare() {
+  return isBrowser() && !!navigator.canShare;
+}
diff --git a/src/shared/utils/browser/is-browser.ts b/src/shared/utils/browser/is-browser.ts
new file mode 100644 (file)
index 0000000..4139b25
--- /dev/null
@@ -0,0 +1,3 @@
+export function isBrowser() {
+  return typeof window !== "undefined";
+}
diff --git a/src/shared/utils/browser/share.ts b/src/shared/utils/browser/share.ts
new file mode 100644 (file)
index 0000000..b1d1b5b
--- /dev/null
@@ -0,0 +1,7 @@
+import { isBrowser } from "./is-browser";
+
+export function share(shareData: ShareData) {
+  if (isBrowser()) {
+    navigator.share(shareData);
+  }
+}
diff --git a/src/shared/utils/helpers/debounce.ts b/src/shared/utils/helpers/debounce.ts
new file mode 100644 (file)
index 0000000..7a1e8b1
--- /dev/null
@@ -0,0 +1,44 @@
+export function debounce<T extends any[], R>(
+  func: (...e: T) => R,
+  wait = 1000,
+  immediate = false
+) {
+  // 'private' variable for instance
+  // The returned function will be able to reference this due to closure.
+  // Each call to the returned function will share this common timer.
+  let timeout: NodeJS.Timeout | null;
+
+  // Calling debounce returns a new anonymous function
+  return function () {
+    // reference the context and args for the setTimeout function
+    const args = arguments;
+
+    // Should the function be called now? If immediate is true
+    //   and not already in a timeout then the answer is: Yes
+    const callNow = immediate && !timeout;
+
+    // This is the basic debounce behavior where you can call this
+    //   function several times, but it will only execute once
+    //   [before or after imposing a delay].
+    //   Each time the returned function is called, the timer starts over.
+    clearTimeout(timeout ?? undefined);
+
+    // Set the new timeout
+    timeout = setTimeout(function () {
+      // Inside the timeout function, clear the timeout variable
+      // which will let the next execution run when in 'immediate' mode
+      timeout = null;
+
+      // Check if the function already ran with the immediate flag
+      if (!immediate) {
+        // Call the original function with apply
+        // apply lets you define the 'this' object as well as the arguments
+        //    (both captured before setTimeout)
+        func.apply(this, args);
+      }
+    }, wait);
+
+    // Immediate mode and no wait timer? Execute the function..
+    if (callNow) func.apply(this, args);
+  } as (...e: T) => R;
+}
diff --git a/src/shared/utils/helpers/get-query-params.ts b/src/shared/utils/helpers/get-query-params.ts
new file mode 100644 (file)
index 0000000..213d352
--- /dev/null
@@ -0,0 +1,19 @@
+import { isBrowser } from "../browser/is-browser";
+
+export function getQueryParams<T extends Record<string, any>>(processors: {
+  [K in keyof T]: (param: string) => T[K];
+}): T {
+  if (isBrowser()) {
+    const searchParams = new URLSearchParams(window.location.search);
+
+    return Array.from(Object.entries(processors)).reduce(
+      (acc, [key, process]) => ({
+        ...acc,
+        [key]: process(searchParams.get(key)),
+      }),
+      {} as T
+    );
+  }
+
+  return {} as T;
+}
diff --git a/src/shared/utils/helpers/get-query-string.ts b/src/shared/utils/helpers/get-query-string.ts
new file mode 100644 (file)
index 0000000..a66b5af
--- /dev/null
@@ -0,0 +1,10 @@
+export function getQueryString<T extends Record<string, string | undefined>>(
+  obj: T
+) {
+  return Object.entries(obj)
+    .filter(([, val]) => val !== undefined && val !== null)
+    .reduce(
+      (acc, [key, val], index) => `${acc}${index > 0 ? "&" : ""}${key}=${val}`,
+      "?"
+    );
+}
diff --git a/src/shared/utils/helpers/group-by.ts b/src/shared/utils/helpers/group-by.ts
new file mode 100644 (file)
index 0000000..4dd5d5d
--- /dev/null
@@ -0,0 +1,8 @@
+export const groupBy = <T>(
+  array: T[],
+  predicate: (value: T, index: number, array: T[]) => string
+) =>
+  array.reduce((acc, value, index, array) => {
+    (acc[predicate(value, index, array)] ||= []).push(value);
+    return acc;
+  }, {} as { [key: string]: T[] });
diff --git a/src/shared/utils/helpers/poll.ts b/src/shared/utils/helpers/poll.ts
new file mode 100644 (file)
index 0000000..055f17f
--- /dev/null
@@ -0,0 +1,12 @@
+import { sleep } from "./sleep";
+
+/**
+ * Polls / repeatedly runs a promise, every X milliseconds
+ */
+export async function poll(promiseFn: any, millis: number) {
+  if (window.document.visibilityState !== "hidden") {
+    await promiseFn();
+  }
+  await sleep(millis);
+  return poll(promiseFn, millis);
+}
diff --git a/src/shared/utils/helpers/sleep.ts b/src/shared/utils/helpers/sleep.ts
new file mode 100644 (file)
index 0000000..5b7c538
--- /dev/null
@@ -0,0 +1,3 @@
+export function sleep(millis: number): Promise<void> {
+  return new Promise(resolve => setTimeout(resolve, millis));
+}
diff --git a/src/shared/utils/roles/am-admin.ts b/src/shared/utils/roles/am-admin.ts
new file mode 100644 (file)
index 0000000..aadf52c
--- /dev/null
@@ -0,0 +1,5 @@
+import { UserService } from "../../services";
+
+export function amAdmin(myUserInfo = UserService.Instance.myUserInfo): boolean {
+  return myUserInfo?.local_user_view.person.admin ?? false;
+}
diff --git a/src/shared/utils/roles/am-community-creator.ts b/src/shared/utils/roles/am-community-creator.ts
new file mode 100644 (file)
index 0000000..20f9b1d
--- /dev/null
@@ -0,0 +1,12 @@
+import { CommunityModeratorView } from "lemmy-js-client";
+import { UserService } from "../../services";
+
+export function amCommunityCreator(
+  creator_id: number,
+  mods?: CommunityModeratorView[],
+  myUserInfo = UserService.Instance.myUserInfo
+): boolean {
+  const myId = myUserInfo?.local_user_view.person.id;
+  // Don't allow mod actions on yourself
+  return myId == mods?.at(0)?.moderator.id && myId != creator_id;
+}
diff --git a/src/shared/utils/roles/am-mod.ts b/src/shared/utils/roles/am-mod.ts
new file mode 100644 (file)
index 0000000..7b792b3
--- /dev/null
@@ -0,0 +1,10 @@
+import { CommunityModeratorView } from "lemmy-js-client";
+import { UserService } from "../../services";
+import { isMod } from "./is-mod";
+
+export function amMod(
+  mods?: CommunityModeratorView[],
+  myUserInfo = UserService.Instance.myUserInfo
+): boolean {
+  return myUserInfo ? isMod(myUserInfo.local_user_view.person.id, mods) : false;
+}
diff --git a/src/shared/utils/roles/am-site-creator.ts b/src/shared/utils/roles/am-site-creator.ts
new file mode 100644 (file)
index 0000000..323ac0a
--- /dev/null
@@ -0,0 +1,11 @@
+import { PersonView } from "lemmy-js-client";
+import { UserService } from "../../services";
+
+export function amSiteCreator(
+  creator_id: number,
+  admins?: PersonView[],
+  myUserInfo = UserService.Instance.myUserInfo
+): boolean {
+  const myId = myUserInfo?.local_user_view.person.id;
+  return myId == admins?.at(0)?.person.id && myId != creator_id;
+}
diff --git a/src/shared/utils/roles/am-top-mod.ts b/src/shared/utils/roles/am-top-mod.ts
new file mode 100644 (file)
index 0000000..4b942da
--- /dev/null
@@ -0,0 +1,9 @@
+import { CommunityModeratorView } from "lemmy-js-client";
+import { UserService } from "../../services";
+
+export function amTopMod(
+  mods: CommunityModeratorView[],
+  myUserInfo = UserService.Instance.myUserInfo
+): boolean {
+  return mods.at(0)?.moderator.id == myUserInfo?.local_user_view.person.id;
+}
diff --git a/src/shared/utils/roles/can-admin.ts b/src/shared/utils/roles/can-admin.ts
new file mode 100644 (file)
index 0000000..080c7ac
--- /dev/null
@@ -0,0 +1,12 @@
+import { PersonView } from "lemmy-js-client";
+import { UserService } from "../../services";
+import { canMod } from "./can-mod";
+
+export function canAdmin(
+  creatorId: number,
+  admins?: PersonView[],
+  myUserInfo = UserService.Instance.myUserInfo,
+  onSelf = false
+): boolean {
+  return canMod(creatorId, undefined, admins, myUserInfo, onSelf);
+}
diff --git a/src/shared/utils/roles/can-create-community.ts b/src/shared/utils/roles/can-create-community.ts
new file mode 100644 (file)
index 0000000..202290d
--- /dev/null
@@ -0,0 +1,12 @@
+import { GetSiteResponse } from "lemmy-js-client";
+import { UserService } from "../../services";
+import { amAdmin } from "./am-admin";
+
+export function canCreateCommunity(
+  siteRes: GetSiteResponse,
+  myUserInfo = UserService.Instance.myUserInfo
+): boolean {
+  const adminOnly = siteRes.site_view.local_site.community_creation_admin_only;
+  // TODO: Make this check if user is logged on as well
+  return !adminOnly || amAdmin(myUserInfo);
+}
diff --git a/src/shared/utils/roles/can-mod.ts b/src/shared/utils/roles/can-mod.ts
new file mode 100644 (file)
index 0000000..2892304
--- /dev/null
@@ -0,0 +1,31 @@
+import { CommunityModeratorView, PersonView } from "lemmy-js-client";
+import { UserService } from "../../services";
+
+export function canMod(
+  creator_id: number,
+  mods?: CommunityModeratorView[],
+  admins?: PersonView[],
+  myUserInfo = UserService.Instance.myUserInfo,
+  onSelf = false
+): boolean {
+  // You can do moderator actions only on the mods added after you.
+  let adminsThenMods =
+    admins
+      ?.map(a => a.person.id)
+      .concat(mods?.map(m => m.moderator.id) ?? []) ?? [];
+
+  if (myUserInfo) {
+    const myIndex = adminsThenMods.findIndex(
+      id => id == myUserInfo.local_user_view.person.id
+    );
+    if (myIndex == -1) {
+      return false;
+    } else {
+      // onSelf +1 on mod actions not for yourself, IE ban, remove, etc
+      adminsThenMods = adminsThenMods.slice(0, myIndex + (onSelf ? 0 : 1));
+      return !adminsThenMods.includes(creator_id);
+    }
+  } else {
+    return false;
+  }
+}
diff --git a/src/shared/utils/roles/is-admin.ts b/src/shared/utils/roles/is-admin.ts
new file mode 100644 (file)
index 0000000..fbf662b
--- /dev/null
@@ -0,0 +1,5 @@
+import { PersonView } from "lemmy-js-client";
+
+export function isAdmin(creatorId: number, admins?: PersonView[]): boolean {
+  return admins?.map(a => a.person.id).includes(creatorId) ?? false;
+}
diff --git a/src/shared/utils/roles/is-banned.ts b/src/shared/utils/roles/is-banned.ts
new file mode 100644 (file)
index 0000000..dd5ffe6
--- /dev/null
@@ -0,0 +1,16 @@
+import { Person } from "lemmy-js-client";
+
+export function isBanned(ps: Person): boolean {
+  const expires = ps.ban_expires;
+  // Add Z to convert from UTC date
+  // TODO this check probably isn't necessary anymore
+  if (expires) {
+    if (ps.banned && new Date(expires + "Z") > new Date()) {
+      return true;
+    } else {
+      return false;
+    }
+  } else {
+    return ps.banned;
+  }
+}
diff --git a/src/shared/utils/roles/is-mod.ts b/src/shared/utils/roles/is-mod.ts
new file mode 100644 (file)
index 0000000..8731107
--- /dev/null
@@ -0,0 +1,8 @@
+import { CommunityModeratorView } from "lemmy-js-client";
+
+export function isMod(
+  creatorId: number,
+  mods?: CommunityModeratorView[]
+): boolean {
+  return mods?.map(m => m.moderator.id).includes(creatorId) ?? false;
+}
diff --git a/src/shared/utils/types/query-params.ts b/src/shared/utils/types/query-params.ts
new file mode 100644 (file)
index 0000000..37705bd
--- /dev/null
@@ -0,0 +1,3 @@
+export type QueryParams<T extends Record<string, any>> = {
+  [key in keyof T]?: string;
+};
index 7cd6447438f39b8c4f0dcfbe67541aab44abf06d..f783f07f84ce5007655e700c23fcd2c67c295de5 100644 (file)
--- a/yarn.lock
+++ b/yarn.lock
@@ -5615,10 +5615,10 @@ leac@^0.6.0:
   resolved "https://registry.yarnpkg.com/leac/-/leac-0.6.0.tgz#dcf136e382e666bd2475f44a1096061b70dc0912"
   integrity sha512-y+SqErxb8h7nE/fiEX07jsbuhrpO9lL8eca7/Y1nuWV2moNlXhyd59iDGcRf6moVyDMbmTNzL40SUyrFU/yDpg==
 
-lemmy-js-client@0.18.0-rc.1:
-  version "0.18.0-rc.1"
-  resolved "https://registry.yarnpkg.com/lemmy-js-client/-/lemmy-js-client-0.18.0-rc.1.tgz#fd0c88810572d90413696011ebaed19e3b8162d8"
-  integrity sha512-lQe443Nr5UCSoY+IxmT7mBe0IRF6EAZ/4PJSRoPSL+U8A+egMMBPbuxnisHzLsC+eDOWRUIgOqZlwlaRnbmuig==
+lemmy-js-client@0.17.2-rc.24:
+  version "0.17.2-rc.24"
+  resolved "https://registry.yarnpkg.com/lemmy-js-client/-/lemmy-js-client-0.17.2-rc.24.tgz#3b09233a6d89286e559be2e840d81c0c549562ad"
+  integrity sha512-aSHz7UTcwnwnNd9poY8tEXP7RA9ieZm9MAfSljcbCNU5ds9CASXYNodmraUVJiqCmT4HWnj7IeVmBC9r7nTHnw==
   dependencies:
     cross-fetch "^3.1.5"
     form-data "^4.0.0"