Skip to content

Recursive Forms ​

Defining a Recursive Group ​

A group that contains itself refers to itself through a function in arrayOf, and takes its type from GroupDefinition:

ts
export interface ConditionTreeInput {
  
match
: 'all' | 'any'
conditions
:
Array
<
InputOf
<typeof
conditionGroup
>>
groups
:
Array
<ConditionTreeInput>
} export const
conditionTreeGroup
:
GroupDefinition
<ConditionTreeInput> =
defineGroup
({
schema
:
z
.
object
({
match
:
z
.
enum
(['all', 'any'], {
error
: 'Choose how the conditions combine',
}), }),
children
: {
conditions
:
arrayOf
(
conditionGroup
),
groups
:
arrayOf
(() =>
conditionTreeGroup
),
}, })

The function delays the reference until a form needs the nested level. TypeScript cannot infer the type of a constant that refers to itself, so the interface describes one level and lists itself under groups.

Rules and Data at Every Level ​

Every level runs the same rules, and childDeps passes the dependencies of the group on to its nested groups:

ts
export const 
conditionTreeGroup
:
GroupDefinition
<
ConditionTreeInput, ConditionTreeInput, AttributeDeps > =
defineGroupWithDeps
<AttributeDeps>()({
schema
:
z
.
object
({
match
:
z
.
enum
(['all', 'any'], {
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
,
})

The dependency type is the third argument of GroupDefinition. A condition at any depth is validated against the same attributes, and an empty group at any depth reports its own error.

Rendering a Tree ​

A component that renders one level, and itself for each nested group, renders the whole tree:

condition-tree.vue
vue
<script setup lang="ts">
import { provideFormNode, useFormNode } from '@formtree/vue'
import ConditionRow from './condition-row.vue'
import { conditionTreeGroup } from './forms/segment'

defineOptions({ name: 'ConditionTree' })

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

const parent = useFormNode(conditionTreeGroup)
let tree = parent
if (props.index != undefined) {
  tree = provideFormNode(parent.array('groups').items[props.index]!)
}
const conditions = tree.array('conditions')
const groups = tree.array('groups')
</script>

<template>
  <fieldset>
    <ConditionRow
      v-for="condition in conditions.items"
      :key="condition.key"
      :index="condition.index"
    />
    <ConditionTree
      v-for="group in groups.items"
      :key="group.key"
      :index="group.index"
    />
  </fieldset>
</template>

Each nested level takes its group by index from the level above and provides it. defineOptions names the component, so its template can render it.

condition-tree.tsx
tsx
import { FormNodeProvider, useFormNode, useNodeState } from '@formtree/react'
import { ConditionRow } from './condition-row'
import { conditionTreeGroup } from './forms/segment'

export function ConditionTree({ index }: { index?: number }) {
  const parent = useFormNode(conditionTreeGroup)
  let tree = parent
  if (index != undefined) {
    tree = parent.array('groups').items[index]!
  }
  const conditions = useNodeState(
    tree.array('conditions'),
    node => node.items,
  )
  const groups = useNodeState(tree.array('groups'), node => node.items)

  return (
    <FormNodeProvider node={tree}>
      <fieldset>
        {conditions.map(condition => (
          <ConditionRow key={condition.key} index={condition.index} />
        ))}
        {groups.map(group => (
          <ConditionTree key={group.key} index={group.index} />
        ))}
      </fieldset>
    </FormNodeProvider>
  )
}

Each nested level takes its group by index from the level above and provides it.

condition-tree.ts
ts
import type { 
NodeOf
} from '@formtree/core'
import {
renderConditionRow
} from './condition-row'
import {
conditionTreeGroup
} from './forms/segment'
type
ConditionTree
=
NodeOf
<typeof
conditionTreeGroup
>
export function
renderConditionTree
(
tree
:
ConditionTree
) {
const
fieldset
=
document
.
createElement
('fieldset')
for (const
condition
of
tree
.
array
('conditions').
items
) {
fieldset
.
append
(
renderConditionRow
(
condition
))
} for (const
group
of
tree
.
array
('groups').
items
) {
fieldset
.
append
(
renderConditionTree
(
group
))
} return
fieldset
}

Segment Builder shows the complete builder.

Released under the MIT License.