Merge branch 'main' into patch-1

This commit is contained in:
n3oney 2023-06-21 00:37:48 +02:00
commit a7d91d3f2c
No known key found for this signature in database
GPG Key ID: C786693DE727850E
134 changed files with 40742 additions and 28371 deletions

View File

@ -3,11 +3,12 @@
"env": { "env": {
"browser": true "browser": true
}, },
"plugins": ["@typescript-eslint"], "plugins": ["@typescript-eslint", "jsx-a11y"],
"extends": [ "extends": [
"eslint:recommended", "eslint:recommended",
"plugin:@typescript-eslint/recommended", "plugin:@typescript-eslint/recommended",
"plugin:inferno/recommended" "plugin:inferno/recommended",
"plugin:jsx-a11y/recommended"
], ],
"parser": "@typescript-eslint/parser", "parser": "@typescript-eslint/parser",
"parserOptions": { "parserOptions": {
@ -20,6 +21,16 @@
"@typescript-eslint/explicit-module-boundary-types": 0, "@typescript-eslint/explicit-module-boundary-types": 0,
"@typescript-eslint/no-empty-function": 0, "@typescript-eslint/no-empty-function": 0,
"arrow-body-style": 0, "arrow-body-style": 0,
"jsx-a11y/alt-text": 1,
"jsx-a11y/anchor-is-valid": 1,
"jsx-a11y/aria-activedescendant-has-tabindex": 1,
"jsx-a11y/aria-role": 1,
"jsx-a11y/click-events-have-key-events": 1,
"jsx-a11y/iframe-has-title": 1,
"jsx-a11y/interactive-supports-focus": 1,
"jsx-a11y/no-redundant-roles": 1,
"jsx-a11y/no-static-element-interactions": 1,
"jsx-a11y/role-has-required-aria-props": 1,
"curly": 0, "curly": 0,
"eol-last": 0, "eol-last": 0,
"eqeqeq": 0, "eqeqeq": 0,

2
.github/CODEOWNERS vendored
View File

@ -1 +1 @@
* @dessalines @SleeplessOne1917 * @dessalines @SleeplessOne1917 @alectrocute

View File

@ -8,7 +8,7 @@ body:
value: | value: |
Found a bug? Please fill out the sections below. 👍 Found a bug? Please fill out the sections below. 👍
Thanks for taking the time to fill out this bug report! Thanks for taking the time to fill out this bug report!
For backend issues, use [lemmy](https://github.com/LemmyNet/lemmy) For backend issues, use [lemmy](https://github.com/LemmyNet/lemmy/issues/new/choose)
- type: checkboxes - type: checkboxes
attributes: attributes:
label: Requirements label: Requirements

View File

@ -1,16 +1,16 @@
name: "\U0001F680 Feature request" name: "\U0001F680 Feature request"
description: Suggest an idea for improving Lemmy description: Suggest an idea for improving Lemmy's UI
labels: ["enhancement"] labels: ["enhancement"]
body: body:
- type: markdown - type: markdown
attributes: attributes:
value: | value: |
Have a suggestion about Lemmy's UI? Have a suggestion about Lemmy's UI?
For backend issues, use [lemmy](https://github.com/LemmyNet/lemmy) For backend issues, use [lemmy](https://github.com/LemmyNet/lemmy/issues/new/choose)
- type: checkboxes - type: checkboxes
attributes: attributes:
label: Requirements label: Requirements
description: Before you create a bug report please do the following. description: Before you create a feature request please do the following.
options: options:
- label: Is this a feature request? For questions or discussions use https://lemmy.ml/c/lemmy_support - label: Is this a feature request? For questions or discussions use https://lemmy.ml/c/lemmy_support
required: true required: true

View File

@ -1,2 +1,3 @@
src/shared/translations src/shared/translations
lemmy-translations lemmy-translations
src/assets/css/themes/*.css

@ -1 +1 @@
Subproject commit f45ddff206adb52ab0ac7555bf14978edac5d2f2 Subproject commit 7fc71d0860bbe5c6d620ec27112350ffe5b9229c

View File

@ -1,6 +1,6 @@
{ {
"name": "lemmy-ui", "name": "lemmy-ui",
"version": "0.18.0-rc.1", "version": "0.18.0-rc.3",
"description": "An isomorphic UI for lemmy", "description": "An isomorphic UI for lemmy",
"repository": "https://github.com/LemmyNet/lemmy-ui", "repository": "https://github.com/LemmyNet/lemmy-ui",
"license": "AGPL-3.0", "license": "AGPL-3.0",
@ -12,14 +12,26 @@
"build:prod": "webpack --mode=production", "build:prod": "webpack --mode=production",
"clean": "yarn run rimraf dist", "clean": "yarn run rimraf dist",
"dev": "yarn start", "dev": "yarn start",
"lint": "node generate_translations.js && tsc --noEmit && eslint --report-unused-disable-directives --ext .js,.ts,.tsx \"src/**\" && prettier --check \"src/**/*.{ts,tsx,js,css,scss}\"", "lint": "yarn translations:generate && tsc --noEmit && eslint --report-unused-disable-directives --ext .js,.ts,.tsx \"src/**\" && prettier --check \"src/**/*.{ts,tsx,js,css,scss}\"",
"prepare": "husky install", "prepare": "husky install",
"start": "yarn build:dev --watch" "start": "yarn build:dev --watch",
"themes:build": "sass src/assets/css/themes/:src/assets/css/themes",
"themes:watch": "sass --watch src/assets/css/themes/:src/assets/css/themes",
"translations:generate": "node generate_translations.js",
"translations:init": "git submodule init && yarn translations:update",
"translations:update": "git submodule update --remote --recursive"
}, },
"lint-staged": { "lint-staged": {
"*.{ts,tsx,js}": ["prettier --write", "eslint --fix"], "*.{ts,tsx,js}": [
"*.{css, scss}": ["prettier --write"], "prettier --write",
"package.json": ["sortpack"] "eslint --fix"
],
"*.{css, scss}": [
"prettier --write"
],
"package.json": [
"sortpack"
]
}, },
"dependencies": { "dependencies": {
"@babel/plugin-proposal-decorators": "^7.21.0", "@babel/plugin-proposal-decorators": "^7.21.0",
@ -54,7 +66,7 @@
"inferno-server": "^8.1.1", "inferno-server": "^8.1.1",
"isomorphic-cookie": "^1.2.4", "isomorphic-cookie": "^1.2.4",
"jwt-decode": "^3.1.2", "jwt-decode": "^3.1.2",
"lemmy-js-client": "0.17.2-rc.24", "lemmy-js-client": "0.18.0-rc.1",
"lodash": "^4.17.21", "lodash": "^4.17.21",
"markdown-it": "^13.0.1", "markdown-it": "^13.0.1",
"markdown-it-container": "^3.0.0", "markdown-it-container": "^3.0.0",
@ -94,9 +106,9 @@
"@types/toastify-js": "^1.11.1", "@types/toastify-js": "^1.11.1",
"@typescript-eslint/eslint-plugin": "^5.59.5", "@typescript-eslint/eslint-plugin": "^5.59.5",
"@typescript-eslint/parser": "^5.59.5", "@typescript-eslint/parser": "^5.59.5",
"bootswatch": "^5.2.3",
"eslint": "^8.40.0", "eslint": "^8.40.0",
"eslint-plugin-inferno": "^7.32.2", "eslint-plugin-inferno": "^7.32.2",
"eslint-plugin-jsx-a11y": "^6.7.1",
"eslint-plugin-prettier": "^4.2.1", "eslint-plugin-prettier": "^4.2.1",
"husky": "^8.0.3", "husky": "^8.0.3",
"import-sort-style-module": "^6.0.0", "import-sort-style-module": "^6.0.0",
@ -109,6 +121,7 @@
"sortpack": "^2.3.4", "sortpack": "^2.3.4",
"style-loader": "^3.3.2", "style-loader": "^3.3.2",
"terser": "^5.17.3", "terser": "^5.17.3",
"tsconfig-paths-webpack-plugin": "^4.0.1",
"typescript": "^5.0.4", "typescript": "^5.0.4",
"webpack-dev-server": "4.15.0" "webpack-dev-server": "4.15.0"
}, },

View File

@ -21,7 +21,7 @@
} }
.upvote:hover { .upvote:hover {
color: var(--info); color: var(--bs-info);
} }
.upvote { .upvote {
@ -29,14 +29,14 @@
} }
.downvote:hover { .downvote:hover {
color: var(--danger); color: var(--bs-danger);
} }
.downvote { .downvote {
margin-top: -10px; margin-top: -10px;
} }
.custom-select { .form-select {
-moz-appearance: none; -moz-appearance: none;
} }
@ -46,7 +46,7 @@
} }
.md-div p:last-child { .md-div p:last-child {
margin-bottom: 0px; margin-bottom: 0;
} }
.md-div img { .md-div img {
@ -84,12 +84,8 @@
margin-top: -6.5px; margin-top: -6.5px;
} }
.post-title {
line-height: 1;
}
.post-title a:visited { .post-title a:visited {
color: var(--gray) !important; color: var(--bs-gray) !important;
} }
.icon { .icon {
@ -179,7 +175,7 @@
} }
blockquote { blockquote {
border-left: 2px solid var(--secondary); border-left: 2px solid var(--bs-secondary);
margin: 0.5em 5px; margin: 0.5em 5px;
padding: 0.1em 5px; padding: 0.1em 5px;
} }
@ -218,7 +214,7 @@ blockquote {
} }
hr { hr {
border-top: 1px solid var(--light); border-top: 1px solid var(--bs-light);
} }
.emoji { .emoji {
@ -270,6 +266,14 @@ hr {
-ms-transform: scale(1.2); -ms-transform: scale(1.2);
} }
/**
* TODO: Fix this in markup rather than this overly specific selector:
* https://getbootstrap.com/docs/5.3/components/buttons/#block-buttons
*/
.btn.d-block + .btn.d-block {
margin-top: 0.5rem;
}
.mini-overlay { .mini-overlay {
position: absolute; position: absolute;
top: 0; top: 0;
@ -367,16 +371,16 @@ br.big {
margin-top: 2px; margin-top: 2px;
padding: 0; padding: 0;
list-style: none; list-style: none;
background: var(--light); background: var(--bs-light);
} }
.tribute-container li { .tribute-container li {
padding: 5px 5px; padding: 5px;
cursor: pointer; cursor: pointer;
} }
.tribute-container li.highlight { .tribute-container li.highlight {
background: var(--primary); background: var(--bs-primary);
} }
.tribute-container li span { .tribute-container li span {
@ -410,13 +414,22 @@ br.big {
-webkit-line-clamp: 3; -webkit-line-clamp: 3;
-webkit-box-orient: vertical; -webkit-box-orient: vertical;
} }
.lang-select-action {
width: 100px;
}
.lang-select-action:focus { #emoji-picker {
width: auto;
}
em-emoji-picker {
width: 100%; width: 100%;
} }
.skip-link {
top: -40px;
transition: top 0.3s ease;
}
@media (prefers-reduced-motion: reduce) {
.skip-link {
transition: none;
}
}
.skip-link:focus {
top: 0;
}

View File

@ -0,0 +1,7 @@
@import "variables.darkly";
$primary: $blue;
$secondary: #444;
$light: $gray-800;
$link-color: $red;

View File

@ -1,35 +1,34 @@
@import "./variables";
// Colors
$white: #fff; $white: #fff;
$gray-100: #f8f9fa;
$gray-200: #ebebeb; $gray-200: #ebebeb;
$gray-300: #dee2e6; $gray-300: #dee2e6;
$gray-400: #ced4da;
$gray-500: #adb5bd; $gray-500: #adb5bd;
$gray-600: #888; $gray-600: #888;
$gray-700: #444; $gray-700: #444;
$gray-800: #303030; $gray-800: #303030;
$gray-900: #222; $gray-900: #222;
$black: #000;
$blue: #375a7f; $blue: #375a7f;
$indigo: #6610f2;
$purple: #6f42c1;
$pink: #e83e8c;
$red: #e74c3c; $red: #e74c3c;
$orange: #fd7e14;
$yellow: #f39c12; $yellow: #f39c12;
$green: #00bc8c; $green: #00bc8c;
$teal: #20c997;
$cyan: #3498db; $cyan: #3498db;
$primary: $blue;
$primary: $green;
$secondary: $gray-700; $secondary: $gray-700;
$success: $green; $success: $green;
$info: $cyan;
$warning: $yellow;
$danger: $red;
$dark: $gray-300; $dark: $gray-300;
$yiq-contrasted-threshold: 175;
$body-bg: $gray-900;
$body-color: $gray-300; $body-color: $gray-300;
$body-bg: $gray-900;
$link-color: $success; $link-color: $success;
$border-color: rgba($body-color, 0.25);
$mark-bg: #333;
$text-muted: $gray-600;
$yiq-contrasted-threshold: 175;
$font-family-sans-serif: "Lato", -apple-system, BlinkMacSystemFont, "Segoe UI", $font-family-sans-serif: "Lato", -apple-system, BlinkMacSystemFont, "Segoe UI",
Roboto, "Helvetica Neue", Arial, sans-serif, "Apple Color Emoji", Roboto, "Helvetica Neue", Arial, sans-serif, "Apple Color Emoji",
"Segoe UI Emoji", "Segoe UI Symbol"; "Segoe UI Emoji", "Segoe UI Symbol";
@ -37,28 +36,10 @@ $font-size-base: 0.9375rem;
$h1-font-size: 3rem; $h1-font-size: 3rem;
$h2-font-size: 2.5rem; $h2-font-size: 2.5rem;
$h3-font-size: 2rem; $h3-font-size: 2rem;
$text-muted: $gray-600;
$table-accent-bg: $gray-800; $card-cap-bg: $gray-700;
$table-border-color: $gray-700; $card-bg: $gray-800;
$input-border-color: $body-bg;
$input-group-addon-color: $gray-500;
$input-group-addon-bg: $gray-700;
$custom-file-color: $gray-500;
$custom-file-border-color: $body-bg;
$dropdown-bg: $gray-900;
$dropdown-border-color: $gray-700;
$dropdown-divider-bg: $gray-700;
$dropdown-link-color: $white;
$dropdown-link-hover-color: $white;
$dropdown-link-hover-bg: $primary;
$nav-link-padding-x: 2rem;
$nav-link-disabled-color: $gray-500;
$nav-tabs-border-color: $gray-700;
$nav-tabs-link-hover-border-color: $nav-tabs-border-color $nav-tabs-border-color
transparent;
$nav-tabs-link-active-color: $white;
$nav-tabs-link-active-border-color: $nav-tabs-border-color
$nav-tabs-border-color transparent;
$navbar-padding-y: 1rem; $navbar-padding-y: 1rem;
$navbar-dark-color: rgba($white, 0.6); $navbar-dark-color: rgba($white, 0.6);
$navbar-dark-hover-color: $white; $navbar-dark-hover-color: $white;
@ -66,6 +47,40 @@ $navbar-light-color: rgba($white, 0.6);
$navbar-light-hover-color: $white; $navbar-light-hover-color: $white;
$navbar-light-active-color: $white; $navbar-light-active-color: $white;
$navbar-light-toggler-border-color: rgba($gray-900, 0.1); $navbar-light-toggler-border-color: rgba($gray-900, 0.1);
$navbar-light-brand-color: $white;
$navbar-light-brand-hover-color: $navbar-light-brand-color;
$nav-link-padding-x: 2rem;
$nav-link-disabled-color: $gray-500;
$nav-tabs-border-color: $gray-700;
$nav-tabs-link-hover-border-color: $nav-tabs-border-color $nav-tabs-border-color
transparent;
$nav-tabs-link-active-color: $white;
$nav-tabs-link-active-border-color: $nav-tabs-border-color
$nav-tabs-border-color transparent;
$input-bg: $gray-700;
$input-color: $white;
$input-disabled-bg: darken($gray-700, 10%);
$input-border-color: $body-bg;
$input-group-addon-color: $gray-500;
$input-group-addon-bg: $gray-700;
$hr-border-color: rgba($body-color, 0.25);
$table-border-color: $gray-700;
$custom-file-color: $gray-500;
$custom-file-border-color: $body-bg;
$dropdown-bg: $gray-900;
$dropdown-border-color: $gray-700;
$dropdown-divider-bg: $gray-700;
$dropdown-link-color: $white;
$dropdown-link-hover-color: $white;
$dropdown-link-hover-bg: $primary;
$pagination-color: $white; $pagination-color: $white;
$pagination-bg: $success; $pagination-bg: $success;
$pagination-border-width: 0; $pagination-border-width: 0;
@ -78,9 +93,8 @@ $pagination-active-border-color: transparent;
$pagination-disabled-color: $white; $pagination-disabled-color: $white;
$pagination-disabled-bg: darken($success, 15%); $pagination-disabled-bg: darken($success, 15%);
$pagination-disabled-border-color: transparent; $pagination-disabled-border-color: transparent;
$jumbotron-bg: $gray-800; $jumbotron-bg: $gray-800;
$card-cap-bg: $gray-700;
$card-bg: $gray-800;
$popover-bg: $gray-800; $popover-bg: $gray-800;
$popover-header-bg: $gray-700; $popover-header-bg: $gray-700;
$toast-background-color: $gray-700; $toast-background-color: $gray-700;
@ -96,12 +110,6 @@ $breadcrumb-bg: $gray-700;
$close-color: $white; $close-color: $white;
$close-text-shadow: none; $close-text-shadow: none;
$pre-color: inherit; $pre-color: inherit;
$mark-bg: #333; $custom-select-bg: $gray-700;
$custom-select-bg: $secondary;
$custom-select-color: $white; $custom-select-color: $white;
$input-bg: $secondary;
$input-color: $white;
$input-disabled-bg: darken($secondary, 10%);
$light: $gray-800; $light: $gray-800;
$navbar-light-brand-color: $navbar-dark-active-color;
$navbar-light-brand-hover-color: $navbar-dark-active-color;

View File

@ -0,0 +1,4 @@
@import "variables.litely";
$secondary: #c80000;
$danger: darken($primary, 24%);

View File

@ -1,33 +1,52 @@
$white: #ffffff; @import "./variables";
$orange: #f1641e;
$cyan: #02bdc2; // Colors
$green: #00c853; $gray-100: #f8f9fa;
$secondary: $green; $gray-600: #6c757d;
$body-color: $gray-700; $gray-700: #495057;
$link-color: theme-color("primary"); $gray-800: #343a40;
$primary: $orange; $gray-900: #212529;
$black: #222;
$blue: #007bff;
$indigo: #6610f2;
$red: #d8486a; $red: #d8486a;
$orange: #f1641e;
$green: #00a846;
$cyan: #02bdc2;
$primary: $orange;
$secondary: $green;
$success: $indigo;
$info: $blue;
$danger: darken($primary, 25%);
$body-color: $gray-700;
$body-bg: #fff;
$link-color: $primary;
$border-color: rgba($body-color, 0.25);
$mark-bg: rgb(255, 252, 239);
$headings-color: $gray-700;
$font-family-sans-serif: -apple-system, BlinkMacSystemFont, "Droid Sans",
"Segoe UI", "Helvetica", Arial, sans-serif;
$font-weight-bold: 600;
$card-color: $gray-700;
$card-cap-color: $gray-700;
$card-bg: $gray-100;
$navbar-dark-toggler-border-color: rgba($black, 0.1);
$navbar-light-color: $gray-600;
$navbar-light-hover-color: $gray-900;
$navbar-light-active-color: $gray-900;
$form-feedback-valid-color: $info;
$input-btn-focus-color: rgba($primary, 0.75);
$border-radius: 0.5rem; $border-radius: 0.5rem;
$border-radius-lg: 0.5rem; $border-radius-lg: 0.5rem;
$border-radius-sm: 1rem; $border-radius-sm: 1rem;
$font-family-sans-serif: -apple-system, BlinkMacSystemFont, "Droid Sans",
"Segoe UI", "Helvetica", Arial, sans-serif;
$headings-color: $gray-700;
$input-btn-focus-color: rgba($component-active-bg, 0.75);
$form-feedback-valid-color: theme-color("info");
$navbar-light-color: $gray-600;
$black: #222222;
$navbar-dark-toggler-border-color: rgba($black, 0.1);
$navbar-light-active-color: $gray-900;
$card-color: $gray-700;
$card-cap-color: $gray-700;
$info: $blue;
$body-bg: #fff;
$success: $indigo;
$danger: darken($primary, 25%);
$navbar-light-hover-color: $gray-900;
$card-bg: $gray-100;
$border-color: $gray-700;
$mark-bg: rgb(255, 252, 239);
$font-weight-bold: 600;
$rounded-pill: 0.25rem; $rounded-pill: 0.25rem;
$hr-border-color: rgba($body-color, 0.25);

View File

@ -0,0 +1,6 @@
$link-decoration: none;
$min-contrast-ratio: 3;
$container-max-widths: (
lg: 1140px,
);

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,2 @@
@import "variables.darkly-red";
@import "../../../../node_modules/bootstrap/scss/bootstrap";

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,2 @@
@import "variables.darkly";
@import "../../../../node_modules/bootstrap/scss/bootstrap";

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,2 @@
@import "variables.litely-red";
@import "../../../../node_modules/bootstrap/scss/bootstrap";

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,2 @@
@import "variables.litely";
@import "../../../../node_modules/bootstrap/scss/bootstrap";

View File

@ -1,14 +1,13 @@
import { hydrate } from "inferno-hydrate"; import { hydrate } from "inferno-hydrate";
import { Router } from "inferno-router"; import { Router } from "inferno-router";
import { App } from "../shared/components/app/app"; import { App } from "../shared/components/app/app";
import { HistoryService } from "../shared/services/HistoryService";
import { initializeSite } from "../shared/utils"; import { initializeSite } from "../shared/utils";
import "bootstrap/js/dist/collapse"; import "bootstrap/js/dist/collapse";
import "bootstrap/js/dist/dropdown"; import "bootstrap/js/dist/dropdown";
import { HistoryService } from "../shared/services/HistoryService";
const site = window.isoData.site_res; initializeSite(window.isoData.site_res);
initializeSite(site);
const wrapper = ( const wrapper = (
<Router history={HistoryService.history}> <Router history={HistoryService.history}>
@ -17,6 +16,7 @@ const wrapper = (
); );
const root = document.getElementById("root"); const root = document.getElementById("root");
if (root) { if (root) {
hydrate(wrapper, root); hydrate(wrapper, root);
} }

View File

@ -0,0 +1,116 @@
import type { Request, Response } from "express";
import { StaticRouter, matchPath } from "inferno-router";
import { renderToString } from "inferno-server";
import IsomorphicCookie from "isomorphic-cookie";
import { GetSite, GetSiteResponse, LemmyHttp } from "lemmy-js-client";
import { App } from "../../shared/components/app/app";
import { getHttpBaseInternal } from "../../shared/env";
import {
InitialFetchRequest,
IsoDataOptionalSite,
RouteData,
} from "../../shared/interfaces";
import { routes } from "../../shared/routes";
import {
FailedRequestState,
wrapClient,
} from "../../shared/services/HttpService";
import { ErrorPageData, initializeSite, isAuthPath } from "../../shared/utils";
import { createSsrHtml } from "../utils/create-ssr-html";
import { getErrorPageData } from "../utils/get-error-page-data";
import { setForwardedHeaders } from "../utils/set-forwarded-headers";
export default async (req: Request, res: Response) => {
try {
const activeRoute = routes.find(route => matchPath(req.path, route));
let auth: string | undefined = IsomorphicCookie.load("jwt", req);
const getSiteForm: GetSite = { auth };
const headers = setForwardedHeaders(req.headers);
const client = wrapClient(new LemmyHttp(getHttpBaseInternal(), headers));
const { path, url, query } = req;
// Get site data first
// This bypasses errors, so that the client can hit the error on its own,
// in order to remove the jwt on the browser. Necessary for wrong jwts
let site: GetSiteResponse | undefined = undefined;
let routeData: RouteData = {};
let errorPageData: ErrorPageData | undefined = undefined;
let try_site = await client.getSite(getSiteForm);
if (try_site.state === "failed" && try_site.msg == "not_logged_in") {
console.error(
"Incorrect JWT token, skipping auth so frontend can remove jwt cookie"
);
getSiteForm.auth = undefined;
auth = undefined;
try_site = await client.getSite(getSiteForm);
}
if (!auth && isAuthPath(path)) {
return res.redirect("/login");
}
if (try_site.state === "success") {
site = try_site.data;
initializeSite(site);
if (path !== "/setup" && !site.site_view.local_site.site_setup) {
return res.redirect("/setup");
}
if (site && activeRoute?.fetchInitialData) {
const initialFetchReq: InitialFetchRequest = {
client,
auth,
path,
query,
site,
};
routeData = await activeRoute.fetchInitialData(initialFetchReq);
}
} else if (try_site.state === "failed") {
errorPageData = getErrorPageData(new Error(try_site.msg), site);
}
const error = Object.values(routeData).find(
res => res.state === "failed"
) as FailedRequestState | undefined;
// Redirect to the 404 if there's an API error
if (error) {
console.error(error.msg);
if (error.msg === "instance_is_private") {
return res.redirect(`/signup`);
} else {
errorPageData = getErrorPageData(new Error(error.msg), site);
}
}
const isoData: IsoDataOptionalSite = {
path,
site_res: site,
routeData,
errorPageData,
};
const wrapper = (
<StaticRouter location={url} context={isoData}>
<App />
</StaticRouter>
);
const root = renderToString(wrapper);
res.send(await createSsrHtml(root, isoData));
} catch (err) {
// If an error is caught here, the error page couldn't even be rendered
console.error(err);
res.statusCode = 500;
return res.send(
process.env.NODE_ENV === "development" ? err.message : "Server error"
);
}
};

View File

@ -0,0 +1,18 @@
import type { Response } from "express";
export default async ({ res }: { res: Response }) => {
res.setHeader("content-type", "text/plain; charset=utf-8");
res.send(`User-Agent: *
Disallow: /login
Disallow: /settings
Disallow: /create_community
Disallow: /create_post
Disallow: /create_private_message
Disallow: /inbox
Disallow: /setup
Disallow: /admin
Disallow: /password_change
Disallow: /search/
`);
};

View File

@ -0,0 +1,14 @@
import type { Response } from "express";
import path from "path";
export default async ({ res }: { res: Response }) => {
res
.setHeader("Content-Type", "application/javascript")
.sendFile(
path.resolve(
`./dist/service-worker${
process.env.NODE_ENV === "development" ? "-development" : ""
}.js`
)
);
};

View File

@ -0,0 +1,32 @@
import type { Request, Response } from "express";
import { existsSync } from "fs";
import path from "path";
const extraThemesFolder =
process.env["LEMMY_UI_EXTRA_THEMES_FOLDER"] || "./extra_themes";
export default async (req: Request, res: Response) => {
res.contentType("text/css");
const theme = req.params.name;
if (!theme.endsWith(".css")) {
res.statusCode = 400;
res.send("Theme must be a css file");
}
const customTheme = path.resolve(extraThemesFolder, theme);
if (existsSync(customTheme)) {
res.sendFile(customTheme);
} else {
const internalTheme = path.resolve(`./dist/assets/css/themes/${theme}`);
// If the theme doesn't exist, just send litely
if (existsSync(internalTheme)) {
res.sendFile(internalTheme);
} else {
res.sendFile(path.resolve("./dist/assets/css/themes/litely.css"));
}
}
};

View File

@ -0,0 +1,6 @@
import type { Response } from "express";
import { buildThemeList } from "../utils/build-themes-list";
export default async ({ res }: { res: Response }) => {
res.type("json").send(JSON.stringify(await buildThemeList()));
};

View File

@ -1,465 +1,38 @@
import express from "express"; import express from "express";
import { existsSync } from "fs";
import { readdir, readFile } from "fs/promises";
import { IncomingHttpHeaders } from "http";
import { Helmet } from "inferno-helmet";
import { matchPath, StaticRouter } from "inferno-router";
import { renderToString } from "inferno-server";
import IsomorphicCookie from "isomorphic-cookie";
import { GetSite, GetSiteResponse, LemmyHttp } from "lemmy-js-client";
import path from "path"; import path from "path";
import process from "process"; import process from "process";
import serialize from "serialize-javascript"; import CatchAllHandler from "./handlers/catch-all-handler";
import sharp from "sharp"; import RobotsHandler from "./handlers/robots-handler";
import { App } from "../shared/components/app/app"; import ServiceWorkerHandler from "./handlers/service-worker-handler";
import { getHttpBaseExternal, getHttpBaseInternal } from "../shared/env"; import ThemeHandler from "./handlers/theme-handler";
import { import ThemesListHandler from "./handlers/themes-list-handler";
ILemmyConfig, import setDefaultCsp from "./middleware/set-default-csp";
InitialFetchRequest,
IsoDataOptionalSite,
} from "../shared/interfaces";
import { routes } from "../shared/routes";
import { RequestState, wrapClient } from "../shared/services/HttpService";
import {
ErrorPageData,
favIconPngUrl,
favIconUrl,
initializeSite,
isAuthPath,
} from "../shared/utils";
const server = express(); const server = express();
const [hostname, port] = process.env["LEMMY_UI_HOST"] const [hostname, port] = process.env["LEMMY_UI_HOST"]
? process.env["LEMMY_UI_HOST"].split(":") ? process.env["LEMMY_UI_HOST"].split(":")
: ["0.0.0.0", "1234"]; : ["0.0.0.0", "1234"];
const extraThemesFolder =
process.env["LEMMY_UI_EXTRA_THEMES_FOLDER"] || "./extra_themes";
if (!process.env["LEMMY_UI_DISABLE_CSP"] && !process.env["LEMMY_UI_DEBUG"]) {
server.use(function (_req, res, next) {
res.setHeader(
"Content-Security-Policy",
`default-src 'self'; manifest-src *; connect-src *; img-src * data:; script-src 'self' 'unsafe-inline' 'unsafe-eval'; style-src 'self' 'unsafe-inline'; form-action 'self'; base-uri 'self'; frame-src *; media-src *`
);
next();
});
}
const customHtmlHeader = process.env["LEMMY_UI_CUSTOM_HTML_HEADER"] || "";
server.use(express.json()); server.use(express.json());
server.use(express.urlencoded({ extended: false })); server.use(express.urlencoded({ extended: false }));
server.use("/static", express.static(path.resolve("./dist"))); server.use("/static", express.static(path.resolve("./dist")));
const robotstxt = `User-Agent: * if (!process.env["LEMMY_UI_DISABLE_CSP"] && !process.env["LEMMY_UI_DEBUG"]) {
Disallow: /login server.use(setDefaultCsp);
Disallow: /settings
Disallow: /create_community
Disallow: /create_post
Disallow: /create_private_message
Disallow: /inbox
Disallow: /setup
Disallow: /admin
Disallow: /password_change
Disallow: /search/
`;
server.get("/service-worker.js", async (_req, res) => {
res.setHeader("Content-Type", "application/javascript");
res.sendFile(
path.resolve(
`./dist/service-worker${
process.env.NODE_ENV === "development" ? "-development" : ""
}.js`
)
);
});
server.get("/robots.txt", async (_req, res) => {
res.setHeader("content-type", "text/plain; charset=utf-8");
res.send(robotstxt);
});
server.get("/css/themes/:name", async (req, res) => {
res.contentType("text/css");
const theme = req.params.name;
if (!theme.endsWith(".css")) {
res.statusCode = 400;
res.send("Theme must be a css file");
}
const customTheme = path.resolve(`${extraThemesFolder}/${theme}`);
if (existsSync(customTheme)) {
res.sendFile(customTheme);
} else {
const internalTheme = path.resolve(`./dist/assets/css/themes/${theme}`);
// If the theme doesn't exist, just send litely
if (existsSync(internalTheme)) {
res.sendFile(internalTheme);
} else {
res.sendFile(path.resolve("./dist/assets/css/themes/litely.css"));
}
}
});
async function buildThemeList(): Promise<string[]> {
const themes = ["darkly", "darkly-red", "litely", "litely-red"];
if (existsSync(extraThemesFolder)) {
const dirThemes = await readdir(extraThemesFolder);
const cssThemes = dirThemes
.filter(d => d.endsWith(".css"))
.map(d => d.replace(".css", ""));
themes.push(...cssThemes);
}
return themes;
} }
server.get("/css/themelist", async (_req, res) => { server.get("/robots.txt", RobotsHandler);
res.type("json"); server.get("/service-worker.js", ServiceWorkerHandler);
res.send(JSON.stringify(await buildThemeList())); server.get("/css/themes/:name", ThemeHandler);
}); server.get("/css/themelist", ThemesListHandler);
server.get("/*", CatchAllHandler);
// server.use(cookieParser());
server.get("/*", async (req, res) => {
try {
const activeRoute = routes.find(route => matchPath(req.path, route));
let auth: string | undefined = IsomorphicCookie.load("jwt", req);
const getSiteForm: GetSite = { auth };
const headers = setForwardedHeaders(req.headers);
const client = wrapClient(new LemmyHttp(getHttpBaseInternal(), headers));
const { path, url, query } = req;
// Get site data first
// This bypasses errors, so that the client can hit the error on its own,
// in order to remove the jwt on the browser. Necessary for wrong jwts
let site: GetSiteResponse | undefined = undefined;
const routeData: RequestState<any>[] = [];
let errorPageData: ErrorPageData | undefined = undefined;
let try_site = await client.getSite(getSiteForm);
if (try_site.state === "failed" && try_site.msg == "not_logged_in") {
console.error(
"Incorrect JWT token, skipping auth so frontend can remove jwt cookie"
);
getSiteForm.auth = undefined;
auth = undefined;
try_site = await client.getSite(getSiteForm);
}
if (!auth && isAuthPath(path)) {
return res.redirect("/login");
}
if (try_site.state === "success") {
site = try_site.data;
initializeSite(site);
if (path !== "/setup" && !site.site_view.local_site.site_setup) {
return res.redirect("/setup");
}
if (site) {
const initialFetchReq: InitialFetchRequest = {
client,
auth,
path,
query,
site,
};
if (activeRoute?.fetchInitialData) {
routeData.push(
...(await Promise.all([
...activeRoute.fetchInitialData(initialFetchReq),
]))
);
}
}
} else if (try_site.state === "failed") {
errorPageData = getErrorPageData(new Error(try_site.msg), site);
}
// Redirect to the 404 if there's an API error
if (routeData[0] && routeData[0].state === "failed") {
const error = routeData[0].msg;
console.error(error);
if (error === "instance_is_private") {
return res.redirect(`/signup`);
} else {
errorPageData = getErrorPageData(new Error(error), site);
}
}
const isoData: IsoDataOptionalSite = {
path,
site_res: site,
routeData,
errorPageData,
};
const wrapper = (
<StaticRouter location={url} context={isoData}>
<App />
</StaticRouter>
);
const root = renderToString(wrapper);
res.send(await createSsrHtml(root, isoData));
} catch (err) {
// If an error is caught here, the error page couldn't even be rendered
console.error(err);
res.statusCode = 500;
return res.send(
process.env.NODE_ENV === "development" ? err.message : "Server error"
);
}
});
server.listen(Number(port), hostname, () => { server.listen(Number(port), hostname, () => {
console.log(`http://${hostname}:${port}`); console.log(`http://${hostname}:${port}`);
}); });
function setForwardedHeaders(headers: IncomingHttpHeaders): {
[key: string]: string;
} {
const out: { [key: string]: string } = {};
if (headers.host) {
out.host = headers.host;
}
const realIp = headers["x-real-ip"];
if (realIp) {
out["x-real-ip"] = realIp as string;
}
const forwardedFor = headers["x-forwarded-for"];
if (forwardedFor) {
out["x-forwarded-for"] = forwardedFor as string;
}
return out;
}
process.on("SIGINT", () => { process.on("SIGINT", () => {
console.info("Interrupted"); console.info("Interrupted");
process.exit(0); process.exit(0);
}); });
const iconSizes = [72, 96, 144, 192, 512];
const defaultLogoPathDirectory = path.join(
process.cwd(),
"dist",
"assets",
"icons"
);
export async function generateManifestBase64({
my_user,
site_view: {
site,
local_site: { community_creation_admin_only },
},
}: GetSiteResponse) {
const url = getHttpBaseExternal();
const icon = site.icon ? await fetchIconPng(site.icon) : null;
const manifest = {
name: site.name,
description: site.description ?? "A link aggregator for the fediverse",
start_url: url,
scope: url,
display: "standalone",
id: "/",
background_color: "#222222",
theme_color: "#222222",
icons: await Promise.all(
iconSizes.map(async size => {
let src = await readFile(
path.join(defaultLogoPathDirectory, `icon-${size}x${size}.png`)
).then(buf => buf.toString("base64"));
if (icon) {
src = await sharp(icon)
.resize(size, size)
.png()
.toBuffer()
.then(buf => buf.toString("base64"));
}
return {
sizes: `${size}x${size}`,
type: "image/png",
src: `data:image/png;base64,${src}`,
purpose: "any maskable",
};
})
),
shortcuts: [
{
name: "Search",
short_name: "Search",
description: "Perform a search.",
url: "/search",
},
{
name: "Communities",
url: "/communities",
short_name: "Communities",
description: "Browse communities",
},
]
.concat(
my_user
? [
{
name: "Create Post",
url: "/create_post",
short_name: "Create Post",
description: "Create a post.",
},
]
: []
)
.concat(
my_user?.local_user_view.person.admin || !community_creation_admin_only
? [
{
name: "Create Community",
url: "/create_community",
short_name: "Create Community",
description: "Create a community",
},
]
: []
),
related_applications: [
{
platform: "f-droid",
url: "https://f-droid.org/packages/com.jerboa/",
id: "com.jerboa",
},
],
};
return Buffer.from(JSON.stringify(manifest)).toString("base64");
}
async function fetchIconPng(iconUrl: string) {
return await fetch(iconUrl)
.then(res => res.blob())
.then(blob => blob.arrayBuffer());
}
function getErrorPageData(error: Error, site?: GetSiteResponse) {
const errorPageData: ErrorPageData = {};
if (site) {
errorPageData.error = error.message;
}
const adminMatrixIds = site?.admins
.map(({ person: { matrix_user_id } }) => matrix_user_id)
.filter(id => id) as string[] | undefined;
if (adminMatrixIds && adminMatrixIds.length > 0) {
errorPageData.adminMatrixIds = adminMatrixIds;
}
return errorPageData;
}
async function createSsrHtml(root: string, isoData: IsoDataOptionalSite) {
const site = isoData.site_res;
const appleTouchIcon = site?.site_view.site.icon
? `data:image/png;base64,${sharp(
await fetchIconPng(site.site_view.site.icon)
)
.resize(180, 180)
.extend({
bottom: 20,
top: 20,
left: 20,
right: 20,
background: "#222222",
})
.png()
.toBuffer()
.then(buf => buf.toString("base64"))}`
: favIconPngUrl;
const erudaStr =
process.env["LEMMY_UI_DEBUG"] === "true"
? renderToString(
<>
<script src="//cdn.jsdelivr.net/npm/eruda"></script>
<script>eruda.init();</script>
</>
)
: "";
const helmet = Helmet.renderStatic();
const config: ILemmyConfig = { wsHost: process.env.LEMMY_UI_LEMMY_WS_HOST };
return `
<!DOCTYPE html>
<html ${helmet.htmlAttributes.toString()}>
<head>
<script>window.isoData = ${serialize(isoData)}</script>
<script>window.lemmyConfig = ${serialize(config)}</script>
<!-- A remote debugging utility for mobile -->
${erudaStr}
<!-- Custom injected script -->
${customHtmlHeader}
${helmet.title.toString()}
${helmet.meta.toString()}
<!-- Required meta tags -->
<meta name="Description" content="Lemmy">
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no, user-scalable=no">
<link
id="favicon"
rel="shortcut icon"
type="image/x-icon"
href=${site?.site_view.site.icon ?? favIconUrl}
/>
<!-- Web app manifest -->
${
site &&
`<link
rel="manifest"
href=${`data:application/manifest+json;base64,${await generateManifestBase64(
site
)}`}
/>`
}
<link rel="apple-touch-icon" href=${appleTouchIcon} />
<link rel="apple-touch-startup-image" href=${appleTouchIcon} />
<!-- Styles -->
<link rel="stylesheet" type="text/css" href="/static/styles/styles.css" />
<!-- Current theme and more -->
${helmet.link.toString()}
</head>
<body ${helmet.bodyAttributes.toString()}>
<noscript>
<div class="alert alert-danger rounded-0" role="alert">
<b>Javascript is disabled. Actions will not work.</b>
</div>
</noscript>
<div id='root'>${root}</div>
<script defer src='/static/js/client.js'></script>
</body>
</html>
`;
}

View File

@ -0,0 +1,10 @@
import type { NextFunction, Response } from "express";
export default function ({ res, next }: { res: Response; next: NextFunction }) {
res.setHeader(
"Content-Security-Policy",
`default-src 'self'; manifest-src *; connect-src *; img-src * data:; script-src 'self' 'unsafe-inline' 'unsafe-eval'; style-src 'self' 'unsafe-inline'; form-action 'self'; base-uri 'self'; frame-src *; media-src *`
);
next();
}

View File

@ -0,0 +1,18 @@
import { existsSync } from "fs";
import { readdir } from "fs/promises";
const extraThemesFolder =
process.env["LEMMY_UI_EXTRA_THEMES_FOLDER"] || "./extra_themes";
const themes = ["darkly", "darkly-red", "litely", "litely-red"];
export async function buildThemeList(): Promise<string[]> {
if (existsSync(extraThemesFolder)) {
const dirThemes = await readdir(extraThemesFolder);
const cssThemes = dirThemes
.filter(d => d.endsWith(".css"))
.map(d => d.replace(".css", ""));
themes.push(...cssThemes);
}
return themes;
}

View File

@ -0,0 +1,109 @@
import { Helmet } from "inferno-helmet";
import { renderToString } from "inferno-server";
import serialize from "serialize-javascript";
import sharp from "sharp";
import { ILemmyConfig, IsoDataOptionalSite } from "../../shared/interfaces";
import { favIconPngUrl, favIconUrl } from "../../shared/utils";
import { fetchIconPng } from "./fetch-icon-png";
import { generateManifestBase64 } from "./generate-manifest-base64";
const customHtmlHeader = process.env["LEMMY_UI_CUSTOM_HTML_HEADER"] || "";
export async function createSsrHtml(
root: string,
isoData: IsoDataOptionalSite
) {
const site = isoData.site_res;
const appleTouchIcon = site?.site_view.site.icon
? `data:image/png;base64,${sharp(
await fetchIconPng(site.site_view.site.icon)
)
.resize(180, 180)
.extend({
bottom: 20,
top: 20,
left: 20,
right: 20,
background: "#222222",
})
.png()
.toBuffer()
.then(buf => buf.toString("base64"))}`
: favIconPngUrl;
const erudaStr =
process.env["LEMMY_UI_DEBUG"] === "true"
? renderToString(
<>
<script src="//cdn.jsdelivr.net/npm/eruda"></script>
<script>eruda.init();</script>
</>
)
: "";
const helmet = Helmet.renderStatic();
const config: ILemmyConfig = { wsHost: process.env.LEMMY_UI_LEMMY_WS_HOST };
return `
<!DOCTYPE html>
<html ${helmet.htmlAttributes.toString()}>
<head>
<script>window.isoData = ${serialize(isoData)}</script>
<script>window.lemmyConfig = ${serialize(config)}</script>
<!-- A remote debugging utility for mobile -->
${erudaStr}
<!-- Custom injected script -->
${customHtmlHeader}
${helmet.title.toString()}
${helmet.meta.toString()}
<!-- Required meta tags -->
<meta name="Description" content="Lemmy">
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no, user-scalable=no">
<link
id="favicon"
rel="shortcut icon"
type="image/x-icon"
href=${site?.site_view.site.icon ?? favIconUrl}
/>
<!-- Web app manifest -->
${
site &&
`<link
rel="manifest"
href=${`data:application/manifest+json;base64,${await generateManifestBase64(
site
)}`}
/>`
}
<link rel="apple-touch-icon" href=${appleTouchIcon} />
<link rel="apple-touch-startup-image" href=${appleTouchIcon} />
<!-- Styles -->
<link rel="stylesheet" type="text/css" href="/static/styles/styles.css" />
<!-- Current theme and more -->
${helmet.link.toString()}
</head>
<body ${helmet.bodyAttributes.toString()}>
<noscript>
<div class="alert alert-danger rounded-0" role="alert">
<b>Javascript is disabled. Actions will not work.</b>
</div>
</noscript>
<div id='root'>${root}</div>
<script defer src='/static/js/client.js'></script>
</body>
</html>
`;
}

View File

@ -0,0 +1,5 @@
export async function fetchIconPng(iconUrl: string) {
return await fetch(iconUrl)
.then(res => res.blob())
.then(blob => blob.arrayBuffer());
}

View File

@ -0,0 +1,107 @@
import { readFile } from "fs/promises";
import { GetSiteResponse } from "lemmy-js-client";
import path from "path";
import sharp from "sharp";
import { getHttpBaseExternal } from "../../shared/env";
import { fetchIconPng } from "./fetch-icon-png";
const iconSizes = [72, 96, 144, 192, 512];
const defaultLogoPathDirectory = path.join(
process.cwd(),
"dist",
"assets",
"icons"
);
export async function generateManifestBase64({
my_user,
site_view: {
site,
local_site: { community_creation_admin_only },
},
}: GetSiteResponse) {
const url = getHttpBaseExternal();
const icon = site.icon ? await fetchIconPng(site.icon) : null;
const manifest = {
name: site.name,
description: site.description ?? "A link aggregator for the fediverse",
start_url: url,
scope: url,
display: "standalone",
id: "/",
background_color: "#222222",
theme_color: "#222222",
icons: await Promise.all(
iconSizes.map(async size => {
let src = await readFile(
path.join(defaultLogoPathDirectory, `icon-${size}x${size}.png`)
).then(buf => buf.toString("base64"));
if (icon) {
src = await sharp(icon)
.resize(size, size)
.png()
.toBuffer()
.then(buf => buf.toString("base64"));
}
return {
sizes: `${size}x${size}`,
type: "image/png",
src: `data:image/png;base64,${src}`,
purpose: "any maskable",
};
})
),
shortcuts: [
{
name: "Search",
short_name: "Search",
description: "Perform a search.",
url: "/search",
},
{
name: "Communities",
url: "/communities",
short_name: "Communities",
description: "Browse communities",
},
]
.concat(
my_user
? [
{
name: "Create Post",
url: "/create_post",
short_name: "Create Post",
description: "Create a post.",
},
]
: []
)
.concat(
my_user?.local_user_view.person.admin || !community_creation_admin_only
? [
{
name: "Create Community",
url: "/create_community",
short_name: "Create Community",
description: "Create a community",
},
]
: []
),
related_applications: [
{
platform: "f-droid",
url: "https://f-droid.org/packages/com.jerboa/",
id: "com.jerboa",
},
],
};
return Buffer.from(JSON.stringify(manifest)).toString("base64");
}

View File

@ -0,0 +1,20 @@
import { GetSiteResponse } from "lemmy-js-client";
import { ErrorPageData } from "../../shared/utils";
export function getErrorPageData(error: Error, site?: GetSiteResponse) {
const errorPageData: ErrorPageData = {};
if (site) {
errorPageData.error = error.message;
}
const adminMatrixIds = site?.admins
.map(({ person: { matrix_user_id } }) => matrix_user_id)
.filter(id => id) as string[] | undefined;
if (adminMatrixIds && adminMatrixIds.length > 0) {
errorPageData.adminMatrixIds = adminMatrixIds;
}
return errorPageData;
}

View File

@ -0,0 +1,25 @@
import { IncomingHttpHeaders } from "http";
export function setForwardedHeaders(headers: IncomingHttpHeaders): {
[key: string]: string;
} {
const out: { [key: string]: string } = {};
if (headers.host) {
out.host = headers.host;
}
const realIp = headers["x-real-ip"];
if (realIp) {
out["x-real-ip"] = realIp as string;
}
const forwardedFor = headers["x-forwarded-for"];
if (forwardedFor) {
out["x-forwarded-for"] = forwardedFor as string;
}
return out;
}

View File

@ -1,4 +1,4 @@
import { Component } from "inferno"; import { Component, createRef, linkEvent, RefObject } from "inferno";
import { Provider } from "inferno-i18next-dess"; import { Provider } from "inferno-i18next-dess";
import { Route, Switch } from "inferno-router"; import { Route, Switch } from "inferno-router";
import { i18n } from "../../i18next"; import { i18n } from "../../i18next";
@ -15,8 +15,15 @@ import { Theme } from "./theme";
export class App extends Component<any, any> { export class App extends Component<any, any> {
private isoData: IsoDataOptionalSite = setIsoData(this.context); private isoData: IsoDataOptionalSite = setIsoData(this.context);
private readonly mainContentRef: RefObject<HTMLElement>;
constructor(props: any, context: any) { constructor(props: any, context: any) {
super(props, context); super(props, context);
this.mainContentRef = createRef();
}
handleJumpToContent(event) {
event.preventDefault();
this.mainContentRef.current?.focus();
} }
render() { render() {
const siteRes = this.isoData.site_res; const siteRes = this.isoData.site_res;
@ -25,7 +32,13 @@ export class App extends Component<any, any> {
return ( return (
<> <>
<Provider i18next={i18n}> <Provider i18next={i18n}>
<div id="app"> <div id="app" className="lemmy-site">
<a
className="skip-link bg-light text-dark p-2 text-decoration-none position-absolute start-0 z-3"
onClick={linkEvent(this, this.handleJumpToContent)}
>
${i18n.t("jump_to_content", "Jump to content")}
</a>
{siteView && ( {siteView && (
<Theme defaultTheme={siteView.local_site.default_theme} /> <Theme defaultTheme={siteView.local_site.default_theme} />
)} )}
@ -39,14 +52,16 @@ export class App extends Component<any, any> {
exact exact
component={routeProps => ( component={routeProps => (
<ErrorGuard> <ErrorGuard>
{RouteComponent && <main tabIndex={-1} ref={this.mainContentRef}>
(isAuthPath(path ?? "") ? ( {RouteComponent &&
<AuthGuard> (isAuthPath(path ?? "") ? (
<AuthGuard>
<RouteComponent {...routeProps} />
</AuthGuard>
) : (
<RouteComponent {...routeProps} /> <RouteComponent {...routeProps} />
</AuthGuard> ))}
) : ( </main>
<RouteComponent {...routeProps} />
))}
</ErrorGuard> </ErrorGuard>
)} )}
/> />

View File

@ -16,7 +16,7 @@ export class ErrorPage extends Component<any, any> {
const { errorPageData } = this.isoData; const { errorPageData } = this.isoData;
return ( return (
<div className="container-lg text-center"> <div className="error-page container-lg text-center">
<h1> <h1>
{errorPageData {errorPageData
? i18n.t("error_page_title") ? i18n.t("error_page_title")

View File

@ -16,9 +16,9 @@ export class Footer extends Component<FooterProps, any> {
render() { render() {
return ( return (
<nav className="container-lg navbar navbar-expand-md navbar-light navbar-bg p-3"> <footer className="app-footer container-lg navbar navbar-expand-md navbar-light navbar-bg p-3">
<div className="navbar-collapse"> <div className="navbar-collapse">
<ul className="navbar-nav ml-auto"> <ul className="navbar-nav ms-auto">
{this.props.site?.version !== VERSION && ( {this.props.site?.version !== VERSION && (
<li className="nav-item"> <li className="nav-item">
<span className="nav-link">UI: {VERSION}</span> <span className="nav-link">UI: {VERSION}</span>
@ -63,7 +63,7 @@ export class Footer extends Component<FooterProps, any> {
</li> </li>
</ul> </ul>
</div> </div>
</nav> </footer>
); );
} }
} }

View File

@ -1,3 +1,6 @@
import { isBrowser } from "@utils/browser";
import { poll } from "@utils/helpers";
import { amAdmin, canCreateCommunity } from "@utils/roles";
import { Component, createRef, linkEvent } from "inferno"; import { Component, createRef, linkEvent } from "inferno";
import { NavLink } from "inferno-router"; import { NavLink } from "inferno-router";
import { import {
@ -10,13 +13,9 @@ import { i18n } from "../../i18next";
import { UserService } from "../../services"; import { UserService } from "../../services";
import { HttpService, RequestState } from "../../services/HttpService"; import { HttpService, RequestState } from "../../services/HttpService";
import { import {
amAdmin,
canCreateCommunity,
donateLemmyUrl, donateLemmyUrl,
isBrowser,
myAuth, myAuth,
numToSI, numToSI,
poll,
showAvatars, showAvatars,
toast, toast,
updateUnreadCountsInterval, updateUnreadCountsInterval,
@ -86,11 +85,15 @@ export class Navbar extends Component<NavbarProps, NavbarState> {
const siteView = this.props.siteRes?.site_view; const siteView = this.props.siteRes?.site_view;
const person = UserService.Instance.myUserInfo?.local_user_view.person; const person = UserService.Instance.myUserInfo?.local_user_view.person;
return ( return (
<nav className="navbar navbar-expand-md navbar-light shadow-sm p-0 px-3 container-lg"> <nav
className="navbar navbar-expand-md navbar-light shadow-sm p-0 px-3 container-lg"
id="navbar"
>
<NavLink <NavLink
id="navTitle"
to="/" to="/"
title={siteView?.site.description ?? siteView?.site.name} title={siteView?.site.description ?? siteView?.site.name}
className="d-flex align-items-center navbar-brand mr-md-3" className="d-flex align-items-center navbar-brand me-md-3"
onMouseUp={linkEvent(this, handleCollapseClick)} onMouseUp={linkEvent(this, handleCollapseClick)}
> >
{siteView?.site.icon && showAvatars() && ( {siteView?.site.icon && showAvatars() && (
@ -99,11 +102,11 @@ export class Navbar extends Component<NavbarProps, NavbarState> {
{siteView?.site.name} {siteView?.site.name}
</NavLink> </NavLink>
{person && ( {person && (
<ul className="navbar-nav d-flex flex-row ml-auto d-md-none"> <ul className="navbar-nav d-flex flex-row ms-auto d-md-none">
<li className="nav-item"> <li id="navMessages" className="nav-item nav-item-icon">
<NavLink <NavLink
to="/inbox" to="/inbox"
className="p-1 nav-link border-0" className="p-1 nav-link border-0 nav-messages"
title={i18n.t("unread_messages", { title={i18n.t("unread_messages", {
count: Number(this.state.unreadApplicationCountRes.state), count: Number(this.state.unreadApplicationCountRes.state),
formattedCount: numToSI(this.unreadInboxCount), formattedCount: numToSI(this.unreadInboxCount),
@ -112,14 +115,14 @@ export class Navbar extends Component<NavbarProps, NavbarState> {
> >
<Icon icon="bell" /> <Icon icon="bell" />
{this.unreadInboxCount > 0 && ( {this.unreadInboxCount > 0 && (
<span className="mx-1 badge badge-light"> <span className="mx-1 badge text-bg-light">
{numToSI(this.unreadInboxCount)} {numToSI(this.unreadInboxCount)}
</span> </span>
)} )}
</NavLink> </NavLink>
</li> </li>
{this.moderatesSomething && ( {this.moderatesSomething && (
<li className="nav-item"> <li className="nav-item nav-item-icon">
<NavLink <NavLink
to="/reports" to="/reports"
className="p-1 nav-link border-0" className="p-1 nav-link border-0"
@ -131,7 +134,7 @@ export class Navbar extends Component<NavbarProps, NavbarState> {
> >
<Icon icon="shield" /> <Icon icon="shield" />
{this.unreadReportCount > 0 && ( {this.unreadReportCount > 0 && (
<span className="mx-1 badge badge-light"> <span className="mx-1 badge text-bg-light">
{numToSI(this.unreadReportCount)} {numToSI(this.unreadReportCount)}
</span> </span>
)} )}
@ -139,7 +142,7 @@ export class Navbar extends Component<NavbarProps, NavbarState> {
</li> </li>
)} )}
{amAdmin() && ( {amAdmin() && (
<li className="nav-item"> <li className="nav-item nav-item-icon">
<NavLink <NavLink
to="/registration_applications" to="/registration_applications"
className="p-1 nav-link border-0" className="p-1 nav-link border-0"
@ -151,7 +154,7 @@ export class Navbar extends Component<NavbarProps, NavbarState> {
> >
<Icon icon="clipboard" /> <Icon icon="clipboard" />
{this.unreadApplicationCount > 0 && ( {this.unreadApplicationCount > 0 && (
<span className="mx-1 badge badge-light"> <span className="mx-1 badge text-bg-light">
{numToSI(this.unreadApplicationCount)} {numToSI(this.unreadApplicationCount)}
</span> </span>
)} )}
@ -178,7 +181,7 @@ export class Navbar extends Component<NavbarProps, NavbarState> {
id="navbarDropdown" id="navbarDropdown"
ref={this.mobileMenuRef} ref={this.mobileMenuRef}
> >
<ul className="mr-auto navbar-nav"> <ul id="navbarLinks" className="me-auto navbar-nav">
<li className="nav-item"> <li className="nav-item">
<NavLink <NavLink
to="/communities" to="/communities"
@ -220,42 +223,51 @@ export class Navbar extends Component<NavbarProps, NavbarState> {
)} )}
<li className="nav-item"> <li className="nav-item">
<a <a
className="nav-link" className="nav-link d-inline-flex align-items-center d-md-inline-block"
title={i18n.t("support_lemmy")} title={i18n.t("support_lemmy")}
href={donateLemmyUrl} href={donateLemmyUrl}
> >
<Icon icon="heart" classes="small" /> <Icon icon="heart" classes="small" />
<span className="d-inline ms-1 d-md-none ms-md-0">
{i18n.t("support_lemmy")}
</span>
</a> </a>
</li> </li>
</ul> </ul>
<ul className="navbar-nav"> <ul id="navbarIcons" className="navbar-nav">
<li className="nav-item"> <li id="navSearch" className="nav-item">
<NavLink <NavLink
to="/search" to="/search"
className="nav-link" className="nav-link d-inline-flex align-items-center d-md-inline-block"
title={i18n.t("search")} title={i18n.t("search")}
onMouseUp={linkEvent(this, handleCollapseClick)} onMouseUp={linkEvent(this, handleCollapseClick)}
> >
<Icon icon="search" /> <Icon icon="search" />
<span className="d-inline ms-1 d-md-none ms-md-0">
{i18n.t("search")}
</span>
</NavLink> </NavLink>
</li> </li>
{amAdmin() && ( {amAdmin() && (
<li className="nav-item"> <li id="navAdmin" className="nav-item">
<NavLink <NavLink
to="/admin" to="/admin"
className="nav-link" className="nav-link d-inline-flex align-items-center d-md-inline-block"
title={i18n.t("admin_settings")} title={i18n.t("admin_settings")}
onMouseUp={linkEvent(this, handleCollapseClick)} onMouseUp={linkEvent(this, handleCollapseClick)}
> >
<Icon icon="settings" /> <Icon icon="settings" />
<span className="d-inline ms-1 d-md-none ms-md-0">
{i18n.t("admin_settings")}
</span>
</NavLink> </NavLink>
</li> </li>
)} )}
{person ? ( {person ? (
<> <>
<li className="nav-item"> <li id="navMessages" className="nav-item">
<NavLink <NavLink
className="nav-link" className="nav-link d-inline-flex align-items-center d-md-inline-block"
to="/inbox" to="/inbox"
title={i18n.t("unread_messages", { title={i18n.t("unread_messages", {
count: Number(this.unreadInboxCount), count: Number(this.unreadInboxCount),
@ -264,17 +276,23 @@ export class Navbar extends Component<NavbarProps, NavbarState> {
onMouseUp={linkEvent(this, handleCollapseClick)} onMouseUp={linkEvent(this, handleCollapseClick)}
> >
<Icon icon="bell" /> <Icon icon="bell" />
<span className="badge text-bg-light d-inline ms-1 d-md-none ms-md-0">
{i18n.t("unread_messages", {
count: Number(this.unreadInboxCount),
formattedCount: numToSI(this.unreadInboxCount),
})}
</span>
{this.unreadInboxCount > 0 && ( {this.unreadInboxCount > 0 && (
<span className="mx-1 badge badge-light"> <span className="mx-1 badge text-bg-light">
{numToSI(this.unreadInboxCount)} {numToSI(this.unreadInboxCount)}
</span> </span>
)} )}
</NavLink> </NavLink>
</li> </li>
{this.moderatesSomething && ( {this.moderatesSomething && (
<li className="nav-item"> <li id="navModeration" className="nav-item">
<NavLink <NavLink
className="nav-link" className="nav-link d-inline-flex align-items-center d-md-inline-block"
to="/reports" to="/reports"
title={i18n.t("unread_reports", { title={i18n.t("unread_reports", {
count: Number(this.unreadReportCount), count: Number(this.unreadReportCount),
@ -283,8 +301,14 @@ export class Navbar extends Component<NavbarProps, NavbarState> {
onMouseUp={linkEvent(this, handleCollapseClick)} onMouseUp={linkEvent(this, handleCollapseClick)}
> >
<Icon icon="shield" /> <Icon icon="shield" />
<span className="badge text-bg-light d-inline ms-1 d-md-none ms-md-0">
{i18n.t("unread_reports", {
count: Number(this.unreadReportCount),
formattedCount: numToSI(this.unreadReportCount),
})}
</span>
{this.unreadReportCount > 0 && ( {this.unreadReportCount > 0 && (
<span className="mx-1 badge badge-light"> <span className="mx-1 badge text-bg-light">
{numToSI(this.unreadReportCount)} {numToSI(this.unreadReportCount)}
</span> </span>
)} )}
@ -292,10 +316,10 @@ export class Navbar extends Component<NavbarProps, NavbarState> {
</li> </li>
)} )}
{amAdmin() && ( {amAdmin() && (
<li className="nav-item"> <li id="navApplications" className="nav-item">
<NavLink <NavLink
to="/registration_applications" to="/registration_applications"
className="nav-link" className="nav-link d-inline-flex align-items-center d-md-inline-block"
title={i18n.t("unread_registration_applications", { title={i18n.t("unread_registration_applications", {
count: Number(this.unreadApplicationCount), count: Number(this.unreadApplicationCount),
formattedCount: numToSI(this.unreadApplicationCount), formattedCount: numToSI(this.unreadApplicationCount),
@ -303,8 +327,14 @@ export class Navbar extends Component<NavbarProps, NavbarState> {
onMouseUp={linkEvent(this, handleCollapseClick)} onMouseUp={linkEvent(this, handleCollapseClick)}
> >
<Icon icon="clipboard" /> <Icon icon="clipboard" />
<span className="badge text-bg-light d-inline ms-1 d-md-none ms-md-0">
{i18n.t("unread_registration_applications", {
count: Number(this.unreadApplicationCount),
formattedCount: numToSI(this.unreadApplicationCount),
})}
</span>
{this.unreadApplicationCount > 0 && ( {this.unreadApplicationCount > 0 && (
<span className="mx-1 badge badge-light"> <span className="mx-1 badge text-bg-light">
{numToSI(this.unreadApplicationCount)} {numToSI(this.unreadApplicationCount)}
</span> </span>
)} )}
@ -312,7 +342,7 @@ export class Navbar extends Component<NavbarProps, NavbarState> {
</li> </li>
)} )}
{person && ( {person && (
<div className="dropdown"> <div id="dropdownUser" className="dropdown">
<button <button
className="btn dropdown-toggle" className="btn dropdown-toggle"
role="button" role="button"
@ -335,7 +365,7 @@ export class Navbar extends Component<NavbarProps, NavbarState> {
title={i18n.t("profile")} title={i18n.t("profile")}
onMouseUp={linkEvent(this, handleCollapseClick)} onMouseUp={linkEvent(this, handleCollapseClick)}
> >
<Icon icon="user" classes="mr-1" /> <Icon icon="user" classes="me-1" />
{i18n.t("profile")} {i18n.t("profile")}
</NavLink> </NavLink>
</li> </li>
@ -346,7 +376,7 @@ export class Navbar extends Component<NavbarProps, NavbarState> {
title={i18n.t("settings")} title={i18n.t("settings")}
onMouseUp={linkEvent(this, handleCollapseClick)} onMouseUp={linkEvent(this, handleCollapseClick)}
> >
<Icon icon="settings" classes="mr-1" /> <Icon icon="settings" classes="me-1" />
{i18n.t("settings")} {i18n.t("settings")}
</NavLink> </NavLink>
</li> </li>
@ -358,7 +388,7 @@ export class Navbar extends Component<NavbarProps, NavbarState> {
className="dropdown-item btn btn-link px-2" className="dropdown-item btn btn-link px-2"
onClick={linkEvent(this, handleLogOut)} onClick={linkEvent(this, handleLogOut)}
> >
<Icon icon="log-out" classes="mr-1" /> <Icon icon="log-out" classes="me-1" />
{i18n.t("logout")} {i18n.t("logout")}
</button> </button>
</li> </li>

View File

@ -21,6 +21,7 @@ interface CommentFormProps {
onReplyCancel?(): void; onReplyCancel?(): void;
allLanguages: Language[]; allLanguages: Language[];
siteLanguages: number[]; siteLanguages: number[];
containerClass?: string;
onUpsertComment(form: EditComment | CreateComment): void; onUpsertComment(form: EditComment | CreateComment): void;
} }
@ -40,7 +41,11 @@ export class CommentForm extends Component<CommentFormProps, any> {
: undefined; : undefined;
return ( return (
<div className="mb-3"> <div
className={["comment-form", "mb-3", this.props.containerClass].join(
" "
)}
>
{UserService.Instance.myUserInfo ? ( {UserService.Instance.myUserInfo ? (
<MarkdownTextArea <MarkdownTextArea
initialContent={initialContent} initialContent={initialContent}
@ -58,7 +63,7 @@ export class CommentForm extends Component<CommentFormProps, any> {
/> />
) : ( ) : (
<div className="alert alert-warning" role="alert"> <div className="alert alert-warning" role="alert">
<Icon icon="alert-triangle" classes="icon-inline mr-2" /> <Icon icon="alert-triangle" classes="icon-inline me-2" />
<T i18nKey="must_login" class="d-inline"> <T i18nKey="must_login" class="d-inline">
# #
<Link className="alert-link" to="/login"> <Link className="alert-link" to="/login">

View File

@ -1,3 +1,11 @@
import {
amCommunityCreator,
canAdmin,
canMod,
isAdmin,
isBanned,
isMod,
} from "@utils/roles";
import classNames from "classnames"; import classNames from "classnames";
import { Component, InfernoNode, linkEvent } from "inferno"; import { Component, InfernoNode, linkEvent } from "inferno";
import { Link } from "inferno-router"; import { Link } from "inferno-router";
@ -40,16 +48,10 @@ import {
} from "../../interfaces"; } from "../../interfaces";
import { UserService } from "../../services"; import { UserService } from "../../services";
import { import {
amCommunityCreator,
canAdmin,
canMod,
colorList, colorList,
commentTreeMaxDepth, commentTreeMaxDepth,
futureDaysToUnixTime, futureDaysToUnixTime,
getCommentParentId, getCommentParentId,
isAdmin,
isBanned,
isMod,
mdToHtml, mdToHtml,
mdToHtmlNoImages, mdToHtmlNoImages,
myAuth, myAuth,
@ -282,7 +284,7 @@ export class CommentNode extends Component<CommentNodeProps, CommentNodeState> {
return ( return (
<li className="comment" role="comment"> <li className="comment" role="comment">
<div <article
id={`comment-${cv.comment.id}`} id={`comment-${cv.comment.id}`}
className={classNames(`details comment-node py-2`, { className={classNames(`details comment-node py-2`, {
"border-top border-light": !this.props.noBorder, "border-top border-light": !this.props.noBorder,
@ -291,12 +293,12 @@ export class CommentNode extends Component<CommentNodeProps, CommentNodeState> {
> >
<div <div
className={classNames({ className={classNames({
"ml-2": !this.props.noIndent, "ms-2": !this.props.noIndent,
})} })}
> >
<div className="d-flex flex-wrap align-items-center text-muted small"> <div className="d-flex flex-wrap align-items-center text-muted small">
<button <button
className="btn btn-sm text-muted mr-2" className="btn btn-sm text-muted me-2"
onClick={linkEvent(this, this.handleCommentCollapse)} onClick={linkEvent(this, this.handleCommentCollapse)}
aria-label={this.expandText} aria-label={this.expandText}
data-tippy-content={this.expandText} data-tippy-content={this.expandText}
@ -306,29 +308,29 @@ export class CommentNode extends Component<CommentNodeProps, CommentNodeState> {
classes="icon-inline" classes="icon-inline"
/> />
</button> </button>
<span className="mr-2"> <span className="me-2">
<PersonListing person={cv.creator} /> <PersonListing person={cv.creator} />
</span> </span>
{cv.comment.distinguished && ( {cv.comment.distinguished && (
<Icon icon="shield" inline classes={`text-danger mr-2`} /> <Icon icon="shield" inline classes={`text-danger me-2`} />
)} )}
{this.isPostCreator && ( {this.isPostCreator && (
<div className="badge badge-light d-none d-sm-inline mr-2"> <div className="badge text-bg-light d-none d-sm-inline me-2">
{i18n.t("creator")} {i18n.t("creator")}
</div> </div>
)} )}
{isMod_ && ( {isMod_ && (
<div className="badge d-none d-sm-inline mr-2"> <div className="badge text-bg-light d-none d-sm-inline me-2">
{i18n.t("mod")} {i18n.t("mod")}
</div> </div>
)} )}
{isAdmin_ && ( {isAdmin_ && (
<div className="badge d-none d-sm-inline mr-2"> <div className="badge text-bg-light d-none d-sm-inline me-2">
{i18n.t("admin")} {i18n.t("admin")}
</div> </div>
)} )}
{cv.creator.bot_account && ( {cv.creator.bot_account && (
<div className="badge d-none d-sm-inline mr-2"> <div className="badge text-bg-light d-none d-sm-inline me-2">
{i18n.t("bot_account").toLowerCase()} {i18n.t("bot_account").toLowerCase()}
</div> </div>
)} )}
@ -337,14 +339,14 @@ export class CommentNode extends Component<CommentNodeProps, CommentNodeState> {
<span className="mx-1">{i18n.t("to")}</span> <span className="mx-1">{i18n.t("to")}</span>
<CommunityLink community={cv.community} /> <CommunityLink community={cv.community} />
<span className="mx-2"></span> <span className="mx-2"></span>
<Link className="mr-2" to={`/post/${cv.post.id}`}> <Link className="me-2" to={`/post/${cv.post.id}`}>
{cv.post.name} {cv.post.name}
</Link> </Link>
</> </>
)} )}
{this.linkBtn(true)} {this.linkBtn(true)}
{cv.comment.language_id !== 0 && ( {cv.comment.language_id !== 0 && (
<span className="badge d-none d-sm-inline mr-2"> <span className="badge text-bg-light d-none d-sm-inline me-2">
{ {
this.props.allLanguages.find( this.props.allLanguages.find(
lang => lang.id === cv.comment.language_id lang => lang.id === cv.comment.language_id
@ -353,7 +355,7 @@ export class CommentNode extends Component<CommentNodeProps, CommentNodeState> {
</span> </span>
)} )}
{/* This is an expanding spacer for mobile */} {/* This is an expanding spacer for mobile */}
<div className="mr-lg-5 flex-grow-1 flex-lg-grow-0 unselectable pointer mx-2" /> <div className="me-lg-5 flex-grow-1 flex-lg-grow-0 unselectable pointer mx-2" />
{showScores() && ( {showScores() && (
<> <>
<a <a
@ -365,7 +367,7 @@ export class CommentNode extends Component<CommentNodeProps, CommentNodeState> {
<Spinner /> <Spinner />
) : ( ) : (
<span <span
className="mr-1 font-weight-bold" className="me-1 font-weight-bold"
aria-label={i18n.t("number_of_points", { aria-label={i18n.t("number_of_points", {
count: Number(this.commentView.counts.score), count: Number(this.commentView.counts.score),
formattedCount: numToSI( formattedCount: numToSI(
@ -377,7 +379,7 @@ export class CommentNode extends Component<CommentNodeProps, CommentNodeState> {
</span> </span>
)} )}
</a> </a>
<span className="mr-1"></span> <span className="me-1"></span>
</> </>
)} )}
<span> <span>
@ -400,6 +402,7 @@ export class CommentNode extends Component<CommentNodeProps, CommentNodeState> {
focus focus
allLanguages={this.props.allLanguages} allLanguages={this.props.allLanguages}
siteLanguages={this.props.siteLanguages} siteLanguages={this.props.siteLanguages}
containerClass="comment-comment-container"
onUpsertComment={this.props.onEditComment} onUpsertComment={this.props.onEditComment}
/> />
)} )}
@ -467,7 +470,7 @@ export class CommentNode extends Component<CommentNodeProps, CommentNodeState> {
{showScores() && {showScores() &&
this.commentView.counts.upvotes !== this.commentView.counts.upvotes !==
this.commentView.counts.score && ( this.commentView.counts.score && (
<span className="ml-1"> <span className="ms-1">
{numToSI(this.commentView.counts.upvotes)} {numToSI(this.commentView.counts.upvotes)}
</span> </span>
)} )}
@ -494,7 +497,7 @@ export class CommentNode extends Component<CommentNodeProps, CommentNodeState> {
{showScores() && {showScores() &&
this.commentView.counts.upvotes !== this.commentView.counts.upvotes !==
this.commentView.counts.score && ( this.commentView.counts.score && (
<span className="ml-1"> <span className="ms-1">
{numToSI(this.commentView.counts.downvotes)} {numToSI(this.commentView.counts.downvotes)}
</span> </span>
)} )}
@ -512,7 +515,7 @@ export class CommentNode extends Component<CommentNodeProps, CommentNodeState> {
</button> </button>
{!this.state.showAdvanced ? ( {!this.state.showAdvanced ? (
<button <button
className="btn btn-link btn-animate text-muted" className="btn btn-link btn-animate text-muted btn-more"
onClick={linkEvent(this, this.handleShowAdvanced)} onClick={linkEvent(this, this.handleShowAdvanced)}
data-tippy-content={i18n.t("more")} data-tippy-content={i18n.t("more")}
aria-label={i18n.t("more")} aria-label={i18n.t("more")}
@ -944,10 +947,10 @@ export class CommentNode extends Component<CommentNodeProps, CommentNodeState> {
</div> </div>
)} )}
</div> </div>
</div> </article>
{showMoreChildren && ( {showMoreChildren && (
<div <div
className={classNames("details ml-1 comment-node py-2", { className={classNames("details ms-1 comment-node py-2", {
"border-top border-light": !this.props.noBorder, "border-top border-light": !this.props.noBorder,
})} })}
style={`border-left: 2px ${moreRepliesBorderColor} solid !important`} style={`border-left: 2px ${moreRepliesBorderColor} solid !important`}
@ -979,7 +982,7 @@ export class CommentNode extends Component<CommentNodeProps, CommentNodeState> {
onSubmit={linkEvent(this, this.handleRemoveComment)} onSubmit={linkEvent(this, this.handleRemoveComment)}
> >
<label <label
className="sr-only" className="visually-hidden"
htmlFor={`mod-remove-reason-${cv.comment.id}`} htmlFor={`mod-remove-reason-${cv.comment.id}`}
> >
{i18n.t("reason")} {i18n.t("reason")}
@ -987,7 +990,7 @@ export class CommentNode extends Component<CommentNodeProps, CommentNodeState> {
<input <input
type="text" type="text"
id={`mod-remove-reason-${cv.comment.id}`} id={`mod-remove-reason-${cv.comment.id}`}
className="form-control mr-2" className="form-control me-2"
placeholder={i18n.t("reason")} placeholder={i18n.t("reason")}
value={this.state.removeReason} value={this.state.removeReason}
onInput={linkEvent(this, this.handleModRemoveReasonChange)} onInput={linkEvent(this, this.handleModRemoveReasonChange)}
@ -1007,7 +1010,7 @@ export class CommentNode extends Component<CommentNodeProps, CommentNodeState> {
onSubmit={linkEvent(this, this.handleReportComment)} onSubmit={linkEvent(this, this.handleReportComment)}
> >
<label <label
className="sr-only" className="visually-hidden"
htmlFor={`report-reason-${cv.comment.id}`} htmlFor={`report-reason-${cv.comment.id}`}
> >
{i18n.t("reason")} {i18n.t("reason")}
@ -1016,7 +1019,7 @@ export class CommentNode extends Component<CommentNodeProps, CommentNodeState> {
type="text" type="text"
required required
id={`report-reason-${cv.comment.id}`} id={`report-reason-${cv.comment.id}`}
className="form-control mr-2" className="form-control me-2"
placeholder={i18n.t("reason")} placeholder={i18n.t("reason")}
value={this.state.reportReason} value={this.state.reportReason}
onInput={linkEvent(this, this.handleReportReasonChange)} onInput={linkEvent(this, this.handleReportReasonChange)}
@ -1032,7 +1035,7 @@ export class CommentNode extends Component<CommentNodeProps, CommentNodeState> {
)} )}
{this.state.showBanDialog && ( {this.state.showBanDialog && (
<form onSubmit={linkEvent(this, this.handleModBanBothSubmit)}> <form onSubmit={linkEvent(this, this.handleModBanBothSubmit)}>
<div className="form-group row col-12"> <div className="mb-3 row col-12">
<label <label
className="col-form-label" className="col-form-label"
htmlFor={`mod-ban-reason-${cv.comment.id}`} htmlFor={`mod-ban-reason-${cv.comment.id}`}
@ -1042,7 +1045,7 @@ export class CommentNode extends Component<CommentNodeProps, CommentNodeState> {
<input <input
type="text" type="text"
id={`mod-ban-reason-${cv.comment.id}`} id={`mod-ban-reason-${cv.comment.id}`}
className="form-control mr-2" className="form-control me-2"
placeholder={i18n.t("reason")} placeholder={i18n.t("reason")}
value={this.state.banReason} value={this.state.banReason}
onInput={linkEvent(this, this.handleModBanReasonChange)} onInput={linkEvent(this, this.handleModBanReasonChange)}
@ -1056,12 +1059,12 @@ export class CommentNode extends Component<CommentNodeProps, CommentNodeState> {
<input <input
type="number" type="number"
id={`mod-ban-expires-${cv.comment.id}`} id={`mod-ban-expires-${cv.comment.id}`}
className="form-control mr-2" className="form-control me-2"
placeholder={i18n.t("number_of_days")} placeholder={i18n.t("number_of_days")}
value={this.state.banExpireDays} value={this.state.banExpireDays}
onInput={linkEvent(this, this.handleModBanExpireDaysChange)} onInput={linkEvent(this, this.handleModBanExpireDaysChange)}
/> />
<div className="form-group"> <div className="input-group mb-3">
<div className="form-check"> <div className="form-check">
<input <input
className="form-check-input" className="form-check-input"
@ -1081,11 +1084,11 @@ export class CommentNode extends Component<CommentNodeProps, CommentNodeState> {
</div> </div>
</div> </div>
{/* TODO hold off on expires until later */} {/* TODO hold off on expires until later */}
{/* <div class="form-group row"> */} {/* <div class="mb-3 row"> */}
{/* <label class="col-form-label">Expires</label> */} {/* <label class="col-form-label">Expires</label> */}
{/* <input type="date" class="form-control mr-2" placeholder={i18n.t('expires')} value={this.state.banExpires} onInput={linkEvent(this, this.handleModBanExpiresChange)} /> */} {/* <input type="date" class="form-control me-2" placeholder={i18n.t('expires')} value={this.state.banExpires} onInput={linkEvent(this, this.handleModBanExpiresChange)} /> */}
{/* </div> */} {/* </div> */}
<div className="form-group row"> <div className="mb-3 row">
<button <button
type="submit" type="submit"
className="btn btn-secondary" className="btn btn-secondary"
@ -1106,7 +1109,7 @@ export class CommentNode extends Component<CommentNodeProps, CommentNodeState> {
{this.state.showPurgeDialog && ( {this.state.showPurgeDialog && (
<form onSubmit={linkEvent(this, this.handlePurgeBothSubmit)}> <form onSubmit={linkEvent(this, this.handlePurgeBothSubmit)}>
<PurgeWarning /> <PurgeWarning />
<label className="sr-only" htmlFor="purge-reason"> <label className="visually-hidden" htmlFor="purge-reason">
{i18n.t("reason")} {i18n.t("reason")}
</label> </label>
<input <input
@ -1117,7 +1120,7 @@ export class CommentNode extends Component<CommentNodeProps, CommentNodeState> {
value={this.state.purgeReason} value={this.state.purgeReason}
onInput={linkEvent(this, this.handlePurgeReasonChange)} onInput={linkEvent(this, this.handlePurgeReasonChange)}
/> />
<div className="form-group row col-12"> <div className="mb-3 row col-12">
{this.state.purgeLoading ? ( {this.state.purgeLoading ? (
<Spinner /> <Spinner />
) : ( ) : (
@ -1143,6 +1146,7 @@ export class CommentNode extends Component<CommentNodeProps, CommentNodeState> {
focus focus
allLanguages={this.props.allLanguages} allLanguages={this.props.allLanguages}
siteLanguages={this.props.siteLanguages} siteLanguages={this.props.siteLanguages}
containerClass="comment-comment-container"
onUpsertComment={this.props.onCreateComment} onUpsertComment={this.props.onCreateComment}
/> />
)} )}

View File

@ -70,7 +70,7 @@ export class CommentReport extends Component<
}; };
return ( return (
<div> <div className="comment-report">
<CommentNode <CommentNode
node={node} node={node}
viewType={CommentViewType.Flat} viewType={CommentViewType.Flat}

View File

@ -0,0 +1,128 @@
import { Link } from "inferno-router";
import {
CommunityAggregates,
CommunityId,
SiteAggregates,
} from "lemmy-js-client";
import { i18n } from "../../i18next";
import { numToSI } from "../../utils";
interface BadgesProps {
counts: CommunityAggregates | SiteAggregates;
communityId?: CommunityId;
}
const isCommunityAggregates = (
counts: CommunityAggregates | SiteAggregates
): counts is CommunityAggregates => {
return "subscribers" in counts;
};
const isSiteAggregates = (
counts: CommunityAggregates | SiteAggregates
): counts is SiteAggregates => {
return "communities" in counts;
};
export const Badges = ({ counts, communityId }: BadgesProps) => {
return (
<ul className="badges my-1 list-inline">
<li
className="list-inline-item badge text-bg-secondary pointer"
data-tippy-content={i18n.t("active_users_in_the_last_day", {
count: Number(counts.users_active_day),
formattedCount: numToSI(counts.users_active_day),
})}
>
{i18n.t("number_of_users", {
count: Number(counts.users_active_day),
formattedCount: numToSI(counts.users_active_day),
})}{" "}
/ {i18n.t("day")}
</li>
<li
className="list-inline-item badge text-bg-secondary pointer"
data-tippy-content={i18n.t("active_users_in_the_last_week", {
count: Number(counts.users_active_week),
formattedCount: numToSI(counts.users_active_week),
})}
>
{i18n.t("number_of_users", {
count: Number(counts.users_active_week),
formattedCount: numToSI(counts.users_active_week),
})}{" "}
/ {i18n.t("week")}
</li>
<li
className="list-inline-item badge text-bg-secondary pointer"
data-tippy-content={i18n.t("active_users_in_the_last_month", {
count: Number(counts.users_active_month),
formattedCount: numToSI(counts.users_active_month),
})}
>
{i18n.t("number_of_users", {
count: Number(counts.users_active_month),
formattedCount: numToSI(counts.users_active_month),
})}{" "}
/ {i18n.t("month")}
</li>
<li
className="list-inline-item badge text-bg-secondary pointer"
data-tippy-content={i18n.t("active_users_in_the_last_six_months", {
count: Number(counts.users_active_half_year),
formattedCount: numToSI(counts.users_active_half_year),
})}
>
{i18n.t("number_of_users", {
count: Number(counts.users_active_half_year),
formattedCount: numToSI(counts.users_active_half_year),
})}{" "}
/ {i18n.t("number_of_months", { count: 6, formattedCount: 6 })}
</li>
{isSiteAggregates(counts) && (
<>
<li className="list-inline-item badge text-bg-secondary">
{i18n.t("number_of_users", {
count: Number(counts.users),
formattedCount: numToSI(counts.users),
})}
</li>
<li className="list-inline-item badge text-bg-secondary">
{i18n.t("number_of_communities", {
count: Number(counts.communities),
formattedCount: numToSI(counts.communities),
})}
</li>
</>
)}
{isCommunityAggregates(counts) && (
<li className="list-inline-item badge text-bg-secondary">
{i18n.t("number_of_subscribers", {
count: Number(counts.subscribers),
formattedCount: numToSI(counts.subscribers),
})}
</li>
)}
<li className="list-inline-item badge text-bg-secondary">
{i18n.t("number_of_posts", {
count: Number(counts.posts),
formattedCount: numToSI(counts.posts),
})}
</li>
<li className="list-inline-item badge text-bg-secondary">
{i18n.t("number_of_comments", {
count: Number(counts.comments),
formattedCount: numToSI(counts.comments),
})}
</li>
<li className="list-inline-item">
<Link
className="badge text-bg-primary"
to={`/modlog${communityId ? `/${communityId}` : ""}`}
>
{i18n.t("modlog")}
</Link>
</li>
</ul>
);
};

View File

@ -15,17 +15,19 @@ export class BannerIconHeader extends Component<BannerIconHeaderProps, any> {
const banner = this.props.banner; const banner = this.props.banner;
const icon = this.props.icon; const icon = this.props.icon;
return ( return (
<div className="position-relative mb-2"> (banner || icon) && (
{banner && <PictrsImage src={banner} banner alt="" />} <div className="banner-icon-header position-relative mb-2">
{icon && ( {banner && <PictrsImage src={banner} banner alt="" />}
<PictrsImage {icon && (
src={icon} <PictrsImage
iconOverlay src={icon}
pushup={!!this.props.banner} iconOverlay
alt="" pushup={!!this.props.banner}
/> alt=""
)} />
</div> )}
</div>
)
); );
} }
} }

View File

@ -40,7 +40,7 @@ export class CommentSortSelect extends Component<
name={this.id} name={this.id}
value={this.state.sort} value={this.state.sort}
onChange={linkEvent(this, this.handleSortChange)} onChange={linkEvent(this, this.handleSortChange)}
className="custom-select w-auto mr-2 mb-2" className="sort-select form-select d-inline-block w-auto me-2 mb-2"
aria-label={i18n.t("sort_type")} aria-label={i18n.t("sort_type")}
> >
<option disabled aria-hidden="true"> <option disabled aria-hidden="true">
@ -52,7 +52,7 @@ export class CommentSortSelect extends Component<
<option value={"Old"}>{i18n.t("old")}</option> <option value={"Old"}>{i18n.t("old")}</option>
</select> </select>
<a <a
className="text-muted" className="sort-select-help text-muted"
href={sortingHelpUrl} href={sortingHelpUrl}
rel={relTags} rel={relTags}
title={i18n.t("sorting_help")} title={i18n.t("sorting_help")}

View File

@ -31,7 +31,7 @@ export class DataTypeSelect extends Component<
render() { render() {
return ( return (
<div className="btn-group btn-group-toggle flex-wrap mb-2"> <div className="data-type-select btn-group btn-group-toggle flex-wrap">
<label <label
className={`pointer btn btn-outline-secondary className={`pointer btn btn-outline-secondary
${this.state.type_ == DataType.Post && "active"} ${this.state.type_ == DataType.Post && "active"}
@ -39,6 +39,7 @@ export class DataTypeSelect extends Component<
> >
<input <input
type="radio" type="radio"
className="btn-check"
value={DataType.Post} value={DataType.Post}
checked={this.state.type_ == DataType.Post} checked={this.state.type_ == DataType.Post}
onChange={linkEvent(this, this.handleTypeChange)} onChange={linkEvent(this, this.handleTypeChange)}
@ -52,6 +53,7 @@ export class DataTypeSelect extends Component<
> >
<input <input
type="radio" type="radio"
className="btn-check"
value={DataType.Comment} value={DataType.Comment}
checked={this.state.type_ == DataType.Comment} checked={this.state.type_ == DataType.Comment}
onChange={linkEvent(this, this.handleTypeChange)} onChange={linkEvent(this, this.handleTypeChange)}

View File

@ -25,7 +25,7 @@ export class EmojiPicker extends Component<EmojiPickerProps, EmojiPickerState> {
} }
render() { render() {
return ( return (
<span> <span className="emoji-picker">
<button <button
className="btn btn-sm text-muted" className="btn btn-sm text-muted"
data-tippy-content={i18n.t("emoji")} data-tippy-content={i18n.t("emoji")}

View File

@ -25,7 +25,7 @@ export class Icon extends Component<IconProps, any> {
<use <use
xlinkHref={`/static/assets/symbols.svg#icon-${this.props.icon}`} xlinkHref={`/static/assets/symbols.svg#icon-${this.props.icon}`}
></use> ></use>
<div className="sr-only"> <div className="visually-hidden">
<title>{this.props.icon}</title> <title>{this.props.icon}</title>
</div> </div>
</svg> </svg>
@ -59,8 +59,8 @@ export class PurgeWarning extends Component<any, any> {
render() { render() {
return ( return (
<div className="mt-2 alert alert-danger" role="alert"> <div className="purge-warning mt-2 alert alert-danger" role="alert">
<Icon icon="alert-triangle" classes="icon-inline mr-2" /> <Icon icon="alert-triangle" classes="icon-inline me-2" />
{i18n.t("purge_warning")} {i18n.t("purge_warning")}
</div> </div>
); );

View File

@ -32,7 +32,7 @@ export class ImageUploadForm extends Component<
render() { render() {
return ( return (
<form className="d-inline"> <form className="image-upload-form d-inline">
<label <label
htmlFor={this.id} htmlFor={this.id}
className="pointer text-muted small font-weight-bold" className="pointer text-muted small font-weight-bold"

View File

@ -49,13 +49,13 @@ export class LanguageSelect extends Component<LanguageSelectProps, any> {
return this.props.iconVersion ? ( return this.props.iconVersion ? (
this.selectBtn this.selectBtn
) : ( ) : (
<div> <div className="language-select">
{this.props.multiple && this.props.showLanguageWarning && ( {this.props.multiple && this.props.showLanguageWarning && (
<div className="alert alert-warning" role="alert"> <div className="alert alert-warning" role="alert">
{i18n.t("undetermined_language_warning")} {i18n.t("undetermined_language_warning")}
</div> </div>
)} )}
<div className="form-group row"> <div className="mb-3 row">
<label <label
className={classNames( className={classNames(
"col-form-label", "col-form-label",
@ -73,14 +73,12 @@ export class LanguageSelect extends Component<LanguageSelectProps, any> {
> >
{this.selectBtn} {this.selectBtn}
{this.props.multiple && ( {this.props.multiple && (
<div className="input-group-append"> <button
<button className="btn btn-outline-secondary"
className="input-group-text" onClick={linkEvent(this, this.handleDeselectAll)}
onClick={linkEvent(this, this.handleDeselectAll)} >
> <Icon icon="x" />
<Icon icon="x" /> </button>
</button>
</div>
)} )}
</div> </div>
</div> </div>
@ -100,12 +98,9 @@ export class LanguageSelect extends Component<LanguageSelectProps, any> {
return ( return (
<select <select
className={classNames( className={classNames("form-select w-auto", {
"lang-select-action", "d-inline-block": !this.props.iconVersion,
this.props.iconVersion })}
? "btn btn-sm text-muted"
: "form-control custom-select"
)}
id={this.id} id={this.id}
onChange={linkEvent(this, this.handleLanguageChange)} onChange={linkEvent(this, this.handleLanguageChange)}
aria-label={i18n.t("language_select_placeholder")} aria-label={i18n.t("language_select_placeholder")}

View File

@ -39,7 +39,7 @@ export class ListingTypeSelect extends Component<
render() { render() {
return ( return (
<div className="btn-group btn-group-toggle flex-wrap mb-2"> <div className="listing-type-select btn-group btn-group-toggle flex-wrap">
{this.props.showSubscribed && ( {this.props.showSubscribed && (
<label <label
title={i18n.t("subscribed_description")} title={i18n.t("subscribed_description")}
@ -51,6 +51,7 @@ export class ListingTypeSelect extends Component<
<input <input
id={`${this.id}-subscribed`} id={`${this.id}-subscribed`}
type="radio" type="radio"
className="btn-check"
value={"Subscribed"} value={"Subscribed"}
checked={this.state.type_ == "Subscribed"} checked={this.state.type_ == "Subscribed"}
onChange={linkEvent(this, this.handleTypeChange)} onChange={linkEvent(this, this.handleTypeChange)}
@ -69,6 +70,7 @@ export class ListingTypeSelect extends Component<
<input <input
id={`${this.id}-local`} id={`${this.id}-local`}
type="radio" type="radio"
className="btn-check"
value={"Local"} value={"Local"}
checked={this.state.type_ == "Local"} checked={this.state.type_ == "Local"}
onChange={linkEvent(this, this.handleTypeChange)} onChange={linkEvent(this, this.handleTypeChange)}
@ -86,6 +88,7 @@ export class ListingTypeSelect extends Component<
<input <input
id={`${this.id}-all`} id={`${this.id}-all`}
type="radio" type="radio"
className="btn-check"
value={"All"} value={"All"}
checked={this.state.type_ == "All"} checked={this.state.type_ == "All"}
onChange={linkEvent(this, this.handleTypeChange)} onChange={linkEvent(this, this.handleTypeChange)}

View File

@ -1,4 +1,6 @@
import { isBrowser } from "@utils/browser";
import autosize from "autosize"; import autosize from "autosize";
import classNames from "classnames";
import { NoOptionI18nKeys } from "i18next"; import { NoOptionI18nKeys } from "i18next";
import { Component, linkEvent } from "inferno"; import { Component, linkEvent } from "inferno";
import { Language } from "lemmy-js-client"; import { Language } from "lemmy-js-client";
@ -7,7 +9,6 @@ import { HttpService, UserService } from "../../services";
import { import {
concurrentImageUpload, concurrentImageUpload,
customEmojisLookup, customEmojisLookup,
isBrowser,
markdownFieldCharacterLimit, markdownFieldCharacterLimit,
markdownHelpUrl, markdownHelpUrl,
maxUploadImages, maxUploadImages,
@ -63,8 +64,9 @@ export class MarkdownTextArea extends Component<
MarkdownTextAreaProps, MarkdownTextAreaProps,
MarkdownTextAreaState MarkdownTextAreaState
> { > {
private id = `comment-textarea-${randomStr()}`; private id = `markdown-textarea-${randomStr()}`;
private formId = `comment-form-${randomStr()}`; private formId = `markdown-form-${randomStr()}`;
private tribute: any; private tribute: any;
state: MarkdownTextAreaState = { state: MarkdownTextAreaState = {
@ -134,7 +136,11 @@ export class MarkdownTextArea extends Component<
// message={i18n.t("block_leaving")} // message={i18n.t("block_leaving")}
// /> // />
return ( return (
<form id={this.formId} onSubmit={linkEvent(this, this.handleSubmit)}> <form
className="markdown-textarea"
id={this.formId}
onSubmit={linkEvent(this, this.handleSubmit)}
>
<NavigationPrompt <NavigationPrompt
when={ when={
!this.props.hideNavigationWarnings && !this.props.hideNavigationWarnings &&
@ -142,102 +148,117 @@ export class MarkdownTextArea extends Component<
!this.state.submitted !this.state.submitted
} }
/> />
<div className="form-group row"> <div className="mb-3 row">
<div className={`col-sm-12`}> <div className="col-12">
<textarea <div className="rounded bg-light border">
id={this.id} <div className="d-flex flex-wrap border-bottom">
className={`form-control ${this.state.previewMode && "d-none"}`} {this.getFormatButton("bold", this.handleInsertBold)}
value={this.state.content} {this.getFormatButton("italic", this.handleInsertItalic)}
onInput={linkEvent(this, this.handleContentChange)} {this.getFormatButton("link", this.handleInsertLink)}
onPaste={linkEvent(this, this.handleImageUploadPaste)} <EmojiPicker
onKeyDown={linkEvent(this, this.handleKeyBinds)} onEmojiClick={e => this.handleEmoji(this, e)}
required disabled={this.isDisabled}
disabled={this.isDisabled} ></EmojiPicker>
rows={2} <form className="btn btn-sm text-muted font-weight-bold">
maxLength={this.props.maxLength ?? markdownFieldCharacterLimit} <label
placeholder={this.props.placeholder} htmlFor={`file-upload-${this.id}`}
/> className={`mb-0 ${
{this.state.previewMode && this.state.content && ( UserService.Instance.myUserInfo && "pointer"
<div }`}
className="card border-secondary card-body md-div" data-tippy-content={i18n.t("upload_image")}
dangerouslySetInnerHTML={mdToHtml(this.state.content)} >
/> {this.state.imageUploadStatus ? (
)} <Spinner />
{this.state.imageUploadStatus && ) : (
this.state.imageUploadStatus.total > 1 && ( <Icon icon="image" classes="icon-inline" />
<ProgressBar )}
className="mt-2" </label>
striped <input
animated id={`file-upload-${this.id}`}
value={this.state.imageUploadStatus.uploaded} type="file"
max={this.state.imageUploadStatus.total} accept="image/*,video/*"
text={i18n.t("pictures_uploded_progess", { name="file"
uploaded: this.state.imageUploadStatus.uploaded, className="d-none"
total: this.state.imageUploadStatus.total, multiple
})} disabled={
/> !UserService.Instance.myUserInfo || this.isDisabled
)} }
</div> onChange={linkEvent(this, this.handleImageUpload)}
<label className="sr-only" htmlFor={this.id}> />
{i18n.t("body")} </form>
</label> {this.getFormatButton("header", this.handleInsertHeader)}
</div> {this.getFormatButton(
<div className="row"> "strikethrough",
<div className="col-sm-12 d-flex flex-wrap"> this.handleInsertStrikethrough
{this.getFormatButton("bold", this.handleInsertBold)}
{this.getFormatButton("italic", this.handleInsertItalic)}
{this.getFormatButton("link", this.handleInsertLink)}
<EmojiPicker
onEmojiClick={e => this.handleEmoji(this, e)}
disabled={this.isDisabled}
></EmojiPicker>
<form className="btn btn-sm text-muted font-weight-bold">
<label
htmlFor={`file-upload-${this.id}`}
className={`mb-0 ${
UserService.Instance.myUserInfo && "pointer"
}`}
data-tippy-content={i18n.t("upload_image")}
>
{this.state.imageUploadStatus ? (
<Spinner />
) : (
<Icon icon="image" classes="icon-inline" />
)} )}
{this.getFormatButton("quote", this.handleInsertQuote)}
{this.getFormatButton("list", this.handleInsertList)}
{this.getFormatButton("code", this.handleInsertCode)}
{this.getFormatButton("subscript", this.handleInsertSubscript)}
{this.getFormatButton(
"superscript",
this.handleInsertSuperscript
)}
{this.getFormatButton("spoiler", this.handleInsertSpoiler)}
<a
href={markdownHelpUrl}
className="btn btn-sm text-muted font-weight-bold"
title={i18n.t("formatting_help")}
rel={relTags}
>
<Icon icon="help-circle" classes="icon-inline" />
</a>
</div>
<div>
<textarea
id={this.id}
className={classNames(
"form-control border-0 rounded-top-0 rounded-bottom",
{
"d-none": this.state.previewMode,
}
)}
value={this.state.content}
onInput={linkEvent(this, this.handleContentChange)}
onPaste={linkEvent(this, this.handleImageUploadPaste)}
onKeyDown={linkEvent(this, this.handleKeyBinds)}
required
disabled={this.isDisabled}
rows={2}
maxLength={
this.props.maxLength ?? markdownFieldCharacterLimit
}
placeholder={this.props.placeholder}
/>
{this.state.previewMode && this.state.content && (
<div
className="card border-secondary card-body md-div"
dangerouslySetInnerHTML={mdToHtml(this.state.content)}
/>
)}
{this.state.imageUploadStatus &&
this.state.imageUploadStatus.total > 1 && (
<ProgressBar
className="mt-2"
striped
animated
value={this.state.imageUploadStatus.uploaded}
max={this.state.imageUploadStatus.total}
text={i18n.t("pictures_uploded_progess", {
uploaded: this.state.imageUploadStatus.uploaded,
total: this.state.imageUploadStatus.total,
})}
/>
)}
</div>
<label className="visually-hidden" htmlFor={this.id}>
{i18n.t("body")}
</label> </label>
<input </div>
id={`file-upload-${this.id}`}
type="file"
accept="image/*,video/*"
name="file"
className="d-none"
multiple
disabled={!UserService.Instance.myUserInfo || this.isDisabled}
onChange={linkEvent(this, this.handleImageUpload)}
/>
</form>
{this.getFormatButton("header", this.handleInsertHeader)}
{this.getFormatButton(
"strikethrough",
this.handleInsertStrikethrough
)}
{this.getFormatButton("quote", this.handleInsertQuote)}
{this.getFormatButton("list", this.handleInsertList)}
{this.getFormatButton("code", this.handleInsertCode)}
{this.getFormatButton("subscript", this.handleInsertSubscript)}
{this.getFormatButton("superscript", this.handleInsertSuperscript)}
{this.getFormatButton("spoiler", this.handleInsertSpoiler)}
<a
href={markdownHelpUrl}
className="btn btn-sm text-muted font-weight-bold"
title={i18n.t("formatting_help")}
rel={relTags}
>
<Icon icon="help-circle" classes="icon-inline" />
</a>
</div> </div>
<div className="col-sm-12 d-flex align-items-center flex-wrap"> <div className="col-12 d-flex align-items-center flex-wrap mt-2">
{this.props.showLanguage && ( {this.props.showLanguage && (
<LanguageSelect <LanguageSelect
iconVersion iconVersion
@ -257,7 +278,7 @@ export class MarkdownTextArea extends Component<
{this.props.buttonTitle && ( {this.props.buttonTitle && (
<button <button
type="submit" type="submit"
className="btn btn-sm btn-secondary mr-2" className="btn btn-sm btn-secondary ms-2"
disabled={this.isDisabled} disabled={this.isDisabled}
> >
{this.state.loading ? ( {this.state.loading ? (
@ -270,7 +291,7 @@ export class MarkdownTextArea extends Component<
{this.props.replyType && ( {this.props.replyType && (
<button <button
type="button" type="button"
className="btn btn-sm btn-secondary mr-2" className="btn btn-sm btn-secondary ms-2"
onClick={linkEvent(this, this.handleReplyCancel)} onClick={linkEvent(this, this.handleReplyCancel)}
> >
{i18n.t("cancel")} {i18n.t("cancel")}
@ -278,7 +299,7 @@ export class MarkdownTextArea extends Component<
)} )}
{this.state.content && ( {this.state.content && (
<button <button
className={`btn btn-sm btn-secondary mr-2 ${ className={`btn btn-sm btn-secondary ms-2 ${
this.state.previewMode && "active" this.state.previewMode && "active"
}`} }`}
onClick={linkEvent(this, this.handlePreviewToggle)} onClick={linkEvent(this, this.handlePreviewToggle)}

View File

@ -36,9 +36,9 @@ export class MomentTime extends Component<MomentTimeProps, any> {
return ( return (
<span <span
data-tippy-content={this.createdAndModifiedTimes()} data-tippy-content={this.createdAndModifiedTimes()}
className="font-italics pointer unselectable" className="moment-time font-italics pointer unselectable"
> >
<Icon icon="edit-2" classes="icon-inline mr-1" /> <Icon icon="edit-2" classes="icon-inline me-1" />
{moment.utc(this.props.updated).fromNow(!this.props.showAgo)} {moment.utc(this.props.updated).fromNow(!this.props.showAgo)}
</span> </span>
); );
@ -46,7 +46,7 @@ export class MomentTime extends Component<MomentTimeProps, any> {
const published = this.props.published; const published = this.props.published;
return ( return (
<span <span
className="pointer unselectable" className="moment-time pointer unselectable"
data-tippy-content={this.format(published)} data-tippy-content={this.format(published)}
> >
{moment.utc(published).fromNow(!this.props.showAgo)} {moment.utc(published).fromNow(!this.props.showAgo)}

View File

@ -12,9 +12,9 @@ export class Paginator extends Component<PaginatorProps, any> {
} }
render() { render() {
return ( return (
<div className="my-2"> <div className="paginator my-2">
<button <button
className="btn btn-secondary mr-2" className="btn btn-secondary me-2"
disabled={this.props.page == 1} disabled={this.props.page == 1}
onClick={linkEvent(this, this.handlePrev)} onClick={linkEvent(this, this.handlePrev)}
> >

View File

@ -22,7 +22,7 @@ export class PictrsImage extends Component<PictrsImageProps, any> {
render() { render() {
return ( return (
<picture> <picture className="pictrs-image d-inline-block overflow-hidden">
<source srcSet={this.src("webp")} type="image/webp" /> <source srcSet={this.src("webp")} type="image/webp" />
<source srcSet={this.props.src} /> <source srcSet={this.props.src} />
<source srcSet={this.src("jpg")} type="image/jpeg" /> <source srcSet={this.src("jpg")} type="image/jpeg" />
@ -39,8 +39,8 @@ export class PictrsImage extends Component<PictrsImageProps, any> {
"img-expanded slight-radius": "img-expanded slight-radius":
!this.props.thumbnail && !this.props.icon, !this.props.thumbnail && !this.props.icon,
"img-blur": this.props.thumbnail && this.props.nsfw, "img-blur": this.props.thumbnail && this.props.nsfw,
"rounded-circle img-cover img-icon mr-2": this.props.icon, "rounded-circle img-cover img-icon me-2": this.props.icon,
"ml-2 mb-0 rounded-circle img-cover avatar-overlay": "ms-2 mb-0 rounded-circle img-cover avatar-overlay":
this.props.iconOverlay, this.props.iconOverlay,
"avatar-pushup": this.props.pushup, "avatar-pushup": this.props.pushup,
})} })}

View File

@ -58,7 +58,7 @@ export class RegistrationApplication extends Component<
const accepted = a.creator_local_user.accepted_application; const accepted = a.creator_local_user.accepted_application;
return ( return (
<div> <div className="registration-application">
<div> <div>
{i18n.t("applicant")}: <PersonListing person={a.creator} /> {i18n.t("applicant")}: <PersonListing person={a.creator} />
</div> </div>
@ -96,7 +96,7 @@ export class RegistrationApplication extends Component<
)} )}
{this.state.denyExpanded && ( {this.state.denyExpanded && (
<div className="form-group row"> <div className="mb-3 row">
<label className="col-sm-2 col-form-label"> <label className="col-sm-2 col-form-label">
{i18n.t("deny_reason")} {i18n.t("deny_reason")}
</label> </label>
@ -113,7 +113,7 @@ export class RegistrationApplication extends Component<
)} )}
{(!ra.admin_id || (ra.admin_id && !accepted)) && ( {(!ra.admin_id || (ra.admin_id && !accepted)) && (
<button <button
className="btn btn-secondary mr-2 my-2" className="btn btn-secondary me-2 my-2"
onClick={linkEvent(this, this.handleApprove)} onClick={linkEvent(this, this.handleApprove)}
aria-label={i18n.t("approve")} aria-label={i18n.t("approve")}
> >
@ -122,7 +122,7 @@ export class RegistrationApplication extends Component<
)} )}
{(!ra.admin_id || (ra.admin_id && accepted)) && ( {(!ra.admin_id || (ra.admin_id && accepted)) && (
<button <button
className="btn btn-secondary mr-2" className="btn btn-secondary me-2"
onClick={linkEvent(this, this.handleDeny)} onClick={linkEvent(this, this.handleDeny)}
aria-label={i18n.t("deny")} aria-label={i18n.t("deny")}
> >

View File

@ -102,11 +102,11 @@ export class SearchableSelect extends Component<
const { searchText, selectedIndex, loadingEllipses } = this.state; const { searchText, selectedIndex, loadingEllipses } = this.state;
return ( return (
<div className="dropdown"> <div className="searchable-select dropdown">
<button <button
id={id} id={id}
type="button" type="button"
className="custom-select text-start" className="form-select d-inline-block text-start"
aria-haspopup="listbox" aria-haspopup="listbox"
data-bs-toggle="dropdown" data-bs-toggle="dropdown"
onClick={linkEvent(this, focusSearch)} onClick={linkEvent(this, focusSearch)}

View File

@ -39,7 +39,7 @@ export class SortSelect extends Component<SortSelectProps, SortSelectState> {
name={this.id} name={this.id}
value={this.state.sort} value={this.state.sort}
onChange={linkEvent(this, this.handleSortChange)} onChange={linkEvent(this, this.handleSortChange)}
className="custom-select w-auto mr-2 mb-2" className="sort-select form-select d-inline-block w-auto me-2"
aria-label={i18n.t("sort_type")} aria-label={i18n.t("sort_type")}
> >
<option disabled aria-hidden="true"> <option disabled aria-hidden="true">
@ -73,7 +73,7 @@ export class SortSelect extends Component<SortSelectProps, SortSelectState> {
<option value={"TopAll"}>{i18n.t("top_all")}</option> <option value={"TopAll"}>{i18n.t("top_all")}</option>
</select> </select>
<a <a
className="text-muted" className="sort-select-icon text-muted"
href={sortingHelpUrl} href={sortingHelpUrl}
rel={relTags} rel={relTags}
title={i18n.t("sorting_help")} title={i18n.t("sorting_help")}

View File

@ -1,3 +1,5 @@
import { getQueryParams, getQueryString } from "@utils/helpers";
import type { QueryParams } from "@utils/types";
import { Component, linkEvent } from "inferno"; import { Component, linkEvent } from "inferno";
import { import {
CommunityResponse, CommunityResponse,
@ -11,11 +13,9 @@ import { InitialFetchRequest } from "../../interfaces";
import { FirstLoadService } from "../../services/FirstLoadService"; import { FirstLoadService } from "../../services/FirstLoadService";
import { HttpService, RequestState } from "../../services/HttpService"; import { HttpService, RequestState } from "../../services/HttpService";
import { import {
QueryParams, RouteDataResponse,
editCommunity, editCommunity,
getPageFromString, getPageFromString,
getQueryParams,
getQueryString,
myAuth, myAuth,
myAuthRequired, myAuthRequired,
numToSI, numToSI,
@ -30,6 +30,10 @@ import { CommunityLink } from "./community-link";
const communityLimit = 50; const communityLimit = 50;
type CommunitiesData = RouteDataResponse<{
listCommunitiesResponse: ListCommunitiesResponse;
}>;
interface CommunitiesState { interface CommunitiesState {
listCommunitiesResponse: RequestState<ListCommunitiesResponse>; listCommunitiesResponse: RequestState<ListCommunitiesResponse>;
siteRes: GetSiteResponse; siteRes: GetSiteResponse;
@ -47,7 +51,7 @@ function getListingTypeFromQuery(listingType?: string): ListingType {
} }
export class Communities extends Component<any, CommunitiesState> { export class Communities extends Component<any, CommunitiesState> {
private isoData = setIsoData(this.context); private isoData = setIsoData<CommunitiesData>(this.context);
state: CommunitiesState = { state: CommunitiesState = {
listCommunitiesResponse: { state: "empty" }, listCommunitiesResponse: { state: "empty" },
siteRes: this.isoData.site_res, siteRes: this.isoData.site_res,
@ -62,9 +66,11 @@ export class Communities extends Component<any, CommunitiesState> {
// Only fetch the data if coming from another route // Only fetch the data if coming from another route
if (FirstLoadService.isFirstLoad) { if (FirstLoadService.isFirstLoad) {
const { listCommunitiesResponse } = this.isoData.routeData;
this.state = { this.state = {
...this.state, ...this.state,
listCommunitiesResponse: this.isoData.routeData[0], listCommunitiesResponse,
isIsomorphic: true, isIsomorphic: true,
}; };
} }
@ -106,9 +112,7 @@ export class Communities extends Component<any, CommunitiesState> {
/> />
</span> </span>
</div> </div>
<div className="col-md-6"> <div className="col-md-6">{this.searchForm()}</div>
<div className="float-md-right">{this.searchForm()}</div>
</div>
</div> </div>
<div className="table-responsive"> <div className="table-responsive">
@ -203,7 +207,7 @@ export class Communities extends Component<any, CommunitiesState> {
render() { render() {
return ( return (
<div className="container-lg"> <div className="communities container-lg">
<HtmlTags <HtmlTags
title={this.documentTitle} title={this.documentTitle}
path={this.context.router.route.match.url} path={this.context.router.route.match.url}
@ -216,25 +220,29 @@ export class Communities extends Component<any, CommunitiesState> {
searchForm() { searchForm() {
return ( return (
<form <form
className="form-inline" className="row justify-content-end"
onSubmit={linkEvent(this, this.handleSearchSubmit)} onSubmit={linkEvent(this, this.handleSearchSubmit)}
> >
<input <div className="col-auto">
type="text" <input
id="communities-search" type="text"
className="form-control mr-2 mb-2" id="communities-search"
value={this.state.searchText} className="form-control me-2 mb-2"
placeholder={`${i18n.t("search")}...`} value={this.state.searchText}
onInput={linkEvent(this, this.handleSearchChange)} placeholder={`${i18n.t("search")}...`}
required onInput={linkEvent(this, this.handleSearchChange)}
minLength={3} required
/> minLength={3}
<label className="sr-only" htmlFor="communities-search"> />
{i18n.t("search")} </div>
</label> <div className="col-auto">
<button type="submit" className="btn btn-secondary mr-2 mb-2"> <label className="visually-hidden" htmlFor="communities-search">
<span>{i18n.t("search")}</span> {i18n.t("search")}
</button> </label>
<button type="submit" className="btn btn-secondary mb-2">
<span>{i18n.t("search")}</span>
</button>
</div>
</form> </form>
); );
} }
@ -274,13 +282,13 @@ export class Communities extends Component<any, CommunitiesState> {
i.context.router.history.push(`/search?q=${searchParamEncoded}`); i.context.router.history.push(`/search?q=${searchParamEncoded}`);
} }
static fetchInitialData({ static async fetchInitialData({
query: { listingType, page }, query: { listingType, page },
client, client,
auth, auth,
}: InitialFetchRequest<QueryParams<CommunitiesProps>>): Promise< }: InitialFetchRequest<
RequestState<any> QueryParams<CommunitiesProps>
>[] { >): Promise<CommunitiesData> {
const listCommunitiesForm: ListCommunities = { const listCommunitiesForm: ListCommunities = {
type_: getListingTypeFromQuery(listingType), type_: getListingTypeFromQuery(listingType),
sort: "TopMonth", sort: "TopMonth",
@ -289,7 +297,11 @@ export class Communities extends Component<any, CommunitiesState> {
auth: auth, auth: auth,
}; };
return [client.listCommunities(listCommunitiesForm)]; return {
listCommunitiesResponse: await client.listCommunities(
listCommunitiesForm
),
};
} }
getCommunitiesQueryParams() { getCommunitiesQueryParams() {

View File

@ -85,7 +85,10 @@ export class CommunityForm extends Component<
render() { render() {
return ( return (
<form onSubmit={linkEvent(this, this.handleCreateCommunitySubmit)}> <form
className="community-form"
onSubmit={linkEvent(this, this.handleCreateCommunitySubmit)}
>
<NavigationPrompt <NavigationPrompt
when={ when={
!this.props.loading && !this.props.loading &&
@ -98,14 +101,14 @@ export class CommunityForm extends Component<
} }
/> />
{!this.props.community_view && ( {!this.props.community_view && (
<div className="form-group row"> <div className="mb-3 row">
<label <label
className="col-12 col-sm-2 col-form-label" className="col-12 col-sm-2 col-form-label"
htmlFor="community-name" htmlFor="community-name"
> >
{i18n.t("name")} {i18n.t("name")}
<span <span
className="position-absolute pointer unselectable ml-2 text-muted" className="position-absolute pointer unselectable ms-2 text-muted"
data-tippy-content={i18n.t("name_explain")} data-tippy-content={i18n.t("name_explain")}
> >
<Icon icon="help-circle" classes="icon-inline" /> <Icon icon="help-circle" classes="icon-inline" />
@ -126,14 +129,14 @@ export class CommunityForm extends Component<
</div> </div>
</div> </div>
)} )}
<div className="form-group row"> <div className="mb-3 row">
<label <label
className="col-12 col-sm-2 col-form-label" className="col-12 col-sm-2 col-form-label"
htmlFor="community-title" htmlFor="community-title"
> >
{i18n.t("display_name")} {i18n.t("display_name")}
<span <span
className="position-absolute pointer unselectable ml-2 text-muted" className="position-absolute pointer unselectable ms-2 text-muted"
data-tippy-content={i18n.t("display_name_explain")} data-tippy-content={i18n.t("display_name_explain")}
> >
<Icon icon="help-circle" classes="icon-inline" /> <Icon icon="help-circle" classes="icon-inline" />
@ -152,8 +155,10 @@ export class CommunityForm extends Component<
/> />
</div> </div>
</div> </div>
<div className="form-group row"> <div className="mb-3 row">
<label className="col-12 col-sm-2">{i18n.t("icon")}</label> <label className="col-12 col-sm-2 col-form-label">
{i18n.t("icon")}
</label>
<div className="col-12 col-sm-10"> <div className="col-12 col-sm-10">
<ImageUploadForm <ImageUploadForm
uploadTitle={i18n.t("upload_icon")} uploadTitle={i18n.t("upload_icon")}
@ -164,8 +169,10 @@ export class CommunityForm extends Component<
/> />
</div> </div>
</div> </div>
<div className="form-group row"> <div className="mb-3 row">
<label className="col-12 col-sm-2">{i18n.t("banner")}</label> <label className="col-12 col-sm-2 col-form-label">
{i18n.t("banner")}
</label>
<div className="col-12 col-sm-10"> <div className="col-12 col-sm-10">
<ImageUploadForm <ImageUploadForm
uploadTitle={i18n.t("upload_banner")} uploadTitle={i18n.t("upload_banner")}
@ -175,7 +182,7 @@ export class CommunityForm extends Component<
/> />
</div> </div>
</div> </div>
<div className="form-group row"> <div className="mb-3 row">
<label className="col-12 col-sm-2 col-form-label" htmlFor={this.id}> <label className="col-12 col-sm-2 col-form-label" htmlFor={this.id}>
{i18n.t("sidebar")} {i18n.t("sidebar")}
</label> </label>
@ -192,7 +199,7 @@ export class CommunityForm extends Component<
</div> </div>
{this.props.enableNsfw && ( {this.props.enableNsfw && (
<div className="form-group row"> <div className="mb-3 row">
<legend className="col-form-label col-sm-2 pt-0"> <legend className="col-form-label col-sm-2 pt-0">
{i18n.t("nsfw")} {i18n.t("nsfw")}
</legend> </legend>
@ -209,7 +216,7 @@ export class CommunityForm extends Component<
</div> </div>
</div> </div>
)} )}
<div className="form-group row"> <div className="mb-3 row">
<legend className="col-form-label col-6 pt-0"> <legend className="col-form-label col-6 pt-0">
{i18n.t("only_mods_can_post_in_community")} {i18n.t("only_mods_can_post_in_community")}
</legend> </legend>
@ -236,11 +243,11 @@ export class CommunityForm extends Component<
multiple={true} multiple={true}
onChange={this.handleDiscussionLanguageChange} onChange={this.handleDiscussionLanguageChange}
/> />
<div className="form-group row"> <div className="mb-3 row">
<div className="col-12"> <div className="col-12">
<button <button
type="submit" type="submit"
className="btn btn-secondary mr-2" className="btn btn-secondary me-2"
disabled={this.props.loading} disabled={this.props.loading}
> >
{this.props.loading ? ( {this.props.loading ? (

View File

@ -37,7 +37,7 @@ export class CommunityLink extends Component<CommunityLinkProps, any> {
return !this.props.realLink ? ( return !this.props.realLink ? (
<Link <Link
title={apubName} title={apubName}
className={`${this.props.muted ? "text-muted" : ""}`} className={`community-link ${this.props.muted ? "text-muted" : ""}`}
to={link} to={link}
> >
{this.avatarAndName(displayName)} {this.avatarAndName(displayName)}
@ -45,7 +45,7 @@ export class CommunityLink extends Component<CommunityLinkProps, any> {
) : ( ) : (
<a <a
title={apubName} title={apubName}
className={`${this.props.muted ? "text-muted" : ""}`} className={`community-link ${this.props.muted ? "text-muted" : ""}`}
href={link} href={link}
rel={relTags} rel={relTags}
> >

View File

@ -1,3 +1,5 @@
import { getQueryParams, getQueryString } from "@utils/helpers";
import type { QueryParams } from "@utils/types";
import { Component, linkEvent } from "inferno"; import { Component, linkEvent } from "inferno";
import { RouteComponentProps } from "inferno-router/dist/Route"; import { RouteComponentProps } from "inferno-router/dist/Route";
import { import {
@ -62,7 +64,7 @@ import { UserService } from "../../services";
import { FirstLoadService } from "../../services/FirstLoadService"; import { FirstLoadService } from "../../services/FirstLoadService";
import { HttpService, RequestState } from "../../services/HttpService"; import { HttpService, RequestState } from "../../services/HttpService";
import { import {
QueryParams, RouteDataResponse,
commentsToFlatNodes, commentsToFlatNodes,
communityRSSUrl, communityRSSUrl,
editComment, editComment,
@ -74,8 +76,6 @@ import {
getCommentParentId, getCommentParentId,
getDataTypeString, getDataTypeString,
getPageFromString, getPageFromString,
getQueryParams,
getQueryString,
myAuth, myAuth,
postToCommentSortType, postToCommentSortType,
relTags, relTags,
@ -100,6 +100,12 @@ import { SiteSidebar } from "../home/site-sidebar";
import { PostListings } from "../post/post-listings"; import { PostListings } from "../post/post-listings";
import { CommunityLink } from "./community-link"; import { CommunityLink } from "./community-link";
type CommunityData = RouteDataResponse<{
communityRes: GetCommunityResponse;
postsRes: GetPostsResponse;
commentsRes: GetCommentsResponse;
}>;
interface State { interface State {
communityRes: RequestState<GetCommunityResponse>; communityRes: RequestState<GetCommunityResponse>;
postsRes: RequestState<GetPostsResponse>; postsRes: RequestState<GetPostsResponse>;
@ -140,7 +146,7 @@ export class Community extends Component<
RouteComponentProps<{ name: string }>, RouteComponentProps<{ name: string }>,
State State
> { > {
private isoData = setIsoData(this.context); private isoData = setIsoData<CommunityData>(this.context);
state: State = { state: State = {
communityRes: { state: "empty" }, communityRes: { state: "empty" },
postsRes: { state: "empty" }, postsRes: { state: "empty" },
@ -194,13 +200,14 @@ export class Community extends Component<
// Only fetch the data if coming from another route // Only fetch the data if coming from another route
if (FirstLoadService.isFirstLoad) { if (FirstLoadService.isFirstLoad) {
const [communityRes, postsRes, commentsRes] = this.isoData.routeData; const { communityRes, commentsRes, postsRes } = this.isoData.routeData;
this.state = { this.state = {
...this.state, ...this.state,
isIsomorphic: true,
commentsRes,
communityRes, communityRes,
postsRes, postsRes,
commentsRes,
isIsomorphic: true,
}; };
} }
} }
@ -227,23 +234,21 @@ export class Community extends Component<
saveScrollPosition(this.context); saveScrollPosition(this.context);
} }
static fetchInitialData({ static async fetchInitialData({
client, client,
path, path,
query: { dataType: urlDataType, page: urlPage, sort: urlSort }, query: { dataType: urlDataType, page: urlPage, sort: urlSort },
auth, auth,
}: InitialFetchRequest<QueryParams<CommunityProps>>): Promise< }: InitialFetchRequest<QueryParams<CommunityProps>>): Promise<
RequestState<any> Promise<CommunityData>
>[] { > {
const pathSplit = path.split("/"); const pathSplit = path.split("/");
const promises: Promise<RequestState<any>>[] = [];
const communityName = pathSplit[2]; const communityName = pathSplit[2];
const communityForm: GetCommunity = { const communityForm: GetCommunity = {
name: communityName, name: communityName,
auth, auth,
}; };
promises.push(client.getCommunity(communityForm));
const dataType = getDataTypeFromQuery(urlDataType); const dataType = getDataTypeFromQuery(urlDataType);
@ -251,6 +256,11 @@ export class Community extends Component<
const page = getPageFromString(urlPage); const page = getPageFromString(urlPage);
let postsResponse: RequestState<GetPostsResponse> = { state: "empty" };
let commentsResponse: RequestState<GetCommentsResponse> = {
state: "empty",
};
if (dataType === DataType.Post) { if (dataType === DataType.Post) {
const getPostsForm: GetPosts = { const getPostsForm: GetPosts = {
community_name: communityName, community_name: communityName,
@ -261,8 +271,8 @@ export class Community extends Component<
saved_only: false, saved_only: false,
auth, auth,
}; };
promises.push(client.getPosts(getPostsForm));
promises.push(Promise.resolve({ state: "empty" })); postsResponse = await client.getPosts(getPostsForm);
} else { } else {
const getCommentsForm: GetComments = { const getCommentsForm: GetComments = {
community_name: communityName, community_name: communityName,
@ -273,11 +283,15 @@ export class Community extends Component<
saved_only: false, saved_only: false,
auth, auth,
}; };
promises.push(Promise.resolve({ state: "empty" }));
promises.push(client.getComments(getCommentsForm)); commentsResponse = await client.getComments(getCommentsForm);
} }
return promises; return {
communityRes: await client.getCommunity(communityForm),
commentsRes: commentsResponse,
postsRes: postsResponse,
};
} }
get documentTitle(): string { get documentTitle(): string {
@ -313,7 +327,7 @@ export class Community extends Component<
{this.communityInfo(res)} {this.communityInfo(res)}
<div className="d-block d-md-none"> <div className="d-block d-md-none">
<button <button
className="btn btn-secondary d-inline-block mb-2 mr-3" className="btn btn-secondary d-inline-block mb-2 me-3"
onClick={linkEvent(this, this.handleShowSidebarMobile)} onClick={linkEvent(this, this.handleShowSidebarMobile)}
> >
{i18n.t("sidebar")}{" "} {i18n.t("sidebar")}{" "}
@ -343,7 +357,9 @@ export class Community extends Component<
} }
render() { render() {
return <div className="container-lg">{this.renderCommunity()}</div>; return (
<div className="community container-lg">{this.renderCommunity()}</div>
);
} }
sidebar(res: GetCommunityResponse) { sidebar(res: GetCommunityResponse) {
@ -360,7 +376,6 @@ export class Community extends Component<
community_view={res.community_view} community_view={res.community_view}
moderators={res.moderators} moderators={res.moderators}
admins={site_res.admins} admins={site_res.admins}
online={res.online}
enableNsfw={enableNsfw(site_res)} enableNsfw={enableNsfw(site_res)}
editable editable
allLanguages={site_res.all_languages} allLanguages={site_res.all_languages}
@ -497,13 +512,13 @@ export class Community extends Component<
return ( return (
<div className="mb-3"> <div className="mb-3">
<span className="mr-3"> <span className="me-3">
<DataTypeSelect <DataTypeSelect
type_={dataType} type_={dataType}
onChange={this.handleDataTypeChange} onChange={this.handleDataTypeChange}
/> />
</span> </span>
<span className="mr-2"> <span className="me-2">
<SortSelect sort={sort} onChange={this.handleSortChange} /> <SortSelect sort={sort} onChange={this.handleSortChange} />
</span> </span>
{communityRss && ( {communityRss && (
@ -647,6 +662,12 @@ export class Community extends Component<
const blockCommunityRes = await HttpService.client.blockCommunity(form); const blockCommunityRes = await HttpService.client.blockCommunity(form);
if (blockCommunityRes.state == "success") { if (blockCommunityRes.state == "success") {
updateCommunityBlock(blockCommunityRes.data); updateCommunityBlock(blockCommunityRes.data);
this.setState(s => {
if (s.communityRes.state == "success") {
s.communityRes.data.community_view.blocked =
blockCommunityRes.data.blocked;
}
});
} }
} }

View File

@ -33,7 +33,7 @@ export class CreateCommunity extends Component<any, CreateCommunityState> {
render() { render() {
return ( return (
<div className="container-lg"> <div className="create-community container-lg">
<HtmlTags <HtmlTags
title={this.documentTitle} title={this.documentTitle}
path={this.context.router.route.match.url} path={this.context.router.route.match.url}

View File

@ -1,3 +1,4 @@
import { amAdmin, amMod, amTopMod } from "@utils/roles";
import { Component, InfernoNode, linkEvent } from "inferno"; import { Component, InfernoNode, linkEvent } from "inferno";
import { T } from "inferno-i18next-dess"; import { T } from "inferno-i18next-dess";
import { Link } from "inferno-router"; import { Link } from "inferno-router";
@ -16,16 +17,8 @@ import {
} from "lemmy-js-client"; } from "lemmy-js-client";
import { i18n } from "../../i18next"; import { i18n } from "../../i18next";
import { UserService } from "../../services"; import { UserService } from "../../services";
import { import { getUnixTime, hostname, mdToHtml, myAuthRequired } from "../../utils";
amAdmin, import { Badges } from "../common/badges";
amMod,
amTopMod,
getUnixTime,
hostname,
mdToHtml,
myAuthRequired,
numToSI,
} from "../../utils";
import { BannerIconHeader } from "../common/banner-icon-header"; import { BannerIconHeader } from "../common/banner-icon-header";
import { Icon, PurgeWarning, Spinner } from "../common/icon"; import { Icon, PurgeWarning, Spinner } from "../common/icon";
import { CommunityForm } from "../community/community-form"; import { CommunityForm } from "../community/community-form";
@ -39,7 +32,6 @@ interface SidebarProps {
allLanguages: Language[]; allLanguages: Language[];
siteLanguages: number[]; siteLanguages: number[];
communityLanguages?: number[]; communityLanguages?: number[];
online: number;
enableNsfw?: boolean; enableNsfw?: boolean;
showIcon?: boolean; showIcon?: boolean;
editable?: boolean; editable?: boolean;
@ -64,7 +56,6 @@ interface SidebarState {
removeCommunityLoading: boolean; removeCommunityLoading: boolean;
leaveModTeamLoading: boolean; leaveModTeamLoading: boolean;
followCommunityLoading: boolean; followCommunityLoading: boolean;
blockCommunityLoading: boolean;
purgeCommunityLoading: boolean; purgeCommunityLoading: boolean;
} }
@ -78,7 +69,6 @@ export class Sidebar extends Component<SidebarProps, SidebarState> {
removeCommunityLoading: false, removeCommunityLoading: false,
leaveModTeamLoading: false, leaveModTeamLoading: false,
followCommunityLoading: false, followCommunityLoading: false,
blockCommunityLoading: false,
purgeCommunityLoading: false, purgeCommunityLoading: false,
}; };
@ -105,7 +95,6 @@ export class Sidebar extends Component<SidebarProps, SidebarState> {
removeCommunityLoading: false, removeCommunityLoading: false,
leaveModTeamLoading: false, leaveModTeamLoading: false,
followCommunityLoading: false, followCommunityLoading: false,
blockCommunityLoading: false,
purgeCommunityLoading: false, purgeCommunityLoading: false,
}); });
} }
@ -113,7 +102,7 @@ export class Sidebar extends Component<SidebarProps, SidebarState> {
render() { render() {
return ( return (
<div> <div className="community-sidebar">
{!this.state.showEdit ? ( {!this.state.showEdit ? (
this.sidebar() this.sidebar()
) : ( ) : (
@ -135,37 +124,42 @@ export class Sidebar extends Component<SidebarProps, SidebarState> {
const myUSerInfo = UserService.Instance.myUserInfo; const myUSerInfo = UserService.Instance.myUserInfo;
const { name, actor_id } = this.props.community_view.community; const { name, actor_id } = this.props.community_view.community;
return ( return (
<div> <aside className="mb-3">
<div className="card border-secondary mb-3"> <div id="sidebarContainer">
<div className="card-body"> <section id="sidebarMain" className="card border-secondary mb-3">
{this.communityTitle()} <div className="card-body">
{this.props.editable && this.adminButtons()} {this.communityTitle()}
{myUSerInfo && this.subscribe()} {this.props.editable && this.adminButtons()}
{this.canPost && this.createPost()} {myUSerInfo && this.subscribe()}
{myUSerInfo && this.blockCommunity()} {this.canPost && this.createPost()}
{!myUSerInfo && ( {myUSerInfo && this.blockCommunity()}
<div className="alert alert-info" role="alert"> {!myUSerInfo && (
<T <div className="alert alert-info" role="alert">
i18nKey="community_not_logged_in_alert" <T
interpolation={{ i18nKey="community_not_logged_in_alert"
community: name, interpolation={{
instance: hostname(actor_id), community: name,
}} instance: hostname(actor_id),
> }}
#<code className="user-select-all">#</code># >
</T> #<code className="user-select-all">#</code>#
</div> </T>
)} </div>
</div> )}
</div>
</section>
<section id="sidebarInfo" className="card border-secondary mb-3">
<div className="card-body">
{this.description()}
<Badges
communityId={this.props.community_view.community.id}
counts={this.props.community_view.counts}
/>
{this.mods()}
</div>
</section>
</div> </div>
<div className="card border-secondary mb-3"> </aside>
<div className="card-body">
{this.description()}
{this.badges()}
{this.mods()}
</div>
</div>
</div>
); );
} }
@ -178,19 +172,19 @@ export class Sidebar extends Component<SidebarProps, SidebarState> {
{this.props.showIcon && !community.removed && ( {this.props.showIcon && !community.removed && (
<BannerIconHeader icon={community.icon} banner={community.banner} /> <BannerIconHeader icon={community.icon} banner={community.banner} />
)} )}
<span className="mr-2"> <span className="me-2">
<CommunityLink community={community} hideAvatar /> <CommunityLink community={community} hideAvatar />
</span> </span>
{subscribed === "Subscribed" && ( {subscribed === "Subscribed" && (
<button <button
className="btn btn-secondary btn-sm mr-2" className="btn btn-secondary btn-sm me-2"
onClick={linkEvent(this, this.handleUnfollowCommunity)} onClick={linkEvent(this, this.handleUnfollowCommunity)}
> >
{this.state.followCommunityLoading ? ( {this.state.followCommunityLoading ? (
<Spinner /> <Spinner />
) : ( ) : (
<> <>
<Icon icon="check" classes="icon-inline text-success mr-1" /> <Icon icon="check" classes="icon-inline text-success me-1" />
{i18n.t("joined")} {i18n.t("joined")}
</> </>
)} )}
@ -198,7 +192,7 @@ export class Sidebar extends Component<SidebarProps, SidebarState> {
)} )}
{subscribed === "Pending" && ( {subscribed === "Pending" && (
<button <button
className="btn btn-warning mr-2" className="btn btn-warning me-2"
onClick={linkEvent(this, this.handleUnfollowCommunity)} onClick={linkEvent(this, this.handleUnfollowCommunity)}
> >
{this.state.followCommunityLoading ? ( {this.state.followCommunityLoading ? (
@ -209,17 +203,17 @@ export class Sidebar extends Component<SidebarProps, SidebarState> {
</button> </button>
)} )}
{community.removed && ( {community.removed && (
<small className="mr-2 text-muted font-italic"> <small className="me-2 text-muted font-italic">
{i18n.t("removed")} {i18n.t("removed")}
</small> </small>
)} )}
{community.deleted && ( {community.deleted && (
<small className="mr-2 text-muted font-italic"> <small className="me-2 text-muted font-italic">
{i18n.t("deleted")} {i18n.t("deleted")}
</small> </small>
)} )}
{community.nsfw && ( {community.nsfw && (
<small className="mr-2 text-muted font-italic"> <small className="me-2 text-muted font-italic">
{i18n.t("nsfw")} {i18n.t("nsfw")}
</small> </small>
)} )}
@ -235,99 +229,6 @@ export class Sidebar extends Component<SidebarProps, SidebarState> {
); );
} }
badges() {
const community_view = this.props.community_view;
const counts = community_view.counts;
return (
<ul className="my-1 list-inline">
<li className="list-inline-item badge badge-secondary">
{i18n.t("number_online", {
count: this.props.online,
formattedCount: numToSI(this.props.online),
})}
</li>
<li
className="list-inline-item badge badge-secondary pointer"
data-tippy-content={i18n.t("active_users_in_the_last_day", {
count: Number(counts.users_active_day),
formattedCount: numToSI(counts.users_active_day),
})}
>
{i18n.t("number_of_users", {
count: Number(counts.users_active_day),
formattedCount: numToSI(counts.users_active_day),
})}{" "}
/ {i18n.t("day")}
</li>
<li
className="list-inline-item badge badge-secondary pointer"
data-tippy-content={i18n.t("active_users_in_the_last_week", {
count: Number(counts.users_active_week),
formattedCount: numToSI(counts.users_active_week),
})}
>
{i18n.t("number_of_users", {
count: Number(counts.users_active_week),
formattedCount: numToSI(counts.users_active_week),
})}{" "}
/ {i18n.t("week")}
</li>
<li
className="list-inline-item badge badge-secondary pointer"
data-tippy-content={i18n.t("active_users_in_the_last_month", {
count: Number(counts.users_active_month),
formattedCount: numToSI(counts.users_active_month),
})}
>
{i18n.t("number_of_users", {
count: Number(counts.users_active_month),
formattedCount: numToSI(counts.users_active_month),
})}{" "}
/ {i18n.t("month")}
</li>
<li
className="list-inline-item badge badge-secondary pointer"
data-tippy-content={i18n.t("active_users_in_the_last_six_months", {
count: Number(counts.users_active_half_year),
formattedCount: numToSI(counts.users_active_half_year),
})}
>
{i18n.t("number_of_users", {
count: Number(counts.users_active_half_year),
formattedCount: numToSI(counts.users_active_half_year),
})}{" "}
/ {i18n.t("number_of_months", { count: 6, formattedCount: 6 })}
</li>
<li className="list-inline-item badge badge-secondary">
{i18n.t("number_of_subscribers", {
count: Number(counts.subscribers),
formattedCount: numToSI(counts.subscribers),
})}
</li>
<li className="list-inline-item badge badge-secondary">
{i18n.t("number_of_posts", {
count: Number(counts.posts),
formattedCount: numToSI(counts.posts),
})}
</li>
<li className="list-inline-item badge badge-secondary">
{i18n.t("number_of_comments", {
count: Number(counts.comments),
formattedCount: numToSI(counts.comments),
})}
</li>
<li className="list-inline-item">
<Link
className="badge badge-primary"
to={`/modlog/${this.props.community_view.community.id}`}
>
{i18n.t("modlog")}
</Link>
</li>
</ul>
);
}
mods() { mods() {
return ( return (
<ul className="list-inline small"> <ul className="list-inline small">
@ -345,7 +246,7 @@ export class Sidebar extends Component<SidebarProps, SidebarState> {
const cv = this.props.community_view; const cv = this.props.community_view;
return ( return (
<Link <Link
className={`btn btn-secondary btn-block mb-2 ${ className={`btn btn-secondary d-block mb-2 w-100 ${
cv.community.deleted || cv.community.removed ? "no-click" : "" cv.community.deleted || cv.community.removed ? "no-click" : ""
}`} }`}
to={`/create_post?communityId=${cv.community.id}`} to={`/create_post?communityId=${cv.community.id}`}
@ -358,10 +259,10 @@ export class Sidebar extends Component<SidebarProps, SidebarState> {
subscribe() { subscribe() {
const community_view = this.props.community_view; const community_view = this.props.community_view;
return ( return (
<div className="mb-2"> <>
{community_view.subscribed == "NotSubscribed" && ( {community_view.subscribed == "NotSubscribed" && (
<button <button
className="btn btn-secondary btn-block" className="btn btn-secondary d-block mb-2 w-100"
onClick={linkEvent(this, this.handleFollowCommunity)} onClick={linkEvent(this, this.handleFollowCommunity)}
> >
{this.state.followCommunityLoading ? ( {this.state.followCommunityLoading ? (
@ -371,41 +272,24 @@ export class Sidebar extends Component<SidebarProps, SidebarState> {
)} )}
</button> </button>
)} )}
</div> </>
); );
} }
blockCommunity() { blockCommunity() {
const community_view = this.props.community_view; const { subscribed, blocked } = this.props.community_view;
const blocked = this.props.community_view.blocked;
return ( return (
<div className="mb-2"> <>
{community_view.subscribed == "NotSubscribed" && {subscribed == "NotSubscribed" && (
(blocked ? ( <button
<button className="btn btn-danger d-block mb-2 w-100"
className="btn btn-danger btn-block" onClick={linkEvent(this, this.handleBlockCommunity)}
onClick={linkEvent(this, this.handleBlockCommunity)} >
> {i18n.t(blocked ? "unblock_community" : "block_community")}
{this.state.blockCommunityLoading ? ( </button>
<Spinner /> )}
) : ( </>
i18n.t("unblock_community")
)}
</button>
) : (
<button
className="btn btn-danger btn-block"
onClick={linkEvent(this, this.handleBlockCommunity)}
>
{this.state.blockCommunityLoading ? (
<Spinner />
) : (
i18n.t("block_community")
)}
</button>
))}
</div>
); );
} }
@ -538,25 +422,25 @@ export class Sidebar extends Component<SidebarProps, SidebarState> {
</ul> </ul>
{this.state.showRemoveDialog && ( {this.state.showRemoveDialog && (
<form onSubmit={linkEvent(this, this.handleRemoveCommunity)}> <form onSubmit={linkEvent(this, this.handleRemoveCommunity)}>
<div className="form-group"> <div className="input-group mb-3">
<label className="col-form-label" htmlFor="remove-reason"> <label className="col-form-label" htmlFor="remove-reason">
{i18n.t("reason")} {i18n.t("reason")}
</label> </label>
<input <input
type="text" type="text"
id="remove-reason" id="remove-reason"
className="form-control mr-2" className="form-control me-2"
placeholder={i18n.t("optional")} placeholder={i18n.t("optional")}
value={this.state.removeReason} value={this.state.removeReason}
onInput={linkEvent(this, this.handleModRemoveReasonChange)} onInput={linkEvent(this, this.handleModRemoveReasonChange)}
/> />
</div> </div>
{/* TODO hold off on expires for now */} {/* TODO hold off on expires for now */}
{/* <div class="form-group row"> */} {/* <div class="mb-3 row"> */}
{/* <label class="col-form-label">Expires</label> */} {/* <label class="col-form-label">Expires</label> */}
{/* <input type="date" class="form-control mr-2" placeholder={i18n.t('expires')} value={this.state.removeExpires} onInput={linkEvent(this, this.handleModRemoveExpiresChange)} /> */} {/* <input type="date" class="form-control me-2" placeholder={i18n.t('expires')} value={this.state.removeExpires} onInput={linkEvent(this, this.handleModRemoveExpiresChange)} /> */}
{/* </div> */} {/* </div> */}
<div className="form-group"> <div className="input-group mb-3">
<button type="submit" className="btn btn-secondary"> <button type="submit" className="btn btn-secondary">
{this.state.removeCommunityLoading ? ( {this.state.removeCommunityLoading ? (
<Spinner /> <Spinner />
@ -569,23 +453,23 @@ export class Sidebar extends Component<SidebarProps, SidebarState> {
)} )}
{this.state.showPurgeDialog && ( {this.state.showPurgeDialog && (
<form onSubmit={linkEvent(this, this.handlePurgeCommunity)}> <form onSubmit={linkEvent(this, this.handlePurgeCommunity)}>
<div className="form-group"> <div className="input-group mb-3">
<PurgeWarning /> <PurgeWarning />
</div> </div>
<div className="form-group"> <div className="input-group mb-3">
<label className="sr-only" htmlFor="purge-reason"> <label className="visually-hidden" htmlFor="purge-reason">
{i18n.t("reason")} {i18n.t("reason")}
</label> </label>
<input <input
type="text" type="text"
id="purge-reason" id="purge-reason"
className="form-control mr-2" className="form-control me-2"
placeholder={i18n.t("reason")} placeholder={i18n.t("reason")}
value={this.state.purgeReason} value={this.state.purgeReason}
onInput={linkEvent(this, this.handlePurgeReasonChange)} onInput={linkEvent(this, this.handlePurgeReasonChange)}
/> />
</div> </div>
<div className="form-group"> <div className="input-group mb-3">
{this.state.purgeCommunityLoading ? ( {this.state.purgeCommunityLoading ? (
<Spinner /> <Spinner />
) : ( ) : (
@ -668,10 +552,11 @@ export class Sidebar extends Component<SidebarProps, SidebarState> {
} }
handleBlockCommunity(i: Sidebar) { handleBlockCommunity(i: Sidebar) {
i.setState({ blockCommunityLoading: true }); const { community, blocked } = i.props.community_view;
i.props.onBlockCommunity({ i.props.onBlockCommunity({
community_id: 0, community_id: community.id,
block: !i.props.community_view.blocked, block: !blocked,
auth: myAuthRequired(), auth: myAuthRequired(),
}); });
} }

View File

@ -14,6 +14,7 @@ import { InitialFetchRequest } from "../../interfaces";
import { FirstLoadService } from "../../services/FirstLoadService"; import { FirstLoadService } from "../../services/FirstLoadService";
import { HttpService, RequestState } from "../../services/HttpService"; import { HttpService, RequestState } from "../../services/HttpService";
import { import {
RouteDataResponse,
capitalizeFirstLetter, capitalizeFirstLetter,
fetchThemeList, fetchThemeList,
myAuthRequired, myAuthRequired,
@ -32,6 +33,11 @@ import RateLimitForm from "./rate-limit-form";
import { SiteForm } from "./site-form"; import { SiteForm } from "./site-form";
import { TaglineForm } from "./tagline-form"; import { TaglineForm } from "./tagline-form";
type AdminSettingsData = RouteDataResponse<{
bannedRes: BannedPersonsResponse;
instancesRes: GetFederatedInstancesResponse;
}>;
interface AdminSettingsState { interface AdminSettingsState {
siteRes: GetSiteResponse; siteRes: GetSiteResponse;
banned: PersonView[]; banned: PersonView[];
@ -46,7 +52,7 @@ interface AdminSettingsState {
} }
export class AdminSettings extends Component<any, AdminSettingsState> { export class AdminSettings extends Component<any, AdminSettingsState> {
private isoData = setIsoData(this.context); private isoData = setIsoData<AdminSettingsData>(this.context);
state: AdminSettingsState = { state: AdminSettingsState = {
siteRes: this.isoData.site_res, siteRes: this.isoData.site_res,
banned: [], banned: [],
@ -70,7 +76,8 @@ export class AdminSettings extends Component<any, AdminSettingsState> {
// Only fetch the data if coming from another route // Only fetch the data if coming from another route
if (FirstLoadService.isFirstLoad) { if (FirstLoadService.isFirstLoad) {
const [bannedRes, instancesRes] = this.isoData.routeData; const { bannedRes, instancesRes } = this.isoData.routeData;
this.state = { this.state = {
...this.state, ...this.state,
bannedRes, bannedRes,
@ -80,47 +87,18 @@ export class AdminSettings extends Component<any, AdminSettingsState> {
} }
} }
async fetchData() { static async fetchInitialData({
this.setState({
bannedRes: { state: "loading" },
instancesRes: { state: "loading" },
themeList: [],
loading: true,
});
const auth = myAuthRequired();
const [bannedRes, instancesRes, themeList] = await Promise.all([
HttpService.client.getBannedPersons({ auth }),
HttpService.client.getFederatedInstances({ auth }),
fetchThemeList(),
]);
this.setState({
bannedRes,
instancesRes,
themeList,
loading: false,
});
}
static fetchInitialData({
auth, auth,
client, client,
}: InitialFetchRequest): Promise<any>[] { }: InitialFetchRequest): Promise<AdminSettingsData> {
const promises: Promise<RequestState<any>>[] = []; return {
bannedRes: await client.getBannedPersons({
if (auth) { auth: auth as string,
promises.push(client.getBannedPersons({ auth })); }),
promises.push(client.getFederatedInstances({ auth })); instancesRes: await client.getFederatedInstances({
} else { auth: auth as string,
promises.push( }),
Promise.resolve({ state: "empty" }), };
Promise.resolve({ state: "empty" })
);
}
return promises;
} }
async componentDidMount() { async componentDidMount() {
@ -142,7 +120,7 @@ export class AdminSettings extends Component<any, AdminSettingsState> {
: undefined; : undefined;
return ( return (
<div className="container-lg"> <div className="admin-settings container-lg">
<HtmlTags <HtmlTags
title={this.documentTitle} title={this.documentTitle}
path={this.context.router.route.match.url} path={this.context.router.route.match.url}
@ -218,6 +196,28 @@ export class AdminSettings extends Component<any, AdminSettingsState> {
); );
} }
async fetchData() {
this.setState({
bannedRes: { state: "loading" },
instancesRes: { state: "loading" },
themeList: [],
});
const auth = myAuthRequired();
const [bannedRes, instancesRes, themeList] = await Promise.all([
HttpService.client.getBannedPersons({ auth }),
HttpService.client.getFederatedInstances({ auth }),
fetchThemeList(),
]);
this.setState({
bannedRes,
instancesRes,
themeList,
});
}
admins() { admins() {
return ( return (
<> <>

View File

@ -75,7 +75,7 @@ export class EmojiForm extends Component<EmojiFormProps, EmojiFormState> {
render() { render() {
return ( return (
<div className="col-12"> <div className="home-emojis-form col-12">
<HtmlTags <HtmlTags
title={this.documentTitle} title={this.documentTitle}
path={this.context.router.route.match.url} path={this.context.router.route.match.url}
@ -258,7 +258,7 @@ export class EmojiForm extends Component<EmojiFormProps, EmojiFormState> {
</table> </table>
<br /> <br />
<button <button
className="btn btn-sm btn-secondary mr-2" className="btn btn-sm btn-secondary me-2"
onClick={linkEvent(this, this.handleAddEmojiClick)} onClick={linkEvent(this, this.handleAddEmojiClick)}
> >
{i18n.t("add_custom_emoji")} {i18n.t("add_custom_emoji")}

View File

@ -1,5 +1,8 @@
import { getQueryParams, getQueryString } from "@utils/helpers";
import { canCreateCommunity } from "@utils/roles";
import type { QueryParams } from "@utils/types";
import { NoOptionI18nKeys } from "i18next"; import { NoOptionI18nKeys } from "i18next";
import { Component, linkEvent, MouseEventHandler } from "inferno"; import { Component, MouseEventHandler, linkEvent } from "inferno";
import { T } from "inferno-i18next-dess"; import { T } from "inferno-i18next-dess";
import { Link } from "inferno-router"; import { Link } from "inferno-router";
import { import {
@ -57,7 +60,7 @@ import { UserService } from "../../services";
import { FirstLoadService } from "../../services/FirstLoadService"; import { FirstLoadService } from "../../services/FirstLoadService";
import { HttpService, RequestState } from "../../services/HttpService"; import { HttpService, RequestState } from "../../services/HttpService";
import { import {
canCreateCommunity, RouteDataResponse,
commentsToFlatNodes, commentsToFlatNodes,
editComment, editComment,
editPost, editPost,
@ -68,13 +71,10 @@ import {
getCommentParentId, getCommentParentId,
getDataTypeString, getDataTypeString,
getPageFromString, getPageFromString,
getQueryParams,
getQueryString,
getRandomFromList, getRandomFromList,
mdToHtml, mdToHtml,
myAuth, myAuth,
postToCommentSortType, postToCommentSortType,
QueryParams,
relTags, relTags,
restoreScrollPosition, restoreScrollPosition,
saveScrollPosition, saveScrollPosition,
@ -117,6 +117,45 @@ interface HomeProps {
page: number; page: number;
} }
type HomeData = RouteDataResponse<{
postsRes: GetPostsResponse;
commentsRes: GetCommentsResponse;
trendingCommunitiesRes: ListCommunitiesResponse;
}>;
function getRss(listingType: ListingType) {
const { sort } = getHomeQueryParams();
const auth = myAuth();
let rss: string | undefined = undefined;
switch (listingType) {
case "All": {
rss = `/feeds/all.xml?sort=${sort}`;
break;
}
case "Local": {
rss = `/feeds/local.xml?sort=${sort}`;
break;
}
case "Subscribed": {
rss = auth ? `/feeds/front/${auth}.xml?sort=${sort}` : undefined;
break;
}
}
return (
rss && (
<>
<a href={rss} rel={relTags} title="RSS">
<Icon icon="rss" classes="text-muted small" />
</a>
<link rel="alternate" type="application/atom+xml" href={rss} />
</>
)
);
}
function getDataTypeFromQuery(type?: string): DataType { function getDataTypeFromQuery(type?: string): DataType {
return type ? DataType[type] : DataType.Post; return type ? DataType[type] : DataType.Post;
} }
@ -155,7 +194,7 @@ const MobileButton = ({
onClick: MouseEventHandler<HTMLButtonElement>; onClick: MouseEventHandler<HTMLButtonElement>;
}) => ( }) => (
<button <button
className="btn btn-secondary d-inline-block mb-2 mr-3" className="btn btn-secondary d-inline-block mb-2 me-3"
onClick={onClick} onClick={onClick}
> >
{i18n.t(textKey)}{" "} {i18n.t(textKey)}{" "}
@ -170,13 +209,13 @@ const LinkButton = ({
path: string; path: string;
translationKey: NoOptionI18nKeys; translationKey: NoOptionI18nKeys;
}) => ( }) => (
<Link className="btn btn-secondary btn-block" to={path}> <Link className="btn btn-secondary d-block" to={path}>
{i18n.t(translationKey)} {i18n.t(translationKey)}
</Link> </Link>
); );
export class Home extends Component<any, HomeState> { export class Home extends Component<any, HomeState> {
private isoData = setIsoData(this.context); private isoData = setIsoData<HomeData>(this.context);
state: HomeState = { state: HomeState = {
postsRes: { state: "empty" }, postsRes: { state: "empty" },
commentsRes: { state: "empty" }, commentsRes: { state: "empty" },
@ -228,14 +267,14 @@ export class Home extends Component<any, HomeState> {
// Only fetch the data if coming from another route // Only fetch the data if coming from another route
if (FirstLoadService.isFirstLoad) { if (FirstLoadService.isFirstLoad) {
const [postsRes, commentsRes, trendingCommunitiesRes] = const { trendingCommunitiesRes, commentsRes, postsRes } =
this.isoData.routeData; this.isoData.routeData;
this.state = { this.state = {
...this.state, ...this.state,
postsRes,
commentsRes,
trendingCommunitiesRes, trendingCommunitiesRes,
commentsRes,
postsRes,
tagline: getRandomFromList(this.state?.siteRes?.taglines ?? []) tagline: getRandomFromList(this.state?.siteRes?.taglines ?? [])
?.content, ?.content,
isIsomorphic: true, isIsomorphic: true,
@ -244,7 +283,12 @@ export class Home extends Component<any, HomeState> {
} }
async componentDidMount() { async componentDidMount() {
if (!this.state.isIsomorphic || !this.isoData.routeData.length) { if (
!this.state.isIsomorphic ||
!Object.values(this.isoData.routeData).some(
res => res.state === "success" || res.state === "failed"
)
) {
await Promise.all([this.fetchTrendingCommunities(), this.fetchData()]); await Promise.all([this.fetchTrendingCommunities(), this.fetchData()]);
} }
@ -255,13 +299,11 @@ export class Home extends Component<any, HomeState> {
saveScrollPosition(this.context); saveScrollPosition(this.context);
} }
static fetchInitialData({ static async fetchInitialData({
client, client,
auth, auth,
query: { dataType: urlDataType, listingType, page: urlPage, sort: urlSort }, query: { dataType: urlDataType, listingType, page: urlPage, sort: urlSort },
}: InitialFetchRequest<QueryParams<HomeProps>>): Promise< }: InitialFetchRequest<QueryParams<HomeProps>>): Promise<HomeData> {
RequestState<any>
>[] {
const dataType = getDataTypeFromQuery(urlDataType); const dataType = getDataTypeFromQuery(urlDataType);
// TODO figure out auth default_listingType, default_sort_type // TODO figure out auth default_listingType, default_sort_type
@ -270,7 +312,10 @@ export class Home extends Component<any, HomeState> {
const page = urlPage ? Number(urlPage) : 1; const page = urlPage ? Number(urlPage) : 1;
const promises: Promise<RequestState<any>>[] = []; let postsRes: RequestState<GetPostsResponse> = { state: "empty" };
let commentsRes: RequestState<GetCommentsResponse> = {
state: "empty",
};
if (dataType === DataType.Post) { if (dataType === DataType.Post) {
const getPostsForm: GetPosts = { const getPostsForm: GetPosts = {
@ -282,8 +327,7 @@ export class Home extends Component<any, HomeState> {
auth, auth,
}; };
promises.push(client.getPosts(getPostsForm)); postsRes = await client.getPosts(getPostsForm);
promises.push(Promise.resolve({ state: "empty" }));
} else { } else {
const getCommentsForm: GetComments = { const getCommentsForm: GetComments = {
page, page,
@ -293,8 +337,8 @@ export class Home extends Component<any, HomeState> {
saved_only: false, saved_only: false,
auth, auth,
}; };
promises.push(Promise.resolve({ state: "empty" }));
promises.push(client.getComments(getCommentsForm)); commentsRes = await client.getComments(getCommentsForm);
} }
const trendingCommunitiesForm: ListCommunities = { const trendingCommunitiesForm: ListCommunities = {
@ -303,9 +347,14 @@ export class Home extends Component<any, HomeState> {
limit: trendingFetchLimit, limit: trendingFetchLimit,
auth, auth,
}; };
promises.push(client.listCommunities(trendingCommunitiesForm));
return promises; return {
trendingCommunitiesRes: await client.listCommunities(
trendingCommunitiesForm
),
commentsRes,
postsRes,
};
} }
get documentTitle(): string { get documentTitle(): string {
@ -325,7 +374,7 @@ export class Home extends Component<any, HomeState> {
} = this.state; } = this.state;
return ( return (
<div className="container-lg"> <div className="home container-lg">
<HtmlTags <HtmlTags
title={this.documentTitle} title={this.documentTitle}
path={this.context.router.route.match.url} path={this.context.router.route.match.url}
@ -340,7 +389,7 @@ export class Home extends Component<any, HomeState> {
></div> ></div>
)} )}
<div className="d-block d-md-none">{this.mobileView}</div> <div className="d-block d-md-none">{this.mobileView}</div>
{this.posts()} {this.posts}
</main> </main>
<aside className="d-none d-md-block col-md-4"> <aside className="d-none d-md-block col-md-4">
{this.mySidebar} {this.mySidebar}
@ -361,7 +410,6 @@ export class Home extends Component<any, HomeState> {
siteRes: { siteRes: {
site_view: { counts, site }, site_view: { counts, site },
admins, admins,
online,
}, },
showSubscribedMobile, showSubscribedMobile,
showTrendingMobile, showTrendingMobile,
@ -393,18 +441,18 @@ export class Home extends Component<any, HomeState> {
site={site} site={site}
admins={admins} admins={admins}
counts={counts} counts={counts}
online={online}
showLocal={showLocal(this.isoData)} showLocal={showLocal(this.isoData)}
isMobile={true}
/> />
)} )}
{showTrendingMobile && ( {showTrendingMobile && (
<div className="col-12 card border-secondary mb-3"> <div className="card border-secondary mb-3">
<div className="card-body">{this.trendingCommunities(true)}</div> {this.trendingCommunities()}
</div> </div>
)} )}
{showSubscribedMobile && ( {showSubscribedMobile && (
<div className="col-12 card border-secondary mb-3"> <div className="card border-secondary mb-3">
<div className="card-body">{this.subscribedCommunities}</div> {this.subscribedCommunities(true)}
</div> </div>
)} )}
</div> </div>
@ -417,16 +465,66 @@ export class Home extends Component<any, HomeState> {
siteRes: { siteRes: {
site_view: { counts, site }, site_view: { counts, site },
admins, admins,
online,
}, },
} = this.state; } = this.state;
return ( return (
<div> <div id="sidebarContainer">
<div> <section id="sidebarMain" className="card border-secondary mb-3">
<div className="card border-secondary mb-3"> {this.trendingCommunities()}
</section>
<SiteSidebar
site={site}
admins={admins}
counts={counts}
showLocal={showLocal(this.isoData)}
/>
{this.hasFollows && (
<div className="accordion">
<section
id="sidebarSubscribed"
className="card border-secondary mb-3"
>
{this.subscribedCommunities(false)}
</section>
</div>
)}
</div>
);
}
trendingCommunities() {
switch (this.state.trendingCommunitiesRes?.state) {
case "loading":
return (
<h5>
<Spinner large />
</h5>
);
case "success": {
const trending = this.state.trendingCommunitiesRes.data.communities;
return (
<>
<header className="card-header d-flex align-items-center">
<h5 className="mb-0">
<T i18nKey="trending_communities">
#
<Link className="text-body" to="/communities">
#
</Link>
</T>
</h5>
</header>
<div className="card-body"> <div className="card-body">
{this.trendingCommunities()} {trending.length > 0 && (
<ul className="list-inline">
{trending.map(cv => (
<li key={cv.community.id} className="list-inline-item">
<CommunityLink community={cv.community} />
</li>
))}
</ul>
)}
{canCreateCommunity(this.state.siteRes) && ( {canCreateCommunity(this.state.siteRes) && (
<LinkButton <LinkButton
path="/create_community" path="/create_community"
@ -438,97 +536,71 @@ export class Home extends Component<any, HomeState> {
translationKey="explore_communities" translationKey="explore_communities"
/> />
</div> </div>
</div> </>
<SiteSidebar
site={site}
admins={admins}
counts={counts}
online={online}
showLocal={showLocal(this.isoData)}
/>
{this.hasFollows && (
<div className="card border-secondary mb-3">
<div className="card-body">{this.subscribedCommunities}</div>
</div>
)}
</div>
</div>
);
}
trendingCommunities(isMobile = false) {
switch (this.state.trendingCommunitiesRes?.state) {
case "loading":
return (
<h5>
<Spinner large />
</h5>
);
case "success": {
const trending = this.state.trendingCommunitiesRes.data.communities;
return (
<div className={!isMobile ? "mb-2" : ""}>
<h5>
<T i18nKey="trending_communities">
#
<Link className="text-body" to="/communities">
#
</Link>
</T>
</h5>
<ul className="list-inline mb-0">
{trending.map(cv => (
<li
key={cv.community.id}
className="list-inline-item d-inline-block"
>
<CommunityLink community={cv.community} />
</li>
))}
</ul>
</div>
); );
} }
} }
} }
get subscribedCommunities() { subscribedCommunities(isMobile = false) {
const { subscribedCollapsed } = this.state; const { subscribedCollapsed } = this.state;
return ( return (
<div> <>
<h5> <header
<T class="d-inline" i18nKey="subscribed_to_communities"> className="card-header d-flex align-items-center"
# id="sidebarSubscribedHeader"
<Link className="text-body" to="/communities"> >
<h5 className="mb-0 d-inline">
<T class="d-inline" i18nKey="subscribed_to_communities">
# #
</Link> <Link className="text-body" to="/communities">
</T> #
<button </Link>
className="btn btn-sm text-muted" </T>
onClick={linkEvent(this, this.handleCollapseSubscribe)} </h5>
aria-label={i18n.t("collapse")} {!isMobile && (
data-tippy-content={i18n.t("collapse")} <button
> type="button"
<Icon className="btn btn-sm text-muted"
icon={`${subscribedCollapsed ? "plus" : "minus"}-square`} onClick={linkEvent(this, this.handleCollapseSubscribe)}
classes="icon-inline" aria-label={
/> subscribedCollapsed ? i18n.t("expand") : i18n.t("collapse")
</button> }
</h5> data-tippy-content={
{!subscribedCollapsed && ( subscribedCollapsed ? i18n.t("expand") : i18n.t("collapse")
<ul className="list-inline mb-0"> }
{UserService.Instance.myUserInfo?.follows.map(cfv => ( data-bs-toggle="collapse"
<li data-bs-target="#sidebarSubscribedBody"
key={cfv.community.id} aria-expanded="true"
className="list-inline-item d-inline-block" aria-controls="sidebarSubscribedBody"
> >
<CommunityLink community={cfv.community} /> <Icon
</li> icon={`${subscribedCollapsed ? "plus" : "minus"}-square`}
))} classes="icon-inline"
</ul> />
)} </button>
</div> )}
</header>
<div
id="sidebarSubscribedBody"
className="collapse show"
aria-labelledby="sidebarSubscribedHeader"
>
<div className="card-body">
<ul className="list-inline mb-0">
{UserService.Instance.myUserInfo?.follows.map(cfv => (
<li
key={cfv.community.id}
className="list-inline-item d-inline-block"
>
<CommunityLink community={cfv.community} />
</li>
))}
</ul>
</div>
</div>
</>
); );
} }
@ -555,7 +627,7 @@ export class Home extends Component<any, HomeState> {
await this.fetchData(); await this.fetchData();
} }
posts() { get posts() {
const { page } = getHomeQueryParams(); const { page } = getHomeQueryParams();
return ( return (
@ -574,7 +646,7 @@ export class Home extends Component<any, HomeState> {
const siteRes = this.state.siteRes; const siteRes = this.state.siteRes;
if (dataType === DataType.Post) { if (dataType === DataType.Post) {
switch (this.state.postsRes?.state) { switch (this.state.postsRes.state) {
case "loading": case "loading":
return ( return (
<h5> <h5>
@ -662,62 +734,29 @@ export class Home extends Component<any, HomeState> {
const { listingType, dataType, sort } = getHomeQueryParams(); const { listingType, dataType, sort } = getHomeQueryParams();
return ( return (
<div className="mb-3"> <div className="row align-items-center mb-3 g-3">
<span className="mr-3"> <div className="col-auto">
<DataTypeSelect <DataTypeSelect
type_={dataType} type_={dataType}
onChange={this.handleDataTypeChange} onChange={this.handleDataTypeChange}
/> />
</span> </div>
<span className="mr-3"> <div className="col-auto">
<ListingTypeSelect <ListingTypeSelect
type_={listingType} type_={listingType}
showLocal={showLocal(this.isoData)} showLocal={showLocal(this.isoData)}
showSubscribed showSubscribed
onChange={this.handleListingTypeChange} onChange={this.handleListingTypeChange}
/> />
</span> </div>
<span className="mr-2"> <div className="col-auto">
<SortSelect sort={sort} onChange={this.handleSortChange} /> <SortSelect sort={sort} onChange={this.handleSortChange} />
</span> </div>
{this.getRss(listingType)} <div className="col-auto ps-0">{getRss(listingType)}</div>
</div> </div>
); );
} }
getRss(listingType: ListingType) {
const { sort } = getHomeQueryParams();
const auth = myAuth();
let rss: string | undefined = undefined;
switch (listingType) {
case "All": {
rss = `/feeds/all.xml?sort=${sort}`;
break;
}
case "Local": {
rss = `/feeds/local.xml?sort=${sort}`;
break;
}
case "Subscribed": {
rss = auth ? `/feeds/front/${auth}.xml?sort=${sort}` : undefined;
break;
}
}
return (
rss && (
<>
<a href={rss} rel={relTags} title="RSS">
<Icon icon="rss" classes="text-muted small" />
</a>
<link rel="alternate" type="application/atom+xml" href={rss} />
</>
)
);
}
async fetchTrendingCommunities() { async fetchTrendingCommunities() {
this.setState({ trendingCommunitiesRes: { state: "loading" } }); this.setState({ trendingCommunitiesRes: { state: "loading" } });
this.setState({ this.setState({

View File

@ -8,10 +8,14 @@ import { i18n } from "../../i18next";
import { InitialFetchRequest } from "../../interfaces"; import { InitialFetchRequest } from "../../interfaces";
import { FirstLoadService } from "../../services/FirstLoadService"; import { FirstLoadService } from "../../services/FirstLoadService";
import { HttpService, RequestState } from "../../services/HttpService"; import { HttpService, RequestState } from "../../services/HttpService";
import { relTags, setIsoData } from "../../utils"; import { RouteDataResponse, relTags, setIsoData } from "../../utils";
import { HtmlTags } from "../common/html-tags"; import { HtmlTags } from "../common/html-tags";
import { Spinner } from "../common/icon"; import { Spinner } from "../common/icon";
type InstancesData = RouteDataResponse<{
federatedInstancesResponse: GetFederatedInstancesResponse;
}>;
interface InstancesState { interface InstancesState {
instancesRes: RequestState<GetFederatedInstancesResponse>; instancesRes: RequestState<GetFederatedInstancesResponse>;
siteRes: GetSiteResponse; siteRes: GetSiteResponse;
@ -19,7 +23,7 @@ interface InstancesState {
} }
export class Instances extends Component<any, InstancesState> { export class Instances extends Component<any, InstancesState> {
private isoData = setIsoData(this.context); private isoData = setIsoData<InstancesData>(this.context);
state: InstancesState = { state: InstancesState = {
instancesRes: { state: "empty" }, instancesRes: { state: "empty" },
siteRes: this.isoData.site_res, siteRes: this.isoData.site_res,
@ -33,7 +37,7 @@ export class Instances extends Component<any, InstancesState> {
if (FirstLoadService.isFirstLoad) { if (FirstLoadService.isFirstLoad) {
this.state = { this.state = {
...this.state, ...this.state,
instancesRes: this.isoData.routeData[0], instancesRes: this.isoData.routeData.federatedInstancesResponse,
isIsomorphic: true, isIsomorphic: true,
}; };
} }
@ -55,10 +59,12 @@ export class Instances extends Component<any, InstancesState> {
}); });
} }
static fetchInitialData( static async fetchInitialData({
req: InitialFetchRequest client,
): Promise<RequestState<any>>[] { }: InitialFetchRequest): Promise<InstancesData> {
return [req.client.getFederatedInstances({})]; return {
federatedInstancesResponse: await client.getFederatedInstances({}),
};
} }
get documentTitle(): string { get documentTitle(): string {
@ -103,7 +109,7 @@ export class Instances extends Component<any, InstancesState> {
render() { render() {
return ( return (
<div className="container-lg"> <div className="home-instances container-lg">
<HtmlTags <HtmlTags
title={this.documentTitle} title={this.documentTitle}
path={this.context.router.route.match.url} path={this.context.router.route.match.url}

View File

@ -25,7 +25,7 @@ export class Legal extends Component<any, LegalState> {
render() { render() {
const legal = this.state.siteRes.site_view.local_site.legal_information; const legal = this.state.siteRes.site_view.local_site.legal_information;
return ( return (
<div className="container-lg"> <div className="legal container-lg">
<HtmlTags <HtmlTags
title={this.documentTitle} title={this.documentTitle}
path={this.context.router.route.match.url} path={this.context.router.route.match.url}

View File

@ -1,9 +1,10 @@
import { isBrowser } from "@utils/browser";
import { Component, linkEvent } from "inferno"; import { Component, linkEvent } from "inferno";
import { GetSiteResponse, LoginResponse } from "lemmy-js-client"; import { GetSiteResponse, LoginResponse } from "lemmy-js-client";
import { i18n } from "../../i18next"; import { i18n } from "../../i18next";
import { UserService } from "../../services"; import { UserService } from "../../services";
import { HttpService, RequestState } from "../../services/HttpService"; import { HttpService, RequestState } from "../../services/HttpService";
import { isBrowser, myAuth, setIsoData, toast, validEmail } from "../../utils"; import { myAuth, setIsoData, toast, validEmail } from "../../utils";
import { HtmlTags } from "../common/html-tags"; import { HtmlTags } from "../common/html-tags";
import { Spinner } from "../common/icon"; import { Spinner } from "../common/icon";
@ -49,7 +50,7 @@ export class Login extends Component<any, State> {
render() { render() {
return ( return (
<div className="container-lg"> <div className="login container-lg">
<HtmlTags <HtmlTags
title={this.documentTitle} title={this.documentTitle}
path={this.context.router.route.match.url} path={this.context.router.route.match.url}
@ -66,7 +67,7 @@ export class Login extends Component<any, State> {
<div> <div>
<form onSubmit={linkEvent(this, this.handleLoginSubmit)}> <form onSubmit={linkEvent(this, this.handleLoginSubmit)}>
<h5>{i18n.t("login")}</h5> <h5>{i18n.t("login")}</h5>
<div className="form-group row"> <div className="mb-3 row">
<label <label
className="col-sm-2 col-form-label" className="col-sm-2 col-form-label"
htmlFor="login-email-or-username" htmlFor="login-email-or-username"
@ -86,7 +87,7 @@ export class Login extends Component<any, State> {
/> />
</div> </div>
</div> </div>
<div className="form-group row"> <div className="mb-3 row">
<label className="col-sm-2 col-form-label" htmlFor="login-password"> <label className="col-sm-2 col-form-label" htmlFor="login-password">
{i18n.t("password")} {i18n.t("password")}
</label> </label>
@ -116,7 +117,7 @@ export class Login extends Component<any, State> {
</div> </div>
</div> </div>
{this.state.showTotp && ( {this.state.showTotp && (
<div className="form-group row"> <div className="mb-3 row">
<label <label
className="col-sm-6 col-form-label" className="col-sm-6 col-form-label"
htmlFor="login-totp-token" htmlFor="login-totp-token"
@ -137,7 +138,7 @@ export class Login extends Component<any, State> {
</div> </div>
</div> </div>
)} )}
<div className="form-group row"> <div className="mb-3 row">
<div className="col-sm-10"> <div className="col-sm-10">
<button type="submit" className="btn btn-secondary"> <button type="submit" className="btn btn-secondary">
{this.state.loginRes.state == "loading" ? ( {this.state.loginRes.state == "loading" ? (
@ -172,7 +173,7 @@ export class Login extends Component<any, State> {
toast(i18n.t("enter_two_factor_code"), "info"); toast(i18n.t("enter_two_factor_code"), "info");
} }
i.setState({ loginRes: { state: "empty" } }); i.setState({ loginRes: { state: "failed", msg: loginRes.msg } });
break; break;
} }

View File

@ -51,29 +51,29 @@ function RateLimits({
rateLimitValue, rateLimitValue,
}: RateLimitsProps) { }: RateLimitsProps) {
return ( return (
<div className="form-group row"> <div className="mb-3 row">
<label className="col-12 col-form-label" htmlFor="rate-limit"> <div className="col-md-6">
{i18n.t("rate_limit")} <label htmlFor="rate-limit">{i18n.t("rate_limit")}</label>
</label> <input
<input type="number"
type="number" id="rate-limit"
id="rate-limit" className="form-control"
className="form-control col-12" min={0}
min={0} value={rateLimitValue}
value={rateLimitValue} onInput={handleRateLimit}
onInput={handleRateLimit} />
/> </div>
<label className="col-12 col-form-label" htmlFor="rate-limit-per-second"> <div className="col-md-6">
{i18n.t("per_second")} <label htmlFor="rate-limit-per-second">{i18n.t("per_second")}</label>
</label> <input
<input type="number"
type="number" id="rate-limit-per-second"
id="rate-limit-per-second" className="form-control"
className="form-control col-12" min={0}
min={0} value={rateLimitPerSecondValue}
value={rateLimitPerSecondValue} onInput={handleRateLimitPerSecond}
onInput={handleRateLimitPerSecond} />
/> </div>
</div> </div>
); );
} }
@ -133,7 +133,10 @@ export default class RateLimitsForm extends Component<
render() { render() {
return ( return (
<form onSubmit={linkEvent(this, submitRateLimitForm)}> <form
className="rate-limit-form"
onSubmit={linkEvent(this, submitRateLimitForm)}
>
<h5>{i18n.t("rate_limit_header")}</h5> <h5>{i18n.t("rate_limit_header")}</h5>
<Tabs <Tabs
tabs={rateLimitTypes.map(rateLimitType => ({ tabs={rateLimitTypes.map(rateLimitType => ({
@ -157,20 +160,18 @@ export default class RateLimitsForm extends Component<
), ),
}))} }))}
/> />
<div className="form-group row"> <div className="col-12 mb-3">
<div className="col-12"> <button
<button type="submit"
type="submit" className="btn btn-secondary me-2"
className="btn btn-secondary mr-2" disabled={this.props.loading}
disabled={this.props.loading} >
> {this.props.loading ? (
{this.props.loading ? ( <Spinner />
<Spinner /> ) : (
) : ( capitalizeFirstLetter(i18n.t("save"))
capitalizeFirstLetter(i18n.t("save")) )}
)} </button>
</button>
</div>
</div> </div>
</form> </form>
); );

View File

@ -60,7 +60,7 @@ export class Setup extends Component<any, State> {
render() { render() {
return ( return (
<div className="container-lg"> <div className="home-setup container-lg">
<Helmet title={this.documentTitle} /> <Helmet title={this.documentTitle} />
<div className="row"> <div className="row">
<div className="col-12 offset-lg-3 col-lg-6"> <div className="col-12 offset-lg-3 col-lg-6">
@ -86,7 +86,7 @@ export class Setup extends Component<any, State> {
return ( return (
<form onSubmit={linkEvent(this, this.handleRegisterSubmit)}> <form onSubmit={linkEvent(this, this.handleRegisterSubmit)}>
<h5>{i18n.t("setup_admin")}</h5> <h5>{i18n.t("setup_admin")}</h5>
<div className="form-group row"> <div className="mb-3 row">
<label className="col-sm-2 col-form-label" htmlFor="username"> <label className="col-sm-2 col-form-label" htmlFor="username">
{i18n.t("username")} {i18n.t("username")}
</label> </label>
@ -103,7 +103,7 @@ export class Setup extends Component<any, State> {
/> />
</div> </div>
</div> </div>
<div className="form-group row"> <div className="mb-3 row">
<label className="col-sm-2 col-form-label" htmlFor="email"> <label className="col-sm-2 col-form-label" htmlFor="email">
{i18n.t("email")} {i18n.t("email")}
</label> </label>
@ -120,7 +120,7 @@ export class Setup extends Component<any, State> {
/> />
</div> </div>
</div> </div>
<div className="form-group row"> <div className="mb-3 row">
<label className="col-sm-2 col-form-label" htmlFor="password"> <label className="col-sm-2 col-form-label" htmlFor="password">
{i18n.t("password")} {i18n.t("password")}
</label> </label>
@ -138,7 +138,7 @@ export class Setup extends Component<any, State> {
/> />
</div> </div>
</div> </div>
<div className="form-group row"> <div className="mb-3 row">
<label className="col-sm-2 col-form-label" htmlFor="verify-password"> <label className="col-sm-2 col-form-label" htmlFor="verify-password">
{i18n.t("verify_password")} {i18n.t("verify_password")}
</label> </label>
@ -156,7 +156,7 @@ export class Setup extends Component<any, State> {
/> />
</div> </div>
</div> </div>
<div className="form-group row"> <div className="mb-3 row">
<div className="col-sm-10"> <div className="col-sm-10">
<button type="submit" className="btn btn-secondary"> <button type="submit" className="btn btn-secondary">
{this.state.registerRes.state == "loading" ? ( {this.state.registerRes.state == "loading" ? (

View File

@ -1,3 +1,4 @@
import { isBrowser } from "@utils/browser";
import { Options, passwordStrength } from "check-password-strength"; import { Options, passwordStrength } from "check-password-strength";
import { NoOptionI18nKeys } from "i18next"; import { NoOptionI18nKeys } from "i18next";
import { Component, linkEvent } from "inferno"; import { Component, linkEvent } from "inferno";
@ -13,7 +14,6 @@ import { i18n } from "../../i18next";
import { UserService } from "../../services"; import { UserService } from "../../services";
import { HttpService, RequestState } from "../../services/HttpService"; import { HttpService, RequestState } from "../../services/HttpService";
import { import {
isBrowser,
joinLemmyUrl, joinLemmyUrl,
mdToHtml, mdToHtml,
myAuth, myAuth,
@ -127,7 +127,7 @@ export class Signup extends Component<any, State> {
render() { render() {
return ( return (
<div className="container-lg"> <div className="home-signup container-lg">
<HtmlTags <HtmlTags
title={this.documentTitle} title={this.documentTitle}
path={this.context.router.route.match.url} path={this.context.router.route.match.url}
@ -148,7 +148,7 @@ export class Signup extends Component<any, State> {
<h5>{this.titleName(siteView)}</h5> <h5>{this.titleName(siteView)}</h5>
{this.isLemmyMl && ( {this.isLemmyMl && (
<div className="form-group row"> <div className="mb-3 row">
<div className="mt-2 mb-0 alert alert-warning" role="alert"> <div className="mt-2 mb-0 alert alert-warning" role="alert">
<T i18nKey="lemmy_ml_registration_message"> <T i18nKey="lemmy_ml_registration_message">
#<a href={joinLemmyUrl}>#</a> #<a href={joinLemmyUrl}>#</a>
@ -157,7 +157,7 @@ export class Signup extends Component<any, State> {
</div> </div>
)} )}
<div className="form-group row"> <div className="mb-3 row">
<label <label
className="col-sm-2 col-form-label" className="col-sm-2 col-form-label"
htmlFor="register-username" htmlFor="register-username"
@ -180,7 +180,7 @@ export class Signup extends Component<any, State> {
</div> </div>
</div> </div>
<div className="form-group row"> <div className="mb-3 row">
<label className="col-sm-2 col-form-label" htmlFor="register-email"> <label className="col-sm-2 col-form-label" htmlFor="register-email">
{i18n.t("email")} {i18n.t("email")}
</label> </label>
@ -204,14 +204,14 @@ export class Signup extends Component<any, State> {
this.state.form.email && this.state.form.email &&
!validEmail(this.state.form.email) && ( !validEmail(this.state.form.email) && (
<div className="mt-2 mb-0 alert alert-warning" role="alert"> <div className="mt-2 mb-0 alert alert-warning" role="alert">
<Icon icon="alert-triangle" classes="icon-inline mr-2" /> <Icon icon="alert-triangle" classes="icon-inline me-2" />
{i18n.t("no_password_reset")} {i18n.t("no_password_reset")}
</div> </div>
)} )}
</div> </div>
</div> </div>
<div className="form-group row"> <div className="mb-3 row">
<label <label
className="col-sm-2 col-form-label" className="col-sm-2 col-form-label"
htmlFor="register-password" htmlFor="register-password"
@ -238,7 +238,7 @@ export class Signup extends Component<any, State> {
</div> </div>
</div> </div>
<div className="form-group row"> <div className="mb-3 row">
<label <label
className="col-sm-2 col-form-label" className="col-sm-2 col-form-label"
htmlFor="register-verify-password" htmlFor="register-verify-password"
@ -261,10 +261,10 @@ export class Signup extends Component<any, State> {
{siteView.local_site.registration_mode == "RequireApplication" && ( {siteView.local_site.registration_mode == "RequireApplication" && (
<> <>
<div className="form-group row"> <div className="mb-3 row">
<div className="offset-sm-2 col-sm-10"> <div className="offset-sm-2 col-sm-10">
<div className="mt-2 alert alert-warning" role="alert"> <div className="mt-2 alert alert-warning" role="alert">
<Icon icon="alert-triangle" classes="icon-inline mr-2" /> <Icon icon="alert-triangle" classes="icon-inline me-2" />
{i18n.t("fill_out_application")} {i18n.t("fill_out_application")}
</div> </div>
{siteView.local_site.application_question && ( {siteView.local_site.application_question && (
@ -278,7 +278,7 @@ export class Signup extends Component<any, State> {
</div> </div>
</div> </div>
<div className="form-group row"> <div className="mb-3 row">
<label <label
className="col-sm-2 col-form-label" className="col-sm-2 col-form-label"
htmlFor="application_answer" htmlFor="application_answer"
@ -298,27 +298,22 @@ export class Signup extends Component<any, State> {
</> </>
)} )}
{this.renderCaptcha()} {this.renderCaptcha()}
{siteView.local_site.enable_nsfw && ( <div className="mb-3 row">
<div className="form-group row"> <div className="col-sm-10">
<div className="col-sm-10"> <div className="form-check">
<div className="form-check"> <input
<input className="form-check-input"
className="form-check-input" id="register-show-nsfw"
id="register-show-nsfw" type="checkbox"
type="checkbox" checked={this.state.form.show_nsfw}
checked={this.state.form.show_nsfw} onChange={linkEvent(this, this.handleRegisterShowNsfwChange)}
onChange={linkEvent(this, this.handleRegisterShowNsfwChange)} />
/> <label className="form-check-label" htmlFor="register-show-nsfw">
<label {i18n.t("show_nsfw")}
className="form-check-label" </label>
htmlFor="register-show-nsfw"
>
{i18n.t("show_nsfw")}
</label>
</div>
</div> </div>
</div> </div>
)} </div>
<input <input
tabIndex={-1} tabIndex={-1}
autoComplete="false" autoComplete="false"
@ -329,7 +324,7 @@ export class Signup extends Component<any, State> {
value={this.state.form.honeypot} value={this.state.form.honeypot}
onInput={linkEvent(this, this.handleHoneyPotChange)} onInput={linkEvent(this, this.handleHoneyPotChange)}
/> />
<div className="form-group row"> <div className="mb-3 row">
<div className="col-sm-10"> <div className="col-sm-10">
<button type="submit" className="btn btn-secondary"> <button type="submit" className="btn btn-secondary">
{this.state.registerRes.state == "loading" ? ( {this.state.registerRes.state == "loading" ? (
@ -351,9 +346,9 @@ export class Signup extends Component<any, State> {
case "success": { case "success": {
const res = this.state.captchaRes.data; const res = this.state.captchaRes.data;
return ( return (
<div className="form-group row"> <div className="mb-3 row">
<label className="col-sm-2" htmlFor="register-captcha"> <label className="col-sm-2" htmlFor="register-captcha">
<span className="mr-2">{i18n.t("enter_code")}</span> <span className="me-2">{i18n.t("enter_code")}</span>
<button <button
type="button" type="button"
className="btn btn-secondary" className="btn btn-secondary"
@ -396,7 +391,7 @@ export class Signup extends Component<any, State> {
/> />
{captchaRes.wav && ( {captchaRes.wav && (
<button <button
className="rounded-bottom btn btn-sm btn-secondary btn-block" className="rounded-bottom btn btn-sm btn-secondary d-block"
style="border-top-right-radius: 0; border-top-left-radius: 0;" style="border-top-right-radius: 0; border-top-left-radius: 0;"
title={i18n.t("play_captcha_audio")} title={i18n.t("play_captcha_audio")}
onClick={linkEvent(this, this.handleCaptchaPlay)} onClick={linkEvent(this, this.handleCaptchaPlay)}

View File

@ -81,7 +81,6 @@ export class SiteForm extends Component<SiteFormProps, SiteFormState> {
slur_filter_regex: ls.slur_filter_regex, slur_filter_regex: ls.slur_filter_regex,
actor_name_max_length: ls.actor_name_max_length, actor_name_max_length: ls.actor_name_max_length,
federation_enabled: ls.federation_enabled, federation_enabled: ls.federation_enabled,
federation_debug: ls.federation_debug,
federation_worker_count: ls.federation_worker_count, federation_worker_count: ls.federation_worker_count,
captcha_enabled: ls.captcha_enabled, captcha_enabled: ls.captcha_enabled,
captcha_difficulty: ls.captcha_difficulty, captcha_difficulty: ls.captcha_difficulty,
@ -121,7 +120,10 @@ export class SiteForm extends Component<SiteFormProps, SiteFormState> {
render() { render() {
const siteSetup = this.props.siteRes.site_view.local_site.site_setup; const siteSetup = this.props.siteRes.site_view.local_site.site_setup;
return ( return (
<form onSubmit={linkEvent(this, this.handleSaveSiteSubmit)}> <form
className="site-form"
onSubmit={linkEvent(this, this.handleSaveSiteSubmit)}
>
<NavigationPrompt <NavigationPrompt
when={ when={
!this.props.loading && !this.props.loading &&
@ -140,7 +142,7 @@ export class SiteForm extends Component<SiteFormProps, SiteFormState> {
? capitalizeFirstLetter(i18n.t("edit")) ? capitalizeFirstLetter(i18n.t("edit"))
: capitalizeFirstLetter(i18n.t("setup")) : capitalizeFirstLetter(i18n.t("setup"))
} ${i18n.t("your_site")}`}</h5> } ${i18n.t("your_site")}`}</h5>
<div className="form-group row"> <div className="mb-3 row">
<label className="col-12 col-form-label" htmlFor="create-site-name"> <label className="col-12 col-form-label" htmlFor="create-site-name">
{i18n.t("name")} {i18n.t("name")}
</label> </label>
@ -157,8 +159,8 @@ export class SiteForm extends Component<SiteFormProps, SiteFormState> {
/> />
</div> </div>
</div> </div>
<div className="form-group"> <div className="input-group mb-3">
<label className="mr-2">{i18n.t("icon")}</label> <label className="me-2 col-form-label">{i18n.t("icon")}</label>
<ImageUploadForm <ImageUploadForm
uploadTitle={i18n.t("upload_icon")} uploadTitle={i18n.t("upload_icon")}
imageSrc={this.state.siteForm.icon} imageSrc={this.state.siteForm.icon}
@ -167,8 +169,8 @@ export class SiteForm extends Component<SiteFormProps, SiteFormState> {
rounded rounded
/> />
</div> </div>
<div className="form-group"> <div className="input-group mb-3">
<label className="mr-2">{i18n.t("banner")}</label> <label className="me-2 col-form-label">{i18n.t("banner")}</label>
<ImageUploadForm <ImageUploadForm
uploadTitle={i18n.t("upload_banner")} uploadTitle={i18n.t("upload_banner")}
imageSrc={this.state.siteForm.banner} imageSrc={this.state.siteForm.banner}
@ -176,7 +178,7 @@ export class SiteForm extends Component<SiteFormProps, SiteFormState> {
onRemove={this.handleBannerRemove} onRemove={this.handleBannerRemove}
/> />
</div> </div>
<div className="form-group row"> <div className="mb-3 row">
<label className="col-12 col-form-label" htmlFor="site-desc"> <label className="col-12 col-form-label" htmlFor="site-desc">
{i18n.t("description")} {i18n.t("description")}
</label> </label>
@ -191,7 +193,7 @@ export class SiteForm extends Component<SiteFormProps, SiteFormState> {
/> />
</div> </div>
</div> </div>
<div className="form-group row"> <div className="mb-3 row">
<label className="col-12 col-form-label">{i18n.t("sidebar")}</label> <label className="col-12 col-form-label">{i18n.t("sidebar")}</label>
<div className="col-12"> <div className="col-12">
<MarkdownTextArea <MarkdownTextArea
@ -203,7 +205,7 @@ export class SiteForm extends Component<SiteFormProps, SiteFormState> {
/> />
</div> </div>
</div> </div>
<div className="form-group row"> <div className="mb-3 row">
<label className="col-12 col-form-label"> <label className="col-12 col-form-label">
{i18n.t("legal_information")} {i18n.t("legal_information")}
</label> </label>
@ -217,7 +219,7 @@ export class SiteForm extends Component<SiteFormProps, SiteFormState> {
/> />
</div> </div>
</div> </div>
<div className="form-group row"> <div className="mb-3 row">
<div className="col-12"> <div className="col-12">
<div className="form-check"> <div className="form-check">
<input <input
@ -236,7 +238,7 @@ export class SiteForm extends Component<SiteFormProps, SiteFormState> {
</div> </div>
</div> </div>
</div> </div>
<div className="form-group row"> <div className="mb-3 row">
<div className="col-12"> <div className="col-12">
<div className="form-check"> <div className="form-check">
<input <input
@ -255,10 +257,10 @@ export class SiteForm extends Component<SiteFormProps, SiteFormState> {
</div> </div>
</div> </div>
</div> </div>
<div className="form-group row"> <div className="mb-3 row">
<div className="col-12"> <div className="col-12">
<label <label
className="form-check-label mr-2" className="form-check-label me-2"
htmlFor="create-site-registration-mode" htmlFor="create-site-registration-mode"
> >
{i18n.t("registration_mode")} {i18n.t("registration_mode")}
@ -267,7 +269,7 @@ export class SiteForm extends Component<SiteFormProps, SiteFormState> {
id="create-site-registration-mode" id="create-site-registration-mode"
value={this.state.siteForm.registration_mode} value={this.state.siteForm.registration_mode}
onChange={linkEvent(this, this.handleSiteRegistrationModeChange)} onChange={linkEvent(this, this.handleSiteRegistrationModeChange)}
className="custom-select w-auto" className="form-select d-inline-block w-auto"
> >
<option value={"RequireApplication"}> <option value={"RequireApplication"}>
{i18n.t("require_registration_application")} {i18n.t("require_registration_application")}
@ -278,7 +280,7 @@ export class SiteForm extends Component<SiteFormProps, SiteFormState> {
</div> </div>
</div> </div>
{this.state.siteForm.registration_mode == "RequireApplication" && ( {this.state.siteForm.registration_mode == "RequireApplication" && (
<div className="form-group row"> <div className="mb-3 row">
<label className="col-12 col-form-label"> <label className="col-12 col-form-label">
{i18n.t("application_questionnaire")} {i18n.t("application_questionnaire")}
</label> </label>
@ -293,7 +295,7 @@ export class SiteForm extends Component<SiteFormProps, SiteFormState> {
</div> </div>
</div> </div>
)} )}
<div className="form-group row"> <div className="mb-3 row">
<div className="col-12"> <div className="col-12">
<div className="form-check"> <div className="form-check">
<input <input
@ -315,7 +317,7 @@ export class SiteForm extends Component<SiteFormProps, SiteFormState> {
</div> </div>
</div> </div>
</div> </div>
<div className="form-group row"> <div className="mb-3 row">
<div className="col-12"> <div className="col-12">
<div className="form-check"> <div className="form-check">
<input <input
@ -337,7 +339,7 @@ export class SiteForm extends Component<SiteFormProps, SiteFormState> {
</div> </div>
</div> </div>
</div> </div>
<div className="form-group row"> <div className="mb-3 row">
<div className="col-12"> <div className="col-12">
<div className="form-check"> <div className="form-check">
<input <input
@ -359,7 +361,7 @@ export class SiteForm extends Component<SiteFormProps, SiteFormState> {
</div> </div>
</div> </div>
</div> </div>
<div className="form-group row"> <div className="mb-3 row">
<div className="col-12"> <div className="col-12">
<div className="form-check"> <div className="form-check">
<input <input
@ -378,10 +380,10 @@ export class SiteForm extends Component<SiteFormProps, SiteFormState> {
</div> </div>
</div> </div>
</div> </div>
<div className="form-group row"> <div className="mb-3 row">
<div className="col-12"> <div className="col-12">
<label <label
className="form-check-label mr-2" className="form-check-label me-2"
htmlFor="create-site-default-theme" htmlFor="create-site-default-theme"
> >
{i18n.t("theme")} {i18n.t("theme")}
@ -390,7 +392,7 @@ export class SiteForm extends Component<SiteFormProps, SiteFormState> {
id="create-site-default-theme" id="create-site-default-theme"
value={this.state.siteForm.default_theme} value={this.state.siteForm.default_theme}
onChange={linkEvent(this, this.handleSiteDefaultTheme)} onChange={linkEvent(this, this.handleSiteDefaultTheme)}
className="custom-select w-auto" className="form-select d-inline-block w-auto"
> >
<option value="browser">{i18n.t("browser_default")}</option> <option value="browser">{i18n.t("browser_default")}</option>
{this.props.themeList?.map(theme => ( {this.props.themeList?.map(theme => (
@ -402,8 +404,10 @@ export class SiteForm extends Component<SiteFormProps, SiteFormState> {
</div> </div>
</div> </div>
{this.props.showLocal && ( {this.props.showLocal && (
<form className="form-group row"> <form className="mb-3 row">
<label className="col-sm-3">{i18n.t("listing_type")}</label> <label className="col-sm-3 col-form-label">
{i18n.t("listing_type")}
</label>
<div className="col-sm-9"> <div className="col-sm-9">
<ListingTypeSelect <ListingTypeSelect
type_={this.state.siteForm.default_post_listing_type ?? "Local"} type_={this.state.siteForm.default_post_listing_type ?? "Local"}
@ -414,7 +418,7 @@ export class SiteForm extends Component<SiteFormProps, SiteFormState> {
</div> </div>
</form> </form>
)} )}
<div className="form-group row"> <div className="mb-3 row">
<div className="col-12"> <div className="col-12">
<div className="form-check"> <div className="form-check">
<input <input
@ -433,7 +437,7 @@ export class SiteForm extends Component<SiteFormProps, SiteFormState> {
</div> </div>
</div> </div>
</div> </div>
<div className="form-group row"> <div className="mb-3 row">
<div className="col-12"> <div className="col-12">
<div className="form-check"> <div className="form-check">
<input <input
@ -452,7 +456,7 @@ export class SiteForm extends Component<SiteFormProps, SiteFormState> {
</div> </div>
</div> </div>
</div> </div>
<div className="form-group row"> <div className="mb-3 row">
<label <label
className="col-12 col-form-label" className="col-12 col-form-label"
htmlFor="create-site-slur-filter-regex" htmlFor="create-site-slur-filter-regex"
@ -479,7 +483,7 @@ export class SiteForm extends Component<SiteFormProps, SiteFormState> {
onChange={this.handleDiscussionLanguageChange} onChange={this.handleDiscussionLanguageChange}
showAll showAll
/> />
<div className="form-group row"> <div className="mb-3 row">
<label <label
className="col-12 col-form-label" className="col-12 col-form-label"
htmlFor="create-site-actor-name" htmlFor="create-site-actor-name"
@ -497,7 +501,7 @@ export class SiteForm extends Component<SiteFormProps, SiteFormState> {
/> />
</div> </div>
</div> </div>
<div className="form-group row"> <div className="mb-3 row">
<div className="col-12"> <div className="col-12">
<div className="form-check"> <div className="form-check">
<input <input
@ -518,11 +522,11 @@ export class SiteForm extends Component<SiteFormProps, SiteFormState> {
</div> </div>
{this.state.siteForm.federation_enabled && ( {this.state.siteForm.federation_enabled && (
<> <>
<div className="form-group row"> <div className="mb-3 row">
{this.federatedInstanceSelect("allowed_instances")} {this.federatedInstanceSelect("allowed_instances")}
{this.federatedInstanceSelect("blocked_instances")} {this.federatedInstanceSelect("blocked_instances")}
</div> </div>
<div className="form-group row"> <div className="mb-3 row">
<div className="col-12"> <div className="col-12">
<div className="form-check"> <div className="form-check">
<input <input
@ -541,7 +545,7 @@ export class SiteForm extends Component<SiteFormProps, SiteFormState> {
</div> </div>
</div> </div>
</div> </div>
<div className="form-group row"> <div className="mb-3 row">
<label <label
className="col-12 col-form-label" className="col-12 col-form-label"
htmlFor="create-site-federation-worker-count" htmlFor="create-site-federation-worker-count"
@ -564,7 +568,7 @@ export class SiteForm extends Component<SiteFormProps, SiteFormState> {
</div> </div>
</> </>
)} )}
<div className="form-group row"> <div className="mb-3 row">
<div className="col-12"> <div className="col-12">
<div className="form-check"> <div className="form-check">
<input <input
@ -584,10 +588,10 @@ export class SiteForm extends Component<SiteFormProps, SiteFormState> {
</div> </div>
</div> </div>
{this.state.siteForm.captcha_enabled && ( {this.state.siteForm.captcha_enabled && (
<div className="form-group row"> <div className="mb-3 row">
<div className="col-12"> <div className="col-12">
<label <label
className="form-check-label mr-2" className="form-check-label me-2"
htmlFor="create-site-captcha-difficulty" htmlFor="create-site-captcha-difficulty"
> >
{i18n.t("captcha_difficulty")} {i18n.t("captcha_difficulty")}
@ -596,7 +600,7 @@ export class SiteForm extends Component<SiteFormProps, SiteFormState> {
id="create-site-captcha-difficulty" id="create-site-captcha-difficulty"
value={this.state.siteForm.captcha_difficulty} value={this.state.siteForm.captcha_difficulty}
onChange={linkEvent(this, this.handleSiteCaptchaDifficulty)} onChange={linkEvent(this, this.handleSiteCaptchaDifficulty)}
className="custom-select w-auto" className="form-select d-inline-block w-auto"
> >
<option value="easy">{i18n.t("easy")}</option> <option value="easy">{i18n.t("easy")}</option>
<option value="medium">{i18n.t("medium")}</option> <option value="medium">{i18n.t("medium")}</option>
@ -605,11 +609,11 @@ export class SiteForm extends Component<SiteFormProps, SiteFormState> {
</div> </div>
</div> </div>
)} )}
<div className="form-group row"> <div className="mb-3 row">
<div className="col-12"> <div className="col-12">
<button <button
type="submit" type="submit"
className="btn btn-secondary mr-2" className="btn btn-secondary me-2"
disabled={this.props.loading} disabled={this.props.loading}
> >
{this.props.loading ? ( {this.props.loading ? (
@ -647,7 +651,7 @@ export class SiteForm extends Component<SiteFormProps, SiteFormState> {
/> />
<button <button
type="button" type="button"
className="btn btn-sm bg-success ml-2" className="btn btn-sm bg-success ms-2"
onClick={linkEvent(key, this.handleAddInstance)} onClick={linkEvent(key, this.handleAddInstance)}
style={"width: 2rem; height: 2rem;"} style={"width: 2rem; height: 2rem;"}
tabIndex={ tabIndex={

View File

@ -1,8 +1,8 @@
import { Component, linkEvent } from "inferno"; import { Component, linkEvent } from "inferno";
import { Link } from "inferno-router";
import { PersonView, Site, SiteAggregates } from "lemmy-js-client"; import { PersonView, Site, SiteAggregates } from "lemmy-js-client";
import { i18n } from "../../i18next"; import { i18n } from "../../i18next";
import { mdToHtml, numToSI } from "../../utils"; import { mdToHtml } from "../../utils";
import { Badges } from "../common/badges";
import { BannerIconHeader } from "../common/banner-icon-header"; import { BannerIconHeader } from "../common/banner-icon-header";
import { Icon } from "../common/icon"; import { Icon } from "../common/icon";
import { PersonListing } from "../person/person-listing"; import { PersonListing } from "../person/person-listing";
@ -12,7 +12,7 @@ interface SiteSidebarProps {
showLocal: boolean; showLocal: boolean;
counts?: SiteAggregates; counts?: SiteAggregates;
admins?: PersonView[]; admins?: PersonView[];
online?: number; isMobile?: boolean;
} }
interface SiteSidebarState { interface SiteSidebarState {
@ -30,39 +30,58 @@ export class SiteSidebar extends Component<SiteSidebarProps, SiteSidebarState> {
render() { render() {
return ( return (
<div className="card border-secondary mb-3"> <div className="site-sidebar accordion">
<div className="card-body"> <section id="sidebarInfo" className="card border-secondary mb-3">
<div> <header
<div className="mb-2">{this.siteName()}</div> className="card-header d-flex align-items-center"
id="sidebarInfoHeader"
>
{this.siteName()}
{!this.state.collapsed && ( {!this.state.collapsed && (
<> <BannerIconHeader banner={this.props.site.banner} />
<BannerIconHeader banner={this.props.site.banner} />
{this.siteInfo()}
</>
)} )}
</header>
<div
id="sidebarInfoBody"
className="collapse show"
aria-labelledby="sidebarInfoHeader"
>
<div className="card-body">{this.siteInfo()}</div>
</div> </div>
</div> </section>
</div> </div>
); );
} }
siteName() { siteName() {
return ( return (
<h5 className="mb-0 d-inline"> <>
{this.props.site.name} <h5 className="mb-0 d-inline">{this.props.site.name}</h5>
<button {!this.props.isMobile && (
className="btn btn-sm text-muted" <button
onClick={linkEvent(this, this.handleCollapseSidebar)} type="button"
aria-label={i18n.t("collapse")} className="btn btn-sm"
data-tippy-content={i18n.t("collapse")} onClick={linkEvent(this, this.handleCollapseSidebar)}
> aria-label={
{this.state.collapsed ? ( this.state.collapsed ? i18n.t("expand") : i18n.t("collapse")
<Icon icon="plus-square" classes="icon-inline" /> }
) : ( data-tippy-content={
<Icon icon="minus-square" classes="icon-inline" /> this.state.collapsed ? i18n.t("expand") : i18n.t("collapse")
)} }
</button> data-bs-toggle="collapse"
</h5> data-bs-target="#sidebarInfoBody"
aria-expanded="true"
aria-controls="sidebarInfoBody"
>
{this.state.collapsed ? (
<Icon icon="plus-square" classes="icon-inline" />
) : (
<Icon icon="minus-square" classes="icon-inline" />
)}
</button>
)}
</>
); );
} }
@ -72,7 +91,7 @@ export class SiteSidebar extends Component<SiteSidebarProps, SiteSidebarState> {
<div> <div>
{site.description && <h6>{site.description}</h6>} {site.description && <h6>{site.description}</h6>}
{site.sidebar && this.siteSidebar(site.sidebar)} {site.sidebar && this.siteSidebar(site.sidebar)}
{this.props.counts && this.badges(this.props.counts)} {this.props.counts && <Badges counts={this.props.counts} />}
{this.props.admins && this.admins(this.props.admins)} {this.props.admins && this.admins(this.props.admins)}
</div> </div>
); );
@ -97,102 +116,6 @@ export class SiteSidebar extends Component<SiteSidebarProps, SiteSidebarState> {
); );
} }
badges(siteAggregates: SiteAggregates) {
const counts = siteAggregates;
const online = this.props.online ?? 1;
return (
<ul className="my-2 list-inline">
<li className="list-inline-item badge badge-secondary">
{i18n.t("number_online", {
count: online,
formattedCount: numToSI(online),
})}
</li>
<li
className="list-inline-item badge badge-secondary pointer"
data-tippy-content={i18n.t("active_users_in_the_last_day", {
count: Number(counts.users_active_day),
formattedCount: numToSI(counts.users_active_day),
})}
>
{i18n.t("number_of_users", {
count: Number(counts.users_active_day),
formattedCount: numToSI(counts.users_active_day),
})}{" "}
/ {i18n.t("day")}
</li>
<li
className="list-inline-item badge badge-secondary pointer"
data-tippy-content={i18n.t("active_users_in_the_last_week", {
count: Number(counts.users_active_week),
formattedCount: numToSI(counts.users_active_week),
})}
>
{i18n.t("number_of_users", {
count: Number(counts.users_active_week),
formattedCount: numToSI(counts.users_active_week),
})}{" "}
/ {i18n.t("week")}
</li>
<li
className="list-inline-item badge badge-secondary pointer"
data-tippy-content={i18n.t("active_users_in_the_last_month", {
count: Number(counts.users_active_month),
formattedCount: numToSI(counts.users_active_month),
})}
>
{i18n.t("number_of_users", {
count: Number(counts.users_active_month),
formattedCount: numToSI(counts.users_active_month),
})}{" "}
/ {i18n.t("month")}
</li>
<li
className="list-inline-item badge badge-secondary pointer"
data-tippy-content={i18n.t("active_users_in_the_last_six_months", {
count: Number(counts.users_active_half_year),
formattedCount: numToSI(counts.users_active_half_year),
})}
>
{i18n.t("number_of_users", {
count: Number(counts.users_active_half_year),
formattedCount: numToSI(counts.users_active_half_year),
})}{" "}
/ {i18n.t("number_of_months", { count: 6, formattedCount: 6 })}
</li>
<li className="list-inline-item badge badge-secondary">
{i18n.t("number_of_users", {
count: Number(counts.users),
formattedCount: numToSI(counts.users),
})}
</li>
<li className="list-inline-item badge badge-secondary">
{i18n.t("number_of_communities", {
count: Number(counts.communities),
formattedCount: numToSI(counts.communities),
})}
</li>
<li className="list-inline-item badge badge-secondary">
{i18n.t("number_of_posts", {
count: Number(counts.posts),
formattedCount: numToSI(counts.posts),
})}
</li>
<li className="list-inline-item badge badge-secondary">
{i18n.t("number_of_comments", {
count: Number(counts.comments),
formattedCount: numToSI(counts.comments),
})}
</li>
<li className="list-inline-item">
<Link className="badge badge-primary" to="/modlog">
{i18n.t("modlog")}
</Link>
</li>
</ul>
);
}
handleCollapseSidebar(i: SiteSidebar) { handleCollapseSidebar(i: SiteSidebar) {
i.setState({ collapsed: !i.state.collapsed }); i.setState({ collapsed: !i.state.collapsed });
} }

View File

@ -31,7 +31,7 @@ export class TaglineForm extends Component<TaglineFormProps, TaglineFormState> {
render() { render() {
return ( return (
<div className="col-12"> <div className="tagline-form col-12">
<HtmlTags <HtmlTags
title={this.documentTitle} title={this.documentTitle}
path={this.context.router.route.match.url} path={this.context.router.route.match.url}
@ -89,10 +89,10 @@ export class TaglineForm extends Component<TaglineFormProps, TaglineFormState> {
))} ))}
</tbody> </tbody>
</table> </table>
<div className="form-group row"> <div className="mb-3 row">
<div className="col-12"> <div className="col-12">
<button <button
className="btn btn-sm btn-secondary mr-2" className="btn btn-sm btn-secondary me-2"
onClick={linkEvent(this, this.handleAddTaglineClick)} onClick={linkEvent(this, this.handleAddTaglineClick)}
> >
{i18n.t("add_tagline")} {i18n.t("add_tagline")}
@ -100,11 +100,11 @@ export class TaglineForm extends Component<TaglineFormProps, TaglineFormState> {
</div> </div>
</div> </div>
<div className="form-group row"> <div className="mb-3 row">
<div className="col-12"> <div className="col-12">
<button <button
onClick={linkEvent(this, this.handleSaveClick)} onClick={linkEvent(this, this.handleSaveClick)}
className="btn btn-secondary mr-2" className="btn btn-secondary me-2"
disabled={this.props.loading} disabled={this.props.loading}
> >
{this.props.loading ? ( {this.props.loading ? (

View File

@ -1,3 +1,6 @@
import { debounce, getQueryParams, getQueryString } from "@utils/helpers";
import { amAdmin, amMod } from "@utils/roles";
import type { QueryParams } from "@utils/types";
import { NoOptionI18nKeys } from "i18next"; import { NoOptionI18nKeys } from "i18next";
import { Component, linkEvent } from "inferno"; import { Component, linkEvent } from "inferno";
import { T } from "inferno-i18next-dess"; import { T } from "inferno-i18next-dess";
@ -13,6 +16,7 @@ import {
GetModlog, GetModlog,
GetModlogResponse, GetModlogResponse,
GetPersonDetails, GetPersonDetails,
GetPersonDetailsResponse,
ModAddCommunityView, ModAddCommunityView,
ModAddView, ModAddView,
ModBanFromCommunityView, ModBanFromCommunityView,
@ -33,16 +37,11 @@ import { FirstLoadService } from "../services/FirstLoadService";
import { HttpService, RequestState } from "../services/HttpService"; import { HttpService, RequestState } from "../services/HttpService";
import { import {
Choice, Choice,
QueryParams, RouteDataResponse,
amAdmin,
amMod,
debounce,
fetchLimit, fetchLimit,
fetchUsers, fetchUsers,
getIdFromString, getIdFromString,
getPageFromString, getPageFromString,
getQueryParams,
getQueryString,
getUpdatedSearchId, getUpdatedSearchId,
myAuth, myAuth,
personToChoice, personToChoice,
@ -74,6 +73,13 @@ type View =
| AdminPurgePostView | AdminPurgePostView
| AdminPurgeCommentView; | AdminPurgeCommentView;
type ModlogData = RouteDataResponse<{
res: GetModlogResponse;
communityRes: GetCommunityResponse;
modUserResponse: GetPersonDetailsResponse;
userResponse: GetPersonDetailsResponse;
}>;
interface ModlogType { interface ModlogType {
id: number; id: number;
type_: ModlogActionType; type_: ModlogActionType;
@ -575,8 +581,8 @@ const Filter = ({
options: Choice[]; options: Choice[];
loading: boolean; loading: boolean;
}) => ( }) => (
<div className="col-sm-6 form-group"> <div className="col-sm-6 mb-3">
<label className="col-form-label" htmlFor={`filter-${filterType}`}> <label className="mb-2" htmlFor={`filter-${filterType}`}>
{i18n.t(`filter_by_${filterType}` as NoOptionI18nKeys)} {i18n.t(`filter_by_${filterType}` as NoOptionI18nKeys)}
</label> </label>
<SearchableSelect <SearchableSelect
@ -631,7 +637,7 @@ export class Modlog extends Component<
RouteComponentProps<{ communityId?: string }>, RouteComponentProps<{ communityId?: string }>,
ModlogState ModlogState
> { > {
private isoData = setIsoData(this.context); private isoData = setIsoData<ModlogData>(this.context);
state: ModlogState = { state: ModlogState = {
res: { state: "empty" }, res: { state: "empty" },
@ -653,25 +659,26 @@ export class Modlog extends Component<
// Only fetch the data if coming from another route // Only fetch the data if coming from another route
if (FirstLoadService.isFirstLoad) { if (FirstLoadService.isFirstLoad) {
const [res, communityRes, filteredModRes, filteredUserRes] = const { res, communityRes, modUserResponse, userResponse } =
this.isoData.routeData; this.isoData.routeData;
this.state = { this.state = {
...this.state, ...this.state,
res, res,
communityRes, communityRes,
}; };
if (filteredModRes.state === "success") { if (modUserResponse.state === "success") {
this.state = { this.state = {
...this.state, ...this.state,
modSearchOptions: [personToChoice(filteredModRes.data.person_view)], modSearchOptions: [personToChoice(modUserResponse.data.person_view)],
}; };
} }
if (filteredUserRes.state === "success") { if (userResponse.state === "success") {
this.state = { this.state = {
...this.state, ...this.state,
userSearchOptions: [personToChoice(filteredUserRes.data.person_view)], userSearchOptions: [personToChoice(userResponse.data.person_view)],
}; };
} }
} }
@ -732,7 +739,7 @@ export class Modlog extends Component<
const { actionType, modId, userId } = getModlogQueryParams(); const { actionType, modId, userId } = getModlogQueryParams();
return ( return (
<div className="container-lg"> <div className="modlog container-lg">
<HtmlTags <HtmlTags
title={this.documentTitle} title={this.documentTitle}
path={this.context.router.route.match.url} path={this.context.router.route.match.url}
@ -746,7 +753,7 @@ export class Modlog extends Component<
<Icon <Icon
icon="alert-triangle" icon="alert-triangle"
inline inline
classes="mr-sm-2 mx-auto d-sm-inline d-block" classes="me-sm-2 mx-auto d-sm-inline d-block"
/> />
<T i18nKey="modlog_content_warning" class="d-inline"> <T i18nKey="modlog_content_warning" class="d-inline">
#<strong>#</strong># #<strong>#</strong>#
@ -763,34 +770,40 @@ export class Modlog extends Component<
<span>{i18n.t("modlog")}</span> <span>{i18n.t("modlog")}</span>
</h5> </h5>
)} )}
<div className="form-row"> <div className="row mb-2">
<select <div className="col-sm-6">
value={actionType} <select
onChange={linkEvent(this, this.handleFilterActionChange)} value={actionType}
className="custom-select col-sm-6" onChange={linkEvent(this, this.handleFilterActionChange)}
aria-label="action" className="form-select"
> aria-label="action"
<option disabled aria-hidden="true"> >
{i18n.t("filter_by_action")} <option disabled aria-hidden="true">
</option> {i18n.t("filter_by_action")}
<option value={"All"}>{i18n.t("all")}</option> </option>
<option value={"ModRemovePost"}>Removing Posts</option> <option value={"All"}>{i18n.t("all")}</option>
<option value={"ModLockPost"}>Locking Posts</option> <option value={"ModRemovePost"}>Removing Posts</option>
<option value={"ModFeaturePost"}>Featuring Posts</option> <option value={"ModLockPost"}>Locking Posts</option>
<option value={"ModRemoveComment"}>Removing Comments</option> <option value={"ModFeaturePost"}>Featuring Posts</option>
<option value={"ModRemoveCommunity"}>Removing Communities</option> <option value={"ModRemoveComment"}>Removing Comments</option>
<option value={"ModBanFromCommunity"}> <option value={"ModRemoveCommunity"}>
Banning From Communities Removing Communities
</option> </option>
<option value={"ModAddCommunity"}>Adding Mod to Community</option> <option value={"ModBanFromCommunity"}>
<option value={"ModTransferCommunity"}> Banning From Communities
Transferring Communities </option>
</option> <option value={"ModAddCommunity"}>
<option value={"ModAdd"}>Adding Mod to Site</option> Adding Mod to Community
<option value={"ModBan"}>Banning From Site</option> </option>
</select> <option value={"ModTransferCommunity"}>
Transferring Communities
</option>
<option value={"ModAdd"}>Adding Mod to Site</option>
<option value={"ModBan"}>Banning From Site</option>
</select>
</div>
</div> </div>
<div className="form-row mb-2"> <div className="row mb-2">
<Filter <Filter
filterType="user" filterType="user"
onChange={this.handleUserChange} onChange={this.handleUserChange}
@ -958,17 +971,14 @@ export class Modlog extends Component<
} }
} }
static fetchInitialData({ static async fetchInitialData({
client, client,
path, path,
query: { modId: urlModId, page, userId: urlUserId, actionType }, query: { modId: urlModId, page, userId: urlUserId, actionType },
auth, auth,
site, site,
}: InitialFetchRequest<QueryParams<ModlogProps>>): Promise< }: InitialFetchRequest<QueryParams<ModlogProps>>): Promise<ModlogData> {
RequestState<any>
>[] {
const pathSplit = path.split("/"); const pathSplit = path.split("/");
const promises: Promise<RequestState<any>>[] = [];
const communityId = getIdFromString(pathSplit[2]); const communityId = getIdFromString(pathSplit[2]);
const modId = !site.site_view.local_site.hide_modlog_mod_names const modId = !site.site_view.local_site.hide_modlog_mod_names
? getIdFromString(urlModId) ? getIdFromString(urlModId)
@ -985,40 +995,50 @@ export class Modlog extends Component<
auth, auth,
}; };
promises.push(client.getModlog(modlogForm)); let communityResponse: RequestState<GetCommunityResponse> = {
state: "empty",
};
if (communityId) { if (communityId) {
const communityForm: GetCommunity = { const communityForm: GetCommunity = {
id: communityId, id: communityId,
auth, auth,
}; };
promises.push(client.getCommunity(communityForm));
} else { communityResponse = await client.getCommunity(communityForm);
promises.push(Promise.resolve({ state: "empty" }));
} }
let modUserResponse: RequestState<GetPersonDetailsResponse> = {
state: "empty",
};
if (modId) { if (modId) {
const getPersonForm: GetPersonDetails = { const getPersonForm: GetPersonDetails = {
person_id: modId, person_id: modId,
auth, auth,
}; };
promises.push(client.getPersonDetails(getPersonForm)); modUserResponse = await client.getPersonDetails(getPersonForm);
} else {
promises.push(Promise.resolve({ state: "empty" }));
} }
let userResponse: RequestState<GetPersonDetailsResponse> = {
state: "empty",
};
if (userId) { if (userId) {
const getPersonForm: GetPersonDetails = { const getPersonForm: GetPersonDetails = {
person_id: userId, person_id: userId,
auth, auth,
}; };
promises.push(client.getPersonDetails(getPersonForm)); userResponse = await client.getPersonDetails(getPersonForm);
} else {
promises.push(Promise.resolve({ state: "empty" }));
} }
return promises; return {
res: await client.getModlog(modlogForm),
communityRes: communityResponse,
modUserResponse,
userResponse,
};
} }
} }

View File

@ -10,7 +10,7 @@ export class CakeDay extends Component<CakeDayProps, any> {
render() { render() {
return ( return (
<div <div
className={`mx-2 d-inline-block unselectable pointer`} className={`cake-day mx-2 d-inline-block unselectable pointer`}
data-tippy-content={this.cakeDayTippy()} data-tippy-content={this.cakeDayTippy()}
> >
<Icon icon="cake" classes="icon-inline" /> <Icon icon="cake" classes="icon-inline" />

View File

@ -24,10 +24,7 @@ import {
DistinguishComment, DistinguishComment,
EditComment, EditComment,
EditPrivateMessage, EditPrivateMessage,
GetPersonMentions,
GetPersonMentionsResponse, GetPersonMentionsResponse,
GetPrivateMessages,
GetReplies,
GetRepliesResponse, GetRepliesResponse,
GetSiteResponse, GetSiteResponse,
MarkCommentReplyAsRead, MarkCommentReplyAsRead,
@ -53,6 +50,7 @@ import { UserService } from "../../services";
import { FirstLoadService } from "../../services/FirstLoadService"; import { FirstLoadService } from "../../services/FirstLoadService";
import { HttpService, RequestState } from "../../services/HttpService"; import { HttpService, RequestState } from "../../services/HttpService";
import { import {
RouteDataResponse,
commentsToFlatNodes, commentsToFlatNodes,
editCommentReply, editCommentReply,
editMention, editMention,
@ -92,6 +90,13 @@ enum ReplyEnum {
Mention, Mention,
Message, Message,
} }
type InboxData = RouteDataResponse<{
repliesRes: GetRepliesResponse;
mentionsRes: GetPersonMentionsResponse;
messagesRes: PrivateMessagesResponse;
}>;
type ReplyType = { type ReplyType = {
id: number; id: number;
type_: ReplyEnum; type_: ReplyEnum;
@ -114,7 +119,7 @@ interface InboxState {
} }
export class Inbox extends Component<any, InboxState> { export class Inbox extends Component<any, InboxState> {
private isoData = setIsoData(this.context); private isoData = setIsoData<InboxData>(this.context);
state: InboxState = { state: InboxState = {
unreadOrAll: UnreadOrAll.Unread, unreadOrAll: UnreadOrAll.Unread,
messageType: MessageType.All, messageType: MessageType.All,
@ -162,7 +167,7 @@ export class Inbox extends Component<any, InboxState> {
// Only fetch the data if coming from another route // Only fetch the data if coming from another route
if (FirstLoadService.isFirstLoad) { if (FirstLoadService.isFirstLoad) {
const [repliesRes, mentionsRes, messagesRes] = this.isoData.routeData; const { mentionsRes, messagesRes, repliesRes } = this.isoData.routeData;
this.state = { this.state = {
...this.state, ...this.state,
@ -211,7 +216,7 @@ export class Inbox extends Component<any, InboxState> {
const auth = myAuth(); const auth = myAuth();
const inboxRss = auth ? `/feeds/inbox/${auth}.xml` : undefined; const inboxRss = auth ? `/feeds/inbox/${auth}.xml` : undefined;
return ( return (
<div className="container-lg"> <div className="inbox container-lg">
<div className="row"> <div className="row">
<div className="col-12"> <div className="col-12">
<HtmlTags <HtmlTags
@ -223,7 +228,7 @@ export class Inbox extends Component<any, InboxState> {
{inboxRss && ( {inboxRss && (
<small> <small>
<a href={inboxRss} title="RSS" rel={relTags}> <a href={inboxRss} title="RSS" rel={relTags}>
<Icon icon="rss" classes="ml-2 text-muted small" /> <Icon icon="rss" classes="ms-2 text-muted small" />
</a> </a>
<link <link
rel="alternate" rel="alternate"
@ -287,6 +292,7 @@ export class Inbox extends Component<any, InboxState> {
> >
<input <input
type="radio" type="radio"
className="btn-check"
value={UnreadOrAll.Unread} value={UnreadOrAll.Unread}
checked={this.state.unreadOrAll == UnreadOrAll.Unread} checked={this.state.unreadOrAll == UnreadOrAll.Unread}
onChange={linkEvent(this, this.handleUnreadOrAllChange)} onChange={linkEvent(this, this.handleUnreadOrAllChange)}
@ -300,6 +306,7 @@ export class Inbox extends Component<any, InboxState> {
> >
<input <input
type="radio" type="radio"
className="btn-check"
value={UnreadOrAll.All} value={UnreadOrAll.All}
checked={this.state.unreadOrAll == UnreadOrAll.All} checked={this.state.unreadOrAll == UnreadOrAll.All}
onChange={linkEvent(this, this.handleUnreadOrAllChange)} onChange={linkEvent(this, this.handleUnreadOrAllChange)}
@ -320,6 +327,7 @@ export class Inbox extends Component<any, InboxState> {
> >
<input <input
type="radio" type="radio"
className="btn-check"
value={MessageType.All} value={MessageType.All}
checked={this.state.messageType == MessageType.All} checked={this.state.messageType == MessageType.All}
onChange={linkEvent(this, this.handleMessageTypeChange)} onChange={linkEvent(this, this.handleMessageTypeChange)}
@ -333,6 +341,7 @@ export class Inbox extends Component<any, InboxState> {
> >
<input <input
type="radio" type="radio"
className="btn-check"
value={MessageType.Replies} value={MessageType.Replies}
checked={this.state.messageType == MessageType.Replies} checked={this.state.messageType == MessageType.Replies}
onChange={linkEvent(this, this.handleMessageTypeChange)} onChange={linkEvent(this, this.handleMessageTypeChange)}
@ -346,6 +355,7 @@ export class Inbox extends Component<any, InboxState> {
> >
<input <input
type="radio" type="radio"
className="btn-check"
value={MessageType.Mentions} value={MessageType.Mentions}
checked={this.state.messageType == MessageType.Mentions} checked={this.state.messageType == MessageType.Mentions}
onChange={linkEvent(this, this.handleMessageTypeChange)} onChange={linkEvent(this, this.handleMessageTypeChange)}
@ -359,6 +369,7 @@ export class Inbox extends Component<any, InboxState> {
> >
<input <input
type="radio" type="radio"
className="btn-check"
value={MessageType.Messages} value={MessageType.Messages}
checked={this.state.messageType == MessageType.Messages} checked={this.state.messageType == MessageType.Messages}
onChange={linkEvent(this, this.handleMessageTypeChange)} onChange={linkEvent(this, this.handleMessageTypeChange)}
@ -372,8 +383,8 @@ export class Inbox extends Component<any, InboxState> {
selects() { selects() {
return ( return (
<div className="mb-2"> <div className="mb-2">
<span className="mr-3">{this.unreadOrAllRadios()}</span> <span className="me-3">{this.unreadOrAllRadios()}</span>
<span className="mr-3">{this.messageTypeRadios()}</span> <span className="me-3">{this.messageTypeRadios()}</span>
<CommentSortSelect <CommentSortSelect
sort={this.state.sort} sort={this.state.sort}
onChange={this.handleSortChange} onChange={this.handleSortChange}
@ -686,50 +697,40 @@ export class Inbox extends Component<any, InboxState> {
await i.refetch(); await i.refetch();
} }
static fetchInitialData({ static async fetchInitialData({
client, client,
auth, auth,
}: InitialFetchRequest): Promise<any>[] { }: InitialFetchRequest): Promise<InboxData> {
const promises: Promise<RequestState<any>>[] = [];
const sort: CommentSortType = "New"; const sort: CommentSortType = "New";
if (auth) { return {
// It can be /u/me, or /username/1 mentionsRes: auth
const repliesForm: GetReplies = { ? await client.getPersonMentions({
sort, sort,
unread_only: true, unread_only: true,
page: 1, page: 1,
limit: fetchLimit, limit: fetchLimit,
auth, auth,
}; })
promises.push(client.getReplies(repliesForm)); : { state: "empty" },
messagesRes: auth
const personMentionsForm: GetPersonMentions = { ? await client.getPrivateMessages({
sort, unread_only: true,
unread_only: true, page: 1,
page: 1, limit: fetchLimit,
limit: fetchLimit, auth,
auth, })
}; : { state: "empty" },
promises.push(client.getPersonMentions(personMentionsForm)); repliesRes: auth
? await client.getReplies({
const privateMessagesForm: GetPrivateMessages = { sort,
unread_only: true, unread_only: true,
page: 1, page: 1,
limit: fetchLimit, limit: fetchLimit,
auth, auth,
}; })
promises.push(client.getPrivateMessages(privateMessagesForm)); : { state: "empty" },
} else { };
promises.push(
Promise.resolve({ state: "empty" }),
Promise.resolve({ state: "empty" }),
Promise.resolve({ state: "empty" })
);
}
return promises;
} }
async refetch() { async refetch() {

View File

@ -40,7 +40,7 @@ export class PasswordChange extends Component<any, State> {
render() { render() {
return ( return (
<div className="container-lg"> <div className="password-change container-lg">
<HtmlTags <HtmlTags
title={this.documentTitle} title={this.documentTitle}
path={this.context.router.route.match.url} path={this.context.router.route.match.url}
@ -58,7 +58,7 @@ export class PasswordChange extends Component<any, State> {
passwordChangeForm() { passwordChangeForm() {
return ( return (
<form onSubmit={linkEvent(this, this.handlePasswordChangeSubmit)}> <form onSubmit={linkEvent(this, this.handlePasswordChangeSubmit)}>
<div className="form-group row"> <div className="mb-3 row">
<label className="col-sm-2 col-form-label" htmlFor="new-password"> <label className="col-sm-2 col-form-label" htmlFor="new-password">
{i18n.t("new_password")} {i18n.t("new_password")}
</label> </label>
@ -74,7 +74,7 @@ export class PasswordChange extends Component<any, State> {
/> />
</div> </div>
</div> </div>
<div className="form-group row"> <div className="mb-3 row">
<label className="col-sm-2 col-form-label" htmlFor="verify-password"> <label className="col-sm-2 col-form-label" htmlFor="verify-password">
{i18n.t("verify_password")} {i18n.t("verify_password")}
</label> </label>
@ -90,7 +90,7 @@ export class PasswordChange extends Component<any, State> {
/> />
</div> </div>
</div> </div>
<div className="form-group row"> <div className="mb-3 row">
<div className="col-sm-10"> <div className="col-sm-10">
<button type="submit" className="btn btn-secondary"> <button type="submit" className="btn btn-secondary">
{this.state.passwordChangeRes.state == "loading" ? ( {this.state.passwordChangeRes.state == "loading" ? (
@ -140,7 +140,7 @@ export class PasswordChange extends Component<any, State> {
UserService.Instance.myUserInfo = site.data.my_user; UserService.Instance.myUserInfo = site.data.my_user;
} }
this.props.history.replace("/"); i.props.history.replace("/");
} }
} }
} }

View File

@ -107,19 +107,9 @@ export class PersonDetails extends Component<PersonDetailsProps, any> {
setupTippy(); setupTippy();
} }
// TODO wut?
// componentDidUpdate(lastProps: UserDetailsProps) {
// for (const key of Object.keys(lastProps)) {
// if (lastProps[key] !== this.props[key]) {
// this.fetchUserData();
// break;
// }
// }
// }
render() { render() {
return ( return (
<div> <div className="person-details">
{this.viewSelector(this.props.view)} {this.viewSelector(this.props.view)}
<Paginator page={this.props.page} onChange={this.handlePageChange} /> <Paginator page={this.props.page} onChange={this.handlePageChange} />

View File

@ -1,3 +1,4 @@
import classNames from "classnames";
import { Component } from "inferno"; import { Component } from "inferno";
import { Link } from "inferno-router"; import { Link } from "inferno-router";
import { Person } from "lemmy-js-client"; import { Person } from "lemmy-js-client";
@ -48,7 +49,13 @@ export class PersonListing extends Component<PersonListingProps, any> {
{!this.props.realLink ? ( {!this.props.realLink ? (
<Link <Link
title={apubName} title={apubName}
className={this.props.muted ? "text-muted" : "text-info"} className={classNames(
"person-listing d-inline-flex align-items-baseline",
{
"text-muted": this.props.muted,
"text-info": !this.props.muted,
}
)}
to={link} to={link}
> >
{this.avatarAndName(displayName)} {this.avatarAndName(displayName)}
@ -56,7 +63,9 @@ export class PersonListing extends Component<PersonListingProps, any> {
) : ( ) : (
<a <a
title={apubName} title={apubName}
className={this.props.muted ? "text-muted" : "text-info"} className={`person-listing d-inline-flex align-items-baseline ${
this.props.muted ? "text-muted" : "text-info"
}`}
href={link} href={link}
rel={relTags} rel={relTags}
> >
@ -73,10 +82,14 @@ export class PersonListing extends Component<PersonListingProps, any> {
const avatar = this.props.person.avatar; const avatar = this.props.person.avatar;
return ( return (
<> <>
{avatar && {!this.props.hideAvatar &&
!this.props.hideAvatar &&
!this.props.person.banned && !this.props.person.banned &&
showAvatars() && <PictrsImage src={avatar} icon />} showAvatars() && (
<PictrsImage
src={avatar ?? "/static/assets/icons/icon-96x96.png"}
icon
/>
)}
<span>{displayName}</span> <span>{displayName}</span>
</> </>
); );

View File

@ -1,3 +1,6 @@
import { getQueryParams, getQueryString } from "@utils/helpers";
import { canMod, isAdmin, isBanned } from "@utils/roles";
import type { QueryParams } from "@utils/types";
import classNames from "classnames"; import classNames from "classnames";
import { NoOptionI18nKeys } from "i18next"; import { NoOptionI18nKeys } from "i18next";
import { Component, linkEvent } from "inferno"; import { Component, linkEvent } from "inferno";
@ -53,8 +56,7 @@ import { UserService } from "../../services";
import { FirstLoadService } from "../../services/FirstLoadService"; import { FirstLoadService } from "../../services/FirstLoadService";
import { HttpService, RequestState } from "../../services/HttpService"; import { HttpService, RequestState } from "../../services/HttpService";
import { import {
QueryParams, RouteDataResponse,
canMod,
capitalizeFirstLetter, capitalizeFirstLetter,
editComment, editComment,
editPost, editPost,
@ -65,10 +67,6 @@ import {
futureDaysToUnixTime, futureDaysToUnixTime,
getCommentParentId, getCommentParentId,
getPageFromString, getPageFromString,
getQueryParams,
getQueryString,
isAdmin,
isBanned,
mdToHtml, mdToHtml,
myAuth, myAuth,
myAuthRequired, myAuthRequired,
@ -90,6 +88,10 @@ import { CommunityLink } from "../community/community-link";
import { PersonDetails } from "./person-details"; import { PersonDetails } from "./person-details";
import { PersonListing } from "./person-listing"; import { PersonListing } from "./person-listing";
type ProfileData = RouteDataResponse<{
personResponse: GetPersonDetailsResponse;
}>;
interface ProfileState { interface ProfileState {
personRes: RequestState<GetPersonDetailsResponse>; personRes: RequestState<GetPersonDetailsResponse>;
personBlocked: boolean; personBlocked: boolean;
@ -156,7 +158,7 @@ export class Profile extends Component<
RouteComponentProps<{ username: string }>, RouteComponentProps<{ username: string }>,
ProfileState ProfileState
> { > {
private isoData = setIsoData(this.context); private isoData = setIsoData<ProfileData>(this.context);
state: ProfileState = { state: ProfileState = {
personRes: { state: "empty" }, personRes: { state: "empty" },
personBlocked: false, personBlocked: false,
@ -208,7 +210,7 @@ export class Profile extends Component<
if (FirstLoadService.isFirstLoad) { if (FirstLoadService.isFirstLoad) {
this.state = { this.state = {
...this.state, ...this.state,
personRes: this.isoData.routeData[0], personRes: this.isoData.routeData.personResponse,
isIsomorphic: true, isIsomorphic: true,
}; };
} }
@ -267,14 +269,12 @@ export class Profile extends Component<
} }
} }
static fetchInitialData({ static async fetchInitialData({
client, client,
path, path,
query: { page, sort, view: urlView }, query: { page, sort, view: urlView },
auth, auth,
}: InitialFetchRequest<QueryParams<ProfileProps>>): Promise< }: InitialFetchRequest<QueryParams<ProfileProps>>): Promise<ProfileData> {
RequestState<any>
>[] {
const pathSplit = path.split("/"); const pathSplit = path.split("/");
const username = pathSplit[2]; const username = pathSplit[2];
@ -289,7 +289,9 @@ export class Profile extends Component<
auth, auth,
}; };
return [client.getPersonDetails(form)]; return {
personResponse: await client.getPersonDetails(form),
};
} }
get documentTitle(): string { get documentTitle(): string {
@ -384,7 +386,11 @@ export class Profile extends Component<
} }
render() { render() {
return <div className="container-lg">{this.renderPersonRes()}</div>; return (
<div className="person-profile container-lg">
{this.renderPersonRes()}
</div>
);
} }
get viewRadios() { get viewRadios() {
@ -410,6 +416,7 @@ export class Profile extends Component<
> >
<input <input
type="radio" type="radio"
className="btn-check"
value={view} value={view}
checked={active} checked={active}
onChange={linkEvent(this, this.handleViewChange)} onChange={linkEvent(this, this.handleViewChange)}
@ -427,7 +434,7 @@ export class Profile extends Component<
return ( return (
<div className="mb-2"> <div className="mb-2">
<span className="mr-3">{this.viewRadios}</span> <span className="me-3">{this.viewRadios}</span>
<SortSelect <SortSelect
sort={sort} sort={sort}
onChange={this.handleSortChange} onChange={this.handleSortChange}
@ -476,22 +483,22 @@ export class Profile extends Component<
/> />
</li> </li>
{isBanned(pv.person) && ( {isBanned(pv.person) && (
<li className="list-inline-item badge badge-danger"> <li className="list-inline-item badge text-bg-danger">
{i18n.t("banned")} {i18n.t("banned")}
</li> </li>
)} )}
{pv.person.deleted && ( {pv.person.deleted && (
<li className="list-inline-item badge badge-danger"> <li className="list-inline-item badge text-bg-danger">
{i18n.t("deleted")} {i18n.t("deleted")}
</li> </li>
)} )}
{pv.person.admin && ( {pv.person.admin && (
<li className="list-inline-item badge badge-light"> <li className="list-inline-item badge text-bg-light">
{i18n.t("admin")} {i18n.t("admin")}
</li> </li>
)} )}
{pv.person.bot_account && ( {pv.person.bot_account && (
<li className="list-inline-item badge badge-light"> <li className="list-inline-item badge text-bg-light">
{i18n.t("bot_account").toLowerCase()} {i18n.t("bot_account").toLowerCase()}
</li> </li>
)} )}
@ -502,7 +509,7 @@ export class Profile extends Component<
{!this.amCurrentUser && UserService.Instance.myUserInfo && ( {!this.amCurrentUser && UserService.Instance.myUserInfo && (
<> <>
<a <a
className={`d-flex align-self-start btn btn-secondary mr-2 ${ className={`d-flex align-self-start btn btn-secondary me-2 ${
!pv.person.matrix_user_id && "invisible" !pv.person.matrix_user_id && "invisible"
}`} }`}
rel={relTags} rel={relTags}
@ -512,7 +519,7 @@ export class Profile extends Component<
</a> </a>
<Link <Link
className={ className={
"d-flex align-self-start btn btn-secondary mr-2" "d-flex align-self-start btn btn-secondary me-2"
} }
to={`/create_private_message/${pv.person.id}`} to={`/create_private_message/${pv.person.id}`}
> >
@ -521,7 +528,7 @@ export class Profile extends Component<
{personBlocked ? ( {personBlocked ? (
<button <button
className={ className={
"d-flex align-self-start btn btn-secondary mr-2" "d-flex align-self-start btn btn-secondary me-2"
} }
onClick={linkEvent( onClick={linkEvent(
pv.person.id, pv.person.id,
@ -533,7 +540,7 @@ export class Profile extends Component<
) : ( ) : (
<button <button
className={ className={
"d-flex align-self-start btn btn-secondary mr-2" "d-flex align-self-start btn btn-secondary me-2"
} }
onClick={linkEvent( onClick={linkEvent(
pv.person.id, pv.person.id,
@ -552,7 +559,7 @@ export class Profile extends Component<
(!isBanned(pv.person) ? ( (!isBanned(pv.person) ? (
<button <button
className={ className={
"d-flex align-self-start btn btn-secondary mr-2" "d-flex align-self-start btn btn-secondary me-2"
} }
onClick={linkEvent(this, this.handleModBanShow)} onClick={linkEvent(this, this.handleModBanShow)}
aria-label={i18n.t("ban")} aria-label={i18n.t("ban")}
@ -562,7 +569,7 @@ export class Profile extends Component<
) : ( ) : (
<button <button
className={ className={
"d-flex align-self-start btn btn-secondary mr-2" "d-flex align-self-start btn btn-secondary me-2"
} }
onClick={linkEvent(this, this.handleModBanSubmit)} onClick={linkEvent(this, this.handleModBanSubmit)}
aria-label={i18n.t("unban")} aria-label={i18n.t("unban")}
@ -581,13 +588,13 @@ export class Profile extends Component<
)} )}
<div> <div>
<ul className="list-inline mb-2"> <ul className="list-inline mb-2">
<li className="list-inline-item badge badge-light"> <li className="list-inline-item badge text-bg-light">
{i18n.t("number_of_posts", { {i18n.t("number_of_posts", {
count: Number(pv.counts.post_count), count: Number(pv.counts.post_count),
formattedCount: numToSI(pv.counts.post_count), formattedCount: numToSI(pv.counts.post_count),
})} })}
</li> </li>
<li className="list-inline-item badge badge-light"> <li className="list-inline-item badge text-bg-light">
{i18n.t("number_of_comments", { {i18n.t("number_of_comments", {
count: Number(pv.counts.comment_count), count: Number(pv.counts.comment_count),
formattedCount: numToSI(pv.counts.comment_count), formattedCount: numToSI(pv.counts.comment_count),
@ -605,7 +612,7 @@ export class Profile extends Component<
</div> </div>
<div className="d-flex align-items-center text-muted mb-2"> <div className="d-flex align-items-center text-muted mb-2">
<Icon icon="cake" /> <Icon icon="cake" />
<span className="ml-2"> <span className="ms-2">
{i18n.t("cake_day_title")}{" "} {i18n.t("cake_day_title")}{" "}
{moment {moment
.utc(pv.person.published) .utc(pv.person.published)
@ -631,14 +638,14 @@ export class Profile extends Component<
return ( return (
showBanDialog && ( showBanDialog && (
<form onSubmit={linkEvent(this, this.handleModBanSubmit)}> <form onSubmit={linkEvent(this, this.handleModBanSubmit)}>
<div className="form-group row col-12"> <div className="mb-3 row col-12">
<label className="col-form-label" htmlFor="profile-ban-reason"> <label className="col-form-label" htmlFor="profile-ban-reason">
{i18n.t("reason")} {i18n.t("reason")}
</label> </label>
<input <input
type="text" type="text"
id="profile-ban-reason" id="profile-ban-reason"
className="form-control mr-2" className="form-control me-2"
placeholder={i18n.t("reason")} placeholder={i18n.t("reason")}
value={this.state.banReason} value={this.state.banReason}
onInput={linkEvent(this, this.handleModBanReasonChange)} onInput={linkEvent(this, this.handleModBanReasonChange)}
@ -649,12 +656,12 @@ export class Profile extends Component<
<input <input
type="number" type="number"
id={`mod-ban-expires`} id={`mod-ban-expires`}
className="form-control mr-2" className="form-control me-2"
placeholder={i18n.t("number_of_days")} placeholder={i18n.t("number_of_days")}
value={this.state.banExpireDays} value={this.state.banExpireDays}
onInput={linkEvent(this, this.handleModBanExpireDaysChange)} onInput={linkEvent(this, this.handleModBanExpireDaysChange)}
/> />
<div className="form-group"> <div className="input-group mb-3">
<div className="form-check"> <div className="form-check">
<input <input
className="form-check-input" className="form-check-input"
@ -674,14 +681,14 @@ export class Profile extends Component<
</div> </div>
</div> </div>
{/* TODO hold off on expires until later */} {/* TODO hold off on expires until later */}
{/* <div class="form-group row"> */} {/* <div class="mb-3 row"> */}
{/* <label class="col-form-label">Expires</label> */} {/* <label class="col-form-label">Expires</label> */}
{/* <input type="date" class="form-control mr-2" placeholder={i18n.t('expires')} value={this.state.banExpires} onInput={linkEvent(this, this.handleModBanExpiresChange)} /> */} {/* <input type="date" class="form-control me-2" placeholder={i18n.t('expires')} value={this.state.banExpires} onInput={linkEvent(this, this.handleModBanExpiresChange)} /> */}
{/* </div> */} {/* </div> */}
<div className="form-group row"> <div className="mb-3 row">
<button <button
type="reset" type="reset"
className="btn btn-secondary mr-2" className="btn btn-secondary me-2"
aria-label={i18n.t("cancel")} aria-label={i18n.t("cancel")}
onClick={linkEvent(this, this.handleModBanSubmitCancel)} onClick={linkEvent(this, this.handleModBanSubmitCancel)}
> >

View File

@ -2,7 +2,6 @@ import { Component, linkEvent } from "inferno";
import { import {
ApproveRegistrationApplication, ApproveRegistrationApplication,
GetSiteResponse, GetSiteResponse,
ListRegistrationApplications,
ListRegistrationApplicationsResponse, ListRegistrationApplicationsResponse,
RegistrationApplicationView, RegistrationApplicationView,
} from "lemmy-js-client"; } from "lemmy-js-client";
@ -12,6 +11,7 @@ import { UserService } from "../../services";
import { FirstLoadService } from "../../services/FirstLoadService"; import { FirstLoadService } from "../../services/FirstLoadService";
import { HttpService, RequestState } from "../../services/HttpService"; import { HttpService, RequestState } from "../../services/HttpService";
import { import {
RouteDataResponse,
editRegistrationApplication, editRegistrationApplication,
fetchLimit, fetchLimit,
myAuthRequired, myAuthRequired,
@ -28,6 +28,10 @@ enum UnreadOrAll {
All, All,
} }
type RegistrationApplicationsData = RouteDataResponse<{
listRegistrationApplicationsResponse: ListRegistrationApplicationsResponse;
}>;
interface RegistrationApplicationsState { interface RegistrationApplicationsState {
appsRes: RequestState<ListRegistrationApplicationsResponse>; appsRes: RequestState<ListRegistrationApplicationsResponse>;
siteRes: GetSiteResponse; siteRes: GetSiteResponse;
@ -40,7 +44,7 @@ export class RegistrationApplications extends Component<
any, any,
RegistrationApplicationsState RegistrationApplicationsState
> { > {
private isoData = setIsoData(this.context); private isoData = setIsoData<RegistrationApplicationsData>(this.context);
state: RegistrationApplicationsState = { state: RegistrationApplicationsState = {
appsRes: { state: "empty" }, appsRes: { state: "empty" },
siteRes: this.isoData.site_res, siteRes: this.isoData.site_res,
@ -59,7 +63,7 @@ export class RegistrationApplications extends Component<
if (FirstLoadService.isFirstLoad) { if (FirstLoadService.isFirstLoad) {
this.state = { this.state = {
...this.state, ...this.state,
appsRes: this.isoData.routeData[0], appsRes: this.isoData.routeData.listRegistrationApplicationsResponse,
isIsomorphic: true, isIsomorphic: true,
}; };
} }
@ -113,7 +117,11 @@ export class RegistrationApplications extends Component<
} }
render() { render() {
return <div className="container-lg">{this.renderApps()}</div>; return (
<div className="registration-applications container-lg">
{this.renderApps()}
</div>
);
} }
unreadOrAllRadios() { unreadOrAllRadios() {
@ -126,6 +134,7 @@ export class RegistrationApplications extends Component<
> >
<input <input
type="radio" type="radio"
className="btn-check"
value={UnreadOrAll.Unread} value={UnreadOrAll.Unread}
checked={this.state.unreadOrAll == UnreadOrAll.Unread} checked={this.state.unreadOrAll == UnreadOrAll.Unread}
onChange={linkEvent(this, this.handleUnreadOrAllChange)} onChange={linkEvent(this, this.handleUnreadOrAllChange)}
@ -139,6 +148,7 @@ export class RegistrationApplications extends Component<
> >
<input <input
type="radio" type="radio"
className="btn-check"
value={UnreadOrAll.All} value={UnreadOrAll.All}
checked={this.state.unreadOrAll == UnreadOrAll.All} checked={this.state.unreadOrAll == UnreadOrAll.All}
onChange={linkEvent(this, this.handleUnreadOrAllChange)} onChange={linkEvent(this, this.handleUnreadOrAllChange)}
@ -152,7 +162,7 @@ export class RegistrationApplications extends Component<
selects() { selects() {
return ( return (
<div className="mb-2"> <div className="mb-2">
<span className="mr-3">{this.unreadOrAllRadios()}</span> <span className="me-3">{this.unreadOrAllRadios()}</span>
</div> </div>
); );
} }
@ -184,25 +194,20 @@ export class RegistrationApplications extends Component<
this.refetch(); this.refetch();
} }
static fetchInitialData({ static async fetchInitialData({
auth, auth,
client, client,
}: InitialFetchRequest): Promise<any>[] { }: InitialFetchRequest): Promise<RegistrationApplicationsData> {
const promises: Promise<RequestState<any>>[] = []; return {
listRegistrationApplicationsResponse: auth
if (auth) { ? await client.listRegistrationApplications({
const form: ListRegistrationApplications = { unread_only: true,
unread_only: true, page: 1,
page: 1, limit: fetchLimit,
limit: fetchLimit, auth: auth as string,
auth, })
}; : { state: "empty" },
promises.push(client.listRegistrationApplications(form)); };
} else {
promises.push(Promise.resolve({ state: "empty" }));
}
return promises;
} }
async refetch() { async refetch() {

View File

@ -1,3 +1,4 @@
import { amAdmin } from "@utils/roles";
import { Component, linkEvent } from "inferno"; import { Component, linkEvent } from "inferno";
import { import {
CommentReportResponse, CommentReportResponse,
@ -23,7 +24,7 @@ import { HttpService, UserService } from "../../services";
import { FirstLoadService } from "../../services/FirstLoadService"; import { FirstLoadService } from "../../services/FirstLoadService";
import { RequestState } from "../../services/HttpService"; import { RequestState } from "../../services/HttpService";
import { import {
amAdmin, RouteDataResponse,
editCommentReport, editCommentReport,
editPostReport, editPostReport,
editPrivateMessageReport, editPrivateMessageReport,
@ -56,6 +57,12 @@ enum MessageEnum {
PrivateMessageReport, PrivateMessageReport,
} }
type ReportsData = RouteDataResponse<{
commentReportsRes: ListCommentReportsResponse;
postReportsRes: ListPostReportsResponse;
messageReportsRes: ListPrivateMessageReportsResponse;
}>;
type ItemType = { type ItemType = {
id: number; id: number;
type_: MessageEnum; type_: MessageEnum;
@ -75,7 +82,7 @@ interface ReportsState {
} }
export class Reports extends Component<any, ReportsState> { export class Reports extends Component<any, ReportsState> {
private isoData = setIsoData(this.context); private isoData = setIsoData<ReportsData>(this.context);
state: ReportsState = { state: ReportsState = {
commentReportsRes: { state: "empty" }, commentReportsRes: { state: "empty" },
postReportsRes: { state: "empty" }, postReportsRes: { state: "empty" },
@ -99,8 +106,9 @@ export class Reports extends Component<any, ReportsState> {
// Only fetch the data if coming from another route // Only fetch the data if coming from another route
if (FirstLoadService.isFirstLoad) { if (FirstLoadService.isFirstLoad) {
const [commentReportsRes, postReportsRes, messageReportsRes] = const { commentReportsRes, postReportsRes, messageReportsRes } =
this.isoData.routeData; this.isoData.routeData;
this.state = { this.state = {
...this.state, ...this.state,
commentReportsRes, commentReportsRes,
@ -111,7 +119,7 @@ export class Reports extends Component<any, ReportsState> {
if (amAdmin()) { if (amAdmin()) {
this.state = { this.state = {
...this.state, ...this.state,
messageReportsRes, messageReportsRes: messageReportsRes,
}; };
} }
} }
@ -134,7 +142,7 @@ export class Reports extends Component<any, ReportsState> {
render() { render() {
return ( return (
<div className="container-lg"> <div className="person-reports container-lg">
<div className="row"> <div className="row">
<div className="col-12"> <div className="col-12">
<HtmlTags <HtmlTags
@ -185,6 +193,7 @@ export class Reports extends Component<any, ReportsState> {
> >
<input <input
type="radio" type="radio"
className="btn-check"
value={UnreadOrAll.Unread} value={UnreadOrAll.Unread}
checked={this.state.unreadOrAll == UnreadOrAll.Unread} checked={this.state.unreadOrAll == UnreadOrAll.Unread}
onChange={linkEvent(this, this.handleUnreadOrAllChange)} onChange={linkEvent(this, this.handleUnreadOrAllChange)}
@ -198,6 +207,7 @@ export class Reports extends Component<any, ReportsState> {
> >
<input <input
type="radio" type="radio"
className="btn-check"
value={UnreadOrAll.All} value={UnreadOrAll.All}
checked={this.state.unreadOrAll == UnreadOrAll.All} checked={this.state.unreadOrAll == UnreadOrAll.All}
onChange={linkEvent(this, this.handleUnreadOrAllChange)} onChange={linkEvent(this, this.handleUnreadOrAllChange)}
@ -218,6 +228,7 @@ export class Reports extends Component<any, ReportsState> {
> >
<input <input
type="radio" type="radio"
className="btn-check"
value={MessageType.All} value={MessageType.All}
checked={this.state.messageType == MessageType.All} checked={this.state.messageType == MessageType.All}
onChange={linkEvent(this, this.handleMessageTypeChange)} onChange={linkEvent(this, this.handleMessageTypeChange)}
@ -231,6 +242,7 @@ export class Reports extends Component<any, ReportsState> {
> >
<input <input
type="radio" type="radio"
className="btn-check"
value={MessageType.CommentReport} value={MessageType.CommentReport}
checked={this.state.messageType == MessageType.CommentReport} checked={this.state.messageType == MessageType.CommentReport}
onChange={linkEvent(this, this.handleMessageTypeChange)} onChange={linkEvent(this, this.handleMessageTypeChange)}
@ -244,6 +256,7 @@ export class Reports extends Component<any, ReportsState> {
> >
<input <input
type="radio" type="radio"
className="btn-check"
value={MessageType.PostReport} value={MessageType.PostReport}
checked={this.state.messageType == MessageType.PostReport} checked={this.state.messageType == MessageType.PostReport}
onChange={linkEvent(this, this.handleMessageTypeChange)} onChange={linkEvent(this, this.handleMessageTypeChange)}
@ -261,6 +274,7 @@ export class Reports extends Component<any, ReportsState> {
> >
<input <input
type="radio" type="radio"
className="btn-check"
value={MessageType.PrivateMessageReport} value={MessageType.PrivateMessageReport}
checked={ checked={
this.state.messageType == MessageType.PrivateMessageReport this.state.messageType == MessageType.PrivateMessageReport
@ -277,8 +291,8 @@ export class Reports extends Component<any, ReportsState> {
selects() { selects() {
return ( return (
<div className="mb-2"> <div className="mb-2">
<span className="mr-3">{this.unreadOrAllRadios()}</span> <span className="me-3">{this.unreadOrAllRadios()}</span>
<span className="mr-3">{this.messageTypeRadios()}</span> <span className="me-3">{this.messageTypeRadios()}</span>
</div> </div>
); );
} }
@ -481,55 +495,48 @@ export class Reports extends Component<any, ReportsState> {
await i.refetch(); await i.refetch();
} }
static fetchInitialData({ static async fetchInitialData({
auth, auth,
client, client,
}: InitialFetchRequest): Promise<any>[] { }: InitialFetchRequest): Promise<ReportsData> {
const promises: Promise<RequestState<any>>[] = [];
const unresolved_only = true; const unresolved_only = true;
const page = 1; const page = 1;
const limit = fetchLimit; const limit = fetchLimit;
if (auth) { const commentReportsForm: ListCommentReports = {
const commentReportsForm: ListCommentReports = { unresolved_only,
page,
limit,
auth: auth as string,
};
const postReportsForm: ListPostReports = {
unresolved_only,
page,
limit,
auth: auth as string,
};
const data: ReportsData = {
commentReportsRes: await client.listCommentReports(commentReportsForm),
postReportsRes: await client.listPostReports(postReportsForm),
messageReportsRes: { state: "empty" },
};
if (amAdmin()) {
const privateMessageReportsForm: ListPrivateMessageReports = {
unresolved_only, unresolved_only,
page, page,
limit, limit,
auth, auth: auth as string,
}; };
promises.push(client.listCommentReports(commentReportsForm));
const postReportsForm: ListPostReports = { data.messageReportsRes = await client.listPrivateMessageReports(
unresolved_only, privateMessageReportsForm
page,
limit,
auth,
};
promises.push(client.listPostReports(postReportsForm));
if (amAdmin()) {
const privateMessageReportsForm: ListPrivateMessageReports = {
unresolved_only,
page,
limit,
auth,
};
promises.push(
client.listPrivateMessageReports(privateMessageReportsForm)
);
} else {
promises.push(Promise.resolve({ state: "empty" }));
}
} else {
promises.push(
Promise.resolve({ state: "empty" }),
Promise.resolve({ state: "empty" }),
Promise.resolve({ state: "empty" })
); );
} }
return promises; return data;
} }
async refetch() { async refetch() {

View File

@ -1,3 +1,4 @@
import { debounce } from "@utils/helpers";
import { NoOptionI18nKeys } from "i18next"; import { NoOptionI18nKeys } from "i18next";
import { Component, linkEvent } from "inferno"; import { Component, linkEvent } from "inferno";
import { import {
@ -18,10 +19,8 @@ import {
Choice, Choice,
capitalizeFirstLetter, capitalizeFirstLetter,
communityToChoice, communityToChoice,
debounce,
elementUrl, elementUrl,
emDash, emDash,
enableNsfw,
fetchCommunities, fetchCommunities,
fetchThemeList, fetchThemeList,
fetchUsers, fetchUsers,
@ -111,7 +110,7 @@ const Filter = ({
onChange: (choice: Choice) => void; onChange: (choice: Choice) => void;
loading: boolean; loading: boolean;
}) => ( }) => (
<div className="form-group row"> <div className="mb-3 row">
<label <label
className="col-md-4 col-form-label" className="col-md-4 col-form-label"
htmlFor={`block-${filterType}-filter`} htmlFor={`block-${filterType}-filter`}
@ -241,7 +240,7 @@ export class Settings extends Component<any, SettingsState> {
render() { render() {
return ( return (
<div className="container-lg"> <div className="person-settings container-lg">
<HtmlTags <HtmlTags
title={this.documentTitle} title={this.documentTitle}
path={this.context.router.route.match.url} path={this.context.router.route.match.url}
@ -305,7 +304,7 @@ export class Settings extends Component<any, SettingsState> {
<> <>
<h5>{i18n.t("change_password")}</h5> <h5>{i18n.t("change_password")}</h5>
<form onSubmit={linkEvent(this, this.handleChangePasswordSubmit)}> <form onSubmit={linkEvent(this, this.handleChangePasswordSubmit)}>
<div className="form-group row"> <div className="mb-3 row">
<label className="col-sm-5 col-form-label" htmlFor="user-password"> <label className="col-sm-5 col-form-label" htmlFor="user-password">
{i18n.t("new_password")} {i18n.t("new_password")}
</label> </label>
@ -321,7 +320,7 @@ export class Settings extends Component<any, SettingsState> {
/> />
</div> </div>
</div> </div>
<div className="form-group row"> <div className="mb-3 row">
<label <label
className="col-sm-5 col-form-label" className="col-sm-5 col-form-label"
htmlFor="user-verify-password" htmlFor="user-verify-password"
@ -340,7 +339,7 @@ export class Settings extends Component<any, SettingsState> {
/> />
</div> </div>
</div> </div>
<div className="form-group row"> <div className="mb-3 row">
<label <label
className="col-sm-5 col-form-label" className="col-sm-5 col-form-label"
htmlFor="user-old-password" htmlFor="user-old-password"
@ -359,8 +358,11 @@ export class Settings extends Component<any, SettingsState> {
/> />
</div> </div>
</div> </div>
<div className="form-group"> <div className="input-group mb-3">
<button type="submit" className="btn btn-block btn-secondary mr-4"> <button
type="submit"
className="btn d-block btn-secondary me-4 w-100"
>
{this.state.changePasswordRes.state === "loading" ? ( {this.state.changePasswordRes.state === "loading" ? (
<Spinner /> <Spinner />
) : ( ) : (
@ -468,11 +470,11 @@ export class Settings extends Component<any, SettingsState> {
<> <>
<h5>{i18n.t("settings")}</h5> <h5>{i18n.t("settings")}</h5>
<form onSubmit={linkEvent(this, this.handleSaveSettingsSubmit)}> <form onSubmit={linkEvent(this, this.handleSaveSettingsSubmit)}>
<div className="form-group row"> <div className="mb-3 row">
<label className="col-sm-5 col-form-label" htmlFor="display-name"> <label className="col-sm-3 col-form-label" htmlFor="display-name">
{i18n.t("display_name")} {i18n.t("display_name")}
</label> </label>
<div className="col-sm-7"> <div className="col-sm-9">
<input <input
id="display-name" id="display-name"
type="text" type="text"
@ -485,7 +487,7 @@ export class Settings extends Component<any, SettingsState> {
/> />
</div> </div>
</div> </div>
<div className="form-group row"> <div className="mb-3 row">
<label className="col-sm-3 col-form-label" htmlFor="user-bio"> <label className="col-sm-3 col-form-label" htmlFor="user-bio">
{i18n.t("bio")} {i18n.t("bio")}
</label> </label>
@ -500,7 +502,7 @@ export class Settings extends Component<any, SettingsState> {
/> />
</div> </div>
</div> </div>
<div className="form-group row"> <div className="mb-3 row">
<label className="col-sm-3 col-form-label" htmlFor="user-email"> <label className="col-sm-3 col-form-label" htmlFor="user-email">
{i18n.t("email")} {i18n.t("email")}
</label> </label>
@ -516,13 +518,13 @@ export class Settings extends Component<any, SettingsState> {
/> />
</div> </div>
</div> </div>
<div className="form-group row"> <div className="mb-3 row">
<label className="col-sm-5 col-form-label" htmlFor="matrix-user-id"> <label className="col-sm-3 col-form-label" htmlFor="matrix-user-id">
<a href={elementUrl} rel={relTags}> <a href={elementUrl} rel={relTags}>
{i18n.t("matrix_user_id")} {i18n.t("matrix_user_id")}
</a> </a>
</label> </label>
<div className="col-sm-7"> <div className="col-sm-9">
<input <input
id="matrix-user-id" id="matrix-user-id"
type="text" type="text"
@ -534,8 +536,10 @@ export class Settings extends Component<any, SettingsState> {
/> />
</div> </div>
</div> </div>
<div className="form-group row"> <div className="mb-3 row">
<label className="col-sm-3">{i18n.t("avatar")}</label> <label className="col-sm-3 col-form-label">
{i18n.t("avatar")}
</label>
<div className="col-sm-9"> <div className="col-sm-9">
<ImageUploadForm <ImageUploadForm
uploadTitle={i18n.t("upload_avatar")} uploadTitle={i18n.t("upload_avatar")}
@ -546,8 +550,10 @@ export class Settings extends Component<any, SettingsState> {
/> />
</div> </div>
</div> </div>
<div className="form-group row"> <div className="mb-3 row">
<label className="col-sm-3">{i18n.t("banner")}</label> <label className="col-sm-3 col-form-label">
{i18n.t("banner")}
</label>
<div className="col-sm-9"> <div className="col-sm-9">
<ImageUploadForm <ImageUploadForm
uploadTitle={i18n.t("upload_banner")} uploadTitle={i18n.t("upload_banner")}
@ -557,8 +563,8 @@ export class Settings extends Component<any, SettingsState> {
/> />
</div> </div>
</div> </div>
<div className="form-group row"> <div className="mb-3 row">
<label className="col-sm-3" htmlFor="user-language"> <label className="col-sm-3 form-label" htmlFor="user-language">
{i18n.t("interface_language")} {i18n.t("interface_language")}
</label> </label>
<div className="col-sm-9"> <div className="col-sm-9">
@ -566,7 +572,7 @@ export class Settings extends Component<any, SettingsState> {
id="user-language" id="user-language"
value={this.state.saveUserSettingsForm.interface_language} value={this.state.saveUserSettingsForm.interface_language}
onChange={linkEvent(this, this.handleInterfaceLangChange)} onChange={linkEvent(this, this.handleInterfaceLangChange)}
className="custom-select w-auto" className="form-select d-inline-block w-auto"
> >
<option disabled aria-hidden="true"> <option disabled aria-hidden="true">
{i18n.t("interface_language")} {i18n.t("interface_language")}
@ -594,8 +600,8 @@ export class Settings extends Component<any, SettingsState> {
showSite showSite
onChange={this.handleDiscussionLanguageChange} onChange={this.handleDiscussionLanguageChange}
/> />
<div className="form-group row"> <div className="mb-3 row">
<label className="col-sm-3" htmlFor="user-theme"> <label className="col-sm-3 col-form-label" htmlFor="user-theme">
{i18n.t("theme")} {i18n.t("theme")}
</label> </label>
<div className="col-sm-9"> <div className="col-sm-9">
@ -603,7 +609,7 @@ export class Settings extends Component<any, SettingsState> {
id="user-theme" id="user-theme"
value={this.state.saveUserSettingsForm.theme} value={this.state.saveUserSettingsForm.theme}
onChange={linkEvent(this, this.handleThemeChange)} onChange={linkEvent(this, this.handleThemeChange)}
className="custom-select w-auto" className="form-select d-inline-block w-auto"
> >
<option disabled aria-hidden="true"> <option disabled aria-hidden="true">
{i18n.t("theme")} {i18n.t("theme")}
@ -617,8 +623,8 @@ export class Settings extends Component<any, SettingsState> {
</select> </select>
</div> </div>
</div> </div>
<form className="form-group row"> <form className="mb-3 row">
<label className="col-sm-3">{i18n.t("type")}</label> <label className="col-sm-3 col-form-label">{i18n.t("type")}</label>
<div className="col-sm-9"> <div className="col-sm-9">
<ListingTypeSelect <ListingTypeSelect
type_={ type_={
@ -631,8 +637,10 @@ export class Settings extends Component<any, SettingsState> {
/> />
</div> </div>
</form> </form>
<form className="form-group row"> <form className="mb-3 row">
<label className="col-sm-3">{i18n.t("sort_type")}</label> <label className="col-sm-3 col-form-label">
{i18n.t("sort_type")}
</label>
<div className="col-sm-9"> <div className="col-sm-9">
<SortSelect <SortSelect
sort={ sort={
@ -642,23 +650,21 @@ export class Settings extends Component<any, SettingsState> {
/> />
</div> </div>
</form> </form>
{enableNsfw(this.state.siteRes) && ( <div className="input-group mb-3">
<div className="form-group"> <div className="form-check">
<div className="form-check"> <input
<input className="form-check-input"
className="form-check-input" id="user-show-nsfw"
id="user-show-nsfw" type="checkbox"
type="checkbox" checked={this.state.saveUserSettingsForm.show_nsfw}
checked={this.state.saveUserSettingsForm.show_nsfw} onChange={linkEvent(this, this.handleShowNsfwChange)}
onChange={linkEvent(this, this.handleShowNsfwChange)} />
/> <label className="form-check-label" htmlFor="user-show-nsfw">
<label className="form-check-label" htmlFor="user-show-nsfw"> {i18n.t("show_nsfw")}
{i18n.t("show_nsfw")} </label>
</label>
</div>
</div> </div>
)} </div>
<div className="form-group"> <div className="input-group mb-3">
<div className="form-check"> <div className="form-check">
<input <input
className="form-check-input" className="form-check-input"
@ -672,7 +678,7 @@ export class Settings extends Component<any, SettingsState> {
</label> </label>
</div> </div>
</div> </div>
<div className="form-group"> <div className="input-group mb-3">
<div className="form-check"> <div className="form-check">
<input <input
className="form-check-input" className="form-check-input"
@ -686,7 +692,7 @@ export class Settings extends Component<any, SettingsState> {
</label> </label>
</div> </div>
</div> </div>
<div className="form-group"> <div className="input-group mb-3">
<div className="form-check"> <div className="form-check">
<input <input
className="form-check-input" className="form-check-input"
@ -700,7 +706,7 @@ export class Settings extends Component<any, SettingsState> {
</label> </label>
</div> </div>
</div> </div>
<div className="form-group"> <div className="input-group mb-3">
<div className="form-check"> <div className="form-check">
<input <input
className="form-check-input" className="form-check-input"
@ -717,7 +723,7 @@ export class Settings extends Component<any, SettingsState> {
</label> </label>
</div> </div>
</div> </div>
<div className="form-group"> <div className="input-group mb-3">
<div className="form-check"> <div className="form-check">
<input <input
className="form-check-input" className="form-check-input"
@ -734,7 +740,7 @@ export class Settings extends Component<any, SettingsState> {
</label> </label>
</div> </div>
</div> </div>
<div className="form-group"> <div className="input-group mb-3">
<div className="form-check"> <div className="form-check">
<input <input
className="form-check-input" className="form-check-input"
@ -751,7 +757,7 @@ export class Settings extends Component<any, SettingsState> {
</label> </label>
</div> </div>
</div> </div>
<div className="form-group"> <div className="input-group mb-3">
<div className="form-check"> <div className="form-check">
<input <input
className="form-check-input" className="form-check-input"
@ -775,8 +781,8 @@ export class Settings extends Component<any, SettingsState> {
</div> </div>
</div> </div>
{this.totpSection()} {this.totpSection()}
<div className="form-group"> <div className="input-group mb-3">
<button type="submit" className="btn btn-block btn-secondary mr-4"> <button type="submit" className="btn d-block btn-secondary me-4">
{this.state.saveRes.state === "loading" ? ( {this.state.saveRes.state === "loading" ? (
<Spinner /> <Spinner />
) : ( ) : (
@ -785,9 +791,9 @@ export class Settings extends Component<any, SettingsState> {
</button> </button>
</div> </div>
<hr /> <hr />
<div className="form-group"> <div className="input-group mb-3">
<button <button
className="btn btn-block btn-danger" className="btn d-block btn-danger"
onClick={linkEvent( onClick={linkEvent(
this, this,
this.handleDeleteAccountShowConfirmToggle this.handleDeleteAccountShowConfirmToggle
@ -812,7 +818,7 @@ export class Settings extends Component<any, SettingsState> {
className="form-control my-2" className="form-control my-2"
/> />
<button <button
className="btn btn-danger mr-4" className="btn btn-danger me-4"
disabled={!this.state.deleteAccountForm.password} disabled={!this.state.deleteAccountForm.password}
onClick={linkEvent(this, this.handleDeleteAccount)} onClick={linkEvent(this, this.handleDeleteAccount)}
> >
@ -846,7 +852,7 @@ export class Settings extends Component<any, SettingsState> {
return ( return (
<> <>
{!totpUrl && ( {!totpUrl && (
<div className="form-group"> <div className="input-group mb-3">
<div className="form-check"> <div className="form-check">
<input <input
className="form-check-input" className="form-check-input"
@ -869,7 +875,7 @@ export class Settings extends Component<any, SettingsState> {
{i18n.t("two_factor_link")} {i18n.t("two_factor_link")}
</a> </a>
</div> </div>
<div className="form-group"> <div className="input-group mb-3">
<div className="form-check"> <div className="form-check">
<input <input
className="form-check-input" className="form-check-input"

View File

@ -52,7 +52,7 @@ export class VerifyEmail extends Component<any, State> {
render() { render() {
return ( return (
<div className="container-lg"> <div className="verfy-email container-lg">
<HtmlTags <HtmlTags
title={this.documentTitle} title={this.documentTitle}
path={this.context.router.route.match.url} path={this.context.router.route.match.url}

View File

@ -1,8 +1,11 @@
import { getQueryParams } from "@utils/helpers";
import type { QueryParams } from "@utils/types";
import { Component } from "inferno"; import { Component } from "inferno";
import { RouteComponentProps } from "inferno-router/dist/Route"; import { RouteComponentProps } from "inferno-router/dist/Route";
import { import {
CreatePost as CreatePostI, CreatePost as CreatePostI,
GetCommunity, GetCommunity,
GetCommunityResponse,
GetSiteResponse, GetSiteResponse,
ListCommunitiesResponse, ListCommunitiesResponse,
} from "lemmy-js-client"; } from "lemmy-js-client";
@ -16,11 +19,10 @@ import {
} from "../../services/HttpService"; } from "../../services/HttpService";
import { import {
Choice, Choice,
QueryParams, RouteDataResponse,
enableDownvotes, enableDownvotes,
enableNsfw, enableNsfw,
getIdFromString, getIdFromString,
getQueryParams,
myAuth, myAuth,
setIsoData, setIsoData,
} from "../../utils"; } from "../../utils";
@ -32,6 +34,11 @@ export interface CreatePostProps {
communityId?: number; communityId?: number;
} }
type CreatePostData = RouteDataResponse<{
communityResponse: GetCommunityResponse;
initialCommunitiesRes: ListCommunitiesResponse;
}>;
function getCreatePostQueryParams() { function getCreatePostQueryParams() {
return getQueryParams<CreatePostProps>({ return getQueryParams<CreatePostProps>({
communityId: getIdFromString, communityId: getIdFromString,
@ -54,7 +61,7 @@ export class CreatePost extends Component<
RouteComponentProps<Record<string, never>>, RouteComponentProps<Record<string, never>>,
CreatePostState CreatePostState
> { > {
private isoData = setIsoData(this.context); private isoData = setIsoData<CreatePostData>(this.context);
state: CreatePostState = { state: CreatePostState = {
siteRes: this.isoData.site_res, siteRes: this.isoData.site_res,
loading: true, loading: true,
@ -71,7 +78,15 @@ export class CreatePost extends Component<
// Only fetch the data if coming from another route // Only fetch the data if coming from another route
if (FirstLoadService.isFirstLoad) { if (FirstLoadService.isFirstLoad) {
const [communityRes, listCommunitiesRes] = this.isoData.routeData; const { communityResponse: communityRes, initialCommunitiesRes } =
this.isoData.routeData;
this.state = {
...this.state,
loading: false,
initialCommunitiesRes,
isIsomorphic: true,
};
if (communityRes?.state === "success") { if (communityRes?.state === "success") {
const communityChoice: Choice = { const communityChoice: Choice = {
@ -84,13 +99,6 @@ export class CreatePost extends Component<
selectedCommunityChoice: communityChoice, selectedCommunityChoice: communityChoice,
}; };
} }
this.state = {
...this.state,
loading: false,
initialCommunitiesRes: listCommunitiesRes,
isIsomorphic: true,
};
} }
} }
@ -155,7 +163,7 @@ export class CreatePost extends Component<
| undefined; | undefined;
return ( return (
<div className="container-lg"> <div className="create-post container-lg">
<HtmlTags <HtmlTags
title={this.documentTitle} title={this.documentTitle}
path={this.context.router.route.match.url} path={this.context.router.route.match.url}
@ -166,7 +174,10 @@ export class CreatePost extends Component<
</h5> </h5>
) : ( ) : (
<div className="row"> <div className="row">
<div className="col-12 col-lg-6 offset-lg-3 mb-4"> <div
id="createPostForm"
className="col-12 col-lg-6 offset-lg-3 mb-4"
>
<h5>{i18n.t("create_post")}</h5> <h5>{i18n.t("create_post")}</h5>
<PostForm <PostForm
onCreate={this.handlePostCreate} onCreate={this.handlePostCreate}
@ -231,14 +242,17 @@ export class CreatePost extends Component<
} }
} }
static fetchInitialData({ static async fetchInitialData({
client, client,
query: { communityId }, query: { communityId },
auth, auth,
}: InitialFetchRequest<QueryParams<CreatePostProps>>): Promise< }: InitialFetchRequest<
RequestState<any> QueryParams<CreatePostProps>
>[] { >): Promise<CreatePostData> {
const promises: Promise<RequestState<any>>[] = []; const data: CreatePostData = {
initialCommunitiesRes: await fetchCommunitiesForOptions(client),
communityResponse: { state: "empty" },
};
if (communityId) { if (communityId) {
const form: GetCommunity = { const form: GetCommunity = {
@ -246,13 +260,9 @@ export class CreatePost extends Component<
id: getIdFromString(communityId), id: getIdFromString(communityId),
}; };
promises.push(client.getCommunity(form)); data.communityResponse = await client.getCommunity(form);
} else {
promises.push(Promise.resolve({ state: "empty" }));
} }
promises.push(fetchCommunitiesForOptions(client)); return data;
return promises;
} }
} }

View File

@ -30,7 +30,7 @@ export class MetadataCard extends Component<
return ( return (
<> <>
{!this.state.expanded && post.embed_title && post.url && ( {!this.state.expanded && post.embed_title && post.url && (
<div className="card border-secondary mt-3 mb-2"> <div className="post-metadata-card card border-secondary mt-3 mb-2">
<div className="row"> <div className="row">
<div className="col-12"> <div className="col-12">
<div className="card-body"> <div className="card-body">
@ -41,14 +41,14 @@ export class MetadataCard extends Component<
{post.embed_title} {post.embed_title}
</a> </a>
</h5> </h5>
<span className="d-inline-block ml-2 mb-2 small text-muted"> <span className="d-inline-block ms-2 mb-2 small text-muted">
<a <a
className="text-muted font-italic" className="text-muted font-italic"
href={post.url} href={post.url}
rel={relTags} rel={relTags}
> >
{new URL(post.url).hostname} {new URL(post.url).hostname}
<Icon icon="external-link" classes="ml-1" /> <Icon icon="external-link" classes="ms-1" />
</a> </a>
</span> </span>
</> </>
@ -75,7 +75,10 @@ export class MetadataCard extends Component<
</div> </div>
)} )}
{this.state.expanded && post.embed_video_url && ( {this.state.expanded && post.embed_video_url && (
<iframe src={post.embed_video_url}></iframe> <iframe
className="post-metadata-iframe"
src={post.embed_video_url}
></iframe>
)} )}
</> </>
); );

View File

@ -1,3 +1,4 @@
import { debounce } from "@utils/helpers";
import autosize from "autosize"; import autosize from "autosize";
import { Component, InfernoNode, linkEvent } from "inferno"; import { Component, InfernoNode, linkEvent } from "inferno";
import { import {
@ -18,7 +19,6 @@ import {
archiveTodayUrl, archiveTodayUrl,
capitalizeFirstLetter, capitalizeFirstLetter,
communityToChoice, communityToChoice,
debounce,
fetchCommunities, fetchCommunities,
getIdFromString, getIdFromString,
ghostArchiveUrl, ghostArchiveUrl,
@ -193,7 +193,10 @@ export class PostForm extends Component<PostFormProps, PostFormState> {
// !!this.state.form.name || !!this.state.form.url || !!this.state.form.body; // !!this.state.form.name || !!this.state.form.url || !!this.state.form.body;
// <Prompt when={promptCheck} message={i18n.t("block_leaving")} /> // <Prompt when={promptCheck} message={i18n.t("block_leaving")} />
return ( return (
<form onSubmit={linkEvent(this, this.handlePostSubmit)}> <form
className="post-form"
onSubmit={linkEvent(this, this.handlePostSubmit)}
>
<NavigationPrompt <NavigationPrompt
when={ when={
!!( !!(
@ -203,7 +206,7 @@ export class PostForm extends Component<PostFormProps, PostFormState> {
) && !this.state.submitted ) && !this.state.submitted
} }
/> />
<div className="form-group row"> <div className="mb-3 row">
<label className="col-sm-2 col-form-label" htmlFor="post-url"> <label className="col-sm-2 col-form-label" htmlFor="post-url">
{i18n.t("url")} {i18n.t("url")}
</label> </label>
@ -241,7 +244,7 @@ export class PostForm extends Component<PostFormProps, PostFormState> {
<div> <div>
<a <a
href={`${webArchiveUrl}/save/${encodeURIComponent(url)}`} href={`${webArchiveUrl}/save/${encodeURIComponent(url)}`}
className="mr-2 d-inline-block float-right text-muted small font-weight-bold" className="me-2 d-inline-block float-right text-muted small font-weight-bold"
rel={relTags} rel={relTags}
> >
archive.org {i18n.t("archive_link")} archive.org {i18n.t("archive_link")}
@ -250,7 +253,7 @@ export class PostForm extends Component<PostFormProps, PostFormState> {
href={`${ghostArchiveUrl}/search?term=${encodeURIComponent( href={`${ghostArchiveUrl}/search?term=${encodeURIComponent(
url url
)}`} )}`}
className="mr-2 d-inline-block float-right text-muted small font-weight-bold" className="me-2 d-inline-block float-right text-muted small font-weight-bold"
rel={relTags} rel={relTags}
> >
ghostarchive.org {i18n.t("archive_link")} ghostarchive.org {i18n.t("archive_link")}
@ -259,7 +262,7 @@ export class PostForm extends Component<PostFormProps, PostFormState> {
href={`${archiveTodayUrl}/?run=1&url=${encodeURIComponent( href={`${archiveTodayUrl}/?run=1&url=${encodeURIComponent(
url url
)}`} )}`}
className="mr-2 d-inline-block float-right text-muted small font-weight-bold" className="me-2 d-inline-block float-right text-muted small font-weight-bold"
rel={relTags} rel={relTags}
> >
archive.today {i18n.t("archive_link")} archive.today {i18n.t("archive_link")}
@ -277,7 +280,7 @@ export class PostForm extends Component<PostFormProps, PostFormState> {
aria-label={i18n.t("delete")} aria-label={i18n.t("delete")}
data-tippy-content={i18n.t("delete")} data-tippy-content={i18n.t("delete")}
> >
<Icon icon="x" classes="icon-inline mr-1" /> <Icon icon="x" classes="icon-inline me-1" />
{capitalizeFirstLetter(i18n.t("delete"))} {capitalizeFirstLetter(i18n.t("delete"))}
</button> </button>
)} )}
@ -316,7 +319,7 @@ export class PostForm extends Component<PostFormProps, PostFormState> {
)} )}
</div> </div>
</div> </div>
<div className="form-group row"> <div className="mb-3 row">
<label className="col-sm-2 col-form-label" htmlFor="post-title"> <label className="col-sm-2 col-form-label" htmlFor="post-title">
{i18n.t("title")} {i18n.t("title")}
</label> </label>
@ -342,7 +345,7 @@ export class PostForm extends Component<PostFormProps, PostFormState> {
</div> </div>
</div> </div>
<div className="form-group row"> <div className="mb-3 row">
<label className="col-sm-2 col-form-label">{i18n.t("body")}</label> <label className="col-sm-2 col-form-label">{i18n.t("body")}</label>
<div className="col-sm-10"> <div className="col-sm-10">
<MarkdownTextArea <MarkdownTextArea
@ -355,7 +358,7 @@ export class PostForm extends Component<PostFormProps, PostFormState> {
</div> </div>
</div> </div>
{!this.props.post_view && ( {!this.props.post_view && (
<div className="form-group row"> <div className="mb-3 row">
<label className="col-sm-2 col-form-label" htmlFor="post-community"> <label className="col-sm-2 col-form-label" htmlFor="post-community">
{i18n.t("community")} {i18n.t("community")}
</label> </label>
@ -378,7 +381,7 @@ export class PostForm extends Component<PostFormProps, PostFormState> {
</div> </div>
)} )}
{this.props.enableNsfw && ( {this.props.enableNsfw && (
<div className="form-group row"> <div className="mb-3 row">
<legend className="col-form-label col-sm-2 pt-0"> <legend className="col-form-label col-sm-2 pt-0">
{i18n.t("nsfw")} {i18n.t("nsfw")}
</legend> </legend>
@ -412,12 +415,12 @@ export class PostForm extends Component<PostFormProps, PostFormState> {
value={this.state.form.honeypot} value={this.state.form.honeypot}
onInput={linkEvent(this, this.handleHoneyPotChange)} onInput={linkEvent(this, this.handleHoneyPotChange)}
/> />
<div className="form-group row"> <div className="mb-3 row">
<div className="col-sm-10"> <div className="col-sm-10">
<button <button
disabled={!this.state.form.community_id || this.state.loading} disabled={!this.state.form.community_id || this.state.loading}
type="submit" type="submit"
className="btn btn-secondary mr-2" className="btn btn-secondary me-2"
> >
{this.state.loading ? ( {this.state.loading ? (
<Spinner /> <Spinner />

View File

@ -1,3 +1,14 @@
import { canShare, share } from "@utils/browser";
import {
amAdmin,
amCommunityCreator,
amMod,
canAdmin,
canMod,
isAdmin,
isBanned,
isMod,
} from "@utils/roles";
import classNames from "classnames"; import classNames from "classnames";
import { Component, linkEvent } from "inferno"; import { Component, linkEvent } from "inferno";
import { Link } from "inferno-router"; import { Link } from "inferno-router";
@ -28,18 +39,9 @@ import { i18n } from "../../i18next";
import { BanType, PostFormParams, PurgeType, VoteType } from "../../interfaces"; import { BanType, PostFormParams, PurgeType, VoteType } from "../../interfaces";
import { UserService } from "../../services"; import { UserService } from "../../services";
import { import {
amAdmin,
amCommunityCreator,
amMod,
canAdmin,
canMod,
canShare,
futureDaysToUnixTime, futureDaysToUnixTime,
hostname, hostname,
isAdmin,
isBanned,
isImage, isImage,
isMod,
isVideo, isVideo,
mdNoImages, mdNoImages,
mdToHtml, mdToHtml,
@ -49,7 +51,6 @@ import {
numToSI, numToSI,
relTags, relTags,
setupTippy, setupTippy,
share,
showScores, showScores,
} from "../../utils"; } from "../../utils";
import { Icon, PurgeWarning, Spinner } from "../common/icon"; import { Icon, PurgeWarning, Spinner } from "../common/icon";
@ -201,7 +202,7 @@ export class PostListing extends Component<PostListingProps, PostListingState> {
const post = this.postView.post; const post = this.postView.post;
return ( return (
<div className="post-listing"> <div className="post-listing mt-2">
{!this.state.showEdit ? ( {!this.state.showEdit ? (
<> <>
{this.listing()} {this.listing()}
@ -230,13 +231,13 @@ export class PostListing extends Component<PostListingProps, PostListingState> {
body() { body() {
const body = this.postView.post.body; const body = this.postView.post.body;
return body ? ( return body ? (
<div className="col-12 card my-2 p-2"> <article id="postContent" className="col-12 card my-2 p-2">
{this.state.viewSource ? ( {this.state.viewSource ? (
<pre>{body}</pre> <pre>{body}</pre>
) : ( ) : (
<div className="md-div" dangerouslySetInnerHTML={mdToHtml(body)} /> <div className="md-div" dangerouslySetInnerHTML={mdToHtml(body)} />
)} )}
</div> </article>
) : ( ) : (
<></> <></>
); );
@ -367,33 +368,31 @@ export class PostListing extends Component<PostListingProps, PostListingState> {
createdLine() { createdLine() {
const post_view = this.postView; const post_view = this.postView;
const url = post_view.post.url;
const body = post_view.post.body;
return ( return (
<ul className="list-inline mb-1 text-muted small"> <ul className="list-inline mb-1 text-muted small mt-2">
<li className="list-inline-item"> <li className="list-inline-item">
<PersonListing person={post_view.creator} /> <PersonListing person={post_view.creator} />
{this.creatorIsMod_ && ( {this.creatorIsMod_ && (
<span className="mx-1 badge">{i18n.t("mod")}</span> <span className="mx-1 badge text-bg-light">{i18n.t("mod")}</span>
)} )}
{this.creatorIsAdmin_ && ( {this.creatorIsAdmin_ && (
<span className="mx-1 badge">{i18n.t("admin")}</span> <span className="mx-1 badge text-bg-light">{i18n.t("admin")}</span>
)} )}
{post_view.creator.bot_account && ( {post_view.creator.bot_account && (
<span className="mx-1 badge"> <span className="mx-1 badge text-bg-light">
{i18n.t("bot_account").toLowerCase()} {i18n.t("bot_account").toLowerCase()}
</span> </span>
)} )}
{this.props.showCommunity && ( {this.props.showCommunity && (
<span> <>
<span className="mx-1"> {i18n.t("to")} </span> {" "}
<CommunityLink community={post_view.community} /> {i18n.t("to")} <CommunityLink community={post_view.community} />
</span> </>
)} )}
</li> </li>
{post_view.post.language_id !== 0 && ( {post_view.post.language_id !== 0 && (
<span className="mx-1 badge"> <span className="mx-1 badge text-bg-light">
{ {
this.props.allLanguages.find( this.props.allLanguages.find(
lang => lang.id === post_view.post.language_id lang => lang.id === post_view.post.language_id
@ -402,21 +401,6 @@ export class PostListing extends Component<PostListingProps, PostListingState> {
</span> </span>
)} )}
<li className="list-inline-item"></li> <li className="list-inline-item"></li>
{url && !(hostname(url) === getExternalHost()) && (
<>
<li className="list-inline-item">
<a
className="text-muted font-italic"
href={url}
title={url}
rel={relTags}
>
{hostname(url)}
</a>
</li>
<li className="list-inline-item"></li>
</>
)}
<li className="list-inline-item"> <li className="list-inline-item">
<span> <span>
<MomentTime <MomentTime
@ -425,28 +409,13 @@ export class PostListing extends Component<PostListingProps, PostListingState> {
/> />
</span> </span>
</li> </li>
{body && (
<>
<li className="list-inline-item"></li>
<li className="list-inline-item">
<button
className="text-muted btn btn-sm btn-link p-0"
data-tippy-content={mdNoImages.render(body)}
data-tippy-allowHtml={true}
onClick={linkEvent(this, this.handleShowBody)}
>
<Icon icon="book-open" classes="icon-inline mr-1" />
</button>
</li>
</>
)}
</ul> </ul>
); );
} }
voteBar() { voteBar() {
return ( return (
<div className={`vote-bar col-1 pr-0 small text-center`}> <div className={`vote-bar col-1 pe-0 small text-center`}>
<button <button
className={`btn-animate btn btn-link p-0 ${ className={`btn-animate btn btn-link p-0 ${
this.postView.my_vote == 1 ? "text-info" : "text-muted" this.postView.my_vote == 1 ? "text-info" : "text-muted"
@ -464,7 +433,7 @@ export class PostListing extends Component<PostListingProps, PostListingState> {
</button> </button>
{showScores() ? ( {showScores() ? (
<div <div
className={`unselectable pointer font-weight-bold text-muted px-1`} className={`unselectable pointer text-muted px-1 post-score`}
data-tippy-content={this.pointsTippy} data-tippy-content={this.pointsTippy}
> >
{numToSI(this.postView.counts.score)} {numToSI(this.postView.counts.score)}
@ -497,7 +466,7 @@ export class PostListing extends Component<PostListingProps, PostListingState> {
const post = this.postView.post; const post = this.postView.post;
return ( return (
<Link <Link
className={`d-inline-block ${ className={`d-inline ${
!post.featured_community && !post.featured_local !post.featured_community && !post.featured_local
? "text-body" ? "text-body"
: "text-primary" : "text-primary"
@ -505,8 +474,8 @@ export class PostListing extends Component<PostListingProps, PostListingState> {
to={`/post/${post.id}`} to={`/post/${post.id}`}
title={i18n.t("comments")} title={i18n.t("comments")}
> >
<div <span
className="d-inline-block" className="d-inline"
dangerouslySetInnerHTML={mdToHtmlInline(post.name)} dangerouslySetInnerHTML={mdToHtmlInline(post.name)}
/> />
</Link> </Link>
@ -518,35 +487,29 @@ export class PostListing extends Component<PostListingProps, PostListingState> {
const url = post.url; const url = post.url;
return ( return (
<div className="post-title overflow-hidden"> <>
<h5> <div className="post-title overflow-hidden">
{url ? ( <h5 className="d-inline">
this.props.showBody ? ( {url && this.props.showBody ? (
<a <a
className={`d-inline-block ${ className={
!post.featured_community && !post.featured_local !post.featured_community && !post.featured_local
? "text-body" ? "text-body"
: "text-primary" : "text-primary"
}`} }
href={url} href={url}
title={url} title={url}
rel={relTags} rel={relTags}
> dangerouslySetInnerHTML={mdToHtmlInline(post.name)}
<div ></a>
className="d-inline-block"
dangerouslySetInnerHTML={mdToHtmlInline(post.name)}
/>
</a>
) : ( ) : (
this.postLink this.postLink
) )}
) : ( </h5>
this.postLink
)}
{(url && isImage(url)) || {(url && isImage(url)) ||
(post.thumbnail_url && ( (post.thumbnail_url && (
<button <button
className="btn btn-link text-monospace text-muted small d-inline-block" className="btn btn-sm text-monospace text-muted d-inline-block"
data-tippy-content={i18n.t("expand_here")} data-tippy-content={i18n.t("expand_here")}
onClick={linkEvent(this, this.handleImageExpandClick)} onClick={linkEvent(this, this.handleImageExpandClick)}
> >
@ -559,13 +522,13 @@ export class PostListing extends Component<PostListingProps, PostListingState> {
</button> </button>
))} ))}
{post.removed && ( {post.removed && (
<small className="ml-2 text-muted font-italic"> <small className="ms-2 badge text-bg-secondary">
{i18n.t("removed")} {i18n.t("removed")}
</small> </small>
)} )}
{post.deleted && ( {post.deleted && (
<small <small
className="unselectable pointer ml-2 text-muted font-italic" className="unselectable pointer ms-2 text-muted font-italic"
data-tippy-content={i18n.t("deleted")} data-tippy-content={i18n.t("deleted")}
> >
<Icon icon="trash" classes="icon-inline text-danger" /> <Icon icon="trash" classes="icon-inline text-danger" />
@ -573,7 +536,7 @@ export class PostListing extends Component<PostListingProps, PostListingState> {
)} )}
{post.locked && ( {post.locked && (
<small <small
className="unselectable pointer ml-2 text-muted font-italic" className="unselectable pointer ms-2 text-muted font-italic"
data-tippy-content={i18n.t("locked")} data-tippy-content={i18n.t("locked")}
> >
<Icon icon="lock" classes="icon-inline text-danger" /> <Icon icon="lock" classes="icon-inline text-danger" />
@ -581,27 +544,50 @@ export class PostListing extends Component<PostListingProps, PostListingState> {
)} )}
{post.featured_community && ( {post.featured_community && (
<small <small
className="unselectable pointer ml-2 text-muted font-italic" className="unselectable pointer ms-2 text-muted font-italic"
data-tippy-content={i18n.t("featured")} data-tippy-content={i18n.t("featured_in_community")}
aria-label={i18n.t("featured_in_community")}
> >
<Icon icon="pin" classes="icon-inline text-primary" /> <Icon icon="pin" classes="icon-inline text-primary" />
</small> </small>
)} )}
{post.featured_local && ( {post.featured_local && (
<small <small
className="unselectable pointer ml-2 text-muted font-italic" className="unselectable pointer ms-2 text-muted font-italic"
data-tippy-content={i18n.t("featured")} data-tippy-content={i18n.t("featured_in_local")}
aria-label={i18n.t("featured_in_local")}
> >
<Icon icon="pin" classes="icon-inline text-secondary" /> <Icon icon="pin" classes="icon-inline text-secondary" />
</small> </small>
)} )}
{post.nsfw && ( {post.nsfw && (
<small className="ml-2 text-muted font-italic"> <small className="ms-2 badge text-bg-danger">
{i18n.t("nsfw")} {i18n.t("nsfw")}
</small> </small>
)} )}
</h5> </div>
</div> {url && this.urlLine()}
</>
);
}
urlLine() {
const post = this.postView.post;
const url = post.url;
return (
<p className="d-flex text-muted align-items-center gap-1 small m-0">
{url && !(hostname(url) === getExternalHost()) && (
<a
className="text-muted font-italic"
href={url}
title={url}
rel={relTags}
>
{hostname(url)}
</a>
)}
</p>
); );
} }
@ -610,9 +596,9 @@ export class PostListing extends Component<PostListingProps, PostListingState> {
return dupes && dupes.length > 0 ? ( return dupes && dupes.length > 0 ? (
<ul className="list-inline mb-1 small text-muted"> <ul className="list-inline mb-1 small text-muted">
<> <>
<li className="list-inline-item mr-2">{i18n.t("cross_posted_to")}</li> <li className="list-inline-item me-2">{i18n.t("cross_posted_to")}</li>
{dupes.map(pv => ( {dupes.map(pv => (
<li key={pv.post.id} className="list-inline-item mr-2"> <li key={pv.post.id} className="list-inline-item me-2">
<Link to={`/post/${pv.post.id}`}> <Link to={`/post/${pv.post.id}`}>
{pv.community.local {pv.community.local
? pv.community.name ? pv.community.name
@ -631,11 +617,11 @@ export class PostListing extends Component<PostListingProps, PostListingState> {
const post = this.postView.post; const post = this.postView.post;
return ( return (
<div className="d-flex justify-content-start flex-wrap text-muted font-weight-bold mb-1"> <div className="d-flex align-items-center justify-content-start flex-wrap text-muted">
{this.commentsButton} {this.commentsButton}
{canShare() && ( {canShare() && (
<button <button
className="btn btn-link" className="btn btn-sm btn-animate text-muted py-0"
onClick={linkEvent(this, this.handleShare)} onClick={linkEvent(this, this.handleShare)}
type="button" type="button"
> >
@ -644,7 +630,7 @@ export class PostListing extends Component<PostListingProps, PostListingState> {
)} )}
{!post.local && ( {!post.local && (
<a <a
className="btn btn-link btn-animate text-muted py-0" className="btn btn-sm btn-animate text-muted py-0"
title={i18n.t("link")} title={i18n.t("link")}
href={post.ap_id} href={post.ap_id}
> >
@ -654,50 +640,94 @@ export class PostListing extends Component<PostListingProps, PostListingState> {
{mobile && !this.props.viewOnly && this.mobileVotes} {mobile && !this.props.viewOnly && this.mobileVotes}
{UserService.Instance.myUserInfo && {UserService.Instance.myUserInfo &&
!this.props.viewOnly && !this.props.viewOnly &&
this.postActions(mobile)} this.postActions()}
</div> </div>
); );
} }
postActions(mobile = false) { showPreviewButton() {
const post_view = this.postView;
const body = post_view.post.body;
return (
<button
className="btn btn-sm btn-animate text-muted py-0"
data-tippy-content={body && mdNoImages.render(body)}
data-tippy-allowHtml={true}
onClick={linkEvent(this, this.handleShowBody)}
>
<Icon
icon="book-open"
classes={classNames("icon-inline me-1", {
"text-success": this.state.showBody,
})}
/>
</button>
);
}
postActions() {
// Possible enhancement: Priority+ pattern instead of just hard coding which get hidden behind the show more button. // Possible enhancement: Priority+ pattern instead of just hard coding which get hidden behind the show more button.
// Possible enhancement: Make each button a component. // Possible enhancement: Make each button a component.
const post_view = this.postView; const post_view = this.postView;
const post = post_view.post;
return ( return (
<> <>
{this.saveButton} {this.saveButton}
{this.crossPostButton} {this.crossPostButton}
{mobile && this.showMoreButton}
{(!mobile || this.state.showAdvanced) && ( {/**
<> * If there is a URL, or if the post has a body and we were told not to
{!this.myPost && ( * show the body, show the MetadataCard/body toggle.
*/}
{(post.url || (post.body && !this.props.showBody)) &&
this.showPreviewButton()}
{this.showBody && post_view.post.body && this.viewSourceButton}
<div className="dropdown">
<button
className="btn btn-sm btn-animate text-muted py-0 dropdown-toggle"
onClick={linkEvent(this, this.handleShowAdvanced)}
data-tippy-content={i18n.t("more")}
data-bs-toggle="dropdown"
aria-expanded="false"
aria-controls="advancedButtonsDropdown"
aria-label={i18n.t("more")}
>
<Icon icon="more-vertical" inline />
</button>
<ul className="dropdown-menu" id="advancedButtonsDropdown">
{!this.myPost ? (
<> <>
{this.reportButton} <li>{this.reportButton}</li>
{this.blockButton} <li>{this.blockButton}</li>
</>
) : (
<>
<li>{this.editButton}</li>
<li>{this.deleteButton}</li>
</> </>
)} )}
{this.myPost && (this.showBody || this.state.showAdvanced) && (
<>
{this.editButton}
{this.deleteButton}
</>
)}
</>
)}
{this.state.showAdvanced && (
<>
{this.showBody && post_view.post.body && this.viewSourceButton}
{/* Any mod can do these, not limited to hierarchy*/} {/* Any mod can do these, not limited to hierarchy*/}
{(amMod(this.props.moderators) || amAdmin()) && ( {(amMod(this.props.moderators) || amAdmin()) && (
<> <>
{this.lockButton} <li>
{this.featureButton} <hr className="dropdown-divider" />
</li>
<li>{this.lockButton}</li>
{this.featureButtons}
</> </>
)} )}
{(this.canMod_ || this.canAdmin_) && <>{this.modRemoveButton}</>}
</> {(this.canMod_ || this.canAdmin_) && (
)} <li>{this.modRemoveButton}</li>
{!mobile && this.showMoreButton} )}
</ul>
</div>
</> </>
); );
} }
@ -706,15 +736,15 @@ export class PostListing extends Component<PostListingProps, PostListingState> {
const post_view = this.postView; const post_view = this.postView;
return ( return (
<Link <Link
className="btn btn-link text-muted py-0 pl-0 text-muted" className="btn btn-link text-muted ps-0 text-muted"
title={i18n.t("number_of_comments", { title={i18n.t("number_of_comments", {
count: Number(post_view.counts.comments), count: Number(post_view.counts.comments),
formattedCount: Number(post_view.counts.comments), formattedCount: Number(post_view.counts.comments),
})} })}
to={`/post/${post_view.post.id}?scrollToComments=true`} to={`/post/${post_view.post.id}?scrollToComments=true`}
> >
<Icon icon="message-square" classes="mr-1" inline /> <Icon icon="message-square" classes="me-1" inline />
<span className="mr-2"> <span className="me-2">
{i18n.t("number_of_comments", { {i18n.t("number_of_comments", {
count: Number(post_view.counts.comments), count: Number(post_view.counts.comments),
formattedCount: numToSI(post_view.counts.comments), formattedCount: numToSI(post_view.counts.comments),
@ -759,7 +789,7 @@ export class PostListing extends Component<PostListingProps, PostListingState> {
<> <>
<Icon icon="arrow-up1" classes="icon-inline small" /> <Icon icon="arrow-up1" classes="icon-inline small" />
{showScores() && ( {showScores() && (
<span className="ml-2"> <span className="ms-2">
{numToSI(this.postView.counts.upvotes)} {numToSI(this.postView.counts.upvotes)}
</span> </span>
)} )}
@ -768,7 +798,7 @@ export class PostListing extends Component<PostListingProps, PostListingState> {
</button> </button>
{this.props.enableDownvotes && ( {this.props.enableDownvotes && (
<button <button
className={`ml-2 btn-animate btn py-0 px-1 ${ className={`ms-2 btn-animate btn py-0 px-1 ${
this.postView.my_vote === -1 ? "text-danger" : "text-muted" this.postView.my_vote === -1 ? "text-danger" : "text-muted"
}`} }`}
onClick={linkEvent(this, this.handleDownvote)} onClick={linkEvent(this, this.handleDownvote)}
@ -783,7 +813,7 @@ export class PostListing extends Component<PostListingProps, PostListingState> {
<Icon icon="arrow-down1" classes="icon-inline small" /> <Icon icon="arrow-down1" classes="icon-inline small" />
{showScores() && ( {showScores() && (
<span <span
className={classNames("ml-2", { className={classNames("ms-2", {
invisible: this.postView.counts.downvotes === 0, invisible: this.postView.counts.downvotes === 0,
})} })}
> >
@ -804,7 +834,7 @@ export class PostListing extends Component<PostListingProps, PostListingState> {
const label = saved ? i18n.t("unsave") : i18n.t("save"); const label = saved ? i18n.t("unsave") : i18n.t("save");
return ( return (
<button <button
className="btn btn-link btn-animate text-muted py-0" className="btn btn-sm btn-animate text-muted py-0"
onClick={linkEvent(this, this.handleSavePostClick)} onClick={linkEvent(this, this.handleSavePostClick)}
data-tippy-content={label} data-tippy-content={label}
aria-label={label} aria-label={label}
@ -825,7 +855,7 @@ export class PostListing extends Component<PostListingProps, PostListingState> {
get crossPostButton() { get crossPostButton() {
return ( return (
<Link <Link
className="btn btn-link btn-animate text-muted py-0" className="btn btn-sm btn-animate text-muted py-0"
to={{ to={{
/* Empty string properties are required to satisfy type*/ /* Empty string properties are required to satisfy type*/
pathname: "/create_post", pathname: "/create_post",
@ -846,12 +876,12 @@ export class PostListing extends Component<PostListingProps, PostListingState> {
get reportButton() { get reportButton() {
return ( return (
<button <button
className="btn btn-link btn-animate text-muted py-0" className="btn btn-link btn-sm d-flex align-items-center rounded-0 dropdown-item"
onClick={linkEvent(this, this.handleShowReportDialog)} onClick={linkEvent(this, this.handleShowReportDialog)}
data-tippy-content={i18n.t("show_report_dialog")}
aria-label={i18n.t("show_report_dialog")} aria-label={i18n.t("show_report_dialog")}
> >
<Icon icon="flag" inline /> <Icon classes="me-1" icon="flag" inline />
{i18n.t("create_report")}
</button> </button>
); );
} }
@ -859,12 +889,16 @@ export class PostListing extends Component<PostListingProps, PostListingState> {
get blockButton() { get blockButton() {
return ( return (
<button <button
className="btn btn-link btn-animate text-muted py-0" className="btn btn-link btn-sm d-flex align-items-center rounded-0 dropdown-item"
onClick={linkEvent(this, this.handleBlockPersonClick)} onClick={linkEvent(this, this.handleBlockPersonClick)}
data-tippy-content={i18n.t("block_user")}
aria-label={i18n.t("block_user")} aria-label={i18n.t("block_user")}
> >
{this.state.blockLoading ? <Spinner /> : <Icon icon="slash" inline />} {this.state.blockLoading ? (
<Spinner />
) : (
<Icon classes="me-1" icon="slash" inline />
)}
{i18n.t("block_user")}
</button> </button>
); );
} }
@ -872,12 +906,12 @@ export class PostListing extends Component<PostListingProps, PostListingState> {
get editButton() { get editButton() {
return ( return (
<button <button
className="btn btn-link btn-animate text-muted py-0" className="btn btn-link btn-sm d-flex align-items-center rounded-0 dropdown-item"
onClick={linkEvent(this, this.handleEditClick)} onClick={linkEvent(this, this.handleEditClick)}
data-tippy-content={i18n.t("edit")}
aria-label={i18n.t("edit")} aria-label={i18n.t("edit")}
> >
<Icon icon="edit" inline /> <Icon classes="me-1" icon="edit" inline />
{i18n.t("edit")}
</button> </button>
); );
} }
@ -887,41 +921,30 @@ export class PostListing extends Component<PostListingProps, PostListingState> {
const label = !deleted ? i18n.t("delete") : i18n.t("restore"); const label = !deleted ? i18n.t("delete") : i18n.t("restore");
return ( return (
<button <button
className="btn btn-link btn-animate text-muted py-0" className="btn btn-link btn-sm d-flex align-items-center rounded-0 dropdown-item"
onClick={linkEvent(this, this.handleDeleteClick)} onClick={linkEvent(this, this.handleDeleteClick)}
data-tippy-content={label}
aria-label={label} aria-label={label}
> >
{this.state.deleteLoading ? ( {this.state.deleteLoading ? (
<Spinner /> <Spinner />
) : ( ) : (
<Icon <>
icon="trash" <Icon
classes={classNames({ "text-danger": deleted })} icon="trash"
inline classes={classNames("me-1", { "text-danger": deleted })}
/> inline
/>
{label}
</>
)} )}
</button> </button>
); );
} }
get showMoreButton() {
return (
<button
className="btn btn-link btn-animate text-muted py-0"
onClick={linkEvent(this, this.handleShowAdvanced)}
data-tippy-content={i18n.t("more")}
aria-label={i18n.t("more")}
>
<Icon icon="more-vertical" inline />
</button>
);
}
get viewSourceButton() { get viewSourceButton() {
return ( return (
<button <button
className="btn btn-link btn-animate text-muted py-0" className="btn btn-sm btn-animate text-muted py-0"
onClick={linkEvent(this, this.handleViewSource)} onClick={linkEvent(this, this.handleViewSource)}
data-tippy-content={i18n.t("view_source")} data-tippy-content={i18n.t("view_source")}
aria-label={i18n.t("view_source")} aria-label={i18n.t("view_source")}
@ -940,25 +963,27 @@ export class PostListing extends Component<PostListingProps, PostListingState> {
const label = locked ? i18n.t("unlock") : i18n.t("lock"); const label = locked ? i18n.t("unlock") : i18n.t("lock");
return ( return (
<button <button
className="btn btn-link btn-animate text-muted py-0" className="btn btn-link btn-sm d-flex align-items-center rounded-0 dropdown-item"
onClick={linkEvent(this, this.handleModLock)} onClick={linkEvent(this, this.handleModLock)}
data-tippy-content={label}
aria-label={label} aria-label={label}
> >
{this.state.lockLoading ? ( {this.state.lockLoading ? (
<Spinner /> <Spinner />
) : ( ) : (
<Icon <>
icon="lock" <Icon
classes={classNames({ "text-danger": locked })} icon="lock"
inline classes={classNames("me-1", { "text-danger": locked })}
/> inline
/>
{label}
</>
)} )}
</button> </button>
); );
} }
get featureButton() { get featureButtons() {
const featuredCommunity = this.postView.post.featured_community; const featuredCommunity = this.postView.post.featured_community;
const labelCommunity = featuredCommunity const labelCommunity = featuredCommunity
? i18n.t("unfeature_from_community") ? i18n.t("unfeature_from_community")
@ -969,48 +994,56 @@ export class PostListing extends Component<PostListingProps, PostListingState> {
? i18n.t("unfeature_from_local") ? i18n.t("unfeature_from_local")
: i18n.t("feature_in_local"); : i18n.t("feature_in_local");
return ( return (
<span> <>
<button <li>
className="btn btn-link btn-animate text-muted py-0 pl-0"
onClick={linkEvent(this, this.handleModFeaturePostCommunity)}
data-tippy-content={labelCommunity}
aria-label={labelCommunity}
>
{this.state.featureCommunityLoading ? (
<Spinner />
) : (
<span>
<Icon
icon="pin"
classes={classNames({ "text-success": featuredCommunity })}
inline
/>
{i18n.t("community")}
</span>
)}
</button>
{amAdmin() && (
<button <button
className="btn btn-link btn-animate text-muted py-0" className="btn btn-link btn-sm d-flex align-items-center rounded-0 dropdown-item"
onClick={linkEvent(this, this.handleModFeaturePostLocal)} onClick={linkEvent(this, this.handleModFeaturePostCommunity)}
data-tippy-content={labelLocal} data-tippy-content={labelCommunity}
aria-label={labelLocal} aria-label={labelCommunity}
> >
{this.state.featureLocalLoading ? ( {this.state.featureCommunityLoading ? (
<Spinner /> <Spinner />
) : ( ) : (
<span> <>
<Icon <Icon
icon="pin" icon="pin"
classes={classNames({ "text-success": featuredLocal })} classes={classNames("me-1", {
"text-success": featuredCommunity,
})}
inline inline
/> />
{i18n.t("local")} {i18n.t("community")}
</span> </>
)} )}
</button> </button>
)} </li>
</span> <li>
{amAdmin() && (
<button
className="btn btn-link btn-sm d-flex align-items-center rounded-0 dropdown-item"
onClick={linkEvent(this, this.handleModFeaturePostLocal)}
data-tippy-content={labelLocal}
aria-label={labelLocal}
>
{this.state.featureLocalLoading ? (
<Spinner />
) : (
<>
<Icon
icon="pin"
classes={classNames("me-1", {
"text-success": featuredLocal,
})}
inline
/>
{i18n.t("local")}
</>
)}
</button>
)}
</li>
</>
); );
} }
@ -1018,7 +1051,7 @@ export class PostListing extends Component<PostListingProps, PostListingState> {
const removed = this.postView.post.removed; const removed = this.postView.post.removed;
return ( return (
<button <button
className="btn btn-link btn-animate text-muted py-0" className="btn btn-link btn-sm d-flex align-items-center rounded-0 dropdown-item"
onClick={linkEvent( onClick={linkEvent(
this, this,
!removed ? this.handleModRemoveShow : this.handleModRemoveSubmit !removed ? this.handleModRemoveShow : this.handleModRemoveSubmit
@ -1110,13 +1143,13 @@ export class PostListing extends Component<PostListingProps, PostListingState> {
) : ( ) : (
<> <>
<button <button
className="d-inline-block mr-1 btn btn-link btn-animate text-muted py-0" className="d-inline-block me-1 btn btn-link btn-animate text-muted py-0"
aria-label={i18n.t("are_you_sure")} aria-label={i18n.t("are_you_sure")}
> >
{i18n.t("are_you_sure")} {i18n.t("are_you_sure")}
</button> </button>
<button <button
className="btn btn-link btn-animate text-muted py-0 d-inline-block mr-1" className="btn btn-link btn-animate text-muted py-0 d-inline-block me-1"
aria-label={i18n.t("yes")} aria-label={i18n.t("yes")}
onClick={linkEvent(this, this.handleTransferCommunity)} onClick={linkEvent(this, this.handleTransferCommunity)}
> >
@ -1215,13 +1248,16 @@ export class PostListing extends Component<PostListingProps, PostListingState> {
className="form-inline" className="form-inline"
onSubmit={linkEvent(this, this.handleModRemoveSubmit)} onSubmit={linkEvent(this, this.handleModRemoveSubmit)}
> >
<label className="sr-only" htmlFor="post-listing-remove-reason"> <label
className="visually-hidden"
htmlFor="post-listing-remove-reason"
>
{i18n.t("reason")} {i18n.t("reason")}
</label> </label>
<input <input
type="text" type="text"
id="post-listing-remove-reason" id="post-listing-remove-reason"
className="form-control mr-2" className="form-control me-2"
placeholder={i18n.t("reason")} placeholder={i18n.t("reason")}
value={this.state.removeReason} value={this.state.removeReason}
onInput={linkEvent(this, this.handleModRemoveReasonChange)} onInput={linkEvent(this, this.handleModRemoveReasonChange)}
@ -1237,7 +1273,7 @@ export class PostListing extends Component<PostListingProps, PostListingState> {
)} )}
{this.state.showBanDialog && ( {this.state.showBanDialog && (
<form onSubmit={linkEvent(this, this.handleModBanBothSubmit)}> <form onSubmit={linkEvent(this, this.handleModBanBothSubmit)}>
<div className="form-group row col-12"> <div className="mb-3 row col-12">
<label <label
className="col-form-label" className="col-form-label"
htmlFor="post-listing-ban-reason" htmlFor="post-listing-ban-reason"
@ -1247,7 +1283,7 @@ export class PostListing extends Component<PostListingProps, PostListingState> {
<input <input
type="text" type="text"
id="post-listing-ban-reason" id="post-listing-ban-reason"
className="form-control mr-2" className="form-control me-2"
placeholder={i18n.t("reason")} placeholder={i18n.t("reason")}
value={this.state.banReason} value={this.state.banReason}
onInput={linkEvent(this, this.handleModBanReasonChange)} onInput={linkEvent(this, this.handleModBanReasonChange)}
@ -1258,12 +1294,12 @@ export class PostListing extends Component<PostListingProps, PostListingState> {
<input <input
type="number" type="number"
id={`mod-ban-expires`} id={`mod-ban-expires`}
className="form-control mr-2" className="form-control me-2"
placeholder={i18n.t("number_of_days")} placeholder={i18n.t("number_of_days")}
value={this.state.banExpireDays} value={this.state.banExpireDays}
onInput={linkEvent(this, this.handleModBanExpireDaysChange)} onInput={linkEvent(this, this.handleModBanExpireDaysChange)}
/> />
<div className="form-group"> <div className="input-group mb-3">
<div className="form-check"> <div className="form-check">
<input <input
className="form-check-input" className="form-check-input"
@ -1283,11 +1319,11 @@ export class PostListing extends Component<PostListingProps, PostListingState> {
</div> </div>
</div> </div>
{/* TODO hold off on expires until later */} {/* TODO hold off on expires until later */}
{/* <div class="form-group row"> */} {/* <div class="mb-3 row"> */}
{/* <label class="col-form-label">Expires</label> */} {/* <label class="col-form-label">Expires</label> */}
{/* <input type="date" class="form-control mr-2" placeholder={i18n.t('expires')} value={this.state.banExpires} onInput={linkEvent(this, this.handleModBanExpiresChange)} /> */} {/* <input type="date" class="form-control me-2" placeholder={i18n.t('expires')} value={this.state.banExpires} onInput={linkEvent(this, this.handleModBanExpiresChange)} /> */}
{/* </div> */} {/* </div> */}
<div className="form-group row"> <div className="mb-3 row">
<button <button
type="submit" type="submit"
className="btn btn-secondary" className="btn btn-secondary"
@ -1309,13 +1345,13 @@ export class PostListing extends Component<PostListingProps, PostListingState> {
className="form-inline" className="form-inline"
onSubmit={linkEvent(this, this.handleReportSubmit)} onSubmit={linkEvent(this, this.handleReportSubmit)}
> >
<label className="sr-only" htmlFor="post-report-reason"> <label className="visually-hidden" htmlFor="post-report-reason">
{i18n.t("reason")} {i18n.t("reason")}
</label> </label>
<input <input
type="text" type="text"
id="post-report-reason" id="post-report-reason"
className="form-control mr-2" className="form-control me-2"
placeholder={i18n.t("reason")} placeholder={i18n.t("reason")}
required required
value={this.state.reportReason} value={this.state.reportReason}
@ -1336,13 +1372,13 @@ export class PostListing extends Component<PostListingProps, PostListingState> {
onSubmit={linkEvent(this, this.handlePurgeSubmit)} onSubmit={linkEvent(this, this.handlePurgeSubmit)}
> >
<PurgeWarning /> <PurgeWarning />
<label className="sr-only" htmlFor="purge-reason"> <label className="visually-hidden" htmlFor="purge-reason">
{i18n.t("reason")} {i18n.t("reason")}
</label> </label>
<input <input
type="text" type="text"
id="purge-reason" id="purge-reason"
className="form-control mr-2" className="form-control me-2"
placeholder={i18n.t("reason")} placeholder={i18n.t("reason")}
value={this.state.purgeReason} value={this.state.purgeReason}
onInput={linkEvent(this, this.handlePurgeReasonChange)} onInput={linkEvent(this, this.handlePurgeReasonChange)}
@ -1398,7 +1434,7 @@ export class PostListing extends Component<PostListingProps, PostListingState> {
<> <>
{/* The mobile view*/} {/* The mobile view*/}
<div className="d-block d-sm-none"> <div className="d-block d-sm-none">
<div className="row"> <article className="row post-container">
<div className="col-12"> <div className="col-12">
{this.createdLine()} {this.createdLine()}
@ -1413,14 +1449,14 @@ export class PostListing extends Component<PostListingProps, PostListingState> {
{this.duplicatesLine()} {this.duplicatesLine()}
{this.removeAndBanDialogs()} {this.removeAndBanDialogs()}
</div> </div>
</div> </article>
</div> </div>
{/* The larger view*/} {/* The larger view*/}
<div className="d-none d-sm-block"> <div className="d-none d-sm-block">
<div className="row"> <article className="row post-container">
{!this.props.viewOnly && this.voteBar()} {!this.props.viewOnly && this.voteBar()}
<div className="col-sm-2 pr-0"> <div className="col-sm-2 pe-0 post-media">
<div className="">{this.thumbnail()}</div> <div className="">{this.thumbnail()}</div>
</div> </div>
<div className="col-12 col-sm-9"> <div className="col-12 col-sm-9">
@ -1435,7 +1471,7 @@ export class PostListing extends Component<PostListingProps, PostListingState> {
</div> </div>
</div> </div>
</div> </div>
</div> </article>
</div> </div>
</> </>
); );

View File

@ -66,7 +66,7 @@ export class PostListings extends Component<PostListingsProps, any> {
render() { render() {
return ( return (
<div> <div className="post-listings">
{this.posts.length > 0 ? ( {this.posts.length > 0 ? (
this.posts.map((post_view, idx) => ( this.posts.map((post_view, idx) => (
<> <>
@ -96,9 +96,7 @@ export class PostListings extends Component<PostListingsProps, any> {
onAddAdmin={this.props.onAddAdmin} onAddAdmin={this.props.onAddAdmin}
onTransferCommunity={this.props.onTransferCommunity} onTransferCommunity={this.props.onTransferCommunity}
/> />
{idx + 1 !== this.posts.length && ( {idx + 1 !== this.posts.length && <hr className="my-3" />}
<hr className="my-3 border border-primary" />
)}
</> </>
)) ))
) : ( ) : (

View File

@ -60,7 +60,7 @@ export class PostReport extends Component<PostReportProps, PostReportState> {
}; };
return ( return (
<div> <div className="post-report">
<PostListing <PostListing
post_view={pv} post_view={pv}
showCommunity={true} showCommunity={true}

View File

@ -1,3 +1,5 @@
import { isBrowser } from "@utils/browser";
import { debounce } from "@utils/helpers";
import autosize from "autosize"; import autosize from "autosize";
import { Component, createRef, linkEvent, RefObject } from "inferno"; import { Component, createRef, linkEvent, RefObject } from "inferno";
import { import {
@ -64,7 +66,6 @@ import {
buildCommentsTree, buildCommentsTree,
commentsToFlatNodes, commentsToFlatNodes,
commentTreeMaxDepth, commentTreeMaxDepth,
debounce,
editComment, editComment,
editWith, editWith,
enableDownvotes, enableDownvotes,
@ -73,10 +74,10 @@ import {
getCommentParentId, getCommentParentId,
getDepthFromComment, getDepthFromComment,
getIdFromProps, getIdFromProps,
isBrowser,
isImage, isImage,
myAuth, myAuth,
restoreScrollPosition, restoreScrollPosition,
RouteDataResponse,
saveScrollPosition, saveScrollPosition,
setIsoData, setIsoData,
setupTippy, setupTippy,
@ -93,6 +94,11 @@ import { PostListing } from "./post-listing";
const commentsShownInterval = 15; const commentsShownInterval = 15;
type PostData = RouteDataResponse<{
postRes: GetPostResponse;
commentsRes: GetCommentsResponse;
}>;
interface PostState { interface PostState {
postId?: number; postId?: number;
commentId?: number; commentId?: number;
@ -110,7 +116,7 @@ interface PostState {
} }
export class Post extends Component<any, PostState> { export class Post extends Component<any, PostState> {
private isoData = setIsoData(this.context); private isoData = setIsoData<PostData>(this.context);
private commentScrollDebounced: () => void; private commentScrollDebounced: () => void;
state: PostState = { state: PostState = {
postRes: { state: "empty" }, postRes: { state: "empty" },
@ -169,7 +175,7 @@ export class Post extends Component<any, PostState> {
// Only fetch the data if coming from another route // Only fetch the data if coming from another route
if (FirstLoadService.isFirstLoad) { if (FirstLoadService.isFirstLoad) {
const [postRes, commentsRes] = this.isoData.routeData; const { commentsRes, postRes } = this.isoData.routeData;
this.state = { this.state = {
...this.state, ...this.state,
@ -220,13 +226,12 @@ export class Post extends Component<any, PostState> {
} }
} }
static fetchInitialData({ static async fetchInitialData({
auth,
client, client,
path, path,
}: InitialFetchRequest): Promise<any>[] { auth,
}: InitialFetchRequest): Promise<PostData> {
const pathSplit = path.split("/"); const pathSplit = path.split("/");
const promises: Promise<RequestState<any>>[] = [];
const pathType = pathSplit.at(1); const pathType = pathSplit.at(1);
const id = pathSplit.at(2) ? Number(pathSplit.at(2)) : undefined; const id = pathSplit.at(2) ? Number(pathSplit.at(2)) : undefined;
@ -252,10 +257,10 @@ export class Post extends Component<any, PostState> {
commentsForm.parent_id = id; commentsForm.parent_id = id;
} }
promises.push(client.getPost(postForm)); return {
promises.push(client.getComments(commentsForm)); postRes: await client.getPost(postForm),
commentsRes: await client.getComments(commentsForm),
return promises; };
} }
componentWillUnmount() { componentWillUnmount() {
@ -384,12 +389,13 @@ export class Post extends Component<any, PostState> {
disabled={res.post_view.post.locked} disabled={res.post_view.post.locked}
allLanguages={this.state.siteRes.all_languages} allLanguages={this.state.siteRes.all_languages}
siteLanguages={this.state.siteRes.discussion_languages} siteLanguages={this.state.siteRes.discussion_languages}
containerClass="post-comment-container"
onUpsertComment={this.handleCreateComment} onUpsertComment={this.handleCreateComment}
finished={this.state.finished.get(0)} finished={this.state.finished.get(0)}
/> />
<div className="d-block d-md-none"> <div className="d-block d-md-none">
<button <button
className="btn btn-secondary d-inline-block mb-2 mr-3" className="btn btn-secondary d-inline-block mb-2 me-3"
onClick={linkEvent(this, this.handleShowSidebarMobile)} onClick={linkEvent(this, this.handleShowSidebarMobile)}
> >
{i18n.t("sidebar")}{" "} {i18n.t("sidebar")}{" "}
@ -418,13 +424,13 @@ export class Post extends Component<any, PostState> {
} }
render() { render() {
return <div className="container-lg">{this.renderPostRes()}</div>; return <div className="post container-lg">{this.renderPostRes()}</div>;
} }
sortRadios() { sortRadios() {
return ( return (
<> <>
<div className="btn-group btn-group-toggle flex-wrap mr-3 mb-2"> <div className="btn-group btn-group-toggle flex-wrap me-3 mb-2">
<label <label
className={`btn btn-outline-secondary pointer ${ className={`btn btn-outline-secondary pointer ${
this.state.commentSort === "Hot" && "active" this.state.commentSort === "Hot" && "active"
@ -433,6 +439,7 @@ export class Post extends Component<any, PostState> {
{i18n.t("hot")} {i18n.t("hot")}
<input <input
type="radio" type="radio"
className="btn-check"
value={"Hot"} value={"Hot"}
checked={this.state.commentSort === "Hot"} checked={this.state.commentSort === "Hot"}
onChange={linkEvent(this, this.handleCommentSortChange)} onChange={linkEvent(this, this.handleCommentSortChange)}
@ -446,6 +453,7 @@ export class Post extends Component<any, PostState> {
{i18n.t("top")} {i18n.t("top")}
<input <input
type="radio" type="radio"
className="btn-check"
value={"Top"} value={"Top"}
checked={this.state.commentSort === "Top"} checked={this.state.commentSort === "Top"}
onChange={linkEvent(this, this.handleCommentSortChange)} onChange={linkEvent(this, this.handleCommentSortChange)}
@ -459,6 +467,7 @@ export class Post extends Component<any, PostState> {
{i18n.t("new")} {i18n.t("new")}
<input <input
type="radio" type="radio"
className="btn-check"
value={"New"} value={"New"}
checked={this.state.commentSort === "New"} checked={this.state.commentSort === "New"}
onChange={linkEvent(this, this.handleCommentSortChange)} onChange={linkEvent(this, this.handleCommentSortChange)}
@ -472,6 +481,7 @@ export class Post extends Component<any, PostState> {
{i18n.t("old")} {i18n.t("old")}
<input <input
type="radio" type="radio"
className="btn-check"
value={"Old"} value={"Old"}
checked={this.state.commentSort === "Old"} checked={this.state.commentSort === "Old"}
onChange={linkEvent(this, this.handleCommentSortChange)} onChange={linkEvent(this, this.handleCommentSortChange)}
@ -487,6 +497,7 @@ export class Post extends Component<any, PostState> {
{i18n.t("chat")} {i18n.t("chat")}
<input <input
type="radio" type="radio"
className="btn-check"
value={CommentViewType.Flat} value={CommentViewType.Flat}
checked={this.state.commentViewType === CommentViewType.Flat} checked={this.state.commentViewType === CommentViewType.Flat}
onChange={linkEvent(this, this.handleCommentViewTypeChange)} onChange={linkEvent(this, this.handleCommentViewTypeChange)}
@ -547,25 +558,22 @@ export class Post extends Component<any, PostState> {
const res = this.state.postRes; const res = this.state.postRes;
if (res.state === "success") { if (res.state === "success") {
return ( return (
<div className="mb-3"> <Sidebar
<Sidebar community_view={res.data.community_view}
community_view={res.data.community_view} moderators={res.data.moderators}
moderators={res.data.moderators} admins={this.state.siteRes.admins}
admins={this.state.siteRes.admins} enableNsfw={enableNsfw(this.state.siteRes)}
online={res.data.online} showIcon
enableNsfw={enableNsfw(this.state.siteRes)} allLanguages={this.state.siteRes.all_languages}
showIcon siteLanguages={this.state.siteRes.discussion_languages}
allLanguages={this.state.siteRes.all_languages} onDeleteCommunity={this.handleDeleteCommunityClick}
siteLanguages={this.state.siteRes.discussion_languages} onLeaveModTeam={this.handleAddModToCommunity}
onDeleteCommunity={this.handleDeleteCommunityClick} onFollowCommunity={this.handleFollow}
onLeaveModTeam={this.handleAddModToCommunity} onRemoveCommunity={this.handleModRemoveCommunity}
onFollowCommunity={this.handleFollow} onPurgeCommunity={this.handlePurgeCommunity}
onRemoveCommunity={this.handleModRemoveCommunity} onBlockCommunity={this.handleBlockCommunity}
onPurgeCommunity={this.handlePurgeCommunity} onEditCommunity={this.handleEditCommunity}
onBlockCommunity={this.handleBlockCommunity} />
onEditCommunity={this.handleEditCommunity}
/>
</div>
); );
} }
} }
@ -582,14 +590,14 @@ export class Post extends Component<any, PostState> {
{!!this.state.commentId && ( {!!this.state.commentId && (
<> <>
<button <button
className="pl-0 d-block btn btn-link text-muted" className="ps-0 d-block btn btn-link text-muted"
onClick={linkEvent(this, this.handleViewPost)} onClick={linkEvent(this, this.handleViewPost)}
> >
{i18n.t("view_all_comments")} {i18n.t("view_all_comments")}
</button> </button>
{showContextButton && ( {showContextButton && (
<button <button
className="pl-0 d-block btn btn-link text-muted" className="ps-0 d-block btn btn-link text-muted"
onClick={linkEvent(this, this.handleViewContext)} onClick={linkEvent(this, this.handleViewContext)}
> >
{i18n.t("show_context")} {i18n.t("show_context")}
@ -729,19 +737,14 @@ export class Post extends Component<any, PostState> {
async handleBlockCommunity(form: BlockCommunity) { async handleBlockCommunity(form: BlockCommunity) {
const blockCommunityRes = await HttpService.client.blockCommunity(form); const blockCommunityRes = await HttpService.client.blockCommunity(form);
// TODO Probably isn't necessary
this.setState(s => {
if (
s.postRes.state == "success" &&
blockCommunityRes.state == "success"
) {
s.postRes.data.community_view = blockCommunityRes.data.community_view;
}
return s;
});
if (blockCommunityRes.state == "success") { if (blockCommunityRes.state == "success") {
updateCommunityBlock(blockCommunityRes.data); updateCommunityBlock(blockCommunityRes.data);
this.setState(s => {
if (s.postRes.state == "success") {
s.postRes.data.community_view.blocked =
blockCommunityRes.data.blocked;
}
});
} }
} }

View File

@ -10,6 +10,7 @@ import { InitialFetchRequest } from "../../interfaces";
import { FirstLoadService } from "../../services/FirstLoadService"; import { FirstLoadService } from "../../services/FirstLoadService";
import { HttpService, RequestState } from "../../services/HttpService"; import { HttpService, RequestState } from "../../services/HttpService";
import { import {
RouteDataResponse,
getRecipientIdFromProps, getRecipientIdFromProps,
myAuth, myAuth,
setIsoData, setIsoData,
@ -19,6 +20,10 @@ import { HtmlTags } from "../common/html-tags";
import { Spinner } from "../common/icon"; import { Spinner } from "../common/icon";
import { PrivateMessageForm } from "./private-message-form"; import { PrivateMessageForm } from "./private-message-form";
type CreatePrivateMessageData = RouteDataResponse<{
recipientDetailsResponse: GetPersonDetailsResponse;
}>;
interface CreatePrivateMessageState { interface CreatePrivateMessageState {
siteRes: GetSiteResponse; siteRes: GetSiteResponse;
recipientRes: RequestState<GetPersonDetailsResponse>; recipientRes: RequestState<GetPersonDetailsResponse>;
@ -30,7 +35,7 @@ export class CreatePrivateMessage extends Component<
any, any,
CreatePrivateMessageState CreatePrivateMessageState
> { > {
private isoData = setIsoData(this.context); private isoData = setIsoData<CreatePrivateMessageData>(this.context);
state: CreatePrivateMessageState = { state: CreatePrivateMessageState = {
siteRes: this.isoData.site_res, siteRes: this.isoData.site_res,
recipientRes: { state: "empty" }, recipientRes: { state: "empty" },
@ -47,7 +52,7 @@ export class CreatePrivateMessage extends Component<
if (FirstLoadService.isFirstLoad) { if (FirstLoadService.isFirstLoad) {
this.state = { this.state = {
...this.state, ...this.state,
recipientRes: this.isoData.routeData[0], recipientRes: this.isoData.routeData.recipientDetailsResponse,
isIsomorphic: true, isIsomorphic: true,
}; };
} }
@ -59,6 +64,25 @@ export class CreatePrivateMessage extends Component<
} }
} }
static async fetchInitialData({
client,
path,
auth,
}: InitialFetchRequest): Promise<CreatePrivateMessageData> {
const person_id = Number(path.split("/").pop());
const form: GetPersonDetails = {
person_id,
sort: "New",
saved_only: false,
auth,
};
return {
recipientDetailsResponse: await client.getPersonDetails(form),
};
}
async fetchPersonDetails() { async fetchPersonDetails() {
this.setState({ this.setState({
recipientRes: { state: "loading" }, recipientRes: { state: "loading" },
@ -74,19 +98,6 @@ export class CreatePrivateMessage extends Component<
}); });
} }
static fetchInitialData(
req: InitialFetchRequest
): Promise<RequestState<any>>[] {
const person_id = Number(req.path.split("/").pop());
const form: GetPersonDetails = {
person_id,
sort: "New",
saved_only: false,
auth: req.auth,
};
return [req.client.getPersonDetails(form)];
}
get documentTitle(): string { get documentTitle(): string {
if (this.state.recipientRes.state == "success") { if (this.state.recipientRes.state == "success") {
const name_ = this.state.recipientRes.data.person_view.person.name; const name_ = this.state.recipientRes.data.person_view.person.name;
@ -123,7 +134,7 @@ export class CreatePrivateMessage extends Component<
render() { render() {
return ( return (
<div className="container-lg"> <div className="create-private-message container-lg">
<HtmlTags <HtmlTags
title={this.documentTitle} title={this.documentTitle}
path={this.context.router.route.match.url} path={this.context.router.route.match.url}

View File

@ -73,14 +73,17 @@ export class PrivateMessageForm extends Component<
render() { render() {
return ( return (
<form onSubmit={linkEvent(this, this.handlePrivateMessageSubmit)}> <form
className="private-message-form"
onSubmit={linkEvent(this, this.handlePrivateMessageSubmit)}
>
<NavigationPrompt <NavigationPrompt
when={ when={
!this.state.loading && !!this.state.content && !this.state.submitted !this.state.loading && !!this.state.content && !this.state.submitted
} }
/> />
{!this.props.privateMessageView && ( {!this.props.privateMessageView && (
<div className="form-group row"> <div className="mb-3 row">
<label className="col-sm-2 col-form-label"> <label className="col-sm-2 col-form-label">
{capitalizeFirstLetter(i18n.t("to"))} {capitalizeFirstLetter(i18n.t("to"))}
</label> </label>
@ -90,7 +93,7 @@ export class PrivateMessageForm extends Component<
</div> </div>
</div> </div>
)} )}
<div className="form-group row"> <div className="mb-3 row">
<label className="col-sm-2 col-form-label"> <label className="col-sm-2 col-form-label">
{i18n.t("message")} {i18n.t("message")}
<button <button
@ -114,7 +117,7 @@ export class PrivateMessageForm extends Component<
</div> </div>
{this.state.showDisclaimer && ( {this.state.showDisclaimer && (
<div className="form-group row"> <div className="mb-3 row">
<div className="offset-sm-2 col-sm-10"> <div className="offset-sm-2 col-sm-10">
<div className="alert alert-danger" role="alert"> <div className="alert alert-danger" role="alert">
<T i18nKey="private_message_disclaimer"> <T i18nKey="private_message_disclaimer">
@ -131,11 +134,11 @@ export class PrivateMessageForm extends Component<
</div> </div>
</div> </div>
)} )}
<div className="form-group row"> <div className="mb-3 row">
<div className="offset-sm-2 col-sm-10"> <div className="offset-sm-2 col-sm-10">
<button <button
type="submit" type="submit"
className="btn btn-secondary mr-2" className="btn btn-secondary me-2"
disabled={this.state.loading} disabled={this.state.loading}
> >
{this.state.loading ? ( {this.state.loading ? (

View File

@ -43,7 +43,7 @@ export class PrivateMessageReport extends Component<Props, State> {
); );
return ( return (
<div> <div className="private-message-report">
<div> <div>
{i18n.t("creator")}:{" "} {i18n.t("creator")}:{" "}
<PersonListing person={r.private_message_creator} /> <PersonListing person={r.private_message_creator} />

View File

@ -88,7 +88,7 @@ export class PrivateMessage extends Component<
: message_view.creator; : message_view.creator;
return ( return (
<div className="border-top border-light"> <div className="private-message border-top border-light">
<div> <div>
<ul className="list-inline mb-0 text-muted small"> <ul className="list-inline mb-0 text-muted small">
{/* TODO refactor this */} {/* TODO refactor this */}
@ -248,13 +248,13 @@ export class PrivateMessage extends Component<
className="form-inline" className="form-inline"
onSubmit={linkEvent(this, this.handleReportSubmit)} onSubmit={linkEvent(this, this.handleReportSubmit)}
> >
<label className="sr-only" htmlFor="pm-report-reason"> <label className="visually-hidden" htmlFor="pm-report-reason">
{i18n.t("reason")} {i18n.t("reason")}
</label> </label>
<input <input
type="text" type="text"
id="pm-report-reason" id="pm-report-reason"
className="form-control mr-2" className="form-control me-2"
placeholder={i18n.t("reason")} placeholder={i18n.t("reason")}
required required
value={this.state.reportReason} value={this.state.reportReason}

View File

@ -1,3 +1,5 @@
import { debounce, getQueryParams, getQueryString } from "@utils/helpers";
import type { QueryParams } from "@utils/types";
import type { NoOptionI18nKeys } from "i18next"; import type { NoOptionI18nKeys } from "i18next";
import { Component, linkEvent } from "inferno"; import { Component, linkEvent } from "inferno";
import { import {
@ -26,11 +28,10 @@ import { FirstLoadService } from "../services/FirstLoadService";
import { HttpService, RequestState } from "../services/HttpService"; import { HttpService, RequestState } from "../services/HttpService";
import { import {
Choice, Choice,
QueryParams, RouteDataResponse,
capitalizeFirstLetter, capitalizeFirstLetter,
commentsToFlatNodes, commentsToFlatNodes,
communityToChoice, communityToChoice,
debounce,
enableDownvotes, enableDownvotes,
enableNsfw, enableNsfw,
fetchCommunities, fetchCommunities,
@ -38,8 +39,6 @@ import {
fetchUsers, fetchUsers,
getIdFromString, getIdFromString,
getPageFromString, getPageFromString,
getQueryParams,
getQueryString,
getUpdatedSearchId, getUpdatedSearchId,
myAuth, myAuth,
numToSI, numToSI,
@ -70,6 +69,14 @@ interface SearchProps {
page: number; page: number;
} }
type SearchData = RouteDataResponse<{
communityResponse: GetCommunityResponse;
listCommunitiesResponse: ListCommunitiesResponse;
creatorDetailsResponse: GetPersonDetailsResponse;
searchResponse: SearchResponse;
resolveObjectResponse: ResolveObjectResponse;
}>;
type FilterType = "creator" | "community"; type FilterType = "creator" | "community";
interface SearchState { interface SearchState {
@ -173,8 +180,8 @@ const Filter = ({
loading: boolean; loading: boolean;
}) => { }) => {
return ( return (
<div className="form-group col-sm-6"> <div className="mb-3 col-sm-6">
<label className="col-form-label" htmlFor={`${filterType}-filter`}> <label className="col-form-label me-2" htmlFor={`${filterType}-filter`}>
{capitalizeFirstLetter(i18n.t(filterType))} {capitalizeFirstLetter(i18n.t(filterType))}
</label> </label>
<SearchableSelect <SearchableSelect
@ -228,7 +235,8 @@ function getListing(
} }
export class Search extends Component<any, SearchState> { export class Search extends Component<any, SearchState> {
private isoData = setIsoData(this.context); private isoData = setIsoData<SearchData>(this.context);
state: SearchState = { state: SearchState = {
resolveObjectRes: { state: "empty" }, resolveObjectRes: { state: "empty" },
creatorDetailsRes: { state: "empty" }, creatorDetailsRes: { state: "empty" },
@ -262,42 +270,63 @@ export class Search extends Component<any, SearchState> {
// Only fetch the data if coming from another route // Only fetch the data if coming from another route
if (FirstLoadService.isFirstLoad) { if (FirstLoadService.isFirstLoad) {
const [ const {
communityRes, communityResponse: communityRes,
communitiesRes, creatorDetailsResponse: creatorDetailsRes,
creatorDetailsRes, listCommunitiesResponse: communitiesRes,
searchRes, resolveObjectResponse: resolveObjectRes,
resolveObjectRes, searchResponse: searchRes,
] = this.isoData.routeData; } = this.isoData.routeData;
this.state = { this.state = {
...this.state, ...this.state,
communitiesRes,
communityRes,
creatorDetailsRes,
creatorSearchOptions:
creatorDetailsRes.state == "success"
? [personToChoice(creatorDetailsRes.data.person_view)]
: [],
isIsomorphic: true, isIsomorphic: true,
}; };
if (communityRes.state === "success") { if (creatorDetailsRes?.state === "success") {
this.state = { this.state = {
...this.state, ...this.state,
communitySearchOptions: [ creatorSearchOptions:
communityToChoice(communityRes.data.community_view), creatorDetailsRes?.state === "success"
], ? [personToChoice(creatorDetailsRes.data.person_view)]
: [],
creatorDetailsRes,
}; };
} }
if (q) { if (communitiesRes?.state === "success") {
this.state = { this.state = {
...this.state, ...this.state,
searchRes, communitiesRes,
resolveObjectRes,
}; };
} }
if (communityRes?.state === "success") {
this.state = {
...this.state,
communityRes,
};
}
if (q !== "") {
this.state = {
...this.state,
};
if (searchRes?.state === "success") {
this.state = {
...this.state,
searchRes,
};
}
if (resolveObjectRes?.state === "success") {
this.state = {
...this.state,
resolveObjectRes,
};
}
}
} }
} }
@ -328,23 +357,25 @@ export class Search extends Component<any, SearchState> {
saveScrollPosition(this.context); saveScrollPosition(this.context);
} }
static fetchInitialData({ static async fetchInitialData({
client, client,
auth, auth,
query: { communityId, creatorId, q, type, sort, listingType, page }, query: { communityId, creatorId, q, type, sort, listingType, page },
}: InitialFetchRequest<QueryParams<SearchProps>>): Promise< }: InitialFetchRequest<QueryParams<SearchProps>>): Promise<SearchData> {
RequestState<any>
>[] {
const promises: Promise<RequestState<any>>[] = [];
const community_id = getIdFromString(communityId); const community_id = getIdFromString(communityId);
let communityResponse: RequestState<GetCommunityResponse> = {
state: "empty",
};
let listCommunitiesResponse: RequestState<ListCommunitiesResponse> = {
state: "empty",
};
if (community_id) { if (community_id) {
const getCommunityForm: GetCommunity = { const getCommunityForm: GetCommunity = {
id: community_id, id: community_id,
auth, auth,
}; };
promises.push(client.getCommunity(getCommunityForm));
promises.push(Promise.resolve({ state: "empty" })); communityResponse = await client.getCommunity(getCommunityForm);
} else { } else {
const listCommunitiesForm: ListCommunities = { const listCommunitiesForm: ListCommunities = {
type_: defaultListingType, type_: defaultListingType,
@ -352,23 +383,32 @@ export class Search extends Component<any, SearchState> {
limit: fetchLimit, limit: fetchLimit,
auth, auth,
}; };
promises.push(Promise.resolve({ state: "empty" }));
promises.push(client.listCommunities(listCommunitiesForm)); listCommunitiesResponse = await client.listCommunities(
listCommunitiesForm
);
} }
const creator_id = getIdFromString(creatorId); const creator_id = getIdFromString(creatorId);
let creatorDetailsResponse: RequestState<GetPersonDetailsResponse> = {
state: "empty",
};
if (creator_id) { if (creator_id) {
const getCreatorForm: GetPersonDetails = { const getCreatorForm: GetPersonDetails = {
person_id: creator_id, person_id: creator_id,
auth, auth,
}; };
promises.push(client.getPersonDetails(getCreatorForm));
} else { creatorDetailsResponse = await client.getPersonDetails(getCreatorForm);
promises.push(Promise.resolve({ state: "empty" }));
} }
const query = getSearchQueryFromQuery(q); const query = getSearchQueryFromQuery(q);
let searchResponse: RequestState<SearchResponse> = { state: "empty" };
let resolveObjectResponse: RequestState<ResolveObjectResponse> = {
state: "empty",
};
if (query) { if (query) {
const form: SearchForm = { const form: SearchForm = {
q: query, q: query,
@ -383,21 +423,24 @@ export class Search extends Component<any, SearchState> {
}; };
if (query !== "") { if (query !== "") {
promises.push(client.search(form)); searchResponse = await client.search(form);
if (auth) { if (auth) {
const resolveObjectForm: ResolveObject = { const resolveObjectForm: ResolveObject = {
q: query, q: query,
auth, auth,
}; };
promises.push(client.resolveObject(resolveObjectForm)); resolveObjectResponse = await client.resolveObject(resolveObjectForm);
} }
} else {
promises.push(Promise.resolve({ state: "empty" }));
promises.push(Promise.resolve({ state: "empty" }));
} }
} }
return promises; return {
communityResponse,
creatorDetailsResponse,
listCommunitiesResponse,
resolveObjectResponse,
searchResponse,
};
} }
get documentTitle(): string { get documentTitle(): string {
@ -410,7 +453,7 @@ export class Search extends Component<any, SearchState> {
const { type, page } = getSearchQueryParams(); const { type, page } = getSearchQueryParams();
return ( return (
<div className="container-lg"> <div className="search container-lg">
<HtmlTags <HtmlTags
title={this.documentTitle} title={this.documentTitle}
path={this.context.router.route.match.url} path={this.context.router.route.match.url}
@ -448,27 +491,28 @@ export class Search extends Component<any, SearchState> {
get searchForm() { get searchForm() {
return ( return (
<form <form className="row" onSubmit={linkEvent(this, this.handleSearchSubmit)}>
className="form-inline" <div className="col-auto">
onSubmit={linkEvent(this, this.handleSearchSubmit)} <input
> type="text"
<input className="form-control me-2 mb-2 col-sm-8"
type="text" value={this.state.searchText}
className="form-control mr-2 mb-2" placeholder={`${i18n.t("search")}...`}
value={this.state.searchText} aria-label={i18n.t("search")}
placeholder={`${i18n.t("search")}...`} onInput={linkEvent(this, this.handleQChange)}
aria-label={i18n.t("search")} required
onInput={linkEvent(this, this.handleQChange)} minLength={1}
required />
minLength={1} </div>
/> <div className="col-auto">
<button type="submit" className="btn btn-secondary mr-2 mb-2"> <button type="submit" className="btn btn-secondary mb-2">
{this.state.searchRes.state == "loading" ? ( {this.state.searchRes.state === "loading" ? (
<Spinner /> <Spinner />
) : ( ) : (
<span>{i18n.t("search")}</span> <span>{i18n.t("search")}</span>
)} )}
</button> </button>
</div>
</form> </form>
); );
} }
@ -493,7 +537,7 @@ export class Search extends Component<any, SearchState> {
<select <select
value={type} value={type}
onChange={linkEvent(this, this.handleTypeChange)} onChange={linkEvent(this, this.handleTypeChange)}
className="custom-select w-auto mb-2" className="form-select d-inline-block w-auto mb-2"
aria-label={i18n.t("type")} aria-label={i18n.t("type")}
> >
<option disabled aria-hidden="true"> <option disabled aria-hidden="true">
@ -505,7 +549,7 @@ export class Search extends Component<any, SearchState> {
</option> </option>
))} ))}
</select> </select>
<span className="ml-2"> <span className="ms-2">
<ListingTypeSelect <ListingTypeSelect
type_={listingType} type_={listingType}
showLocal={showLocal(this.isoData)} showLocal={showLocal(this.isoData)}
@ -513,7 +557,7 @@ export class Search extends Component<any, SearchState> {
onChange={this.handleListingTypeChange} onChange={this.handleListingTypeChange}
/> />
</span> </span>
<span className="ml-2"> <span className="ms-2">
<SortSelect <SortSelect
sort={sort} sort={sort}
onChange={this.handleSortChange} onChange={this.handleSortChange}
@ -521,7 +565,7 @@ export class Search extends Component<any, SearchState> {
hideMostComments hideMostComments
/> />
</span> </span>
<div className="form-row"> <div className="row">
{hasCommunities && ( {hasCommunities && (
<Filter <Filter
filterType="community" filterType="community"

View File

@ -1,4 +1,4 @@
import { isBrowser } from "./utils"; import { isBrowser } from "@utils/browser";
const testHost = "0.0.0.0:8536"; const testHost = "0.0.0.0:8536";

Some files were not shown because too many files have changed in this diff Show More