List pagination, sorting, and filtering for every list
Use one contract for every list, from a public guide card list to a signed-in source list. The same query words, the same sort choice, and the same total count mean the same thing on every surface.
What each list does today
Read this comparison before you change a list. Each row states the current behavior in the site pack, in the file named.
| Surface | Filters and address today | Sort today | Count and total today | Gap to close |
|---|---|---|---|---|
| Guides index, in public/guides/index.html | Search words as q, plus role, stage, and topic. Typing adds a history entry after the debounce pause. Back restores the view. | No sort control. Cards stay in the order listed on the page. | Showing count of 45 guides, in a status line. | Synonym matching appears only here. Typing history handling differs from My Answers. |
| Terminology page, in public/site.js | Search words as q only. Typing replaces the address only. No restore on back is stated in the code. | No sort control. Entries stay in the order listed. | Count of entries shown, with the total number of entries, in a status line. | A word start matches at one letter. No synonym list. Count wording differs from the guides index. |
| My Answers, in public/my-answers.html | Search words as q, one collection, and sort. Typing replaces the address. A discrete change pushes a history entry. Back and persisted page show restore the view. | Most relevant, recently opened, newest saved, or title A to Z. Relevance uses field weights that appear only here. | Showing count of total saved answers, stated in two status lines. | The whole phrase must appear as a substring. No word start rule and no spelling rule applies here. |
| Signed-in list sample, in APPKIT.md | No filter parameter is stated for the sample list. | Order by updated time descending only. | Limit 200 rows. No total count is returned with the rows. | No offset, no total, and no sort choice are stated, so a screen cannot show a page count or a stable next page. |
| Reports list behind a number, in public/reports.html and public/guides/read-reports.html | College or system view, assistant, channel, and date range are stated on the screen. | No sort choice is stated for the list behind a number. | Each headline number opens the list behind it, with the count behind the number. | No page size, offset, or total contract is stated, so two lists can page differently. |
Complete inventory of list endpoints in this pack
Use this inventory as the checklist for the contract below. Every list in the pack is one row. A list not in this table is not a list endpoint and must not invent its own parameter names. Browser-only lists (guides, terminology, device saved answers, and the weekly demo table) apply the same parameter names, defaults, and ordering semantics in the client; signed-in lists apply them on the server. The tenant, test-exclusion, and permission rules in the contract apply to every signed-in row.
| List surface | Canonical filters allowed | Default sort | Allowed sorts | Paging |
|---|---|---|---|---|
| Public guides index (public/guides/index.html) | q, role, stage, topic | relevant when q is present, otherwise listed order (title_asc as the stable listed order) | relevant, title_asc | limit/offset; client renders all matches when total is at most the applied limit, with the count status always shown |
| Terminology page (public/site.js) | q | listed order (title_asc as the stable listed order) | title_asc | limit/offset in the client; no server total is invented for a browser list |
| My Answers, My Library and other device saved-answer lists (public/my-answers.html, public/guides/my-library.html) | q, collection, folder and tag where the screen offers them (echoed as collection in data.filters) | relevant | relevant, last_opened_desc (UI: recently opened), created_desc (UI: newest saved), title_asc (UI: title A to Z) | limit/offset in the client; UI sort labels are unchanged, wire values are the canonical values in this row |
| Weekly quality weekly table (public/guides/weekly-quality-rate.html) | week (YYYY-MM-DD or all), signal | week_desc | week_desc, week_asc | Legacy page/pageSize only on this demo table; convert with the legacy mapping below. Screen choices stay 5, 10, 20; server limit is never above 200 |
| Sources (signed-in) | q, status, owner | updated_desc | updated_desc, updated_asc, title_asc, review_date_asc | limit/offset on the server |
| Assistants (signed-in) | q, status | name_asc | name_asc, updated_desc, updated_asc | limit/offset on the server |
| Questions, Ask history, and Reports list behind a number (signed-in) | q, assistant, channel, outcome/status, from, to | submitted_desc | submitted_desc, submitted_asc | limit/offset on the server; total uses the identical filters before paging |
| Unanswered themes / Improve queue (signed-in) | q, assistant, owner, status | count_desc | count_desc, updated_desc, due_date_asc | limit/offset on the server |
| Handoffs and Activity (signed-in) | q, status, owner, assistant | created_desc | created_desc, created_asc | limit/offset on the server |
| Personal history and personal saved answers (signed-in, as specified in public/guides/personal-history.html) | q, assistant, outcome, saved, from, to | submitted_desc | submitted_desc, submitted_asc, last_opened_desc where the screen offers it | limit/offset on the server, scoped to tenant_id and owner_user_id from the session |
| Shared collections, study sets, and library entries (signed-in, as specified in public/guides/workspace-shared-answers.html and public/guides/study-sets.html) | q, status, collection | position_asc for items in a collection, otherwise updated_desc | position_asc, updated_desc, updated_asc, title_asc | limit/offset on the server; position is the stored order and is never re-sorted by title on the server |
| Owner dashboard median fetch (public/guides/owner-dashboard-metrics.html Query 3B) and system-view grouped counts | Not a user-facing list; workspace, week bounds, and has_citation only | elapsed_asc with id_asc tie break (median only) | elapsed_asc only | Exempt from limit/offset: LIMIT 2 OFFSET (n-1)/2 after a COUNT. Do not expose this as a list endpoint and do not apply limit/offset user parameters to it |
Public search returns no workspace question text, no saved item, and no workspace source record. System view returns counts grouped by workspace only. Those scope rules override any filter or sort in this table.
Unified contract: request params
Every list endpoint accepts the same params. A param that is missing or invalid falls back as stated and the applied value is returned in the response, so the screen never guesses.
| Param | Meaning | Default and fallback |
|---|---|---|
| q | Search words, trimmed. Empty means no text filter. | Empty by default. Trimmed to at most 120 characters before matching; data.filters.q reports the trimmed value actually used. Token rules are in the filtering section below. No new server limit is stated in page text before the code that sets it ships. |
| limit | Maximum rows returned in one page. | Default 50. Parsed strictly as a base-10 integer (see Canonical parsing below). A parsed value below 1 falls back to 50. A value above 200 clamps to 200, the row limit documented in the APPKIT sample. The applied limit is returned. |
| offset | Rows to skip from the start of the filtered list. | Default 0. Parsed strictly as a base-10 integer. A negative, non-integer, or non-numeric value falls back to 0. A value above 1000000 falls back to 0. An offset at or past the total returns an empty items list with the total unchanged. |
| sort | Sort choice for that endpoint. Direction is part of the value (for example updated_desc), never a separate order parameter on a canonical endpoint. | Endpoint default in the inventory and sorting tables. Case-sensitive exact match only. An unknown sort, including a legacy device or week value on a signed-in endpoint, falls back to the endpoint default and the applied sort is returned. |
| fields | Comma-separated field names the screen shows on that list. | Default is the summary field set in the trimming table below. Unknown field names are ignored. Full-text, history, and attachment-content field names are never returned in a list, even when named. |
| status, owner, assistant, channel, collection, role, stage, topic, signal, week, saved, and from/to date range filters | One allowlisted filter per endpoint, using the names already shown on that screen and the inventory above. from/to are YYYY-MM-DD dates in college local time for signed-in lists. | All, empty, or the full range by default. An unknown enum value falls back to all for that filter only. A malformed date, or from after to, falls back to the full range for both dates. No new filter name is added in page text. |
Canonical parsing, ordering semantics, and legacy aliases
Apply parsing in one shared helper per module (pure functions, no network call, as in Step 2 of the implementation plan). Query parameters arrive as strings: trim, then for limit/offset require the form 0 or a non-zero digit followed by digits only. Values such as 1.5, 1e2, +5, 0x10, empty after trim, or a value with internal spaces are non-numeric for limit/offset and use the fallback above; they are never parsed as floats and never coerced silently. Enum and sort values are case-sensitive and are never lowercased before the allowlist check. Unknown query parameters are ignored and are never echoed in data.filters.
| Rule | Semantics |
|---|---|
| Order of operations | Filter first (tenant, test exclusion, enum/date filters, then q tokens), then sort, then offset/limit. The total is the filtered count before offset/limit. Changing any filter, sort, or limit returns to offset 0 on the client. |
| Tie break | Every sort ends with the record id in ascending order as the final tie break, so page one plus page two hold every filtered row once. For relevant, the order is relevance score descending, then id ascending; relevant is only a valid sort when q is non-empty, otherwise it falls back to the endpoint default. |
| Null and missing values | Rows with a null or missing sort value sort last in both ascending and descending sorts, then by id ascending. A null is never treated as 0, an empty string, or the earliest date. |
| Direction encoding | _asc means ascending and _desc means descending on the named field. There is no separate order parameter on canonical endpoints. A sort value without a direction suffix (relevant, position_asc is the exception because position is always ascending) is invalid except where the inventory lists it verbatim. |
| GET fallback is not an error | For read-only list GETs, an invalid limit, offset, sort, enum, or date uses the fallback above and still returns HTTP 200 with ok true and the applied values echoed. It is never a 400. The structured 400 with fields in public/guides/request-validation.html applies to mutating POST routes (for example POST /api/public/request), not to list GET parameters; do not turn a list GET into a 400. |
| Legacy form in the pack | Canonical conversion | Where it appears |
|---|---|---|
| page (1-based) + pageSize (screen choices 5, 10, 20) | limit = pageSize, offset = (page - 1) * pageSize. Page below 1 becomes page 1. Invalid pageSize becomes 5. PageSize above 100 clamps to 100 on the weekly demo table; signed-in endpoints clamp limit to 200 as above. Echo limit/offset in the response, never page/pageSize. | public/guides/weekly-quality-rate.html and the corrected filter logic in public/guides/search-scope.html |
| sort=week + order=asc|desc | sort = week_asc when order=asc, week_desc when order=desc. Unknown order falls back to week_desc. | Weekly quality weekly table |
| Device sort labels: relevant, recent, newest, title | relevant stays relevant; recent becomes last_opened_desc; newest becomes created_desc; title becomes title_asc. UI labels (Most relevant, Recently opened, Newest saved, Title A to Z) do not change. | public/my-answers.html and public/guides/my-library.html; public/guides/pagination-and-filtering.html sorting table |
| APPKIT sample: LIMIT 200 with no offset, no total, updated time descending only | limit=200 is the maximum, not a default. Add offset, total, hasMore, and the endpoint sort allowlist. Default limit stays 50. | APPKIT.md sample list, cited in the inventory above |
Response fields
Use the response convention on the status page and in public/guides/request-validation.html. A successful response has ok set to true and carries its values in data. An error response has ok set to false and carries a plain message in error that tells the person what to do, plus code; it has no data. List GET fallbacks above are successes, not errors.
| Field | Type | Rule |
|---|---|---|
| data.items | Array | The rows for the page requested, after filtering, sorting, offset, and limit. Each row holds only the requested summary fields from the trimming table below. An empty result is an empty array, never null. Full text, history, and attachment content load only from the detail route for one record. |
| data.total | Integer | The filtered count before pagination, with the same tenant, test exclusion, and filters as the items query. Zero is the number 0. An offset at or past the total returns items [] with this total unchanged. |
| data.limit | Integer | The applied limit after clamping, so the screen can show the page size it actually used. |
| data.offset | Integer | The applied offset after fallback. |
| data.sort | String | The applied sort after fallback, from the allowlist for that endpoint. Never echo a legacy page/pageSize or order value here. |
| data.filters | Object | The applied filter values, including the trimmed q actually used, so the screen and the address show the same view that produced the count. Unknown parameters are not echoed. |
| data.hasMore | Boolean | True when offset plus the number of items returned is below the total. The screen derives the page count from total and limit and shows it beside the pager. |
Unified contract: sorting, filtering, and total counts
Sort and filter the same way on every endpoint. The total count is the contract that keeps pagination honest.
Sorting allowlists
| Endpoint group | Default sort | Allowed sorts |
|---|---|---|
| Sources | updated_desc | updated_desc, updated_asc, title_asc, review_date_asc |
| Assistants | name_asc | name_asc, updated_desc, updated_asc |
| Questions and reports lists | submitted_desc | submitted_desc, submitted_asc |
| Unanswered themes | count_desc | count_desc, updated_desc, due_date_asc |
| Handoffs and activity | created_desc | created_desc, created_asc |
| Saved answers on this device | relevant | relevant, last_opened_desc, created_desc, title_asc (UI labels: Most relevant, Recently opened, Newest saved, Title A to Z) |
Every sort ends with the record id in ascending order as a tie break, and null sort values sort last in both directions, so a page boundary never moves a row between pages when two rows share a sort value.
Filtering and total count rules
- Every query stays scoped to one college workspace. A person in another college cannot open a result, and system view returns counts grouped by college only.
- Test and staff preview sessions are excluded from items and from the total, and the screen labels them as excluded.
- Search words use one token rule on every surface. A typed word matches when it is exact, when it starts a word of two letters or more, when it appears inside a word of three letters or more, or when it is one letter off a word of four letters or more. Every typed word must match.
- One shared synonym list applies on the guides index, the terminology page, and workspace search, or no synonym list applies on any of them. The search hint states which choice ships.
- The total is counted with the same filters as the items, before offset and limit. Items, total, and applied params are read together, so the count on screen always matches the list behind it.
- An empty filtered list returns total 0 and an empty items array. The screen shows the empty state for that list and no pager.
How a list request flows
```mermaid
flowchart LR
A[Screen sends q, filters, sort, limit, offset, fields] --> B[Server parses params with fallbacks]
B --> C[Server counts filtered rows for that college only]
C --> D[Server selects one page in sort order with id tie break]
D --> E[Screen shows items, total, applied sort, and pager]
E --> F{Next page or filter change}
F -->|Next page| A
F -->|Filter change| A
```
Response-field trimming contract
Every list holds summary fields only. A detail view for one record holds full fields. This keeps a page of 50 rows small and keeps full text off the list path.
| Endpoint group | List fields returned | Fields moved to detail only | Page size |
|---|---|---|---|
| Sources | Id, title, owner office, status, review date, updated time | Source body, approval history | 50 by default, 200 maximum |
| Assistants | Id, name, status, updated time | Welcome text body, source passages | 50 by default, 200 maximum |
| Questions and reports lists | Id, title, workspace, assistant, channel, outcome, submitted time, source title, source link, last checked date, helpful and not helpful counts | Question body, answer body, source body, history, rating comments, attachment content | 50 by default, 200 maximum |
| Unanswered themes | Id, theme, question count, not answered count, owner, due date | Example question text beyond one example, full thread | 50 by default, 200 maximum |
| Handoffs and activity | Id, thread id, status, owner, created time | Full message bodies, file bytes | 50 by default, 200 maximum |
| Saved answers on this device | Id, title, workspace, assistant, collection, created time, last opened time | Question, answer, source body | 50 by default, 200 maximum |
- Code locations: src/app/
.ts pure ListParams helper parses fields against the allowlist above and selects only those columns. SQL uses the same allowlist, tenant_id = c.session.tenantId in every query, and LIMIT and OFFSET from the applied limit and offset. Public views in public/app/views/ .js ask for the summary set only and load full text in the detail view the person opens. Tests in test/ .test.ts call the helper with no network call. - Unknown fields are ignored. They never widen the college scope and never add a row from another college.
- Client lists in public/guides/index.html, public/my-answers.html, and public/site.js follow the same summary field set. Full text renders only in the detail view that the person opens.
- At 50 rows, trimming holds each row to summary size. The worked example in API payload performance shows about 8400 bytes per full answer row and 620 bytes per summary row, saving about 194500 bytes per 25 rows.
Client rules shared by every list
Apply these rules on the public filters and on every signed-in list screen, so a reader learns one behavior.
- Filter after a short pause of 120 milliseconds while typing. Keep the search words in the page address as q, plus the applied role, stage, topic, collection, sort, limit, and offset where the screen uses them.
- Typing replaces the address. A discrete change, such as a filter, sort, clear, or pager choice, pushes a history entry. Back and persisted page show restore the applied view.
- Clear search or clear filters removes the params from the address, restores the full list, and returns focus to the search field.
- Show the count shown and the total in a status region, such as Showing X of Y guides, and announce a filtered empty result in that region.
- Use the search icon empty state for a search or filter result, with one title that names the empty list, one brief explanation that names the filter, and one primary clear action. Keep suggested entries as plain links outside the empty state.
- Keep the page heading and filter controls visible when the list is empty, show one empty state per list, keep controls at least 44 pixels high, keep focus visible by keyboard, and stack the icon above the text on a phone.
- Show a pager only when the total is more than the limit. Label the pager with the page position derived from offset, limit, and total, and keep the same filters on every page.
Implementation plan in order
Ship in this order, through the normal build, with no manual step. Each step keeps every existing test passing before the next step starts.
Step 1: Confirm names once
Confirm the question records table name and the list routes once in the shipped build, then use those names in every query below. Field logic does not change in this step.
Step 2: Add pure param and sort helpers per module
In each list API module, add exported pure functions that parse limit, offset, sort, fields, and filters with the strict integer, enum, date, and q-length rules above, and that build the sort clause from the allowlist for that endpoint, with nulls last and id ascending. Tests call these functions with no network call, including float, exponent, signed, and over-max inputs.
Step 3: Add the count query and the paged query together
For each endpoint, run one count query with the same tenant scope, test exclusion, and filters as the items query, then run the items query with the same filters, the allowlisted sort with the id tie break, and the bound limit and offset. Select only the allowlisted summary fields. Load full text only from the detail route for one record. Start with sources, then assistants, then questions, themes, handoffs, and activity.
Step 4: Return the envelope and echo applied params
Return ok true with data holding items, total, limit, offset, sort, filters, and hasMore. Return an empty array for an empty list and the number 0 for a zero total. Keep the error shape already stated on the status page: failures have ok false, error, and code, and no data. List GET fallbacks are successes, never 400.
Step 5: Add the pager to each signed-in list screen
On each list screen, show the count status, the items for the page, and previous and next controls with the page position. Keep heading and filters visible on every page. Use the empty state from the empty states guide when the total is zero.
Step 6: Align the public filters in one change
Update public/site.js for terminology, public/guides/index.html for guides, and public/my-answers.html for saved answers in the same change. Apply the token rule, the shared synonym choice, the 120 millisecond pause, the replace and push history rule, the restore on back, the count wording, and the empty state rule to all three. Move suggested guides outside the empty state on the guides index. Convert the weekly quality demo table from page/pageSize to limit/offset using the legacy mapping, keeping its 5/10/20 screen choices.
Step 7: Add tests for the contract
Add tests that the total is unchanged across pages, that an offset at or past the total returns an empty list with the total unchanged, that an invalid limit, offset, or sort falls back and echoes the applied value, that float, exponent, signed, and over-1000000 offset inputs fall back, that q over 120 characters is trimmed and echoed, that a malformed or reversed from/to falls back to the full range, that the id tie break and nulls-last rule keep a stable page order, that a one letter query does not match by word start while a two letter query does, that a spelling one letter off matches a word of four letters or more, that legacy page/pageSize converts to the same rows as limit/offset, that test sessions are excluded from items and total, that a record from another college never appears in items or total, and that a list row holds no body field and no attachment content while a detail request for one record holds the full fields.
Step 8: Publish the shipped values
In the same change that ships the server values, add the shipped limit, sort allowlists, and filter names to the operations page table. Do not publish a value on a page before the code that sets it ships.
Checks before you ship
Run each check on phone and desktop. If a check fails, fix it before you publish.
- The same query words give the same match result on the guides index and on terminology, including a one letter query, a two letter word start, and a spelling one letter off.
- Typing does not add a history entry per keystroke, a discrete change does, back restores the applied view, and clear removes the params from the address.
- Page one and page two together hold every filtered row once, with no row repeated and no row skipped, and the total matches the count on screen on both pages.
- An offset at or past the total shows the empty state, the filtered total unchanged in data.total, and no pager, with focus on the search field.
- An invalid limit, offset, sort, or filter value shows the fallback view with the applied value echoed, and never widens the college scope. Float, exponent, and signed limit/offset values fall back; they do not page as floats.
- A record from another college never appears in items or in the total, and test sessions are excluded from both and labeled as excluded.
- The count status, the empty state, the pager, and the address all state the same filters, sort, and total.
- A legacy page/pageSize link and the converted limit/offset link show the same rows, the same total, and the same order; the response echoes limit/offset/sort, never page/pageSize/order.
- Rows with a null sort value appear last on every page in both directions, and repeated requests return rows in an identical order.
- A list payload holds no body field, no history field, and no attachment content. Opening one row adds one detail payload only, and the detail shows full text with source title, source link, and last checked date.
Follow Search scope for query scope and permission rules, Empty states for the shared layout, Read reports for counts by college and assistant, and Configuration and safe defaults for shipped values.
Use one list contract everywhere
Start with one endpoint, add the count and the pager, then apply the same contract to the next list.