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,
0andfalsekeep 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/themesin the first slice (see Q6).
Public API
Parts and exports
The first slice adds these exports to @ghostvue/vue:
| Export | Kind | Contract |
|---|---|---|
useGhostQueryBuilder | Composable | Render-free draft and applied state, tree edits, Apply, restore, reset and clear. See Composable. |
GhostQueryBuilder | Component | Thin unstyled component over the composable: renders the tree, names, issues, focus recovery and announcements. |
defineQueryFields | Function | Identity helper that keeps literal field ids, types and option values so expressions and slots narrow by field. |
validateQueryExpression | Function | Pure, synchronous parse and validation of unknown input against a field schema. Used by restore, usable on a server. |
| Public types | Types | Field 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.
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:
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 type | Operators | Value |
|---|---|---|
choice | is, isNot | One option value (string) |
choice | isAnyOf, isNoneOf | Non-empty array of option values, de-duplicated on Apply |
boolean | is | true or false |
date | on, before, after | ISO calendar date 'YYYY-MM-DD' |
date | between | { start: 'YYYY-MM-DD', end: 'YYYY-MM-DD' }, inclusive |
text | equals, notEquals, contains, notContains, startsWith | Non-empty string, stored exactly as typed |
text | isEmpty, isNotEmpty | None. Tests for the empty string "" |
number | equals, notEquals, lessThan, lessThanOrEqual, greaterThan, greaterThanOrEqual | Finite number. -0 is stored as 0 |
number | between | { min: number, max: number }, inclusive, min <= max |
| Every type | isMissing, isPresent | None. 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
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:
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> | GhostQueryStoredValueGhostQueryDraftValueFor is keyed by field, not operator, because an operator change keeps the editor mounted. Which member an operator uses follows the operator table:
| Field type | Operators | Draft value an editor proposes |
|---|---|---|
choice | is, isNot | One literal option value |
choice | isAnyOf, isNoneOf | Array of literal option values; [] while empty |
boolean | is | true or false |
date | on, before, after | 'YYYY-MM-DD' |
date | between | GhostQueryPartialDateRange; complete when both ends are strings |
number | comparisons | Finite number |
number | between | GhostQueryPartialNumberRange; complete when both ends are set |
text | comparisons | Non-empty string |
| Any | isMissing, isPresent, isEmpty, isNotEmpty | None: 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 state | Representation | Issue on Apply |
|---|---|---|
| New rule, no field yet | field: null, operator: null, no value | field-required |
| Field picked, operator not chosen | Never: picking a field sets its default operator | — |
| Unknown or retired field | field: 'severity', stored operator and value kept | field-unknown / field-retired |
| Operator not valid for the field | operator: 'contains' kept as stored | operator-incompatible |
| Empty text, number, date or choice | No value key (cleared inputs remove it) | value-required |
| Empty multi-choice | value: [] | value-required |
| Half-entered date range | value: { start: '2026-12-01', end: null } | value-incomplete |
| Half-entered number range | value: { min: 1, max: null } | value-incomplete |
| Restored value of the wrong shape | value: { kind: 'stored', raw: 'abc' } | value-invalid |
| Editor holding uncommitted text | Not in the draft; tracked per rule from setPending | value-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
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:
- Structure. Input that is not a version 1 expression (not an object, a root that is not a group, a node without
kindorid, a non-arraychildren, a combinator other thanand/or, a non-booleannot, or a field or operator that is not a string) returnsmalformed. A newerversionreturnsunsupported-version; repeated node ids returnduplicate-id. No draft is produced. - Meaning. A structurally sound expression is checked against
fieldswith the same rules as Apply, exceptvalue-pending, which only a mounted editor can report. Any issue returnsneeds-repairwith the draft and a non-empty issue list in document order. Otherwise the result isvalidwith 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
| Prop | Type | Default | Contract |
|---|---|---|---|
fields | readonly GhostQueryField[] | required | Consumer-owned schema. Reactive: a change revalidates the draft and never changes the applied expression. |
defaultExpression | unknown | null | Initial draft, read once at setup through validateQueryExpression. Malformed input starts an empty draft and reports a development warning. |
applyDefault | boolean | false | When 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') => string | instance counter | Mints 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. |
maxDepth | number | 3 | Nesting levels the user can create, counting the root as 1. Restored deeper groups are kept and stay editable, but offer no Add group action. |
disabled | boolean | false | Disables every control. Programmatic restore, reset, clear and apply still work. |
readonly | boolean | false | Renders the draft as static text with no form controls and no add or remove actions (Q7). disabled takes precedence. |
messages | Partial<GhostQueryBuilderMessages> | English defaults | Reactive 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.
| Member | Type | Contract |
|---|---|---|
apply(options?) | (o?: { focus?: boolean }) => GhostQueryApplyResult | Validates 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 }) => GhostQueryRestoreResult | Replaces the draft with a parsed expression. With apply: true it then applies without moving focus. Malformed input changes nothing. |
reset() | () => void | Replaces the draft with the baseline: the applied expression, else the last restored or default input, else an empty root group. |
clear() | () => void | Replaces the draft with an empty root group, keeping the root id. Does not apply. |
draft | GhostQueryDeepReadonly<GhostQueryDraft> | Current draft. Read-only; edit through the UI or restore. |
applied | GhostQueryDeepReadonly<GhostQueryExpression<Fields>> | null | Last applied expression, or null before the first Apply. |
revision | number | Revision of applied; 0 before the first Apply. |
dirty | boolean | true when the draft differs from applied (or from an empty root when nothing is applied). |
issues | readonly GhostQueryIssue[] | Current blocking issues of the draft, in document order, whether or not they are displayed yet. |
appliedIssues | readonly GhostQueryIssue[] | Issues found when applied is revalidated against the current fields. Empty unless a schema change made the applied expression stale. See Schema changes. |
/** 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.
actionsbinds{ 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.valuereplaces the value editor of every rule. See Value editor customization.emptyrenders inside an empty root group, before its Add rule action. Default content ismessages.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.
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:
/** 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:
<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.
| Key | English default |
|---|---|
groupName(path) | Group {path} (root: the root's accessible name) |
combinatorLabel | Match |
combinatorAnd / Or | All conditions (AND) / Any condition (OR) |
notLabel | NOT: exclude issues that match this group |
ruleName(index) | Condition {index} |
fieldLabel / operatorLabel / valueLabel | Field / Operator / Value |
rangeStart / rangeEnd | From / To |
addRule / addGroup | Add 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 |
announceApplied | Filter applied. |
announceBlocked(count) | Filter not applied. {count} conditions need attention. |
announceRestored(count) | Saved filter opened. {count} conditions need attention. |
announceAdded / announceRemoved | Condition added. / Condition {index} removed. |
emptyRoot | No conditions. All issues match. |
User-facing text says "condition" because filter users rarely say "rule". API names keep rule.
Issue messages
| Code | Attached to | English default |
|---|---|---|
field-required | field | Choose a field. |
field-unknown | field | {fieldId} is no longer available. Choose another field or remove this condition. |
field-retired | field | {label} is no longer available. Choose another field or remove this condition. |
field-duplicate | field | {label} is defined more than once, so it cannot be used. Choose another field or remove this condition. |
field-misconfigured | field | {label} is set up incorrectly and cannot be used. Choose another field or remove this condition. |
operator-incompatible | operator | {operator} does not work with {label}. Choose another operator. |
value-required | value | Enter a value. To match an empty value, choose "is empty text" or "is missing". |
value-incomplete | value | Enter both dates. / Enter both numbers. |
value-pending | value | The custom editor's message, else: Finish entering this value. |
value-invalid | value | Enter a valid {type}. |
value-out-of-range | value | Enter a value between {min} and {max}. |
range-order | value | The start must be on or before the end. |
option-retired | value | {label} is no longer an option. Choose another value or remove this condition. |
value-rejected | value | The field's validate message. |
group-empty | group | Add 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
| From | Action | Draft | Applied and revision | Visible result |
|---|---|---|---|---|
| Any | Edit a control | Updated | Unchanged | dirty becomes true when it differs. Shown issues update live. |
| Any | Apply, no blocking issue | Normalized to the applied value | Deep copy, revision + 1 | apply emitted, "Filter applied." announced, focus stays. dirty is false. |
| Any | Apply, blocking issues | Unchanged, issues now shown | Unchanged | Every issue shown and linked. Focus moves to the first invalid control. Count announced. |
| Any | Reset | Baseline | Unchanged | Issue display returns to restore-time issues only. |
| Any | Clear | Empty root (same root id) | Unchanged | empty slot content. |
| Any | App saves | Unchanged | Unchanged | The app persists applied. |
| Any | Restore, malformed input | Unchanged | Unchanged | { ok: false }. The app explains that the saved filter cannot be opened. |
| Any | Restore, valid | Replaced | Unchanged | Draft shows the saved filter. dirty reflects the difference. |
| Any | Restore with apply, valid | Replaced, normalized | Deep copy, revision + 1 | apply emitted. Focus does not move. dirty is false. |
| Any | Restore (with or without apply), issues | Replaced, restore-time issues shown | Unchanged | Issues shown immediately. "Saved filter opened. N conditions need attention." announced. |
| Any | fields changes | Revalidated | Kept; appliedIssues recomputed | New 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
applyevent 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-emptyissue. - 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
nottofalse. Restored input with an empty negated group, including the root, reportsgroup-empty("Add a condition to this group or turn off NOT"), so an applied expression never contains an empty group withnot: 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.
disabledwins overreadonly. Neither changesappliedor the issue list. Whilereadonlyistrue(anddisabledis 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 novalueslot 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:
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:
- Apply
Open AND (High priority OR Overdue): revision 2, slow request A. - Edit to
Open AND Overdueand Apply: revision 3, fast request B. - B resolves first and shows
GV-102for revision 3. - A resolves later. Revision 2 is not the latest, so it is discarded and
GV-102stays.
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
fieldsarray and of field objects in it, and revalidates the draft andappliedIssueseither way. Mutating a field object in place is not detected.validatemust be synchronous and pure. - Input to
restoreanddefaultExpression. Treated as untrustedunknown. It is parsed into a new draft; the caller's object is never kept or mutated. Extra properties are dropped. - Emitted expressions. Each
applypayload and the exposedappliedvalue are frozen deep copies with a fixed key order (kind,id, then node fields), soJSON.stringifyoutput 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
andmatches when every child matches; withor, when any child matches. An empty group matches every record; only the root can be empty in an applied expression, and never withnot: true.not: truematches exactly the records the same group withoutnotdoes not match. isMissingmatches whenr[f]isundefinedornull.isPresentis its complement.- Every value comparison, including
isNot,isNoneOf,notEqualsandnotContains, matches only whenr[f]is present. A missing value never matches a comparison (see Q3). UseisMissinginside anorgroup, or NOT on a group, to include missing values on purpose. isEmptymatches only"".isNotEmptymatches 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.
betweenincludes both ends. Numberbetweenincludes 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:
| Rule | Matches record value | Does not match |
|---|---|---|
assignee isMissing | absent, null | "", "ana" |
assignee isEmpty | "" | absent, null, "ana" |
estimate equals 0 | 0 | absent, null, "", false |
estimate isMissing | absent, null | 0 |
archived is false | false | absent, null, 0, "" |
archived isMissing | absent, null | false |
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
| ID | status | priority | overdue | archived | assignee | estimate | dueDate |
|---|---|---|---|---|---|---|---|
| GV-101 | open | high | false | false | "ana" | 0 | 2026-12-20 |
| GV-102 | open | normal | true | absent | "" | 3 | 2026-11-28 |
| GV-103 | closed | high | true | true | "ben" | null | 2026-11-30 |
| GV-104 | open | low | false | false | null | 5 | absent |
| GV-105 | open | absent | false | false | "cy" | 2 | 2026-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:
{
"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
}
]
}
]
}
}| Step | Draft | Applied (revision) | Matching IDs |
|---|---|---|---|
| 1. Empty builder | empty root | null (0) | app shows all |
| 2. Build the expression above | expression | null (0) | unchanged |
| 3. Apply | expression | expression (1) | GV-101, GV-102 |
4. Save: app stores JSON.stringify(applied) | expression | expression (1) | GV-101, GV-102 |
5. Reload the page, restore(JSON.parse(saved), { apply: true }) | expression | expression (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):
{
"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"
}
]
}| Issue | Open | Inner group | NOT inner | Result |
|---|---|---|---|---|
| GV-101 | yes | archived false, assignee "ana": no | yes | match |
| GV-102 | yes | archived absent: no; assignee "": yes | no | excluded |
| GV-103 | no | excluded | ||
| GV-104 | yes | archived false: no; assignee null is missing, not empty: no | yes | match |
| GV-105 | yes | no | yes | match |
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:
| Rule | Expected IDs |
|---|---|
assignee isMissing | GV-104 |
assignee isEmpty | GV-102 |
estimate equals 0 | GV-101 |
estimate isMissing | GV-103 |
archived is false | GV-101, GV-104, GV-105 |
archived isMissing | GV-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 }.
- Applied is still the expression from step 5 (revision 1), showing GV-101 and GV-102.
- Apply fails with
value-incompleteon the rule's "To" input: "Enter both dates." Focus moves to that input, and the count is announced. applied,revisionand the results are unchanged. Nothing is emitted.- 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-15added 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:
{
"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.
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 marksseverityas retired, its label "Severity" is shown. An id missing from the schema entirely reportsfield-unknownand shows the raw id.- 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.
- Repair by replacing the field. The user chooses "Priority" in that rule's field control. The operator
isis kept becauseprioritysupports it. The valuecriticalis not a priority option, so it is cleared and the value control showsvalue-required(restore-time rules keep live display). The user picks "High" and the issue list empties. - 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.
- 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'saria-labeloraria-labelledby. Each nested group is an element withrole="group"named througharia-labelledbyby 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 isaria-hidden="true"because the group name states it once. - Each rule is an
<li>containing arole="group"named "Condition 2". Its field, operator and value controls are named "Field", "Operator" and "Value" (or "From"/"To"), shown as visible labels (thelabelpart) and linked byaria-labelledbyso 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
GhostRadioGroupnamed "Match" with two options. NOT is aGhostCheckboxlabelled bymessages.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 anaria-describedbyreference 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.
| Focus | Key | Result |
|---|---|---|
| Anywhere in the builder | Tab / Shift+Tab | Moves in document order: group header (Match, NOT, Remove group), conditions, Add condition, Add group. |
| Match radio group | Arrow keys | Selects All or Any (GhostRadioGroup contract). The group name and connectors update. |
| NOT checkbox | Space | Toggles NOT for the whole group. Disabled while the group is empty. |
| Field, operator, choice value | GhostSelect keys | Opens, moves and selects as in the Select spec. Escape closes only the popup. |
| Yes/no value | Arrow keys | Selects Yes or No (GhostRadioGroup). |
| Text value | Native editing | Enter performs native implicit submission when the builder is inside a <form>. |
| Number value | GhostNumberInput keys | Arrow Up/Down step; Enter as for text. |
| Date value | GhostDatePicker keys | As in the date picker spec; Enter commits typed text. |
| Add condition / Add group | Enter / Space | Appends a condition (or a group with one empty condition) and focuses its Field control. |
| Remove condition / Remove group | Enter / Space | Removes 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:
- Props and messages. Field schema, operator subsets, labels and all component-owned text.
- Slots.
actionsfor Apply, Reset and the app's Save button;valuefor custom editors;emptyfor the empty root. - Styling hooks. Stable
data-partvalues: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"anddata-negatedon groups,data-depthon groups and rules,data-invalidon rules and groups with shown issues,data-retiredon a rule with an unavailable field, anddata-disabled/data-readonlyon the root. Consumerclassandstyleapply 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
| Need | Reused primitive |
|---|---|
| Field, operator, choice | GhostSelect (single); GhostSelect with multiple for isAnyOf |
| Combinator, yes/no | GhostRadioGroup |
| NOT | GhostCheckbox |
| Text value | GhostInput |
| Number and number range | GhostNumberInput (two for between) |
| Date and date range | GhostDatePicker (selectionMode single or range, keyed per operator because the mode is fixed per instance) |
| Labels, descriptions, errors | GhostField parts and GhostVisuallyHidden |
| Add and remove | Native buttons with the GhostButton behavior |
| Ids | useGhostId |
| Result association | useGhostDataTableServerRequest 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;-0becomes0; choice arrays de-duplicate in order, and after a successful Apply of['high', 'high']the draft holds['high']anddirtyisfalse; eachvalidateQueryExpressionstatus (valid,needs-repair,malformed) and its accompanying values; duplicate field ids and unusable operator lists reportfield-duplicateandfield-misconfigured; repeated choice option values, an empty option value'', a numberstepof0,-1,NaNorInfinity, a dateminormaxthat is not a real'YYYY-MM-DD'date, a dateminaftermax, and an active choice field withoptions: []reportfield-misconfiguredwith a development warning, while a retired choice field withoptions: []reports onlyfield-retired; a schema change that removes a field used byappliedfillsappliedIssueswithout changingapplied; an empty negated group reportsgroup-emptyand the NOT control is disabled while a group is empty; composable edit methods never mutate a previous draft;addRuleandaddGroupreturnnullfor an unknown group id, while disabled or read-only and (foraddGroup) atmaxDepth, without changing the draft; withdisabledorreadonlypassed as a ref, every other edit method leaves the draft unchanged and edits work again once the ref turnsfalse, whileapply,restore,resetandclearkeep 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.stringifythenJSON.parsethen 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
appliedor emit; a failed Apply keepsapplied,revisionand emits nothing; a successful Apply emits a frozen copy and incrementsrevision; 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;fieldsreplacement, and replacing one entry of a reactivefieldsarray (for example marking a used fieldretired), revalidatesissuesandappliedIssueswithout changingapplied; reset, clear and restore baselines;createIdcollisions; consumer schema and restore input are not mutated;maxDepth; disabled and read-only, including that toggling either prop reaches the composable soaddRulereturnsnulland later edits work again; message overrides and locale change. - Custom editor. A test editor in the
valueslot receives the narrowed field and current value, itssetValueupdates the draft,setPendingblocks Apply withvalue-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; assertaria-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
createIdthat returns random values; the server and the hydrated client both have root id'root',createIdis not called, and there is no hydration mismatch. - Type tests.
defineQueryFieldskeeps literal ids; narrowing onrule.fieldnarrowsoperatorandvalue; thevalueslot'sfieldandsetValuenarrow by field type; afterslot.fieldId === 'assignee',slot.setValue(123)fails to compile; on thepriorityfieldsetValue('urgent')fails andsetValue(['high'])compiles; a date field accepts{ start: '2026-12-01', end: null }and rejects{ min: 1, max: 2 }; no field accepts aGhostQueryStoredValuefromsetValue. Negative type tests reject a number value on a text field,isAnyOfon a boolean field,nullas a value, an emptyoperatorslist andcontainsin a choice field'soperators. On the exposed and composabledraftandapplied, on theapplypayload and on the slot'srule, writes such asdraft.root.not = true,draft.root.children.push(…), assigning a rule'sfield, andvalue.start = …on a date range fail to compile, while narrowing onfieldandoperatorstill narrowsvalueand a read-only applied expression is still assignable toGhostQueryExpression<Fields>. For an active choice field withoptions: [],GhostQueryRulerejects every rule, including{ operator: 'is' }withoutvalue,{ operator: 'is', value: 'x' }and{ operator: 'isMissing' }; on a field with options,iswithoutvalueis rejected andisMissingwith novaluecompiles.
Documentation plan
- A component page
docs/components/query-builder.mdwith 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 withrestore(…, { apply: true })and shows the same IDs, includes a person picker through thevalueslot, and applies results with a revision guard and a simulated delay that can resolve out of order. A second saved filter contains the retiredseverityrule 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.
- Expression model. Field schema types,
defineQueryFields,validateQueryExpression,useGhostQueryBuilderwith the draft/applied split, tree edits, Apply validation, restore and serialization, with the model unit tests and type tests. - Editor structure.
GhostQueryBuilderrendering groups and conditions, AND/OR, NOT, add and remove, names, keyboard and focus recovery, the status region, the text value editor and thevalueslot, with behavior, browser, SSR and type tests, manifest and API docs. - Typed value editors. Choice, yes/no, date (including range) and number editors with their tests.
- 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.
- 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 whileappliedIssuesis non-empty. Whendirtyistruethe example labels Save "Save applied filter" and offers Apply first. Alternative: save the draft, which could store an invalid or never-run filter. - Q2. The composable owns behavior; the component owns DOM concerns.
useGhostQueryBuilderfollows the canonical headless pattern and exposes state and tree edits only. Names, issue relationships, focus recovery and announcements stay inGhostQueryBuilder, 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. - 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. - 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.
- Q5. Editor customization through one
valueslot chosen byfield.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. - Q6. Headless only in the first slice. A themed recipe follows as a separate proposal once the headless parts are stable.
- Q7. What
readonlyrenders. Thereadonlyprop promises focusable, non-editable controls, butGhostCheckbox,GhostRadioGroupandGhostSelectoffer onlydisabled, 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 usesdisabledcontrols, 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.