diff --git a/.github/workflows/playground-ci.yml b/.github/workflows/playground-ci.yml
index 2ed7b46..2db5852 100644
--- a/.github/workflows/playground-ci.yml
+++ b/.github/workflows/playground-ci.yml
@@ -48,6 +48,8 @@ jobs:
- run: npm ci
# Same build the deploy runs: tsc --noEmit && vite build.
- run: npm run build
+ - name: Live data preview regression
+ run: npm run test:preview
# DSL-emitter regression checks (hunt #7). Compiled with the tsc that is
# already a devDependency so no test runner has to be added; the script
# throws on a failed check, which fails the step.
diff --git a/playground/README.md b/playground/README.md
index 2277068..cf2b883 100644
--- a/playground/README.md
+++ b/playground/README.md
@@ -10,8 +10,27 @@ into the **Query** node, and the resulting DSL string is generated live.
npm install
npm run dev # http://localhost:5173
npm run build # static bundle in dist/
+npm run test:preview # live DSL/table regression checks
```
+## Live data examples
+
+Below the canvas, the live data preview parses the generated DSL string and applies
+it to 18 sample customer accounts and their orders. Six presets demonstrate nested
+conditions, active customers, revenue and date ranges, case-insensitive name search,
+pagination, and filtered Orders preloads. Loading a preset also updates the canvas.
+
+Edit the preview's DSL to try your own filters, or enable **Follow visual builder**
+to resume using the canvas output. **All source rows** shows the original dataset
+with badges for matching, excluded, and paginated-out rows. Expand a row's Orders
+button to compare the original orders with the query's filtered preload.
+
+This is a browser-side demonstration, not a database execution engine. Comparisons
+are typed, NULL predicates follow SQL three-valued logic, and sorting places NULLs
+last. Regex operators and relations other than Orders report an explicit error.
+Backend collation, date coercion, and NULL ordering can differ. The Go adapters
+remain authoritative for actual database queries.
+
## Blocks
| Block | Emits | Notes |
diff --git a/playground/index.html b/playground/index.html
index f704ac3..c3edf45 100644
--- a/playground/index.html
+++ b/playground/index.html
@@ -26,8 +26,8 @@
.project-intro p { margin: 8px 0; }
.project-intro a, .project-guide a { color: #9baeff; text-underline-offset: 3px; }
.project-intro nav { display: flex; flex-wrap: wrap; gap: 8px 24px; }
- #root { height: 85vh; min-height: 540px; }
- #root .app { height: 100%; }
+ body > #root { height: auto; }
+ #root .app { height: 85vh; min-height: 540px; }
.project-guide { padding-top: 32px; padding-bottom: 48px; }
.project-guide section { margin: 0 0 32px; }
.project-guide h2 { font-size: 24px; line-height: 1.3; }
@@ -49,15 +49,16 @@
figo — Go dynamic query builder and filter DSL
Source code on GitHub
Go quick start
+ Try live data filtering
Examples and documentation
-
+
Try the visual filter builder
Add a Condition block, choose a field and operator, and connect it to the Query node. Combine conditions with AND, OR, and NOT blocks. Sort, Page, and Load blocks add sorting, pagination, and relation filters. Copy the generated DSL into your application.
- The playground generates filter text in your browser. It does not run Go code or connect to your database. JavaScript is needed for the interactive builder; the examples and documentation below are available without it.
+ The playground generates filter text in your browser. The live data preview applies that DSL to sample accounts and orders, so you can see matching rows, sorting, and pagination immediately. It does not run Go code or connect to your database. JavaScript is needed for the interactive builder and preview; the examples and documentation below are available without it.
Build database queries from API filters in Go
diff --git a/playground/package.json b/playground/package.json
index 86aca96..5b1bda1 100644
--- a/playground/package.json
+++ b/playground/package.json
@@ -6,7 +6,8 @@
"scripts": {
"dev": "vite",
"build": "tsc --noEmit && vite build",
- "preview": "vite preview"
+ "preview": "vite preview",
+ "test:preview": "tsc src/preview.test.ts --outDir node_modules/.cache/preview-tests --target es2022 --module esnext --moduleResolution bundler --skipLibCheck && node node_modules/.cache/preview-tests/preview.test.js"
},
"dependencies": {
"@xyflow/react": "^12.8.2",
diff --git a/playground/src/App.tsx b/playground/src/App.tsx
index 4ed8c95..b128d7b 100644
--- a/playground/src/App.tsx
+++ b/playground/src/App.tsx
@@ -1,4 +1,4 @@
-import { useCallback, useMemo, useRef } from 'react'
+import { useCallback, useEffect, useMemo, useRef, useState } from 'react'
import {
Background,
BackgroundVariant,
@@ -19,6 +19,8 @@ import { edgeTypes } from './edges'
import { Palette, type PaletteItem } from './Palette'
import { DslPanel } from './DslPanel'
import { generateDsl, type AppNode } from './dsl'
+import { DataPreview } from './DataPreview'
+import { sampleGraph } from './samples'
type Kind = 'expr' | 'sort' | 'page' | 'load'
@@ -235,7 +237,9 @@ function defaultData(item: PaletteItem): Record {
function Flow() {
const [nodes, setNodes, onNodesChange] = useNodesState(presetNodes())
const [edges, setEdges, onEdgesChange] = useEdgesState(presetEdges())
- const { screenToFlowPosition, getNode } = useReactFlow()
+ const { screenToFlowPosition, getNode, fitView } = useReactFlow()
+ const [sampleId, setSampleId] = useState('complex')
+ const [sampleRevision, setSampleRevision] = useState(0)
const wrapRef = useRef(null)
const nodeSeq = useRef(0)
@@ -344,23 +348,33 @@ function Flow() {
[addNode, screenToFlowPosition],
)
- const loadExample = useCallback(() => {
- setNodes(presetNodes())
- setEdges(presetEdges())
+ const loadSample = useCallback((id: string) => {
+ const graph = id === 'complex' ? { nodes: presetNodes(), edges: presetEdges() } : sampleGraph(id)
+ setNodes(graph.nodes)
+ setEdges(graph.edges)
+ setSampleId(id)
+ setSampleRevision((revision) => revision + 1)
}, [setNodes, setEdges])
+ useEffect(() => {
+ const timer = window.setTimeout(() => { void fitView({ padding: 0.16, maxZoom: 1 }) }, 50)
+ return () => window.clearTimeout(timer)
+ }, [sampleRevision, fitView])
+
const clearAll = useCallback(() => {
setNodes((nds) => nds.filter((n) => n.type === 'root'))
setEdges([])
}, [setNodes, setEdges])
return (
+ <>
+
+ >
)
}
diff --git a/playground/src/DataPreview.tsx b/playground/src/DataPreview.tsx
new file mode 100644
index 0000000..435513c
--- /dev/null
+++ b/playground/src/DataPreview.tsx
@@ -0,0 +1,114 @@
+import { Fragment, useEffect, useMemo, useState } from 'react'
+import { CUSTOMER_FIELDS, CUSTOMERS, type Customer } from './sampleData'
+import { previewDsl } from './preview'
+import { SAMPLES } from './samples'
+
+const dollars = new Intl.NumberFormat('en-US', { style: 'currency', currency: 'USD', maximumFractionDigits: 0 })
+const nullable = (value: string | null) => value ?? 'NULL'
+
+export function DataPreview({ dsl, sampleId, revision, onSample }: {
+ dsl: string; sampleId: string; revision: number; onSample: (id: string) => void
+}) {
+ const [editedDsl, setEditedDsl] = useState(null)
+ const [showAll, setShowAll] = useState(false)
+ const [expanded, setExpanded] = useState>(new Set())
+ useEffect(() => { setEditedDsl(null) }, [revision])
+ const activeDsl = editedDsl ?? dsl
+ const result = useMemo(() => {
+ try { return { preview: previewDsl(activeDsl, CUSTOMERS), error: null } }
+ catch (error) { return { preview: null, error: error instanceof Error ? error.message : 'This filter could not be applied.' } }
+ }, [activeDsl])
+ const { preview, error } = result
+ const rows = preview ? showAll ? CUSTOMERS : preview.rows : []
+ const sample = SAMPLES.find((item) => item.id === sampleId) ?? SAMPLES[0]
+ const toggle = (id: number) => setExpanded((previous) => {
+ const next = new Set(previous); if (next.has(id)) next.delete(id); else next.add(id); return next
+ })
+ const matchLabel = (row: Customer) => !preview?.matchingIds.has(row.id) ? 'Filtered out' : !preview.visibleIds.has(row.id) ? 'Outside page' : 'In results'
+
+ return (
+
+
+
+
DSL → sample data
+
See your filter in action
+
Change the blocks above or edit the DSL below. The table updates immediately.
+
+
+ Load an example
+ {
+ setEditedDsl(null); setShowAll(false); onSample(event.target.value)
+ }}>
+ {SAMPLES.map((item) => {item.name} )}
+
+
+
+ {sample.description}
+
+ DSL applied to the table
+
+ setEditedDsl(event.target.checked ? null : dsl)} />
+ Follow visual builder
+
+
+
+ )
+}
diff --git a/playground/src/preview.test.ts b/playground/src/preview.test.ts
new file mode 100644
index 0000000..3654a1a
--- /dev/null
+++ b/playground/src/preview.test.ts
@@ -0,0 +1,62 @@
+import { previewDsl } from './preview.js'
+import { CUSTOMERS } from './sampleData.js'
+import { generateDsl } from './dsl.js'
+import { sampleGraph, SAMPLES } from './samples.js'
+
+let checks = 0
+function equal(actual: unknown, expected: unknown, message: string) {
+ checks++
+ if (JSON.stringify(actual) !== JSON.stringify(expected)) throw new Error(`${message}: got ${JSON.stringify(actual)}, expected ${JSON.stringify(expected)}`)
+}
+function ids(dsl: string) { return previewDsl(dsl, CUSTOMERS).rows.map((row) => row.id) }
+function rejects(dsl: string) {
+ checks++
+ try { previewDsl(dsl, CUSTOMERS) } catch { return }
+ throw new Error(`Invalid or unsupported DSL was accepted: ${dsl}`)
+}
+
+const full = '(status["active","trialing"] or (plan="enterprise" and seats>=50)) and not (email=^"%@test.local" or name=^"QA %") and signup_date(2024-01-01..2024-12-31) and deleted_at and last_login and mrr>99.5 sort=mrr:desc,name:asc page=skip:0,take:20 load=[Orders:total>100 and status!="refunded"]'
+const result = previewDsl(full, CUSTOMERS)
+equal(result.rows.map((row) => row.id), [4, 15, 3, 2, 16, 18, 1, 14], 'Full user example: filtering and stable multi-column sorting')
+equal(result.rows.find((row) => row.id === 1)?.Orders.map((order) => order.id), [12], 'Preload filters child orders')
+equal(result.rows.find((row) => row.id === 14)?.Orders, [], 'Preload with no matching children keeps the parent account')
+equal(CUSTOMERS[0].Orders.length, 3, 'Preview never mutates source orders')
+equal(ids('').length, 18, 'Empty DSL shows the dataset')
+equal(ids('page=skip:17,take:0'), [18], 'take:0 means no limit, with skip applied')
+equal(ids('page=skip:100,take:3'), [], 'Out-of-range page is empty')
+equal(ids('status="trialing" or status="paused" and seats>=50'), [2, 3, 11, 14], 'AND has higher precedence than OR')
+equal(ids('(status="trialing" or status="paused") and seats>=50'), [3], 'Parentheses override precedence')
+equal(ids('not last_login="2026-10-20"'), [], 'NOT preserves SQL UNKNOWN for NULL values')
+equal(ids('last_login=null'), [8, 13], 'Equality to null is IS NULL')
+equal(ids('last_login[]'), [], 'Empty IN matches nothing, including NULL rows')
+equal(ids('last_login[]').length, 18, 'Empty NOT IN matches everything')
+equal(ids('last_login last_login["different",null]'), [], 'NULL in NOT IN yields UNKNOWN')
+equal(ids('name.=^"%AL%"'), [1, 7, 16], 'Case-insensitive LIKE')
+equal(ids('name=^"Alice ____"'), [1], 'LIKE underscore matches one character')
+equal(ids('signup_date(2024-01-01..2024-01-01)'), [16], 'BETWEEN bounds are inclusive')
+equal(ids('mrr(299..299)'), [2, 16, 18], 'Numeric range is inclusive')
+equal(ids('name="Alice Chen" or name="QA Kelly"'), [1, 10], 'Quoted strings with spaces')
+equal(ids('id[1,2] sort=name:desc page=skip:0,take:1'), [2], 'Filter, sort, and pagination execute in order')
+equal(ids('id=14 load=[Orders:total>100]'), [14], 'Load does not become an EXISTS filter')
+
+for (const sample of SAMPLES.filter((sample) => sample.id !== 'complex')) {
+ const graph = sampleGraph(sample.id), generated = generateDsl(graph.nodes, graph.edges)
+ equal(generated.warnings, [], `${sample.name}: valid graph DSL`)
+ const preview = previewDsl(generated.dsl, CUSTOMERS)
+ equal(preview.rows.length > 0, true, `${sample.name}: returns illustrative data`)
+ if (sample.id === 'page') equal(preview.rows.map((row) => row.id), [7, 6, 16], 'Second-page preset is reproducible')
+ if (sample.id === 'orders') {
+ equal(preview.rows.find((row) => row.id === 1)?.Orders.length, 1, 'Orders preset applies preload')
+ equal(preview.rows.find((row) => row.id === 18)?.Orders.length, 0, 'Orders preset includes a parent with no qualifying children')
+ }
+}
+
+for (const dsl of [
+ 'unknown=1', 'name=~"(a+)+$"', 'name="unfinished', 'mrr(10..)',
+ 'status="active" and', 'page=skip:-1,take:3', 'page=skip:0,take:1.5',
+ 'sort=unknown:asc', 'sort=name:sideways', 'load=[Missing:total>1]',
+ 'load=[Orders:unknown=1]', 'mrr>1 trailing', 'id "=" 1', 'sort=name:"asc"',
+ '('.repeat(45) + 'id=1' + ')'.repeat(45),
+]) rejects(dsl)
+
+console.log(`Live data preview: ${checks} checks passed`)
diff --git a/playground/src/preview.ts b/playground/src/preview.ts
new file mode 100644
index 0000000..318fce8
--- /dev/null
+++ b/playground/src/preview.ts
@@ -0,0 +1,232 @@
+import { CUSTOMER_FIELDS, ORDER_FIELDS, type Customer, type Order } from './sampleData.js'
+
+type Scalar = string | number | boolean | null
+type Truth = boolean | null
+type Row = Customer | Order
+type Predicate = (row: Row) => Truth
+type Token = { text: string; quoted: boolean; at: number }
+type Sort = { field: string; descending: boolean }
+
+export interface Preview {
+ rows: Customer[]
+ matchingIds: Set
+ visibleIds: Set
+ matched: number
+ skip: number
+ take: number
+ loadsOrders: boolean
+}
+
+const OPS = ['', '', '', '', '', '!=^', '.=^', '=^', '!=~', '=~', '>=', '<=', '!=', '>', '<', '=']
+const DIRECTIVES = ['sort', 'page', 'load']
+
+function tokenize(dsl: string): Token[] {
+ if (dsl.length > 12000) throw new Error('The demo accepts at most 12,000 characters of DSL.')
+ const tokens: Token[] = []
+ let i = 0
+ while (i < dsl.length) {
+ if (/\s/.test(dsl[i])) { i++; continue }
+ const at = i
+ if (dsl[i] === '"') {
+ const end = dsl.indexOf('"', i + 1)
+ if (end < 0) throw new Error(`Unclosed quoted value at character ${i + 1}.`)
+ tokens.push({ text: dsl.slice(i + 1, end), quoted: true, at }); i = end + 1
+ } else {
+ const op = OPS.find((candidate) => dsl.startsWith(candidate, i))
+ if (op) { tokens.push({ text: op, quoted: false, at }); i += op.length }
+ else if (dsl.startsWith('..', i)) { tokens.push({ text: '..', quoted: false, at }); i += 2 }
+ else if ('()[],:|'.includes(dsl[i])) { tokens.push({ text: dsl[i++], quoted: false, at }) }
+ else {
+ while (i < dsl.length && !/[\s"()\[\],:|<>=!~^]/.test(dsl[i]) && !dsl.startsWith('..', i) && !dsl.startsWith('.=^', i)) i++
+ if (i === at) throw new Error(`Unexpected character at position ${i + 1}.`)
+ tokens.push({ text: dsl.slice(at, i), quoted: false, at })
+ }
+ }
+ if (tokens.length > 1000) throw new Error('This filter is too large for the sample preview.')
+ }
+ return tokens
+}
+
+function fieldValue(row: Row, field: string): Scalar {
+ return (row as unknown as Record)[field]
+}
+
+function and(a: Truth, b: Truth): Truth { return a === false || b === false ? false : a === null || b === null ? null : true }
+function or(a: Truth, b: Truth): Truth { return a === true || b === true ? true : a === null || b === null ? null : false }
+function not(a: Truth): Truth { return a === null ? null : !a }
+
+// SQL LIKE matching in bounded O(pattern × text) time, without evaluating user regexes.
+function like(text: string, pattern: string, insensitive: boolean): boolean {
+ if (pattern.length > 256) throw new Error('LIKE patterns in the demo are limited to 256 characters.')
+ if (insensitive) { text = text.toLowerCase(); pattern = pattern.toLowerCase() }
+ const chars = Array.from(text)
+ let previous = Array(chars.length + 1).fill(false)
+ previous[0] = true
+ for (const char of pattern) {
+ const next = Array(chars.length + 1).fill(false)
+ next[0] = char === '%' && previous[0]
+ for (let i = 1; i <= chars.length; i++) {
+ next[i] = char === '%' ? previous[i] || next[i - 1] : previous[i - 1] && (char === '_' || char === chars[i - 1])
+ }
+ previous = next
+ }
+ return previous[chars.length]
+}
+
+function compare(a: Scalar, b: Scalar): number | null {
+ if (a === null || b === null || typeof a !== typeof b) return null
+ return a === b ? 0 : a < b ? -1 : 1
+}
+
+class Parser {
+ private pos = 0
+ private depth = 0
+ constructor(private tokens: Token[]) {}
+ private peek(offset = 0) { return this.tokens[this.pos + offset] }
+ private is(text: string) { const t = this.peek(); return t !== undefined && !t.quoted && t.text === text }
+ private take(text: string) { if (!this.is(text)) return false; this.pos++; return true }
+ private expect(text: string) {
+ if (!this.take(text)) throw new Error(`Expected ${text} near character ${(this.peek()?.at ?? 0) + 1}.`)
+ }
+ private directive() { return this.peek() && !this.peek().quoted && DIRECTIVES.includes(this.peek().text) && this.peek(1)?.text === '=' && !this.peek(1).quoted }
+ private field(fields: readonly string[]) {
+ const token = this.tokens[this.pos++]
+ if (!token || token.quoted || !fields.includes(token.text)) {
+ throw new Error(`Unknown field ${JSON.stringify(token?.text ?? '')}. Available fields: ${fields.join(', ')}.`)
+ }
+ return token.text
+ }
+ private scalar(): Scalar {
+ const token = this.tokens[this.pos++]
+ if (!token || (!token.quoted && ['(', ')', '[', ']', ',', ':', '|', '..', ...OPS].includes(token.text))) {
+ throw new Error('A comparison value is missing or incomplete.')
+ }
+ if (token.quoted) return token.text
+ if (token.text === 'null') return null
+ if (token.text === 'true' || token.text === 'false') return token.text === 'true'
+ if (/^-?\d+(\.\d+)?$/.test(token.text)) {
+ const value = Number(token.text)
+ if (!Number.isFinite(value)) throw new Error('Numeric values must be finite.')
+ return value
+ }
+ return token.text
+ }
+ private unary(fields: readonly string[]): Predicate {
+ if (++this.depth > 40) throw new Error('The demo supports at most 40 levels of grouping.')
+ try {
+ if (this.take('not')) { const expr = this.unary(fields); return (row) => not(expr(row)) }
+ if (this.take('(')) { const expr = this.expr(fields); this.expect(')'); return expr }
+ const field = this.field(fields)
+ const operator = this.tokens[this.pos++]
+ const op = operator?.text
+ if (!op || operator.quoted || !OPS.includes(op)) throw new Error(`Choose a comparison operator for ${field}.`)
+ if (op === '=~' || op === '!=~') throw new Error('Regex preview is not supported. Use LIKE (=^) or the Go adapters for regular expressions.')
+ if (op === '' || op === '') return (row) => (fieldValue(row, field) === null) === (op === '')
+ let values: Scalar[]
+ if (op === '' || op === '') {
+ this.expect('['); values = []
+ if (!this.take(']')) {
+ do { values.push(this.scalar()) } while (this.take(','))
+ this.expect(']')
+ }
+ } else if (op === '') {
+ this.expect('('); const lo = this.scalar(); this.expect('..'); const hi = this.scalar(); this.expect(')'); values = [lo, hi]
+ } else values = [this.scalar()]
+ if (['=^', '!=^', '.=^'].includes(op) && (typeof values[0] !== 'string' || values[0].length > 256)) {
+ throw new Error('LIKE needs a string pattern of at most 256 characters.')
+ }
+ return (row) => {
+ const actual = fieldValue(row, field), value = values[0]
+ if (op === '' || op === '') {
+ if (values.length === 0) return op === ''
+ const found: Truth = actual === null ? null : values.includes(actual) ? true : values.includes(null) ? null : false
+ return op === '' ? not(found) : found
+ }
+ if ((op === '=' || op === '!=') && value === null) return (actual === null) === (op === '=')
+ if (actual === null || value === null) return null
+ if (['=^', '!=^', '.=^'].includes(op)) {
+ const matched = typeof actual === 'string' && like(actual, value as string, op === '.=^')
+ return op === '!=^' ? !matched : matched
+ }
+ if (op === '') {
+ const lo = compare(actual, values[0]), hi = compare(actual, values[1])
+ return lo === null || hi === null ? null : lo >= 0 && hi <= 0
+ }
+ if (op === '=') return actual === value
+ if (op === '!=') return actual !== value
+ const c = compare(actual, value)
+ if (c === null) return false
+ return op === '>' ? c > 0 : op === '>=' ? c >= 0 : op === '<' ? c < 0 : c <= 0
+ }
+ } finally { this.depth-- }
+ }
+ private conjunction(fields: readonly string[]): Predicate {
+ let left = this.unary(fields)
+ while (this.peek() && !this.is('or') && !this.is(')') && !this.is(']') && !this.is('|') && !this.directive()) {
+ this.take('and') // Adjacent predicates also mean AND in figo.
+ const a = left, b = this.unary(fields)
+ left = (row) => and(a(row), b(row))
+ }
+ return left
+ }
+ private expr(fields: readonly string[]): Predicate {
+ let left = this.conjunction(fields)
+ while (this.take('or')) { const a = left, b = this.conjunction(fields); left = (row) => or(a(row), b(row)) }
+ return left
+ }
+ parse() {
+ const filter = this.peek() && !this.directive() ? this.expr(CUSTOMER_FIELDS) : () => true
+ const sort: Sort[] = []
+ let skip = 0, take = 0, orders: Predicate | null = null
+ while (this.peek()) {
+ const directive = this.peek().text
+ if (!this.directive()) throw new Error(`Unexpected token ${JSON.stringify(directive)}.`)
+ this.pos += 2
+ if (directive === 'sort') {
+ do {
+ const field = this.field(CUSTOMER_FIELDS); this.expect(':')
+ const direction = this.tokens[this.pos++]
+ if (!direction || direction.quoted || (direction.text !== 'asc' && direction.text !== 'desc')) throw new Error('Sort direction must be asc or desc.')
+ sort.push({ field, descending: direction.text === 'desc' })
+ } while (this.take(','))
+ } else if (directive === 'page') {
+ do {
+ const token = this.tokens[this.pos++]
+ const key = token?.text
+ if (!token || token.quoted || (key !== 'skip' && key !== 'take')) throw new Error('Page accepts skip and take.')
+ this.expect(':'); const value = this.scalar()
+ if (typeof value !== 'number' || !Number.isSafeInteger(value) || value < 0) throw new Error('Page skip/take must be non-negative whole numbers; take:0 means all rows.')
+ if (key === 'skip') skip = value; else take = value
+ } while (this.take(','))
+ } else {
+ this.expect('[')
+ if (!this.take('Orders')) throw new Error('The sample dataset has one relation: Orders (case-sensitive).')
+ if (orders) throw new Error('Use one Orders preload in the sample preview.')
+ this.expect(':'); orders = this.expr(ORDER_FIELDS); this.expect(']')
+ }
+ }
+ return { filter, sort, skip, take, orders }
+ }
+}
+
+/** Parse the emitted DSL string, not the diagram, then filter → sort → page → preload. */
+export function previewDsl(dsl: string, source: Customer[]): Preview {
+ const query = new Parser(tokenize(dsl)).parse()
+ const matches = source.filter((row) => query.filter(row) === true)
+ matches.sort((a, b) => {
+ for (const sort of query.sort) {
+ const av = fieldValue(a, sort.field), bv = fieldValue(b, sort.field)
+ // The demo consistently places NULLs last; database defaults vary.
+ const c = av === bv ? 0 : av === null ? 1 : bv === null ? -1 : (compare(av, bv) ?? 0) * (sort.descending ? -1 : 1)
+ if (c) return c
+ }
+ return 0
+ })
+ const rows = matches.slice(query.skip, query.take ? query.skip + query.take : undefined).map((row) => ({
+ ...row, Orders: row.Orders.filter((order) => !query.orders || query.orders(order) === true),
+ }))
+ return {
+ rows, matchingIds: new Set(matches.map((row) => row.id)), visibleIds: new Set(rows.map((row) => row.id)),
+ matched: matches.length, skip: query.skip, take: query.take, loadsOrders: query.orders !== null,
+ }
+}
diff --git a/playground/src/sampleData.ts b/playground/src/sampleData.ts
new file mode 100644
index 0000000..4fa32f0
--- /dev/null
+++ b/playground/src/sampleData.ts
@@ -0,0 +1,72 @@
+export interface Order {
+ id: number
+ total: number
+ status: string
+}
+
+export interface Customer {
+ id: number
+ name: string
+ email: string
+ status: string
+ plan: string
+ seats: number
+ signup_date: string
+ deleted_at: string | null
+ last_login: string | null
+ mrr: number
+ Orders: Order[]
+}
+
+function customer(
+ id: number, name: string, status: string, plan: string, seats: number, mrr: number,
+ signup_date = '2024-06-15', overrides: Partial = {},
+): Customer {
+ return {
+ id, name, status, plan, seats, mrr, signup_date,
+ email: `${name.toLowerCase().replaceAll(' ', '.')}@example.com`,
+ deleted_at: null, last_login: '2026-10-20',
+ Orders: [
+ { id: id * 10 + 1, total: 75, status: 'paid' },
+ { id: id * 10 + 2, total: 240, status: 'paid' },
+ { id: id * 10 + 3, total: 160, status: 'refunded' },
+ ],
+ ...overrides,
+ }
+}
+
+// Fixed dates and deliberately varied values keep every example reproducible.
+export const CUSTOMERS: Customer[] = [
+ customer(1, 'Alice Chen', 'active', 'pro', 12, 149),
+ customer(2, 'Ben Carter', 'trialing', 'pro', 8, 299),
+ customer(3, 'Carla Diaz', 'paused', 'enterprise', 80, 1299),
+ customer(4, 'Daniel Evans', 'active', 'enterprise', 100, 2499, '2024-03-10', {
+ Orders: [{ id: 41, total: 1000, status: 'paid' }, { id: 42, total: 600, status: 'paid' }, { id: 43, total: 70, status: 'pending' }],
+ }),
+ customer(5, 'Ella Foster', 'active', 'pro', 10, 199, '2023-08-05'),
+ customer(6, 'Farah Green', 'active', 'pro', 15, 349, '2025-02-12', {
+ Orders: [{ id: 61, total: 350, status: 'paid' }, { id: 62, total: 120, status: 'pending' }, { id: 63, total: 160, status: 'refunded' }],
+ }),
+ customer(7, 'George Hall', 'active', 'pro', 20, 399, '2024-07-20', { deleted_at: '2026-09-01' }),
+ customer(8, 'Hana Ito', 'active', 'pro', 5, 129, '2024-04-14', { last_login: null }),
+ customer(9, 'Ivan Jones', 'active', 'pro', 4, 49),
+ customer(10, 'QA Kelly', 'active', 'enterprise', 60, 899),
+ customer(11, 'Liam Moore', 'trialing', 'pro', 5, 199, '2024-10-02', { email: 'liam@test.local' }),
+ customer(12, 'Maya Nair', 'paused', 'enterprise', 30, 799),
+ customer(13, 'Noah Owen', 'churned', 'pro', 10, 0, '2024-01-15', { last_login: null, Orders: [] }),
+ customer(14, 'Olivia Park', 'trialing', 'starter', 3, 119, '2024-11-01', {
+ Orders: [{ id: 141, total: 90, status: 'paid' }],
+ }),
+ customer(15, 'Pablo Reed', 'active', 'enterprise', 50, 1499, '2024-12-31'),
+ customer(16, 'Salma Stone', 'active', 'pro', 8, 299, '2024-01-01'),
+ customer(17, 'Theo Taylor', 'paused', 'starter', 2, 29),
+ customer(18, 'Zara West', 'active', 'pro', 10, 299, '2024-09-09', {
+ Orders: [{ id: 181, total: 60, status: 'paid' }, { id: 182, total: 160, status: 'refunded' }],
+ }),
+]
+
+export const CUSTOMER_FIELDS = [
+ 'id', 'name', 'email', 'status', 'plan', 'seats', 'signup_date',
+ 'deleted_at', 'last_login', 'mrr',
+] as const
+export const ORDER_FIELDS = ['id', 'total', 'status'] as const
diff --git a/playground/src/samples.ts b/playground/src/samples.ts
new file mode 100644
index 0000000..84ddc3d
--- /dev/null
+++ b/playground/src/samples.ts
@@ -0,0 +1,68 @@
+import type { Edge } from '@xyflow/react'
+import type { AppNode } from './dsl.js'
+
+export const SAMPLES = [
+ { id: 'complex', name: '01 · Nested conditions + orders', description: 'The full example: grouped conditions, NOT, dates, NULL checks, sorting, pagination, and filtered orders.' },
+ { id: 'active', name: '02 · Active customers', description: 'Keep active, undeleted accounts and sort by monthly revenue.' },
+ { id: 'revenue', name: '03 · Revenue + signup dates', description: 'Active or trialing accounts with at least $250 MRR that signed up during 2024.' },
+ { id: 'names', name: '04 · Case-insensitive name search', description: 'Find names containing “al”, regardless of letter case.' },
+ { id: 'page', name: '05 · Second page of results', description: 'Sort active customers, skip the first three matches, and return the next three.' },
+ { id: 'orders', name: '06 · Filter related orders', description: 'Keep active customers, then load only orders above $100 that were not refunded. Customers with no qualifying orders remain visible.' },
+] as const
+
+type Condition = { field: string; op: string; value?: string; value2?: string }
+const presets: Record = {
+ active: {
+ conditions: [{ field: 'status', op: '=', value: 'active' }, { field: 'deleted_at', op: '' }],
+ sort: [['mrr', 'desc']],
+ },
+ revenue: {
+ conditions: [{ field: 'status', op: '', value: 'active, trialing' }, { field: 'mrr', op: '>=', value: '250' }, { field: 'signup_date', op: '', value: '2024-01-01', value2: '2024-12-31' }],
+ sort: [['mrr', 'desc'], ['name', 'asc']],
+ },
+ names: { conditions: [{ field: 'name', op: '.=^', value: '%al%' }], sort: [['name', 'asc']] },
+ page: { conditions: [{ field: 'status', op: '=', value: 'active' }], sort: [['mrr', 'desc'], ['name', 'asc']], page: [3, 3] },
+ orders: {
+ conditions: [{ field: 'status', op: '=', value: 'active' }, { field: 'deleted_at', op: '' }],
+ sort: [['name', 'asc']],
+ orders: [{ field: 'total', op: '>', value: '100' }, { field: 'status', op: '!=', value: 'refunded' }],
+ },
+}
+
+export function sampleGraph(id: string): { nodes: AppNode[]; edges: Edge[] } {
+ const preset = presets[id]
+ if (!preset) throw new Error(`Unknown sample: ${id}`)
+ const nodes: AppNode[] = [{ id: 'root', type: 'root', position: { x: 960, y: 190 }, deletable: false, data: {} }]
+ const edges: Edge[] = []
+ const connect = (source: string, target: string, targetHandle: string, color = '#8b9cc0') => {
+ edges.push({ id: `sample-${source}-${target}-${targetHandle}`, source, target, targetHandle, type: 'pip', style: { stroke: color, strokeWidth: 1.6 } })
+ }
+ const conditions = (items: Condition[], prefix: string, y: number, target: string, handle: string) => {
+ const group = items.length > 1 ? `${prefix}-and` : null
+ items.forEach((data, i) => {
+ const id = `${prefix}-${i}`
+ nodes.push({ id, type: 'condition', position: { x: 20, y: y + i * 125 }, data: { value: '', value2: '', ...data } })
+ connect(id, group ?? target, group ? 'in' : handle)
+ })
+ if (group) {
+ nodes.push({ id: group, type: 'logic', position: { x: 420, y: y + (items.length - 1) * 62 }, data: { kind: 'and' } })
+ connect(group, target, handle)
+ }
+ }
+ conditions(preset.conditions, 'filter', 0, 'root', 'filter')
+ preset.sort.forEach(([field, dir], i) => {
+ const id = `sample-sort-${i}`
+ nodes.push({ id, type: 'sort', position: { x: 710, y: 420 + i * 120 }, data: { field, dir } })
+ connect(id, 'root', 'sort', '#2dd4bf')
+ })
+ if (preset.page) {
+ nodes.push({ id: 'sample-page', type: 'page', position: { x: 1000, y: 430 }, data: { skip: preset.page[0], take: preset.page[1] } })
+ connect('sample-page', 'root', 'page', '#38bdf8')
+ }
+ if (preset.orders) {
+ nodes.push({ id: 'sample-load', type: 'load', position: { x: 710, y: 720 }, data: { relation: 'Orders' } })
+ conditions(preset.orders, 'orders', 650, 'sample-load', 'filter')
+ connect('sample-load', 'root', 'load', '#4ade80')
+ }
+ return { nodes, edges }
+}
diff --git a/playground/src/styles.css b/playground/src/styles.css
index 0e1e0c3..512339b 100644
--- a/playground/src/styles.css
+++ b/playground/src/styles.css
@@ -531,3 +531,62 @@ body,
.tok-num {
color: #e0af68;
}
+
+/* ---------- live sample data ---------- */
+
+.data-preview { padding: 32px max(24px, calc((100% - 1280px) / 2)); border-top: 1px solid var(--border); background: #101522; scroll-margin-top: 16px; }
+.preview-heading { display: flex; align-items: flex-start; justify-content: space-between; flex-wrap: wrap; gap: 20px; }
+.preview-heading h2 { font-size: clamp(23px, 3vw, 30px); line-height: 1.2; margin: 6px 0 10px; color: #e1e7ff; }
+.preview-heading p { margin: 0; }
+.preview-eyebrow { font-size: 11px; letter-spacing: 1.4px; text-transform: uppercase; color: #2dd4bf; font-weight: 700; }
+.sample-picker { display: flex; flex-direction: column; gap: 7px; font-size: 12px; color: #a9b8d9; min-width: 260px; }
+.sample-picker select { padding: 10px 12px; border: 1px solid #465275; border-radius: 8px; background: var(--panel); color: var(--text); font: inherit; font-size: 13px; }
+.sample-description { color: #a9b8d9; margin: 18px 0 22px; line-height: 1.6; }
+.preview-editor-heading { display: flex; align-items: center; justify-content: space-between; flex-wrap: wrap; gap: 12px; margin-bottom: 8px; font-size: 12px; font-weight: 600; }
+.follow-builder { display: inline-flex; align-items: center; gap: 7px; font-weight: 400; color: #b1bfdd; cursor: pointer; }
+.follow-builder input { accent-color: #2dd4bf; width: 15px; height: 15px; }
+#preview-dsl { display: block; width: 100%; min-height: 100px; resize: vertical; padding: 14px; border: 1px solid #465275; border-radius: 8px; background: #0b101b; color: #d5dfff; font: 12.5px/1.7 ui-monospace, 'SF Mono', Menlo, monospace; }
+#preview-dsl:focus, .sample-picker select:focus-visible, .preview-table-scroll:focus-visible { outline: 2px solid #818cf8; outline-offset: 3px; }
+.preview-summary { display: flex; align-items: center; flex-wrap: wrap; gap: 12px 28px; min-height: 68px; padding: 14px 0; font-size: 13px; color: #a9b8d9; }
+.preview-summary strong { font-size: 19px; color: #e1e7ff; }
+.preview-error { margin: 0; padding: 12px; border: 1px solid #ab555e; border-radius: 8px; color: #ffbcc4; background: #331e2a; line-height: 1.6; width: 100%; }
+.preview-toolbar { display: flex; align-items: center; justify-content: space-between; flex-wrap: wrap; gap: 12px; padding: 0 0 14px; font-size: 12px; color: #a9b8d9; }
+.preview-tabs { display: inline-flex; gap: 4px; padding: 4px; border: 1px solid var(--card-border); border-radius: 9px; background: #0d1220; }
+.preview-tabs button, .orders-toggle { border: 1px solid transparent; border-radius: 6px; background: transparent; color: #b2c0df; font: inherit; cursor: pointer; padding: 7px 12px; }
+.preview-tabs button[aria-pressed='true'] { background: #26335a; color: #e3eaff; }
+.preview-tabs button:hover, .orders-toggle:hover { background: #26335a; color: #e3eaff; }
+.preview-tabs button:focus-visible, .orders-toggle:focus-visible { outline: 2px solid #818cf8; outline-offset: 2px; }
+.preview-table-scroll { overflow-x: auto; border: 1px solid #303b56; border-radius: 10px; }
+.preview-table { width: 100%; border-collapse: collapse; white-space: nowrap; font-size: 12px; text-align: left; }
+.preview-table th, .preview-table td { padding: 13px 14px; border-bottom: 1px solid #29324a; }
+.preview-table thead { background: #1b2439; color: #cdd9f5; }
+.preview-table thead th { font-size: 11px; font-weight: 600; }
+.preview-table tbody > tr { background: #121a2b; }
+.preview-table tbody > tr:nth-child(4n + 1) { background: #151e31; }
+.preview-table th[scope='row'] { font-weight: 500; color: #e1e7ff; }
+.preview-table small { display: block; margin-top: 4px; color: #a9b8d9; font-size: 10.5px; font-weight: 400; }
+.preview-table .numeric { font-variant-numeric: tabular-nums; color: #b8f0df; }
+.preview-table .null-value { color: #96a3c0; font-family: ui-monospace, monospace; font-size: 10.5px; }
+.status-badge, .match-badge { display: inline-block; padding: 4px 7px; border-radius: 5px; font-size: 10.5px; background: #28324a; color: #bdcae6; }
+.status-active, .match-yes { color: #a4ebd0; background: #163d37; }
+.status-trialing { color: #c3c2ff; background: #322f57; }
+.status-churned { color: #ffb2b8; background: #442c3b; }
+.row-excluded > th, .row-excluded > td { color: #96a3c0; }
+.row-excluded th[scope='row'] > span { color: #b2bdd7; }
+.orders-toggle { border-color: #3d4967; padding: 5px 8px; font-size: 11px; white-space: nowrap; }
+.preview-table .orders-detail > td { padding: 20px; background: #0d1423; white-space: normal; }
+.orders-detail p { max-width: 760px; color: #a9b8d9; font-size: 12px; }
+.orders-detail table { border-collapse: collapse; width: min(100%, 520px); margin-top: 12px; }
+.orders-detail table td, .orders-detail table th { padding: 8px 12px; }
+.preview-table .preview-empty { white-space: normal; text-align: center; padding: 36px; color: #b7c3df; line-height: 1.7; }
+.preview-fields { margin-top: 18px; font-size: 12px; color: #a9b8d9; line-height: 1.7; }
+.preview-fields summary { cursor: pointer; color: #c5d1ee; }
+.preview-fields code { color: #c5d1ee; }
+.visually-hidden { position: absolute; width: 1px; height: 1px; padding: 0; margin: -1px; overflow: hidden; clip-path: inset(50%); white-space: nowrap; border: 0; }
+@media (max-width: 640px) {
+ .data-preview { padding: 24px 16px; }
+ .sample-picker { width: 100%; min-width: 0; }
+ .preview-summary { gap: 10px 20px; }
+ .preview-tabs { width: 100%; }
+ .preview-tabs button { flex: 1; }
+}