GhostQueryBuilder
GhostQueryBuilder edits a saved, grouped filter such as Title contains "crash" AND (Assignee is missing OR Reporter equals "ana"). The application defines the fields, runs the applied expression locally or on a server, shows the results and stores saved filters. The builder edits a draft, validates it on Apply and emits a frozen, JSON-serializable expression. It is headless: import it from @ghostvue/vue and bring your own styles.
Every field type has a built-in value editor, and the value slot replaces it where an app needs its own. See the approved specification for the full contract.
Build and apply a filter
Build `Title contains "crash" AND (Assignee is missing OR Reporter equals "ana")` with the keyboard, apply it, and see the applied expression and revision. An empty text value blocks Apply and focus moves to it.
Edit a condition, then select Apply filter. Edits change only the draft, so the applied expression and its revision stay as they were until Apply succeeds. Clear the Title value and apply: the builder keeps the previous expression, shows "Enter a value." next to the input, moves focus there and announces how many conditions need attention. Reset returns the draft to the applied expression.
const fields = defineQueryFields([
{ id: 'title', label: 'Title', type: 'text' },
{ id: 'assignee', label: 'Assignee', type: 'text' },
] as const)defineQueryFields keeps the literal ids and types, so the apply payload and the value slot narrow by field. A field's id is what saved expressions store; its label may change.
Value editors
The Operator list of a condition offers only the operators of its field's type (or the field's own operators subset), and the Value control matches the operator. Operators without a value ("is missing", "is present", "is empty text", "is not empty text") show no Value control.
| Field type | Operators | Value editor |
|---|---|---|
choice | is, is not | GhostSelect with the field's active options |
choice | is any of, is none of | GhostSelect with multiple |
boolean | is | GhostRadioGroup with Yes and No |
date | is on, is before, is after | GhostDatePicker bounded by the field's min/max |
date | is between | Two date pickers labelled From and To |
text | equals, does not equal, contains, does not contain, starts with | GhostInput |
number | comparisons | GhostNumberInput with the field's min, max, step |
number | is between | Two number inputs labelled From and To |
- Missing, empty, zero and false stay distinct. Clearing an input removes the value, so the condition reports "Enter a value." and never stores
""or0in its place.0and "No" (false) are ordinary values, and a yes/no condition has no selection until the user picks one. Use "is missing" for an absent value and "is empty text" for"". - Ranges. "is between" stores
{ min, max }or{ start, end }, inclusive. While only one end is set, Apply is blocked with "Enter both numbers." or "Enter both dates.", focus moves to the missing To control, and the last applied expression stays in place. A start after the end reports "The start must be on or before the end." - Typed dates. A date picker commits typed text on Enter or when focus leaves it. Text it cannot commit yet (half typed or not a date) blocks Apply as pending, with the picker's message when it shows one.
- Retired options. A restored value that names a retired or unknown option stays selected with its issue. Retired options are never offered for new values; in a multiple select the stored option stays listed until the user deselects it.
- Operator changes keep the editor and its value. A value that does not fit the new operator (one date after switching to "is between") is kept and reported on Apply until the user replaces it.
- Values the editor cannot show, such as a restored date that is not a real date or text saved on a number field, are kept and printed next to the editor (the
value-textpart, which also describes the control) with their issue, until the first edit replaces them. - Native form reset. Resetting the enclosing
<form>does not change the draft: the editors show the draft again. Use the builder'sreset()to return the draft to its baseline.
The Yes and No labels come from the messages.value formatter, and the From and To labels from messages.rangeStart and messages.rangeEnd.
Draft versus applied
| Action | Draft | Applied and revision |
|---|---|---|
| Edit a control | Updated | Unchanged |
| Apply, no issue | Normalized | Fresh copy, +1 |
| Apply, blocking issues | Unchanged, issues shown | Unchanged, nothing sent |
reset() | Applied, else baseline | Unchanged |
clear() | Empty root, same root id | Unchanged |
restore(saved) | Saved filter | Unchanged |
Issues caused by the user's own edits, such as a new condition without a value, appear after the first failed Apply and then update live. Issues the user did not cause (a retired field in a restored filter, or a field the app just retired) appear at once. Save the applied expression, not the draft, so a saved filter always passed validation and matches the results on screen. Do not save or re-run applied while appliedIssues is non-empty: the schema changed under it.
Triage issues end to end
Apply `Open AND (High priority OR Overdue)` to five sample issues, save the applied filter separately, and reopen it with the same matching IDs. A saved filter with a retired Severity rule blocks Apply until it is repaired, the Assignee field uses a custom person picker, and a slower, older search never replaces newer results.
The example is a complete app around the builder, with public imports only. It defines the fields, runs each applied filter through a demo search, shows the matching issues and keeps saved filters in memory. It starts with Open AND (High priority OR Overdue) applied, which matches GV-101 and GV-102. Try these steps with the keyboard:
- Tab to the NOT checkbox of Group 2 and press Space. The group heading becomes "Group 2: NOT any condition (OR)", but the results and their revision stay, because only the draft changed. Save now reads Save applied filter: it stores what is applied, not the draft.
- Press Apply filter. The draft becomes revision 2 and the results show GV-104 and GV-105.
- Press Save filter, open "Urgent open issues", then open the filter you saved. The builder shows the negated group again and the results are GV-104 and GV-105 again.
- Open "Last quarter triage". Its Severity condition names a retired field, so Apply is blocked and the previous results stay on screen. Press Remove condition 2: Severity is critical, then Apply filter: the repaired filter applies and shows GV-101 and GV-102.
- Add a condition on Due date with "is between", enter only the From date and apply. Focus moves to To and the results do not change.
- Add a condition on Assignee. Its value is a custom editor: a person picker that blocks Apply while it holds a name it does not know.
The matching code in the example is example code, not a GhostVue API. See Match records for the rules it follows.
Save and restore
Save is a separate action from Apply. Store the applied expression, never the draft, so a saved filter always passed validation and matches the results on screen:
const saved = JSON.stringify(builder.value?.applied)
// Later, after a reload:
const result = builder.value?.restore(JSON.parse(saved), { apply: true })- Disable Save while
appliedisnullorappliedIssuesis non-empty. - While
dirtyistrue, label the button "Save applied filter" so the user knows the edits are not part of it, and offer Apply first. restorereplaces the draft and discards unapplied edits. Ask before calling it whiledirtyistrue.restore(…, { apply: true })emitsapplywith a new revision, so the app runs the same search it runs for Apply. Node ids, grouping, NOT and values come back unchanged, so the same records match.
restore parses untrusted input with validateQueryExpression. Malformed input returns { ok: false, reason } and changes nothing; tell the user the saved filter cannot be opened. restore(…, { apply: true }) never moves focus. Pass a saved filter as defaultExpression to start from it, and applyDefault to make it the initial applied expression at revision 1 without an apply event. With applyDefault, start the first search yourself, for example in onMounted from the template ref's applied and revision, as the triage example does.
Repair a saved filter
A filter can name a field the app has since retired or removed. restore then returns { ok: true, applied: false, issues }:
- The condition keeps its position. Its Field control shows the field's label (or the raw id of an unknown field) with "Severity is no longer available. Choose another field or remove this condition.", and its operator and value are shown as text.
- The issues show at once, because the user did not cause them, and "Saved filter opened. 1 condition needs attention." is announced.
- Nothing is applied. Keep the previous results and say that they belong to the previous filter, as the triage example does. On a first load with nothing applied, show "Repair this filter to see results" rather than unfiltered rows.
- The user picks another field or removes the condition, then applies. The repaired filter no longer names the retired field, so saving it replaces the old one cleanly.
Keep retired fields in the schema with retired: true so their labels stay readable in saved filters. An incompatible stored operator or a retired choice option follows the same pattern, with the issue on the operator or value control.
Match records
GhostVue does not ship a function that runs an expression against records. The app runs it, locally or on a server, and every runner should agree on these rules:
- A group with
andmatches when every child matches; withor, when any child matches. An empty root matches every record, whatever its combinator, so check for no children beforeeveryorsome.not: truematches exactly the records the same group without NOT does not match. - A value comparison, including "is not", "is none of" and "does not equal", never matches a missing (
undefinedornull) value. Use "is missing" inside an OR group, or NOT on a group, to include missing values on purpose. - Ranges include both ends. Dates compare as calendar dates.
- Text comparison case is the app's choice; document it. The triage example compares case-insensitively.
Missing versus empty
Missing, empty text, 0 and false are different values, in the editors, in the applied expression and after a save and restore:
| Condition | Matches | Does not match |
|---|---|---|
assignee isMissing | absent, null | "", "ana" |
assignee isEmpty | "" | absent, null, "ana" |
estimate equals 0 | 0 | absent, null, "", false |
archived is false | false | absent, null, 0, "" |
In the triage data, GV-102 has an empty assignee and GV-104 has none, so "Assignee is empty text" matches only GV-102.
Translate for a server
Walk the expression the same way the local matcher does and emit your query language. A sketch for SQL with bound parameters:
function toSql(group: Group, params: unknown[]): string {
const parts = group.children.map((child) =>
child.kind === 'group' ? toSql(child, params) : ruleToSql(child, params),
)
// An empty root matches every row.
const joined = parts.length
? parts.join(group.combinator === 'and' ? ' AND ' : ' OR ')
: 'TRUE'
return group.not ? `NOT (${joined})` : `(${joined})`
}
// ruleToSql looks up columns in your own field-to-column map, never in the
// input, and returns TRUE or FALSE, never NULL: for example
// `COALESCE(status <> $1, FALSE)`.SQL compares NULL as unknown, and NOT of unknown is still unknown, so a bare status <> $1 inside a negated group would drop rows with a missing status. Wrapping each rule in COALESCE(…, FALSE) keeps both rules above: a comparison never matches a missing value, and NOT on a group is the exact complement.
Translate every operator explicitly and reject unknown ones. Validate the input on the server with validateQueryExpression(input, fields) before translating it: only a valid result is safe to run.
Show the latest results
The builder is synchronous; your search is not. Two Apply actions can resolve out of order, so tie each response to the revision that started it and write only the newest one. useGhostDataTableServerRequest is a guard for any increasing id:
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 }
}In the triage example the demo search answers slower for longer filters. Apply Open AND (High priority OR Overdue), remove "Priority is High" and apply again at once: the shorter search answers first and shows GV-102, and the slower, older answer is discarded when it arrives. Gate the loading indicator and any error with isLatest as well, so an old response cannot clear the loading state of a newer one. Draft edits never change the revision, so results stay tied to the applied expression while the user edits.
Custom value editors
A `value` slot editor for the Assignee field proposes typed values and reports half-typed text as pending, which blocks Apply; other fields keep the built-in editor.
The triage example uses the same person picker for its Assignee field, next to the built-in choice, yes/no, number and date editors.
The value slot replaces the editor of every condition whose field is usable and whose operator takes a value. Check slot.fieldId or slot.fieldType: that narrows field, value and setValue together, so proposing a number for a text field fails to compile. Render slot.DefaultEditor for the other fields.
- Bind
slot.controlPropsto the editor's control. It carries theidthat a failed Apply focuses, the label reference and, while an issue is shown,aria-invalidand the issue's description. setValueproposes a draft value and never applies. Passundefinedto remove the value; never store""or0to mean "empty".- Call
setPending(message)while the editor holds text it has not committed, andsetPending(null)when it commits or clears. While pending, Apply reportsvalue-pendingwith your message. - The builder still validates every proposed value, so a custom editor cannot apply an incompatible value.
Keyboard and focus
The builder is a structured form, not a composite widget. Every control is its own Tab stop and keeps its primitive's keys: the Field, Operator and choice Value controls are GhostSelect comboboxes, Match and the yes/no value are GhostRadioGroups (arrow keys), NOT is a GhostCheckbox (Space), the text value is a GhostInput, the number value is a GhostNumberInput (Arrow Up and Down step), and the date value is a GhostDatePicker (Enter commits typed text; its calendar button opens a dialog). The builder binds no Enter, Delete or Escape of its own. Wrap it in a <form> whose submit handler calls apply(), so Enter in a text or number value applies through native implicit submission.
- Add condition and Add group append and focus the new condition's Field control.
- Remove moves focus, when it was inside the removed item, to the remove button of the item now at that position, else the previous item's, else the group's Add condition button.
- A failed Apply focuses the first invalid control in document order: the missing To control of a half range, or the checked (else first) radio of a yes/no value. Pass
apply({ focus: false })to leave focus alone. - When
restore,resetorclearremoves the node that held focus, focus moves to the root's Add condition button. - Changing a field keeps focus on the Field control.
Accessibility
Name the builder with aria-label or aria-labelledby, for example the id of a visible "Issue filter" heading; a development warning (GHOST043) reports a missing name. Nested groups are named by their visible heading ("Group 2: Any condition (OR)"), and each condition is a group named "Condition 2" whose controls are labelled by visible "Field", "Operator" and "Value" labels (the label part). A range value is a group named "Value" holding "From" and "To" controls. Conditions are list items, so screen readers report how many a group holds; the AND/OR connectors are hidden from assistive technology because the group name states the combinator. A shown issue is rendered next to its control, which gets aria-invalid and an aria-describedby reference to it. One polite status region announces additions, removals, Apply results and restore results.
Disabled and read-only
disabled disables every control; restore, reset, clear and apply still work. readonly renders each condition as static text (field, operator and value) and each group with its combinator and NOT, with no form controls and no Tab stops of its own. disabled wins over readonly.
Localization
Pass messages to override any component-owned string. 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, for example ruleName: (index) => \Bedingung ${index}`. The issue` formatter receives each issue with its field and node, for localized issue text.
Styling hooks
Style the builder's data-part values: root, group, group-header, group-name, combinator, not, children, connector, rule, field, operator, value, value-text, label, remove, add-rule, add-group, issue, empty and status. Groups carry data-combinator, data-negated and data-depth; rules carry data-depth and data-retired; both carry data-invalid while an issue is shown. The root carries data-disabled and data-readonly. The nested primitives keep their own parts (a select's trigger and value, a radio group's root), so scope selectors with child combinators, as the examples do. The Field, Operator and choice Value popups are portaled to <body> and carry the ghost-query-builder-listbox class; date calendars carry ghost-query-builder-calendar. Wrapper nesting between parts is not a contract.
Custom markup
useGhostQueryBuilder holds all behavior: the draft and applied state, tree edits, Apply, restore, reset and clear. Call it to render your own markup. Names, issue relationships, focus movement and announcements are then yours to provide, as described in Accessibility and Keyboard and focus.
API
| Prop | Type | Default | Description |
|---|---|---|---|
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. |
createId | ((kind: 'group' | 'rule') => string) | — | Mints ids for nodes the user adds. Never called during setup, so a random or counter id is SSR-safe. A returned duplicate is a development error and is replaced. |
defaultExpression | unknown | — | Initial draft, read once at setup through validateQueryExpression. Malformed input starts an empty draft and warns in development. |
disabled | boolean | false | Disables every control. Programmatic restore, reset, clear and apply still work. |
fields | Fields | Required | Consumer-owned schema. Reactive: a change revalidates the draft and never changes the applied expression. |
maxDepth | number | 3 | Nesting levels the user can create, counting the root as 1. |
messages | Partial<GhostQueryBuilderMessages> | — | Reactive overrides for every component-owned string. Omitted entries use the English defaults. |
readonly | boolean | false | Renders the draft as static text with no form controls and no add or remove actions. disabled takes precedence. |
| Event | Payload | Description |
|---|---|---|
apply | GhostQueryApplyEvent<Fields> | After every successful Apply, including a programmatic one, a restore with apply: true and an Apply of an unchanged draft. The expression is a fresh, frozen, deep copy; revision increases by one each time. A failed Apply emits nothing. |
| Slot | Slot props | Description |
|---|---|---|
actions | — | Renders after the root group, typically Apply, Reset and the app's Save button. |
empty | — | Renders inside an empty root group, before its Add condition button. |
value | — | Replaces the value editor of every rule that has a usable field and an operator that takes a value. |
Template ref
The template ref exposes apply(options?), restore(input, options?), reset() and clear(), and the read-only state draft, applied, revision, dirty, issues and appliedIssues (GhostQueryBuilderExposed<Fields>). The actions slot binds the same members except restore and draft (GhostQueryActionsSlotProps<Fields>). The value slot binds GhostQueryValueSlotProps<Fields>: fieldId, fieldType, field, rule, operator, value, setValue, setPending, controlProps and DefaultEditor.
Issue codes
| Code | Attached to | Meaning |
|---|---|---|
field-required | field | No field chosen yet. |
field-unknown | field | The stored field id is not in the schema. |
field-retired | field | The field is retired. |
field-duplicate | field | The schema defines the field id more than once. |
field-misconfigured | field | The field is set up incorrectly. |
operator-incompatible | operator | The operator does not work with the field. |
value-required | value | No value entered. |
value-incomplete | value | One end of a range is missing. |
value-pending | value | An editor holds text it has not committed. |
value-invalid | value | The value does not fit the field and operator. |
value-out-of-range | value | The value is outside the field's min and max. |
range-order | value | The start of a range is after its end. |
option-retired | value | A chosen option is retired. |
value-rejected | value | The field's validate returned a message. |
group-empty | group | A nested group, or a negated root, has no conditions. |