This commit is contained in:
Ivan Li 2021-04-24 14:47:22 +08:00
parent 065e1679ba
commit 2e70c31849
17 changed files with 29290 additions and 42 deletions

23
.vscode/launch.json vendored Normal file
View File

@ -0,0 +1,23 @@
{
// Use IntelliSense to learn about possible attributes.
// Hover to view descriptions of existing attributes.
// For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
"version": "0.2.0",
"configurations": [
{
"name": "Launch blog.localhost",
"type": "firefox",
"request": "launch",
"reAttach": true,
"url": "http://blog.localhost/",
"webRoot": "${workspaceFolder}"
},
{
"type": "chrome",
"request": "launch",
"name": "Launch Chrome against blog.localhost",
"url": "http://blog.localhost/",
"webRoot": "${workspaceFolder}"
}
]
}

View File

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

8
apollo.config.js Normal file
View File

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

12
codegen.yml Normal file
View File

@ -0,0 +1,12 @@
overwrite: true
schema: "http://localhost:7132/graphql"
# documents: "src/**/*.graphql"
generates:
src/generated/graphql.tsx:
plugins:
- "typescript"
- "typescript-operations"
- "typescript-react-apollo"
./graphql.schema.json:
plugins:
- "introspection"

1544
graphql.schema.json Normal file

File diff suppressed because it is too large Load Diff

27170
package-lock.json generated

File diff suppressed because it is too large Load Diff

View File

@ -4,8 +4,10 @@
"private": true, "private": true,
"dependencies": { "dependencies": {
"@apollo/client": "^3.3.15", "@apollo/client": "^3.3.15",
"@date-io/date-fns": "^1.3.13",
"@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/pickers": "^3.3.10",
"@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",
@ -13,19 +15,28 @@
"@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",
"fontsource-roboto": "^4.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": "^15.5.0",
"react": "^17.0.2", "react": "^17.0.2",
"react-dom": "^17.0.2", "react-dom": "^17.0.2",
"react-router-dom": "^5.2.0",
"react-scripts": "4.0.3", "react-scripts": "4.0.3",
"typescript": "^4.2.4", "typescript": "^4.2.4",
"web-vitals": "^1.1.1" "vditor": "^3.8.4",
"web-vitals": "^1.1.1",
"yup": "^0.32.9"
}, },
"scripts": { "scripts": {
"start": "react-scripts start", "prestart": "npm run graphql",
"start": "PORT=7133 react-scripts start",
"build": "react-scripts build", "build": "react-scripts build",
"test": "react-scripts test", "test": "react-scripts test",
"eject": "react-scripts eject" "eject": "react-scripts eject",
"graphql": "graphql-codegen --config codegen.yml"
}, },
"eslintConfig": { "eslintConfig": {
"extends": [ "extends": [
@ -46,6 +57,16 @@
] ]
}, },
"devDependencies": { "devDependencies": {
"@types/graphql": "^14.5.0" "@graphql-codegen/cli": "1.21.3",
"@graphql-codegen/introspection": "1.18.1",
"@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/react-router-dom": "^5.1.7",
"@types/sass": "^1.16.0",
"@types/yup": "^0.29.11",
"sass": "^1.32.11"
} }
} }

View File

@ -1,13 +1,9 @@
import React from 'react';
import logo from './logo.svg';
import './App.css'; import './App.css';
import { Button } from '@material-ui/core'; import { DefaultLayout } from './layouts';
function App() { function App() {
return ( return (
<Button variant="contained" color="primary"> <DefaultLayout></DefaultLayout>
</Button>
); );
} }

View File

@ -0,0 +1,131 @@
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 {
CreateArticleInput,
UpdateArticleInput,
} from "../generated/graphql";
import { DateTimePicker } from 'formik-material-ui-pickers';
import { gql, useMutation } from '@apollo/client';
const CREATE_ARTICLE = gql`
mutation createArticle($input: CreateArticleInput!) {
createArticle(input: $input) {
id,
}
}
`
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 [createArticle] = useMutation(CREATE_ARTICLE);
const SubmitForm = (
values: Values,
{ setSubmitting }: FormikHelpers<Values>
) => {
if ('id' in article!) {
console.log('update', article)
} else {
const title = /# (.+)$/.exec(values.content ?? '')?.[1];
if (!title) {
console.log('no title')
setSubmitting(false);
return;
}
createArticle({
variables: {
...values,
title,
},
}).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,
};

56
src/articles/index.tsx Normal file
View File

@ -0,0 +1,56 @@
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,43 @@
import { FormControl, FormHelperText, FormLabel } 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';
type Props = (FieldHookConfig<string>) & {
label?: string;
className?: string;
};
export const Editor: FC<Props> = ({ label, className, ...props }) => {
const [field, 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));
useEffect(() => {
if (!editor.current) {
return;
}
const _instance = new Vditor(editor.current, {
cache: {
id: containerKey,
},
fullscreen: {
index: 1500,
},
input: (val) => helpers.setValue(val),
blur: () => helpers.setTouched(true),
});
setInstance(_instance);
return () => {
instance?.destroy();
};
}, []);
return (
<FormControl>
<FormLabel>{label}</FormLabel>
<div className={className} ref={editor} key={containerKey}></div>
{meta.error && <FormHelperText error={true}>{meta.error}</FormHelperText>}
</FormControl>
);
};

View File

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

79
src/generated/graphql.tsx Normal file
View File

@ -0,0 +1,79 @@
import { gql } from '@apollo/client';
export type Maybe<T> = T | null;
export type Exact<T extends { [key: string]: unknown }> = { [K in keyof T]: T[K] };
export type MakeOptional<T, K extends keyof T> = Omit<T, K> & { [SubKey in K]?: Maybe<T[SubKey]> };
export type MakeMaybe<T, K extends keyof T> = Omit<T, K> & { [SubKey in K]: Maybe<T[SubKey]> };
/** All built-in and custom scalars, mapped to their actual values */
export type Scalars = {
ID: string;
String: string;
Boolean: boolean;
Int: number;
Float: number;
/** A date-time string at UTC, such as 2019-12-03T09:54:33Z, compliant with the date-time format. */
DateTime: any;
};
export type Article = {
__typename?: 'Article';
id: Scalars['ID'];
title: Scalars['String'];
content: Scalars['String'];
publishedAt?: Maybe<Scalars['DateTime']>;
tags: Array<Scalars['String']>;
};
export type CreateArticleInput = {
title: Scalars['String'];
content: Scalars['String'];
publishedAt?: Maybe<Scalars['DateTime']>;
tags: Array<Scalars['String']>;
};
export type Hello = {
__typename?: 'Hello';
message: Scalars['String'];
};
export type Mutation = {
__typename?: 'Mutation';
createArticle: Article;
updateArticle: Article;
removeArticle: Article;
};
export type MutationCreateArticleArgs = {
createArticleInput: CreateArticleInput;
};
export type MutationUpdateArticleArgs = {
updateArticleInput: UpdateArticleInput;
};
export type MutationRemoveArticleArgs = {
id: Scalars['String'];
};
export type Query = {
__typename?: 'Query';
hello: Hello;
articles: Array<Article>;
article: Article;
};
export type QueryArticleArgs = {
id: Scalars['String'];
};
export type UpdateArticleInput = {
title?: Maybe<Scalars['String']>;
content?: Maybe<Scalars['String']>;
publishedAt?: Maybe<Scalars['DateTime']>;
tags?: Maybe<Array<Scalars['String']>>;
id: Scalars['Int'];
};

View File

@ -11,3 +11,8 @@ code {
font-family: source-code-pro, Menlo, Monaco, Consolas, 'Courier New', font-family: source-code-pro, Menlo, Monaco, Consolas, 'Courier New',
monospace; monospace;
} }
a {
text-decoration: none;
color: inherit;
}

View File

@ -4,12 +4,21 @@ 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 { ApolloProvider } from '@apollo/client';
import { MuiPickersUtilsProvider } from '@material-ui/pickers';
import DateFnsUtils from "@date-io/date-fns";
import zhLocale from "date-fns/locale/zh-CN";
ReactDOM.render( ReactDOM.render(
<React.StrictMode> <React.StrictMode>
<App /> <ApolloProvider client={client}>
<MuiPickersUtilsProvider utils={DateFnsUtils} locale={zhLocale}>
<App />
</MuiPickersUtilsProvider>
</ApolloProvider>
</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

199
src/layouts/default.tsx Normal file
View File

@ -0,0 +1,199 @@
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 { Link, Route, BrowserRouter, Switch } from 'react-router-dom';
import { AddCircle, Description, LocalOffer } from '@material-ui/icons';
import { ArticleIndex } from '../articles';
import { ArticleEditor } from '../articles/article-editor';
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),
},
})
);
export const DefaultLayout: FC = ({children}) => {
const classes = useStyles();
const theme = useTheme();
const [open, setOpen] = React.useState(false);
const handleDrawerOpen = () => {
setOpen(true);
};
const handleDrawerClose = () => {
setOpen(false);
};
return (
<div className={classes.root}>
<BrowserRouter>
<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 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 />
</Drawer>
<main className={classes.content}>
<div className={classes.toolbar} />
<Switch>
<Route path="/articles/create">
<ArticleEditor />
</Route>
<Route path="/articles">
<ArticleIndex />
</Route>
<Route path="/tags">Tags</Route>
</Switch>
</main>
</BrowserRouter>
</div>
);
}

1
src/layouts/index.tsx Normal file
View File

@ -0,0 +1 @@
export * from './default';