Compare commits

11 Commits

28 changed files with 28640 additions and 12630 deletions

23
.cracorc.js Normal file
View File

@ -0,0 +1,23 @@
const { ServiceRegister } = require("@fennec/configuration");
const { findFreePorts } = require("find-free-ports");
module.exports = async function () {
return {
devServer: {
open: false,
port: await findFreePorts().then((ports) => ports[0]),
onListening(devServer) {
if (!devServer) {
throw new Error("webpack-dev-server is not defined");
}
const port = devServer.listeningApp.address().port;
const register = new ServiceRegister({
etcd: { hosts: ["http://rpi:2379"] },
});
register.register("admin.blog", `http://localhost:${port}/`);
console.log("Listening on port:", port);
},
},
};
};

2
.vscode/launch.json vendored
View File

@ -9,7 +9,7 @@
"type": "chrome",
"request": "launch",
"reAttach": true,
"url": "http://admin.blog.localhost/",
"url": "http://admin.blog.localhost:7070/",
"webRoot": "${workspaceFolder}",
"userDataDir": "/Users/ivan/Projects/.chrome"
}

View File

@ -1,8 +1,10 @@
{
"cSpell.words": [
"Formik",
"clsx",
"fontsource",
"Formik",
"notistack",
"Swipeable",
"vditor"
]
}

View File

@ -1,8 +1,8 @@
module.exports = {
client: {
service: {
name: 'blog-be',
url: 'http://api.blog.localhost/graphql'
}
}
name: "blog-be",
url: "http://api.blog.localhost:7070/graphql",
},
},
};

View File

@ -1,5 +1,5 @@
overwrite: true
schema: "http://localhost:7132/graphql"
schema: "http://api.blog.localhost:7070/graphql"
# documents: "src/**/*.graphql"
generates:
src/generated/graphql.tsx:
@ -7,6 +7,6 @@ generates:
- "typescript"
- "typescript-operations"
- "typescript-react-apollo"
./graphql.schema.json:
src/generated/graphql.schema.json:
plugins:
- "introspection"

View File

@ -3,11 +3,16 @@ module.exports = {
{
name: "blog-bs",
script: "serve",
args: "-s build",
args: "",
watch: false,
ignore_watch: ["node_modules"],
log_date_format: "MM-DD HH:mm:ss.SSS Z",
env: {},
env: {
PM2_SERVE_PATH: "./build",
PM2_SERVE_PORT: 7135,
PM2_SERVE_SPA: "true",
PM2_SERVE_HOMEPAGE: "/index.html",
},
max_restarts: 5,
},
],

39293
package-lock.json generated

File diff suppressed because it is too large Load Diff

View File

@ -4,14 +4,17 @@
"private": true,
"dependencies": {
"@apollo/client": "^3.3.15",
"@curi/react-dom": "^2.0.4",
"@curi/router": "^2.1.2",
"@craco/craco": "^6.4.0",
"@date-io/date-fns": "^1.3.13",
"@emotion/react": "^11.6.0",
"@emotion/styled": "^11.6.0",
"@fennec/configuration": "^0.0.1",
"@hickory/browser": "^2.1.0",
"@material-ui/core": "^4.11.3",
"@material-ui/icons": "^4.11.2",
"@material-ui/lab": "*",
"@material-ui/pickers": "^3.3.10",
"@mui/icons-material": "^5.2.0",
"@mui/lab": "^5.0.0-alpha.56",
"@mui/material": "^5.2.0",
"@mui/styles": "^5.2.0",
"@nestjs-lib/auth": "^0.1.1",
"@testing-library/jest-dom": "^5.11.10",
"@testing-library/react": "^11.2.6",
"@testing-library/user-event": "^12.8.3",
@ -19,26 +22,35 @@
"@types/node": "^12.20.10",
"@types/react": "^17.0.3",
"@types/react-dom": "^17.0.3",
"date-fns": "^2.21.1",
"apollo-link-scalars": "^2.1.3",
"configuration": "^2.4.2",
"date-fns": "^2.22.1",
"eventemitter3": "^4.0.7",
"events": "^3.3.0",
"find-free-ports": "^3.0.0",
"fontsource-roboto": "^4.0.0",
"formik": "^2.2.6",
"formik-material-ui": "^3.0.1",
"formik-material-ui-pickers": "^0.0.12",
"graphql": "^15.5.0",
"graphql-scalars": "^1.10.0",
"notistack": "^1.0.9",
"npm": "^7.20.6",
"ramda": "^0.27.1",
"react": "^17.0.2",
"react-dom": "^17.0.2",
"react-router-dom": "^6.0.2",
"react-scripts": "4.0.3",
"subscriptions-transport-ws": "^0.9.19",
"typescript": "^4.2.4",
"vditor": "^3.8.4",
"web-vitals": "^1.1.1",
"yup": "^0.32.9"
},
"scripts": {
"start": "PORT=7135 BROWSER=none react-scripts start",
"build": "react-scripts build",
"test": "react-scripts test",
"eject": "react-scripts eject",
"start": "craco start",
"build": "craco build",
"test": "craco test",
"prestart": "npm run graphql",
"graphql": "graphql-codegen --config codegen.yml"
},
@ -66,9 +78,9 @@
"@graphql-codegen/typescript": "1.21.1",
"@graphql-codegen/typescript-operations": "1.17.15",
"@graphql-codegen/typescript-react-apollo": "2.2.3",
"@types/date-fns": "^2.6.0",
"@types/graphql": "^14.5.0",
"@types/ramda": "^0.27.40",
"@types/react-router-dom": "^5.3.2",
"@types/sass": "^1.16.0",
"@types/yup": "^0.29.11",
"sass": "^1.32.11"

View File

@ -1,15 +1,12 @@
import { useResponse } from '@curi/react-dom';
import './App.css';
import { DefaultLayout } from './layouts';
import { BrowserRouter } from "react-router-dom";
import "./App.css";
import { AppRoutes } from "./routes";
function App() {
const { response } = useResponse();
const { body: Body } = response;
return (
<DefaultLayout>
<Body response={response} />
</DefaultLayout>
<BrowserRouter>
<AppRoutes />
</BrowserRouter>
);
}

View File

@ -0,0 +1,5 @@
import { FC } from "react";
export const ArticleEditorHistory: FC = () => {
return <div>ArticleEditorHistory</div>;
};

View File

@ -1,18 +1,39 @@
import {
Badge,
Box,
Button,
createStyles,
Grid,
makeStyles,
IconButton,
Paper,
} from "@material-ui/core";
import { Field, Form, Formik, FormikHelpers } from "formik";
import { FC } from "react";
SwipeableDrawer,
Typography,
useTheme,
} from "@mui/material";
import createStyles from "@mui/styles/createStyles";
import makeStyles from "@mui/styles/makeStyles";
import { Field, Form, Formik, FormikHelpers, FormikProps } from "formik";
import { FC, useCallback, useRef, useState } from "react";
import { Editor } from "../commons/editor/vditor";
import * as Yup from "yup";
import { Article, CreateArticleInput, UpdateArticleInput } from "../generated/graphql";
import {
Article,
CreateArticleInput,
ArticleHistory,
UpdateArticleInput,
} from "../generated/graphql";
import { DateTimePicker } from "formik-material-ui-pickers";
import { gql, useMutation } from "@apollo/client";
import { useRouter } from "@curi/react-universal";
import * as R from "ramda";
import { useNavigate } from "react-router-dom";
import { useDrafts } from "./hooks/useDrafts";
import Timeline from "@mui/lab/Timeline";
import TimelineItem from "@mui/lab/TimelineItem";
import TimelineSeparator from "@mui/lab/TimelineSeparator";
import TimelineConnector from "@mui/lab/TimelineConnector";
import TimelineContent from "@mui/lab/TimelineContent";
import TimelineDot from "@mui/lab/TimelineDot";
import { HistoryEduOutlined } from "@mui/icons-material";
import { format } from "date-fns";
const CREATE_ARTICLE = gql`
mutation createArticle($createArticleInput: CreateArticleInput!) {
@ -47,13 +68,19 @@ const useStyles = makeStyles((theme) =>
})
);
type Values = CreateArticleInput | UpdateArticleInput;
const fields = ["title", "content", "publishedAt", "tags"] as const;
type Values = Pick<Article, typeof fields[number]> &
Partial<Pick<Article, "id">>;
interface Props {
article?: Values;
draftKey: string;
}
export const ArticleEditor: FC<Props> = ({ article }) => {
export const ArticleEditor: FC<Props> = ({ article, draftKey }) => {
const classes = useStyles();
const navigate = useNavigate();
const formik = useRef<FormikProps<Values>>(null);
const { draft, putDraft, drafts, getDraft } = useDrafts(draftKey);
const validationSchema = Yup.object({
content: Yup.string()
@ -61,11 +88,13 @@ export const ArticleEditor: FC<Props> = ({ article }) => {
.required("文章内容不得为空"),
publishedAt: Yup.date(),
});
const router = useRouter();
const [createArticle] = useMutation<{createArticle: Article} ,{
createArticleInput: CreateArticleInput;
}>(CREATE_ARTICLE, {
const [createArticle] = useMutation<
{ createArticle: Article },
{
createArticleInput: CreateArticleInput;
}
>(CREATE_ARTICLE, {
update(cache, { data }) {
cache.modify({
fields: {
@ -91,7 +120,7 @@ export const ArticleEditor: FC<Props> = ({ article }) => {
updateArticleInput: UpdateArticleInput;
}>(UPDATE_ARTICLE);
const SubmitForm = (
const submitForm = async (
values: Values,
{ setSubmitting }: FormikHelpers<Values>
) => {
@ -102,7 +131,7 @@ export const ArticleEditor: FC<Props> = ({ article }) => {
setSubmitting(false);
return;
}
updateArticle({
await updateArticle({
variables: {
updateArticleInput: {
...values,
@ -111,10 +140,7 @@ export const ArticleEditor: FC<Props> = ({ article }) => {
},
})
.then(() => {
router.navigate({
url: router.url({ name: "articles" }),
method: "replace",
});
navigate("/articles", { replace: true });
})
.finally(() => {
setSubmitting(false);
@ -126,19 +152,16 @@ export const ArticleEditor: FC<Props> = ({ article }) => {
setSubmitting(false);
return;
}
createArticle({
await createArticle({
variables: {
createArticleInput: {
...values as CreateArticleInput,
...(values as CreateArticleInput),
title,
},
},
})
.then(() => {
router.navigate({
url: router.url({ name: "articles" }),
method: "replace",
});
navigate("/articles", { replace: true });
})
.finally(() => {
setSubmitting(false);
@ -146,13 +169,28 @@ export const ArticleEditor: FC<Props> = ({ article }) => {
}
setSubmitting(false);
};
const handleSave = useCallback(
async (automatically = true) => {
await putDraft({
key: draftKey,
payload: formik.current?.values,
automatically,
});
},
[draftKey, putDraft, formik]
);
return (
<Paper>
<Formik
initialValues={article!}
initialValues={{
...R.pick(fields, article!),
}}
innerRef={formik}
validationSchema={validationSchema}
autoComplete="off"
onSubmit={SubmitForm}
onSubmit={submitForm}
>
{({ submitForm, isSubmitting }) => (
<Form className={classes.form}>
@ -178,10 +216,24 @@ export const ArticleEditor: FC<Props> = ({ article }) => {
variant="contained"
color="primary"
disabled={isSubmitting}
onClick={() => handleSave(false)}
>
Save
</Button>
<Button
style={{ marginLeft: "10px" }}
variant="contained"
color="secondary"
disabled={isSubmitting}
onClick={submitForm}
>
Submit
Publish
</Button>
<HistoryDrawer
drafts={drafts}
setCurrentDraft={(draft) => getDraft(draft.id)}
/>
</Grid>
</Grid>
</Form>
@ -191,11 +243,83 @@ export const ArticleEditor: FC<Props> = ({ article }) => {
);
};
interface HistoryDrawerProps {
drafts?: DraftArticle[];
setCurrentDraft: (draft: DraftArticle) => void;
}
const HistoryDrawer: FC<HistoryDrawerProps> = ({ drafts, setCurrentDraft }) => {
const theme = useTheme();
const [open, setOpen] = useState(false);
return (
<>
<IconButton aria-label="history" onClick={() => setOpen(!open)}>
<Badge color="secondary" badgeContent={drafts?.length}>
<HistoryEduOutlined />
</Badge>
</IconButton>
<SwipeableDrawer
container={window.document.body}
anchor="right"
open={open}
onClose={() => setOpen(false)}
onOpen={() => setOpen(true)}
swipeAreaWidth={50}
disableSwipeToOpen={false}
ModalProps={{
keepMounted: true,
BackdropProps: {
sx: {
backgroundColor: "transparent",
},
},
}}
>
<Box
sx={{
borderTopLeftRadius: 8,
borderTopRightRadius: 8,
visibility: "visible",
height: "100%",
width: "200px",
overflowY: "auto",
overflowX: "hidden",
mt: theme.mixins.toolbar.minHeight,
}}
>
<Timeline>
{drafts?.map((draft, index) => (
<TimelineItem
sx={{
"&:before": {
content: "unset",
},
}}
>
<TimelineSeparator>
<TimelineDot />
<TimelineConnector />
</TimelineSeparator>
<TimelineContent>
<Typography>
{index + 1} - {format(draft.updatedAt, "yyyy-MM-dd")}
</Typography>
<Typography>{format(draft.updatedAt, "HH:mm:ss")}</Typography>
</TimelineContent>
</TimelineItem>
))}
</Timeline>
</Box>
</SwipeableDrawer>
</>
);
};
ArticleEditor.defaultProps = {
article: {
title: "",
content: "",
publishedAt: new Date(),
tags: [],
} as CreateArticleInput,
} as Values,
};

View File

@ -8,13 +8,14 @@ import {
TableContainer,
TableHead,
TableRow,
} from "@material-ui/core";
} from "@mui/material";
import React, { FC } from "react";
import { Article } from "../generated/graphql";
import EditIcon from "@material-ui/icons/Edit";
import { useRouter } from "@curi/react-dom";
import { ARTICLES, REMOVE_ARTICLE } from './articles.constants';
import { Delete } from '@material-ui/icons';
import EditIcon from "@mui/icons-material/Edit";
import { ARTICLES, REMOVE_ARTICLE } from "./articles.constants";
import { Delete } from "@mui/icons-material";
import { format } from "date-fns";
import { useNavigate } from "react-router-dom";
export const ArticleIndex: FC = () => {
const { data } = useQuery<{
@ -23,7 +24,7 @@ export const ArticleIndex: FC = () => {
const [removeArticle] = useMutation<any, { id: string }>(REMOVE_ARTICLE);
const router = useRouter();
const navigate = useNavigate();
return (
<section>
@ -35,6 +36,7 @@ export const ArticleIndex: FC = () => {
<TableCell>Published At</TableCell>
<TableCell>Views</TableCell>
<TableCell>Comments</TableCell>
<TableCell>Status</TableCell>
<TableCell>Actions</TableCell>
</TableRow>
</TableHead>
@ -44,20 +46,19 @@ export const ArticleIndex: FC = () => {
<TableCell component="th" scope="row">
{article.title}
</TableCell>
<TableCell>{article.publishedAt}</TableCell>
<TableCell>
{article.publishedAt
? format(article.publishedAt, "yyyy-MM-dd HH:mm:ss")
: "--"}
</TableCell>
<TableCell align="right"> -- </TableCell>
<TableCell align="right"> -- </TableCell>
<TableCell align="center">{"Published"}</TableCell>
<TableCell>
<IconButton
aria-label="edit"
onClick={() =>
router.navigate({
url: router.url({
name: "modify-article",
params: article,
}),
})
}
onClick={() => navigate(`/articles/${article.id}`)}
size="large"
>
<EditIcon />
</IconButton>
@ -68,6 +69,7 @@ export const ArticleIndex: FC = () => {
variables: article,
})
}
size="large"
>
<Delete />
</IconButton>

View File

@ -7,6 +7,11 @@ export const ARTICLE = gql`
title
content
publishedAt
histories {
updatedAt
payload
automatically
}
}
}
`;

View File

@ -0,0 +1,147 @@
import { gql, useLazyQuery, useMutation, useQuery } from "@apollo/client";
import { useCallback, useState } from "react";
import { CreateDraftArticleInput, DraftArticle } from "../../generated/graphql";
export interface useDraftsProps {
key: string;
}
export interface useDraftsReturn {
drafts?: DraftArticle[];
draft?: DraftArticle;
listLoading: boolean;
itemLoading: boolean;
getDraft: (id: string) => Promise<DraftArticle>;
putDraft: (input: CreateDraftArticleInput) => Promise<DraftArticle>;
}
export const useDrafts = (key: string): useDraftsReturn => {
const { data: { drafts, lastDraft: last } = {}, loading: listLoading } =
useQuery<
{ drafts: DraftArticle[]; lastDraft: DraftArticle },
{ key: string }
>(
gql`
query DraftArticles($key: String!) {
drafts: listDraftForArticle(key: $key) {
id
key
automatically
updatedAt
}
lastDraft: lastDraftForArticle(key: $key) {
id
key
payload
automatically
updatedAt
}
}
`,
{
variables: { key },
}
);
const [
get,
{ data: { draft } = { draft: undefined }, loading: itemLoading },
] = useLazyQuery<
{
draft: DraftArticle;
},
{
id: string;
}
>(
gql`
query DraftArticles($id: String!) {
draft: lastDraftForArticle(id: $id) {
id
key
payload
automatically
updatedAt
}
}
`
);
const [put] = useMutation<
{
draft: DraftArticle;
},
{
draft: CreateDraftArticleInput;
}
>(
gql`
mutation PutDraftForArticle($draft: CreateDraftArticleInput!) {
draft: putDraftForArticle(draft: $draft) {
id
key
payload
automatically
updatedAt
}
}
`,
{
update(cache, { data }) {
if (data?.draft) {
const newDraftRef = cache.writeFragment({
data: data.draft,
fragment: gql`
fragment NewDraftArticle on DraftArticle {
id
key
payload
automatically
updatedAt
}
`,
});
cache.modify({
fields: {
drafts(existingDrafts: DraftArticle[] = [], { readField }) {
return [
newDraftRef,
...existingDrafts.filter(
(draft: any) => readField("id", draft) !== data.draft.id
),
];
},
lastDraft() {
return newDraftRef;
},
},
});
}
},
}
);
const getDraft = useCallback(
async (id: string) => {
return get({ variables: { id } }).then(({ data }) => data!.draft);
},
[get]
);
const putDraft = useCallback(
async (input: CreateDraftArticleInput) => {
return put({ variables: { draft: input } }).then(
({ data }) => data!.draft
);
},
[put]
);
return {
drafts,
draft: draft ?? last,
listLoading,
itemLoading,
getDraft,
putDraft,
};
};

View File

@ -0,0 +1,55 @@
import { createContext, useContext, useState } from "react";
import { FC } from "react";
import { Login } from "./login";
export interface AuthContext {
accessToken: string | null;
setAccessToken: (token: string) => void;
setRefreshToken: (token: string) => void;
refreshToken: string | undefined;
login: (dto: any) => void;
account?: any;
setAccount: (dto: any) => void;
logout: () => void;
}
const Context = createContext({} as AuthContext);
export const useAuth = () => useContext(Context);
export const AuthProvider: FC = ({ children }) => {
const [accessToken, setAccessToken] = useState<string | null>(
localStorage.getItem("accessToken")
);
const [refreshToken, setRefreshToken] = useState<string>();
const [account, setAccount] = useState<any>();
const login = (dto: any) => {
setAccessToken(dto.accessToken);
setRefreshToken(dto.refreshToken);
setAccount(dto.account);
localStorage.setItem("accessToken", dto.accessToken);
};
const logout = () => {
setAccessToken(null);
setRefreshToken(undefined);
setAccount(undefined);
};
return (
<Context.Provider
value={{
accessToken,
setAccessToken,
refreshToken,
setRefreshToken,
login,
account,
setAccount,
logout,
}}
>
{children}
{accessToken ? null : <Login />}
</Context.Provider>
);
};

View File

@ -0,0 +1,66 @@
import makeStyles from '@mui/styles/makeStyles';
import { FC, Fragment, useEffect, useRef } from "react";
import { useAuth } from "./auth.provider";
const useStyles = makeStyles((theme) => ({
iframe: {
height: "300px",
width: "500px",
position: "absolute",
top: "100px",
left: "50%",
transform: "translateX(-50%)",
zIndex: theme.zIndex.modal,
border: "none",
boxShadow: theme.shadows[4],
},
mask: {
top: "0",
left: "0",
bottom: "0",
right: "0",
position: "absolute",
backgroundColor: "rgba(0, 0, 0, 0.3)",
zIndex: theme.zIndex.modal,
},
}));
export const Login: FC = () => {
const iframeRef = useRef<HTMLIFrameElement>(null);
const { login } = useAuth();
useEffect(() => {
const iframe = iframeRef.current;
if (!iframe) {
return;
}
let messagePort: MessagePort;
const onLoad = (ev: MessageEvent) => {
if (ev.data !== "init-channel") {
return;
}
messagePort = ev.ports?.[0] as MessagePort;
messagePort.onmessage = (ev: MessageEvent) => {
if (ev.data?.type === "logged") {
login(ev.data.payload);
}
};
};
window.addEventListener("message", onLoad);
return () => {
window.removeEventListener("message", onLoad);
};
}, [login]);
const classes = useStyles();
return (
<Fragment>
<div className={classes.mask} />
<iframe
ref={iframeRef}
className={classes.iframe}
title="Auth"
src="https://user.rpi.ivanli.cc/auth/login"
></iframe>
</Fragment>
);
};

View File

@ -1,10 +1,13 @@
import { createStyles, FormControl, FormHelperText, FormLabel, makeStyles } from '@material-ui/core';
import { FieldHookConfig, useField } from 'formik';
import React, { FC, useEffect, useRef, useState } from 'react';
import Vditor from 'vditor';
import 'vditor/src/assets/scss/index.scss';
import { FormControl, FormHelperText, FormLabel } from '@mui/material';
import createStyles from '@mui/styles/createStyles';
import makeStyles from '@mui/styles/makeStyles';
import { Skeleton } from '@mui/material';
import { FieldHookConfig, useField } from "formik";
import React, { FC, useEffect, useMemo, useRef, useState } from "react";
import Vditor from "vditor";
import "vditor/src/assets/scss/index.scss";
type Props = (FieldHookConfig<string>) & {
type Props = FieldHookConfig<string> & {
label?: string;
className?: string;
};
@ -12,16 +15,19 @@ type Props = (FieldHookConfig<string>) & {
const useStyles = makeStyles((theme) =>
createStyles({
formControl: {
width: '100%',
width: "100%",
},
})
);
export const Editor: FC<Props> = ({ label, className, ...props }) => {
const [field, meta, helpers] = useField(props);
const [, meta, helpers] = useField(props);
const editor = useRef<HTMLDivElement>(null);
const [instance, setInstance] = useState<Vditor | null>(() => null);
const [containerKey] = useState(() => Math.random().toString(36).slice(2, 8));
const containerKey = useMemo(
() => Math.random().toString(36).slice(2, 8),
[]
);
useEffect(() => {
if (!editor.current) {
return;
@ -36,19 +42,36 @@ export const Editor: FC<Props> = ({ label, className, ...props }) => {
value: meta.initialValue,
input: (val) => helpers.setValue(val),
blur: () => helpers.setTouched(true),
after: () => {
setInstance(_instance);
},
});
setInstance(_instance);
return () => {
instance?.destroy();
_instance?.destroy();
};
}, []);
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [containerKey]);
const classes = useStyles();
return (
<FormControl className={classes.formControl}>
<FormLabel>{label}</FormLabel>
<div className={className} ref={editor} key={containerKey}></div>
<div
className={`${className} vditor`}
ref={editor}
key={containerKey}
></div>
{meta.error && <FormHelperText error={true}>{meta.error}</FormHelperText>}
{instance ? null : (
<Skeleton
variant="rectangular"
animation="wave"
height="100%"
width="100%"
style={{ position: "absolute" }}
/>
)}
</FormControl>
);
};

View File

@ -1,6 +0,0 @@
import { ApolloClient, InMemoryCache } from "@apollo/client";
export const client = new ApolloClient({
uri: "/api/graphql",
cache: new InMemoryCache(),
});

View File

@ -0,0 +1,178 @@
import {
ApolloClient,
ApolloLink,
HttpLink,
InMemoryCache,
split,
ApolloProvider,
fromPromise,
FetchResult,
} from "@apollo/client";
import { withScalars } from "apollo-link-scalars";
import { buildClientSchema, IntrospectionQuery } from "graphql";
import { DateTimeResolver } from "graphql-scalars";
import { FC } from "react";
import introspectionResult from "../../generated/graphql.schema.json";
import { onError } from "@apollo/client/link/error";
import { WebSocketLink } from "@apollo/client/link/ws";
import { getMainDefinition, Observable } from "@apollo/client/utilities";
import { useSnackbar } from "notistack";
import { deepOmit } from "../../utils/deep-omit";
import { useMemo } from "react";
import { EventEmitter } from "events";
import { useState } from "react";
import { useAuth } from "../auth/auth.provider";
import { useEffect } from "react";
import { useRef } from "react";
import { setContext } from "@apollo/client/link/context";
const schema = buildClientSchema(
introspectionResult as unknown as IntrospectionQuery
);
const typesMap = {
DateTime: DateTimeResolver,
};
const cleanTypeName = new ApolloLink((operation, forward) => {
if (operation.variables) {
operation.variables = deepOmit(["__typename"], operation.variables);
}
const rt = forward(operation);
return (
rt.map?.((data) => {
return data;
}) ?? rt
);
});
export const AppApolloClientProvider: FC = ({ children }) => {
const { enqueueSnackbar } = useSnackbar();
const { accessToken, logout } = useAuth();
const [loggedEventTarget] = useState(() => new EventEmitter());
const accessTokenRef = useRef(accessToken);
const logoutRef = useRef(logout);
useEffect(() => {
accessTokenRef.current = accessToken;
if (accessToken) {
loggedEventTarget.emit("logged", accessToken);
}
}, [loggedEventTarget, accessToken]);
useEffect(() => {
logoutRef.current = logout;
}, [logout]);
const client = useMemo(() => {
const authLink = onError(
({ graphQLErrors, networkError, operation, forward }) => {
if (graphQLErrors) {
for (const error of graphQLErrors) {
if (error.extensions?.code === "401") {
return fromPromise(
new Promise<Observable<FetchResult>>((resolve) => {
loggedEventTarget.once("logged", (accessToken: string) => {
const oldHeaders = operation.getContext().headers;
operation.setContext({
headers: {
...oldHeaders,
authorization: `Bearer ${accessToken}`,
},
});
resolve(forward(operation));
});
logoutRef.current();
})
).flatMap((v) => v);
}
}
}
const httpResult = (networkError as any)?.result;
if (httpResult?.statusCode === 401) {
return fromPromise(
new Promise<Observable<FetchResult>>((resolve) => {
loggedEventTarget.once("logged", (accessToken: string) => {
const oldHeaders = operation.getContext().headers;
operation.setContext({
headers: {
...oldHeaders,
authorization: `Bearer ${accessToken}`,
},
});
resolve(forward(operation));
});
logoutRef.current();
})
).flatMap((v) => v);
}
}
).concat(
setContext(() => ({
headers: {
authorization: `Bearer ${accessTokenRef.current}`,
},
}))
);
const errorLink = onError(({ graphQLErrors, networkError }) => {
if (graphQLErrors) {
graphQLErrors.forEach((error) => {
enqueueSnackbar(error.message, {
variant: "error",
});
});
graphQLErrors.forEach(({ message, locations, path }) => {
console.error(
`[GraphQL error]: Message: ${message}, Location: ${locations}, Path: ${path}`
);
});
}
if (networkError) {
console.log(`[Network error]: ${networkError}`);
enqueueSnackbar(networkError.message, {
variant: "error",
});
}
});
const wsLink = new WebSocketLink({
uri: `${window.location.protocol.replace("http", "ws")}//${
window.location.hostname
}:${window.location.port}/api/graphql`,
options: {
reconnect: true,
},
});
const httpLink = new HttpLink({
uri: "/api/graphql",
});
const splitLink = split(
({ query }) => {
const definition = getMainDefinition(query);
return (
definition.kind === "OperationDefinition" &&
definition.operation === "subscription"
);
},
wsLink,
httpLink
);
const link = ApolloLink.from([
errorLink,
authLink,
withScalars({ schema, typesMap }) as unknown as ApolloLink,
cleanTypeName,
splitLink,
]);
const client = new ApolloClient({
connectToDevTools: true,
ssrMode: typeof window === "undefined",
link,
cache: new InMemoryCache({
typePolicies: {},
}),
});
return client;
}, [enqueueSnackbar, loggedEventTarget]);
return <ApolloProvider client={client}>{children}</ApolloProvider>;
};

View File

@ -96,6 +96,58 @@
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "html",
"description": null,
"args": [],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "SCALAR",
"name": "String",
"ofType": null
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "description",
"description": null,
"args": [],
"type": {
"kind": "SCALAR",
"name": "String",
"ofType": null
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "histories",
"description": null,
"args": [],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "LIST",
"name": null,
"ofType": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "OBJECT",
"name": "ArticleHistory",
"ofType": null
}
}
}
},
"isDeprecated": false,
"deprecationReason": null
}
],
"inputFields": null,
@ -123,6 +175,91 @@
"enumValues": null,
"possibleTypes": null
},
{
"kind": "OBJECT",
"name": "ArticleHistory",
"description": null,
"fields": [
{
"name": "payload",
"description": null,
"args": [],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "SCALAR",
"name": "Object",
"ofType": null
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "updatedAt",
"description": null,
"args": [],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "SCALAR",
"name": "DateTime",
"ofType": null
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "automatic",
"description": null,
"args": [],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "SCALAR",
"name": "Boolean",
"ofType": null
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "published",
"description": null,
"args": [],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "SCALAR",
"name": "Boolean",
"ofType": null
}
},
"isDeprecated": false,
"deprecationReason": null
}
],
"inputFields": null,
"interfaces": [],
"enumValues": null,
"possibleTypes": null
},
{
"kind": "SCALAR",
"name": "Boolean",
"description": "The `Boolean` scalar type represents `true` or `false`.",
"fields": null,
"inputFields": null,
"interfaces": null,
"enumValues": null,
"possibleTypes": null
},
{
"kind": "INPUT_OBJECT",
"name": "CreateArticleInput",
@ -202,6 +339,33 @@
"enumValues": null,
"possibleTypes": null
},
{
"kind": "INPUT_OBJECT",
"name": "CreateTagInput",
"description": null,
"fields": null,
"inputFields": [
{
"name": "name",
"description": null,
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "SCALAR",
"name": "String",
"ofType": null
}
},
"defaultValue": null,
"isDeprecated": false,
"deprecationReason": null
}
],
"interfaces": null,
"enumValues": null,
"possibleTypes": null
},
{
"kind": "SCALAR",
"name": "DateTime",
@ -342,6 +506,105 @@
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "createTag",
"description": null,
"args": [
{
"name": "createTagInput",
"description": null,
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "INPUT_OBJECT",
"name": "CreateTagInput",
"ofType": null
}
},
"defaultValue": null,
"isDeprecated": false,
"deprecationReason": null
}
],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "OBJECT",
"name": "Tag",
"ofType": null
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "updateTag",
"description": null,
"args": [
{
"name": "updateTagInput",
"description": null,
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "INPUT_OBJECT",
"name": "UpdateTagInput",
"ofType": null
}
},
"defaultValue": null,
"isDeprecated": false,
"deprecationReason": null
}
],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "OBJECT",
"name": "Tag",
"ofType": null
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "removeTag",
"description": null,
"args": [
{
"name": "id",
"description": null,
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "SCALAR",
"name": "String",
"ofType": null
}
},
"defaultValue": null,
"isDeprecated": false,
"deprecationReason": null
}
],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "OBJECT",
"name": "Tag",
"ofType": null
}
},
"isDeprecated": false,
"deprecationReason": null
}
],
"inputFields": null,
@ -359,6 +622,16 @@
"enumValues": null,
"possibleTypes": null
},
{
"kind": "SCALAR",
"name": "Object",
"description": "The `JSONObject` scalar type represents JSON objects as specified by [ECMA-404](http://www.ecma-international.org/publications/files/ECMA-ST/ECMA-404.pdf).",
"fields": null,
"inputFields": null,
"interfaces": null,
"enumValues": null,
"possibleTypes": null
},
{
"kind": "OBJECT",
"name": "Query",
@ -436,6 +709,106 @@
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "tags",
"description": null,
"args": [],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "LIST",
"name": null,
"ofType": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "OBJECT",
"name": "Tag",
"ofType": null
}
}
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "tag",
"description": null,
"args": [
{
"name": "id",
"description": null,
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "SCALAR",
"name": "String",
"ofType": null
}
},
"defaultValue": null,
"isDeprecated": false,
"deprecationReason": null
}
],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "OBJECT",
"name": "Tag",
"ofType": null
}
},
"isDeprecated": false,
"deprecationReason": null
}
],
"inputFields": null,
"interfaces": [],
"enumValues": null,
"possibleTypes": null
},
{
"kind": "OBJECT",
"name": "Tag",
"description": null,
"fields": [
{
"name": "id",
"description": null,
"args": [],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "SCALAR",
"name": "ID",
"ofType": null
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "name",
"description": null,
"args": [],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "SCALAR",
"name": "String",
"ofType": null
}
},
"isDeprecated": false,
"deprecationReason": null
}
],
"inputFields": null,
@ -527,11 +900,40 @@
"possibleTypes": null
},
{
"kind": "SCALAR",
"name": "Boolean",
"description": "The `Boolean` scalar type represents `true` or `false`.",
"kind": "INPUT_OBJECT",
"name": "UpdateTagInput",
"description": null,
"fields": null,
"inputFields": null,
"inputFields": [
{
"name": "name",
"description": null,
"type": {
"kind": "SCALAR",
"name": "String",
"ofType": null
},
"defaultValue": null,
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "id",
"description": null,
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "SCALAR",
"name": "String",
"ofType": null
}
},
"defaultValue": null,
"isDeprecated": false,
"deprecationReason": null
}
],
"interfaces": null,
"enumValues": null,
"possibleTypes": null
@ -1278,7 +1680,20 @@
{
"name": "args",
"description": null,
"args": [],
"args": [
{
"name": "includeDeprecated",
"description": null,
"type": {
"kind": "SCALAR",
"name": "Boolean",
"ofType": null
},
"defaultValue": "false",
"isDeprecated": false,
"deprecationReason": null
}
],
"type": {
"kind": "NON_NULL",
"name": null,

View File

@ -12,6 +12,8 @@ export type Scalars = {
Float: number;
/** A date-time string at UTC, such as 2019-12-03T09:54:33Z, compliant with the date-time format. */
DateTime: any;
/** The `JSONObject` scalar type represents JSON objects as specified by [ECMA-404](http://www.ecma-international.org/publications/files/ECMA-ST/ECMA-404.pdf). */
Object: any;
};
export type Article = {
@ -21,6 +23,17 @@ export type Article = {
content: Scalars['String'];
publishedAt?: Maybe<Scalars['DateTime']>;
tags: Array<Scalars['String']>;
html: Scalars['String'];
description?: Maybe<Scalars['String']>;
histories: Array<ArticleHistory>;
};
export type ArticleHistory = {
__typename?: 'ArticleHistory';
payload: Scalars['Object'];
updatedAt: Scalars['DateTime'];
automatic: Scalars['Boolean'];
published: Scalars['Boolean'];
};
export type CreateArticleInput = {
@ -30,6 +43,10 @@ export type CreateArticleInput = {
tags: Array<Scalars['String']>;
};
export type CreateTagInput = {
name: Scalars['String'];
};
export type Hello = {
__typename?: 'Hello';
@ -41,6 +58,9 @@ export type Mutation = {
createArticle: Article;
updateArticle: Article;
removeArticle: Scalars['Int'];
createTag: Tag;
updateTag: Tag;
removeTag: Tag;
};
@ -58,11 +78,29 @@ export type MutationRemoveArticleArgs = {
id: Scalars['String'];
};
export type MutationCreateTagArgs = {
createTagInput: CreateTagInput;
};
export type MutationUpdateTagArgs = {
updateTagInput: UpdateTagInput;
};
export type MutationRemoveTagArgs = {
id: Scalars['String'];
};
export type Query = {
__typename?: 'Query';
hello: Hello;
articles: Array<Article>;
article: Article;
tags: Array<Tag>;
tag: Tag;
};
@ -70,6 +108,17 @@ export type QueryArticleArgs = {
id: Scalars['String'];
};
export type QueryTagArgs = {
id: Scalars['String'];
};
export type Tag = {
__typename?: 'Tag';
id: Scalars['ID'];
name: Scalars['String'];
};
export type UpdateArticleInput = {
title?: Maybe<Scalars['String']>;
content?: Maybe<Scalars['String']>;
@ -77,3 +126,8 @@ export type UpdateArticleInput = {
tags?: Maybe<Array<Scalars['String']>>;
id: Scalars['String'];
};
export type UpdateTagInput = {
name?: Maybe<Scalars['String']>;
id: Scalars['String'];
};

View File

@ -4,40 +4,44 @@ import "./index.css";
import "fontsource-roboto";
import App from "./App";
import reportWebVitals from "./reportWebVitals";
import { client } from "./commons/graphql/client";
import { ApolloProvider } from "@apollo/client";
import { AppApolloClientProvider } from "./commons/graphql/client";
import { MuiPickersUtilsProvider } from "@material-ui/pickers";
import DateFnsUtils from "@date-io/date-fns";
import zhLocale from "date-fns/locale/zh-CN";
import { createRouterComponent } from "@curi/react-dom";
import { createRouter, announce } from "@curi/router";
import { browser } from "@hickory/browser";
import routes from "./routes";
import { SnackbarProvider } from "notistack";
import { AuthProvider } from "./commons/auth/auth.provider";
import {
ThemeProvider,
Theme,
StyledEngineProvider,
createTheme,
} from "@mui/material/styles";
const router = createRouter(browser, routes, {
sideEffects: [
announce(({ response }) => {
return `Navigated to ${response.location.pathname}`;
}),
],
external: { client }
});
const Router = createRouterComponent(router);
declare module "@mui/styles/defaultTheme" {
// eslint-disable-next-line @typescript-eslint/no-empty-interface
interface DefaultTheme extends Theme {}
}
router.once(() => {
ReactDOM.render(
<React.StrictMode>
<ApolloProvider client={client}>
<MuiPickersUtilsProvider utils={DateFnsUtils} locale={zhLocale}>
<Router>
<App />
</Router>
</MuiPickersUtilsProvider>
</ApolloProvider>
</React.StrictMode>,
document.getElementById("root")
);
});
const theme = createTheme();
ReactDOM.render(
<React.StrictMode>
<StyledEngineProvider injectFirst>
<ThemeProvider theme={theme}>
<SnackbarProvider maxSnack={5}>
<AuthProvider>
<AppApolloClientProvider>
<MuiPickersUtilsProvider utils={DateFnsUtils} locale={zhLocale}>
<App />
</MuiPickersUtilsProvider>
</AppApolloClientProvider>
</AuthProvider>
</SnackbarProvider>
</ThemeProvider>
</StyledEngineProvider>
</React.StrictMode>,
document.getElementById("root")
);
// If you want to start measuring performance in your app, pass a function
// to log results (for example: reportWebVitals(console.log))

View File

@ -1,95 +1,96 @@
import React, { FC } from "react";
import clsx from "clsx";
import {
createStyles,
makeStyles,
useTheme,
Theme,
} from "@material-ui/core/styles";
import Drawer from "@material-ui/core/Drawer";
import AppBar from "@material-ui/core/AppBar";
import Toolbar from "@material-ui/core/Toolbar";
import List from "@material-ui/core/List";
import CssBaseline from "@material-ui/core/CssBaseline";
import Typography from "@material-ui/core/Typography";
import Divider from "@material-ui/core/Divider";
import IconButton from "@material-ui/core/IconButton";
import MenuIcon from "@material-ui/icons/Menu";
import ChevronLeftIcon from "@material-ui/icons/ChevronLeft";
import ChevronRightIcon from "@material-ui/icons/ChevronRight";
import ListItem from "@material-ui/core/ListItem";
import ListItemIcon from "@material-ui/core/ListItemIcon";
import ListItemText from "@material-ui/core/ListItemText";
import { AddCircle, Description, LocalOffer } from '@material-ui/icons';
import { Link } from '@curi/react-dom';
import React, { FC, Suspense } from "react";
import { useTheme, Theme, CSSObject, styled } from "@mui/material/styles";
import Drawer from "@mui/material/Drawer";
import AppBar, { AppBarProps } from "@mui/material/AppBar";
import Toolbar from "@mui/material/Toolbar";
import List from "@mui/material/List";
import CssBaseline from "@mui/material/CssBaseline";
import Typography from "@mui/material/Typography";
import Divider from "@mui/material/Divider";
import IconButton from "@mui/material/IconButton";
import MenuIcon from "@mui/icons-material/Menu";
import ChevronLeftIcon from "@mui/icons-material/ChevronLeft";
import ChevronRightIcon from "@mui/icons-material/ChevronRight";
import ListItem from "@mui/material/ListItem";
import ListItemIcon from "@mui/material/ListItemIcon";
import ListItemText from "@mui/material/ListItemText";
import { AddCircle, Description, LocalOffer } from "@mui/icons-material";
import { Box } from "@mui/system";
import { Link } from "react-router-dom";
const drawerWidth = 240;
const useStyles = makeStyles((theme: Theme) =>
createStyles({
root: {
display: "flex",
},
appBar: {
zIndex: theme.zIndex.drawer + 1,
transition: theme.transitions.create(["width", "margin"], {
easing: theme.transitions.easing.sharp,
duration: theme.transitions.duration.leavingScreen,
}),
},
appBarShift: {
marginLeft: drawerWidth,
width: `calc(100% - ${drawerWidth}px)`,
transition: theme.transitions.create(["width", "margin"], {
easing: theme.transitions.easing.sharp,
duration: theme.transitions.duration.enteringScreen,
}),
},
menuButton: {
marginRight: 36,
},
hide: {
display: "none",
},
drawer: {
width: drawerWidth,
flexShrink: 0,
whiteSpace: "nowrap",
},
drawerOpen: {
width: drawerWidth,
transition: theme.transitions.create("width", {
easing: theme.transitions.easing.sharp,
duration: theme.transitions.duration.enteringScreen,
}),
},
drawerClose: {
transition: theme.transitions.create("width", {
easing: theme.transitions.easing.sharp,
duration: theme.transitions.duration.leavingScreen,
}),
overflowX: "hidden",
width: theme.spacing(7) + 1,
[theme.breakpoints.up("sm")]: {
width: theme.spacing(9) + 1,
},
},
toolbar: {
display: "flex",
alignItems: "center",
justifyContent: "flex-end",
padding: theme.spacing(0, 1),
// necessary for content to be below app bar
...theme.mixins.toolbar,
},
content: {
flexGrow: 1,
padding: theme.spacing(3),
},
})
);
const openedMixin = (theme: Theme): CSSObject => ({
width: drawerWidth,
transition: theme.transitions.create("width", {
easing: theme.transitions.easing.sharp,
duration: theme.transitions.duration.enteringScreen,
}),
overflowX: "hidden",
});
export const DefaultLayout: FC = ({children}) => {
const classes = useStyles();
const closedMixin = (theme: Theme): CSSObject => ({
transition: theme.transitions.create("width", {
easing: theme.transitions.easing.sharp,
duration: theme.transitions.duration.leavingScreen,
}),
overflowX: "hidden",
width: `calc(${theme.spacing(7)} + 1px)`,
});
const DrawerHeader = styled("div")(({ theme }) => ({
display: "flex",
alignItems: "center",
justifyContent: "flex-end",
padding: theme.spacing(0, 1),
// necessary for content to be below app bar
...theme.mixins.toolbar,
}));
const Main = styled("main")(({ theme }) => ({
padding: theme.spacing(2, 2),
[theme.breakpoints.up("md")]: {
padding: theme.spacing(4, 3),
},
width: "100%",
marginTop: theme.mixins.toolbar.minHeight,
}));
const StyledAppBar = styled(AppBar, {
shouldForwardProp: (prop) => prop !== "open",
})<AppBarProps & { open?: boolean }>(({ theme, open }) => ({
zIndex: theme.zIndex.drawer + 1,
transition: theme.transitions.create(["width", "margin"], {
easing: theme.transitions.easing.sharp,
duration: theme.transitions.duration.leavingScreen,
}),
...(open && {
marginLeft: drawerWidth,
width: `calc(100% - ${drawerWidth}px)`,
transition: theme.transitions.create(["width", "margin"], {
easing: theme.transitions.easing.sharp,
duration: theme.transitions.duration.enteringScreen,
}),
}),
}));
const StyledDrawer = styled(Drawer, {
shouldForwardProp: (prop) => prop !== "open",
})(({ theme, open }) => ({
width: drawerWidth,
flexShrink: 0,
whiteSpace: "nowrap",
boxSizing: "border-box",
...(open && {
...openedMixin(theme),
"& .MuiDrawer-paper": openedMixin(theme),
}),
...(!open && {
...closedMixin(theme),
"& .MuiDrawer-paper": closedMixin(theme),
}),
}));
export const DefaultLayout: FC = ({ children }) => {
const theme = useTheme();
const [open, setOpen] = React.useState(false);
@ -102,86 +103,70 @@ export const DefaultLayout: FC = ({children}) => {
};
return (
<div className={classes.root}>
<CssBaseline />
<AppBar
position="fixed"
className={clsx(classes.appBar, {
[classes.appBarShift]: open,
})}
>
<Toolbar>
<IconButton
color="inherit"
aria-label="open drawer"
onClick={handleDrawerOpen}
edge="start"
className={clsx(classes.menuButton, {
[classes.hide]: open,
})}
>
<MenuIcon />
</IconButton>
<Typography variant="h6" noWrap>
Mini variant drawer
</Typography>
</Toolbar>
</AppBar>
<Drawer
variant="permanent"
className={clsx(classes.drawer, {
[classes.drawerOpen]: open,
[classes.drawerClose]: !open,
})}
classes={{
paper: clsx({
[classes.drawerOpen]: open,
[classes.drawerClose]: !open,
}),
}}
>
<div className={classes.toolbar}>
<IconButton onClick={handleDrawerClose}>
{theme.direction === "rtl" ? (
<ChevronRightIcon />
) : (
<ChevronLeftIcon />
)}
</IconButton>
</div>
<Divider />
<List>
<Link name="create-article">
<ListItem button>
<ListItemIcon>
<AddCircle />
</ListItemIcon>
<ListItemText primary="New Article" />
</ListItem>
</Link>
<Link name="articles">
<ListItem button>
<ListItemIcon>
<Description />
</ListItemIcon>
<ListItemText primary="Articles" />
</ListItem>
</Link>
<Link name="tags">
<ListItem button>
<ListItemIcon>
<LocalOffer />
</ListItemIcon>
<ListItemText primary="Tags" />
</ListItem>
</Link>
</List>
<Divider />
</Drawer>
<main className={classes.content}>
<div className={classes.toolbar} />
{ children }
</main>
</div>
<Box sx={{ display: "flex" }}>
<CssBaseline />
<StyledAppBar position="fixed" open={open}>
<Toolbar>
<IconButton
color="inherit"
aria-label="open drawer"
onClick={handleDrawerOpen}
edge="start"
sx={{
marginRight: "36px",
...(open && { display: "none" }),
}}
size="large"
>
<MenuIcon />
</IconButton>
<Typography variant="h6" noWrap>
Mini variant drawer
</Typography>
</Toolbar>
</StyledAppBar>
<StyledDrawer variant="permanent" open={open}>
<DrawerHeader>
<IconButton onClick={handleDrawerClose} size="large">
{theme.direction === "rtl" ? (
<ChevronRightIcon />
) : (
<ChevronLeftIcon />
)}
</IconButton>
</DrawerHeader>
<Divider />
<List>
<Link to="/articles/create">
<ListItem button>
<ListItemIcon>
<AddCircle />
</ListItemIcon>
<ListItemText primary="New Article" />
</ListItem>
</Link>
<Link to="/articles">
<ListItem button>
<ListItemIcon>
<Description />
</ListItemIcon>
<ListItemText primary="Articles" />
</ListItem>
</Link>
<Link to="/tags">
<ListItem button>
<ListItemIcon>
<LocalOffer />
</ListItemIcon>
<ListItemText primary="Tags" />
</ListItem>
</Link>
</List>
<Divider />
</StyledDrawer>
<Main>
<Suspense fallback={"Loading"}>{children}</Suspense>
</Main>
</Box>
);
}
};

View File

@ -1,69 +1,113 @@
import { ApolloClient } from "@apollo/client";
import { prepareRoutes } from "@curi/router";
import { omit } from 'ramda';
import { useApolloClient } from "@apollo/client";
import * as R from "ramda";
import { FC, lazy, useMemo } from "react";
import {
Navigate,
useParams,
useRoutes,
useSearchParams,
} from "react-router-dom";
import { ARTICLE } from "./articles";
import { Article } from './generated/graphql';
import { Article } from "./generated/graphql";
import { DefaultLayout } from "./layouts";
export default prepareRoutes([
{
name: "dashboard",
path: "",
respond() {
return { body: () => <div>DashBoard</div> };
const CreateArticle = () => {
const ArticleEditor = lazy(() =>
import(
/* webpackChunkName: "article-editor" */ "./articles/article-editor"
).then((m) => ({
default: m.ArticleEditor,
}))
);
const [search] = useSearchParams();
if (!search.has("key")) {
search.set("key", new Date().toISOString());
return <Navigate to={`/articles/create?${search}`} replace />;
}
return <ArticleEditor draftKey={search.get("key")!} />;
};
const ModifyArticle: FC = () => {
const { id } = useParams();
const client = useApolloClient();
const Lazy = useMemo(
() =>
lazy(async () => {
const [{ ArticleEditor }, article] = await Promise.all([
import(
/* webpackChunkName: "article-editor" */ "./articles/article-editor"
),
client
.query<{ article: Article }, { id: string }>({
query: ARTICLE,
variables: { id: id! },
})
.then(({ data }) => {
return R.omit(["__typename"], data.article);
}),
]);
return {
default: () => (
<ArticleEditor article={article} draftKey={article.key!} />
),
};
}),
[id, client]
);
return <Lazy />;
};
const ArticleIndex = lazy(() =>
import(/* webpackChunkName: "articles" */ "./articles").then((m) => ({
default: m.ArticleIndex,
}))
);
const TagIndex = lazy(() =>
import(/* webpackChunkName: "tags" */ "./tags").then((m) => ({
default: m.TagsIndex,
}))
);
export const AppRoutes: FC = () => {
const element = useRoutes([
{
index: true,
element: <div>DashBoard</div>,
},
},
{
name: "create-article",
path: "articles/create",
resolve() {
const body = import(
/* webpackChunkName: "article-editor" */ "./articles"
).then((m) => m.ArticleEditor);
return body;
{
path: "/articles/create",
element: (
<DefaultLayout>
<CreateArticle />
</DefaultLayout>
),
},
respond({ resolved }) {
return { body: resolved };
{
path: "/articles/:id",
element: (
<DefaultLayout>
<ModifyArticle />
</DefaultLayout>
),
},
},
{
name: "modify-article",
path: "articles/:id",
async resolve(matched, { client }: { client: ApolloClient<any> }) {
const [ArticleEditor, result] = await Promise.all([
import(/* webpackChunkName: "article-editor" */ "./articles").then(
(m) => m.ArticleEditor
),
client.query<{article: Article}, { id: string }>({
query: ARTICLE,
variables: { id: matched!.params.id },
}),
]);
console.log(ArticleEditor, result);
return () => (
<ArticleEditor article={omit(["__typename"], result.data.article)} />
);
{
path: "articles",
element: (
<DefaultLayout>
<ArticleIndex />
</DefaultLayout>
),
},
respond({ resolved }) {
return { body: resolved };
{
path: "tags",
element: (
<DefaultLayout>
<TagIndex />
</DefaultLayout>
),
},
},
{
name: "articles",
path: "articles",
resolve() {
return import(/* webpackChunkName: "articles" */ "./articles").then(
(m) => m.ArticleIndex
);
},
respond({ resolved }) {
return { body: resolved };
},
},
{
name: "tags",
path: "tags",
respond() {
return { body: () => <div>Tags</div> };
},
},
]);
]);
return element;
};

2
src/tags/index.ts Normal file
View File

@ -0,0 +1,2 @@
export * from "./tags-index";
export * from "./tags.constants";

75
src/tags/tags-index.tsx Normal file
View File

@ -0,0 +1,75 @@
import { useMutation, useQuery } from "@apollo/client";
import {
IconButton,
Paper,
Table,
TableBody,
TableCell,
TableContainer,
TableHead,
TableRow,
} from "@mui/material";
import { FC } from "react";
import { Tag } from "../generated/graphql";
import EditIcon from "@mui/icons-material/Edit";
import { Delete } from "@mui/icons-material";
import { REMOVE_TAG, TAGS } from "./tags.constants";
import { useNavigate } from "react-router-dom";
export const TagsIndex: FC = () => {
const { data } = useQuery<{
tags: Tag[];
}>(TAGS, {});
const [removeArticle] = useMutation<any, { id: string }>(REMOVE_TAG);
const navigate = useNavigate();
return (
<section>
<TableContainer component={Paper}>
<Table aria-label="articles table">
<TableHead>
<TableRow>
<TableCell>Tag Name</TableCell>
<TableCell>Views</TableCell>
<TableCell>Articles</TableCell>
<TableCell>Actions</TableCell>
</TableRow>
</TableHead>
<TableBody>
{data?.tags.map((tag) => (
<TableRow key={tag.id}>
<TableCell component="th" scope="row">
{tag.name}
</TableCell>
<TableCell align="right"> -- </TableCell>
<TableCell align="right"> -- </TableCell>
<TableCell>
<IconButton
aria-label="edit"
onClick={() => navigate(`/tags/${tag.id}/modify`)}
size="large"
>
<EditIcon />
</IconButton>
<IconButton
aria-label="delete"
onClick={() =>
removeArticle({
variables: tag,
})
}
size="large"
>
<Delete />
</IconButton>
</TableCell>
</TableRow>
))}
</TableBody>
</Table>
</TableContainer>
</section>
);
};

View File

@ -0,0 +1,16 @@
import { gql } from "@apollo/client";
export const TAGS = gql`
query Tags {
tags {
id
name
}
}
`;
export const REMOVE_TAG = gql`
mutation RemoveTag($id: ID!) {
removeTag(id: $id)
}
`;

22
src/utils/deep-omit.ts Normal file
View File

@ -0,0 +1,22 @@
import { fromPairs, map, omit, pipe, toPairs, type } from "ramda";
export const deepOmit = <T = any, K = any>(
names: readonly string[],
value: K
): T => {
switch (type(value)) {
case "Array":
return (value as unknown as Array<any>).map((item: any) =>
deepOmit(names, item)
) as unknown as T;
case "Object":
return pipe(
omit(names),
toPairs,
map(([key, val]) => [key, deepOmit(names, val)] as any),
fromPairs
)(value) as unknown as T;
default:
return value as unknown as T;
}
};