Skip to content

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 ​

Filter by text fields Headless

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.

Issue filter

Match
  • Field
    Operator
    Value
  • Group 2: Any condition (OR)
    Match
    • Field
      Operator
    • Field
      Operator
      Value

Applied filter (revision 0)

Nothing applied yet.

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.

ts
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 typeOperatorsValue editor
choiceis, is notGhostSelect with the field's active options
choiceis any of, is none ofGhostSelect with multiple
booleanisGhostRadioGroup with Yes and No
dateis on, is before, is afterGhostDatePicker bounded by the field's min/max
dateis betweenTwo date pickers labelled From and To
textequals, does not equal, contains, does not contain, starts withGhostInput
numbercomparisonsGhostNumberInput with the field's min, max, step
numberis betweenTwo 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 "" or 0 in its place. 0 and "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-text part, 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's reset() 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 ​

ActionDraftApplied and revision
Edit a controlUpdatedUnchanged
Apply, no issueNormalizedFresh copy, +1
Apply, blocking issuesUnchanged, issues shownUnchanged, nothing sent
reset()Applied, else baselineUnchanged
clear()Empty root, same root idUnchanged
restore(saved)Saved filterUnchanged

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 ​

Triage issues with saved filters Headless

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.

Issue filter

Match
  • Field
    Operator
    Value
  • Group 2: Any condition (OR)
    Match
    • Field
      Operator
      Value
    • Field
      Operator
      Value

Saved filters

  • Urgent open issues
  • Open, hide archived and unassigned
  • Last quarter triage

Matching issues

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:

  1. 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.
  2. Press Apply filter. The draft becomes revision 2 and the results show GV-104 and GV-105.
  3. 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.
  4. 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.
  5. 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.
  6. 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:

ts
const saved = JSON.stringify(builder.value?.applied)
// Later, after a reload:
const result = builder.value?.restore(JSON.parse(saved), { apply: true })
  • Disable Save while applied is null or appliedIssues is non-empty.
  • While dirty is true, label the button "Save applied filter" so the user knows the edits are not part of it, and offer Apply first.
  • restore replaces the draft and discards unapplied edits. Ask before calling it while dirty is true.
  • restore(…, { apply: true }) emits apply with 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 and matches when every child matches; with or, when any child matches. An empty root matches every record, whatever its combinator, so check for no children before every or some. not: true matches 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 (undefined or null) 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:

ConditionMatchesDoes not match
assignee isMissingabsent, null"", "ana"
assignee isEmpty""absent, null, "ana"
estimate equals 00absent, null, "", false
archived is falsefalseabsent, 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:

ts
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:

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

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

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 ​

Custom value editor Headless

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.

Assignment filter

Match
  • Field
    Operator
    Value

Nothing applied yet.

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.controlProps to the editor's control. It carries the id that a failed Apply focuses, the label reference and, while an issue is shown, aria-invalid and the issue's description.
  • setValue proposes a draft value and never applies. Pass undefined to remove the value; never store "" or 0 to mean "empty".
  • Call setPending(message) while the editor holds text it has not committed, and setPending(null) when it commits or clears. While pending, Apply reports value-pending with 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, reset or clear removes 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 ​

PropTypeDefaultDescription
applyDefaultbooleanfalseWhen 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.
defaultExpressionunknown—Initial draft, read once at setup through validateQueryExpression. Malformed input starts an empty draft and warns in development.
disabledbooleanfalseDisables every control. Programmatic restore, reset, clear and apply still work.
fieldsFieldsRequiredConsumer-owned schema. Reactive: a change revalidates the draft and never changes the applied expression.
maxDepthnumber3Nesting levels the user can create, counting the root as 1.
messagesPartial<GhostQueryBuilderMessages>—Reactive overrides for every component-owned string. Omitted entries use the English defaults.
readonlybooleanfalseRenders the draft as static text with no form controls and no add or remove actions. disabled takes precedence.
EventPayloadDescription
applyGhostQueryApplyEvent<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.
SlotSlot propsDescription
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 ​

CodeAttached toMeaning
field-requiredfieldNo field chosen yet.
field-unknownfieldThe stored field id is not in the schema.
field-retiredfieldThe field is retired.
field-duplicatefieldThe schema defines the field id more than once.
field-misconfiguredfieldThe field is set up incorrectly.
operator-incompatibleoperatorThe operator does not work with the field.
value-requiredvalueNo value entered.
value-incompletevalueOne end of a range is missing.
value-pendingvalueAn editor holds text it has not committed.
value-invalidvalueThe value does not fit the field and operator.
value-out-of-rangevalueThe value is outside the field's min and max.
range-ordervalueThe start of a range is after its end.
option-retiredvalueA chosen option is retired.
value-rejectedvalueThe field's validate returned a message.
group-emptygroupA nested group, or a negated root, has no conditions.