Skip to content

GhostQueryBuilder specification ​

Important

Status: Approved for 0.5.0. The maintainer approved the public API on 2026-12-04 with the recommended option for each of Q1–Q7; see Approval. The implementation gate lists the work that this approval releases.

Purpose and user problems ​

A team lead triages issues with a filter such as Open AND (High priority OR Overdue). They build it from fields the application defines, apply it to see matching issues, save it, and reopen it later with exactly the same meaning. While they refine the filter, the results of the last applied filter stay on screen.

GhostQueryBuilder is a headless Vue editor for that filter. It edits a tree of rules and groups, validates the tree on Apply, and emits a structured, JSON-serializable expression. The application owns the field schema, executes the expression locally or on a server, shows the results and stores saved filters.

The component solves these problems:

  • Grouped logic. Nested AND/OR groups and NOT on a whole group keep their structure through editing, saving and restoring. A flattened chip row cannot express Open AND (High priority OR Overdue).
  • Draft versus applied. Edits never change the results until Apply succeeds. An incomplete or invalid edit keeps the last applied expression.
  • Schema drift. A saved filter that names a field the application has since retired keeps that rule in place, explains the problem and blocks Apply until the user repairs or removes the rule.
  • Typed values. Choice, yes/no, date, text and number fields offer only compatible operators and values. Missing values, empty text, 0 and false keep distinct meanings.

Non-goals ​

  • Quick-filter chips or a single-row filter bar. A later design can map a chip row onto the same expression.
  • A general row evaluator. GhostVue does not ship a function that runs an expression against records. This spec defines reference semantics so a local matcher and a server translation agree. The executable example contains a small local matcher for its own data only.
  • Fetching and persistence. The component never loads records, sends requests or writes saved filters.
  • Report definitions. Column selection, sorting, grouping, aggregation and result previews stay outside this component.
  • Relative dates (such as "in the last 7 days"), asynchronously loaded choice options, and application-defined operators. A field can still use a custom value editor, for example a person picker that loads its options.
  • Reordering rules or groups by keyboard or drag in the first slice (see Q4). New rules and groups are appended. Restored order is always kept.
  • A themed recipe in @ghostvue/themes in the first slice (see Q6).

Public API ​

Parts and exports ​

The first slice adds these exports to @ghostvue/vue:

ExportKindContract
useGhostQueryBuilderComposableRender-free draft and applied state, tree edits, Apply, restore, reset and clear. See Composable.
GhostQueryBuilderComponentThin unstyled component over the composable: renders the tree, names, issues, focus recovery and announcements.
defineQueryFieldsFunctionIdentity helper that keeps literal field ids, types and option values so expressions and slots narrow by field.
validateQueryExpressionFunctionPure, synchronous parse and validation of unknown input against a field schema. Used by restore, usable on a server.
Public typesTypesField schema, expression, draft, issue, message, slot and result types listed below.

Following the headless pattern in the architecture rules, behavior lives in useGhostQueryBuilder and GhostQueryBuilder is a thin unstyled component built on it. The tree is rendered by the root component. Groups and rules are not separate public components in the first slice. Their DOM is reached through documented data-part hooks, and the value editor is replaceable through the value slot.

Field schema ​

The application owns the schema. A field's id is the stable identifier that saved expressions store. Its label can change without breaking a saved filter.

ts
type GhostQueryFieldType = 'choice' | 'boolean' | 'date' | 'text' | 'number'

interface GhostQueryFieldBase<Id extends string = string> {
  /** Stable identifier stored in expressions. Never reuse a retired id. */
  id: Id
  /** Visible name. May change between releases of the app. */
  label: string
  description?: string
  /** Key passed to the `value` slot so the app can choose a custom editor. */
  editor?: string
  /**
   * Keeps the label for rules in saved filters. A retired field is never
   * offered for a new rule, and a rule that uses it blocks Apply.
   */
  retired?: boolean
  /** Synchronous business validation of a complete value. */
  validate?: (value: unknown, operator: string) => string | null
}

interface GhostQueryChoiceOption<Value extends string = string> {
  /** Non-empty and unique within the field. */
  value: Value
  label: string
  /** Kept for saved filters. Not offered for new values. Blocks Apply. */
  retired?: boolean
}

type GhostQueryPresenceOperator = 'isMissing' | 'isPresent'
type GhostQueryChoiceOperator =
  'is' | 'isNot' | 'isAnyOf' | 'isNoneOf' | GhostQueryPresenceOperator
type GhostQueryBooleanOperator = 'is' | GhostQueryPresenceOperator
type GhostQueryDateOperator =
  'on' | 'before' | 'after' | 'between' | GhostQueryPresenceOperator
type GhostQueryTextOperator =
  | 'equals'
  | 'notEquals'
  | 'contains'
  | 'notContains'
  | 'startsWith'
  | 'isEmpty'
  | 'isNotEmpty'
  | GhostQueryPresenceOperator
type GhostQueryNumberOperator =
  | 'equals'
  | 'notEquals'
  | 'lessThan'
  | 'lessThanOrEqual'
  | 'greaterThan'
  | 'greaterThanOrEqual'
  | 'between'
  | GhostQueryPresenceOperator

/** Operators that never take a value, whatever the field's options. */
type GhostQueryValuelessOperator =
  GhostQueryPresenceOperator | 'isEmpty' | 'isNotEmpty'

/** Non-empty subset and order of a type's operators. The first is the default. */
type GhostQueryOperatorList<Operator extends string> = readonly [
  Operator,
  ...Operator[],
]

type GhostQueryField =
  | (GhostQueryFieldBase & {
      type: 'choice'
      options: readonly GhostQueryChoiceOption[]
      operators?: GhostQueryOperatorList<GhostQueryChoiceOperator>
    })
  | (GhostQueryFieldBase & {
      type: 'boolean'
      operators?: GhostQueryOperatorList<GhostQueryBooleanOperator>
    })
  | (GhostQueryFieldBase & {
      type: 'date'
      min?: string
      max?: string
      operators?: GhostQueryOperatorList<GhostQueryDateOperator>
    })
  | (GhostQueryFieldBase & {
      type: 'text'
      operators?: GhostQueryOperatorList<GhostQueryTextOperator>
    })
  | (GhostQueryFieldBase & {
      type: 'number'
      min?: number
      max?: number
      step?: number
      operators?: GhostQueryOperatorList<GhostQueryNumberOperator>
    })

An omitted operators list means every operator of the type, in the order of the operator table. The tuple type rejects an empty list and any operator of another type at compile time. Because schemas can also come from untyped sources, the same rules hold at runtime: unknown and repeated entries are dropped with a development warning, and a list with no valid operator left makes the field unusable. Such a field is not offered for new rules, and a rule that uses it gets a blocking field-misconfigured issue. A restored rule whose operator belongs to the type but is excluded by the field's list gets operator-incompatible.

defineQueryFields follows the precedent of defineDataTableColumns. It returns its argument unchanged and preserves literal types:

ts
const fields = defineQueryFields([
  {
    id: 'status',
    label: 'Status',
    type: 'choice',
    options: [
      { value: 'open', label: 'Open' },
      { value: 'closed', label: 'Closed' },
    ],
  },
  {
    id: 'priority',
    label: 'Priority',
    type: 'choice',
    options: [
      { value: 'low', label: 'Low' },
      { value: 'normal', label: 'Normal' },
      { value: 'high', label: 'High' },
    ],
  },
  { id: 'overdue', label: 'Overdue', type: 'boolean' },
  { id: 'archived', label: 'Archived', type: 'boolean' },
  { id: 'assignee', label: 'Assignee', type: 'text', editor: 'person' },
  { id: 'estimate', label: 'Estimate (points)', type: 'number', min: 0 },
  { id: 'dueDate', label: 'Due date', type: 'date' },
  {
    id: 'severity',
    label: 'Severity',
    type: 'choice',
    retired: true,
    options: [],
  },
] as const)

Option values must be non-empty and unique within a choice field, as in GhostSelect, which does not support '' as an option value. Untyped schemas are checked at runtime: a choice field with a repeated or empty option value is a configuration error with a development warning that names the value. The field is not offered for new rules, and every rule that uses it gets a blocking field-misconfigured issue, so a repeated value can never be stored ambiguously and no value is stored that the editor cannot select.

A choice field that is not retired must have at least one option. Its value-taking operators could never be satisfied otherwise. A choice field with an empty options list is a configuration error with a development warning, handled like a repeated option value: it is not offered for new rules, and every rule that uses it gets a blocking field-misconfigured issue. The types agree: such a field's option value type is never, and GhostQueryRule has no member for it, so no rule on it compiles, not even a presence rule. A retired choice field may have an empty options list, as severity does above, because it is never offered and its rules already report field-retired.

A number field's step, when given, must be a finite number greater than 0, as GhostNumberInput requires. A step of 0, a negative number, NaN or an infinity is a configuration error with a development warning that names the field, handled the same way: the field is not offered for new rules, and every rule that uses it gets a blocking field-misconfigured issue. The editor never substitutes another step.

A date field's min and max, when given, must be real ISO calendar dates 'YYYY-MM-DD' (so '2026-02-30' is rejected), and min must not be later than max. GhostDatePicker treats reversed bounds as a configuration error, and the builder converts bounds with parseDate. A bound that is not such a date, or a min after max, is a configuration error with a development warning that names the field, handled the same way: the field is not offered for new rules, and every rule that uses it gets a blocking field-misconfigured issue.

Field ids must be unique, non-empty strings. Duplicate field ids are a configuration error: a development warning names the id, no field with that id is offered for new rules, and every rule that uses the id gets a blocking field-duplicate issue on its field control.

Operators and values ​

Operators are fixed per field type. A field's operators list can restrict or reorder them but cannot add new ones. All values are JSON-native so a saved expression round-trips through JSON.stringify and JSON.parse.

Field typeOperatorsValue
choiceis, isNotOne option value (string)
choiceisAnyOf, isNoneOfNon-empty array of option values, de-duplicated on Apply
booleanistrue or false
dateon, before, afterISO calendar date 'YYYY-MM-DD'
datebetween{ start: 'YYYY-MM-DD', end: 'YYYY-MM-DD' }, inclusive
textequals, notEquals, contains, notContains, startsWithNon-empty string, stored exactly as typed
textisEmpty, isNotEmptyNone. Tests for the empty string ""
numberequals, notEquals, lessThan, lessThanOrEqual, greaterThan, greaterThanOrEqualFinite number. -0 is stored as 0
numberbetween{ min: number, max: number }, inclusive, min <= max
Every typeisMissing, isPresentNone. Tests for an absent or null record value

An operator without a value omits the value key. An expression never uses null as a value: "missing" is an operator, not a value. 0, false and "" are ordinary values (see Missing, empty, zero and false).

The first operator in a field's list is the default for a new rule and after a field change.

Expression ​

ts
type GhostQueryFields = readonly GhostQueryField[]

interface GhostQueryExpression<
  Fields extends GhostQueryFields = GhostQueryFields,
> {
  version: 1
  root: GhostQueryGroup<Fields>
}

interface GhostQueryGroup<Fields extends GhostQueryFields = GhostQueryFields> {
  kind: 'group'
  id: string
  combinator: 'and' | 'or'
  /** NOT on the whole group: matches records the group does not match. */
  not: boolean
  children: readonly (GhostQueryRule<Fields> | GhostQueryGroup<Fields>)[]
}

/** One member per usable field, operator and value shape. Retired and option-less choice fields are excluded. */
type GhostQueryRule<Fields extends GhostQueryFields = GhostQueryFields> =
  GhostQueryRuleForField<Fields[number]>

type GhostQueryRuleForField<F> = F extends GhostQueryField
  ? F extends { retired: true }
    ? never
    : F extends { type: 'choice' } // a choice field with no options is unusable
      ? [GhostQueryOptionValueOf<F>] extends [never]
        ? never
        : GhostQueryRuleForOperator<F, GhostQueryOperatorOf<F>>
      : GhostQueryRuleForOperator<F, GhostQueryOperatorOf<F>>
  : never

type GhostQueryRuleForOperator<
  F extends GhostQueryField,
  Op extends string,
> = Op extends string // distributes over the operator union
  ? Op extends GhostQueryValuelessOperator
    ? { kind: 'rule'; id: string; field: F['id']; operator: Op }
    : {
        kind: 'rule'
        id: string
        field: F['id']
        operator: Op
        value: GhostQueryValueOf<F, Op>
      }
  : never

interface GhostQueryOperatorsByType {
  choice: GhostQueryChoiceOperator
  boolean: GhostQueryBooleanOperator
  date: GhostQueryDateOperator
  text: GhostQueryTextOperator
  number: GhostQueryNumberOperator
}

/** The field's own `operators` list when given, else every operator of its type. */
type GhostQueryOperatorOf<F extends GhostQueryField> = F extends {
  operators: GhostQueryOperatorList<infer Op>
}
  ? Op
  : GhostQueryOperatorsByType[F['type']]

/** Complete value for one operator; `never` for valueless operators. */
type GhostQueryValueOf<
  F extends GhostQueryField,
  Op extends string,
> = Op extends GhostQueryValuelessOperator
  ? never
  : F extends { type: 'choice' }
    ? Op extends 'isAnyOf' | 'isNoneOf'
      ? readonly [GhostQueryOptionValueOf<F>, ...GhostQueryOptionValueOf<F>[]]
      : GhostQueryOptionValueOf<F>
    : F extends { type: 'boolean' }
      ? boolean
      : F extends { type: 'date' }
        ? Op extends 'between'
          ? { start: string; end: string }
          : string
        : F extends { type: 'number' }
          ? Op extends 'between'
            ? { min: number; max: number }
            : number
          : F extends { type: 'text' }
            ? string
            : never

/** The schema-wide value union, used where no field is known. */
type GhostQueryValue =
  | string
  | number
  | boolean
  | readonly string[]
  | { start: string; end: string }
  | { min: number; max: number }

GhostQueryExpression<Fields> is recursive: groups hold rules and groups typed by the same Fields. Each rule is a union member per usable field and operator, so rule.field === 'priority' narrows operator to the choice operators, and operator === 'is' then narrows value to 'low' | 'normal' | 'high' (isAnyOf to a non-empty array of them, and a presence operator to no value key). Whether a rule has a value key depends only on its operator, never on the inferred value type: every operator outside GhostQueryValuelessOperator requires value. With the default type argument, the same types describe any schema with field: string. The applied expression always has this narrowed type because Apply validated it. The draft uses the wider GhostQueryDraft type so that restored and half-edited rules are preserved for repair.

Rule and group ids are stable strings. They survive save and restore and identify which rule an issue belongs to. Ids must be unique within one expression. New nodes receive ids from the createId prop.

Draft ​

The draft mirrors the expression node for node, with the same kind, id, combinator, not and child order. Only rules are wider:

ts
interface GhostQueryDraft {
  version: 1
  root: GhostQueryDraftGroup
}

interface GhostQueryDraftGroup {
  kind: 'group'
  id: string
  combinator: 'and' | 'or'
  not: boolean
  /** Document order. An empty nested group is a `group-empty` issue. */
  children: readonly GhostQueryDraftNode[]
}

interface GhostQueryDraftRule {
  kind: 'rule'
  id: string
  /** `null` until the user picks a field. May name an unknown field. */
  field: string | null
  /** `null` until a field is picked. May be incompatible with the field. */
  operator: string | null
  /** Absent when no value has been entered or the operator takes none. */
  value?: GhostQueryDraftValue
}

type GhostQueryDraftNode = GhostQueryDraftGroup | GhostQueryDraftRule

type GhostQueryDraftValue =
  | GhostQueryValue
  | GhostQueryPartialDateRange
  | GhostQueryPartialNumberRange
  | GhostQueryStoredValue

/** Date `between` with one or both ends still empty. */
interface GhostQueryPartialDateRange {
  start: string | null
  end: string | null
}

/** Number `between` with one or both ends still empty. */
interface GhostQueryPartialNumberRange {
  min: number | null
  max: number | null
}

/** A restored value that fits no shape for its field, kept verbatim for display. */
interface GhostQueryStoredValue {
  kind: 'stored'
  raw: unknown
}

type GhostQueryFieldById<
  Fields extends readonly GhostQueryField[],
  Id extends string,
> = Extract<Fields[number], { id: Id }>

/** Literal option values of a choice field, from `defineQueryFields`; `never` for `options: []`. */
type GhostQueryOptionValueOf<F> = F extends {
  type: 'choice'
  options: infer Options extends readonly GhostQueryChoiceOption[]
}
  ? Options[number]['value']
  : never

/** Values an editor may propose for one field, for any of its operators. */
type GhostQueryDraftValueForField<F extends GhostQueryField> = F extends {
  type: 'choice'
}
  ? GhostQueryOptionValueOf<F> | readonly GhostQueryOptionValueOf<F>[]
  : F extends { type: 'boolean' }
    ? boolean
    : F extends { type: 'date' }
      ? string | GhostQueryPartialDateRange
      : F extends { type: 'number' }
        ? number | GhostQueryPartialNumberRange
        : F extends { type: 'text' }
          ? string
          : never

type GhostQueryDraftValueFor<
  Fields extends readonly GhostQueryField[],
  Id extends string,
> = GhostQueryDraftValueForField<GhostQueryFieldById<Fields, Id>>

/** What a rule on this field can hold: proposals plus a restored stored value. */
type GhostQueryDraftValueReadFor<
  Fields extends readonly GhostQueryField[],
  Id extends string,
> = GhostQueryDraftValueFor<Fields, Id> | GhostQueryStoredValue

GhostQueryDraftValueFor is keyed by field, not operator, because an operator change keeps the editor mounted. Which member an operator uses follows the operator table:

Field typeOperatorsDraft value an editor proposes
choiceis, isNotOne literal option value
choiceisAnyOf, isNoneOfArray of literal option values; [] while empty
booleanistrue or false
dateon, before, after'YYYY-MM-DD'
datebetweenGhostQueryPartialDateRange; complete when both ends are strings
numbercomparisonsFinite number
numberbetweenGhostQueryPartialNumberRange; complete when both ends are set
textcomparisonsNon-empty string
AnyisMissing, isPresent, isEmpty, isNotEmptyNone: the value slot does not render and value is absent

A value of the field's type that does not fit the current operator (an array for is, a single date for between) is kept and reports value-invalid on Apply. Editors never propose GhostQueryStoredValue; it appears only after restore and is replaced by the first setValue.

Traverse the draft recursively from root, visiting children in order; that order is the document order used for issues and focus. Every edit produces a new draft object, so consumers can watch it by reference. Each draft is deeply frozen when created. Nodes an edit does not touch are shared with the previous draft, so an edit freezes only the nodes it creates, and setValue stores a frozen copy, never the editor's own object. How each incomplete state is represented, and what Apply and validateQueryExpression report for it:

Draft stateRepresentationIssue on Apply
New rule, no field yetfield: null, operator: null, no valuefield-required
Field picked, operator not chosenNever: picking a field sets its default operator—
Unknown or retired fieldfield: 'severity', stored operator and value keptfield-unknown / field-retired
Operator not valid for the fieldoperator: 'contains' kept as storedoperator-incompatible
Empty text, number, date or choiceNo value key (cleared inputs remove it)value-required
Empty multi-choicevalue: []value-required
Half-entered date rangevalue: { start: '2026-12-01', end: null }value-incomplete
Half-entered number rangevalue: { min: 1, max: null }value-incomplete
Restored value of the wrong shapevalue: { kind: 'stored', raw: 'abc' }value-invalid
Editor holding uncommitted textNot in the draft; tracked per rule from setPendingvalue-pending

Clearing a number input removes value rather than storing 0, and an empty text input removes value rather than storing "", which keeps missing, empty, zero and false distinct. A restored "" on a text comparison stays as stored and reports value-required. Pending editor state is kept outside the draft so it never affects dirty or a saved filter. A valid draft converts to the expression one to one: field and operator become non-null strings, value keeps only complete shapes, and nothing else changes.

Validation ​

ts
function validateQueryExpression<
  const Fields extends readonly GhostQueryField[],
>(input: unknown, fields: Fields): GhostQueryValidationResult<Fields>

type GhostQueryMalformedReason =
  'malformed' | 'unsupported-version' | 'duplicate-id'

type GhostQueryValidationResult<Fields extends GhostQueryFields> =
  | {
      status: 'valid'
      /** Frozen, normalized expression ready to execute or apply. */
      expression: GhostQueryDeepReadonly<GhostQueryExpression<Fields>>
      draft: GhostQueryDeepReadonly<GhostQueryDraft>
      issues: readonly []
    }
  | {
      status: 'needs-repair'
      /** Every node in its original position, for display and repair. */
      draft: GhostQueryDeepReadonly<GhostQueryDraft>
      issues: readonly [GhostQueryIssue, ...GhostQueryIssue[]]
    }
  | { status: 'malformed'; reason: GhostQueryMalformedReason }

The function is pure and synchronous, never throws for any input, and never mutates input or fields. It runs in two stages:

  1. Structure. Input that is not a version 1 expression (not an object, a root that is not a group, a node without kind or id, a non-array children, a combinator other than and/or, a non-boolean not, or a field or operator that is not a string) returns malformed. A newer version returns unsupported-version; repeated node ids return duplicate-id. No draft is produced.
  2. Meaning. A structurally sound expression is checked against fields with the same rules as Apply, except value-pending, which only a mounted editor can report. Any issue returns needs-repair with the draft and a non-empty issue list in document order. Otherwise the result is valid with both the normalized expression and its draft.

restore and defaultExpression use this function. A server or loader can call it to decide whether a saved filter is executable before rendering.

Props and configuration ​

PropTypeDefaultContract
fieldsreadonly GhostQueryField[]requiredConsumer-owned schema. Reactive: a change revalidates the draft and never changes the applied expression.
defaultExpressionunknownnullInitial draft, read once at setup through validateQueryExpression. Malformed input starts an empty draft and reports a development warning.
applyDefaultbooleanfalseWhen the default expression has no blocking issue, it is also the initial applied expression at revision 1. No apply event is emitted for it.
createId(kind: 'rule' | 'group') => stringinstance counterMints ids for nodes the user adds. Never called during setup, so a random or counter id is SSR-safe. The default prefixes a useGhostId value and skips ids already in the draft. A returned duplicate is a development error and is replaced.
maxDepthnumber3Nesting levels the user can create, counting the root as 1. Restored deeper groups are kept and stay editable, but offer no Add group action.
disabledbooleanfalseDisables every control. Programmatic restore, reset, clear and apply still work.
readonlybooleanfalseRenders the draft as static text with no form controls and no add or remove actions (Q7). disabled takes precedence.
messagesPartial<GhostQueryBuilderMessages>English defaultsReactive overrides for every component-owned string. See Messages.

The root requires an accessible name through native aria-label or aria-labelledby, for example the visible heading "Issue filter". A development warning reports a missing name.

v-model contracts ​

There is no v-model in the first slice. The draft is internal state, and the applied expression changes only through Apply. A controlled applied value would let a parent install an expression that never passed validation, which breaks the guarantee that the applied expression is always executable. Apps load a saved filter with restore and read the applied expression from the apply event or the exposed state.

Events, slots, and exposed methods ​

Event. apply(payload: GhostQueryApplyEvent<Fields>) is emitted after every successful Apply, including a programmatic one and an Apply of an unchanged draft (a refresh). The expression is a fresh, frozen, deep copy. revision increases by one for every successful Apply and never decreases for the life of the instance. A failed Apply emits nothing.

Exposed methods and state (template ref). The same members are bound to the actions slot.

MemberTypeContract
apply(options?)(o?: { focus?: boolean }) => GhostQueryApplyResultValidates the draft. Success replaces the applied expression and emits apply. Failure keeps it, shows every issue and, unless focus: false, focuses the first invalid control.
restore(input, options?)(input: unknown, o?: { apply?: boolean }) => GhostQueryRestoreResultReplaces the draft with a parsed expression. With apply: true it then applies without moving focus. Malformed input changes nothing.
reset()() => voidReplaces the draft with the baseline: the applied expression, else the last restored or default input, else an empty root group.
clear()() => voidReplaces the draft with an empty root group, keeping the root id. Does not apply.
draftGhostQueryDeepReadonly<GhostQueryDraft>Current draft. Read-only; edit through the UI or restore.
appliedGhostQueryDeepReadonly<GhostQueryExpression<Fields>> | nullLast applied expression, or null before the first Apply.
revisionnumberRevision of applied; 0 before the first Apply.
dirtybooleantrue when the draft differs from applied (or from an empty root when nothing is applied).
issuesreadonly GhostQueryIssue[]Current blocking issues of the draft, in document order, whether or not they are displayed yet.
appliedIssuesreadonly GhostQueryIssue[]Issues found when applied is revalidated against the current fields. Empty unless a schema change made the applied expression stale. See Schema changes.
ts
/** Recursively read-only view of a frozen draft or expression snapshot. */
type GhostQueryDeepReadonly<T> = T extends object
  ? { readonly [K in keyof T]: GhostQueryDeepReadonly<T[K]> }
  : T

interface GhostQueryApplyEvent<Fields extends GhostQueryFields> {
  expression: GhostQueryDeepReadonly<GhostQueryExpression<Fields>>
  revision: number
}

type GhostQueryApplyResult<Fields extends GhostQueryFields> =
  | {
      ok: true
      expression: GhostQueryDeepReadonly<GhostQueryExpression<Fields>>
      revision: number
    }
  | { ok: false; issues: readonly GhostQueryIssue[] }

/** Mirrors the validation result: `issues` is empty when status was `valid`. */
type GhostQueryRestoreResult =
  | { ok: true; issues: readonly GhostQueryIssue[]; applied: boolean }
  | { ok: false; reason: GhostQueryMalformedReason }

interface GhostQueryIssue {
  nodeId: string
  code: GhostQueryIssueCode
  /** Which control the issue is attached to. */
  target: 'field' | 'operator' | 'value' | 'group'
  message: string
}

type GhostQueryIssueCode =
  | 'field-required'
  | 'field-unknown'
  | 'field-retired'
  | 'field-duplicate'
  | 'field-misconfigured'
  | 'operator-incompatible'
  | 'value-required'
  | 'value-incomplete'
  | 'value-pending'
  | 'value-invalid'
  | 'value-out-of-range'
  | 'range-order'
  | 'option-retired'
  | 'value-rejected'
  | 'group-empty'

Slots.

  • actions binds { apply, reset, clear, applied, revision, dirty, issues, appliedIssues } and renders after the root group, typically the Apply and Reset buttons. The app renders its own Save button, usually here.
  • value replaces the value editor of every rule. See Value editor customization.
  • empty renders inside an empty root group, before its Add rule action. Default content is messages.emptyRoot ("No conditions. All issues match.").

Composable ​

useGhostQueryBuilder(options) holds the behavior. GhostQueryBuilder calls it with its props, passing fields, maxDepth, disabled and readonly as getters so the composable sees their current values, and adds only DOM concerns: names, issue relationships, focus movement and announcements. Consumers who need fully custom markup call the composable and take on those concerns themselves, as the accessibility contract describes.

ts
interface UseGhostQueryBuilderOptions<
  Fields extends readonly GhostQueryField[],
> {
  fields: MaybeRefOrGetter<Fields>
  defaultExpression?: unknown
  applyDefault?: boolean
  createId?: (kind: 'rule' | 'group') => string
  maxDepth?: MaybeRefOrGetter<number>
  /** Default `false`. Edit methods do nothing while `true`. */
  disabled?: MaybeRefOrGetter<boolean>
  /** Default `false`. Edit methods do nothing while `true`. */
  readonly?: MaybeRefOrGetter<boolean>
  onApply?: (event: GhostQueryApplyEvent<Fields>) => void
}

interface UseGhostQueryBuilderReturn<Fields extends GhostQueryFields> {
  draft: Readonly<Ref<GhostQueryDeepReadonly<GhostQueryDraft>>>
  applied: Readonly<
    Ref<GhostQueryDeepReadonly<GhostQueryExpression<Fields>> | null>
  >
  revision: Readonly<Ref<number>>
  dirty: Readonly<Ref<boolean>>
  /** Non-empty when a schema change made `applied` stale. */
  appliedIssues: Readonly<Ref<readonly GhostQueryIssue[]>>
  /** All current blocking issues of the draft. */
  issues: Readonly<Ref<readonly GhostQueryIssue[]>>
  /** Issues to display under the timing rule in the state model. */
  shownIssues: Readonly<Ref<readonly GhostQueryIssue[]>>
  apply(): GhostQueryApplyResult<Fields>
  restore(
    input: unknown,
    options?: { apply?: boolean },
  ): GhostQueryRestoreResult
  reset(): void
  clear(): void
  /** New rule id, or `null` when nothing was inserted. */
  addRule(groupId: string): string | null
  /** New group id, or `null` when nothing was inserted. */
  addGroup(groupId: string): string | null
  removeNode(nodeId: string): void
  setCombinator(groupId: string, combinator: 'and' | 'or'): void
  setNot(groupId: string, not: boolean): void
  setField(ruleId: string, fieldId: string): void
  setOperator(ruleId: string, operator: string): void
  setValue(ruleId: string, value: GhostQueryDraftValue | undefined): void
  setPending(ruleId: string, message: string | null): void
}

Every edit method creates a new draft and never mutates a previous one. draft and applied hold frozen snapshots and are exposed as read-only refs, so neither the ref nor any node in it can be written; edits go through these methods. addRule and addGroup return the new node id, and addGroup adds one empty condition to the new group. They return null and leave the draft unchanged when groupId names no group, when the builder is disabled or read-only, or, for addGroup, when the group is already at maxDepth. While disabled or readonly is true, every edit method (addRule through setPending) leaves the draft unchanged without a warning; apply, restore, reset and clear still work, as the props describe. setField applies the operator and value carry-over described in the retired field walkthrough. Methods on an unknown id do nothing and warn in development. removeNode(draft.root.id) also does nothing and warns in development: the root group is never removed, and clear() is the way to empty it. The composable does not touch the DOM, so apply() here never moves focus; the component's apply adds focus on failure. The composable is SSR-safe and creates no listeners or timers.

Value editor customization ​

The value slot is the supported path for an application-supplied editor. It renders once per rule that has a known field and an operator that takes a value. Its bindings are typed by field:

ts
/** One member per field id, so checking `fieldId` narrows every binding. */
type GhostQueryValueSlotProps<Fields extends readonly GhostQueryField[]> = {
  [Id in Fields[number]['id']]: GhostQueryValueSlotPropsFor<Fields, Id>
}[Fields[number]['id']]

interface GhostQueryValueSlotPropsFor<
  Fields extends readonly GhostQueryField[],
  Id extends string,
> {
  /** Top-level discriminants: TypeScript does not narrow on `field.id`. */
  fieldId: Id
  fieldType: Extract<Fields[number], { id: Id }>['type']
  field: Extract<Fields[number], { id: Id }>
  rule: GhostQueryDeepReadonly<GhostQueryDraftRule>
  /** The rule's operator, which takes a value for this slot to render. */
  operator: string
  /** Current draft value, possibly incomplete, stored or absent. */
  value: GhostQueryDraftValueReadFor<Fields, Id> | undefined
  /** Proposes a new draft value for this field only; `undefined` removes it. Never applies. */
  setValue(value: GhostQueryDraftValueFor<Fields, Id> | undefined): void
  /**
   * Reports text the editor holds but has not committed yet. While set,
   * Apply reports `value-pending` with this message on the rule.
   */
  setPending(message: string | null): void
  /** Bindings for the editor's labelled control(s). */
  controlProps: {
    id: string
    'aria-labelledby': string
    'aria-describedby'?: string
    'aria-invalid'?: 'true'
    disabled: boolean
    readonly: boolean
  }
  /** Renders the built-in editor for this rule. */
  DefaultEditor: Component
}

Checking slot.fieldId (or slot.fieldType) narrows field, value and setValue together, so setValue(123) on a text field fails to compile. A typical slot picks a custom editor by field and otherwise renders the default:

vue
<GhostQueryBuilder :fields="fields" aria-labelledby="filter-heading">
  <template #value="slot">
    <PersonPicker
      v-if="slot.fieldId === 'assignee'"
      v-bind="slot.controlProps"
      :model-value="typeof slot.value === 'string' ? slot.value : ''"
      @update:model-value="slot.setValue"
      @pending="slot.setPending"
    />
    <component :is="slot.DefaultEditor" v-else />
  </template>
</GhostQueryBuilder>

The builder still validates the value against the field type and validate, so a custom editor cannot apply an incompatible value. An editor that keeps unparsed text (for example a half-typed name) must call setPending so Apply cannot silently use the previous value. The editor owns its own keyboard behavior inside its control, and must keep focus inside the rule.

Messages ​

Export GhostQueryBuilderMessages with English defaults, following the message-override pattern of GhostTagsInput. Overrides are read when text is produced, so a locale change updates names and the next announcement. Formatters receive positions and labels and handle plurals.

KeyEnglish default
groupName(path)Group {path} (root: the root's accessible name)
combinatorLabelMatch
combinatorAnd / OrAll conditions (AND) / Any condition (OR)
notLabelNOT: exclude issues that match this group
ruleName(index)Condition {index}
fieldLabel / operatorLabel / valueLabelField / Operator / Value
rangeStart / rangeEndFrom / To
addRule / addGroupAdd condition / Add group
removeRule(index, summary)Remove condition {index}: {summary}
removeGroup(path)Remove group {path}
operator(op, type)is, is not, is any of, is missing, is empty text, and so on
issue(issue, context)See issue messages
announceAppliedFilter applied.
announceBlocked(count)Filter not applied. {count} conditions need attention.
announceRestored(count)Saved filter opened. {count} conditions need attention.
announceAdded / announceRemovedCondition added. / Condition {index} removed.
emptyRootNo conditions. All issues match.

User-facing text says "condition" because filter users rarely say "rule". API names keep rule.

Issue messages ​

CodeAttached toEnglish default
field-requiredfieldChoose a field.
field-unknownfield{fieldId} is no longer available. Choose another field or remove this condition.
field-retiredfield{label} is no longer available. Choose another field or remove this condition.
field-duplicatefield{label} is defined more than once, so it cannot be used. Choose another field or remove this condition.
field-misconfiguredfield{label} is set up incorrectly and cannot be used. Choose another field or remove this condition.
operator-incompatibleoperator{operator} does not work with {label}. Choose another operator.
value-requiredvalueEnter a value. To match an empty value, choose "is empty text" or "is missing".
value-incompletevalueEnter both dates. / Enter both numbers.
value-pendingvalueThe custom editor's message, else: Finish entering this value.
value-invalidvalueEnter a valid {type}.
value-out-of-rangevalueEnter a value between {min} and {max}.
range-ordervalueThe start must be on or before the end.
option-retiredvalue{label} is no longer an option. Choose another value or remove this condition.
value-rejectedvalueThe field's validate message.
group-emptygroupAdd a condition to this group or remove it.

State model ​

The builder holds two independent values:

  • Draft. What the user is editing. It can be incomplete or invalid and can contain unknown fields. It is never emitted on its own.
  • Applied. The last expression that passed validation, with its revision. Only a successful Apply changes it.

Saving is an application action, not a component state. The app reads applied (see Q1) and persists it. Restoring goes through restore.

Transitions ​

FromActionDraftApplied and revisionVisible result
AnyEdit a controlUpdatedUnchangeddirty becomes true when it differs. Shown issues update live.
AnyApply, no blocking issueNormalized to the applied valueDeep copy, revision + 1apply emitted, "Filter applied." announced, focus stays. dirty is false.
AnyApply, blocking issuesUnchanged, issues now shownUnchangedEvery issue shown and linked. Focus moves to the first invalid control. Count announced.
AnyResetBaselineUnchangedIssue display returns to restore-time issues only.
AnyClearEmpty root (same root id)Unchangedempty slot content.
AnyApp savesUnchangedUnchangedThe app persists applied.
AnyRestore, malformed inputUnchangedUnchanged{ ok: false }. The app explains that the saved filter cannot be opened.
AnyRestore, validReplacedUnchangedDraft shows the saved filter. dirty reflects the difference.
AnyRestore with apply, validReplaced, normalizedDeep copy, revision + 1apply emitted. Focus does not move. dirty is false.
AnyRestore (with or without apply), issuesReplaced, restore-time issues shownUnchangedIssues shown immediately. "Saved filter opened. N conditions need attention." announced.
Anyfields changesRevalidatedKept; appliedIssues recomputedNew restore-time issues (such as a newly retired field) are shown. A stale applied expression is flagged, not re-run.

A successful Apply normalizes the expression (choice arrays de-duplicated in order, -0 stored as 0). The draft is then replaced by the draft of the applied expression, so it holds the same normalized values and dirty is false. Node ids, order and pending editor state are unchanged, so no control is remounted and focus stays where it was. When normalization changed nothing, the draft object is kept. The same holds for the draft of a valid result from validateQueryExpression.

Issue display follows one rule. Issues found by restore or by a schema change (unknown or retired fields, retired options, incompatible operators and invalid stored values) are shown at once because the user did not cause them. Issues from the user's own edits, such as a new rule with no value yet, are shown after the first failed Apply and then update live until the next successful Apply.

restore discards unapplied draft edits. The app confirms with the user before calling it when dirty is true.

Schema changes and the applied expression ​

A fields change can retire or remove a field, an option or an operator that the applied expression uses. The builder then keeps applied and revision unchanged, because they still describe the results on screen, and sets appliedIssues to the issues validateQueryExpression(applied, fields) reports. While appliedIssues is non-empty the applied expression is stale:

  • The app must not execute it again (for example on refresh or paging) or save it. The example disables Save and shows "This filter uses fields that changed. Repair and apply it to refresh results."
  • The draft shows the same issues at once, so the user repairs it and applies. A successful Apply replaces the stale expression and clears appliedIssues.
  • The apply event is not emitted by the schema change, and the stale expression keeps its type, since it was valid for the schema it was applied with.

appliedIssues is also bound to the actions slot. A schema change that does not affect the applied expression leaves appliedIssues empty.

Loading, empty, disabled, read-only, and error states ​

  • Empty. An empty root group without NOT is valid and applies "no conditions", which the app executes as "all records". An empty nested group is a group-empty issue.
  • NOT on an empty group. The NOT checkbox is disabled while its group has no children, and removing the last child of a negated group sets not to false. Restored input with an empty negated group, including the root, reports group-empty ("Add a condition to this group or turn off NOT"), so an applied expression never contains an empty group with not: true.
  • Loading. The builder has no loading state. While the app runs a query, the user can keep editing. The app shows its own pending indicator next to the results.
  • Disabled and read-only. disabled wins over readonly. Neither changes applied or the issue list. While readonly is true (and disabled is not), each condition renders as static text (field label, operator label and formatted value) and each group renders its combinator and NOT as text with a summary of its conditions. No form controls, add, remove or NOT actions, and no value slot editor are rendered, so the builder adds no Tab stops of its own (Q7).
  • Errors. Rule issues are attached to one control per the table above. A rule can carry one field or operator issue plus one value issue. Group issues are attached to the group.

Async behavior ​

The builder is synchronous. Validation, validate callbacks and restore do not await anything. The app associates results with an applied expression by revision:

ts
const request = useGhostDataTableServerRequest()
const results = shallowRef<{ revision: number; ids: string[] } | null>(null)

async function onApply({
  expression,
  revision,
}: GhostQueryApplyEvent<typeof fields>) {
  request.begin(revision) // synchronously, before any await
  const ids = await searchIssues(expression)
  if (!request.isLatest(revision)) return // a newer Apply superseded it
  results.value = { revision, ids }
}

Trace with two Apply actions that resolve out of order:

  1. Apply Open AND (High priority OR Overdue): revision 2, slow request A.
  2. Edit to Open AND Overdue and Apply: revision 3, fast request B.
  3. B resolves first and shows GV-102 for revision 3.
  4. A resolves later. Revision 2 is not the latest, so it is discarded and GV-102 stays.

Draft edits never change the revision, so results stay tied to the applied expression while the user edits. The results view can show the applied filter's summary next to the rows, because applied and the rows' revision come from the same Apply.

Consumer data ​

  • Field schema. Read, never mutated. The builder does not make it deeply reactive; it reacts to replacement of the fields array and of field objects in it, and revalidates the draft and appliedIssues either way. Mutating a field object in place is not detected. validate must be synchronous and pure.
  • Input to restore and defaultExpression. Treated as untrusted unknown. It is parsed into a new draft; the caller's object is never kept or mutated. Extra properties are dropped.
  • Emitted expressions. Each apply payload and the exposed applied value are frozen deep copies with a fixed key order (kind, id, then node fields), so JSON.stringify output is stable and comparable.
  • Identity. Field ids identify fields; option values identify choices; rule and group ids identify nodes. Labels are display only.

Reference semantics ​

The app executes expressions. These semantics define what a correct execution returns, so local matching, a server translation and the executable example agree. For a record r and a rule on field f:

  • A group with and matches when every child matches; with or, when any child matches. An empty group matches every record; only the root can be empty in an applied expression, and never with not: true. not: true matches exactly the records the same group without not does not match.
  • isMissing matches when r[f] is undefined or null. isPresent is its complement.
  • Every value comparison, including isNot, isNoneOf, notEquals and notContains, matches only when r[f] is present. A missing value never matches a comparison (see Q3). Use isMissing inside an or group, or NOT on a group, to include missing values on purpose.
  • isEmpty matches only "". isNotEmpty matches a present string other than "". Whitespace is not trimmed.
  • Text comparison case and normalization are the app's choice and must be documented by the app. The example compares case-insensitively.
  • Date operators compare calendar dates. between includes both ends. Number between includes both ends.

Missing, empty, zero and false ​

These values never collapse into one another, in the draft, in the applied expression or through a save and restore:

RuleMatches record valueDoes not match
assignee isMissingabsent, null"", "ana"
assignee isEmpty""absent, null, "ana"
estimate equals 00absent, null, "", false
estimate isMissingabsent, null0
archived is falsefalseabsent, null, 0, ""
archived isMissingabsent, nullfalse

The editors keep them apart as well. Clearing a number input leaves the rule without a value (value-required), never 0. A yes/no editor has no selection until the user picks one, and "No" stores false. A text rule with an empty value reports value-required and points to "is empty text"; it never stores "" as an equals value.

Worked example ​

Sample issues ​

IDstatuspriorityoverduearchivedassigneeestimatedueDate
GV-101openhighfalsefalse"ana"02026-12-20
GV-102opennormaltrueabsent""32026-11-28
GV-103closedhightruetrue"ben"null2026-11-30
GV-104openlowfalsefalsenull5absent
GV-105openabsentfalsefalse"cy"22026-12-10

GV-101 is the open high-priority issue, GV-102 the open overdue issue of normal priority, and GV-103 the closed high-priority overdue issue.

Open AND (High priority OR Overdue) ​

The serialized expression the app saves:

json
{
  "version": 1,
  "root": {
    "kind": "group",
    "id": "g-root",
    "combinator": "and",
    "not": false,
    "children": [
      {
        "kind": "rule",
        "id": "r-status",
        "field": "status",
        "operator": "is",
        "value": "open"
      },
      {
        "kind": "group",
        "id": "g-urgent",
        "combinator": "or",
        "not": false,
        "children": [
          {
            "kind": "rule",
            "id": "r-priority",
            "field": "priority",
            "operator": "is",
            "value": "high"
          },
          {
            "kind": "rule",
            "id": "r-overdue",
            "field": "overdue",
            "operator": "is",
            "value": true
          }
        ]
      }
    ]
  }
}
StepDraftApplied (revision)Matching IDs
1. Empty builderempty rootnull (0)app shows all
2. Build the expression aboveexpressionnull (0)unchanged
3. Applyexpressionexpression (1)GV-101, GV-102
4. Save: app stores JSON.stringify(applied)expressionexpression (1)GV-101, GV-102
5. Reload the page, restore(JSON.parse(saved), { apply: true })expressionexpression (1)GV-101, GV-102

After the restore the ids, grouping and values are identical, so the matching IDs are identical: GV-101, GV-102 before and after. GV-103 is excluded because it is closed. GV-104 is open but low priority and not overdue. GV-105 has no priority (missing never matches is high) and is not overdue.

If grouping were lost and the rules were read left to right as (Open AND High priority) OR Overdue, GV-103 would wrongly match. A test pins this: the restored expression must not match GV-103.

Negated group ​

Open AND NOT (Archived is Yes OR Assignee is empty text):

json
{
  "kind": "group",
  "id": "g-hide",
  "combinator": "or",
  "not": true,
  "children": [
    {
      "kind": "rule",
      "id": "r-archived",
      "field": "archived",
      "operator": "is",
      "value": true
    },
    {
      "kind": "rule",
      "id": "r-unassigned",
      "field": "assignee",
      "operator": "isEmpty"
    }
  ]
}
IssueOpenInner groupNOT innerResult
GV-101yesarchived false, assignee "ana": noyesmatch
GV-102yesarchived absent: no; assignee "": yesnoexcluded
GV-103noexcluded
GV-104yesarchived false: no; assignee null is missing, not empty: noyesmatch
GV-105yesnoyesmatch

Expected IDs: GV-101, GV-104, GV-105, before and after a save and restore. If not were dropped, the result would be GV-102 only. The not: true flag is stored on the group, so it survives serialization.

Missing versus "", 0 and false ​

Each rule applied alone to the sample issues:

RuleExpected IDs
assignee isMissingGV-104
assignee isEmptyGV-102
estimate equals 0GV-101
estimate isMissingGV-103
archived is falseGV-101, GV-104, GV-105
archived isMissingGV-102

After a save and restore, "value": 0, "value": false and the valueless isEmpty and isMissing rules are unchanged, so each row's IDs are unchanged.

Incomplete date range ​

The user adds Due date between and picks only the start date. The date editor holds { start: '2026-12-01', end: null }.

  1. Applied is still the expression from step 5 (revision 1), showing GV-101 and GV-102.
  2. Apply fails with value-incomplete on the rule's "To" input: "Enter both dates." Focus moves to that input, and the count is announced.
  3. applied, revision and the results are unchanged. Nothing is emitted.
  4. The user picks 2026-12-15 as the end date. The issue clears. Apply succeeds at revision 2 with Due date between 2026-12-01 and 2026-12-15 added to the root group: GV-101 (due 2026-12-20) drops out and GV-102 (due 2026-11-28) drops out, so the result is empty, and the app shows its empty state.

A start after the end reports range-order instead. Unparseable typed text in the date input is reported by the date picker as pending, and Apply reports value-pending.

Retired field and repair ​

A filter saved last quarter contains a rule on severity, which the app has since retired in favour of priority:

json
{
  "kind": "rule",
  "id": "r-sev",
  "field": "severity",
  "operator": "is",
  "value": "critical"
}

It sits second in the g-urgent group, between r-priority and r-overdue.

  1. restore(saved, { apply: true }) returns { ok: true, applied: false, issues: [{ nodeId: 'r-sev', code: 'field-retired', target: 'field', … }] }. The rule stays second in its group with its stored operator and value. Because the schema marks severity as retired, its label "Severity" is shown. An id missing from the schema entirely reports field-unknown and shows the raw id.
  2. The field control shows "Severity" with the error "Severity is no longer available. Choose another field or remove this condition." Its operator and value are shown as read-only text, because no editor exists for an unavailable field. "Saved filter opened. 1 condition needs attention." is announced. Nothing is applied; the app keeps the previous results or, on first load, shows "Repair this filter to see results" rather than unfiltered rows labelled as the saved filter.
  3. Repair by replacing the field. The user chooses "Priority" in that rule's field control. The operator is is kept because priority supports it. The value critical is not a priority option, so it is cleared and the value control shows value-required (restore-time rules keep live display). The user picks "High" and the issue list empties.
  4. Or repair by removing it. The user activates "Remove condition 2: Severity is critical". Focus moves to the remove button of the condition now in that position (Overdue), and "Condition 2 removed." is announced.
  5. Apply succeeds. The app saves the repaired expression, which no longer names severity.

An incompatible stored operator (for example contains on a choice field) and a retired choice option follow the same pattern: the rule keeps its position, the issue is attached to the operator or value control, and Apply is blocked until the user fixes or removes it.

Accessibility contract ​

Semantics and relationships ​

  • The root is an element with role="group" named by the consumer's aria-label or aria-labelledby. Each nested group is an element with role="group" named through aria-labelledby by its visible heading, for example "Group 2: Any condition (OR)" or "Group 2: NOT any condition".
  • Children are in a list (<ul>/<li>) so screen readers report the number of conditions in a group. The visible "AND"/"OR" connector between items is aria-hidden="true" because the group name states it once.
  • Each rule is an <li> containing a role="group" named "Condition 2". Its field, operator and value controls are named "Field", "Operator" and "Value" (or "From"/"To"), shown as visible labels (the label part) and linked by aria-labelledby so names stay correct when consumers restyle them. (Amended during implementation: the maintainer chose visible labels over a visually hidden default in PR #783, so a control that shows an issue still has a visible label.)
  • The combinator is a GhostRadioGroup named "Match" with two options. NOT is a GhostCheckbox labelled by messages.notLabel. The root group also offers NOT.
  • Add and remove actions are native <button type="button"> elements. Remove names include the condition's position and a summary, for example "Remove condition 2: Priority is High".
  • An issue's text is rendered next to its control, which gets aria-invalid="true" and an aria-describedby reference to that text. Group issues are referenced by the group element and its Add condition button.
  • One polite status region per builder announces additions, removals, Apply success, Apply failure counts and restore results. It starts empty.

Keyboard interaction ​

The builder is a structured form, not a composite widget. There is no roving tabindex across conditions and no custom shortcut. Every control is its own Tab stop and keeps the keyboard contract of the primitive it uses.

FocusKeyResult
Anywhere in the builderTab / Shift+TabMoves in document order: group header (Match, NOT, Remove group), conditions, Add condition, Add group.
Match radio groupArrow keysSelects All or Any (GhostRadioGroup contract). The group name and connectors update.
NOT checkboxSpaceToggles NOT for the whole group. Disabled while the group is empty.
Field, operator, choice valueGhostSelect keysOpens, moves and selects as in the Select spec. Escape closes only the popup.
Yes/no valueArrow keysSelects Yes or No (GhostRadioGroup).
Text valueNative editingEnter performs native implicit submission when the builder is inside a <form>.
Number valueGhostNumberInput keysArrow Up/Down step; Enter as for text.
Date valueGhostDatePicker keysAs in the date picker spec; Enter commits typed text.
Add condition / Add groupEnter / SpaceAppends a condition (or a group with one empty condition) and focuses its Field control.
Remove condition / Remove groupEnter / SpaceRemoves the item and recovers focus as below.

The recommended composition wraps the builder in a <form> whose submit handler calls apply() and whose submit button is "Apply filter". Enter in a text or number value then applies through native implicit submission. The builder itself never binds Enter, Delete or Escape, so text editing and popups keep their native behavior.

Focus behavior ​

  • Add. A new condition's Field control receives focus. Add group creates a group containing one empty condition and focuses that condition's Field control.
  • Remove a condition or group with focus inside the removed item (including its remove button): focus the remove button of the item now at the same position in the parent group; else the previous item's remove button; else the parent group's Add condition button. This allows repeated removal and never drops focus to <body>. Activating a remove button without focusing it (pointer on some platforms) moves focus the same way only if focus was inside the removed item.
  • Failed Apply. Focus moves to the first invalid control in document order unless apply({ focus: false }) was used. restore(…, { apply: true }) never moves focus.
  • Restore, reset and clear while focus is inside a node that disappears: focus the root group's Add condition button. Focus outside the builder is left alone.
  • Field change keeps focus on the Field control. The operator and value controls are replaced in place.
  • Focus indicators are visible on every control, using each primitive's styling hooks.

Assistive technology expectations ​

Entering a group announces its name ("Group 2: Any condition (OR)", list of 2 items). Each condition reads as "Condition 1, group" followed by its labelled controls, their values and any error description. A Remove button announces what it removes. The status region announces the outcome of add, remove, Apply and restore once, without repeating the full expression. Verification covers NVDA with Firefox and VoiceOver with Safari when the component is proposed for stable, per the assistive technology review.

Rendering and customization ​

From simplest to most flexible:

  1. Props and messages. Field schema, operator subsets, labels and all component-owned text.
  2. Slots. actions for Apply, Reset and the app's Save button; value for custom editors; empty for the empty root.
  3. Styling hooks. Stable data-part values: root, group, group-header, group-name, combinator, not, children, connector, rule, field, operator, value, label, remove, add-rule, add-group, issue, status. State attributes: data-combinator="and|or" and data-negated on groups, data-depth on groups and rules, data-invalid on rules and groups with shown issues, data-retired on a rule with an unavailable field, and data-disabled/data-readonly on the root. Consumer class and style apply to the root.

Wrapper nesting between those parts is not a contract. The headless output carries no visual styles. The executable example adds minimal CSS for indentation and narrow-width wrapping.

Environment behavior ​

SSR and hydration ​

Validation and parsing are pure and synchronous, so the server renders the same draft, the same restore-time issues and the same DOM ids as the client. DOM ids come from useGhostId. Node ids come from the expression; new ids are minted only on client interaction. When there is no default expression, or it is malformed, the bootstrap root group gets the fixed id 'root' without calling createId, so server and client agree. clear() keeps the current root id, and a restored expression keeps its own root id. The default createId never returns 'root'. The status region renders empty, and setup and hydration emit nothing and move no focus. With applyDefault, applied and revision: 1 exist on both server and client without an event, so an app can render the saved filter's results on the server. The app calls validateQueryExpression(saved, fields) itself: for status: 'valid' it executes result.expression and passes applyDefault; for needs-repair it renders the builder without results and a repair message; for malformed it explains that the saved filter cannot be opened.

Mobile and touch ​

All controls are native or existing GhostVue primitives with their own touch behavior and target sizes. Pickers use the primitives' popups; the date picker keeps its modal calendar. Conditions wrap so the field, operator and value controls stack at phone width, and nesting indentation is limited by maxDepth. The virtual keyboard type follows the value editor (inputmode from GhostNumberInput for numbers).

Performance ​

Expected scale: up to about 50 conditions, nesting up to maxDepth, and up to about 200 fields. Validation is O(nodes) and runs on each draft change. The schema is not made deeply reactive. The fields array is read shallowly, so replacing the array or any entry in it (fields[i] = … on a reactive array) is tracked, and the field lookup map is rebuilt when the array or the identity of any entry changes, in O(fields). A field object mutated in place is not detected, as Consumer data states. dirty compares the draft with the applied snapshot structurally in O(nodes). Emitted snapshots are frozen so consumers can cache them by reference. No virtualization is planned; an app with hundreds of fields can provide a searchable field picker later through a follow-up, or uses the operator subset to keep lists short.

Composition ​

NeedReused primitive
Field, operator, choiceGhostSelect (single); GhostSelect with multiple for isAnyOf
Combinator, yes/noGhostRadioGroup
NOTGhostCheckbox
Text valueGhostInput
Number and number rangeGhostNumberInput (two for between)
Date and date rangeGhostDatePicker (selectionMode single or range, keyed per operator because the mode is fixed per instance)
Labels, descriptions, errorsGhostField parts and GhostVisuallyHidden
Add and removeNative buttons with the GhostButton behavior
IdsuseGhostId
Result associationuseGhostDataTableServerRequest in the app (guards any monotonic id)

Date values are stored as ISO strings and converted with parseDate for the date picker, so expressions stay JSON-native. The date editor reads the date picker's pending and errors slot state and calls the same pending path as a custom editor, so half-typed dates block Apply.

Nothing is duplicated from these primitives. The builder adds only the tree, the draft/applied split, validation and focus recovery. The DataTable is not coupled to the builder: an app passes the applied expression into its own server request or local filter, as the example does.

Test plan ​

  • Framework-neutral unit tests (model). Parse and validate every operator and value shape; malformed inputs (wrong version, non-group root, duplicate ids, non-boolean not) are rejected without changing the draft; restore-time issues for unknown and retired fields, retired options, incompatible operators and invalid stored values keep the rule in place; every draft node and applied node is frozen, and writing to one throws in strict mode without changing the draft; -0 becomes 0; choice arrays de-duplicate in order, and after a successful Apply of ['high', 'high'] the draft holds ['high'] and dirty is false; each validateQueryExpression status (valid, needs-repair, malformed) and its accompanying values; duplicate field ids and unusable operator lists report field-duplicate and field-misconfigured; repeated choice option values, an empty option value '', a number step of 0, -1, NaN or Infinity, a date min or max that is not a real 'YYYY-MM-DD' date, a date min after max, and an active choice field with options: [] report field-misconfigured with a development warning, while a retired choice field with options: [] reports only field-retired; a schema change that removes a field used by applied fills appliedIssues without changing applied; an empty negated group reports group-empty and the NOT control is disabled while a group is empty; composable edit methods never mutate a previous draft; addRule and addGroup return null for an unknown group id, while disabled or read-only and (for addGroup) at maxDepth, without changing the draft; with disabled or readonly passed as a ref, every other edit method leaves the draft unchanged and edits work again once the ref turns false, while apply, restore, reset and clear keep working; removeNode(draft.root.id) called directly on the composable leaves the draft, including the root id and its children, unchanged and warns in development; JSON.stringify then JSON.parse then restore yields an identical expression. A reference matcher in the test fixtures runs every worked example: Open AND (High priority OR Overdue) matches GV-101 and GV-102 before and after the round trip and never GV-103; the negated group matches GV-101, GV-104 and GV-105 and loses nothing on round trip; each missing, empty, zero and false row matches its listed IDs.
  • Vue behavior tests. Draft edits do not change applied or emit; a failed Apply keeps applied, revision and emits nothing; a successful Apply emits a frozen copy and increments revision; refresh Apply emits; the incomplete date range blocks Apply; the retired-field repair by replacement and by removal; field change keeps or clears operator and value as specified; fields replacement, and replacing one entry of a reactive fields array (for example marking a used field retired), revalidates issues and appliedIssues without changing applied; reset, clear and restore baselines; createId collisions; consumer schema and restore input are not mutated; maxDepth; disabled and read-only, including that toggling either prop reaches the composable so addRule returns null and later edits work again; message overrides and locale change.
  • Custom editor. A test editor in the value slot receives the narrowed field and current value, its setValue updates the draft, setPending blocks Apply with value-pending, and an incompatible value from it is still rejected on Apply.
  • Browser tests (Playwright). Press every documented key; assert real focus with toBeFocused() after add, after removing first, middle and last conditions and groups (including the last item of a group), after a failed Apply and after restore; assert aria-invalid, descriptions, group names and list counts; run axe with the builder empty, populated, invalid and with a picker open; narrow-width layout; RTL.
  • Out-of-order results. In the executable example, resolve two applied requests in reverse order and assert only the latest revision's IDs render.
  • SSR and hydration. Render a default expression with a retired field on the server; hydrate with identical markup, issues and ids, no warnings, no emitted events and no focus change; two instances on a page have distinct DOM ids. Render a builder with no default expression and a createId that returns random values; the server and the hydrated client both have root id 'root', createId is not called, and there is no hydration mismatch.
  • Type tests. defineQueryFields keeps literal ids; narrowing on rule.field narrows operator and value; the value slot's field and setValue narrow by field type; after slot.fieldId === 'assignee', slot.setValue(123) fails to compile; on the priority field setValue('urgent') fails and setValue(['high']) compiles; a date field accepts { start: '2026-12-01', end: null } and rejects { min: 1, max: 2 }; no field accepts a GhostQueryStoredValue from setValue. Negative type tests reject a number value on a text field, isAnyOf on a boolean field, null as a value, an empty operators list and contains in a choice field's operators. On the exposed and composable draft and applied, on the apply payload and on the slot's rule, writes such as draft.root.not = true, draft.root.children.push(…), assigning a rule's field, and value.start = … on a date range fail to compile, while narrowing on field and operator still narrows value and a read-only applied expression is still assignable to GhostQueryExpression<Fields>. For an active choice field with options: [], GhostQueryRule rejects every rule, including { operator: 'is' } without value, { operator: 'is', value: 'x' } and { operator: 'isMissing' }; on a field with options, is without value is rejected and isMissing with no value compiles.

Documentation plan ​

  • A component page docs/components/query-builder.md with generated props, events and slots tables, the exposed members table and the issue codes.
  • Executable example examples/query-builder/issue-triage.vue, headless, using public imports only. It defines the sample fields and issues above, wraps the builder in a form with Apply, Reset and a separate Save button, stores saved filters in memory, reopens one with restore(…, { apply: true }) and shows the same IDs, includes a person picker through the value slot, and applies results with a revision guard and a simulated delay that can resolve out of order. A second saved filter contains the retired severity rule to show repair. The example's local matcher implements the reference semantics for its own fields and is labelled as example code, not a GhostVue API.
  • Guide sections: draft versus applied, saving and restoring, repairing a saved filter, missing versus empty, writing a server translation, custom editors, keyboard and focus, and the out-of-order results pattern.
  • A playground exercise covering every field type, nested and negated groups, and a retired field.

Compatibility and release impact ​

The proposal adds new exports to @ghostvue/vue and changes no existing component. Each implementation step adds a Changeset for @ghostvue/vue, regenerated manifests and API docs. The manifest starts as experimental.

The serialized expression is a durable contract because apps persist it. version: 1 is part of every expression. A later version must restore version 1 expressions with the same meaning; restore reports unsupported-version for a newer version rather than guessing. Adding operators or field types is additive. Renaming an operator, changing a value shape or changing reference semantics is breaking.

Package boundary ​

Everything lives in @ghostvue/vue: the pure model (parsing, validation, id minting and snapshots, as framework-neutral TypeScript with no Vue import), the component and the types. It depends only on existing @ghostvue/vue primitives and adds no runtime dependency. @ghostvue/themes gains nothing in the first slice and must not be required. The example lives under the unpublished examples/ tree. No application concern (fetching, persistence, row evaluation) enters a package.

Implementation gate ​

Approval of this spec on master releases the first implementation step. Each later step starts when the previous one has merged into master.

  1. Expression model. Field schema types, defineQueryFields, validateQueryExpression, useGhostQueryBuilder with the draft/applied split, tree edits, Apply validation, restore and serialization, with the model unit tests and type tests.
  2. Editor structure. GhostQueryBuilder rendering groups and conditions, AND/OR, NOT, add and remove, names, keyboard and focus recovery, the status region, the text value editor and the value slot, with behavior, browser, SSR and type tests, manifest and API docs.
  3. Typed value editors. Choice, yes/no, date (including range) and number editors with their tests.
  4. Runnable example and guide. The issue-triage example, guide sections, playground coverage, and the browser checks for keys, focus, axe and out-of-order results.

These implementation steps are tracked by the maintainers rather than as public issues, so this PR adds no implementationGates entry to .github/release-scope.json. If a step is opened as a public issue, its gate entry maps this prerequisite to query-builder.

Open architectural questions ​

Resolved 2026-12-04. The maintainer approved the recommended option for each decision below, including (a) for Q7. The alternatives stay listed as the record of what was considered.

  1. Q1. Save stores the applied expression. The app's Save reads applied, so a saved filter always passed validation and matches the results on screen. Save is unavailable while appliedIssues is non-empty. When dirty is true the example labels Save "Save applied filter" and offers Apply first. Alternative: save the draft, which could store an invalid or never-run filter.
  2. Q2. The composable owns behavior; the component owns DOM concerns.useGhostQueryBuilder follows the canonical headless pattern and exposes state and tree edits only. Names, issue relationships, focus recovery and announcements stay in GhostQueryBuilder, so custom markup built on the composable must provide them. Alternative: also export DOM helpers for focus recovery, which would grow the first slice's public surface.
  3. Q3. Missing values never match a value comparison, including negative ones (isNot, notEquals). This matches SQL and most search back ends, so local and server execution agree. NOT on a group is the strict complement and does include missing values, as GV-104 shows. Alternative: treat missing as "not equal", which differs from SQL.
  4. Q4. No reordering in the first slice. Logic does not depend on order within a group, and restored order is preserved. Move up/down actions can follow with their own focus contract.
  5. Q5. Editor customization through one value slot chosen by field.editor, rather than an editor-component map prop. A slot works through nested groups through the root, types its bindings per field and adds no registry.
  6. Q6. Headless only in the first slice. A themed recipe follows as a separate proposal once the headless parts are stable.
  7. Q7. What readonly renders. The readonly prop promises focusable, non-editable controls, but GhostCheckbox, GhostRadioGroup and GhostSelect offer only disabled, and the checkbox spec rejects a read-only state. Options: (a) read-only renders each condition as static text plus a summary, with no form controls; (b) read-only uses disabled controls, accepting that they leave the Tab order and may be skipped by screen readers in forms mode; (c) amend those primitives with a read-only state in a separate change first. Recommended: (a), which changes no other component. Decided: (a).

Approval ​

Approved by @zprue743 on 2026-12-04 in PR #768, at the revision that PR merged. Decisions Q1–Q6 take the option described in Open architectural questions, and Q7 takes option (a): read-only renders static text with no form controls. This is design approval of the public API only. It releases the first step of the implementation gate and is not merge approval of any implementation.