Skip to content

Segment Builder ​

A segment of users built from conditions and groups of conditions, nested to any depth.

Live exampleA form that contains itself

Users matching

Group

Output

Submit to see the output

Uncheck the device attribute to see every level reject it, or empty a group to see the error of its rule.

vue
<script setup lang="ts">
import type { OutputOf } from '@formtree/vue'

import { provideFormNode, useField, useForm } from '@formtree/vue'
import { computed, ref, shallowRef } from 'vue'

import { ATTRIBUTES } from '../forms/api'
import { MATCH, segmentForm } from '../forms/segment'
import ConditionTree from './condition-tree.vue'

const deviceAvailable = ref(true)

const attributes = computed(() => {
  if (deviceAvailable.value) {
    return ATTRIBUTES
  }
  return ATTRIBUTES.filter(attribute => attribute.id != 'device')
})

const form = useForm(segmentForm, {
  deps: () => ({ attributes: attributes.value }),
  mode: 'all',
  initialValue: {
    name: 'Engaged customers',
    rules: {
      match: MATCH.all,
      conditions: [{ attribute: 'country', operator: 'is', value: 'DE' }],
      groups: [
        {
          match: MATCH.any,
          conditions: [
            { attribute: 'plan', operator: 'is', value: 'pro' },
            { attribute: 'device', operator: 'is', value: 'mobile' },
          ],
          groups: [],
        },
      ],
    },
  },
})

const name = useField(form.field('name'))
provideFormNode(form.group('rules'))

const output = shallowRef<OutputOf<typeof segmentForm>>()
const outputText = computed(() => {
  if (output.value == undefined) {
    return 'Submit to see the output'
  }
  return JSON.stringify(output.value, null, 2)
})

const saveSegment = form.handleSubmit(segment => {
  output.value = segment
})
</script>

<template>
  <div class="demo-columns">
    <form class="demo-form" novalidate @submit.prevent="saveSegment">
      <div class="demo-field">
        <label :for="name.id">Segment name</label>
        <input v-model="name.model" v-bind="name.attrs" autocomplete="off" />
        <p :id="name.errorId" class="demo-error">{{ name.errorMessage }}</p>
      </div>
      <ConditionTree />
      <label class="demo-row">
        <input
          v-model="deviceAvailable"
          type="checkbox"
          style="width: auto"
        />
        The server offers the "device" attribute
      </label>
      <div class="demo-row">
        <button type="submit">Save segment</button>
      </div>
    </form>

    <div class="demo-form">
      <p class="demo-hint">Output</p>
      <pre class="demo-output">{{ outputText }}</pre>
    </div>
  </div>
</template>
vue
<script setup lang="ts">
import { provideFormNode, useFormNode } from '@formtree/vue'

import SelectField from '../components/select-field.vue'
import { conditionTreeGroup, MATCH } from '../forms/segment'
import ConditionRow from './condition-row.vue'

defineOptions({ name: 'ConditionTree' })

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

const MATCH_OPTIONS = [
  { value: MATCH.all, label: 'All of these' },
  { value: MATCH.any, label: 'Any of these' },
]

const parent = useFormNode(conditionTreeGroup)
const tree = props.index == undefined ? parent : provideGroup(props.index)
const conditions = tree.array('conditions')
const groups = tree.array('groups')

function provideGroup(index: number) {
  return provideFormNode(parent.array('groups').items[index]!)
}

function addCondition() {
  conditions.push({})
}

function addGroup() {
  groups.push({ match: MATCH.all })
}
</script>

<template>
  <fieldset class="demo-fieldset">
    <legend>{{ index == undefined ? 'Users matching' : 'Group' }}</legend>
    <SelectField name="match" label="Match" :options="MATCH_OPTIONS" />
    <ConditionRow
      v-for="condition in conditions.items"
      :key="condition.key"
      :index="condition.index"
    />
    <p class="demo-error">{{ conditions.errorMessage }}</p>
    <ConditionTree
      v-for="group in groups.items"
      :key="group.key"
      :index="group.index"
    />
    <div class="demo-row">
      <button type="button" @click="addCondition">Add condition</button>
      <button type="button" @click="addGroup">Add group</button>
      <button
        v-if="index != undefined"
        type="button"
        @click="parent.array('groups').remove(index)"
      >
        Remove group
      </button>
    </div>
  </fieldset>
</template>
vue
<script setup lang="ts">
import { provideFormNode, useFormNode } from '@formtree/vue'

import SelectField from '../components/select-field.vue'
import TextField from '../components/text-field.vue'
import { ATTRIBUTES } from '../forms/api'
import { conditionTreeGroup, OPERATOR } from '../forms/segment'

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

const ATTRIBUTE_OPTIONS = ATTRIBUTES.map(attribute => ({
  value: attribute.id,
  label: attribute.label,
}))
const OPERATOR_OPTIONS = [
  { value: OPERATOR.is, label: 'is' },
  { value: OPERATOR.isNot, label: 'is not' },
]

const conditions = useFormNode(conditionTreeGroup).array('conditions')
provideFormNode(conditions.items[props.index]!)
</script>

<template>
  <div class="demo-row" style="align-items: flex-start">
    <SelectField
      name="attribute"
      label="Attribute"
      :options="ATTRIBUTE_OPTIONS"
    />
    <SelectField
      name="operator"
      label="Operator"
      :options="OPERATOR_OPTIONS"
    />
    <TextField name="value" label="Value" />
    <button
      type="button"
      style="margin-top: 22px"
      @click="conditions.remove(index)"
    >
      Remove
    </button>
  </div>
</template>
ts
import type { GroupDefinition, InputOf } from '@formtree/core'

import { arrayOf, defineGroupWithDeps } from '@formtree/core'
import { z } from 'zod'

import { requiredText } from './schemas'

export const OPERATOR = {
  is: 'is',
  isNot: 'isNot',
} as const

export const MATCH = {
  all: 'all',
  any: 'any',
} as const

export interface AttributeConfig {
  readonly id: string
  readonly label: string
}

export interface AttributeDeps {
  readonly attributes: ReadonlyArray<AttributeConfig>
}

export const conditionGroup = defineGroupWithDeps<AttributeDeps>()({
  schema: ({ deps }) =>
    z.object({
      attribute: z
        .string({ error: 'Choose an attribute' })
        .refine(id => deps.attributes.some(attribute => attribute.id == id), {
          error: 'This attribute is not available',
        }),
      operator: z.enum(OPERATOR, { error: 'Choose an operator' }),
      value: requiredText('Enter a value'),
    }),
})

export interface ConditionTreeInput {
  match: 'all' | 'any'
  conditions: Array<InputOf<typeof conditionGroup>>
  groups: Array<ConditionTreeInput>
}

export const conditionTreeGroup: GroupDefinition<
  ConditionTreeInput,
  ConditionTreeInput,
  AttributeDeps
> = defineGroupWithDeps<AttributeDeps>()({
  schema: z.object({
    match: z.enum(MATCH, { error: 'Choose how the conditions combine' }),
  }),
  children: {
    conditions: arrayOf(conditionGroup),
    groups: arrayOf(() => conditionTreeGroup),
  },
  childDeps: {
    conditions: ({ deps }) => deps,
    groups: ({ deps }) => deps,
  },
  validate: ({ value }) =>
    value.conditions.length + value.groups.length == 0
      ? { path: 'conditions', code: 'Add a condition or a group' }
      : undefined,
})

export const segmentForm = defineGroupWithDeps<AttributeDeps>()({
  schema: z.object({ name: requiredText('Name the segment') }),
  children: { rules: conditionTreeGroup },
  childDeps: {
    rules: ({ deps }) => deps,
  },
})
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'

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>
vue
<script setup lang="ts">
import { useField } from '@formtree/vue'

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

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>
    <input v-model="field.model" v-bind="field.attrs" autocomplete="off" />
    <p :id="field.errorId" class="demo-error">{{ field.errorMessage }}</p>
  </div>
</template>

Released under the MIT License.