Skip to content

Inline Price Editing ​

A table where each price is a form of its own, built from priceField.

Live exampleA field as the root of a form
ProductPrice
Mug
T-shirt
Cap

Change a price and press Enter to save it. Clear it or make it negative to see an error.

vue
<script setup lang="ts">
import PriceCell from './price-cell.vue'

const PRODUCTS = [
  { id: 1, name: 'Mug', price: 12 },
  { id: 2, name: 'T-shirt', price: 24.9 },
  { id: 3, name: 'Cap', price: 18.5 },
]
</script>

<template>
  <table>
    <thead>
      <tr>
        <th>Product</th>
        <th>Price</th>
      </tr>
    </thead>
    <tbody>
      <tr v-for="product in PRODUCTS" :key="product.id">
        <td>{{ product.name }}</td>
        <td><PriceCell :price="product.price" /></td>
      </tr>
    </tbody>
  </table>
</template>
vue
<script setup lang="ts">
import { useField, useForm } from '@formtree/vue'
import { computed } from 'vue'

import { updatePrice } from '../forms/api'
import { priceField } from '../forms/product'

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

const cell = useForm(priceField, { initialValue: props.price })
const price = useField(cell)

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

const saveHint = computed(() => {
  if (cell.state.submitting) {
    return 'Saving…'
  }
  return cell.state.dirty ? 'Press Enter to save' : ''
})

const savePrice = cell.handleSubmit(async newPrice => {
  cell.reset({ value: await updatePrice(newPrice) })
})
</script>

<template>
  <form class="demo-row" novalidate @submit.prevent="savePrice">
    <input
      v-model="text"
      v-bind="price.attrs"
      type="number"
      step="0.1"
      style="width: 110px"
    />
    <span class="demo-hint">{{ saveHint }}</span>
    <span :id="price.errorId" class="demo-error">
      {{ price.errorMessage }}
    </span>
  </form>
</template>
ts
import { defineField } from '@formtree/core'
import { z } from 'zod'

export const priceField = defineField({
  schema: z.number({ error: 'Price is required' }).positive({
    error: 'Price must be positive',
  }),
})
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)
    })
  })
}

Released under the MIT License.