Skip to content

Commit

Permalink
feat: frontend use router
Browse files Browse the repository at this point in the history
  • Loading branch information
samuelncui committed Dec 13, 2022
1 parent b9355ad commit cda9244
Show file tree
Hide file tree
Showing 10 changed files with 166 additions and 61 deletions.
13 changes: 6 additions & 7 deletions cmd/tape-httpd/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -96,15 +96,14 @@ func main() {
fs := http.FileServer(http.Dir("./frontend/assets"))
mux.Handle("/assets/", http.StripPrefix("/assets/", fs))

indexBuf, err := ioutil.ReadFile("./frontend/index.html")
if err != nil {
panic(err)
}

indexBuf = bytes.ReplaceAll(indexBuf, []byte("%%API_BASE%%"), []byte(fmt.Sprintf("%s/services", conf.Domain)))
mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
indexBuf, err := ioutil.ReadFile("./frontend/index.html")
if err != nil {
panic(err)
}

w.Header().Set("Content-Type", "text/html; charset=utf-8")
w.Write(indexBuf)
w.Write(bytes.ReplaceAll(indexBuf, []byte("%%API_BASE%%"), []byte(fmt.Sprintf("%s/services", conf.Domain))))
})

srv := &http.Server{
Expand Down
4 changes: 2 additions & 2 deletions executor/job_archive_exe.go
Original file line number Diff line number Diff line change
Expand Up @@ -84,7 +84,7 @@ func (a *jobArchiveExecutor) handle(ctx context.Context, param *entity.JobArchiv
}

tools.Working()
go tools.Wrap(ctx, func() {
go tools.WrapWithLogger(ctx, a.logger, func() {
defer tools.Done()
if err := a.makeTape(tools.ShutdownContext, p.Device, p.Barcode, p.Name); err != nil {
a.logger.WithContext(ctx).WithError(err).Errorf("make type has error, barcode= '%s' name= '%s'", p.Barcode, p.Name)
Expand Down Expand Up @@ -246,7 +246,7 @@ func (a *jobArchiveExecutor) makeTape(ctx context.Context, device, barcode, name
a.logger.WithContext(ctx).WithError(err).Warnf("open report file fail, barcode= '%s'", barcode)
} else {
defer reportFile.Close()
tools.Wrap(ctx, func() {
tools.WrapWithLogger(ctx, a.logger, func() {
reportFile.Write([]byte(report.ToJSONString(false)))
})
}
Expand Down
6 changes: 5 additions & 1 deletion frontend/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -26,12 +26,16 @@
"fast-text-encoding": "^1.0.6",
"filesize": "^10.0.5",
"format-duration": "^2.0.0",
"localforage": "^1.10.0",
"match-sorter": "^6.3.1",
"moment": "^2.29.4",
"react": "^18.2.0",
"react-dnd": "^11.1.3",
"react-dnd-html5-backend": "^11.1.3",
"react-dom": "^18.2.0",
"react-is": "^18.2.0"
"react-is": "^18.2.0",
"react-router-dom": "^6.4.5",
"sort-by": "^1.2.0"
},
"devDependencies": {
"@protobuf-ts/plugin": "^2.8.2",
Expand Down
74 changes: 74 additions & 0 deletions frontend/pnpm-lock.yaml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

69 changes: 32 additions & 37 deletions frontend/src/app.tsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
import { useEffect } from "react";
import { useState, useCallback } from "react";
import { ChangeEvent } from "react";
import { Fragment, useCallback, ChangeEvent } from "react";
import { Routes, Route, Link, useNavigate, Navigate, useLocation } from "react-router-dom";

import Tabs from "@mui/material/Tabs";
import Tab from "@mui/material/Tab";
Expand All @@ -13,62 +12,58 @@ import { JobsBrowser, JobsType } from "./jobs";
import "./app.less";
import { sleep } from "./api";
import { Nullable } from "tsdef";
import { Job } from "./entity";
import { useEffect } from "react";
import { useState } from "react";

// import reactLogo from './assets/react.svg'
// <img src={reactLogo} className="logo react" alt="React logo" />

const theme = createTheme({});

const typeToElement = (type: string) => {
switch (type) {
case FileBrowserType:
return <FileBrowser />;
case BackupType:
return <BackupBrowser />;
case JobsType:
return <JobsBrowser />;
default:
return null;
}
const Delay = ({ inner }: { inner: JSX.Element }) => {
const [ok, setOK] = useState(false);
useEffect(() => {
setOK(false);
(async () => {
await sleep(0);
setOK(true);
})();
return () => {
setOK(false);
};
}, [inner]);

return ok ? inner : null;
};

const App = () => {
const [tabValue, setTabValue] = useState(FileBrowserType);
const [inner, setInner] = useState<Nullable<JSX.Element>>(null);

const setType = useCallback(
(newValue: string) => {
(async () => {
setTabValue(newValue);
setInner(null);
await sleep(0);
setInner(typeToElement(newValue));
})();
},
[setTabValue, setInner]
);

const location = useLocation();
const navigate = useNavigate();
const handleTabChange = useCallback(
(_: ChangeEvent<{}>, newValue: string) => {
setType(newValue);
navigate("/" + newValue);
},
[setTabValue]
[navigate]
);

useEffect(() => {
setType(FileBrowserType);
}, []);

return (
<div id="app">
<ThemeProvider theme={theme}>
<Tabs className="tabs" value={tabValue} onChange={handleTabChange} indicatorColor="secondary">
<Tabs className="tabs" value={location.pathname.slice(1)} onChange={handleTabChange} indicatorColor="secondary">
<Tab label="File" value={FileBrowserType} />
<Tab label="Source" value={BackupType} />
<Tab label="Jobs" value={JobsType} />
</Tabs>
<Routes>
<Route path="/*">
<Route path={FileBrowserType} element={<Delay inner={<FileBrowser />} />} />
<Route path={BackupType} element={<Delay inner={<BackupBrowser />} />} />
<Route path={JobsType} element={<Delay inner={<JobsBrowser />} />} />
<Route path="*" element={<Navigate to={"/" + FileBrowserType} replace />} />
</Route>
</Routes>
</ThemeProvider>
{inner}
</div>
);
};
Expand Down
32 changes: 23 additions & 9 deletions frontend/src/file.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import { useState, useRef, useEffect, useMemo, useCallback } from "react";

import Grid from "@mui/material/Grid";
import Box from "@mui/material/Box";
import { FullFileBrowser, FileBrowserHandle, FileArray } from "chonky";
import { FullFileBrowser, FileBrowserProps, FileBrowserHandle, FileArray } from "chonky";
import { ChonkyActions, ChonkyFileActionData } from "chonky";

import "./app.less";
Expand Down Expand Up @@ -32,7 +32,7 @@ const useDualSide = () => {
return { instances, refreshAll };
};

const useFileBrowser = (refreshAll: () => Promise<void>, openDetailModel: (detail: FileGetReply) => void) => {
const useFileBrowser = (storageKey: string, refreshAll: () => Promise<void>, openDetailModel: (detail: FileGetReply) => void) => {
const [files, setFiles] = useState<FileArray>(Array(1).fill(null));
const [folderChain, setFolderChan] = useState<FileArray>([Root]);
const currentID = useMemo(() => {
Expand All @@ -48,15 +48,28 @@ const useFileBrowser = (refreshAll: () => Promise<void>, openDetailModel: (detai
return last.id;
}, [folderChain]);

const openFolder = useCallback((id: string) => {
const openFolder = useCallback(async (id: string) => {
const [file, folderChain] = await Promise.all([cli.fileGet({ id: BigInt(id) }).response, cli.fileListParents({ id: BigInt(id) }).response]);

setFiles(convertFiles(file.children));
setFolderChan([Root, ...convertFiles(folderChain.parents)]);
localStorage.setItem(storageKey, id);
}, []);
useEffect(() => {
(async () => {
const [file, folderChain] = await Promise.all([cli.fileGet({ id: BigInt(id) }).response, cli.fileListParents({ id: BigInt(id) }).response]);
const storagedID = localStorage.getItem(storageKey);
if (storagedID) {
try {
await openFolder(storagedID);
return;
} catch (e) {
console.log("open storaged id fail, err= ", e);
}
}

setFiles(convertFiles(file.children));
setFolderChan([Root, ...convertFiles(folderChain.parents)]);
openFolder(Root.id);
})();
}, []);
useEffect(() => openFolder(Root.id), []);

const onFileAction = useCallback(
(data: ChonkyFileActionData) => {
Expand Down Expand Up @@ -157,8 +170,8 @@ export const FileBrowser = () => {
const { instances, refreshAll } = useDualSide();
const { detail, openDetailModel, closeDetailModel } = useDetailModal();

const leftProps = useFileBrowser(refreshAll, openDetailModel);
const rightProps = useFileBrowser(refreshAll, openDetailModel);
const leftProps = useFileBrowser("file_browser:left:current_id", refreshAll, openDetailModel);
const rightProps = useFileBrowser("file_browser:right:current_id", refreshAll, openDetailModel);

useEffect(() => {
Object.values(instances).map((inst) => inst.current?.requestFileAction(ChonkyActions.ToggleHiddenFiles, {}));
Expand All @@ -167,6 +180,7 @@ export const FileBrowser = () => {
}, 10000);
return () => clearInterval(interval);
}, []);
useEffect(() => {});

return (
<Box className="browser-box">
Expand Down
Loading

0 comments on commit cda9244

Please sign in to comment.