This commit is contained in:
Ivan Li 2021-12-01 19:15:22 +08:00
parent 48dd4a88bf
commit 6fabc1243b
8 changed files with 415 additions and 359 deletions

View File

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

View File

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

View File

@ -1,21 +1,39 @@
import { Button, Grid, Paper } from "@mui/material"; import {
import createStyles from '@mui/styles/createStyles'; Badge,
import makeStyles from '@mui/styles/makeStyles'; Box,
Button,
Grid,
IconButton,
Paper,
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 { Field, Form, Formik, FormikHelpers, FormikProps } from "formik";
import { FC, useCallback, useMemo, useRef, useState } from "react"; import { FC, useCallback, 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, Article,
CreateArticleInput, CreateArticleInput,
CreateDraftArticleInput, ArticleHistory,
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 * as R from "ramda"; import * as R from "ramda";
import { useNavigate } from "react-router-dom"; 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` const CREATE_ARTICLE = gql`
mutation createArticle($createArticleInput: CreateArticleInput!) { mutation createArticle($createArticleInput: CreateArticleInput!) {
@ -52,15 +70,17 @@ const useStyles = makeStyles((theme) =>
const fields = ["title", "content", "publishedAt", "tags"] as const; const fields = ["title", "content", "publishedAt", "tags"] as const;
type Values = Pick<Article, typeof fields[number]> & type Values = Pick<Article, typeof fields[number]> &
Partial<Pick<Article, "id" | "key">>; Partial<Pick<Article, "id">>;
interface Props { interface Props {
article?: Values; article?: Values;
draftKey: string;
} }
export const ArticleEditor: FC<Props> = ({ article }) => { export const ArticleEditor: FC<Props> = ({ article, draftKey }) => {
const classes = useStyles(); const classes = useStyles();
const navigate = useNavigate(); const navigate = useNavigate();
const formik = useRef<FormikProps<Values>>(null); const formik = useRef<FormikProps<Values>>(null);
const { draft, putDraft, drafts, getDraft } = useDrafts(draftKey);
const validationSchema = Yup.object({ const validationSchema = Yup.object({
content: Yup.string() content: Yup.string()
@ -100,30 +120,6 @@ export const ArticleEditor: FC<Props> = ({ article }) => {
updateArticleInput: UpdateArticleInput; updateArticleInput: UpdateArticleInput;
}>(UPDATE_ARTICLE); }>(UPDATE_ARTICLE);
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 ( const submitForm = async (
values: Values, values: Values,
{ setSubmitting }: FormikHelpers<Values> { setSubmitting }: FormikHelpers<Values>
@ -174,33 +170,15 @@ export const ArticleEditor: FC<Props> = ({ article }) => {
setSubmitting(false); setSubmitting(false);
}; };
const [drafts, setDrafts] = useState<DraftArticle[]>([]);
const handleSave = useCallback( const handleSave = useCallback(
async (automatically = true) => { async (automatically = true) => {
const { data } = await putDraft({ await putDraft({
variables: { key: draftKey,
draft: { payload: formik.current?.values,
key: tempKey, automatically,
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] [draftKey, putDraft, formik]
); );
return ( return (
@ -251,6 +229,11 @@ export const ArticleEditor: FC<Props> = ({ article }) => {
> >
Publish Publish
</Button> </Button>
<HistoryDrawer
drafts={drafts}
setCurrentDraft={(draft) => getDraft(draft.id)}
/>
</Grid> </Grid>
</Grid> </Grid>
</Form> </Form>
@ -260,6 +243,78 @@ 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 = { ArticleEditor.defaultProps = {
article: { article: {
title: "", title: "",

View File

@ -7,6 +7,11 @@ export const ARTICLE = gql`
title title
content content
publishedAt 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

@ -97,18 +97,6 @@
"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,
@ -136,6 +124,30 @@
}, },
"isDeprecated": false, "isDeprecated": false,
"deprecationReason": null "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, "inputFields": null,
@ -163,6 +175,91 @@
"enumValues": null, "enumValues": null,
"possibleTypes": 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", "kind": "INPUT_OBJECT",
"name": "CreateArticleInput", "name": "CreateArticleInput",
@ -242,71 +339,6 @@
"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",
@ -344,81 +376,6 @@
"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",
@ -550,113 +507,6 @@
"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,
@ -775,7 +625,7 @@
{ {
"kind": "SCALAR", "kind": "SCALAR",
"name": "Object", "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).", "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, "fields": null,
"inputFields": null, "inputFields": null,
"interfaces": null, "interfaces": null,

View File

@ -12,7 +12,7 @@ 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). */ /** 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; Object: any;
}; };
@ -23,9 +23,17 @@ 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']>;
histories: Array<ArticleHistory>;
};
export type ArticleHistory = {
__typename?: 'ArticleHistory';
payload: Scalars['Object'];
updatedAt: Scalars['DateTime'];
automatic: Scalars['Boolean'];
published: Scalars['Boolean'];
}; };
export type CreateArticleInput = { export type CreateArticleInput = {
@ -35,25 +43,11 @@ 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'];
@ -64,9 +58,6 @@ 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;
@ -88,21 +79,6 @@ 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;
}; };

View File

@ -1,18 +1,31 @@
import { useApolloClient } from "@apollo/client"; import { useApolloClient } from "@apollo/client";
import * as R from "ramda"; import * as R from "ramda";
import { FC, lazy, useMemo } from "react"; import { FC, lazy, useMemo } from "react";
import { useParams, useRoutes } from "react-router-dom"; import {
Navigate,
useParams,
useRoutes,
useSearchParams,
} from "react-router-dom";
import { ARTICLE } from "./articles"; import { ARTICLE } from "./articles";
import { Article } from "./generated/graphql"; import { Article } from "./generated/graphql";
import { DefaultLayout } from "./layouts"; import { DefaultLayout } from "./layouts";
const CreateArticle = lazy(() => const CreateArticle = () => {
import( const ArticleEditor = lazy(() =>
/* webpackChunkName: "article-editor" */ "./articles/article-editor" import(
).then((m) => ({ /* webpackChunkName: "article-editor" */ "./articles/article-editor"
default: m.ArticleEditor, ).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 ModifyArticle: FC = () => {
const { id } = useParams(); const { id } = useParams();
@ -33,7 +46,11 @@ const ModifyArticle: FC = () => {
return R.omit(["__typename"], data.article); return R.omit(["__typename"], data.article);
}), }),
]); ]);
return { default: () => <ArticleEditor article={article} /> }; return {
default: () => (
<ArticleEditor article={article} draftKey={article.key!} />
),
};
}), }),
[id, client] [id, client]
); );