From 3ab95c4da443c4c441a991d2441c0137d63a61fa Mon Sep 17 00:00:00 2001 From: Thor Whalen <1906276+thorwhalen@users.noreply.github.com> Date: Tue, 1 Dec 2026 19:50:38 +0100 Subject: [PATCH 1/2] polytag/views: the timeline layout of a view model (dated items by year, approximate times, undated apart) through the same contract (S7 of #3) --- .../0002-view-model-port-and-contract.md | 2 +- packages/polytag/src/views/layout-dom.ts | 67 ++++++++++++++++- packages/polytag/subpaths.json | 2 +- .../polytag/tests/timeline-layout.test.ts | 74 +++++++++++++++++++ .../tests/view-contract.layout.test.ts | 6 +- 5 files changed, 144 insertions(+), 7 deletions(-) create mode 100644 packages/polytag/tests/timeline-layout.test.ts diff --git a/docs/decisions/0002-view-model-port-and-contract.md b/docs/decisions/0002-view-model-port-and-contract.md index da20868..d24f98c 100644 --- a/docs/decisions/0002-view-model-port-and-contract.md +++ b/docs/decisions/0002-view-model-port-and-contract.md @@ -23,4 +23,4 @@ Eight default views (three-pane, file manager, gallery, faceted, triage, board, ## Addendum: lenses that are not a list of everything in scope -The board (`boardOf`, `move-to-column`) runs the same contract as the list layouts (primary `multiValue`, so a card is in one column). **Triage** shows the unfiled items one at a time: its rows, selection and commands are the queue whatever the scope, so the generic contract's dataset (which needs filed items on screen) does not apply; `tests/triage.test.ts` runs the points that do (the queue is the unfiled items, filing is one command with a message on refusal, undo brings the item back and the count down, every gesture is a command with a reason when disabled, labels are text, keys ignored in text fields, focus kept, the next item announced). Calendar and timeline layouts will be added the same way. +The board (`boardOf`, `move-to-column`) runs the same contract as the list layouts (primary `multiValue`, so a card is in one column). **Triage** shows the unfiled items one at a time: its rows, selection and commands are the queue whatever the scope, so the generic contract's dataset (which needs filed items on screen) does not apply; `tests/triage.test.ts` runs the points that do (the queue is the unfiled items, filing is one command with a message on refusal, undo brings the item back and the count down, every gesture is a command with a reason when disabled, labels are text, keys ignored in text fields, focus kept, the next item announced). The **timeline** layout (`renderLayout` with `layout.kind: 'timeline'`, over `timelineModel`) runs the generic contract (a record without a date is undated, still a row); a calendar will be added the same way. diff --git a/packages/polytag/src/views/layout-dom.ts b/packages/polytag/src/views/layout-dom.ts index a0d748e..8ed1008 100644 --- a/packages/polytag/src/views/layout-dom.ts +++ b/packages/polytag/src/views/layout-dom.ts @@ -27,6 +27,7 @@ */ import { boardOf } from './board.js'; +import { datetimeAttr, formatTime, timelineModel } from './timeline.js'; import type { ItemRow, ViewModel } from './model.js'; export interface RenderLayoutOptions> { @@ -59,6 +60,7 @@ export function renderLayout(el: Element, model: ViewModel, const maxChips = options.maxChips ?? 3; const newRecord = options.newRecord ?? ((title: string) => ({ title }) as unknown as Partial); let alive = true; + const closedYears = new Set(); let typedTitle = ''; const make = (tag: K, attrs: Record = {}, text?: string): HTMLElementTagNameMap[K] => { @@ -108,10 +110,14 @@ export function renderLayout(el: Element, model: ViewModel, const draw = (): void => { if (!alive) return; + for (const d of content.querySelectorAll('details[data-year]')) { + if (d.open) closedYears.delete(d.getAttribute('data-year')!); + else closedYears.add(d.getAttribute('data-year')!); + } const rows = model.items(); const selection = model.selection(); const kind = model.view.layout.kind; - const layout = kind === 'table' || kind === 'cards' || kind === 'board' || kind === 'triage' ? kind : 'list'; + const layout = kind === 'table' || kind === 'cards' || kind === 'board' || kind === 'triage' || kind === 'timeline' ? kind : 'list'; root.setAttribute('data-layout', layout); bar.hidden = layout === 'triage'; // one item at a time: no select-all, no new-item box (Undo is on the card) @@ -150,7 +156,8 @@ export function renderLayout(el: Element, model: ViewModel, // rows: rebuilt only when the items, their chips, the layout or the order change const tri = layout === 'triage' ? model.triage() : undefined; - const key = `${layout}|${tri ? `${tri.current?.id ?? ''}\u0000${tri.current?.label ?? ''}|${tri.remaining}|${tri.done}|${model.commands().find((c) => c.id === 'revert')?.enabled}` : ''}|${model.groups().map((g) => `${g.id}:${g.family ?? ''}:${g.label ?? ''}`).join(',')}|${rows.map((r) => `${r.id}\u0000${r.label}\u0000${r.chips.map((c) => `${c.group}:${c.kind}:${c.label}`).join(',')}`).join('\u0001')}`; + const dateKey = layout === 'timeline' && model.view.layout.kind === 'timeline' ? rows.map((r) => `${String((r.record as Record)[(model.view.layout as { startField: string }).startField])}~${String((r.record as Record)[(model.view.layout as { endField?: string }).endField ?? ''])}`).join(',') : ''; + const key = `${layout}|${dateKey}|${tri ? `${tri.current?.id ?? ''}\u0000${tri.current?.label ?? ''}|${tri.remaining}|${tri.done}|${model.commands().find((c) => c.id === 'revert')?.enabled}` : ''}|${model.groups().map((g) => `${g.id}:${g.family ?? ''}:${g.label ?? ''}`).join(',')}|${rows.map((r) => `${r.id}\u0000${r.label}\u0000${r.chips.map((c) => `${c.group}:${c.kind}:${c.label}`).join(',')}`).join('\u0001')}`; const active = doc.activeElement; const focusAttr = active && content.contains(active) ? (['data-triage-assign', 'data-triage-skip', 'data-move-to'] as const).map((a) => [a, active.getAttribute(a)] as const).find(([, v]) => v !== null) : undefined; const focusId = active && content.contains(active) ? active.getAttribute('data-row-select') : null; @@ -179,6 +186,62 @@ export function renderLayout(el: Element, model: ViewModel, } } else if (rows.length === 0) { content.replaceChildren(make('p', { 'data-empty': '' }, 'Nothing to show here.')); + } else if (layout === 'timeline' && model.view.layout.kind === 'timeline') { + const cfg = model.view.layout; + const byId = new Map(rows.map((r) => [r.id, r] as const)); + let model2; + try { + model2 = timelineModel( + rows.map((r) => ({ id: r.id, [cfg.startField]: (r.record as Record)[cfg.startField], ...(cfg.endField ? { [cfg.endField]: (r.record as Record)[cfg.endField] } : {}) })), + { startField: cfg.startField, endField: cfg.endField }, + ); + } catch (error) { + model2 = undefined; + content.replaceChildren(make('p', { 'data-error': '' }, `The timeline cannot be drawn: ${error instanceof Error ? error.message : String(error)}`)); + } + if (model2) { + const li = (id: string, when?: (typeof model2.entries)[number], reason?: string): HTMLElement => { + const row = byId.get(id)!; + const item = make('li', { 'data-id': id, ...(when?.approximate ? { 'data-approximate': 'true' } : {}), ...(reason ? { title: reason } : {}) }); + item.append(checkbox(row)); + if (when) { + const dt = datetimeAttr(when); + item.append(make('time', dt ? { datetime: dt } : {}, formatTime(when))); + if (when.approximate) item.append(make('span', { 'data-approx-marker': '', title: 'approximate time' }, '≈')); + } + item.append(make('span', { 'data-title': '' }, row.label), chips(row)); + return item; + }; + const wrap = make('div', { 'data-layout-timeline': '' }); + const placed = make('div', { 'data-timeline': 'placed' }); + const years = new Map(); + for (const entry of model2.entries) { + const year = String(new Date(entry.start).getUTCFullYear()); + const list = years.get(year); + const node = li(entry.id, entry); + if (list) list.push(node); + else years.set(year, [node]); + } + for (const [year, nodes] of years) { + const details = make('details', { 'data-year': year }); + if (!closedYears.has(year)) details.setAttribute('open', ''); + details.append(make('summary', {}, `${year} (${nodes.length})`)); + const ul = make('ul'); + ul.append(...nodes); + details.append(ul); + placed.append(details); + } + wrap.append(placed); + if (model2.undated.length) { + const section = make('section', { 'data-bucket': 'undated' }); + section.append(make('h3', {}, `Undated (${model2.undated.length})`)); + const ul = make('ul'); + for (const u of model2.undated) ul.append(li(u.id, undefined, u.reason)); + section.append(ul); + wrap.append(section); + } + content.replaceChildren(wrap); + } } else if (layout === 'board' && model.view.layout.kind === 'board') { const cfg = model.view.layout; const board = boardOf(rows, model.groups(), { family: cfg.groupBy.family, multiValue: cfg.multiValue, showEmpty: cfg.showEmpty }); diff --git a/packages/polytag/subpaths.json b/packages/polytag/subpaths.json index b4ebf50..f35021e 100644 --- a/packages/polytag/subpaths.json +++ b/packages/polytag/subpaths.json @@ -2,5 +2,5 @@ ".": { "source": "src/index.ts", "tagAware": true }, "./formats": { "source": "src/formats/index.ts", "tests": ["tests/formats.test.ts"] }, "./backends": { "source": "src/backends/index.ts", "tests": ["tests/backends.test.ts", "tests/registry.test.ts"] }, - "./views": { "source": "src/views/index.ts", "tests": ["tests/views.test.ts", "tests/registry.test.ts", "tests/timeline.test.ts", "tests/view-contract.model.test.ts", "tests/view-model-review.test.ts"], "unguardedTests": ["tests/triage.test.ts", "tests/board.test.ts", "tests/view-contract.layout.test.ts", "tests/layout-review.test.ts", "tests/timeline-dom.test.ts", "tests/timeline-review.test.ts"] } + "./views": { "source": "src/views/index.ts", "tests": ["tests/views.test.ts", "tests/registry.test.ts", "tests/timeline.test.ts", "tests/view-contract.model.test.ts", "tests/view-model-review.test.ts"], "unguardedTests": ["tests/timeline-layout.test.ts", "tests/triage.test.ts", "tests/board.test.ts", "tests/view-contract.layout.test.ts", "tests/layout-review.test.ts", "tests/timeline-dom.test.ts", "tests/timeline-review.test.ts"] } } diff --git a/packages/polytag/tests/timeline-layout.test.ts b/packages/polytag/tests/timeline-layout.test.ts new file mode 100644 index 0000000..a2d96df --- /dev/null +++ b/packages/polytag/tests/timeline-layout.test.ts @@ -0,0 +1,74 @@ +// @vitest-environment jsdom +import { describe, expect, it } from 'vitest'; +import { DEFAULT_VIEWS, createViewModel, renderLayout, type ViewConfig } from '../src/views/index.js'; +import { GROUPS, type Item, memoryPort } from './support/memory-port.js'; + +type Dated = Item & { when?: string; until?: string }; +const caps = { roles: { start: 'when' }, maxGroupsPerItem: null as number | null }; +const lens: ViewConfig = { ...DEFAULT_VIEWS.find((v) => v.id === 'timeline')!.config(caps), layout: { kind: 'timeline', startField: 'when', endField: 'until' } }; +const DATA: Dated[] = [ + { id: 'a', title: 'Old', groups: ['x'], when: '2019-05-03' }, + { id: 'b', title: 'Approx', groups: ['y'], when: 'around 2021' }, + { id: 'c', title: 'After', groups: [], when: 'after a' }, + { id: 'd', title: 'No date', groups: [] }, + { id: 'e', title: ' Span', groups: ['x'], when: '2020', until: '2022' }, +]; +const mount = (items: Dated[] = structuredClone(DATA)) => { + const model = createViewModel(memoryPort(items as Item[], structuredClone(GROUPS)), lens); + const el = document.createElement('div'); + document.body.append(el); + renderLayout(el, model as never); + return { el, model }; +}; +const ids = (el: Element) => [...el.querySelectorAll('[data-id]')].map((n) => n.getAttribute('data-id')); +const $ = (el: Element, s: string) => el.querySelector(s) as HTMLElement; + +describe('the timeline layout of a view model: dated items, newest first, undated apart', () => { + it('lists placed items newest first under their years, and the undated ones in their own section', () => { + const { el } = mount(); + expect(ids($(el, '[data-timeline="placed"]'))).toEqual(['b', 'e', 'c', 'a']); + expect(ids($(el, '[data-bucket="undated"]'))).toEqual(['d']); + expect([...el.querySelectorAll('details[data-year]')].map((d) => d.getAttribute('data-year'))).toEqual(['2021', '2020', '2019']); + }); + + it('shows each time as text, marks the approximate ones, shows a span with a dash', () => { + const { el } = mount(); + expect($(el, '[data-id="b"]').getAttribute('data-approximate')).toBe('true'); + expect($(el, '[data-id="b"] time').textContent).toBe('c. 2021'); + expect($(el, '[data-id="e"] time').textContent).toBe('2020–2022'); + expect($(el, '[data-id="c"] time').textContent).toBe('after a'); + expect($(el, '[data-id="a"] time').getAttribute('datetime')).toBe('2019-05-03'); + }); + + it('keeps selection, chips and labels as in the other layouts; labels are text', () => { + const { el, model } = mount(); + ($(el, '[data-id="a"] input[data-row-select]') as HTMLInputElement).click(); + expect(model.selection().ids).toEqual(['a']); + expect([...el.querySelectorAll('[data-id="a"] [data-chip]')].map((n) => n.textContent)).toEqual(['Baking']); + expect(el.querySelector('img')).toBeNull(); + expect($(el, '[data-id="e"] [data-title]').textContent).toContain(' { + const { el, model } = mount(); + ($(el, 'details[data-year="2019"]') as HTMLDetailsElement).open = false; + model.dispatch('select', { ids: ['b'] }); + expect(($(el, 'details[data-year="2019"]') as HTMLDetailsElement).open).toBe(false); + const none = mount([]); + expect(none.el.textContent).toMatch(/nothing/i); + }); + + it('an unreadable date goes to the undated section, with the reason as its title', () => { + const { el } = mount([{ id: 'z', title: 'Z', groups: [], when: 'sometime' }]); + expect($(el, '[data-bucket="undated"] [data-id="z"]').getAttribute('title')).toMatch(/unparseable/); + }); + + it('a filter and a scope narrow the timeline like any other layout', () => { + const { el, model } = mount(); + model.dispatch('set-filter', { text: 'approx' }); + expect(ids(el)).toEqual(['b']); + model.dispatch('set-filter', { text: '' }); + model.dispatch('set-scope', { group: 'x' }); + expect(ids(el).sort()).toEqual(['a', 'e']); + }); +}); diff --git a/packages/polytag/tests/view-contract.layout.test.ts b/packages/polytag/tests/view-contract.layout.test.ts index 759cd8c..8b97b44 100644 --- a/packages/polytag/tests/view-contract.layout.test.ts +++ b/packages/polytag/tests/view-contract.layout.test.ts @@ -13,9 +13,9 @@ const click = (el: Element | null) => (el as HTMLElement).click(); const texts = (root: Element, sel: string) => [...root.querySelectorAll(sel)].map((n) => n.textContent ?? ''); /** The layout is driven through the DOM; the shell's concerns (scope, filter, inspector, links) go through the model. */ -function layoutDriver(layout: 'table' | 'list' | 'cards' | 'board'): ContractDriver & { el: HTMLElement; model: ViewModel } { +function layoutDriver(layout: 'table' | 'list' | 'cards' | 'board' | 'timeline'): ContractDriver & { el: HTMLElement; model: ViewModel } { const base = lensOf('three-pane'); - const view: ViewConfig = { ...base, layout: layout === 'table' ? { kind: 'table' } : layout === 'list' ? { kind: 'list' } : layout === 'board' ? { kind: 'board', groupBy: { family: 'status' }, multiValue: 'primary', showEmpty: true } : { kind: 'cards' } }; + const view: ViewConfig = { ...base, layout: layout === 'table' ? { kind: 'table' } : layout === 'list' ? { kind: 'list' } : layout === 'board' ? { kind: 'board', groupBy: { family: 'status' }, multiValue: 'primary', showEmpty: true } : layout === 'timeline' ? { kind: 'timeline', startField: 'when' } : { kind: 'cards' } }; const model = createViewModel(memoryPort(structuredClone(ITEMS), structuredClone(GROUPS)), view) as unknown as ViewModel; const el = document.createElement('div'); document.body.append(el); @@ -86,7 +86,7 @@ function layoutDriver(layout: 'table' | 'list' | 'cards' | 'board'): ContractDri // Until then the driver runs those gestures (tagging, scope, filter, inspector) through the model's // commands and reads their effect from the DOM: M3 (inspector), M4, M5 and M9 therefore say nothing about // widgets, and the shell's own contract run (S4) is where they are met by real controls. -for (const layout of ['table', 'list', 'cards', 'board'] as const) { +for (const layout of ['table', 'list', 'cards', 'board', 'timeline'] as const) { describeViewContract(`layout DOM, ${layout}`, () => layoutDriver(layout)); } From 9c9ab2a5e3943f4bf74d9948e378d19978b4a2c7 Mon Sep 17 00:00:00 2001 From: Thor Whalen <1906276+thorwhalen@users.noreply.github.com> Date: Tue, 1 Dec 2026 19:58:34 +0100 Subject: [PATCH 2/2] timeline layout: review fixes (relations placed over the whole collection, ids that cannot be placed go to undated, collapsed years out of the keys, words for undated, BC headings, selected counts, labels for relative times, aria) (S7 of #3) --- packages/polytag/src/views/layout-dom.ts | 111 +++++++++--------- packages/polytag/src/views/model.ts | 38 ++++++ packages/polytag/src/views/timeline.ts | 27 ++++- packages/polytag/tests/exports.test.ts | 2 +- .../polytag/tests/timeline-layout.test.ts | 85 +++++++++++++- 5 files changed, 199 insertions(+), 64 deletions(-) diff --git a/packages/polytag/src/views/layout-dom.ts b/packages/polytag/src/views/layout-dom.ts index 8ed1008..393b6df 100644 --- a/packages/polytag/src/views/layout-dom.ts +++ b/packages/polytag/src/views/layout-dom.ts @@ -27,7 +27,7 @@ */ import { boardOf } from './board.js'; -import { datetimeAttr, formatTime, timelineModel } from './timeline.js'; +import { datetimeAttr, formatTime, undatedText, yearsOf } from './timeline.js'; import type { ItemRow, ViewModel } from './model.js'; export interface RenderLayoutOptions> { @@ -45,6 +45,7 @@ export interface LayoutHandle { export const LAYOUT_COMMANDS = ['select-all', 'clear-selection', 'create-item', 'remove-from-scope', 'delete', 'revert'] as const; const mounted = new WeakMap(); +let instances = 0; const isTextTarget = (t: EventTarget | null): boolean => { const n = t as HTMLElement | null; @@ -60,6 +61,7 @@ export function renderLayout(el: Element, model: ViewModel, const maxChips = options.maxChips ?? 3; const newRecord = options.newRecord ?? ((title: string) => ({ title }) as unknown as Partial); let alive = true; + const instance = ++instances; const closedYears = new Set(); let typedTitle = ''; @@ -94,7 +96,8 @@ export function renderLayout(el: Element, model: ViewModel, box.checked = row.selected; return box; }; - const boxes = (): HTMLInputElement[] => [...content.querySelectorAll('input[data-row-select]')]; + // a checkbox inside a collapsed year cannot take focus: leave it out of the keys and the tab stop + const boxes = (): HTMLInputElement[] => [...content.querySelectorAll('input[data-row-select]')].filter((b) => !b.closest('details:not([open])')); const enabled = (id: string): boolean => model.commands().some((c) => c.id === id && c.enabled); @@ -156,7 +159,8 @@ export function renderLayout(el: Element, model: ViewModel, // rows: rebuilt only when the items, their chips, the layout or the order change const tri = layout === 'triage' ? model.triage() : undefined; - const dateKey = layout === 'timeline' && model.view.layout.kind === 'timeline' ? rows.map((r) => `${String((r.record as Record)[(model.view.layout as { startField: string }).startField])}~${String((r.record as Record)[(model.view.layout as { endField?: string }).endField ?? ''])}`).join(',') : ''; + const tl = layout === 'timeline' ? model.timeline() : undefined; + const dateKey = tl ? `${tl.entries.map((e) => `${e.id}:${e.start}:${e.end}:${e.precision}:${e.approximate}:${e.relativeTo ?? ''}`).join(',')}|${tl.undated.map((u) => `${u.id}:${u.reason}`).join(',')}` : ''; const key = `${layout}|${dateKey}|${tri ? `${tri.current?.id ?? ''}\u0000${tri.current?.label ?? ''}|${tri.remaining}|${tri.done}|${model.commands().find((c) => c.id === 'revert')?.enabled}` : ''}|${model.groups().map((g) => `${g.id}:${g.family ?? ''}:${g.label ?? ''}`).join(',')}|${rows.map((r) => `${r.id}\u0000${r.label}\u0000${r.chips.map((c) => `${c.group}:${c.kind}:${c.label}`).join(',')}`).join('\u0001')}`; const active = doc.activeElement; const focusAttr = active && content.contains(active) ? (['data-triage-assign', 'data-triage-skip', 'data-move-to'] as const).map((a) => [a, active.getAttribute(a)] as const).find(([, v]) => v !== null) : undefined; @@ -186,62 +190,45 @@ export function renderLayout(el: Element, model: ViewModel, } } else if (rows.length === 0) { content.replaceChildren(make('p', { 'data-empty': '' }, 'Nothing to show here.')); - } else if (layout === 'timeline' && model.view.layout.kind === 'timeline') { - const cfg = model.view.layout; - const byId = new Map(rows.map((r) => [r.id, r] as const)); - let model2; - try { - model2 = timelineModel( - rows.map((r) => ({ id: r.id, [cfg.startField]: (r.record as Record)[cfg.startField], ...(cfg.endField ? { [cfg.endField]: (r.record as Record)[cfg.endField] } : {}) })), - { startField: cfg.startField, endField: cfg.endField }, - ); - } catch (error) { - model2 = undefined; - content.replaceChildren(make('p', { 'data-error': '' }, `The timeline cannot be drawn: ${error instanceof Error ? error.message : String(error)}`)); - } - if (model2) { - const li = (id: string, when?: (typeof model2.entries)[number], reason?: string): HTMLElement => { - const row = byId.get(id)!; - const item = make('li', { 'data-id': id, ...(when?.approximate ? { 'data-approximate': 'true' } : {}), ...(reason ? { title: reason } : {}) }); - item.append(checkbox(row)); - if (when) { - const dt = datetimeAttr(when); - item.append(make('time', dt ? { datetime: dt } : {}, formatTime(when))); - if (when.approximate) item.append(make('span', { 'data-approx-marker': '', title: 'approximate time' }, '≈')); - } - item.append(make('span', { 'data-title': '' }, row.label), chips(row)); - return item; - }; - const wrap = make('div', { 'data-layout-timeline': '' }); - const placed = make('div', { 'data-timeline': 'placed' }); - const years = new Map(); - for (const entry of model2.entries) { - const year = String(new Date(entry.start).getUTCFullYear()); - const list = years.get(year); - const node = li(entry.id, entry); - if (list) list.push(node); - else years.set(year, [node]); - } - for (const [year, nodes] of years) { - const details = make('details', { 'data-year': year }); - if (!closedYears.has(year)) details.setAttribute('open', ''); - details.append(make('summary', {}, `${year} (${nodes.length})`)); - const ul = make('ul'); - ul.append(...nodes); - details.append(ul); - placed.append(details); + } else if (tl) { + const labels = new Map(rows.map((r) => [r.id, r.label] as const)); + let counter = 0; + const li = (row: ItemRow, when?: (typeof tl.entries)[number], reason?: string): HTMLElement => { + const item = make('li', { 'data-id': row.id, ...(when?.approximate ? { 'data-approximate': 'true' } : {}) }); + const box = checkbox(row); + item.append(box); + if (when) { + const dt = datetimeAttr(when); + const time = make('time', { ...(dt ? { datetime: dt } : {}), id: `polytag-time-${instance}-${counter++}` }, formatTime(when, (id) => labels.get(id))); + box.setAttribute('aria-describedby', time.id); + item.append(time); + if (when.approximate) item.append(make('span', { 'data-approx-marker': '', 'aria-hidden': 'true', title: 'approximate time' }, '≈')); } - wrap.append(placed); - if (model2.undated.length) { - const section = make('section', { 'data-bucket': 'undated' }); - section.append(make('h3', {}, `Undated (${model2.undated.length})`)); - const ul = make('ul'); - for (const u of model2.undated) ul.append(li(u.id, undefined, u.reason)); - section.append(ul); - wrap.append(section); - } - content.replaceChildren(wrap); + item.append(make('span', { 'data-title': '' }, row.label), chips(row)); + if (reason) item.append(make('span', { 'data-undated-reason': '' }, ` (${reason})`)); + return item; + }; + const wrap = make('div', { 'data-layout-timeline': '' }); + const placed = make('div', { 'data-timeline': 'placed' }); + for (const group of yearsOf(tl.entries)) { + const details = make('details', { 'data-year': group.key, 'data-year-label': group.label }); + if (!closedYears.has(group.key)) details.setAttribute('open', ''); + details.append(make('summary', {}, `${group.label} (${group.entries.length})`)); + const ol = make('ol'); + for (const entry of group.entries) ol.append(li(entry.row, entry)); + details.append(ol); + placed.append(details); } + wrap.append(placed); + if (tl.undated.length) { + const section = make('section', { 'data-bucket': 'undated' }); + section.append(make('h3', {}, `Undated (${tl.undated.length})`)); + const ol = make('ol'); + for (const u of tl.undated) ol.append(li(u.row, undefined, undatedText(u.reason))); + section.append(ol); + wrap.append(section); + } + content.replaceChildren(wrap); } else if (layout === 'board' && model.view.layout.kind === 'board') { const cfg = model.view.layout; const board = boardOf(rows, model.groups(), { family: cfg.groupBy.family, multiValue: cfg.multiValue, showEmpty: cfg.showEmpty }); @@ -301,6 +288,13 @@ export function renderLayout(el: Element, model: ViewModel, if (row.selected) node.setAttribute('data-selected', 'true'); else node.removeAttribute('data-selected'); } + for (const d of content.querySelectorAll('details[data-year]')) { + const total = d.querySelectorAll('li[data-id]').length; + const picked = d.querySelectorAll('input[data-row-select]:checked').length; + const summary = d.querySelector('summary'); + const text = `${d.getAttribute('data-year-label') ?? d.getAttribute('data-year')} (${total}${picked ? `, ${picked} selected` : ''})`; + if (summary && summary.textContent !== text) summary.textContent = text; + } const movable = enabled('move-to-column'); const moveReason = model.commands().find((c) => c.id === 'move-to-column')?.reason; for (const b of content.querySelectorAll('button[data-move-to]')) { @@ -432,6 +426,8 @@ export function renderLayout(el: Element, model: ViewModel, draw(); el.addEventListener('click', onClick); el.addEventListener('keydown', onKeydown); + const onToggle = (): void => syncTabStop(null); + el.addEventListener('toggle', onToggle, true); const off = model.subscribe(draw); const handle: LayoutHandle = { destroy() { @@ -440,6 +436,7 @@ export function renderLayout(el: Element, model: ViewModel, off(); el.removeEventListener('click', onClick); el.removeEventListener('keydown', onKeydown); + el.removeEventListener('toggle', onToggle, true); el.replaceChildren(); if (mounted.get(el) === handle) mounted.delete(el); }, diff --git a/packages/polytag/src/views/model.ts b/packages/polytag/src/views/model.ts index f2cf362..2f0d6c4 100644 --- a/packages/polytag/src/views/model.ts +++ b/packages/polytag/src/views/model.ts @@ -27,6 +27,7 @@ * Tag-agnostic: nothing here knows what a group space is beyond ids, labels and families. */ +import { type TimelineEntry, type UndatedReason, timelineModel } from './timeline.js'; import { type SavedView, type ViewConfig, SavedViewSchema } from './config.js'; /** Where a membership comes from; only a static one can be removed from here. */ @@ -173,6 +174,11 @@ export interface CommandResult { readonly inverse?: unknown; } +export interface TimelineView> { + readonly entries: readonly (TimelineEntry<{ id: string }> & { readonly row: ItemRow })[]; + readonly undated: readonly { readonly id: string; readonly reason: UndatedReason; readonly row: ItemRow }[]; +} + export interface TriageState> { /** The unfiled items that match the text filter: the unskipped first, then the skipped, in the order they were skipped. */ readonly queue: readonly ItemRow[]; @@ -201,6 +207,8 @@ export interface ViewModel> { tagging(): readonly TagState[]; /** The groups the collection has (a board's columns, a tag menu's choices). */ groups(): readonly GroupInfo[]; + /** The timeline layout's placement: relations (`after x`) are resolved over the whole collection, then cut to the rows shown. Empty outside a timeline lens. */ + timeline(): TimelineView; /** The triage queue (what is in no group, one at a time): empty and without a current item outside a triage lens. */ triage(): TriageState; commands(): readonly CommandInfo[]; @@ -704,6 +712,35 @@ export function createViewModel>( return { queue, current: queue[0], remaining: queue.length, done: doneIds.length }; }; + const timelineView = (): TimelineView => { + if (view.layout.kind !== 'timeline') return { entries: [], undated: [] }; + const cfg = view.layout; + const shown = rows(); + const byId = new Map>(); + for (const r of shown) if (!byId.has(r.id)) byId.set(r.id, r); + // a record with no id, or an id seen before, cannot be placed: it is undated, and the rest are still drawn + const seen = new Set(); + const bad: { id: string; reason: UndatedReason; row: ItemRow }[] = []; + const wrapped: Record[] = []; + for (const r of snapshot().records) { + const id = port.idOf(r); + const rec = r as Record; + const row = shown.find((x) => x.record === r); + if (id === '' || seen.has(id)) { + if (row) bad.push({ id, reason: id === '' ? 'no-id' : 'same-id', row }); + continue; + } + seen.add(id); + wrapped.push({ id, [cfg.startField]: rec[cfg.startField], ...(cfg.endField ? { [cfg.endField]: rec[cfg.endField] } : {}) }); + } + const m = timelineModel(wrapped as { id: string }[], { startField: cfg.startField, endField: cfg.endField }); + const inView = new Set(shown.map((r) => r.id)); + return { + entries: m.entries.filter((e) => inView.has(e.id)).map((e) => ({ ...e, row: byId.get(e.id)! })), + undated: [...m.undated.filter((u) => inView.has(u.id)).map((u) => ({ id: u.id, reason: u.reason, row: byId.get(u.id)! })), ...bad], + }; + }; + const scopes = (): ScopeEntry[] => { const { ids, chips, groups } = snapshot(); const inGroup = new Map(); @@ -730,6 +767,7 @@ export function createViewModel>( tagging, groups: () => snapshot().groups, triage, + timeline: timelineView, commands, dispatch, subscribe(listener) { diff --git a/packages/polytag/src/views/timeline.ts b/packages/polytag/src/views/timeline.ts index e01288c..6bcc270 100644 --- a/packages/polytag/src/views/timeline.ts +++ b/packages/polytag/src/views/timeline.ts @@ -77,7 +77,12 @@ export function parseTime(value: unknown): ParsedTime | undefined { } /** Why an item is not on the axis. */ -export type UndatedReason = 'missing' | 'unparseable' | 'unresolved-reference'; +export type UndatedReason = 'missing' | 'unparseable' | 'unresolved-reference' | 'no-id' | 'same-id'; + +/** Why an item is undated, in words. */ +export function undatedText(reason: UndatedReason): string { + return { missing: 'no date', unparseable: 'unreadable date', 'unresolved-reference': 'the item it is placed against was not found', 'no-id': 'no id', 'same-id': 'same id as another item' }[reason]; +} export interface TimelineEntry> { readonly id: string; @@ -281,10 +286,26 @@ export function datetimeAttr(entry: Pick): } /** A time for people: by precision, `c.` in front when approximate, a dash for a span. */ -export function formatTime(entry: Pick): string { +export function formatTime( + entry: Pick, + labelOf?: (id: string) => string | undefined, +): string { const first = formatAt(entry.start, entry.precision); const last = entry.span ? formatAt(entry.end, entry.endPrecision ?? entry.precision) : first; const text = last === first ? first : `${first}–${last}`; - if (entry.relativeTo) return `${entry.relation ?? 'after'} ${entry.relativeTo}`; + if (entry.relativeTo) return `${entry.relation ?? 'after'} ${labelOf?.(entry.relativeTo) ?? entry.relativeTo}`; return entry.approximate ? `c. ${text}` : text; } + +/** The placed entries grouped by UTC year, in the order given: `key` is the number, `label` what a person reads (BC before year 1). */ +export function yearsOf>(entries: readonly T[]): { key: string; label: string; entries: T[] }[] { + const out = new Map(); + for (const e of entries) { + const y = new Date(e.start).getUTCFullYear(); + const key = String(y); + const group = out.get(key); + if (group) group.entries.push(e); + else out.set(key, { key, label: y < 1 ? `${1 - y} BCE` : key, entries: [e] }); + } + return [...out.values()]; +} diff --git a/packages/polytag/tests/exports.test.ts b/packages/polytag/tests/exports.test.ts index a717efb..958531a 100644 --- a/packages/polytag/tests/exports.test.ts +++ b/packages/polytag/tests/exports.test.ts @@ -38,7 +38,7 @@ const EXPECTED: Record = { 'InspectorConfigSchema', 'InteractionConfigSchema', 'LAYOUT_COMMANDS', 'LayoutConfigSchema', 'NavigatorConfigSchema', 'NavigatorSurfaceSchema', 'SavedViewSchema', 'ShellSchema', 'VIEW_ENVELOPE', 'VIEW_LINK_KEY', 'ViewConfigSchema', 'availableViews', 'boardOf', 'createViewMenu', 'createViewModel', 'datetimeAttr', 'defaultViewMenu', 'formatTime', 'isDirty', - 'lanesOf', 'parseSavedView', 'parseTime', 'parseViewConfig', 'renderLayout', 'renderTimeline', 'timelineModel', 'viewFromLink', 'viewToLink', + 'lanesOf', 'parseSavedView', 'parseTime', 'parseViewConfig', 'renderLayout', 'renderTimeline', 'timelineModel', 'undatedText', 'viewFromLink', 'viewToLink', 'yearsOf', ], }; diff --git a/packages/polytag/tests/timeline-layout.test.ts b/packages/polytag/tests/timeline-layout.test.ts index a2d96df..8f71924 100644 --- a/packages/polytag/tests/timeline-layout.test.ts +++ b/packages/polytag/tests/timeline-layout.test.ts @@ -36,7 +36,7 @@ describe('the timeline layout of a view model: dated items, newest first, undate expect($(el, '[data-id="b"]').getAttribute('data-approximate')).toBe('true'); expect($(el, '[data-id="b"] time').textContent).toBe('c. 2021'); expect($(el, '[data-id="e"] time').textContent).toBe('2020–2022'); - expect($(el, '[data-id="c"] time').textContent).toBe('after a'); + expect($(el, '[data-id="c"] time').textContent).toBe('after Old'); expect($(el, '[data-id="a"] time').getAttribute('datetime')).toBe('2019-05-03'); }); @@ -58,9 +58,9 @@ describe('the timeline layout of a view model: dated items, newest first, undate expect(none.el.textContent).toMatch(/nothing/i); }); - it('an unreadable date goes to the undated section, with the reason as its title', () => { + it('an unreadable date goes to the undated section, with the reason in words', () => { const { el } = mount([{ id: 'z', title: 'Z', groups: [], when: 'sometime' }]); - expect($(el, '[data-bucket="undated"] [data-id="z"]').getAttribute('title')).toMatch(/unparseable/); + expect($(el, '[data-bucket="undated"] [data-id="z"]').textContent).toMatch(/unreadable date/); }); it('a filter and a scope narrow the timeline like any other layout', () => { @@ -72,3 +72,82 @@ describe('the timeline layout of a view model: dated items, newest first, undate expect(ids(el).sort()).toEqual(['a', 'e']); }); }); + +// ---- findings of the independent review + +const one = (items: object[]) => mount(items as Dated[]); + +describe('the timeline layout, review fixes', () => { + it('a filter that hides the reference does not move a relative item (relations are placed over the whole collection)', () => { + const { el, model } = one([{ id: 'a', title: 'Wedding', groups: [], when: '2019-06-01' }, { id: 'c', title: 'Honeymoon', groups: [], when: 'after a' }]); + model.dispatch('set-filter', { text: 'honey' }); + expect(el.querySelector('details[data-year="2019"] [data-id="c"]')).not.toBeNull(); + }); + + it('a relative time names its reference by label', () => { + const { el } = one([{ id: 'k3f9-uuid', title: 'Wedding', groups: [], when: '2019' }, { id: 'b', title: 'B', groups: [], when: 'after k3f9-uuid' }]); + expect($(el, '[data-id="b"] time').textContent).toContain('Wedding'); + expect($(el, '[data-id="b"] time').textContent).not.toContain('uuid'); + }); + + it('a record with an empty or a repeated id goes to the undated section; the others are still drawn', () => { + const { el } = one([{ id: 'a', title: 'A', groups: [], when: '2021' }, { id: '', title: 'Blank', groups: [], when: '2020' }, { id: 'a', title: 'Again', groups: [], when: '2018' }]); + expect(el.querySelector('[data-timeline="placed"] [data-id="a"]')).not.toBeNull(); + expect(el.querySelector('[data-error]')).toBeNull(); + expect($(el, '[data-bucket="undated"]').textContent).toMatch(/no id|same id/i); + }); + + it('arrow keys skip rows in a collapsed year, and the tab stop is never inside one', () => { + const { el, model } = one([{ id: 'a', title: 'A', groups: [], when: '2021' }, { id: 'b', title: 'B', groups: [], when: '2020' }, { id: 'c', title: 'C', groups: [], when: '2019' }]); + ($(el, 'details[data-year="2020"]') as HTMLDetailsElement).open = false; + const a = $(el, '[data-row-select="a"]'); + a.focus(); + a.dispatchEvent(new KeyboardEvent('keydown', { key: 'ArrowDown', bubbles: true })); + expect((document.activeElement as HTMLElement).getAttribute('data-row-select')).toBe('c'); + ($(el, 'details[data-year="2021"]') as HTMLDetailsElement).open = false; + model.dispatch('select', { ids: ['c'] }); + const stop = $(el, 'input[data-row-select][tabindex="0"]'); + expect(stop.closest('details:not([open])')).toBeNull(); + }); + + it('says in words why an item is undated, and on screen', () => { + const { el } = one([{ id: 'a', title: 'A', groups: [], when: 'after nobody' }, { id: 'b', title: 'B', groups: [] }, { id: 'c', title: 'C', groups: [], when: 'sometime' }]); + const text = $(el, '[data-bucket="undated"]').textContent!; + expect(text).toMatch(/not found/i); + expect(text).toMatch(/no date/i); + expect(text).toMatch(/unreadable/i); + }); + + it('a BCE year heading says BC; a collapsed year says how many of its items are selected', () => { + const bce = one([{ id: 'c', title: 'Caesar', groups: [], when: Date.UTC(2000, 0, 1) - 2044 * 365.25 * 86_400_000 }]); + expect($(bce.el, 'details summary').textContent).toMatch(/BC/); + const { el } = one([{ id: 'a', title: 'A', groups: [], when: '2021' }, { id: 'b', title: 'B', groups: [], when: '2020' }]); + ($(el, 'details[data-year="2020"]') as HTMLDetailsElement).open = false; + ($(el, 'input[data-select-header]') as HTMLInputElement).click(); + expect($(el, 'details[data-year="2020"] summary').textContent).toMatch(/1 selected/); + }); + + it('a date changed in place is redrawn; a collapsed year survives a rebuild; the year is the UTC one', () => { + const a = one([{ id: 'a', title: 'A', groups: [], when: '2021' }]); + ((a.model as unknown as { items(): { record: Dated }[] }).items()[0]!.record).when = '2018'; + a.model.refresh(); + expect($(a.el, '[data-id="a"] time').textContent).toBe('2018'); + const { el, model } = one([{ id: 'a', title: 'Alpha', groups: [], when: '2021' }, { id: 'b', title: 'Beta', groups: [], when: '2020' }]); + ($(el, 'details[data-year="2020"]') as HTMLDetailsElement).open = false; + const before = $(el, 'details[data-year="2020"]'); + model.dispatch('set-filter', { text: 'beta' }); + model.dispatch('set-filter', { text: '' }); + expect($(el, 'details[data-year="2020"]')).not.toBe(before); + expect(($(el, 'details[data-year="2020"]') as HTMLDetailsElement).open).toBe(false); + const late = one([{ id: 'l', title: 'L', groups: [], when: '2019-12-31T23:30:00Z' }]); + expect(late.el.querySelector('details[data-year="2019"]')).not.toBeNull(); + }); + + it('the approximate marker is hidden from assistive tech (the text says c.), and the date describes the checkbox', () => { + const { el } = one([{ id: 'a', title: 'A', groups: [], when: 'c. 2019' }]); + expect($(el, '[data-approx-marker]').getAttribute('aria-hidden')).toBe('true'); + const time = $(el, '[data-id="a"] time'); + expect($(el, '[data-id="a"] input[data-row-select]').getAttribute('aria-describedby')).toBe(time.id); + expect(time.id).not.toBe(''); + }); +});