Skip to content
81 changes: 81 additions & 0 deletions docs/syntax/tables.md
Original file line number Diff line number Diff line change
Expand Up @@ -191,6 +191,87 @@ The table is rendered server-side and stays fully usable without JavaScript, bec

:::::

### Choose which columns get dropdown filters

The automatic choice offers a dropdown for any column with 2 to 12 distinct values. That suits type and status columns, but it also catches columns of scores or counts, where a dropdown can only match one exact number. Two options let you choose instead:

- `:filterable: search` adds the search box and count, with no dropdown filters.
- `:filter-columns:` lists the columns that get a dropdown filter, by header text and separated by commas. Every other column gets none. Names match the header text readers see. Matching ignores case, extra spaces, inline formatting such as bold, and footnote markers, and it uses a substitution's value instead of its name. For example, `support status` matches a `**Support** status` header. A listed column gets a dropdown however many distinct values it has, as long as it has at least two. A name that matches no header is a build error.

#### Search only

:::::{tab-set}

::::{tab-item} Output
:::{table}
:filterable: search

| Provider | Model | Alert analysis | Threat hunting |
|----------|-------|----------------|----------------|
| Vendor A | Model 1 | 9 | 9 |
| Vendor B | Model 2 | 8 | 9 |
| Vendor A | Model 3 | 7 | 8 |
| Vendor C | Model 4 | 9 | 7 |
| Vendor B | Model 5 | 6 | 9 |
:::
::::

::::{tab-item} Markdown
```markdown
:::{table}
:filterable: search

| Provider | Model | Alert analysis | Threat hunting |
|----------|-------|----------------|----------------|
| Vendor A | Model 1 | 9 | 9 |
| Vendor B | Model 2 | 8 | 9 |
| Vendor A | Model 3 | 7 | 8 |
| Vendor C | Model 4 | 9 | 7 |
| Vendor B | Model 5 | 6 | 9 |
:::
```
::::

:::::

#### Chosen columns

:::::{tab-set}

::::{tab-item} Output
:::{table}
:filterable:
:filter-columns: Provider

| Provider | Model | Alert analysis | Threat hunting |
|----------|-------|----------------|----------------|
| Vendor A | Model 1 | 9 | 9 |
| Vendor B | Model 2 | 8 | 9 |
| Vendor A | Model 3 | 7 | 8 |
| Vendor C | Model 4 | 9 | 7 |
| Vendor B | Model 5 | 6 | 9 |
:::
::::

::::{tab-item} Markdown
```markdown
:::{table}
:filterable:
:filter-columns: Provider

| Provider | Model | Alert analysis | Threat hunting |
|----------|-------|----------------|----------------|
| Vendor A | Model 1 | 9 | 9 |
| Vendor B | Model 2 | 8 | 9 |
| Vendor A | Model 3 | 7 | 8 |
| Vendor C | Model 4 | 9 | 7 |
| Vendor B | Model 5 | 6 | 9 |
:::
```
::::

:::::

## Table directive with column widths

The `{table}` directive wraps a pipe table and lets you control column widths using a 12-unit grid system (similar to Bootstrap). Use the `:widths:` option to specify how space is distributed across columns.
Expand Down
33 changes: 32 additions & 1 deletion src/Elastic.Documentation.Site/Assets/markdown/table.css
Original file line number Diff line number Diff line change
Expand Up @@ -298,13 +298,44 @@
font-size: 0.875rem;
}

/* The browser's own arrow sits against the right border. Draw one inset
from the edge instead, in the text color, and leave room for it. */
.filterable-table-facet select {
padding: 0.25rem 0.5rem;
appearance: none;
padding: 0.25rem 2rem 0.25rem 0.5rem;
border: 1px solid var(--color-grey-30);
border-radius: 6px;
background-color: var(--color-white);
background-image:
linear-gradient(
45deg,
transparent calc(50% - 0.75px),
currentColor calc(50% - 0.75px) calc(50% + 0.75px),
transparent calc(50% + 0.75px)
),
linear-gradient(
135deg,
transparent calc(50% - 0.75px),
currentColor calc(50% - 0.75px) calc(50% + 0.75px),
transparent calc(50% + 0.75px)
);
background-position:
calc(100% - 1rem) 50%,
calc(100% - 0.625rem) 50%;
background-size: 0.375rem 0.375rem;
background-repeat: no-repeat;
font-size: 0.875rem;
}

/* Forced-colors mode (Windows High Contrast) drops gradient backgrounds,
so the drawn arrow would vanish. Bring back the browser's own. */
@media (forced-colors: active) {
.filterable-table-facet select {
appearance: auto;
padding-right: 0.5rem;
}
}

.filterable-table-status {
margin-inline-start: auto;
font-size: 0.8125rem;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -516,3 +516,123 @@ describe('filterable-table', () => {
expect(visibleRows()).toHaveLength(2)
})
})

describe('filterable-table author-chosen dropdowns', () => {
// Scores have few distinct values, so the heuristic would offer a dropdown
// for each score column. Provider is the column a reader wants to filter.
const SCORES_HTML = (attributes: string) => `
<filterable-table ${attributes}>
<table>
<thead><tr><th>Provider</th><th>Model</th><th>Score A</th><th>Score B</th></tr></thead>
<tbody>
<tr><td>Anthropic</td><td>m1</td><td>9.00</td><td>7.00</td></tr>
<tr><td>Google</td><td>m2</td><td>9.00</td><td>8.00</td></tr>
<tr><td>OpenAI</td><td>m3</td><td>4.00</td><td>7.00</td></tr>
<tr><td>Anthropic</td><td>m4</td><td>7.00</td><td>8.00</td></tr>
</tbody>
</table>
</filterable-table>`

const facetLabels = () =>
Array.from(document.querySelectorAll('.filterable-table-facet')).map(
(f) => f.textContent?.split(':')[0]
)

it('offers a dropdown for every qualifying column by default', () => {
document.body.innerHTML = SCORES_HTML('')
customElements.upgrade(document.body)
expect(facetLabels()).toEqual(['Provider', 'Score A', 'Score B'])
})

it('shows the search box but no dropdowns for data-facets="none"', () => {
document.body.innerHTML = SCORES_HTML('data-facets="none"')
customElements.upgrade(document.body)
expect(
document.querySelector('.filterable-table-search')
).not.toBeNull()
expect(facetLabels()).toEqual([])
expect(
document.querySelector('.filterable-table-status')?.textContent
).toBe('Showing 4 of 4')
})

it('offers dropdowns only for the listed columns', () => {
document.body.innerHTML = SCORES_HTML('data-facet-columns="0"')
customElements.upgrade(document.body)
expect(facetLabels()).toEqual(['Provider'])

const select = document.querySelector<HTMLSelectElement>(
'.filterable-table-facet select'
)!
select.value = 'Anthropic'
select.dispatchEvent(new Event('change'))
expect(visibleRows().map((r) => r.cells[1].textContent)).toEqual([
'm1',
'm4',
])
})

it('builds the listed columns in table order', () => {
document.body.innerHTML = SCORES_HTML('data-facet-columns="3,0"')
customElements.upgrade(document.body)
expect(facetLabels()).toEqual(['Provider', 'Score B'])
})

it('honors a listed column the heuristic would skip', () => {
// Model holds one value per row, so the heuristic treats it as a key
// column. Listing it is the author's call, so it gets a dropdown.
document.body.innerHTML = SCORES_HTML('data-facet-columns="1"')
customElements.upgrade(document.body)
expect(facetLabels()).toEqual(['Model'])
})

it('lifts the distinct-value cap for a listed column', () => {
const rows = Array.from(
{ length: 14 },
(_, i) => `<tr><td>row ${i}</td><td>Provider ${i % 13}</td></tr>`
).join('')
const table = (attributes: string) => `
<filterable-table ${attributes}>
<table>
<thead><tr><th>Name</th><th>Provider</th></tr></thead>
<tbody>${rows}</tbody>
</table>
</filterable-table>`

// Thirteen providers is over the cap, so the heuristic skips it.
document.body.innerHTML = table('')
customElements.upgrade(document.body)
expect(facetLabels()).toEqual([])

document.body.innerHTML = table('data-facet-columns="1"')
customElements.upgrade(document.body)
expect(facetLabels()).toEqual(['Provider'])
})

it('finds a chosen column whose header has extra text', () => {
// The build matched `:filter-columns: Status` to this header, whose
// footnote marker and extra spaces make its text "Status 1" here.
// Matching by position means that text never has to agree.
document.body.innerHTML = `
<filterable-table data-facet-columns="1">
<table>
<thead><tr><th>Name</th><th>Status <a class="footnote-ref" href="#fn:1"><sup>1</sup></a></th></tr></thead>
<tbody>
<tr><td>a</td><td>Core</td></tr>
<tr><td>b</td><td>Extended</td></tr>
<tr><td>c</td><td>Core</td></tr>
</tbody>
</table>
</filterable-table>`
customElements.upgrade(document.body)
expect(
document.querySelectorAll('.filterable-table-facet')
).toHaveLength(1)
})

it('ignores a position that is not a number', () => {
document.body.innerHTML = SCORES_HTML('data-facet-columns="0,x"')
customElements.upgrade(document.body)
expect(facetLabels()).toEqual(['Provider'])
})
})
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,9 @@
// Progressive-enhancement custom element for the `{table}` directive's
// `:filterable:` option. The server renders a normal, fully-usable table; when
// this module loads, it wraps that table with a search box and per-column
// dropdown filters (auto-generated for low-cardinality columns) and shows/hides
// rows client-side. No framework is required, so there is no hydration cost and
// dropdown filters and shows/hides rows client-side. The dropdowns are
// auto-generated for low-cardinality columns unless the author chose them:
// `:filterable: search` turns them off and `:filter-columns:` names them. No framework is required, so there is no hydration cost and
// the table degrades gracefully when JavaScript is unavailable.

// Columns with at most this many distinct values become dropdown filters.
Expand Down Expand Up @@ -149,14 +150,37 @@ class FilterableTableElement extends HTMLElement {
return this.rows.map((row) => this.cellValues(row.cells[colIndex]))
}

/**
* The zero-based positions of the columns the author chose for dropdowns,
* or null when the choice is automatic. `:filterable: search` renders
* `data-facets="none"` (an empty choice). `:filter-columns:` names columns
* by header text, and the build matches those names and renders the
* positions in `data-facet-columns`, so header text is never compared here.
*/
private chosenColumns(): Set<number> | null {
if (this.dataset.facets === 'none') return new Set()
const listed = this.dataset.facetColumns
if (listed === undefined) return null
return new Set(
listed
.split(',')
.map((position) => Number.parseInt(position.trim(), 10))
.filter((position) => Number.isInteger(position))
)
}

/** The dropdowns the current table content warrants, in column order. */
private facetSpecs(): FacetSpec[] {
const specs: FacetSpec[] = []
const chosen = this.chosenColumns()
this.headerLabels().forEach((label, colIndex) => {
// A blank header leaves the dropdown with no label and no
// accessible name, so skip the column: a nameless filter is worse
// than none.
if (!label) return
// The author's choice replaces the heuristic below, so a column of
// scores never gets a dropdown just because it has few values.
if (chosen && !chosen.has(colIndex)) return
const perRow = this.columnValues(colIndex)
const values = Array.from(new Set(perRow.flat())).sort((a, b) =>
a.localeCompare(b)
Expand All @@ -168,14 +192,12 @@ class FilterableTableElement extends HTMLElement {
const isKeyColumn =
perRow.every((v) => v.length === 1) &&
values.length === this.rows.length
// Only offer a dropdown for columns that partition the data
// meaningfully: at least two values, few enough to scan, and not a
// key column.
if (
values.length < 2 ||
values.length > FACET_MAX_DISTINCT ||
isKeyColumn
)
// A column with one value can't narrow anything, chosen or not.
if (values.length < 2) return
// Left to the heuristic, only offer a dropdown for columns that
// partition the data meaningfully: few enough values to scan, and
// not a key column. A column the author chose skips both checks.
if (!chosen && (values.length > FACET_MAX_DISTINCT || isKeyColumn))
return
specs.push({ colIndex, label, values })
})
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -256,6 +256,38 @@ filterable-table {
min-width: 16rem;
}

/* The browser's own arrow sits against the right border. Draw one inset from the edge instead, in the text colour, and leave room for it. */
.filterable-table-facet select {
appearance: none;
padding-inline-end: calc(var(--space-2) + 1.25rem);
background-image:
linear-gradient(
45deg,
transparent calc(50% - 0.75px),
currentColor calc(50% - 0.75px) calc(50% + 0.75px),
transparent calc(50% + 0.75px)
),
linear-gradient(
135deg,
transparent calc(50% - 0.75px),
currentColor calc(50% - 0.75px) calc(50% + 0.75px),
transparent calc(50% + 0.75px)
);
background-position:
calc(100% - 1rem) 50%,
calc(100% - 0.625rem) 50%;
background-size: 0.375rem 0.375rem;
background-repeat: no-repeat;
}
Comment thread
infra-vault-gh-plugin-prod[bot] marked this conversation as resolved.
Resolved

/* Forced-colors mode (Windows High Contrast) drops gradient backgrounds, so the drawn arrow would vanish. Bring back the browser's own. */
@media (forced-colors: active) {
.filterable-table-facet select {
appearance: auto;
padding-inline-end: var(--space-2);
}
}

.filterable-table-facet {
display: inline-flex;
align-items: center;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -451,7 +451,9 @@ private static void WriteTableDirective(HtmlRenderer renderer, TableDirectiveBlo
DirectiveBlock = block,
ColumnWidths = block.ColumnWidths,
Matrix = block.Matrix,
Filterable = block.Filterable
Filterable = block.Filterable,
FilterSearchOnly = block.FilterSearchOnly,
FilterColumnIndexes = block.FilterColumnIndexes
});
RenderRazorSlice(slice, renderer);
}
Expand Down
Loading
Loading