@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 +21 -0
- package/README.md +99 -2
- package/dist/index.cjs +463 -0
- package/dist/index.cjs.map +1 -0
- package/dist/index.d.cts +38 -0
- package/dist/index.d.ts +38 -0
- package/dist/index.js +437 -0
- package/dist/index.js.map +1 -0
- package/dist/style.css +165 -0
- package/package.json +84 -4
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/index.ts","../src/morse.tsx","../src/math.ts","../src/label.tsx","../src/tick.tsx","../src/use-headings.ts","../src/use-scroll.ts"],"sourcesContent":["export { Morse, type MorseProps } from './morse'\n","import { useRef, useState, type MouseEvent, type ReactElement } from 'react'\nimport { motion, useMotionValue, useReducedMotion, useTransform } from 'motion/react'\nimport {\n LONG_TICK_WIDTH,\n MAX_TICK_SCALE,\n nearestHeadingIndex,\n POINTER_AWAY,\n TICK_COUNT,\n TICK_GAP,\n TICK_HEIGHT,\n TICK_PITCH,\n tickCenter,\n} from './math'\nimport { Label, type LabelDirection, type LabelEntrance } from './label'\nimport { Tick } from './tick'\nimport { useArticleHeadings } from './use-headings'\nimport { useRulerScroll } from './use-scroll'\n\n/** h1 is usually the page title, and h4 and deeper would crowd 28 ticks. `[data-toc]` opts anything else in. */\nconst DEFAULT_SELECTOR = 'h2, h3, [data-toc]'\n/** Most article layouts wrap the body in one. Without it the ruler maps the whole page. */\nconst DEFAULT_ROOT_SELECTOR = 'article'\n/**\n * Room above a heading after a jump, so it doesn't land under a sticky header. Under ACTIVATION_OFFSET, so\n * the heading you land on is marked current.\n */\nconst DEFAULT_JUMP_OFFSET = 80\n/** Clear of a fully swollen long tick, plus a 16px gap. */\nconst LABEL_LEFT = Math.ceil(LONG_TICK_WIDTH * MAX_TICK_SCALE) + 16\n/** Half the 18px line-height in style.css, so the first line centres on the tick. Change both together. */\nconst LABEL_FIRST_LINE_CENTER = 9\nconst NO_HEADING = -1\n/**\n * Like a row of tooltips: the first label arrives slowly, but back on the ruler within this long of leaving,\n * it returns quickly.\n */\nconst WARM_MS = 400\n/**\n * Small, so it reads as a position, not a second cursor. Must match the 6px of .morse-marker in style.css;\n * it centres the dot on a tick.\n */\nconst MARKER_SIZE = 6\n/** In the rail's margin, left of the ticks, so the dot never covers one. */\nconst MARKER_LEFT = -14\n\ninterface LabelState {\n index: number\n isVisible: boolean\n shouldGlide: boolean\n /** Which way the pointer moved to reach this heading, so the text rolls in from that side. */\n direction: LabelDirection\n entrance: LabelEntrance\n}\n\nconst HIDDEN_LABEL: LabelState = {\n index: NO_HEADING,\n isVisible: false,\n shouldGlide: false,\n direction: 'down',\n entrance: 'slow',\n}\n\n/**\n * Scrolls to the heading, puts it in the URL so the section can be shared, and moves focus onto it so the\n * next Tab carries on from the section rather than from the ruler.\n */\nfunction jumpTo(element: HTMLElement, offset: number, isReducedMotion: boolean) {\n const top = element.getBoundingClientRect().top + window.scrollY - offset\n window.scrollTo({ top, behavior: isReducedMotion ? 'auto' : 'smooth' })\n // Keep whatever a client-side router stored for this entry.\n window.history.replaceState(window.history.state, '', `#${element.id}`)\n if (!element.hasAttribute('tabindex')) element.setAttribute('tabindex', '-1')\n element.focus({ preventScroll: true })\n}\n\n/** A modified or non-primary click is the browser's: open in a new tab, copy the link. */\nfunction isPlainClick(event: MouseEvent<HTMLElement>): boolean {\n return event.button === 0 && !event.metaKey && !event.ctrlKey && !event.shiftKey && !event.altKey\n}\n\nexport type MorseProps = {\n /**\n * Which elements inside the root count as headings. Add `data-toc-ignore` to skip one, `data-toc-title` to\n * shorten its label, `data-toc-subtitle` for a second line. Headings without an id get one made from their\n * text. Headings inside a GFM footnotes section are skipped.\n * @default 'h2, h3, [data-toc]'\n */\n selector?: string\n /**\n * The element whose headings the ruler maps and whose length it measures. If nothing matches, the whole\n * page is used.\n * @default 'article'\n */\n rootSelector?: string\n /**\n * px left above a heading after a jump. Raise it for a taller sticky header, but keep it under 120 or the\n * heading you land on won't be marked current.\n * @default 80\n */\n jumpOffset?: number\n /** Added to the nav's own `morse` class. Colour, stacking and label width come from `--morse-*` variables. */\n className?: string\n}\n\n/**\n * The article's contents as a ruler at the left edge: one rounded long tick per heading, placed where the\n * heading sits in the article, quiet short ticks between, and a small dot that rides down as you read.\n * Headings already read are full ink; the ones ahead are half ink. Hovering shows the full text of the\n * heading nearest the pointer (one at a time, so long headings wrap instead of being cut); clicking jumps to\n * it. Tabbing walks the headings and shows the same label.\n *\n * Shows up to 28 headings. Needs `style.css`, and stays hidden below 1280px and in print. With no headings,\n * it stays out of the landmarks list.\n */\nexport function Morse({\n selector = DEFAULT_SELECTOR,\n rootSelector = DEFAULT_ROOT_SELECTOR,\n jumpOffset = DEFAULT_JUMP_OFFSET,\n className,\n}: MorseProps): ReactElement {\n const isReducedMotion = useReducedMotion() ?? false\n const layout = useArticleHeadings(selector, rootSelector)\n const { lineY, activeIndex } = useRulerScroll(layout, isReducedMotion)\n const pointerY = useMotionValue(POINTER_AWAY)\n const markerTransform = useTransform(lineY, (offset) => `translate3d(0, ${offset}px, 0)`)\n const ticksRef = useRef<HTMLDivElement | null>(null)\n const [label, setLabel] = useState<LabelState>(HIDDEN_LABEL)\n const hiddenAt = useRef<number | null>(null)\n\n const { headings, headingTicks } = layout\n const headingIndexAtTick = new Map(headingTicks.map((tick, index) => [tick, index]))\n\n // `at` is the event's timeStamp, so leaving and returning use the same clock (the one tests fake).\n const showLabel = (index: number, at: number) => {\n if (index === NO_HEADING) return\n const isWarm = hiddenAt.current !== null && at - hiddenAt.current < WARM_MS\n setLabel((previous) => {\n if (previous.isVisible && previous.index === index) return previous\n // Only an arrival from hidden picks its pace; heading to heading is the quick spring and roll.\n if (previous.isVisible) {\n return {\n index,\n isVisible: true,\n shouldGlide: true,\n direction: index < previous.index ? 'up' : 'down',\n entrance: previous.entrance,\n }\n }\n return { index, isVisible: true, shouldGlide: false, direction: 'down', entrance: isWarm ? 'quick' : 'slow' }\n })\n }\n const hideLabel = (at: number) => {\n hiddenAt.current = at\n setLabel((previous) => ({ ...previous, isVisible: false, shouldGlide: false }))\n }\n\n const headingAtPointer = (clientY: number) =>\n nearestHeadingIndex(clientY - (ticksRef.current?.getBoundingClientRect().top ?? 0), headingTicks)\n\n const handleMouseMove = (event: MouseEvent<HTMLDivElement>) => {\n pointerY.set(event.clientY)\n showLabel(headingAtPointer(event.clientY), event.timeStamp)\n }\n const handleMouseLeave = (event: MouseEvent<HTMLDivElement>) => {\n pointerY.set(POINTER_AWAY)\n hideLabel(event.timeStamp)\n }\n const handleRulerClick = (event: MouseEvent<HTMLDivElement>) => {\n if (!isPlainClick(event)) return\n const heading = headings[headingAtPointer(event.clientY)]\n if (heading) jumpTo(heading.element, jumpOffset, isReducedMotion)\n }\n\n return (\n <nav\n aria-label=\"Contents\"\n // An empty contents landmark is noise for screen readers; the quiet ticks can stay on screen.\n aria-hidden={headings.length === 0 ? true : undefined}\n className={className ? `morse ${className}` : 'morse'}\n >\n <div className=\"morse-rail\">\n <div\n data-testid=\"morse-ticks\"\n className=\"morse-track\"\n onMouseMove={handleMouseMove}\n onMouseLeave={handleMouseLeave}\n onClick={handleRulerClick}\n >\n <div ref={ticksRef} aria-hidden=\"true\" className=\"morse-ticks\" style={{ gap: TICK_GAP }}>\n {Array.from({ length: TICK_COUNT }, (_, tick) => {\n const headingIndex = headingIndexAtTick.get(tick)\n return (\n <Tick\n key={tick}\n index={tick}\n isHeading={headingIndex !== undefined}\n isPassed={headingIndex !== undefined && headingIndex <= activeIndex}\n lineY={lineY}\n pointerY={pointerY}\n isReducedMotion={isReducedMotion}\n />\n )\n })}\n </div>\n\n <ol className=\"morse-links\">\n {headings.map((heading, index) => (\n <li key={heading.id}>\n <a\n href={`#${heading.id}`}\n aria-current={index === activeIndex ? 'location' : undefined}\n onClick={(event) => {\n // Otherwise the track's click handler jumps again, to whatever heading is nearest the pointer.\n event.stopPropagation()\n if (!isPlainClick(event)) return\n event.preventDefault()\n jumpTo(heading.element, jumpOffset, isReducedMotion)\n }}\n onFocus={(event) => showLabel(index, event.timeStamp)}\n onBlur={(event) => hideLabel(event.timeStamp)}\n className=\"morse-link\"\n style={{\n top: tickCenter(headingTicks[index] ?? 0) - TICK_PITCH / 2,\n width: LONG_TICK_WIDTH,\n height: TICK_PITCH,\n }}\n >\n <span className=\"morse-sr-only\">{heading.text}</span>\n </a>\n </li>\n ))}\n </ol>\n </div>\n\n <motion.div\n data-testid=\"morse-marker\"\n aria-hidden=\"true\"\n className=\"morse-marker\"\n style={{ left: MARKER_LEFT, marginTop: TICK_HEIGHT / 2 - MARKER_SIZE / 2, transform: markerTransform }}\n />\n\n <Label\n heading={headings[label.index]}\n offsetY={tickCenter(headingTicks[label.index] ?? 0) - LABEL_FIRST_LINE_CENTER}\n left={LABEL_LEFT}\n isVisible={label.isVisible}\n shouldGlide={label.shouldGlide}\n direction={label.direction}\n entrance={label.entrance}\n isReducedMotion={isReducedMotion}\n />\n </div>\n </nav>\n )\n}\n","/**\n * The numbers behind the ruler, kept apart from React so they test without a browser. Long ticks mark\n * headings; the marker tracks the root element's scroll, not the whole page's.\n */\n\n/**\n * Also the most headings the ruler can show: placeHeadingTicks drops any past this. At 11px a tick, 28 keeps\n * the ruler under 300px tall.\n */\nexport const TICK_COUNT = 28\n/** 2px: thin, but thick enough for the rounded ends to read. */\nexport const TICK_HEIGHT = 2\n/** Close enough that the ticks read as one ruler and the swell rolls across several at once. */\nexport const TICK_GAP = 9\n/** One tick plus its gap. Tick i's centre is i * TICK_PITCH + TICK_HEIGHT / 2. */\nexport const TICK_PITCH = TICK_GAP + TICK_HEIGHT\n/** First tick to last: how far the marker rides as the root scrolls. */\nexport const LINE_TRAVEL = (TICK_COUNT - 1) * TICK_PITCH\n/**\n * Long enough to read as a section at a glance. Also the width of each heading's link, so the hit area\n * matches the tick.\n */\nexport const LONG_TICK_WIDTH = 36\n/** Clearly shorter than a heading tick, so the rail between headings stays quiet. */\nexport const SHORT_TICK_WIDTH = 20\n/** How far a tick can swell under the pointer. The label is placed clear of a long tick at this scale. */\nexport const MAX_TICK_SCALE = 2.2\n\n/**\n * A heading counts as the one being read once its top is within this many px of the viewport top. Keep it\n * above the jump offset, or a heading you jump to won't count as the one being read.\n */\nexport const ACTIVATION_OFFSET = 120\n\n/**\n * The pointer is off the ruler. Infinitely far, so no tick swells at any height. Ticks also check for it\n * before letting the scroll swell run.\n */\nexport const POINTER_AWAY = Number.NEGATIVE_INFINITY\n\n/** A tick at rest, at its own width. */\nexport const BASE_SCALE = 1\n/** About six ticks either side, so the swell rolls across several at once. */\nconst PROXIMITY_RADIUS = 64\nconst PROXIMITY_INTENSITY = MAX_TICK_SCALE - BASE_SCALE\nconst LAST_TICK = TICK_COUNT - 1\n\n/** Scroll positions, in document px, where the marker sits on the first and last tick. */\nexport interface ScrollRange {\n start: number\n end: number\n}\n\n/** An element's top and bottom in document px, not viewport px. */\nexport interface VerticalBounds {\n top: number\n bottom: number\n}\n\nexport const lerp = (from: number, to: number, amount: number): number => from + (to - from) * amount\nexport const clamp = (value: number, min: number, max: number): number => Math.min(max, Math.max(min, value))\n\n/** Centre of tick `tick`, in px from the first tick's top edge. */\nexport const tickCenter = (tick: number): number => tick * TICK_PITCH + TICK_HEIGHT / 2\n\n/**\n * How far a tick stretches for something `distance` px from its centre: MAX_TICK_SCALE on top of it, easing\n * to 1 at PROXIMITY_RADIUS on a cosine bell. The bell is flat at both ends, so moving along the ruler rolls a\n * wave instead of stepping tick by tick.\n */\nexport function proximityScale(distance: number): number {\n if (Math.abs(distance) >= PROXIMITY_RADIUS) return BASE_SCALE\n const closeness = 0.5 * (1 + Math.cos((Math.PI * Math.abs(distance)) / PROXIMITY_RADIUS))\n return BASE_SCALE + closeness * PROXIMITY_INTENSITY\n}\n\n/**\n * The scroll positions the ruler spans, in document px: from the root's top reaching the activation line to\n * its bottom reaching the viewport bottom. Never empty, so progress never divides by zero.\n */\nexport function scrollRange(article: VerticalBounds, viewportHeight: number): ScrollRange {\n const start = article.top - ACTIVATION_OFFSET\n const end = Math.max(start + 1, article.bottom - viewportHeight)\n return { start, end }\n}\n\n/** Clamped, so the marker rests on the end ticks above and below the root. */\nexport function progressAt(scrollY: number, range: ScrollRange): number {\n return clamp((scrollY - range.start) / (range.end - range.start), 0, 1)\n}\n\n/** Clamps again, so no caller can push the marker off the ruler. */\nexport function markerTravel(progress: number): number {\n return clamp(progress, 0, 1) * LINE_TRAVEL\n}\n\n/**\n * One tick per heading, nearest its place in the root. A heading that lands on a taken tick moves down;\n * headings packed against the end are pushed back up so each keeps its own. More headings than ticks: the\n * extras are dropped rather than stacked. Expects progresses in document order.\n */\nexport function placeHeadingTicks(progresses: readonly number[]): number[] {\n const kept = progresses.slice(0, TICK_COUNT)\n const nearest = kept.map((progress) => Math.round(clamp(progress, 0, 1) * LAST_TICK))\n\n const forward = nearest.reduce<number[]>((placed, tick) => {\n const previous = placed.at(-1) ?? -1\n return [...placed, Math.max(tick, previous + 1)]\n }, [])\n\n // Room left after each heading: the i-th of n can sit no lower than LAST_TICK - (n - 1 - i).\n return forward.map((tick, index) => Math.min(tick, LAST_TICK - (forward.length - 1 - index)))\n}\n\n/** The heading whose tick sits nearest `offsetY` px down the ruler; -1 when there are none. */\nexport function nearestHeadingIndex(offsetY: number, headingTicks: readonly number[]): number {\n return headingTicks.reduce(\n (best, tick, index) => {\n const distance = Math.abs(tick * TICK_PITCH - offsetY)\n return best.index === -1 || distance < best.distance ? { index, distance } : best\n },\n { index: -1, distance: Number.POSITIVE_INFINITY },\n ).index\n}\n\n/**\n * The heading being read: the last one whose top (viewport px) has reached the activation line. -1 before\n * the first one has (the intro is still on screen) and with no headings.\n */\nexport function activeHeadingIndex(headingTops: readonly number[]): number {\n return headingTops.reduce((last, top, index) => (top <= ACTIVATION_OFFSET ? index : last), -1)\n}\n","import { useEffect, useLayoutEffect } from 'react'\nimport { AnimatePresence, motion, useSpring, type Transition } from 'motion/react'\nimport type { RulerHeading } from './use-headings'\n\n/** Which way the pointer moved along the ruler; the text rolls in from that side. */\nexport type LabelDirection = 'up' | 'down'\n/** `slow` for the first label, `quick` when the pointer comes back to a ruler that is still warm. */\nexport type LabelEntrance = 'slow' | 'quick'\n\n/** The same ease-out as `--morse-ease-out` in style.css, for motion's JS side. */\nconst EASE_OUT: [number, number, number, number] = [0.23, 1, 0.32, 1]\n/**\n * The label's position follows the pointer on a spring, not a tween: a fast scrub keeps its momentum\n * instead of restarting a fixed-length glide at every heading. Damped just past critical, so it never overshoots.\n */\nconst POSITION_SPRING = { stiffness: 380, damping: 40, mass: 0.9 }\n/** How far the text rolls in from the direction of travel. */\nconst ROLL_PX = 6\n/** Quick enough to keep up with a scrub, long enough to see the roll. */\nconst SWAP: Transition = { duration: 0.24, ease: EASE_OUT }\n/** React 18 warns about layout effects during server rendering; there is nothing to measure there anyway. */\nconst useIsomorphicLayoutEffect = typeof window === 'undefined' ? useEffect : useLayoutEffect\n\ninterface RollContext {\n /** +1 rolls up from below (moving down the ruler), -1 rolls down from above. */\n sign: number\n isReducedMotion: boolean\n}\n\nconst rollVariants = {\n enter: ({ sign, isReducedMotion }: RollContext) =>\n isReducedMotion ? { opacity: 0 } : { opacity: 0, y: sign * ROLL_PX, filter: 'blur(3px)' },\n center: ({ isReducedMotion }: RollContext) =>\n isReducedMotion ? { opacity: 1 } : { opacity: 1, y: 0, filter: 'blur(0px)' },\n exit: ({ sign, isReducedMotion }: RollContext) =>\n isReducedMotion ? { opacity: 0 } : { opacity: 0, y: -sign * ROLL_PX, filter: 'blur(3px)' },\n}\n\ntype Props = {\n heading: RulerHeading | undefined\n /** px from the ruler's first tick to the label's top edge. */\n offsetY: number\n left: number\n isVisible: boolean\n /** Glide to a new heading only while already showing; a label coming back from hidden appears in place. */\n shouldGlide: boolean\n direction: LabelDirection\n entrance: LabelEntrance\n isReducedMotion: boolean\n}\n\n/**\n * The hover label, as plain text (a chip would snap size whenever the text changed). Like a row of tooltips:\n * the first arrival is slow and soft, moving to another heading glides on a spring and rolls in from the\n * direction of travel, and coming back while warm skips the slow arrival. The arrival timings live in\n * style.css. Under reduced motion it only fades.\n */\nexport function Label({ heading, offsetY, left, isVisible, shouldGlide, direction, entrance, isReducedMotion }: Props) {\n const y = useSpring(offsetY, POSITION_SPRING)\n\n // Before paint, so a label coming back from hidden never shows a frame at its old place.\n useIsomorphicLayoutEffect(() => {\n if (shouldGlide && !isReducedMotion) y.set(offsetY)\n else y.jump(offsetY)\n }, [offsetY, shouldGlide, isReducedMotion, y])\n\n const roll: RollContext = { sign: direction === 'down' ? 1 : -1, isReducedMotion }\n\n return (\n <motion.div\n data-testid=\"morse-label\"\n data-visible={isVisible}\n data-glide={shouldGlide}\n data-direction={direction}\n data-entrance={entrance}\n aria-hidden=\"true\"\n className=\"morse-label\"\n style={{ left, y }}\n >\n <div className=\"morse-label-body\">\n {/* popLayout takes the leaving text out of flow, so old and new overlap instead of stacking. */}\n <AnimatePresence mode=\"popLayout\" initial={false} custom={roll}>\n {heading && (\n <motion.span\n key={heading.id}\n className=\"morse-label-text\"\n custom={roll}\n variants={rollVariants}\n initial=\"enter\"\n animate=\"center\"\n exit=\"exit\"\n transition={SWAP}\n >\n {heading.text}\n {heading.subtitle && <span className=\"morse-label-subtitle\">{heading.subtitle}</span>}\n </motion.span>\n )}\n </AnimatePresence>\n </div>\n </motion.div>\n )\n}\n","import { useRef } from 'react'\nimport { motion, useMotionValueEvent, useSpring, type MotionValue } from 'motion/react'\nimport {\n BASE_SCALE,\n clamp,\n lerp,\n LONG_TICK_WIDTH,\n POINTER_AWAY,\n proximityScale,\n SHORT_TICK_WIDTH,\n TICK_HEIGHT,\n tickCenter,\n} from './math'\n\n/** Soft enough that neighbours trail the pointer a little, so the swell reads as a wave, not a step. */\nconst TICK_SPRING = { stiffness: 420, damping: 38 }\n/** Scroll speed (px/s of marker travel) at which ticks next to the marker swell fully. */\nconst FULL_SWELL_VELOCITY = 300\n\n/** Plain ticks are a quiet rail; headings ahead are half ink; headings already read are full ink. */\ntype Tone = 'plain' | 'ahead' | 'passed'\n\ntype Props = {\n index: number\n isHeading: boolean\n isPassed: boolean\n lineY: MotionValue<number>\n pointerY: MotionValue<number>\n isReducedMotion: boolean\n}\n\nfunction toneOf(isHeading: boolean, isPassed: boolean): Tone {\n if (!isHeading) return 'plain'\n return isPassed ? 'passed' : 'ahead'\n}\n\n/**\n * A rounded tick that stretches near the pointer. While the pointer is off the ruler and the page scrolls\n * fast, it stretches as the marker passes too. A heading tick inks in once its section is reached. Under\n * reduced motion it stays still.\n */\nexport function Tick({ index, isHeading, isPassed, lineY, pointerY, isReducedMotion }: Props) {\n const ref = useRef<HTMLDivElement | null>(null)\n const scaleX = useSpring(BASE_SCALE, TICK_SPRING)\n\n useMotionValueEvent(pointerY, 'change', (clientY) => {\n if (isReducedMotion) return\n const box = ref.current?.getBoundingClientRect()\n if (!box) return\n scaleX.set(proximityScale(clientY - (box.top + box.height / 2)))\n })\n useMotionValueEvent(lineY, 'change', (offset) => {\n // The pointer wins: the marker eases for a moment after every scroll, and its swell would flatten the\n // ticks the reader is reaching for.\n if (isReducedMotion || pointerY.get() !== POINTER_AWAY) return\n const target = proximityScale(offset - tickCenter(index))\n const swell = clamp(Math.abs(lineY.getVelocity()) / FULL_SWELL_VELOCITY, 0, 1)\n scaleX.set(lerp(BASE_SCALE, target, swell))\n })\n\n return (\n <motion.div\n ref={ref}\n data-testid=\"morse-tick\"\n data-kind={isHeading ? 'heading' : 'plain'}\n data-passed={isHeading ? isPassed : undefined}\n data-tone={toneOf(isHeading, isPassed)}\n className=\"morse-tick\"\n style={{\n width: isHeading ? LONG_TICK_WIDTH : SHORT_TICK_WIDTH,\n height: TICK_HEIGHT,\n scaleX,\n transformOrigin: '0 50%',\n }}\n />\n )\n}\n","import { useEffect, useState } from 'react'\nimport {\n ACTIVATION_OFFSET,\n placeHeadingTicks,\n progressAt,\n scrollRange,\n type ScrollRange,\n type VerticalBounds,\n} from './math'\n\n/** A heading as the ruler sees it: the link target, the label text, and the element to measure and jump to. */\nexport interface RulerHeading {\n id: string\n text: string\n /** Optional second line in the label, from `data-toc-subtitle`. */\n subtitle?: string\n element: HTMLElement\n}\n\n/** Measured again when the page changes size. Keeps its identity when nothing moved. */\nexport interface RulerLayout {\n headings: RulerHeading[]\n /** The tick each heading sits on, in the same order. */\n headingTicks: number[]\n range: ScrollRange\n}\n\n/** Before the first measure, and on the server. The range isn't empty, so progress never divides by zero. */\nconst EMPTY_LAYOUT: RulerLayout = { headings: [], headingTicks: [], range: { start: 0, end: 1 } }\n\nfunction slugify(text: string): string {\n return text\n .trim()\n .toLowerCase()\n .replace(/\\s+/g, '-')\n .replace(/[^\\p{L}\\p{N}_-]/gu, '')\n}\n\n/**\n * The id a heading links to. Markdown renderers often leave headings without one, so one is made from the\n * text and kept unique on the page.\n */\nfunction ensureId(element: HTMLElement, index: number): string {\n if (element.id) return element.id\n const base = slugify(element.textContent ?? '') || `section-${index}`\n const isTaken = (id: string) => document.getElementById(id) !== null\n const free = (suffix: number): string => (isTaken(`${base}-${suffix}`) ? free(suffix + 1) : `${base}-${suffix}`)\n const id = isTaken(base) ? free(1) : base\n element.id = id\n return id\n}\n\nfunction scanHeadings(selector: string, root: ParentNode): RulerHeading[] {\n return Array.from(root.querySelectorAll<HTMLElement>(selector))\n .filter((element) => !element.hasAttribute('data-toc-ignore'))\n // GFM footnotes add a hidden \"Footnotes\" h2.\n .filter((element) => !element.closest('[data-footnotes]'))\n .map((element, index) => ({\n id: ensureId(element, index),\n text: element.getAttribute('data-toc-title') || element.textContent?.trim() || 'Section',\n subtitle: element.getAttribute('data-toc-subtitle') || undefined,\n element,\n }))\n}\n\nfunction findRoot(rootSelector: string | undefined): HTMLElement | null {\n return rootSelector ? document.querySelector<HTMLElement>(rootSelector) : null\n}\n\n/** Document px bounds of the root, or of the whole page when there is no root. */\nfunction rootBounds(root: HTMLElement | null): VerticalBounds {\n if (!root) return { top: 0, bottom: document.documentElement.scrollHeight }\n const box = root.getBoundingClientRect()\n return { top: box.top + window.scrollY, bottom: box.bottom + window.scrollY }\n}\n\nfunction measure(headings: RulerHeading[], root: HTMLElement | null): RulerLayout {\n const range = scrollRange(rootBounds(root), window.innerHeight)\n // A heading's tick is where the marker will be when that heading reaches the activation line.\n const progresses = headings.map((heading) =>\n progressAt(heading.element.getBoundingClientRect().top + window.scrollY - ACTIVATION_OFFSET, range),\n )\n const headingTicks = placeHeadingTicks(progresses)\n return { headings: headings.slice(0, headingTicks.length), headingTicks, range }\n}\n\nconst isSameNumbers = (a: readonly number[], b: readonly number[]) =>\n a.length === b.length && a.every((value, index) => value === b[index])\n\n/** Same headings, labels and ticks over the same range: nothing for the ruler to redraw. */\nfunction isSameLayout(previous: RulerLayout, next: RulerLayout): boolean {\n return (\n previous.range.start === next.range.start &&\n previous.range.end === next.range.end &&\n isSameNumbers(previous.headingTicks, next.headingTicks) &&\n previous.headings.length === next.headings.length &&\n previous.headings.every((heading, index) => {\n const other = next.headings[index]\n return (\n heading.element === other?.element &&\n heading.id === other.id &&\n heading.text === other.text &&\n heading.subtitle === other.subtitle\n )\n })\n )\n}\n\n/**\n * Finds the headings inside the root and lays them out on the ruler. Lays them out again when the page\n * changes size: images, embeds and fonts load after the first paint and push headings down, and content that\n * streams in brings its headings with it. An unchanged layout keeps its identity, so the scroll hook doesn't\n * re-subscribe while something on the page animates its height.\n */\nexport function useArticleHeadings(selector: string, rootSelector: string | undefined): RulerLayout {\n const [layout, setLayout] = useState<RulerLayout>(EMPTY_LAYOUT)\n\n useEffect(() => {\n let isCancelled = false\n let frame: number | null = null\n\n const update = () => {\n frame = null\n if (isCancelled) return\n const root = findRoot(rootSelector)\n const next = measure(scanHeadings(selector, root ?? document), root)\n setLayout((previous) => (isSameLayout(previous, next) ? previous : next))\n }\n const schedule = () => {\n if (frame === null) frame = window.requestAnimationFrame(update)\n }\n\n update()\n window.addEventListener('resize', schedule)\n const observer = typeof ResizeObserver === 'undefined' ? null : new ResizeObserver(schedule)\n observer?.observe(document.body)\n // A missed re-layout is harmless; the next resize catches up.\n document.fonts?.ready.then(schedule).catch(() => undefined)\n\n return () => {\n isCancelled = true\n window.removeEventListener('resize', schedule)\n observer?.disconnect()\n if (frame !== null) window.cancelAnimationFrame(frame)\n }\n }, [selector, rootSelector])\n\n return layout\n}\n","import { useEffect, useRef, useState } from 'react'\nimport { useAnimationFrame, useSpring, type MotionValue } from 'motion/react'\nimport { activeHeadingIndex, lerp, markerTravel, progressAt } from './math'\nimport type { RulerLayout } from './use-headings'\n\n/** Stiff, so the marker keeps up with a fast scroll. */\nconst LINE_SPRING = { stiffness: 650, damping: 40 }\n/** Each frame closes half the gap to the target, so a jumpy wheel still reads as one glide. */\nconst LINE_SMOOTHING = 0.5\n/** Below this the marker counts as arrived, and the frame loop stops writing to it. */\nconst LINE_SETTLE_PX = 0.01\n\ninterface RulerScroll {\n /** The marker's offset down the ruler, in px. */\n lineY: MotionValue<number>\n /** Index of the heading being read, -1 with none. */\n activeIndex: number\n}\n\n/**\n * Follows the scroll. The marker closes half the gap each frame on a spring, so it glides; under reduced\n * motion it jumps. Also tracks the heading being read, for aria-current and the inked ticks.\n */\nexport function useRulerScroll({ headings, range }: RulerLayout, isReducedMotion: boolean): RulerScroll {\n const lineY = useSpring(0, LINE_SPRING)\n const target = useRef(0)\n const [activeIndex, setActiveIndex] = useState(-1)\n\n useEffect(() => {\n let frame: number | null = null\n\n const update = () => {\n frame = null\n target.current = markerTravel(progressAt(window.scrollY, range))\n if (isReducedMotion) lineY.jump(target.current)\n setActiveIndex(activeHeadingIndex(headings.map((heading) => heading.element.getBoundingClientRect().top)))\n }\n const schedule = () => {\n if (frame === null) frame = window.requestAnimationFrame(update)\n }\n\n update()\n window.addEventListener('scroll', schedule, { passive: true })\n return () => {\n window.removeEventListener('scroll', schedule)\n if (frame !== null) window.cancelAnimationFrame(frame)\n }\n }, [headings, range, isReducedMotion, lineY])\n\n useAnimationFrame(() => {\n if (isReducedMotion) return\n const current = lineY.get()\n const next = ler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W,MAAM;AAAA,YACjB,aAAa,MAAM;AAAA,YACnB,WAAW,MAAM;AAAA,YACjB,UAAU,MAAM;AAAA,YAChB;AAAA;AAAA,QACF;AAAA,SACF;AAAA;AAAA,EACF;AAEJ;","names":["import_react","import_react","import_react","import_jsx_runtime","import_react","id","import_react","import_jsx_runtime"]}
|
package/dist/index.d.cts
ADDED
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
import { ReactElement } from 'react';
|
|
2
|
+
|
|
3
|
+
type MorseProps = {
|
|
4
|
+
/**
|
|
5
|
+
* Which elements inside the root count as headings. Add `data-toc-ignore` to skip one, `data-toc-title` to
|
|
6
|
+
* shorten its label, `data-toc-subtitle` for a second line. Headings without an id get one made from their
|
|
7
|
+
* text. Headings inside a GFM footnotes section are skipped.
|
|
8
|
+
* @default 'h2, h3, [data-toc]'
|
|
9
|
+
*/
|
|
10
|
+
selector?: string;
|
|
11
|
+
/**
|
|
12
|
+
* The element whose headings the ruler maps and whose length it measures. If nothing matches, the whole
|
|
13
|
+
* page is used.
|
|
14
|
+
* @default 'article'
|
|
15
|
+
*/
|
|
16
|
+
rootSelector?: string;
|
|
17
|
+
/**
|
|
18
|
+
* px left above a heading after a jump. Raise it for a taller sticky header, but keep it under 120 or the
|
|
19
|
+
* heading you land on won't be marked current.
|
|
20
|
+
* @default 80
|
|
21
|
+
*/
|
|
22
|
+
jumpOffset?: number;
|
|
23
|
+
/** Added to the nav's own `morse` class. Colour, stacking and label width come from `--morse-*` variables. */
|
|
24
|
+
className?: string;
|
|
25
|
+
};
|
|
26
|
+
/**
|
|
27
|
+
* The article's contents as a ruler at the left edge: one rounded long tick per heading, placed where the
|
|
28
|
+
* heading sits in the article, quiet short ticks between, and a small dot that rides down as you read.
|
|
29
|
+
* Headings already read are full ink; the ones ahead are half ink. Hovering shows the full text of the
|
|
30
|
+
* heading nearest the pointer (one at a time, so long headings wrap instead of being cut); clicking jumps to
|
|
31
|
+
* it. Tabbing walks the headings and shows the same label.
|
|
32
|
+
*
|
|
33
|
+
* Shows up to 28 headings. Needs `style.css`, and stays hidden below 1280px and in print. With no headings,
|
|
34
|
+
* it stays out of the landmarks list.
|
|
35
|
+
*/
|
|
36
|
+
declare function Morse({ selector, rootSelector, jumpOffset, className, }: MorseProps): ReactElement;
|
|
37
|
+
|
|
38
|
+
export { Morse, type MorseProps };
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
import { ReactElement } from 'react';
|
|
2
|
+
|
|
3
|
+
type MorseProps = {
|
|
4
|
+
/**
|
|
5
|
+
* Which elements inside the root count as headings. Add `data-toc-ignore` to skip one, `data-toc-title` to
|
|
6
|
+
* shorten its label, `data-toc-subtitle` for a second line. Headings without an id get one made from their
|
|
7
|
+
* text. Headings inside a GFM footnotes section are skipped.
|
|
8
|
+
* @default 'h2, h3, [data-toc]'
|
|
9
|
+
*/
|
|
10
|
+
selector?: string;
|
|
11
|
+
/**
|
|
12
|
+
* The element whose headings the ruler maps and whose length it measures. If nothing matches, the whole
|
|
13
|
+
* page is used.
|
|
14
|
+
* @default 'article'
|
|
15
|
+
*/
|
|
16
|
+
rootSelector?: string;
|
|
17
|
+
/**
|
|
18
|
+
* px left above a heading after a jump. Raise it for a taller sticky header, but keep it under 120 or the
|
|
19
|
+
* heading you land on won't be marked current.
|
|
20
|
+
* @default 80
|
|
21
|
+
*/
|
|
22
|
+
jumpOffset?: number;
|
|
23
|
+
/** Added to the nav's own `morse` class. Colour, stacking and label width come from `--morse-*` variables. */
|
|
24
|
+
className?: string;
|
|
25
|
+
};
|
|
26
|
+
/**
|
|
27
|
+
* The article's contents as a ruler at the left edge: one rounded long tick per heading, placed where the
|
|
28
|
+
* heading sits in the article, quiet short ticks between, and a small dot that rides down as you read.
|
|
29
|
+
* Headings already read are full ink; the ones ahead are half ink. Hovering shows the full text of the
|
|
30
|
+
* heading nearest the pointer (one at a time, so long headings wrap instead of being cut); clicking jumps to
|
|
31
|
+
* it. Tabbing walks the headings and shows the same label.
|
|
32
|
+
*
|
|
33
|
+
* Shows up to 28 headings. Needs `style.css`, and stays hidden below 1280px and in print. With no headings,
|
|
34
|
+
* it stays out of the landmarks list.
|
|
35
|
+
*/
|
|
36
|
+
declare function Morse({ selector, rootSelector, jumpOffset, className, }: MorseProps): ReactElement;
|
|
37
|
+
|
|
38
|
+
export { Morse, type MorseProps };
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,437 @@
|
|
|
1
|
+
'use client'
|
|
2
|
+
|
|
3
|
+
// src/morse.tsx
|
|
4
|
+
import { useRef as useRef3, useState as useState3 } from "react";
|
|
5
|
+
import { motion as motion3, useMotionValue, useReducedMotion, useTransform } from "motion/react";
|
|
6
|
+
|
|
7
|
+
// src/math.ts
|
|
8
|
+
var TICK_COUNT = 28;
|
|
9
|
+
var TICK_HEIGHT = 2;
|
|
10
|
+
var TICK_GAP = 9;
|
|
11
|
+
var TICK_PITCH = TICK_GAP + TICK_HEIGHT;
|
|
12
|
+
var LINE_TRAVEL = (TICK_COUNT - 1) * TICK_PITCH;
|
|
13
|
+
var LONG_TICK_WIDTH = 36;
|
|
14
|
+
var SHORT_TICK_WIDTH = 20;
|
|
15
|
+
var MAX_TICK_SCALE = 2.2;
|
|
16
|
+
var ACTIVATION_OFFSET = 120;
|
|
17
|
+
var POINTER_AWAY = Number.NEGATIVE_INFINITY;
|
|
18
|
+
var BASE_SCALE = 1;
|
|
19
|
+
var PROXIMITY_RADIUS = 64;
|
|
20
|
+
var PROXIMITY_INTENSITY = MAX_TICK_SCALE - BASE_SCALE;
|
|
21
|
+
var LAST_TICK = TICK_COUNT - 1;
|
|
22
|
+
var lerp = (from, to, amount) => from + (to - from) * amount;
|
|
23
|
+
var clamp = (value, min, max) => Math.min(max, Math.max(min, value));
|
|
24
|
+
var tickCenter = (tick) => tick * TICK_PITCH + TICK_HEIGHT / 2;
|
|
25
|
+
function proximityScale(distance) {
|
|
26
|
+
if (Math.abs(distance) >= PROXIMITY_RADIUS) return BASE_SCALE;
|
|
27
|
+
const closeness = 0.5 * (1 + Math.cos(Math.PI * Math.abs(distance) / PROXIMITY_RADIUS));
|
|
28
|
+
return BASE_SCALE + closeness * PROXIMITY_INTENSITY;
|
|
29
|
+
}
|
|
30
|
+
function scrollRange(article, viewportHeight) {
|
|
31
|
+
const start = article.top - ACTIVATION_OFFSET;
|
|
32
|
+
const end = Math.max(start + 1, article.bottom - viewportHeight);
|
|
33
|
+
return { start, end };
|
|
34
|
+
}
|
|
35
|
+
function progressAt(scrollY, range) {
|
|
36
|
+
return clamp((scrollY - range.start) / (range.end - range.start), 0, 1);
|
|
37
|
+
}
|
|
38
|
+
function markerTravel(progress) {
|
|
39
|
+
return clamp(progress, 0, 1) * LINE_TRAVEL;
|
|
40
|
+
}
|
|
41
|
+
function placeHeadingTicks(progresses) {
|
|
42
|
+
const kept = progresses.slice(0, TICK_COUNT);
|
|
43
|
+
const nearest = kept.map((progress) => Math.round(clamp(progress, 0, 1) * LAST_TICK));
|
|
44
|
+
const forward = nearest.reduce((placed, tick) => {
|
|
45
|
+
const previous = placed.at(-1) ?? -1;
|
|
46
|
+
return [...placed, Math.max(tick, previous + 1)];
|
|
47
|
+
}, []);
|
|
48
|
+
return forward.map((tick, index) => Math.min(tick, LAST_TICK - (forward.length - 1 - index)));
|
|
49
|
+
}
|
|
50
|
+
function nearestHeadingIndex(offsetY, headingTicks) {
|
|
51
|
+
return headingTicks.reduce(
|
|
52
|
+
(best, tick, index) => {
|
|
53
|
+
const distance = Math.abs(tick * TICK_PITCH - offsetY);
|
|
54
|
+
return best.index === -1 || distance < best.distance ? { index, distance } : best;
|
|
55
|
+
},
|
|
56
|
+
{ index: -1, distance: Number.POSITIVE_INFINITY }
|
|
57
|
+
).index;
|
|
58
|
+
}
|
|
59
|
+
function activeHeadingIndex(headingTops) {
|
|
60
|
+
return headingTops.reduce((last, top, index) => top <= ACTIVATION_OFFSET ? index : last, -1);
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
// src/label.tsx
|
|
64
|
+
import { useEffect, useLayoutEffect } from "react";
|
|
65
|
+
import { AnimatePresence, motion, useSpring } from "motion/react";
|
|
66
|
+
import { jsx, jsxs } from "react/jsx-runtime";
|
|
67
|
+
var EASE_OUT = [0.23, 1, 0.32, 1];
|
|
68
|
+
var POSITION_SPRING = { stiffness: 380, damping: 40, mass: 0.9 };
|
|
69
|
+
var ROLL_PX = 6;
|
|
70
|
+
var SWAP = { duration: 0.24, ease: EASE_OUT };
|
|
71
|
+
var useIsomorphicLayoutEffect = typeof window === "undefined" ? useEffect : useLayoutEffect;
|
|
72
|
+
var rollVariants = {
|
|
73
|
+
enter: ({ sign, isReducedMotion }) => isReducedMotion ? { opacity: 0 } : { opacity: 0, y: sign * ROLL_PX, filter: "blur(3px)" },
|
|
74
|
+
center: ({ isReducedMotion }) => isReducedMotion ? { opacity: 1 } : { opacity: 1, y: 0, filter: "blur(0px)" },
|
|
75
|
+
exit: ({ sign, isReducedMotion }) => isReducedMotion ? { opacity: 0 } : { opacity: 0, y: -sign * ROLL_PX, filter: "blur(3px)" }
|
|
76
|
+
};
|
|
77
|
+
function Label({ heading, offsetY, left, isVisible, shouldGlide, direction, entrance, isReducedMotion }) {
|
|
78
|
+
const y = useSpring(offsetY, POSITION_SPRING);
|
|
79
|
+
useIsomorphicLayoutEffect(() => {
|
|
80
|
+
if (shouldGlide && !isReducedMotion) y.set(offsetY);
|
|
81
|
+
else y.jump(offsetY);
|
|
82
|
+
}, [offsetY, shouldGlide, isReducedMotion, y]);
|
|
83
|
+
const roll = { sign: direction === "down" ? 1 : -1, isReducedMotion };
|
|
84
|
+
return /* @__PURE__ */ jsx(
|
|
85
|
+
motion.div,
|
|
86
|
+
{
|
|
87
|
+
"data-testid": "morse-label",
|
|
88
|
+
"data-visible": isVisible,
|
|
89
|
+
"data-glide": shouldGlide,
|
|
90
|
+
"data-direction": direction,
|
|
91
|
+
"data-entrance": entrance,
|
|
92
|
+
"aria-hidden": "true",
|
|
93
|
+
className: "morse-label",
|
|
94
|
+
style: { left, y },
|
|
95
|
+
children: /* @__PURE__ */ jsx("div", { className: "morse-label-body", children: /* @__PURE__ */ jsx(AnimatePresence, { mode: "popLayout", initial: false, custom: roll, children: heading && /* @__PURE__ */ jsxs(
|
|
96
|
+
motion.span,
|
|
97
|
+
{
|
|
98
|
+
className: "morse-label-text",
|
|
99
|
+
custom: roll,
|
|
100
|
+
variants: rollVariants,
|
|
101
|
+
initial: "enter",
|
|
102
|
+
animate: "center",
|
|
103
|
+
exit: "exit",
|
|
104
|
+
transition: SWAP,
|
|
105
|
+
children: [
|
|
106
|
+
heading.text,
|
|
107
|
+
heading.subtitle && /* @__PURE__ */ jsx("span", { className: "morse-label-subtitle", children: heading.subtitle })
|
|
108
|
+
]
|
|
109
|
+
},
|
|
110
|
+
heading.id
|
|
111
|
+
) }) })
|
|
112
|
+
}
|
|
113
|
+
);
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
// src/tick.tsx
|
|
117
|
+
import { useRef } from "react";
|
|
118
|
+
import { motion as motion2, useMotionValueEvent, useSpring as useSpring2 } from "motion/react";
|
|
119
|
+
import { jsx as jsx2 } from "react/jsx-runtime";
|
|
120
|
+
var TICK_SPRING = { stiffness: 420, damping: 38 };
|
|
121
|
+
var FULL_SWELL_VELOCITY = 300;
|
|
122
|
+
function toneOf(isHeading, isPassed) {
|
|
123
|
+
if (!isHeading) return "plain";
|
|
124
|
+
return isPassed ? "passed" : "ahead";
|
|
125
|
+
}
|
|
126
|
+
function Tick({ index, isHeading, isPassed, lineY, pointerY, isReducedMotion }) {
|
|
127
|
+
const ref = useRef(null);
|
|
128
|
+
const scaleX = useSpring2(BASE_SCALE, TICK_SPRING);
|
|
129
|
+
useMotionValueEvent(pointerY, "change", (clientY) => {
|
|
130
|
+
if (isReducedMotion) return;
|
|
131
|
+
const box = ref.current?.getBoundingClientRect();
|
|
132
|
+
if (!box) return;
|
|
133
|
+
scaleX.set(proximityScale(clientY - (box.top + box.height / 2)));
|
|
134
|
+
});
|
|
135
|
+
useMotionValueEvent(lineY, "change", (offset) => {
|
|
136
|
+
if (isReducedMotion || pointerY.get() !== POINTER_AWAY) return;
|
|
137
|
+
const target = proximityScale(offset - tickCenter(index));
|
|
138
|
+
const swell = clamp(Math.abs(lineY.getVelocity()) / FULL_SWELL_VELOCITY, 0, 1);
|
|
139
|
+
scaleX.set(lerp(BASE_SCALE, target, swell));
|
|
140
|
+
});
|
|
141
|
+
return /* @__PURE__ */ jsx2(
|
|
142
|
+
motion2.div,
|
|
143
|
+
{
|
|
144
|
+
ref,
|
|
145
|
+
"data-testid": "morse-tick",
|
|
146
|
+
"data-kind": isHeading ? "heading" : "plain",
|
|
147
|
+
"data-passed": isHeading ? isPassed : void 0,
|
|
148
|
+
"data-tone": toneOf(isHeading, isPassed),
|
|
149
|
+
className: "morse-tick",
|
|
150
|
+
style: {
|
|
151
|
+
width: isHeading ? LONG_TICK_WIDTH : SHORT_TICK_WIDTH,
|
|
152
|
+
height: TICK_HEIGHT,
|
|
153
|
+
scaleX,
|
|
154
|
+
transformOrigin: "0 50%"
|
|
155
|
+
}
|
|
156
|
+
}
|
|
157
|
+
);
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
// src/use-headings.ts
|
|
161
|
+
import { useEffect as useEffect2, useState } from "react";
|
|
162
|
+
var EMPTY_LAYOUT = { headings: [], headingTicks: [], range: { start: 0, end: 1 } };
|
|
163
|
+
function slugify(text) {
|
|
164
|
+
return text.trim().toLowerCase().replace(/\s+/g, "-").replace(/[^\p{L}\p{N}_-]/gu, "");
|
|
165
|
+
}
|
|
166
|
+
function ensureId(element, index) {
|
|
167
|
+
if (element.id) return element.id;
|
|
168
|
+
const base = slugify(element.textContent ?? "") || `section-${index}`;
|
|
169
|
+
const isTaken = (id2) => document.getElementById(id2) !== null;
|
|
170
|
+
const free = (suffix) => isTaken(`${base}-${suffix}`) ? free(suffix + 1) : `${base}-${suffix}`;
|
|
171
|
+
const id = isTaken(base) ? free(1) : base;
|
|
172
|
+
element.id = id;
|
|
173
|
+
return id;
|
|
174
|
+
}
|
|
175
|
+
function scanHeadings(selector, root) {
|
|
176
|
+
return Array.from(root.querySelectorAll(selector)).filter((element) => !element.hasAttribute("data-toc-ignore")).filter((element) => !element.closest("[data-footnotes]")).map((element, index) => ({
|
|
177
|
+
id: ensureId(element, index),
|
|
178
|
+
text: element.getAttribute("data-toc-title") || element.textContent?.trim() || "Section",
|
|
179
|
+
subtitle: element.getAttribute("data-toc-subtitle") || void 0,
|
|
180
|
+
element
|
|
181
|
+
}));
|
|
182
|
+
}
|
|
183
|
+
function findRoot(rootSelector) {
|
|
184
|
+
return rootSelector ? document.querySelector(rootSelector) : null;
|
|
185
|
+
}
|
|
186
|
+
function rootBounds(root) {
|
|
187
|
+
if (!root) return { top: 0, bottom: document.documentElement.scrollHeight };
|
|
188
|
+
const box = root.getBoundingClientRect();
|
|
189
|
+
return { top: box.top + window.scrollY, bottom: box.bottom + window.scrollY };
|
|
190
|
+
}
|
|
191
|
+
function measure(headings, root) {
|
|
192
|
+
const range = scrollRange(rootBounds(root), window.innerHeight);
|
|
193
|
+
const progresses = headings.map(
|
|
194
|
+
(heading) => progressAt(heading.element.getBoundingClientRect().top + window.scrollY - ACTIVATION_OFFSET, range)
|
|
195
|
+
);
|
|
196
|
+
const headingTicks = placeHeadingTicks(progresses);
|
|
197
|
+
return { headings: headings.slice(0, headingTicks.length), headingTicks, range };
|
|
198
|
+
}
|
|
199
|
+
var isSameNumbers = (a, b) => a.length === b.length && a.every((value, index) => value === b[index]);
|
|
200
|
+
function isSameLayout(previous, next) {
|
|
201
|
+
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) => {
|
|
202
|
+
const other = next.headings[index];
|
|
203
|
+
return heading.element === other?.element && heading.id === other.id && heading.text === other.text && heading.subtitle === other.subtitle;
|
|
204
|
+
});
|
|
205
|
+
}
|
|
206
|
+
function useArticleHeadings(selector, rootSelector) {
|
|
207
|
+
const [layout, setLayout] = useState(EMPTY_LAYOUT);
|
|
208
|
+
useEffect2(() => {
|
|
209
|
+
let isCancelled = false;
|
|
210
|
+
let frame = null;
|
|
211
|
+
const update = () => {
|
|
212
|
+
frame = null;
|
|
213
|
+
if (isCancelled) return;
|
|
214
|
+
const root = findRoot(rootSelector);
|
|
215
|
+
const next = measure(scanHeadings(selector, root ?? document), root);
|
|
216
|
+
setLayout((previous) => isSameLayout(previous, next) ? previous : next);
|
|
217
|
+
};
|
|
218
|
+
const schedule = () => {
|
|
219
|
+
if (frame === null) frame = window.requestAnimationFrame(update);
|
|
220
|
+
};
|
|
221
|
+
update();
|
|
222
|
+
window.addEventListener("resize", schedule);
|
|
223
|
+
const observer = typeof ResizeObserver === "undefined" ? null : new ResizeObserver(schedule);
|
|
224
|
+
observer?.observe(document.body);
|
|
225
|
+
document.fonts?.ready.then(schedule).catch(() => void 0);
|
|
226
|
+
return () => {
|
|
227
|
+
isCancelled = true;
|
|
228
|
+
window.removeEventListener("resize", schedule);
|
|
229
|
+
observer?.disconnect();
|
|
230
|
+
if (frame !== null) window.cancelAnimationFrame(frame);
|
|
231
|
+
};
|
|
232
|
+
}, [selector, rootSelector]);
|
|
233
|
+
return layout;
|
|
234
|
+
}
|
|
235
|
+
|
|
236
|
+
// src/use-scroll.ts
|
|
237
|
+
import { useEffect as useEffect3, useRef as useRef2, useState as useState2 } from "react";
|
|
238
|
+
import { useAnimationFrame, useSpring as useSpring3 } from "motion/react";
|
|
239
|
+
var LINE_SPRING = { stiffness: 650, damping: 40 };
|
|
240
|
+
var LINE_SMOOTHING = 0.5;
|
|
241
|
+
var LINE_SETTLE_PX = 0.01;
|
|
242
|
+
function useRulerScroll({ headings, range }, isReducedMotion) {
|
|
243
|
+
const lineY = useSpring3(0, LINE_SPRING);
|
|
244
|
+
const target = useRef2(0);
|
|
245
|
+
const [activeIndex, setActiveIndex] = useState2(-1);
|
|
246
|
+
useEffect3(() => {
|
|
247
|
+
let frame = null;
|
|
248
|
+
const update = () => {
|
|
249
|
+
frame = null;
|
|
250
|
+
target.current = markerTravel(progressAt(window.scrollY, range));
|
|
251
|
+
if (isReducedMotion) lineY.jump(target.current);
|
|
252
|
+
setActiveIndex(activeHeadingIndex(headings.map((heading) => heading.element.getBoundingClientRect().top)));
|
|
253
|
+
};
|
|
254
|
+
const schedule = () => {
|
|
255
|
+
if (frame === null) frame = window.requestAnimationFrame(update);
|
|
256
|
+
};
|
|
257
|
+
update();
|
|
258
|
+
window.addEventListener("scroll", schedule, { passive: true });
|
|
259
|
+
return () => {
|
|
260
|
+
window.removeEventListener("scroll", schedule);
|
|
261
|
+
if (frame !== null) window.cancelAnimationFrame(frame);
|
|
262
|
+
};
|
|
263
|
+
}, [headings, range, isReducedMotion, lineY]);
|
|
264
|
+
useAnimationFrame(() => {
|
|
265
|
+
if (isReducedMotion) return;
|
|
266
|
+
const current = lineY.get();
|
|
267
|
+
const next = lerp(current, target.current, LINE_SMOOTHING);
|
|
268
|
+
if (Math.abs(next - current) > LINE_SETTLE_PX) lineY.set(next);
|
|
269
|
+
});
|
|
270
|
+
return { lineY, activeIndex };
|
|
271
|
+
}
|
|
272
|
+
|
|
273
|
+
// src/morse.tsx
|
|
274
|
+
import { jsx as jsx3, jsxs as jsxs2 } from "react/jsx-runtime";
|
|
275
|
+
var DEFAULT_SELECTOR = "h2, h3, [data-toc]";
|
|
276
|
+
var DEFAULT_ROOT_SELECTOR = "article";
|
|
277
|
+
var DEFAULT_JUMP_OFFSET = 80;
|
|
278
|
+
var LABEL_LEFT = Math.ceil(LONG_TICK_WIDTH * MAX_TICK_SCALE) + 16;
|
|
279
|
+
var LABEL_FIRST_LINE_CENTER = 9;
|
|
280
|
+
var NO_HEADING = -1;
|
|
281
|
+
var WARM_MS = 400;
|
|
282
|
+
var MARKER_SIZE = 6;
|
|
283
|
+
var MARKER_LEFT = -14;
|
|
284
|
+
var HIDDEN_LABEL = {
|
|
285
|
+
index: NO_HEADING,
|
|
286
|
+
isVisible: false,
|
|
287
|
+
shouldGlide: false,
|
|
288
|
+
direction: "down",
|
|
289
|
+
entrance: "slow"
|
|
290
|
+
};
|
|
291
|
+
function jumpTo(element, offset, isReducedMotion) {
|
|
292
|
+
const top = element.getBoundingClientRect().top + window.scrollY - offset;
|
|
293
|
+
window.scrollTo({ top, behavior: isReducedMotion ? "auto" : "smooth" });
|
|
294
|
+
window.history.replaceState(window.history.state, "", `#${element.id}`);
|
|
295
|
+
if (!element.hasAttribute("tabindex")) element.setAttribute("tabindex", "-1");
|
|
296
|
+
element.focus({ preventScroll: true });
|
|
297
|
+
}
|
|
298
|
+
function isPlainClick(event) {
|
|
299
|
+
return event.button === 0 && !event.metaKey && !event.ctrlKey && !event.shiftKey && !event.altKey;
|
|
300
|
+
}
|
|
301
|
+
function Morse({
|
|
302
|
+
selector = DEFAULT_SELECTOR,
|
|
303
|
+
rootSelector = DEFAULT_ROOT_SELECTOR,
|
|
304
|
+
jumpOffset = DEFAULT_JUMP_OFFSET,
|
|
305
|
+
className
|
|
306
|
+
}) {
|
|
307
|
+
const isReducedMotion = useReducedMotion() ?? false;
|
|
308
|
+
const layout = useArticleHeadings(selector, rootSelector);
|
|
309
|
+
const { lineY, activeIndex } = useRulerScroll(layout, isReducedMotion);
|
|
310
|
+
const pointerY = useMotionValue(POINTER_AWAY);
|
|
311
|
+
const markerTransform = useTransform(lineY, (offset) => `translate3d(0, ${offset}px, 0)`);
|
|
312
|
+
const ticksRef = useRef3(null);
|
|
313
|
+
const [label, setLabel] = useState3(HIDDEN_LABEL);
|
|
314
|
+
const hiddenAt = useRef3(null);
|
|
315
|
+
const { headings, headingTicks } = layout;
|
|
316
|
+
const headingIndexAtTick = new Map(headingTicks.map((tick, index) => [tick, index]));
|
|
317
|
+
const showLabel = (index, at) => {
|
|
318
|
+
if (index === NO_HEADING) return;
|
|
319
|
+
const isWarm = hiddenAt.current !== null && at - hiddenAt.current < WARM_MS;
|
|
320
|
+
setLabel((previous) => {
|
|
321
|
+
if (previous.isVisible && previous.index === index) return previous;
|
|
322
|
+
if (previous.isVisible) {
|
|
323
|
+
return {
|
|
324
|
+
index,
|
|
325
|
+
isVisible: true,
|
|
326
|
+
shouldGlide: true,
|
|
327
|
+
direction: index < previous.index ? "up" : "down",
|
|
328
|
+
entrance: previous.entrance
|
|
329
|
+
};
|
|
330
|
+
}
|
|
331
|
+
return { index, isVisible: true, shouldGlide: false, direction: "down", entrance: isWarm ? "quick" : "slow" };
|
|
332
|
+
});
|
|
333
|
+
};
|
|
334
|
+
const hideLabel = (at) => {
|
|
335
|
+
hiddenAt.current = at;
|
|
336
|
+
setLabel((previous) => ({ ...previous, isVisible: false, shouldGlide: false }));
|
|
337
|
+
};
|
|
338
|
+
const headingAtPointer = (clientY) => nearestHeadingIndex(clientY - (ticksRef.current?.getBoundingClientRect().top ?? 0), headingTicks);
|
|
339
|
+
const handleMouseMove = (event) => {
|
|
340
|
+
pointerY.set(event.clientY);
|
|
341
|
+
showLabel(headingAtPointer(event.clientY), event.timeStamp);
|
|
342
|
+
};
|
|
343
|
+
const handleMouseLeave = (event) => {
|
|
344
|
+
pointerY.set(POINTER_AWAY);
|
|
345
|
+
hideLabel(event.timeStamp);
|
|
346
|
+
};
|
|
347
|
+
const handleRulerClick = (event) => {
|
|
348
|
+
if (!isPlainClick(event)) return;
|
|
349
|
+
const heading = headings[headingAtPointer(event.clientY)];
|
|
350
|
+
if (heading) jumpTo(heading.element, jumpOffset, isReducedMotion);
|
|
351
|
+
};
|
|
352
|
+
return /* @__PURE__ */ jsx3(
|
|
353
|
+
"nav",
|
|
354
|
+
{
|
|
355
|
+
"aria-label": "Contents",
|
|
356
|
+
"aria-hidden": headings.length === 0 ? true : void 0,
|
|
357
|
+
className: className ? `morse ${className}` : "morse",
|
|
358
|
+
children: /* @__PURE__ */ jsxs2("div", { className: "morse-rail", children: [
|
|
359
|
+
/* @__PURE__ */ jsxs2(
|
|
360
|
+
"div",
|
|
361
|
+
{
|
|
362
|
+
"data-testid": "morse-ticks",
|
|
363
|
+
className: "morse-track",
|
|
364
|
+
onMouseMove: handleMouseMove,
|
|
365
|
+
onMouseLeave: handleMouseLeave,
|
|
366
|
+
onClick: handleRulerClick,
|
|
367
|
+
children: [
|
|
368
|
+
/* @__PURE__ */ jsx3("div", { ref: ticksRef, "aria-hidden": "true", className: "morse-ticks", style: { gap: TICK_GAP }, children: Array.from({ length: TICK_COUNT }, (_, tick) => {
|
|
369
|
+
const headingIndex = headingIndexAtTick.get(tick);
|
|
370
|
+
return /* @__PURE__ */ jsx3(
|
|
371
|
+
Tick,
|
|
372
|
+
{
|
|
373
|
+
index: tick,
|
|
374
|
+
isHeading: headingIndex !== void 0,
|
|
375
|
+
isPassed: headingIndex !== void 0 && headingIndex <= activeIndex,
|
|
376
|
+
lineY,
|
|
377
|
+
pointerY,
|
|
378
|
+
isReducedMotion
|
|
379
|
+
},
|
|
380
|
+
tick
|
|
381
|
+
);
|
|
382
|
+
}) }),
|
|
383
|
+
/* @__PURE__ */ jsx3("ol", { className: "morse-links", children: headings.map((heading, index) => /* @__PURE__ */ jsx3("li", { children: /* @__PURE__ */ jsx3(
|
|
384
|
+
"a",
|
|
385
|
+
{
|
|
386
|
+
href: `#${heading.id}`,
|
|
387
|
+
"aria-current": index === activeIndex ? "location" : void 0,
|
|
388
|
+
onClick: (event) => {
|
|
389
|
+
event.stopPropagation();
|
|
390
|
+
if (!isPlainClick(event)) return;
|
|
391
|
+
event.preventDefault();
|
|
392
|
+
jumpTo(heading.element, jumpOffset, isReducedMotion);
|
|
393
|
+
},
|
|
394
|
+
onFocus: (event) => showLabel(index, event.timeStamp),
|
|
395
|
+
onBlur: (event) => hideLabel(event.timeStamp),
|
|
396
|
+
className: "morse-link",
|
|
397
|
+
style: {
|
|
398
|
+
top: tickCenter(headingTicks[index] ?? 0) - TICK_PITCH / 2,
|
|
399
|
+
width: LONG_TICK_WIDTH,
|
|
400
|
+
height: TICK_PITCH
|
|
401
|
+
},
|
|
402
|
+
children: /* @__PURE__ */ jsx3("span", { className: "morse-sr-only", children: heading.text })
|
|
403
|
+
}
|
|
404
|
+
) }, heading.id)) })
|
|
405
|
+
]
|
|
406
|
+
}
|
|
407
|
+
),
|
|
408
|
+
/* @__PURE__ */ jsx3(
|
|
409
|
+
motion3.div,
|
|
410
|
+
{
|
|
411
|
+
"data-testid": "morse-marker",
|
|
412
|
+
"aria-hidden": "true",
|
|
413
|
+
className: "morse-marker",
|
|
414
|
+
style: { left: MARKER_LEFT, marginTop: TICK_HEIGHT / 2 - MARKER_SIZE / 2, transform: markerTransform }
|
|
415
|
+
}
|
|
416
|
+
),
|
|
417
|
+
/* @__PURE__ */ jsx3(
|
|
418
|
+
Label,
|
|
419
|
+
{
|
|
420
|
+
heading: headings[label.index],
|
|
421
|
+
offsetY: tickCenter(headingTicks[label.index] ?? 0) - LABEL_FIRST_LINE_CENTER,
|
|
422
|
+
left: LABEL_LEFT,
|
|
423
|
+
isVisible: label.isVisible,
|
|
424
|
+
shouldGlide: label.shouldGlide,
|
|
425
|
+
direction: label.direction,
|
|
426
|
+
entrance: label.entrance,
|
|
427
|
+
isReducedMotion
|
|
428
|
+
}
|
|
429
|
+
)
|
|
430
|
+
] })
|
|
431
|
+
}
|
|
432
|
+
);
|
|
433
|
+
}
|
|
434
|
+
export {
|
|
435
|
+
Morse
|
|
436
|
+
};
|
|
437
|
+
//# sourceMappingURL=index.js.map
|