Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
---
'@red-hat-developer-hub/backstage-plugin-orchestrator-form-react': patch
'@red-hat-developer-hub/backstage-plugin-orchestrator-form-widgets': patch
---

Enable backward navigation in multi-step workflow forms by clicking completed stepper steps, while keeping the current and future steps display-only.
Original file line number Diff line number Diff line change
Expand Up @@ -16,12 +16,14 @@

import Button from '@mui/material/Button';
import Step from '@mui/material/Step';
import StepButton from '@mui/material/StepButton';
import StepLabel from '@mui/material/StepLabel';
import Stepper from '@mui/material/Stepper';
import Typography from '@mui/material/Typography';
import { makeStyles } from 'tss-react/mui';

import { useTranslation } from '../hooks/useTranslation';
import { isBackwardStepNavigable } from '../utils/isBackwardStepNavigable';
import { useStepperContext } from '../utils/StepperContext';
import SubmitButton from './SubmitButton';

Expand All @@ -45,6 +47,10 @@ const useStyles = makeStyles()(theme => ({
formWrapper: {
padding: theme.spacing(2),
},
stepper: {
overflowX: 'auto',
overflowY: 'hidden',
},
}));

export type OrchestratorFormStep = {
Expand All @@ -60,7 +66,7 @@ const OrchestratorFormStepper = ({
}) => {
const { t } = useTranslation();
const { classes } = useStyles();
const { activeStep, reviewStep } = useStepperContext();
const { activeStep, goToStep, reviewStep } = useStepperContext();
const stepsWithReview = [
...steps,
{ content: reviewStep, title: t('common.review'), key: 'review' },
Expand All @@ -71,22 +77,37 @@ const OrchestratorFormStepper = ({
<Stepper
activeStep={activeStep}
variant="elevation"
style={{ overflowX: 'auto' }}
className={classes.stepper}
alternativeLabel
>
{stepsWithReview?.map((step, index) => (
<Step key={step.key} className={classes.step}>
<StepLabel
aria-label={`Step ${index + 1} ${step.title}`}
aria-disabled="false"
tabIndex={0}
{stepsWithReview?.map((step, index) => {
const canNavigateBack = isBackwardStepNavigable(index, activeStep);
const stepLabel = (
<Typography variant="h6" component="h2">
{step.title}
</Typography>
);
const ariaLabel = `Step ${index + 1} ${step.title}`;

return (
<Step
key={step.key}
className={classes.step}
completed={canNavigateBack}
>
<Typography variant="h6" component="h2">
{step.title}
</Typography>
</StepLabel>
</Step>
))}
{canNavigateBack ? (
<StepButton
onClick={() => goToStep(index)}
aria-label={ariaLabel}
>
{stepLabel}
</StepButton>
) : (
<StepLabel aria-label={ariaLabel}>{stepLabel}</StepLabel>
)}
</Step>
);
})}
</Stepper>
<div className={classes.formWrapper}>
{stepsWithReview[activeStep].content}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@
* limitations under the License.
*/

import { useMemo, useState } from 'react';
import { useEffect, useMemo, useState } from 'react';

import { ErrorPanel } from '@backstage/core-components';
import { JsonObject } from '@backstage/types';
Expand All @@ -38,6 +38,7 @@ import {
rjsfIdToFieldPath,
} from '../utils/clearExtraErrorAtPath';
import { getActiveStepKey } from '../utils/getSortedStepEntries';
import { normalizeErrorSchema } from '../utils/resolveStepErrorSchema';
import { useStepperContext } from '../utils/StepperContext';
import { toRootExtraErrors } from '../utils/toRootExtraErrors';
import useValidator from '../utils/useValidator';
Expand All @@ -58,12 +59,27 @@ const FormComponent = (decoratorProps: FormDecoratorProps) => {
>();
const numStepsInMultiStepSchema = formContext?.numStepsInMultiStepSchema;
const isMultiStep = numStepsInMultiStepSchema !== undefined;
const { handleNext, activeStep, handleValidateStarted, handleValidateEnded } =
useStepperContext();
const {
handleNext,
activeStep,
handleValidateStarted,
handleValidateEnded,
clearFormErrorsRef,
} = useStepperContext();
const [validationError, setValidationError] = useState<Error | undefined>();
const validator = useValidator(isMultiStep);
const { t } = useTranslation();

useEffect(() => {
clearFormErrorsRef.current = () => {
setExtraErrors(undefined);
setValidationError(undefined);
};
return () => {
clearFormErrorsRef.current = undefined;
};
}, [clearFormErrorsRef]);

if (!formContext) {
return <div>{t('formDecorator.error')}</div>;
}
Expand Down Expand Up @@ -107,7 +123,9 @@ const FormComponent = (decoratorProps: FormDecoratorProps) => {
extraErrorsUiSchema,
);

setExtraErrors(toRootExtraErrors(activeKey, _extraErrors));
setExtraErrors(
normalizeErrorSchema(toRootExtraErrors(activeKey, _extraErrors)),
);
} catch (err) {
_validationError = err as Error;
} finally {
Expand Down Expand Up @@ -166,7 +184,7 @@ const FormComponent = (decoratorProps: FormDecoratorProps) => {
formData={formData}
formContext={formContext}
noHtml5Validate
extraErrors={extraErrors}
extraErrors={normalizeErrorSchema(extraErrors)}
onSubmit={e => onSubmit(e.formData || {})}
onChange={onChange}
>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,8 @@ import type { JSONSchema7 } from 'json-schema';

import { useTranslation } from '../hooks/useTranslation';
import { getSortedStepEntries } from '../utils/getSortedStepEntries';
import { resolveStepErrorSchema } from '../utils/resolveStepErrorSchema';
import { useStepperContext } from '../utils/StepperContext';
import OrchestratorFormStepper, {
OrchestratorFormStep,
OrchestratorFormToolbar,
Expand All @@ -39,6 +41,7 @@ const StepperObjectField = ({
...props
}: FieldProps<JsonObject, JSONSchema7>) => {
const { t } = useTranslation();
const { activeStep } = useStepperContext();

const sortedStepEntries = useMemo(
() => getSortedStepEntries(schema, formData),
Expand All @@ -48,6 +51,8 @@ const StepperObjectField = ({
throw new Error(t('stepperObjectField.error'));
}

const activeStepKey = sortedStepEntries[activeStep]?.[0];

const steps = sortedStepEntries.reduce<OrchestratorFormStep[]>(
(prev, [key, subSchema]) => {
if (typeof subSchema === 'boolean') {
Expand Down Expand Up @@ -75,7 +80,11 @@ const StepperObjectField = ({
ObjectField: ObjectField, // undo override of objectfield
},
}}
errorSchema={errorSchema?.[key] as ErrorSchema<JsonObject>}
errorSchema={resolveStepErrorSchema(
errorSchema as ErrorSchema<JsonObject>,
key,
activeStepKey,
)}
/>
<OrchestratorFormToolbar />
</>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,14 +14,25 @@
* limitations under the License.
*/

import { createContext, ReactNode, useContext, useMemo, useState } from 'react';
import {
createContext,
MutableRefObject,
ReactNode,
useContext,
useMemo,
useRef,
useState,
} from 'react';

import { TranslationFunction } from '../hooks/useTranslation';
import { isBackwardStepNavigable } from './isBackwardStepNavigable';

export type StepperContext = {
activeStep: number;
handleNext: () => void;
handleBack: () => void;
goToStep: (step: number) => void;
clearFormErrorsRef: MutableRefObject<(() => void) | undefined>;
reviewStep: ReactNode;
isValidating: boolean;
handleValidateStarted: () => void;
Expand Down Expand Up @@ -54,14 +65,30 @@ export const StepperContextProvider = ({
const [activeStep, setActiveStep] = useState<number>(0);
const [isValidating, setIsValidating] = useState<boolean>(false);
const [fetchingCount, setFetchingCount] = useState<number>(0);
const clearFormErrorsRef = useRef<(() => void) | undefined>();

const contextData = useMemo(() => {
const clearFormErrors = () => clearFormErrorsRef.current?.();

return {
activeStep,
clearFormErrorsRef,
handleNext: () => {
setActiveStep(curActiveStep => curActiveStep + 1);
},
handleBack: () => setActiveStep(curActiveStep => curActiveStep - 1),
handleBack: () => {
clearFormErrors();
setActiveStep(curActiveStep => curActiveStep - 1);
},
goToStep: (step: number) => {
setActiveStep(curActiveStep => {
if (!isBackwardStepNavigable(step, curActiveStep)) {
return curActiveStep;
}
clearFormErrors();
return step;
});
},
reviewStep,
isValidating,
handleValidateStarted: () => setIsValidating(true),
Expand All @@ -80,6 +107,7 @@ export const StepperContextProvider = ({
setIsValidating,
fetchingCount,
setFetchingCount,
clearFormErrorsRef,
]);
return <context.Provider value={contextData}>{children}</context.Provider>;
};
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
/*
* Copyright Red Hat, Inc.
*
* 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 { isBackwardStepNavigable } from './isBackwardStepNavigable';

describe('isBackwardStepNavigable', () => {
it('allows navigating to any step before the active step', () => {
expect(isBackwardStepNavigable(0, 2)).toBe(true);
expect(isBackwardStepNavigable(1, 2)).toBe(true);
});

it('disallows the active step and future steps', () => {
expect(isBackwardStepNavigable(2, 2)).toBe(false);
expect(isBackwardStepNavigable(3, 2)).toBe(false);
});

it('disallows negative step indices', () => {
expect(isBackwardStepNavigable(-1, 2)).toBe(false);
});
});
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
/*
* Copyright Red Hat, Inc.
*
* 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.
*/

/** True when the user may jump to `targetStep` from `activeStep` (backward only). */
export const isBackwardStepNavigable = (
targetStep: number,
activeStep: number,
): boolean => targetStep >= 0 && targetStep < activeStep;
Original file line number Diff line number Diff line change
@@ -0,0 +1,76 @@
/*
* Copyright Red Hat, Inc.
*
* 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 { ERRORS_KEY } from '@rjsf/utils';

import {
isFieldErrorSchema,
normalizeErrorSchema,
resolveStepErrorSchema,
} from './resolveStepErrorSchema';

describe('resolveStepErrorSchema', () => {
it('returns the nested slice when the root error schema is keyed by step', () => {
const stepErrors = { fieldA: { [ERRORS_KEY]: ['required'] } };
const tree = { stepOne: stepErrors };

expect(resolveStepErrorSchema(tree, 'stepOne', 'stepOne')).toStrictEqual(
stepErrors,
);
});

it('returns the root error schema when it is already scoped to the active step', () => {
const slice = { fieldA: { [ERRORS_KEY]: ['required'] } };

expect(resolveStepErrorSchema(slice, 'stepOne', 'stepOne')).toStrictEqual(
slice,
);
});

it('returns undefined for non-active steps without a nested slice', () => {
const slice = { fieldA: { [ERRORS_KEY]: ['required'] } };

expect(resolveStepErrorSchema(slice, 'stepTwo', 'stepOne')).toBeUndefined();
});
});

describe('normalizeErrorSchema', () => {
it('coerces string __errors values to arrays', () => {
expect(normalizeErrorSchema({ [ERRORS_KEY]: 'invalid' } as any)).toEqual({
[ERRORS_KEY]: ['invalid'],
});
});

it('normalizes nested error trees', () => {
expect(
normalizeErrorSchema({
stepOne: { fieldA: { [ERRORS_KEY]: 'required' } },
} as any),
).toEqual({
stepOne: { fieldA: { [ERRORS_KEY]: ['required'] } },
});
});
});

describe('isFieldErrorSchema', () => {
it('detects field-level error objects', () => {
expect(isFieldErrorSchema({ [ERRORS_KEY]: ['msg'] })).toBe(true);
});

it('rejects non-array __errors values', () => {
expect(isFieldErrorSchema({ [ERRORS_KEY]: 'msg' })).toBe(false);
});
});
Loading
Loading