From 4092c3c45071173592e39985b4d9d28ae160e937 Mon Sep 17 00:00:00 2001 From: Harenome Ranaivoarivony-Razanajato Date: Tue, 17 Nov 2026 16:30:24 +0100 Subject: [PATCH 01/18] refactor(web): build a card toolkit beside the table toolkit The table toolkit's field dicts gain a `card` role naming the slot a field fills (status, tag, meta, check, icon, title, text, badge, note, stat, alert, action), and `table` false for a field on cards only; a page's items are dicts of display values, so the field list only says where each goes. `_cards.html` renders them: an
whose title link is stretched over the card, labels before values in up to three stats, initials beside real icons only, and the slot limits checked. NulliusTable.cards runs the controls row's search and Filter over the cards, sharing them with the tables through `narrow`; a controls row can leave out Sort by, and shows no buttons group when it has none. --- app/static/catalogue/catalogue.css | 15 ++++ app/static/tables.js | 62 +++++++++++---- app/templates/_cards.html | 71 +++++++++++++++++ app/templates/_tables.html | 25 +++--- app/templates/base.html | 1 + app/ui_tests/test_cards.py | 122 +++++++++++++++++++++++++++++ app/ui_tests/test_tables.py | 6 ++ 7 files changed, 276 insertions(+), 26 deletions(-) create mode 100644 app/templates/_cards.html create mode 100644 app/ui_tests/test_cards.py diff --git a/app/static/catalogue/catalogue.css b/app/static/catalogue/catalogue.css index 1fb1e407..44e4233e 100644 --- a/app/static/catalogue/catalogue.css +++ b/app/static/catalogue/catalogue.css @@ -30,6 +30,16 @@ .bench-card { display: flex; flex-direction: column; gap: 14px; padding: 20px; border-radius: 12px; background: var(--surface); border: 1px solid var(--border-soft); color: var(--text); transition: border-color .13s ease; } .bench-card:hover { border-color: var(--accent); text-decoration: none; } .bench-card:focus-visible { outline: none; box-shadow: 0 0 0 3px var(--accent-soft), 0 0 0 1px var(--accent); } +/* a card of the card toolkit (templates/_cards.html): its title's link stretched over it, so the whole card opens it; + a checkbox, a button or a value with a tooltip sits above that link */ +article.bench-card { position: relative; } +.card-link, .card-link:hover { color: inherit; text-decoration: none; } +.card-link::after { content: ""; position: absolute; inset: -1px; border-radius: 12px; } +.card-link:focus-visible { outline: none; } +.card-link:focus-visible::after { box-shadow: 0 0 0 3px var(--accent-soft), 0 0 0 1px var(--accent); } +.bench-card :is(input, button, .btn, [title]) { position: relative; z-index: 1; } +.bench-card-top .bench-harness { margin-left: auto; } +.bench-card-actions { display: flex; flex-wrap: wrap; gap: 8px; } .bench-shelf.st-community .bench-card { background: transparent; border-style: dashed; border-color: var(--border); } .bench-shelf.st-community .bench-card:hover { border-color: var(--accent); } .bench-card-top { display: flex; justify-content: space-between; align-items: center; gap: 8px; } @@ -45,6 +55,11 @@ .bench-stats b { font-size: 18px; font-weight: 500; font-variant-numeric: tabular-nums; } .bench-stats b.word { font-size: 14px; font-weight: 500; line-height: 1.35; padding-top: 3px; } .bench-stats span { font-size: 12px; color: var(--text-faint); } +/* the card toolkit's stats: each its label, then its value */ +.bench-stats:is(dl) { margin: auto 0 0; } +.bench-stats dd { margin: 0; font-size: 18px; font-weight: 500; font-variant-numeric: tabular-nums; } +.bench-stats dd.word { font-size: 14px; line-height: 1.35; padding-top: 3px; } +.bench-stats dt { font-size: 12px; color: var(--text-faint); } .bench-card-blocker { font-size: 13px; line-height: 1.5; color: var(--text-dim); } .bench-none { color: var(--text-dim); font-size: 14px; } diff --git a/app/static/tables.js b/app/static/tables.js index 9e71a5f1..0e06a312 100644 --- a/app/static/tables.js +++ b/app/static/tables.js @@ -1,6 +1,6 @@ /* The table toolkit's script: each function is a feature a table.grid opts into (the macros of templates/_tables.html; their styles in style.css, - "the table toolkit"). */ + "the table toolkit"), and the card toolkit's (templates/_cards.html). */ window.NulliusTable = { /* A header with data-type sorts its column on a click or Enter; num sorts descending first. A cell's data-sort wins over its text. A header that @@ -124,15 +124,13 @@ window.NulliusTable = { btn.addEventListener('focusout', left); }, - /* A table's search box, Filter and Sort by menus (the controls macro), - under `tools`; each optional. Search keeps the rows whose data-search - holds every word of the query, in any order and case; Escape clears it. Filter counts the columns it - narrows; Sort by sets the sort, and follows a header click. `changed` - runs after any of them. Returns {passes, resort}, as filters and sortable - do. */ - toolbar(table, tools, changed) { - const [fbtn, fmenu, sbtn, smenu] = ['filter', 'sort'].flatMap(k => - [tools.querySelector(`[data-tools-btn="${k}"]`), tools.querySelector(`[data-tools="${k}"]`)]); + /* A controls row's search box and Filter menu (the controls macro), under + `tools`; each optional. Search keeps the rows (or cards) whose + data-search holds every word of the query, in any order and case; + Escape clears it. Filter counts the columns it narrows. `changed` runs + after either. Returns passes(row). */ + narrow(tools, changed) { + const [fbtn, fmenu] = [tools.querySelector('[data-tools-btn="filter"]'), tools.querySelector('[data-tools="filter"]')]; const q = tools.querySelector('[data-search]'); if (q) { q.addEventListener('input', changed); @@ -155,6 +153,15 @@ window.NulliusTable = { fmenu.querySelector('[data-clear]').addEventListener('click', () => { f.clear(); narrowed(); }); this.menu(fbtn, fmenu); } + return row => f.passes(row) && found(row); + }, + + /* A table's controls row: narrow's search and Filter, and the Sort by + menu, which sets the sort and follows a header click. Returns + {passes, resort}, as narrow and sortable do. */ + toolbar(table, tools, changed) { + const passes = this.narrow(tools, changed); + const [sbtn, smenu] = [tools.querySelector('[data-tools-btn="sort"]'), tools.querySelector('[data-tools="sort"]')]; const heads = [...table.tHead.rows[0].cells]; const sync = () => { if (!smenu) return; @@ -173,7 +180,7 @@ window.NulliusTable = { sync(); this.menu(sbtn, smenu); } - return {passes: row => f.passes(row) && found(row), resort}; + return {passes, resort}; }, /* A table of the table macro (data-table): its controls row (id @@ -193,6 +200,25 @@ window.NulliusTable = { first = this.pager(table, table.id + '.per', t.passes, ticks); }, + /* A collection of the cards macro (data-cards): its controls row (id + -tools) shows the cards (data-card) that pass, the note when none + does; a data-group holding cards hides when none of them shows, and its + data-group-n counts those that do. */ + cards(root) { + const items = [...root.querySelectorAll('[data-card]')], empty = document.querySelector(`[data-empty="${CSS.escape(root.id)}"]`); + const draw = () => { + items.forEach(c => { c.hidden = !passes(c); }); + root.querySelectorAll('[data-group]').forEach(g => { + const n = [...g.querySelectorAll('[data-card]')].filter(c => !c.hidden).length, count = g.querySelector('[data-group-n]'); + g.hidden = !n; + if (count) count.textContent = n; + }); + empty.hidden = items.some(c => !c.hidden); + }; + const passes = this.narrow(document.getElementById(root.id + '-tools'), draw); + draw(); + }, + /* A checkbox column (a `check` column, check_cell in each row): the header ticks or unticks every visible row, and shows all, none or some of them ticked. Returns sync(), to run when rows show or hide. */ @@ -276,10 +302,14 @@ window.NulliusTable = { }, }; -/* Every table with sticky columns, and every table of the table macro, set up once the page is read. */ -const nulliusTables = () => document.querySelectorAll('table.grid').forEach(t => { - if (t.querySelector('.sticky-col')) NulliusTable.sticky(t); - if (t.hasAttribute('data-table')) NulliusTable.wire(t); -}); +/* Every table with sticky columns, every table of the table macro and every collection of the cards macro, set up + once the page is read. */ +const nulliusTables = () => { + document.querySelectorAll('table.grid').forEach(t => { + if (t.querySelector('.sticky-col')) NulliusTable.sticky(t); + if (t.hasAttribute('data-table')) NulliusTable.wire(t); + }); + document.querySelectorAll('[data-cards]').forEach(c => NulliusTable.cards(c)); +}; if (document.readyState === 'loading') document.addEventListener('DOMContentLoaded', nulliusTables); else nulliusTables(); diff --git a/app/templates/_cards.html b/app/templates/_cards.html new file mode 100644 index 00000000..cdbde74e --- /dev/null +++ b/app/templates/_cards.html @@ -0,0 +1,71 @@ +{#- The card toolkit: items as cards over the same field list as the table toolkit (_tables.html), run by + static/tables.js (NulliusTable.cards) and styled in catalogue/catalogue.css. A field's `card` names the slot it + fills; a field without one is not on the card, and `table` false keeps a card-only field off a table. Slots, in + order: `status`, `tag`*, `meta`, `check` (the top row); `icon`, `title` (exactly one); `text`; `badge`*, `note`*; + `stat` (up to 3, below a line); `alert`; `action`* (* any number, the others at most one). + An item is a dict of display values by field key: a string, a dict {text, class, title, label, href, value} or a + list of them, empty for none; plus `href` (its title's link), `id`, `search` (what the search reads) and `keys`. + A field's `class` goes on each of its values; `card_label` names a stat when its column header does not, and a + value's `label` names it for that item; `style` 'code' sets the text as code; `icon` puts #i- before a + note. `icon` values are image URLs: when one item has one, the others show initials; when none has, no icon. -#} +{% from '_tables.html' import controls, empty_note %} + +{#- Each value of `fields` in `item`, as a dict, to the call block with its field. #} +{% macro each(item, fields) %}{% for f in fields %}{% set v = item.get(f.key) %} +{%- for x in ([v] if v is string or v is mapping or v is number else v or []) if x is not none and x != '' %}{{ caller(f, x if x is mapping else {'text': x}) }}{% endfor %}{% endfor %}{% endmacro %} + +{#- A value as a pill: its field's class and its own, its tooltip. #} +{% macro pill(f, v) %}{% set cls = [f.class, v.class]|select|join(' ') %}{{ v.text }}{% endmacro %} + +{# A collection of cards (NulliusTable.cards): its controls row, its cards, the note when none passes. `id` names it; + `search`, `choices`, `only` as the table's controls. The call block, when given, writes the cards instead (grid + for each group, such as the Benchmarks' shelves); a section in it marked data-group hides when none of its cards + shows, and its data-group-n counts them. #} +{% macro cards(id, cols, items, search='', choices={}, only={}, empty='No items match.') %} +{{ controls(id, cols, search, choices=choices, only=only, sort=false) }} +
{% if caller is defined %}{{ caller() }}{% else %}{{ grid(cols, items, choices=choices) }}{% endif %}
+{{ empty_note(id, empty) }} +{% endmacro %} + +{# The cards of `items`. `every`: the collection the icon rule reads, when `items` is a part of it; `choices`: the + filtered fields, each written on the card for the filter. #} +{% macro grid(cols, items, every=none, choices={}) %} +{%- set fields = cols|selectattr('card')|list %} +{%- set by = {} %}{% for slot in ['status', 'tag', 'meta', 'check', 'icon', 'title', 'text', 'badge', 'note', 'stat', 'alert', 'action'] %}{% set _ = by.update({slot: fields|selectattr('card', 'equalto', slot)|list}) %}{% endfor %} +{#- the limits, each failing the page: one title, at most three stats, at most one of each other single slot #} +{%- if not by.title or by.stat|length > 3 %}{{ cards_take_one_title_and_at_most_three_stats() }}{% endif %} +{%- for slot in ['status', 'meta', 'check', 'icon', 'title', 'text', 'alert'] if by[slot]|length > 1 %}{{ cards_take_one_of_each_single_slot() }}{% endfor %} +{%- set icon = by.icon[0] if by.icon else none %} +{%- set icons = icon and (every or items)|selectattr(icon.key)|list|length > 0 %} +
+{%- for item in items %} +
+ {%- set top %}{% call(f, v) each(item, by.status) %}{{ pill(f, v) }}{% endcall %} + {%- set tags %}{% call(f, v) each(item, by.tag) %}{{ pill(f, v) }}{% endcall %}{% endset %}{% if tags %}{{ tags }}{% endif %} + {%- call(f, v) each(item, by.meta) %}{{ v.text }}{% endcall %} + {%- call(f, v) each(item, by.check) %}{% endcall %}{% endset %} + {%- if top %} +
{{ top }}
{% endif %} + {%- set title = by.title[0] %}{% set name = item.get(title.key) %}{% set name = name.text if name is mapping else name %} +
{% if icons %}{% set src = item.get(icon.key) %} + {%- if not src %} + {%- elif '#' in src %} + {%- else %}{% endif %}{% endif -%} + {{ name }}
+ {%- call(f, v) each(item, by.text) %} +
{% if f.style == 'code' %}{{ v.text }}{% else %}{{ v.text }}{% endif %}
{% endcall %} + {%- set badges %}{% call(f, v) each(item, by.badge) %}{{ pill(f, v) }}{% endcall %}{% endset %}{% if badges %} +
{{ badges }}
{% endif %} + {%- call(f, v) each(item, by.note) %} +
{% if f.icon %}{% endif %}{{ v.text }}
{% endcall %} + {%- set stats %}{% call(f, v) each(item, by.stat) %}
{{ v.label or f.card_label or f.label }}
{{ v.text }}
{% endcall %}{% endset %}{% if stats %} +
{{ stats }}
{% endif %} + {%- call(f, v) each(item, by.alert) %} +
{{ v.text }}
{% endcall %} + {%- set actions %}{% call(f, v) each(item, by.action) %}{% if v.href %}{{ v.text }}{% else %}{% endif %}{% endcall %}{% endset %}{% if actions %} +
{{ actions }}
{% endif %} +
+{%- endfor %} +
+{%- endmacro %} diff --git a/app/templates/_tables.html b/app/templates/_tables.html index a8a68dc9..0a977c1e 100644 --- a/app/templates/_tables.html +++ b/app/templates/_tables.html @@ -8,7 +8,8 @@ `check`: blank, a checkbox that ticks every visible row (check_cell in each row); `sr`: the label for a screen reader only; `title`: its tooltip; `menu` false: not in the Columns menu; `fixed`: in it, always on; `off`: off until the viewer chooses; `width` in a table macro's table: 'fit' (default), as wide as its widest cell on one - line, or 'expand', the rest of the width, wrapping. #} + line, or 'expand', the rest of the width, wrapping; `table` false: on cards only (_cards.html, where `card` names + the slot a field fills), never in a table. #} {#- The class attribute of a column's header or cell: its alignment, whether it is pinned, `edge` whether it is the last pinned; `extra` adds to it. #} @@ -33,6 +34,7 @@ writes that cell with the cell macro. Opt-ins: `search`, `columns`, `choices`, `only`, `views`, `actions` as controls'; `empty` and `noun` as pager's. #} {% macro table(id, cols, rows, tr, class='', search='', columns=false, choices={}, only={}, empty='No rows match.', noun='rows', views=none, actions=none) %} +{%- set cols = cols|rejectattr('table', 'sameas', false)|list %} {{ controls(id, cols, search, columns, choices, only, views, actions) }} {%- for c in cols if c.width == 'expand' %} @@ -62,13 +64,13 @@ {# A table's controls row (static/tables.js `toolbar`) over the columns `cols`; each feature on only when asked. `search`: the search box's name and placeholder, over each row's data-search text; `columns`: the Columns menu; `choices`: column -> its (value, label) pairs, a Filter menu of them; `only`: column -> the one value - ticked at load, the others unticked; then the Sort by menu. `views` and `actions`: macros writing a page's own - buttons, each any number of them, run by the page: views (how the table looks) before Columns, actions (on the - rows or the selection) last. The search goes left, the buttons right. `id`: the table's. #} -{% macro controls(id, cols, search='', columns=false, choices={}, only={}, views=none, actions=none) %} + ticked at load, the others unticked; then the Sort by menu, unless `sort` is false. `views` and `actions`: macros + writing a page's own buttons, each any number of them, run by the page: views (how the table looks) before + Columns, actions (on the rows or the selection) last. The search goes left, the buttons right. `id`: the table's. #} +{% macro controls(id, cols, search='', columns=false, choices={}, only={}, views=none, actions=none, sort=true) %}
{% if search %}{% endif %} -
+ {% if columns or choices or sort or views or actions %}
{{ slot('views', views) }} {% if columns %}{% endif %} {% if choices %}
{% endif %} - {% endif %} {{ slot('actions', actions) }} -
+
{% endif %} {% endmacro %} @@ -128,7 +130,7 @@ and the page before and after; `empty` shows when no row passes. After a change, what is shown is read out once typing pauses, counted in `noun`. #} {% macro pager(table, empty='No rows match.', noun='rows') %} - +{{ empty_note(table, empty) }}
@@ -139,6 +141,9 @@
{% endmacro %} +{#- The note shown when no row of the table (or card of the collection) `id` passes. #} +{% macro empty_note(id, text) %}{% endmacro %} + {#- A button that cannot act here: greyed, still focusable, `why` its description and, after `action` when given, its tooltip; `id` names the description. An icon button by default; `class` and `text` make it another, such as a count. The cell or line that holds it is positioned, so the hidden reason stays in it. #} diff --git a/app/templates/base.html b/app/templates/base.html index 5ec09fc9..5a787e30 100644 --- a/app/templates/base.html +++ b/app/templates/base.html @@ -87,6 +87,7 @@ + diff --git a/app/ui_tests/test_cards.py b/app/ui_tests/test_cards.py new file mode 100644 index 00000000..7561e937 --- /dev/null +++ b/app/ui_tests/test_cards.py @@ -0,0 +1,122 @@ +"""The card toolkit: its macros (templates/_cards.html) as a page renders them, and its script +(NulliusTable.cards in static/tables.js) run under Node on the table toolkit's stand-in DOM.""" +import re +import unittest + +import jinja2 + +from .test_tables import APP, node + +# One field of each slot, given in an order unlike the card's. +COLS = [dict(key='stat1', label='Tasks', card='stat'), dict(key='alert', label='Blocker', card='alert'), + dict(key='title', label='Name', card='title'), dict(key='act', label='Open', card='action'), + dict(key='stat2', label='Scored by', card_label='Scorer', card='stat', **{'class': 'word'}), + dict(key='note', label='Needs', card='note', icon='wrench'), dict(key='badge', label='Runs with', card='badge', **{'class': 'run-tag'}), + dict(key='text', label='About', card='text', style='code'), dict(key='icon', label='Logo', card='icon', **{'class': 'bench-mark'}), + dict(key='check', label='Pick', card='check'), dict(key='meta', label='Version', card='meta'), + dict(key='tag', label='Kind', card='tag', **{'class': 'cat-tag'}), dict(key='status', label='State', card='status'), + dict(key='hidden', label='Only in a table')] +FULL = {'href': '/a', 'id': 'a', 'search': 'Alpha one', 'keys': 'a', 'stat1': {'text': 5, 'label': 'Tasks each'}, 'alert': 'Blocked', + 'title': 'Alpha', 'act': {'text': 'Open', 'href': '/a/open'}, 'stat2': 'tests', 'note': {'text': 'needs docker', 'title': 'Install docker'}, + 'badge': [{'text': 'Nullius', 'class': 'rt-standard'}, 'Harbor'], 'text': 'a.port/v1', 'icon': '/m.svg#bm-a', + 'check': {'text': 'Pick Alpha', 'value': 'a'}, 'meta': 'v1', 'tag': 'coding', 'status': 'ready', 'hidden': 'never on a card'} + + +class Macros(unittest.TestCase): + env = jinja2.Environment(loader=jinja2.FileSystemLoader(APP / "templates"), autoescape=True) + + def render(self, cols, items, **kw): + return re.sub(r">\s+<", "><", self.env.from_string("{% from '_cards.html' import cards %}{{ cards('c', cols, items, **kw) }}") + .render(cols=cols, items=items, kw=kw)) + + def test_slots_come_in_their_order_and_a_field_without_one_stays_off(self): + html = self.render(COLS, [FULL]) + order = ['>ready<', 'class="cat-tag">coding<', 'class="bench-harness">v1<', 'aria-label="Pick Alpha"', 'href="/m.svg#bm-a"', + 'class="card-link" href="/a">Alpha<', 'a.port/v1', 'class="run-tag rt-standard">Nullius<', 'class="run-tag">Harbor<', + 'title="Install docker">needs docker<', + '
Tasks each
5
Scorer
tests
', + 'class="bench-card-blocker">Blocked<', 'Open'] + at = [html.index(part) for part in order] + self.assertEqual(at, sorted(at)) + self.assertNotIn('never on a card', html) + self.assertIn('
', html) + self.assertEqual(html.count('
Tasks
0
', html) # a zero is a value + self.assertNotIn('bench-stats', self.render(COLS[2:3], [{'href': '/b', 'title': 'Beta'}])) + + def test_one_title_at_most_one_text_and_three_stats(self): + title, stat, text = COLS[2], COLS[0], COLS[7] + for cols in ([stat], [title, title], [title, text, text], [title] + [stat] * 4, [title, COLS[8], COLS[8]]): + with self.subTest(cols=[c['card'] for c in cols]), self.assertRaises(jinja2.UndefinedError): + self.render(cols, [FULL]) + self.render([title] + [stat] * 3, [FULL]) + + def test_initials_only_beside_a_real_icon(self): + cols = [COLS[8], COLS[2]] + html = self.render(cols, [{'href': '/a', 'title': 'Alpha', 'icon': '/logo.svg'}, {'href': '/b', 'title': 'beta'}]) + self.assertIn('', html) + self.assertIn('', html) + html = self.render(cols, [{'href': '/a', 'title': 'Alpha'}, {'href': '/b', 'title': 'Beta', 'icon': None}]) + self.assertNotIn('aria-hidden="true"><', html.split('data-cards>')[1]) # no icon slot at all + + def test_values_are_escaped(self): + bad = '"' + html = self.render(COLS, [dict(FULL, title=bad, text=bad, search=bad, tag={'text': bad, 'title': bad}, stat2=bad, href='/"x')], + choices={'tag': [(bad, bad)]}) + self.assertNotIn('{% endif %}{% endblock %} +{% from '_cards.html' import cards %} {% block body %} {% if entry %} {% set d = entry.d %} @@ -35,19 +37,12 @@

Checks

{% else %}
-

Kits

{{ entries|length }} conformance kits

-
- {% for value, label in [('', 'All'), ('agent', 'Agents'), ('capability', 'Capabilities')] %}{% endfor %} -
-
- +

Kits

{{ items|length }} conformance kits

+ {#- A card's fields (web/agents.py `_kit_card`); the filter is the family. #} + {% set cols = [dict(key='family', label='Family', card='tag', class='std-tag'), dict(key='version', label='Version', card='meta'), + dict(key='title', label='Name', card='title'), dict(key='port', label='Port', card='text', style='code'), + dict(key='checks', label='Checks', type='num', card='stat')] %} + {{ cards('kits', cols, items, search='Name, port, check', choices={'family': [('agent', 'Agents'), ('capability', 'Capabilities')]}, empty='No kits match.') }}
{% endif %} {% endblock %} diff --git a/app/templates/agents/standard.html b/app/templates/agents/standard.html index f09b944d..d1f85ea6 100644 --- a/app/templates/agents/standard.html +++ b/app/templates/agents/standard.html @@ -2,14 +2,16 @@ {% set plural = 'Agents' if kind == 'agent' else 'Capabilities' %} {% block title %}{{ plural }} — Nullius{% endblock %} {% block crumb %}/ {{ plural|lower }}{% endblock %} -{% block head %}{% endblock %} +{% block head %} +{% endblock %} +{% from '_cards.html' import cards %} {% block body %} {# The standard's agents (or capabilities) as cards, as the benchmarks are; a card opens its own page. docs/standard.md #}

{{ plural }}

-

{{ entries|length }} {{ plural|lower if entries|length != 1 else kind }} · +

{{ items|length }} {{ plural|lower if items|length != 1 else kind }} · {% if kind == 'agent' %}driven over ACP, the benchmark's tools served over MCP{% else %}driven over JSON lines{% endif %} · every model call through the relay

@@ -37,22 +39,15 @@

{{ plural }}

{% endcall %} {% if problems %}
Not offered: a definition with problems
    {% for p in problems %}
  • {{ p }}
  • {% endfor %}
{% endif %} - {% if not entries %}

No {{ kind }} yet.

{% endif %} + {% if not items %}

No {{ kind }} yet.

{% endif %} - + {#- A card's fields (web/agents.py `_card`). #} + {% set cols = [dict(key='kind', label='Kind', card='tag', class='cat-tag'), dict(key='protocol', label='Protocol', card='tag', class='std-tag'), + dict(key='example', label='Example', card='tag', class='std-tag'), dict(key='version', label='Version', card='meta'), + dict(key='icon', label='Logo', card='icon', table=false, class='std-mark small'), dict(key='title', label='Name', card='title'), + dict(key='summary', label='Summary', card='text', class='std-clamp'), dict(key='ports', label='Ports proven', card='stat'), + dict(key='runs', label='Benchmarks it runs', card='stat'), dict(key='installs', label='Installs', card='stat', class='word')] %} + {% if items %}{{ cards(plural|lower, cols, items, search='Name, protocol, summary', empty='No ' ~ kind ~ ' matches.') }}{% endif %}
{% endblock %} {% block scripts %}{% endblock %} diff --git a/app/templates/catalogue/benchmarks.html b/app/templates/catalogue/benchmarks.html index 2b3c1dd3..70473ec2 100644 --- a/app/templates/catalogue/benchmarks.html +++ b/app/templates/catalogue/benchmarks.html @@ -1,12 +1,11 @@ {% extends "base.html" %} {% block title %}Benchmarks — Nullius{% endblock %} {% block crumb %}/ benchmarks{% endblock %} -{% block head %}{% endblock %} +{% block head %} +{% endblock %} +{% from '_cards.html' import cards, grid %} {% block body %} {% set listed = cat.listed_benchmarks %} -{#- a route's name, the same on the filter chips and on the cards' bubbles #} -{% set run_labels = {'harbor': 'Harbor', 'standard': 'Nullius'} %} -{% set run_names = {'harbor': 'Harbor', 'standard': 'the Nullius standard'} %} {% set count = namespace(datasets=0) %}{% for b in listed %}{% set count.datasets = count.datasets + b.datasets|length %}{% endfor %}
@@ -15,9 +14,6 @@

Benchmarks

{{ listed|length }} benchmarks · {{ count.datasets }} datasets

-
@@ -37,55 +33,25 @@

Benchmarks

{% endcall %} -
-
- - {% for c in cat.categories %} - {% endfor %} -
-
- - {% for r in ['standard', 'harbor'] %} - {% endfor %} -
-
- - {% for o in origins %} - {% endfor %} -
-
- - {# Two shelves: the official benchmarks, then the community benchmarks. A card opens the benchmark's own page. #} + {#- A card's fields (web/catalogue.py `_card`); the filters are the category, what runs it and the origin. #} + {% set cols = [dict(key='category', label='Category', card='tag', class='cat-tag'), dict(key='origin', label='Origin', card='tag', class='origin-tag'), + dict(key='icon', label='Mark', card='icon', table=false, class='bench-mark'), dict(key='title', label='Name', card='title'), + dict(key='domain', label='Domain', card='text'), dict(key='runs', label='Runs with', card='badge', class='run-tag'), + dict(key='needs', label='Needs', card='note', icon='wrench'), dict(key='tasks', label='Tasks', type='num', card='stat'), + dict(key='datasets', label='Datasets', type='num', card='stat'), dict(key='scoring', label='Scored by', card='stat', class='word'), + dict(key='blocker', label='Blocker', card='alert')] %} + {#- Two shelves: the official benchmarks, then the community benchmarks. A card opens the benchmark's own page. #} + {% call cards('benchmarks', cols, items, search='Name, category, dataset', choices=choices, empty='No benchmark matches.') %} {% for state, heading in [('official', 'Official'), ('community', 'Community')] %} - {% set shelf = listed|selectattr('origin', 'equalto', state)|list %} + {% set shelf = items|selectattr('shelf', 'equalto', state)|list %} {% if shelf %} -
-

{{ heading }} {{ shelf|length }}

- +
+

{{ heading }} {{ shelf|length }}

+ {{ grid(cols, shelf, every=items, choices=choices) }}
{% endif %} {% endfor %} - + {% endcall %}
{% endblock %} {% block scripts %}{% endblock %} diff --git a/app/ui_tests/test_agents.py b/app/ui_tests/test_agents.py index 50277f1b..7f0718a0 100644 --- a/app/ui_tests/test_agents.py +++ b/app/ui_tests/test_agents.py @@ -55,7 +55,7 @@ def test_examples_lead_catalogue_and_sidebar(self): with patch.object(definitions, "load", _LOAD): for url in ("/agents", "/capabilities"): html = self.get(url).get_data(as_text=True) - cards = re.findall(r']*class="bench-card[^"]*"[^>]*>(.*?)', html, re.S) + cards = re.findall(r'
]*>(.*?)
', html, re.S) self.assertTrue(cards) self.assertIn("Example", cards[0]) tree = html.split('data-tree="nav-' + ("agent" if url == "/agents" else "capability") + '"', 1)[1] @@ -82,9 +82,16 @@ def test_bundled_agents_use_shared_marks(self): self.assertIn(f'/static/catalogue/agents/{key}.svg', html) self.assertIn('/static/brand/marks.svg#openai', html) self.assertIn('/static/brand/marks.svg#harbor', html) - # Personal entries without a bundled mark remain legible. + # Beside the logos, an agent without one shows its initials; where none has a logo, no card has an icon. + self.assertIn('', html) fixture_html = self.get("/agents").get_data(as_text=True) - self.assertIn('std-mark small', fixture_html) + self.assertIn('', fixture_html) + self.assertNotIn('std-mark', fixture_html) + with patch.object(definitions, "load", _LOAD): + capabilities = self.get("/capabilities").get_data(as_text=True) + self.assertNotIn('std-mark', capabilities) # capabilities have no logos: no letters either + self.assertIn('', page) + self.assertIn('data-keys="agent-task-v1" data-f-family="agent "', page) + self.assertIn('', page) + self.assertIn('
Checks
3
', page) + self.assertNotIn('bench-card-title">Agents", html) card = html[html.index('id="fake"'):] self.assertIn('href="/agents/fake"', card) - self.assertIn("2/7ports proven", card) # task and workspace, of the seven agent ports - self.assertIn("1/1benchmarks it runs", card) - self.assertNotIn("agent.task/v1", card[:card.index("")]) # the detail is on its page + self.assertIn("
Ports proven
2/7
", card) # task and workspace, of the seven agent ports + self.assertIn("
Benchmarks it runs
1/1
", card) + self.assertNotIn("agent.task/v1", card[:card.index("
")]) # the detail is on its page self.assertEqual(self.get("/agents/nope").status_code, 404) def test_the_add_dialog_builds_a_prompt_and_keeps_the_steps_by_hand_for_each_kind(self): diff --git a/app/ui_tests/test_benchmark_new.py b/app/ui_tests/test_benchmark_new.py index 0d0a49cb..7344496a 100644 --- a/app/ui_tests/test_benchmark_new.py +++ b/app/ui_tests/test_benchmark_new.py @@ -262,10 +262,10 @@ def test_a_harbor_route_joins_a_benchmark_the_standard_runs_as_one_card(self): self.assertEqual(Path(self.root, "benchmarks", "longmemeval", name).read_bytes(), content) self.assertFalse(os.path.exists(os.path.join(self.root, "benchmarks", "code-bench"))) # no second entry cards = self.get("/benchmarks").get_data(as_text=True) - self.assertEqual(cards.count('")] + self.assertEqual(cards.count('")] self.assertEqual([x for x in ("rt-harbor", "rt-standard", "rt-runner") if x in card], ["rt-harbor", "rt-standard"]) node = shutil.which("node") if node: # its Harbor dataset opens a Harbor recipe, its own the standard's diff --git a/app/ui_tests/test_catalogue_routes.py b/app/ui_tests/test_catalogue_routes.py index 2d8428ec..6f3845a9 100644 --- a/app/ui_tests/test_catalogue_routes.py +++ b/app/ui_tests/test_catalogue_routes.py @@ -13,8 +13,6 @@ from __future__ import annotations import re -import shutil -import subprocess import unittest from contextlib import ExitStack from html import unescape @@ -50,7 +48,7 @@ def get(self, url, status=200): def card(self, key): """One benchmark's card on the list, as markup.""" - match = re.search(r'\s*(?=\s*)' % re.escape(key), self.html, re.S) + match = re.search(r'
).)*href="/benchmarks/%s".*?
' % re.escape(key), self.html, re.S) self.assertIsNotNone(match, key) return match.group(0) @@ -77,22 +75,29 @@ def test_a_card_and_its_page_carry_the_origin(self): self.assertIn('Official', self.page_html(key)) self.assertIn('Official', self.card("gaia")) self.assertIn('Official', self.page_html("gaia")) - self.assertIn('
', self.card(key)) # beside the category, on the left + self.assertIn('', self.card(key)) # beside the category, on the left def test_the_list_filters_by_what_runs_it(self): html = self.get("/benchmarks") - self.assertIn('data-filter="runs"', html) - self.assertIn('data-runs="standard harbor"', self.card("swe-bench-verified")); self.assertIn('data-runs="standard"', self.card("longmemeval")) + self.assertIn('
', html) + self.assertIn('data-f-runs="Nullius Harbor "', self.card("swe-bench-verified")); self.assertIn('data-f-runs="Nullius "', self.card("longmemeval")) def test_the_list_filters_by_origin(self): html = self.get("/benchmarks") - self.assertIn('data-filter="origin"', html) + self.assertIn('
', html) for o in catalog.ORIGINS: - self.assertIn(f'data-value="{o}"', html) - self.assertIn('data-origin="official"', self.card("terminal-bench")) - self.assertIn('data-origin="official"', self.card("longmemeval")) - self.assertIn('data-origin="official"', self.card("gaia")) - self.assertNotIn('data-value="experiment"', html) + self.assertIn(f'data-value="{o.capitalize()}"', html) + self.assertIn('data-f-origin="Official "', self.card("terminal-bench")) + self.assertIn('data-f-origin="Official "', self.card("longmemeval")) + self.assertIn('data-f-origin="Official "', self.card("gaia")) + self.assertNotIn('data-value="Experiment"', html) + + def test_the_list_searches_by_name_category_and_dataset(self): + self.assertIn('', self.html) + self.assertNotIn('data-tools-btn="sort"', self.html) # cards do not sort + self.assertIn('', self.html) class CitationSeal(PageCase): @@ -118,7 +123,7 @@ def test_overlapping_datasets_use_the_distinct_headline_count(self): cat = catalog.Catalog(benchmarks=[benchmark], datasets=datasets) with patch.object(web.shared, "_catalog_cached", return_value=cat): self.html = self.get("/benchmarks") - self.assertIn("165 tasks", visible(self.card("overlap"))) + self.assertIn("Tasks 165", visible(self.card("overlap"))) page = self.page("overlap") self.assertIn("Tasks 165", page) self.assertNotIn("26–165", page) @@ -127,7 +132,7 @@ def test_overlapping_datasets_use_the_distinct_headline_count(self): def test_every_listed_benchmark_is_a_card_opening_its_page(self): cat = catalog.load() - keys = re.findall(r'Your ', section) -class CategoryFilters(unittest.TestCase): - def test_multiword_categories_and_multiple_runners(self): - node = shutil.which("node") - if not node: - self.skipTest("node is needed to exercise catalogue filters") - script = Path(__file__).resolve().parents[1] / "static/catalogue/catalogue.js" - program = r""" -const assert = require('node:assert/strict'); -const cards = [ - {dataset: {category:'Tool use', runs:'standard harbor', find:'appworld', keys:'appworld'}}, - {dataset: {category:'Customer service', runs:'standard', find:'tau', keys:'tau'}}, - {dataset: {category:'Coding', runs:'harbor', find:'swe', keys:'swe'}} -]; -const chips = [['category','Tool use'], ['category','Customer service'], ['category',''], - ['runs','harbor'], ['runs','standard'], ['runs','']].map(([filter,value])=>({ - dataset:{value}, closest:()=>({dataset:{filter}}), - classList:{toggle(){}}, setAttribute(){}, addEventListener(_,fn){this.click=fn;} -})); -const none={}; -global.location={hash:''}; -global.document={ - querySelectorAll:s=>s==='.bench-card'?cards:s==='[data-filter] .bench-cat'?chips:[], - getElementById:id=>id==='bench-none'?none:null -}; -require(process.argv[1]); -const shown=()=>cards.filter(c=>!c.hidden).map(c=>c.dataset.keys); -chips[0].click(); assert.deepEqual(shown(),['appworld']); -chips[3].click(); assert.deepEqual(shown(),['appworld']); -chips[1].click(); assert.deepEqual(shown(),[]); assert.equal(none.hidden,false); -chips[4].click(); assert.deepEqual(shown(),['tau']); -chips[2].click(); assert.deepEqual(shown(),['appworld','tau']); -chips[5].click(); assert.equal(shown().length,3); -""" - subprocess.run([node, "-e", program, str(script)], check=True, capture_output=True, text=True) - - if __name__ == "__main__": unittest.main() diff --git a/app/ui_tests/test_routes.py b/app/ui_tests/test_routes.py index 4605254c..529eb82d 100644 --- a/app/ui_tests/test_routes.py +++ b/app/ui_tests/test_routes.py @@ -220,7 +220,7 @@ def test_catalogue_routes_keep_native_anchor_targets_and_source_count_meanings(s self.assertIn(key, ids) self.assertIn("Official", html) self.assertEqual('data-shelf="community"' in html, any(b.origin == "community" for b in cat.listed_benchmarks)) # a shelf only when something is on it - self.assertIn("500tasks", html) + self.assertIn("
Tasks
500
", html) # Datasets belong on their benchmark's page. response = self.client.get("/datasets") self.addCleanup(response.close) diff --git a/app/web/agents.py b/app/web/agents.py index b791d254..d6b23297 100644 --- a/app/web/agents.py +++ b/app/web/agents.py @@ -34,6 +34,7 @@ from .core import app from . import shared from . import execute +from .filters import AGENT_MARKS from . import settings as settings_web @@ -87,8 +88,28 @@ def _entries(kind: str, every: bool = False) -> dict: def _page(kind: str): example = os.path.join(definitions.CATALOGUE, "agents", "reference") if kind == "agent" else \ os.path.join(definitions.CATALOGUE, "capabilities", "keyword-memory") + found = _entries(kind) return render_template("agents/standard.html", kind=kind, how=howto.steps(kind), prompts=howto.prompts(), - catalogue_dir=paths.catalogue_dir(), example_dir=example, **_entries(kind)) + catalogue_dir=paths.catalogue_dir(), example_dir=example, problems=found["problems"], + items=[_card(kind, e) for e in found["entries"]]) + + +def _card(kind: str, e: dict) -> dict: + """An agent's or a capability's card on its list (templates/_cards.html).""" + d = e["d"] + version, n = (d.get("upstream") or {}).get("version"), len(d.get("_versions") or ()) + mark = AGENT_MARKS.get(d["key"].split("@")[0]) if kind == "agent" else None + path, _, frag = (mark or "").partition("#") + return {"href": url_for("agent_page" if kind == "agent" else "feature_page", key=d["key"]), "id": d["key"], + "search": " ".join([d["label"], d["key"], d.get("kind", ""), e["protocol"], d.get("summary", "")]), + "kind": d.get("kind") if kind == "capability" else None, "protocol": e["protocol"], + "example": {"text": "example", "title": "Nullius's own, to read or copy - not an agent to compare"} if d.get("example") else None, + "version": ("v" + str(version) if version else "") + (f" · {n} versions" if n > 1 else ""), + "icon": mark and url_for("static", filename=path) + ("#" + frag if frag else ""), "title": d["label"], + "summary": d.get("summary"), + "ports": "{}/{}".format(sum(p["state"] == "proven" for p in e["ports"]), len(e["ports"])), + "runs": "{}/{}".format(sum(not f["why"] for f in e["fits"]), len(e["fits"])), + "installs": "yes" if e["install"] else "no"} def _entry(kind: str, key: str): @@ -184,7 +205,17 @@ def _kit_entries(): @app.route("/kits") def kits_page(): - return render_template("agents/kits.html", entries=_kit_entries(), entry=None) + return render_template("agents/kits.html", items=[_kit_card(e) for e in _kit_entries()], entry=None) + + +def _kit_card(e: dict) -> dict: + """A kit's card on its list (templates/_cards.html).""" + d = e["d"] + checks = d.get("check_details", {}) + return {"href": url_for("kit_page", key=d["key"]), "keys": d["key"], + "search": " ".join([e["label"], e["port"], d["summary"], *checks, *(str(v) for c in checks.values() for v in c.values())]), + "family": d["family"], "version": f"v{e['version']}", "title": e["label"], "port": e["port"], + "checks": sum(x["units"] for x in d["datasets"])} def _python_tokens(code): @@ -227,4 +258,4 @@ def kit_page(key): for source in sorted(folder.glob("*.py"))] for source in entry["sources"]: source["tokens"] = _python_tokens(source["code"]) - return render_template("agents/kits.html", entry=entry, entries=[]) + return render_template("agents/kits.html", entry=entry) diff --git a/app/web/catalogue.py b/app/web/catalogue.py index 4c0fbde6..356e971d 100644 --- a/app/web/catalogue.py +++ b/app/web/catalogue.py @@ -26,8 +26,37 @@ def benchmarks_page(): # the benchmarks of the standard some of whose options need a machine's setup (``host``): a bubble on their card setup = {b["key"]: sorted(b["host"]) for b in standard_definitions.load("benchmark")[0] if b.get("host")} - return render_template("catalogue/benchmarks.html", cat=shared._catalog_cached(), origins=catalog.ORIGINS, - prompts=howto.prompts(), catalogue_dir=paths.catalogue_dir(), setup=setup) + cat = shared._catalog_cached() + with open(MARKS, encoding="utf-8") as fh: + sprite = fh.read() + sheet = url_for("static", filename="catalogue/marks.svg") + items = [_card(cat, b, setup.get(b.key), sheet if f' dict: + """A benchmark's card on the list (templates/_cards.html): ``needs`` what some of its options need installed, + ``sheet`` the sprite holding its own mark, none when it has none.""" + ds = cat.datasets_of(b) + tasks, unit = cat.tasks_of(b) + return {"href": url_for("benchmark_page", key=b.key), "shelf": b.origin, "keys": " ".join([b.key, *b.datasets]), + "search": " ".join([b.title, b.category, b.key, *(d.title for d in ds), *b.datasets]), + "category": b.category, "origin": {"text": b.label, "class": b.origin}, + "icon": sheet and f"{sheet}#bm-{b.key}", "title": b.title, "domain": b.domain, + "runs": [{"text": label, "class": "rt-" + way, "title": "Runs with " + name} + for way, (label, name) in RUNS_WITH.items() if way in b.harness], + "needs": needs and {"text": "needs " + ", ".join(needs), + "title": f"Some of its options need {', '.join(needs)} installed on the machine it runs on: see its page"}, + "tasks": {"text": tasks, "label": unit.capitalize()}, + "datasets": {"text": len(ds), "label": "Datasets" if len(ds) != 1 else "Dataset"}, + "scoring": b.scoring, "blocker": b.blocker[:1].upper() + b.blocker[1:]} @app.route("/benchmarks/") @@ -189,17 +218,7 @@ def benchmark_marks(): text = fh.read() cat = shared._catalog_cached() for b in cat.benchmarks: - symbol = None - try: - with open(os.path.join(cat.entry_dir(b.key), "logo.json"), encoding="utf-8") as fh: - logo = json.load(fh) - if (isinstance(logo, dict) and logo.get("kind") in LOGO_TYPES.values() - and isinstance(logo.get("data"), str) and len(logo["data"]) * 3 // 4 <= LOGO_MAX - and re.fullmatch(r"[A-Za-z0-9+/=]+", logo["data"])): - symbol = (f'' - f'') - except (OSError, ValueError): - pass + symbol = _user_mark(cat, b) have = re.search(rf'', text) if have: if symbol: @@ -210,6 +229,21 @@ def benchmark_marks(): return app.response_class(text, mimetype="image/svg+xml", headers={"Cache-Control": "no-cache"}) +def _user_mark(cat, b): + """The sprite's symbol of the logo kept beside ``b``'s user entry, or None.""" + try: + with open(os.path.join(cat.entry_dir(b.key), "logo.json"), encoding="utf-8") as fh: + logo = json.load(fh) + if (isinstance(logo, dict) and logo.get("kind") in LOGO_TYPES.values() + and isinstance(logo.get("data"), str) and len(logo["data"]) * 3 // 4 <= LOGO_MAX + and re.fullmatch(r"[A-Za-z0-9+/=]+", logo["data"])): + return (f'' + f'') + except (OSError, ValueError): + pass + return None + + def _logo(values: dict): """``({kind, data, name} or None, problem or None)``: the file chosen now, else the one a save that came back kept in the form (``logo_kept``).""" From e225887f56d724894af2a595d71f12e84eb1e291 Mon Sep 17 00:00:00 2001 From: Harenome Ranaivoarivony-Razanajato Date: Tue, 17 Nov 2026 17:03:45 +0100 Subject: [PATCH 03/18] feat(web): announce how many cards show once changes pause A card collection gets the toolkit's one debounced live region, as a table's pager has; both now share NulliusTable.voice. --- app/static/tables.js | 21 ++++++++++++++++----- app/templates/_cards.html | 1 + app/ui_tests/test_cards.py | 21 ++++++++++++++++++++- 3 files changed, 37 insertions(+), 6 deletions(-) diff --git a/app/static/tables.js b/app/static/tables.js index 0e06a312..f6064f1b 100644 --- a/app/static/tables.js +++ b/app/static/tables.js @@ -203,9 +203,11 @@ window.NulliusTable = { /* A collection of the cards macro (data-cards): its controls row (id -tools) shows the cards (data-card) that pass, the note when none does; a data-group holding cards hides when none of them shows, and its - data-group-n counts those that do. */ + data-group-n counts those that do. A screen reader hears how many + show once the changes pause. */ cards(root) { const items = [...root.querySelectorAll('[data-card]')], empty = document.querySelector(`[data-empty="${CSS.escape(root.id)}"]`); + const say = this.voice(document.querySelector(`[data-live="${CSS.escape(root.id)}"]`)); const draw = () => { items.forEach(c => { c.hidden = !passes(c); }); root.querySelectorAll('[data-group]').forEach(g => { @@ -213,7 +215,9 @@ window.NulliusTable = { g.hidden = !n; if (count) count.textContent = n; }); - empty.hidden = items.some(c => !c.hidden); + const n = items.filter(c => !c.hidden).length; + empty.hidden = n > 0; + say(n ? `${n} of ${items.length}` : empty.textContent); }; const passes = this.narrow(document.getElementById(root.id + '-tools'), draw); draw(); @@ -264,6 +268,13 @@ window.NulliusTable = { place(); }, + /* A live region: say(text) reads out the last text once the changes + pause. */ + voice(live) { + let t; + return text => { clearTimeout(t); t = setTimeout(() => { live.textContent = text; }, 300); }; + }, + /* A table's pages (the pager macro named after its id): the rows `passes` lets through, a page of them at a time, the page's size remembered per viewer under `key`; its empty note shows when none passes. After a @@ -274,7 +285,8 @@ window.NulliusTable = { pager(table, key, passes = () => true, drawn = () => {}) { const bar = document.querySelector(`[data-pager="${CSS.escape(table.id)}"]`), empty = document.querySelector(`[data-empty="${CSS.escape(table.id)}"]`); const [per, note, prev, next, live] = ['[data-per]', '[data-note]', '[data-prev]', '[data-next]', '[data-live]'].map(s => bar.querySelector(s)); - let page = 0, said, loaded = false; + let page = 0, loaded = false; + const say = this.voice(live); try { const n = localStorage.getItem(key); if (n !== null && [...per.options].some(o => o.value === n)) per.value = n; } catch {} const draw = () => { const rows = [...table.tBodies[0].rows], hit = rows.filter(passes), n = +per.value || hit.length || 1; @@ -285,8 +297,7 @@ window.NulliusTable = { prev.disabled = page === 0; next.disabled = (page + 1) * n >= hit.length; empty.hidden = hit.length > 0; - clearTimeout(said); - if (loaded) said = setTimeout(() => { live.textContent = hit.length ? `${note.textContent} ${live.dataset.noun}` : empty.textContent; }, 300); + if (loaded) say(hit.length ? `${note.textContent} ${live.dataset.noun}` : empty.textContent); drawn(); }; const first = () => { page = 0; draw(); }; diff --git a/app/templates/_cards.html b/app/templates/_cards.html index cdbde74e..6b1beccb 100644 --- a/app/templates/_cards.html +++ b/app/templates/_cards.html @@ -25,6 +25,7 @@ {{ controls(id, cols, search, choices=choices, only=only, sort=false) }}
{% if caller is defined %}{{ caller() }}{% else %}{{ grid(cols, items, choices=choices) }}{% endif %}
{{ empty_note(id, empty) }} + {% endmacro %} {# The cards of `items`. `every`: the collection the icon rule reads, when `items` is a part of it; `choices`: the diff --git a/app/ui_tests/test_cards.py b/app/ui_tests/test_cards.py index 7561e937..86a8c120 100644 --- a/app/ui_tests/test_cards.py +++ b/app/ui_tests/test_cards.py @@ -96,7 +96,7 @@ def test_search_and_filter_hide_cards_and_their_empty_groups(self): el('div', {'data-tools': 'filter', hidden: true}, el('button', {'data-clear': ''}), el('fieldset', {'data-filter-menu': 'kind'}, ...['coding', 'math'].map(v => el('label', {}, el('input', {type: 'checkbox', 'data-value': v, checked: true})))))); const root = el('div', {id: 'c', 'data-cards': ''}, a, b), empty = el('p', {'data-empty': 'c', hidden: true}, 'No card matches.'); -document.appendChild(el('main', {}, tools, root, empty)); +document.appendChild(el('main', {}, tools, root, empty, el('span', {'data-live': 'c'}))); T.cards(root); const shown = () => root.querySelectorAll('[data-card]').filter(c => !c.hidden).map(c => c.textContent); const state = () => [shown(), [a, b].map(g => [g.hidden, g.querySelector('[data-group-n]').textContent]), empty.hidden]; @@ -117,6 +117,25 @@ def test_search_and_filter_hide_cards_and_their_empty_groups(self): [["B"], [[False, "1"], [True, "0"]], True], [["A", "B", "C"], [[False, "2"], [False, "1"]], True]]) + def test_a_screen_reader_hears_how_many_show_once_changes_pause(self): + got = node(r''' +const card = (name, kind) => el('article', {'data-card': '', 'data-search': name, 'data-f-kind': kind + '\n'}, name); +const tools = el('div', {id: 'c-tools'}, el('label', {}, el('input', {type: 'search', 'data-search': ''})), + el('div', {'data-pills': 'kind'}, el('button', {class: 'filter-pill', 'data-all': 'kind', 'aria-pressed': 'true'}), + ...['x', 'y'].map(v => el('button', {class: 'filter-pill', 'data-value': v, 'aria-pressed': 'false'})))); +const root = el('div', {id: 'c', 'data-cards': ''}, card('A', 'x'), card('B', 'y'), card('C', 'x')), live = el('span', {'data-live': 'c'}); +document.appendChild(el('main', {}, tools, root, el('p', {'data-empty': 'c', hidden: true}, 'No card matches.'), live)); +T.cards(root); +const out = []; +const type = q => { const box = tools.querySelector('[data-search]'); box.value = q; box.dispatch('input'); }; +setTimeout(() => { + out.push(live.textContent); // once read + tools.querySelector('[data-value="x"]').click(); type('a'); out.push(live.textContent); // still changing: nothing new + setTimeout(() => { out.push(live.textContent); type('zzz'); setTimeout(() => { out.push(live.textContent); process.stdout.write(JSON.stringify(out)); }, 350); }, 350); +}, 350); +''') + self.assertEqual(got, ["3 of 3", "3 of 3", "1 of 3", "No card matches."]) + if __name__ == "__main__": unittest.main() From 53be06badac501b705d4dd78b5bc15e93a5eef8f Mon Sep 17 00:00:00 2001 From: Harenome Ranaivoarivony-Razanajato Date: Tue, 17 Nov 2026 17:03:49 +0100 Subject: [PATCH 04/18] fix(catalogue): wrap a long stat label within its column "Benchmarks it runs" ran into the next stat on the Agents cards at 1280 px: a label now breaks, hyphenated where the browser can, rather than overflow. --- app/static/catalogue/catalogue.css | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/app/static/catalogue/catalogue.css b/app/static/catalogue/catalogue.css index 60acb381..b8123d0d 100644 --- a/app/static/catalogue/catalogue.css +++ b/app/static/catalogue/catalogue.css @@ -42,7 +42,7 @@ .bench-stats > div { display: flex; flex-direction: column; gap: 2px; min-width: 0; } .bench-stats dd { margin: 0; font-size: 18px; font-weight: 500; font-variant-numeric: tabular-nums; } .bench-stats dd.word { font-size: 14px; line-height: 1.35; padding-top: 3px; } -.bench-stats dt { font-size: 12px; color: var(--text-faint); } +.bench-stats dt { font-size: 12px; color: var(--text-faint); overflow-wrap: anywhere; hyphens: auto; } /* a long label wraps in its column */ .bench-card-blocker { font-size: 13px; line-height: 1.5; color: var(--text-dim); } .bench-none { color: var(--text-dim); font-size: 14px; } From ded951019dc7ca25e1cabe1186d2f385ac42bce2 Mon Sep 17 00:00:00 2001 From: Harenome Ranaivoarivony-Razanajato Date: Tue, 17 Nov 2026 17:03:55 +0100 Subject: [PATCH 05/18] feat(web): filter a table or cards by pills and dropdowns too A column's `filter` puts its choices in the Filter menu (the default), a dropdown of its own in the controls row, a row of pills under it, or several of these. Every form shows one state per column: a pill toggles its value, All clears the column, Clear filters clears them all, and an `only` preset shows in each. The Filter button counts only its own columns, a dropdown the values chosen. --- app/static/style.css | 6 ++ app/static/tables.js | 96 ++++++++++++++----------- app/templates/_cards.html | 2 +- app/templates/_tables.html | 43 ++++++++---- app/ui_tests/test_cards.py | 11 +++ app/ui_tests/test_tables.py | 135 +++++++++++++++++++++++++++++++++--- 6 files changed, 229 insertions(+), 64 deletions(-) diff --git a/app/static/style.css b/app/static/style.css index 12331dc0..ef52ff6e 100644 --- a/app/static/style.css +++ b/app/static/style.css @@ -458,6 +458,12 @@ button.seg:hover { filter: brightness(1.25); } /* a column's alignment (its `align`), header and cells */ .grid .align-right { text-align: right; } .grid .align-center { text-align: center; } +/* a row of filter pills (the controls macro's `pills`), under the search and the buttons */ +.filter-pills { display: flex; flex-wrap: wrap; flex: 1 0 100%; gap: 8px; } +.filter-pill { font: inherit; font-size: 13px; cursor: pointer; color: var(--text-dim); background: transparent; border: 1px solid var(--border); border-radius: 999px; padding: 8px 16px; min-height: 40px; } +.filter-pill:hover { border-color: var(--accent); color: var(--text); } +.filter-pill[aria-pressed="true"] { background: var(--accent); border-color: var(--accent); color: var(--btn-fg); font-weight: 500; } +.filter-pill:focus-visible { outline: 2px solid var(--accent); outline-offset: 2px; } .tools-count { margin-left: .4rem; padding: 0 .4em; border-radius: 99px; background: var(--accent-soft); color: var(--text); font-size: .72rem; font-variant-numeric: tabular-nums; } .chip.clear { border-style: dashed; } diff --git a/app/static/tables.js b/app/static/tables.js index f6064f1b..92dee2e4 100644 --- a/app/static/tables.js +++ b/app/static/tables.js @@ -50,37 +50,50 @@ window.NulliusTable = { return resort; }, - /* The value lists (data-filter-menu) under `scope`, the controls macro's - Filter menu. `allowed`: column -> the Set of values ticked, or null when - all are. A row passes when, for each column, one of its values - (data-f-, one per line) is ticked; a box unticked at load filters - from the start. `changed` runs after each change, a list's change event - included. */ + /* The filters under `scope`, the controls macro's: value lists + (data-filter-menu) and rows of pills (data-pills). `allowed`: column -> + the Set of values chosen, or null when all are; every list and row of a + column shows that one state. A row passes when, for each column, one of + its values (data-f-, one per line) is chosen; a choice made at load + filters from the start. `changed` runs after each change, a list's + change event included. */ filters(scope, changed) { - const allowed = {}; - scope.querySelectorAll('[data-filter-menu]').forEach(menu => { - const col = menu.dataset.filterMenu; - const boxes = () => [...menu.querySelectorAll('input[data-value]')]; - const read = () => { - const on = boxes().filter(b => b.checked).map(b => b.dataset.value); - allowed[col] = on.length === boxes().length ? null : new Set(on); // all ticked: no filter - }; - const sync = () => { read(); changed(); }; - read(); - menu.addEventListener('change', sync); - menu.addEventListener('click', e => { - if (e.target.closest('[data-all]')) { boxes().forEach(b => b.checked = true); sync(); } - if (e.target.closest('[data-none]')) { boxes().forEach(b => b.checked = false); sync(); } + const allowed = {}, views = [...scope.querySelectorAll('[data-filter-menu], [data-pills]')]; + const col = v => v.dataset.filterMenu ?? v.dataset.pills; + const values = v => [...v.querySelectorAll('[data-value]')]; + const draw = () => views.forEach(v => { + const set = allowed[col(v)]; + values(v).forEach(b => { if (b.matches('input')) b.checked = !set || set.has(b.dataset.value); else b.setAttribute('aria-pressed', String(Boolean(set?.has(b.dataset.value)))); }); + v.querySelector('.filter-pill[data-all]')?.setAttribute('aria-pressed', String(!set)); + }); + // All chosen means "no filter": keeps the active markers honest. + const choose = (v, on) => { allowed[col(v)] = on && on.size < values(v).length ? on : null; }; + const set = (v, on) => { choose(v, on); draw(); changed(); }; + const chosen = v => new Set(values(v).filter(b => b.checked || b.getAttribute('aria-pressed') === 'true').map(b => b.dataset.value)); + views.forEach(v => { + if (!(col(v) in allowed)) { const on = chosen(v); choose(v, v.dataset.pills !== undefined && !on.size ? null : on); } + if (v.dataset.pills !== undefined) { + // a pill toggles its value; none left is All + v.addEventListener('click', e => { + const b = e.target.closest('[data-value]'), now = allowed[col(v)]; + if (e.target.closest('[data-all]')) return set(v, null); + if (!b) return; + const on = new Set(now || []); + on.has(b.dataset.value) ? on.delete(b.dataset.value) : on.add(b.dataset.value); + set(v, on.size ? on : null); + }); + return; + } + v.addEventListener('change', () => set(v, chosen(v))); + v.addEventListener('click', e => { + if (e.target.closest('[data-all]')) set(v, null); + if (e.target.closest('[data-none]')) set(v, new Set()); }); }); + draw(); const passes = row => Object.entries(allowed).every(([col, set]) => !set || (row.getAttribute('data-f-' + col) ?? '').split('\n').some(v => set.has(v))); - const clear = () => { - scope.querySelectorAll('[data-filter-menu]').forEach(menu => { - menu.querySelectorAll('input[data-value]').forEach(b => b.checked = true); - allowed[menu.dataset.filterMenu] = null; - }); - }; + const clear = () => { Object.keys(allowed).forEach(c => { allowed[c] = null; }); draw(); }; return {allowed, passes, clear}; }, @@ -124,11 +137,12 @@ window.NulliusTable = { btn.addEventListener('focusout', left); }, - /* A controls row's search box and Filter menu (the controls macro), under + /* A controls row's search box and filters (the controls macro), under `tools`; each optional. Search keeps the rows (or cards) whose data-search holds every word of the query, in any order and case; - Escape clears it. Filter counts the columns it narrows. `changed` runs - after either. Returns passes(row). */ + Escape clears it. The Filter button counts the columns it narrows, a + dropdown the values chosen; Clear filters clears every column. `changed` + runs after any of them. Returns passes(row). */ narrow(tools, changed) { const [fbtn, fmenu] = [tools.querySelector('[data-tools-btn="filter"]'), tools.querySelector('[data-tools="filter"]')]; const q = tools.querySelector('[data-search]'); @@ -140,19 +154,19 @@ window.NulliusTable = { const text = (row.dataset.search ?? '').toLowerCase(); return !q || q.value.toLowerCase().split(/\s+/).every(w => text.includes(w)); }; - const count = fbtn?.querySelector('.tools-count'); - const mark = () => { - const n = Object.values(f.allowed).filter(Boolean).length; - count.textContent = n || ''; - count.hidden = !n; - }; + const menus = [...(fmenu ? [[fbtn, fmenu, () => 1]] : []), + ...[...tools.querySelectorAll('[data-dropdown]')].map(b => [b, b.parentNode.querySelector('.menu'), set => set.size])]; + const mark = () => menus.forEach(([btn, menu, n]) => { + const sets = [...menu.querySelectorAll('[data-filter-menu]')].map(v => f.allowed[v.dataset.filterMenu]).filter(Boolean); + const count = btn.querySelector('.tools-count'); + count.textContent = sets.length ? sets.reduce((sum, set) => sum + n(set), 0) : ''; + count.hidden = !sets.length; + }); const narrowed = () => { mark(); changed(); }; - const f = fmenu ? this.filters(fmenu, narrowed) : {allowed: {}, passes: () => true}; - if (fmenu) { - mark(); - fmenu.querySelector('[data-clear]').addEventListener('click', () => { f.clear(); narrowed(); }); - this.menu(fbtn, fmenu); - } + const f = this.filters(tools, narrowed); + mark(); + menus.forEach(([btn, menu]) => this.menu(btn, menu)); + fmenu?.querySelector('[data-clear]').addEventListener('click', () => { f.clear(); narrowed(); }); return row => f.passes(row) && found(row); }, diff --git a/app/templates/_cards.html b/app/templates/_cards.html index 6b1beccb..68216f64 100644 --- a/app/templates/_cards.html +++ b/app/templates/_cards.html @@ -18,7 +18,7 @@ {% macro pill(f, v) %}{% set cls = [f.class, v.class]|select|join(' ') %}{{ v.text }}{% endmacro %} {# A collection of cards (NulliusTable.cards): its controls row, its cards, the note when none passes. `id` names it; - `search`, `choices`, `only` as the table's controls. The call block, when given, writes the cards instead (grid + `search`, `choices`, `only` and each field's `filter` as the table's controls. The call block, when given, writes the cards instead (grid for each group, such as the Benchmarks' shelves); a section in it marked data-group hides when none of its cards shows, and its data-group-n counts them. #} {% macro cards(id, cols, items, search='', choices={}, only={}, empty='No items match.') %} diff --git a/app/templates/_tables.html b/app/templates/_tables.html index 0a977c1e..8d7d6f7d 100644 --- a/app/templates/_tables.html +++ b/app/templates/_tables.html @@ -63,27 +63,29 @@ {# A table's controls row (static/tables.js `toolbar`) over the columns `cols`; each feature on only when asked. `search`: the search box's name and placeholder, over each row's data-search text; `columns`: the - Columns menu; `choices`: column -> its (value, label) pairs, a Filter menu of them; `only`: column -> the one value - ticked at load, the others unticked; then the Sort by menu, unless `sort` is false. `views` and `actions`: macros - writing a page's own buttons, each any number of them, run by the page: views (how the table looks) before - Columns, actions (on the rows or the selection) last. The search goes left, the buttons right. `id`: the table's. #} + Columns menu; `choices`: column -> its (value, label) pairs to filter by; `only`: column -> the one value chosen + at load; then the Sort by menu, unless `sort` is false. `views` and `actions`: macros writing a page's own + buttons, each any number of them, run by the page: views (how the table looks) before Columns, actions (on the + rows or the selection) last. The search goes left, the buttons right. A column's + `filter` says where its choices go, one form or a list of them: 'button' (the default), in the Filter menu; + 'dropdown', a menu of its own; 'pills', a row of toggles under the controls. `id`: the table's. #} {% macro controls(id, cols, search='', columns=false, choices={}, only={}, views=none, actions=none, sort=true) %} +{%- set by = {'button': [], 'dropdown': [], 'pills': []} %}{% for c in cols if c.key in choices %}{% for f in ([c.filter] if c.filter is string else c.filter or ['button']) %}{% set _ = by[f].append(c) %}{% endfor %}{% endfor %}
{% if search %}{% endif %} - {% if columns or choices or sort or views or actions %}
+ {% if columns or by.dropdown or by.button or sort or views or actions %}
{{ slot('views', views) }} {% if columns %}{% endif %} - {% if choices %}{% endif %} {{ slot('actions', actions) }}
{% endif %} + {% for c in by.pills %} +
+ + {%- for value, text in choices[c.key] %}{% endfor %} +
+ {% endfor %}
{% endmacro %} @@ -111,6 +119,15 @@ writes nothing. #} {% macro slot(name, fill) %}{% set html = fill() if fill else '' %}{% if html|trim %}
{{ html }}
{% endif %}{% endmacro %} +{#- A column's choices as checkboxes, in the Filter menu or a dropdown: all ticked, or only its `only` value. #} +{% macro values(c, choices, only) %} +
+ {{ c.label }} + + {% for value, text in choices %}{% endfor %} +
+{% endmacro %} + {# A Columns menu (static/tables.js `columns`): its button, and the menu of `cols`' definitions, each a checkbox that shows or hides the cells of that data-col. The menu opens under the .menu-wrap that holds it. #} {% macro columns_button() %}{% endmacro %} diff --git a/app/ui_tests/test_cards.py b/app/ui_tests/test_cards.py index 86a8c120..d84bcdf7 100644 --- a/app/ui_tests/test_cards.py +++ b/app/ui_tests/test_cards.py @@ -83,6 +83,17 @@ def test_controls_search_and_filter_without_sort(self): self.assertNotIn('data-tools-btn="sort"', html) self.assertIn('', html) + def test_two_collections_with_every_form_keep_their_ids_apart(self): + cols = [dict(COLS[2]), dict(COLS[11], filter='pills'), dict(COLS[10], filter=['dropdown', 'button'])] + page = self.env.from_string("{% from '_cards.html' import cards %}{% for id in ['p', 'q'] %}{{ cards(id, cols, items, search='Find', choices=choices) }}{% endfor %}") + html = page.render(cols=cols, items=[{'href': '/x', 'title': 'X', 'tag': 'coding', 'meta': 'v1'}], + choices={'tag': [('coding', 'Coding')], 'meta': [('v1', 'v1')]}) + self.assertEqual(re.findall(r' id="([^"]+)"', html), ['p-tools', 'p', 'q-tools', 'q']) + self.assertEqual(html.count('aria-live="polite"'), 2) # one live region a collection + self.assertIn('', html) + self.assertEqual(html.count('data-pills="tag"'), 2) + self.assertEqual(html.count('data-dropdown'), 2) + class Script(unittest.TestCase): def test_search_and_filter_hide_cards_and_their_empty_groups(self): diff --git a/app/ui_tests/test_tables.py b/app/ui_tests/test_tables.py index 1617e15f..c4cf5924 100644 --- a/app/ui_tests/test_tables.py +++ b/app/ui_tests/test_tables.py @@ -95,18 +95,28 @@ class El { require(process.argv[1]); const T = window.NulliusTable; +// A column's choices as the controls macro writes them: `only` the value chosen at load, if any. +const fieldOf = ([col, values], only = {}) => el('fieldset', {'data-filter-menu': col}, el('span', {}, el('button', {'data-all': col}), el('button', {'data-none': col})), + ...values.map(v => el('label', {}, el('input', {type: 'checkbox', 'data-value': v, ...(col in only && only[col] !== v ? {} : {checked: true})}), ' ' + v))); +const pillsOf = ([col, values], only = {}) => el('div', {'data-pills': col}, el('button', {class: 'filter-pill', 'data-all': col, 'aria-pressed': String(!(col in only))}), + ...values.map(v => el('button', {class: 'filter-pill', 'data-value': v, 'aria-pressed': String(only[col] === v)}, v))); +const dropdownOf = (c, only) => el('div', {}, el('button', {'data-dropdown': ''}, c[0], el('span', {class: 'tools-count', hidden: true})), el('div', {class: 'menu', hidden: true}, fieldOf(c, only))); + // A table as the table macro writes it: `id`; columns [key, type]; rows, each {search, f-, cells}; `filter`: a -// column and its values; `search`; `sort`; `noun`, what the live region counts. -global.build = ({id, cols, rows, filter, search = true, sort = true, check = false, noun = 'rows'}) => { +// column and its values, or a list of them, in the Filter menu; `dropdowns` and `pills`: lists of them, in those forms; +// `only`: column -> its value chosen at load; `search`; `sort`; `noun`, what the live region counts. +global.build = ({id, cols, rows, filter, dropdowns = [], pills = [], only = {}, search = true, sort = true, check = false, noun = 'rows'}) => { const radio = (k, v) => el('label', {}, el('input', {type: 'radio', name: `${id}-sort-${k}`, [`data-sort-${k}`]: '', value: v}), ' ' + v); + const button = !filter ? [] : typeof filter[0] === 'string' ? [filter] : filter; const tools = el('div', {id: id + '-tools'}, ...(search ? [el('label', {}, el('input', {type: 'search', 'data-search': ''}))] : []), - ...(filter ? [el('button', {'data-tools-btn': 'filter'}, 'Filter', el('span', {class: 'tools-count', hidden: true})), - el('div', {'data-tools': 'filter', hidden: true}, el('button', {'data-clear': ''}), - el('fieldset', {'data-filter-menu': filter[0]}, ...filter[1].map(v => el('label', {}, el('input', {type: 'checkbox', 'data-value': v, checked: true}), ' ' + v))))] : []), + ...dropdowns.map(c => dropdownOf(c, only)), + ...(button.length ? [el('button', {'data-tools-btn': 'filter'}, 'Filter', el('span', {class: 'tools-count', hidden: true})), + el('div', {'data-tools': 'filter', hidden: true}, el('button', {'data-clear': ''}), ...button.map(c => fieldOf(c, only)))] : []), ...(sort ? [el('button', {'data-tools-btn': 'sort'}), el('div', {'data-tools': 'sort', hidden: true}, el('fieldset', {}, radio('col', ''), ...cols.map(([k]) => radio('col', k))), - el('fieldset', {}, radio('dir', 'asc'), radio('dir', 'desc')))] : [])); + el('fieldset', {}, radio('dir', 'asc'), radio('dir', 'desc')))] : []), + ...pills.map(c => pillsOf(c, only))); const head = el('tr', {}, ...(check ? [el('th', {}, el('input', {type: 'checkbox', 'data-check-all': ''}))] : []), ...cols.map(([k, type]) => el('th', {'data-col': k, 'data-type': type}, k))); const body = el('tbody', {}, ...rows.map(r => el('tr', Object.fromEntries(Object.entries(r).filter(([k]) => k !== 'cells').map(([k, v]) => [k === 'search' ? 'data-search' : 'data-' + k, v])), @@ -186,6 +196,72 @@ def test_a_screen_reader_hears_a_change_once_typing_pauses(self): self.assertNotIn('role="status"', html) +# Thirty rows of a state and a kind; the kind in pills, a dropdown and the Filter menu, the state in the Filter menu. +FORMS = r''' +const kinds = ['a', 'b', 'c']; +const rows = Array.from({length: 30}, (_, i) => ({search: `L${i}`, 'f-state': i % 2 ? 'finished' : 'failed', 'f-kind': kinds[i % 3], cells: [`L${i}`]})); +const make = (only = {}) => build({id: 't', cols: [['launch', 'text']], rows, only, + filter: [['state', ['failed', 'finished']], ['kind', kinds]], dropdowns: [['kind', kinds]], pills: [['kind', kinds]]}); +// each form's view of the kind: the pills pressed, the dropdown's and the Filter menu's boxes ticked; the dropdown's +// count, the Filter's; the pager's note +const look = t => { + const row = t.tools.querySelector('[data-pills]'), [drop, menu] = t.tools.querySelectorAll('[data-filter-menu="kind"]'); + const ticked = v => v.querySelectorAll('input').filter(b => b.checked).map(b => b.dataset.value).join(''); + const count = b => b.querySelector('.tools-count').hidden ? '' : b.querySelector('.tools-count').textContent; + return [row.querySelectorAll('button').filter(b => b.getAttribute('aria-pressed') === 'true').map(b => b.dataset.value ?? 'All').join(''), + ticked(drop), ticked(menu), count(t.tools.querySelector('[data-dropdown]')), count(t.tools.querySelector('[data-tools-btn="filter"]')), t.note()]; +}; +const pill = (t, v) => t.tools.querySelector('[data-pills]').querySelector(v ? `[data-value="${v}"]` : '[data-all]').click(); +const drop = t => t.tools.querySelector('[data-dropdown]').parentNode.querySelector('.menu'); +''' + + +class FilterForms(unittest.TestCase): + """Pills, a dropdown and the Filter menu: three views of one choice per column.""" + + def test_the_forms_stay_in_step(self): + got = node(FORMS + r''' +const t = make(), out = {start: look(t)}; +t.per.value = '10'; t.per.dispatch('change'); t.pager.querySelector('[data-next]').click(); out.page2 = t.note(); +pill(t, 'a'); out.a = [look(t), t.shown()[0]]; // back to the first page +pill(t, 'b'); out.ab = look(t); // pills add up +drop(t).querySelector('[data-value="a"]').click(); out.dropped = look(t); +pill(t, 'b'); out.none = look(t); // the last one off: All +pill(t, 'a'); pill(t, 'b'); pill(t, 'c'); out.every = look(t); // every one on: All +pill(t, 'c'); t.tools.querySelector('[data-tools="filter"]').querySelector('[data-value="finished"]').click(); out.two = look(t); +drop(t).querySelector('[data-all]').click(); out.all = look(t); +t.tools.querySelector('[data-tools="filter"]').querySelector('[data-none="kind"]').click(); out.nothing = [look(t), t.empty()]; +pill(t, 'c'); t.tools.querySelector('[data-clear]').click(); out.clear = look(t); // every column +pill(t, 'b'); pill(t, null); out.pillAll = look(t); +const dd = t.tools.querySelector('[data-dropdown]'); +dd.click(); out.open = [drop(t).hidden, dd.getAttribute('aria-expanded'), document.activeElement === drop(t).querySelector('button')]; +document.dispatch('keydown', {key: 'Escape'}); out.closed = [drop(t).hidden, document.activeElement === dd]; +process.stdout.write(JSON.stringify(out)); +''') + self.assertEqual(got["start"], ["All", "abc", "abc", "", "", "1–25 of 30"]) + self.assertEqual(got["page2"], "11–20 of 30") + self.assertEqual(got["a"], [["a", "a", "a", "1", "1", "1–10 of 10"], "L0"]) + self.assertEqual(got["ab"], ["ab", "ab", "ab", "2", "1", "1–10 of 20"]) + self.assertEqual(got["dropped"], ["b", "b", "b", "1", "1", "1–10 of 10"]) + self.assertEqual(got["none"], ["All", "abc", "abc", "", "", "1–10 of 30"]) + self.assertEqual(got["every"], got["none"]) + self.assertEqual(got["two"], ["c", "c", "c", "1", "2", "1–5 of 5"]) # the Filter counts its columns + self.assertEqual(got["all"], ["All", "abc", "abc", "", "1", "1–10 of 15"]) + self.assertEqual(got["nothing"], [["", "", "", "0", "2", ""], True]) # None: no pill pressed, nothing shows + self.assertEqual(got["clear"], ["All", "abc", "abc", "", "", "1–10 of 30"]) + self.assertEqual(got["pillAll"], got["clear"]) + self.assertEqual(got["open"], [False, "true", True]) + self.assertEqual(got["closed"], [True, True]) + + def test_a_preset_shows_in_every_form(self): + got = node(FORMS + r''' +const t = make({kind: 'b'}), out = [look(t)]; +pill(t, null); out.push(look(t)); +process.stdout.write(JSON.stringify(out)); +''') + self.assertEqual(got, [["b", "b", "b", "1", "1", "1–10 of 10"], ["All", "abc", "abc", "", "", "1–25 of 30"]]) + + class Checks(unittest.TestCase): def test_the_header_follows_the_visible_rows(self): got = node(r''' @@ -315,7 +391,7 @@ def test_the_cells_follow_the_columns(self): "{% macro views() %}{{ two('v1', 'v2') }}{% endmacro %}{% macro actions() %}{{ two('a1', 'a2') }}{% endmacro %}" "{% macro nothing() %} {% endmacro %}") - def controls(self, call): + def slotted(self, call): return re.sub(r">\s+<", "><", self.render("{% from '_tables.html' import controls %}" + self.SLOTS + call)) def test_a_controls_row_places_its_slots_around_the_buttons(self): @@ -323,17 +399,58 @@ def test_a_controls_row_places_its_slots_around_the_buttons(self): for call in (f"{{{{ controls('t', {cols}, search='Find', columns=true, choices={{'x': [('a', 'A')]}}, views=views, actions=actions) }}}}", f"{{% call(r, c) table('t', {cols}, [], none, search='Find', columns=true, choices={{'x': [('a', 'A')]}}, views=views, actions=actions) %}}{{% endcall %}}"): with self.subTest(call=call[:12]): - html = self.controls(call) + html = self.slotted(call) self.assertEqual(re.findall(r'data-search|data-slot="(\w+)"|data-tools-btn="(\w+)"|', html), [("", "", ""), ("views", "", ""), ("", "", "v1"), ("", "", "v2"), ("", "columns", ""), ("", "filter", ""), ("", "sort", ""), ("actions", "", ""), ("", "", "a1"), ("", "", "a2")]) self.assertEqual(html.count('class="table-slot"'), 2) # each slot one group, spaced as the buttons self.assertIn('
', html) for call in ("{{ controls('t', [dict(key='x', label='X')]) }}", "{{ controls('t', [dict(key='x', label='X')], views=nothing, actions=nothing) }}"): - self.assertNotIn("data-slot", self.controls(call)) # none asked, or one writing nothing: no group + self.assertNotIn("data-slot", self.slotted(call)) # none asked, or one writing nothing: no group css = (APP / "static" / "style.css").read_text() self.assertIn(".table-buttons, .table-slot { display: flex; flex-wrap: wrap; justify-content: flex-end; align-items: center; gap: .75rem; }", css) + def controls(self, cols, **kw): + return re.sub(r">\s+<", "><", self.env.from_string("{% from '_tables.html' import controls %}{{ controls('t', cols, sort=false, **kw) }}") + .render(cols=cols, kw=kw)) + + def test_each_column_in_the_forms_it_names(self): + cols = [dict(key="a", label="A"), dict(key="b", label="B", filter="dropdown"), dict(key="c", label="C", filter="pills"), + dict(key="d", label="D", filter=["pills", "button"])] + choices = {k: [("x", "X"), ("y", "Y")] for k in "abcd"} + html = self.controls(cols, choices=choices) + menu = html.split('data-tools="filter"')[1].split("
")[0] + self.assertEqual(re.findall(r'data-filter-menu="(\w)"', menu), ["a", "d"]) # the Filter menu: a, by default, and d + self.assertIn('