feat(pipelines): edit view.

This commit is contained in:
Ivan Li 2021-06-27 00:27:57 +08:00
parent 120a720be5
commit 653d779efb
10 changed files with 464 additions and 33 deletions

View File

@ -29,9 +29,12 @@ const cleanTypeName = new ApolloLink((operation, forward) => {
if (operation.variables) { if (operation.variables) {
operation.variables = deepOmit(["__typename"], operation.variables); operation.variables = deepOmit(["__typename"], operation.variables);
} }
return forward(operation).map((data) => { const rt = forward(operation);
return (
rt.map?.((data) => {
return data; return data;
}); }) ?? rt
);
}); });
export const FennecApolloClientProvider: FC = ({ children }) => { export const FennecApolloClientProvider: FC = ({ children }) => {

View File

@ -718,7 +718,7 @@
"description": null, "description": null,
"args": [ "args": [
{ {
"name": "Pipeline", "name": "pipeline",
"description": null, "description": null,
"type": { "type": {
"kind": "NON_NULL", "kind": "NON_NULL",
@ -2249,7 +2249,7 @@
"name": null, "name": null,
"ofType": { "ofType": {
"kind": "SCALAR", "kind": "SCALAR",
"name": "Float", "name": "Int",
"ofType": null "ofType": null
} }
}, },
@ -2286,6 +2286,16 @@
"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": "INPUT_OBJECT", "kind": "INPUT_OBJECT",
"name": "WorkUnitMetadataInput", "name": "WorkUnitMetadataInput",
@ -2297,7 +2307,7 @@
"description": null, "description": null,
"type": { "type": {
"kind": "SCALAR", "kind": "SCALAR",
"name": "Float", "name": "Int",
"ofType": null "ofType": null
}, },
"defaultValue": "1", "defaultValue": "1",

View File

@ -99,7 +99,7 @@ export type MutationCreatePipelineArgs = {
export type MutationUpdatePipelineArgs = { export type MutationUpdatePipelineArgs = {
Pipeline: UpdatePipelineInput; pipeline: UpdatePipelineInput;
}; };
@ -284,11 +284,11 @@ export type WorkUnitInput = {
export type WorkUnitMetadata = { export type WorkUnitMetadata = {
__typename?: 'WorkUnitMetadata'; __typename?: 'WorkUnitMetadata';
version: Scalars['Float']; version: Scalars['Int'];
units: Array<WorkUnit>; units: Array<WorkUnit>;
}; };
export type WorkUnitMetadataInput = { export type WorkUnitMetadataInput = {
version?: Maybe<Scalars['Float']>; version?: Maybe<Scalars['Int']>;
units: Array<WorkUnitInput>; units: Array<WorkUnitInput>;
}; };

View File

@ -1,7 +1,7 @@
import { gql, useQuery, useSubscription } from "@apollo/client"; import { gql, useQuery, useSubscription } from "@apollo/client";
import { LinearProgress, makeStyles, Typography } from "@material-ui/core"; import { LinearProgress, makeStyles, Typography } from "@material-ui/core";
import { format } from "date-fns"; import { format } from "date-fns";
import React, { FC, useState } from "react"; import { FC, useState } from "react";
import { ErrorPage } from "../commons/fallbacks/error-page"; import { ErrorPage } from "../commons/fallbacks/error-page";
import { import {
PipelineTask, PipelineTask,
@ -11,7 +11,6 @@ import {
} from "../generated/graphql"; } from "../generated/graphql";
import { PIPELINE_TASK_EVENT } from "./subscriptions"; import { PIPELINE_TASK_EVENT } from "./subscriptions";
import { clone, find, propEq } from "ramda"; import { clone, find, propEq } from "ramda";
import { PipelineUnits } from '../generated/graphql';
interface Props { interface Props {
taskId: string; taskId: string;

View File

@ -0,0 +1,43 @@
import { gql } from "@apollo/client";
export const CREATE_PIPELINE = gql`
mutation CreatePipeline($pipeline: CreatePipelineInput!) {
createPipeline(pipeline: $pipeline) {
id
projectId
branch
name
workUnitMetadata {
version
units {
type
scripts
}
}
}
}
`;
export const UPDATE_PIPELINE = gql`
mutation UpdatePipeline($pipeline: UpdatePipelineInput!) {
updatePipeline(pipeline: $pipeline) {
id
projectId
branch
name
workUnitMetadata {
version
units {
type
scripts
}
}
}
}
`;
export const DELETE_PIPELINE = gql`
mutation DeletePipeline($id: String!) {
deletePipeline(id: $id)
}
`;

View File

@ -0,0 +1,285 @@
import { gql, Reference, useMutation, useQuery } from "@apollo/client";
import { useRouter } from "@curi/react-dom";
import {
Button,
Grid,
IconButton,
LinearProgress,
makeStyles,
Paper,
Portal,
Typography,
} from "@material-ui/core";
import { Delete } from "@material-ui/icons";
import { FormikHelpers, Formik, Form, Field } from "formik";
import { TextField, TextFieldProps } from "formik-material-ui";
import { TextField as MuiTextField } from "@material-ui/core";
import { useConfirm } from "material-ui-confirm";
import { useSnackbar } from "notistack";
import { not, omit } from "ramda";
import { ChangeEvent, FC } from "react";
import {
Pipeline,
WorkUnitMetadata,
PipelineUnits,
} from "../generated/graphql";
import { useHeaderContainer } from "../layouts";
import { CREATE_PIPELINE, DELETE_PIPELINE, UPDATE_PIPELINE } from "./mutations";
import { PIPELINE } from "./queries";
import * as Yup from "yup";
import { useField } from "formik";
type Values = Partial<Pipeline>;
interface Props {
pipeline: Values;
}
const useStyles = makeStyles((theme) => ({
root: {
flex: "1 1 100%",
},
nested: {
paddingLeft: theme.spacing(4),
},
form: {
margin: 16,
},
metadataList: {
padding: 0,
},
metadataItem: {
listStyle: "none",
},
metadataContainer: {
padding: "10px 30px",
margin: "10px 0",
},
}));
export const PipelineEditor: FC<Props> = ({ pipeline }) => {
const { enqueueSnackbar } = useSnackbar();
const isCreate = not("id" in pipeline);
const [createPipeline] = useMutation<{ createPipeline: Pipeline }>(
CREATE_PIPELINE,
{
update(cache, { data }) {
cache.modify({
fields: {
pipelines(exiting = []) {
const pipelineRef = cache.writeFragment({
data: data!.createPipeline,
fragment: gql`
fragment newPipeline on Pipeline {
id
projectId
branch
name
workUnitMetadata {
version
units {
type
scripts
}
}
}
`,
});
return [pipelineRef, ...exiting];
},
},
});
},
}
);
const [updatePipeline] = useMutation(UPDATE_PIPELINE);
const router = useRouter();
const submitForm = async (
values: Values,
formikHelpers: FormikHelpers<Values>
) => {
try {
let pipelineId = pipeline.id;
let projectId = pipeline.projectId;
if (isCreate) {
await createPipeline({
variables: {
input: values,
},
}).then(({ data }) => {
pipelineId = data!.createPipeline.id;
projectId = data!.createPipeline.projectId;
});
} else {
await updatePipeline({
variables: {
pipeline: omit(["projectId"], values),
},
});
}
enqueueSnackbar("Saved successfully", {
variant: "success",
});
router.navigate({
url: router.url({
name: "pipeline-commits",
params: {
pipelineId,
projectId,
},
}),
method: "replace",
});
} finally {
formikHelpers.setSubmitting(false);
}
};
const [deletePipeline, { loading: deleting }] = useMutation(DELETE_PIPELINE, {
variables: { id: pipeline.id },
update(cache) {
cache.modify({
fields: {
projects(exiting: Reference[] = [], { readField }) {
return exiting.filter(
(ref) => pipeline.id !== readField("id", ref)
);
},
},
});
},
});
const confirm = useConfirm();
const handleDelete = async () => {
try {
await confirm({ description: `This will delete ${pipeline.name}.` });
await deletePipeline();
enqueueSnackbar("Deleted successfully", {
variant: "success",
});
router.navigate({
url: router.url({
name: "dashboard",
}),
});
} catch {}
};
const headerContainer = useHeaderContainer();
const units = [
PipelineUnits.Checkout,
PipelineUnits.InstallDependencies,
PipelineUnits.Test,
PipelineUnits.Deploy,
PipelineUnits.CleanUp,
];
const classes = useStyles();
return (
<Paper className={classes.root}>
<Portal container={headerContainer}>
<Grid container justify="space-between" alignItems="center">
<Typography variant="h6" component="h1">
{isCreate ? "Create" : "Edit"} Pipeline
</Typography>
{isCreate ? null : (
<IconButton
color="inherit"
onClick={handleDelete}
disabled={deleting}
>
<Delete />
</IconButton>
)}
</Grid>
</Portal>
<Formik
initialValues={pipeline}
validationSchema={Yup.object({
name: Yup.string()
.max(32, "Must be 32 characters or less")
.required("Required"),
branch: Yup.string()
.max(32, "Must be 32 characters or less")
.required("Required"),
})}
onSubmit={submitForm}
>
{({ submitForm, isSubmitting, values }) => {
return (
<Form className={classes.form}>
<Field component={TextField} name="name" label="Name" fullWidth />
<Field
component={TextField}
name="branch"
label="Branch"
fullWidth
margin="normal"
/>
<Paper className={classes.metadataContainer}>
<Field
component={TextField}
name="workUnitMetadata.version"
label="Version"
fullWidth
readonly
margin="normal"
/>
<ol className={classes.metadataList}>
{units.map((unit, index) => {
return (
<li key={unit} className={classes.metadataItem}>
<Field
name={`workUnitMetadata.units[${index}].scripts]`}
component={ScriptsField}
label={`${unit} Scripts`}
fullWidth
multiline
margin="normal"
/>
</li>
);
})}
</ol>
</Paper>
{isSubmitting && <LinearProgress />}
<Button
variant="contained"
color="primary"
disabled={isSubmitting}
onClick={submitForm}
fullWidth
>
Submit
</Button>
</Form>
);
}}
</Formik>
</Paper>
);
};
const ScriptsField: FC<TextFieldProps> = ({ field, form, meta, ...props }) => {
return (
<TextField
{...props}
form={form}
meta={meta}
field={{
...field,
value: field.value?.join("\n") ?? "",
onChange: (ev: ChangeEvent<HTMLInputElement>) =>
form.setFieldValue(
field.name,
ev.target.value?.split("\n").map((it) => it.trim()) ?? []
),
}}
/>
);
};

View File

@ -1,9 +1,18 @@
import { gql, useQuery } from '@apollo/client'; import { gql, useQuery } from "@apollo/client";
import { Link } from '@curi/react-dom'; import { Link, useRouter } from "@curi/react-dom";
import { List, ListItem, Typography, ListItemText } from '@material-ui/core'; import {
import { FC } from 'react'; List,
import { Pipeline } from '../generated/graphql'; ListItem,
import { CallMerge } from '@material-ui/icons'; Typography,
ListItemText,
ListItemSecondaryAction,
IconButton,
} from "@material-ui/core";
import { FC, MouseEventHandler, useMemo } from "react";
import { Pipeline, Project } from "../generated/graphql";
import { CallMerge, Edit } from "@material-ui/icons";
import { clone } from "ramda";
import { useEffect } from "react";
interface Props { interface Props {
projectId: string; projectId: string;
@ -16,16 +25,28 @@ const PIPELINES = gql`
name name
branch branch
} }
project(id: $projectId) {
id
} }
` }
`;
export const PipelineList: FC<Props> = ({ projectId }) => { export const PipelineList: FC<Props> = ({ projectId }) => {
const {data, loading} = useQuery<{pipelines: Pipeline[]}, {projectId: string}>(PIPELINES, { const { data, loading } = useQuery<
variables: {projectId} { pipelines: Pipeline[]; project: Project },
}) { projectId: string }
>(PIPELINES, {
variables: { projectId },
});
const pipelines = useMemo(() => {
return data?.pipelines?.map((pipeline) => ({
...pipeline,
project: data?.project,
}));
}, [data]);
return ( return (
<List> <List>
{data?.pipelines.map((pipeline) => ( {pipelines?.map((pipeline) => (
<Link <Link
name="pipeline-commits" name="pipeline-commits"
params={{ pipelineId: pipeline.id, projectId: projectId }} params={{ pipelineId: pipeline.id, projectId: projectId }}
@ -36,10 +57,19 @@ export const PipelineList: FC<Props> = ({ projectId }) => {
))} ))}
</List> </List>
); );
} };
const Item = ({pipeline}: {pipeline: Pipeline}) => {
const Item = ({ pipeline }: { pipeline: Pipeline }) => {
const { navigate, url } = useRouter();
const modify: MouseEventHandler = (ev) => {
ev.preventDefault();
navigate({
url: url({
name: "edit-pipeline",
params: { pipelineId: pipeline.id, projectId: pipeline.project.id },
}),
});
};
return ( return (
<ListItem button> <ListItem button>
<ListItemText <ListItemText
@ -51,6 +81,11 @@ const Item = ({pipeline}: {pipeline: Pipeline}) => {
</Typography> </Typography>
} }
/> />
<ListItemSecondaryAction>
<IconButton edge="end" aria-label="edit" onClick={modify}>
<Edit />
</IconButton>
</ListItemSecondaryAction>
</ListItem> </ListItem>
); );
} };

View File

@ -5,6 +5,7 @@ export const PIPELINE = gql`
pipeline(id: $id) { pipeline(id: $id) {
id id
name name
projectId
branch branch
workUnitMetadata { workUnitMetadata {
version version
@ -15,4 +16,4 @@ export const PIPELINE = gql`
} }
} }
} }
` `;

View File

@ -60,12 +60,17 @@ export const ProjectDetail: FC<Props> = ({ project, children }) => {
alignItems="stretch" alignItems="stretch"
className={classes.root} className={classes.root}
> >
<Grid item lg={1} style={{ height: "100%", display: "flex" }}> <Grid item xs={3} lg={2} style={{ height: "100%", display: "flex" }}>
<Paper className={classes.pipelineListContainer}> <Paper className={classes.pipelineListContainer}>
<PipelineList projectId={project.id} /> <PipelineList projectId={project.id} />
</Paper> </Paper>
</Grid> </Grid>
<Grid item xs={10} lg={11} style={{ height: "100%", display: "flex", overflowY: 'auto' }}> <Grid
item
xs={9}
lg={10}
style={{ height: "100%", display: "flex", overflowY: "auto" }}
>
{children} {children}
</Grid> </Grid>
</Grid> </Grid>

View File

@ -1,12 +1,19 @@
import { ApolloClient, InMemoryCache } from "@apollo/client"; import { ApolloClient, InMemoryCache } from "@apollo/client";
import { prepareRoutes } from "@curi/router"; import { prepareRoutes } from "@curi/router";
import { omit } from 'ramda'; import { omit } from 'ramda';
import React from 'react'; import React from "react";
import { CreateProjectInput, Pipeline, Project } from './generated/graphql';
import { ProjectDetail, ProjectEditor, PROJECT } from "./projects"; import { ProjectDetail, ProjectEditor, PROJECT } from "./projects";
import { COMMIT_LIST_QUERY } from './commons/graphql/queries'; import { COMMIT_LIST_QUERY } from './commons/graphql/queries';
import { CommitList } from './commits/commit-list'; import { CommitList } from './commits/commit-list';
import { PipelineTaskDetail } from './pipeline-tasks/pipeline-task-detail'; import { PipelineTaskDetail } from './pipeline-tasks/pipeline-task-detail';
import { PipelineEditor } from "./pipelines/pipeline-editor";
import {
CreatePipelineInput,
CreateProjectInput,
Pipeline,
Project,
} from "./generated/graphql";
import { PIPELINE } from "./pipelines";
export default prepareRoutes([ export default prepareRoutes([
{ {
@ -51,6 +58,49 @@ export default prepareRoutes([
return resolved; return resolved;
}, },
}, // edit-project }, // edit-project
{
name: "create-pipeline",
path: "projects/:projectId/pipelines/create",
async resolve(
matched,
{ client }: { client: ApolloClient<InMemoryCache> }
) {
const input: CreatePipelineInput = {
name: "",
branch: "",
projectId: matched!.params.projectId,
workUnitMetadata: {
version: 1,
units: [],
},
};
return {
body: () => <PipelineEditor pipeline={input as any} />,
};
},
respond({ resolved }) {
return resolved;
},
}, // create-pipeline
{
name: "edit-pipeline",
path: "projects/:projectId/pipelines/:pipelineId/edit",
async resolve(
matched,
{ client }: { client: ApolloClient<InMemoryCache> }
) {
const { data } = await client.query<{ pipeline: Pipeline }>({
query: PIPELINE,
variables: { id: matched?.params.pipelineId },
});
return {
body: () => <PipelineEditor pipeline={data.pipeline} />,
};
},
respond({ resolved }) {
return resolved;
},
}, // edit-pipeline
{ {
name: "project-detail", name: "project-detail",
path: "projects/:projectId", path: "projects/:projectId",
@ -100,7 +150,7 @@ export default prepareRoutes([
respond({ resolved, error }) { respond({ resolved, error }) {
return resolved || <div>Failed</div>; return resolved || <div>Failed</div>;
}, },
}, }, // pipeline-commits
{ {
name: "pipeline-task-detail", name: "pipeline-task-detail",
path: "pipelines/:pipelineId/tasks/:taskId", path: "pipelines/:pipelineId/tasks/:taskId",
@ -129,7 +179,7 @@ export default prepareRoutes([
respond({ resolved, error }) { respond({ resolved, error }) {
return resolved || <div>Failed</div>; return resolved || <div>Failed</div>;
}, },
}, }, // pipeline-task-detail
], ],
}, // project-detail }, // project-detail
]); ]);