11 Commits

Author SHA1 Message Date
1eb8099d03 feat: 文章保存到草稿。 2021-11-23 22:23:10 +08:00
cf24177017 feat: 为富文本编辑器表单项添加加载动画。 2021-10-31 18:54:08 +08:00
3a6822bcec build: 服务发现。 2021-10-31 15:08:34 +08:00
c5ca8819e7 feat: tags list. 2021-07-24 10:33:32 +08:00
9490d874a9 feat: 添加登录支持。 2021-07-17 17:31:44 +08:00
7d04d53d02 build: use pm2 serve for prod. 2021-05-03 12:03:18 +08:00
e21e6fc3e2 build(dep): remove @types/date-fns. 2021-05-03 10:35:30 +08:00
9334a45e55 build: pm2 ecosystem config. 2021-05-03 10:21:42 +08:00
d29eeaae90 build: fix vscode launch.json. 2021-05-02 22:14:16 +08:00
4a533748f3 build: 复原 graphql 配置,修改开发 port. 2021-05-01 17:45:31 +08:00
183564aed8 feat: Article 模块 2021-05-01 15:13:38 +08:00
30 changed files with 28329 additions and 15243 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);
},
},
};
};

14
.vscode/launch.json vendored
View File

@ -5,19 +5,13 @@
"version": "0.2.0", "version": "0.2.0",
"configurations": [ "configurations": [
{ {
"name": "chrome",
"type": "chrome", "type": "chrome",
"request": "launch", "request": "launch",
"name": "Launch Chrome against blog.localhost",
"url": "http://localhost:8090/",
"webRoot": "${workspaceFolder}"
},
{
"name": "Launch blog.localhost",
"type": "firefox",
"request": "launch",
"reAttach": true, "reAttach": true,
"url": "http://blog.localhost/", "url": "http://admin.blog.localhost:7070/",
"webRoot": "${workspaceFolder}" "webRoot": "${workspaceFolder}",
"userDataDir": "/Users/ivan/Projects/.chrome"
} }
] ]
} }

View File

@ -3,6 +3,7 @@
"Formik", "Formik",
"clsx", "clsx",
"fontsource", "fontsource",
"notistack",
"vditor" "vditor"
] ]
} }

View File

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

View File

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

19
ecosystem.config.js Normal file
View File

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

41502
package-lock.json generated

File diff suppressed because it is too large Load Diff

View File

@ -4,13 +4,17 @@
"private": true, "private": true,
"dependencies": { "dependencies": {
"@apollo/client": "^3.3.15", "@apollo/client": "^3.3.15",
"@craco/craco": "^6.4.0",
"@curi/react-dom": "^2.0.4", "@curi/react-dom": "^2.0.4",
"@curi/router": "^2.1.2", "@curi/router": "^2.1.2",
"@date-io/date-fns": "^1.3.13", "@date-io/date-fns": "^1.3.13",
"@fennec/configuration": "^0.0.1",
"@hickory/browser": "^2.1.0", "@hickory/browser": "^2.1.0",
"@material-ui/core": "^4.11.3", "@material-ui/core": "^4.11.3",
"@material-ui/icons": "^4.11.2", "@material-ui/icons": "^4.11.2",
"@material-ui/lab": "*",
"@material-ui/pickers": "^3.3.10", "@material-ui/pickers": "^3.3.10",
"@nestjs-lib/auth": "^0.1.1",
"@testing-library/jest-dom": "^5.11.10", "@testing-library/jest-dom": "^5.11.10",
"@testing-library/react": "^11.2.6", "@testing-library/react": "^11.2.6",
"@testing-library/user-event": "^12.8.3", "@testing-library/user-event": "^12.8.3",
@ -18,25 +22,35 @@
"@types/node": "^12.20.10", "@types/node": "^12.20.10",
"@types/react": "^17.0.3", "@types/react": "^17.0.3",
"@types/react-dom": "^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", "fontsource-roboto": "^4.0.0",
"formik": "^2.2.6", "formik": "^2.2.6",
"formik-material-ui": "^3.0.1", "formik-material-ui": "^3.0.1",
"formik-material-ui-pickers": "^0.0.12", "formik-material-ui-pickers": "^0.0.12",
"graphql": "^15.5.0", "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": "^17.0.2",
"react-dom": "^17.0.2", "react-dom": "^17.0.2",
"react-scripts": "4.0.3", "react-scripts": "4.0.3",
"subscriptions-transport-ws": "^0.9.19",
"typescript": "^4.2.4", "typescript": "^4.2.4",
"vditor": "^3.8.4", "vditor": "^3.8.4",
"web-vitals": "^1.1.1", "web-vitals": "^1.1.1",
"yup": "^0.32.9" "yup": "^0.32.9"
}, },
"scripts": { "scripts": {
"start": "PORT=7133 BROWSER=none react-scripts start", "start": "craco start",
"build": "react-scripts build", "build": "craco build",
"test": "react-scripts test", "test": "craco test",
"eject": "react-scripts eject", "prestart": "npm run graphql",
"graphql": "graphql-codegen --config codegen.yml" "graphql": "graphql-codegen --config codegen.yml"
}, },
"eslintConfig": { "eslintConfig": {
@ -63,9 +77,8 @@
"@graphql-codegen/typescript": "1.21.1", "@graphql-codegen/typescript": "1.21.1",
"@graphql-codegen/typescript-operations": "1.17.15", "@graphql-codegen/typescript-operations": "1.17.15",
"@graphql-codegen/typescript-react-apollo": "2.2.3", "@graphql-codegen/typescript-react-apollo": "2.2.3",
"@types/date-fns": "^2.6.0",
"@types/graphql": "^14.5.0", "@types/graphql": "^14.5.0",
"@types/react-router-dom": "^5.1.7", "@types/ramda": "^0.27.40",
"@types/sass": "^1.16.0", "@types/sass": "^1.16.0",
"@types/yup": "^0.29.11", "@types/yup": "^0.29.11",
"sass": "^1.32.11" "sass": "^1.32.11"

View File

@ -1,9 +0,0 @@
import React from 'react';
import { render, screen } from '@testing-library/react';
import App from './App';
test('renders learn react link', () => {
render(<App />);
const linkElement = screen.getByText(/learn react/i);
expect(linkElement).toBeInTheDocument();
});

View File

@ -5,24 +5,43 @@ import {
makeStyles, makeStyles,
Paper, Paper,
} from "@material-ui/core"; } from "@material-ui/core";
import { Field, Form, Formik, FormikHelpers } from "formik"; import { Field, Form, Formik, FormikHelpers, FormikProps } from "formik";
import { FC } from "react"; import { FC, useCallback, useMemo, useRef, useState } from "react";
import { Editor } from "../commons/editor/vditor"; import { Editor } from "../commons/editor/vditor";
import * as Yup from "yup"; import * as Yup from "yup";
import { import {
Article,
CreateArticleInput, CreateArticleInput,
CreateDraftArticleInput,
DraftArticle,
UpdateArticleInput, UpdateArticleInput,
} from "../generated/graphql"; } from "../generated/graphql";
import { DateTimePicker } from 'formik-material-ui-pickers'; import { DateTimePicker } from "formik-material-ui-pickers";
import { gql, useMutation } from '@apollo/client'; import { gql, useMutation } from "@apollo/client";
import { useRouter } from "@curi/react-universal";
import * as R from "ramda";
const CREATE_ARTICLE = gql` const CREATE_ARTICLE = gql`
mutation createArticle($input: CreateArticleInput!) { mutation createArticle($createArticleInput: CreateArticleInput!) {
createArticle(input: $input) { createArticle(createArticleInput: $createArticleInput) {
id, id
title
content
publishedAt
} }
} }
` `;
const UPDATE_ARTICLE = gql`
mutation updateArticle($updateArticleInput: UpdateArticleInput!) {
updateArticle(updateArticleInput: $updateArticleInput) {
id
title
content
publishedAt
}
}
`;
const useStyles = makeStyles((theme) => const useStyles = makeStyles((theme) =>
createStyles({ createStyles({
@ -35,54 +54,175 @@ 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" | "key">>;
interface Props { interface Props {
article?: Values; article?: Values;
} }
export const ArticleEditor: FC<Props> = ({ article }) => { export const ArticleEditor: FC<Props> = ({ article }) => {
const classes = useStyles(); const classes = useStyles();
const router = useRouter();
const formik = useRef<FormikProps<Values>>(null);
const validationSchema = Yup.object({ const validationSchema = Yup.object({
content: Yup.string() content: Yup.string()
.max(65535, "文章内容不得超过 65535 个字符") .max(65535, "文章内容不得超过 65535 个字符")
.required("文章内容不得为空"), .required("文章内容不得为空"),
publishedAt: Yup.date() publishedAt: Yup.date(),
}); });
const [createArticle] = useMutation(CREATE_ARTICLE); const [createArticle] = useMutation<
{ createArticle: Article },
{
createArticleInput: CreateArticleInput;
}
>(CREATE_ARTICLE, {
update(cache, { data }) {
cache.modify({
fields: {
articles(existingArticles = []) {
const newArticleRef = cache.writeFragment({
data: data!.createArticle,
fragment: gql`
fragment NewArticle on Article {
id
title
content
publishedAt
}
`,
});
return [newArticleRef, ...existingArticles];
},
},
});
},
});
const [updateArticle] = useMutation<{
updateArticleInput: UpdateArticleInput;
}>(UPDATE_ARTICLE);
const SubmitForm = ( const [putDraft] = useMutation<
{
draft: DraftArticle;
},
{
draft: CreateDraftArticleInput;
}
>(gql`
mutation ($draft: CreateDraftArticleInput!) {
draft: putDraftForArticle(draft: $draft) {
id
createdAt
}
}
`);
const tempKey = useMemo(() => {
if (article?.key) {
return article.key;
} else {
return new Date().valueOf().toString();
}
}, [article]);
const submitForm = async (
values: Values, values: Values,
{ setSubmitting }: FormikHelpers<Values> { setSubmitting }: FormikHelpers<Values>
) => { ) => {
if ('id' in article!) { if ("id" in article!) {
console.log('update', article) const title = /# (.+)$/m.exec(values.content ?? "")?.[1];
} else {
const title = /# (.+)$/.exec(values.content ?? '')?.[1];
if (!title) { if (!title) {
console.log('no title') console.log("no title");
setSubmitting(false); setSubmitting(false);
return; return;
} }
createArticle({ await updateArticle({
variables: { variables: {
updateArticleInput: {
...values, ...values,
title, title,
}, },
}).finally(() => { },
})
.then(() => {
router.navigate({
url: router.url({ name: "articles" }),
method: "replace",
});
})
.finally(() => {
setSubmitting(false);
});
} else {
const title = /# (.+)$/m.exec(values.content ?? "")?.[1];
if (!title) {
console.log("no title");
setSubmitting(false);
return;
}
await createArticle({
variables: {
createArticleInput: {
...(values as CreateArticleInput),
title,
},
},
})
.then(() => {
router.navigate({
url: router.url({ name: "articles" }),
method: "replace",
});
})
.finally(() => {
setSubmitting(false); setSubmitting(false);
}); });
} }
setSubmitting(false); setSubmitting(false);
}; };
const [drafts, setDrafts] = useState<DraftArticle[]>([]);
const handleSave = useCallback(
async (automatically = true) => {
const { data } = await putDraft({
variables: {
draft: {
key: tempKey,
payload: formik.current?.values,
automatically,
},
},
});
if (!data?.draft) {
return;
}
setDrafts((drafts) => {
const index = drafts.findIndex((it) => it.id === data.draft.id);
if (index === -1) {
return [data.draft, ...drafts];
} else {
const arr = [...drafts];
arr[index] = data.draft;
return arr;
}
});
},
[tempKey, putDraft, formik, drafts]
);
return ( return (
<Paper> <Paper>
<Formik <Formik
initialValues={article!} initialValues={{
...R.pick(fields, article!),
}}
innerRef={formik}
validationSchema={validationSchema} validationSchema={validationSchema}
autoComplete="off" autoComplete="off"
onSubmit={SubmitForm} onSubmit={submitForm}
> >
{({ submitForm, isSubmitting }) => ( {({ submitForm, isSubmitting }) => (
<Form className={classes.form}> <Form className={classes.form}>
@ -108,9 +248,18 @@ export const ArticleEditor: FC<Props> = ({ article }) => {
variant="contained" variant="contained"
color="primary" color="primary"
disabled={isSubmitting} disabled={isSubmitting}
onClick={() => handleSave(false)}
>
Save
</Button>
<Button
style={{ marginLeft: "10px" }}
variant="contained"
color="secondary"
disabled={isSubmitting}
onClick={submitForm} onClick={submitForm}
> >
Submit Publish
</Button> </Button>
</Grid> </Grid>
</Grid> </Grid>
@ -127,5 +276,5 @@ ArticleEditor.defaultProps = {
content: "", content: "",
publishedAt: new Date(), publishedAt: new Date(),
tags: [], tags: [],
} as CreateArticleInput, } as Values,
}; };

View File

@ -0,0 +1,89 @@
import { useMutation, useQuery } from "@apollo/client";
import {
IconButton,
Paper,
Table,
TableBody,
TableCell,
TableContainer,
TableHead,
TableRow,
} from "@material-ui/core";
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 { format } from "date-fns";
export const ArticleIndex: FC = () => {
const { data } = useQuery<{
articles: Article[];
}>(ARTICLES, {});
const [removeArticle] = useMutation<any, { id: string }>(REMOVE_ARTICLE);
const router = useRouter();
return (
<section>
<TableContainer component={Paper}>
<Table aria-label="articles table">
<TableHead>
<TableRow>
<TableCell>Article Title</TableCell>
<TableCell>Published At</TableCell>
<TableCell>Views</TableCell>
<TableCell>Comments</TableCell>
<TableCell>Status</TableCell>
<TableCell>Actions</TableCell>
</TableRow>
</TableHead>
<TableBody>
{data?.articles.map((article) => (
<TableRow key={article.id}>
<TableCell component="th" scope="row">
{article.title}
</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,
}),
})
}
>
<EditIcon />
</IconButton>
<IconButton
aria-label="delete"
onClick={() =>
removeArticle({
variables: article,
})
}
>
<Delete />
</IconButton>
</TableCell>
</TableRow>
))}
</TableBody>
</Table>
</TableContainer>
</section>
);
};

View File

@ -0,0 +1,26 @@
import { gql } from "@apollo/client";
export const ARTICLE = gql`
query Article($id: String!) {
article(id: $id) {
id
title
content
publishedAt
}
}
`;
export const ARTICLES = gql`
query Articles {
articles {
id
title
publishedAt
}
}
`;
export const REMOVE_ARTICLE = gql`
mutation RemoveArticle($id: String!) {
removeArticle(id: $id)
}
`;

3
src/articles/index.ts Normal file
View File

@ -0,0 +1,3 @@
export * from './article-editor';
export * from './articles-index';
export * from './articles.constants'

View File

@ -1,56 +0,0 @@
import { gql, useQuery } from "@apollo/client";
import {
Paper,
Table,
TableBody,
TableCell,
TableContainer,
TableHead,
TableRow,
} from "@material-ui/core";
import React, { FC } from "react";
import { Article } from '../generated/graphql';
const articles = gql`
query Articles {
articles {
id
title
publishedAt
}
}`;
export const ArticleIndex: FC = () => {
const { data } = useQuery<{
articles: Article[];
}>(articles, {});
return (
<section>
<TableContainer component={Paper}>
<Table aria-label="articles table">
<TableHead>
<TableRow>
<TableCell>Article Title</TableCell>
<TableCell>Published At</TableCell>
<TableCell>Views</TableCell>
<TableCell>Comments</TableCell>
</TableRow>
</TableHead>
<TableBody>
{data?.articles.map((article) => (
<TableRow key={article.id}>
<TableCell component="th" scope="row">
{article.title}
</TableCell>
<TableCell align="right">{article.publishedAt}</TableCell>
<TableCell align="right"> -- </TableCell>
<TableCell align="right"> -- </TableCell>
</TableRow>
))}
</TableBody>
</Table>
</TableContainer>
</section>
);
};

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 "@material-ui/core";
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,19 +1,31 @@
import { FormControl, FormHelperText, FormLabel } from '@material-ui/core'; import { createStyles, FormControl, FormHelperText, FormLabel, makeStyles } from '@material-ui/core';
import { FieldHookConfig, useField } from 'formik'; import { Skeleton } from "@material-ui/lab";
import React, { FC, useEffect, useRef, useState } from 'react'; import { FieldHookConfig, useField } from "formik";
import Vditor from 'vditor'; import React, { FC, useEffect, useMemo, useRef, useState } from "react";
import 'vditor/src/assets/scss/index.scss'; import Vditor from "vditor";
import "vditor/src/assets/scss/index.scss";
type Props = (FieldHookConfig<string>) & { type Props = FieldHookConfig<string> & {
label?: string; label?: string;
className?: string; className?: string;
}; };
const useStyles = makeStyles((theme) =>
createStyles({
formControl: {
width: "100%",
},
})
);
export const Editor: FC<Props> = ({ label, className, ...props }) => { 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 editor = useRef<HTMLDivElement>(null);
const [instance, setInstance] = useState<Vditor | null>(() => 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(() => { useEffect(() => {
if (!editor.current) { if (!editor.current) {
return; return;
@ -25,19 +37,39 @@ export const Editor: FC<Props> = ({ label, className, ...props }) => {
fullscreen: { fullscreen: {
index: 1500, index: 1500,
}, },
value: meta.initialValue,
input: (val) => helpers.setValue(val), input: (val) => helpers.setValue(val),
blur: () => helpers.setTouched(true), blur: () => helpers.setTouched(true),
}); after: () => {
setInstance(_instance); setInstance(_instance);
},
});
return () => { return () => {
instance?.destroy(); _instance?.destroy();
}; };
}, []); // eslint-disable-next-line react-hooks/exhaustive-deps
}, [containerKey]);
const classes = useStyles();
return ( return (
<FormControl> <FormControl className={classes.formControl}>
<FormLabel>{label}</FormLabel> <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>} {meta.error && <FormHelperText error={true}>{meta.error}</FormHelperText>}
{instance ? null : (
<Skeleton
variant="rect"
animation="wave"
height="100%"
width="100%"
style={{ position: "absolute" }}
/>
)}
</FormControl> </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

@ -0,0 +1,20 @@
import { ActiveHookProps, Link, LinkProps, useActive } from '@curi/react-dom';
import React, { FC, ReactNode } from 'react';
export type ActiveLinkProps = ActiveHookProps &
LinkProps & {
className?: string;
children: ReactNode;
};
export const ActiveLink:FC<ActiveLinkProps> = ({ name, params, partial, className = "", ...rest }) => {
const active = useActive({ name, params, partial });
return (
<Link
name={name}
params={params}
{...rest}
className={active ? `${className} active` : className}
/>
);
};

View File

@ -0,0 +1,31 @@
import { useApolloClient } from "@apollo/client";
import { createRouterComponent } from "@curi/react-dom";
import { createRouter, announce } from "@curi/router";
import { browser } from "@hickory/browser";
import { FC, useEffect, useState } from "react";
import routes from "../../routes";
import { LinearProgress } from "@material-ui/core";
const Component: FC = ({ children }) => {
const client = useApolloClient();
const [body, setBody] = useState<any>(null);
useEffect(() => {
const router = createRouter(browser, routes, {
sideEffects: [
announce(({ response }) => {
return `Navigated to ${response.location.pathname}`;
}),
],
external: { client },
});
const Router = createRouterComponent(router);
router.once(() => {
setBody(<Router>{children}</Router>);
});
}, [setBody, client, children]);
return body ?? <LinearProgress />;
};
export default Component;

View File

@ -96,6 +96,46 @@
}, },
"isDeprecated": false, "isDeprecated": false,
"deprecationReason": null "deprecationReason": null
},
{
"name": "key",
"description": null,
"args": [],
"type": {
"kind": "SCALAR",
"name": "String",
"ofType": null
},
"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
} }
], ],
"inputFields": null, "inputFields": null,
@ -202,6 +242,98 @@
"enumValues": null, "enumValues": null,
"possibleTypes": null "possibleTypes": null
}, },
{
"kind": "INPUT_OBJECT",
"name": "CreateDraftArticleInput",
"description": null,
"fields": null,
"inputFields": [
{
"name": "payload",
"description": null,
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "SCALAR",
"name": "Object",
"ofType": null
}
},
"defaultValue": null,
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "key",
"description": null,
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "SCALAR",
"name": "String",
"ofType": null
}
},
"defaultValue": null,
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "automatically",
"description": null,
"type": {
"kind": "SCALAR",
"name": "Boolean",
"ofType": null
},
"defaultValue": "true",
"isDeprecated": false,
"deprecationReason": null
}
],
"interfaces": null,
"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": "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", "kind": "SCALAR",
"name": "DateTime", "name": "DateTime",
@ -212,6 +344,81 @@
"enumValues": null, "enumValues": null,
"possibleTypes": null "possibleTypes": null
}, },
{
"kind": "OBJECT",
"name": "DraftArticle",
"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": "payload",
"description": null,
"args": [],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "SCALAR",
"name": "Object",
"ofType": null
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "key",
"description": null,
"args": [],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "SCALAR",
"name": "String",
"ofType": null
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "automatically",
"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": "OBJECT", "kind": "OBJECT",
"name": "Hello", "name": "Hello",
@ -331,12 +538,218 @@
"deprecationReason": null "deprecationReason": null
} }
], ],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "SCALAR",
"name": "Int",
"ofType": null
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "putDraftForArticle",
"description": null,
"args": [
{
"name": "draft",
"description": null,
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "INPUT_OBJECT",
"name": "CreateDraftArticleInput",
"ofType": null
}
},
"defaultValue": null,
"isDeprecated": false,
"deprecationReason": null
}
],
"type": { "type": {
"kind": "NON_NULL", "kind": "NON_NULL",
"name": null, "name": null,
"ofType": { "ofType": {
"kind": "OBJECT", "kind": "OBJECT",
"name": "Article", "name": "DraftArticle",
"ofType": null
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "listDraftForArticle",
"description": null,
"args": [
{
"name": "key",
"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": "LIST",
"name": null,
"ofType": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "OBJECT",
"name": "DraftArticle",
"ofType": null
}
}
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "lastDraftForArticle",
"description": null,
"args": [
{
"name": "key",
"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": "DraftArticle",
"ofType": null
}
},
"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 "ofType": null
} }
}, },
@ -349,6 +762,26 @@
"enumValues": null, "enumValues": null,
"possibleTypes": null "possibleTypes": null
}, },
{
"kind": "SCALAR",
"name": "Int",
"description": "The `Int` scalar type represents non-fractional signed whole numeric values. Int can represent values between -(2^31) and 2^31 - 1.",
"fields": null,
"inputFields": null,
"interfaces": null,
"enumValues": null,
"possibleTypes": null
},
{
"kind": "SCALAR",
"name": "Object",
"description": "The `JSON` scalar type represents JSON values 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", "kind": "OBJECT",
"name": "Query", "name": "Query",
@ -426,6 +859,106 @@
}, },
"isDeprecated": false, "isDeprecated": false,
"deprecationReason": null "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, "inputFields": null,
@ -503,7 +1036,7 @@
"name": null, "name": null,
"ofType": { "ofType": {
"kind": "SCALAR", "kind": "SCALAR",
"name": "Int", "name": "String",
"ofType": null "ofType": null
} }
}, },
@ -517,21 +1050,40 @@
"possibleTypes": null "possibleTypes": null
}, },
{ {
"kind": "SCALAR", "kind": "INPUT_OBJECT",
"name": "Int", "name": "UpdateTagInput",
"description": "The `Int` scalar type represents non-fractional signed whole numeric values. Int can represent values between -(2^31) and 2^31 - 1.", "description": null,
"fields": null, "fields": null,
"inputFields": null, "inputFields": [
"interfaces": null, {
"enumValues": null, "name": "name",
"possibleTypes": null "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", "kind": "SCALAR",
"name": "Boolean", "name": "String",
"description": "The `Boolean` scalar type represents `true` or `false`.", "ofType": null
"fields": null, }
"inputFields": null, },
"defaultValue": null,
"isDeprecated": false,
"deprecationReason": null
}
],
"interfaces": null, "interfaces": null,
"enumValues": null, "enumValues": null,
"possibleTypes": null "possibleTypes": null
@ -1278,7 +1830,20 @@
{ {
"name": "args", "name": "args",
"description": null, "description": null,
"args": [], "args": [
{
"name": "includeDeprecated",
"description": null,
"type": {
"kind": "SCALAR",
"name": "Boolean",
"ofType": null
},
"defaultValue": "false",
"isDeprecated": false,
"deprecationReason": null
}
],
"type": { "type": {
"kind": "NON_NULL", "kind": "NON_NULL",
"name": null, "name": null,

View File

@ -12,6 +12,8 @@ export type Scalars = {
Float: number; Float: number;
/** A date-time string at UTC, such as 2019-12-03T09:54:33Z, compliant with the date-time format. */ /** A date-time string at UTC, such as 2019-12-03T09:54:33Z, compliant with the date-time format. */
DateTime: any; DateTime: any;
/** The `JSON` scalar type represents JSON values as specified by [ECMA-404](http://www.ecma-international.org/publications/files/ECMA-ST/ECMA-404.pdf). */
Object: any;
}; };
export type Article = { export type Article = {
@ -21,6 +23,9 @@ export type Article = {
content: Scalars['String']; content: Scalars['String'];
publishedAt?: Maybe<Scalars['DateTime']>; publishedAt?: Maybe<Scalars['DateTime']>;
tags: Array<Scalars['String']>; tags: Array<Scalars['String']>;
key?: Maybe<Scalars['String']>;
html: Scalars['String'];
description?: Maybe<Scalars['String']>;
}; };
export type CreateArticleInput = { export type CreateArticleInput = {
@ -30,6 +35,24 @@ export type CreateArticleInput = {
tags: Array<Scalars['String']>; tags: Array<Scalars['String']>;
}; };
export type CreateDraftArticleInput = {
payload: Scalars['Object'];
key: Scalars['String'];
automatically?: Maybe<Scalars['Boolean']>;
};
export type CreateTagInput = {
name: Scalars['String'];
};
export type DraftArticle = {
__typename?: 'DraftArticle';
id: Scalars['ID'];
payload: Scalars['Object'];
key: Scalars['String'];
automatically: Scalars['Boolean'];
};
export type Hello = { export type Hello = {
__typename?: 'Hello'; __typename?: 'Hello';
@ -40,7 +63,13 @@ export type Mutation = {
__typename?: 'Mutation'; __typename?: 'Mutation';
createArticle: Article; createArticle: Article;
updateArticle: Article; updateArticle: Article;
removeArticle: Article; removeArticle: Scalars['Int'];
putDraftForArticle: DraftArticle;
listDraftForArticle: Array<DraftArticle>;
lastDraftForArticle: DraftArticle;
createTag: Tag;
updateTag: Tag;
removeTag: Tag;
}; };
@ -58,11 +87,44 @@ export type MutationRemoveArticleArgs = {
id: Scalars['String']; id: Scalars['String'];
}; };
export type MutationPutDraftForArticleArgs = {
draft: CreateDraftArticleInput;
};
export type MutationListDraftForArticleArgs = {
key: Scalars['String'];
};
export type MutationLastDraftForArticleArgs = {
key: Scalars['String'];
};
export type MutationCreateTagArgs = {
createTagInput: CreateTagInput;
};
export type MutationUpdateTagArgs = {
updateTagInput: UpdateTagInput;
};
export type MutationRemoveTagArgs = {
id: Scalars['String'];
};
export type Query = { export type Query = {
__typename?: 'Query'; __typename?: 'Query';
hello: Hello; hello: Hello;
articles: Array<Article>; articles: Array<Article>;
article: Article; article: Article;
tags: Array<Tag>;
tag: Tag;
}; };
@ -70,10 +132,26 @@ export type QueryArticleArgs = {
id: Scalars['String']; id: Scalars['String'];
}; };
export type QueryTagArgs = {
id: Scalars['String'];
};
export type Tag = {
__typename?: 'Tag';
id: Scalars['ID'];
name: Scalars['String'];
};
export type UpdateArticleInput = { export type UpdateArticleInput = {
title?: Maybe<Scalars['String']>; title?: Maybe<Scalars['String']>;
content?: Maybe<Scalars['String']>; content?: Maybe<Scalars['String']>;
publishedAt?: Maybe<Scalars['DateTime']>; publishedAt?: Maybe<Scalars['DateTime']>;
tags?: Maybe<Array<Scalars['String']>>; tags?: Maybe<Array<Scalars['String']>>;
id: Scalars['Int']; id: Scalars['String'];
};
export type UpdateTagInput = {
name?: Maybe<Scalars['String']>;
id: Scalars['String'];
}; };

View File

@ -1,42 +1,33 @@
import React from 'react'; import React from "react";
import ReactDOM from 'react-dom'; import ReactDOM from "react-dom";
import './index.css'; import "./index.css";
import "fontsource-roboto"; import "fontsource-roboto";
import App from './App'; import App from "./App";
import reportWebVitals from './reportWebVitals'; import reportWebVitals from "./reportWebVitals";
import { client } from './commons/graphql/client'; import { AppApolloClientProvider } from "./commons/graphql/client";
import { ApolloProvider } from '@apollo/client'; import { MuiPickersUtilsProvider } from "@material-ui/pickers";
import { MuiPickersUtilsProvider } from '@material-ui/pickers';
import DateFnsUtils from "@date-io/date-fns"; import DateFnsUtils from "@date-io/date-fns";
import zhLocale from "date-fns/locale/zh-CN"; import zhLocale from "date-fns/locale/zh-CN";
import { createRouterComponent } from '@curi/react-dom'; import { SnackbarProvider } from "notistack";
import { createRouter, announce } from '@curi/router'; import Router from "./commons/route/router";
import { browser } from '@hickory/browser'; import { AuthProvider } from "./commons/auth/auth.provider";
import routes from './routes';
const router = createRouter(browser, routes, { ReactDOM.render(
sideEffects: [
announce(({ response }) => {
return `Navigated to ${response.location.pathname}`;
})
]
});
const Router = createRouterComponent(router);
router.once(() => {
ReactDOM.render(
<React.StrictMode> <React.StrictMode>
<ApolloProvider client={client}> <SnackbarProvider maxSnack={5}>
<AuthProvider>
<AppApolloClientProvider>
<MuiPickersUtilsProvider utils={DateFnsUtils} locale={zhLocale}> <MuiPickersUtilsProvider utils={DateFnsUtils} locale={zhLocale}>
<Router> <Router>
<App /> <App />
</Router> </Router>
</MuiPickersUtilsProvider> </MuiPickersUtilsProvider>
</ApolloProvider> </AppApolloClientProvider>
</AuthProvider>
</SnackbarProvider>
</React.StrictMode>, </React.StrictMode>,
document.getElementById("root") document.getElementById("root")
); );
})
// If you want to start measuring performance in your app, pass a function // If you want to start measuring performance in your app, pass a function
// to log results (for example: reportWebVitals(console.log)) // to log results (for example: reportWebVitals(console.log))

View File

@ -1,50 +1,74 @@
import { prepareRoutes } from '@curi/router' import { ApolloClient } from "@apollo/client";
import { prepareRoutes } from "@curi/router";
import { omit } from 'ramda';
import { ARTICLE } from "./articles";
import { Article } from './generated/graphql';
export default prepareRoutes([ export default prepareRoutes([
{ {
name: 'dashboard', name: "dashboard",
path: '', path: "",
respond() { respond() {
return { body: () => (<div>DashBoard</div>) } return { body: () => <div>DashBoard</div> };
} },
}, },
{ {
name: 'create-article', name: "create-article",
path: 'articles/create', path: "articles/create",
resolve() { resolve() {
const body = import(/* webpackChunkName: "create-article" */ './articles/article-editor').then(m => m.ArticleEditor); const body = import(
/* webpackChunkName: "article-editor" */ "./articles"
).then((m) => m.ArticleEditor);
return body; return body;
}, },
respond({ resolved }) { respond({ resolved }) {
return { body: resolved } return { body: resolved };
} },
}, },
{ {
name: 'modify-article', name: "modify-article",
path: 'articles/:id', path: "articles/:id",
resolve() { async resolve(matched, { client }: { client: ApolloClient<any> }) {
return import(/* webpackChunkName: "modify-article" */ './articles/article-editor').then(m => m.ArticleEditor); 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)} />
);
}, },
respond({ resolved }) { respond({ resolved }) {
const ModifyArticle = () => resolved(); return { body: resolved };
return { body: <ModifyArticle /> } },
}
}, },
{ {
name: 'articles', name: "articles",
path: 'articles', path: "articles",
resolve() { resolve() {
return import(/* webpackChunkName: "articles" */ './articles/index').then(m => m.ArticleIndex); return import(/* webpackChunkName: "articles" */ "./articles").then(
(m) => m.ArticleIndex
);
}, },
respond({ resolved }) { respond({ resolved }) {
return { body: resolved } return { body: resolved };
} },
}, },
{ {
name: 'tags', name: "tags",
path: 'tags', path: "tags",
respond() { resolve() {
return { body: () => (<div>Tags</div>) } return import(/* webpackChunkName: "tags" */ "./tags").then(
} (m) => m.TagsIndex
);
}, },
]) respond({ resolved }) {
return { body: resolved };
},
},
]);

201
src/tags/article-editor.tsx Normal file
View File

@ -0,0 +1,201 @@
import {
Button,
createStyles,
Grid,
makeStyles,
Paper,
} from "@material-ui/core";
import { Field, Form, Formik, FormikHelpers } from "formik";
import { FC } from "react";
import { Editor } from "../commons/editor/vditor";
import * as Yup from "yup";
import { Article, CreateArticleInput, UpdateArticleInput } from "../generated/graphql";
import { DateTimePicker } from "formik-material-ui-pickers";
import { gql, useMutation } from "@apollo/client";
import { useRouter } from "@curi/react-universal";
const CREATE_ARTICLE = gql`
mutation createArticle($createArticleInput: CreateArticleInput!) {
createArticle(createArticleInput: $createArticleInput) {
id
title
content
publishedAt
}
}
`;
const UPDATE_ARTICLE = gql`
mutation updateArticle($updateArticleInput: UpdateArticleInput!) {
updateArticle(updateArticleInput: $updateArticleInput) {
id
title
content
publishedAt
}
}
`;
const useStyles = makeStyles((theme) =>
createStyles({
form: {
padding: "15px 30px",
},
editor: {
height: "700px",
},
})
);
type Values = CreateArticleInput | UpdateArticleInput;
interface Props {
article?: Values;
}
export const ArticleEditor: FC<Props> = ({ article }) => {
const classes = useStyles();
const validationSchema = Yup.object({
content: Yup.string()
.max(65535, "文章内容不得超过 65535 个字符")
.required("文章内容不得为空"),
publishedAt: Yup.date(),
});
const router = useRouter();
const [createArticle] = useMutation<{createArticle: Article} ,{
createArticleInput: CreateArticleInput;
}>(CREATE_ARTICLE, {
update(cache, { data }) {
cache.modify({
fields: {
articles(existingArticles = []) {
const newArticleRef = cache.writeFragment({
data: data!.createArticle,
fragment: gql`
fragment NewArticle on Article {
id
title
content
publishedAt
}
`,
});
return [newArticleRef, ...existingArticles];
},
},
});
},
});
const [updateArticle] = useMutation<{
updateArticleInput: UpdateArticleInput;
}>(UPDATE_ARTICLE);
const SubmitForm = (
values: Values,
{ setSubmitting }: FormikHelpers<Values>
) => {
if ("id" in article!) {
const title = /# (.+)$/m.exec(values.content ?? "")?.[1];
if (!title) {
console.log("no title");
setSubmitting(false);
return;
}
updateArticle({
variables: {
updateArticleInput: {
...values,
title,
},
},
})
.then(() => {
router.navigate({
url: router.url({ name: "articles" }),
method: "replace",
});
})
.finally(() => {
setSubmitting(false);
});
} else {
const title = /# (.+)$/m.exec(values.content ?? "")?.[1];
if (!title) {
console.log("no title");
setSubmitting(false);
return;
}
createArticle({
variables: {
createArticleInput: {
...values as CreateArticleInput,
title,
},
},
})
.then(() => {
router.navigate({
url: router.url({ name: "articles" }),
method: "replace",
});
})
.finally(() => {
setSubmitting(false);
});
}
setSubmitting(false);
};
return (
<Paper>
<Formik
initialValues={article!}
validationSchema={validationSchema}
autoComplete="off"
onSubmit={SubmitForm}
>
{({ submitForm, isSubmitting }) => (
<Form className={classes.form}>
<Grid container spacing={3}>
<Grid item xs={12}>
<Editor
className={classes.editor}
name="content"
label="Content"
/>
</Grid>
<Grid item xs={12}>
<Field
ampm={false}
component={DateTimePicker}
label="Published At"
name="publishedAt"
format="yyyy-MM-dd HH:mm:ss"
/>
</Grid>
<Grid item xs={12}>
<Button
variant="contained"
color="primary"
disabled={isSubmitting}
onClick={submitForm}
>
Submit
</Button>
</Grid>
</Grid>
</Form>
)}
</Formik>
</Paper>
);
};
ArticleEditor.defaultProps = {
article: {
title: "",
content: "",
publishedAt: new Date(),
tags: [],
} as CreateArticleInput,
};

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

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

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

@ -0,0 +1,80 @@
import { useMutation, useQuery } from "@apollo/client";
import {
IconButton,
Paper,
Table,
TableBody,
TableCell,
TableContainer,
TableHead,
TableRow,
} from "@material-ui/core";
import { FC } from "react";
import { Tag } from "../generated/graphql";
import EditIcon from "@material-ui/icons/Edit";
import { useRouter } from "@curi/react-dom";
import { Delete } from "@material-ui/icons";
import { REMOVE_TAG, TAGS } from "./tags.constants";
export const TagsIndex: FC = () => {
const { data } = useQuery<{
tags: Tag[];
}>(TAGS, {});
const [removeArticle] = useMutation<any, { id: string }>(REMOVE_TAG);
const router = useRouter();
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={() =>
router.navigate({
url: router.url({
name: "modify-tag",
params: tag,
}),
})
}
>
<EditIcon />
</IconButton>
<IconButton
aria-label="delete"
onClick={() =>
removeArticle({
variables: tag,
})
}
>
<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;
}
};