keep only Workflow component and move it into scaffolder-react

Signed-off-by: Paul Cowan <paul.cowan@cutting.scot>
This commit is contained in:
Paul Cowan
2023-01-12 15:17:10 +00:00
parent f19d51fa4d
commit d6be4ae291
11 changed files with 35 additions and 293 deletions
+1
View File
@@ -57,6 +57,7 @@
"json-schema": "^0.4.0",
"json-schema-library": "^7.3.9",
"lodash": "^4.17.21",
"react-use": "^17.2.4",
"qs": "^6.9.4",
"zen-observable": "^0.10.0",
"zod": "~3.18.0",
@@ -21,20 +21,17 @@ import {
Progress,
} from '@backstage/core-components';
import { stringifyEntityRef } from '@backstage/catalog-model';
import { useTemplateParameterSchema } from '../TemplateWizardPage/TemplateWizardPage';
import type { ErrorTransformer } from '@rjsf/utils';
import type { JsonValue } from '@backstage/types';
import { makeStyles } from '@material-ui/core';
import { BackstageTheme } from '@backstage/theme';
import { errorApiRef, useApi } from '@backstage/core-plugin-api';
import {
ReviewState,
type ReviewStateProps,
SecretsContextProvider,
Stepper,
type NextFieldExtensionOptions,
} from '@backstage/plugin-scaffolder-react';
import { type FormProps } from '@backstage/plugin-scaffolder-react';
import { type NextFieldExtensionOptions } from '../../extensions/types';
import { type FormProps } from '../../types';
import { ReviewState, ReviewStateProps } from '../ReviewState/ReviewState';
import { useTemplateParameterSchema } from '../../hooks/useTemplateParameterSchema';
import { Stepper } from '../Stepper/Stepper';
import { SecretsContextProvider } from '../../../secrets/SecretsContext';
const useStyles = makeStyles<BackstageTheme>(() => ({
markdown: {
@@ -65,6 +62,9 @@ export interface WorkflowProps {
ReviewStateWrapper?: (props: ReviewStateProps) => JSX.Element;
}
/**
* @alpha
*/
export const Workflow = ({
ReviewStateWrapper = ReviewState,
FormProps = {},
@@ -122,6 +122,9 @@ export const Workflow = ({
);
};
/**
* @alpha
*/
export const EmbeddableWorkflow = (props: WorkflowProps) => (
<SecretsContextProvider>
<Workflow {...props} />
@@ -13,4 +13,4 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
export { EmbeddableWorkflow, type WorkflowProps } from './Workflow';
export { Workflow, EmbeddableWorkflow, type WorkflowProps } from './Workflow';
@@ -17,3 +17,4 @@ export * from './Stepper';
export * from './TemplateCard';
export * from './ReviewState';
export * from './TemplateGroup';
export * from './Workflow';
@@ -18,3 +18,4 @@ export {
useTemplateSchema,
type ParsedTemplateSchema,
} from './useTemplateSchema';
export { useTemplateParameterSchema } from './useTemplateParameterSchema';
@@ -1,5 +1,7 @@
import { useApi } from '@backstage/core-plugin-api';
/*
* Copyright 2022 The Backstage Authors
* Copyright 2023 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.
@@ -13,7 +15,18 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
export {
EmbeddedScaffolderWorkflow,
type EmbeddedScaffolderWorkflowProps,
} from './EmbeddedScaffolderWorkflow';
import useAsync from 'react-use/lib/useAsync';
import { scaffolderApiRef } from '../../api/ref';
/**
* @alpha
*/
export const useTemplateParameterSchema = (templateRef: string) => {
const scaffolderApi = useApi(scaffolderApiRef);
const { value, loading, error } = useAsync(
() => scaffolderApi.getTemplateParameterSchema(templateRef),
[scaffolderApi, templateRef],
);
return { manifest: value, loading, error };
};
-5
View File
@@ -45,11 +45,6 @@ export * from './deprecated';
/** next exports */
export { NextScaffolderPage } from './plugin';
export {
EmbeddedScaffolderWorkflow,
type EmbeddedScaffolderWorkflowProps,
type WorkflowProps,
} from './next';
export {
nextRouteRef,
nextScaffolderTaskRouteRef,
@@ -1,149 +0,0 @@
/*
* 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 { ApiProvider } from '@backstage/core-app-api';
import {
MockAnalyticsApi,
renderInTestApp,
TestApiRegistry,
} from '@backstage/test-utils';
import { act, fireEvent } from '@testing-library/react';
import React from 'react';
import { EmbeddedScaffolderWorkflow } from './EmbeddedScaffolderWorkflow';
import {
scaffolderApiRef,
type ScaffolderApi,
} from '@backstage/plugin-scaffolder-react';
import { analyticsApiRef } from '@backstage/core-plugin-api';
const scaffolderApiMock: jest.Mocked<ScaffolderApi> = {
scaffold: jest.fn(),
getTemplateParameterSchema: jest.fn(),
getIntegrationsList: jest.fn(),
getTask: jest.fn(),
streamLogs: jest.fn(),
listActions: jest.fn(),
listTasks: jest.fn(),
};
const analyticsMock = new MockAnalyticsApi();
const apis = TestApiRegistry.from(
[scaffolderApiRef, scaffolderApiMock],
[analyticsApiRef, analyticsMock],
);
describe('<EmbeddedScaffolderWorkflow />', () => {
it('should embed workflow inside another component', async () => {
const onComplete = jest.fn();
const onError = jest.fn();
scaffolderApiMock.scaffold.mockResolvedValue({ taskId: 'xyz' });
scaffolderApiMock.getTemplateParameterSchema.mockResolvedValue({
steps: [
{
title: 'Step 1',
schema: {
properties: {
name: {
type: 'string',
},
},
},
},
],
title: 'React JSON Schema Form Test',
});
const { getByRole, getAllByRole, getByText } = await renderInTestApp(
<ApiProvider apis={apis}>
<EmbeddedScaffolderWorkflow
title="Different title than template"
description={`
## This is markdown
- overriding the template description
`}
onComplete={onComplete}
onError={onError}
namespace="default"
templateName="docs-template"
initialFormState={{
name: 'prefilled-name',
}}
customFieldExtensions={[]}
frontPage={
<>
<h1>Security Insights</h1>
<p>
Security insights actionable advice to improve security posture
of your application
</p>
<p>
You must complete on-boarding process to activate security
insights on this project.
</p>
</>
}
finishPage={
<>
<h1>Congratulations, this application is complete!</h1>
</>
}
ReviewStateWrapper={() => (
<h1>This is a different wrapper for the review page</h1>
)}
/>
</ApiProvider>,
);
// frontPage is rendered
expect(getByRole('heading').innerHTML).toBe('Security Insights');
// move to workflow
await act(async () => {
fireEvent.click(getByRole('button'));
});
// Test template title is overriden
expect(getByRole('heading').innerHTML).toBe(
'Different title than template',
);
expect(getByRole('textbox').innerHTML).toBeDefined();
const input = getByRole('textbox') as HTMLInputElement;
// The initial state of the form can be set
expect(input.value).toBe('prefilled-name');
await act(async () => {
fireEvent.click(getAllByRole('button')[1] as HTMLButtonElement);
});
// Can supply a different Review wrapper
expect(
getByText('This is a different wrapper for the review page'),
).toBeDefined();
await act(async () => {
fireEvent.click(getAllByRole('button')[1] as HTMLButtonElement);
});
// the final page is inserted after the workflow
expect(
getByText('Congratulations, this application is complete!'),
).toBeDefined();
});
});
@@ -1,108 +0,0 @@
/*
* 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, useCallback } from 'react';
import type { ReactNode } from 'react';
import type { JsonValue } from '@backstage/types';
import { EmbeddableWorkflow, type WorkflowProps } from '../Workflow/Workflow';
import { FormProps } from '@backstage/plugin-scaffolder-react';
import { Box, Button } from '@material-ui/core';
/**
* @alpha
*/
export type EmbeddedScaffolderWorkflowProps = Omit<
WorkflowProps,
'onComplete' | 'FormProps'
> & {
customExtensionsElement?: React.ReactNode;
initialFormState?: Record<string, JsonValue>;
onComplete: (values: Record<string, JsonValue>) => Promise<void>;
onError(error: Error | undefined): JSX.Element | null;
FormProps?: FormProps;
frontPage: ReactNode;
finishPage: ReactNode;
} & Partial<Pick<WorkflowProps, 'onComplete'>>;
type Display = 'front' | 'workflow' | 'finish';
type DisplayComponents = Record<Display, JSX.Element>;
type OnCompleteArgs = Parameters<WorkflowProps['onComplete']>[0];
/**
* Allows the EmbeddableWorkflow to be called from outside of a normal scaffolder workflow
* @alpha
*/
export function EmbeddedScaffolderWorkflow({
namespace,
templateName,
frontPage,
finishPage,
onComplete = async (_values: OnCompleteArgs) => void 0,
onError,
title,
description,
ReviewStateWrapper,
initialFormState,
customFieldExtensions,
FormProps: formProps = {},
}: EmbeddedScaffolderWorkflowProps): JSX.Element {
const [display, setDisplay] = useState<Display>('front');
const startTemplate = useCallback(() => setDisplay('workflow'), []);
const onWorkFlowComplete = useCallback(
async (values: OnCompleteArgs) => {
setDisplay('finish');
await onComplete(values);
},
[onComplete],
);
const DisplayElements: DisplayComponents = {
front: (
<Box display="flex" alignItems="center" flexDirection="column">
{frontPage}
<Button variant="contained" onClick={startTemplate}>
SETUP
</Button>
</Box>
),
workflow: (
<EmbeddableWorkflow
title={title}
description={description}
namespace={namespace}
templateName={templateName}
onComplete={onWorkFlowComplete}
onError={onError}
customFieldExtensions={customFieldExtensions}
ReviewStateWrapper={ReviewStateWrapper}
initialFormState={initialFormState}
FormProps={formProps}
/>
),
finish: (
<Box display="flex" alignItems="center" flexDirection="column">
{finishPage}
</Box>
),
};
return <>{DisplayElements[display]}</>;
}
@@ -27,29 +27,18 @@ import {
useTemplateSecrets,
NextFieldExtensionOptions,
} from '@backstage/plugin-scaffolder-react';
import useAsync from 'react-use/lib/useAsync';
import { JsonValue } from '@backstage/types';
import { FormProps } from '@backstage/plugin-scaffolder-react';
import { nextRouteRef } from '../routes';
import { scaffolderTaskRouteRef, selectedTemplateRouteRef } from '../../routes';
import { Header, Page } from '@backstage/core-components';
import { Workflow } from '../Workflow/Workflow';
import { Workflow } from '@backstage/plugin-scaffolder-react';
type TemplateWizardPageProps = {
customFieldExtensions: NextFieldExtensionOptions<any, any>[];
FormProps?: FormProps;
};
export const useTemplateParameterSchema = (templateRef: string) => {
const scaffolderApi = useApi(scaffolderApiRef);
const { value, loading, error } = useAsync(
() => scaffolderApi.getTemplateParameterSchema(templateRef),
[scaffolderApi, templateRef],
);
return { manifest: value, loading, error };
};
export const TemplateWizardPage = (props: TemplateWizardPageProps) => {
const rootRef = useRouteRef(nextRouteRef);
const taskRoute = useRouteRef(scaffolderTaskRouteRef);
-4
View File
@@ -18,7 +18,3 @@ export * from './TemplateListPage';
export * from './TemplateWizardPage';
export * from './types';
export * from './routes';
export * from './Workflow';
export * from './EmbeddedScaffolderWorkflow';
export type { WorkflowProps } from './Workflow';