chroniko 0.0.0-stage → 0.2.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 ADDED
@@ -0,0 +1,43 @@
1
+ # Changelog
2
+
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
+
5
+ ## [0.2.0] - 2026-10-15
6
+
7
+ ### Added
8
+
9
+ - `language` option: translates the toolbar, story, screen-reader labels, dates and durations. Built in: `en` (default), `zh-Hant`, `zh-Hans`, `yue`, `ja`, `ko`, `fr`, `de`, `it`, `es`, `pt`, `pl`, `nl`. An unknown code throws. The root element gets a matching `lang` attribute.
10
+ - `uiText` option: replaces individual UI strings of the chosen language.
11
+ - `categoryLabels` option: text shown for each category in the legend and on cards, while the category name stays the key for colors, the URL hash and `getState()`.
12
+ - `formatDate`, `formatDuration` and `formatYear` take an optional `language` argument (default `'en'`).
13
+ - The example page has a language dropdown (also `?lang=<code>`) and shows translated category labels for every built-in language except English.
14
+ - `textSizeToggle` option: shows an **Aa** button in the toolbar that switches the event and category labels from 13px to 14px and the time axis labels from 12px to 13px. The lanes are repacked for the new size.
15
+
16
+ ### Fixed
17
+
18
+ - Labels no longer overlap or leave gaps when a web font finishes loading after the events are set: label widths are measured again and the lanes are repacked.
19
+ - Label widths now use the styles on `.ck-label` itself, including `font-style`, `letter-spacing`, `word-spacing` and `text-transform: uppercase | lowercase`, not just the font on `.ck-lanes`.
20
+
21
+ ## [0.1.1] - 2026-10-14
22
+
23
+ ### Added
24
+
25
+ - `storyPosition` option: `'below'` (default) keeps the story under the timeline; `'right'` puts it beside the timeline. The toolbar and timeline stick to the top of the window while the page scrolls the story. When nothing is selected, the story column shows a placeholder so the first click doesn't resize the timeline. When the component is 640px wide or narrower, it falls back to the stacked layout.
26
+ - `split` option: with `storyPosition: 'right'`, the timeline's share of the width, between 0 and 1 (default `0.6`).
27
+ - `--ck-sticky-top` custom property (default `0px`) to keep the sticky timeline below a fixed page header.
28
+ - The example page shows the side-by-side layout when opened with `?story=right`.
29
+
30
+ ### Changed
31
+
32
+ - The constructor throws if `storyPosition` or `split` is invalid.
33
+ - The toolbar and timeline are now wrapped in `.ck-main`, and together with the story in `.ck-layout`. Custom CSS that relies on direct children of `.chroniko` (e.g. `.chroniko > .ck-toolbar`) needs updating.
34
+ - The README lists the options in a table with their types, whether they're required, and their defaults.
35
+ - Chroniko is published on npm. The README's jsDelivr links now load it from npm (`cdn.jsdelivr.net/npm/chroniko@0.1.1/...`) instead of GitHub.
36
+
37
+ ## [0.1.0] - 2026-10-14
38
+
39
+ - Initial release.
40
+
41
+ [0.2.0]: https://github.com/ykyuen/chroniko/compare/0.1.1...0.2.0
42
+ [0.1.1]: https://github.com/ykyuen/chroniko/compare/0.1.0...0.1.1
43
+ [0.1.0]: https://github.com/ykyuen/chroniko/releases/tag/0.1.0
package/LICENSE ADDED
@@ -0,0 +1,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
package/README.md CHANGED
@@ -1,3 +1,253 @@
1
- # Temporary Holding Version
1
+ # chroniko
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ 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/).
4
+
5
+ ## Install
6
+
7
+ ```sh
8
+ npm install chroniko
9
+ ```
10
+
11
+ ## Run the example
12
+
13
+ ```sh
14
+ npm start # http://localhost:3000/
15
+ ```
16
+
17
+ Add `?story=right` to the example's URL to see the [story beside the timeline](#story-beside-the-timeline), or `?lang=ja` (any [language code](#languages)) to see the UI in another language. Both can be combined, e.g. `?story=right&lang=zh-Hant`.
18
+
19
+ ## Usage
20
+
21
+ The minified files can be loaded from jsDelivr without installing anything.
22
+
23
+ ```html
24
+ <!DOCTYPE html>
25
+ <html lang="en">
26
+ <head>
27
+ <meta charset="utf-8">
28
+ <meta name="viewport" content="width=device-width, initial-scale=1">
29
+ <title>Chroniko</title>
30
+ <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/chroniko@0.2.0/dist/chroniko.min.css">
31
+ </head>
32
+ <body>
33
+ <div id="timeline"></div>
34
+
35
+ <script type="module">
36
+ import { Chroniko } from 'https://cdn.jsdelivr.net/npm/chroniko@0.2.0/dist/chroniko.min.js';
37
+
38
+ const timeline = new Chroniko('#timeline', {
39
+ events: [
40
+ { id: 'caesar', title: 'Assassination of Julius Caesar', start: '-44-03-15', category: 'politics' },
41
+ { id: 'ww2', title: 'World War II', start: '1939-09-01', end: '1945-09-02', category: 'war',
42
+ description: 'The deadliest conflict in human history.' },
43
+ ],
44
+ onSelectionChange: (events) => console.log(events),
45
+ });
46
+ </script>
47
+ </body>
48
+ </html>
49
+ ```
50
+
51
+ ### Event fields
52
+
53
+ | Field | Required | Notes |
54
+ | ------------- | -------- | ----- |
55
+ | `title` | yes | |
56
+ | `start` | yes | Year number, `"YYYY"`, `"YYYY-MM"` or `"YYYY-MM-DD"`. Negative years are BCE. A date that doesn't exist (month 13, 31 April) throws an error naming the event. 29 February is accepted in any year, since historical dates may follow the Julian calendar. |
57
+ | `end` | no | Same formats as `start`. If set, the event is drawn as a bar. |
58
+ | `id` | no | Must be unique. See [Event ids](#event-ids). |
59
+ | `category` | no | Used for colors and the legend filter. |
60
+ | `description` | no | Shown in the detail panel. |
61
+ | `url` | no | `http(s)` link shown in the detail panel. |
62
+ | `color` | no | Overrides the category color. |
63
+
64
+ ### Event ids
65
+
66
+ An event's `id` identifies it for `select(id)`, `deselect(id)`, `toggle(id)` and for keeping the selection across `setEvents` calls. Ids are compared as strings, so `7` and `'7'` are the same id.
67
+
68
+ If an event has no `id`, one is generated from its category and its 0-based position in the `events` array: the category is lowercased and each run of whitespace becomes a hyphen. For example, the event at position 3 in category `"Olympic Game"` gets `"olympic-game-3"`. An event without a category uses `event`, e.g. `"event-3"`.
69
+
70
+ 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.
71
+
72
+ 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.
73
+
74
+ ### Options
75
+
76
+ | Option | Type | Required | Default | Notes |
77
+ | ------------------- | -------------------- | -------- | ------- | ----- |
78
+ | `events` | `object[]` | no | `[]` | Array of events. See [Event fields](#event-fields). |
79
+ | `start` | `number \| string` | no | Fit all events | Start of the initial visible range. Same formats as event dates, or a fractional year. Only used if `end` is also set. |
80
+ | `end` | `number \| string` | no | Fit all events | End of the initial visible range. Only used if `start` is also set. |
81
+ | `colors` | `object` | no | `{}` | Category → color, e.g. `{ war: '#c0392b' }`. Categories without a color get one from the built-in palette. |
82
+ | `minSpan` | `number` | no | `1/12` (one month) | Smallest visible span in years. |
83
+ | `maxSpan` | `number` | no | 3× the data span, at least 100 years | Largest visible span in years. |
84
+ | `onSelectionChange` | `function(events)` | no | N/A | Called with the selected events in chronological order. |
85
+ | `syncUrl` | `boolean` | no | `false` | Keep the view, selection and hidden categories in the URL hash. See [Sharing](#sharing). |
86
+ | `storyPosition` | `'below' \| 'right'` | no | `'below'` | Where the [story](#story-view) goes. See [Story beside the timeline](#story-beside-the-timeline). |
87
+ | `split` | `number` | no | `0.6` | With `storyPosition: 'right'`, the timeline's share of the width, between 0 and 1 (exclusive). The story gets the rest. |
88
+ | `textSizeToggle` | `boolean` | no | `false` | Show an **Aa** button in the toolbar that switches the event and category labels from 13px to 14px and the time axis labels from 12px to 13px. |
89
+ | `language` | `string` | no | `'en'` | Language of the timeline's own text and dates. See [Languages](#languages). An unknown code throws. |
90
+ | `uiText` | `object` | no | N/A | Replaces individual UI strings of the chosen language. See [Languages](#languages). |
91
+ | `categoryLabels` | `object` | no | `{}` | Category → text shown in the legend and on cards, e.g. `{ war: '戰爭' }`. Categories without a label show their name. |
92
+
93
+ ### Methods
94
+
95
+ `setEvents(events)`, `zoomTo(start, end)`, `zoomBy(factor)`, `panBy(px)`, `fit()`, `select(id)`, `deselect(id)`, `toggle(id)`, `clearSelection()`, `getSelection()`, `reveal(id)`, `getState()`, `setState(state)`, `destroy()`.
96
+
97
+ `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.
98
+
99
+ `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.
100
+
101
+ ### Sharing
102
+
103
+ `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.
104
+
105
+ With `syncUrl: true`, the timeline keeps this state in the URL hash, so the address bar is always a shareable link:
106
+
107
+ ```
108
+ #ck-view=1300,1500&ck-sel=black-death,constantinople&ck-hide=science
109
+ ```
110
+
111
+ - Opening the link restores the view, selection and hidden categories. Editing the hash on an open page applies it too.
112
+ - The URL is updated with `history.replaceState` shortly after each change, so it doesn't fill the back-button history. Loading the page doesn't change the URL.
113
+ - Other hash parameters are kept, but the hash no longer works as a plain `#section` anchor once the timeline writes to it. Use `syncUrl` on one timeline per page.
114
+ - Generated ids depend on position (see [Event ids](#event-ids)), so give events explicit ids if shared links must survive changes to the event list.
115
+ - When a link restores a selection, `onSelectionChange` is called during construction, before `new Chroniko(...)` returns.
116
+
117
+ ### Navigation
118
+
119
+ Drag, use the arrow keys or scroll sideways to pan. To zoom, use the +/− buttons or keys, or hold Ctrl (⌘ on macOS) while scrolling; trackpad pinch works too. On touch screens, pinch with two fingers to zoom around the point between them, and slide both fingers to pan while zooming. Once the timeline has focus (click it), a plain vertical scroll zooms as well, and a faint ring around the timeline shows this mode is on. Until then it scrolls the page, so the timeline doesn't trap readers scrolling past it.
120
+
121
+ Events keep their row while you pan. While a wheel, trackpad or touch zoom is in progress the rows stay put and are rearranged once the gesture settles.
122
+
123
+ ### Story view
124
+
125
+ Clicking an event toggles its selection. Selected events are listed below the timeline (or beside it, see below) in chronological order. Each event appears at its start date, and an event with an `end` also gets a small "End of …" marker at its end date, showing how long it lasted (e.g. "lasted 2 years, 11 months"); clicking the marker jumps to the event's card. Durations use the coarser precision of the two dates (a year-only date gives whole years) and show at most two units. There is no year zero, so 27 BCE to 14 CE lasted 40 years. The same text is available as `formatDuration(parseDate(start), parseDate(end), language)`, exported alongside `parseDate`, `formatDate(date, language)` and `formatYear(year, language)`; `language` defaults to `'en'`. **Show on timeline** on a card calls `reveal(id)` for that event. Hovering or focusing an event, its card or its end marker highlights all three. Press Esc or **Clear all** to clear the selection.
126
+
127
+ #### Story beside the timeline
128
+
129
+ With `storyPosition: 'right'`, the toolbar and timeline take the left `split` of the width and the story takes the rest:
130
+
131
+ ```js
132
+ new Chroniko('#timeline', { events, storyPosition: 'right', split: 0.6 });
133
+ ```
134
+
135
+ - The timeline sticks to the top of the browser window while the page scrolls the story beside it. Scrolling over the timeline scrolls the story too, until you click the timeline. Its height is `--ck-height` (`420px` by default), as in the stacked layout.
136
+ - If your page has a fixed header, set `--ck-sticky-top` on `.chroniko` to its height (e.g. `--ck-sticky-top: 56px`) so the timeline sticks below the header.
137
+ - The story column is shown even when nothing is selected, with a short hint, so the first click doesn't resize the timeline.
138
+ - When the component is 640px wide or narrower, it falls back to the stacked layout. This uses the component's own width, not the window's, so it also works in a narrow column. It relies on CSS container queries and `overflow: clip`, which all current browsers support.
139
+
140
+ ### Languages
141
+
142
+ Set `language` when creating the timeline to translate its own text: the toolbar, the story, screen-reader labels, and how dates and durations are written. The language is fixed for the timeline's lifetime.
143
+
144
+ ```js
145
+ new Chroniko('#timeline', { events, language: 'zh-Hant' });
146
+ ```
147
+
148
+ | Code | Language | Example date | Example duration |
149
+ | --------- | -------- | ------------ | ---------------- |
150
+ | `en` | English (default) | 19 Mar 1644 · 221 BCE | 3 years, 2 months |
151
+ | `zh-Hant` | Traditional Chinese | 1644年3月19日 · 公元前221年 | 3年2個月 |
152
+ | `zh-Hans` | Simplified Chinese | 1644年3月19日 · 公元前221年 | 3年2个月 |
153
+ | `yue` | Cantonese (colloquial, traditional characters) | 1644年3月19日 · 公元前221年 | 3年2個月 |
154
+ | `ja` | Japanese | 1644年3月19日 · 紀元前221年 | 3年2か月 |
155
+ | `ko` | Korean | 1644년 3월 19일 · 기원전 221년 | 3년 2개월 |
156
+ | `fr` | French | 19 mars 1644 · 221 av. J.-C. | 3 ans et 2 mois |
157
+ | `de` | German | 19. März 1644 · 221 v. Chr. | 3 Jahre, 2 Monate |
158
+ | `it` | Italian | 19 mar 1644 · 221 a.C. | 3 anni e 2 mesi |
159
+ | `es` | Spanish | 19 mar 1644 · 221 a. C. | 3 años y 2 meses |
160
+ | `pt` | Portuguese | 19 mar 1644 · 221 a.C. | 3 anos e 2 meses |
161
+ | `pl` | Polish | 19 mar 1644 · 221 p.n.e. | 3 lata, 2 miesiące |
162
+ | `nl` | Dutch | 19 mrt 1644 · 221 v.Chr. | 3 jaar en 2 maanden |
163
+
164
+ - **Your events aren't translated.** Titles, descriptions and category names come from your data, so pass events in the reader's language. Keep the same `id`s across languages so shared links work in every language.
165
+ - **Category names are keys.** They're used by `colors`, the URL hash and `getState()`, so translate them with `categoryLabels` rather than in the events: `{ category: 'war' }` plus `categoryLabels: { war: 'Krieg' }`.
166
+ - The component's root gets the `lang` attribute, so screen readers use the right pronunciation and browsers use the right Chinese, Japanese or Korean character forms.
167
+ - `uiText` replaces individual strings, e.g. `uiText: { fit: 'Show all' }`. The keys, and what each function receives, are listed in [`src/locales/en.js`](src/locales/en.js). Keys you leave out keep the language's text.
168
+ - To add a language, copy `src/locales/en.js`, translate it, and register it in `src/locales/index.js`.
169
+
170
+ ### Colors
171
+
172
+ There are two kinds of color: the colors of the events, set from JavaScript, and the colors of the component itself (background, text, borders), set with CSS.
173
+
174
+ #### Event colors
175
+
176
+ Each event's color is picked in this order:
177
+
178
+ 1. The event's own `color` field.
179
+ 2. The color of its category in the `colors` option.
180
+ 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.
181
+
182
+ ```js
183
+ new Chroniko('#timeline', {
184
+ colors: { war: '#c0392b', politics: '#2c7be5' },
185
+ events: [
186
+ { title: 'World War II', start: 1939, end: 1945, category: 'war' },
187
+ { title: 'Moon landing', start: '1969-07-20', category: 'science' }, // palette color
188
+ { title: 'Fall of the Berlin Wall', start: '1989-11-09', category: 'politics',
189
+ color: 'gold' }, // overrides 'politics'
190
+ ],
191
+ });
192
+ ```
193
+
194
+ Any CSS color works, e.g. `'#c0392b'`, `'rgb(192 57 43)'`, `'tomato'` or `'var(--my-war-color)'`. The legend uses the category colors, so an event with its own `color` doesn't change its category's legend entry. To change colors after construction, pass new events with `setEvents(events)`.
195
+
196
+ Event colors are the same in light and dark mode. To use a different color in each, point the option at a CSS variable of your own and set that variable per mode:
197
+
198
+ ```js
199
+ colors: { war: 'var(--war-color)' }
200
+ ```
201
+
202
+ ```css
203
+ .chroniko { --war-color: #c0392b; }
204
+ @media (prefers-color-scheme: dark) {
205
+ .chroniko { --war-color: #ff7b72; }
206
+ }
207
+ ```
208
+
209
+ #### Component colors
210
+
211
+ The component's colors are CSS custom properties on `.chroniko`:
212
+
213
+ | Property | Used for | Light | Dark |
214
+ | -------------- | -------- | --------- | --------- |
215
+ | `--ck-bg` | Timeline and card background | `#ffffff` | `#0d1117` |
216
+ | `--ck-surface` | Toolbar and story list background | `#f6f7f9` | `#161b22` |
217
+ | `--ck-fg` | Text | `#1f2328` | `#e6edf3` |
218
+ | `--ck-muted` | Secondary text, axis labels | `#656d76` | `#8d96a0` |
219
+ | `--ck-border` | Borders and dividers | `#d8dee4` | `#30363d` |
220
+ | `--ck-grid` | Grid lines behind the events | `#eef1f4` | `#1c2128` |
221
+ | `--ck-focus` | Focus rings and links | `#0969da` | `#4493f8` |
222
+
223
+ Override them in your own stylesheet, loaded after `chroniko.min.css`:
224
+
225
+ ```css
226
+ .chroniko {
227
+ --ck-bg: #fffdf7;
228
+ --ck-surface: #f5f0e6;
229
+ --ck-border: #e0d6c3;
230
+ }
231
+ ```
232
+
233
+ The dark values are set in a `prefers-color-scheme: dark` media query. A rule like the one above applies in both modes, so if your page supports dark mode, also override the dark values:
234
+
235
+ ```css
236
+ @media (prefers-color-scheme: dark) {
237
+ .chroniko {
238
+ --ck-bg: #1b1915;
239
+ --ck-surface: #24211c;
240
+ --ck-border: #3a352d;
241
+ }
242
+ }
243
+ ```
244
+
245
+ To theme one timeline only, use a more specific selector such as `#timeline.chroniko`.
246
+
247
+ ### Theming
248
+
249
+ Besides the [colors](#component-colors), you can override `--ck-height` (the timeline's height, `420px` by default) and `--ck-sticky-top` (see [Story beside the timeline](#story-beside-the-timeline)) on `.chroniko`. Dark mode follows `prefers-color-scheme`. All other class names inside the component use the `ck-` prefix (e.g. `.ck-event`, `.ck-card`), so they won't clash with your page's styles.
250
+
251
+ ## License
252
+
253
+ [Apache License 2.0](LICENSE)
@@ -0,0 +1 @@
1
+ .chroniko{--ck-height:420px;--ck-sticky-top:0px;--ck-bg:#fff;--ck-surface:#f6f7f9;--ck-fg:#1f2328;--ck-muted:#656d76;--ck-border:#d8dee4;--ck-grid:#eef1f4;--ck-focus:#0969da;background:var(--ck-bg);border:1px solid var(--ck-border);border-radius:8px;color:var(--ck-fg);font:13px/1.4 system-ui,-apple-system,Segoe UI,Roboto,sans-serif;overflow:hidden}@media (prefers-color-scheme:dark){.chroniko{--ck-bg:#0d1117;--ck-surface:#161b22;--ck-fg:#e6edf3;--ck-muted:#8d96a0;--ck-border:#30363d;--ck-grid:#1c2128;--ck-focus:#4493f8}}.chroniko button{color:inherit;font:inherit}.ck-toolbar{align-items:center;background:var(--ck-surface);border-bottom:1px solid var(--ck-border);gap:8px;justify-content:space-between;padding:8px 12px}.ck-legend,.ck-toolbar{display:flex;flex-wrap:wrap}.ck-legend{gap:6px}.ck-legend-item{align-items:center;background:var(--ck-bg);border:1px solid var(--ck-border);border-radius:999px;cursor:pointer;display:inline-flex;gap:6px;padding:3px 10px;text-transform:capitalize}.ck-legend-item[aria-pressed=false]{color:var(--ck-muted);opacity:.6}.ck-swatch{background:var(--ck-color);border:2px solid var(--ck-color);border-radius:50%;box-sizing:border-box;height:10px;width:10px}.ck-legend-item[aria-pressed=false] .ck-swatch{background:transparent}.ck-controls{display:flex;gap:4px}.ck-controls button{background:var(--ck-bg);border:1px solid var(--ck-border);border-radius:6px;cursor:pointer;height:28px;min-width:30px;padding:0 8px}.ck-controls button[aria-pressed=true]{border-color:var(--ck-focus);color:var(--ck-focus)}.ck-controls button:hover,.ck-legend-item:hover{border-color:var(--ck-muted)}.ck-viewport{cursor:grab;height:var(--ck-height);overflow:hidden;position:relative;touch-action:pan-y;user-select:none}.ck-viewport.ck-dragging{cursor:grabbing}.ck-viewport:after{box-shadow:inset 0 0 0 2px color-mix(in srgb,var(--ck-focus) 40%,transparent);content:"";inset:0;opacity:0;pointer-events:none;position:absolute;transition:opacity .15s;z-index:2}.ck-viewport:focus-within:after{opacity:1}.chroniko .ck-viewport:focus-visible{outline:none}.ck-viewport:focus-visible:after{box-shadow:inset 0 0 0 2px var(--ck-focus)}.ck-hint{background:color-mix(in srgb,var(--ck-fg) 85%,transparent);border-radius:6px;color:var(--ck-bg);left:50%;opacity:0;padding:6px 12px;pointer-events:none;position:absolute;top:50%;transform:translate(-50%,-50%);transition:opacity .2s;white-space:nowrap;z-index:1}.ck-hint.ck-visible{opacity:1}.chroniko :focus-visible{outline:2px solid var(--ck-focus);outline-offset:-2px}.ck-grid{inset:0;pointer-events:none;position:absolute}.ck-gridline{background:var(--ck-grid);bottom:0;position:absolute;top:0;width:1px}.ck-lanes{font-weight:500;inset:0 0 32px 0;overflow:hidden auto;position:absolute}.ck-large-text .ck-lanes,.ck-large-text .ck-legend-item{font-size:14px}.ck-large-text .ck-tick{font-size:13px}.ck-lanes-inner{position:relative}.ck-axis{background:var(--ck-bg);border-top:1px solid var(--ck-border);bottom:0;height:32px;left:0;position:absolute;right:0}.ck-tick{color:var(--ck-muted);font-size:12px;font-variant-numeric:tabular-nums;padding-top:8px;position:absolute;top:0;transform:translateX(-50%);white-space:nowrap}.ck-tick:before{background:var(--ck-border);content:"";height:5px;left:50%;position:absolute;top:0;width:1px}.ck-event{background:none;border:0;cursor:pointer;height:22px;margin:0;padding:0;position:absolute;text-align:left}.ck-event,.ck-label{white-space:nowrap}.ck-event:hover .ck-label{text-decoration:underline}.ck-range{background:color-mix(in srgb,var(--ck-color) 22%,transparent);border-left:3px solid var(--ck-color);border-radius:4px}.ck-range .ck-label{position:absolute;top:50%;transform:translateY(-50%)}.ck-range.ck-selected{box-shadow:0 0 0 2px var(--ck-color)}.ck-point{align-items:center;display:flex;gap:6px}.ck-dot{background:var(--ck-color);border-radius:50%;box-shadow:0 0 0 2px var(--ck-bg);flex:none;height:10px;width:10px}.ck-point.ck-selected .ck-dot{box-shadow:0 0 0 2px var(--ck-bg),0 0 0 4px var(--ck-color)}.ck-event.ck-hover{z-index:1}.ck-event.ck-hover .ck-label{text-decoration:underline}.ck-range.ck-hover{background:color-mix(in srgb,var(--ck-color) 40%,transparent)}.ck-point.ck-hover .ck-dot{transform:scale(1.3)}.ck-event.ck-flash{animation:ck-event-flash 1.5s ease-out;border-radius:6px;z-index:1}@keyframes ck-event-flash{0%,40%{box-shadow:0 0 0 4px color-mix(in srgb,var(--ck-color) 60%,transparent)}to{box-shadow:0 0 0 4px transparent}}@media (prefers-reduced-motion:reduce){.ck-event.ck-flash{animation-timing-function:step-end}}.ck-story{background:var(--ck-surface);border-top:1px solid var(--ck-border);padding:12px 16px 16px}.ck-story[hidden]{display:none}.ck-story-header{align-items:center;display:flex;gap:8px;justify-content:space-between}.ck-story-title{font-weight:600}.ck-count{background:var(--ck-border);border-radius:999px;font-size:12px;font-weight:500;margin-left:4px;padding:0 7px}.chroniko .ck-clear{background:var(--ck-bg);border:1px solid var(--ck-border);border-radius:6px;cursor:pointer;padding:3px 10px}.chroniko .ck-clear:hover{border-color:var(--ck-muted)}.ck-story-list{list-style:none;margin:0;padding:0 0 0 20px;position:relative}.ck-card{background:var(--ck-bg);border:1px solid var(--ck-border);border-left:3px solid var(--ck-color);border-radius:6px;margin-top:10px;padding:10px 44px 12px 14px;position:relative}.ck-card:before{background:var(--ck-color);border-radius:50%;box-shadow:0 0 0 2px var(--ck-surface);content:"";height:10px;left:-22px;position:absolute;top:15px;width:10px}.ck-story-list>li:not(:last-child):after{background:var(--ck-border);bottom:-26px;content:"";left:-18px;position:absolute;top:25px;width:2px}.ck-card:focus{outline:none}.ck-card.ck-flash{animation:ck-flash 1.2s ease-out}@keyframes ck-flash{0%{box-shadow:0 0 0 3px color-mix(in srgb,var(--ck-color) 55%,transparent)}to{box-shadow:0 0 0 3px transparent}}@media (prefers-reduced-motion:reduce){.ck-card.ck-flash{animation-duration:.01ms;outline:2px solid var(--ck-color)}}.ck-end{margin-top:10px;position:relative}.ck-end:before{background:var(--ck-surface);border:2px solid var(--ck-color);border-radius:50%;content:"";height:6px;left:-19px;position:absolute;top:13px;width:6px}.ck-story-list>.ck-end:not(:last-child):after{left:-15px;top:23px}.chroniko .ck-end-jump{align-items:baseline;background:none;border:1px dashed var(--ck-border);border-left:3px solid color-mix(in srgb,var(--ck-color) 50%,transparent);border-radius:6px;color:var(--ck-muted);cursor:pointer;display:flex;flex-wrap:wrap;font:inherit;font-size:13px;gap:4px 10px;padding:6px 14px;text-align:left;width:100%}.chroniko .ck-end-jump.ck-hover,.chroniko .ck-end-jump:hover{border-color:var(--ck-muted);border-left-color:var(--ck-color)}.ck-end-jump strong{color:var(--ck-fg);font-weight:600}.ck-end-date,.ck-end-duration,.ck-meta{font-size:12px}.ck-meta{align-items:center;color:var(--ck-muted);display:flex;flex-wrap:wrap;gap:8px}.ck-badge{background:color-mix(in srgb,var(--ck-color) 22%,transparent);border-radius:999px;color:var(--ck-fg);padding:1px 8px;text-transform:capitalize}.ck-title{font-size:16px;margin:4px 0 2px}.ck-description{margin:4px 0 0;max-width:70ch}.ck-card.ck-hover{border-color:color-mix(in srgb,var(--ck-color) 60%,var(--ck-border));border-left-color:var(--ck-color)}.ck-card-actions{align-items:center;display:flex;flex-wrap:wrap;gap:4px 16px;margin-top:6px}.chroniko .ck-locate,.ck-link{color:var(--ck-focus)}.chroniko .ck-locate{background:none;border:0;cursor:pointer;padding:0}.chroniko .ck-locate:hover{text-decoration:underline}.chroniko .ck-remove{background:none;border:0;border-radius:6px;color:var(--ck-muted);cursor:pointer;font-size:20px;height:28px;line-height:1;position:absolute;right:10px;top:8px;width:28px}.chroniko .ck-remove:hover{background:var(--ck-border)}.chroniko.ck-side{container:chroniko/inline-size;overflow:clip}.ck-side .ck-layout{display:grid;grid-template-columns:calc(var(--ck-split)*100%) minmax(0,1fr)}.ck-side .ck-main{align-self:start;min-width:0;position:sticky;top:var(--ck-sticky-top)}.ck-side .ck-story{border-left:1px solid var(--ck-border);border-top:0;min-width:0}.ck-story-placeholder{color:var(--ck-muted);margin:0}@container chroniko (max-width: 640px){.ck-side .ck-layout{display:block}.ck-side .ck-main{position:static}.ck-side .ck-story{border-left:0;border-top:1px solid var(--ck-border)}.ck-side .ck-story.ck-empty{display:none}}
@@ -0,0 +1 @@
1
+ const e={en:{zoomIn:"Zoom in",zoomOut:"Zoom out",fit:"Fit",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 ↗",remove:e=>`Remove ${e} from selection`,endOf:e=>`End of ${e}`,lasted:e=>`lasted ${e}`,endsAria:(e,t,n)=>`${e} ends ${t}${n?`, after ${n}`:""}. 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,n)=>`${e} ${t} ${n}`,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:"全覽",largerText:"放大文字",categories:"類別",ctrlKey:"Ctrl",viewport:e=>`時間軸。拖曳或使用方向鍵平移;按 + 和 −、${e} + 滾輪或雙指縮放。`,hint:e=>`${e} + 滾輪縮放,或先點擊時間軸`,selectedEvents:"已選事件",clearAll:"全部清除",placeholder:"點擊事件以加入此處。",showOnTimeline:"在時間軸上顯示",readMore:"了解更多 ↗",remove:e=>`從已選事件中移除「${e}」`,endOf:e=>`${e}結束`,lasted:e=>`歷時${e}`,endsAria:(e,t,n)=>`${e}於${t}結束${n?`,歷時${n}`:""}。前往事件`,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,n)=>`${n}${t}${e}日`,units:{year:{other:"#年"},month:{other:"#個月"},day:{other:"#天"}},unitJoin:"",lessThan:{year:"不足一年",month:"不足一個月",day:"不足一天"}},"zh-Hans":{zoomIn:"放大",zoomOut:"缩小",fit:"全览",largerText:"放大文字",categories:"类别",ctrlKey:"Ctrl",viewport:e=>`时间轴。拖动或使用方向键平移;按 + 和 −、${e} + 滚轮或双指缩放。`,hint:e=>`${e} + 滚轮缩放,或先点击时间轴`,selectedEvents:"已选事件",clearAll:"全部清除",placeholder:"点击事件以添加到此处。",showOnTimeline:"在时间轴上显示",readMore:"了解更多 ↗",remove:e=>`从已选事件中移除“${e}”`,endOf:e=>`${e}结束`,lasted:e=>`历时${e}`,endsAria:(e,t,n)=>`${e}于${t}结束${n?`,历时${n}`:""}。前往事件`,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,n)=>`${n}${t}${e}日`,units:{year:{other:"#年"},month:{other:"#个月"},day:{other:"#天"}},unitJoin:"",lessThan:{year:"不足一年",month:"不足一个月",day:"不足一天"}},yue:{zoomIn:"放大",zoomOut:"縮細",fit:"睇晒",largerText:"大啲字",categories:"類別",ctrlKey:"Ctrl",viewport:e=>`時間軸。拖或者用方向鍵左右移;撳 + 同 −、${e} + 碌滾輪或者用兩隻手指縮放。`,hint:e=>`${e} + 碌滾輪就可以縮放,或者先撳一下時間軸`,selectedEvents:"揀咗嘅事件",clearAll:"清晒",placeholder:"撳一下事件就會加入呢度。",showOnTimeline:"喺時間軸度睇",readMore:"睇多啲 ↗",remove:e=>`移走「${e}」`,endOf:e=>`${e}完結`,lasted:e=>`維持咗${e}`,endsAria:(e,t,n)=>`${e}喺${t}完結${n?`,維持咗${n}`:""}。去返個事件`,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,n)=>`${n}${t}${e}日`,units:{year:{other:"#年"},month:{other:"#個月"},day:{other:"#日"}},unitJoin:"",lessThan:{year:"唔夠一年",month:"唔夠一個月",day:"唔夠一日"}},ja:{zoomIn:"拡大",zoomOut:"縮小",fit:"全体表示",largerText:"文字を大きく",categories:"カテゴリ",ctrlKey:"Ctrl",viewport:e=>`タイムライン。ドラッグまたは矢印キーで移動し、+ と −、${e} + スクロール、またはピンチで拡大・縮小します。`,hint:e=>`${e} + スクロールで拡大・縮小、または先にタイムラインをクリック`,selectedEvents:"選択した出来事",clearAll:"すべて解除",placeholder:"出来事をクリックするとここに追加されます。",showOnTimeline:"タイムラインで表示",readMore:"詳しく見る ↗",remove:e=>`「${e}」を選択から外す`,endOf:e=>`${e}の終わり`,lasted:e=>`期間:${e}`,endsAria:(e,t,n)=>`${e}は${t}に終了${n?`(期間:${n})`:""}。出来事へ移動`,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,n)=>`${n}${t}${e}日`,units:{year:{other:"#年"},month:{other:"#か月"},day:{other:"#日"}},unitJoin:"",lessThan:{year:"1年未満",month:"1か月未満",day:"1日未満"}},ko:{zoomIn:"확대",zoomOut:"축소",fit:"전체 보기",largerText:"글자 크게",categories:"분류",ctrlKey:"Ctrl",viewport:e=>`타임라인. 드래그하거나 화살표 키로 이동하고, + 와 −, ${e}+스크롤 또는 핀치로 확대/축소합니다.`,hint:e=>`${e} + 스크롤로 확대/축소하거나 먼저 타임라인을 클릭하세요`,selectedEvents:"선택한 사건",clearAll:"모두 지우기",placeholder:"사건을 클릭하면 여기에 추가됩니다.",showOnTimeline:"타임라인에서 보기",readMore:"더 보기 ↗",remove:e=>`선택에서 ${e} 제거`,endOf:e=>`${e} 종료`,lasted:e=>`기간: ${e}`,endsAria:(e,t,n)=>`${e} 종료: ${t}${n?`, 기간 ${n}`:""}. 사건으로 이동`,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,n)=>`${n} ${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",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 ↗",remove:e=>`Retirer ${e} de la sélection`,endOf:e=>`Fin : ${e}`,lasted:e=>`durée : ${e}`,endsAria:(e,t,n)=>`Fin de « ${e} » : ${t}${n?`, durée ${n}`:""}. 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,n)=>`${1===e?"1er":e} ${t} ${n}`,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",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 ↗",remove:e=>`${e} aus der Auswahl entfernen`,endOf:e=>`Ende: ${e}`,lasted:e=>`Dauer: ${e}`,endsAria:(e,t,n)=>`Ende von ${e}: ${t}${n?`, Dauer ${n}`:""}. 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,n)=>`${e}. ${t} ${n}`,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",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ù ↗",remove:e=>`Rimuovi ${e} dalla selezione`,endOf:e=>`Fine: ${e}`,lasted:e=>`durata: ${e}`,endsAria:(e,t,n)=>`Fine di ${e}: ${t}${n?`, durata ${n}`:""}. 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,n)=>`${e} ${t} ${n}`,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",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 ↗",remove:e=>`Quitar ${e} de la selección`,endOf:e=>`Fin: ${e}`,lasted:e=>`duración: ${e}`,endsAria:(e,t,n)=>`Fin de ${e}: ${t}${n?`, duración ${n}`:""}. 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,n)=>`${e} ${t} ${n}`,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",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 ↗",remove:e=>`Remover ${e} da seleção`,endOf:e=>`Fim: ${e}`,lasted:e=>`duração: ${e}`,endsAria:(e,t,n)=>`Fim de ${e}: ${t}${n?`, duração ${n}`:""}. 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,n)=>`${e} ${t} ${n}`,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",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 ↗",remove:e=>`Usuń ${e} z wyboru`,endOf:e=>`Koniec: ${e}`,lasted:e=>`czas trwania: ${e}`,endsAria:(e,t,n)=>`Koniec: ${e}, ${t}${n?`, czas trwania ${n}`:""}. 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,n)=>`${e} ${t} ${n}`,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",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 ↗",remove:e=>`${e} uit selectie verwijderen`,endOf:e=>`Einde: ${e}`,lasted:e=>`duur: ${e}`,endsAria:(e,t,n)=>`Einde van ${e}: ${t}${n?`, duur ${n}`:""}. 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,n)=>`${e} ${t} ${n}`,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"],n={year:1,month:1/12,day:1/372},i=[1/12,1/4,...[1,10,100,1e3,1e4,1e5].flatMap(e=>[e,2*e,5*e])];function s(t){if(null==t||""===t)return null;const n="object"==typeof t?JSON.stringify(t):"string"==typeof t?`"${t}"`:String(t);let i,s,a;if("number"==typeof t){if(!Number.isFinite(t))throw new Error(`Chroniko: invalid date ${n}`);return r(t)}if("object"==typeof t)({year:i,month:s,day:a}=t);else{const e=/^(-?\d+)(?:-(\d{1,2}))?(?:-(\d{1,2}))?$/.exec(String(t).trim());if(!e)throw new Error(`Chroniko: cannot parse date ${n}`);[i,s,a]=[Number(e[1]),e[2]&&Number(e[2]),e[3]&&Number(e[3])]}const l=function(t,n,i){if(!Number.isInteger(t))return"year must be a whole number";if(null!=n&&!(Number.isInteger(n)&&n>=1&&n<=12))return"month must be 1–12";if(null!=i){if(null==n)return"a day needs a month";if(!(Number.isInteger(i)&&i>=1&&i<=o[n-1]))return`day must be 1–${o[n-1]} in ${e.en.months[n-1]}`}return null}(i,s??null,a??null);if(l)throw new Error(`Chroniko: invalid date ${n}: ${l}`);return r(i,s,a)}const o=[31,29,31,30,31,30,31,31,30,31,30,31];function r(e,t,n){let i=e;t&&(i+=(t-1)/12),n&&(i+=(n-1)/372);return{year:e,month:t||null,day:n||null,precision:n?"day":t?"month":"year",value:i}}const a=new Map;function l(t,n){if(!Object.hasOwn(e,t)){const n=Object.keys(e).map(e=>`'${e}'`).join(", ");throw new Error(`Chroniko: language must be one of ${n}, got ${JSON.stringify(t)}`)}if(!n&&a.has(t))return a.get(t);const i={...e.en,...e[t],...n,number:new Intl.NumberFormat(t),plural:new Intl.PluralRules(t)};return n||a.set(t,i),i}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 n=t.year(e.year);return e.day?t.day(e.day,t.months[e.month-1],n):e.month?t.month(t.months[e.month-1],n):n}function u(e,t,n="en"){return m(e,t,l(n))}function m(e,t,n){const i=e=>e<0?e+1:e,s=[e.precision,t.precision],o=s.includes("year")?"year":s.includes("month")?"month":"day";let r=i(t.year)-i(e.year),a="year"===o?0:t.month-e.month,l="day"===o?t.day-e.day:0;if(l<0&&(a-=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]}(i(t.year),t.month-1)-e.day,0)+t.day),a<0&&(r-=1,a+=12),r<0)return"";const d=[["year",r],["month",a],["day",l]],h=d.findIndex(([,e])=>e>0);if(h<0)return n.lessThan[o];const c=([e,t])=>{const i=n.units[e];return(i[n.plural.select(t)]??i.other).replace("#",n.number.format(t))},u=d[h+1];return u?.[1]>0?`${c(d[h])}${n.unitJoin}${c(u)}`:c(d[h])}function p(e,t){const n=c(e.start,t);return e.end?`${n} – ${c(e.end,t)}`:n}function y(e,t){return`${String(e.category??"").trim().toLowerCase().replace(/\s+/g,"-")||"event"}-${t}`}function $(){const e=new Map;for(const t of location.hash.slice(1).split("&")){if(!t)continue;const n=t.indexOf("=");n<0?e.set(t,null):e.set(t.slice(0,n),t.slice(n+1))}return e}function g(e,t,n){if(t>=1)return n.year(Math.round(e));const i=Math.floor(e+1e-9),s=Math.round(12*(e-i))%12;return 0===s?n.year(i):n.months[s]}function f(e){return String(e).replace(/[&<>"']/g,e=>({"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;"}[e]))}class v{constructor(e,t={}){const n="string"==typeof e?document.querySelector(e):e;if(!n)throw new Error("Chroniko: container not found");this.options={minSpan:1/12,colors:{},storyPosition:"below",split:.6,language:"en",categoryLabels:{},...t};const{storyPosition:i,split:s}=this.options;if("below"!==i&&"right"!==i)throw new Error(`Chroniko: storyPosition must be 'below' or 'right', got ${JSON.stringify(i)}`);if(!("number"==typeof s&&s>0&&s<1))throw new Error(`Chroniko: split must be a number between 0 and 1, got ${JSON.stringify(s)}`);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(n),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 i=e.map((e,t)=>{const i=n=>{try{return s(e[n])}catch(i){const s=i.message.replace(/^Chroniko: /,"");throw new Error(`Chroniko: event "${e.title??t}" has an invalid ${n}: ${s}`)}},o=i("start");if(!o)throw new Error(`Chroniko: event "${e.title??t}" has no start date`);const r=i("end");return{event:e,id:String(e.id??y(e,t)),start:o,end:r,from:o.value,to:r?r.value+n[r.precision]:null,category:e.category??null}}).sort((e,t)=>e.from-t.from),o=new Map;for(const e of i){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=i,this.categories=[...new Set(this.items.map(e=>e.category).filter(Boolean))];const r=new Set(Object.values(this.options.colors)),a=t.filter(e=>!r.has(e));let l=0;this.colorOf=new Map(this.categories.map(e=>[e,this.options.colors[e]??a[l++%a.length]??t[0]]));for(const e of this.items)e.color=e.event.color??this.colorOf.get(e.category)??t[0];const[d,h]=this._extent();this._dataSpan=h-d,this._measureLabels(),this._renderLegend(),this.selected=new Set(this.items.filter(e=>this.selected.has(e.id)).map(e=>e.id)),this._renderStory(),this._invalidateLayout()}zoomTo(e,t){const n=s(e)?.value,i=s(t)?.value;if(null==n||null==i)throw new Error("Chroniko: zoomTo needs both a start and an end");if(n>=i)throw new Error(`Chroniko: zoomTo start (${e}) must be before end (${t})`);const o=(n+i)/2,r=this._clampSpan(i-n);this._setView(o-r/2,o+r/2)}fit(){if(!this.items.length)return this._setView(0,2e3);const[e,t]=this._extent(),n=Math.max(t-e,1);this._setView(e-.04*n,t+.12*n)}zoomBy(e,t=.5){const n=this.end-this.start,i=this.start+n*t,s=this._clampSpan(n*e);this._setView(i-s*t,i-s*t+s)}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 n=null!=t.to?(t.from+t.to)/2:t.from,i=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(n-i/2,n+i/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));const t=this.m,n=/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.textSizeToggle?`<button type="button" data-action="text-size" aria-pressed="false" aria-label="${f(t.largerText)}">Aa</button>`:""}\n </div>\n </div>\n <div class="ck-viewport" tabindex="0" aria-label="${t.viewport(f(n))}">\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.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(n))}_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():"text-size"===t&&this._toggleTextSize(e.target.closest("button"))}),this.legendEl.addEventListener("click",e=>{const t=e.target.closest(".ck-legend-item")?.dataset.category;if(null==t)return;const n=new Set(this.hidden);n.has(t)?n.delete(t):n.add(t),this._setHidden(n)});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 n=1===t.deltaMode?16:2===t.deltaMode?e.clientWidth:1,i=t.deltaX*n,s=t.deltaY*n;if(Math.abs(i)>Math.abs(s))return t.preventDefault(),void this.panBy(i);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*s),this._ratioAt(t.clientX))):this._showHint()},{passive:!1});const n=new Map;let i=null,s=null;const o=(e,t)=>{i={id:e,x:t,start:this.start,span:this.end-this.start,moved:!1}},r=()=>{const[e,t]=n.values();return{dist:Math.max(Math.hypot(e.x-t.x,e.y-t.y),1),ratio:this._ratioAt((e.x+t.x)/2)}},a=()=>{const{dist:e,ratio:t}=r(),n=this.end-this.start;s={dist:e,span:n,anchor:this.start+n*t}};e.addEventListener("pointerdown",t=>{if(0===t.button)if(n.set(t.pointerId,{x:t.clientX,y:t.clientY}),1===n.size)this._suppressClick=!1,o(t.pointerId,t.clientX);else if(2===n.size){for(const t of n.keys())e.setPointerCapture(t);a(),i=null,this._zooming=!0,e.classList.add("ck-dragging")}}),e.addEventListener("pointermove",t=>{const o=n.get(t.pointerId);if(!o)return;if(o.x=t.clientX,o.y=t.clientY,s){const{dist:e,ratio:t}=r(),n=this._clampSpan(s.span*s.dist/e),i=s.anchor-n*t;return void this._setView(i,i+n)}if(!i||t.pointerId!==i.id)return;const a=t.clientX-i.x;if(!i.moved){if(Math.abs(a)<4)return;i.moved=!0,e.setPointerCapture(t.pointerId),e.classList.add("ck-dragging")}const l=i.start-a/this._scale();this._setView(l,l+i.span)});const l=t=>{if(n.delete(t.pointerId)){if(s){if(n.size>=2)return void a();s=null,this._suppressClick=!0,this._zooming=!1,this._scheduleRender();const[e]=n;if(e)return o(e[0],e[1].x),void(i.moved=!0)}else i?.id===t.pointerId&&i.moved&&(this._suppressClick=!0);n.size||(i=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 n=.1*e.clientWidth,i={ArrowLeft:()=>this.panBy(-n),ArrowRight:()=>this.panBy(n),"+":()=>this.zoomBy(1/1.5),"=":()=>this.zoomBy(1/1.5),"-":()=>this.zoomBy(1.5),Escape:()=>this.clearSelection()};i[t.key]&&(t.preventDefault(),i[t.key]())}),this.storyEl.addEventListener("click",e=>{const t=e.target.closest(".ck-remove"),n=e.target.closest(".ck-end-jump"),i=e.target.closest(".ck-locate");t?this.deselect(t.dataset.id):n?this._jumpToCard(n.dataset.id):i?this.reveal(i.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)}_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._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=$(),t=t=>{const n=e.get(t);if(!n)return[];try{return n.split(",").map(decodeURIComponent)}catch{return[]}},n={},i=e.get("ck-view")?.split(",").map(Number);2===i?.length&&i.every(Number.isFinite)&&i[0]<i[1]&&([n.start,n.end]=i),e.has("ck-sel")&&(n.selected=t("ck-sel")),e.has("ck-hide")&&(n.hidden=t("ck-hide")),this.setState(n)}_writeHash(){const{start:e,end:t,selected:n,hidden:i}=this.getState(),s=$(),o=Math.min(6,Math.max(0,Math.ceil(3-Math.log10(t-e))));s.set("ck-view",`${+e.toFixed(o)},${+t.toFixed(o)}`);for(const[e,t]of[["ck-sel",n],["ck-hide",i]])t.length?s.set(e,t.map(encodeURIComponent).join(",")):s.delete(e);const r=[...s].map(([e,t])=>null==t?e:`${e}=${t}`).join("&");history.replaceState(history.state,"",`${location.pathname}${location.search}#${r}`)}_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 n of this.items)e=Math.min(e,n.from),t=Math.max(t,n.to??n.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 n=getComputedStyle(t);e.font=`${n.fontStyle} ${n.fontWeight} ${n.fontSize} ${n.fontFamily}`,e.letterSpacing="normal"===n.letterSpacing?"0px":n.letterSpacing,e.wordSpacing="normal"===n.wordSpacing?"0px":n.wordSpacing;const i=n.textTransform;t.remove();for(const t of this.items){let n=t.event.title??"";"uppercase"===i?n=n.toUpperCase():"lowercase"===i&&(n=n.toLowerCase()),t.labelWidth=e.measureText(n).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),n=e=>(e-this.start)*t,i=null==this._layoutScale||Math.abs(t/this._layoutScale-1)>1e-6;(null==this._layoutScale||i&&!this._zooming)&&this._layout(t),this._renderAxis(t,n),this._renderEvents(e,n)}_layout(e){const t=[];for(const n of this.items){if(n.category&&this.hidden.has(n.category)){n.lane=-1;continue}const i=null!=n.to,s=n.from*e,o=i?n.to*e:s,r=i?s:s-5,a=i?6:16,l=Math.max(o,r+a+n.labelWidth)+12;let d=t.findIndex(e=>e<=r);d<0?d=t.push(l)-1:t[d]=l,n.lane=d}this._laneCount=t.length,this._layoutScale=e}_invalidateLayout(){this._layoutScale=null,this._scheduleRender()}_renderAxis(e,t){const n=i.find(t=>t*e>=90)??i.at(-1);let s="",o="";for(let e=Math.ceil(this.start/n);e*n<=this.end;e++){const i=e*n,r=t(i).toFixed(1);s+=`<span class="ck-tick" style="left:${r}px">${f(g(i,n,this.m))}</span>`,o+=`<span class="ck-gridline" style="left:${r}px"></span>`}this.axisEl.innerHTML=s,this.gridEl.innerHTML=o}_renderEvents(e,t){const n=this.lanesEl.contains(document.activeElement)?document.activeElement.dataset.id:null,i=this._revealing,s=i?performance.now()-i.at:1/0;let o="";for(const n of this.items){if(n.lane<0)continue;const r=null!=n.to,a=t(n.from),l=r?t(n.to):a,d=r?a:a-5,h=r?Math.min(Math.max(0,-a),Math.max(0,l-a-n.labelWidth-6))+6:16,c=Math.max(l,d+h+n.labelWidth);if((r?l:c)<0||d>e)continue;const u=12+30*n.lane,m=this.selected.has(n.id),y=i?.id===n.id&&s<1500,$=`ck-event ${r?"ck-range":"ck-point"}${m?" ck-selected":""}${this._hoverClass(n)}${y?" ck-flash":""}`,g=`--ck-color:${f(n.color)};left:${d.toFixed(1)}px;top:${u}px`+(y?`;animation-delay:-${Math.round(s)}ms`:""),v=f(n.event.title??""),k=`type="button" class="${$}" data-id="${f(n.id)}" aria-pressed="${m}"\n title="${v} · ${f(p(n,this.m))}"`;o+=r?`<button ${k} style="${g};width:${Math.max(l-a,4).toFixed(1)}px">\n <span class="ck-label" style="left:${h.toFixed(1)}px">${v}</span></button>`:`<button ${k} style="${g}">\n <span class="ck-dot"></span><span class="ck-label">${v}</span></button>`}const r=24+30*this._laneCount;if(this.lanesEl.innerHTML=`<div class="ck-lanes-inner" style="height:${r}px">${o}</div>`,null!=n){([...this.lanesEl.querySelectorAll(".ck-event")].find(e=>e.dataset.id===n)??this.viewport).focus({preventScroll:!0})}i?.pending&&this._finishReveal(i)}_finishReveal(e){e.pending=!1;const t=[...this.lanesEl.querySelectorAll(".ck-event")].find(t=>t.dataset.id===e.id);if(!t)return;const n=this.lanesEl;(t.offsetTop<n.scrollTop||t.offsetTop+t.offsetHeight>n.scrollTop+n.clientHeight)&&(n.scrollTop=t.offsetTop-(n.clientHeight-t.offsetHeight)/2);const i=matchMedia("(prefers-reduced-motion: reduce)").matches;this.viewport.scrollIntoView({block:"nearest",behavior:i?"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("")}_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),!e.length)return void(this.storyEl.innerHTML=t?`<p class="ck-story-placeholder">${f(this.m.placeholder)}</p>`:"");const n=e.map(e=>({item:e,at:e.from,isEnd:!1}));for(const t of e)t.end&&t.end.value>t.from&&n.push({item:t,at:t.end.value,isEnd:!0});n.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">${n.map(e=>e.isEnd?this._storyEnd(e.item):this._storyCard(e.item)).join("")}</ol>`}_storyEnd(e){const t=this.m,n=f(e.event.title??""),i=f(c(e.end,t)),s=f(m(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(n,i,s)}">\n <span class="ck-end-date">${i}</span>\n <span>${t.endOf(`<strong>${n}</strong>`)}</span>\n ${s?`<span class="ck-end-duration">${t.lasted(s)}</span>`:""}\n </button>\n </li>`}_jumpToCard(e){const t=[...this.storyEl.querySelectorAll(".ck-card")].find(t=>t.dataset.id===e);if(!t)return;const n=matchMedia("(prefers-reduced-motion: reduce)").matches;t.scrollIntoView({block:"nearest",behavior:n?"auto":"smooth"}),t.focus({preventScroll:!0}),t.classList.remove("ck-flash"),t.offsetWidth,t.classList.add("ck-flash")}_storyCard(e){const t=e.event,n=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(p(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 <div class="ck-card-actions">\n <button type="button" class="ck-locate" data-id="${f(e.id)}">${f(this.m.showOnTimeline)}</button>\n ${n?`<a class="ck-link" href="${f(n)}" 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}}export{v as Chroniko,h as formatDate,u as formatDuration,d as formatYear,s as parseDate};
package/package.json CHANGED
@@ -1,6 +1,48 @@
1
1
  {
2
2
  "name": "chroniko",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.2.0",
4
+ "description": "Render historical events on a single zoomable time axis. Plain HTML, CSS and JavaScript, no dependencies.",
5
+ "license": "Apache-2.0",
6
+ "type": "module",
7
+ "main": "./dist/chroniko.min.js",
8
+ "exports": {
9
+ ".": "./dist/chroniko.min.js",
10
+ "./chroniko.css": "./dist/chroniko.min.css"
11
+ },
12
+ "scripts": {
13
+ "start": "node scripts/serve.js",
14
+ "build": "webpack",
15
+ "prepack": "npm run build"
16
+ },
17
+ "keywords": [
18
+ "timeline",
19
+ "history",
20
+ "events",
21
+ "chronology"
22
+ ],
23
+ "author": "Ying Kit Yuen <yingkityuen@gmail.com>",
24
+ "repository": {
25
+ "type": "git",
26
+ "url": "git+https://github.com/ykyuen/chroniko.git"
27
+ },
28
+ "homepage": "https://github.com/ykyuen/chroniko#readme",
29
+ "bugs": {
30
+ "url": "https://github.com/ykyuen/chroniko/issues"
31
+ },
32
+ "sideEffects": [
33
+ "*.css"
34
+ ],
35
+ "devDependencies": {
36
+ "css-loader": "^7.1.5",
37
+ "css-minimizer-webpack-plugin": "^8.0.0",
38
+ "mini-css-extract-plugin": "^2.10.2",
39
+ "terser-webpack-plugin": "^5.6.1",
40
+ "webpack": "^5.111.1",
41
+ "webpack-cli": "^7.2.3",
42
+ "webpack-remove-empty-scripts": "^1.1.1"
43
+ },
44
+ "files": [
45
+ "dist",
46
+ "CHANGELOG.md"
47
+ ]
48
+ }