Skip to content
Open Cloud

Vuetify ​

Map Vuetify inputs to Formhaus field types through the components prop of FormRenderer from @formhaus/vue.

Open in StackBlitz · Source

Install ​

bash
npm install @formhaus/core @formhaus/vue vuetify

Component map ​

mapControls maps one Vuetify control per field type. Vuetify inputs render their own label and messages, so only the choice groups have a shell:

ts
import type { FieldComponentMap, FieldProps } from '@formhaus/vue';
import { type ControlOption, mapControls } from '@formhaus/vue/controls';
import { h } from 'vue';
import { VCheckbox, VCombobox, VRadio, VRadioGroup, VRating, VSelect, VSwitch, VTextarea, VTextField } from 'vuetify/components';
import FileField from './fields/FileField.vue';
import GroupShell from './fields/GroupShell.vue';
import MatrixRow from './fields/MatrixRow.vue';
import OptionTiles from './fields/OptionTiles.vue';
import { RevealBlock } from './fields/reveal';

const labels = (f: FieldProps) => ({
  label: f.required ? `${f.label} *` : f.label,
  errorMessages: f.error,
  hint: f.helperText,
  persistentHint: !!f.helperText,
  ...(f.maxLength && { counter: f.maxLength, persistentCounter: true }),
});
const legend = (f: FieldProps) => ({ 'aria-labelledby': `${f.id}-legend` });
const unset = (f: FieldProps) => (f.value === '' || f.value == null ? { modelValue: null } : {});
const items = (f: FieldProps, options: ControlOption[]) => ({ ...unset(f), items: options, itemTitle: 'label', itemValue: 'value' });
const radios = (options: ControlOption[]) => () =>
  options.flatMap((option) => [
    h(VRadio, { label: option.label, value: option.value, 'aria-controls': option.reveal?.id }),
    option.reveal ? h(RevealBlock, { reveal: option.reveal }) : [],
  ]);
const cells = (f: FieldProps, options: ControlOption[]) => ({
  inline: true,
  hideDetails: true,
  error: f.invalid,
  'aria-labelledby': `${f.id}-label`,
  'aria-describedby': f.describedBy,
  class: 'matrix-row__group',
  children: () =>
    options.map((option, index) =>
      h(VRadio, {
        value: option.value,
        'aria-label': option.label,
        'data-testid': f.option({ ...option, value: String(option.value) }, index)['data-testid'],
        class: 'matrix-row__cell',
        onBlur: f.blur,
        onFocus: f.focus,
      }),
    ),
});

export const components: FieldComponentMap = {
  ...mapControls({
    shell: { group: GroupShell },
    labels,
    kinds: { multiselect: 'input' },
    freeText: true,
    conditionalReveal: ['radio'],
    matrix: mapControls({ shell: MatrixRow, controls: { radio: { component: VRadioGroup, props: cells } } }).radio,
    controls: {
      input: VTextField,
      textarea: VTextarea,
      select: { component: VSelect, props: items },
      multiselect: { component: VSelect, props: (f, options) => ({ ...items(f, options), multiple: true }) },
      autocomplete: { component: VCombobox, props: (f, options) => ({ ...unset(f), items: options.map((option) => option.label) }) },
      checkbox: { component: VCheckbox, props: () => ({ hideDetails: 'auto' }) },
      switch: { component: VSwitch, props: () => ({ color: 'primary' }) },
      radio: {
        component: VRadioGroup,
        props: (f, options) => ({
          ...legend(f),
          hideDetails: true,
          error: f.invalid,
          children: options.some((option) => option.image) ? () => h(OptionTiles, { f }) : radios(options),
        }),
      },
      scale: {
        component: VRadioGroup,
        props: (f, options) => ({ ...legend(f), inline: true, hideDetails: true, error: f.invalid, children: radios(options) }),
      },
      rating: {
        component: VRating,
        props: (f, options) => ({
          length: options.length,
          color: f.invalid ? 'error' : undefined,
          activeColor: 'amber-darken-2',
          density: 'comfortable',
          hover: true,
        }),
      },
      file: { component: FileField, props: (f, _, { field }) => ({ f, field }) },
    },
  }),
};

Group shell ​

vue
<script setup lang="ts">
import { controlShellProps } from '@formhaus/vue/controls';
import { cloneVNode, useSlots } from 'vue';

const props = defineProps(controlShellProps);
const slots = useSlots();
const controls = () => {
  const nodes = slots.default?.() ?? [];
  return props.field.layout === 'inline' ? nodes.map((node) => cloneVNode(node, { inline: true })) : nodes;
};
</script>

<template>
  <fieldset v-bind="props.rootProps" class="group">
    <legend :id="`${props.f.id}-legend`" class="text-body-1 text-medium-emphasis">
      {{ props.f.label }}<span v-if="props.f.required" aria-hidden="true"> *</span>
    </legend>
    <div :class="{ group__scale: props.field.type === 'scale' }">
      <component :is="node" v-for="(node, index) in controls()" :key="index" />
      <div v-if="props.anchors.some(Boolean)" class="group__anchors text-caption">
        <span v-for="(anchor, index) in props.anchors" :key="index">{{ anchor?.label }}</span>
      </div>
    </div>
    <div v-if="props.f.helperText" :id="props.f.helperId" class="text-caption px-4">{{ props.f.helperText }}</div>
    <div v-if="props.f.error" :id="props.f.errorId" class="text-caption text-error px-4">{{ props.f.error }}</div>
  </fieldset>
</template>

<style scoped>
.group {
  min-width: 0;
  margin: 8px 0 16px;
  padding: 0;
  border: 0;
}

.group__scale {
  width: fit-content;
  max-width: 100%;
}

.group__anchors {
  display: flex;
  justify-content: space-between;
  gap: 16px;
}
</style>

App ​

vue
<script setup>
import { ref } from 'vue';
import { FormRenderer } from '@formhaus/vue';
import { components } from './component-map';
import FormActions from './actions/FormActions.vue';
import StepProgress from './actions/StepProgress.vue';
import ErrorSummary from './actions/ErrorSummary.vue';
import FormSection from './actions/FormSection.vue';
import FormGroup from './actions/FormGroup.vue';
import GroupItem from './actions/GroupItem.vue';
import ConfirmDialog from './actions/ConfirmDialog.vue';
import FormCompletion from './actions/FormCompletion.vue';
import json from './definition.json';

defineProps({ definition: { type: Object, default: () => json } });

const layout = {
  actions: FormActions,
  progress: StepProgress,
  section: FormSection,
  errorSummary: ErrorSummary,
  group: FormGroup,
  groupItem: GroupItem,
  confirmDialog: ConfirmDialog,
};

const submitted = ref(null);

function onSubmit(values) {
  submitted.value = values;
}
</script>

<template>
  <v-app>
    <v-container style="max-width: 632px">
      <FormCompletion v-if="submitted" :definition="definition" :values="submitted" @restart="submitted = null" />
      <FormRenderer v-else :definition="definition" :components="components" :layout="layout" conditional-reveal @submit="onSubmit" />
    </v-container>
  </v-app>
</template>

The option tiles and the matrix row are in src/fields, the layout slots in src/actions.

Server validation ​

The example validates in the browser only. On the server, run validateSubmission() from @formhaus/core/server on the posted values and pass the returned errors to the errors prop. See Server-side validation and Nuxt for a complete server route.