Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
27 changes: 22 additions & 5 deletions AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -24,8 +24,8 @@ solid-querybuilder/
└── ssr/ # hand-rolled Vite SSR consumer; the SSR gate
```

**Target is Solid 2 only.** Peers are `solid-js@^2.0.0-rc.0` **and
`@solidjs/web@^2.0.0-rc.0`** — in Solid 2 the DOM runtime is its own package. There is no
**Target is Solid 2 only.** Peers are `solid-js@^2.0.0` **and `@solidjs/web@^2.0.0`** — in
Solid 2 the DOM runtime is its own package. There is no
`^1.9` leg anywhere: in the manifest, in CI, or in the source. A v1-target port, if it ever
happens, is a separate repo publishing as `@react-querybuilder/solid1`; do not add compatibility
shims or `solid-js@1` code paths here.
Expand Down Expand Up @@ -165,8 +165,15 @@ type-only module erased by the bundler), and allows `./foo.jsx` under `dist/sour
Every write-then-read must `flush()` first. Never paper over this with `setTimeout` or tick
counts. `@solidjs/testing-library`'s `render` populates the container synchronously; subsequent
updates need `flush()`.
- Return getter objects (not objects of accessors, not memoized fresh objects) from composables
- **Return getter objects** (not objects of accessors, not memoized fresh objects) from composables
whose result is read once by a Solid context or passed as a prop.
- ⚠️ **A memo that returns fresh objects notifies every reader.** E.g. `RuleGroupBody`'s
`keyedRules` rebuilds each row's entry on any child change; per-row reads go through
equality-gated memos (`pathsAreEqual` for paths) or one edit re-runs every rule's props.
`fine-grained.test.tsx` (200 rules, one edit → one value-editor recompute) is the gate.
- ⚠️ **The controlled-`query` sync effect is `{ defer: true }`.** Seeding already applied the
mount-time query; a first run compares the raw prop to the _prepared_ one (gained a root `id`),
sees `:id`, and commits — firing `onQueryChange` and an undo entry on mount.
- **There is no `onMount`.** Solid 2 does not export one. The post-commit-mount equivalent is
`createEffect(() => undefined, () => { … })`: a constant compute phase runs the apply phase once,
after render, and never under SSR — which is what React's mount `useEffect` does.
Expand Down Expand Up @@ -317,6 +324,16 @@ The example gate was proved red twice, independently, and reverted both times:
hydration surface comparison red while every markup assertion stayed green. Those two failure
modes share no code, which is the point of having both.

The SSR example also renders a radio editor and the not-toggle (`createUniqueId` users). Its id
check (ids unique, every `label[for]` resolves) was proved red: a constant `NotToggle` id → "duplicate
ids". ⚠️ Client-side id **drift** is not detectable here and the gate does not claim it: Solid 2
hydration adopts server attributes, so a client-only id suffix _and_ an extra client-only
`createUniqueId()` call both left the surface unchanged and hydration error-free.

New unit gates (#3), each proved red: `fine-grained.test.tsx` (without the `RuleGroupBody` memos,
all 200 value editors recompute) and the controlled-mount / store-feedback tests in
`createQueryBuilder.test.ts` (without `{ defer: true }`, both red).

All five were proven red once and reverted: coverage (threshold to 99 + an injected
uncovered function), export-condition **order** (`import` moved first), export-condition
**target** (`solid` repointed at `dist/index.js`), the SSR **markup** assertion (component's label
Expand Down Expand Up @@ -354,5 +371,5 @@ is how CI runs it.

## Repo status

**Remote-less.** The repo is a local git repo with no GitHub remote and nothing pushed.
`.github/workflows/ci.yml` exists so it is in place whenever a remote is added.
GitHub remote: `react-querybuilder/solid-querybuilder` (`origin`). Work lands via PRs against
`main`; CI is `.github/workflows/ci.yml`.
13 changes: 13 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,19 @@ adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).

## [Unreleased]

### Fixed

- Radio value-editor ids are now index-based (`<uid>-<index>`) instead of name-based
(`<uid>-<name>`). Duplicate option names no longer collide, and names like core's `~`
placeholder (rendered by default when `autoSelectValue` is off, as in React) no longer leak into
ids. Ids remain opaque; DOM parity is unaffected.
- Controlled mode no longer commits on mount. A `query` without a root `id` (the usual case) was
re-applied by the sync effect's first run against the prepared query, firing `onQueryChange`
and leaving an undo entry even with `enableMountQueryChange={false}`.
- A single edit no longer re-evaluates every rule's props. `RuleGroupBody` rebuilt every row's
entry on any child change; per-row values are now equality-gated memos. Guarded by a 200-rule
fine-grained test.

### Removed

- **Breaking:** `createRuleContext` and `createRuleGroupContext` are no longer exported. Each was a
Expand Down
32 changes: 21 additions & 11 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,14 +7,13 @@ byte-identical DOM output.

## ⚠️ Requires Solid 2.0

This package targets **Solid 2 only**. Its peer dependencies are `solid-js@^2.0.0-rc.0` **and**
`@solidjs/web@^2.0.0-rc.0` — in Solid 2 the DOM runtime ships as its own package, so both are
This package targets **Solid 2 only**. Its peer dependencies are `solid-js@^2.0.0` **and**
`@solidjs/web@^2.0.0` — in Solid 2 the DOM runtime ships as its own package, so both are
required.

Solid 2 is currently in **beta**, and this package tracks it deliberately rather than waiting: the
port is built on Solid 2 idiom (`merge`/`omit`, split effects, `createStore` from `solid-js`) that
has no faithful Solid 1 equivalent. It does not carry `solid-js@1` compatibility shims and it never
will. Should demand warrant a Solid 1.x port, it would be published separately as
The port is built on Solid 2 idiom (`merge`/`omit`, split effects, `createStore` from `solid-js`)
that has no faithful Solid 1 equivalent. It does not carry `solid-js@1` compatibility shims and it
never will. Should demand warrant a Solid 1.x port, it would be published separately as
`@react-querybuilder/solid1`.

## Installation
Expand All @@ -23,9 +22,8 @@ will. Should demand warrant a Solid 1.x port, it would be published separately a
npm install solid-querybuilder
```

`solid-js@^2.0.0-rc.0` and `@solidjs/web@^2.0.0-rc.0` are peer dependencies. Install
`@solidjs/web` from the `next` dist-tag; its `latest` tag is `2.0.0-experimental.0`, an incompatible
line. `@react-querybuilder/core` is a regular dependency and is re-exported in full — `formatQuery`,
`solid-js@^2.0.0` and `@solidjs/web@^2.0.0` are peer dependencies.
`@react-querybuilder/core` is a regular dependency and is re-exported in full — `formatQuery`,
`defaultOperators`, `transformQuery`, `QueryManager` and the rest all import from
`solid-querybuilder` — so you never need to depend on it directly.

Expand Down Expand Up @@ -57,6 +55,8 @@ function App() {
}
```

`query={query()}` is a getter, so the prop tracks the signal. ⚠️ Solid 2 defers writes: a read right after `setQuery(...)` still returns the previous value until the next microtask (or `flush()`). See [deferred writes](./docs/differences-from-react-querybuilder.md#4-query-binding).

## Driving the query

| Approach | Use when |
Expand Down Expand Up @@ -119,6 +119,15 @@ identities) rather than `state.query` (a plain identity signal) whenever you are
`state.manager` is the underlying [`QueryManager`](https://react-querybuilder.js.org); everything
else is derived from it.

Core's path helpers (`findPath`, `getParentPath`, `pathsAreEqual`, `pathIsDisabled`, `add`, `remove`, `move`, `update`, and the rest) are exported from `solid-querybuilder`. Custom UIs can do path math without depending on core directly:

```tsx
import { findPath, getParentPath } from 'solid-querybuilder';

const node = findPath([1, 0], state.query); // rule or group at path [1, 0]
const parentPath = getParentPath([1, 0]); // [1]
```

## Styling

Two prebuilt stylesheets ship in `dist`: `query-builder.css` (full) and
Expand All @@ -130,7 +139,7 @@ Two prebuilt stylesheets ship in `dist`: `query-builder.css` (full) and

- [`docs/customization.md`](./docs/customization.md) — translations, `controlElements`, context,
writing a replacement component, external control, class names.
- [`docs/differences-from-react-querybuilder.md`](./docs/differences-from-react-querybuilder.md) —
- [`docs/differences-from-react-querybuilder.md`](./docs/differences-from-react-querybuilder.md#4-query-binding).—
what is and is not ported, and every intentional divergence.
- [`docs/styling.md`](./docs/styling.md) — stylesheets, custom properties, class-name overrides.
- [React Query Builder's documentation](https://react-querybuilder.js.org) applies to props,
Expand All @@ -146,7 +155,8 @@ Two prebuilt stylesheets ship in `dist`: `query-builder.css` (full) and
## Non-goals

Drag and drop, UI-framework compatibility packages, `expr`/`datetime` UI, async option lists,
a Redux store, and deprecated-prop fallbacks are all out of scope for v1.
a Redux store (and with it `qbId`), `preserveQueryStateOnUnmount`, and deprecated-prop fallbacks
are all out of scope for v1.

## License

Expand Down
46 changes: 46 additions & 0 deletions docs/customization.md
Original file line number Diff line number Diff line change
Expand Up @@ -157,6 +157,48 @@ Two smaller notes:
- Build class strings with core's `clsx`, not template interpolation, if you care about matching
React Query Builder's output byte for byte.

### Replacing `rule` / `ruleGroup`

`controlElements.rule` receives `RuleProps`, and `controlElements.ruleGroup` receives `RuleGroupProps`. Both are exported, and they share these members:

| Prop | Meaning |
| -------------------------------------------- | ---------------------------------------------------------------------- |
| `rule` / `ruleGroup` | The node itself, a store-mirror proxy with a stable identity per `id`. |
| `path` | Its `Path` (`number[]`). Use core's path helpers to do path math. |
| `schema` | Fields, operators, resolvers, flags, and `schema.controls`. |
| `actions` | `onPropChange`, `onRuleAdd`, `onRuleRemove`, `moveRule`, and so on. |
| `translations`, `context` | Same as in React Query Builder. |
| `disabled`, `parentDisabled`, `parentMuted` | Disabled and muted state, both the node's own and inherited. |
| `shiftUpDisabled`, `shiftDownDisabled`, `id` | Positional flags, and the node `id`. |

The simplest replacement wraps the default:

```tsx
import { Rule, type RuleProps } from 'solid-querybuilder';

const MyRule = (props: RuleProps) => (
<div class="my-rule-wrapper">
<Rule {...props} />
</div>
);
```

A rule built from scratch writes through `actions` with its own `path`:

```tsx
const MyRule = (props: RuleProps) => (
<input
value={String(props.rule.value ?? '')}
disabled={props.disabled || props.parentDisabled}
onInput={e => props.actions.onPropChange('value', e.currentTarget.value, props.path)}
/>
);
```

`createRuleState(props)` and `createRuleGroupState(props)` are exported too. They are the primitives the default components use (class names, the resolved field and operator, and handlers), so a from-scratch replacement can reuse them instead of rebuilding them. A replacement `ruleGroup` that renders its own children should render each child through `props.schema.controls.rule` / `props.schema.controls.ruleGroup`, so that nested overrides still apply.

Generic replacements: Solid components have no compile-time prop enumeration. If your component is generic over field or operator types, write it against the default type parameters and widen once at the boundary (`props as unknown as RuleProps`), which is what the default components do.

## External control

Pass a `QueryManager` you own and drive the query from anywhere:
Expand All @@ -183,6 +225,10 @@ The manager owns every write; the component subscribes. ⚠️ Hand the manager
deep-freezes its inputs with Immer, which rejects a Solid store proxy. If a query came out of a
Solid store, `snapshot()` it first.

⚠️ **The component never reconfigures an external manager, and reads it once.** Structural props (`fields`, `operators`, `combinators`, and so on) are not pushed into a manager you pass in, so configure it directly (`new QueryManager(query, { fields, … })` / `manager.reconfigure(…)`). The `manager` prop is read at mount only, so swapping in a different instance later is ignored. To switch managers, remount the component.

⚠️ **The manager's query wins at mount.** With both `manager` and `query` passed, the mount-time `query` is ignored: the component renders the manager's current query, and the mount-time `onQueryChange` (when `enableMountQueryChange` is on) reports that query, not the prop. Only later `query` changes are pushed into the manager. Seed the manager with the initial query instead (`new QueryManager(query, …)`).

Between the `manager` prop and the veto callbacks (`onAddRule`, `onAddGroup`, `onRemove`,
`onMoveRule`, `onMoveGroup`, `onGroupRule`, `onGroupGroup`, `onUngroup` — each of which can cancel or rewrite the
pending change), this replaces everything React Query Builder's Redux store was used for. See
Expand Down
14 changes: 14 additions & 0 deletions examples/ssr/src/App.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,17 @@ export const fields: Field[] = [
{ name: 'firstName', label: 'First Name' },
{ name: 'lastName', label: 'Last Name' },
{ name: 'age', label: 'Age', inputType: 'number' },
// Radio editor and (via `showNotToggle`) the not-toggle both mint ids with `createUniqueId`;
// the hydration surface compares `id`/`for`, so a server/client id drift fails the gate.
{
name: 'color',
label: 'Color',
valueEditorType: 'radio',
values: [
{ name: 'red', label: 'Red' },
{ name: 'blue', label: 'Blue' },
],
},
];

/**
Expand All @@ -31,6 +42,8 @@ export const query: RuleGroupTypeIC = {
{ id: 'r-2', field: 'lastName', operator: '=', value: 'Vai' },
'and',
{ id: 'r-3', field: 'age', operator: '<', value: 90 },
'and',
{ id: 'r-4', field: 'color', operator: '=', value: 'blue' },
],
},
],
Expand Down Expand Up @@ -58,6 +71,7 @@ export const App = (props: { query: RuleGroupTypeIC }) => (
<QueryBuilder
fields={fields}
defaultQuery={props.query}
showNotToggle
controlElements={{ removeRuleAction: CustomRemoveRule }}
/>
);
24 changes: 22 additions & 2 deletions examples/ssr/ssr-smoke-test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -126,11 +126,13 @@ const fragments = [
'data-testid="inline-combinator"',
// The one control passed through `controlElements`.
'custom-remove-rule',
'data-testid="not-toggle"',
'type="radio"',
// Server-side `formatQuery(query, 'sql')`, in its HTML-escaped form: Solid's SSR escapes text
// content, so `'` is `&#39;` and `>` is `&gt;`. Matching the raw SQL here would be a
// false-negative waiting to happen. [Vue hindsight]
'(firstName like &#39;Stev&#39;&#39;e%&#39; and age &gt; &#39;28&#39; or ' +
'(lastName = &#39;Vai&#39; and age &lt; &#39;90&#39;))',
'(lastName = &#39;Vai&#39; and age &lt; &#39;90&#39; and color = &#39;blue&#39;))',
];

for (const fragment of fragments) {
Expand All @@ -152,8 +154,14 @@ const surface = (root: Element): string =>
el.getAttribute('class') ?? '',
el.getAttribute('data-testid') ?? '',
el.getAttribute('data-path') ?? '',
// `createUniqueId` output (radio editor, not-toggle): must survive hydration unchanged.
el.getAttribute('id') ?? '',
el.getAttribute('for') ?? '',
el.getAttribute('name') ?? '',
];
if (el instanceof (el.ownerDocument.defaultView!.HTMLInputElement)) parts.push(el.value);
if (el instanceof (el.ownerDocument.defaultView!.HTMLInputElement)) {
parts.push(el.value, String(el.checked));
}
if (el instanceof (el.ownerDocument.defaultView!.HTMLSelectElement)) parts.push(el.value);
if (el instanceof (el.ownerDocument.defaultView!.HTMLTextAreaElement)) parts.push(el.value);
return parts.join('|');
Expand Down Expand Up @@ -182,6 +190,18 @@ const serverRoot = window.document.querySelector('#root');
check(serverRoot !== null, 'served HTML has no #root element (did the render throw?)');
const serverSurface = serverRoot ? surface(serverRoot) : '';

// `createUniqueId` (radio editor, not-toggle): ids unique, and every `<label for>` resolves.
// Client-side id drift is invisible here by design — hydration adopts server attributes.
if (serverRoot) {
const ids = [...serverRoot.querySelectorAll('[id]')].map(el => el.id);
check(ids.length >= 3, `expected radio + not-toggle ids, found ${ids.length}`);
check(new Set(ids).size === ids.length, `duplicate ids in served HTML: ${ids.join(', ')}`);
for (const label of serverRoot.querySelectorAll('label[for]')) {
const target = label.getAttribute('for')!;
check(ids.includes(target), `<label for="${target}"> has no matching id`);
}
}

// The built client entry is a self-contained ES module, so it is imported into *this* process
// against jsdom's globals rather than executed by jsdom, which cannot run `type="module"`.
const restore = installGlobals(window);
Expand Down
33 changes: 33 additions & 0 deletions packages/solid-querybuilder/src/components/QueryBuilder.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -159,6 +159,39 @@ describe('QueryBuilder', () => {
expect(container.querySelectorAll('[data-testid="rule"]')).toHaveLength(0);
});

it('lets an external manager take precedence over a mount-time query prop', () => {
const manager = new QueryManager<RuleGroupType>(query, { fields, history: true });
const [q, setQ] = createSignal<RuleGroupType>({
id: 'root',
combinator: 'and',
rules: [
{ id: 'a', field: 'f1', operator: '=', value: 'a' },
{ id: 'b', field: 'f2', operator: '=', value: 'b' },
],
});
const onQueryChange = vi.fn();
const { container } = render(() => (
<QueryBuilder
fields={fields}
manager={manager as never}
query={q()}
onQueryChange={onQueryChange}
/>
));
flush();
expect(container.querySelectorAll('[data-testid="rule"]')).toHaveLength(1);
expect(manager.getQuery()).toBe(query);
// Only the standard mount notification, carrying the manager's query.
expect(onQueryChange).toHaveBeenCalledTimes(1);
expect(onQueryChange).toHaveBeenLastCalledWith(query);

// A later `query` change is still pushed into the manager.
setQ({ id: 'root', combinator: 'and', rules: [] });
flush();
expect(container.querySelectorAll('[data-testid="rule"]')).toHaveLength(0);
expect(onQueryChange).toHaveBeenCalledTimes(2);
});

/** The props-reactivity gate for this component. */
it('updates when its configuration props change', () => {
const [showCloneButtons, setShowCloneButtons] = createSignal(false);
Expand Down
20 changes: 20 additions & 0 deletions packages/solid-querybuilder/src/components/ValueEditor.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -117,6 +117,26 @@ describe('ValueEditor', () => {
expect(handleOnChange).toHaveBeenCalledWith('s2');
});

it('derives radio ids from position, not option name', () => {
const odd = [
{ name: '~', value: '~', label: '------' },
{ name: 'a b', value: 'a b', label: 'A B' },
{ name: 'dup', value: 'dup', label: 'Dup 1' },
{ name: 'dup', value: 'dup', label: 'Dup 2' },
];
const { getByTestId } = render(() => (
<ValueEditor {...baseProps({ type: 'radio', values: odd })} />
));
const span = getByTestId('value-editor');
const inputs = [...span.querySelectorAll('input')];
expect(inputs.map(i => i.value)).toEqual(['~', 'a b', 'dup', 'dup']);
expect(new Set(inputs.map(i => i.id)).size).toBe(4);
for (const input of inputs) expect(input.id).not.toMatch(/[~\s]|dup/);
for (const label of span.querySelectorAll('label')) {
expect(span.querySelector(`[id="${label.getAttribute('for')}"]`)).not.toBeNull();
}
});

it('renders a single selector for `select` and a multiselect for `multiselect`', () => {
const { getByTestId, unmount } = render(() => (
<ValueEditor {...baseProps({ type: 'select', values, value: 's2' })} />
Expand Down
Loading