}
}
],
- ["@babel/typescript", {"isTSX": true, "allExtensions": true}]
+ ["@babel/typescript", { "isTSX": true, "allExtensions": true }]
],
"plugins": [
"@babel/plugin-transform-runtime",
- ["babel-plugin-inferno", { "imports": true }],
- ["@babel/plugin-proposal-class-properties", { "loose": true }],
+ ["babel-plugin-inferno", { "imports": true }],
+ ["@babel/plugin-proposal-class-properties", { "loose": true }]
]
}
generate_translations.js
webpack.config.js
src/api_tests
+**/*.png
+**/*.css
+**/*.scss
+**/*.svg
"env": {
"browser": true
},
- "plugins": [
- "@typescript-eslint"
- ],
+ "plugins": ["@typescript-eslint"],
"extends": [
"eslint:recommended",
"plugin:@typescript-eslint/recommended",
---
name: "\U0001F41E Bug Report"
about: Create a report to help us improve Lemmy
-title: ''
+title: ""
labels: bug
-assignees: ''
-
+assignees: ""
---
Found a bug? Please fill out the sections below. 👍
A summary of the bug.
-
### Steps to Reproduce
1. (for example) I clicked login, and an endless spinner show up.
### Technical details
-* Please post your log: `sudo docker-compose logs > lemmy_log.out`.
-* What OS are you trying to install lemmy on?
-* Any browser console errors?
+- Please post your log: `sudo docker-compose logs > lemmy_log.out`.
+- What OS are you trying to install lemmy on?
+- Any browser console errors?
---
name: "\U0001F680 Feature request"
about: Suggest an idea for improving Lemmy
-title: ''
+title: ""
labels: enhancement
-assignees: ''
-
+assignees: ""
---
For backend issues, use [lemmy](https://github.com/LemmyNet/lemmy)
---
name: "? Question"
about: General questions about Lemmy
-title: ''
+title: ""
labels: question
-assignees: ''
-
+assignees: ""
---
What's the question you have about lemmy?
---
name: Hexbear
about: For hexbear issues
-title: ''
+title: ""
labels: hexbear
-assignees: ''
-
+assignees: ""
---
For hexbear-related issues
-src/shared/translations
\ No newline at end of file
+src/shared/translations
+lemmy-translations
\ No newline at end of file
publish_release_docker_manifest:
image: plugins/manifest
- settings:
+ settings:
username:
from_secret: docker_username
password:
publish_latest_release_docker_manifest:
image: plugins/manifest
- settings:
+ settings:
username:
from_secret: docker_username
password:
-# lemmy-ui\r
-\r
-The official web app for [Lemmy](https://github.com/LemmyNet/lemmy), written in inferno.\r
-\r
-Based off of MrFoxPro's [inferno-isomorphic-template](https://github.com/MrFoxPro/inferno-isomorphic-template).\r
-\r
-## Configuration\r
-\r
-The following environment variables can be used to configure lemmy-ui:\r
-\r
-`ENV_VAR` | type | default | description\r
---- | --- | --- | ---\r
-`LEMMY_UI_HOST` | `string` | `0.0.0.0:1234` | The IP / port that the lemmy-ui isomorphic node server is hosted at.\r
-`LEMMY_UI_LEMMY_INTERNAL_HOST` | `string` | `0.0.0.0:8536` | The internal IP / port that lemmy is hosted at. Often `lemmy:8536` if using docker.\r
-`LEMMY_UI_LEMMY_EXTERNAL_HOST` | `string` | `0.0.0.0:8536` | The external IP / port that lemmy is hosted at. Often `DOMAIN.TLD`.\r
-`LEMMY_UI_LEMMY_WS_HOST` | `string` | `0.0.0.0:8536` | An alternate location for lemmy's websocket address. Not usually necessary.\r
-`LEMMY_UI_HTTPS` | `bool` | `false` | Whether to use https.\r
-`LEMMY_UI_EXTRA_THEMES_FOLDER` | `string` | `./extra_themes` | A location for additional lemmy css themes.\r
-`LEMMY_UI_DEBUG` | `bool` | `false` | Loads the [Eruda](https://github.com/liriliri/eruda) debugging utility.\r
-`LEMMY_UI_DISABLE_CSP` | `bool` | `false` | Disables CSP security headers\r
-`LEMMY_UI_CUSTOM_HTML_HEADER` | `string` | | Injects a custom script into `<head>`.\r
+# lemmy-ui
+
+The official web app for [Lemmy](https://github.com/LemmyNet/lemmy), written in inferno.
+
+Based off of MrFoxPro's [inferno-isomorphic-template](https://github.com/MrFoxPro/inferno-isomorphic-template).
+
+## Configuration
+
+The following environment variables can be used to configure lemmy-ui:
+
+| `ENV_VAR` | type | default | description |
+| ------------------------------ | -------- | ---------------- | ----------------------------------------------------------------------------------- |
+| `LEMMY_UI_HOST` | `string` | `0.0.0.0:1234` | The IP / port that the lemmy-ui isomorphic node server is hosted at. |
+| `LEMMY_UI_LEMMY_INTERNAL_HOST` | `string` | `0.0.0.0:8536` | The internal IP / port that lemmy is hosted at. Often `lemmy:8536` if using docker. |
+| `LEMMY_UI_LEMMY_EXTERNAL_HOST` | `string` | `0.0.0.0:8536` | The external IP / port that lemmy is hosted at. Often `DOMAIN.TLD`. |
+| `LEMMY_UI_LEMMY_WS_HOST` | `string` | `0.0.0.0:8536` | An alternate location for lemmy's websocket address. Not usually necessary. |
+| `LEMMY_UI_HTTPS` | `bool` | `false` | Whether to use https. |
+| `LEMMY_UI_EXTRA_THEMES_FOLDER` | `string` | `./extra_themes` | A location for additional lemmy css themes. |
+| `LEMMY_UI_DEBUG` | `bool` | `false` | Loads the [Eruda](https://github.com/liriliri/eruda) debugging utility. |
+| `LEMMY_UI_DISABLE_CSP` | `bool` | `false` | Disables CSP security headers |
+| `LEMMY_UI_CUSTOM_HTML_HEADER` | `string` | | Injects a custom script into `<head>`. |
"build:prod": "webpack --mode=production",
"clean": "yarn run rimraf dist",
"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": "node generate_translations.js && tsc --noEmit && eslint --report-unused-disable-directives --ext .js,.ts,.tsx \"src/**\" && prettier --check \"src/**/*.{ts,tsx,js,css,scss}\"",
"prepare": "husky install",
"start": "yarn build:dev --watch"
},
"isomorphic-cookie": "^1.2.4",
"jwt-decode": "^3.1.2",
"lemmy-js-client": "0.17.2-rc.17",
+ "lodash": "^4.17.21",
"markdown-it": "^13.0.1",
"markdown-it-container": "^3.0.0",
"markdown-it-emoji": "^2.0.2",
"sass": "^1.62.1",
"sass-loader": "^13.2.2",
"serialize-javascript": "^6.0.1",
+ "service-worker-webpack": "^1.0.0",
"sharp": "^0.32.1",
"tippy.js": "^6.3.7",
"toastify-js": "^1.12.0",
"prettier-plugin-organize-imports": "^3.2.2",
"prettier-plugin-packagejson": "^2.4.3",
"rimraf": "^5.0.0",
- "service-worker-webpack": "^1.0.0",
"sortpack": "^2.3.4",
"style-loader": "^3.3.2",
"terser": "^5.17.3",
import {
ILemmyConfig,
InitialFetchRequest,
- IsoData,
+ IsoDataOptionalSite,
} from "../shared/interfaces";
import { routes } from "../shared/routes";
-import { favIconPngUrl, favIconUrl, initializeSite } from "../shared/utils";
+import {
+ ErrorPageData,
+ favIconPngUrl,
+ favIconUrl,
+ initializeSite,
+ isAuthPath,
+} from "../shared/utils";
const server = express();
const [hostname, port] = process.env["LEMMY_UI_HOST"]
res.contentType("text/css");
const theme = req.params.name;
if (!theme.endsWith(".css")) {
+ res.statusCode = 400;
res.send("Theme must be a css file");
}
server.get("/*", async (req, res) => {
try {
const activeRoute = routes.find(route => matchPath(req.path, route));
- const context = {} as any;
let auth: string | undefined = IsomorphicCookie.load("jwt", req);
const getSiteForm: GetSite = { auth };
- const promises: Promise<any>[] = [];
-
const headers = setForwardedHeaders(req.headers);
const client = 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 try_site: any = await client.getSite(getSiteForm);
- if (try_site.error == "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);
- }
- const site: GetSiteResponse = try_site;
- initializeSite(site);
-
- const initialFetchReq: InitialFetchRequest = {
- client,
- auth,
- path: req.path,
- query: req.query,
- site,
- };
+ let site: GetSiteResponse | undefined = undefined;
+ let routeData: any[] = [];
+ let errorPageData: ErrorPageData | undefined;
+ try {
+ let try_site: any = await client.getSite(getSiteForm);
+ if (try_site.error == "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 (activeRoute?.fetchInitialData) {
- promises.push(...activeRoute.fetchInitialData(initialFetchReq));
- }
+ if (!auth && isAuthPath(path)) {
+ res.redirect("/login");
+ return;
+ }
- const routeData = await Promise.all(promises);
+ site = try_site;
+ initializeSite(site);
+
+ if (site) {
+ const initialFetchReq: InitialFetchRequest = {
+ client,
+ auth,
+ path,
+ query,
+ site,
+ };
+
+ if (activeRoute?.fetchInitialData) {
+ routeData = await Promise.all([
+ ...activeRoute.fetchInitialData(initialFetchReq),
+ ]);
+ }
+ }
+ } catch (error) {
+ errorPageData = getErrorPageData(error, site);
+ }
// Redirect to the 404 if there's an API error
if (routeData[0] && routeData[0].error) {
if (error === "instance_is_private") {
return res.redirect(`/signup`);
} else {
- return res.send(`404: ${removeAuthParam(error)}`);
+ errorPageData = getErrorPageData(error, site);
}
}
- const isoData: IsoData = {
- path: req.path,
+ const isoData: IsoDataOptionalSite = {
+ path,
site_res: site,
routeData,
+ errorPageData,
};
const wrapper = (
- <StaticRouter location={req.url} context={isoData}>
+ <StaticRouter location={url} context={isoData}>
<App />
</StaticRouter>
);
- if (context.url) {
- return res.redirect(context.url);
- }
-
- const eruda = (
- <>
- <script src="//cdn.jsdelivr.net/npm/eruda"></script>
- <script>eruda.init();</script>
- </>
- );
- const erudaStr = process.env["LEMMY_UI_DEBUG"] ? renderToString(eruda) : "";
const root = renderToString(wrapper);
- const helmet = Helmet.renderStatic();
-
- const config: ILemmyConfig = { wsHost: process.env.LEMMY_UI_LEMMY_WS_HOST };
-
- 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;
-
- res.send(`
- <!DOCTYPE html>
- <html ${helmet.htmlAttributes.toString()} lang="en">
- <head>
- <script>window.isoData = ${JSON.stringify(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">
- <link
- id="favicon"
- rel="shortcut icon"
- type="image/x-icon"
- href=${site.site_view.site.icon ?? favIconUrl}
- />
-
- <!-- Web app manifest -->
- <link rel="manifest" href="data:application/manifest+json;base64,${await generateManifestBase64(
- site.site_view.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>
-`);
+
+ 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);
- return res.send(`404: ${removeAuthParam(err)}`);
+ res.statusCode = 500;
+ return res.send(
+ process.env.NODE_ENV === "development" ? err.message : "Server error"
+ );
}
});
process.exit(0);
});
-function removeAuthParam(err: any): string {
- return removeParam(err.toString(), "auth");
-}
-
-function removeParam(url: string, parameter: string): string {
- return url
- .replace(new RegExp("[?&]" + parameter + "=[^&#]*(#.*)?$"), "$1")
- .replace(new RegExp("([?&])" + parameter + "=[^&]*&"), "$1");
-}
-
const iconSizes = [72, 96, 128, 144, 152, 192, 384, 512];
const defaultLogoPathDirectory = path.join(
process.cwd(),
async function fetchIconPng(iconUrl: string) {
return await fetch(
- iconUrl.replace(/https?:\/\/localhost:\d+/g, getHttpBaseInternal())
+ iconUrl.replace(/https?:\/\/[^\/]+/g, getHttpBaseInternal())
)
.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 eruda = (
+ <>
+ <script src="//cdn.jsdelivr.net/npm/eruda"></script>
+ <script>eruda.init();</script>
+ </>
+ );
+
+ const erudaStr = process.env["LEMMY_UI_DEBUG"] ? renderToString(eruda) : "";
+
+ const helmet = Helmet.renderStatic();
+
+ const config: ILemmyConfig = { wsHost: process.env.LEMMY_UI_LEMMY_WS_HOST };
+
+ return `
+ <!DOCTYPE html>
+ <html ${helmet.htmlAttributes.toString()} lang="en">
+ <head>
+ <script>window.isoData = ${JSON.stringify(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">
+ <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.site_view.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>
+`;
+}
import { Component } from "inferno";
import { Provider } from "inferno-i18next-dess";
import { Route, Switch } from "inferno-router";
+import { IsoDataOptionalSite } from "shared/interfaces";
import { i18n } from "../../i18next";
import { routes } from "../../routes";
-import { setIsoData } from "../../utils";
+import { isAuthPath, setIsoData } from "../../utils";
+import AuthGuard from "../common/auth-guard";
+import ErrorGuard from "../common/error-guard";
+import { ErrorPage } from "./error-page";
import { Footer } from "./footer";
import { Navbar } from "./navbar";
-import { NoMatch } from "./no-match";
import "./styles.scss";
import { Theme } from "./theme";
export class App extends Component<any, any> {
- private isoData = setIsoData(this.context);
+ private isoData: IsoDataOptionalSite = setIsoData(this.context);
constructor(props: any, context: any) {
super(props, context);
}
render() {
- let siteRes = this.isoData.site_res;
- let siteView = siteRes.site_view;
+ const siteRes = this.isoData.site_res;
+ const siteView = siteRes?.site_view;
return (
<>
<Provider i18next={i18n}>
<div id="app">
- <Theme defaultTheme={siteView.local_site.default_theme} />
+ {siteView && (
+ <Theme defaultTheme={siteView.local_site.default_theme} />
+ )}
<Navbar siteRes={siteRes} />
<div className="mt-4 p-0 fl-1">
<Switch>
- {routes.map(({ path, component }) => (
- <Route key={path} path={path} exact component={component} />
+ {routes.map(({ path, component: RouteComponent }) => (
+ <Route
+ key={path}
+ path={path}
+ exact
+ component={routeProps => (
+ <ErrorGuard>
+ {RouteComponent &&
+ (isAuthPath(path ?? "") ? (
+ <AuthGuard>
+ <RouteComponent {...routeProps} />
+ </AuthGuard>
+ ) : (
+ <RouteComponent {...routeProps} />
+ ))}
+ </ErrorGuard>
+ )}
+ />
))}
- <Route component={NoMatch} />
+ <Route component={ErrorPage} />
</Switch>
</div>
<Footer site={siteRes} />
--- /dev/null
+import { Component } from "inferno";
+import { T } from "inferno-i18next-dess";
+import { Link } from "inferno-router";
+import { i18n } from "../../i18next";
+import { IsoDataOptionalSite } from "../../interfaces";
+import { setIsoData } from "../../utils";
+
+export class ErrorPage extends Component<any, any> {
+ private isoData: IsoDataOptionalSite = setIsoData(this.context);
+
+ constructor(props: any, context: any) {
+ super(props, context);
+ }
+
+ render() {
+ const { errorPageData } = this.isoData;
+
+ return (
+ <div className="container-lg text-center">
+ <h1>
+ {errorPageData
+ ? i18n.t("error_page_title")
+ : i18n.t("not_found_page_title")}
+ </h1>
+ {errorPageData ? (
+ <T i18nKey="error_page_paragraph" className="p-4" parent="p">
+ #<a href="https://lemmy.ml/c/lemmy_support">#</a>#
+ <a href="https://matrix.to/#/#lemmy-space:matrix.org">#</a>#
+ </T>
+ ) : (
+ <p>{i18n.t("not_found_page_message")}</p>
+ )}
+ {!errorPageData && (
+ <Link to="/" replace>
+ {i18n.t("not_found_return_home_button")}
+ </Link>
+ )}
+ {errorPageData?.adminMatrixIds &&
+ errorPageData.adminMatrixIds.length > 0 && (
+ <>
+ <div>
+ {i18n.t("error_page_admin_matrix", {
+ instance:
+ this.isoData.site_res?.site_view.site.name ??
+ "this instance",
+ })}
+ </div>
+ <ul className="mx-auto mt-2" style={{ width: "fit-content" }}>
+ {errorPageData.adminMatrixIds.map(matrixId => (
+ <li key={matrixId} className="text-info">
+ {matrixId}
+ </li>
+ ))}
+ </ul>
+ </>
+ )}
+ {errorPageData?.error && (
+ <T
+ i18nKey="error_code_message"
+ parent="p"
+ interpolation={{ error: errorPageData.error }}
+ >
+ #<strong className="text-danger">#</strong>#
+ </T>
+ )}
+ </div>
+ );
+ }
+}
import { VERSION } from "../../version";
interface FooterProps {
- site: GetSiteResponse;
+ site?: GetSiteResponse;
}
export class Footer extends Component<FooterProps, any> {
<nav className="container-lg navbar navbar-expand-md navbar-light navbar-bg p-3">
<div className="navbar-collapse">
<ul className="navbar-nav ml-auto">
- {this.props.site.version !== VERSION && (
+ {this.props.site?.version !== VERSION && (
<li className="nav-item">
<span className="nav-link">UI: {VERSION}</span>
</li>
)}
<li className="nav-item">
- <span className="nav-link">BE: {this.props.site.version}</span>
+ <span className="nav-link">BE: {this.props.site?.version}</span>
</li>
<li className="nav-item">
<NavLink className="nav-link" to="/modlog">
{i18n.t("modlog")}
</NavLink>
</li>
- {this.props.site.site_view.local_site.legal_information && (
+ {this.props.site?.site_view.local_site.legal_information && (
<li className="nav-item">
<NavLink className="nav-link" to="/legal">
{i18n.t("legal_information")}
</NavLink>
</li>
)}
- {this.props.site.site_view.local_site.federation_enabled && (
+ {this.props.site?.site_view.local_site.federation_enabled && (
<li className="nav-item">
<NavLink className="nav-link" to="/instances">
{i18n.t("instances")}
import { PictrsImage } from "../common/pictrs-image";
interface NavbarProps {
- siteRes: GetSiteResponse;
+ siteRes?: GetSiteResponse;
}
interface NavbarState {
// TODO class active corresponding to current page
render() {
- const siteView = this.props.siteRes.site_view;
+ const siteView = this.props.siteRes?.site_view;
const person = UserService.Instance.myUserInfo?.local_user_view.person;
return (
<nav className="navbar navbar-expand-md navbar-light shadow-sm p-0 px-3 container-lg">
<NavLink
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"
onMouseUp={linkEvent(this, handleCollapseClick)}
>
- {siteView.site.icon && showAvatars() && (
+ {siteView?.site.icon && showAvatars() && (
<PictrsImage src={siteView.site.icon} icon />
)}
- {siteView.site.name}
+ {siteView?.site.name}
</NavLink>
{person && (
<ul className="navbar-nav d-flex flex-row ml-auto d-md-none">
{i18n.t("create_post")}
</NavLink>
</li>
- {canCreateCommunity(this.props.siteRes) && (
+ {this.props.siteRes && canCreateCommunity(this.props.siteRes) && (
<li className="nav-item">
<NavLink
to="/create_community"
+++ /dev/null
-import { NoOptionI18nKeys } from "i18next";
-import { Component } from "inferno";
-import { i18n } from "../../i18next";
-
-export class NoMatch extends Component<any, any> {
- private errCode = new URLSearchParams(this.props.location.search).get(
- "err"
- ) as NoOptionI18nKeys;
-
- constructor(props: any, context: any) {
- super(props, context);
- }
-
- render() {
- return (
- <div className="container-lg">
- <h1>404</h1>
- {this.errCode && (
- <h3>
- {i18n.t("code")}: {i18n.t(this.errCode)}
- </h3>
- )}
- </div>
- );
- }
-}
--- /dev/null
+import { InfernoNode } from "inferno";
+import { Redirect } from "inferno-router";
+import { UserService } from "../../services";
+
+function AuthGuard(props: { children?: InfernoNode }) {
+ if (!UserService.Instance.myUserInfo) {
+ return <Redirect to="/login" />;
+ } else {
+ return props.children;
+ }
+}
+
+export default AuthGuard;
--- /dev/null
+import { Component } from "inferno";
+import { setIsoData } from "../../utils";
+import { ErrorPage } from "../app/error-page";
+
+class ErrorGuard extends Component<any, any> {
+ private isoData = setIsoData(this.context);
+
+ constructor(props: any, context: any) {
+ super(props, context);
+ }
+
+ render() {
+ const errorPageData = this.isoData.errorPageData;
+ const siteRes = this.isoData.site_res;
+
+ if (errorPageData || !siteRes) {
+ return <ErrorPage />;
+ } else {
+ return this.props.children;
+ }
+ }
+}
+
+export default ErrorGuard;
--- /dev/null
+import { Component, InfernoNode, linkEvent } from "inferno";
+
+interface TabItem {
+ key: string;
+ getNode: () => InfernoNode;
+ label: string;
+}
+
+interface TabsProps {
+ tabs: TabItem[];
+}
+
+interface TabsState {
+ currentTab: string;
+}
+
+function handleSwitchTab({ ctx, tab }: { ctx: Tabs; tab: string }) {
+ ctx.setState({ currentTab: tab });
+}
+
+export default class Tabs extends Component<TabsProps, TabsState> {
+ constructor(props: TabsProps, context) {
+ super(props, context);
+
+ this.state = {
+ currentTab: props.tabs.length > 0 ? props.tabs[0].key : "",
+ };
+ }
+
+ render() {
+ return (
+ <div>
+ <ul className="nav nav-tabs mb-2">
+ {this.props.tabs.map(({ key, label }) => (
+ <li key={key} className="nav-item">
+ <button
+ type="button"
+ className={`nav-link btn${
+ this.state?.currentTab === key ? " active" : ""
+ }`}
+ onClick={linkEvent({ ctx: this, tab: key }, handleSwitchTab)}
+ >
+ {label}
+ </button>
+ </li>
+ ))}
+ </ul>
+ {this.props.tabs
+ .find(tab => tab.key === this.state?.currentTab)
+ ?.getNode()}
+ </div>
+ );
+ }
+}
import { Component } from "inferno";
-import { Redirect } from "inferno-router";
import { CommunityView, GetSiteResponse } from "lemmy-js-client";
import { Subscription } from "rxjs";
import { i18n } from "../../i18next";
-import { UserService } from "../../services/UserService";
import {
enableNsfw,
isBrowser,
render() {
return (
<div className="container-lg">
- {!UserService.Instance.myUserInfo && <Redirect to="/login" />}
<HtmlTags
title={this.documentTitle}
path={this.context.router.route.match.url}
} from "../../utils";
import { HtmlTags } from "../common/html-tags";
import { Spinner } from "../common/icon";
+import Tabs from "../common/tabs";
import { PersonListing } from "../person/person-listing";
import { EmojiForm } from "./emojis-form";
+import RateLimitForm from "./rate-limit-form";
import { SiteForm } from "./site-form";
import { TaglineForm } from "./tagline-form";
banned: PersonView[];
loading: boolean;
leaveAdminTeamLoading: boolean;
- currentTab: string;
}
export class AdminSettings extends Component<any, AdminSettingsState> {
banned: [],
loading: true,
leaveAdminTeamLoading: false,
- currentTab: "site",
};
constructor(props: any, context: any) {
render() {
return (
<div className="container-lg">
+ <HtmlTags
+ title={this.documentTitle}
+ path={this.context.router.route.match.url}
+ />
{this.state.loading ? (
<h5>
<Spinner large />
</h5>
) : (
- <div>
- <HtmlTags
- title={this.documentTitle}
- path={this.context.router.route.match.url}
- />
- <ul className="nav nav-tabs mb-2">
- <li className="nav-item">
- <button
- className={`nav-link btn ${
- this.state.currentTab == "site" && "active"
- }`}
- onClick={linkEvent(
- { ctx: this, tab: "site" },
- this.handleSwitchTab
- )}
- >
- {i18n.t("site")}
- </button>
- </li>
- <li className="nav-item">
- <button
- className={`nav-link btn ${
- this.state.currentTab == "taglines" && "active"
- }`}
- onClick={linkEvent(
- { ctx: this, tab: "taglines" },
- this.handleSwitchTab
- )}
- >
- {i18n.t("taglines")}
- </button>
- </li>
- <li className="nav-item">
- <button
- className={`nav-link btn ${
- this.state.currentTab == "emojis" && "active"
- }`}
- onClick={linkEvent(
- { ctx: this, tab: "emojis" },
- this.handleSwitchTab
- )}
- >
- {i18n.t("emojis")}
- </button>
- </li>
- </ul>
- {this.state.currentTab == "site" && (
- <div className="row">
- <div className="col-12 col-md-6">
- <SiteForm
- siteRes={this.state.siteRes}
- instancesRes={this.state.instancesRes}
- showLocal={showLocal(this.isoData)}
+ <Tabs
+ tabs={[
+ {
+ key: "site",
+ label: i18n.t("site"),
+ getNode: () => (
+ <div className="row">
+ <div className="col-12 col-md-6">
+ <SiteForm
+ siteRes={this.state.siteRes}
+ instancesRes={this.state.instancesRes}
+ showLocal={showLocal(this.isoData)}
+ />
+ </div>
+ <div className="col-12 col-md-6">
+ {this.admins()}
+ {this.bannedUsers()}
+ </div>
+ </div>
+ ),
+ },
+ {
+ key: "rate_limiting",
+ label: "Rate Limiting",
+ getNode: () => (
+ <RateLimitForm
+ localSiteRateLimit={
+ this.state.siteRes.site_view.local_site_rate_limit
+ }
+ applicationQuestion={
+ this.state.siteRes.site_view.local_site
+ .application_question
+ }
/>
- </div>
- <div className="col-12 col-md-6">
- {this.admins()}
- {this.bannedUsers()}
- </div>
- </div>
- )}
- {this.state.currentTab == "taglines" && (
- <div className="row">
- <TaglineForm siteRes={this.state.siteRes}></TaglineForm>
- </div>
- )}
- {this.state.currentTab == "emojis" && (
- <div className="row">
- <EmojiForm></EmojiForm>
- </div>
- )}
- </div>
+ ),
+ },
+ {
+ key: "taglines",
+ label: i18n.t("taglines"),
+ getNode: () => (
+ <div className="row">
+ <TaglineForm siteRes={this.state.siteRes} />
+ </div>
+ ),
+ },
+ {
+ key: "emojis",
+ label: i18n.t("emojis"),
+ getNode: () => (
+ <div className="row">
+ <EmojiForm />
+ </div>
+ ),
+ },
+ ]}
+ />
)}
</div>
);
);
}
- handleSwitchTab(i: { ctx: AdminSettings; tab: string }) {
- i.ctx.setState({ currentTab: i.tab });
- }
-
handleLeaveAdminTeam(i: AdminSettings) {
let auth = myAuth();
if (auth) {
--- /dev/null
+import { Component, FormEventHandler, linkEvent } from "inferno";
+import { EditSite, LocalSiteRateLimit } from "lemmy-js-client";
+import { i18n } from "../../i18next";
+import { WebSocketService } from "../../services";
+import { capitalizeFirstLetter, myAuth, wsClient } from "../../utils";
+import { Spinner } from "../common/icon";
+import Tabs from "../common/tabs";
+
+const rateLimitTypes = [
+ "message",
+ "post",
+ "image",
+ "comment",
+ "search",
+ "register",
+] as const;
+
+interface RateLimitsProps {
+ handleRateLimit: FormEventHandler<HTMLInputElement>;
+ handleRateLimitPerSecond: FormEventHandler<HTMLInputElement>;
+ rateLimitValue?: number;
+ rateLimitPerSecondValue?: number;
+}
+
+interface RateLimitFormProps {
+ localSiteRateLimit: LocalSiteRateLimit;
+ applicationQuestion?: string;
+}
+
+interface RateLimitFormState {
+ form: {
+ message?: number;
+ message_per_second?: number;
+ post?: number;
+ post_per_second?: number;
+ comment?: number;
+ comment_per_second?: number;
+ image?: number;
+ image_per_second?: number;
+ search?: number;
+ search_per_second?: number;
+ register?: number;
+ register_per_second?: number;
+ };
+ loading: boolean;
+}
+
+function RateLimits({
+ handleRateLimit,
+ handleRateLimitPerSecond,
+ rateLimitPerSecondValue,
+ rateLimitValue,
+}: RateLimitsProps) {
+ return (
+ <div className="form-group row">
+ <label className="col-12 col-form-label" htmlFor="rate-limit">
+ {i18n.t("rate_limit")}
+ </label>
+ <input
+ type="number"
+ id="rate-limit"
+ className="form-control col-12"
+ min={0}
+ value={rateLimitValue}
+ onInput={handleRateLimit}
+ />
+ <label className="col-12 col-form-label" htmlFor="rate-limit-per-second">
+ {i18n.t("per_second")}
+ </label>
+ <input
+ type="number"
+ id="rate-limit-per-second"
+ className="form-control col-12"
+ min={0}
+ value={rateLimitPerSecondValue}
+ onInput={handleRateLimitPerSecond}
+ />
+ </div>
+ );
+}
+
+function handleRateLimitChange(
+ { rateLimitType, ctx }: { rateLimitType: string; ctx: RateLimitsForm },
+ event: any
+) {
+ ctx.setState(prev => ({
+ ...prev,
+ form: {
+ ...prev.form,
+ [rateLimitType]: Number(event.target.value),
+ },
+ }));
+}
+
+function handlePerSecondChange(
+ { rateLimitType, ctx }: { rateLimitType: string; ctx: RateLimitsForm },
+ event: any
+) {
+ ctx.setState(prev => ({
+ ...prev,
+ form: {
+ ...prev.form,
+ [`${rateLimitType}_per_second`]: Number(event.target.value),
+ },
+ }));
+}
+
+function submitRateLimitForm(i: RateLimitsForm, event: any) {
+ event.preventDefault();
+ const auth = myAuth() ?? "TODO";
+ const form: EditSite = Object.entries(i.state.form).reduce(
+ (acc, [key, val]) => {
+ acc[`rate_limit_${key}`] = val;
+ return acc;
+ },
+ { auth, application_question: i.props.applicationQuestion }
+ );
+
+ i.setState({ loading: true });
+
+ WebSocketService.Instance.send(wsClient.editSite(form));
+}
+
+export default class RateLimitsForm extends Component<
+ RateLimitFormProps,
+ RateLimitFormState
+> {
+ state: RateLimitFormState = {
+ loading: false,
+ form: {},
+ };
+ constructor(props: RateLimitFormProps, context) {
+ super(props, context);
+
+ const {
+ comment,
+ comment_per_second,
+ image,
+ image_per_second,
+ message,
+ message_per_second,
+ post,
+ post_per_second,
+ register,
+ register_per_second,
+ search,
+ search_per_second,
+ } = props.localSiteRateLimit;
+
+ this.state = {
+ ...this.state,
+ form: {
+ comment,
+ comment_per_second,
+ image,
+ image_per_second,
+ message,
+ message_per_second,
+ post,
+ post_per_second,
+ register,
+ register_per_second,
+ search,
+ search_per_second,
+ },
+ };
+ }
+
+ render() {
+ return (
+ <form onSubmit={linkEvent(this, submitRateLimitForm)}>
+ <h5>{i18n.t("rate_limit_header")}</h5>
+ <Tabs
+ tabs={rateLimitTypes.map(rateLimitType => ({
+ key: rateLimitType,
+ label: i18n.t(`rate_limit_${rateLimitType}`),
+ getNode: () => (
+ <RateLimits
+ handleRateLimit={linkEvent(
+ { rateLimitType, ctx: this },
+ handleRateLimitChange
+ )}
+ handleRateLimitPerSecond={linkEvent(
+ { rateLimitType, ctx: this },
+ handlePerSecondChange
+ )}
+ rateLimitValue={this.state.form[rateLimitType]}
+ rateLimitPerSecondValue={
+ this.state.form[`${rateLimitType}_per_second`]
+ }
+ />
+ ),
+ }))}
+ />
+ <div className="form-group row">
+ <div className="col-12">
+ <button
+ type="submit"
+ className="btn btn-secondary mr-2"
+ disabled={this.state.loading}
+ >
+ {this.state.loading ? (
+ <Spinner />
+ ) : (
+ capitalizeFirstLetter(i18n.t("save"))
+ )}
+ </button>
+ </div>
+ </div>
+ </form>
+ );
+ }
+
+ componentDidUpdate({ localSiteRateLimit }: RateLimitFormProps) {
+ if (
+ this.state.loading &&
+ Object.entries(localSiteRateLimit).some(
+ ([key, val]) => this.state.form[key] !== val
+ )
+ ) {
+ this.setState({ loading: false });
+ }
+ }
+}
let site = this.props.siteRes.site_view.site;
let ls = this.props.siteRes.site_view.local_site;
- let lsrl = this.props.siteRes.site_view.local_site_rate_limit;
this.state = {
...this.state,
siteForm: {
discussion_languages: this.props.siteRes.discussion_languages,
slur_filter_regex: ls.slur_filter_regex,
actor_name_max_length: ls.actor_name_max_length,
- rate_limit_message: lsrl.message,
- rate_limit_message_per_second: lsrl.message_per_second,
- rate_limit_comment: lsrl.comment,
- rate_limit_comment_per_second: lsrl.comment_per_second,
- rate_limit_image: lsrl.image,
- rate_limit_image_per_second: lsrl.image_per_second,
- rate_limit_post: lsrl.post,
- rate_limit_post_per_second: lsrl.post_per_second,
- rate_limit_register: lsrl.register,
- rate_limit_register_per_second: lsrl.register_per_second,
- rate_limit_search: lsrl.search,
- rate_limit_search_per_second: lsrl.search_per_second,
federation_enabled: ls.federation_enabled,
federation_debug: ls.federation_debug,
federation_worker_count: ls.federation_worker_count,
</div>
</div>
)}
- <div className="form-group row">
- <label
- className="col-12 col-form-label"
- htmlFor="create-site-rate-limit-message"
- >
- {i18n.t("rate_limit_message")}
- </label>
- <div className="col-12">
- <input
- type="number"
- id="create-site-rate-limit-message"
- className="form-control"
- min={0}
- value={this.state.siteForm.rate_limit_message}
- onInput={linkEvent(this, this.handleSiteRateLimitMessage)}
- />
- </div>
- </div>
- <div className="form-group row">
- <label
- className="col-12 col-form-label"
- htmlFor="create-site-rate-limit-message-per-second"
- >
- {i18n.t("per_second")}
- </label>
- <div className="col-12">
- <input
- type="number"
- id="create-site-rate-limit-message-per-second"
- className="form-control"
- min={0}
- value={this.state.siteForm.rate_limit_message_per_second}
- onInput={linkEvent(
- this,
- this.handleSiteRateLimitMessagePerSecond
- )}
- />
- </div>
- </div>
- <div className="form-group row">
- <label
- className="col-12 col-form-label"
- htmlFor="create-site-rate-limit-post"
- >
- {i18n.t("rate_limit_post")}
- </label>
- <div className="col-12">
- <input
- type="number"
- id="create-site-rate-limit-post"
- className="form-control"
- min={0}
- value={this.state.siteForm.rate_limit_post}
- onInput={linkEvent(this, this.handleSiteRateLimitPost)}
- />
- </div>
- </div>
- <div className="form-group row">
- <label
- className="col-12 col-form-label"
- htmlFor="create-site-rate-limit-post-per-second"
- >
- {i18n.t("per_second")}
- </label>
- <div className="col-12">
- <input
- type="number"
- id="create-site-rate-limit-post-per-second"
- className="form-control"
- min={0}
- value={this.state.siteForm.rate_limit_post_per_second}
- onInput={linkEvent(this, this.handleSiteRateLimitPostPerSecond)}
- />
- </div>
- </div>
- <div className="form-group row">
- <label
- className="col-12 col-form-label"
- htmlFor="create-site-rate-limit-register"
- >
- {i18n.t("rate_limit_register")}
- </label>
- <div className="col-12">
- <input
- type="number"
- id="create-site-rate-limit-register"
- className="form-control"
- min={0}
- value={this.state.siteForm.rate_limit_register}
- onInput={linkEvent(this, this.handleSiteRateLimitRegister)}
- />
- </div>
- </div>
- <div className="form-group row">
- <label
- className="col-12 col-form-label"
- htmlFor="create-site-rate-limit-register-per-second"
- >
- {i18n.t("per_second")}
- </label>
- <div className="col-12">
- <input
- type="number"
- id="create-site-rate-limit-register-per-second"
- className="form-control"
- min={0}
- value={this.state.siteForm.rate_limit_register_per_second}
- onInput={linkEvent(
- this,
- this.handleSiteRateLimitRegisterPerSecond
- )}
- />
- </div>
- </div>
- <div className="form-group row">
- <label
- className="col-12 col-form-label"
- htmlFor="create-site-rate-limit-image"
- >
- {i18n.t("rate_limit_image")}
- </label>
- <div className="col-12">
- <input
- type="number"
- id="create-site-rate-limit-image"
- className="form-control"
- min={0}
- value={this.state.siteForm.rate_limit_image}
- onInput={linkEvent(this, this.handleSiteRateLimitImage)}
- />
- </div>
- </div>
- <div className="form-group row">
- <label
- className="col-12 col-form-label"
- htmlFor="create-site-rate-limit-image-per-second"
- >
- {i18n.t("per_second")}
- </label>
- <div className="col-12">
- <input
- type="number"
- id="create-site-rate-limit-image-per-second"
- className="form-control"
- min={0}
- value={this.state.siteForm.rate_limit_image_per_second}
- onInput={linkEvent(
- this,
- this.handleSiteRateLimitImagePerSecond
- )}
- />
- </div>
- </div>
- <div className="form-group row">
- <label
- className="col-12 col-form-label"
- htmlFor="create-site-rate-limit-comment"
- >
- {i18n.t("rate_limit_comment")}
- </label>
- <div className="col-12">
- <input
- type="number"
- id="create-site-rate-limit-comment"
- className="form-control"
- min={0}
- value={this.state.siteForm.rate_limit_comment}
- onInput={linkEvent(this, this.handleSiteRateLimitComment)}
- />
- </div>
- </div>
- <div className="form-group row">
- <label
- className="col-12 col-form-label"
- htmlFor="create-site-rate-limit-comment-per-second"
- >
- {i18n.t("per_second")}
- </label>
- <div className="col-12">
- <input
- type="number"
- id="create-site-rate-limit-comment-per-second"
- className="form-control"
- min={0}
- value={this.state.siteForm.rate_limit_comment_per_second}
- onInput={linkEvent(
- this,
- this.handleSiteRateLimitCommentPerSecond
- )}
- />
- </div>
- </div>
- <div className="form-group row">
- <label
- className="col-12 col-form-label"
- htmlFor="create-site-rate-limit-search"
- >
- {i18n.t("rate_limit_search")}
- </label>
- <div className="col-12">
- <input
- type="number"
- id="create-site-rate-limit-search"
- className="form-control"
- min={0}
- value={this.state.siteForm.rate_limit_search}
- onInput={linkEvent(this, this.handleSiteRateLimitSearch)}
- />
- </div>
- </div>
- <div className="form-group row">
- <label
- className="col-12 col-form-label"
- htmlFor="create-site-rate-limit-search-per-second"
- >
- {i18n.t("per_second")}
- </label>
- <div className="col-12">
- <input
- type="number"
- id="create-site-rate-limit-search-per-second"
- className="form-control"
- min={0}
- value={this.state.siteForm.rate_limit_search_per_second}
- onInput={linkEvent(
- this,
- this.handleSiteRateLimitSearchPerSecond
- )}
- />
- </div>
- </div>
-
<div className="form-group row">
<div className="col-12">
<button
legal_information: sForm.legal_information,
slur_filter_regex: sForm.slur_filter_regex,
actor_name_max_length: sForm.actor_name_max_length,
- rate_limit_message: sForm.rate_limit_message,
- rate_limit_message_per_second: sForm.rate_limit_message_per_second,
- rate_limit_comment: sForm.rate_limit_comment,
- rate_limit_comment_per_second: sForm.rate_limit_comment_per_second,
- rate_limit_image: sForm.rate_limit_image,
- rate_limit_image_per_second: sForm.rate_limit_image_per_second,
- rate_limit_post: sForm.rate_limit_post,
- rate_limit_post_per_second: sForm.rate_limit_post_per_second,
- rate_limit_register: sForm.rate_limit_register,
- rate_limit_register_per_second: sForm.rate_limit_register_per_second,
- rate_limit_search: sForm.rate_limit_search,
- rate_limit_search_per_second: sForm.rate_limit_search_per_second,
federation_enabled: sForm.federation_enabled,
federation_debug: sForm.federation_debug,
federation_worker_count: sForm.federation_worker_count,
);
}
- handleSiteRateLimitMessage(i: SiteForm, event: any) {
- i.setState(
- s => ((s.siteForm.rate_limit_message = Number(event.target.value)), s)
- );
- }
-
- handleSiteRateLimitMessagePerSecond(i: SiteForm, event: any) {
- i.setState(
- s => (
- (s.siteForm.rate_limit_message_per_second = Number(event.target.value)),
- s
- )
- );
- }
-
- handleSiteRateLimitPost(i: SiteForm, event: any) {
- i.setState(
- s => ((s.siteForm.rate_limit_post = Number(event.target.value)), s)
- );
- }
-
- handleSiteRateLimitPostPerSecond(i: SiteForm, event: any) {
- i.setState(
- s => (
- (s.siteForm.rate_limit_post_per_second = Number(event.target.value)), s
- )
- );
- }
-
- handleSiteRateLimitImage(i: SiteForm, event: any) {
- i.setState(
- s => ((s.siteForm.rate_limit_image = Number(event.target.value)), s)
- );
- }
-
- handleSiteRateLimitImagePerSecond(i: SiteForm, event: any) {
- i.setState(
- s => (
- (s.siteForm.rate_limit_image_per_second = Number(event.target.value)), s
- )
- );
- }
-
- handleSiteRateLimitComment(i: SiteForm, event: any) {
- i.setState(
- s => ((s.siteForm.rate_limit_comment = Number(event.target.value)), s)
- );
- }
-
- handleSiteRateLimitCommentPerSecond(i: SiteForm, event: any) {
- i.setState(
- s => (
- (s.siteForm.rate_limit_comment_per_second = Number(event.target.value)),
- s
- )
- );
- }
-
- handleSiteRateLimitSearch(i: SiteForm, event: any) {
- i.setState(
- s => ((s.siteForm.rate_limit_search = Number(event.target.value)), s)
- );
- }
-
- handleSiteRateLimitSearchPerSecond(i: SiteForm, event: any) {
- i.setState(
- s => (
- (s.siteForm.rate_limit_search_per_second = Number(event.target.value)),
- s
- )
- );
- }
-
- handleSiteRateLimitRegister(i: SiteForm, event: any) {
- i.setState(
- s => ((s.siteForm.rate_limit_register = Number(event.target.value)), s)
- );
- }
-
- handleSiteRateLimitRegisterPerSecond(i: SiteForm, event: any) {
- i.setState(
- s => (
- (s.siteForm.rate_limit_register_per_second = Number(
- event.target.value
- )),
- s
- )
- );
- }
-
handleSiteFederationEnabled(i: SiteForm, event: any) {
i.state.siteForm.federation_enabled = event.target.checked;
i.setState(i.state);
this.handleSortChange = this.handleSortChange.bind(this);
this.handlePageChange = this.handlePageChange.bind(this);
- if (!UserService.Instance.myUserInfo && isBrowser()) {
- toast(i18n.t("not_logged_in"), "danger");
- this.context.router.history.push(`/login`);
- }
-
this.parseMessage = this.parseMessage.bind(this);
this.subscription = wsSubscribe(this.parseMessage);
this.handlePageChange = this.handlePageChange.bind(this);
- if (!UserService.Instance.myUserInfo && isBrowser()) {
- toast(i18n.t("not_logged_in"), "danger");
- this.context.router.history.push(`/login`);
- }
-
this.parseMessage = this.parseMessage.bind(this);
this.subscription = wsSubscribe(this.parseMessage);
this.handlePageChange = this.handlePageChange.bind(this);
- if (!UserService.Instance.myUserInfo && isBrowser()) {
- toast(i18n.t("not_logged_in"), "danger");
- this.context.router.history.push(`/login`);
- }
-
this.parseMessage = this.parseMessage.bind(this);
this.subscription = wsSubscribe(this.parseMessage);
import { MarkdownTextArea } from "../common/markdown-textarea";
import { SearchableSelect } from "../common/searchable-select";
import { SortSelect } from "../common/sort-select";
+import Tabs from "../common/tabs";
import { CommunityLink } from "../community/community-link";
import { PersonListing } from "./person-listing";
this.handleBannerUpload = this.handleBannerUpload.bind(this);
this.handleBannerRemove = this.handleBannerRemove.bind(this);
+ this.userSettings = this.userSettings.bind(this);
+ this.blockCards = this.blockCards.bind(this);
this.parseMessage = this.parseMessage.bind(this);
this.subscription = wsSubscribe(this.parseMessage);
render() {
return (
<div className="container-lg">
- <>
- <HtmlTags
- title={this.documentTitle}
- path={this.context.router.route.match.url}
- description={this.documentTitle}
- image={this.state.saveUserSettingsForm.avatar}
- />
- <ul className="nav nav-tabs mb-2">
- <li className="nav-item">
- <button
- className={`nav-link btn ${
- this.state.currentTab == "settings" && "active"
- }`}
- onClick={linkEvent(
- { ctx: this, tab: "settings" },
- this.handleSwitchTab
- )}
- >
- {i18n.t("settings")}
- </button>
- </li>
- <li className="nav-item">
- <button
- className={`nav-link btn ${
- this.state.currentTab == "blocks" && "active"
- }`}
- onClick={linkEvent(
- { ctx: this, tab: "blocks" },
- this.handleSwitchTab
- )}
- >
- {i18n.t("blocks")}
- </button>
- </li>
- </ul>
- {this.state.currentTab == "settings" && this.userSettings()}
- {this.state.currentTab == "blocks" && this.blockCards()}
- </>
+ <HtmlTags
+ title={this.documentTitle}
+ path={this.context.router.route.match.url}
+ description={this.documentTitle}
+ image={this.state.saveUserSettingsForm.avatar}
+ />
+ <Tabs
+ tabs={[
+ {
+ key: "settings",
+ label: i18n.t("settings"),
+ getNode: this.userSettings,
+ },
+ {
+ key: "blocks",
+ label: i18n.t("blocks"),
+ getNode: this.blockCards,
+ },
+ ]}
+ />
</div>
);
}
toast(i18n.t(msg.error), "danger");
return;
} else if (op == UserOperation.SaveUserSettings) {
- let data = wsJsonToRes<LoginResponse>(msg);
- UserService.Instance.login(data);
- location.reload();
this.setState({ saveUserSettingsLoading: false });
toast(i18n.t("saved"));
window.scrollTo(0, 0);
import { Component } from "inferno";
-import { Redirect } from "inferno-router";
import { RouteComponentProps } from "inferno-router/dist/Route";
import {
GetCommunity,
import { Subscription } from "rxjs";
import { InitialFetchRequest, PostFormParams } from "shared/interfaces";
import { i18n } from "../../i18next";
-import { UserService, WebSocketService } from "../../services";
+import { WebSocketService } from "../../services";
import {
Choice,
QueryParams,
return (
<div className="container-lg">
- {!UserService.Instance.myUserInfo && <Redirect to="/login" />}
<HtmlTags
title={this.documentTitle}
path={this.context.router.route.match.url}
import { Subscription } from "rxjs";
import { i18n } from "../../i18next";
import { InitialFetchRequest } from "../../interfaces";
-import { UserService, WebSocketService } from "../../services";
+import { WebSocketService } from "../../services";
import {
getRecipientIdFromProps,
isBrowser,
this.parseMessage = this.parseMessage.bind(this);
this.subscription = wsSubscribe(this.parseMessage);
- if (!UserService.Instance.myUserInfo && isBrowser()) {
- toast(i18n.t("not_logged_in"), "danger");
- this.context.router.history.push(`/login`);
- }
-
// Only fetch the data if coming from another route
if (this.isoData.path == this.context.router.route.match.url) {
this.state = {
import { CommentView, GetSiteResponse, LemmyHttp } from "lemmy-js-client";
import type { ParsedQs } from "qs";
+import { ErrorPageData } from "./utils";
/**
* This contains serialized data, it needs to be deserialized before use.
path: string;
routeData: any[];
site_res: GetSiteResponse;
+ errorPageData?: ErrorPageData;
}
+export type IsoDataOptionalSite = Partial<IsoData> &
+ Pick<IsoData, Exclude<keyof IsoData, "site_res">>;
+
export interface ILemmyConfig {
wsHost?: string;
}
| "gray"
| "gray-dark";
+export interface ErrorPageData {
+ error?: string;
+ adminMatrixIds?: string[];
+}
+
let customEmojis: EmojiMartCategory[] = [];
export let customEmojisLookup: Map<string, CustomEmojiView> = new Map<
string,
export function setIsoData(context: any): IsoData {
// If its the browser, you need to deserialize the data from the window
if (isBrowser()) {
- let json = window.isoData;
- let routeData = json.routeData;
- let site_res = json.site_res;
-
- let isoData: IsoData = {
- path: json.path,
- site_res,
- routeData,
- };
- return isoData;
+ return window.isoData;
} else return context.router.staticContext;
}
return local ? pName : `${hostname(actor_id)}/${pName}`;
}
-export function initializeSite(site: GetSiteResponse) {
- UserService.Instance.myUserInfo = site.my_user;
+export function initializeSite(site?: GetSiteResponse) {
+ UserService.Instance.myUserInfo = site?.my_user;
i18n.changeLanguage(getLanguages()[0]);
- setupEmojiDataModel(site.custom_emojis);
+ if (site) {
+ setupEmojiDataModel(site.custom_emojis);
+ }
setupMarkdown();
}
-{\r
- "compilerOptions": {\r
- "pretty": true,\r
- "target": "esnext",\r
- "module": "esnext",\r
- "allowSyntheticDefaultImports": true,\r
- "preserveConstEnums": true,\r
- "sourceMap": true,\r
- "moduleResolution": "node",\r
- "lib": ["es2017", "dom"],\r
- "types": [\r
- "inferno"\r
- ],\r
- "jsx": "preserve",\r
- "noUnusedLocals": true,\r
- "baseUrl": "./src",\r
- "noEmit": true,\r
- "skipLibCheck": true,\r
- "noUnusedParameters": true,\r
- "noImplicitReturns": true,\r
- "experimentalDecorators": true,\r
- "strictNullChecks": true,\r
- "noFallthroughCasesInSwitch": true\r
- },\r
- "include": [\r
- "src/**/*",\r
- "node_modules/inferno/dist/index.d.ts"\r
- ]\r
-}\r
+{
+ "compilerOptions": {
+ "pretty": true,
+ "target": "esnext",
+ "module": "esnext",
+ "allowSyntheticDefaultImports": true,
+ "preserveConstEnums": true,
+ "sourceMap": true,
+ "moduleResolution": "node",
+ "lib": ["es2017", "dom"],
+ "types": ["inferno"],
+ "jsx": "preserve",
+ "noUnusedLocals": true,
+ "baseUrl": "./src",
+ "noEmit": true,
+ "skipLibCheck": true,
+ "noUnusedParameters": true,
+ "noImplicitReturns": true,
+ "experimentalDecorators": true,
+ "strictNullChecks": true,
+ "noFallthroughCasesInSwitch": true
+ },
+ "include": [
+ "src/**/*.ts",
+ "src/**/*.tsx",
+ "node_modules/inferno/dist/index.d.ts"
+ ]
+}
resolved "https://registry.yarnpkg.com/lodash/-/lodash-3.10.1.tgz#5bf45e8e49ba4189e17d482789dfd15bd140b7b6"
integrity sha512-9mDDwqVIma6OZX79ZlDACZl8sBm0TEnkf99zV3iMA4GzkIT/9hiqP5mY0HoT1iNLCrKc/R1HByV+yJfRWVJryQ==
-lodash@^4.17.20:
+lodash@^4.17.20, lodash@^4.17.21:
version "4.17.21"
resolved "https://registry.yarnpkg.com/lodash/-/lodash-4.17.21.tgz#679591c564c3bffaae8454cf0b3df370c3d6911c"
integrity sha512-v2kDEe57lecTulaDIuNTPy3Ry4gLGJ6Z1O3vE1krgXZNrsQ+LFTGHVxVjcXPs17LhbZVGedAJv8XZ1tvj5FvSg==