feat: 文章保存到草稿。

This commit is contained in:
Ivan Li 2021-11-23 22:23:10 +08:00
parent cf24177017
commit 1eb8099d03
6 changed files with 1511 additions and 983 deletions

2046
package-lock.json generated

File diff suppressed because it is too large Load Diff

View File

@ -5,14 +5,21 @@ 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 { Article, CreateArticleInput, UpdateArticleInput } from "../generated/graphql"; import {
Article,
CreateArticleInput,
CreateDraftArticleInput,
DraftArticle,
UpdateArticleInput,
} 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 { useRouter } from "@curi/react-universal";
import * as R from "ramda";
const CREATE_ARTICLE = gql` const CREATE_ARTICLE = gql`
mutation createArticle($createArticleInput: CreateArticleInput!) { mutation createArticle($createArticleInput: CreateArticleInput!) {
@ -47,13 +54,17 @@ 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()
@ -61,11 +72,13 @@ export const ArticleEditor: FC<Props> = ({ article }) => {
.required("文章内容不得为空"), .required("文章内容不得为空"),
publishedAt: Yup.date(), publishedAt: Yup.date(),
}); });
const router = useRouter();
const [createArticle] = useMutation<{createArticle: Article} ,{ const [createArticle] = useMutation<
createArticleInput: CreateArticleInput; { createArticle: Article },
}>(CREATE_ARTICLE, { {
createArticleInput: CreateArticleInput;
}
>(CREATE_ARTICLE, {
update(cache, { data }) { update(cache, { data }) {
cache.modify({ cache.modify({
fields: { fields: {
@ -91,7 +104,31 @@ export const ArticleEditor: FC<Props> = ({ article }) => {
updateArticleInput: UpdateArticleInput; updateArticleInput: UpdateArticleInput;
}>(UPDATE_ARTICLE); }>(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>
) => { ) => {
@ -102,7 +139,7 @@ export const ArticleEditor: FC<Props> = ({ article }) => {
setSubmitting(false); setSubmitting(false);
return; return;
} }
updateArticle({ await updateArticle({
variables: { variables: {
updateArticleInput: { updateArticleInput: {
...values, ...values,
@ -126,10 +163,10 @@ export const ArticleEditor: FC<Props> = ({ article }) => {
setSubmitting(false); setSubmitting(false);
return; return;
} }
createArticle({ await createArticle({
variables: { variables: {
createArticleInput: { createArticleInput: {
...values as CreateArticleInput, ...(values as CreateArticleInput),
title, title,
}, },
}, },
@ -146,13 +183,46 @@ export const ArticleEditor: FC<Props> = ({ article }) => {
} }
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}>
@ -178,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>
@ -197,5 +276,5 @@ ArticleEditor.defaultProps = {
content: "", content: "",
publishedAt: new Date(), publishedAt: new Date(),
tags: [], tags: [],
} as CreateArticleInput, } as Values,
}; };

View File

@ -36,6 +36,7 @@ export const ArticleIndex: FC = () => {
<TableCell>Published At</TableCell> <TableCell>Published At</TableCell>
<TableCell>Views</TableCell> <TableCell>Views</TableCell>
<TableCell>Comments</TableCell> <TableCell>Comments</TableCell>
<TableCell>Status</TableCell>
<TableCell>Actions</TableCell> <TableCell>Actions</TableCell>
</TableRow> </TableRow>
</TableHead> </TableHead>
@ -46,10 +47,13 @@ export const ArticleIndex: FC = () => {
{article.title} {article.title}
</TableCell> </TableCell>
<TableCell> <TableCell>
{format(article.publishedAt, "yyyy-MM-dd HH:mm:ss")} {article.publishedAt
? format(article.publishedAt, "yyyy-MM-dd HH:mm:ss")
: "--"}
</TableCell> </TableCell>
<TableCell align="right"> -- </TableCell> <TableCell align="right"> -- </TableCell>
<TableCell align="right"> -- </TableCell> <TableCell align="right"> -- </TableCell>
<TableCell align="center">{"Published"}</TableCell>
<TableCell> <TableCell>
<IconButton <IconButton
aria-label="edit" aria-label="edit"

View File

@ -1,7 +1,7 @@
import { createStyles, FormControl, FormHelperText, FormLabel, makeStyles } from '@material-ui/core'; import { createStyles, FormControl, FormHelperText, FormLabel, makeStyles } from '@material-ui/core';
import { Skeleton } from "@material-ui/lab"; import { Skeleton } from "@material-ui/lab";
import { FieldHookConfig, useField } from "formik"; import { FieldHookConfig, useField } from "formik";
import React, { FC, useEffect, useRef, useState } from "react"; import React, { FC, useEffect, useMemo, useRef, useState } from "react";
import Vditor from "vditor"; import Vditor from "vditor";
import "vditor/src/assets/scss/index.scss"; import "vditor/src/assets/scss/index.scss";
@ -22,7 +22,10 @@ export const Editor: FC<Props> = ({ label, className, ...props }) => {
const [, 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;
@ -45,13 +48,18 @@ export const Editor: FC<Props> = ({ label, className, ...props }) => {
return () => { return () => {
_instance?.destroy(); _instance?.destroy();
}; };
}, []); // eslint-disable-next-line react-hooks/exhaustive-deps
}, [containerKey]);
const classes = useStyles(); const classes = useStyles();
return ( return (
<FormControl className={classes.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 : ( {instance ? null : (
<Skeleton <Skeleton

View File

@ -97,6 +97,18 @@
"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", "name": "html",
"description": null, "description": null,
@ -230,6 +242,71 @@
"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", "kind": "INPUT_OBJECT",
"name": "CreateTagInput", "name": "CreateTagInput",
@ -267,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",
@ -398,6 +550,113 @@
"isDeprecated": false, "isDeprecated": false,
"deprecationReason": null "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": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "OBJECT",
"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", "name": "createTag",
"description": null, "description": null,
@ -513,6 +772,16 @@
"enumValues": null, "enumValues": null,
"possibleTypes": 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",
@ -819,16 +1088,6 @@
"enumValues": null, "enumValues": null,
"possibleTypes": 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": "OBJECT", "kind": "OBJECT",
"name": "__Schema", "name": "__Schema",

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,7 @@ 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']; html: Scalars['String'];
description?: Maybe<Scalars['String']>; description?: Maybe<Scalars['String']>;
}; };
@ -32,11 +35,25 @@ 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 = { export type CreateTagInput = {
name: Scalars['String']; 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';
message: Scalars['String']; message: Scalars['String'];
@ -47,6 +64,9 @@ export type Mutation = {
createArticle: Article; createArticle: Article;
updateArticle: Article; updateArticle: Article;
removeArticle: Scalars['Int']; removeArticle: Scalars['Int'];
putDraftForArticle: DraftArticle;
listDraftForArticle: Array<DraftArticle>;
lastDraftForArticle: DraftArticle;
createTag: Tag; createTag: Tag;
updateTag: Tag; updateTag: Tag;
removeTag: Tag; removeTag: Tag;
@ -68,6 +88,21 @@ export type MutationRemoveArticleArgs = {
}; };
export type MutationPutDraftForArticleArgs = {
draft: CreateDraftArticleInput;
};
export type MutationListDraftForArticleArgs = {
key: Scalars['String'];
};
export type MutationLastDraftForArticleArgs = {
key: Scalars['String'];
};
export type MutationCreateTagArgs = { export type MutationCreateTagArgs = {
createTagInput: CreateTagInput; createTagInput: CreateTagInput;
}; };
@ -82,6 +117,7 @@ export type MutationRemoveTagArgs = {
id: Scalars['String']; id: Scalars['String'];
}; };
export type Query = { export type Query = {
__typename?: 'Query'; __typename?: 'Query';
hello: Hello; hello: Hello;