File size: 13,553 Bytes
c3e4cb4 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 | // ---------------------------------------------------------------------------
// automation/CondBuilder.tsx β the condition TREE editor (contract C4).
//
// ONE editor, three callers: the trigger's "when a record matches conditions"
// (image 4), a conditional group's "Run actions in this group ifβ¦" (image 9),
// and a Find records step. They are the same shape (`Cond`) evaluated by the
// same engine function, so a second implementation would be a second set of
// bugs β and the one that matters is silent: a tree the editor can BUILD but
// the server refuses reads to the user as "it just doesn't save".
//
// β THE VOCABULARY IS THE SERVER'S. The operators are `flow.condOps`, the
// value-free ones are `flow.nullaryCondOps`, and the depth/breadth ceilings are
// `flow.maxCondDepth`/`maxCondChildren` β all off `GET /automations`. This file
// holds NO list of operators. It holds a WORDING for the ones it recognises and
// falls through to the raw key for anything it does not, which is visible and
// therefore reportable; a `switch` with no arm for a new op would render the row
// as nothing at all (the wave-9 silent-drop class).
//
// β IT NEVER PREDICTS A REFUSAL. `clean_cond` refuses an empty group, an
// unknown op, a valueless compare and an over-deep tree, each with a sentence.
// This editor SAYS a condition is incomplete β the red line Airtable shows β and
// still lets the save happen, so the authority on legality stays in one place.
// A client that blocked Save on its own arithmetic can block a tree the server
// would have taken, and the user cannot tell which of the two is wrong
// (`DiscoverGuard`'s note in automationApi states the same rule for the corpus
// filter, and it is the same rule).
// ---------------------------------------------------------------------------
import type { Cond } from "./automationApi";
import { groupParts, isCondGroup } from "./automationApi";
interface Field {
key: string;
label: string;
type?: string;
}
interface Props {
/** The stored tree. `null` = no conditions yet, which is a legal state, not an empty one. */
cond: Cond | null;
onChange: (next: Cond | null) => void;
fields: Field[];
/** `flow.condOps` β the comparisons the engine can answer. */
ops: string[];
/** `flow.nullaryCondOps` β the ones that take no value. */
nullaryOps: string[];
maxDepth: number;
maxChildren: number;
/** Prefix on the first row. Airtable says "When" at a trigger and nothing inside a group. */
lead?: string;
disabled?: boolean;
}
/**
* The WORDING of an operator, never the LIST of them.
*
* β The keys are the engine's `LANE_OPS` and the fallback is the key itself: an operator this
* table has not heard of renders as `>=` rather than as a blank cell. Ugly beats invisible β
* a blank is indistinguishable from a bug and nobody reports the row they cannot see.
* (Booked in the B mailbox as a small ask: `condOpLabels` on the wire would delete this map.)
*/
const OP_WORDS: Record<string, string> = {
"=": "is",
"!=": "is not",
">": "is greater than",
">=": "is at least",
"<": "is less than",
"<=": "is at most",
includes: "contains",
not_includes: "does not contain",
is_empty: "is empty",
is_not_empty: "is not empty",
};
export function opWord(op: string): string {
return OP_WORDS[op] || op;
}
/** A fresh leaf, using the FIRST operator the server offered rather than a hard-coded "=". */
function newLeaf(ops: string[]): Cond {
return { field: "", op: ops[0] || "", value: "" };
}
/**
* β ONE CHILD IS STORED AS A BARE LEAF, not as a group of one.
*
* Both are legal (`cond_match` dispatches on shape), and the engine's own note says a stored
* leaf is never rewritten at rest. Emitting the leaf keeps a one-condition trigger byte-identical
* to what wave 22 wrote, so opening an old automation in this editor and saving it unchanged
* does not produce a diff β a save that silently reshapes stored data is how "I only looked at
* it" turns into a migration nobody reviewed.
*/
function pack(join: "all" | "any", children: Cond[]): Cond | null {
if (!children.length) return null;
if (children.length === 1 && !isCondGroup(children[0])) return children[0];
return join === "all" ? { all: children } : { any: children };
}
/** Is every leaf in this tree answerable? Drives the red line, never the Save button. */
export function condComplete(cond: Cond | null | undefined, nullaryOps: string[]): boolean {
if (!cond) return true;
if (isCondGroup(cond)) {
const { children } = groupParts(cond);
return children.length > 0 && children.every((c) => condComplete(c, nullaryOps));
}
const leaf = cond as { field: string; op: string; value?: string | number };
if (!leaf.field || !leaf.op) return false;
if (nullaryOps.includes(leaf.op)) return true;
return leaf.value !== undefined && String(leaf.value).trim() !== "";
}
export default function CondBuilder({
cond,
onChange,
fields,
ops,
nullaryOps,
maxDepth,
maxChildren,
lead = "When",
disabled,
}: Props) {
// The editor always works on a GROUP even when one leaf is stored β a list of one is still a
// list, and `pack` puts it back the way it was found.
const { join, children } = isCondGroup(cond)
? groupParts(cond)
: { join: "all" as const, children: cond ? [cond] : [] };
const emit = (nextJoin: "all" | "any", next: Cond[]) => onChange(pack(nextJoin, next));
const replace = (i: number, next: Cond) =>
emit(join, children.map((c, j) => (j === i ? next : c)));
return (
<div className="autoc-tree">
{children.map((child, i) => (
/*
β THE KEY CARRIES THE ROW COUNT, and that is what makes the uncontrolled value input
above safe. Keyed by index alone, removing row 0 would REUSE row 0's DOM node for what
used to be row 1 β and an uncontrolled input keeps its own DOM value, so the reader
would be looking at the deleted row's text under the surviving row's field. Changing
the count remounts the whole list, which discards every stale DOM value at exactly the
moment the structure changes.
*/
<div className="autoc-row" key={`${children.length}:${i}`}>
<button
type="button"
className="autoc-drop"
disabled={disabled}
aria-label="Remove this condition"
title="Remove this condition"
onClick={() => emit(join, children.filter((_c, j) => j !== i))}
>
<svg width="12" height="12" viewBox="0 0 16 16" fill="none" aria-hidden="true">
<path
d="M4 4l8 8M12 4l-8 8"
stroke="currentColor"
strokeWidth="1.5"
strokeLinecap="round"
/>
</svg>
</button>
{/*
THE JOIN IS THE GROUP'S, AND IT IS EDITED IN EXACTLY ONE PLACE. Row 2 carries the
dropdown; every later row prints the word it chose. Giving each row its own
and/or select would offer a mixed tree the shape cannot express β `{all: [β¦]}` has
one join β and the user would discover that only when their third row silently
behaved like the second's.
*/}
<span className="autoc-join">
{i === 0 ? (
lead
) : i === 1 ? (
<select
className="auto-input is-tiny"
value={join}
disabled={disabled}
aria-label="Match all or any of these conditions"
onChange={(e) => emit(e.target.value === "any" ? "any" : "all", children)}
>
<option value="all">and</option>
<option value="any">or</option>
</select>
) : (
<span className="autoc-join-word">{join === "all" ? "and" : "or"}</span>
)}
</span>
{isCondGroup(child) ? (
<div className="autoc-nest">
<CondBuilder
cond={child}
onChange={(next) =>
next
? replace(i, next)
: emit(join, children.filter((_c, j) => j !== i))
}
fields={fields}
ops={ops}
nullaryOps={nullaryOps}
maxDepth={maxDepth - 1}
maxChildren={maxChildren}
lead=""
{...(disabled ? { disabled: true } : {})}
/>
</div>
) : (
<Leaf
leaf={child as { field: string; op: string; value?: string | number }}
fields={fields}
ops={ops}
nullaryOps={nullaryOps}
{...(disabled ? { disabled: true } : {})}
onChange={(next) => replace(i, next)}
/>
)}
</div>
))}
<div className="autoc-adds">
<button
type="button"
className="autoc-add"
disabled={disabled || children.length >= maxChildren}
title={
children.length >= maxChildren
? `This group holds at most ${maxChildren} conditions.`
: undefined
}
onClick={() => emit(join, [...children, newLeaf(ops)])}
>
+ Add condition
</button>
{/* Nesting is offered only while the SERVER's depth allows it β the ceiling rides the
payload, so this control disappears at the same depth `clean_cond` refuses. */}
{maxDepth > 1 ? (
<button
type="button"
className="autoc-add"
disabled={disabled || children.length >= maxChildren}
onClick={() => emit(join, [...children, { all: [newLeaf(ops)] }])}
>
+ Add condition group
</button>
) : null}
</div>
{/* THE RED LINE (image 4). A statement about the tree, not a wall in front of Save. */}
{!condComplete(pack(join, children), nullaryOps) ? (
<p className="autoc-bad">A condition is incomplete or invalid.</p>
) : null}
</div>
);
}
function Leaf({
leaf,
fields,
ops,
nullaryOps,
disabled,
onChange,
}: {
leaf: { field: string; op: string; value?: string | number };
fields: Field[];
ops: string[];
nullaryOps: string[];
disabled?: boolean;
onChange: (next: Cond) => void;
}) {
const nullary = nullaryOps.includes(leaf.op);
return (
<>
<select
className="auto-input is-tiny"
value={leaf.field}
disabled={disabled}
aria-label="Field"
onChange={(e) => onChange({ ...leaf, field: e.target.value })}
>
<option value="">Choose a fieldβ¦</option>
{/*
β THE STORED VALUE IS ALWAYS AN OPTION. A <select> whose `value` matches no <option>
renders the FIRST one, so a condition on a column this list has not caught up with
would LOOK like a condition on a different column β and the next Save would write that
different column without anybody choosing it. This repo has paid for that twice
([[cg-condition-builder-items]]).
*/}
{leaf.field && !fields.some((f) => f.key === leaf.field) ? (
<option value={leaf.field}>{leaf.field} (not in this database)</option>
) : null}
{fields.map((f) => (
<option key={f.key} value={f.key}>
{f.label}
</option>
))}
</select>
<select
className="auto-input is-tiny"
value={leaf.op}
disabled={disabled}
aria-label="Comparison"
onChange={(e) => {
const op = e.target.value;
// Moving to a value-free comparison DROPS the value rather than keeping it out of
// sight: a stored `value` under `is_empty` is a fact the sentence does not show and
// the next operator change would silently resurrect.
onChange(nullaryOps.includes(op) ? { field: leaf.field, op } : { ...leaf, op });
}}
>
{leaf.op && !ops.includes(leaf.op) ? (
<option value={leaf.op}>{opWord(leaf.op)} (not offered here)</option>
) : null}
{ops.map((op) => (
<option key={op} value={op}>
{opWord(op)}
</option>
))}
</select>
{nullary ? null : (
/*
β FREE TEXT COMMITS ON BLUR, like every other free-text field in this builder β and
the controlled version this replaced was worse than merely chatty. `onChange` reached
`patchTrigger` β PATCH, so typing "New" fired THREE requests; the displayed value
could not advance until each round-trip landed; and `disabled={busy}` disabled the
input under the typist's fingers. The two selects beside it stay controlled because
each is ONE discrete decision, which is exactly the distinction the cron field made
(AutomationTrigger's note) and the reason this input is not one.
*/
<input
className="auto-input is-tiny autoc-value"
defaultValue={leaf.value === undefined ? "" : String(leaf.value)}
disabled={disabled}
aria-label="Value"
placeholder="Value"
onBlur={(e) => {
if (e.target.value !== String(leaf.value ?? "")) onChange({ ...leaf, value: e.target.value });
}}
/>
)}
</>
);
}
|