Skip to content

Commit f16c0d3

Browse files
committed
Let table panels follow the page's current filters
A panel pinned to a table page can opt in to seeing the page's filters. It then gets datasette.context.filters, datasette.pageRows() for the rows the page shows, and datasette.pageQuery(sql) where {{filtered}} stands for the table with the page's filters applied. The filtered SQL comes from Datasette's own table JSON API, and the app must already have query access to the table's database. Panel templates accept {{filtered}} in CONFIG.sql, fall back to the whole table when filters are not shared, and show a Filtered badge. Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_016BvfqCDRL45ozGqcaFb36Q
1 parent f684bc3 commit f16c0d3

16 files changed

Lines changed: 573 additions & 29 deletions

File tree

‎README.md‎

Lines changed: 25 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -132,6 +132,29 @@ A panel is the same sandboxed iframe as the full app page, with the same CSP and
132132

133133
Inside a pinned app, `datasette.context` describes where it is running - `{target: "table", database: "shop", table: "orders", panel: {width, height}}`, or `{target: "app"}` on the app's own page - and `datasette.resize(height)` asks the host page for a different frame height.
134134

135+
#### Panels that follow the page's filters
136+
137+
A panel pinned to a table page can optionally be told about the filters currently applied to that page, so a chart above the table shows the same rows the table does. This is off by default and is switched on per panel with **Let this app see the page's current filters** when pinning, or later in the panel's settings.
138+
139+
With it on, the app gets:
140+
141+
- `datasette.context.filters` - `{query_string, params, active}`. `query_string` is the page's raw query string, `params` is the list of `[key, value]` pairs that actually filter rows (column filters, `_search`, `_where`, `_through`), and `active` says whether there are any.
142+
- `await datasette.pageQuery(sql, params)` - runs read-only SQL in which `{{filtered}}` stands for the table with the page's filters applied:
143+
144+
```javascript
145+
const result = await datasette.pageQuery(
146+
"select status, count(*) as n from {{filtered}} group by 1"
147+
);
148+
```
149+
150+
- `await datasette.pageRows({size})` - the rows the page is showing, in the page's sort order, as `{columns, rows, count}` (up to 100 rows).
151+
152+
Datasette's table pages reload when a filter changes, so the panel always loads with the current filters. Page size, pagination, sort order and column selection are ignored when working out `{{filtered}}`: it is every row matching the filters.
153+
154+
The filtered query is built by Datasette itself - the server asks the table's own JSON API for the SQL behind the page and substitutes that for `{{filtered}}` - so it matches the page exactly and runs with the viewer's permissions. It grants no new access: the table's database must already be on the app's list of SQL query databases, and the page says which panel is asking, not the app.
155+
156+
Panel templates understand `{{filtered}}` in `CONFIG.sql`. When the panel does not have access to the page's filters, or the app is opened on its own page, `{{filtered}}` falls back to the whole table (`CONFIG.table`). A small "Filtered" badge appears next to the label whenever the numbers reflect a filter. Templates started from a table's **Add app panel** page use `{{filtered}}` and have filter-following ticked by default.
157+
135158
#### Panel templates
136159

137160
The create page offers a gallery of **panel templates**, so that panels made by different people (and by agents) look like one family:
@@ -148,13 +171,13 @@ The create page offers a gallery of **panel templates**, so that panels made by
148171
| `calendar` | A heatmap of activity by day | rows of `day`, `value` |
149172
| `note` | A text callout | no query |
150173

151-
Each template is an ordinary self-contained app. It starts with a `CONFIG` block - label, database, SQL, number format - which is the only part that normally needs editing, followed by a shared "panel kit" of styles and helpers that is identical in every template. Writing `{{table}}` in the SQL means "the table this panel is pinned to", so one app can be pinned to several tables.
174+
Each template is an ordinary self-contained app. It starts with a `CONFIG` block - label, database, SQL, number format - which is the only part that normally needs editing, followed by a shared "panel kit" of styles and helpers that is identical in every template. Writing `{{table}}` in the SQL means "the table this panel is pinned to", so one app can be pinned to several tables, and `{{filtered}}` means that table narrowed to the page's current filters.
152175

153176
Starting a template from a table's **Add app panel** page pre-fills the query from that table's columns (a date-like column to trend over, a low-cardinality text column to group by) and pins the new app back to the table when it is created.
154177

155178
`/-/apps/templates.json` lists the templates and their settings.
156179

157-
If [datasette-agent](https://github.com/datasette/datasette-agent) is installed the agent gets matching tools: `app_panel_templates` lists the templates, `app_create` accepts `template` and `template_config` in place of `html`, and `app_pin_panel` / `app_unpin_panel` place and remove panels. Asking "put a chart of orders per month at the top of the orders table" then costs the agent one SQL query and a few settings rather than a page of HTML.
180+
If [datasette-agent](https://github.com/datasette/datasette-agent) is installed the agent gets matching tools: `app_panel_templates` lists the templates, `app_create` accepts `template` and `template_config` in place of `html`, and `app_pin_panel` / `app_unpin_panel` place and remove panels (`share_filters` makes a table panel follow the page's filters). Asking "put a chart of orders per month at the top of the orders table" then costs the agent one SQL query and a few settings rather than a page of HTML.
158181

159182
To try all of this against sample data:
160183

‎datasette_apps/__init__.py‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,7 @@
1414
from .registry import Registry
1515
from .views import (
1616
app_json,
17+
app_page_data,
1718
app_query,
1819
app_revision,
1920
apps_index,
@@ -52,6 +53,7 @@ def register_routes():
5253
(r"^/-/apps/(?P<id>[^/]+)/unpin$", unpin_app),
5354
(r"^/-/apps/(?P<id>[^/]+)/launch$", launch_app),
5455
(r"^/-/apps/(?P<id>[^/]+)/query$", app_query),
56+
(r"^/-/apps/(?P<id>[^/]+)/page$", app_page_data),
5557
(r"^/-/apps/(?P<id>[^/]+)$", view_app),
5658
]
5759

‎datasette_apps/agent_tools.py‎

Lines changed: 20 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -91,7 +91,15 @@
9191
"four width-3 stat tiles make a row. The panel is only visible to "
9292
"the current user unless shared is true, which needs the "
9393
"apps-share-panels permission. Inside a pinned app, "
94-
"datasette.context gives {target, database, table}."
94+
"datasette.context gives {target, database, table}. For a table "
95+
"target, pass share_filters true to make the panel follow the "
96+
"filters the user applies on the table page: write {{filtered}} in "
97+
"place of the table name in a template's SQL (select count(*) as "
98+
"value from {{filtered}}) and it becomes the table restricted to "
99+
"the page's current filters. Hand-written apps get the same through "
100+
"await datasette.pageQuery(sql, params), plus await "
101+
"datasette.pageRows() for the rows shown and "
102+
"datasette.context.filters for the raw filter arguments."
95103
),
96104
"unpin_panel": (
97105
"Remove a panel from the page it is pinned to, by panel_id. The "
@@ -462,6 +470,7 @@ async def _app_pin_panel(
462470
width=None,
463471
height=None,
464472
shared=False,
473+
share_filters=False,
465474
):
466475
if width is None or height is None:
467476
version = await Registry(datasette).get_current_version(app_id)
@@ -480,6 +489,7 @@ async def _app_pin_panel(
480489
width=width,
481490
height=height,
482491
is_shared=bool(shared),
492+
share_filters=bool(share_filters),
483493
)
484494
except PanelError as e:
485495
return _error(str(e), app_id)
@@ -493,6 +503,7 @@ async def _app_pin_panel(
493503
"width": panel["width"],
494504
"height": panel["height"],
495505
"shared": bool(panel["is_shared"]),
506+
"share_filters": bool(panel["share_filters"]),
496507
"path": target_path(
497508
datasette,
498509
panel["target_type"],
@@ -1056,6 +1067,14 @@ async def app_render(datasette, actor, app_id):
10561067
"type": "integer",
10571068
"description": "Frame height in pixels",
10581069
},
1070+
"share_filters": {
1071+
"type": "boolean",
1072+
"description": (
1073+
"Table targets only: let the app read the page's "
1074+
"current filters and query the filtered rows; "
1075+
"defaults to false"
1076+
),
1077+
},
10591078
"shared": {
10601079
"type": "boolean",
10611080
"description": (

‎datasette_apps/db.py‎

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -118,6 +118,9 @@
118118
width INTEGER NOT NULL DEFAULT 12,
119119
height INTEGER NOT NULL DEFAULT 240,
120120
show_header INTEGER NOT NULL DEFAULT 1,
121+
-- Table panels only: the app may read the page's current filters and
122+
-- query the filtered rows
123+
share_filters INTEGER NOT NULL DEFAULT 0,
121124
sort_order INTEGER NOT NULL DEFAULT 0,
122125
created_at TEXT NOT NULL,
123126
updated_at TEXT NOT NULL,
@@ -398,6 +401,14 @@ def create_schema(conn):
398401
AND app_revisions.version = apps.current_version
399402
)
400403
""")
404+
if "app_panels" in existing_tables:
405+
panel_columns = {
406+
row[1] for row in conn.execute("PRAGMA table_info(app_panels)")
407+
}
408+
if "share_filters" not in panel_columns:
409+
conn.execute(
410+
"ALTER TABLE app_panels ADD COLUMN share_filters INTEGER NOT NULL DEFAULT 0"
411+
)
401412
conn.execute("DROP TABLE IF EXISTS app_versions")
402413
conn.executescript(SCHEMA)
403414

‎datasette_apps/panel_kit.py‎

Lines changed: 24 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -43,6 +43,10 @@
4343
"Database to query. Leave empty to use the database of the page the "
4444
"panel is pinned to."
4545
),
46+
"table": (
47+
"Table that {{table}} and {{filtered}} in the SQL refer to when the "
48+
"panel is not pinned to a table page."
49+
),
4650
"label": "Short sentence-case label shown above the data.",
4751
"prefix": 'Text placed before numbers, for example "$".',
4852
"suffix": 'Text placed after numbers, for example " ms".',
@@ -114,6 +118,7 @@ def _thumb(body):
114118
config={
115119
"label": "Total orders",
116120
"database": "",
121+
"table": "",
117122
"sql": "select 1284 as value, 1140 as previous",
118123
"delta_label": "vs previous period",
119124
"up_is_good": True,
@@ -148,6 +153,7 @@ def _thumb(body):
148153
height=96,
149154
config={
150155
"database": "",
156+
"table": "",
151157
"sql": (
152158
'select 1284 as "Orders", 312 as "Customers", '
153159
'58210 as "Revenue", 4.6 as "Avg rating"'
@@ -183,6 +189,7 @@ def _thumb(body):
183189
config={
184190
"label": "Orders per month",
185191
"database": "",
192+
"table": "",
186193
"sql": (
187194
"select '2026-01' as x, 80 as value union all select '2026-02', 96 "
188195
"union all select '2026-03', 91 union all select '2026-04', 118 "
@@ -224,6 +231,7 @@ def _thumb(body):
224231
config={
225232
"label": "Orders per month",
226233
"database": "",
234+
"table": "",
227235
"sql": (
228236
"select '2026-01' as x, 80 as value union all select '2026-02', 96 "
229237
"union all select '2026-03', 91 union all select '2026-04', 118 "
@@ -259,6 +267,7 @@ def _thumb(body):
259267
config={
260268
"label": "Orders by status",
261269
"database": "",
270+
"table": "",
262271
"sql": (
263272
"select 'Delivered' as label, 840 as value union all "
264273
"select 'Shipped', 260 union all select 'Processing', 120 "
@@ -292,6 +301,7 @@ def _thumb(body):
292301
config={
293302
"label": "Latest orders",
294303
"database": "",
304+
"table": "",
295305
"sql": (
296306
"select 'Order #1284' as title, 'Ada Lovelace' as subtitle, "
297307
"'2026-05-14' as meta union all "
@@ -323,6 +333,7 @@ def _thumb(body):
323333
config={
324334
"label": "Orders this quarter",
325335
"database": "",
336+
"table": "",
326337
"sql": "select 1284 as value",
327338
"goal": 2000,
328339
"caption": "of quarterly goal",
@@ -357,6 +368,7 @@ def _thumb(body):
357368
config={
358369
"label": "Orders per day",
359370
"database": "",
371+
"table": "",
360372
"sql": (
361373
"with recursive days(day, n) as (select date('2026-05-31'), 0 "
362374
"union all select date(day, '-1 day'), n + 1 from days where n < 180) "
@@ -475,7 +487,10 @@ def _config_docs(template):
475487
if template.sql_shape and "sql" in template.config:
476488
lines.append(f"// The query returns: {template.sql_shape}")
477489
lines.append(
478-
"// Write {{table}} in the SQL to mean the table the panel is pinned to."
490+
"// In the SQL, {{table}} means the table the panel is pinned to and"
491+
)
492+
lines.append(
493+
"// {{filtered}} means that table with the page's current filters applied."
479494
)
480495
for key, doc in template.field_docs().items():
481496
if doc:
@@ -591,7 +606,11 @@ async def suggest_panel_config(datasette, template_id, database=None, table=None
591606
info = await describe_table(datasette, database, table)
592607
except Exception:
593608
return config
594-
t = escape_sqlite(table)
609+
# {{filtered}} follows the table page's filters when the panel is allowed
610+
# to see them, and is the whole of CONFIG.table everywhere else
611+
t = "{{filtered}}"
612+
if "table" in template.config:
613+
config["table"] = table
595614
title = table[:1].upper() + table[1:]
596615
date_col = escape_sqlite(info["date_column"]) if info["date_column"] else None
597616
cat_col = (
@@ -643,7 +662,9 @@ async def suggest_panel_config(datasette, template_id, database=None, table=None
643662
config.update(
644663
label=f"Latest {table}",
645664
sql=(
646-
"select " + ", ".join(columns) + f"\nfrom {t}\n"
665+
"select " + ", ".join(columns)
666+
# rowid is not visible through the {{filtered}} subquery
667+
+ f"\nfrom {t if date_col else '{{table}}'}\n"
647668
f"order by {date_col or 'rowid'} desc limit 8"
648669
),
649670
)

‎datasette_apps/panel_templates/_kit.css‎

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -105,3 +105,12 @@ svg.pk-chart { display: block; overflow: visible; }
105105
.pk-chart .pk-area { fill: var(--pk-accent-wash); }
106106
.pk-chart .pk-dot { fill: var(--pk-accent); stroke: #fff; stroke-width: 2; }
107107
.pk-chart .pk-cross { stroke: var(--pk-ink-3); stroke-width: 1; }
108+
.pk-filtered {
109+
background: var(--pk-accent-soft);
110+
border-radius: 3px;
111+
color: #104281;
112+
font-size: 10.5px;
113+
font-weight: 600;
114+
margin-left: 6px;
115+
padding: 1px 5px;
116+
}

‎datasette_apps/panel_templates/_kit.js‎

Lines changed: 28 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -3,16 +3,34 @@ const Panel = (() => {
33
const context = (window.datasette && datasette.context) || {target: "app"};
44
const quoteName = name => '"' + String(name).replace(/"/g, '""') + '"';
55

6-
// {{table}} in CONFIG.sql becomes the table this panel is pinned to, so
7-
// one app can be pinned to several tables.
6+
// The table this panel is about: the page it is pinned to, else CONFIG.table
7+
const tableName = context.table || CONFIG.table;
8+
const FILTERED = /\{\{\s*filtered\s*\}\}/g;
9+
// True when the page's filters are shared with this panel
10+
const followsFilters = !!(context.filters && window.datasette && datasette.pageQuery);
11+
let usedFilters = false;
12+
13+
// {{table}} in CONFIG.sql becomes the table this panel is about, so one
14+
// app can be pinned to several tables.
815
const expandSql = sql => String(sql).replace(/\{\{\s*table\s*\}\}/g, () => {
9-
if (!context.table) {
10-
throw new Error("This panel uses {{table}}: pin it to a table page");
16+
if (!tableName) {
17+
throw new Error("This panel needs a table: pin it to a table page or set CONFIG.table");
1118
}
12-
return quoteName(context.table);
19+
return quoteName(tableName);
1320
});
1421

22+
// {{filtered}} means "the table, with the page's current filters applied".
23+
// That needs the host page's help; without it the whole table is used.
1524
async function query(sql, params) {
25+
sql = String(sql);
26+
if (FILTERED.test(sql)) {
27+
FILTERED.lastIndex = 0;
28+
if (followsFilters) {
29+
usedFilters = true;
30+
return (await datasette.pageQuery(expandSql(sql), params || {})).rows;
31+
}
32+
sql = sql.replace(FILTERED, "{{table}}");
33+
}
1634
const database = CONFIG.database || context.database;
1735
if (!database) {
1836
throw new Error("Set CONFIG.database, or pin this panel to a database or table page");
@@ -227,6 +245,11 @@ const Panel = (() => {
227245
root.textContent = "";
228246
try {
229247
if (template.draw(data, root) === false) state("empty", CONFIG.empty_text || "No data");
248+
// Say so when the numbers reflect the page's filters, not the whole table
249+
const label = root.querySelector(".pk-label");
250+
if (label && usedFilters && context.filters.active) {
251+
label.append(el("span", {class: "pk-filtered", text: "Filtered"}));
252+
}
230253
} catch (error) {
231254
state("error", error.message || String(error));
232255
}

0 commit comments

Comments
 (0)