@hanifrestian/morse 0.0.0-stage → 0.1.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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Hanif Restian Pratikno
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,100 @@
1
- # Temporary Holding Version
1
+ # Morse TOC
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
+ A table of contents in dots and dashes.
4
+
5
+ Morse is a React table of contents drawn as a ruler on the left edge of the page. Each heading is a long tick, placed where it really sits in the article, with short ticks between. A small dot rides down as you read, so the ruler shows how far you've come and how much is left. Hover or press Tab to read a heading, click to jump to it.
6
+
7
+ <!-- Demo GIF goes here once it's recorded. -->
8
+
9
+ ## Install
10
+
11
+ ```sh
12
+ pnpm add @hanifrestian/morse
13
+ ```
14
+
15
+ Or `npm install @hanifrestian/morse`. It needs `react` 18 or 19 and `motion` 11.11 to 13, which you probably have already.
16
+
17
+ ## Use
18
+
19
+ ```tsx
20
+ import { Morse } from '@hanifrestian/morse'
21
+ import '@hanifrestian/morse/style.css'
22
+
23
+ export default function Post() {
24
+ return (
25
+ <>
26
+ <article>
27
+ <h1>Title</h1>
28
+ <h2>First section</h2>
29
+ <h2>Second section</h2>
30
+ </article>
31
+ <Morse />
32
+ </>
33
+ )
34
+ }
35
+ ```
36
+
37
+ Import the stylesheet once. Without it the ruler has no layout and its links show as plain text.
38
+
39
+ ## Props
40
+
41
+ | Prop | Default | What it does |
42
+ | --- | --- | --- |
43
+ | `selector` | `'h2, h3, [data-toc]'` | Which elements inside the root count as headings. |
44
+ | `rootSelector` | `'article'` | The element whose headings are mapped and whose length the ruler measures. If nothing matches, the whole page is used. |
45
+ | `jumpOffset` | `80` | Pixels left above a heading after a jump. Raise it for a taller sticky header, but keep it under 120 so the heading you land on is marked current. |
46
+ | `className` | | Added to the ruler's own `morse` class. |
47
+
48
+ ## Heading attributes
49
+
50
+ Set these on a heading to change how it shows up.
51
+
52
+ | Attribute | Effect |
53
+ | --- | --- |
54
+ | `data-toc` | With the default selector, counts any element inside the root as a heading. |
55
+ | `data-toc-ignore` | Leaves the heading off the ruler. |
56
+ | `data-toc-title="Short label"` | Shows this label instead of the heading text. |
57
+ | `data-toc-subtitle="Part two"` | Adds a second, quieter line under the label. |
58
+
59
+ Headings without an `id` get one made from their text, so every heading has a link you can share. Headings inside a GitHub Flavored Markdown (GFM) footnotes section are skipped.
60
+
61
+ ## Styling
62
+
63
+ The ruler takes its colour from the text around it. Three variables change the rest:
64
+
65
+ ```css
66
+ .morse {
67
+ --morse-ink: #1a1a1a; /* ticks, dot and label, default currentColor */
68
+ --morse-label-width: 280px; /* default 240px */
69
+ --morse-z: 60; /* default 41 */
70
+ }
71
+ ```
72
+
73
+ It's hidden below 1280px, where most layouts have no free left margin, and in print. To show it on narrower screens, add your own rule:
74
+
75
+ ```css
76
+ @media (min-width: 1024px) {
77
+ .morse {
78
+ display: flex;
79
+ }
80
+ }
81
+ ```
82
+
83
+ ## How it behaves
84
+
85
+ - **One label at a time.** Hovering shows the full text of the nearest heading, wrapped rather than cut. The first label arrives slowly; moving to the next heading is quick, and coming back within a moment skips the slow start.
86
+ - **Clicks jump.** Clicking a tick scrolls to its heading, puts it in the URL and moves focus there, so the next Tab carries on from the section. Cmd-click or Ctrl-click is left to the browser.
87
+ - **Keyboard and screen readers.** The ruler is a `Contents` nav with a real link per heading and `aria-current` on the link for the section being read. With no headings, it stays out of the landmarks list.
88
+ - **Reduced motion.** Nothing swells or slides; labels only fade and jumps are instant.
89
+ - **Server rendering.** Safe with React 18 and 19, including the Next.js App Router. The package marks itself as a client component.
90
+ - **Changing pages.** It lays itself out again when the page changes size, so images, embeds and late content don't leave the ticks behind.
91
+
92
+ ## Where it came from
93
+
94
+ The ruler started as a line minimap in a contract-signing tool I built for myself. It turned out long essays wanted it more, so it moved to [hanif.rest](https://hanif.rest/projects/morse).
95
+
96
+ ## License
97
+
98
+ MIT
99
+
100
+ Made with love by [Hanif Restian Pratikno](https://hanif.rest)
package/dist/index.cjs ADDED
@@ -0,0 +1,463 @@
1
+ 'use client'
2
+ "use strict";
3
+ var __defProp = Object.defineProperty;
4
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
+ var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
7
+ var __export = (target, all) => {
8
+ for (var name in all)
9
+ __defProp(target, name, { get: all[name], enumerable: true });
10
+ };
11
+ var __copyProps = (to, from, except, desc) => {
12
+ if (from && typeof from === "object" || typeof from === "function") {
13
+ for (let key of __getOwnPropNames(from))
14
+ if (!__hasOwnProp.call(to, key) && key !== except)
15
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
16
+ }
17
+ return to;
18
+ };
19
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
20
+
21
+ // src/index.ts
22
+ var index_exports = {};
23
+ __export(index_exports, {
24
+ Morse: () => Morse
25
+ });
26
+ module.exports = __toCommonJS(index_exports);
27
+
28
+ // src/morse.tsx
29
+ var import_react8 = require("react");
30
+ var import_react9 = require("motion/react");
31
+
32
+ // src/math.ts
33
+ var TICK_COUNT = 28;
34
+ var TICK_HEIGHT = 2;
35
+ var TICK_GAP = 9;
36
+ var TICK_PITCH = TICK_GAP + TICK_HEIGHT;
37
+ var LINE_TRAVEL = (TICK_COUNT - 1) * TICK_PITCH;
38
+ var LONG_TICK_WIDTH = 36;
39
+ var SHORT_TICK_WIDTH = 20;
40
+ var MAX_TICK_SCALE = 2.2;
41
+ var ACTIVATION_OFFSET = 120;
42
+ var POINTER_AWAY = Number.NEGATIVE_INFINITY;
43
+ var BASE_SCALE = 1;
44
+ var PROXIMITY_RADIUS = 64;
45
+ var PROXIMITY_INTENSITY = MAX_TICK_SCALE - BASE_SCALE;
46
+ var LAST_TICK = TICK_COUNT - 1;
47
+ var lerp = (from, to, amount) => from + (to - from) * amount;
48
+ var clamp = (value, min, max) => Math.min(max, Math.max(min, value));
49
+ var tickCenter = (tick) => tick * TICK_PITCH + TICK_HEIGHT / 2;
50
+ function proximityScale(distance) {
51
+ if (Math.abs(distance) >= PROXIMITY_RADIUS) return BASE_SCALE;
52
+ const closeness = 0.5 * (1 + Math.cos(Math.PI * Math.abs(distance) / PROXIMITY_RADIUS));
53
+ return BASE_SCALE + closeness * PROXIMITY_INTENSITY;
54
+ }
55
+ function scrollRange(article, viewportHeight) {
56
+ const start = article.top - ACTIVATION_OFFSET;
57
+ const end = Math.max(start + 1, article.bottom - viewportHeight);
58
+ return { start, end };
59
+ }
60
+ function progressAt(scrollY, range) {
61
+ return clamp((scrollY - range.start) / (range.end - range.start), 0, 1);
62
+ }
63
+ function markerTravel(progress) {
64
+ return clamp(progress, 0, 1) * LINE_TRAVEL;
65
+ }
66
+ function placeHeadingTicks(progresses) {
67
+ const kept = progresses.slice(0, TICK_COUNT);
68
+ const nearest = kept.map((progress) => Math.round(clamp(progress, 0, 1) * LAST_TICK));
69
+ const forward = nearest.reduce((placed, tick) => {
70
+ const previous = placed.at(-1) ?? -1;
71
+ return [...placed, Math.max(tick, previous + 1)];
72
+ }, []);
73
+ return forward.map((tick, index) => Math.min(tick, LAST_TICK - (forward.length - 1 - index)));
74
+ }
75
+ function nearestHeadingIndex(offsetY, headingTicks) {
76
+ return headingTicks.reduce(
77
+ (best, tick, index) => {
78
+ const distance = Math.abs(tick * TICK_PITCH - offsetY);
79
+ return best.index === -1 || distance < best.distance ? { index, distance } : best;
80
+ },
81
+ { index: -1, distance: Number.POSITIVE_INFINITY }
82
+ ).index;
83
+ }
84
+ function activeHeadingIndex(headingTops) {
85
+ return headingTops.reduce((last, top, index) => top <= ACTIVATION_OFFSET ? index : last, -1);
86
+ }
87
+
88
+ // src/label.tsx
89
+ var import_react = require("react");
90
+ var import_react2 = require("motion/react");
91
+ var import_jsx_runtime = require("react/jsx-runtime");
92
+ var EASE_OUT = [0.23, 1, 0.32, 1];
93
+ var POSITION_SPRING = { stiffness: 380, damping: 40, mass: 0.9 };
94
+ var ROLL_PX = 6;
95
+ var SWAP = { duration: 0.24, ease: EASE_OUT };
96
+ var useIsomorphicLayoutEffect = typeof window === "undefined" ? import_react.useEffect : import_react.useLayoutEffect;
97
+ var rollVariants = {
98
+ enter: ({ sign, isReducedMotion }) => isReducedMotion ? { opacity: 0 } : { opacity: 0, y: sign * ROLL_PX, filter: "blur(3px)" },
99
+ center: ({ isReducedMotion }) => isReducedMotion ? { opacity: 1 } : { opacity: 1, y: 0, filter: "blur(0px)" },
100
+ exit: ({ sign, isReducedMotion }) => isReducedMotion ? { opacity: 0 } : { opacity: 0, y: -sign * ROLL_PX, filter: "blur(3px)" }
101
+ };
102
+ function Label({ heading, offsetY, left, isVisible, shouldGlide, direction, entrance, isReducedMotion }) {
103
+ const y = (0, import_react2.useSpring)(offsetY, POSITION_SPRING);
104
+ useIsomorphicLayoutEffect(() => {
105
+ if (shouldGlide && !isReducedMotion) y.set(offsetY);
106
+ else y.jump(offsetY);
107
+ }, [offsetY, shouldGlide, isReducedMotion, y]);
108
+ const roll = { sign: direction === "down" ? 1 : -1, isReducedMotion };
109
+ return /* @__PURE__ */ (0, import_jsx_runtime.jsx)(
110
+ import_react2.motion.div,
111
+ {
112
+ "data-testid": "morse-label",
113
+ "data-visible": isVisible,
114
+ "data-glide": shouldGlide,
115
+ "data-direction": direction,
116
+ "data-entrance": entrance,
117
+ "aria-hidden": "true",
118
+ className: "morse-label",
119
+ style: { left, y },
120
+ children: /* @__PURE__ */ (0, import_jsx_runtime.jsx)("div", { className: "morse-label-body", children: /* @__PURE__ */ (0, import_jsx_runtime.jsx)(import_react2.AnimatePresence, { mode: "popLayout", initial: false, custom: roll, children: heading && /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(
121
+ import_react2.motion.span,
122
+ {
123
+ className: "morse-label-text",
124
+ custom: roll,
125
+ variants: rollVariants,
126
+ initial: "enter",
127
+ animate: "center",
128
+ exit: "exit",
129
+ transition: SWAP,
130
+ children: [
131
+ heading.text,
132
+ heading.subtitle && /* @__PURE__ */ (0, import_jsx_runtime.jsx)("span", { className: "morse-label-subtitle", children: heading.subtitle })
133
+ ]
134
+ },
135
+ heading.id
136
+ ) }) })
137
+ }
138
+ );
139
+ }
140
+
141
+ // src/tick.tsx
142
+ var import_react3 = require("react");
143
+ var import_react4 = require("motion/react");
144
+ var import_jsx_runtime2 = require("react/jsx-runtime");
145
+ var TICK_SPRING = { stiffness: 420, damping: 38 };
146
+ var FULL_SWELL_VELOCITY = 300;
147
+ function toneOf(isHeading, isPassed) {
148
+ if (!isHeading) return "plain";
149
+ return isPassed ? "passed" : "ahead";
150
+ }
151
+ function Tick({ index, isHeading, isPassed, lineY, pointerY, isReducedMotion }) {
152
+ const ref = (0, import_react3.useRef)(null);
153
+ const scaleX = (0, import_react4.useSpring)(BASE_SCALE, TICK_SPRING);
154
+ (0, import_react4.useMotionValueEvent)(pointerY, "change", (clientY) => {
155
+ if (isReducedMotion) return;
156
+ const box = ref.current?.getBoundingClientRect();
157
+ if (!box) return;
158
+ scaleX.set(proximityScale(clientY - (box.top + box.height / 2)));
159
+ });
160
+ (0, import_react4.useMotionValueEvent)(lineY, "change", (offset) => {
161
+ if (isReducedMotion || pointerY.get() !== POINTER_AWAY) return;
162
+ const target = proximityScale(offset - tickCenter(index));
163
+ const swell = clamp(Math.abs(lineY.getVelocity()) / FULL_SWELL_VELOCITY, 0, 1);
164
+ scaleX.set(lerp(BASE_SCALE, target, swell));
165
+ });
166
+ return /* @__PURE__ */ (0, import_jsx_runtime2.jsx)(
167
+ import_react4.motion.div,
168
+ {
169
+ ref,
170
+ "data-testid": "morse-tick",
171
+ "data-kind": isHeading ? "heading" : "plain",
172
+ "data-passed": isHeading ? isPassed : void 0,
173
+ "data-tone": toneOf(isHeading, isPassed),
174
+ className: "morse-tick",
175
+ style: {
176
+ width: isHeading ? LONG_TICK_WIDTH : SHORT_TICK_WIDTH,
177
+ height: TICK_HEIGHT,
178
+ scaleX,
179
+ transformOrigin: "0 50%"
180
+ }
181
+ }
182
+ );
183
+ }
184
+
185
+ // src/use-headings.ts
186
+ var import_react5 = require("react");
187
+ var EMPTY_LAYOUT = { headings: [], headingTicks: [], range: { start: 0, end: 1 } };
188
+ function slugify(text) {
189
+ return text.trim().toLowerCase().replace(/\s+/g, "-").replace(/[^\p{L}\p{N}_-]/gu, "");
190
+ }
191
+ function ensureId(element, index) {
192
+ if (element.id) return element.id;
193
+ const base = slugify(element.textContent ?? "") || `section-${index}`;
194
+ const isTaken = (id2) => document.getElementById(id2) !== null;
195
+ const free = (suffix) => isTaken(`${base}-${suffix}`) ? free(suffix + 1) : `${base}-${suffix}`;
196
+ const id = isTaken(base) ? free(1) : base;
197
+ element.id = id;
198
+ return id;
199
+ }
200
+ function scanHeadings(selector, root) {
201
+ return Array.from(root.querySelectorAll(selector)).filter((element) => !element.hasAttribute("data-toc-ignore")).filter((element) => !element.closest("[data-footnotes]")).map((element, index) => ({
202
+ id: ensureId(element, index),
203
+ text: element.getAttribute("data-toc-title") || element.textContent?.trim() || "Section",
204
+ subtitle: element.getAttribute("data-toc-subtitle") || void 0,
205
+ element
206
+ }));
207
+ }
208
+ function findRoot(rootSelector) {
209
+ return rootSelector ? document.querySelector(rootSelector) : null;
210
+ }
211
+ function rootBounds(root) {
212
+ if (!root) return { top: 0, bottom: document.documentElement.scrollHeight };
213
+ const box = root.getBoundingClientRect();
214
+ return { top: box.top + window.scrollY, bottom: box.bottom + window.scrollY };
215
+ }
216
+ function measure(headings, root) {
217
+ const range = scrollRange(rootBounds(root), window.innerHeight);
218
+ const progresses = headings.map(
219
+ (heading) => progressAt(heading.element.getBoundingClientRect().top + window.scrollY - ACTIVATION_OFFSET, range)
220
+ );
221
+ const headingTicks = placeHeadingTicks(progresses);
222
+ return { headings: headings.slice(0, headingTicks.length), headingTicks, range };
223
+ }
224
+ var isSameNumbers = (a, b) => a.length === b.length && a.every((value, index) => value === b[index]);
225
+ function isSameLayout(previous, next) {
226
+ return previous.range.start === next.range.start && previous.range.end === next.range.end && isSameNumbers(previous.headingTicks, next.headingTicks) && previous.headings.length === next.headings.length && previous.headings.every((heading, index) => {
227
+ const other = next.headings[index];
228
+ return heading.element === other?.element && heading.id === other.id && heading.text === other.text && heading.subtitle === other.subtitle;
229
+ });
230
+ }
231
+ function useArticleHeadings(selector, rootSelector) {
232
+ const [layout, setLayout] = (0, import_react5.useState)(EMPTY_LAYOUT);
233
+ (0, import_react5.useEffect)(() => {
234
+ let isCancelled = false;
235
+ let frame = null;
236
+ const update = () => {
237
+ frame = null;
238
+ if (isCancelled) return;
239
+ const root = findRoot(rootSelector);
240
+ const next = measure(scanHeadings(selector, root ?? document), root);
241
+ setLayout((previous) => isSameLayout(previous, next) ? previous : next);
242
+ };
243
+ const schedule = () => {
244
+ if (frame === null) frame = window.requestAnimationFrame(update);
245
+ };
246
+ update();
247
+ window.addEventListener("resize", schedule);
248
+ const observer = typeof ResizeObserver === "undefined" ? null : new ResizeObserver(schedule);
249
+ observer?.observe(document.body);
250
+ document.fonts?.ready.then(schedule).catch(() => void 0);
251
+ return () => {
252
+ isCancelled = true;
253
+ window.removeEventListener("resize", schedule);
254
+ observer?.disconnect();
255
+ if (frame !== null) window.cancelAnimationFrame(frame);
256
+ };
257
+ }, [selector, rootSelector]);
258
+ return layout;
259
+ }
260
+
261
+ // src/use-scroll.ts
262
+ var import_react6 = require("react");
263
+ var import_react7 = require("motion/react");
264
+ var LINE_SPRING = { stiffness: 650, damping: 40 };
265
+ var LINE_SMOOTHING = 0.5;
266
+ var LINE_SETTLE_PX = 0.01;
267
+ function useRulerScroll({ headings, range }, isReducedMotion) {
268
+ const lineY = (0, import_react7.useSpring)(0, LINE_SPRING);
269
+ const target = (0, import_react6.useRef)(0);
270
+ const [activeIndex, setActiveIndex] = (0, import_react6.useState)(-1);
271
+ (0, import_react6.useEffect)(() => {
272
+ let frame = null;
273
+ const update = () => {
274
+ frame = null;
275
+ target.current = markerTravel(progressAt(window.scrollY, range));
276
+ if (isReducedMotion) lineY.jump(target.current);
277
+ setActiveIndex(activeHeadingIndex(headings.map((heading) => heading.element.getBoundingClientRect().top)));
278
+ };
279
+ const schedule = () => {
280
+ if (frame === null) frame = window.requestAnimationFrame(update);
281
+ };
282
+ update();
283
+ window.addEventListener("scroll", schedule, { passive: true });
284
+ return () => {
285
+ window.removeEventListener("scroll", schedule);
286
+ if (frame !== null) window.cancelAnimationFrame(frame);
287
+ };
288
+ }, [headings, range, isReducedMotion, lineY]);
289
+ (0, import_react7.useAnimationFrame)(() => {
290
+ if (isReducedMotion) return;
291
+ const current = lineY.get();
292
+ const next = lerp(current, target.current, LINE_SMOOTHING);
293
+ if (Math.abs(next - current) > LINE_SETTLE_PX) lineY.set(next);
294
+ });
295
+ return { lineY, activeIndex };
296
+ }
297
+
298
+ // src/morse.tsx
299
+ var import_jsx_runtime3 = require("react/jsx-runtime");
300
+ var DEFAULT_SELECTOR = "h2, h3, [data-toc]";
301
+ var DEFAULT_ROOT_SELECTOR = "article";
302
+ var DEFAULT_JUMP_OFFSET = 80;
303
+ var LABEL_LEFT = Math.ceil(LONG_TICK_WIDTH * MAX_TICK_SCALE) + 16;
304
+ var LABEL_FIRST_LINE_CENTER = 9;
305
+ var NO_HEADING = -1;
306
+ var WARM_MS = 400;
307
+ var MARKER_SIZE = 6;
308
+ var MARKER_LEFT = -14;
309
+ var HIDDEN_LABEL = {
310
+ index: NO_HEADING,
311
+ isVisible: false,
312
+ shouldGlide: false,
313
+ direction: "down",
314
+ entrance: "slow"
315
+ };
316
+ function jumpTo(element, offset, isReducedMotion) {
317
+ const top = element.getBoundingClientRect().top + window.scrollY - offset;
318
+ window.scrollTo({ top, behavior: isReducedMotion ? "auto" : "smooth" });
319
+ window.history.replaceState(window.history.state, "", `#${element.id}`);
320
+ if (!element.hasAttribute("tabindex")) element.setAttribute("tabindex", "-1");
321
+ element.focus({ preventScroll: true });
322
+ }
323
+ function isPlainClick(event) {
324
+ return event.button === 0 && !event.metaKey && !event.ctrlKey && !event.shiftKey && !event.altKey;
325
+ }
326
+ function Morse({
327
+ selector = DEFAULT_SELECTOR,
328
+ rootSelector = DEFAULT_ROOT_SELECTOR,
329
+ jumpOffset = DEFAULT_JUMP_OFFSET,
330
+ className
331
+ }) {
332
+ const isReducedMotion = (0, import_react9.useReducedMotion)() ?? false;
333
+ const layout = useArticleHeadings(selector, rootSelector);
334
+ const { lineY, activeIndex } = useRulerScroll(layout, isReducedMotion);
335
+ const pointerY = (0, import_react9.useMotionValue)(POINTER_AWAY);
336
+ const markerTransform = (0, import_react9.useTransform)(lineY, (offset) => `translate3d(0, ${offset}px, 0)`);
337
+ const ticksRef = (0, import_react8.useRef)(null);
338
+ const [label, setLabel] = (0, import_react8.useState)(HIDDEN_LABEL);
339
+ const hiddenAt = (0, import_react8.useRef)(null);
340
+ const { headings, headingTicks } = layout;
341
+ const headingIndexAtTick = new Map(headingTicks.map((tick, index) => [tick, index]));
342
+ const showLabel = (index, at) => {
343
+ if (index === NO_HEADING) return;
344
+ const isWarm = hiddenAt.current !== null && at - hiddenAt.current < WARM_MS;
345
+ setLabel((previous) => {
346
+ if (previous.isVisible && previous.index === index) return previous;
347
+ if (previous.isVisible) {
348
+ return {
349
+ index,
350
+ isVisible: true,
351
+ shouldGlide: true,
352
+ direction: index < previous.index ? "up" : "down",
353
+ entrance: previous.entrance
354
+ };
355
+ }
356
+ return { index, isVisible: true, shouldGlide: false, direction: "down", entrance: isWarm ? "quick" : "slow" };
357
+ });
358
+ };
359
+ const hideLabel = (at) => {
360
+ hiddenAt.current = at;
361
+ setLabel((previous) => ({ ...previous, isVisible: false, shouldGlide: false }));
362
+ };
363
+ const headingAtPointer = (clientY) => nearestHeadingIndex(clientY - (ticksRef.current?.getBoundingClientRect().top ?? 0), headingTicks);
364
+ const handleMouseMove = (event) => {
365
+ pointerY.set(event.clientY);
366
+ showLabel(headingAtPointer(event.clientY), event.timeStamp);
367
+ };
368
+ const handleMouseLeave = (event) => {
369
+ pointerY.set(POINTER_AWAY);
370
+ hideLabel(event.timeStamp);
371
+ };
372
+ const handleRulerClick = (event) => {
373
+ if (!isPlainClick(event)) return;
374
+ const heading = headings[headingAtPointer(event.clientY)];
375
+ if (heading) jumpTo(heading.element, jumpOffset, isReducedMotion);
376
+ };
377
+ return /* @__PURE__ */ (0, import_jsx_runtime3.jsx)(
378
+ "nav",
379
+ {
380
+ "aria-label": "Contents",
381
+ "aria-hidden": headings.length === 0 ? true : void 0,
382
+ className: className ? `morse ${className}` : "morse",
383
+ children: /* @__PURE__ */ (0, import_jsx_runtime3.jsxs)("div", { className: "morse-rail", children: [
384
+ /* @__PURE__ */ (0, import_jsx_runtime3.jsxs)(
385
+ "div",
386
+ {
387
+ "data-testid": "morse-ticks",
388
+ className: "morse-track",
389
+ onMouseMove: handleMouseMove,
390
+ onMouseLeave: handleMouseLeave,
391
+ onClick: handleRulerClick,
392
+ children: [
393
+ /* @__PURE__ */ (0, import_jsx_runtime3.jsx)("div", { ref: ticksRef, "aria-hidden": "true", className: "morse-ticks", style: { gap: TICK_GAP }, children: Array.from({ length: TICK_COUNT }, (_, tick) => {
394
+ const headingIndex = headingIndexAtTick.get(tick);
395
+ return /* @__PURE__ */ (0, import_jsx_runtime3.jsx)(
396
+ Tick,
397
+ {
398
+ index: tick,
399
+ isHeading: headingIndex !== void 0,
400
+ isPassed: headingIndex !== void 0 && headingIndex <= activeIndex,
401
+ lineY,
402
+ pointerY,
403
+ isReducedMotion
404
+ },
405
+ tick
406
+ );
407
+ }) }),
408
+ /* @__PURE__ */ (0, import_jsx_runtime3.jsx)("ol", { className: "morse-links", children: headings.map((heading, index) => /* @__PURE__ */ (0, import_jsx_runtime3.jsx)("li", { children: /* @__PURE__ */ (0, import_jsx_runtime3.jsx)(
409
+ "a",
410
+ {
411
+ href: `#${heading.id}`,
412
+ "aria-current": index === activeIndex ? "location" : void 0,
413
+ onClick: (event) => {
414
+ event.stopPropagation();
415
+ if (!isPlainClick(event)) return;
416
+ event.preventDefault();
417
+ jumpTo(heading.element, jumpOffset, isReducedMotion);
418
+ },
419
+ onFocus: (event) => showLabel(index, event.timeStamp),
420
+ onBlur: (event) => hideLabel(event.timeStamp),
421
+ className: "morse-link",
422
+ style: {
423
+ top: tickCenter(headingTicks[index] ?? 0) - TICK_PITCH / 2,
424
+ width: LONG_TICK_WIDTH,
425
+ height: TICK_PITCH
426
+ },
427
+ children: /* @__PURE__ */ (0, import_jsx_runtime3.jsx)("span", { className: "morse-sr-only", children: heading.text })
428
+ }
429
+ ) }, heading.id)) })
430
+ ]
431
+ }
432
+ ),
433
+ /* @__PURE__ */ (0, import_jsx_runtime3.jsx)(
434
+ import_react9.motion.div,
435
+ {
436
+ "data-testid": "morse-marker",
437
+ "aria-hidden": "true",
438
+ className: "morse-marker",
439
+ style: { left: MARKER_LEFT, marginTop: TICK_HEIGHT / 2 - MARKER_SIZE / 2, transform: markerTransform }
440
+ }
441
+ ),
442
+ /* @__PURE__ */ (0, import_jsx_runtime3.jsx)(
443
+ Label,
444
+ {
445
+ heading: headings[label.index],
446
+ offsetY: tickCenter(headingTicks[label.index] ?? 0) - LABEL_FIRST_LINE_CENTER,
447
+ left: LABEL_LEFT,
448
+ isVisible: label.isVisible,
449
+ shouldGlide: label.shouldGlide,
450
+ direction: label.direction,
451
+ entrance: label.entrance,
452
+ isReducedMotion
453
+ }
454
+ )
455
+ ] })
456
+ }
457
+ );
458
+ }
459
+ // Annotate the CommonJS export names for ESM import in node:
460
+ 0 && (module.exports = {
461
+ Morse
462
+ });
463
+ //# sourceMappingURL=index.cjs.map