Skip to content
Open
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
7 changes: 6 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
3 changes: 2 additions & 1 deletion docs/format.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
8 changes: 7 additions & 1 deletion docs/readme/README.ru.md
Original file line number Diff line number Diff line change
Expand Up @@ -65,7 +65,13 @@ Timeline открывает файлы `.timeline` — по одному на х
становится тёмным или светлым, чтобы читаться на нём) и **форма**: прямоугольная или
**круглая** — медальон с картинкой и названием под ним или круг с названием внутри, ровно
над своей точкой. У периода картинок нет: фото, брошенные на его полосу, становятся
событиями.
событиями. Событие можно **привязать к периодам** — жизням, правлениям, войнам, ко всем,
к которым оно относится: в его окне галочками отмечаются периоды из тех, в которые входит
его дата, и список следует за датой, пока её вводят. В подробностях каждого периода —
список его событий, каждое — шаг к нему; «Добавить в него событие» создаёт уже
привязанное. Если новые даты периода не включают событие, оно отвязывается от этого
периода; при удалении периода — тоже; остальные его периоды остаются (одна отмена
возвращает всё).
- **Тесные места**: карточка никогда не сжимается и не прячется из-за нехватки места. Где
карточки не помещаются рядом, они ложатся друг на друга — более позднее событие поверх
раннего, а карточка под указателем поднимается наверх. Скрывает карточки только
Expand Down
58 changes: 56 additions & 2 deletions src/app/details.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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';
Expand All @@ -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;
Expand Down Expand Up @@ -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]));
Expand All @@ -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')));
}
Expand Down
9 changes: 8 additions & 1 deletion src/app/editing.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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';
Expand Down Expand Up @@ -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();
Expand Down
64 changes: 62 additions & 2 deletions src/app/editor.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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';
Expand Down Expand Up @@ -149,6 +149,46 @@ export async function openEditor(existing: Item | null, defaults: Partial<Item>
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;
Expand Down Expand Up @@ -329,6 +369,7 @@ export async function openEditor(existing: Item | null, defaults: Partial<Item>
// 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' });
Expand Down Expand Up @@ -406,6 +447,7 @@ export async function openEditor(existing: Item | null, defaults: Partial<Item>
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,
Expand Down Expand Up @@ -461,6 +503,10 @@ export async function openEditor(existing: Item | null, defaults: Partial<Item>
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;
Expand Down Expand Up @@ -530,7 +576,17 @@ export async function openEditor(existing: Item | null, defaults: Partial<Item>
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);
Expand All @@ -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 };
Expand Down
1 change: 1 addition & 0 deletions src/app/reading.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down
2 changes: 2 additions & 0 deletions src/app/state.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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;
};
Expand Down
Loading