chroniko 0.3.1 → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -2,6 +2,20 @@
2
2
 
3
3
  All notable changes to Chroniko are documented in this file. The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/), and the project follows [Semantic Versioning](https://semver.org/).
4
4
 
5
+ ## [0.4.0] - 2026-10-28
6
+
7
+ ### Added
8
+
9
+ - `addEvents(events)`, `updateEvent(id, patch)` and `removeEvents(ids)`: change some events without replacing them all with `setEvents`. The view and selection are kept. `addEvents` returns the added events' ids, and adds none of them if any is invalid. Events added later than all others are packed into the existing lanes, so the lanes already shown don't move. The legend, tag bar and story are redrawn at most once per animation frame.
10
+ - Events added without an `id` continue the position numbering from `setEvents`, so adding events never changes existing generated ids.
11
+ - An API reference in [`docs/API.md`](docs/API.md), linked from the README.
12
+ - The example page has a form under the timeline that adds events, and edits or deletes the event last selected in the timeline.
13
+
14
+ ### Changed
15
+
16
+ - `setEvents` calls `onSelectionChange` when selected events are no longer in the new list and so leave the selection, as `removeEvents` does. With `syncUrl`, the URL is updated too. Before, the selection changed without either.
17
+ - A category keeps its palette color for the timeline's lifetime. Before, every `setEvents` call assigned palette colors again from scratch, so a category could change color when the events changed.
18
+
5
19
  ## [0.3.1] - 2026-10-19
6
20
 
7
21
  ### Added
@@ -59,6 +73,7 @@ All notable changes to Chroniko are documented in this file. The format is based
59
73
 
60
74
  - Initial release.
61
75
 
76
+ [0.4.0]: https://github.com/ykyuen/chroniko/compare/0.3.1...0.4.0
62
77
  [0.3.1]: https://github.com/ykyuen/chroniko/compare/0.3.0...0.3.1
63
78
  [0.3.0]: https://github.com/ykyuen/chroniko/compare/0.2.1...0.3.0
64
79
  [0.2.1]: https://github.com/ykyuen/chroniko/compare/0.2.0...0.2.1
package/README.md CHANGED
@@ -5,7 +5,9 @@
5
5
 
6
6
  # Chroniko
7
7
 
8
- Render historical events on a single zoomable time axis. Plain HTML, CSS and JavaScript, with no dependencies. Here is the [demo](https://chroniko.ykyuen.info/philosophers-in-history/?lang=en).
8
+ Render historical events on a single zoomable time axis. Plain HTML, CSS and JavaScript, with no dependencies.
9
+
10
+ View the [demos](https://chroniko.ykyuen.info/).
9
11
 
10
12
  ## Install
11
13
 
@@ -32,13 +34,13 @@ The minified files can be loaded from jsDelivr without installing anything.
32
34
  <meta charset="utf-8">
33
35
  <meta name="viewport" content="width=device-width, initial-scale=1">
34
36
  <title>Chroniko</title>
35
- <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/chroniko@0.3.1/dist/chroniko.min.css">
37
+ <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/chroniko@0.4.0/dist/chroniko.min.css">
36
38
  </head>
37
39
  <body>
38
40
  <div id="timeline"></div>
39
41
 
40
42
  <script type="module">
41
- import { Chroniko } from 'https://cdn.jsdelivr.net/npm/chroniko@0.3.1/dist/chroniko.min.js';
43
+ import { Chroniko } from 'https://cdn.jsdelivr.net/npm/chroniko@0.4.0/dist/chroniko.min.js';
42
44
 
43
45
  const timeline = new Chroniko('#timeline', {
44
46
  events: [
@@ -75,6 +77,8 @@ If an event has no `id`, one is generated from its category and its 0-based posi
75
77
 
76
78
  Generated ids depend on position, so they change when events are inserted, removed or reordered. Give events an explicit `id` if you call `setEvents` more than once and want the selection to follow the same events.
77
79
 
80
+ Events passed to `addEvents` without an `id` continue the numbering: after `setEvents` with 5 events, the next event added gets position 5, then 6, and so on, even if some events were removed in between. So adding events never changes the ids of the ones already there.
81
+
78
82
  Ids must be unique. If two events end up with the same id, whether given or generated, `setEvents` (and the constructor) throws an error naming both events and leaves the timeline unchanged.
79
83
 
80
84
  ### Options
@@ -100,12 +104,31 @@ Ids must be unique. If two events end up with the same id, whether given or gene
100
104
 
101
105
  ### Methods
102
106
 
103
- `setEvents(events)`, `zoomTo(start, end)`, `zoomBy(factor)`, `panBy(px)`, `fit()`, `select(id)`, `deselect(id)`, `toggle(id)`, `clearSelection()`, `getSelection()`, `reveal(id)`, `getState()`, `setState(state)`, `destroy()`.
107
+ `setEvents(events)`, `addEvents(events)`, `updateEvent(id, patch)`, `removeEvents(ids)`, `zoomTo(start, end)`, `zoomBy(factor)`, `panBy(px)`, `fit()`, `select(id)`, `deselect(id)`, `toggle(id)`, `clearSelection()`, `getSelection()`, `reveal(id)`, `getState()`, `setState(state)`, `destroy()`.
108
+
109
+ See the [API reference](docs/API.md) for every method's parameters, return value and errors.
104
110
 
105
111
  `zoomTo(start, end)` takes the same date formats as events, or fractional years. `start` must be before `end`, or it throws. A span outside `minSpan` / `maxSpan` is clamped around the middle of the range. This also applies to the `start` / `end` options, `setState` and shared links.
106
112
 
107
113
  `reveal(id)` pans and zooms so the event is in view (a range fills the middle of the timeline; a point is centered at the current zoom), shows its category if hidden, scrolls the timeline onto the screen, focuses the event and briefly highlights it.
108
114
 
115
+ ### Updating events
116
+
117
+ `setEvents(events)` replaces every event. To change a few without starting over, use:
118
+
119
+ ```js
120
+ const [id] = timeline.addEvents({ title: 'Deploy started', start: '2026-10-28', category: 'deploy' });
121
+ timeline.updateEvent(id, { end: '2026-10-30' });
122
+ timeline.removeEvents(id);
123
+ ```
124
+
125
+ - `addEvents(events)` takes one event or an array and returns the added events' ids. It throws, naming the event, on an invalid date, a missing start or an id that is already used, and then adds none of them. An event without an `id` gets one as if it were appended to the `events` array (see [Event ids](#event-ids)), so existing ids never change.
126
+ - `updateEvent(id, patch)` merges `patch` into the event, e.g. `{ end: '1945-09-02' }`; a field set to `undefined` is removed. It throws if there is no event with that id, if the patch changes the id (remove the event and add it again instead), or if the result is invalid, and then leaves the event as it was.
127
+ - `removeEvents(ids)` takes one id or an array; unknown ids are ignored. Removed events leave the selection, and `onSelectionChange` is called if the selection changed.
128
+ - The view doesn't move, and selected events stay selected. Call `fit()` to show everything again.
129
+ - Events added later than all others keep the lanes of those already shown. An earlier event, an update or a removal rearranges the lanes.
130
+ - The legend, tag bar and story are redrawn once per animation frame, however many calls were made in it, so adding events one at a time is cheap.
131
+
109
132
  ### Sharing
110
133
 
111
134
  `getState()` returns `{ start, end, selected, hidden }`: the visible range in fractional years (e.g. `1453.5` is mid-1453; negative is BCE), the selected event ids in chronological order, and the hidden categories. `setState(state)` restores it. Every field is optional, so `setState({ selected: ['ww2'] })` changes only the selection; unknown ids are ignored. Use these to save a story yourself, for example in `localStorage` or your own URL format.
@@ -186,7 +209,7 @@ Each event's color is picked in this order:
186
209
 
187
210
  1. The event's own `color` field.
188
211
  2. The color of its category in the `colors` option.
189
- 3. A color from the built-in palette. Each category without a configured color gets the next palette color that isn't already used in `colors`. Events without a category use the first palette color.
212
+ 3. A color from the built-in palette. Each category without a configured color gets the next palette color that isn't already used in `colors`, and keeps it for the timeline's lifetime, so adding or replacing events never recolors a category. Events without a category use the first palette color.
190
213
 
191
214
  ```js
192
215
  new Chroniko('#timeline', {
@@ -1 +1 @@
1
- const e={en:{zoomIn:"Zoom in",zoomOut:"Zoom out",fit:"Fit",dimUnselected:"Dim unselected events",largerText:"Larger text",categories:"Categories",ctrlKey:"Ctrl",viewport:e=>`Timeline. Drag or use arrow keys to pan; press + and −, ${e}+scroll or pinch to zoom.`,hint:e=>`${e} + scroll to zoom, or click the timeline first`,selectedEvents:"Selected events",clearAll:"Clear all",placeholder:"Click an event to add it here.",showOnTimeline:"Show on timeline",readMore:"Read more ↗",tags:"Tags",remove:e=>`Remove ${e} from selection`,endOf:e=>`End of ${e}`,lasted:e=>`lasted ${e}`,endsAria:(e,t,s)=>`${e} ends ${t}${s?`, after ${s}`:""}. Go to event`,months:["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],year:e=>e<0?-e+" BCE":String(e),month:(e,t)=>`${e} ${t}`,day:(e,t,s)=>`${e} ${t} ${s}`,units:{year:{one:"# year",other:"# years"},month:{one:"# month",other:"# months"},day:{one:"# day",other:"# days"}},unitJoin:", ",lessThan:{year:"less than a year",month:"less than a month",day:"less than a day"}},"zh-Hant":{zoomIn:"放大",zoomOut:"縮小",fit:"全覽",dimUnselected:"淡化未選事件",largerText:"放大文字",categories:"類別",ctrlKey:"Ctrl",viewport:e=>`時間軸。拖曳或使用方向鍵平移;按 + 和 −、${e} + 滾輪或雙指縮放。`,hint:e=>`${e} + 滾輪縮放,或先點擊時間軸`,selectedEvents:"已選事件",clearAll:"全部清除",placeholder:"點擊事件以加入此處。",showOnTimeline:"在時間軸上顯示",readMore:"了解更多 ↗",tags:"標籤",remove:e=>`從已選事件中移除「${e}」`,endOf:e=>`${e}結束`,lasted:e=>`歷時${e}`,endsAria:(e,t,s)=>`${e}於${t}結束${s?`,歷時${s}`:""}。前往事件`,months:["1月","2月","3月","4月","5月","6月","7月","8月","9月","10月","11月","12月"],year:e=>e<0?`公元前${-e}年`:`${e}年`,month:(e,t)=>`${t}${e}`,day:(e,t,s)=>`${s}${t}${e}日`,units:{year:{other:"#年"},month:{other:"#個月"},day:{other:"#天"}},unitJoin:"",lessThan:{year:"不足一年",month:"不足一個月",day:"不足一天"}},"zh-Hans":{zoomIn:"放大",zoomOut:"缩小",fit:"全览",dimUnselected:"淡化未选事件",largerText:"放大文字",categories:"类别",ctrlKey:"Ctrl",viewport:e=>`时间轴。拖动或使用方向键平移;按 + 和 −、${e} + 滚轮或双指缩放。`,hint:e=>`${e} + 滚轮缩放,或先点击时间轴`,selectedEvents:"已选事件",clearAll:"全部清除",placeholder:"点击事件以添加到此处。",showOnTimeline:"在时间轴上显示",readMore:"了解更多 ↗",tags:"标签",remove:e=>`从已选事件中移除“${e}”`,endOf:e=>`${e}结束`,lasted:e=>`历时${e}`,endsAria:(e,t,s)=>`${e}于${t}结束${s?`,历时${s}`:""}。前往事件`,months:["1月","2月","3月","4月","5月","6月","7月","8月","9月","10月","11月","12月"],year:e=>e<0?`公元前${-e}年`:`${e}年`,month:(e,t)=>`${t}${e}`,day:(e,t,s)=>`${s}${t}${e}日`,units:{year:{other:"#年"},month:{other:"#个月"},day:{other:"#天"}},unitJoin:"",lessThan:{year:"不足一年",month:"不足一个月",day:"不足一天"}},yue:{zoomIn:"放大",zoomOut:"縮細",fit:"睇晒",dimUnselected:"淡化未揀嘅",largerText:"大啲字",categories:"類別",ctrlKey:"Ctrl",viewport:e=>`時間軸。拖或者用方向鍵左右移;撳 + 同 −、${e} + 碌滾輪或者用兩隻手指縮放。`,hint:e=>`${e} + 碌滾輪就可以縮放,或者先撳一下時間軸`,selectedEvents:"揀咗嘅事件",clearAll:"清晒",placeholder:"撳一下事件就會加入呢度。",showOnTimeline:"喺時間軸度睇",readMore:"睇多啲 ↗",tags:"標籤",remove:e=>`移走「${e}」`,endOf:e=>`${e}完結`,lasted:e=>`維持咗${e}`,endsAria:(e,t,s)=>`${e}喺${t}完結${s?`,維持咗${s}`:""}。去返個事件`,months:["1月","2月","3月","4月","5月","6月","7月","8月","9月","10月","11月","12月"],year:e=>e<0?`公元前${-e}年`:`${e}年`,month:(e,t)=>`${t}${e}`,day:(e,t,s)=>`${s}${t}${e}日`,units:{year:{other:"#年"},month:{other:"#個月"},day:{other:"#日"}},unitJoin:"",lessThan:{year:"唔夠一年",month:"唔夠一個月",day:"唔夠一日"}},ja:{zoomIn:"拡大",zoomOut:"縮小",fit:"全体表示",dimUnselected:"選択外を暗く",largerText:"文字を大きく",categories:"カテゴリ",ctrlKey:"Ctrl",viewport:e=>`タイムライン。ドラッグまたは矢印キーで移動し、+ と −、${e} + スクロール、またはピンチで拡大・縮小します。`,hint:e=>`${e} + スクロールで拡大・縮小、または先にタイムラインをクリック`,selectedEvents:"選択した出来事",clearAll:"すべて解除",placeholder:"出来事をクリックするとここに追加されます。",showOnTimeline:"タイムラインで表示",readMore:"詳しく見る ↗",tags:"タグ",remove:e=>`「${e}」を選択から外す`,endOf:e=>`${e}の終わり`,lasted:e=>`期間:${e}`,endsAria:(e,t,s)=>`${e}は${t}に終了${s?`(期間:${s})`:""}。出来事へ移動`,months:["1月","2月","3月","4月","5月","6月","7月","8月","9月","10月","11月","12月"],year:e=>e<0?`紀元前${-e}年`:`${e}年`,month:(e,t)=>`${t}${e}`,day:(e,t,s)=>`${s}${t}${e}日`,units:{year:{other:"#年"},month:{other:"#か月"},day:{other:"#日"}},unitJoin:"",lessThan:{year:"1年未満",month:"1か月未満",day:"1日未満"}},ko:{zoomIn:"확대",zoomOut:"축소",fit:"전체 보기",dimUnselected:"선택 안 된 항목 흐리게",largerText:"글자 크게",categories:"분류",ctrlKey:"Ctrl",viewport:e=>`타임라인. 드래그하거나 화살표 키로 이동하고, + 와 −, ${e}+스크롤 또는 핀치로 확대/축소합니다.`,hint:e=>`${e} + 스크롤로 확대/축소하거나 먼저 타임라인을 클릭하세요`,selectedEvents:"선택한 사건",clearAll:"모두 지우기",placeholder:"사건을 클릭하면 여기에 추가됩니다.",showOnTimeline:"타임라인에서 보기",readMore:"더 보기 ↗",tags:"태그",remove:e=>`선택에서 ${e} 제거`,endOf:e=>`${e} 종료`,lasted:e=>`기간: ${e}`,endsAria:(e,t,s)=>`${e} 종료: ${t}${s?`, 기간 ${s}`:""}. 사건으로 이동`,months:["1월","2월","3월","4월","5월","6월","7월","8월","9월","10월","11월","12월"],year:e=>e<0?`기원전 ${-e}년`:`${e}년`,month:(e,t)=>`${t} ${e}`,day:(e,t,s)=>`${s} ${t} ${e}일`,units:{year:{other:"#년"},month:{other:"#개월"},day:{other:"#일"}},unitJoin:" ",lessThan:{year:"1년 미만",month:"1개월 미만",day:"1일 미만"}},fr:{zoomIn:"Zoom avant",zoomOut:"Zoom arrière",fit:"Ajuster",dimUnselected:"Atténuer les non sélectionnés",largerText:"Texte plus grand",categories:"Catégories",ctrlKey:"Ctrl",viewport:e=>`Frise chronologique. Faites glisser ou utilisez les flèches pour vous déplacer ; appuyez sur + et −, ${e}+molette ou pincez pour zoomer.`,hint:e=>`${e} + molette pour zoomer, ou cliquez d’abord sur la frise`,selectedEvents:"Événements sélectionnés",clearAll:"Tout effacer",placeholder:"Cliquez sur un événement pour l’ajouter ici.",showOnTimeline:"Afficher sur la frise",readMore:"En savoir plus ↗",tags:"Étiquettes",remove:e=>`Retirer ${e} de la sélection`,endOf:e=>`Fin : ${e}`,lasted:e=>`durée : ${e}`,endsAria:(e,t,s)=>`Fin de « ${e} » : ${t}${s?`, durée ${s}`:""}. Aller à l’événement`,months:["janv.","févr.","mars","avr.","mai","juin","juil.","août","sept.","oct.","nov.","déc."],year:e=>e<0?-e+" av. J.-C.":String(e),month:(e,t)=>`${e} ${t}`,day:(e,t,s)=>`${1===e?"1er":e} ${t} ${s}`,units:{year:{one:"# an",other:"# ans"},month:{one:"# mois",other:"# mois"},day:{one:"# jour",other:"# jours"}},unitJoin:" et ",lessThan:{year:"moins d’un an",month:"moins d’un mois",day:"moins d’un jour"}},de:{zoomIn:"Vergrößern",zoomOut:"Verkleinern",fit:"Einpassen",dimUnselected:"Nicht ausgewählte abblenden",largerText:"Größere Schrift",categories:"Kategorien",ctrlKey:"Strg",viewport:e=>`Zeitleiste. Zum Verschieben ziehen oder die Pfeiltasten verwenden; zum Zoomen + und −, ${e}+Mausrad oder zwei Finger verwenden.`,hint:e=>`${e} + Mausrad zum Zoomen, oder zuerst auf die Zeitleiste klicken`,selectedEvents:"Ausgewählte Ereignisse",clearAll:"Alle entfernen",placeholder:"Klicken Sie auf ein Ereignis, um es hier hinzuzufügen.",showOnTimeline:"Auf der Zeitleiste anzeigen",readMore:"Mehr erfahren ↗",tags:"Schlagwörter",remove:e=>`${e} aus der Auswahl entfernen`,endOf:e=>`Ende: ${e}`,lasted:e=>`Dauer: ${e}`,endsAria:(e,t,s)=>`Ende von ${e}: ${t}${s?`, Dauer ${s}`:""}. Zum Ereignis`,months:["Jan.","Feb.","März","Apr.","Mai","Juni","Juli","Aug.","Sept.","Okt.","Nov.","Dez."],year:e=>e<0?-e+" v. Chr.":String(e),month:(e,t)=>`${e} ${t}`,day:(e,t,s)=>`${e}. ${t} ${s}`,units:{year:{one:"# Jahr",other:"# Jahre"},month:{one:"# Monat",other:"# Monate"},day:{one:"# Tag",other:"# Tage"}},unitJoin:", ",lessThan:{year:"weniger als ein Jahr",month:"weniger als ein Monat",day:"weniger als ein Tag"}},it:{zoomIn:"Ingrandisci",zoomOut:"Riduci",fit:"Adatta",dimUnselected:"Attenua i non selezionati",largerText:"Testo più grande",categories:"Categorie",ctrlKey:"Ctrl",viewport:e=>`Linea del tempo. Trascina o usa i tasti freccia per spostarti; premi + e −, ${e}+rotellina o pizzica per lo zoom.`,hint:e=>`${e} + rotellina per lo zoom, oppure fai prima clic sulla linea del tempo`,selectedEvents:"Eventi selezionati",clearAll:"Cancella tutto",placeholder:"Fai clic su un evento per aggiungerlo qui.",showOnTimeline:"Mostra sulla linea del tempo",readMore:"Scopri di più ↗",tags:"Tag",remove:e=>`Rimuovi ${e} dalla selezione`,endOf:e=>`Fine: ${e}`,lasted:e=>`durata: ${e}`,endsAria:(e,t,s)=>`Fine di ${e}: ${t}${s?`, durata ${s}`:""}. Vai all’evento`,months:["gen","feb","mar","apr","mag","giu","lug","ago","set","ott","nov","dic"],year:e=>e<0?-e+" a.C.":String(e),month:(e,t)=>`${e} ${t}`,day:(e,t,s)=>`${e} ${t} ${s}`,units:{year:{one:"# anno",other:"# anni"},month:{one:"# mese",other:"# mesi"},day:{one:"# giorno",other:"# giorni"}},unitJoin:" e ",lessThan:{year:"meno di un anno",month:"meno di un mese",day:"meno di un giorno"}},es:{zoomIn:"Acercar",zoomOut:"Alejar",fit:"Ajustar",dimUnselected:"Atenuar los no seleccionados",largerText:"Texto más grande",categories:"Categorías",ctrlKey:"Ctrl",viewport:e=>`Línea de tiempo. Arrastra o usa las flechas para desplazarte; pulsa + y −, ${e}+rueda o pellizca para hacer zoom.`,hint:e=>`${e} + rueda para hacer zoom, o haz clic primero en la línea de tiempo`,selectedEvents:"Eventos seleccionados",clearAll:"Borrar todo",placeholder:"Haz clic en un evento para añadirlo aquí.",showOnTimeline:"Mostrar en la línea de tiempo",readMore:"Más información ↗",tags:"Etiquetas",remove:e=>`Quitar ${e} de la selección`,endOf:e=>`Fin: ${e}`,lasted:e=>`duración: ${e}`,endsAria:(e,t,s)=>`Fin de ${e}: ${t}${s?`, duración ${s}`:""}. Ir al evento`,months:["ene","feb","mar","abr","may","jun","jul","ago","sept","oct","nov","dic"],year:e=>e<0?-e+" a. C.":String(e),month:(e,t)=>`${e} ${t}`,day:(e,t,s)=>`${e} ${t} ${s}`,units:{year:{one:"# año",other:"# años"},month:{one:"# mes",other:"# meses"},day:{one:"# día",other:"# días"}},unitJoin:" y ",lessThan:{year:"menos de un año",month:"menos de un mes",day:"menos de un día"}},pt:{zoomIn:"Ampliar",zoomOut:"Reduzir",fit:"Ajustar",dimUnselected:"Escurecer os não selecionados",largerText:"Texto maior",categories:"Categorias",ctrlKey:"Ctrl",viewport:e=>`Linha do tempo. Arraste ou use as setas para deslocar; use + e −, ${e}+roda ou o gesto de pinça para ampliar ou reduzir.`,hint:e=>`${e} + roda para ampliar ou reduzir, ou clique primeiro na linha do tempo`,selectedEvents:"Eventos selecionados",clearAll:"Limpar tudo",placeholder:"Clique num evento para adicioná-lo aqui.",showOnTimeline:"Mostrar na linha do tempo",readMore:"Saiba mais ↗",tags:"Etiquetas",remove:e=>`Remover ${e} da seleção`,endOf:e=>`Fim: ${e}`,lasted:e=>`duração: ${e}`,endsAria:(e,t,s)=>`Fim de ${e}: ${t}${s?`, duração ${s}`:""}. Ir para o evento`,months:["jan","fev","mar","abr","mai","jun","jul","ago","set","out","nov","dez"],year:e=>e<0?-e+" a.C.":String(e),month:(e,t)=>`${e} ${t}`,day:(e,t,s)=>`${e} ${t} ${s}`,units:{year:{one:"# ano",other:"# anos"},month:{one:"# mês",other:"# meses"},day:{one:"# dia",other:"# dias"}},unitJoin:" e ",lessThan:{year:"menos de um ano",month:"menos de um mês",day:"menos de um dia"}},pl:{zoomIn:"Powiększ",zoomOut:"Pomniejsz",fit:"Dopasuj",dimUnselected:"Przyciemnij niezaznaczone",largerText:"Większy tekst",categories:"Kategorie",ctrlKey:"Ctrl",viewport:e=>`Oś czasu. Przeciągnij lub użyj klawiszy strzałek, aby przesuwać; naciśnij + i −, ${e}+kółko myszy lub zsuń palce, aby zmienić powiększenie.`,hint:e=>`${e} + kółko myszy, aby zmienić powiększenie, lub najpierw kliknij oś czasu`,selectedEvents:"Wybrane wydarzenia",clearAll:"Wyczyść wszystko",placeholder:"Kliknij wydarzenie, aby dodać je tutaj.",showOnTimeline:"Pokaż na osi czasu",readMore:"Więcej ↗",tags:"Tagi",remove:e=>`Usuń ${e} z wyboru`,endOf:e=>`Koniec: ${e}`,lasted:e=>`czas trwania: ${e}`,endsAria:(e,t,s)=>`Koniec: ${e}, ${t}${s?`, czas trwania ${s}`:""}. Przejdź do wydarzenia`,months:["sty","lut","mar","kwi","maj","cze","lip","sie","wrz","paź","lis","gru"],year:e=>e<0?-e+" p.n.e.":String(e),month:(e,t)=>`${e} ${t}`,day:(e,t,s)=>`${e} ${t} ${s}`,units:{year:{one:"# rok",few:"# lata",many:"# lat",other:"# roku"},month:{one:"# miesiąc",few:"# miesiące",many:"# miesięcy",other:"# miesiąca"},day:{one:"# dzień",few:"# dni",many:"# dni",other:"# dnia"}},unitJoin:", ",lessThan:{year:"mniej niż rok",month:"mniej niż miesiąc",day:"mniej niż dzień"}},nl:{zoomIn:"Inzoomen",zoomOut:"Uitzoomen",fit:"Passend maken",dimUnselected:"Niet-geselecteerde dimmen",largerText:"Grotere tekst",categories:"Categorieën",ctrlKey:"Ctrl",viewport:e=>`Tijdlijn. Sleep of gebruik de pijltjestoetsen om te verschuiven; druk op + en −, ${e}+scrollen of knijp om te zoomen.`,hint:e=>`${e} + scrollen om te zoomen, of klik eerst op de tijdlijn`,selectedEvents:"Geselecteerde gebeurtenissen",clearAll:"Alles wissen",placeholder:"Klik op een gebeurtenis om die hier toe te voegen.",showOnTimeline:"Tonen op tijdlijn",readMore:"Meer lezen ↗",tags:"Tags",remove:e=>`${e} uit selectie verwijderen`,endOf:e=>`Einde: ${e}`,lasted:e=>`duur: ${e}`,endsAria:(e,t,s)=>`Einde van ${e}: ${t}${s?`, duur ${s}`:""}. Ga naar gebeurtenis`,months:["jan","feb","mrt","apr","mei","jun","jul","aug","sep","okt","nov","dec"],year:e=>e<0?-e+" v.Chr.":String(e),month:(e,t)=>`${e} ${t}`,day:(e,t,s)=>`${e} ${t} ${s}`,units:{year:{one:"# jaar",other:"# jaar"},month:{one:"# maand",other:"# maanden"},day:{one:"# dag",other:"# dagen"}},unitJoin:" en ",lessThan:{year:"minder dan een jaar",month:"minder dan een maand",day:"minder dan een dag"}}},t=["#4e79a7","#e15759","#59a14f","#f28e2b","#b07aa1","#76b7b2","#edc948","#9c755f"],s={year:1,month:1/12,day:1/372},n=[1/12,1/4,...[1,10,100,1e3,1e4,1e5].flatMap(e=>[e,2*e,5*e])];function i(t){if(null==t||""===t)return null;const s="object"==typeof t?JSON.stringify(t):"string"==typeof t?`"${t}"`:String(t);let n,i,r;if("number"==typeof t){if(!Number.isFinite(t))throw new Error(`Chroniko: invalid date ${s}`);return a(t)}if("object"==typeof t)({year:n,month:i,day:r}=t);else{const e=/^(-?\d+)(?:-(\d{1,2}))?(?:-(\d{1,2}))?$/.exec(String(t).trim());if(!e)throw new Error(`Chroniko: cannot parse date ${s}`);[n,i,r]=[Number(e[1]),e[2]&&Number(e[2]),e[3]&&Number(e[3])]}const l=function(t,s,n){if(!Number.isInteger(t))return"year must be a whole number";if(null!=s&&!(Number.isInteger(s)&&s>=1&&s<=12))return"month must be 1–12";if(null!=n){if(null==s)return"a day needs a month";if(!(Number.isInteger(n)&&n>=1&&n<=o[s-1]))return`day must be 1–${o[s-1]} in ${e.en.months[s-1]}`}return null}(n,i??null,r??null);if(l)throw new Error(`Chroniko: invalid date ${s}: ${l}`);return a(n,i,r)}const o=[31,29,31,30,31,30,31,31,30,31,30,31];function a(e,t,s){let n=e;t&&(n+=(t-1)/12),s&&(n+=(s-1)/372);return{year:e,month:t||null,day:s||null,precision:s?"day":t?"month":"year",value:n}}const r=new Map;function l(t,s){if(!Object.hasOwn(e,t)){const s=Object.keys(e).map(e=>`'${e}'`).join(", ");throw new Error(`Chroniko: language must be one of ${s}, got ${JSON.stringify(t)}`)}if(!s&&r.has(t))return r.get(t);const n={...e.en,...e[t],...s,number:new Intl.NumberFormat(t),plural:new Intl.PluralRules(t)};return s||r.set(t,n),n}function d(e,t="en"){return l(t).year(e)}function c(e,t="en"){return h(e,l(t))}function h(e,t){const s=t.year(e.year);return e.day?t.day(e.day,t.months[e.month-1],s):e.month?t.month(t.months[e.month-1],s):s}function m(e,t,s="en"){return u(e,t,l(s))}function u(e,t,s){const n=e=>e<0?e+1:e,i=[e.precision,t.precision],o=i.includes("year")?"year":i.includes("month")?"month":"day";let a=n(t.year)-n(e.year),r="year"===o?0:t.month-e.month,l="day"===o?t.day-e.day:0;if(l<0&&(r-=1,l=Math.max(function(e,t){if(0===t)return 31;return[31,e%4==0&&e%100!=0||e%400==0?29:28,31,30,31,30,31,31,30,31,30,31][t-1]}(n(t.year),t.month-1)-e.day,0)+t.day),r<0&&(a-=1,r+=12),a<0)return"";const d=[["year",a],["month",r],["day",l]],c=d.findIndex(([,e])=>e>0);if(c<0)return s.lessThan[o];const h=([e,t])=>{const n=s.units[e];return(n[s.plural.select(t)]??n.other).replace("#",s.number.format(t))},m=d[c+1];return m?.[1]>0?`${h(d[c])}${s.unitJoin}${h(m)}`:h(d[c])}function g(e,t){const s=h(e.start,t);return e.end?`${s} – ${h(e.end,t)}`:s}function p(e,t){return`${String(e.category??"").trim().toLowerCase().replace(/\s+/g,"-")||"event"}-${t}`}function y(){const e=new Map;for(const t of location.hash.slice(1).split("&")){if(!t)continue;const s=t.indexOf("=");s<0?e.set(t,null):e.set(t.slice(0,s),t.slice(s+1))}return e}function $(e,t,s){if(t>=1)return s.year(Math.round(e));const n=Math.floor(e+1e-9),i=Math.round(12*(e-n))%12;return 0===i?s.year(n):s.months[i]}function f(e){return String(e).replace(/[&<>"']/g,e=>({"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;"}[e]))}class v{constructor(e,t={}){const s="string"==typeof e?document.querySelector(e):e;if(!s)throw new Error("Chroniko: container not found");this.options={minSpan:1/12,colors:{},storyPosition:"below",split:.6,dimToggle:!0,language:"en",categoryLabels:{},tagLabels:{},...t};const{storyPosition:n,split:i}=this.options;if("below"!==n&&"right"!==n)throw new Error(`Chroniko: storyPosition must be 'below' or 'right', got ${JSON.stringify(n)}`);if(!("number"==typeof i&&i>0&&i<1))throw new Error(`Chroniko: split must be a number between 0 and 1, got ${JSON.stringify(i)}`);this.m=l(this.options.language,this.options.uiText),this.items=[],this.hidden=new Set,this.selected=new Set,this.start=0,this.end=1,this._frame=0,this._build(s),this._bind(),this.setEvents(t.events??[]),null!=t.start&&null!=t.end?this.zoomTo(t.start,t.end):this.fit(),this.options.syncUrl&&(this._onHashChange=()=>this._readHash(),window.addEventListener("hashchange",this._onHashChange),this._readHash(),clearTimeout(this._hashTimer))}setEvents(e){const n=e.map((e,t)=>{const n=s=>{try{return i(e[s])}catch(n){const i=n.message.replace(/^Chroniko: /,"");throw new Error(`Chroniko: event "${e.title??t}" has an invalid ${s}: ${i}`)}},o=n("start");if(!o)throw new Error(`Chroniko: event "${e.title??t}" has no start date`);const a=n("end");return{event:e,id:String(e.id??p(e,t)),start:o,end:a,from:o.value,to:a?a.value+s[a.precision]:null,category:e.category??null,tags:[...new Set([e.tags??[]].flat().map(e=>String(e).trim()).filter(Boolean))]}}).sort((e,t)=>e.from-t.from),o=new Map;for(const e of n){const t=o.get(e.id);if(t)throw new Error(`Chroniko: events "${t.event.title}" and "${e.event.title}" share the id "${e.id}"; ids must be unique`);o.set(e.id,e)}this.items=n,this.categories=[...new Set(this.items.map(e=>e.category).filter(Boolean))];const a=new Set(Object.values(this.options.colors)),r=t.filter(e=>!a.has(e));let l=0;this.colorOf=new Map(this.categories.map(e=>[e,this.options.colors[e]??r[l++%r.length]??t[0]]));for(const e of this.items)e.color=e.event.color??this.colorOf.get(e.category)??t[0];const[d,c]=this._extent();this._dataSpan=c-d,this._measureLabels(),this._renderLegend(),this._renderTagbar(),this.selected=new Set(this.items.filter(e=>this.selected.has(e.id)).map(e=>e.id)),this._renderStory(),this._syncTags(),this._invalidateLayout()}zoomTo(e,t){const s=i(e)?.value,n=i(t)?.value;if(null==s||null==n)throw new Error("Chroniko: zoomTo needs both a start and an end");if(s>=n)throw new Error(`Chroniko: zoomTo start (${e}) must be before end (${t})`);const o=(s+n)/2,a=this._clampSpan(n-s);this._setView(o-a/2,o+a/2)}fit(){if(!this.items.length)return this._setView(0,2e3);const[e,t]=this._extent(),s=Math.max(t-e,1);this._setView(e-.04*s,t+.12*s)}zoomBy(e,t=.5){const s=this.end-this.start,n=this.start+s*t,i=this._clampSpan(s*e);this._setView(n-i*t,n-i*t+i)}panBy(e){const t=e/this._scale();this._setView(this.start+t,this.end+t)}select(e){e=String(e),!this.selected.has(e)&&this.items.some(t=>t.id===e)&&this._setSelection([...this.selected,e])}deselect(e){e=String(e),this.selected.has(e)&&this._setSelection([...this.selected].filter(t=>t!==e))}toggle(e){this.selected.has(String(e))?this.deselect(e):this.select(e)}clearSelection(){this.selected.size&&this._setSelection([])}getSelection(){return this.items.filter(e=>this.selected.has(e.id)).map(e=>e.event)}reveal(e){const t=this.items.find(t=>t.id===String(e));if(!t)return;t.category&&this.hidden.has(t.category)&&this._setHidden([...this.hidden].filter(e=>e!==t.category));const s=null!=t.to?(t.from+t.to)/2:t.from,n=null!=t.to?this._clampSpan((t.to-t.from)/.6):this.end-this.start;this._revealing={id:t.id,at:performance.now(),pending:!0},this._setView(s-n/2,s+n/2)}getState(){return{start:this.start,end:this.end,selected:this.items.filter(e=>this.selected.has(e.id)).map(e=>e.id),hidden:[...this.hidden]}}setState(e={}){if(null!=e.start&&null!=e.end&&this.zoomTo(e.start,e.end),e.hidden&&this._setHidden(e.hidden.map(String)),e.selected){const t=new Set(e.selected.map(String));this._setSelection(this.items.filter(e=>t.has(e.id)).map(e=>e.id))}}destroy(){cancelAnimationFrame(this._frame),clearTimeout(this._zoomTimer),clearTimeout(this._hintTimer),clearTimeout(this._hashTimer),this._onHashChange&&window.removeEventListener("hashchange",this._onHashChange),this._resizeObserver.disconnect(),document.fonts?.removeEventListener("loadingdone",this._onFontsLoaded),this.root.remove()}_build(e){this.root=document.createElement("div"),this.root.className="chroniko",this.root.lang=this.options.language,"right"===this.options.storyPosition&&(this.root.classList.add("ck-side"),this.root.style.setProperty("--ck-split",this.options.split)),this.options.dimToggle&&this.root.classList.add("ck-dim");const t=this.m,s=/Mac|iPhone|iPad/.test(navigator.userAgentData?.platform??navigator.platform)?"⌘":t.ctrlKey;this.root.innerHTML=`\n <div class="ck-layout">\n <div class="ck-main">\n <div class="ck-toolbar">\n <div class="ck-legend" role="group" aria-label="${f(t.categories)}"></div>\n <div class="ck-controls">\n <button type="button" data-action="zoom-in" aria-label="${f(t.zoomIn)}">+</button>\n <button type="button" data-action="zoom-out" aria-label="${f(t.zoomOut)}">−</button>\n <button type="button" data-action="fit">${f(t.fit)}</button>\n ${this.options.dimToggle?`<button type="button" data-action="dim" aria-pressed="true" aria-label="${f(t.dimUnselected)}">◐</button>`:""}\n ${this.options.textSizeToggle?`<button type="button" data-action="text-size" aria-pressed="false" aria-label="${f(t.largerText)}">Aa</button>`:""}\n </div>\n </div>\n <details class="ck-tagbar" hidden>\n <summary>${f(t.tags)} <span class="ck-count"></span></summary>\n <ul class="ck-tags" aria-label="${f(t.tags)}"></ul>\n </details>\n <div class="ck-viewport" tabindex="0" aria-label="${t.viewport(f(s))}">\n <div class="ck-grid"></div>\n <div class="ck-lanes"></div>\n <div class="ck-axis"></div>\n <div class="ck-hint" aria-hidden="true"></div>\n </div>\n </div>\n <section class="ck-story" aria-label="${f(t.selectedEvents)}" hidden></section>\n </div>`,e.append(this.root),this.legendEl=this.root.querySelector(".ck-legend"),this.tagbarEl=this.root.querySelector(".ck-tagbar"),this.viewport=this.root.querySelector(".ck-viewport"),this.gridEl=this.root.querySelector(".ck-grid"),this.lanesEl=this.root.querySelector(".ck-lanes"),this.axisEl=this.root.querySelector(".ck-axis"),this.storyEl=this.root.querySelector(".ck-story"),this.hintEl=this.root.querySelector(".ck-hint"),this.hintEl.innerHTML=t.hint(f(s))}_showHint(){this.hintEl.classList.add("ck-visible"),clearTimeout(this._hintTimer),this._hintTimer=setTimeout(()=>this.hintEl.classList.remove("ck-visible"),1500)}_bind(){const e=this.viewport;this.root.querySelector(".ck-controls").addEventListener("click",e=>{const t=e.target.closest("button")?.dataset.action;"zoom-in"===t?this.zoomBy(1/1.5):"zoom-out"===t?this.zoomBy(1.5):"fit"===t?this.fit():"dim"===t?this._toggleDim(e.target.closest("button")):"text-size"===t&&this._toggleTextSize(e.target.closest("button"))}),this.tagbarEl.addEventListener("click",e=>{const t=e.target.closest(".ck-tag");t&&this._toggleTag(t.dataset.tag,t)}),this.legendEl.addEventListener("click",e=>{const t=e.target.closest(".ck-legend-item")?.dataset.category;if(null==t)return;const s=new Set(this.hidden);s.has(t)?s.delete(t):s.add(t),this._setHidden(s)});const t=e=>{e.pointerType&&"mouse"!==e.pointerType||this._setHover(e.target.closest(".ck-event, .ck-card, .ck-end-jump")?.dataset.id??null)};for(const e of[this.lanesEl,this.storyEl])e.addEventListener("pointerover",t),e.addEventListener("focusin",t),e.addEventListener("pointerleave",()=>this._setHover(null)),e.addEventListener("focusout",()=>this._setHover(null));e.addEventListener("wheel",t=>{const s=1===t.deltaMode?16:2===t.deltaMode?e.clientWidth:1,n=t.deltaX*s,i=t.deltaY*s;if(Math.abs(n)>Math.abs(i))return t.preventDefault(),void this.panBy(n);t.ctrlKey||t.metaKey||e.contains(document.activeElement)?(t.preventDefault(),this._zooming=!0,clearTimeout(this._zoomTimer),this._zoomTimer=setTimeout(()=>{this._zooming=!1,this._scheduleRender()},150),this.zoomBy(Math.exp(.002*i),this._ratioAt(t.clientX))):this._showHint()},{passive:!1});const s=new Map;let n=null,i=null;const o=(e,t)=>{n={id:e,x:t,start:this.start,span:this.end-this.start,moved:!1}},a=()=>{const[e,t]=s.values();return{dist:Math.max(Math.hypot(e.x-t.x,e.y-t.y),1),ratio:this._ratioAt((e.x+t.x)/2)}},r=()=>{const{dist:e,ratio:t}=a(),s=this.end-this.start;i={dist:e,span:s,anchor:this.start+s*t}};e.addEventListener("pointerdown",t=>{if(0===t.button)if(s.set(t.pointerId,{x:t.clientX,y:t.clientY}),1===s.size)this._suppressClick=!1,o(t.pointerId,t.clientX);else if(2===s.size){for(const t of s.keys())e.setPointerCapture(t);r(),n=null,this._zooming=!0,e.classList.add("ck-dragging")}}),e.addEventListener("pointermove",t=>{const o=s.get(t.pointerId);if(!o)return;if(o.x=t.clientX,o.y=t.clientY,i){const{dist:e,ratio:t}=a(),s=this._clampSpan(i.span*i.dist/e),n=i.anchor-s*t;return void this._setView(n,n+s)}if(!n||t.pointerId!==n.id)return;const r=t.clientX-n.x;if(!n.moved){if(Math.abs(r)<4)return;n.moved=!0,e.setPointerCapture(t.pointerId),e.classList.add("ck-dragging")}const l=n.start-r/this._scale();this._setView(l,l+n.span)});const l=t=>{if(s.delete(t.pointerId)){if(i){if(s.size>=2)return void r();i=null,this._suppressClick=!0,this._zooming=!1,this._scheduleRender();const[e]=s;if(e)return o(e[0],e[1].x),void(n.moved=!0)}else n?.id===t.pointerId&&n.moved&&(this._suppressClick=!0);s.size||(n=null,e.classList.remove("ck-dragging"))}};e.addEventListener("pointerup",l),e.addEventListener("pointercancel",l),e.addEventListener("click",e=>{if(this._suppressClick)return void(this._suppressClick=!1);const t=e.target.closest(".ck-event")?.dataset.id;null!=t&&this.toggle(t)}),e.addEventListener("keydown",t=>{const s=.1*e.clientWidth,n={ArrowLeft:()=>this.panBy(-s),ArrowRight:()=>this.panBy(s),"+":()=>this.zoomBy(1/1.5),"=":()=>this.zoomBy(1/1.5),"-":()=>this.zoomBy(1.5),Escape:()=>this.clearSelection()};n[t.key]&&(t.preventDefault(),n[t.key]())}),this.storyEl.addEventListener("click",e=>{const t=e.target.closest(".ck-remove"),s=e.target.closest(".ck-end-jump"),n=e.target.closest(".ck-locate"),i=e.target.closest(".ck-tag");i?this._toggleTag(i.dataset.tag,i):t?this.deselect(t.dataset.id):s?this._jumpToCard(s.dataset.id):n?this.reveal(n.dataset.id):e.target.closest(".ck-clear")&&this.clearSelection()}),this._resizeObserver=new ResizeObserver(()=>this._scheduleRender()),this._resizeObserver.observe(e),this._onFontsLoaded=()=>{this._measureLabels(),this._invalidateLayout()},document.fonts?.addEventListener("loadingdone",this._onFontsLoaded)}_toggleTag(e,t){const s=new Set(this.items.filter(t=>t.tags.includes(e)).map(e=>e.id)),n=[...s].every(e=>this.selected.has(e))?[...this.selected].filter(e=>!s.has(e)):[...new Set([...this.selected,...s])],i=t.closest(".ck-card")?.dataset.id,o=null!=i&&t===document.activeElement;if(this._setSelection(n),!o)return;const a=[...this.storyEl.querySelectorAll(".ck-card")].find(e=>e.dataset.id===i);[...a?.querySelectorAll(".ck-tag")??[]].find(t=>t.dataset.tag===e)?.focus()}_tagStates(){const e=new Map;for(const t of this.items){const s=this.selected.has(t.id);for(const n of t.tags){const t=e.get(n)??{some:!1,all:!0};t.some||=s,t.all&&=s,e.set(n,t)}}return new Map([...e].map(([e,t])=>[e,t.all?"true":t.some?"mixed":"false"]))}_syncTags(){const e=this._tagStates();for(const t of this.root.querySelectorAll(".ck-tag"))t.setAttribute("aria-pressed",e.get(t.dataset.tag)??"false")}_toggleDim(e){e.setAttribute("aria-pressed",this.root.classList.toggle("ck-dim"))}_toggleTextSize(e){const t=this.root.classList.toggle("ck-large-text");e.setAttribute("aria-pressed",t),this._measureLabels(),this._invalidateLayout()}_setSelection(e){this.selected=new Set(e);for(const e of this.lanesEl.querySelectorAll(".ck-event")){const t=this.selected.has(e.dataset.id);e.classList.toggle("ck-selected",t),e.setAttribute("aria-pressed",t)}this._renderStory(),this._syncTags(),this._stateChanged(),this.options.onSelectionChange?.(this.getSelection())}_setView(e,t){this.start=e,this.end=t,this._scheduleRender(),this._stateChanged()}_setHidden(e){this.hidden=new Set(e),this._renderLegend(),this._invalidateLayout(),this._stateChanged()}_setHover(e){if(e!==this._hoverId){this._hoverId=e;for(const t of this.root.querySelectorAll(".ck-event, .ck-card, .ck-end-jump"))t.classList.toggle("ck-hover",t.dataset.id===e)}}_stateChanged(){this.options.syncUrl&&(clearTimeout(this._hashTimer),this._hashTimer=setTimeout(()=>this._writeHash(),250))}_readHash(){const e=y(),t=t=>{const s=e.get(t);if(!s)return[];try{return s.split(",").map(decodeURIComponent)}catch{return[]}},s={},n=e.get("ck-view")?.split(",").map(Number);2===n?.length&&n.every(Number.isFinite)&&n[0]<n[1]&&([s.start,s.end]=n),e.has("ck-sel")&&(s.selected=t("ck-sel")),e.has("ck-hide")&&(s.hidden=t("ck-hide")),this.setState(s)}_writeHash(){const{start:e,end:t,selected:s,hidden:n}=this.getState(),i=y(),o=Math.min(6,Math.max(0,Math.ceil(3-Math.log10(t-e))));i.set("ck-view",`${+e.toFixed(o)},${+t.toFixed(o)}`);for(const[e,t]of[["ck-sel",s],["ck-hide",n]])t.length?i.set(e,t.map(encodeURIComponent).join(",")):i.delete(e);const a=[...i].map(([e,t])=>null==t?e:`${e}=${t}`).join("&");history.replaceState(history.state,"",`${location.pathname}${location.search}#${a}`)}_clampSpan(e){const t=this.options.maxSpan??Math.max(3*this._dataSpan,100);return Math.min(Math.max(e,this.options.minSpan),t)}_scale(){return(this.viewport.clientWidth||1)/(this.end-this.start)}_ratioAt(e){const t=this.viewport.getBoundingClientRect();return(e-t.left)/t.width}_extent(){let e=1/0,t=-1/0;for(const s of this.items)e=Math.min(e,s.from),t=Math.max(t,s.to??s.from);return this.items.length?[e,t]:[0,0]}_measureLabels(){const e=this._ctx??=document.createElement("canvas").getContext("2d"),t=document.createElement("span");t.className="ck-label",t.style.visibility="hidden",this.lanesEl.append(t);const s=getComputedStyle(t);e.font=`${s.fontStyle} ${s.fontWeight} ${s.fontSize} ${s.fontFamily}`,e.letterSpacing="normal"===s.letterSpacing?"0px":s.letterSpacing,e.wordSpacing="normal"===s.wordSpacing?"0px":s.wordSpacing;const n=s.textTransform;t.remove();for(const t of this.items){let s=t.event.title??"";"uppercase"===n?s=s.toUpperCase():"lowercase"===n&&(s=s.toLowerCase()),t.labelWidth=e.measureText(s).width}}_scheduleRender(){this._frame||(this._frame=requestAnimationFrame(()=>{this._frame=0,this._render()}))}_render(){const e=this.viewport.clientWidth;if(!e)return;const t=e/(this.end-this.start),s=e=>(e-this.start)*t,n=null==this._layoutScale||Math.abs(t/this._layoutScale-1)>1e-6;(null==this._layoutScale||n&&!this._zooming)&&this._layout(t),this._renderAxis(t,s),this._renderEvents(e,s)}_layout(e){const t=[];for(const s of this.items){if(s.category&&this.hidden.has(s.category)){s.lane=-1;continue}const n=null!=s.to,i=s.from*e,o=n?s.to*e:i,a=n?i:i-5,r=n?6:16,l=Math.max(o,a+r+s.labelWidth)+12;let d=t.findIndex(e=>e<=a);d<0?d=t.push(l)-1:t[d]=l,s.lane=d}this._laneCount=t.length,this._layoutScale=e}_invalidateLayout(){this._layoutScale=null,this._scheduleRender()}_renderAxis(e,t){const s=n.find(t=>t*e>=90)??n.at(-1);let i="",o="";for(let e=Math.ceil(this.start/s);e*s<=this.end;e++){const n=e*s,a=t(n).toFixed(1);i+=`<span class="ck-tick" style="left:${a}px">${f($(n,s,this.m))}</span>`,o+=`<span class="ck-gridline" style="left:${a}px"></span>`}this.axisEl.innerHTML=i,this.gridEl.innerHTML=o}_renderEvents(e,t){const s=this.lanesEl.contains(document.activeElement)?document.activeElement.dataset.id:null,n=this._revealing,i=n?performance.now()-n.at:1/0;let o="";for(const s of this.items){if(s.lane<0)continue;const a=null!=s.to,r=t(s.from),l=a?t(s.to):r,d=a?r:r-5,c=a?Math.min(Math.max(0,-r),Math.max(0,l-r-s.labelWidth-6))+6:16,h=Math.max(l,d+c+s.labelWidth);if((a?l:h)<0||d>e)continue;const m=12+30*s.lane,u=this.selected.has(s.id),p=n?.id===s.id&&i<1500,y=`ck-event ${a?"ck-range":"ck-point"}${u?" ck-selected":""}${this._hoverClass(s)}${p?" ck-flash":""}`,$=`--ck-color:${f(s.color)};left:${d.toFixed(1)}px;top:${m}px`+(p?`;animation-delay:-${Math.round(i)}ms`:""),v=f(s.event.title??""),k=`type="button" class="${y}" data-id="${f(s.id)}" aria-pressed="${u}"\n title="${v} · ${f(g(s,this.m))}"`;o+=a?`<button ${k} style="${$};width:${Math.max(l-r,4).toFixed(1)}px">\n <span class="ck-label" style="left:${c.toFixed(1)}px">${v}</span></button>`:`<button ${k} style="${$}">\n <span class="ck-dot"></span><span class="ck-label">${v}</span></button>`}const a=24+30*this._laneCount;if(this.lanesEl.innerHTML=`<div class="ck-lanes-inner" style="height:${a}px">${o}</div>`,null!=s){([...this.lanesEl.querySelectorAll(".ck-event")].find(e=>e.dataset.id===s)??this.viewport).focus({preventScroll:!0})}n?.pending&&this._finishReveal(n)}_finishReveal(e){e.pending=!1;const t=[...this.lanesEl.querySelectorAll(".ck-event")].find(t=>t.dataset.id===e.id);if(!t)return;const s=this.lanesEl;(t.offsetTop<s.scrollTop||t.offsetTop+t.offsetHeight>s.scrollTop+s.clientHeight)&&(s.scrollTop=t.offsetTop-(s.clientHeight-t.offsetHeight)/2);const n=matchMedia("(prefers-reduced-motion: reduce)").matches;this.viewport.scrollIntoView({block:"nearest",behavior:n?"auto":"smooth"}),t.focus({preventScroll:!0})}_renderLegend(){this.legendEl.innerHTML=this.categories.map(e=>`<button type="button" class="ck-legend-item" data-category="${f(e)}"\n aria-pressed="${!this.hidden.has(e)}" style="--ck-color:${f(this.colorOf.get(e))}">\n <span class="ck-swatch"></span>${f(this._categoryLabel(e))}</button>`).join("")}_renderTagbar(){const e=new Map;for(const t of this.items)for(const s of t.tags)e.set(s,(e.get(s)??0)+1);const t=[...e.keys()].sort((e,t)=>this._tagLabel(e).localeCompare(this._tagLabel(t),this.options.language));this.tagbarEl.hidden=!t.length,this.tagbarEl.querySelector(".ck-count").textContent=t.length,this.tagbarEl.querySelector(".ck-tags").innerHTML=t.map(t=>`<li><button type="button" class="ck-tag" data-tag="${f(t)}" aria-pressed="false">${f(this._tagLabel(t))} <span class="ck-tag-count">${e.get(t)}</span></button></li>`).join("")}_renderStory(){const e=this.items.filter(e=>this.selected.has(e.id)),t="right"===this.options.storyPosition;if(this.storyEl.hidden=!e.length&&!t,this.storyEl.classList.toggle("ck-empty",!e.length),this.root.classList.toggle("ck-has-selection",e.length>0),!e.length)return void(this.storyEl.innerHTML=t?`<p class="ck-story-placeholder">${f(this.m.placeholder)}</p>`:"");const s=e.map(e=>({item:e,at:e.from,isEnd:!1}));for(const t of e)t.end&&t.end.value>t.from&&s.push({item:t,at:t.end.value,isEnd:!0});s.sort((e,t)=>e.at-t.at||t.isEnd-e.isEnd),this.storyEl.innerHTML=`\n <div class="ck-story-header">\n <span class="ck-story-title">${f(this.m.selectedEvents)} <span class="ck-count">${this.m.number.format(e.length)}</span></span>\n <button type="button" class="ck-clear">${f(this.m.clearAll)}</button>\n </div>\n <ol class="ck-story-list">${s.map(e=>e.isEnd?this._storyEnd(e.item):this._storyCard(e.item)).join("")}</ol>`}_storyEnd(e){const t=this.m,s=f(e.event.title??""),n=f(h(e.end,t)),i=f(u(e.start,e.end,t));return`\n <li class="ck-end" style="--ck-color:${f(e.color)}">\n <button type="button" class="ck-end-jump${this._hoverClass(e)}" data-id="${f(e.id)}"\n aria-label="${t.endsAria(s,n,i)}">\n <span class="ck-end-date">${n}</span>\n <span>${t.endOf(`<strong>${s}</strong>`)}</span>\n ${i?`<span class="ck-end-duration">${t.lasted(i)}</span>`:""}\n </button>\n </li>`}_jumpToCard(e){const t=[...this.storyEl.querySelectorAll(".ck-card")].find(t=>t.dataset.id===e);if(!t)return;const s=matchMedia("(prefers-reduced-motion: reduce)").matches;t.scrollIntoView({block:"nearest",behavior:s?"auto":"smooth"}),t.focus({preventScroll:!0}),t.classList.remove("ck-flash"),t.offsetWidth,t.classList.add("ck-flash")}_storyCard(e){const t=e.event,s=t.url&&/^https?:\/\//i.test(t.url)?t.url:null;return`\n <li class="ck-card${this._hoverClass(e)}" data-id="${f(e.id)}" tabindex="-1"\n style="--ck-color:${f(e.color)}">\n <button type="button" class="ck-remove" data-id="${f(e.id)}"\n aria-label="${this.m.remove(f(t.title??""))}">×</button>\n <div class="ck-meta">\n ${e.category?`<span class="ck-badge">${f(this._categoryLabel(e.category))}</span>`:""}\n <span>${f(g(e,this.m))}</span>\n </div>\n <h3 class="ck-title">${f(t.title??"")}</h3>\n ${t.description?`<p class="ck-description">${f(t.description)}</p>`:""}\n ${e.tags.length?`<ul class="ck-tags" aria-label="${f(this.m.tags)}">${e.tags.map(e=>`<li><button type="button" class="ck-tag" data-tag="${f(e)}" aria-pressed="false">${f(this._tagLabel(e))}</button></li>`).join("")}</ul>`:""}\n <div class="ck-card-actions">\n <button type="button" class="ck-locate" data-id="${f(e.id)}">${f(this.m.showOnTimeline)}</button>\n ${s?`<a class="ck-link" href="${f(s)}" target="_blank" rel="noopener">${f(this.m.readMore)}</a>`:""}\n </div>\n </li>`}_hoverClass(e){return this._hoverId===e.id?" ck-hover":""}_categoryLabel(e){return this.options.categoryLabels[e]??e}_tagLabel(e){return this.options.tagLabels[e]??e}}export{v as Chroniko,c as formatDate,m as formatDuration,d as formatYear,i as parseDate};
1
+ const e={en:{zoomIn:"Zoom in",zoomOut:"Zoom out",fit:"Fit",dimUnselected:"Dim unselected events",largerText:"Larger text",categories:"Categories",ctrlKey:"Ctrl",viewport:e=>`Timeline. Drag or use arrow keys to pan; press + and −, ${e}+scroll or pinch to zoom.`,hint:e=>`${e} + scroll to zoom, or click the timeline first`,selectedEvents:"Selected events",clearAll:"Clear all",placeholder:"Click an event to add it here.",showOnTimeline:"Show on timeline",readMore:"Read more ↗",tags:"Tags",remove:e=>`Remove ${e} from selection`,endOf:e=>`End of ${e}`,lasted:e=>`lasted ${e}`,endsAria:(e,t,s)=>`${e} ends ${t}${s?`, after ${s}`:""}. Go to event`,months:["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],year:e=>e<0?-e+" BCE":String(e),month:(e,t)=>`${e} ${t}`,day:(e,t,s)=>`${e} ${t} ${s}`,units:{year:{one:"# year",other:"# years"},month:{one:"# month",other:"# months"},day:{one:"# day",other:"# days"}},unitJoin:", ",lessThan:{year:"less than a year",month:"less than a month",day:"less than a day"}},"zh-Hant":{zoomIn:"放大",zoomOut:"縮小",fit:"全覽",dimUnselected:"淡化未選事件",largerText:"放大文字",categories:"類別",ctrlKey:"Ctrl",viewport:e=>`時間軸。拖曳或使用方向鍵平移;按 + 和 −、${e} + 滾輪或雙指縮放。`,hint:e=>`${e} + 滾輪縮放,或先點擊時間軸`,selectedEvents:"已選事件",clearAll:"全部清除",placeholder:"點擊事件以加入此處。",showOnTimeline:"在時間軸上顯示",readMore:"了解更多 ↗",tags:"標籤",remove:e=>`從已選事件中移除「${e}」`,endOf:e=>`${e}結束`,lasted:e=>`歷時${e}`,endsAria:(e,t,s)=>`${e}於${t}結束${s?`,歷時${s}`:""}。前往事件`,months:["1月","2月","3月","4月","5月","6月","7月","8月","9月","10月","11月","12月"],year:e=>e<0?`公元前${-e}年`:`${e}年`,month:(e,t)=>`${t}${e}`,day:(e,t,s)=>`${s}${t}${e}日`,units:{year:{other:"#年"},month:{other:"#個月"},day:{other:"#天"}},unitJoin:"",lessThan:{year:"不足一年",month:"不足一個月",day:"不足一天"}},"zh-Hans":{zoomIn:"放大",zoomOut:"缩小",fit:"全览",dimUnselected:"淡化未选事件",largerText:"放大文字",categories:"类别",ctrlKey:"Ctrl",viewport:e=>`时间轴。拖动或使用方向键平移;按 + 和 −、${e} + 滚轮或双指缩放。`,hint:e=>`${e} + 滚轮缩放,或先点击时间轴`,selectedEvents:"已选事件",clearAll:"全部清除",placeholder:"点击事件以添加到此处。",showOnTimeline:"在时间轴上显示",readMore:"了解更多 ↗",tags:"标签",remove:e=>`从已选事件中移除“${e}”`,endOf:e=>`${e}结束`,lasted:e=>`历时${e}`,endsAria:(e,t,s)=>`${e}于${t}结束${s?`,历时${s}`:""}。前往事件`,months:["1月","2月","3月","4月","5月","6月","7月","8月","9月","10月","11月","12月"],year:e=>e<0?`公元前${-e}年`:`${e}年`,month:(e,t)=>`${t}${e}`,day:(e,t,s)=>`${s}${t}${e}日`,units:{year:{other:"#年"},month:{other:"#个月"},day:{other:"#天"}},unitJoin:"",lessThan:{year:"不足一年",month:"不足一个月",day:"不足一天"}},yue:{zoomIn:"放大",zoomOut:"縮細",fit:"睇晒",dimUnselected:"淡化未揀嘅",largerText:"大啲字",categories:"類別",ctrlKey:"Ctrl",viewport:e=>`時間軸。拖或者用方向鍵左右移;撳 + 同 −、${e} + 碌滾輪或者用兩隻手指縮放。`,hint:e=>`${e} + 碌滾輪就可以縮放,或者先撳一下時間軸`,selectedEvents:"揀咗嘅事件",clearAll:"清晒",placeholder:"撳一下事件就會加入呢度。",showOnTimeline:"喺時間軸度睇",readMore:"睇多啲 ↗",tags:"標籤",remove:e=>`移走「${e}」`,endOf:e=>`${e}完結`,lasted:e=>`維持咗${e}`,endsAria:(e,t,s)=>`${e}喺${t}完結${s?`,維持咗${s}`:""}。去返個事件`,months:["1月","2月","3月","4月","5月","6月","7月","8月","9月","10月","11月","12月"],year:e=>e<0?`公元前${-e}年`:`${e}年`,month:(e,t)=>`${t}${e}`,day:(e,t,s)=>`${s}${t}${e}日`,units:{year:{other:"#年"},month:{other:"#個月"},day:{other:"#日"}},unitJoin:"",lessThan:{year:"唔夠一年",month:"唔夠一個月",day:"唔夠一日"}},ja:{zoomIn:"拡大",zoomOut:"縮小",fit:"全体表示",dimUnselected:"選択外を暗く",largerText:"文字を大きく",categories:"カテゴリ",ctrlKey:"Ctrl",viewport:e=>`タイムライン。ドラッグまたは矢印キーで移動し、+ と −、${e} + スクロール、またはピンチで拡大・縮小します。`,hint:e=>`${e} + スクロールで拡大・縮小、または先にタイムラインをクリック`,selectedEvents:"選択した出来事",clearAll:"すべて解除",placeholder:"出来事をクリックするとここに追加されます。",showOnTimeline:"タイムラインで表示",readMore:"詳しく見る ↗",tags:"タグ",remove:e=>`「${e}」を選択から外す`,endOf:e=>`${e}の終わり`,lasted:e=>`期間:${e}`,endsAria:(e,t,s)=>`${e}は${t}に終了${s?`(期間:${s})`:""}。出来事へ移動`,months:["1月","2月","3月","4月","5月","6月","7月","8月","9月","10月","11月","12月"],year:e=>e<0?`紀元前${-e}年`:`${e}年`,month:(e,t)=>`${t}${e}`,day:(e,t,s)=>`${s}${t}${e}日`,units:{year:{other:"#年"},month:{other:"#か月"},day:{other:"#日"}},unitJoin:"",lessThan:{year:"1年未満",month:"1か月未満",day:"1日未満"}},ko:{zoomIn:"확대",zoomOut:"축소",fit:"전체 보기",dimUnselected:"선택 안 된 항목 흐리게",largerText:"글자 크게",categories:"분류",ctrlKey:"Ctrl",viewport:e=>`타임라인. 드래그하거나 화살표 키로 이동하고, + 와 −, ${e}+스크롤 또는 핀치로 확대/축소합니다.`,hint:e=>`${e} + 스크롤로 확대/축소하거나 먼저 타임라인을 클릭하세요`,selectedEvents:"선택한 사건",clearAll:"모두 지우기",placeholder:"사건을 클릭하면 여기에 추가됩니다.",showOnTimeline:"타임라인에서 보기",readMore:"더 보기 ↗",tags:"태그",remove:e=>`선택에서 ${e} 제거`,endOf:e=>`${e} 종료`,lasted:e=>`기간: ${e}`,endsAria:(e,t,s)=>`${e} 종료: ${t}${s?`, 기간 ${s}`:""}. 사건으로 이동`,months:["1월","2월","3월","4월","5월","6월","7월","8월","9월","10월","11월","12월"],year:e=>e<0?`기원전 ${-e}년`:`${e}년`,month:(e,t)=>`${t} ${e}`,day:(e,t,s)=>`${s} ${t} ${e}일`,units:{year:{other:"#년"},month:{other:"#개월"},day:{other:"#일"}},unitJoin:" ",lessThan:{year:"1년 미만",month:"1개월 미만",day:"1일 미만"}},fr:{zoomIn:"Zoom avant",zoomOut:"Zoom arrière",fit:"Ajuster",dimUnselected:"Atténuer les non sélectionnés",largerText:"Texte plus grand",categories:"Catégories",ctrlKey:"Ctrl",viewport:e=>`Frise chronologique. Faites glisser ou utilisez les flèches pour vous déplacer ; appuyez sur + et −, ${e}+molette ou pincez pour zoomer.`,hint:e=>`${e} + molette pour zoomer, ou cliquez d’abord sur la frise`,selectedEvents:"Événements sélectionnés",clearAll:"Tout effacer",placeholder:"Cliquez sur un événement pour l’ajouter ici.",showOnTimeline:"Afficher sur la frise",readMore:"En savoir plus ↗",tags:"Étiquettes",remove:e=>`Retirer ${e} de la sélection`,endOf:e=>`Fin : ${e}`,lasted:e=>`durée : ${e}`,endsAria:(e,t,s)=>`Fin de « ${e} » : ${t}${s?`, durée ${s}`:""}. Aller à l’événement`,months:["janv.","févr.","mars","avr.","mai","juin","juil.","août","sept.","oct.","nov.","déc."],year:e=>e<0?-e+" av. J.-C.":String(e),month:(e,t)=>`${e} ${t}`,day:(e,t,s)=>`${1===e?"1er":e} ${t} ${s}`,units:{year:{one:"# an",other:"# ans"},month:{one:"# mois",other:"# mois"},day:{one:"# jour",other:"# jours"}},unitJoin:" et ",lessThan:{year:"moins d’un an",month:"moins d’un mois",day:"moins d’un jour"}},de:{zoomIn:"Vergrößern",zoomOut:"Verkleinern",fit:"Einpassen",dimUnselected:"Nicht ausgewählte abblenden",largerText:"Größere Schrift",categories:"Kategorien",ctrlKey:"Strg",viewport:e=>`Zeitleiste. Zum Verschieben ziehen oder die Pfeiltasten verwenden; zum Zoomen + und −, ${e}+Mausrad oder zwei Finger verwenden.`,hint:e=>`${e} + Mausrad zum Zoomen, oder zuerst auf die Zeitleiste klicken`,selectedEvents:"Ausgewählte Ereignisse",clearAll:"Alle entfernen",placeholder:"Klicken Sie auf ein Ereignis, um es hier hinzuzufügen.",showOnTimeline:"Auf der Zeitleiste anzeigen",readMore:"Mehr erfahren ↗",tags:"Schlagwörter",remove:e=>`${e} aus der Auswahl entfernen`,endOf:e=>`Ende: ${e}`,lasted:e=>`Dauer: ${e}`,endsAria:(e,t,s)=>`Ende von ${e}: ${t}${s?`, Dauer ${s}`:""}. Zum Ereignis`,months:["Jan.","Feb.","März","Apr.","Mai","Juni","Juli","Aug.","Sept.","Okt.","Nov.","Dez."],year:e=>e<0?-e+" v. Chr.":String(e),month:(e,t)=>`${e} ${t}`,day:(e,t,s)=>`${e}. ${t} ${s}`,units:{year:{one:"# Jahr",other:"# Jahre"},month:{one:"# Monat",other:"# Monate"},day:{one:"# Tag",other:"# Tage"}},unitJoin:", ",lessThan:{year:"weniger als ein Jahr",month:"weniger als ein Monat",day:"weniger als ein Tag"}},it:{zoomIn:"Ingrandisci",zoomOut:"Riduci",fit:"Adatta",dimUnselected:"Attenua i non selezionati",largerText:"Testo più grande",categories:"Categorie",ctrlKey:"Ctrl",viewport:e=>`Linea del tempo. Trascina o usa i tasti freccia per spostarti; premi + e −, ${e}+rotellina o pizzica per lo zoom.`,hint:e=>`${e} + rotellina per lo zoom, oppure fai prima clic sulla linea del tempo`,selectedEvents:"Eventi selezionati",clearAll:"Cancella tutto",placeholder:"Fai clic su un evento per aggiungerlo qui.",showOnTimeline:"Mostra sulla linea del tempo",readMore:"Scopri di più ↗",tags:"Tag",remove:e=>`Rimuovi ${e} dalla selezione`,endOf:e=>`Fine: ${e}`,lasted:e=>`durata: ${e}`,endsAria:(e,t,s)=>`Fine di ${e}: ${t}${s?`, durata ${s}`:""}. Vai all’evento`,months:["gen","feb","mar","apr","mag","giu","lug","ago","set","ott","nov","dic"],year:e=>e<0?-e+" a.C.":String(e),month:(e,t)=>`${e} ${t}`,day:(e,t,s)=>`${e} ${t} ${s}`,units:{year:{one:"# anno",other:"# anni"},month:{one:"# mese",other:"# mesi"},day:{one:"# giorno",other:"# giorni"}},unitJoin:" e ",lessThan:{year:"meno di un anno",month:"meno di un mese",day:"meno di un giorno"}},es:{zoomIn:"Acercar",zoomOut:"Alejar",fit:"Ajustar",dimUnselected:"Atenuar los no seleccionados",largerText:"Texto más grande",categories:"Categorías",ctrlKey:"Ctrl",viewport:e=>`Línea de tiempo. Arrastra o usa las flechas para desplazarte; pulsa + y −, ${e}+rueda o pellizca para hacer zoom.`,hint:e=>`${e} + rueda para hacer zoom, o haz clic primero en la línea de tiempo`,selectedEvents:"Eventos seleccionados",clearAll:"Borrar todo",placeholder:"Haz clic en un evento para añadirlo aquí.",showOnTimeline:"Mostrar en la línea de tiempo",readMore:"Más información ↗",tags:"Etiquetas",remove:e=>`Quitar ${e} de la selección`,endOf:e=>`Fin: ${e}`,lasted:e=>`duración: ${e}`,endsAria:(e,t,s)=>`Fin de ${e}: ${t}${s?`, duración ${s}`:""}. Ir al evento`,months:["ene","feb","mar","abr","may","jun","jul","ago","sept","oct","nov","dic"],year:e=>e<0?-e+" a. C.":String(e),month:(e,t)=>`${e} ${t}`,day:(e,t,s)=>`${e} ${t} ${s}`,units:{year:{one:"# año",other:"# años"},month:{one:"# mes",other:"# meses"},day:{one:"# día",other:"# días"}},unitJoin:" y ",lessThan:{year:"menos de un año",month:"menos de un mes",day:"menos de un día"}},pt:{zoomIn:"Ampliar",zoomOut:"Reduzir",fit:"Ajustar",dimUnselected:"Escurecer os não selecionados",largerText:"Texto maior",categories:"Categorias",ctrlKey:"Ctrl",viewport:e=>`Linha do tempo. Arraste ou use as setas para deslocar; use + e −, ${e}+roda ou o gesto de pinça para ampliar ou reduzir.`,hint:e=>`${e} + roda para ampliar ou reduzir, ou clique primeiro na linha do tempo`,selectedEvents:"Eventos selecionados",clearAll:"Limpar tudo",placeholder:"Clique num evento para adicioná-lo aqui.",showOnTimeline:"Mostrar na linha do tempo",readMore:"Saiba mais ↗",tags:"Etiquetas",remove:e=>`Remover ${e} da seleção`,endOf:e=>`Fim: ${e}`,lasted:e=>`duração: ${e}`,endsAria:(e,t,s)=>`Fim de ${e}: ${t}${s?`, duração ${s}`:""}. Ir para o evento`,months:["jan","fev","mar","abr","mai","jun","jul","ago","set","out","nov","dez"],year:e=>e<0?-e+" a.C.":String(e),month:(e,t)=>`${e} ${t}`,day:(e,t,s)=>`${e} ${t} ${s}`,units:{year:{one:"# ano",other:"# anos"},month:{one:"# mês",other:"# meses"},day:{one:"# dia",other:"# dias"}},unitJoin:" e ",lessThan:{year:"menos de um ano",month:"menos de um mês",day:"menos de um dia"}},pl:{zoomIn:"Powiększ",zoomOut:"Pomniejsz",fit:"Dopasuj",dimUnselected:"Przyciemnij niezaznaczone",largerText:"Większy tekst",categories:"Kategorie",ctrlKey:"Ctrl",viewport:e=>`Oś czasu. Przeciągnij lub użyj klawiszy strzałek, aby przesuwać; naciśnij + i −, ${e}+kółko myszy lub zsuń palce, aby zmienić powiększenie.`,hint:e=>`${e} + kółko myszy, aby zmienić powiększenie, lub najpierw kliknij oś czasu`,selectedEvents:"Wybrane wydarzenia",clearAll:"Wyczyść wszystko",placeholder:"Kliknij wydarzenie, aby dodać je tutaj.",showOnTimeline:"Pokaż na osi czasu",readMore:"Więcej ↗",tags:"Tagi",remove:e=>`Usuń ${e} z wyboru`,endOf:e=>`Koniec: ${e}`,lasted:e=>`czas trwania: ${e}`,endsAria:(e,t,s)=>`Koniec: ${e}, ${t}${s?`, czas trwania ${s}`:""}. Przejdź do wydarzenia`,months:["sty","lut","mar","kwi","maj","cze","lip","sie","wrz","paź","lis","gru"],year:e=>e<0?-e+" p.n.e.":String(e),month:(e,t)=>`${e} ${t}`,day:(e,t,s)=>`${e} ${t} ${s}`,units:{year:{one:"# rok",few:"# lata",many:"# lat",other:"# roku"},month:{one:"# miesiąc",few:"# miesiące",many:"# miesięcy",other:"# miesiąca"},day:{one:"# dzień",few:"# dni",many:"# dni",other:"# dnia"}},unitJoin:", ",lessThan:{year:"mniej niż rok",month:"mniej niż miesiąc",day:"mniej niż dzień"}},nl:{zoomIn:"Inzoomen",zoomOut:"Uitzoomen",fit:"Passend maken",dimUnselected:"Niet-geselecteerde dimmen",largerText:"Grotere tekst",categories:"Categorieën",ctrlKey:"Ctrl",viewport:e=>`Tijdlijn. Sleep of gebruik de pijltjestoetsen om te verschuiven; druk op + en −, ${e}+scrollen of knijp om te zoomen.`,hint:e=>`${e} + scrollen om te zoomen, of klik eerst op de tijdlijn`,selectedEvents:"Geselecteerde gebeurtenissen",clearAll:"Alles wissen",placeholder:"Klik op een gebeurtenis om die hier toe te voegen.",showOnTimeline:"Tonen op tijdlijn",readMore:"Meer lezen ↗",tags:"Tags",remove:e=>`${e} uit selectie verwijderen`,endOf:e=>`Einde: ${e}`,lasted:e=>`duur: ${e}`,endsAria:(e,t,s)=>`Einde van ${e}: ${t}${s?`, duur ${s}`:""}. Ga naar gebeurtenis`,months:["jan","feb","mrt","apr","mei","jun","jul","aug","sep","okt","nov","dec"],year:e=>e<0?-e+" v.Chr.":String(e),month:(e,t)=>`${e} ${t}`,day:(e,t,s)=>`${e} ${t} ${s}`,units:{year:{one:"# jaar",other:"# jaar"},month:{one:"# maand",other:"# maanden"},day:{one:"# dag",other:"# dagen"}},unitJoin:" en ",lessThan:{year:"minder dan een jaar",month:"minder dan een maand",day:"minder dan een dag"}}},t=["#4e79a7","#e15759","#59a14f","#f28e2b","#b07aa1","#76b7b2","#edc948","#9c755f"],s={year:1,month:1/12,day:1/372},n=[1/12,1/4,...[1,10,100,1e3,1e4,1e5].flatMap(e=>[e,2*e,5*e])];function i(t){if(null==t||""===t)return null;const s="object"==typeof t?JSON.stringify(t):"string"==typeof t?`"${t}"`:String(t);let n,i,r;if("number"==typeof t){if(!Number.isFinite(t))throw new Error(`Chroniko: invalid date ${s}`);return a(t)}if("object"==typeof t)({year:n,month:i,day:r}=t);else{const e=/^(-?\d+)(?:-(\d{1,2}))?(?:-(\d{1,2}))?$/.exec(String(t).trim());if(!e)throw new Error(`Chroniko: cannot parse date ${s}`);[n,i,r]=[Number(e[1]),e[2]&&Number(e[2]),e[3]&&Number(e[3])]}const l=function(t,s,n){if(!Number.isInteger(t))return"year must be a whole number";if(null!=s&&!(Number.isInteger(s)&&s>=1&&s<=12))return"month must be 1–12";if(null!=n){if(null==s)return"a day needs a month";if(!(Number.isInteger(n)&&n>=1&&n<=o[s-1]))return`day must be 1–${o[s-1]} in ${e.en.months[s-1]}`}return null}(n,i??null,r??null);if(l)throw new Error(`Chroniko: invalid date ${s}: ${l}`);return a(n,i,r)}const o=[31,29,31,30,31,30,31,31,30,31,30,31];function a(e,t,s){let n=e;t&&(n+=(t-1)/12),s&&(n+=(s-1)/372);return{year:e,month:t||null,day:s||null,precision:s?"day":t?"month":"year",value:n}}const r=new Map;function l(t,s){if(!Object.hasOwn(e,t)){const s=Object.keys(e).map(e=>`'${e}'`).join(", ");throw new Error(`Chroniko: language must be one of ${s}, got ${JSON.stringify(t)}`)}if(!s&&r.has(t))return r.get(t);const n={...e.en,...e[t],...s,number:new Intl.NumberFormat(t),plural:new Intl.PluralRules(t)};return s||r.set(t,n),n}function d(e,t="en"){return l(t).year(e)}function h(e,t="en"){return c(e,l(t))}function c(e,t){const s=t.year(e.year);return e.day?t.day(e.day,t.months[e.month-1],s):e.month?t.month(t.months[e.month-1],s):s}function m(e,t,s="en"){return u(e,t,l(s))}function u(e,t,s){const n=e=>e<0?e+1:e,i=[e.precision,t.precision],o=i.includes("year")?"year":i.includes("month")?"month":"day";let a=n(t.year)-n(e.year),r="year"===o?0:t.month-e.month,l="day"===o?t.day-e.day:0;if(l<0&&(r-=1,l=Math.max(function(e,t){if(0===t)return 31;return[31,e%4==0&&e%100!=0||e%400==0?29:28,31,30,31,30,31,31,30,31,30,31][t-1]}(n(t.year),t.month-1)-e.day,0)+t.day),r<0&&(a-=1,r+=12),a<0)return"";const d=[["year",a],["month",r],["day",l]],h=d.findIndex(([,e])=>e>0);if(h<0)return s.lessThan[o];const c=([e,t])=>{const n=s.units[e];return(n[s.plural.select(t)]??n.other).replace("#",s.number.format(t))},m=d[h+1];return m?.[1]>0?`${c(d[h])}${s.unitJoin}${c(m)}`:c(d[h])}function g(e,t){const s=c(e.start,t);return e.end?`${s} – ${c(e.end,t)}`:s}function p(e,t){return`${String(e.category??"").trim().toLowerCase().replace(/\s+/g,"-")||"event"}-${t}`}function y(){const e=new Map;for(const t of location.hash.slice(1).split("&")){if(!t)continue;const s=t.indexOf("=");s<0?e.set(t,null):e.set(t.slice(0,s),t.slice(s+1))}return e}function $(e,t,s){if(t>=1)return s.year(Math.round(e));const n=Math.floor(e+1e-9),i=Math.round(12*(e-n))%12;return 0===i?s.year(n):s.months[i]}function f(e){return String(e).replace(/[&<>"']/g,e=>({"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;"}[e]))}class v{constructor(e,t={}){const s="string"==typeof e?document.querySelector(e):e;if(!s)throw new Error("Chroniko: container not found");this.options={minSpan:1/12,colors:{},storyPosition:"below",split:.6,dimToggle:!0,language:"en",categoryLabels:{},tagLabels:{},...t};const{storyPosition:n,split:i}=this.options;if("below"!==n&&"right"!==n)throw new Error(`Chroniko: storyPosition must be 'below' or 'right', got ${JSON.stringify(n)}`);if(!("number"==typeof i&&i>0&&i<1))throw new Error(`Chroniko: split must be a number between 0 and 1, got ${JSON.stringify(i)}`);this.m=l(this.options.language,this.options.uiText),this.items=[],this.hidden=new Set,this.selected=new Set,this.colorOf=new Map,this._paletteNext=0,this._nextIndex=0,this.start=0,this.end=1,this._frame=0,this._build(s),this._bind(),this.setEvents(t.events??[]),null!=t.start&&null!=t.end?this.zoomTo(t.start,t.end):this.fit(),this.options.syncUrl&&(this._onHashChange=()=>this._readHash(),window.addEventListener("hashchange",this._onHashChange),this._readHash(),clearTimeout(this._hashTimer))}setEvents(e){const t=e.map((e,t)=>this._toItem(e,String(e.id??p(e,t)))).sort((e,t)=>e.from-t.from);this._checkIds(t),this.items=t,this._nextIndex=e.length,this._assignColors(t),this._itemsChanged(),this._measureLabels(),this._renderLegend(),this._renderTagbar();const s=this.selected.size;this.selected=new Set(this.items.filter(e=>this.selected.has(e.id)).map(e=>e.id)),this._renderStory(),this._syncTags(),this._invalidateLayout(),this.selected.size<s&&(this._stateChanged(),this.options.onSelectionChange?.(this.getSelection()))}addEvents(e){const t=(e=[e].flat()).map((e,t)=>this._toItem(e,String(e.id??p(e,this._nextIndex+t)))).sort((e,t)=>e.from-t.from);this._checkIds([...this.items,...t]),this._nextIndex+=e.length;const s=!this.items.length||!t.length||t[0].from>=this.items.at(-1).from;for(const e of t)this._insert(e);return this._assignColors(t),this._itemsChanged(),this._measureLabels(t),s&&null!=this._layoutScale?this._pack(t):this._layoutScale=null,this._dataChanged(!1),t.map(e=>e.id)}updateEvent(e,t){e=String(e);const s=this.items.findIndex(t=>t.id===e);if(s<0)throw new Error(`Chroniko: updateEvent found no event with the id "${e}"`);if(null!=t.id&&String(t.id)!==e)throw new Error(`Chroniko: updateEvent cannot change the id of "${e}"; remove the event and add it again`);const n=this._toItem({...this.items[s].event,...t},e);this.items.splice(s,1),this._insert(n),this._assignColors([n]),this._itemsChanged(),this._measureLabels([n]),this._layoutScale=null,this._dataChanged(this.selected.has(e))}removeEvents(e){const t=new Set([e].flat().map(String)),s=this.items.filter(e=>!t.has(e.id));if(s.length===this.items.length)return;this.items=s,this._itemsChanged(),this._layoutScale=null,this._dataChanged(!1);const n=[...this.selected].filter(e=>!t.has(e));n.length<this.selected.size&&this._setSelection(n)}zoomTo(e,t){const s=i(e)?.value,n=i(t)?.value;if(null==s||null==n)throw new Error("Chroniko: zoomTo needs both a start and an end");if(s>=n)throw new Error(`Chroniko: zoomTo start (${e}) must be before end (${t})`);const o=(s+n)/2,a=this._clampSpan(n-s);this._setView(o-a/2,o+a/2)}fit(){if(!this.items.length)return this._setView(0,2e3);const[e,t]=this._extent(),s=Math.max(t-e,1);this._setView(e-.04*s,t+.12*s)}zoomBy(e,t=.5){const s=this.end-this.start,n=this.start+s*t,i=this._clampSpan(s*e);this._setView(n-i*t,n-i*t+i)}panBy(e){const t=e/this._scale();this._setView(this.start+t,this.end+t)}select(e){e=String(e),!this.selected.has(e)&&this.items.some(t=>t.id===e)&&this._setSelection([...this.selected,e])}deselect(e){e=String(e),this.selected.has(e)&&this._setSelection([...this.selected].filter(t=>t!==e))}toggle(e){this.selected.has(String(e))?this.deselect(e):this.select(e)}clearSelection(){this.selected.size&&this._setSelection([])}getSelection(){return this.items.filter(e=>this.selected.has(e.id)).map(e=>e.event)}reveal(e){const t=this.items.find(t=>t.id===String(e));if(!t)return;t.category&&this.hidden.has(t.category)&&this._setHidden([...this.hidden].filter(e=>e!==t.category));const s=null!=t.to?(t.from+t.to)/2:t.from,n=null!=t.to?this._clampSpan((t.to-t.from)/.6):this.end-this.start;this._revealing={id:t.id,at:performance.now(),pending:!0},this._setView(s-n/2,s+n/2)}getState(){return{start:this.start,end:this.end,selected:this.items.filter(e=>this.selected.has(e.id)).map(e=>e.id),hidden:[...this.hidden]}}setState(e={}){if(null!=e.start&&null!=e.end&&this.zoomTo(e.start,e.end),e.hidden&&this._setHidden(e.hidden.map(String)),e.selected){const t=new Set(e.selected.map(String));this._setSelection(this.items.filter(e=>t.has(e.id)).map(e=>e.id))}}destroy(){cancelAnimationFrame(this._frame),clearTimeout(this._zoomTimer),clearTimeout(this._hintTimer),clearTimeout(this._hashTimer),this._onHashChange&&window.removeEventListener("hashchange",this._onHashChange),this._resizeObserver.disconnect(),document.fonts?.removeEventListener("loadingdone",this._onFontsLoaded),this.root.remove()}_build(e){this.root=document.createElement("div"),this.root.className="chroniko",this.root.lang=this.options.language,"right"===this.options.storyPosition&&(this.root.classList.add("ck-side"),this.root.style.setProperty("--ck-split",this.options.split)),this.options.dimToggle&&this.root.classList.add("ck-dim");const t=this.m,s=/Mac|iPhone|iPad/.test(navigator.userAgentData?.platform??navigator.platform)?"⌘":t.ctrlKey;this.root.innerHTML=`\n <div class="ck-layout">\n <div class="ck-main">\n <div class="ck-toolbar">\n <div class="ck-legend" role="group" aria-label="${f(t.categories)}"></div>\n <div class="ck-controls">\n <button type="button" data-action="zoom-in" aria-label="${f(t.zoomIn)}">+</button>\n <button type="button" data-action="zoom-out" aria-label="${f(t.zoomOut)}">−</button>\n <button type="button" data-action="fit">${f(t.fit)}</button>\n ${this.options.dimToggle?`<button type="button" data-action="dim" aria-pressed="true" aria-label="${f(t.dimUnselected)}">◐</button>`:""}\n ${this.options.textSizeToggle?`<button type="button" data-action="text-size" aria-pressed="false" aria-label="${f(t.largerText)}">Aa</button>`:""}\n </div>\n </div>\n <details class="ck-tagbar" hidden>\n <summary>${f(t.tags)} <span class="ck-count"></span></summary>\n <ul class="ck-tags" aria-label="${f(t.tags)}"></ul>\n </details>\n <div class="ck-viewport" tabindex="0" aria-label="${t.viewport(f(s))}">\n <div class="ck-grid"></div>\n <div class="ck-lanes"></div>\n <div class="ck-axis"></div>\n <div class="ck-hint" aria-hidden="true"></div>\n </div>\n </div>\n <section class="ck-story" aria-label="${f(t.selectedEvents)}" hidden></section>\n </div>`,e.append(this.root),this.legendEl=this.root.querySelector(".ck-legend"),this.tagbarEl=this.root.querySelector(".ck-tagbar"),this.viewport=this.root.querySelector(".ck-viewport"),this.gridEl=this.root.querySelector(".ck-grid"),this.lanesEl=this.root.querySelector(".ck-lanes"),this.axisEl=this.root.querySelector(".ck-axis"),this.storyEl=this.root.querySelector(".ck-story"),this.hintEl=this.root.querySelector(".ck-hint"),this.hintEl.innerHTML=t.hint(f(s))}_showHint(){this.hintEl.classList.add("ck-visible"),clearTimeout(this._hintTimer),this._hintTimer=setTimeout(()=>this.hintEl.classList.remove("ck-visible"),1500)}_bind(){const e=this.viewport;this.root.querySelector(".ck-controls").addEventListener("click",e=>{const t=e.target.closest("button")?.dataset.action;"zoom-in"===t?this.zoomBy(1/1.5):"zoom-out"===t?this.zoomBy(1.5):"fit"===t?this.fit():"dim"===t?this._toggleDim(e.target.closest("button")):"text-size"===t&&this._toggleTextSize(e.target.closest("button"))}),this.tagbarEl.addEventListener("click",e=>{const t=e.target.closest(".ck-tag");t&&this._toggleTag(t.dataset.tag,t)}),this.legendEl.addEventListener("click",e=>{const t=e.target.closest(".ck-legend-item")?.dataset.category;if(null==t)return;const s=new Set(this.hidden);s.has(t)?s.delete(t):s.add(t),this._setHidden(s)});const t=e=>{e.pointerType&&"mouse"!==e.pointerType||this._setHover(e.target.closest(".ck-event, .ck-card, .ck-end-jump")?.dataset.id??null)};for(const e of[this.lanesEl,this.storyEl])e.addEventListener("pointerover",t),e.addEventListener("focusin",t),e.addEventListener("pointerleave",()=>this._setHover(null)),e.addEventListener("focusout",()=>this._setHover(null));e.addEventListener("wheel",t=>{const s=1===t.deltaMode?16:2===t.deltaMode?e.clientWidth:1,n=t.deltaX*s,i=t.deltaY*s;if(Math.abs(n)>Math.abs(i))return t.preventDefault(),void this.panBy(n);t.ctrlKey||t.metaKey||e.contains(document.activeElement)?(t.preventDefault(),this._zooming=!0,clearTimeout(this._zoomTimer),this._zoomTimer=setTimeout(()=>{this._zooming=!1,this._scheduleRender()},150),this.zoomBy(Math.exp(.002*i),this._ratioAt(t.clientX))):this._showHint()},{passive:!1});const s=new Map;let n=null,i=null;const o=(e,t)=>{n={id:e,x:t,start:this.start,span:this.end-this.start,moved:!1}},a=()=>{const[e,t]=s.values();return{dist:Math.max(Math.hypot(e.x-t.x,e.y-t.y),1),ratio:this._ratioAt((e.x+t.x)/2)}},r=()=>{const{dist:e,ratio:t}=a(),s=this.end-this.start;i={dist:e,span:s,anchor:this.start+s*t}};e.addEventListener("pointerdown",t=>{if(0===t.button)if(s.set(t.pointerId,{x:t.clientX,y:t.clientY}),1===s.size)this._suppressClick=!1,o(t.pointerId,t.clientX);else if(2===s.size){for(const t of s.keys())e.setPointerCapture(t);r(),n=null,this._zooming=!0,e.classList.add("ck-dragging")}}),e.addEventListener("pointermove",t=>{const o=s.get(t.pointerId);if(!o)return;if(o.x=t.clientX,o.y=t.clientY,i){const{dist:e,ratio:t}=a(),s=this._clampSpan(i.span*i.dist/e),n=i.anchor-s*t;return void this._setView(n,n+s)}if(!n||t.pointerId!==n.id)return;const r=t.clientX-n.x;if(!n.moved){if(Math.abs(r)<4)return;n.moved=!0,e.setPointerCapture(t.pointerId),e.classList.add("ck-dragging")}const l=n.start-r/this._scale();this._setView(l,l+n.span)});const l=t=>{if(s.delete(t.pointerId)){if(i){if(s.size>=2)return void r();i=null,this._suppressClick=!0,this._zooming=!1,this._scheduleRender();const[e]=s;if(e)return o(e[0],e[1].x),void(n.moved=!0)}else n?.id===t.pointerId&&n.moved&&(this._suppressClick=!0);s.size||(n=null,e.classList.remove("ck-dragging"))}};e.addEventListener("pointerup",l),e.addEventListener("pointercancel",l),e.addEventListener("click",e=>{if(this._suppressClick)return void(this._suppressClick=!1);const t=e.target.closest(".ck-event")?.dataset.id;null!=t&&this.toggle(t)}),e.addEventListener("keydown",t=>{const s=.1*e.clientWidth,n={ArrowLeft:()=>this.panBy(-s),ArrowRight:()=>this.panBy(s),"+":()=>this.zoomBy(1/1.5),"=":()=>this.zoomBy(1/1.5),"-":()=>this.zoomBy(1.5),Escape:()=>this.clearSelection()};n[t.key]&&(t.preventDefault(),n[t.key]())}),this.storyEl.addEventListener("click",e=>{const t=e.target.closest(".ck-remove"),s=e.target.closest(".ck-end-jump"),n=e.target.closest(".ck-locate"),i=e.target.closest(".ck-tag");i?this._toggleTag(i.dataset.tag,i):t?this.deselect(t.dataset.id):s?this._jumpToCard(s.dataset.id):n?this.reveal(n.dataset.id):e.target.closest(".ck-clear")&&this.clearSelection()}),this._resizeObserver=new ResizeObserver(()=>this._scheduleRender()),this._resizeObserver.observe(e),this._onFontsLoaded=()=>{this._measureLabels(),this._invalidateLayout()},document.fonts?.addEventListener("loadingdone",this._onFontsLoaded)}_toggleTag(e,t){const s=new Set(this.items.filter(t=>t.tags.includes(e)).map(e=>e.id)),n=[...s].every(e=>this.selected.has(e))?[...this.selected].filter(e=>!s.has(e)):[...new Set([...this.selected,...s])],i=t.closest(".ck-card")?.dataset.id,o=null!=i&&t===document.activeElement;if(this._setSelection(n),!o)return;const a=[...this.storyEl.querySelectorAll(".ck-card")].find(e=>e.dataset.id===i);[...a?.querySelectorAll(".ck-tag")??[]].find(t=>t.dataset.tag===e)?.focus()}_tagStates(){const e=new Map;for(const t of this.items){const s=this.selected.has(t.id);for(const n of t.tags){const t=e.get(n)??{some:!1,all:!0};t.some||=s,t.all&&=s,e.set(n,t)}}return new Map([...e].map(([e,t])=>[e,t.all?"true":t.some?"mixed":"false"]))}_syncTags(){const e=this._tagStates();for(const t of this.root.querySelectorAll(".ck-tag"))t.setAttribute("aria-pressed",e.get(t.dataset.tag)??"false")}_toggleDim(e){e.setAttribute("aria-pressed",this.root.classList.toggle("ck-dim"))}_toggleTextSize(e){const t=this.root.classList.toggle("ck-large-text");e.setAttribute("aria-pressed",t),this._measureLabels(),this._invalidateLayout()}_setSelection(e){this.selected=new Set(e);for(const e of this.lanesEl.querySelectorAll(".ck-event")){const t=this.selected.has(e.dataset.id);e.classList.toggle("ck-selected",t),e.setAttribute("aria-pressed",t)}this._renderStory(),this._syncTags(),this._stateChanged(),this.options.onSelectionChange?.(this.getSelection())}_setView(e,t){this.start=e,this.end=t,this._scheduleRender(),this._stateChanged()}_setHidden(e){this.hidden=new Set(e),this._renderLegend(),this._invalidateLayout(),this._stateChanged()}_setHover(e){if(e!==this._hoverId){this._hoverId=e;for(const t of this.root.querySelectorAll(".ck-event, .ck-card, .ck-end-jump"))t.classList.toggle("ck-hover",t.dataset.id===e)}}_stateChanged(){this.options.syncUrl&&(clearTimeout(this._hashTimer),this._hashTimer=setTimeout(()=>this._writeHash(),250))}_readHash(){const e=y(),t=t=>{const s=e.get(t);if(!s)return[];try{return s.split(",").map(decodeURIComponent)}catch{return[]}},s={},n=e.get("ck-view")?.split(",").map(Number);2===n?.length&&n.every(Number.isFinite)&&n[0]<n[1]&&([s.start,s.end]=n),e.has("ck-sel")&&(s.selected=t("ck-sel")),e.has("ck-hide")&&(s.hidden=t("ck-hide")),this.setState(s)}_writeHash(){const{start:e,end:t,selected:s,hidden:n}=this.getState(),i=y(),o=Math.min(6,Math.max(0,Math.ceil(3-Math.log10(t-e))));i.set("ck-view",`${+e.toFixed(o)},${+t.toFixed(o)}`);for(const[e,t]of[["ck-sel",s],["ck-hide",n]])t.length?i.set(e,t.map(encodeURIComponent).join(",")):i.delete(e);const a=[...i].map(([e,t])=>null==t?e:`${e}=${t}`).join("&");history.replaceState(history.state,"",`${location.pathname}${location.search}#${a}`)}_clampSpan(e){const t=this.options.maxSpan??Math.max(3*this._dataSpan,100);return Math.min(Math.max(e,this.options.minSpan),t)}_scale(){return(this.viewport.clientWidth||1)/(this.end-this.start)}_ratioAt(e){const t=this.viewport.getBoundingClientRect();return(e-t.left)/t.width}_toItem(e,t){const n=s=>{try{return i(e[s])}catch(n){const i=n.message.replace(/^Chroniko: /,"");throw new Error(`Chroniko: event "${e.title??t}" has an invalid ${s}: ${i}`)}},o=n("start");if(!o)throw new Error(`Chroniko: event "${e.title??t}" has no start date`);const a=n("end");return{event:e,id:t,start:o,end:a,from:o.value,to:a?a.value+s[a.precision]:null,category:e.category??null,tags:[...new Set([e.tags??[]].flat().map(e=>String(e).trim()).filter(Boolean))]}}_checkIds(e){const t=new Map;for(const s of e){const e=t.get(s.id);if(e)throw new Error(`Chroniko: events "${e.event.title}" and "${s.event.title}" share the id "${s.id}"; ids must be unique`);t.set(s.id,s)}}_insert(e){let t=0,s=this.items.length;for(;t<s;){const n=t+s>>1;this.items[n].from<=e.from?t=n+1:s=n}this.items.splice(t,0,e)}_assignColors(e){const s=new Set(Object.values(this.options.colors)),n=t.filter(e=>!s.has(e));for(const s of e){const e=s.category;e&&!this.colorOf.has(e)&&this.colorOf.set(e,this.options.colors[e]??n[this._paletteNext++%n.length]??t[0]),s.color=s.event.color??this.colorOf.get(e)??t[0]}}_itemsChanged(){this.categories=[...new Set(this.items.map(e=>e.category).filter(Boolean))];const[e,t]=this._extent();this._dataSpan=t-e}_dataChanged(e){this._pendingData={story:this._pendingData?.story||e},this._scheduleRender()}_flushData(){const{story:e}=this._pendingData;this._pendingData=null,this._renderLegend(),this._renderTagbar(),e&&this._renderStory(),this._syncTags()}_extent(){let e=1/0,t=-1/0;for(const s of this.items)e=Math.min(e,s.from),t=Math.max(t,s.to??s.from);return this.items.length?[e,t]:[0,0]}_measureLabels(e=this.items){const t=this._ctx??=document.createElement("canvas").getContext("2d"),s=document.createElement("span");s.className="ck-label",s.style.visibility="hidden",this.lanesEl.append(s);const n=getComputedStyle(s);t.font=`${n.fontStyle} ${n.fontWeight} ${n.fontSize} ${n.fontFamily}`,t.letterSpacing="normal"===n.letterSpacing?"0px":n.letterSpacing,t.wordSpacing="normal"===n.wordSpacing?"0px":n.wordSpacing;const i=n.textTransform;s.remove();for(const s of e){let e=s.event.title??"";"uppercase"===i?e=e.toUpperCase():"lowercase"===i&&(e=e.toLowerCase()),s.labelWidth=t.measureText(e).width}}_scheduleRender(){this._frame||(this._frame=requestAnimationFrame(()=>{this._frame=0,this._render()}))}_render(){this._pendingData&&this._flushData();const e=this.viewport.clientWidth;if(!e)return;const t=e/(this.end-this.start),s=e=>(e-this.start)*t,n=null==this._layoutScale||Math.abs(t/this._layoutScale-1)>1e-6;(null==this._layoutScale||n&&!this._zooming)&&this._layout(t),this._renderAxis(t,s),this._renderEvents(e,s)}_layout(e){this._layoutScale=e,this._laneEnds=[],this._pack(this.items)}_pack(e){const t=this._layoutScale,s=this._laneEnds;for(const n of e){if(n.category&&this.hidden.has(n.category)){n.lane=-1;continue}const e=null!=n.to,i=n.from*t,o=e?n.to*t:i,a=e?i:i-5,r=e?6:16,l=Math.max(o,a+r+n.labelWidth)+12;let d=s.findIndex(e=>e<=a);d<0?d=s.push(l)-1:s[d]=l,n.lane=d}this._laneCount=s.length}_invalidateLayout(){this._layoutScale=null,this._scheduleRender()}_renderAxis(e,t){const s=n.find(t=>t*e>=90)??n.at(-1);let i="",o="";for(let e=Math.ceil(this.start/s);e*s<=this.end;e++){const n=e*s,a=t(n).toFixed(1);i+=`<span class="ck-tick" style="left:${a}px">${f($(n,s,this.m))}</span>`,o+=`<span class="ck-gridline" style="left:${a}px"></span>`}this.axisEl.innerHTML=i,this.gridEl.innerHTML=o}_renderEvents(e,t){const s=this.lanesEl.contains(document.activeElement)?document.activeElement.dataset.id:null,n=this._revealing,i=n?performance.now()-n.at:1/0;let o="";for(const s of this.items){if(s.lane<0)continue;const a=null!=s.to,r=t(s.from),l=a?t(s.to):r,d=a?r:r-5,h=a?Math.min(Math.max(0,-r),Math.max(0,l-r-s.labelWidth-6))+6:16,c=Math.max(l,d+h+s.labelWidth);if((a?l:c)<0||d>e)continue;const m=12+30*s.lane,u=this.selected.has(s.id),p=n?.id===s.id&&i<1500,y=`ck-event ${a?"ck-range":"ck-point"}${u?" ck-selected":""}${this._hoverClass(s)}${p?" ck-flash":""}`,$=`--ck-color:${f(s.color)};left:${d.toFixed(1)}px;top:${m}px`+(p?`;animation-delay:-${Math.round(i)}ms`:""),v=f(s.event.title??""),_=`type="button" class="${y}" data-id="${f(s.id)}" aria-pressed="${u}"\n title="${v} · ${f(g(s,this.m))}"`;o+=a?`<button ${_} style="${$};width:${Math.max(l-r,4).toFixed(1)}px">\n <span class="ck-label" style="left:${h.toFixed(1)}px">${v}</span></button>`:`<button ${_} style="${$}">\n <span class="ck-dot"></span><span class="ck-label">${v}</span></button>`}const a=24+30*this._laneCount;if(this.lanesEl.innerHTML=`<div class="ck-lanes-inner" style="height:${a}px">${o}</div>`,null!=s){([...this.lanesEl.querySelectorAll(".ck-event")].find(e=>e.dataset.id===s)??this.viewport).focus({preventScroll:!0})}n?.pending&&this._finishReveal(n)}_finishReveal(e){e.pending=!1;const t=[...this.lanesEl.querySelectorAll(".ck-event")].find(t=>t.dataset.id===e.id);if(!t)return;const s=this.lanesEl;(t.offsetTop<s.scrollTop||t.offsetTop+t.offsetHeight>s.scrollTop+s.clientHeight)&&(s.scrollTop=t.offsetTop-(s.clientHeight-t.offsetHeight)/2);const n=matchMedia("(prefers-reduced-motion: reduce)").matches;this.viewport.scrollIntoView({block:"nearest",behavior:n?"auto":"smooth"}),t.focus({preventScroll:!0})}_renderLegend(){this.legendEl.innerHTML=this.categories.map(e=>`<button type="button" class="ck-legend-item" data-category="${f(e)}"\n aria-pressed="${!this.hidden.has(e)}" style="--ck-color:${f(this.colorOf.get(e))}">\n <span class="ck-swatch"></span>${f(this._categoryLabel(e))}</button>`).join("")}_renderTagbar(){const e=new Map;for(const t of this.items)for(const s of t.tags)e.set(s,(e.get(s)??0)+1);const t=[...e.keys()].sort((e,t)=>this._tagLabel(e).localeCompare(this._tagLabel(t),this.options.language));this.tagbarEl.hidden=!t.length,this.tagbarEl.querySelector(".ck-count").textContent=t.length,this.tagbarEl.querySelector(".ck-tags").innerHTML=t.map(t=>`<li><button type="button" class="ck-tag" data-tag="${f(t)}" aria-pressed="false">${f(this._tagLabel(t))} <span class="ck-tag-count">${e.get(t)}</span></button></li>`).join("")}_renderStory(){const e=this.items.filter(e=>this.selected.has(e.id)),t="right"===this.options.storyPosition;if(this.storyEl.hidden=!e.length&&!t,this.storyEl.classList.toggle("ck-empty",!e.length),this.root.classList.toggle("ck-has-selection",e.length>0),!e.length)return void(this.storyEl.innerHTML=t?`<p class="ck-story-placeholder">${f(this.m.placeholder)}</p>`:"");const s=e.map(e=>({item:e,at:e.from,isEnd:!1}));for(const t of e)t.end&&t.end.value>t.from&&s.push({item:t,at:t.end.value,isEnd:!0});s.sort((e,t)=>e.at-t.at||t.isEnd-e.isEnd),this.storyEl.innerHTML=`\n <div class="ck-story-header">\n <span class="ck-story-title">${f(this.m.selectedEvents)} <span class="ck-count">${this.m.number.format(e.length)}</span></span>\n <button type="button" class="ck-clear">${f(this.m.clearAll)}</button>\n </div>\n <ol class="ck-story-list">${s.map(e=>e.isEnd?this._storyEnd(e.item):this._storyCard(e.item)).join("")}</ol>`}_storyEnd(e){const t=this.m,s=f(e.event.title??""),n=f(c(e.end,t)),i=f(u(e.start,e.end,t));return`\n <li class="ck-end" style="--ck-color:${f(e.color)}">\n <button type="button" class="ck-end-jump${this._hoverClass(e)}" data-id="${f(e.id)}"\n aria-label="${t.endsAria(s,n,i)}">\n <span class="ck-end-date">${n}</span>\n <span>${t.endOf(`<strong>${s}</strong>`)}</span>\n ${i?`<span class="ck-end-duration">${t.lasted(i)}</span>`:""}\n </button>\n </li>`}_jumpToCard(e){const t=[...this.storyEl.querySelectorAll(".ck-card")].find(t=>t.dataset.id===e);if(!t)return;const s=matchMedia("(prefers-reduced-motion: reduce)").matches;t.scrollIntoView({block:"nearest",behavior:s?"auto":"smooth"}),t.focus({preventScroll:!0}),t.classList.remove("ck-flash"),t.offsetWidth,t.classList.add("ck-flash")}_storyCard(e){const t=e.event,s=t.url&&/^https?:\/\//i.test(t.url)?t.url:null;return`\n <li class="ck-card${this._hoverClass(e)}" data-id="${f(e.id)}" tabindex="-1"\n style="--ck-color:${f(e.color)}">\n <button type="button" class="ck-remove" data-id="${f(e.id)}"\n aria-label="${this.m.remove(f(t.title??""))}">×</button>\n <div class="ck-meta">\n ${e.category?`<span class="ck-badge">${f(this._categoryLabel(e.category))}</span>`:""}\n <span>${f(g(e,this.m))}</span>\n </div>\n <h3 class="ck-title">${f(t.title??"")}</h3>\n ${t.description?`<p class="ck-description">${f(t.description)}</p>`:""}\n ${e.tags.length?`<ul class="ck-tags" aria-label="${f(this.m.tags)}">${e.tags.map(e=>`<li><button type="button" class="ck-tag" data-tag="${f(e)}" aria-pressed="false">${f(this._tagLabel(e))}</button></li>`).join("")}</ul>`:""}\n <div class="ck-card-actions">\n <button type="button" class="ck-locate" data-id="${f(e.id)}">${f(this.m.showOnTimeline)}</button>\n ${s?`<a class="ck-link" href="${f(s)}" target="_blank" rel="noopener">${f(this.m.readMore)}</a>`:""}\n </div>\n </li>`}_hoverClass(e){return this._hoverId===e.id?" ck-hover":""}_categoryLabel(e){return this.options.categoryLabels[e]??e}_tagLabel(e){return this.options.tagLabels[e]??e}}export{v as Chroniko,h as formatDate,m as formatDuration,d as formatYear,i as parseDate};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "chroniko",
3
- "version": "0.3.1",
3
+ "version": "0.4.0",
4
4
  "description": "Render historical events on a single zoomable time axis. Plain HTML, CSS and JavaScript, no dependencies.",
5
5
  "license": "Apache-2.0",
6
6
  "type": "module",