筛选栏按条件筛选列表。每个条件由字段、比较方式和值组成,例如“状态为 Ready”或“耗时小于 60 秒”。条件在弹出层中编辑,一并应用后,以胶囊标签显示在筛选栏上,每个标签都可以单独移除。筛选栏适用于任何列表:这里用它筛选部署列表,在表格视图中,同一个筛选栏用来筛选表格。
筛选栏
<section class="sheet container-inline flex flex-col overflow-hidden" data-example="filter-bar" aria-labelledby="fb-title"> <header class="flex flex-wrap items-center justify-between gap-sm p-md"> <div class="flex flex-col gap-3xs"> <h2 class="heading heading-sm" id="fb-title">Deployments</h2> <p class="m(0) fg-text-muted" id="fb-summary" aria-live="polite">30 deployments in the last two weeks</p> </div> </header> <div class="flex flex-wrap items-center gap-xs px-md pb-md"> <button type="button" class="btn btn-sm" popovertarget="fb-panel" data-filter="open"> <svg class="icon" viewBox="0 0 16 16" fill="none" stroke="currentColor" stroke-width="1" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"> <path d="M4.5365 3L11.4635 3A1 1 0 0 1 12.2548 4.6114L9.4587 8.2299A1 1 0 0 0 9.25 8.8413L9.25 11.323A1 1 0 0 1 8.6214 12.2514L7.875 12.55A0.8203 0.8203 0 0 1 6.75 11.7883L6.75 8.8413A1 1 0 0 0 6.5413 8.2299L3.7452 4.6114A1 1 0 0 1 4.5365 3Z" /> </svg>Filters <span data-filter="count" aria-hidden="true" hidden> <span class="badge badge-sm badge-ink badge-pill">0</span> </span> </button> <div data-filter="applied" hidden> <div class="flex flex-wrap items-center gap-xs"> <ul class="flex flex-wrap gap-xs m(0) p(0)" aria-label="Applied filters" data-filter="chips"></ul> <button type="button" class="btn btn-quiet btn-sm" data-filter="clear-all">Clear all</button> </div> </div> </div> <div class="popover p(0) w(560)" id="fb-panel" popover role="dialog" aria-labelledby="fb-panel-title" style="--popover-max-width: min(36rem, calc(100vw - 2rem))" data-filter="panel"> <form class="flex flex-col" data-filter="form" novalidate> <header class="flex flex-col gap-3xs px-md pt-md pb-sm"> <h3 class="heading heading-xs" id="fb-panel-title">Filter deployments</h3> <p class="m(0) fg-text-muted">A deployment shows when it meets every condition.</p> </header> <ul class="flex flex-col gap-xs m(0) px-md py-xs" data-filter="conditions"></ul> <p class="m(0) px-md py-xs fg-text-muted" data-filter="empty">No conditions yet: every deployment shows.</p> <p class="m(0) px-md py-xs fg-danger" id="fb-error" role="alert" data-filter="error" hidden></p> <div class="px-md pb-md"> <button type="button" class="btn btn-quiet btn-sm" data-filter="add"> <svg class="icon" viewBox="0 0 16 16" fill="none" stroke="currentColor" stroke-width="1" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"> <path d="M3 8L13 8" /> <path d="M8 3L8 13" /> </svg>Add condition</button> </div> <footer class="flex flex-wrap items-center justify-between gap-xs p-md bt(1) bt-solid b-line-hair"> <button type="button" class="btn btn-quiet btn-sm" data-filter="clear">Clear</button> <div class="flex gap-xs"> <button type="button" class="btn btn-sm" data-filter="cancel">Cancel</button> <button type="submit" class="btn btn-primary btn-sm">Apply</button> </div> </footer> </form> </div> <ul class="list px-md bt(1) bt-solid b-line-hair" id="fb-results" aria-label="Matching deployments"></ul> <p class="m(0) px-md pb-md pt-xs fg-text-muted" id="fb-more" hidden></p> <template data-filter="row"> <li class="flex flex-wrap items-center gap-xs"> <span class="w(44) shrink(0) fg-text-muted text-end" data-part="joiner">Where</span> <select class="select select-sm" aria-label="Field" data-part="field"></select> <select class="select select-sm" aria-label="Comparison" data-part="operator"></select> <input class="input input-sm grow(1) basis(128) min-w(0)" aria-label="Value" data-part="value" required> <button type="button" class="btn btn-quiet btn-square btn-sm" aria-label="Remove condition" data-part="remove"> <svg class="icon" viewBox="0 0 16 16" fill="none" stroke="currentColor" stroke-width="1" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"> <path d="M4 4L12 12" /> <path d="M4 12L12 4" /> </svg> </button> </li> </template> <template data-filter="choice"> <select class="select select-sm grow(1) basis(128)" aria-label="Value" data-part="value"></select> </template> <template data-filter="chip"> <li> <span class="chip"> <span class="chip-label"></span> <button type="button" class="chip-remove" aria-label="Remove the filter"> <svg class="icon" viewBox="0 0 16 16" fill="none" stroke="currentColor" stroke-width="1" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"> <path d="M4 4L12 12" /> <path d="M4 12L12 4" /> </svg> </button> </span> </li> </template> <template id="fb-row"> <ul class="list"> <li class="list-row"> <div class="list-body"> <p class="list-title"></p> <p class="list-description"></p> </div> <span class="list-end flex items-center gap-sm"> <span class="fg-text-muted"></span> <span class="badge badge-dot"></span> </span> </li> </ul> </template> <template id="fb-none"> <ul class="list"> <li class="list-row"> <div class="list-body"> <p class="list-title">No deployments match</p> <p class="list-description">Remove a filter, or clear them all to see every deployment.</p> </div> </li> </ul> </template></section>import { filters } from './filters.js'import { filter, formatDate, sort } from './query.js'import { deployments, fields } from './deployments.js'const tones = { ready: ['badge-success', 'Ready'], building: ['badge-info', 'Building'], queued: ['badge-warning', 'Queued'], failed: ['badge-danger', 'Failed'] }const shown = 6/** * The filter bar on a list of deployments: two conditions applied to start with, the newest matches listed, and * a summary that says how many match. Returns the function that stops it. */export function mount(root) { const results = root.querySelector('#fb-results') const summary = root.querySelector('#fb-summary') const more = root.querySelector('#fb-more') const row = (id) => root.querySelector(id).content.querySelector('.list-row').cloneNode(true) function draw(applied) { const found = sort(filter(deployments, applied, fields), 'date', 'descending') summary.textContent = applied.length ? `${found.length} of ${deployments.length} deployments match ${applied.length === 1 ? 'the filter' : `all ${applied.length} filters`}` : `${deployments.length} deployments in the last two weeks` results.replaceChildren(...(found.length ? found.slice(0, shown).map((deployment) => { const item = row('#fb-row') item.querySelector('.list-title').textContent = deployment.project item.querySelector('.list-description').textContent = `${deployment.branch} · ${formatDate(deployment.date)}` item.querySelector('.list-end > span').textContent = deployment.duration ? `${deployment.duration}s` : '—' const [tone, words] = tones[deployment.status] const badge = item.querySelector('.badge') badge.classList.add(tone) badge.textContent = words return item }) : [row('#fb-none')])) more.hidden = found.length <= shown more.textContent = `and ${found.length - shown} older ${found.length - shown === 1 ? 'deployment' : 'deployments'}` } const bar = filters(root, { fields, applied: [ { field: 'status', operator: 'is', value: 'ready' }, { field: 'date', operator: 'after', value: '2026-11-05' }, ], onChange: draw, }) draw(bar.applied) return () => bar.destroy()}import { condition, describe, operatorsOf, problem } from './query.js'/** * A filter bar: conditions staged in a popover and applied together, then shown as chips that each remove one. * The page writes the bar's elements and marks them with `data-filter`, with a `<template>` for a condition's row, * a value to choose and an applied chip; this copies the templates, fills them in and says the applied conditions * to `onChange`. * * - The popover holds a draft. Opening it copies what is applied; Cancel, Escape or a click outside drop the draft. * - Apply checks every row first. A row that cannot be applied is marked `aria-invalid`, the message says why and * focus goes to it; nothing is applied until every row can be. * - Clear empties the draft, so Apply then shows every row. Clear all, beside the chips, applies at once. * * @param {HTMLElement} root The element that holds the bar, its chips and its popover. * @param {{ fields: object[], applied?: object[], onChange: (applied: object[]) => void }} options * @returns {{ readonly applied: object[], setFields(fields: object[], applied?: object[]): void, destroy(): void }} */export function filters(root, options) { const part = (name) => root.querySelector(`[data-filter="${name}"]`) const open = part('open') const count = part('count') const chips = part('chips') const clearAll = part('clear-all') const shown = part('applied') const panel = part('panel') const form = part('form') const list = part('conditions') const empty = part('empty') const error = part('error') const add = part('add') const controller = new AbortController() const { signal } = controller let fields = options.fields let applied = [...(options.applied ?? [])] let draft = [] const fieldOf = (key) => fields.find((field) => field.key === key) /** A copy of one of the page's templates: the markup is the page's, this only fills it in. */ const clone = (name) => part(name).content.firstElementChild.cloneNode(true) /** @param {[string, string][]} choices @param {string} chosen */ const fill = (select, choices, chosen) => select.replaceChildren(...choices.map(([value, words]) => { const option = new Option(words, value, false, value === chosen) option.className = 'select-option' return option })) /** The control for a condition's value: what its field holds. */ function valueControl(given, field, index) { const label = `Value of condition ${index + 1}` if (field.type === 'enum') { const select = clone('choice') fill(select, field.options, given.value) // Nothing is chosen for a new condition: a first option that cannot be chosen again says so. const prompt = new Option(`Choose a ${field.label.toLowerCase()}`, '', true, !given.value) prompt.disabled = true prompt.className = 'select-option' select.prepend(prompt) select.setAttribute('aria-label', label) return select } const input = clone('row').querySelector('[data-part="value"]') input.type = field.type === 'number' ? 'number' : field.type === 'date' ? 'date' : 'text' if (field.type === 'number') Object.assign(input, { step: 'any', min: '0', inputMode: 'decimal' }) if (field.type === 'text') input.placeholder = 'Value' input.setAttribute('aria-label', field.unit ? `${label}, in ${field.unit}` : label) input.value = given.value return input } /** Write the draft's rows. Focus goes back to the control it was on, by row and part. */ function drawDraft(focus) { list.replaceChildren(...draft.map((given, index) => { const field = fieldOf(given.field) const row = clone('row') row.dataset.index = String(index) row.querySelector('[data-part="joiner"]').textContent = index === 0 ? 'Where' : 'and' const fieldSelect = row.querySelector('[data-part="field"]') fill(fieldSelect, fields.map((each) => [each.key, each.label]), given.field) fieldSelect.setAttribute('aria-label', `Field of condition ${index + 1}`) const operator = row.querySelector('[data-part="operator"]') fill(operator, operatorsOf(field), given.operator) operator.setAttribute('aria-label', `Comparison of condition ${index + 1}`) row.querySelector('[data-part="value"]').replaceWith(valueControl(given, field, index)) row.querySelector('[data-part="remove"]').setAttribute('aria-label', `Remove condition ${index + 1}`) return row })) empty.hidden = draft.length > 0 if (focus) list.querySelector(`[data-index="${focus.index}"] [data-part="${focus.part}"]`)?.focus() } function say(message, control) { error.textContent = message ?? '' error.hidden = !message for (const invalid of list.querySelectorAll('[aria-invalid="true"]')) { invalid.removeAttribute('aria-invalid') invalid.removeAttribute('aria-describedby') } if (control) { control.setAttribute('aria-invalid', 'true') control.setAttribute('aria-describedby', error.id) } } /** Write the applied conditions: a chip each, the count on the button, and Clear all when there is any. */ function drawApplied() { chips.replaceChildren(...applied.map((given, index) => { const words = describe(given, fieldOf(given.field)) const chip = clone('chip') chip.querySelector('.chip-label').textContent = words const remove = chip.querySelector('.chip-remove') remove.setAttribute('aria-label', `Remove the filter ${words}`) remove.dataset.index = String(index) return chip })) // The wrappers have no display of their own, so `hidden` hides them whatever their content's classes say. shown.hidden = applied.length === 0 count.firstElementChild.textContent = String(applied.length) count.hidden = applied.length === 0 open.setAttribute('aria-label', applied.length ? `Filters, ${applied.length} applied` : 'Filters') } function commit(next, focusAfter) { applied = next drawApplied() options.onChange(applied) focusAfter?.focus() } // Opening copies what is applied into the draft; closing without Apply drops it. panel.addEventListener('toggle', (event) => { if (event.newState !== 'open') return draft = applied.map((given) => ({ ...given })) say(null) drawDraft() ;(list.querySelector('[data-part="field"]') ?? add).focus() }, { signal }) add.addEventListener('click', () => { draft.push(condition(fields[0])) say(null) drawDraft({ index: draft.length - 1, part: 'field' }) }, { signal }) list.addEventListener('click', (event) => { const remove = event.target.closest('[data-part="remove"]') if (!remove) return const index = Number(remove.closest('li').dataset.index) draft.splice(index, 1) say(null) if (draft.length) drawDraft({ index: Math.min(index, draft.length - 1), part: 'field' }) else { drawDraft(); add.focus() } }, { signal }) // A new field brings its own comparisons and its own kind of value. list.addEventListener('change', (event) => { const control = event.target.closest('[data-part]') const index = Number(control?.closest('li')?.dataset.index) if (!control || Number.isNaN(index)) return if (control.dataset.part === 'field') { draft[index] = condition(fieldOf(control.value)) // What was said about the condition this row held is no longer true of it. say(null) drawDraft({ index, part: 'field' }) } else if (control.dataset.part === 'operator') { draft[index].operator = control.value } else { draft[index].value = control.value } }, { signal }) list.addEventListener('input', (event) => { const control = event.target.closest('[data-part="value"]') if (!control) return draft[Number(control.closest('li').dataset.index)].value = control.value if (control.getAttribute('aria-invalid') === 'true') say(null) }, { signal }) form.addEventListener('submit', (event) => { event.preventDefault() for (const [index, given] of draft.entries()) { const control = list.querySelector(`[data-index="${index}"] [data-part="value"]`) const message = problem(given, fieldOf(given.field), control?.validity) if (message) { say(draft.length > 1 ? `Condition ${index + 1}: ${message}` : message, control) control?.focus() return } } panel.hidePopover() commit(draft.map((given) => ({ ...given, value: String(given.value).trim() })), open) }, { signal }) part('cancel').addEventListener('click', () => panel.hidePopover(), { signal }) part('clear').addEventListener('click', () => { draft = [] say(null) drawDraft() add.focus() }, { signal }) chips.addEventListener('click', (event) => { const remove = event.target.closest('.chip-remove') if (!remove) return const index = Number(remove.dataset.index) const next = applied.filter((_, at) => at !== index) commit(next) // Focus stays in the row of chips: on the next one, or the one before, or the button that opens the filters. ;(chips.querySelectorAll('.chip-remove')[Math.min(index, next.length - 1)] ?? open).focus() }, { signal }) clearAll.addEventListener('click', () => commit([], open), { signal }) drawApplied() return { get applied() { return applied.map((given) => ({ ...given })) }, setFields(next, start = []) { fields = next applied = start drawApplied() }, destroy() { controller.abort() if (panel.matches(':popover-open')) panel.hidePopover() }, }}/** * The demo's query logic, shared by the filter bar and the table view: conditions on a field, an operator and a * value, all of which a row must meet (one level of AND), plus search, sort and pages. It reads plain rows and * plain fields and touches no element. An application asks its own data source the same questions; this is * not a query engine to publish. * * A field is `{ key, label, type, options? }`: `type` is `text`, `enum`, `number` or `date`, and an enum lists * its `options` as `[value, label]`. A date is `YYYY-MM-DD`, so dates compare as text. *//** The operators each type of field offers, in the order a reader meets them: `[name, words]`. */export const operators = { text: [['contains', 'contains'], ['is', 'is'], ['is-not', 'is not'], ['starts', 'starts with']], enum: [['is', 'is'], ['is-not', 'is not']], number: [['is', 'is'], ['more', 'is more than'], ['less', 'is less than']], date: [['on', 'is on'], ['before', 'is before'], ['after', 'is after']],}/** @param {{ type: keyof typeof operators }} field */export const operatorsOf = (field) => operators[field.type]/** A new condition on a field: its first operator, and a value still to give, even a choice. */export function condition(field) { return { field: field.key, operator: operatorsOf(field)[0][0], value: '' }}/** * What is wrong with a condition, in words, or null when it can be applied. The input's own validity comes first, * so a number field that holds letters is caught as the browser sees it. * @param {{ field: string, operator: string, value: string }} given * @param {{ type: string, label: string, options?: string[][] }} field * @param {ValidityState} [validity] */export function problem(given, field, validity) { if (!field) return 'Choose a field.' if (!operatorsOf(field).some(([name]) => name === given.operator)) return `Choose how ${field.label.toLowerCase()} compares.` const value = String(given.value ?? '').trim() if (validity?.badInput) return field.type === 'date' ? `Enter a whole date for ${field.label.toLowerCase()}.` : `Enter a number for ${field.label.toLowerCase()}.` if (!value) return field.type === 'enum' ? `Choose a ${field.label.toLowerCase()}, or remove the condition.` : `Enter a value for ${field.label.toLowerCase()}, or remove the condition.` if (field.type === 'number' && !Number.isFinite(Number(value))) return `Enter a number for ${field.label.toLowerCase()}.` if (field.type === 'date' && !/^\d{4}-\d{2}-\d{2}$/.test(value)) return `Enter a whole date for ${field.label.toLowerCase()}.` if (field.type === 'enum' && !field.options.some(([option]) => option === value)) return `Choose a ${field.label.toLowerCase()}.` return null}/** Whether a row meets one condition. */function meets(row, given, field) { const have = row[field.key] const want = given.value switch (field.type) { case 'text': { const text = String(have).toLowerCase() const term = String(want).trim().toLowerCase() if (given.operator === 'contains') return text.includes(term) if (given.operator === 'starts') return text.startsWith(term) return given.operator === 'is' ? text === term : text !== term } case 'enum': return given.operator === 'is' ? have === want : have !== want case 'number': { const number = Number(want) if (given.operator === 'more') return have > number if (given.operator === 'less') return have < number return have === number } case 'date': if (given.operator === 'before') return have < want if (given.operator === 'after') return have > want return have === want } return true}/** The rows that meet every condition. */export function filter(rows, conditions, fields) { const keyed = new Map(fields.map((field) => [field.key, field])) return rows.filter((row) => conditions.every((given) => meets(row, given, keyed.get(given.field))))}/** The rows whose given text holds what was typed, without regard to case. */export function search(rows, text, keys) { const term = text.trim().toLowerCase() if (!term) return rows return rows.filter((row) => keys.some((key) => String(row[key]).toLowerCase().includes(term)))}/** The rows in the order of one field, ascending or descending; ties keep the order they had. */export function sort(rows, key, direction = 'ascending') { const sign = direction === 'descending' ? -1 : 1 const compare = (a, b) => typeof a === 'number' ? a - b : String(a).localeCompare(String(b), 'en', { numeric: true }) return [...rows].sort((a, b) => compare(a[key], b[key]) * sign)}/** One page of rows, and where it stands among them. A page past the end is the last one. */export function paginate(rows, page, size) { const pages = Math.max(1, Math.ceil(rows.length / size)) const current = Math.min(Math.max(1, page), pages) const start = (current - 1) * size return { rows: rows.slice(start, start + size), page: current, pages, from: rows.length ? start + 1 : 0, to: Math.min(start + size, rows.length), total: rows.length }}const dates = new Intl.DateTimeFormat('en-US', { month: 'short', day: 'numeric', year: 'numeric', timeZone: 'UTC' })/** A date as a reader reads it: `Nov 13, 2026`. */export const formatDate = (value) => dates.format(new Date(`${value}T00:00:00Z`))/** A condition in words, for its chip: `Status is Ready`. */export function describe(given, field) { const words = operatorsOf(field).find(([name]) => name === given.operator)?.[1] ?? given.operator const value = field.type === 'enum' ? field.options.find(([option]) => option === given.value)?.[1] ?? given.value : field.type === 'date' ? formatDate(given.value) : field.type === 'text' ? `“${String(given.value).trim()}”` : given.value return `${field.label} ${words} ${value}${field.unit ? ` ${field.unit}` : ''}`}/** * Thirty deployments of Atlas Labs' projects over the last two weeks: what the filter bar narrows. A queued * deployment has not run, so its duration is 0 seconds. */export const fields = [ { key: 'project', label: 'Project', type: 'enum', options: [['Atlas', 'Atlas'], ['Borealis', 'Borealis'], ['Cinder', 'Cinder'], ['Drift', 'Drift'], ['Ember', 'Ember'], ['Fathom', 'Fathom']] }, { key: 'branch', label: 'Branch', type: 'text' }, { key: 'status', label: 'Status', type: 'enum', options: [['ready', 'Ready'], ['building', 'Building'], ['queued', 'Queued'], ['failed', 'Failed']] }, { key: 'duration', label: 'Duration', type: 'number', unit: 'seconds' }, { key: 'date', label: 'Date', type: 'date' },]export const deployments = [ { id: 'dpl_3200', project: 'Atlas', branch: 'main', status: 'ready', duration: 47, date: '2026-11-14' }, { id: 'dpl_3199', project: 'Borealis', branch: 'release/0.9', status: 'ready', duration: 42, date: '2026-11-14' }, { id: 'dpl_3198', project: 'Cinder', branch: 'main', status: 'ready', duration: 112, date: '2026-11-13' }, { id: 'dpl_3197', project: 'Drift', branch: 'main', status: 'queued', duration: 0, date: '2026-11-13' }, { id: 'dpl_3196', project: 'Ember', branch: 'main', status: 'ready', duration: 71, date: '2026-11-12' }, { id: 'dpl_3195', project: 'Drift', branch: 'release/0.9', status: 'ready', duration: 51, date: '2026-11-12' }, { id: 'dpl_3194', project: 'Atlas', branch: 'main', status: 'queued', duration: 0, date: '2026-11-11' }, { id: 'dpl_3193', project: 'Borealis', branch: 'main', status: 'ready', duration: 51, date: '2026-11-11' }, { id: 'dpl_3192', project: 'Cinder', branch: 'fix/avatar-fallback', status: 'failed', duration: 38, date: '2026-11-10' }, { id: 'dpl_3191', project: 'Drift', branch: 'feat/schedule-view', status: 'ready', duration: 96, date: '2026-11-10' }, { id: 'dpl_3190', project: 'Atlas', branch: 'feat/schedule-view', status: 'ready', duration: 71, date: '2026-11-09' }, { id: 'dpl_3189', project: 'Fathom', branch: 'feat/category-colors', status: 'queued', duration: 0, date: '2026-11-09' }, { id: 'dpl_3188', project: 'Atlas', branch: 'feat/schedule-view', status: 'queued', duration: 0, date: '2026-11-08' }, { id: 'dpl_3187', project: 'Borealis', branch: 'fix/avatar-fallback', status: 'ready', duration: 112, date: '2026-11-08' }, { id: 'dpl_3186', project: 'Cinder', branch: 'release/0.9', status: 'ready', duration: 42, date: '2026-11-07' }, { id: 'dpl_3185', project: 'Drift', branch: 'fix/avatar-fallback', status: 'ready', duration: 112, date: '2026-11-07' }, { id: 'dpl_3184', project: 'Ember', branch: 'main', status: 'building', duration: 128, date: '2026-11-06' }, { id: 'dpl_3183', project: 'Fathom', branch: 'chore/deps', status: 'ready', duration: 84, date: '2026-11-06' }, { id: 'dpl_3182', project: 'Atlas', branch: 'fix/avatar-fallback', status: 'ready', duration: 55, date: '2026-11-05' }, { id: 'dpl_3181', project: 'Borealis', branch: 'fix/avatar-fallback', status: 'ready', duration: 145, date: '2026-11-05' }, { id: 'dpl_3180', project: 'Atlas', branch: 'feat/category-colors', status: 'ready', duration: 112, date: '2026-11-04' }, { id: 'dpl_3179', project: 'Drift', branch: 'main', status: 'queued', duration: 0, date: '2026-11-04' }, { id: 'dpl_3178', project: 'Ember', branch: 'release/0.9', status: 'building', duration: 55, date: '2026-11-03' }, { id: 'dpl_3177', project: 'Fathom', branch: 'main', status: 'ready', duration: 96, date: '2026-11-03' }, { id: 'dpl_3176', project: 'Atlas', branch: 'main', status: 'ready', duration: 163, date: '2026-11-02' }, { id: 'dpl_3175', project: 'Drift', branch: 'chore/deps', status: 'ready', duration: 241, date: '2026-11-02' }, { id: 'dpl_3174', project: 'Cinder', branch: 'release/0.9', status: 'failed', duration: 38, date: '2026-11-01' }, { id: 'dpl_3173', project: 'Drift', branch: 'main', status: 'queued', duration: 0, date: '2026-11-01' }, { id: 'dpl_3172', project: 'Ember', branch: 'main', status: 'ready', duration: 145, date: '2026-10-31' }, { id: 'dpl_3171', project: 'Fathom', branch: 'chore/deps', status: 'building', duration: 112, date: '2026-10-31' },]打开 Filters 修改或添加条件,然后点 Apply。点胶囊标签上的叉号即可移除对应条件。
区块提供可直接复制的标记,沿用页面的文字颜色和字号。预览在 body 上设置 fg-text-body text-sm。每个区块都是尺寸容器,会根据自身宽度重排,无论放在宽页面、侧边栏大小的空间还是对话框中。
#区块组成
- 一个按钮打开条件编辑。 “Filters”按钮旁用墨色徽标显示已应用的条件数,即使筛选栏收起,也能看出列表已被筛选。按钮的可访问名称同样说明这一点:“Filters, 2 applied”。
- 条件先作为草稿编辑。 弹出层打开时,编辑的是已应用条件的副本。添加条件、更换字段、修改值,在点 Apply 之前都不会影响列表。Cancel、Escape 或点击外部会丢弃草稿;Clear 会清空草稿,此时再点 Apply 会显示所有行。
- 每个条件占一行,第一行前写“Where”,其余各行前写“and”:一行数据必须满足全部条件。条件只有一层,不能分组,也没有“或”。每行包含选择字段的下拉选择框、选择比较方式的下拉选择框、值,以及一个用于删除该行的低调按钮。
- 字段决定其余部分。 文本字段可选“包含”“是”“不是”“开头是”,值为文字;选项字段可选“是”“不是”,值为该字段的某个选项;数字字段可选“大于”或“小于”,用数字输入框填写值;日期字段可选“等于”“早于”或“晚于”,用日期输入框填写值。更换字段会重置该行,因此比较方式不会遇到无法解读的值。
- 无法生效的条件永远不会被应用。 值缺失、数字中含有字母或日期不完整时,值会被标记为
aria-invalid="true",输入框随之显示危险色边框,条件列表下方的消息会说明是哪个条件、原因是什么。焦点会移到值有误的输入控件,列表保持不变。 - 已应用的条件显示为胶囊标签。 每个标签用文字写出条件,并带有一个以条件命名的移除按钮,例如“Remove the filter Status is Ready”。行尾的 Clear all 一次移除全部条件。
- 列表会说明当前显示的内容。 标题下的摘要显示匹配数与总数,例如“12 of 30 deployments match all 2 filters”;没有匹配项时,列表会说明这一点并告诉读者如何恢复。
#哪些操作需要脚本
示例由三个模块组成。query.js 管理条件:每种类型提供的比较方式、条件哪里有误、一行是否满足条件,以及搜索、排序和分页;它只读取普通的行数据,不操作任何元素。filters.js 驱动筛选栏:复制标记中为条件行、选项和胶囊标签准备的模板并填入内容,再以已应用的条件调用 onChange。main.js 据此绘制列表。应用可以向自己的数据源提出同样的查询,筛选栏无需改动:把已应用的条件发送给服务器,而不是交给 filter()。
没有脚本时,筛选栏无法暂存条件:改为给列表加一个 <form method="get">,为每个字段放一个下拉选择框,由服务器响应查询字符串。
#无障碍
- 弹出层是
role="dialog",以其标题“Filter deployments”命名。打开时,焦点移到第一个条件的字段;没有条件时移到 Add condition。关闭时,焦点回到 Filters。 - 每行中的控件都以条件序号命名,例如“Field of condition 2”“Value of condition 2”“Remove condition 2”。数字值会说明单位。
- 关于无法应用的条件的消息是
role="alert",并通过aria-describedby关联到对应的值,因此出现时会被朗读,之后从该值上还能再次读到。 - 移除一个胶囊标签后,焦点移到下一个标签;移除的是最后一个时,焦点移到 Filters。Clear all 会把焦点移到 Filters。摘要是 polite 实时区域,变更后会朗读新的数量。
- 条件在胶囊标签中用文字表达,从不只靠颜色:列表中的状态保留徽标色调,并附有状态名称。