Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

First pass at full-form preview rendering #175

Draft
wants to merge 6 commits into
base: main
Choose a base branch
from
Draft
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
148 changes: 148 additions & 0 deletions src/components/FormPreview.stories.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,148 @@
import {Meta, StoryObj} from '@storybook/react';
import {expect, userEvent, waitFor, within} from '@storybook/test';

import {BuilderContextDecorator} from '@/sb-decorators';

import FormPreview from './FormPreview';

export default {
title: 'Public API/FormPreview (⚠️ UNSTABLE)',
component: FormPreview,
decorators: [BuilderContextDecorator],
parameters: {
modal: {noModal: true},
},
} satisfies Meta<typeof FormPreview>;

type Story = StoryObj<typeof FormPreview>;

export const SingleTextField: Story = {
name: 'Form with text field',
args: {
components: [
{
id: 'oiejwa',
type: 'textfield',
key: 'parent.aTextField',
label: 'A text field',
defaultValue: 'a default value',
},
],
},
play: async ({canvasElement}) => {
const canvas = within(canvasElement);
await userEvent.click(canvas.getByRole('button', {name: 'Edit'}));
await waitFor(async () => {
expect(await canvas.findByRole('dialog')).toBeVisible();
});
},
};

export const FieldSet: Story = {
name: 'Form with fieldset',
args: {
components: [
{
id: 'oiejwa',
type: 'textfield',
key: 'aTextField',
label: 'A text field',
},
{
id: 'wieurq4',
type: 'fieldset',
key: 'aFieldset',
label: 'Fieldset with nested components',
hideHeader: false,
components: [
{
id: 'vr832jc',
type: 'textfield',
key: 'nestedTextfield',
label: 'Nested textfield',
},
{
id: 'vrekjc',
type: 'textfield',
key: 'nestedTextfield2',
label: 'Nested textfield 2',
},
],
},
{
id: 'cols1',
type: 'columns',
key: 'cols1',
columns: [
{
size: 6,
sizeMobile: 4,
components: [
{
id: 'number1',
type: 'number',
key: 'number1',
label: 'Number',
},
],
},
{
size: 3,
sizeMobile: 4,
components: [
{
id: 'email1',
type: 'email',
key: 'email1',
label: 'Email 1',
validateOn: 'blur',
},
{
id: 'email2',
type: 'email',
key: 'email2',
label: 'Email 2',
validateOn: 'blur',
},
],
},
{
size: 3,
sizeMobile: 4,
components: [
{
id: 'content1',
type: 'content',
key: 'content1',
html: '<p>Some free form content</p>',
},
],
},
],
},
{
id: 'editgrid1',
type: 'editgrid',
key: 'editgrid1',
label: 'Contacts',
groupLabel: 'Person',
disableAddingRemovingRows: false,
components: [
{
id: 'editgridNested1',
type: 'textfield',
key: 'editgridNested1',
label: 'Name',
},
{
id: 'editgridNested2',
type: 'phoneNumber',
key: 'editgridNested2',
label: 'Phone number',
inputMask: null,
},
],
},
],
},
};
86 changes: 86 additions & 0 deletions src/components/FormPreview.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,86 @@
import {AnyComponentSchema} from '@open-formulieren/types';
import clsx from 'clsx';
import {Formik} from 'formik';
import {set} from 'lodash';
import {useState} from 'react';
import {FormattedMessage} from 'react-intl';

import ModeToggle from '@/components/ModeToggle';
import {getRegistryEntry} from '@/registry';
import {hasOwnProperty} from '@/types';

import {NestedComponents, PreviewMode} from './previews';

export interface FormPreviewProps {
components: AnyComponentSchema[];
}

/**
* Renders a preview of a Formio form definition.
*
* Pass the formio form configuration as an array of component definitions, and they
* will be rendered in order (and recursively). Preview components get controls for
* editing and some visual feedback about state (such as hidden/visible).
*
* The preview renders in one of two modes: structure or webform:
*
* - structure mode shows the hierarchy and allows you to re-arrange/modify the
* individual components
* - webform mode gives an impression of the resulting form, without any distracting
* controls
*/
const FormPreview: React.FC<FormPreviewProps> = ({components}) => {
const [previewMode, setPreviewMode] = useState<PreviewMode>('structure');

const initialValues: Record<string, unknown> = {};

// TODO: delegate this to the registry so that we can get default values for nested
// components too (basically the equivalent of iter_components)
for (const component of components) {
const entry = getRegistryEntry(component);
const defaultValue = hasOwnProperty(component, 'defaultValue')
? component.defaultValue
: entry.defaultValue ?? '';
set(initialValues, component.key, defaultValue);
}

return (
<div className={clsx('offb-form-preview', `offb-form-preview--${previewMode}`)}>
<ModeToggle<PreviewMode>
name="previewMode"
currentMode={previewMode}
onToggle={mode => setPreviewMode(mode)}
modes={[
{
value: 'structure',
label: (
<FormattedMessage
description="Form 'structure' preview mode"
defaultMessage="Structure"
/>
),
},
{
value: 'webform',
label: (
<FormattedMessage description="Form 'Form' preview mode" defaultMessage="Form" />
),
},
]}
className="offb-form-preview__mode-toggle"
/>

<Formik
enableReinitialize
initialValues={initialValues}
onSubmit={() => {
window.alert("Can't submit a preview form.");
}}
>
<NestedComponents components={components} previewMode={previewMode} />
</Formik>
</div>
);
};

export default FormPreview;
14 changes: 14 additions & 0 deletions src/components/previews/ActionIcon.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
interface ActionIconProps {
icon: string;
label: string;
onClick: (event: React.MouseEvent<HTMLButtonElement>) => void;
}

const ActionIcon: React.FC<ActionIconProps> = ({icon, label, onClick}) => (
<button type="button" onClick={onClick} className="offb-form-preview-action" title={label}>
<i className={`fa fa-fw fa-${icon}`} aria-hidden="true" />
<span className="sr-only">{label}</span>
</button>
);

export default ActionIcon;
34 changes: 34 additions & 0 deletions src/components/previews/NestedComponents.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
import {AnyComponentSchema} from '@open-formulieren/types';

import StructurePreview from './StructurePreview';
import WebformPreview from './WebformPreview';
import {PreviewMode} from './types';

const getRenderComponent = (previewMode: PreviewMode) => {
switch (previewMode) {
case 'structure': {
return StructurePreview;
}
case 'webform': {
return WebformPreview;
}
}
};

interface NestedComponentsProps {
components: AnyComponentSchema[];
previewMode: PreviewMode;
}

const NestedComponents: React.FC<NestedComponentsProps> = ({components, previewMode}) => {
const Component = getRenderComponent(previewMode);
return (
<>
{components.map(component => (
<Component key={component.id} component={component} />
))}
</>
);
};

export default NestedComponents;
109 changes: 109 additions & 0 deletions src/components/previews/StructurePreview.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,109 @@
import {AnyComponentSchema} from '@open-formulieren/types';
import clsx from 'clsx';
import {useState} from 'react';
import {useIntl} from 'react-intl';

import ComponentEditForm from '@/components/ComponentEditForm';
import Modal from '@/components/Modal';
import {getRegistryEntry} from '@/registry';
import {hasOwnProperty} from '@/types';

import ActionIcon from './ActionIcon';
import NestedComponents from './NestedComponents';

const getDefaultSummary = (component: AnyComponentSchema): string => {
if (hasOwnProperty(component, 'label')) {
return String(component.label);
}
return component.id || '-';
};

export interface StructurePreviewProps {
component: AnyComponentSchema;
}

const StructurePreview: React.FC<StructurePreviewProps> = ({component}) => {
const intl = useIntl();
const [editModalOpen, setEditModalOpen] = useState(false);

const {
getSummary = getDefaultSummary,
preview: {structureSubtree: StructureSubtree},
} = getRegistryEntry(component);

const className = clsx(
'offb-form-preview-component',
`offb-form-preview-component--${component.type}`,
{
'offb-form-preview-component--hidden': component.hidden,
}
);

const subtree = StructureSubtree ? (
<StructureSubtree
component={component}
renderSubtree={components => (
<NestedComponents components={components} previewMode="structure" />
)}
/>
) : null;

return (
<div className={className}>
<button className="offb-form-preview-component__drag-handle">
<i
className="fa fa-grip-vertical"
aria-label={intl.formatMessage({
description: 'Accessible label for drag-and-drop handle icon',
defaultMessage: 'Hold to drag',
})}
/>
</button>
<div className="offb-form-preview-component__representation">
<span className="offb-form-preview-component__representation-text">
{getSummary(component)}
</span>
<span className="offb-form-preview-component__component-type">
{/* TODO: add translations for the type values -> grab this from the builderInfo */}
{component.type}
</span>
</div>
<div className="offb-form-preview-component__controls">
<ActionIcon icon="pencil" label="Edit" onClick={() => setEditModalOpen(true)} />
<ActionIcon icon="times" label="Delete" onClick={() => alert('TODO')} />
</div>
{subtree && <div className="offb-form-preview-component__children">{subtree}</div>}

<Modal
isOpen={editModalOpen}
closeModal={() => setEditModalOpen(false)}
className="component-settings"
>
<div className="component-edit-container">
<ComponentEditForm
isNew={false}
component={component}
builderInfo={{
title: 'TODO',
group: 'TODO',
icon: 'todo',
schema: component,
weight: 10,
}}
onCancel={() => setEditModalOpen(false)}
onRemove={() => {
console.log('REMOVE component', component);
setEditModalOpen(false);
}}
onSubmit={() => {
console.log('ALTER component', component);
setEditModalOpen(false);
}}
/>
</div>
</Modal>
</div>
);
};

export default StructurePreview;
Loading
Loading