Skip to content

Line Items ​

A cart where each row validates and saves on its own.

Live exampleRows that save on their own

Saved

Saved
Everything is saved

Change a quantity and save the row, or pick the same product twice to see the error of the rule across rows.

vue
<script setup lang="ts">
import { defineGroup, provideFormNode, useForm } from '@formtree/vue'
import { computed } from 'vue'

import { lineItemsArray } from '../forms/line-items'
import LineItemRow from './line-item-row.vue'

const cartForm = defineGroup({
  children: { lineItems: lineItemsArray },
})

const form = useForm(cartForm, {
  initialValue: {
    lineItems: [
      { id: 101, sku: 'MUG-01', quantity: 2 },
      { id: 102, sku: 'TEE-02', quantity: 1 },
    ],
  },
})

const lineItems = provideFormNode(form.array('lineItems'))

const cartStatus = computed(() => {
  if (lineItems.state.dirty) {
    return 'The cart has unsaved changes'
  }
  return 'Everything is saved'
})

function addItem() {
  lineItems.push({ quantity: 1 })
}
</script>

<template>
  <div class="demo-form">
    <LineItemRow
      v-for="lineItem in lineItems.items"
      :key="lineItem.key"
      :index="lineItem.index"
    />
    <div class="demo-row">
      <button type="button" @click="addItem">Add item</button>
      <span class="demo-hint">{{ cartStatus }}</span>
    </div>
  </div>
</template>
vue
<script setup lang="ts">
import { provideFormNode, useFormNode } from '@formtree/vue'
import { computed } from 'vue'

import NumberField from '../components/number-field.vue'
import SelectField from '../components/select-field.vue'
import { saveLineItem } from '../forms/api'
import { lineItemsArray } from '../forms/line-items'

const props = defineProps<{ index: number }>()

const PRODUCT_OPTIONS = [
  { value: 'MUG-01', label: 'Mug' },
  { value: 'TEE-02', label: 'T-shirt' },
  { value: 'CAP-03', label: 'Cap' },
]

const lineItems = useFormNode(lineItemsArray)
const row = provideFormNode(lineItems.items[props.index]!)

const status = computed(() => {
  if (row.state.submitting) {
    return 'Saving…'
  }
  if (row.state.value.id == undefined) {
    return 'Not saved'
  }
  return row.state.dirty ? 'Unsaved changes' : 'Saved'
})

const save = row.handleSubmit(async item => {
  row.reset({ value: await saveLineItem(item) })
})

function moveUp() {
  lineItems.move(props.index, props.index - 1)
}
</script>

<template>
  <div class="demo-row" style="align-items: flex-start">
    <SelectField name="sku" label="Product" :options="PRODUCT_OPTIONS" />
    <NumberField name="quantity" label="Quantity" />
    <div class="demo-row" style="margin-top: 22px">
      <button type="button" @click="save">Save</button>
      <button type="button" :disabled="index == 0" @click="moveUp">
        Move up
      </button>
      <button type="button" @click="lineItems.remove(index)">Remove</button>
      <span class="demo-hint">{{ status }}</span>
    </div>
  </div>
</template>
ts
import { arrayOf, defineGroup } from '@formtree/core'
import { z } from 'zod'

import { requiredText } from './schemas'

export const lineItemGroup = defineGroup({
  schema: z.object({
    id: z.number().int().positive().optional(),
    sku: requiredText('Product is required'),
    quantity: z.number({ error: 'Quantity is required' }).int().positive({
      error: 'Quantity must be at least 1',
    }),
  }),
})

export const lineItemsArray = arrayOf(lineItemGroup, {
  validate: rows => duplicateProducts(rows),
})

interface LineItemDraft {
  readonly sku?: string
}

function duplicateProducts(rows: ReadonlyArray<LineItemDraft>) {
  const seen = new Set<string>()
  return rows.flatMap((row, index) => {
    if (row.sku == undefined || row.sku == '') {
      return []
    }
    if (seen.has(row.sku)) {
      return [
        {
          path: `${index}.sku`,
          code: 'This product is already in the cart',
          params: { sku: row.sku },
        },
      ]
    }
    seen.add(row.sku)
    return []
  })
}
ts
import { z } from 'zod'

export function requiredText(message: string) {
  return z.string({ error: message }).trim().min(1, { error: message })
}
ts
const LATENCY_MS = 400

const VALID_PROMO_CODES = ['WELCOME10', 'FREESHIP']

export const SHIPPING_COUNTRIES = ['DE', 'NL', 'TR', 'US']

export const ATTRIBUTES = [
  { id: 'country', label: 'Country' },
  { id: 'plan', label: 'Plan' },
  { id: 'device', label: 'Device' },
]

export interface PromoCodeCheck {
  readonly code: string
  readonly cartId: string
}

export interface AddressCheck {
  readonly street: string
  readonly postalCode: string
  readonly country: string
}

export interface LineItemRequest {
  readonly id?: number
  readonly sku: string
  readonly quantity: number
}

export interface SavedLineItem {
  readonly id: number
  readonly sku: string
  readonly quantity: number
}

export interface ContactMessage {
  readonly name: string
  readonly email: string
  readonly message: string
}

let lastLineItemId = 100

export async function checkPromoCode(
  check: PromoCodeCheck,
  signal?: AbortSignal,
): Promise<boolean> {
  await delay(signal)
  return VALID_PROMO_CODES.includes(check.code)
}

export async function verifyAddress(
  address: AddressCheck,
  signal?: AbortSignal,
): Promise<boolean> {
  await delay(signal)
  return /\d/.test(address.street)
}

export async function saveLineItem(
  item: LineItemRequest,
): Promise<SavedLineItem> {
  await delay()
  lastLineItemId += 1
  return {
    id: item.id ?? lastLineItemId,
    sku: item.sku,
    quantity: item.quantity,
  }
}

export async function updatePrice(price: number): Promise<number> {
  await delay()
  return price
}

export async function sendMessage(
  contact: ContactMessage,
): Promise<ContactMessage> {
  await delay()
  return contact
}

function delay(signal?: AbortSignal): Promise<void> {
  return new Promise((resolve, reject) => {
    const timer = setTimeout(resolve, LATENCY_MS)
    signal?.addEventListener('abort', () => {
      clearTimeout(timer)
      reject(signal.reason)
    })
  })
}
vue
<script setup lang="ts">
import { useField } from '@formtree/vue'
import { computed } from 'vue'

const props = defineProps<{
  name: string
  label: string
  placeholder?: string
}>()

const field = useField<number>(() => props.name)

const text = computed({
  get: () => (field.model == undefined ? '' : String(field.model)),
  set: value => {
    field.model = value === '' ? undefined : Number(value)
  },
})
</script>

<template>
  <div class="demo-field">
    <label :for="field.id">
      {{ label }}<span v-if="field.state.required" aria-hidden="true">*</span>
    </label>
    <input
      v-model="text"
      v-bind="field.attrs"
      type="number"
      :placeholder="placeholder"
    />
    <p :id="field.errorId" class="demo-error">{{ field.errorMessage }}</p>
  </div>
</template>
vue
<script setup lang="ts">
import { useField } from '@formtree/vue'

interface SelectOption {
  readonly value: string
  readonly label: string
}

const props = defineProps<{
  name: string
  label: string
  options: ReadonlyArray<SelectOption>
}>()

const field = useField<string>(() => props.name)
</script>

<template>
  <div class="demo-field">
    <label :for="field.id">
      {{ label }}<span v-if="field.state.required" aria-hidden="true">*</span>
    </label>
    <select v-model="field.model" v-bind="field.attrs">
      <option :value="undefined" disabled>Choose…</option>
      <option
        v-for="option in options"
        :key="option.value"
        :value="option.value"
      >
        {{ option.label }}
      </option>
    </select>
    <p :id="field.errorId" class="demo-error">{{ field.errorMessage }}</p>
  </div>
</template>

Released under the MIT License.