Merge pull request #16295 from backstage/blam/scaffolder/next/editor

scaffolder/next: `TemplateEditorPage` support
This commit is contained in:
Fredrik Adelöw
2023-02-14 13:50:06 +01:00
committed by GitHub
18 changed files with 982 additions and 8 deletions
+5
View File
@@ -0,0 +1,5 @@
---
'@backstage/plugin-scaffolder-react': minor
---
Added `DescriptionField` field override to the `next/scaffolder`
+6
View File
@@ -0,0 +1,6 @@
---
'@backstage/plugin-scaffolder-react': minor
'@backstage/plugin-scaffolder': minor
---
Migrating the `TemplateEditorPage` to work with the new components from `@backstage/plugin-scaffolder-react`
+6 -1
View File
@@ -7,13 +7,14 @@
import { ApiHolder } from '@backstage/core-plugin-api';
import { ApiRef } from '@backstage/core-plugin-api';
import { ComponentType } from 'react';
import { Dispatch } from 'react';
import { Extension } from '@backstage/core-plugin-api';
import { FieldProps } from '@rjsf/core';
import { FieldProps as FieldProps_2 } from '@rjsf/utils';
import { FieldValidation } from '@rjsf/core';
import { FieldValidation as FieldValidation_2 } from '@rjsf/utils';
import type { FormProps as FormProps_2 } from '@rjsf/core-v5';
import { FormProps as FormProps_2 } from '@rjsf/core-v5';
import { IconComponent } from '@backstage/core-plugin-api';
import { JsonObject } from '@backstage/types';
import { JSONSchema7 } from 'json-schema';
@@ -22,6 +23,7 @@ import { Observable } from '@backstage/types';
import { PropsWithChildren } from 'react';
import { default as React_2 } from 'react';
import { ReactNode } from 'react';
import { RJSFSchema } from '@rjsf/utils';
import { SetStateAction } from 'react';
import { TaskSpec } from '@backstage/plugin-scaffolder-common';
import { TaskStep } from '@backstage/plugin-scaffolder-common';
@@ -126,6 +128,9 @@ export type FieldExtensionOptions<
schema?: CustomFieldExtensionSchema;
};
// @alpha (undocumented)
export const Form: ComponentType<FormProps_2<any, RJSFSchema, any>>;
// @public
export type FormProps = Pick<
FormProps_2,
@@ -0,0 +1,23 @@
/*
* Copyright 2022 The Backstage Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import { withTheme } from '@rjsf/core-v5';
// TODO(blam): We require here, as the types in this package depend on @rjsf/core explicitly
// which is what we're using here as the default types, it needs to depend on @rjsf/core-v5 because
// of the re-writing we're doing. Once we've migrated, we can import this the exact same as before.
/** @alpha */
export const Form = withTheme(require('@rjsf/material-ui-v5').Theme);
@@ -0,0 +1,17 @@
/*
* Copyright 2022 The Backstage Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
export { Form } from './Form';
@@ -0,0 +1,22 @@
/*
* Copyright 2021 The Backstage Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import React from 'react';
import { MarkdownContent } from '@backstage/core-components';
import { FieldProps } from '@rjsf/utils';
export const DescriptionField = ({ description }: FieldProps) =>
description && <MarkdownContent content={description} linkTarget="_blank" />;
@@ -0,0 +1,16 @@
/*
* Copyright 2021 The Backstage Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
export { DescriptionField } from './DescriptionField';
@@ -22,7 +22,7 @@ import {
Button,
makeStyles,
} from '@material-ui/core';
import { type IChangeEvent, withTheme } from '@rjsf/core-v5';
import { type IChangeEvent } from '@rjsf/core-v5';
import { ErrorSchema } from '@rjsf/utils';
import React, { useCallback, useMemo, useState, type ReactNode } from 'react';
import { NextFieldExtensionOptions } from '../../extensions';
@@ -39,6 +39,8 @@ import { FormProps } from '../../types';
import { LayoutOptions } from '../../../layouts';
import { useTransformSchemaToProps } from '../../hooks/useTransformSchemaToProps';
import { hasErrors } from './utils';
import * as FieldOverrides from './FieldOverrides';
import { Form } from '../Form';
const useStyles = makeStyles(theme => ({
backButton: {
@@ -74,11 +76,6 @@ export type StepperProps = {
layouts?: LayoutOptions[];
};
// TODO(blam): We require here, as the types in this package depend on @rjsf/core explicitly
// which is what we're using here as the default types, it needs to depend on @rjsf/core-v5 because
// of the re-writing we're doing. Once we've migrated, we can import this the exact same as before.
const Form = withTheme(require('@rjsf/material-ui-v5').Theme);
/**
* The `Stepper` component is the Wizard that is rendered when a user selects a template
* @alpha
@@ -175,7 +172,7 @@ export const Stepper = (stepperProps: StepperProps) => {
schema={currentStep.schema}
uiSchema={currentStep.uiSchema}
onSubmit={handleNext}
fields={extensions}
fields={{ ...FieldOverrides, ...extensions }}
showErrorList={false}
onChange={handleChange}
{...(props.FormProps ?? {})}
@@ -19,3 +19,4 @@ export * from './ReviewState';
export * from './TemplateGroup';
export * from './Workflow';
export * from './TemplateOutputs';
export * from './Form';
+1
View File
@@ -58,6 +58,7 @@
"@rjsf/core": "^3.2.1",
"@rjsf/material-ui": "^3.2.1",
"@rjsf/utils": "5.1.0",
"@rjsf/validator-ajv8": "5.1.0",
"@uiw/react-codemirror": "^4.9.3",
"classnames": "^2.2.6",
"git-url-parse": "^13.0.0",
@@ -32,6 +32,7 @@ import { DEFAULT_SCAFFOLDER_FIELD_EXTENSIONS } from '../../extensions/default';
import {
nextActionsRouteRef,
nextEditRouteRef,
nextScaffolderListTaskRouteRef,
nextScaffolderTaskRouteRef,
nextSelectedTemplateRouteRef,
@@ -40,6 +41,7 @@ import { ErrorPage } from '@backstage/core-components';
import { OngoingTask } from '../OngoingTask';
import { ActionsPage } from '../../components/ActionsPage';
import { ListTasksPage } from '../../components/ListTasksPage';
import { TemplateEditorPage } from '../TemplateEditorPage';
/**
* The Props for the Scaffolder Router
@@ -130,6 +132,18 @@ export const Router = (props: PropsWithChildren<NextRouterProps>) => {
/>
}
/>
<Route
path={nextEditRouteRef.path}
element={
<SecretsContextProvider>
<TemplateEditorPage
customFieldExtensions={fieldExtensions}
layouts={customLayouts}
/>
</SecretsContextProvider>
}
/>
<Route path={nextActionsRouteRef.path} element={<ActionsPage />} />
<Route
path={nextScaffolderListTaskRouteRef.path}
@@ -0,0 +1,196 @@
/*
* Copyright 2022 The Backstage Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import { StreamLanguage } from '@codemirror/language';
import { yaml as yamlSupport } from '@codemirror/legacy-modes/mode/yaml';
import {
Button,
Card,
CardContent,
CardHeader,
FormControl,
IconButton,
InputLabel,
makeStyles,
MenuItem,
Select,
} from '@material-ui/core';
import CloseIcon from '@material-ui/icons/Close';
import CodeMirror from '@uiw/react-codemirror';
import React, { useCallback, useMemo, useState } from 'react';
import yaml from 'yaml';
import {
NextFieldExtensionOptions,
Form,
} from '@backstage/plugin-scaffolder-react';
import { TemplateEditorForm } from './TemplateEditorForm';
import validator from '@rjsf/validator-ajv8';
const useStyles = makeStyles(theme => ({
root: {
gridArea: 'pageContent',
display: 'grid',
gridTemplateAreas: `
"controls controls"
"fieldForm preview"
`,
gridTemplateRows: 'auto 1fr',
gridTemplateColumns: '1fr 1fr',
},
controls: {
gridArea: 'controls',
display: 'flex',
flexFlow: 'row nowrap',
alignItems: 'center',
margin: theme.spacing(1),
},
fieldForm: {
gridArea: 'fieldForm',
},
preview: {
gridArea: 'preview',
},
}));
export const CustomFieldExplorer = ({
customFieldExtensions = [],
onClose,
}: {
customFieldExtensions?: NextFieldExtensionOptions<any, any>[];
onClose?: () => void;
}) => {
const classes = useStyles();
const fieldOptions = customFieldExtensions.filter(field => !!field.schema);
const [selectedField, setSelectedField] = useState(fieldOptions[0]);
const [fieldFormState, setFieldFormState] = useState({});
const [refreshKey, setRefreshKey] = useState(Date.now());
const sampleFieldTemplate = useMemo(
() =>
yaml.stringify({
parameters: [
{
title: `${selectedField.name} Example`,
properties: {
[selectedField.name]: {
type: selectedField.schema?.returnValue?.type,
'ui:field': selectedField.name,
'ui:options': fieldFormState,
},
},
},
],
}),
[fieldFormState, selectedField],
);
const fieldComponents = useMemo(() => {
return Object.fromEntries(
customFieldExtensions.map(({ name, component }) => [name, component]),
);
}, [customFieldExtensions]);
const handleSelectionChange = useCallback(
selection => {
setSelectedField(selection);
setFieldFormState({});
},
[setFieldFormState, setSelectedField],
);
const handleFieldConfigChange = useCallback(
state => {
setFieldFormState(state);
// Force TemplateEditorForm to re-render since some fields
// may not be responsive to ui:option changes
setRefreshKey(Date.now());
},
[setFieldFormState, setRefreshKey],
);
return (
<main className={classes.root}>
<div className={classes.controls}>
<FormControl variant="outlined" size="small" fullWidth>
<InputLabel id="select-field-label">
Choose Custom Field Extension
</InputLabel>
<Select
value={selectedField}
label="Choose Custom Field Extension"
labelId="select-field-label"
onChange={e => handleSelectionChange(e.target.value)}
>
{fieldOptions.map((option, idx) => (
<MenuItem key={idx} value={option as any}>
{option.name}
</MenuItem>
))}
</Select>
</FormControl>
<IconButton size="medium" onClick={onClose}>
<CloseIcon />
</IconButton>
</div>
<div className={classes.fieldForm}>
<Card>
<CardHeader title="Field Options" />
<CardContent>
<Form
showErrorList={false}
fields={{ ...fieldComponents }}
noHtml5Validate
formData={fieldFormState}
formContext={{ fieldFormState }}
onSubmit={e => handleFieldConfigChange(e.formData)}
validator={validator}
schema={selectedField.schema?.uiOptions || {}}
>
<Button
variant="contained"
color="primary"
type="submit"
disabled={!selectedField.schema?.uiOptions}
>
Apply
</Button>
</Form>
</CardContent>
</Card>
</div>
<div className={classes.preview}>
<Card>
<CardHeader title="Example Template Spec" />
<CardContent>
<CodeMirror
readOnly
theme="dark"
height="100%"
extensions={[StreamLanguage.define(yamlSupport)]}
value={sampleFieldTemplate}
/>
</CardContent>
</Card>
<TemplateEditorForm
key={refreshKey}
content={sampleFieldTemplate}
contentIsSpec
fieldExtensions={customFieldExtensions}
setErrorText={() => null}
/>
</div>
</main>
);
};
@@ -0,0 +1,94 @@
/*
* Copyright 2022 The Backstage Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import { makeStyles } from '@material-ui/core';
import React, { useState } from 'react';
import type {
LayoutOptions,
NextFieldExtensionOptions,
} from '@backstage/plugin-scaffolder-react';
import { TemplateDirectoryAccess } from '../../lib/filesystem';
import { DirectoryEditorProvider } from '../../components/TemplateEditorPage/DirectoryEditorContext';
import { DryRunProvider } from '../../components/TemplateEditorPage/DryRunContext';
import { DryRunResults } from '../../components/TemplateEditorPage/DryRunResults';
import { TemplateEditorBrowser } from '../../components/TemplateEditorPage/TemplateEditorBrowser';
import { TemplateEditorForm } from './TemplateEditorForm';
import { TemplateEditorTextArea } from '../../components/TemplateEditorPage/TemplateEditorTextArea';
const useStyles = makeStyles({
// Reset and fix sizing to make sure scrolling behaves correctly
root: {
gridArea: 'pageContent',
display: 'grid',
gridTemplateAreas: `
"browser editor preview"
"results results results"
`,
gridTemplateColumns: '1fr 3fr 2fr',
gridTemplateRows: '1fr auto',
},
browser: {
gridArea: 'browser',
overflow: 'auto',
},
editor: {
gridArea: 'editor',
overflow: 'auto',
},
preview: {
gridArea: 'preview',
overflow: 'auto',
},
results: {
gridArea: 'results',
},
});
export const TemplateEditor = (props: {
directory: TemplateDirectoryAccess;
fieldExtensions?: NextFieldExtensionOptions<any, any>[];
layouts?: LayoutOptions[];
onClose?: () => void;
}) => {
const classes = useStyles();
const [errorText, setErrorText] = useState<string>();
return (
<DirectoryEditorProvider directory={props.directory}>
<DryRunProvider>
<main className={classes.root}>
<section className={classes.browser}>
<TemplateEditorBrowser onClose={props.onClose} />
</section>
<section className={classes.editor}>
<TemplateEditorTextArea.DirectoryEditor errorText={errorText} />
</section>
<section className={classes.preview}>
<TemplateEditorForm.DirectoryEditorDryRun
setErrorText={setErrorText}
fieldExtensions={props.fieldExtensions}
layouts={props.layouts}
/>
</section>
<section className={classes.results}>
<DryRunResults />
</section>
</main>
</DryRunProvider>
</DirectoryEditorProvider>
);
};
@@ -0,0 +1,233 @@
/*
* Copyright 2022 The Backstage Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import { useApiHolder } from '@backstage/core-plugin-api';
import { JsonObject, JsonValue } from '@backstage/types';
import { makeStyles } from '@material-ui/core/styles';
import React, { Component, ReactNode, useState } from 'react';
import useDebounce from 'react-use/lib/useDebounce';
import yaml from 'yaml';
import {
LayoutOptions,
NextFieldExtensionOptions,
Stepper,
TemplateParameterSchema,
} from '@backstage/plugin-scaffolder-react';
import { useDryRun } from '../../components/TemplateEditorPage/DryRunContext';
import { useDirectoryEditor } from '../../components/TemplateEditorPage/DirectoryEditorContext';
const useStyles = makeStyles({
containerWrapper: {
position: 'relative',
width: '100%',
height: '100%',
},
container: {
position: 'absolute',
top: 0,
bottom: 0,
left: 0,
right: 0,
overflow: 'auto',
},
});
interface ErrorBoundaryProps {
invalidator: unknown;
setErrorText(errorText: string | undefined): void;
children: ReactNode;
}
interface ErrorBoundaryState {
shouldRender: boolean;
}
class ErrorBoundary extends Component<ErrorBoundaryProps, ErrorBoundaryState> {
state = {
shouldRender: true,
};
componentDidUpdate(prevProps: { invalidator: unknown }) {
if (prevProps.invalidator !== this.props.invalidator) {
this.setState({ shouldRender: true });
}
}
componentDidCatch(error: Error) {
this.props.setErrorText(error.message);
this.setState({ shouldRender: false });
}
render() {
return this.state.shouldRender ? this.props.children : null;
}
}
interface TemplateEditorFormProps {
content?: string;
/** Setting this to true will cause the content to be parsed as if it is the template entity spec */
contentIsSpec?: boolean;
setErrorText: (errorText?: string) => void;
onDryRun?: (data: JsonObject) => Promise<void>;
fieldExtensions?: NextFieldExtensionOptions<any, any>[];
layouts?: LayoutOptions[];
}
function isJsonObject(value: JsonValue | undefined): value is JsonObject {
return typeof value === 'object' && value !== null && !Array.isArray(value);
}
/** Shows the a template form that is parsed from the provided content */
export function TemplateEditorForm(props: TemplateEditorFormProps) {
const {
content,
contentIsSpec,
onDryRun,
setErrorText,
fieldExtensions = [],
layouts = [],
} = props;
const classes = useStyles();
const apiHolder = useApiHolder();
const [steps, setSteps] = useState<TemplateParameterSchema['steps']>();
useDebounce(
() => {
try {
if (!content) {
setSteps(undefined);
return;
}
const parsed: JsonValue = yaml.parse(content);
if (!isJsonObject(parsed)) {
setSteps(undefined);
return;
}
let rootObj = parsed;
if (!contentIsSpec) {
const isTemplate =
String(parsed.kind).toLocaleLowerCase('en-US') === 'template';
if (!isTemplate) {
setSteps(undefined);
return;
}
rootObj = isJsonObject(parsed.spec) ? parsed.spec : {};
}
const { parameters } = rootObj;
if (!Array.isArray(parameters)) {
setErrorText('Template parameters must be an array');
setSteps(undefined);
return;
}
setErrorText();
setSteps(
parameters.flatMap(param =>
isJsonObject(param)
? [
{
title: String(param.title),
schema: param,
},
]
: [],
),
);
} catch (e) {
setErrorText(e.message);
}
},
250,
[contentIsSpec, content, apiHolder],
);
if (!steps) {
return null;
}
return (
<div className={classes.containerWrapper}>
<div className={classes.container}>
<ErrorBoundary invalidator={steps} setErrorText={setErrorText}>
<Stepper
manifest={{ steps, title: 'Template Editor' }}
extensions={fieldExtensions}
onCreate={async data => {
await onDryRun?.(data);
}}
layouts={layouts}
components={{ createButtonText: onDryRun && 'Try It' }}
/>
</ErrorBoundary>
</div>
</div>
);
}
/** A version of the TemplateEditorForm that is connected to the DirectoryEditor and DryRun contexts */
export function TemplateEditorFormDirectoryEditorDryRun(
props: Pick<
TemplateEditorFormProps,
'setErrorText' | 'fieldExtensions' | 'layouts'
>,
) {
const { setErrorText, fieldExtensions = [], layouts } = props;
const dryRun = useDryRun();
const directoryEditor = useDirectoryEditor();
const { selectedFile } = directoryEditor;
const handleDryRun = async (values: JsonObject) => {
if (!selectedFile) {
return;
}
try {
await dryRun.execute({
templateContent: selectedFile.content,
values,
files: directoryEditor.files,
});
setErrorText();
} catch (e) {
setErrorText(String(e.cause || e));
throw e;
}
};
const content =
selectedFile && selectedFile.path.match(/\.ya?ml$/)
? selectedFile.content
: undefined;
return (
<TemplateEditorForm
onDryRun={handleDryRun}
fieldExtensions={fieldExtensions}
setErrorText={setErrorText}
content={content}
layouts={layouts}
/>
);
}
TemplateEditorForm.DirectoryEditorDryRun =
TemplateEditorFormDirectoryEditorDryRun;
@@ -0,0 +1,107 @@
/*
* Copyright 2022 The Backstage Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import React, { useState } from 'react';
import { Content, Header, Page } from '@backstage/core-components';
import {
TemplateDirectoryAccess,
WebFileSystemAccess,
} from '../../lib/filesystem';
import { CustomFieldExplorer } from './CustomFieldExplorer';
import { TemplateEditor } from './TemplateEditor';
import { TemplateFormPreviewer } from './TemplateFormPreviewer';
import {
NextFieldExtensionOptions,
type LayoutOptions,
} from '@backstage/plugin-scaffolder-react';
import { TemplateEditorIntro } from '../../components/TemplateEditorPage/TemplateEditorIntro';
type Selection =
| {
type: 'local';
directory: TemplateDirectoryAccess;
}
| {
type: 'form';
}
| {
type: 'field-explorer';
};
interface TemplateEditorPageProps {
defaultPreviewTemplate?: string;
customFieldExtensions?: NextFieldExtensionOptions<any, any>[];
layouts?: LayoutOptions[];
}
export function TemplateEditorPage(props: TemplateEditorPageProps) {
const [selection, setSelection] = useState<Selection>();
let content: JSX.Element | null = null;
if (selection?.type === 'local') {
content = (
<TemplateEditor
directory={selection.directory}
fieldExtensions={props.customFieldExtensions}
onClose={() => setSelection(undefined)}
layouts={props.layouts}
/>
);
} else if (selection?.type === 'form') {
content = (
<TemplateFormPreviewer
defaultPreviewTemplate={props.defaultPreviewTemplate}
customFieldExtensions={props.customFieldExtensions}
onClose={() => setSelection(undefined)}
layouts={props.layouts}
/>
);
} else if (selection?.type === 'field-explorer') {
content = (
<CustomFieldExplorer
customFieldExtensions={props.customFieldExtensions}
onClose={() => setSelection(undefined)}
/>
);
} else {
content = (
<Content>
<TemplateEditorIntro
onSelect={option => {
if (option === 'local') {
WebFileSystemAccess.requestDirectoryAccess()
.then(directory => setSelection({ type: 'local', directory }))
.catch(() => {});
} else if (option === 'form') {
setSelection({ type: 'form' });
} else if (option === 'field-explorer') {
setSelection({ type: 'field-explorer' });
}
}}
/>
</Content>
);
}
return (
<Page themeId="home">
<Header
title="Template Editor"
subtitle="Edit, preview, and try out templates and template forms"
/>
{content}
</Page>
);
}
@@ -0,0 +1,219 @@
/*
* Copyright 2022 The Backstage Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import { Entity } from '@backstage/catalog-model';
import { alertApiRef, useApi } from '@backstage/core-plugin-api';
import {
catalogApiRef,
humanizeEntityRef,
} from '@backstage/plugin-catalog-react';
import {
FormControl,
IconButton,
InputLabel,
LinearProgress,
makeStyles,
MenuItem,
Select,
} from '@material-ui/core';
import CloseIcon from '@material-ui/icons/Close';
import React, { useCallback, useState } from 'react';
import useAsync from 'react-use/lib/useAsync';
import yaml from 'yaml';
import {
NextFieldExtensionOptions,
type LayoutOptions,
} from '@backstage/plugin-scaffolder-react';
import { TemplateEditorForm } from './TemplateEditorForm';
import { TemplateEditorTextArea } from '../../components/TemplateEditorPage/TemplateEditorTextArea';
const EXAMPLE_TEMPLATE_PARAMS_YAML = `# Edit the template parameters below to see how they will render in the scaffolder form UI
parameters:
- title: Fill in some steps
required:
- name
properties:
name:
title: Name
type: string
description: Unique name of the component
owner:
title: Owner
type: string
description: Owner of the component
ui:field: OwnerPicker
ui:options:
catalogFilter:
kind: Group
- title: Choose a location
required:
- repoUrl
properties:
repoUrl:
title: Repository Location
type: string
ui:field: RepoUrlPicker
ui:options:
allowedHosts:
- github.com
steps:
- id: fetch-base
name: Fetch Base
action: fetch:template
input:
url: ./template
values:
name: \${{parameters.name}}
`;
type TemplateOption = {
label: string;
value: Entity;
};
const useStyles = makeStyles(theme => ({
root: {
gridArea: 'pageContent',
display: 'grid',
gridTemplateAreas: `
"controls controls"
"textArea preview"
`,
gridTemplateRows: 'auto 1fr',
gridTemplateColumns: '1fr 1fr',
},
controls: {
gridArea: 'controls',
display: 'flex',
flexFlow: 'row nowrap',
alignItems: 'center',
margin: theme.spacing(1),
},
textArea: {
gridArea: 'textArea',
},
preview: {
gridArea: 'preview',
},
}));
export const TemplateFormPreviewer = ({
defaultPreviewTemplate = EXAMPLE_TEMPLATE_PARAMS_YAML,
customFieldExtensions = [],
onClose,
layouts = [],
}: {
defaultPreviewTemplate?: string;
customFieldExtensions?: NextFieldExtensionOptions<any, any>[];
onClose?: () => void;
layouts?: LayoutOptions[];
}) => {
const classes = useStyles();
const alertApi = useApi(alertApiRef);
const catalogApi = useApi(catalogApiRef);
const [selectedTemplate, setSelectedTemplate] = useState('');
const [errorText, setErrorText] = useState<string>();
const [templateOptions, setTemplateOptions] = useState<TemplateOption[]>([]);
const [templateYaml, setTemplateYaml] = useState(defaultPreviewTemplate);
const { loading } = useAsync(
() =>
catalogApi
.getEntities({
filter: { kind: 'template' },
fields: [
'kind',
'metadata.namespace',
'metadata.name',
'metadata.title',
'spec.parameters',
'spec.steps',
'spec.output',
],
})
.then(({ items }) =>
setTemplateOptions(
items.map(template => ({
label:
template.metadata.title ??
humanizeEntityRef(template, { defaultKind: 'template' }),
value: template,
})),
),
)
.catch(e =>
alertApi.post({
message: `Error loading exisiting templates: ${e.message}`,
severity: 'error',
}),
),
[catalogApi],
);
const handleSelectChange = useCallback(
selected => {
setSelectedTemplate(selected);
setTemplateYaml(yaml.stringify(selected.spec));
},
[setTemplateYaml],
);
return (
<>
{loading && <LinearProgress />}
<main className={classes.root}>
<div className={classes.controls}>
<FormControl variant="outlined" size="small" fullWidth>
<InputLabel id="select-template-label">
Load Existing Template
</InputLabel>
<Select
value={selectedTemplate}
label="Load Existing Template"
labelId="select-template-label"
onChange={e => handleSelectChange(e.target.value)}
>
{templateOptions.map((option, idx) => (
<MenuItem key={idx} value={option.value as any}>
{option.label}
</MenuItem>
))}
</Select>
</FormControl>
<IconButton size="medium" onClick={onClose}>
<CloseIcon />
</IconButton>
</div>
<div className={classes.textArea}>
<TemplateEditorTextArea
content={templateYaml}
onUpdate={setTemplateYaml}
errorText={errorText}
/>
</div>
<div className={classes.preview}>
<TemplateEditorForm
content={templateYaml}
contentIsSpec
fieldExtensions={customFieldExtensions}
setErrorText={setErrorText}
layouts={layouts}
/>
</div>
</main>
</>
);
};
@@ -0,0 +1,17 @@
/*
* Copyright 2022 The Backstage Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
export { TemplateEditorPage } from './TemplateEditorPage';
+1
View File
@@ -7758,6 +7758,7 @@ __metadata:
"@rjsf/core": ^3.2.1
"@rjsf/material-ui": ^3.2.1
"@rjsf/utils": 5.1.0
"@rjsf/validator-ajv8": 5.1.0
"@testing-library/jest-dom": ^5.10.1
"@testing-library/react": ^12.1.3
"@testing-library/react-hooks": ^8.0.0