chroniko 0.0.0-stage → 0.1.1
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 +26 -0
- package/LICENSE +202 -0
- package/README.md +218 -2
- package/dist/chroniko.min.css +1 -0
- package/dist/chroniko.min.js +1 -0
- package/package.json +46 -4
package/CHANGELOG.md
ADDED
|
@@ -0,0 +1,26 @@
|
|
|
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.1.1] - 2026-10-14
|
|
6
|
+
|
|
7
|
+
### Added
|
|
8
|
+
|
|
9
|
+
- `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.
|
|
10
|
+
- `split` option: with `storyPosition: 'right'`, the timeline's share of the width, between 0 and 1 (default `0.6`).
|
|
11
|
+
- `--ck-sticky-top` custom property (default `0px`) to keep the sticky timeline below a fixed page header.
|
|
12
|
+
- The example page shows the side-by-side layout when opened with `?story=right`.
|
|
13
|
+
|
|
14
|
+
### Changed
|
|
15
|
+
|
|
16
|
+
- The constructor throws if `storyPosition` or `split` is invalid.
|
|
17
|
+
- 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.
|
|
18
|
+
- The README lists the options in a table with their types, whether they're required, and their defaults.
|
|
19
|
+
- 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.
|
|
20
|
+
|
|
21
|
+
## [0.1.0] - 2026-10-14
|
|
22
|
+
|
|
23
|
+
- Initial release.
|
|
24
|
+
|
|
25
|
+
[0.1.1]: https://github.com/ykyuen/chroniko/compare/0.1.0...0.1.1
|
|
26
|
+
[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,219 @@
|
|
|
1
|
-
#
|
|
1
|
+
# chroniko
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
Render historical events on a single zoomable time axis. Plain HTML, CSS and JavaScript, with no dependencies.
|
|
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).
|
|
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.1.1/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.1.1/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
|
+
|
|
89
|
+
### Methods
|
|
90
|
+
|
|
91
|
+
`setEvents(events)`, `zoomTo(start, end)`, `zoomBy(factor)`, `panBy(px)`, `fit()`, `select(id)`, `deselect(id)`, `toggle(id)`, `clearSelection()`, `getSelection()`, `reveal(id)`, `getState()`, `setState(state)`, `destroy()`.
|
|
92
|
+
|
|
93
|
+
`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.
|
|
94
|
+
|
|
95
|
+
`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.
|
|
96
|
+
|
|
97
|
+
### Sharing
|
|
98
|
+
|
|
99
|
+
`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.
|
|
100
|
+
|
|
101
|
+
With `syncUrl: true`, the timeline keeps this state in the URL hash, so the address bar is always a shareable link:
|
|
102
|
+
|
|
103
|
+
```
|
|
104
|
+
#ck-view=1300,1500&ck-sel=black-death,constantinople&ck-hide=science
|
|
105
|
+
```
|
|
106
|
+
|
|
107
|
+
- Opening the link restores the view, selection and hidden categories. Editing the hash on an open page applies it too.
|
|
108
|
+
- 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.
|
|
109
|
+
- 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.
|
|
110
|
+
- 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.
|
|
111
|
+
- When a link restores a selection, `onSelectionChange` is called during construction, before `new Chroniko(...)` returns.
|
|
112
|
+
|
|
113
|
+
### Navigation
|
|
114
|
+
|
|
115
|
+
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.
|
|
116
|
+
|
|
117
|
+
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.
|
|
118
|
+
|
|
119
|
+
### Story view
|
|
120
|
+
|
|
121
|
+
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))`, exported alongside `parseDate` and `formatDate`. **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.
|
|
122
|
+
|
|
123
|
+
#### Story beside the timeline
|
|
124
|
+
|
|
125
|
+
With `storyPosition: 'right'`, the toolbar and timeline take the left `split` of the width and the story takes the rest:
|
|
126
|
+
|
|
127
|
+
```js
|
|
128
|
+
new Chroniko('#timeline', { events, storyPosition: 'right', split: 0.6 });
|
|
129
|
+
```
|
|
130
|
+
|
|
131
|
+
- 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.
|
|
132
|
+
- 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.
|
|
133
|
+
- The story column is shown even when nothing is selected, with a short hint, so the first click doesn't resize the timeline.
|
|
134
|
+
- 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.
|
|
135
|
+
|
|
136
|
+
### Colors
|
|
137
|
+
|
|
138
|
+
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.
|
|
139
|
+
|
|
140
|
+
#### Event colors
|
|
141
|
+
|
|
142
|
+
Each event's color is picked in this order:
|
|
143
|
+
|
|
144
|
+
1. The event's own `color` field.
|
|
145
|
+
2. The color of its category in the `colors` option.
|
|
146
|
+
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.
|
|
147
|
+
|
|
148
|
+
```js
|
|
149
|
+
new Chroniko('#timeline', {
|
|
150
|
+
colors: { war: '#c0392b', politics: '#2c7be5' },
|
|
151
|
+
events: [
|
|
152
|
+
{ title: 'World War II', start: 1939, end: 1945, category: 'war' },
|
|
153
|
+
{ title: 'Moon landing', start: '1969-07-20', category: 'science' }, // palette color
|
|
154
|
+
{ title: 'Fall of the Berlin Wall', start: '1989-11-09', category: 'politics',
|
|
155
|
+
color: 'gold' }, // overrides 'politics'
|
|
156
|
+
],
|
|
157
|
+
});
|
|
158
|
+
```
|
|
159
|
+
|
|
160
|
+
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)`.
|
|
161
|
+
|
|
162
|
+
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:
|
|
163
|
+
|
|
164
|
+
```js
|
|
165
|
+
colors: { war: 'var(--war-color)' }
|
|
166
|
+
```
|
|
167
|
+
|
|
168
|
+
```css
|
|
169
|
+
.chroniko { --war-color: #c0392b; }
|
|
170
|
+
@media (prefers-color-scheme: dark) {
|
|
171
|
+
.chroniko { --war-color: #ff7b72; }
|
|
172
|
+
}
|
|
173
|
+
```
|
|
174
|
+
|
|
175
|
+
#### Component colors
|
|
176
|
+
|
|
177
|
+
The component's colors are CSS custom properties on `.chroniko`:
|
|
178
|
+
|
|
179
|
+
| Property | Used for | Light | Dark |
|
|
180
|
+
| -------------- | -------- | --------- | --------- |
|
|
181
|
+
| `--ck-bg` | Timeline and card background | `#ffffff` | `#0d1117` |
|
|
182
|
+
| `--ck-surface` | Toolbar and story list background | `#f6f7f9` | `#161b22` |
|
|
183
|
+
| `--ck-fg` | Text | `#1f2328` | `#e6edf3` |
|
|
184
|
+
| `--ck-muted` | Secondary text, axis labels | `#656d76` | `#8d96a0` |
|
|
185
|
+
| `--ck-border` | Borders and dividers | `#d8dee4` | `#30363d` |
|
|
186
|
+
| `--ck-grid` | Grid lines behind the events | `#eef1f4` | `#1c2128` |
|
|
187
|
+
| `--ck-focus` | Focus rings and links | `#0969da` | `#4493f8` |
|
|
188
|
+
|
|
189
|
+
Override them in your own stylesheet, loaded after `chroniko.min.css`:
|
|
190
|
+
|
|
191
|
+
```css
|
|
192
|
+
.chroniko {
|
|
193
|
+
--ck-bg: #fffdf7;
|
|
194
|
+
--ck-surface: #f5f0e6;
|
|
195
|
+
--ck-border: #e0d6c3;
|
|
196
|
+
}
|
|
197
|
+
```
|
|
198
|
+
|
|
199
|
+
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:
|
|
200
|
+
|
|
201
|
+
```css
|
|
202
|
+
@media (prefers-color-scheme: dark) {
|
|
203
|
+
.chroniko {
|
|
204
|
+
--ck-bg: #1b1915;
|
|
205
|
+
--ck-surface: #24211c;
|
|
206
|
+
--ck-border: #3a352d;
|
|
207
|
+
}
|
|
208
|
+
}
|
|
209
|
+
```
|
|
210
|
+
|
|
211
|
+
To theme one timeline only, use a more specific selector such as `#timeline.chroniko`.
|
|
212
|
+
|
|
213
|
+
### Theming
|
|
214
|
+
|
|
215
|
+
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.
|
|
216
|
+
|
|
217
|
+
## License
|
|
218
|
+
|
|
219
|
+
[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: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-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 t=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],e=["#4e79a7","#e15759","#59a14f","#f28e2b","#b07aa1","#76b7b2","#edc948","#9c755f"],s={year:1,month:1/12,day:1/372},i=[1/12,1/4,...[1,10,100,1e3,1e4,1e5].flatMap(t=>[t,2*t,5*t])];function n(e){if(null==e||""===e)return null;const s="object"==typeof e?JSON.stringify(e):"string"==typeof e?`"${e}"`:String(e);let i,n,a;if("number"==typeof e){if(!Number.isFinite(e))throw new Error(`Chroniko: invalid date ${s}`);return r(e)}if("object"==typeof e)({year:i,month:n,day:a}=e);else{const t=/^(-?\d+)(?:-(\d{1,2}))?(?:-(\d{1,2}))?$/.exec(String(e).trim());if(!t)throw new Error(`Chroniko: cannot parse date ${s}`);[i,n,a]=[Number(t[1]),t[2]&&Number(t[2]),t[3]&&Number(t[3])]}const l=function(e,s,i){if(!Number.isInteger(e))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!=i){if(null==s)return"a day needs a month";if(!(Number.isInteger(i)&&i>=1&&i<=o[s-1]))return`day must be 1–${o[s-1]} in ${t[s-1]}`}return null}(i,n??null,a??null);if(l)throw new Error(`Chroniko: invalid date ${s}: ${l}`);return r(i,n,a)}const o=[31,29,31,30,31,30,31,31,30,31,30,31];function r(t,e,s){let i=t;e&&(i+=(e-1)/12),s&&(i+=(s-1)/372);return{year:t,month:e||null,day:s||null,precision:s?"day":e?"month":"year",value:i}}function a(t){return t<0?-t+" BCE":String(t)}function l(e){const s=a(e.year);return e.day?`${e.day} ${t[e.month-1]} ${s}`:e.month?`${t[e.month-1]} ${s}`:s}function c(t,e){const s=t=>t<0?t+1:t,i=[t.precision,e.precision],n=i.includes("year")?"year":i.includes("month")?"month":"day";let o=s(e.year)-s(t.year),r="year"===n?0:e.month-t.month,a="day"===n?e.day-t.day:0;if(a<0&&(r-=1,a=Math.max(function(t,e){if(0===e)return 31;return[31,t%4==0&&t%100!=0||t%400==0?29:28,31,30,31,30,31,31,30,31,30,31][e-1]}(s(e.year),e.month-1)-t.day,0)+e.day),r<0&&(o-=1,r+=12),o<0)return"";const l=[["year",o],["month",r],["day",a]],c=l.findIndex(([,t])=>t>0);if(c<0)return`less than a ${n}`;const h=([t,e])=>`${e.toLocaleString("en-US")} ${t}${1===e?"":"s"}`,d=l[c+1];return d?.[1]>0?`${h(l[c])}, ${h(d)}`:h(l[c])}function h(t){const e=l(t.start);return t.end?`${e} – ${l(t.end)}`:e}function d(t,e){return`${String(t.category??"").trim().toLowerCase().replace(/\s+/g,"-")||"event"}-${e}`}function u(){const t=new Map;for(const e of location.hash.slice(1).split("&")){if(!e)continue;const s=e.indexOf("=");s<0?t.set(e,null):t.set(e.slice(0,s),e.slice(s+1))}return t}function m(e,s){if(s>=1)return a(Math.round(e));const i=Math.floor(e+1e-9),n=Math.round(12*(e-i))%12;return 0===n?a(i):t[n]}function p(t){return String(t).replace(/[&<>"']/g,t=>({"&":"&","<":"<",">":">",'"':""","'":"'"}[t]))}class f{constructor(t,e={}){const s="string"==typeof t?document.querySelector(t):t;if(!s)throw new Error("Chroniko: container not found");this.options={minSpan:1/12,colors:{},storyPosition:"below",split:.6,...e};const{storyPosition:i,split:n}=this.options;if("below"!==i&&"right"!==i)throw new Error(`Chroniko: storyPosition must be 'below' or 'right', got ${JSON.stringify(i)}`);if(!("number"==typeof n&&n>0&&n<1))throw new Error(`Chroniko: split must be a number between 0 and 1, got ${JSON.stringify(n)}`);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(e.events??[]),null!=e.start&&null!=e.end?this.zoomTo(e.start,e.end):this.fit(),this.options.syncUrl&&(this._onHashChange=()=>this._readHash(),window.addEventListener("hashchange",this._onHashChange),this._readHash(),clearTimeout(this._hashTimer))}setEvents(t){const i=t.map((t,e)=>{const i=s=>{try{return n(t[s])}catch(i){const n=i.message.replace(/^Chroniko: /,"");throw new Error(`Chroniko: event "${t.title??e}" has an invalid ${s}: ${n}`)}},o=i("start");if(!o)throw new Error(`Chroniko: event "${t.title??e}" has no start date`);const r=i("end");return{event:t,id:String(t.id??d(t,e)),start:o,end:r,from:o.value,to:r?r.value+s[r.precision]:null,category:t.category??null}}).sort((t,e)=>t.from-e.from),o=new Map;for(const t of i){const e=o.get(t.id);if(e)throw new Error(`Chroniko: events "${e.event.title}" and "${t.event.title}" share the id "${t.id}"; ids must be unique`);o.set(t.id,t)}this.items=i,this.categories=[...new Set(this.items.map(t=>t.category).filter(Boolean))];const r=new Set(Object.values(this.options.colors)),a=e.filter(t=>!r.has(t));let l=0;this.colorOf=new Map(this.categories.map(t=>[t,this.options.colors[t]??a[l++%a.length]??e[0]]));for(const t of this.items)t.color=t.event.color??this.colorOf.get(t.category)??e[0];const[c,h]=this._extent();this._dataSpan=h-c,this._measureLabels(),this._renderLegend(),this.selected=new Set(this.items.filter(t=>this.selected.has(t.id)).map(t=>t.id)),this._renderStory(),this._invalidateLayout()}zoomTo(t,e){const s=n(t)?.value,i=n(e)?.value;if(null==s||null==i)throw new Error("Chroniko: zoomTo needs both a start and an end");if(s>=i)throw new Error(`Chroniko: zoomTo start (${t}) must be before end (${e})`);const o=(s+i)/2,r=this._clampSpan(i-s);this._setView(o-r/2,o+r/2)}fit(){if(!this.items.length)return this._setView(0,2e3);const[t,e]=this._extent(),s=Math.max(e-t,1);this._setView(t-.04*s,e+.12*s)}zoomBy(t,e=.5){const s=this.end-this.start,i=this.start+s*e,n=this._clampSpan(s*t);this._setView(i-n*e,i-n*e+n)}panBy(t){const e=t/this._scale();this._setView(this.start+e,this.end+e)}select(t){t=String(t),!this.selected.has(t)&&this.items.some(e=>e.id===t)&&this._setSelection([...this.selected,t])}deselect(t){t=String(t),this.selected.has(t)&&this._setSelection([...this.selected].filter(e=>e!==t))}toggle(t){this.selected.has(String(t))?this.deselect(t):this.select(t)}clearSelection(){this.selected.size&&this._setSelection([])}getSelection(){return this.items.filter(t=>this.selected.has(t.id)).map(t=>t.event)}reveal(t){const e=this.items.find(e=>e.id===String(t));if(!e)return;e.category&&this.hidden.has(e.category)&&this._setHidden([...this.hidden].filter(t=>t!==e.category));const s=null!=e.to?(e.from+e.to)/2:e.from,i=null!=e.to?this._clampSpan((e.to-e.from)/.6):this.end-this.start;this._revealing={id:e.id,at:performance.now(),pending:!0},this._setView(s-i/2,s+i/2)}getState(){return{start:this.start,end:this.end,selected:this.items.filter(t=>this.selected.has(t.id)).map(t=>t.id),hidden:[...this.hidden]}}setState(t={}){if(null!=t.start&&null!=t.end&&this.zoomTo(t.start,t.end),t.hidden&&this._setHidden(t.hidden.map(String)),t.selected){const e=new Set(t.selected.map(String));this._setSelection(this.items.filter(t=>e.has(t.id)).map(t=>t.id))}}destroy(){cancelAnimationFrame(this._frame),clearTimeout(this._zoomTimer),clearTimeout(this._hintTimer),clearTimeout(this._hashTimer),this._onHashChange&&window.removeEventListener("hashchange",this._onHashChange),this._resizeObserver.disconnect(),this.root.remove()}_build(t){this.root=document.createElement("div"),this.root.className="chroniko","right"===this.options.storyPosition&&(this.root.classList.add("ck-side"),this.root.style.setProperty("--ck-split",this.options.split)),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="Categories"></div>\n <div class="ck-controls">\n <button type="button" data-action="zoom-in" aria-label="Zoom in">+</button>\n <button type="button" data-action="zoom-out" aria-label="Zoom out">−</button>\n <button type="button" data-action="fit">Fit</button>\n </div>\n </div>\n <div class="ck-viewport" tabindex="0"\n aria-label="Timeline. Drag or use arrow keys to pan; press + and −, Ctrl+scroll or pinch to zoom.">\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="Selected events" hidden></section>\n </div>',t.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");const e=/Mac|iPhone|iPad/.test(navigator.userAgentData?.platform??navigator.platform);this.hintEl.textContent=(e?"⌘":"Ctrl")+" + scroll to zoom, or click the timeline first"}_showHint(){this.hintEl.classList.add("ck-visible"),clearTimeout(this._hintTimer),this._hintTimer=setTimeout(()=>this.hintEl.classList.remove("ck-visible"),1500)}_bind(){const t=this.viewport;this.root.querySelector(".ck-controls").addEventListener("click",t=>{const e=t.target.closest("button")?.dataset.action;"zoom-in"===e?this.zoomBy(1/1.5):"zoom-out"===e?this.zoomBy(1.5):"fit"===e&&this.fit()}),this.legendEl.addEventListener("click",t=>{const e=t.target.closest(".ck-legend-item")?.dataset.category;if(null==e)return;const s=new Set(this.hidden);s.has(e)?s.delete(e):s.add(e),this._setHidden(s)});const e=t=>{t.pointerType&&"mouse"!==t.pointerType||this._setHover(t.target.closest(".ck-event, .ck-card, .ck-end-jump")?.dataset.id??null)};for(const t of[this.lanesEl,this.storyEl])t.addEventListener("pointerover",e),t.addEventListener("focusin",e),t.addEventListener("pointerleave",()=>this._setHover(null)),t.addEventListener("focusout",()=>this._setHover(null));t.addEventListener("wheel",e=>{const s=1===e.deltaMode?16:2===e.deltaMode?t.clientWidth:1,i=e.deltaX*s,n=e.deltaY*s;if(Math.abs(i)>Math.abs(n))return e.preventDefault(),void this.panBy(i);e.ctrlKey||e.metaKey||t.contains(document.activeElement)?(e.preventDefault(),this._zooming=!0,clearTimeout(this._zoomTimer),this._zoomTimer=setTimeout(()=>{this._zooming=!1,this._scheduleRender()},150),this.zoomBy(Math.exp(.002*n),this._ratioAt(e.clientX))):this._showHint()},{passive:!1});const s=new Map;let i=null,n=null;const o=(t,e)=>{i={id:t,x:e,start:this.start,span:this.end-this.start,moved:!1}},r=()=>{const[t,e]=s.values();return{dist:Math.max(Math.hypot(t.x-e.x,t.y-e.y),1),ratio:this._ratioAt((t.x+e.x)/2)}},a=()=>{const{dist:t,ratio:e}=r(),s=this.end-this.start;n={dist:t,span:s,anchor:this.start+s*e}};t.addEventListener("pointerdown",e=>{if(0===e.button)if(s.set(e.pointerId,{x:e.clientX,y:e.clientY}),1===s.size)this._suppressClick=!1,o(e.pointerId,e.clientX);else if(2===s.size){for(const e of s.keys())t.setPointerCapture(e);a(),i=null,this._zooming=!0,t.classList.add("ck-dragging")}}),t.addEventListener("pointermove",e=>{const o=s.get(e.pointerId);if(!o)return;if(o.x=e.clientX,o.y=e.clientY,n){const{dist:t,ratio:e}=r(),s=this._clampSpan(n.span*n.dist/t),i=n.anchor-s*e;return void this._setView(i,i+s)}if(!i||e.pointerId!==i.id)return;const a=e.clientX-i.x;if(!i.moved){if(Math.abs(a)<4)return;i.moved=!0,t.setPointerCapture(e.pointerId),t.classList.add("ck-dragging")}const l=i.start-a/this._scale();this._setView(l,l+i.span)});const l=e=>{if(s.delete(e.pointerId)){if(n){if(s.size>=2)return void a();n=null,this._suppressClick=!0,this._zooming=!1,this._scheduleRender();const[t]=s;if(t)return o(t[0],t[1].x),void(i.moved=!0)}else i?.id===e.pointerId&&i.moved&&(this._suppressClick=!0);s.size||(i=null,t.classList.remove("ck-dragging"))}};t.addEventListener("pointerup",l),t.addEventListener("pointercancel",l),t.addEventListener("click",t=>{if(this._suppressClick)return void(this._suppressClick=!1);const e=t.target.closest(".ck-event")?.dataset.id;null!=e&&this.toggle(e)}),t.addEventListener("keydown",e=>{const s=.1*t.clientWidth,i={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()};i[e.key]&&(e.preventDefault(),i[e.key]())}),this.storyEl.addEventListener("click",t=>{const e=t.target.closest(".ck-remove"),s=t.target.closest(".ck-end-jump"),i=t.target.closest(".ck-locate");e?this.deselect(e.dataset.id):s?this._jumpToCard(s.dataset.id):i?this.reveal(i.dataset.id):t.target.closest(".ck-clear")&&this.clearSelection()}),this._resizeObserver=new ResizeObserver(()=>this._scheduleRender()),this._resizeObserver.observe(t)}_setSelection(t){this.selected=new Set(t);for(const t of this.lanesEl.querySelectorAll(".ck-event")){const e=this.selected.has(t.dataset.id);t.classList.toggle("ck-selected",e),t.setAttribute("aria-pressed",e)}this._renderStory(),this._stateChanged(),this.options.onSelectionChange?.(this.getSelection())}_setView(t,e){this.start=t,this.end=e,this._scheduleRender(),this._stateChanged()}_setHidden(t){this.hidden=new Set(t),this._renderLegend(),this._invalidateLayout(),this._stateChanged()}_setHover(t){if(t!==this._hoverId){this._hoverId=t;for(const e of this.root.querySelectorAll(".ck-event, .ck-card, .ck-end-jump"))e.classList.toggle("ck-hover",e.dataset.id===t)}}_stateChanged(){this.options.syncUrl&&(clearTimeout(this._hashTimer),this._hashTimer=setTimeout(()=>this._writeHash(),250))}_readHash(){const t=u(),e=e=>{const s=t.get(e);if(!s)return[];try{return s.split(",").map(decodeURIComponent)}catch{return[]}},s={},i=t.get("ck-view")?.split(",").map(Number);2===i?.length&&i.every(Number.isFinite)&&i[0]<i[1]&&([s.start,s.end]=i),t.has("ck-sel")&&(s.selected=e("ck-sel")),t.has("ck-hide")&&(s.hidden=e("ck-hide")),this.setState(s)}_writeHash(){const{start:t,end:e,selected:s,hidden:i}=this.getState(),n=u(),o=Math.min(6,Math.max(0,Math.ceil(3-Math.log10(e-t))));n.set("ck-view",`${+t.toFixed(o)},${+e.toFixed(o)}`);for(const[t,e]of[["ck-sel",s],["ck-hide",i]])e.length?n.set(t,e.map(encodeURIComponent).join(",")):n.delete(t);const r=[...n].map(([t,e])=>null==e?t:`${t}=${e}`).join("&");history.replaceState(history.state,"",`${location.pathname}${location.search}#${r}`)}_clampSpan(t){const e=this.options.maxSpan??Math.max(3*this._dataSpan,100);return Math.min(Math.max(t,this.options.minSpan),e)}_scale(){return(this.viewport.clientWidth||1)/(this.end-this.start)}_ratioAt(t){const e=this.viewport.getBoundingClientRect();return(t-e.left)/e.width}_extent(){let t=1/0,e=-1/0;for(const s of this.items)t=Math.min(t,s.from),e=Math.max(e,s.to??s.from);return this.items.length?[t,e]:[0,0]}_measureLabels(){const t=this._ctx??=document.createElement("canvas").getContext("2d"),e=getComputedStyle(this.lanesEl);t.font=`${e.fontWeight} ${e.fontSize} ${e.fontFamily}`;for(const e of this.items)e.labelWidth=t.measureText(e.event.title??"").width}_scheduleRender(){this._frame||(this._frame=requestAnimationFrame(()=>{this._frame=0,this._render()}))}_render(){const t=this.viewport.clientWidth;if(!t)return;const e=t/(this.end-this.start),s=t=>(t-this.start)*e,i=null==this._layoutScale||Math.abs(e/this._layoutScale-1)>1e-6;(null==this._layoutScale||i&&!this._zooming)&&this._layout(e),this._renderAxis(e,s),this._renderEvents(t,s)}_layout(t){const e=[];for(const s of this.items){if(s.category&&this.hidden.has(s.category)){s.lane=-1;continue}const i=null!=s.to,n=s.from*t,o=i?s.to*t:n,r=i?n:n-5,a=i?6:16,l=Math.max(o,r+a+s.labelWidth)+12;let c=e.findIndex(t=>t<=r);c<0?c=e.push(l)-1:e[c]=l,s.lane=c}this._laneCount=e.length,this._layoutScale=t}_invalidateLayout(){this._layoutScale=null,this._scheduleRender()}_renderAxis(t,e){const s=i.find(e=>e*t>=90)??i.at(-1);let n="",o="";for(let t=Math.ceil(this.start/s);t*s<=this.end;t++){const i=t*s,r=e(i).toFixed(1);n+=`<span class="ck-tick" style="left:${r}px">${m(i,s)}</span>`,o+=`<span class="ck-gridline" style="left:${r}px"></span>`}this.axisEl.innerHTML=n,this.gridEl.innerHTML=o}_renderEvents(t,e){const s=this.lanesEl.contains(document.activeElement)?document.activeElement.dataset.id:null,i=this._revealing,n=i?performance.now()-i.at:1/0;let o="";for(const s of this.items){if(s.lane<0)continue;const r=null!=s.to,a=e(s.from),l=r?e(s.to):a,c=r?a:a-5,d=r?Math.min(Math.max(0,-a),Math.max(0,l-a-s.labelWidth-6))+6:16,u=Math.max(l,c+d+s.labelWidth);if((r?l:u)<0||c>t)continue;const m=12+30*s.lane,f=this.selected.has(s.id),v=i?.id===s.id&&n<1500,y=`ck-event ${r?"ck-range":"ck-point"}${f?" ck-selected":""}${this._hoverClass(s)}${v?" ck-flash":""}`,g=`--ck-color:${p(s.color)};left:${c.toFixed(1)}px;top:${m}px`+(v?`;animation-delay:-${Math.round(n)}ms`:""),_=p(s.event.title??""),k=`type="button" class="${y}" data-id="${p(s.id)}" aria-pressed="${f}"\n title="${_} · ${p(h(s))}"`;o+=r?`<button ${k} style="${g};width:${Math.max(l-a,4).toFixed(1)}px">\n <span class="ck-label" style="left:${d.toFixed(1)}px">${_}</span></button>`:`<button ${k} style="${g}">\n <span class="ck-dot"></span><span class="ck-label">${_}</span></button>`}const r=24+30*this._laneCount;if(this.lanesEl.innerHTML=`<div class="ck-lanes-inner" style="height:${r}px">${o}</div>`,null!=s){([...this.lanesEl.querySelectorAll(".ck-event")].find(t=>t.dataset.id===s)??this.viewport).focus({preventScroll:!0})}i?.pending&&this._finishReveal(i)}_finishReveal(t){t.pending=!1;const e=[...this.lanesEl.querySelectorAll(".ck-event")].find(e=>e.dataset.id===t.id);if(!e)return;const s=this.lanesEl;(e.offsetTop<s.scrollTop||e.offsetTop+e.offsetHeight>s.scrollTop+s.clientHeight)&&(s.scrollTop=e.offsetTop-(s.clientHeight-e.offsetHeight)/2);const i=matchMedia("(prefers-reduced-motion: reduce)").matches;this.viewport.scrollIntoView({block:"nearest",behavior:i?"auto":"smooth"}),e.focus({preventScroll:!0})}_renderLegend(){this.legendEl.innerHTML=this.categories.map(t=>`<button type="button" class="ck-legend-item" data-category="${p(t)}"\n aria-pressed="${!this.hidden.has(t)}" style="--ck-color:${p(this.colorOf.get(t))}">\n <span class="ck-swatch"></span>${p(t)}</button>`).join("")}_renderStory(){const t=this.items.filter(t=>this.selected.has(t.id)),e="right"===this.options.storyPosition;if(this.storyEl.hidden=!t.length&&!e,this.storyEl.classList.toggle("ck-empty",!t.length),!t.length)return void(this.storyEl.innerHTML=e?'<p class="ck-story-placeholder">Click an event to add it here.</p>':"");const s=t.map(t=>({item:t,at:t.from,isEnd:!1}));for(const e of t)e.end&&e.end.value>e.from&&s.push({item:e,at:e.end.value,isEnd:!0});s.sort((t,e)=>t.at-e.at||e.isEnd-t.isEnd),this.storyEl.innerHTML=`\n <div class="ck-story-header">\n <span class="ck-story-title">Selected events <span class="ck-count">${t.length}</span></span>\n <button type="button" class="ck-clear">Clear all</button>\n </div>\n <ol class="ck-story-list">${s.map(t=>t.isEnd?this._storyEnd(t.item):this._storyCard(t.item)).join("")}</ol>`}_storyEnd(t){const e=p(t.event.title??""),s=p(c(t.start,t.end));return`\n <li class="ck-end" style="--ck-color:${p(t.color)}">\n <button type="button" class="ck-end-jump${this._hoverClass(t)}" data-id="${p(t.id)}"\n aria-label="${e} ends ${p(l(t.end))}${s?`, after ${s}`:""}. Go to event">\n <span class="ck-end-date">${p(l(t.end))}</span>\n <span>End of <strong>${e}</strong></span>\n ${s?`<span class="ck-end-duration">lasted ${s}</span>`:""}\n </button>\n </li>`}_jumpToCard(t){const e=[...this.storyEl.querySelectorAll(".ck-card")].find(e=>e.dataset.id===t);if(!e)return;const s=matchMedia("(prefers-reduced-motion: reduce)").matches;e.scrollIntoView({block:"nearest",behavior:s?"auto":"smooth"}),e.focus({preventScroll:!0}),e.classList.remove("ck-flash"),e.offsetWidth,e.classList.add("ck-flash")}_storyCard(t){const e=t.event,s=e.url&&/^https?:\/\//i.test(e.url)?e.url:null;return`\n <li class="ck-card${this._hoverClass(t)}" data-id="${p(t.id)}" tabindex="-1"\n style="--ck-color:${p(t.color)}">\n <button type="button" class="ck-remove" data-id="${p(t.id)}"\n aria-label="Remove ${p(e.title??"")} from selection">×</button>\n <div class="ck-meta">\n ${t.category?`<span class="ck-badge">${p(t.category)}</span>`:""}\n <span>${p(h(t))}</span>\n </div>\n <h3 class="ck-title">${p(e.title??"")}</h3>\n ${e.description?`<p class="ck-description">${p(e.description)}</p>`:""}\n <div class="ck-card-actions">\n <button type="button" class="ck-locate" data-id="${p(t.id)}">Show on timeline</button>\n ${s?`<a class="ck-link" href="${p(s)}" target="_blank" rel="noopener">Read more ↗</a>`:""}\n </div>\n </li>`}_hoverClass(t){return this._hoverId===t.id?" ck-hover":""}}export{f as Chroniko,l as formatDate,c as formatDuration,a as formatYear,n as parseDate};
|
package/package.json
CHANGED
|
@@ -1,6 +1,48 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "chroniko",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "0.1.1",
|
|
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
|
+
}
|