Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

chore: update data initial requests #538

Merged
merged 1 commit into from
Nov 22, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 3 additions & 3 deletions api/system.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,9 @@ package api
import "github.com/usememos/memos/server/profile"

type SystemStatus struct {
Host *User `json:"host"`
Profile *profile.Profile `json:"profile"`
DBSize int64 `json:"dbSize"`
Host *User `json:"host"`
Profile profile.Profile `json:"profile"`
DBSize int64 `json:"dbSize"`

// System settings
// Allow sign up.
Expand Down
2 changes: 1 addition & 1 deletion server/system.go
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,7 @@ func (s *Server) registerSystemRoutes(g *echo.Group) {

systemStatus := api.SystemStatus{
Host: hostUser,
Profile: s.Profile,
Profile: *s.Profile,
DBSize: 0,
AllowSignUp: false,
AdditionalStyle: "",
Expand Down
40 changes: 17 additions & 23 deletions web/src/App.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,49 +2,43 @@ import { CssVarsProvider } from "@mui/joy/styles";
import { useEffect } from "react";
import { useTranslation } from "react-i18next";
import { RouterProvider } from "react-router-dom";
import { globalService, locationService } from "./services";
import { locationService } from "./services";
import { useAppSelector } from "./store";
import router from "./router";
import * as api from "./helpers/api";
import * as storage from "./helpers/storage";

function App() {
const { i18n } = useTranslation();
const global = useAppSelector((state) => state.global);
const { locale, systemStatus } = useAppSelector((state) => state.global);

useEffect(() => {
locationService.updateStateWithLocation();
window.onpopstate = () => {
locationService.updateStateWithLocation();
};

globalService.initialState();
}, []);

// Inject additional style and script codes.
useEffect(() => {
api.getSystemStatus().then(({ data }) => {
const { data: status } = data;
if (status.additionalStyle) {
const styleEl = document.createElement("style");
styleEl.innerHTML = status.additionalStyle;
styleEl.setAttribute("type", "text/css");
document.head.appendChild(styleEl);
}
if (status.additionalScript) {
const scriptEl = document.createElement("script");
scriptEl.innerHTML = status.additionalScript;
document.head.appendChild(scriptEl);
}
});
}, []);
if (systemStatus.additionalStyle) {
const styleEl = document.createElement("style");
styleEl.innerHTML = systemStatus.additionalStyle;
styleEl.setAttribute("type", "text/css");
document.head.appendChild(styleEl);
}
if (systemStatus.additionalScript) {
const scriptEl = document.createElement("script");
scriptEl.innerHTML = systemStatus.additionalScript;
document.head.appendChild(scriptEl);
}
}, [systemStatus]);

useEffect(() => {
i18n.changeLanguage(global.locale);
i18n.changeLanguage(locale);
storage.set({
locale: global.locale,
locale: locale,
});
}, [global.locale]);
}, [locale]);

return (
<CssVarsProvider>
Expand Down
37 changes: 9 additions & 28 deletions web/src/components/AboutSiteDialog.tsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
import { useEffect, useState } from "react";
import { useTranslation } from "react-i18next";
import * as api from "../helpers/api";
import { useAppSelector } from "../store";
import Icon from "./Icon";
import { generateDialog } from "./Dialog";
import GitHubBadge from "./GitHubBadge";
Expand All @@ -10,23 +9,7 @@ type Props = DialogProps;

const AboutSiteDialog: React.FC<Props> = ({ destroy }: Props) => {
const { t } = useTranslation();
const [profile, setProfile] = useState<Profile>();

useEffect(() => {
try {
api.getSystemStatus().then(({ data }) => {
const {
data: { profile },
} = data;
setProfile(profile);
});
} catch (error) {
setProfile({
mode: "dev",
version: "0.0.0",
});
}
}, []);
const profile = useAppSelector((state) => state.global.systemStatus.profile);

const handleCloseBtnClick = () => {
destroy();
Expand All @@ -49,15 +32,13 @@ const AboutSiteDialog: React.FC<Props> = ({ destroy }: Props) => {
<br />
<div className="addtion-info-container">
<GitHubBadge />
{profile !== undefined && (
<>
{t("common.version")}:
<span className="pre-text">
{profile?.version}-{profile?.mode}
</span>
🎉
</>
)}
<>
{t("common.version")}:
<span className="pre-text">
{profile.version}-{profile.mode}
</span>
🎉
</>
</div>
</div>
</>
Expand Down
1 change: 1 addition & 0 deletions web/src/components/MemoFilter.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import "../less/memo-filter.less";

const MemoFilter = () => {
const { t } = useTranslation();
useAppSelector((state) => state.shortcut.shortcuts);
const query = useAppSelector((state) => state.location.query);
const { tag: tagQuery, duration, type: memoType, text: textQuery, shortcutId, visibility } = query;
const shortcut = shortcutId ? shortcutService.getShortcutById(shortcutId) : null;
Expand Down
33 changes: 11 additions & 22 deletions web/src/components/UpdateVersionBanner.tsx
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { useEffect, useState } from "react";
import { useAppSelector } from "../store";
import * as api from "../helpers/api";
import * as storage from "../helpers/storage";
import Icon from "./Icon";
Expand All @@ -10,35 +11,23 @@ interface State {
}

const UpdateVersionBanner: React.FC = () => {
const profile = useAppSelector((state) => state.global.systemStatus.profile);
const [state, setState] = useState<State>({
latestVersion: "",
show: false,
});

useEffect(() => {
Promise.all([api.getRepoLatestTag(), api.getSystemStatus()])
.then(
([
latestTag,
{
data: {
data: { profile },
},
},
]) => {
const { skippedVersion } = storage.get(["skippedVersion"]);
const latestVersion = latestTag.slice(1) || "0.0.0";
const currentVersion = profile.version;
const skipped = skippedVersion ? skippedVersion === latestVersion : false;
setState({
latestVersion,
show: !skipped && currentVersion < latestVersion,
});
}
)
.catch(() => {
// do nth
api.getRepoLatestTag().then((latestTag) => {
const { skippedVersion } = storage.get(["skippedVersion"]);
const latestVersion = latestTag.slice(1) || "0.0.0";
const currentVersion = profile.version;
const skipped = skippedVersion ? skippedVersion === latestVersion : false;
setState({
latestVersion,
show: !skipped && currentVersion < latestVersion,
});
});
}, []);

const onSkip = () => {
Expand Down
68 changes: 25 additions & 43 deletions web/src/pages/Auth.tsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import { useEffect, useState } from "react";
import { useState } from "react";
import { useTranslation } from "react-i18next";
import { useNavigate } from "react-router-dom";
import { useAppSelector } from "../store";
import * as api from "../helpers/api";
import { validate, ValidatorConfig } from "../helpers/validator";
import useLoading from "../hooks/useLoading";
Expand All @@ -19,23 +20,11 @@ const validateConfig: ValidatorConfig = {
const Auth = () => {
const { t, i18n } = useTranslation();
const navigate = useNavigate();
const pageLoadingState = useLoading(true);
const [systemStatus, setSystemStatus] = useState<SystemStatus>();
const [email, setEmail] = useState("");
const [password, setPassword] = useState("");
const systemStatus = useAppSelector((state) => state.global.systemStatus);
const actionBtnLoadingState = useLoading(false);

useEffect(() => {
api.getSystemStatus().then(({ data }) => {
const { data: status } = data;
setSystemStatus(status);
if (status.profile.mode === "dev") {
setEmail("[email protected]");
setPassword("secret");
}
pageLoadingState.setFinish();
});
}, []);
const mode = systemStatus.profile.mode;
const [email, setEmail] = useState(mode === "dev" ? "[email protected]" : "");
const [password, setPassword] = useState(mode === "dev" ? "secret" : "");

const handleEmailInputChanged = (e: React.ChangeEvent<HTMLInputElement>) => {
const text = e.target.value as string;
Expand Down Expand Up @@ -138,39 +127,32 @@ const Auth = () => {
</div>
</div>
<div className="action-btns-container">
{!pageLoadingState.isLoading && (
{systemStatus?.host ? (
<>
{systemStatus?.host ? (
{actionBtnLoadingState.isLoading && <Icon.Loader className="w-4 h-auto animate-spin" />}
{systemStatus?.allowSignUp && (
<>
{actionBtnLoadingState.isLoading && <Icon.Loader className="w-4 h-auto animate-spin" />}
{systemStatus?.allowSignUp && (
<>
<button
className={`btn signup-btn ${actionBtnLoadingState.isLoading ? "requesting" : ""}`}
onClick={() => handleSignUpBtnsClick("USER")}
>
{t("common.sign-up")}
</button>
<span className="mr-2 font-mono text-gray-200">/</span>
</>
)}
<button
className={`btn signin-btn ${actionBtnLoadingState.isLoading ? "requesting" : ""}`}
onClick={handleSigninBtnsClick}
className={`btn signup-btn ${actionBtnLoadingState.isLoading ? "requesting" : ""}`}
onClick={() => handleSignUpBtnsClick("USER")}
>
{t("common.sign-in")}
</button>
</>
) : (
<>
<button
className={`btn signin-btn ${actionBtnLoadingState.isLoading ? "requesting" : ""}`}
onClick={() => handleSignUpBtnsClick("HOST")}
>
{t("auth.signup-as-host")}
{t("common.sign-up")}
</button>
<span className="mr-2 font-mono text-gray-200">/</span>
</>
)}
<button className={`btn signin-btn ${actionBtnLoadingState.isLoading ? "requesting" : ""}`} onClick={handleSigninBtnsClick}>
{t("common.sign-in")}
</button>
</>
) : (
<>
<button
className={`btn signin-btn ${actionBtnLoadingState.isLoading ? "requesting" : ""}`}
onClick={() => handleSignUpBtnsClick("HOST")}
>
{t("auth.signup-as-host")}
</button>
</>
)}
</div>
Expand Down
13 changes: 12 additions & 1 deletion web/src/router/index.tsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { createBrowserRouter, redirect } from "react-router-dom";
import { isNullorUndefined } from "../helpers/utils";
import { userService } from "../services";
import { globalService, userService } from "../services";
import Auth from "../pages/Auth";
import Explore from "../pages/Explore";
import Home from "../pages/Home";
Expand All @@ -10,12 +10,20 @@ const router = createBrowserRouter([
{
path: "/auth",
element: <Auth />,
loader: async () => {
try {
await globalService.initialState();
} catch (error) {
// do nth
}
},
},
{
path: "/",
element: <Home />,
loader: async () => {
try {
await globalService.initialState();
await userService.initialState();
} catch (error) {
// do nth
Expand All @@ -34,6 +42,7 @@ const router = createBrowserRouter([
element: <Home />,
loader: async () => {
try {
await globalService.initialState();
await userService.initialState();
} catch (error) {
// do nth
Expand All @@ -50,6 +59,7 @@ const router = createBrowserRouter([
element: <Explore />,
loader: async () => {
try {
await globalService.initialState();
await userService.initialState();
} catch (error) {
// do nth
Expand All @@ -66,6 +76,7 @@ const router = createBrowserRouter([
element: <MemoDetail />,
loader: async () => {
try {
await globalService.initialState();
await userService.initialState();
} catch (error) {
// do nth
Expand Down
14 changes: 8 additions & 6 deletions web/src/services/globalService.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@ import store from "../store";
import * as api from "../helpers/api";
import * as storage from "../helpers/storage";
import { setGlobalState, setLocale } from "../store/modules/global";
import { convertResponseModelUser } from "./userService";

const globalService = {
getState: () => {
Expand All @@ -12,19 +11,22 @@ const globalService = {
initialState: async () => {
const defaultGlobalState = {
locale: "en" as Locale,
systemStatus: {
allowSignUp: false,
additionalStyle: "",
additionalScript: "",
} as SystemStatus,
};

const { locale: storageLocale } = storage.get(["locale"]);
if (storageLocale) {
defaultGlobalState.locale = storageLocale;
}

try {
const { data } = (await api.getMyselfUser()).data;
const { data } = (await api.getSystemStatus()).data;
if (data) {
const user = convertResponseModelUser(data);
if (user.setting.locale) {
defaultGlobalState.locale = user.setting.locale;
}
defaultGlobalState.systemStatus = data;
}
} catch (error) {
// do nth
Expand Down
Loading