From cf9d186ad3971673d4f816d65a41ea1125450a95 Mon Sep 17 00:00:00 2001 From: Alex Andreyev <54985783+alex-andreyev@users.noreply.github.com> Date: Tue, 17 Nov 2026 18:00:39 -0800 Subject: [PATCH] Attach events to the periods they are about An event can now name the periods it is about: a life, a reign, a war, as many as it takes. The first flight is in both brothers' lives and in the age of powered flight. The file keeps them as `periods`, a list of period ids on the event. - The event's window ticks any of the periods its date falls within. The list follows the date as it is typed, and a tick is kept while the date moves out of a period and back. - An event's details link to its periods. A period's details list its events and, in edit mode, offer to add one already attached. - New dates that leave an event out of a period, or deleting the period, detach the event from that period alone, in the same command. Co-Authored-By: Claude Opus 5.5 --- README.md | 7 +- docs/format.md | 3 +- docs/readme/README.ru.md | 8 ++- src/app/details.ts | 58 +++++++++++++++- src/app/editing.ts | 9 ++- src/app/editor.ts | 64 +++++++++++++++++- src/app/reading.ts | 1 + src/app/state.ts | 2 + src/app/styles.css | 140 ++++++++++++++++++++++++++++++++++++++- src/core/model.ts | 50 +++++++++++++- src/locales/ru.json | 26 +++++++- tests/app.mjs | 55 +++++++++++++++ tests/model.mjs | 59 ++++++++++++++++- 13 files changed, 469 insertions(+), 13 deletions(-) diff --git a/README.md b/README.md index 728f83f..f120689 100644 --- a/README.md +++ b/README.md @@ -66,7 +66,12 @@ disk. **card background** (the text turns dark or light to read on it), and its **shape**: a rectangle, or **round** — a medallion with its picture and the title under it, or a disc that holds the title, centred over its dot. A period has no pictures: photos dropped on - its bar become events. + its bar become events. An event may belong to **periods** — lives, reigns, wars, as many + as it is about: its window ticks them from those its date falls within, and the list + follows the date as it is typed. Each period's details list its events, each a step to it; + "Add an event to it" starts one attached already. A period whose new dates leave an event + out lets it go, and so does a deleted period, the event's other periods kept (one undo + brings it all back). - **Crowded stretches**: a card is never shrunk or hidden for want of room. Where cards do not fit side by side, they lie over each other — a later event over an earlier one — and the one under the pointer comes to the top. Only zooming out hides cards, the smaller diff --git a/docs/format.md b/docs/format.md index 379b129..58ced6a 100644 --- a/docs/format.md +++ b/docs/format.md @@ -175,13 +175,14 @@ the app sorts them by date when it saves. | `background` | event | `"#rrggbb"`: the card's own fill. The text turns light or dark to stay readable. | | `lane` | event, period | 0–99: a row fixed by hand. Normally left out: the app lays rows out itself. | | `shift` | event | An integer, −5,000 … 5,000: px the card was moved by hand to the right of where it would stand (negative: to the left). The date and its dot stay; a line joins the card to them. Normally left out. | +| `periods` | event | The `id`s of the periods the event is about, as many as it takes: a first flight is in both brothers' lives and in the age of powered flight. Each must be a `period` of the same file (anything else is left out with a warning; one named twice is kept once), and its dates should take in the event's date — the app offers only such periods, and lets an event go of a period whose new dates leave it out, keeping its others. Each period's details list its events. Leave it out rather than writing `[]`. | **The three kinds:** - **event**: something that happened on a date. A card above the axis with a dot on it. - **period**: something that lasted, such as a life, a reign or a war. A bar in the rows under the axis. Periods may overlap freely. A period can have pictures in the file, but - the app's editor offers none for it. + the app's editor offers none for it. Events may be attached to it (`periods` on the event). - **era**: a stretch of the whole chronology. A coloured band along the axis. Eras should **follow one another without overlapping**: each one begins after the previous one ends. The app's Eras editor treats them as a list where each era ends the day before the next diff --git a/docs/readme/README.ru.md b/docs/readme/README.ru.md index b05cea9..89fca99 100644 --- a/docs/readme/README.ru.md +++ b/docs/readme/README.ru.md @@ -65,7 +65,13 @@ Timeline открывает файлы `.timeline` — по одному на х становится тёмным или светлым, чтобы читаться на нём) и **форма**: прямоугольная или **круглая** — медальон с картинкой и названием под ним или круг с названием внутри, ровно над своей точкой. У периода картинок нет: фото, брошенные на его полосу, становятся - событиями. + событиями. Событие можно **привязать к периодам** — жизням, правлениям, войнам, ко всем, + к которым оно относится: в его окне галочками отмечаются периоды из тех, в которые входит + его дата, и список следует за датой, пока её вводят. В подробностях каждого периода — + список его событий, каждое — шаг к нему; «Добавить в него событие» создаёт уже + привязанное. Если новые даты периода не включают событие, оно отвязывается от этого + периода; при удалении периода — тоже; остальные его периоды остаются (одна отмена + возвращает всё). - **Тесные места**: карточка никогда не сжимается и не прячется из-за нехватки места. Где карточки не помещаются рядом, они ложатся друг на друга — более позднее событие поверх раннего, а карточка под указателем поднимается наверх. Скрывает карточки только diff --git a/src/app/details.ts b/src/app/details.ts index da7e596..0643f5a 100644 --- a/src/app/details.ts +++ b/src/app/details.ts @@ -9,9 +9,9 @@ */ import { formatDuration, formatRange, formatSpread, formatWhen, isNow } from '../core/dates'; -import { t } from '../core/i18n'; +import { t, tn } from '../core/i18n'; import { parseMarkdown, type Inline } from '../core/markdown'; -import { colorOf, picturesOf, spanOf, type Doc, type Item } from '../core/model'; +import { colorOf, eventsOf, picturesOf, spanOf, type Doc, type Item } from '../core/model'; import { byId, h } from './dom'; import { detailsGallery, type Gallery } from './gallery'; import type { ImageStore } from './images'; @@ -22,6 +22,8 @@ export interface DetailsHandlers { edit(id: string): void; /** Makes the item the anchor of the second ruler. */ anchor(id: string): void; + /** A new event, attached to this period. */ + addToPeriod(id: string): void; close(): void; /** Whether edit mode is on: Edit and "count from here" appear only then. */ editing(): boolean; @@ -119,6 +121,55 @@ export class Details { ), ); } + // An event's periods, a period's events: each a step to the other. + const periods = item.kind === 'event' ? doc.items.filter((i) => item.periods?.includes(i.id)) : []; + if (periods.length) { + parts.push( + h( + 'div', + { class: 'details-period' }, + h('span', { class: 'details-period-label' }, periods.length === 1 ? t('details', 'Period') : t('details', 'Periods')), + ...periods.map((period) => + h( + 'button', + { class: 'details-period-name details-period-link', type: 'button', lang, style: `--cat:${colorOf(period, doc)}`, onclick: () => this.handlers.show(period.id) }, + h('span', { class: 'details-mark', 'aria-hidden': 'true' }), + period.title, + ), + ), + ), + ); + } + if (item.kind === 'period') { + const events = eventsOf(doc, item.id); + if (events.length) { + parts.push( + h( + 'section', + { class: 'details-events', 'aria-label': t('details', 'Events of this period') }, + h('h3', { class: 'details-events-title' }, tn('details', '{count} event in this period', '{count} events in this period', events.length)), + h( + 'ul', + { class: 'details-events-list' }, + ...events.map((event) => + h( + 'li', + {}, + h( + 'button', + { class: 'details-event', type: 'button', style: `--cat:${colorOf(event, doc)}`, onclick: () => this.handlers.show(event.id) }, + h('span', { class: 'details-mark', 'aria-hidden': 'true' }), + h('span', { class: 'details-event-date' }, formatWhen(event.start)), + h('span', { class: 'details-event-title', lang }, event.title), + ), + ), + ), + ), + ), + ); + } + } + const meta: Node[] = []; const kinds = { event: t('details', 'Event'), period: t('details', 'Period'), era: t('details', 'Era') }; meta.push(h('span', { class: 'chip chip--plain' }, kinds[item.kind])); @@ -140,6 +191,9 @@ export class Details { const actions = h('div', { class: 'details-actions' }); if (this.handlers.editing()) { actions.append(h('button', { class: 'button', type: 'button', onclick: () => this.handlers.edit(item.id) }, t('details', 'Edit'))); + if (item.kind === 'period') { + actions.append(h('button', { class: 'text-button', type: 'button', onclick: () => this.handlers.addToPeriod(item.id) }, t('details', 'Add an event to it'))); + } if (item.kind === 'period' || item.kind === 'event') { actions.append(h('button', { class: 'text-button', type: 'button', onclick: () => this.handlers.anchor(item.id) }, t('details', 'Count years from here'))); } diff --git a/src/app/editing.ts b/src/app/editing.ts index 528d39b..3beb6dd 100644 --- a/src/app/editing.ts +++ b/src/app/editing.ts @@ -23,7 +23,7 @@ import { itemChange, imageChange, fieldChange, type Change } from '../core/comma import { endDay, formatDuration, formatRange, formatWhen, isNow, shiftWhen, snapTo, startOf, type When } from '../core/dates'; import { shortId } from '../core/hash'; import { t, tn } from '../core/i18n'; -import { MAX_SHIFT, picturesOf, spanOf, type CardSize, type Item, type ItemKind } from '../core/model'; +import { MAX_SHIFT, periodHolds, picturesOf, spanOf, type CardSize, type Item, type ItemKind } from '../core/model'; import { byId, h, isMac, isNarrow, isTouch, isTyping, swallowClick, trackPointer } from './dom'; import { deleteItem, openEditor, SIZE_OPTIONS, sizeLabel, whenAt } from './editor'; import { encodeImage } from './images'; @@ -613,6 +613,13 @@ export function setupEditing(): void { }); on('closed', () => setEditing(false)); on('anchor', (id) => void makeAnchor(id)); + // A new event in a period: at the middle of the screen when the period takes it in, else at the period's start. + on('addToPeriod', (id) => { + const period = app.session?.doc.items.find((i) => i.id === id && i.kind === 'period'); + if (!period) return; + const here = whenAt(app.strip.view.center); + void openEditor(null, { kind: 'event', start: periodHolds(period, here) ? here : { ...period.start }, periods: [period.id] }); + }); document.addEventListener('keydown', onKey); setupEditBar(); setupDragging(); diff --git a/src/app/editor.ts b/src/app/editor.ts index 8f4542c..7d1050f 100644 --- a/src/app/editor.ts +++ b/src/app/editor.ts @@ -9,8 +9,8 @@ import { itemChange, imageChange, fieldChange, type Change } from '../core/commands'; import { formatRange, isNow, snapTo, startOf, type End, type When } from '../core/dates'; import { shortId } from '../core/hash'; -import { t } from '../core/i18n'; -import { DEFAULT_COLOR, picturesOf, type CardShape, type CardSize, type Credit, type ImageInfo, type Item, type ItemKind } from '../core/model'; +import { t, tn } from '../core/i18n'; +import { colorOf, DEFAULT_COLOR, detachFrom, eventsOf, periodHolds, periodsAt, picturesOf, type CardShape, type CardSize, type Credit, type ImageInfo, type Item, type ItemKind } from '../core/model'; import { h, icon, shape, trackPointer } from './dom'; import { colorField, dateField, field, group, hint, textFields } from './forms'; import { encodeImage, type NewImage } from './images'; @@ -149,6 +149,46 @@ export async function openEditor(existing: Item | null, defaults: Partial explainSize(); const sizeField = group(t('editor', 'Size — the larger, the more it matters'), sizeRow, sizeHint); + // An event's periods, any number of them: only those its date falls within are offered, and the list follows the date as it is typed. + /** The periods ticked: kept while the date is moved out of one and back, so a slip of the year does not lose it. */ + const chosen = new Set(base.periods ?? []); + const periodList = h('div', { class: 'period-checks', id: 'edit-periods', role: 'group', 'aria-label': t('editor', 'Periods'), 'aria-describedby': 'edit-periods-hint' }); + const periodHint = h('p', { class: 'field-hint', id: 'edit-periods-hint' }); + const fillPeriods = () => { + const when = start.read(); + const offered = when ? periodsAt(doc, when) : []; + periodList.replaceChildren( + ...offered.map((p) => { + const box = h('input', { type: 'checkbox', value: p.id, checked: chosen.has(p.id) }); + box.addEventListener('change', () => (box.checked ? chosen.add(p.id) : chosen.delete(p.id))); + return h( + 'label', + { class: 'inline-check period-check', style: `--cat:${colorOf(p, doc)}` }, + box, + h('span', { class: 'period-swatch', 'aria-hidden': 'true' }), + h('span', { class: 'period-check-title', lang: doc.lang }, p.title), + h('span', { class: 'period-check-meta' }, formatRange(p.start, p.end)), + ); + }), + ); + periodList.hidden = !offered.length; + const lost = doc.items.filter((i) => chosen.has(i.id) && !offered.includes(i)); + periodHint.textContent = !when + ? t('editor', 'The periods are offered once the date is a date.') + : lost.length === 1 + ? t('editor', '“{title}” does not take in this date: saved so, the event leaves it.', { title: lost[0]!.title }) + : lost.length + ? t('editor', '{titles} do not take in this date: saved so, the event leaves them.', { titles: lost.map((l) => t('editor', '“{title}”', { title: l.title })).join(', ') }) + : offered.length + ? t('editor', 'Tick the periods it is about, as many as it takes: only those this date falls within are offered. Each period’s details list its events.') + : t('editor', 'No period takes in this date.'); + periodHint.classList.toggle('field-hint--warning', !!lost.length); + }; + start.el.addEventListener('change', fillPeriods); + start.el.addEventListener('input', fillPeriods); + fillPeriods(); + const periodField = group(t('editor', 'Periods'), periodList, periodHint); + // A card moved by hand (its row, and how far from its dot) or a bar's row: kept, or given back to the layout. const keepLane = h('input', { type: 'checkbox', checked: true }); const moved = base.lane !== undefined || base.shift !== undefined; @@ -329,6 +369,7 @@ export async function openEditor(existing: Item | null, defaults: Partial // A photo's own date fills an empty new event. if (!existing && encoded.taken && kind === 'event' && pictures.length === 1) { start.set(encoded.taken); + fillPeriods(); } } catch (error) { toast(t('editor', 'This picture could not be read: {error}', { error: (error as Error).message }), { kind: 'error' }); @@ -406,6 +447,7 @@ export async function openEditor(existing: Item | null, defaults: Partial isEra ? h('p', { class: 'field-hint' }, `${formatRange(base.start, base.end)} · ${t('editor', 'An era’s dates are set in the list of eras, where they meet the eras beside it.')}`) : h('div', { class: 'editor-dates' }, start.el, kind === 'period' ? endBox : null), + isEvent ? periodField : null, isEvent ? sizeField : null, color.el, isEvent ? background.el : null, @@ -461,6 +503,10 @@ export async function openEditor(existing: Item | null, defaults: Partial if (!s) return fail(t('editor', 'The start date is not a date.')); const item: Item = { ...base, id: base.id || newId(kind), kind, start: s, title }; if (isEvent) { + // The list follows the date; a period that does not take it in is never saved. Kept in time order. + const periods = periodsAt(doc, s).filter((p) => chosen.has(p.id)).map((p) => p.id); + if (periods.length) item.periods = periods; + else delete item.periods; const fill = background.value(); if (fill) item.background = fill; else delete item.background; @@ -530,7 +576,17 @@ export async function openEditor(existing: Item | null, defaults: Partial else delete item.gallery; } if (!existing || JSON.stringify(existing) !== JSON.stringify(item)) changes.push(itemChange(doc, item.id, item)); + // A period's new dates may no longer take in some of its events: they leave it, in the same command (one undo brings them back). + let left = 0; + if (kind === 'period' && existing) { + for (const event of eventsOf(doc, item.id)) { + if (periodHolds(item, event.start)) continue; + changes.push(itemChange(doc, event.id, detachFrom(event, item.id))); + left++; + } + } run(existing ? t('editor', 'Edit {title}', { title: item.title }) : t('editor', 'Add {title}', { title: item.title }), changes); + if (left) toast(tn('editor', '{count} event is outside the new dates of “{title}” and is no longer attached to it', '{count} events are outside the new dates of “{title}” and are no longer attached to it', left, { title: item.title })); const added = doc.items.find((i) => i.id === item.id); if (added) { app.strip.reveal(added); @@ -543,6 +599,10 @@ export function deleteItem(id: string): void { const item = session?.doc.items.find((i) => i.id === id); if (!session || !item) return; const changes: Change[] = [itemChange(session.doc, id, undefined)]; + // A period's events stay, no longer attached to it (their other periods kept); undo attaches them again. + if (item.kind === 'period') { + for (const event of eventsOf(session.doc, id)) changes.push(itemChange(session.doc, event.id, detachFrom(event, id))); + } // An anchor on the item goes with it. if (session.doc.anchor?.item === id) changes.push(fieldChange(session.doc, 'anchor', undefined)); const command = { label: t('editor', 'Delete {title}', { title: item.title }), changes }; diff --git a/src/app/reading.ts b/src/app/reading.ts index 7163d68..918fa21 100644 --- a/src/app/reading.ts +++ b/src/app/reading.ts @@ -104,6 +104,7 @@ export function setupReading(): void { }, edit: (id) => emit('open', id), anchor: (id) => emit('anchor', id), + addToPeriod: (id) => emit('addToPeriod', id), close: () => select(null), editing: () => app.editing, ordered: inOrder, diff --git a/src/app/state.ts b/src/app/state.ts index 839119e..660bcf1 100644 --- a/src/app/state.ts +++ b/src/app/state.ts @@ -51,6 +51,8 @@ type Events = { start: void; /** "Count years from here" on an item. */ anchor: string; + /** "Add an event to it" on a period: a new event, attached to it. */ + addToPeriod: string; /** The PWA's update state changed. */ update: void; }; diff --git a/src/app/styles.css b/src/app/styles.css index e137b57..fa74dac 100644 --- a/src/app/styles.css +++ b/src/app/styles.css @@ -759,7 +759,8 @@ body.dropping::after { .dot, .era, .bar, -.details-mark { +.details-mark, +.period-swatch { --cat-shown: color-mix(in oklab, var(--cat), white var(--lift)); } @@ -2163,6 +2164,143 @@ body.editing .details { color: var(--today); } +/* An event's periods, a period's events: steps from one to the other. */ +.details-period { + display: flex; + align-items: baseline; + flex-wrap: wrap; + gap: 4px 8px; + margin: 10px 0 4px; + font-size: 13px; +} + +.details-period-label { + font: 600 11px/1.4 var(--sans); + letter-spacing: 0.06em; + text-transform: uppercase; + color: var(--ink-faint); +} + +.details-period-name { + font: 600 14px/1.35 var(--serif); + color: var(--ink-soft); +} + +.details-period-link { + display: inline-flex; + align-items: center; + gap: 6px; + padding: 0; + border: 0; + background: none; + color: var(--accent); + cursor: pointer; + text-align: left; +} + +.details-period-link:hover { + text-decoration: underline; +} + +/* An event's periods in its window: one line each, ticked or not; only those its date falls within. */ +.period-checks { + display: flex; + flex-direction: column; + gap: 6px; + max-height: 13em; + padding: 2px 0; + overflow-y: auto; +} + +.period-check { + display: flex; + gap: 8px; + color: var(--ink); + cursor: pointer; +} + +.period-check .period-swatch { + flex: none; + width: 4px; + height: 14px; + margin: 0; + align-self: center; + border-radius: 2px; + background: var(--cat-shown); +} + +.period-check-title { + font-weight: 600; +} + +.period-check-meta { + font-size: 12px; + color: var(--ink-faint); +} + +.details-events { + margin: 16px 0 0; + padding-top: 12px; + border-top: 1px solid var(--rule); +} + +.details-events-title { + margin: 0 0 6px; + font: 600 11px/1.4 var(--sans); + letter-spacing: 0.06em; + text-transform: uppercase; + color: var(--ink-faint); +} + +.details-events-list { + margin: 0; + padding: 0; + list-style: none; +} + +.details-event { + display: grid; + grid-template-columns: 10px auto 1fr; + align-items: baseline; + gap: 8px; + width: calc(100% + 12px); + padding: 5px 6px; + margin: 0 -6px; + border: 0; + border-radius: 6px; + background: none; + cursor: pointer; + text-align: left; + font-size: 13px; +} + +.details-event:hover { + background: color-mix(in oklab, var(--ink) 6%, transparent); +} + +.details-event .details-mark { + align-self: center; + width: 8px; + height: 8px; +} + +.details-event-date { + color: var(--ink-faint); + font-size: 12px; + font-variant-numeric: tabular-nums; + white-space: nowrap; +} + +.details-event-title { + color: var(--ink); + font-family: var(--serif); + font-size: 14px; +} + +.field-hint--warning { + color: var(--danger); +} + /* ---------- Settings and form fields ---------- */ .settings { diff --git a/src/core/model.ts b/src/core/model.ts index 4cae9d9..f33e8ac 100644 --- a/src/core/model.ts +++ b/src/core/model.ts @@ -154,6 +154,12 @@ export interface Item { * (negative: to the left). Its date and its dot stay; a line joins them. */ shift?: number; + /** + * An event's periods: the ids of the periods it is about, each one's dates + * taking in the event's date — a first flight is in both brothers' lives and + * in the age of powered flight. Each period's details list it. + */ + periods?: string[]; extra?: Extra; } @@ -248,7 +254,7 @@ const KEYS = { style: ['paper', 'texture', 'color', 'font'], music: ['file', 'ext', 'title', 'credit'], view: ['center', 'scale'], - item: ['id', 'kind', 'start', 'end', 'title', 'text', 'refs', 'links', 'color', 'background', 'tags', 'image', 'gallery', 'size', 'shape', 'lane', 'shift'], + item: ['id', 'kind', 'start', 'end', 'title', 'text', 'refs', 'links', 'color', 'background', 'tags', 'periods', 'image', 'gallery', 'size', 'shape', 'lane', 'shift'], when: ['y', 'm', 'd', 'approx', 'spread'], } as const; @@ -426,6 +432,8 @@ export function parseDoc(json: unknown): { doc: Doc; warnings: Warning[] } { // items const itemIds = new Set(); + /** Events that name their periods: checked once every item is read, as a period may come after its events. */ + const periodLinks: { item: Item; id: string; path: string }[] = []; if (json.items !== undefined && !Array.isArray(json.items)) dropped('items'); (Array.isArray(json.items) ? json.items : []).forEach((value: unknown, i: number) => { const path = `items[${i}]`; @@ -521,11 +529,25 @@ export function parseDoc(json: unknown): { doc: Doc; warnings: Warning[] } { if (kind === 'event' && Number.isInteger(value.shift) && Math.abs(value.shift as number) <= MAX_SHIFT) item.shift = value.shift as number; else dropped(`${path}.shift`); } + if (value.periods !== undefined) { + if (kind === 'event' && Array.isArray(value.periods)) { + value.periods.forEach((link: unknown, j: number) => { + if (isString(link) && ID_PATTERN.test(link)) periodLinks.push({ item, id: link, path: `${path}.periods[${j}]` }); + else dropped(`${path}.periods[${j}]`); + }); + } else dropped(`${path}.periods`); + } const extra = extraOf(value, ITEM_KEYS); if (extra) item.extra = extra; itemIds.add(id); doc.items.push(item); }); + // An event keeps a period only if that is a period of this file; one named twice is kept once. + const periodIds = new Set(doc.items.filter((i) => i.kind === 'period').map((i) => i.id)); + for (const link of periodLinks) { + if (!periodIds.has(link.id)) dropped(link.path); + else if (!link.item.periods?.includes(link.id)) (link.item.periods ??= []).push(link.id); + } if (json.cover !== undefined) { if (isString(json.cover) && doc.images[json.cover]) doc.cover = json.cover; @@ -665,6 +687,7 @@ function docToJson(doc: Doc): Record { ['color', item.color], ['background', item.background], ['tags', item.tags], + ['periods', item.periods?.length ? item.periods : undefined], ['image', item.image], ['gallery', item.gallery?.length ? item.gallery : undefined], ['size', item.size], @@ -811,6 +834,31 @@ export function spanOf(item: Item, now = new Date()): [number, number] { return end > start ? [start, end] : [startOf(item.start), endDay(item.end, now)]; } +/** + * Whether a period takes in a date: the date's own span — a year, a month, a + * day — meets the period's, from the first day of its start to the last day + * of its end. "1957" is in "Oct 1957 – 1975"; "1956" is not. + */ +export function periodHolds(period: Item, when: When, now = new Date()): boolean { + if (period.kind !== 'period' || !period.end) return false; + return startOf(when) < endDay(period.end, now) && endOf(when) > startOf(period.start); +} + +/** The periods a date falls within, in time order: what an event can be attached to. */ +export const periodsAt = (doc: Doc, when: When, now = new Date()): Item[] => inTimeOrder(doc.items.filter((item) => periodHolds(item, when, now))); + +/** The events attached to a period, in time order. */ +export const eventsOf = (doc: Doc, periodId: string): Item[] => inTimeOrder(doc.items.filter((item) => item.kind === 'event' && !!item.periods?.includes(periodId))); + +/** An event no longer attached to a period: a copy, its other periods kept; `periods` goes once none is left. */ +export function detachFrom(event: Item, periodId: string): Item { + const next: Item = { ...event }; + const periods = event.periods?.filter((id) => id !== periodId); + if (periods?.length) next.periods = periods; + else delete next.periods; + return next; +} + /** A new, empty chronology. */ export function emptyDoc(kind: DocKind, id: string, title: string, lang: string, generator: string, now = new Date()): Doc { const day = now.toISOString().slice(0, 10); diff --git a/src/locales/ru.json b/src/locales/ru.json index bbd0109..9d5382c 100644 --- a/src/locales/ru.json +++ b/src/locales/ru.json @@ -8,7 +8,16 @@ "Edit": "Изменить", "Count years from here": "Считать годы отсюда", "Close (Esc)": "Закрыть (Esc)", - "Close": "Закрыть" + "Close": "Закрыть", + "Events of this period": "События этого периода", + "{count} events in this period": { + "one": "{count} событие в этом периоде", + "few": "{count} события в этом периоде", + "many": "{count} событий в этом периоде", + "other": "{count} события в этом периоде" + }, + "Add an event to it": "Добавить в него событие", + "Periods": "Периоды" }, "editor": { "Year": "Год", @@ -118,7 +127,20 @@ "Huge: a turning point, the largest card, its gallery beside its picture.": "Огромная: поворотный момент, самая большая карточка, галерея рядом с картинкой.", "Size — the larger, the more it matters": "Размер — чем больше, тем важнее", "“{title}” is {size} now: cards that size show from closer. Zoom in to see it.": "«{title}» теперь {size}: такие карточки видны ближе. Приблизьте, чтобы её увидеть.", - "Keep the card where it was dragged to; its date stays as set above": "Оставить карточку там, куда её перетащили; дата остаётся такой, как задана выше" + "Keep the card where it was dragged to; its date stays as set above": "Оставить карточку там, куда её перетащили; дата остаётся такой, как задана выше", + "The periods are offered once the date is a date.": "Периоды появятся, когда дата будет введена верно.", + "“{title}” does not take in this date: saved so, the event leaves it.": "«{title}» не включает эту дату: если сохранить так, событие выйдет из него.", + "{count} events are outside the new dates of “{title}” and are no longer attached to it": { + "one": "{count} событие вне новых дат «{title}» и больше к нему не привязано", + "few": "{count} события вне новых дат «{title}» и больше к нему не привязаны", + "many": "{count} событий вне новых дат «{title}» и больше к нему не привязаны", + "other": "{count} события вне новых дат «{title}» и больше к нему не привязаны" + }, + "Periods": "Периоды", + "{titles} do not take in this date: saved so, the event leaves them.": "{titles} не включают эту дату: если сохранить так, событие выйдет из них.", + "Tick the periods it is about, as many as it takes: only those this date falls within are offered. Each period’s details list its events.": "Отметьте периоды, к которым относится событие, — сколько нужно. Предлагаются только те, в которые входит дата. В подробностях каждого периода — список его событий.", + "No period takes in this date.": "Ни один период не включает эту дату.", + "“{title}”": "«{title}»" }, "ui": { "Cancel": "Отмена", diff --git a/tests/app.mjs b/tests/app.mjs index 7b00be4..82f9ae7 100644 --- a/tests/app.mjs +++ b/tests/app.mjs @@ -595,6 +595,61 @@ try { check('the saved event is in the reopened file', await ev(tab, "[...document.querySelectorAll('.card, .dot')].some(el => el.textContent.includes('A test event') || el.title?.includes('A test event'))"), true); check('…with its colour', await ev(tab, "timeline.session.doc.items.find(i => i.title === 'A test event')?.color"), '#7b5e8a'); await key('e', 'KeyE', 69, 'e'); + // An event attached to periods, as many as it is about: only those its date falls within are offered, and the list follows the date. + const ctrl = (k, code, vk, shift = false) => chrome.send('Input.dispatchKeyEvent', { type: 'keyDown', key: k, code, windowsVirtualKeyCode: vk, modifiers: shift ? 10 : 2 }, tab); + await key('e', 'KeyE', 69, 'e'); + await ev(tab, "document.activeElement?.blur(); timeline.strip.selected = 'wright'; document.querySelector('[data-id=wright]')?.focus()"); + await key('e', 'KeyE', 69, 'e'); + const periodBoxes = "[...document.querySelectorAll('dialog[open] #edit-periods input')].map(i => i.value)"; + const periodTicked = "[...document.querySelectorAll('dialog[open] #edit-periods input:checked')].map(i => i.value)"; + const tickPeriod = (id) => ev(tab, `document.querySelector('dialog[open] #edit-periods input[value="${id}"]').click()`); + check('an event’s window offers the periods its date falls within', await chrome.until(tab, "document.querySelectorAll('dialog[open] #edit-periods input').length === 4"), true); + check('…17 Dec 1903: the Wrights, Lindbergh’s childhood, powered flight — none ticked', await ev(tab, `[${periodBoxes}, ${periodTicked}]`), [['wilbur', 'orville', 'lindbergh-life', 'aviation-age'], []]); + const setYear = (y) => ev(tab, `(() => { const y = document.querySelector('dialog[open] .date-year'); y.value = '${y}'; y.dispatchEvent(new Event('input', { bubbles: true })); })()`); + await tickPeriod('aviation-age'); + await setYear(1902); + check('…another year, other periods: the one ticked goes, and the window says so', await ev(tab, `[${periodBoxes}, ${periodTicked}, document.getElementById('edit-periods-hint').textContent.startsWith('“Powered flight” does not take in this date'), document.getElementById('edit-periods-hint').classList.contains('field-hint--warning')]`), [['wilbur', 'orville', 'lindbergh-life'], [], true, true]); + await setYear(1903); + check('…back in it, the period ticked is ticked again', await ev(tab, periodTicked), ['aviation-age']); + await tickPeriod('orville'); + await shot(tab, '30-event-period'); + await ev(tab, "document.querySelector('dialog[open] .button--primary').click()"); + check('saved, the event is attached to both, in time order', await chrome.until(tab, "!document.querySelector('dialog[open]') && JSON.stringify(timeline.session.doc.items.find(i => i.id === 'wright').periods) === JSON.stringify(['orville', 'aviation-age'])"), true); + check('…its details name the periods, each a step to it', await chrome.until(tab, "document.querySelector('.details-period-label')?.textContent === 'Periods' && [...document.querySelectorAll('.details-period-link')].map(b => b.textContent).join() === 'Orville Wright,Powered flight'"), true); + await ev(tab, "document.querySelector('.details-period-link').click()"); + check('…the period’s details list its events', await chrome.until(tab, "document.getElementById('details-title').textContent === 'Orville Wright' && [...document.querySelectorAll('.details-event-title')].map(e => e.textContent).join() === 'The Wright brothers fly'"), true); + check('…and offer to add another to it', await ev(tab, "[...document.querySelectorAll('.details-actions button')].some(b => b.textContent === 'Add an event to it')"), true); + await ev(tab, "[...document.querySelectorAll('.details-actions button')].find(b => b.textContent === 'Add an event to it').click()"); + check('…a new event, attached to it already', await chrome.until(tab, `JSON.stringify(${periodTicked}) === JSON.stringify(['orville'])`), true); + await ev(tab, "document.querySelector('dialog[open]').close()"); + await chrome.until(tab, "!document.querySelector('dialog[open]')"); + const wrightPeriods = "JSON.stringify(timeline.session.doc.items.find(i => i.id === 'wright').periods)"; + // New dates that leave an event out: it is let go of in the same command, its other period kept, and one undo attaches it again. + await ev(tab, "document.activeElement?.blur(); timeline.strip.selected = 'orville'; document.querySelector('[data-id=orville]')?.focus()"); + await key('e', 'KeyE', 69, 'e'); + await chrome.until(tab, "document.querySelector('dialog[open] #edit-title')?.value === 'Orville Wright'"); + await ev(tab, "(() => { const y = document.querySelector('dialog[open] .date-year'); y.value = '1905'; y.dispatchEvent(new Event('input', { bubbles: true })); document.querySelector('dialog[open] .button--primary').click(); })()"); + check('a period’s new dates let go of the events they leave out; their other periods stay', await chrome.until(tab, `!document.querySelector('dialog[open]') && ${wrightPeriods} === '["aviation-age"]'`), true); + check('…and say so', await ev(tab, "[...document.querySelectorAll('.toast')].some(t => t.textContent.includes('no longer attached to it'))"), true); + await ev(tab, "document.activeElement?.blur()"); + await ctrl('z', 'KeyZ', 90); + check('…one undo: the dates and the link are back', await chrome.until(tab, `(() => { const o = timeline.session.doc.items.find(i => i.id === 'orville'); return o.start.y === 1871 && ${wrightPeriods} === '["orville","aviation-age"]'; })()`), true); + // Deleting a period keeps its events, no longer attached to it; undo attaches them again. + await ev(tab, "timeline.strip.selected = 'orville'; document.querySelector('[data-id=orville]')?.focus()"); + await chrome.send('Input.dispatchKeyEvent', { type: 'keyDown', key: 'Delete', code: 'Delete', windowsVirtualKeyCode: 46 }, tab); + check('a deleted period’s events stay, in their other periods only', await chrome.until(tab, `!timeline.session.doc.items.some(i => i.id === 'orville') && ${wrightPeriods} === '["aviation-age"]'`), true); + await ev(tab, "document.activeElement?.blur()"); + await ctrl('z', 'KeyZ', 90); + check('…undo brings the period back, its event attached', await chrome.until(tab, `${wrightPeriods} === '["orville","aviation-age"]'`), true); + // Saved as a file of its own: it keeps the event's periods. + await ev(tab, "window.__pick = 'periods.timeline'"); + await chrome.send('Input.dispatchKeyEvent', { type: 'keyDown', key: 'S', code: 'KeyS', windowsVirtualKeyCode: 83, modifiers: 10 }, tab); + await chrome.until(tab, "document.getElementById('dirty').hidden"); + const attachedZip = await core.openZip(core.bytesSource(await opfsBytes(tab, 'periods.timeline'))); + const attachedJson = JSON.parse(await attachedZip.text(attachedZip.get('timeline.json'))); + check('saved, the file keeps the event’s periods', attachedJson.items.find((i) => i.id === 'wright').periods, ['orville', 'aviation-age']); + await key('e', 'KeyE', 69, 'e'); + // New → the settings form on an empty file (dates, scale, a pasted cover) → an event with a pasted picture → save. await chrome.click(tab, '#home'); diff --git a/tests/model.mjs b/tests/model.mjs index 9b836c0..3e2757f 100644 --- a/tests/model.mjs +++ b/tests/model.mjs @@ -1,7 +1,7 @@ /** timeline.json: validation with exact warnings, forward compatibility, deterministic output (Task §3, §11). */ import { checker, load } from '../tools/load.mjs'; -const { parseDoc, serializeDoc, colorOf, rankOf, extentOf, usedImages, missingImages, ModelError, ID_PATTERN, parseMarkdown, plainText, dayOf, compareItems, inTimeOrder } = await load('core/model', 'core/markdown', 'core/dates'); +const { parseDoc, serializeDoc, colorOf, rankOf, extentOf, usedImages, missingImages, ModelError, ID_PATTERN, parseMarkdown, plainText, dayOf, compareItems, inTimeOrder, periodHolds, periodsAt, eventsOf, detachFrom } = await load('core/model', 'core/markdown', 'core/dates'); const { check, done } = checker(); const good = { @@ -311,4 +311,61 @@ for (const [name, json, expected] of /** @type {[string, unknown, string][]} */ check('inTimeOrder sorts as compareItems does', inTimeOrder(items).map((i) => i.id), [...items].sort(compareItems).map((i) => i.id)); } + +{ + // An event attached to periods, one or several. + const base = { format: 'timeline', version: 1, meta: { id: 'p', kind: 'history' }, title: 'P' }; + const items = [ + // The event comes before its periods in the list: the links are checked once every item is read. + { id: 'sputnik', kind: 'event', start: { y: 1957, m: 10, d: 4 }, title: 'Sputnik', periods: ['race', 'cold'] }, + { id: 'race', kind: 'period', start: { y: 1957, m: 10 }, end: { y: 1975 }, title: 'Space race' }, + // A period named twice is kept once. + { id: 'moon', kind: 'event', start: { y: 1969 }, title: 'Moon', periods: ['race', 'race'] }, + { id: 'war', kind: 'period', start: { y: 1939 }, end: { y: 1945 }, title: 'War' }, + { id: 'cold', kind: 'period', start: { y: 1947 }, end: { y: 1991 }, title: 'Cold war' }, + { id: 'none', kind: 'event', start: { y: 1960 }, title: 'None', periods: [] }, + ]; + const { doc, warnings } = parseDoc({ ...base, items }); + check('period links read cleanly', warnings, []); + check('the links are kept, in the order given, each once', doc.items.filter((i) => i.periods).map((i) => [i.id, i.periods]), [['sputnik', ['race', 'cold']], ['moon', ['race']]]); + check('…an empty list is no list', 'periods' in doc.items.find((i) => i.id === 'none'), false); + const json = JSON.parse(serializeDoc(doc)); + check('…and written: periods after the tags', Object.keys(json.items.find((i) => i.id === 'sputnik')), ['id', 'kind', 'start', 'title', 'periods']); + check('an empty list is not written', 'periods' in json.items.find((i) => i.id === 'none'), false); + check('the round trip is stable', serializeDoc(parseDoc(json).doc), serializeDoc(doc)); + + const bad = parseDoc({ + ...base, + items: [ + ...items, + { id: 'lost', kind: 'event', start: { y: 1960 }, title: 'Lost', periods: ['nowhere', 'race'] }, + { id: 'era-link', kind: 'event', start: { y: 1960 }, title: 'To an era', periods: ['jet'] }, + { id: 'jet', kind: 'era', start: { y: 1950 }, end: { y: 1990 }, title: 'Jet age' }, + { id: 'sub', kind: 'period', start: { y: 1960 }, end: { y: 1961 }, title: 'Sub', periods: ['race'] }, + { id: 'single', kind: 'event', start: { y: 1960 }, title: 'Single', periods: 'race' }, + { id: 'mixed', kind: 'event', start: { y: 1960 }, title: 'Mixed', periods: ['cold', 7] }, + ], + }); + check( + 'a link to no period, to an era, from a period; not a list, not an id — each left out', + bad.warnings.map((w) => w.path).sort(), + ['items[6].periods[0]', 'items[7].periods[0]', 'items[9].periods', 'items[10].periods', 'items[11].periods[1]'].sort(), + ); + check('…the good links beside a bad one stay, and the items themselves', [bad.doc.items.find((i) => i.id === 'lost').periods, bad.doc.items.find((i) => i.id === 'mixed').periods, bad.doc.items.length], [['race'], ['cold'], 12]); + + const race = doc.items.find((i) => i.id === 'race'); + // Noon by the local clock: the same day in every time zone. + const now = new Date(2026, 9, 13, 12); + check('a period takes in a date whose span meets its own', [{ y: 1957 }, { y: 1957, m: 9 }, { y: 1957, m: 10, d: 1 }, { y: 1975, m: 12, d: 31 }, { y: 1976 }, { y: 1956 }].map((w) => periodHolds(race, w, now)), [true, false, true, true, false, false]); + check('…an event or an era takes in nothing', [periodHolds(doc.items.find((i) => i.id === 'moon'), { y: 1969 }, now)], [false]); + const open = { id: 'open', kind: 'period', start: { y: 2000 }, end: { now: true }, title: 'Open' }; + check('…a period to this day takes in today, not tomorrow’s year', [periodHolds(open, { y: 2026, m: 10, d: 13 }, now), periodHolds(open, { y: 2027 }, now)], [true, false]); + check('the periods a date falls within, in time order', periodsAt(doc, { y: 1944 }, now).map((i) => i.id), ['war']); + check('…several where they overlap', periodsAt(doc, { y: 1969 }, now).map((i) => i.id), ['cold', 'race']); + check('…none for a date outside them all', periodsAt(doc, { y: 1946 }, now), []); + check('a period’s events, in time order: an event in two periods is in both', [eventsOf(doc, 'race').map((i) => i.id), eventsOf(doc, 'cold').map((i) => i.id)], [['sputnik', 'moon'], ['sputnik']]); + const sputnik = doc.items.find((i) => i.id === 'sputnik'); + check('detached from one period, an event keeps the others; from its last, it has none', [detachFrom(sputnik, 'race').periods, 'periods' in detachFrom(detachFrom(sputnik, 'race'), 'cold'), sputnik.periods], [['cold'], false, ['race', 'cold']]); +} + done('model');