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

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions .github/workflows/playground-ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
19 changes: 19 additions & 0 deletions playground/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 |
Expand Down
9 changes: 5 additions & 4 deletions playground/index.html
Original file line number Diff line number Diff line change
Expand Up @@ -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; }
Expand All @@ -49,15 +49,16 @@ <h1>figo — Go dynamic query builder and filter DSL</h1>
<nav aria-label="Project resources">
<a href="https://github.com/bi0dread/figo">Source code on GitHub</a>
<a href="https://github.com/bi0dread/figo#quick-start">Go quick start</a>
<a href="#live-data">Try live data filtering</a>
<a href="#about-figo">Examples and documentation</a>
</nav>
</header>
<div id="root" role="region" aria-label="Visual filter DSL playground"></div>
<div id="root" role="region" aria-label="Visual filter DSL playground and sample data"></div>
<main id="about-figo" class="project-guide">
<section aria-labelledby="how-to-use">
<h2 id="how-to-use">Try the visual filter builder</h2>
<p>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.</p>
<p>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.</p>
<p>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.</p>
</section>
<section aria-labelledby="api-filters">
<h2 id="api-filters">Build database queries from API filters in Go</h2>
Expand Down
3 changes: 2 additions & 1 deletion playground/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -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",
Expand Down
28 changes: 22 additions & 6 deletions playground/src/App.tsx
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { useCallback, useMemo, useRef } from 'react'
import { useCallback, useEffect, useMemo, useRef, useState } from 'react'
import {
Background,
BackgroundVariant,
Expand All @@ -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'

Expand Down Expand Up @@ -235,7 +237,9 @@ function defaultData(item: PaletteItem): Record<string, any> {
function Flow() {
const [nodes, setNodes, onNodesChange] = useNodesState<AppNode>(presetNodes())
const [edges, setEdges, onEdgesChange] = useEdgesState<Edge>(presetEdges())
const { screenToFlowPosition, getNode } = useReactFlow()
const { screenToFlowPosition, getNode, fitView } = useReactFlow()
const [sampleId, setSampleId] = useState('complex')
const [sampleRevision, setSampleRevision] = useState(0)
const wrapRef = useRef<HTMLDivElement>(null)
const nodeSeq = useRef(0)

Expand Down Expand Up @@ -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 (
<>
<div className="app">
<header className="topbar">
<span className="brand">🧩 figo playground</span>
<span className="tagline">drag figo operations, wire them up, read the DSL</span>
<span className="spacer" />
<button onClick={loadExample}>Example</button>
<a href="#live-data">Live data ↓</a>
<button onClick={() => loadSample('complex')}>Example</button>
<button onClick={clearAll}>Clear</button>
<a href="https://github.com/bi0dread/figo" target="_blank" rel="noreferrer">
GitHub ↗
Expand Down Expand Up @@ -396,6 +410,8 @@ function Flow() {
</div>
<DslPanel result={result} />
</div>
<DataPreview dsl={result.dsl} sampleId={sampleId} revision={sampleRevision} onSample={loadSample} />
</>
)
}

Expand Down
114 changes: 114 additions & 0 deletions playground/src/DataPreview.tsx
Original file line number Diff line number Diff line change
@@ -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<string | null>(null)
const [showAll, setShowAll] = useState(false)
const [expanded, setExpanded] = useState<Set<number>>(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 (
<section id="live-data" className="data-preview" aria-labelledby="data-preview-title">
<div className="preview-heading">
<div>
<p className="preview-eyebrow">DSL → sample data</p>
<h2 id="data-preview-title">See your filter in action</h2>
<p>Change the blocks above or edit the DSL below. The table updates immediately.</p>
</div>
<label className="sample-picker">
Load an example
<select value={sampleId} onChange={(event) => {
setEditedDsl(null); setShowAll(false); onSample(event.target.value)
}}>
{SAMPLES.map((item) => <option key={item.id} value={item.id}>{item.name}</option>)}
</select>
</label>
</div>
<p className="sample-description">{sample.description}</p>
<div className="preview-editor-heading">
<label htmlFor="preview-dsl">DSL applied to the table</label>
<label className="follow-builder">
<input type="checkbox" checked={editedDsl === null} onChange={(event) => setEditedDsl(event.target.checked ? null : dsl)} />
Follow visual builder
</label>
</div>
<textarea id="preview-dsl" value={activeDsl} maxLength={12000} rows={3} spellCheck={false}
placeholder='status="active" sort=mrr:desc page=skip:0,take:5'
onChange={(event) => setEditedDsl(event.target.value)} />
<div className="preview-summary" aria-live="polite" aria-atomic="true">
{error ? <p className="preview-error" role="alert">{error}</p> : preview && <>
<span><strong>{preview.matched}</strong> of {CUSTOMERS.length} accounts match</span>
<span><strong>{preview.rows.length}</strong> returned after pagination</span>
<span>skip: {preview.skip} · take: {preview.take || 'all'}</span>
</>}
</div>
<div className="preview-toolbar">
<div className="preview-tabs" role="group" aria-label="Table view">
<button aria-pressed={!showAll} onClick={() => setShowAll(false)}>Query results</button>
<button aria-pressed={showAll} onClick={() => setShowAll(true)}>All source rows</button>
</div>
<span>{showAll ? 'Original data; badges show which rows the query returns.' : preview?.loadsOrders ? 'Expand Orders to see the filtered relation.' : 'Expand Orders to inspect related data.'}</span>
</div>
<div className="preview-table-scroll" tabIndex={0} role="region" aria-label="Customer sample table">
<table className="preview-table">
<caption className="visually-hidden">{showAll ? 'Unfiltered source accounts with query membership' : 'Accounts returned by the current DSL'}</caption>
<thead><tr>
<th scope="col">Account</th><th scope="col">Status</th><th scope="col">Plan / seats</th>
<th scope="col">MRR</th><th scope="col">Signup date</th><th scope="col">Last login</th>
<th scope="col">Deleted at</th><th scope="col">Orders</th>{showAll && <th scope="col">Query result</th>}
</tr></thead>
<tbody>
{rows.map((row) => <Fragment key={row.id}>
<tr className={showAll && !preview?.visibleIds.has(row.id) ? 'row-excluded' : undefined}>
<th scope="row"><span>{row.name}</span><small>#{row.id} · {row.email}</small></th>
<td><span className={`status-badge status-${row.status}`}>{row.status}</span></td>
<td>{row.plan}<small>{row.seats} seats</small></td>
<td className="numeric">{dollars.format(row.mrr)}</td>
<td>{row.signup_date}</td><td className={row.last_login === null ? 'null-value' : undefined}>{nullable(row.last_login)}</td>
<td className={row.deleted_at === null ? 'null-value' : undefined}>{nullable(row.deleted_at)}</td>
<td><button className="orders-toggle" aria-expanded={expanded.has(row.id)} aria-controls={`orders-${row.id}`} onClick={() => toggle(row.id)}>
{row.Orders.length} {preview?.loadsOrders && !showAll ? 'loaded' : 'orders'} {expanded.has(row.id) ? '−' : '+'}
</button></td>
{showAll && <td><span className={`match-badge ${preview?.visibleIds.has(row.id) ? 'match-yes' : ''}`}>{matchLabel(row)}</span></td>}
</tr>
{expanded.has(row.id) && <tr id={`orders-${row.id}`} className="orders-detail"><td colSpan={showAll ? 9 : 8}>
<strong>{row.name} · Orders</strong>
{!showAll && preview?.loadsOrders && <p>Only related orders matching the load filter are shown. The customer stays in the result even if no orders match.</p>}
{row.Orders.length ? <table aria-label={`Orders for ${row.name}`}>
<thead><tr><th scope="col">Order</th><th scope="col">Total</th><th scope="col">Status</th></tr></thead>
<tbody>{row.Orders.map((order) => <tr key={order.id}><td>#{order.id}</td><td>{dollars.format(order.total)}</td><td>{order.status}</td></tr>)}</tbody>
</table> : <p>No orders to display.</p>}
</td></tr>}
</Fragment>)}
{rows.length === 0 && <tr><td colSpan={showAll ? 9 : 8} className="preview-empty">
{error ? 'Fix the DSL above to see results.' : preview?.matched ? 'No rows on this page. Reduce skip or change take.' : 'No accounts match. Try a different condition or clear the DSL to show all accounts.'}
</td></tr>}
</tbody>
</table>
</div>
<details className="preview-fields"><summary>Available fields and demo behavior</summary>
<p>Accounts: <code>{CUSTOMER_FIELDS.join(', ')}</code>. Orders: <code>id, total, status</code>.</p>
<p>This browser demo parses the DSL and uses typed comparisons, SQL-style NULL rules, and NULLs-last sorting. It supports comparisons, IN / NOT IN, BETWEEN, LIKE, AND / OR / NOT, sorting, pagination, and one Orders preload. Regex operators are not evaluated. Your database adapter can have different collation, date, or NULL ordering behavior.</p>
</details>
</section>
)
}
62 changes: 62 additions & 0 deletions playground/src/preview.test.ts
Original file line number Diff line number Diff line change
@@ -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<in>["active","trialing"] or (plan="enterprise" and seats>=50)) and not (email=^"%@test.local" or name=^"QA %") and signup_date<bet>(2024-01-01..2024-12-31) and deleted_at<null> and last_login<notnull> 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<in>[]'), [], 'Empty IN matches nothing, including NULL rows')
equal(ids('last_login<nin>[]').length, 18, 'Empty NOT IN matches everything')
equal(ids('last_login<notnull> last_login<nin>["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<bet>(2024-01-01..2024-01-01)'), [16], 'BETWEEN bounds are inclusive')
equal(ids('mrr<bet>(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<in>[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<bet>(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`)
Loading
Loading