Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion docs/decisions/0002-view-model-port-and-contract.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
66 changes: 63 additions & 3 deletions packages/polytag/src/views/layout-dom.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@
*/

import { boardOf } from './board.js';
import { datetimeAttr, formatTime, undatedText, yearsOf } from './timeline.js';
import type { ItemRow, ViewModel } from './model.js';

export interface RenderLayoutOptions<R extends object = Record<string, unknown>> {
Expand All @@ -44,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<Element, LayoutHandle>();
let instances = 0;

const isTextTarget = (t: EventTarget | null): boolean => {
const n = t as HTMLElement | null;
Expand All @@ -59,6 +61,8 @@ export function renderLayout<R extends object>(el: Element, model: ViewModel<R>,
const maxChips = options.maxChips ?? 3;
const newRecord = options.newRecord ?? ((title: string) => ({ title }) as unknown as Partial<R>);
let alive = true;
const instance = ++instances;
const closedYears = new Set<string>();
let typedTitle = '';

const make = <K extends keyof HTMLElementTagNameMap>(tag: K, attrs: Record<string, string> = {}, text?: string): HTMLElementTagNameMap[K] => {
Expand Down Expand Up @@ -92,7 +96,8 @@ export function renderLayout<R extends object>(el: Element, model: ViewModel<R>,
box.checked = row.selected;
return box;
};
const boxes = (): HTMLInputElement[] => [...content.querySelectorAll<HTMLInputElement>('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<HTMLInputElement>('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);

Expand All @@ -108,10 +113,14 @@ export function renderLayout<R extends object>(el: Element, model: ViewModel<R>,

const draw = (): void => {
if (!alive) return;
for (const d of content.querySelectorAll<HTMLDetailsElement>('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)

Expand Down Expand Up @@ -150,7 +159,9 @@ export function renderLayout<R extends object>(el: Element, model: ViewModel<R>,

// 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 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;
const focusId = active && content.contains(active) ? active.getAttribute('data-row-select') : null;
Expand Down Expand Up @@ -179,6 +190,45 @@ export function renderLayout<R extends object>(el: Element, model: ViewModel<R>,
}
} else if (rows.length === 0) {
content.replaceChildren(make('p', { 'data-empty': '' }, 'Nothing to show here.'));
} else if (tl) {
const labels = new Map(rows.map((r) => [r.id, r.label] as const));
let counter = 0;
const li = (row: ItemRow<R>, 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' }, '≈'));
}
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 });
Expand Down Expand Up @@ -238,6 +288,13 @@ export function renderLayout<R extends object>(el: Element, model: ViewModel<R>,
if (row.selected) node.setAttribute('data-selected', 'true');
else node.removeAttribute('data-selected');
}
for (const d of content.querySelectorAll<HTMLDetailsElement>('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<HTMLButtonElement>('button[data-move-to]')) {
Expand Down Expand Up @@ -369,6 +426,8 @@ export function renderLayout<R extends object>(el: Element, model: ViewModel<R>,
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() {
Expand All @@ -377,6 +436,7 @@ export function renderLayout<R extends object>(el: Element, model: ViewModel<R>,
off();
el.removeEventListener('click', onClick);
el.removeEventListener('keydown', onKeydown);
el.removeEventListener('toggle', onToggle, true);
el.replaceChildren();
if (mounted.get(el) === handle) mounted.delete(el);
},
Expand Down
38 changes: 38 additions & 0 deletions packages/polytag/src/views/model.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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. */
Expand Down Expand Up @@ -173,6 +174,11 @@ export interface CommandResult {
readonly inverse?: unknown;
}

export interface TimelineView<R extends object = Record<string, unknown>> {
readonly entries: readonly (TimelineEntry<{ id: string }> & { readonly row: ItemRow<R> })[];
readonly undated: readonly { readonly id: string; readonly reason: UndatedReason; readonly row: ItemRow<R> }[];
}

export interface TriageState<R extends object = Record<string, unknown>> {
/** The unfiled items that match the text filter: the unskipped first, then the skipped, in the order they were skipped. */
readonly queue: readonly ItemRow<R>[];
Expand Down Expand Up @@ -201,6 +207,8 @@ export interface ViewModel<R extends object = Record<string, unknown>> {
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<R>;
/** The triage queue (what is in no group, one at a time): empty and without a current item outside a triage lens. */
triage(): TriageState<R>;
commands(): readonly CommandInfo[];
Expand Down Expand Up @@ -704,6 +712,35 @@ export function createViewModel<R extends object = Record<string, unknown>>(
return { queue, current: queue[0], remaining: queue.length, done: doneIds.length };
};

const timelineView = (): TimelineView<R> => {
if (view.layout.kind !== 'timeline') return { entries: [], undated: [] };
const cfg = view.layout;
const shown = rows();
const byId = new Map<string, ItemRow<R>>();
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<string>();
const bad: { id: string; reason: UndatedReason; row: ItemRow<R> }[] = [];
const wrapped: Record<string, unknown>[] = [];
for (const r of snapshot().records) {
const id = port.idOf(r);
const rec = r as Record<string, unknown>;
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<string, number>();
Expand All @@ -730,6 +767,7 @@ export function createViewModel<R extends object = Record<string, unknown>>(
tagging,
groups: () => snapshot().groups,
triage,
timeline: timelineView,
commands,
dispatch,
subscribe(listener) {
Expand Down
27 changes: 24 additions & 3 deletions packages/polytag/src/views/timeline.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<T = Record<string, unknown>> {
readonly id: string;
Expand Down Expand Up @@ -281,10 +286,26 @@ export function datetimeAttr(entry: Pick<TimelineEntry, 'start' | 'precision'>):
}

/** A time for people: by precision, `c.` in front when approximate, a dash for a span. */
export function formatTime(entry: Pick<TimelineEntry, 'start' | 'end' | 'precision' | 'endPrecision' | 'span' | 'approximate' | 'relativeTo' | 'relation'>): string {
export function formatTime(
entry: Pick<TimelineEntry, 'start' | 'end' | 'precision' | 'endPrecision' | 'span' | 'approximate' | 'relativeTo' | 'relation'>,
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<T extends Pick<TimelineEntry, 'start'>>(entries: readonly T[]): { key: string; label: string; entries: T[] }[] {
const out = new Map<string, { key: string; label: string; entries: T[] }>();
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()];
}
2 changes: 1 addition & 1 deletion packages/polytag/subpaths.json
Original file line number Diff line number Diff line change
Expand Up @@ -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"] }
}
2 changes: 1 addition & 1 deletion packages/polytag/tests/exports.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@ const EXPECTED: Record<string, string[]> = {
'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',
],
};

Expand Down
Loading