Skip to content

Filtered List

A List with a search, filters, a sort, a summary line, selection, and actions. It is the base the Data Table, the Paginated Table, and the Checkbox List are built on: the List owns the frame, the height, the scrolling, and the empty and loading states, and the Filtered List adds the controls, the data view, and the selection core, so every variation inherits each feature below.

Decision

When Use
Items a reader narrows down, such as a sync queue of media cards or a list of synced content Filtered List
Items with nothing to search, filter, sort, or select A plain List
Rows with columns that sort Data Table
Rows a server pages through with Previous and Next Paginated Table
Choices the reader checks, such as libraries or users Checkbox List

Usage

import { createFilteredList, createMediaCard } from './configurationpage?name=myplugin_stolon.js';

var queue = createFilteredList({
    items: rows,
    render: function (row) { return createMediaCard({ title: row.Name, itemId: row.ItemId, status: { label: row.State } }); },
    search: { keys: ['Name'], placeholder: 'Search the queue' },
    filters: [
        { name: 'State', label: 'States', kind: 'cards', options: [
            { value: 'Queued', label: 'Queued', color: 'orange' },
            { value: 'Synced', label: 'Synced', color: 'green' },
            { value: 'Errored', label: 'Errored', color: 'red' }
        ] },
        { name: 'Direction', label: 'Directions', kind: 'pills', options: [{ value: 'Pull', label: 'Pull' }, { value: 'Push', label: 'Push' }] }
    ],
    sorts: [{ key: 'Added', label: 'Newest', dir: 'desc' }, { key: 'Name', label: 'Name' }],
    height: 'fill'
});
view.querySelector('#queueHost').appendChild(queue.element);

For server data, pass fetch(query) instead of items, and setCounts(name, { value: count }) for the counts on its filters.

The handle is { element, list, toolbar, selectBar, bulkBar, reloadButton, toggleSort, setItems, setSearch, setFilter, setFilterOptions, setSort, setCounts, setHeight, getSelected, getSelectedItems, setSelected, clearSelection, redraw, getState, query, more, setLoadOnScroll, reload, destroy }. list is the List underneath, and toolbar the row a variation adds its own controls to.

A sync queue with selection, actions, and a live refresh:

var queue = createFilteredList({
    items: rows,
    rowKey: 'Id',
    render: function (row) {
        return createMediaCard({ title: row.Name, itemId: row.ItemId, status: { label: row.State, color: colors[row.State] },
            detail: row.Detail, error: row.Error, size: row.Bytes });
    },
    filters: [
        { name: 'State', label: 'States', kind: 'cards', options: stateOptions },
        { name: 'Peer', label: 'Servers', kind: 'pills', clearable: true, options: [] }
    ],
    selectable: 'multiple',
    bulkActions: [{ id: 'ignore', label: 'Ignore', icon: 'block', onClick: function (rows) { ignore(rows); } }],
    actions: [{ id: 'retry', label: 'Retry Errors', icon: 'refresh', onClick: retryErrors, visible: function (state) { return hasErrors(); } }],
    limit: 200,
    limitText: 'Showing the latest {shown} of {total}. Filter by state or server to see more.',
    onOpen: function (row) { openDetail(row); }
});
queue.setFilterOptions('Peer', peers.map(function (p) { return { value: p.Key, label: p.Name }; }));
setInterval(function () { load().then(function (rows) { queue.setItems(rows); }); }, 3000);

States and Modifiers

  • A filter's kind is select (default), pills (a row with an All pill, one choice at a time), cards (count cards that each turn on and off, and with none on every choice shows), or daterange (a Date Range Picker on its own line that keeps the items whose field date falls in the range). A daterange filter needs no options, takes presets, and its values are [from, to].
  • Every choice shows how many items it would match, given the search and the other filters: in its card, after its pill, and in its select option.
  • sorts adds a sort select. The first sort applies at the start unless sort names another.
  • The summary line reads "Showing {shown} of {total}." summaryText replaces it, and summary: false hides it.
  • The height is the List's: auto grows with the page, a length holds a fixed height that scrolls inside, maxHeight caps a growing list, and fill reaches the bottom of the window. pageSize shows that many and loads more as the list scrolls to its end.
  • layout is the List's too, so the items can be rows, a grid of cards, or plain.
  • selectable: 'single' picks one item by a click or Enter, and a second click clears it. selectable: 'multiple' draws a checkbox on each item, which render(item, index, check) may place itself, and a select all over the items shown that is checked, partly checked, or clear. onSelectionChange(ids, items) hears each change, and matchKey compares keys, such as one that ignores case.
  • bulkActions sit on the bar with the select all and the count, such as "3 selected". They are disabled while nothing is selected, and the bar takes the accent wash while something is.
  • onOpen(item) runs on a click and on Enter or Space on an item, apart from its checkbox or any other control inside it, and the item shows a focus ring.
  • setFilterOptions(name, options) swaps a filter's choices at runtime, for pills, cards, and selects, and keeps a picked value that still exists. A pill filter with clearable goes back to All on a second click of the picked pill.
  • setItems, and a server reload, keep the scroll position, the selection, and focus, and draw again only the items whose rowKey is new or whose content changed, so a poll every few seconds does not jump.
  • limit caps the items shown, and while more match the summary shows limitText, even with summary: false.
  • actions are field height buttons beside the search, each shown only while its visible(state) says so.
  • onReload() draws a reload Row Button at the end of the bar with the select all, so it needs selectable: 'multiple'. Its icon turns until the promise onReload returns settles, failed or not. reloadText replaces its title, "Reload".
  • The empty sentence is "Nothing matches." unless emptyText replaces it.
  • With fetch, immediate: false waits for the first query or reload, and loadOnScroll: false stops the end of the list from loading the next page.
  • onSearch(text) runs before a typed search and returns false to run it another way. onChange(state) runs after the items shown change.
  • itemClass(item, index) gives class names for an item's row, such as stolon-selected for an item picked somewhere else. It runs after every draw and every refresh, and a reused row drops the names it was given before. The names are cleaned, so text from data cannot leave the class attribute. With selectable on, the selection owns stolon-selected, so give a picked row another name.

Reference

Generated from the code by scripts/build-docs.mjs. Edit the code, not this section.

createFilteredList

function createFilteredList<T = any>(options: FilteredListOptions<T>): FilteredListHandle<T>

The List with a search, filters, a sort, a summary line, selection, and actions. It is the base the Data Table, the Paginated Table, and the Checkbox List are built on. It is made from Stolon parts: a Search Field, selects, pill rows, and count cards that turn on and off, over a data view that searches, filters, sorts, and pages local items or a server fetch, and the selection core. Each filter choice shows how many items it would match, given the search and the other filters. A next page adds its items under the ones shown, with the loading line beneath them while it loads, and new items keep the scroll position, the selection, and focus, drawing again only the items that changed.

Option Type What it does
render (required) (item: T, index: number, check?: HTMLInputElement | null): ListContent function(item, index, check) drawing one item, such as a media card, where check is the item's checkbox with multiple selection, placed by render or else at the item's start [required]
itemClass (item: T, index: number): unknown function(item, index) returning class names for the item's row, such as 'stolon-selected' for an item picked elsewhere. It runs after every draw and refresh, and replaces the names it gave before [optional]
items T[] | null local items [optional]
fetch (query: DataQuery): Promise<PagedResult<T> | T[]> | PagedResult<T> | T[] function(query) returning a page { Items, TotalCount } or an array, for server data [optional]
rowKey string | ((item: T) => unknown); search?: { keys?: string[] the field or function that names an item, so a refresh keeps what did not change (default 'id' while selectable)
placeholder string
label string aria-label of the list [optional]
delay number
Handle member Type
list ListHandle<T>
toolbar HTMLElement
selectBar HTMLElement | null
bulkBar HTMLElement | null
reloadButton HTMLButtonElement | null
toggleSort (key: string): void
setItems (items: T[] | null | undefined): void
setSearch (text: string): void
setFilter (name: string, values: string[] | null | undefined): void
setFilterOptions (name: string, options: FilteredListOption[] | null | undefined): void
setSort (key: string | null, dir?: 'asc' | 'desc'): void
setCounts (name: string, counts: Record<string, number>): void
setHeight (height: ListHeight, maxHeight?: number | string | null): void
getSelected (): string[]
getSelectedItems (): T[]
setSelected (ids: unknown[] | null | undefined): void
clearSelection (): void
redraw (): void
getState (): DataState<T>
query (change: { search?: string; filters?: Record<string, string[]>; sort?: DataSort | null; }): Promise<DataResult<T>>
more (): Promise<DataResult<T>>
setLoadOnScroll (on: boolean): void
reload (): void
destroy (): void
Type What it is
FilteredListOption One choice of a filter. color tints its card or pill, as a status color name or a hex code.
FilteredListFilter One filter. kind picks how it is shown: a select, a row of pills with an All pill, count cards that each turn on and off, or a Date Range Picker that keeps items whose date field falls in the range. field is the item field it matches (default its name), and test decides a match for anything else. clearable lets a second click on the picked pill go back to All. A daterange filter needs no options, takes presets for its pills, and its values are [from, to].
FilteredListSort One way to sort, shown as a choice in the sort select.
FilteredListBulkAction A button on the bar of selected items. onClick receives the selected items.
FilteredListToolbarAction A button beside the search. visible decides from the state whether it shows, such as Retry Errors only while an item failed.
Class What it looks like
stolon-filtered-list A List with a search, filters, a sort, and a summary line above it, the base a Data Table is built on
stolon-filtered-toolbar The search field and the selects on one line that wraps, the search taking the room left over
stolon-filtered-card Count cards that each turn a choice on and off: on is full strength, off is dimmed, and with none on every choice shows
stolon-filtered-pill-count A row of pills, one per choice and an All pill, each with its count
stolon-filtered-action A button beside the search or on the bar of selected items, hidden while its visible test says no
stolon-filtered-selectbar The bar over a list with multiple selection: the select all, the count of selected items, and the bulk actions, washed while it carries actions
stolon-filtered-checked An item that a checkbox leads, when the item's render did not place the checkbox itself. The checkbox sits on the row's center line, where a media card centers its artwork too
stolon-filtered-summary The line under the controls that says how many items show out of how many

Example

Example Code

<!-- title: Filtered List -->
<div id="mount"></div>
<script type="module">
const base = await window.__baseReady;
const kinds = ['Movie', 'Episode', 'MusicAlbum', 'Series'];
const titles = ['Alien', 'Brazil', 'Cosmos', 'Dune', 'Eraserhead', 'Fargo', 'Gattaca', 'Heat', 'Inception', 'Jaws', 'Kill Bill', 'Logan', 'Memento', 'Nope', 'Oldboy', 'Psycho'];
const peers = [{ value: 'den', label: 'Den' }, { value: 'cabin', label: 'Cabin' }, { value: 'office', label: 'Office' }];
const stateColor = { Synced: 'green', Queued: 'orange', Errored: 'red', Ignored: 'gray' };
const poster = (i) => 'data:image/svg+xml,' + encodeURIComponent('<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 2 3"><rect width="2" height="3" fill="hsl(' + (i * 47 % 360) + ',45%,42%)"/></svg>');
const states = ['Synced', 'Queued', 'Synced', 'Errored', 'Synced', 'Ignored', 'Synced', 'Queued'];
const make = (i, state) => ({
    id: 'item-' + i,
    name: titles[i % titles.length] + ' ' + (Math.floor(i / titles.length) + 1),
    type: kinds[i % kinds.length],
    dir: i % 3 ? 'out' : 'in',
    peer: peers[i % peers.length].value,
    state,
    size: 300000000 + (i * 7919 % 40) * 97000000,
    image: i % 5 ? poster(i) : ''
});
let all = Array.from({ length: 260 }, (_, i) => make(i, states[i % states.length]));
const detailOf = (item) => item.state === 'Queued' ? 'Pending, retry in 2m' : item.state === 'Synced' ? 'Sent to ' + item.peer : item.state === 'Ignored' ? 'Ignored by an administrator' : null;
const setState = (ids, state) => { all = all.map((item) => ids.indexOf(item.id) !== -1 ? Object.assign({}, item, { state }) : item); list.setItems(all); };
const list = base.createFilteredList({
    items: all,
    rowKey: 'id',
    render: (item) => base.createMediaCard({
        title: item.name,
        subtitle: item.type + ', ' + (item.dir === 'in' ? 'from ' : 'to ') + item.peer,
        shape: base.mediaShape(item.type),
        imageUrl: item.image,
        status: { label: item.state, color: stateColor[item.state] },
        detail: detailOf(item),
        error: item.state === 'Errored' ? 'Could not reach the server at 10.0.0.12. The connection timed out after 30 seconds.' : null,
        size: item.size
    }),
    search: { keys: ['name'], placeholder: 'Search titles' },
    filters: [
        { name: 'state', label: 'States', kind: 'cards', options: [{ value: 'Synced', label: 'Synced', color: 'green' }, { value: 'Queued', label: 'Queued', color: 'orange' }, { value: 'Errored', label: 'Errored', color: 'red' }, { value: 'Ignored', label: 'Ignored', color: 'gray' }] },
        { name: 'dir', label: 'Directions', kind: 'pills', options: [{ value: 'out', label: 'Outgoing' }, { value: 'in', label: 'Incoming' }] },
        { name: 'peer', label: 'Servers', kind: 'pills', clearable: true, options: [] }
    ],
    selectable: 'multiple',
    bulkActions: [
        { id: 'ignore', label: 'Ignore', icon: 'block', onClick: (items) => { setState(items.map((i) => i.id), 'Ignored'); list.clearSelection(); } },
        { id: 'queue', label: 'Queue', icon: 'playlist_add', variant: 'primary', onClick: (items) => { setState(items.map((i) => i.id), 'Queued'); list.clearSelection(); } }
    ],
    onReload: () => new Promise((done) => setTimeout(() => { list.setItems(all); done(); }, 800)),
    actions: [{ id: 'retry', label: 'Retry Errors', icon: 'refresh', onClick: () => setState(all.filter((i) => i.state === 'Errored').map((i) => i.id), 'Queued'), visible: () => all.some((i) => i.state === 'Errored') }],
    limit: 200,
    limitText: 'Showing the latest {shown} of {total}. Filter by state or server to see more.',
    onOpen: (item) => base.openDialog({ title: item.name, body: '<p>' + base.escapeHtml(item.type + ', ' + item.state + ', ' + (detailOf(item) || 'no detail')) + '</p>', buttons: [{ text: 'Done', className: 'stolon-button stolon-primary' }] }),
    height: 420
});
// The servers arrive after the first load, so the pills fill in late.
setTimeout(() => list.setFilterOptions('peer', peers), 600);
// A poll every 3 seconds changes one item's state, and only that row draws again.
let tick = 0;
setInterval(() => {
    tick++;
    const at = (tick * 13) % 40;
    all = all.map((item, i) => i === at ? Object.assign({}, item, { state: item.state === 'Synced' ? 'Queued' : 'Synced' }) : item);
    list.setItems(all);
}, 3000);
document.getElementById('mount').appendChild(list.element);
</script>