Installation
Browser — one file each
<link rel="stylesheet" href="dist/k-conditions.min.css">
<script src="dist/k-conditions.min.js"></script>
The bundle is the editor, the evaluator and the SQL builder together, with
every skin — about 21 KB gzipped. It sets both KConditions
and KConditionsEditor on the global, so everything below
applies unchanged.
Browser — the sources, no build step
<link rel="stylesheet" href="src/k-conditions-editor.css">
<link rel="stylesheet" href="src/k-conditions-skins.css">
<script src="src/k-conditions-evaluator.js"></script>
<script src="src/k-conditions-sql.js"></script> <!-- optional -->
<script src="src/k-conditions-editor.js"></script>
The evaluator must load first — the editor uses its operator metadata and its
describe() function. The skins stylesheet is required for every skin
except boxed, and the SQL builder only if you want
SQL output. All three scripts are UMD, so they also work through a
bundler or under Node.
npm
npm install @kastrack/conditions-editor
const KConditions = require('@kastrack/conditions-editor');
// or, in the browser bundle:
import KConditionsEditor from '@kastrack/conditions-editor/editor';
import '@kastrack/conditions-editor/editor.css';
What is in dist/
| File | What it is |
|---|---|
k-conditions.min.css | Base plus every skin, minified — the one stylesheet. |
k-conditions.min.js | Evaluator, SQL builder and editor, minified — the one script. |
k-conditions.css / .js | The same two bundles unminified, for debugging. |
k-conditions-*.min.css / .min.js | One minified file per source, if you would rather pick. |
LICENSE | The licence, so the folder can be vendored as it stands. |
dist/ is generated by npm run build, and from 0.1.2 it
is committed: every tag carries the built files for that version. To vendor a
release, take dist/ from the tag and record the version (it is also in
each file's banner), or load it from a CDN that serves tags —
https://cdn.jsdelivr.net/gh/KAStrack/kConditionsEditor@v0.1.7/dist/k-conditions.min.js.
The npm package carries the same files. The sources remain the deliverable: edit
src/, then rebuild; npm test fails while dist/
is not what the build makes from src/.
Composer
composer require kastrack/conditions-editor
Or without Composer:
require __DIR__ . '/kConditionsEditor/sdk/php/autoload.php';
Editor options
const editor = KConditionsEditor.attach('#conditions', { /* options */ });
| Option | Default | What it does |
|---|---|---|
fields | [] | Array of field definitions. See below. |
operators | {} | Custom operator definitions, keyed by name. |
skin | "prose" | Which visual treatment to use. See Skins. |
theme | null | "light" or "dark" to pin a theme; omit to follow the viewer's system setting. |
layout | from skin | "tree" or "flow". Normally inferred — only set it to pair a flow layout with your own stylesheet. |
emptyText | "Always" | Shown in the collapsed area when there are no conditions. Also settable later with setEmptyText(). |
labels | {} | Every word the editor shows, reads out or puts in a tooltip, including the operator names (labels.operators), the operator list's headings (labels.groups) and the incomplete-rule messages (labels.problems). See Translating. |
startOpen | false | Open the builder immediately instead of showing the Edit button. |
collapsible | true | Show the Done button that returns to the summary view. |
readOnly | false | Render the summary only; no editing. |
showJson | false | Add a collapsible JSON preview under the builder. |
pretty | true | Pretty-print the JSON written to the textarea. |
maxDepth | 6 | How deeply groups may nest. The + Group button disappears at the limit. |
allowGroupNegate | true | Show the NOT checkbox on each group. |
allowConditionNegate | false | Show a NOT checkbox on each condition row too. |
defaultGroupOperator | "and" | Logic used by newly added groups. |
summaryHtml | false | Render the collapsed summary as HTML — bold fields, underlined values. See Showing a rule. |
hideTextarea | true | true hides the field (keeping it in the form), false leaves it visible, "toggle" hides it but adds a Show source button. See Hiding the field. |
hideTarget | null | What to hide instead of the textarea: a CSS selector, an element, or a list of them. |
output | "json" | "json" or "sql" — what gets written into the textarea. See SQL output. |
sql | null | Options handed to the SQL builder (dialect, parameters, …). |
documentInput | null | Selector or element that always receives the JSON, so output: "sql" can be reloaded. |
documentInComment | false | Carry the document in a leading SQL comment instead, so a single existing SQL field round-trips. |
allowWrapGroup | true | Show the AND(…) / OR(…) button that brackets the current group. See Building a rule. |
allowFieldValues | false | Offer the Value / Field selector so a value can point at another field. A field naming comparableWith opts itself in. See Field definitions. |
allowClear | true | Show the "Clear and start over" control in the footer. |
history | true | Undo / redo: footer buttons, Ctrl+Z, and the API. See Undo and reordering. |
historyLimit | 50 | How many steps back the history keeps. |
historyIdle | 500 | Milliseconds of quiet that end a run of typing and commit it as one entry. |
allowReorder | true | Move up / move down controls, and Alt+↑/↓. |
allowDrag | true | The drag grip. The move buttons stay either way. |
connectorPlacement | "below" | Where prose puts each AND / OR. "below": on a line of its own, starting where the text above it starts (the field name, or the ) after a group). "inline": on the row's line, just after the value — more compact. See Where the AND / OR goes. |
alignConnectors | true | With connectorPlacement: "inline", line the operators up into a column per indent level. "group" for one column per group; false for none. |
groupGuides | true | In prose, a thin line down the left of each bracketed group's rows, in its AND / OR colour (dashed when negated). Pointing at a group's AND / OR or a bracket strengthens it. false for none. |
controls | "hover" | When the row controls (grip, arrows, ×, add buttons, a group's tools) are shown: "hover" reveals them on the row pointed at or focused; "always" shows them at rest. A screen with no hover always gets "always". |
previewStyle | "bar" | How the hover/focus preview of an add button or × is drawn: "bar", "highlight", "region", "fade", "color", "marker" or "underline". Independent of skin. |
decorateSelect | null | (select, { role, node, field, editor }) => void | false | Promise. Hand each <select> to the host's own widget once it is built, filled and on the page; called on every render. See A host's select widget. |
releaseSelect | null | (select, { role, node, field }) => void. Tear down a decorated select's widget before a render discards it, and on destroy(). |
focusSelect | null | (select) => void. Focus a decorated select's widget after a render. Without it, the first focusable element in the select's shell. |
kselect | "auto" | kSelect for the long lists: "auto" uses it when the page has it, true uses it and loads it from the CDN if not, false never; or pass the Kselect constructor. See kSelect, built in. |
kselectRoles | long lists | Which selects kSelect takes; ['field', 'fieldValue', 'value', 'values'] unless given. |
kselectOptions | null | kSelect options over the editor's own: an object, or (select, { role, node, field }) => object. |
kselectSrc | pinned CDN | Where kselect: true loads it from: { js, css, jsIntegrity, cssIntegrity }. |
debug | false | Show the View source panel. See Debugging. |
onChange | null | (document, payload) => void. payload carries json, valid, problems and empty. |
input and change events, so existing form
handlers, dirty-tracking and validation keep working untouched.
Building a rule
A rule grows from the logic word rather than from a generic "add row"
button. Every insertion point carries a +AND or
+OR beside the connector it extends:
- The operator the group already uses adds another condition at that point.
- The other operator wraps the condition on that line in a new sub-group carrying it.
So State is CA → +AND → Name is Ben
→ +OR → Name is Nanci produces
State is CA AND (Name is Ben OR Name is Nanci), without anyone
having to think about brackets.
Mid-list positions offer only the group's own operator — the one that reads
naturally next to the connector already printed there. The last row of each
group offers both, so there is exactly one place to reach for when changing
precedence. Two conveniences keep the tree from growing needless levels: a
group of one child is retuned rather than wrapped, and clicking
+OR beside a group that is already an OR extends
it instead of nesting another inside it.
AND(…) and OR(…) — closing a strand
+AND and +OR bind tighter: they act on the
row you clicked. To go the other way, the last row of any group holding more
than one child carries a third button showing whichever operator the group
is not using. It brackets everything built so far, switches
the group to the other operator, and leaves a fresh condition waiting
underneath.
So Name is B → +OR → Name is N →
AND(…) → State is CA → +OR →
State is LA produces
(Name is B OR Name is N) AND (State is CA OR State is LA) — both
halves typed forwards, in reading order, with no going back to insert a
group. Only one of the pair is ever shown, since the group's own operator is
already offered as +AND / +OR beside it.
The fresh condition arrives as a plain sibling rather than inside a group of
its own: a one-child group renders as an empty pair of brackets, and the next
+OR turns it into the group it was going to be anyway. If the
newly bracketed group's operator matches its parent's and neither is negated,
it dissolves into the parent instead of nesting a redundant level. Turn the
button off with allowWrapGroup: false, or drive it from code
with editor.wrapAndContinue(group, 'and').
The buttons stay hidden until the pointer is on the line they belong to, or
until they take keyboard focus. They are boxed and tinted a muted version of
the operator hue, so they never compete with the AND /
OR that actually describe the rule; pointing at one restores the
full colour.
Labels come from labels.addAnd and labels.addOr,
and the colours are derived from --kce-and /
--kce-or via --kce-and-muted and
--kce-or-muted.
Hiding the field
By default the editor conceals the textarea it took over — visually hidden
but still in the form, so it keeps posting exactly as before.
hideTextarea: 'toggle' keeps it hidden and adds a
Show source button to the footer that puts it back on screen.
KConditionsEditor.attach('#conditions', { hideTextarea: 'toggle' });
editor.setSourceVisible(true); // the same from code
editor.isSourceVisible(); // → true
editor.on('source', ({ visible }) => …);
debug: true adds: that one shows the
document the editor is generating, this one shows the field it is
written into. Both label sets are overridable through
labels (revealField / concealField
here, viewSource / hideSource there).
hideTarget
Often the textarea is not the only thing that should disappear — the row
carrying its label would otherwise be left behind labelling nothing.
hideTarget takes a CSS selector, an element, or a list of
either:
<div class="row">
<label for="conditions">Conditions</label>
<textarea id="conditions" name="conditions"></textarea>
</div>
KConditionsEditor.attach('#conditions', {
hideTarget: document.querySelector('#conditions').closest('.row'),
hideTextarea: 'toggle'
});
Three things it takes care of:
- The editor is inserted after the outermost hidden element, not after the textarea — otherwise it would be placed inside the row about to be hidden, and you would never see it.
- The textarea is always hidden too. If your target does not contain it — naming only the label, say — the field is added to the list, because a raw JSON textarea beside the builder is never the intent.
- A selector matching nothing warns and falls back to hiding the textarea, rather than leaving the field on show.
destroy() restores everything it hid.
Finding an editor again
A textarea carries at most one editor, and it points back at it.
KConditionsEditor.get(textareaOrSelector) returns the
instance, or null, for code that never had the value
attach() returned. KConditionsEditor.detach(textareaOrSelector)
calls destroy() on it and returns whether there was one. The
handle is also on the element as textarea.kConditionsEditor,
so $0.kConditionsEditor works in devtools.
Attaching to a textarea that already has an editor replaces
it: the old one is destroyed first, then the new one takes the field as it
stands. There is no "same options, keep the old one" shortcut, on purpose:
an options object carries callbacks, which cannot be compared, and the
field's value may have changed since the first attach. Anything registered
with on() on the old instance goes with it. To reuse an
existing editor rather than replace it, ask get() first.
const editor = KConditionsEditor.get('#conditions') ||
KConditionsEditor.attach('#conditions', options);
Undo and reordering
Undo and redo
Undo and Redo sit in the footer. From the
keyboard: Ctrl/Cmd+Z to undo, and
Ctrl/Cmd+Shift+Z
or Ctrl/Cmd+Y to redo. A history
entry is just a serialised document, with a cursor into a list of them —
there are no inverse operations to get wrong, and undo is a reload of a
state the editor has already been in.
Typing is the one case that needs care. A run of keystrokes in a single
field coalesces into one entry, committed when the typing pauses
(historyIdle), when focus leaves the field, or when anything
else happens. Without that, undo would step one character at a time.
Adding a chip to a list is a discrete act and gets its own entry.
input event feeds the browser's undo
back into the document. Everywhere else, the shortcut is the editor's.
The shortcut listens on the document and asks whether this editor holds
the keyboard: focus decides when there is any — only one editor can
contain it — and otherwise it falls to whichever editor was last clicked
in. A structural change rebuilds the tree and can drop focus, and "I just
clicked that, undo it" is the most common thing anyone asks of
Ctrl+Z, so an element-scoped listener would go
quiet at exactly the wrong moment. Several editors on one page do not all
react to one keystroke, and clicking away from every editor hands the
shortcut back to the page.
editor.on('undo', doc => console.log('back to', doc));
editor.canUndo(); // → true
editor.redo();
Move up, move down, and drag
Every row and every group carries move up / move down
buttons beside its ×, and Alt+↑ /
Alt+↓ anywhere inside a row does the same thing.
These come first and the drag is layered on the same primitive, because a
drag handle is unreachable by keyboard and unusable with a screen reader:
the buttons are the real interface and dragging is the shortcut.
Dragging uses a grip that appears with the row's other controls. It is
built on pointer events rather than the HTML5 drag-and-drop API, which
does not fire on touch at all, so it works on a phone. A drop indicator
marks the boundary the row will land on, indented to the level being
reordered, and Escape cancels mid-drag.
A node moves within its own group. Moving between groups is what
+AND / +OR and AND(…) /
OR(…) already do, and leaving it out of the drag is what
keeps a drop unambiguous in a nested tree.
editor.moveChild(group, 0, 2); // the primitive both interfaces use
Seeing what a button will do
Pointing at +AND, +OR, AND(…),
OR(…) or a × — or reaching one by tab — previews
what the click will do. For an add button: the rows that will end up
bracketed together, the operators between them, and where the new
condition lands. For a ×: everything it would take, brackets
and NOT included.
The colour says which bracket. An add preview carries the hue of the
bracket being formed; the new condition is written in the hue of the
operator that joins it. That is what makes AND(…) readable:
everything in the group is marked blue, because it stays an AND group,
while the new condition reads OR new condition. A ×
preview is red.
How it is drawn is the previewStyle option, independent of the
skin:
previewStyle | Looks like |
|---|---|
bar (default) | One thin bar in the margin beside the range. |
highlight | A tint and outline on each row and operator — the look before 0.0.27. |
region | One soft wash over the range, as wide as its widest line. |
fade | Everything outside the range fades back. |
color | Text in the range takes the hue. |
marker | Each row's drag grip becomes a coloured dot; --kce-preview-marker swaps the glyph. |
underline | Field names, operators and AND / OR in the range are underlined. |
KConditionsEditor.attach('#conditions', { skin: 'prose', previewStyle: 'fade' });
editor.setPreviewStyle('underline'); // live; nothing re-renders
previewTargets() decides what is
marked; the styles only decide how. planAdd() and
planWrap() return what would happen;
addBeside() and wrapAndContinue() carry it out. So
no style can disagree with another, or drift from the behaviour. No style
moves anything on screen, so the button keeps the pointer. The
skins page has a picker for comparing them.
This earns its place mainly in prose, where a group is a range
of lines rather than a box you can see, so a × at the end of
one line gives no indication how much sits underneath it.
Brackets that do nothing
The editor takes out brackets that change nothing: a group with one thing
in it, a group using its parent's AND / OR, and
an empty group. It does this on load, in setDocument() and
after every change, and the rule evaluates exactly as before. Brackets
that carry a NOT stay.
So some clicks take brackets away as well as doing what they say.
Switching a group to its parent's operator merges the group into its
parent. Switching back then switches the parent, because the group is
gone. A × can leave a group holding one thing, and those
brackets go too. Three things make that visible:
- Before the click. Pointing at (or tabbing to) an
AND/OR, a group'sNOTor a×marks the brackets that would go, struck through in the removal colour, with the group's guide. This is the same in everypreviewStyle. The mark comes from making the change to a copy of the rule and tidying it with the same code the click runs, so it cannot disagree with the click. - After it. The rows that came out of the brackets are tinted briefly in their new group's colour.
- A note, with the way back. Removed unneeded
brackets · Undo, beside the change where there is room, otherwise in
the footer next to Undo. It goes on the next change, or after a few
seconds, but not while it is pointed at or focused. A screen reader
hears it through a polite live region. The text is the
bracketsRemovedlabel. Withhistory: falsethe note has no Undo.
AND(…) / OR(…) merges too, when the group it
closes off ends up with its parent's operator, but that is what the button
is for and its preview already shows it, so it raises no note.
Where the AND / OR goes
In prose, connectorPlacement decides where each
AND / OR goes. Either way it stays put when
the row's controls appear, so the word you are about to click doesn't move.
// "below" (the default): a line of its own, under the field name — or
// under the `)` after a group
Name is equal to Ann
AND
State is equal to Florida
AND (
…
// "inline": just after the value — fewer lines, reads along the line
Name is equal to Ann AND
State is equal to Florida AND (
…
"below" reads like a formatted query: the field names and the
operators share one edge, and AND ( stays together. It takes a
short extra line per operator. "inline" takes less vertical
space. Its row controls (arrows and ×) appear after the
AND / OR with the add buttons, because they cannot
sit between the value and an operator that does not move.
editor.setConnectorPlacement("inline") switches live. The
option only affects prose; the other skins already give each operator a
row of its own.
Operator alignment
With connectorPlacement: "inline", a connector sits immediately after the row it follows,
so without help its position depends on how wide that row happens to be —
a group whose values read "Alabama", "California", "Florida" prints its
ORs in three different places, which is the wrong look for a
layout whose whole argument is that a rule should read like an equation.
Connectors share a column per indent level: rows at the same indent
already read as a column, so their operators join it, while a deeper group
is a different thought and keeps its own. The column is measured after
layout and re-measured as an autosizing field grows or the viewport
changes, so it stays true while you type. alignConnectors: "group"
narrows it to one column per group; false turns it off, which
is worth doing if one very long row would drag its neighbours' operators
out to the right.
Skins and theming
The editor ships five visual treatments over the same data. Load the skins
stylesheet alongside the base one — it is required for everything except
boxed — and name the skin you want:
<link rel="stylesheet" href="src/k-conditions-editor.css">
<link rel="stylesheet" href="src/k-conditions-skins.css">
KConditionsEditor.attach('#conditions', { skin: 'prose' });
| Skin | Layout | What it looks like |
|---|---|---|
prose (default) | flow | The rule pretty-printed: one line per condition, indentation by nesting depth, real parentheses, closing bracket on its own line. |
equation | tree | Bracket gutters and indentation, AND/OR on their own lines between rows. No boxes. |
blackboard | tree | The equation layout on a dark slate panel with a chalk palette. |
ledger | tree | Least ink: hairline vertical guides instead of brackets, dashed when a group is negated. |
boxed | tree | Every row a bordered card with an AND/OR toggle in each group header. The 0.0.1 look. |
In prose, each bracketed group also gets a guide:
a thin line down the left of its rows in the group's AND / OR colour,
dashed for a NOT group, nesting with the groups, so any row
can be traced to the group it belongs to. Pointing at a group's AND / OR
word or one of its brackets brings its guide to full strength. The rule's
own top-level AND / OR have a line too, down the whole rule, shown only
while one of them is pointed at. groupGuides: false turns
them off.
In the written-out skins a field, an operator or a choice value reads as a word in the sentence, so each carries a small down chevron to say it opens a list. Boxed draws its own.
Two layouts, not just two stylesheets
prose uses a different DOM from the others, because CSS alone
cannot produce it: an inline formatting context cannot indent wrapped lines,
and a nested block structure cannot put ) AND NOT ( on one
line. The flow layout renders a flat sequence of
.kce-line elements indented by depth; the tree
layout renders nested .kce-group boxes. The skin
option picks the right one for you.
Theming
Set --kce-accent to your own brand colour.
The default blue is a placeholder, not the component's identity — it is
what hover, focus and the active states turn, so in a green host it is a
colour that appears nowhere else on the page:
.kce { --kce-accent: #2e7d4f; --kce-accent-soft: #e6f2ea; }
Every colour and metric is a custom property on .kce, so a skin
can be retinted without touching the stylesheet:
.kce {
--kce-accent: #7c3aed; /* focus, links, active states */
--kce-accent-soft: …; /* hover tints behind them */
--kce-field: #101820; /* field names */
--kce-op: #5f6875; /* operator labels */
--kce-value: #1a5f8a; /* literal values */
--kce-and: #2f6fd0; /* AND connectors */
--kce-or: #a8560c; /* OR connectors and NOT */
--kce-rule: #b6bdc8; /* hairline guides */
--kce-paren: #59636f; /* brackets in the prose skin */
--kce-radius: 12px;
--kce-indent-step: 2.2em;
}
Light and dark are both defined. The editor follows
prefers-color-scheme unless you pin it with the
theme option (or data-kce-theme on the root).
blackboard is deliberately dark in both. Colours you set yourself
have to meet contrast themselves — see Accessibility for
which pairs matter.
Inside someone else's form
The editor is usually embedded in a form that styles its own inputs. The
stylesheet pins the box metrics the editor depends on — width, height,
margins, radius, shadow — above element and class-scoped host rules, so a
dialog's .form input[type=text] { width: 24rem } does not
reach the value slots. A host rule scoped by an ID still
outranks it; exclude the editor there with
#properties input:not(.kce *).
A row is one line: its arrows, × and the AND / OR after it
never drop below it. When the line is short the row gives up width — its
value first, down to a floor, then the field and operator names, which
ellipsis but keep a readable few letters; a name cut short shows itself whole on
hover. between and date
ranges shrink to stay on their line; only an "is one of" tag list wraps,
inside its box, with everything else on its first line. A row that still
cannot fit makes the line scroll sideways rather than overlap.
The controls option decides when the row controls are shown.
With "hover" (the default) the add buttons take no room until
needed — in prose they appear after the AND / OR, or as a small strip
just below it when the line is full — and nothing moves when they do.
With "always" everything is shown at rest. A screen with no
hover gets "always" regardless.
boxed to prose. Pass skin: 'boxed' to
keep the old appearance exactly; nothing about the document format changed.
Field definitions
{
name: 'dob', // required — the key looked up in your data
label: 'Date of Birth', // shown in the UI; defaults to name
type: 'date', // text | number | date | boolean | enum | list
group: 'Application', // a heading in the field list (optional)
column: 'c.date_of_birth', // SQL column name; defaults to name
storage: 'json', // a list kept as a JSON array — see below
countAsBlank: 'json', // stored values that count as empty — see below
choices: [...], // enum and list fields; strings or {value, label}
operators: [...], // explicit operator list, overrides the type default
operatorGroups: [...], // or pick whole groups: ['date', 'existence']
excludeOperators: [...], // remove specific operators from whatever was chosen
values: ['literal','field'], // which value sources are offered
comparableWith: [...], // which fields this one may be compared against
placeholder: '…',
input: { min: 0, max: 100, step: 1, type: 'datetime-local' }
}
group is a display string. Fields that name one are listed under an
<optgroup> of that name, in the field list and in the
compare-with list, with the groups in the order they first appear and the fields
with no group first. A new condition takes the first field the list shows.
comparableWith: 'group:Staff' matches the same string.
Operator selection
With no operators the field gets the groups its type
implies: text → equality, alphanumeric, existence; number → equality, arithmetic,
existence; date → date, existence; boolean → boolean, existence; enum → equality,
alphanumeric, existence; list → list, existence (less is set and is
not set when the list is stored as JSON, or the field has
countAsBlank). Entries in operators may
be a bare operator name or "group:date" to pull in a whole group.
A list stored as a JSON array
A multi-select is often kept in a text column as a JSON array of IDs —
["3184","3152"], and [] for none. storage: 'json'
says so, and every part of the library reads it that way: the editor offers
includes any of, includes all of, is empty and is not
empty, with the values picked by label and stored as IDs (type
defaults to list); describe() names the choices; the
evaluators decode the value when given the same fields; and the SQL
builders emit SQL for that shape (below).
{
name: 'Assigned To', label: 'Assigned To',
type: 'list', storage: 'json',
column: '--ID_FOR_Assigned To',
choices: { 3184: 'Ben Holness', 3152: 'claude claudesson (claude)' }
}
KConditions.evaluate(document, row, { fields }); // JavaScript
evaluate($document, $row, ['fields' => $fields]); // PHP
Every spelling of empty a column collects from its save paths is empty —
NULL, '', [], null,
[""], ["[]"], [null], and "[]",
"", "[\"\"]" (the same saved twice). Text that is not JSON
is not empty but includes no value, which is what the SQL says too, so a rule picks
the same rows in SQL as in an evaluator. Is set means is not empty
and is not set means is empty: a list column clears to
[] on one save path and to NULL on another. The exact
reading is in
SPEC.md §7.
A field without storage behaves exactly as before.
Values that count as blank
Some columns hold a placeholder for "nothing" — [] in a names column,
N/A in a phone column — which a plain text field's is not empty
lets through. countAsBlank names them, and the field stays what it is:
{ name: 'Assigned To', type: 'text', countAsBlank: 'json' } // a preset
{ name: 'Phone', type: 'text', countAsBlank: ['N/A', '-'] } // exact values
A string is a preset: 'json' is the spellings of empty above
([], null, [""], ["[]"],
[null], "[]", "", "[\"\"]"), from
the same list storage: 'json' uses; a preset the library does not know
is ignored. An array is exact values — case counts, nothing is trimmed — and a
string in it is always a value, so ['json'] means the text
json. NULL and '' are always blank.
Is empty and is not empty use those values, in the SQL and in both
evaluators (given the same fields); is set and is not
set mean is not empty and is empty, so the editor offers only
the empty pair. Every other operator — contains,
eq, starts_with — reads the stored text exactly as before,
and nothing is refused; describe() and the value controls do not change.
On a field that also has storage: 'json', a preset adds nothing and an
array adds stored values that count as empty and hold nothing. The exact rules are in
SPEC.md §7.2;
the SQL is below. A field without countAsBlank
behaves exactly as before.
A saved rule the fields no longer fit
A rule saved before a field changed still loads as what it is. An operator the
field no longer offers — contains on a field that is now a list — is
shown, chosen, under its own heading, and kept until someone picks another; a field
the host no longer lists is shown by its name. Loading never changes the rule. The
SQL builders apply unsupportedPolicy to an operator they cannot
translate for the field.
Choices
A field's choices — and a custom values operator's
values — may be written three ways. All three mean the same thing: the
first item is stored in the document, the second is what the user sees.
choices: ['Florida', 'Texas']
choices: [{ value: 'FL', label: 'Florida' }, { value: 'TX', label: 'Texas' }]
choices: { FL: 'Florida', TX: 'Texas' } // an associative map
Labels are used in the dropdowns, in the collapsed summary and in
describe(), so a rule reads [State] is equal to "Florida"
while the document stores "FL".
Except where the operand is not a choice. contains,
does not contain, starts with, ends with,
matches regex and does not match regex take a
fragment or a pattern, not one of the values. On those the editor shows a
free text box instead of the dropdown, and describe() prints what was
typed rather than swapping it for a label:
[State] is equal to "Florida" ← eq: a whole value, so the label
[State] contains "FL" ← contains: a substring, left alone
Operators carry this as valueFromChoices in their metadata (absent
means true). A custom operator whose operand is a fragment should set it
false to get the same treatment.
Comparing against another field
A value can be a literal or a pointer at another field, and where both are possible the editor shows a small Value / Field selector beside the value. That selector is off by default — it costs a control on every row that has a value, to buy a feature most rules never use.
KConditionsEditor.attach('#conditions', { fields, allowFieldValues: true });
Or leave it off and opt in one field at a time: naming comparableWith on
a field is read as asking for it, so it works with the global setting untouched.
comparableWith: false still wins, so a field can opt out even with the
global on. And a document that already holds a field reference always keeps its
selector, whatever the settings say — otherwise there would be no way back to a
literal.
comparableWith silently became comparable with every
other field of its type and carried the selector. If you were relying on that, set
allowFieldValues: true.
comparableWith
Controls which other fields may appear in the Field value dropdown.
| Value | Meaning |
|---|---|
| omitted | Other fields of the same type. |
false or [] | No field comparison — literals only. |
'*' | Every other field. |
['billing_email'] | Exactly the named fields. |
['type:date'] | Every field of that type. |
['group:contact'] | Every field carrying group: 'contact'. |
Entries combine, so ['billing_email', 'type:date'] is valid.
Translating
Every word the editor shows, reads out to a screen reader or puts in a tooltip comes
from labels. Pass the ones you want to change; a key you leave out (or
leave empty) stays English.
KConditionsEditor.attach('#rule', {
fields,
labels: {
edit: 'Redigera villkor', and: 'OCH', or: 'ELLER', not: 'INTE', andJoin: 'och',
removeValue: 'Ta bort {value}',
operators: { eq: 'är lika med', date_within_last_days: 'är inom de senaste {value} dagarna' },
groups: { equality: 'Likhet', date: 'Datum', custom: 'Egna' },
problems: { unknownField: 'Okänt fält "{field}"' }
}
});
// The same object makes a host's own summary read in the same language.
KConditions.describe(document, { fields, labels });
KConditionsEditor.defaultLabels() returns every key with its English —
the list to build a translation catalogue from.
Placeholders. A label holding {name} has it filled
where it is used, so a translation puts the value where its own word order wants it:
'Remove {value}', 'Ta bort {value}',
'删除{value}'. {operator} is your and or
or label.
Operators with a slot. An operator label may hold
{value}, which marks where the operand goes. On the row, the words before
it take the operator's place, then the value box, then the words after it: "is within
the last [7] days". describe() puts the value in the same place. In the
operator list the label reads whole, with … in the slot. The four N-day
date operators use a slot in English too.
Three maps merge key by key, so you can translate part of one:
| Key | Keyed by | Default |
|---|---|---|
operators | operator name, builtin or custom | the operator's own label |
groups | equality, arithmetic, alphanumeric, list, date, boolean, existence, custom | Equality, Arithmetic, … Custom |
problems | the code of a validateDocument() problem; placeholders are its params | Unknown field "{field}", … |
Every other key, with its English:
| Key | English | Where |
|---|---|---|
edit | Edit Conditions | the button on the collapsed summary |
done | Done | the footer button that collapses the editor |
empty | Always | the rule with no conditions; also describe()'s empty text |
addCondition | + Condition | the button in an empty group |
addAnd / addOr | +AND / +OR | the add buttons after a row |
wrapAnd / wrapOr | AND(…) / OR(…) | the button that brackets everything and continues |
and / or / not | AND / OR / NOT | the logic words, on the rule and in describe() |
andJoin | and | between the two values of between |
removeGroup / removeCondition | Remove group / Remove condition | the × buttons |
moveUp / moveDown | Move up / Move down | the arrow buttons |
dragHandle | Drag to reorder | the grip's tooltip |
valueSourceLiteral / valueSourceField | Value / Field | the value-source select's choices |
chooseField | Choose a field… | the field list, when the condition has none |
listHint / listHintEmpty | add… / type a value, press Enter | a list's text box |
listAdd | + add… | the first entry of a list's dropdown of choices |
ghostCondition | new condition | the preview row an add button shows |
invalid | This rule is incomplete: | above the problems under the rule |
bracketsRemoved | Removed unneeded brackets | the note after a change, and the live region |
undo / redo, undoTitle / redoTitle | Undo / Redo, Undo (Ctrl+Z) / Redo (Ctrl+Shift+Z or Ctrl+Y) | the footer buttons and their tooltips |
clear, clearConfirm, clearYes, clearCancel | Clear and start over, Clear every condition?, Clear, Cancel | the footer's clear control |
revealField / concealField | Show source / Hide source | hideTextarea: 'toggle' |
jsonHeading | JSON output | showJson |
viewSource / hideSource, tabDocument / tabSql / tabSummary, copy / copied, sqlMissing | View source / Hide source, Document / SQL / Summary, Copy / Copied, Load k-conditions-sql.js to generate SQL. | the debug panel |
preservedText / preservedDismiss | The existing contents of this field could not be read… / Dismiss | the notice over a field the editor could not read |
fieldSelect, operatorSelect, valueSourceSelect, compareFieldSelect | Field, Operator, Value source, Compare with field | accessible names of the row's selects |
valueInput, valueFrom / valueTo | Value, From / To | accessible names of a value control, and of between's two |
listInput | Add a value | accessible name of a list's text box or dropdown |
removeValue | Remove {value} | accessible name of a list value's × |
addToGroup, addNewGroup | Add another condition to this group, Group this condition with a new one, joined by {operator} | tooltips of the add buttons |
wrapGroup | Group everything in this set, then continue with {operator} | tooltip of AND(…) / OR(…), read as its description |
switchGroup | Switch this group to {operator} | tooltip of an AND / OR you can click |
datePlaceholder | YYYY-MM-DD | a date typed into a text box |
search, noResults, selectedCount, close | Search…, No matches, {n} selected, Close | kSelect's own words, when the editor uses it |
addGroup / chooseOperator | + Group / Choose… | not shown at present; kept so existing label sets still apply |
Field labels, choice labels and field groups are yours already. The
debug panel's body is developer output and stays as it is.
A host's select widget
A host that styles every <select> with a widget of its own can
have the editor hand each one over once it is built, filled and on the page:
KConditionsEditor.attach('#rule', {
fields,
decorateSelect: (select, { role, node, field }) => enhanceSelect(select), // return its promise
releaseSelect: (select) => Kselect.getInstance(select)?.destroy(),
focusSelect: (select) => select.parentElement.querySelector('[role="combobox"]')?.focus()
});
role is 'field', 'operator',
'value', 'values' (a list of choices, built as
<select multiple>), 'source' or
'fieldValue'. node is a copy of the condition and
field its definition.
- The widget keeps the select, hidden, with its value in step, and
fires a bubbling
changeon it — the way kselect and most of its kind work. The editor goes on listening to the select. - It is called on every render, which rebuilds the rule.
releaseSelectruns for each decorated select before a render throws it away, and ondestroy(). Pass it if the widget puts anything outside the editor, such as a dropdown in<body>. - Return
falseto decline a select. Return the widget's promise if it arrives later; focus and layout wait for it. - Focus comes back to the widget standing in for the select that
had it, after a pick that rebuilt the rule, an undo or a move: found through the
select's shell (
.kce-sel) or adata-kce-fornaming the select'sdata-fk. ThenfocusSelect, or the first focusable element in the shell. - The select's label is not drawn beside a widget, and the shell
(
.kce-sel-host) does not shrink: a row too wide for its line scrolls. - An operator with a
{value}slot loses the slot when decorated — the widget shows the whole label. Decline'operator'to keep "is within the last [7] days".
kSelect, built in
If the page already has kSelect, the editor uses it for the long lists with no configuration.
kselect | What happens |
|---|---|
"auto" (default) | Used when window.Kselect is there. If it arrives after the editor, the selects already drawn are upgraded where they stand (the editor looks for 8 s after attaching, and on the window's load; after that, at its next change). |
true | Used; if the page has none, loaded from jsDelivr, pinned to kSelect 1.11.1 with subresource integrity (kselectSrc for a self-hosted copy). Native selects until it arrives; one warning and native selects if it cannot be loaded. |
false | Never. |
the Kselect constructor | Used, for a bundle that does not set the global. |
- Which selects: the field, the field compared with, a value from a
field's choices, and a list of choices. The operator (which keeps its
{value}slot) and the Value / Field switch stay native.kselectRoleschanges the set. - A search box opens with any list of more than 8 entries; field
groups are its headings. - It reads as the sentence: in prose and the equation skins the
closed kSelect is drawn as the word it replaces, at the editor's
--kce-font-size, and its list opens in the editor's colours and dark mode, above a modal dialog too. Boxed keeps kSelect's box. - Long names wrap in the open list rather than ending in "…": it is
as wide as its longest option up to 36em, kept on screen, and an option longer than
that takes a second line — so
"{question}: {item}"fields are told apart by their end. - Its words are
labels.search,labels.noResults,labels.selectedCount,labels.closeandlabels.removeValue. - A host's own
decorateSelectalways wins.
Accessibility
The test suite runs axe-core (WCAG 2.1 A and AA) over every skin, in light, dark and
a dark reader with no theme set, with the controls shown on hover and at rest, in
every state a person meets — a row hovered, an add button's preview, the clear
question, the note after brackets went, the debug panel, the collapsed summary — and
requires zero violations. Every control has an accessible name from
labels; the tree skins' AND / OR toggles carry
aria-pressed; everything is reachable by keyboard.
A host that sets its own colours replaces the defaults, so these pairs (text, 4.5:1) become its to check, in each theme:
| Token | Must read against |
|---|---|
--kce-field, --kce-value, --kce-text | --kce-bg, and the row hover tint (about 11% grey over it) |
--kce-op, --kce-text-muted | the same; these fail first |
--kce-and, --kce-or | --kce-bg; on hover the add buttons darken them towards --kce-text over --kce-accent-soft and --kce-warn-bg |
--kce-and-muted, --kce-or-muted | --kce-bg-sunken (the add buttons at rest) |
--kce-accent-text | --kce-accent and --kce-or |
--kce-accent-strong | --kce-accent-soft |
--kce-danger-text | --kce-danger (new in 0.1.2) |
--kce-warn-text | --kce-warn-bg |
Custom operators
Custom operators are passed to the editor and copied into the document whenever they are actually used, so the JSON stays self-contained. Two kinds.
A fixed set of values
operators: {
is_gulf_state: {
kind: 'values',
label: 'is a Gulf state',
match: 'in', // or 'not_in'
arity: 0, // 0 = fixed list, no value input shown
values: ['Florida', 'Louisiana', 'Texas', 'Mississippi'],
appliesTo: ['state'] // editor-only: which fields offer it
}
}
With arity: 1 the list becomes the choices offered in the editor and
the selected value is stored on the condition instead.
A host function
operators: {
email_is_unique: {
kind: 'callback',
label: 'is not already registered',
arity: 0,
appliesTo: ['email'],
availableIn: ['server'],
callbacks: {
php: { class: '\\App\\Rules\\Email', method: 'isUnique', static: true },
js: { function: 'emailIsUnique' },
python: { module: 'app.rules', function: 'email_is_unique' }
},
policy: {
unresolved: { client: 'skip', server: 'error', '*': 'error' },
error: { client: 'skip', '*': 'error' }
}
}
}
The callback receives (fieldValue, args, context) and returns a
boolean — or the SKIP sentinel to opt out at runtime.
appliesTo is stripped when the operator is written into the document.
SQL output
The same rule can be rendered as a SQL boolean expression — the part that goes
after WHERE. Load the SQL builder and you have SQL:
<script src="src/k-conditions-sql.js"></script>
KConditions.toSql(document, { dialect: 'mysql' });
// → `email` = 'a@b.c' AND `dob` < '1980-01-01'
column is optional. A field's name is used as the
column name unless you say otherwise, so a schema whose columns already match your
field names needs no mapping at all — and a field the builder has never been told
about still resolves to its own name. Give a field a column only where
the two differ.
{ name: 'dob', label: 'Date of Birth', type: 'date', column: 'c.date_of_birth' }
The resolution order per field is column → sql →
name, and the builder's columns option (a plain
{ field: column } map) overrides all three — useful when one document
has to run against two schemas. Entries in fields may also be bare
strings when all you want is the type defaults.
const { sql, params } = editor.getSql({ dialect: 'mysql' });
// or, standalone:
KConditions.toSql(document, { dialect: 'mysql', fields });
use function Kastrack\ConditionsEditor\toSql;
$where = toSql($document, ['dialect' => 'mysql', 'fields' => $fields]);
$rows = $db->query("SELECT * FROM contacts c WHERE $where");
Where to generate it
Both places are supported, and which is right depends on what your endpoint already accepts.
- Server-side, from the document. The browser posts the JSON and the server builds the SQL. Use this when your endpoint receives a rule and you would rather not widen it into accepting SQL.
-
Client-side, into the textarea (
output: 'sql'). Use this when the field already accepts SQL. If a person could previously typestatus = 'x' OR 1=1into that box, a builder writing a nicer expression into it adds no attack surface: the trust boundary is where it always was, and whatever sanitising and sandboxing you do on the way in still applies.
parameters: true wherever your driver supports placeholders, in either
mode.
Options
| Option | Default | Notes |
|---|---|---|
dialect | "standard" | mysql (or mariadb), postgres, sqlite, sqlserver, standard. |
fields | null | Supplies column, type, storage and countAsBlank per field. Optional — without it every field name is used as its own column. |
columns | null | Or map field name to column directly. |
parameters | false | Emit placeholders; the values come back in params. |
placeholderStyle | per dialect | question (?), numbered ($1), named (@p1). |
quoteIdentifiers | true | Turn off if your column names are already exactly as you want them. |
nullSafeNegation | true | Wrap negative operators as (col IS NULL OR …). |
now | null | Resolves the relative date operators. |
pretty | false | Indent nested groups. |
unsupportedPolicy | "error" | What to do when the dialect cannot express an operator. |
List fields stored as JSON
A field with storage: 'json' gets SQL for that shape. MySQL / MariaDB,
with col for the quoted column:
| Operator | SQL |
|---|---|
is_empty, is_not_set | (col IS NULL OR CAST(CAST(col AS CHAR) AS BINARY) IN (…)) |
is_not_empty, is_set | (col IS NOT NULL AND CAST(CAST(col AS CHAR) AS BINARY) NOT IN (…)) |
includes_any A, B | CASE WHEN JSON_VALID(col) THEN JSON_CONTAINS(col, '"A"') OR JSON_CONTAINS(col, '"B"') ELSE 0 END |
includes_all A, B | the same, joined with AND |
… is every spelling of empty. JSON_CONTAINS runs only inside
CASE WHEN JSON_VALID(…), because it fails the whole query on text that
is not JSON ('' included) and MySQL does not promise to short-circuit an
AND. Nothing can be NULL, so a NOT in front keeps
the empty rows. Values are JSON-encoded, then SQL-quoted
('"O''Brien"'), or bound with parameters: true. The text is
compared exactly, byte for byte, as the evaluators compare it: MySQL's default
collation is case-insensitive, so a plain CAST(col AS CHAR) (as until
0.1.7) counted the text NULL as the spelling null. The cast
reads a native JSON column too. An empty operand list never matches.
SQLite gets the same shape with CAST(col AS TEXT) COLLATE BINARY,
json_valid() and json_each(); other dialects, and operators
such as eq or contains on JSON text, fall to
unsupportedPolicy rather than SQL that might be wrong.
Fields with their own blank values
A field with countAsBlank changes the SQL for the four existence
operators, and nothing else. MySQL / MariaDB:
| Operator | SQL |
|---|---|
is_empty, is_not_set | (col IS NULL OR CAST(CAST(col AS CHAR) AS BINARY) IN ('', …)) |
is_not_empty, is_set | (col IS NOT NULL AND CAST(CAST(col AS CHAR) AS BINARY) NOT IN ('', …)) |
contains, eq and the rest | as without the option |
… is the preset's spellings or the field's own values; a host's values are
escaped like any literal, or bound with parameters: true. The exact
comparison matters most here — through a plain cast, MySQL's default collation would
make n/a blank for ['N/A'] — and it reads a native
JSON column too. Neither expression can be NULL. SQLite gets
CAST(col AS TEXT) COLLATE BINARY; PostgreSQL, SQL Server and
standard have no tested exact comparison, so the four existence
operators fall to unsupportedPolicy there.
It is a translation, not the evaluator
SQL has three-valued logic and the evaluator does not, so a row-for-row match is not guaranteed. The choices made here:
- Negative operators are null-safe by default:
col <> 'x'becomes(col IS NULL OR col <> 'x'). is_emptycovers bothNULLand'', and a field'scountAsBlankvalues.date_eqbecomes a half-open day range, which is portable and index-friendly.- The relative date operators resolve against
nowat generation time rather than emittingCURRENT_DATE, so a saved query keeps the dates it was built with. LIKEpatterns escape%,_and the escape character itself, and carry an explicitESCAPEclause.
Operators with no SQL
A callback operator cannot be translated. Give it an sql
template and it can be:
email_is_unique: {
kind: 'callback',
sql: 'NOT EXISTS (SELECT 1 FROM blocked b WHERE b.email = {field})'
}
{field} is the quoted column, {0}/{1} the
rendered values, {values} the comma-separated list. Without a template
the operator falls to the unresolved policy, so
{"unresolved": {"sql": "skip"}} drops it from the WHERE clause and
leaves it to be evaluated in code. Regular expressions are unsupported in SQL Server
and need a UDF in SQLite; those fall to unsupportedPolicy.
Writing SQL into the textarea
output: 'sql' puts the expression in the textarea instead of the JSON.
It defaults to 'json', so you opt in. SQL does not parse back into a
rule, so the editor needs somewhere to keep the document if the rule is to survive a
reload — two ways, depending on whether you can add a field.
You can add a hidden field
<textarea name="conditions"></textarea>
<input type="hidden" name="conditions_doc">
KConditionsEditor.attach('[name=conditions]', {
output: 'sql',
documentInput: '[name=conditions_doc]',
sql: { dialect: 'mysql' },
fields
});
You cannot — it is an existing SQL field and that is all there is
KConditionsEditor.attach('#existing-sql-field', {
output: 'sql',
documentInComment: true, // the rule rides along in a trailing SQL comment
hideTextarea: false, // let people see the SQL it writes
sql: { dialect: 'mysql' },
fields
});
(`c`.`full_name` REGEXP '^ben' AND `a`.`state_code` IN ('FL', 'TX'))
/* kconditions:1.0 {"version":"1.0","operators":{},"root":{…}} */
The comment trails the expression — in a field someone can see, the SQL is the point and the document is baggage. It is a no-op to the database and the editor reads the rule back out of it, so a single field round-trips. Two caveats: anything that strips comments before storing the SQL loses the rule (the SQL still works, the builder just reopens empty), and hand-edits to the generated SQL are overwritten the next time someone touches the builder — so if people will switch between typing SQL and using the builder, keep the raw SQL somewhere the editor does not own.
The field already holds something the editor cannot read
SQL written by hand, say, with no document beside it. The editor does not replace
it: the field keeps its content, byte for byte, until the first change to the rule,
so an untouched form submits exactly what it loaded. Meanwhile a notice above the
rule shows the original text, with a Dismiss button, so the rule can be rebuilt
while reading it (labels preservedText and
preservedDismiss). editor.preserved is
{ text } or null, editor.pristine says
whether the field is still untouched, and the change payload carries
pristine too. Opening the editor, changing skin or theme and
re-attaching do not count as changes; adding, editing, undoing and
setDocument() do. There is no parser: the editor never guesses what a
hand-written expression meant.
Debugging
debug: true adds a View source button to the footer.
It opens a tabbed panel showing the document, the generated SQL — with its bound
parameters, skipped operators and warnings — and the plain-English summary with any
validation problems, each with a copy button.
KConditionsEditor.attach('#conditions', {
fields,
debug: window.APP_DEBUG === true,
sql: { dialect: 'mysql' }
});
Editor API and events
| Member | Returns | Notes |
|---|---|---|
getDocument() | object | The current document, without internal ids. |
getJson() | string | The same thing, serialised the way the textarea has it. |
setDocument(doc) | this | Accepts an object, a JSON string, or a bare node. Brackets that change nothing are taken out, as on load and after every change (see Brackets that do nothing); the result is the same. |
validate() | array | Problems found in the current rule, each { path, code, params, message }; empty means valid. The editor shows them through labels.problems. |
getSql(overrides) | object | {sql, params, dialect, skipped, warnings}. Requires k-conditions-sql.js. |
clear() | this | Empty the rule back to "Always" and fire a clear event. The footer control calls this after confirmation. |
describe() | string | The plain-language rendering used in the collapsed summary. |
describeHtml() | string | The same rendering as escaped HTML. See Showing a rule. |
setSkin(name) | this | Swap skins at runtime; re-renders when the layout differs. |
setConnectorPlacement(mode) | this | "below" or "inline", live (a re-render; the document is untouched). An unknown mode falls back to "below". |
setControls(mode) | this | "hover" or "always", live. An unknown mode falls back to "hover". |
setPreviewStyle(name) | this | Change how previews are drawn, live. Nothing re-renders; an unknown name falls back to "bar". |
setTheme(name) | this | "light", "dark" or null to follow the system. |
setEmptyText(text) | this | Change the "no conditions" wording at any time. |
open() / close() | — | Use setOpen(true|false). |
setSourceVisible(bool) | this | Show or hide the field the editor took over. See Hiding the field. |
isSourceVisible() | boolean | Whether it is currently on screen. |
undo() / redo() | this | Step through the history. See Undo and reordering. |
canUndo() / canRedo() | boolean | What the footer buttons use to enable themselves. |
moveChild(group, from, to) | this | Reorder within a group. Both the move buttons and the drag call this. |
addBeside(group, index, op) | this | What +AND / +OR call. |
wrapAndContinue(group, op) | this | What AND(…) / OR(…) call. |
removeNode(node, parent) | this | Remove a condition or group. |
setGroupOperator(g, op), setNegate(n, on),setField(n, name), setOperator(n, name),setValue(value, v) | this | The rest of the mutation API. Every change to the document goes through one of these, which is what gives undo a single place to hook. |
destroy() | — | Removes the UI and restores the textarea. Safe to call twice. |
preserved / pristine | object | null, boolean | Content the editor could not read on attach, and whether the field is still untouched. See SQL output. |
KConditionsEditor.defaultLabels() | object | Every label key with its English, operators filled in with each builtin operator's label: the list a translation has to cover. A fresh copy each call. |
KConditionsEditor.get(target) | editor | null | The editor on a textarea (element or selector), for code that did not keep what attach() returned. |
KConditionsEditor.detach(target) | boolean | destroy() the editor on a textarea, if there is one. attach() on a textarea that already has one replaces it. See Finding an editor again. |
on(event, fn) | this | Events: change, open, close, clear, undo, redo, source. |
editor.on('change', function (payload) {
console.log(payload.valid, payload.problems, payload.document);
});
The document format
{
"version": "1.0",
"generator": "kConditionsEditor/0.0.1",
"operators": { /* custom operators used by this rule */ },
"root": {
"type": "group",
"operator": "and",
"negate": false,
"children": [
{
"type": "condition",
"field": "name",
"operator": "regex",
"values": [{ "source": "literal", "value": "^ben" }]
}
]
}
}
A value node is either { "source": "literal", "value": … } or
{ "source": "field", "field": "other_field" }. An empty
children array means "no conditions", which evaluates to the
evaluator's emptyResult (true by default).
The full specification is in SPEC.md, with a machine-readable JSON Schema.
Builtin operators
| Group | Operators | Arity |
|---|---|---|
| equality | eq, neq | 1 |
| arithmetic | lt, lte, gt, gte | 1 |
| arithmetic | between, not_between | 2 |
| alphanumeric | contains, not_contains, starts_with, ends_with, regex, not_regex | 1 |
| alphanumeric | in_list, not_in_list | list |
| list | includes_any, includes_all | list (the field's own value is a list; SQL for a list stored as JSON, or through an sql template) |
| date | date_eq, date_before, date_after | 1 |
| date | date_between | 2 |
| date | date_is_today | 0 |
| date | date_within_last_days, date_within_next_days, date_more_than_days_ago, date_more_than_days_ahead | 1 (a number, read in the label's {value} slot: "is within the last 7 days") |
| boolean | is_true, is_false | 0 |
| existence | is_set, is_not_set, is_empty, is_not_empty | 0 |
Comparison rules
- Equality compares numerically when both sides look numeric, otherwise as strings. Arrays compare structurally.
- Arithmetic comparisons are false when either side is not numeric — they never throw.
- Dates accept
YYYY,YYYY-MM,YYYY-MM-DD, full ISO timestamps, epoch milliseconds and native date objects. A partial date expands to its earliest UTC instant, so is before 1980 means before1980-01-01T00:00:00Z. date_eqanddate_is_todaycompare UTC calendar days; everything else compares instants.- String comparison is case-sensitive unless the evaluator is given
caseInsensitive: true. - Regex values are bare patterns without delimiters. Stick to the common subset — anchors, classes, quantifiers, groups — for cross-language parity.
Failure policies
Two things can go wrong with a condition: the operator cannot be resolved
in this runtime, or evaluating it throws. Each is governed by a
policy resolving to skip, true, false or
error.
Where a policy comes from
condition.policy.unresolved/.erroroperators[name].policy.unresolved/.error- the evaluator's
unresolvedPolicy/errorPolicyoption — both default toerror
Context labels
A policy may be a bare string, or a map keyed by context label. Labels are matched
in this order: each entry of profiles, then environment,
then runtime, then "*" / "default".
{ "client": "skip", "server": "error", "js": "skip", "*": "error" }
That is why the same rule works in a browser and under Node on a server: the two
evaluators are constructed with different environment values and pick
different branches.
What skipping means
emptyResult. A skipped condition can never turn an OR true.
Skipped nodes are listed in the detailed result, so a server-side pass can see exactly what the client deferred.
JavaScript / Node SDK
The evaluator is one file with no dependencies,
src/k-conditions-evaluator.js,
and the same file runs in the browser and under Node. The SQL builder,
src/k-conditions-sql.js,
is optional and attaches toSql() to it.
const K = require('@kastrack/conditions-editor');
// One-shot
const ok = K.evaluate(document, data, { environment: 'server' });
// Reusable, with your own operators registered
const evaluator = new K.Evaluator({
environment: 'server',
unresolvedPolicy: 'error',
now: () => Date.now(),
caseInsensitive: false,
trace: true
});
evaluator.registerOperator('email_is_unique', async () => { /* … */ });
const details = evaluator.evaluateDetailed(document, data);
// { result, skipped, errors, trace, allSkipped }
Evaluator options
| Option | Default | Notes |
|---|---|---|
runtime | "js" | Context label for the language. |
environment | null | client, server, or anything you like. |
profiles | [] | Extra labels, highest priority, in order. |
unresolvedPolicy | "error" | Fallback when the document says nothing. |
errorPolicy | "error" | Fallback for throwing operators. |
emptyResult | true | Result for an empty or fully skipped document. |
caseInsensitive | false | Applies to all string operators and regex. |
now | null | Date, epoch ms, ISO string or function — makes date rules testable. |
callbacks | null | Map of operator name to function, same as registerOperator. |
allowManifestCallbacks | false | See Security. |
callbackAllowList | null | Restrict manifest dispatch to these operator names. |
fields | null | The same field definitions the editor takes. Only storage and countAsBlank are read: a field with storage: 'json' is decoded before any operator sees it, and a field's own blank values decide is_empty and is_set. See A list stored as a JSON array and Values that count as blank. |
trace | false | Record per-node results in the detailed output. |
PHP SDK
The PHP SDK is in sdk/php:
PSR-4 under Kastrack\ConditionsEditor, PHP 8.1+, no dependencies.
Install it with Composer, or require its autoload.php directly
(see Installation).
use Kastrack\ConditionsEditor\Evaluator;
use function Kastrack\ConditionsEditor\evaluate;
// One-shot — the document may be the raw POSTed JSON string
$ok = evaluate($_POST['conditions'], $submission, ['environment' => 'server']);
// Reusable
$evaluator = new Evaluator([
'environment' => 'server',
'now' => new DateTimeImmutable('2026-08-27T12:00:00Z'),
]);
$evaluator->registerOperator(
'email_is_unique',
fn (mixed $value, array $args, array $ctx): bool => !User::emailExists($value)
);
$details = $evaluator->evaluateDetailed($document, $submission);
$details->result; // bool
$details->skipped; // array
$details->errors; // array
Options match the JavaScript SDK key for key, with runtime defaulting
to "php" and an extra container option — any object with a
get() method — used to build instances for non-static manifest
callbacks. $data may be an array or an object, and dot paths reach into
nested arrays and public properties.
An operator may return Skip::instance() to opt out at runtime.
Running the tests
composer install && vendor/bin/phpunit
# or, with no dependencies at all:
php tests/php/conformance.php
The result hook
Every SDK entry point takes an optional trailing callable. When supplied, the SDK returns that callable's return value instead of the boolean. It receives the original call's arguments, then the computed result, then the details.
const outcome = K.evaluate(document, data, options,
(document, data, options, result, details) => {
metrics.increment(result ? 'rule.pass' : 'rule.fail');
return { ok: result, deferred: details.skipped.map(s => s.operator) };
});
$outcome = evaluate($document, $data, $options,
function (array $document, array $data, array $options, bool $result, $details) {
Log::info('rule evaluated', ['result' => $result, 'skipped' => $details->skipped]);
return new RuleOutcome($result, $details->skipped);
});
Evaluator::evaluate() accepts the hook as its third argument, where the
options were supplied to the constructor instead.
Showing a rule to a reader
A stored document is JSON. To put it in front of someone — a confirmation page, an audit log, an email — both SDKs render it as a sentence.
KConditions.describe(document, { fields });
// [State] is equal to "Florida"
KConditions.describeHtml(document, { fields });
// <span class="kcd"><strong class="kcd-field">State</strong> <span class="kcd-op">is equal to</span> <span class="kcd-value">Florida</span></span>
use function Kastrack\ConditionsEditor\{describe, describeHtml};
describe($document, ['fields' => $fields]);
describeHtml($document, ['fields' => $fields]);
The two say the same thing: the brackets and quotes that mark a field and a value in
plain text become a bold field and an underlined value in HTML. Both take the same
options — fields (for labels and choice labels), operators
(custom operator definitions), labels and emptyText — and
both walk the document with the same function, so they cannot disagree about
bracketing, NOT placement or which label won. Only the leaf formatting
differs.
labels is the editor's own labels object, passed as it is:
describe() reads and, or, not,
andJoin, empty and the operators map, so a
host's own summary reads in the same language as the editor. An operator label with a
{value} slot gets its operand there — [Arrival] is within the last 7
days, [Arrival] 在过去7天内 — with the spacing round the slot kept as
written. emptyText, when given, wins over labels.empty.
KConditions.describe(document, { fields, labels: { or: 'ELLER', operators: { eq: 'är lika med' } } });
// ([State] är lika med "Florida" ELLER [Score] is greater than 3)
describeHtml() always escapes, and there is no way to turn that
off. A document is client-supplied input — field labels, values and
emptyText all come from somewhere you do not control — so
<img src=x onerror=…> in a value comes back as text, every time.
That is also why it is a separate function rather than a flag on
describe(): the call site says out loud that it is producing markup.
A longer one, rendered live below — this page loads
src/k-conditions-editor.css and nothing else, and has no editor
anywhere on it:
(Name is equal to A AND NOT (State is equal to Florida OR State is equal to Texas))
The classes it emits
| Class | Wraps |
|---|---|
.kcd | The whole rendering. |
.kcd-field | A field name — a <strong>. |
.kcd-op | An operator phrase. |
.kcd-value | A value. |
.kcd-list / .kcd-sep | A list of values, and the commas between them. |
.kcd-logic (plus .kcd-and or .kcd-or) | A joining operator. |
.kcd-not | A negation. |
.kcd-paren | A bracket. |
.kcd-join | The word between the two halves of a two-value operator — the and in is between 5 and 10. |
The stylesheet ships a default look for these — bold field, dashed-underlined value
in the value colour, italic operator, coloured AND / OR —
and that block is deliberately not scoped to the editor, so a page
that renders a rule server-side with no editor on it can load the CSS and get the
same look. The colours defer to the editor's --kce-* tokens when they are
present and fall back to their own otherwise, so the rendering also stays in step
with a theme when the editor is on the page. The markup carries no inline
styles, so restyling it is a matter of overriding those classes.
In the editor
summaryHtml: true renders the collapsed summary with
describeHtml() instead of plain text, so the field names and values in
the header get the same treatment. The editor also exposes both directly, using its
own fields and operators so you need not pass them again.
const editor = KConditionsEditor.attach('#conditions', { fields, summaryHtml: true });
editor.describe(); // string
editor.describeHtml(); // string of HTML
Security
-
Callback dispatch is off by default. Resolving a function name out
of a JSON document is arbitrary dispatch, so every SDK looks in its own registry
first and ignores the
callbacksblock entirely unless you setallowManifestCallbacks: true. Narrow it further withcallbackAllowList. Registering your callables withregisterOperator()is the recommended route and needs no opt-in. -
Validate against your own field list before evaluating, so a
tampered document cannot reference fields you never offered:
validateDocument(doc, { fields }). -
Regular expressions come from the document. A pathological pattern
can be expensive to run. If documents can be authored by people you do not trust,
drop
regexfrom the operator lists, or evaluate behind a timeout. - Never let a client-side result stand in for the server's. The point of the skip policy is to pre-check what can be pre-checked; the server still has to evaluate the whole rule.
Porting to another language
The document format is deliberately small. A port needs: a recursive walk over
group and condition nodes, the operator table, the four coercion helpers
(toNumber, toDate, toBool, toList),
and the policy resolver.
Then point it at tests/fixtures/cases.json. Those fixtures are the
contract — the JavaScript and PHP suites run the identical file, and a port that
passes them agrees with both.