@sinnstack/ui 0.0.0-stage → 0.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +15 -0
- package/LICENSE +373 -0
- package/README.md +186 -2
- package/docs/blocks.md +364 -0
- package/docs/data.md +128 -0
- package/docs/motion.md +166 -0
- package/docs/primitives.md +510 -0
- package/docs/seo.md +187 -0
- package/docs/tokens.md +122 -0
- package/package.json +141 -3
- package/scripts/check-contrast.mjs +180 -0
- package/src/blocks/BlockRenderer.astro +54 -0
- package/src/blocks/CTABanner.astro +121 -0
- package/src/blocks/CTAPair.astro +110 -0
- package/src/blocks/CardGrid.astro +167 -0
- package/src/blocks/ConsentEmbed.astro +125 -0
- package/src/blocks/ConsentManager.astro +147 -0
- package/src/blocks/ConsentScript.astro +47 -0
- package/src/blocks/ContactCard.astro +164 -0
- package/src/blocks/ContactForm.astro +224 -0
- package/src/blocks/ErrorPage.astro +242 -0
- package/src/blocks/FAQ.astro +135 -0
- package/src/blocks/FeatureGrid.astro +148 -0
- package/src/blocks/Hero.astro +171 -0
- package/src/blocks/HeroCarousel.astro +220 -0
- package/src/blocks/HighlightCards.astro +107 -0
- package/src/blocks/LocationHours.astro +311 -0
- package/src/blocks/LogoCloud.astro +135 -0
- package/src/blocks/MaintenancePage.astro +168 -0
- package/src/blocks/MediaText.astro +177 -0
- package/src/blocks/PageHeader.astro +126 -0
- package/src/blocks/ProseSection.astro +98 -0
- package/src/blocks/Reviews.astro +194 -0
- package/src/blocks/RichText.astro +57 -0
- package/src/blocks/StatsBand.astro +117 -0
- package/src/blocks/Steps.astro +141 -0
- package/src/blocks/Testimonials.astro +144 -0
- package/src/blocks/Topbar.astro +158 -0
- package/src/blocks/cms/card-grid.ts +80 -0
- package/src/blocks/cms/consent.ts +45 -0
- package/src/blocks/cms/contact-card.ts +88 -0
- package/src/blocks/cms/contact-form.ts +55 -0
- package/src/blocks/cms/cta-banner.ts +48 -0
- package/src/blocks/cms/cta-pair.ts +63 -0
- package/src/blocks/cms/data-base.ts +7 -0
- package/src/blocks/cms/data.ts +257 -0
- package/src/blocks/cms/faq.ts +70 -0
- package/src/blocks/cms/feature-grid.ts +80 -0
- package/src/blocks/cms/fixtures.ts +599 -0
- package/src/blocks/cms/hero-carousel.ts +80 -0
- package/src/blocks/cms/hero.ts +77 -0
- package/src/blocks/cms/highlight-cards.ts +76 -0
- package/src/blocks/cms/images.ts +38 -0
- package/src/blocks/cms/index.ts +87 -0
- package/src/blocks/cms/location-hours.ts +149 -0
- package/src/blocks/cms/logo-cloud.ts +62 -0
- package/src/blocks/cms/media-text.ts +44 -0
- package/src/blocks/cms/page-header.ts +49 -0
- package/src/blocks/cms/pages.ts +81 -0
- package/src/blocks/cms/prose-section.ts +45 -0
- package/src/blocks/cms/reviews.ts +101 -0
- package/src/blocks/cms/shared.ts +115 -0
- package/src/blocks/cms/stats-band.ts +61 -0
- package/src/blocks/cms/steps.ts +67 -0
- package/src/blocks/cms/testimonials.ts +80 -0
- package/src/blocks/cms/topbar.ts +64 -0
- package/src/blocks/cms/types.ts +63 -0
- package/src/blocks/consent.ts +14 -0
- package/src/blocks/icons.ts +47 -0
- package/src/blocks/index.ts +42 -0
- package/src/blocks/internal/Actions.astro +29 -0
- package/src/blocks/internal/BlockHeader.astro +45 -0
- package/src/blocks/internal/BlockShell.astro +58 -0
- package/src/blocks/internal/CarouselScript.astro +7 -0
- package/src/blocks/internal/ConsentEmbedScript.astro +7 -0
- package/src/blocks/internal/ConsentManagerScript.astro +7 -0
- package/src/blocks/internal/HoursScript.astro +7 -0
- package/src/blocks/internal/Placeholder.astro +13 -0
- package/src/blocks/internal/RichTextNode.astro +133 -0
- package/src/blocks/internal/StandaloneDocument.astro +53 -0
- package/src/blocks/internal/tina.ts +19 -0
- package/src/blocks/internal/util.ts +23 -0
- package/src/blocks/lib/consent.ts +96 -0
- package/src/blocks/lib/contact.ts +86 -0
- package/src/blocks/lib/error-pages.ts +119 -0
- package/src/blocks/lib/faq.ts +37 -0
- package/src/blocks/lib/hours.ts +201 -0
- package/src/blocks/lib/maintenance.ts +129 -0
- package/src/blocks/lib/reviews.ts +22 -0
- package/src/blocks/lib/rich-text.ts +143 -0
- package/src/blocks/lib/slug.ts +12 -0
- package/src/blocks/registry.ts +79 -0
- package/src/blocks/scripts/carousel.ts +218 -0
- package/src/blocks/scripts/consent-embed.ts +105 -0
- package/src/blocks/scripts/consent-manager.ts +112 -0
- package/src/blocks/scripts/consent-store.ts +86 -0
- package/src/blocks/scripts/error-page.ts +71 -0
- package/src/blocks/scripts/hours.ts +106 -0
- package/src/blocks/scripts/maintenance.ts +109 -0
- package/src/blocks/styles/blocks.css +1320 -0
- package/src/blocks/styles/consent.css +102 -0
- package/src/blocks/styles/faq.css +28 -0
- package/src/blocks/styles/location.css +92 -0
- package/src/blocks/styles/prose-section.css +13 -0
- package/src/blocks/styles/quotes.css +123 -0
- package/src/blocks/styles/rich-text.css +14 -0
- package/src/blocks/types.ts +283 -0
- package/src/data/ChartAxis.astro +19 -0
- package/src/data/ChartContainer.astro +151 -0
- package/src/data/ChartLegend.astro +25 -0
- package/src/data/ChartSeries.astro +14 -0
- package/src/data/ChartTable.astro +17 -0
- package/src/data/ChartTooltip.astro +20 -0
- package/src/data/Sparkline.astro +55 -0
- package/src/data/cms.ts +190 -0
- package/src/data/index.ts +10 -0
- package/src/data/lib/chart.ts +450 -0
- package/src/data/lib/render.ts +219 -0
- package/src/data/lib/scale.ts +107 -0
- package/src/data/lib/sparkline.ts +117 -0
- package/src/data/scripts/chart.ts +324 -0
- package/src/data/styles/chart.css +392 -0
- package/src/motion/Marquee.astro +90 -0
- package/src/motion/MotionProvider.astro +50 -0
- package/src/motion/PageTransitions.astro +61 -0
- package/src/motion/Parallax.astro +44 -0
- package/src/motion/ParallaxLayer.astro +31 -0
- package/src/motion/RevealOnScroll.astro +59 -0
- package/src/motion/SceneRegistry.astro +38 -0
- package/src/motion/ScrollScene.astro +81 -0
- package/src/motion/index.ts +12 -0
- package/src/motion/integration.ts +48 -0
- package/src/motion/runtime/page-transitions.ts +68 -0
- package/src/motion/runtime/runtime.ts +180 -0
- package/src/motion/runtime/scenes.ts +248 -0
- package/src/motion/runtime/types.ts +103 -0
- package/src/motion/styles/motion.css +332 -0
- package/src/motion/transitions.ts +74 -0
- package/src/motion/virtual.d.ts +4 -0
- package/src/primitives/Accordion.astro +129 -0
- package/src/primitives/Breadcrumbs.astro +50 -0
- package/src/primitives/BulletList.astro +69 -0
- package/src/primitives/Button.astro +73 -0
- package/src/primitives/ButtonGroup.astro +54 -0
- package/src/primitives/Callout.astro +137 -0
- package/src/primitives/Caption.astro +35 -0
- package/src/primitives/Card.astro +72 -0
- package/src/primitives/CardContent.astro +24 -0
- package/src/primitives/CardFooter.astro +36 -0
- package/src/primitives/CardHeader.astro +86 -0
- package/src/primitives/Checkbox.astro +38 -0
- package/src/primitives/ChoiceGroup.astro +23 -0
- package/src/primitives/Cluster.astro +49 -0
- package/src/primitives/Container.astro +44 -0
- package/src/primitives/DescriptionList.astro +83 -0
- package/src/primitives/Dialog.astro +38 -0
- package/src/primitives/Disclosure.astro +67 -0
- package/src/primitives/Divider.astro +93 -0
- package/src/primitives/Drawer.astro +33 -0
- package/src/primitives/Fieldset.astro +80 -0
- package/src/primitives/Flex.astro +64 -0
- package/src/primitives/FocusRing.astro +63 -0
- package/src/primitives/FocusTrap.astro +64 -0
- package/src/primitives/Footer.astro +155 -0
- package/src/primitives/Form.astro +68 -0
- package/src/primitives/FormDescription.astro +26 -0
- package/src/primitives/FormError.astro +106 -0
- package/src/primitives/FormField.astro +72 -0
- package/src/primitives/Grid.astro +64 -0
- package/src/primitives/Heading.astro +45 -0
- package/src/primitives/IconButton.astro +48 -0
- package/src/primitives/Image.astro +125 -0
- package/src/primitives/Input.astro +84 -0
- package/src/primitives/Label.astro +50 -0
- package/src/primitives/Link.astro +81 -0
- package/src/primitives/LinkButton.astro +66 -0
- package/src/primitives/List.astro +39 -0
- package/src/primitives/ListItem.astro +178 -0
- package/src/primitives/MediaObject.astro +66 -0
- package/src/primitives/MetricCard.astro +276 -0
- package/src/primitives/NavLink.astro +81 -0
- package/src/primitives/NavMenu.astro +109 -0
- package/src/primitives/Navbar.astro +197 -0
- package/src/primitives/Panel.astro +153 -0
- package/src/primitives/Picture.astro +167 -0
- package/src/primitives/Popover.astro +95 -0
- package/src/primitives/Prose.astro +45 -0
- package/src/primitives/Radio.astro +21 -0
- package/src/primitives/Rating.astro +135 -0
- package/src/primitives/ReducedMotion.astro +90 -0
- package/src/primitives/SegmentedControl.astro +132 -0
- package/src/primitives/Select.astro +107 -0
- package/src/primitives/Sheet.astro +45 -0
- package/src/primitives/SkipLink.astro +31 -0
- package/src/primitives/Slider.astro +186 -0
- package/src/primitives/Spacer.astro +35 -0
- package/src/primitives/Stack.astro +51 -0
- package/src/primitives/Surface.astro +70 -0
- package/src/primitives/Switch.astro +22 -0
- package/src/primitives/Table.astro +382 -0
- package/src/primitives/Tabs.astro +126 -0
- package/src/primitives/Text.astro +56 -0
- package/src/primitives/Textarea.astro +73 -0
- package/src/primitives/Thumbnail.astro +154 -0
- package/src/primitives/Toggle.astro +99 -0
- package/src/primitives/Tooltip.astro +50 -0
- package/src/primitives/VisuallyHidden.astro +29 -0
- package/src/primitives/index.ts +103 -0
- package/src/primitives/internal/AccordionScript.astro +7 -0
- package/src/primitives/internal/ChoiceField.astro +89 -0
- package/src/primitives/internal/FocusTrapScript.astro +8 -0
- package/src/primitives/internal/FormValidationScript.astro +10 -0
- package/src/primitives/internal/IndeterminateScript.astro +13 -0
- package/src/primitives/internal/ModalPanel.astro +114 -0
- package/src/primitives/internal/OverlayScript.astro +7 -0
- package/src/primitives/internal/ReducedMotionScript.astro +7 -0
- package/src/primitives/internal/SliderScript.astro +7 -0
- package/src/primitives/internal/SparklineScript.astro +7 -0
- package/src/primitives/internal/TableSortScript.astro +7 -0
- package/src/primitives/internal/TabsScript.astro +7 -0
- package/src/primitives/internal/TooltipScript.astro +7 -0
- package/src/primitives/lib/deprecate.ts +47 -0
- package/src/primitives/lib/focus-trap.ts +197 -0
- package/src/primitives/lib/focus.ts +60 -0
- package/src/primitives/lib/image-plan.ts +82 -0
- package/src/primitives/lib/image.ts +129 -0
- package/src/primitives/lib/motion.ts +68 -0
- package/src/primitives/lib/slider.ts +170 -0
- package/src/primitives/scripts/accordion.ts +123 -0
- package/src/primitives/scripts/form-validation.ts +225 -0
- package/src/primitives/scripts/overlay.ts +71 -0
- package/src/primitives/scripts/reduced-motion.ts +59 -0
- package/src/primitives/scripts/slider.ts +150 -0
- package/src/primitives/scripts/sparkline.ts +131 -0
- package/src/primitives/scripts/table-sort.ts +68 -0
- package/src/primitives/scripts/tabs.ts +151 -0
- package/src/primitives/scripts/tooltip.ts +28 -0
- package/src/primitives/styles/a11y.css +104 -0
- package/src/primitives/styles/accordion.css +53 -0
- package/src/primitives/styles/breadcrumbs.css +59 -0
- package/src/primitives/styles/bullet-list.css +89 -0
- package/src/primitives/styles/button.css +237 -0
- package/src/primitives/styles/choice.css +164 -0
- package/src/primitives/styles/cluster.css +24 -0
- package/src/primitives/styles/container.css +19 -0
- package/src/primitives/styles/data.css +849 -0
- package/src/primitives/styles/disclosure.css +140 -0
- package/src/primitives/styles/divider.css +50 -0
- package/src/primitives/styles/flex.css +42 -0
- package/src/primitives/styles/form.css +241 -0
- package/src/primitives/styles/grid.css +36 -0
- package/src/primitives/styles/media.css +247 -0
- package/src/primitives/styles/nav.css +792 -0
- package/src/primitives/styles/overlay.css +362 -0
- package/src/primitives/styles/prose.css +146 -0
- package/src/primitives/styles/scale.css +175 -0
- package/src/primitives/styles/segmented.css +165 -0
- package/src/primitives/styles/slider.css +170 -0
- package/src/primitives/styles/spacer.css +17 -0
- package/src/primitives/styles/stack.css +25 -0
- package/src/primitives/styles/surface.css +403 -0
- package/src/primitives/styles/tabs.css +223 -0
- package/src/primitives/styles/typography.css +144 -0
- package/src/primitives/styles/utilities.css +24 -0
- package/src/primitives/types.ts +385 -0
- package/src/primitives/utils.ts +254 -0
- package/src/seo/JSONLD.astro +35 -0
- package/src/seo/SEOHead.astro +47 -0
- package/src/seo/cms.ts +80 -0
- package/src/seo/index.ts +10 -0
- package/src/seo/integration.ts +231 -0
- package/src/seo/lib/jsonld.ts +334 -0
- package/src/seo/lib/meta.ts +205 -0
- package/src/seo/lib/redirects.ts +283 -0
- package/src/seo/lib/robots.ts +33 -0
- package/src/seo/lib/rss.ts +98 -0
- package/src/seo/lib/sitemap.ts +105 -0
- package/src/seo/lib/url.ts +68 -0
- package/src/tokens/base.css +71 -0
- package/src/tokens/tokens.css +210 -0
|
@@ -0,0 +1,107 @@
|
|
|
1
|
+
/** Scales and ticks. Pure. */
|
|
2
|
+
|
|
3
|
+
/** A "nice" step (1, 2, 2.5 or 5 × 10ⁿ) that splits `span` into about `count` parts. */
|
|
4
|
+
export function niceStep(span: number, count: number): number {
|
|
5
|
+
if (!(span > 0)) return 1;
|
|
6
|
+
const raw = span / Math.max(1, count);
|
|
7
|
+
const mag = 10 ** Math.floor(Math.log10(raw));
|
|
8
|
+
const norm = raw / mag;
|
|
9
|
+
const nice = norm <= 1 ? 1 : norm <= 2 ? 2 : norm <= 2.5 ? 2.5 : norm <= 5 ? 5 : 10;
|
|
10
|
+
return nice * mag;
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
const round = (v: number) => Math.round(v * 1e9) / 1e9;
|
|
14
|
+
|
|
15
|
+
/** Expands [min, max] to nice bounds and returns the ticks between them. */
|
|
16
|
+
export function niceDomain(min: number, max: number, count = 5): { min: number; max: number; step: number; ticks: number[] } {
|
|
17
|
+
if (!Number.isFinite(min) || !Number.isFinite(max)) return { min: 0, max: 1, step: 0.25, ticks: [0, 0.25, 0.5, 0.75, 1] };
|
|
18
|
+
if (min === max) {
|
|
19
|
+
const pad = min === 0 ? 1 : Math.abs(min) * 0.5;
|
|
20
|
+
min -= min === 0 ? 0 : pad;
|
|
21
|
+
max += pad;
|
|
22
|
+
}
|
|
23
|
+
let step = niceStep(max - min, count);
|
|
24
|
+
let lo = Math.floor(min / step) * step;
|
|
25
|
+
let hi = Math.ceil(max / step) * step;
|
|
26
|
+
// Too many ticks after rounding outward: take the next nice step.
|
|
27
|
+
if ((hi - lo) / step > count + 2) {
|
|
28
|
+
step = niceStep(max - min, Math.max(2, count - 2));
|
|
29
|
+
lo = Math.floor(min / step) * step;
|
|
30
|
+
hi = Math.ceil(max / step) * step;
|
|
31
|
+
}
|
|
32
|
+
const ticks: number[] = [];
|
|
33
|
+
for (let v = lo; v <= hi + step / 2; v += step) ticks.push(round(v));
|
|
34
|
+
return { min: round(lo), max: round(hi), step, ticks };
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
/** Position of `v` from the top of the plot, in percent (SVG y grows downward). */
|
|
38
|
+
export const yPct = (v: number, min: number, max: number) => round((1 - (v - min) / (max - min)) * 100);
|
|
39
|
+
/** Position of `v` from the left, in percent. */
|
|
40
|
+
export const xPct = (v: number, min: number, max: number) => (max === min ? 50 : round(((v - min) / (max - min)) * 100));
|
|
41
|
+
|
|
42
|
+
// ---------------- Time ----------------
|
|
43
|
+
|
|
44
|
+
const DAY = 86_400_000;
|
|
45
|
+
export type TimeUnit = 'day' | 'week' | 'month' | 'quarter' | 'year';
|
|
46
|
+
const STEPS: Array<{ unit: TimeUnit; n: number; approx: number }> = [
|
|
47
|
+
{ unit: 'day', n: 1, approx: DAY },
|
|
48
|
+
{ unit: 'day', n: 2, approx: 2 * DAY },
|
|
49
|
+
{ unit: 'week', n: 1, approx: 7 * DAY },
|
|
50
|
+
{ unit: 'week', n: 2, approx: 14 * DAY },
|
|
51
|
+
{ unit: 'month', n: 1, approx: 30.4 * DAY },
|
|
52
|
+
{ unit: 'quarter', n: 1, approx: 91 * DAY },
|
|
53
|
+
{ unit: 'month', n: 6, approx: 182 * DAY },
|
|
54
|
+
{ unit: 'year', n: 1, approx: 365 * DAY },
|
|
55
|
+
{ unit: 'year', n: 2, approx: 730 * DAY },
|
|
56
|
+
{ unit: 'year', n: 5, approx: 1826 * DAY },
|
|
57
|
+
{ unit: 'year', n: 10, approx: 3652 * DAY },
|
|
58
|
+
];
|
|
59
|
+
|
|
60
|
+
/** Calendar-aligned ticks (UTC) between two times, about `count` of them. */
|
|
61
|
+
export function timeTicks(min: number, max: number, count = 6): { ticks: number[]; unit: TimeUnit } {
|
|
62
|
+
const span = Math.max(DAY, max - min);
|
|
63
|
+
const step = STEPS.find((s) => span / s.approx <= count) ?? STEPS[STEPS.length - 1];
|
|
64
|
+
const d = new Date(min);
|
|
65
|
+
let t: Date;
|
|
66
|
+
if (step.unit === 'day' || step.unit === 'week') t = new Date(Date.UTC(d.getUTCFullYear(), d.getUTCMonth(), d.getUTCDate()));
|
|
67
|
+
else if (step.unit === 'year') t = new Date(Date.UTC(Math.floor(d.getUTCFullYear() / step.n) * step.n, 0, 1));
|
|
68
|
+
else {
|
|
69
|
+
const months = step.unit === 'quarter' ? 3 : step.n;
|
|
70
|
+
t = new Date(Date.UTC(d.getUTCFullYear(), Math.floor(d.getUTCMonth() / months) * months, 1));
|
|
71
|
+
}
|
|
72
|
+
const ticks: number[] = [];
|
|
73
|
+
let guard = 0;
|
|
74
|
+
while (t.getTime() <= max && guard++ < 500) {
|
|
75
|
+
if (t.getTime() >= min) ticks.push(t.getTime());
|
|
76
|
+
if (step.unit === 'day') t = new Date(t.getTime() + step.n * DAY);
|
|
77
|
+
else if (step.unit === 'week') t = new Date(t.getTime() + 7 * step.n * DAY);
|
|
78
|
+
else if (step.unit === 'month') t = new Date(Date.UTC(t.getUTCFullYear(), t.getUTCMonth() + step.n, 1));
|
|
79
|
+
else if (step.unit === 'quarter') t = new Date(Date.UTC(t.getUTCFullYear(), t.getUTCMonth() + 3, 1));
|
|
80
|
+
else t = new Date(Date.UTC(t.getUTCFullYear() + step.n, 0, 1));
|
|
81
|
+
}
|
|
82
|
+
return { ticks, unit: step.unit === 'week' ? 'day' : step.unit };
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
/** Finest calendar unit that distinguishes the data's dates (for tooltip/table labels). */
|
|
86
|
+
export function dataGranularity(times: number[]): 'day' | 'month' | 'year' {
|
|
87
|
+
const ds = times.map((t) => new Date(t));
|
|
88
|
+
if (ds.every((d) => d.getUTCMonth() === 0 && d.getUTCDate() === 1)) return 'year';
|
|
89
|
+
if (ds.every((d) => d.getUTCDate() === 1)) return 'month';
|
|
90
|
+
return 'day';
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
/** Short tick label: "Jan", "Jan 2026" when the year changes, "Mar 4", "2026". */
|
|
94
|
+
export function timeTickLabel(t: number, unit: TimeUnit, locale: string, previous?: number): string {
|
|
95
|
+
const d = new Date(t);
|
|
96
|
+
const yearChanged = previous === undefined || new Date(previous).getUTCFullYear() !== d.getUTCFullYear();
|
|
97
|
+
const f = (o: Intl.DateTimeFormatOptions) => new Intl.DateTimeFormat(locale, { timeZone: 'UTC', ...o }).format(d);
|
|
98
|
+
if (unit === 'year') return f({ year: 'numeric' });
|
|
99
|
+
if (unit === 'month' || unit === 'quarter') return yearChanged ? f({ month: 'short', year: 'numeric' }) : f({ month: 'short' });
|
|
100
|
+
return yearChanged ? f({ month: 'short', day: 'numeric', year: 'numeric' }) : f({ month: 'short', day: 'numeric' });
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
/** Full date label for tooltips and the table, at the data's granularity. */
|
|
104
|
+
export function timeFullLabel(t: number, granularity: 'day' | 'month' | 'year', locale: string): string {
|
|
105
|
+
const o: Intl.DateTimeFormatOptions = granularity === 'year' ? { year: 'numeric' } : granularity === 'month' ? { month: 'long', year: 'numeric' } : { month: 'short', day: 'numeric', year: 'numeric' };
|
|
106
|
+
return new Intl.DateTimeFormat(locale, { timeZone: 'UTC', ...o }).format(new Date(t));
|
|
107
|
+
}
|
|
@@ -0,0 +1,117 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* defineSparkline — a compact, axis-free trend: positions as percentages (responsive without JS),
|
|
3
|
+
* a de-emphasized line with the highlighted point in the accent, and a sentence for screen readers.
|
|
4
|
+
*/
|
|
5
|
+
import { formatValue } from '../../primitives/utils';
|
|
6
|
+
import type { ValueFormat } from '../../primitives/types';
|
|
7
|
+
|
|
8
|
+
export interface SparklineInput {
|
|
9
|
+
values: Array<number | null | undefined>;
|
|
10
|
+
/** Label per value ("Jan", "Week 3"), used in the tooltip and summary. */
|
|
11
|
+
labels?: string[];
|
|
12
|
+
/** What it measures ("Visits"), for the summary. */
|
|
13
|
+
label?: string;
|
|
14
|
+
format?: ValueFormat;
|
|
15
|
+
type?: 'line' | 'area' | 'bar';
|
|
16
|
+
/** Which point gets the accent dot. */
|
|
17
|
+
highlight?: 'last' | 'max' | 'min' | 'none';
|
|
18
|
+
/** A target or average drawn as a hairline. */
|
|
19
|
+
reference?: number;
|
|
20
|
+
referenceLabel?: string;
|
|
21
|
+
/** Include zero in the range (always for bars). */
|
|
22
|
+
zero?: boolean;
|
|
23
|
+
locale?: string;
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
export interface SparklineModel {
|
|
27
|
+
linePath: string;
|
|
28
|
+
areaPath: string;
|
|
29
|
+
points: Array<{ xPct: number; yPct: number; display: string; label: string } | null>;
|
|
30
|
+
bars: Array<{ xPct: number; widthPct: number; topPct: number; heightPct: number; highlight: boolean; negative: boolean }>;
|
|
31
|
+
highlight?: { xPct: number; yPct: number; index: number };
|
|
32
|
+
referencePct?: number;
|
|
33
|
+
baselinePct: number;
|
|
34
|
+
direction: 'up' | 'down' | 'flat';
|
|
35
|
+
summary: string;
|
|
36
|
+
type: 'line' | 'area' | 'bar';
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
const r2 = (v: number) => Math.round(v * 100) / 100;
|
|
40
|
+
|
|
41
|
+
export function defineSparkline(input: SparklineInput): SparklineModel {
|
|
42
|
+
const locale = input.locale ?? 'en-US';
|
|
43
|
+
const type = input.type ?? 'line';
|
|
44
|
+
const fmt = (v: number | null | undefined) => formatValue(v, input.format ?? 'number', locale);
|
|
45
|
+
const values = input.values.map((v) => (typeof v === 'number' && Number.isFinite(v) ? v : null));
|
|
46
|
+
const n = values.length;
|
|
47
|
+
const nums = values.filter((v): v is number => v !== null);
|
|
48
|
+
let lo = nums.length ? Math.min(...nums) : 0;
|
|
49
|
+
let hi = nums.length ? Math.max(...nums) : 1;
|
|
50
|
+
if (input.reference !== undefined) (lo = Math.min(lo, input.reference)), (hi = Math.max(hi, input.reference));
|
|
51
|
+
if (type === 'bar' || input.zero) (lo = Math.min(lo, 0)), (hi = Math.max(hi, 0));
|
|
52
|
+
if (lo === hi) (lo -= 1), (hi += 1);
|
|
53
|
+
// A little headroom so the line and dots never touch the edges.
|
|
54
|
+
const pad = type === 'bar' ? 0 : (hi - lo) * 0.08;
|
|
55
|
+
const yMin = lo - (type === 'bar' && lo === 0 ? 0 : pad);
|
|
56
|
+
const yMax = hi + pad;
|
|
57
|
+
const Y = (v: number) => r2((1 - (v - yMin) / (yMax - yMin)) * 100);
|
|
58
|
+
const X = (i: number) => (type === 'bar' ? r2(((i + 0.5) / n) * 100) : n === 1 ? 50 : r2((i / (n - 1)) * 100));
|
|
59
|
+
const labelAt = (i: number) => input.labels?.[i] ?? `${i + 1} of ${n}`;
|
|
60
|
+
|
|
61
|
+
const points = values.map((v, i) => (v === null ? null : { xPct: X(i), yPct: Y(v), display: fmt(v), label: labelAt(i) }));
|
|
62
|
+
let linePath = '';
|
|
63
|
+
let areaPath = '';
|
|
64
|
+
// Areas fill down to zero when zero is in range, otherwise to the bottom edge.
|
|
65
|
+
const base = yMin <= 0 && yMax >= 0 ? Y(0) : 100;
|
|
66
|
+
let run: Array<{ xPct: number; yPct: number }> = [];
|
|
67
|
+
const flush = () => {
|
|
68
|
+
if (!run.length) return;
|
|
69
|
+
linePath += run.map((p, j) => `${j ? 'L' : 'M'}${r2(p.xPct * 10)} ${r2(p.yPct * 10)}`).join('');
|
|
70
|
+
areaPath += `M${r2(run[0].xPct * 10)} ${r2(base * 10)}${run.map((p) => `L${r2(p.xPct * 10)} ${r2(p.yPct * 10)}`).join('')}L${r2(run[run.length - 1].xPct * 10)} ${r2(base * 10)}Z`;
|
|
71
|
+
run = [];
|
|
72
|
+
};
|
|
73
|
+
points.forEach((p) => (p ? run.push(p) : flush()));
|
|
74
|
+
flush();
|
|
75
|
+
|
|
76
|
+
const idx = values.map((v, i) => [v, i] as const).filter(([v]) => v !== null) as Array<readonly [number, number]>;
|
|
77
|
+
const pick = input.highlight ?? 'last';
|
|
78
|
+
const hiIdx = !idx.length || pick === 'none' ? -1 : pick === 'max' ? idx.reduce((a, b) => (b[0] > a[0] ? b : a))[1] : pick === 'min' ? idx.reduce((a, b) => (b[0] < a[0] ? b : a))[1] : idx[idx.length - 1][1];
|
|
79
|
+
|
|
80
|
+
const zeroPct = Y(0);
|
|
81
|
+
const bw = r2((100 / Math.max(1, n)) * 0.62);
|
|
82
|
+
const bars =
|
|
83
|
+
type === 'bar'
|
|
84
|
+
? values.flatMap((v, i) =>
|
|
85
|
+
v === null ? [] : [{ xPct: X(i), widthPct: bw, topPct: Math.min(Y(v), zeroPct), heightPct: Math.max(r2(Math.abs(zeroPct - Y(v))), 0.5), highlight: i === hiIdx, negative: v < 0 }],
|
|
86
|
+
)
|
|
87
|
+
: [];
|
|
88
|
+
|
|
89
|
+
const first = idx[0];
|
|
90
|
+
const last = idx[idx.length - 1];
|
|
91
|
+
let direction: SparklineModel['direction'] = 'flat';
|
|
92
|
+
let summary = `${input.label ?? 'Trend'}: no data.`;
|
|
93
|
+
if (first && last) {
|
|
94
|
+
const change = first[0] === 0 ? undefined : (last[0] - first[0]) / Math.abs(first[0]);
|
|
95
|
+
direction = Math.abs(last[0] - first[0]) < 1e-9 || (change !== undefined && Math.abs(change) < 0.005) ? 'flat' : last[0] > first[0] ? 'up' : 'down';
|
|
96
|
+
const max = idx.reduce((a, b) => (b[0] > a[0] ? b : a));
|
|
97
|
+
const min = idx.reduce((a, b) => (b[0] < a[0] ? b : a));
|
|
98
|
+
const pct = change !== undefined ? ` (${direction === 'flat' ? 'no change' : `${direction} ${formatValue(Math.abs(change), { kind: 'percent', digits: 0 }, locale)}`})` : '';
|
|
99
|
+
summary =
|
|
100
|
+
`${input.label ?? 'Trend'}: ${fmt(first[0])} ${input.labels ? `in ${labelAt(first[1])} ` : ''}to ${fmt(last[0])}${input.labels ? ` in ${labelAt(last[1])}` : ''}${pct}. ` +
|
|
101
|
+
`High ${fmt(max[0])}${input.labels ? ` (${labelAt(max[1])})` : ''}, low ${fmt(min[0])}${input.labels ? ` (${labelAt(min[1])})` : ''}.` +
|
|
102
|
+
(input.reference !== undefined ? ` ${input.referenceLabel ?? 'Target'}: ${fmt(input.reference)}.` : '');
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
return {
|
|
106
|
+
type,
|
|
107
|
+
linePath,
|
|
108
|
+
areaPath,
|
|
109
|
+
points,
|
|
110
|
+
bars,
|
|
111
|
+
highlight: hiIdx >= 0 && points[hiIdx] ? { xPct: points[hiIdx]!.xPct, yPct: points[hiIdx]!.yPct, index: hiIdx } : undefined,
|
|
112
|
+
referencePct: input.reference !== undefined ? Y(input.reference) : undefined,
|
|
113
|
+
baselinePct: zeroPct,
|
|
114
|
+
direction,
|
|
115
|
+
summary,
|
|
116
|
+
};
|
|
117
|
+
}
|
|
@@ -0,0 +1,324 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Chart interaction (the charts are complete without it):
|
|
3
|
+
* - Tooltip: on lines/areas a crosshair snaps to the nearest x and lists every series there; on
|
|
4
|
+
* bars the band lifts and the bar under the pointer leads the list. Same on keyboard focus:
|
|
5
|
+
* ←/→ move, Home/End jump, PageUp/PageDown move 5, Esc hides; each move is announced politely.
|
|
6
|
+
* - Legend: buttons show/hide a series (Alt/Option-click isolates it); at least one stays visible;
|
|
7
|
+
* colors never change. "Show all" restores everything.
|
|
8
|
+
* - Sparkline: the same readout for one series.
|
|
9
|
+
* Text from data (series names, labels) is inserted with textContent only.
|
|
10
|
+
*/
|
|
11
|
+
type Row = [series: string, display: string, yPct: number | null];
|
|
12
|
+
type Hit = [from: number, to: number, x: number, label: string, rows: Row[], total: string | null];
|
|
13
|
+
interface ChartData {
|
|
14
|
+
type: 'line' | 'area' | 'bar';
|
|
15
|
+
stacked: boolean;
|
|
16
|
+
series: Record<string, [label: string, slot: string]>;
|
|
17
|
+
hits: Hit[];
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
const debounce = (fn: (msg: string) => void, ms = 180) => {
|
|
21
|
+
let t: ReturnType<typeof setTimeout> | undefined;
|
|
22
|
+
return (msg: string) => {
|
|
23
|
+
clearTimeout(t);
|
|
24
|
+
t = setTimeout(() => fn(msg), ms);
|
|
25
|
+
};
|
|
26
|
+
};
|
|
27
|
+
const hiddenOf = (fig: Element | null) => new Set((fig as HTMLElement | null)?.dataset.hiddenSeries?.split(' ').filter(Boolean) ?? []);
|
|
28
|
+
const KEYS: Record<string, (i: number, n: number) => number> = {
|
|
29
|
+
ArrowRight: (i, n) => Math.min(n - 1, i + 1),
|
|
30
|
+
ArrowDown: (i, n) => Math.min(n - 1, i + 1),
|
|
31
|
+
ArrowLeft: (i) => Math.max(0, i - 1),
|
|
32
|
+
ArrowUp: (i) => Math.max(0, i - 1),
|
|
33
|
+
Home: () => 0,
|
|
34
|
+
End: (_i, n) => n - 1,
|
|
35
|
+
PageDown: (i, n) => Math.min(n - 1, i + 5),
|
|
36
|
+
PageUp: (i) => Math.max(0, i - 5),
|
|
37
|
+
};
|
|
38
|
+
|
|
39
|
+
function setupChart(layer: HTMLElement): void {
|
|
40
|
+
if (layer.dataset.ready) return;
|
|
41
|
+
layer.dataset.ready = '';
|
|
42
|
+
let data: ChartData;
|
|
43
|
+
try {
|
|
44
|
+
data = JSON.parse(layer.dataset.chart ?? '');
|
|
45
|
+
} catch {
|
|
46
|
+
return;
|
|
47
|
+
}
|
|
48
|
+
const fig = layer.closest<HTMLElement>('.sinn-chart');
|
|
49
|
+
const hover = layer.querySelector<SVGSVGElement>('.sinn-chart__hover');
|
|
50
|
+
const tip = layer.querySelector<HTMLElement>('.sinn-chart-tooltip');
|
|
51
|
+
const title = tip?.querySelector('.sinn-chart-tooltip__title');
|
|
52
|
+
const list = tip?.querySelector('.sinn-chart-tooltip__rows');
|
|
53
|
+
const total = tip?.querySelector<HTMLElement>('.sinn-chart-tooltip__total');
|
|
54
|
+
const live = layer.querySelector<HTMLElement>('[data-sinn-chart-live]');
|
|
55
|
+
const marks = fig?.querySelector<SVGSVGElement>('.sinn-chart__marks') ?? null;
|
|
56
|
+
const announce = debounce((msg) => live && (live.textContent = msg));
|
|
57
|
+
const isBar = data.type === 'bar';
|
|
58
|
+
let current = -1;
|
|
59
|
+
let currentSeries: string | undefined;
|
|
60
|
+
|
|
61
|
+
function show(i: number, opts: { series?: string; speak?: boolean } = {}): void {
|
|
62
|
+
const h = data.hits[i];
|
|
63
|
+
if (!h || !hover || !tip || !list || !title) return;
|
|
64
|
+
current = i;
|
|
65
|
+
currentSeries = opts.series;
|
|
66
|
+
const hidden = hiddenOf(fig);
|
|
67
|
+
const [from, to, x, label, rows, sum] = h;
|
|
68
|
+
hover.setAttribute('visibility', 'visible');
|
|
69
|
+
if (isBar) {
|
|
70
|
+
const band = hover.querySelector('.sinn-chart__band');
|
|
71
|
+
band?.setAttribute('x', `${from}%`);
|
|
72
|
+
band?.setAttribute('width', `${to - from}%`);
|
|
73
|
+
if (marks) {
|
|
74
|
+
marks.toggleAttribute('data-hovering', true);
|
|
75
|
+
marks.querySelectorAll<SVGElement>('[data-index]').forEach((el) => el.toggleAttribute('data-on', el.dataset.index === String(i)));
|
|
76
|
+
}
|
|
77
|
+
} else {
|
|
78
|
+
const line = hover.querySelector('.sinn-chart__crosshair');
|
|
79
|
+
line?.setAttribute('x1', `${x}%`);
|
|
80
|
+
line?.setAttribute('x2', `${x}%`);
|
|
81
|
+
hover.querySelectorAll<SVGCircleElement>('.sinn-chart__hover-dot').forEach((dot) => {
|
|
82
|
+
const row = rows.find((r) => r[0] === dot.dataset.series);
|
|
83
|
+
const visible = row && row[2] !== null && !hidden.has(row[0]);
|
|
84
|
+
dot.setAttribute('visibility', visible ? 'visible' : 'hidden');
|
|
85
|
+
if (visible) {
|
|
86
|
+
dot.setAttribute('cx', `${x}%`);
|
|
87
|
+
dot.setAttribute('cy', `${row![2]}%`);
|
|
88
|
+
}
|
|
89
|
+
});
|
|
90
|
+
}
|
|
91
|
+
title.textContent = label;
|
|
92
|
+
const items: HTMLElement[] = [];
|
|
93
|
+
const visibleRows = rows.filter((r) => !hidden.has(r[0]));
|
|
94
|
+
// On bars, the hovered bar leads; otherwise keep the series order (the legend's order).
|
|
95
|
+
const ordered = opts.series ? [...visibleRows.filter((r) => r[0] === opts.series), ...visibleRows.filter((r) => r[0] !== opts.series)] : visibleRows;
|
|
96
|
+
for (const [sid, display] of ordered) {
|
|
97
|
+
const [name, slot] = data.series[sid] ?? [sid, 'muted'];
|
|
98
|
+
const li = document.createElement('li');
|
|
99
|
+
li.dataset.slot = slot;
|
|
100
|
+
if (sid === opts.series) li.dataset.current = '';
|
|
101
|
+
const key = document.createElement('span');
|
|
102
|
+
key.className = 'sinn-chart-tooltip__key';
|
|
103
|
+
const value = document.createElement('strong');
|
|
104
|
+
value.className = 'sinn-chart-tooltip__value';
|
|
105
|
+
value.textContent = display;
|
|
106
|
+
const text = document.createElement('span');
|
|
107
|
+
text.className = 'sinn-chart-tooltip__label';
|
|
108
|
+
text.textContent = name;
|
|
109
|
+
li.append(key, value, text);
|
|
110
|
+
items.push(li);
|
|
111
|
+
}
|
|
112
|
+
list.replaceChildren(...items);
|
|
113
|
+
if (total) {
|
|
114
|
+
const showTotal = Boolean(sum) && hidden.size === 0;
|
|
115
|
+
total.hidden = !showTotal;
|
|
116
|
+
if (showTotal) {
|
|
117
|
+
const strong = document.createElement('strong');
|
|
118
|
+
strong.textContent = sum!;
|
|
119
|
+
total.replaceChildren(document.createTextNode('Total '), strong);
|
|
120
|
+
}
|
|
121
|
+
}
|
|
122
|
+
// CSSOM writes are allowed under a strict CSP (only style attributes in markup are blocked).
|
|
123
|
+
tip.style.left = `${x}%`;
|
|
124
|
+
tip.dataset.edge = x > 62 ? 'end' : 'start';
|
|
125
|
+
tip.hidden = false;
|
|
126
|
+
if (opts.speak) announce(`${label}: ${ordered.map(([sid, d]) => `${data.series[sid]?.[0] ?? sid} ${d}`).join(', ')}${sum && hidden.size === 0 ? `, total ${sum}` : ''}`);
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
function hide(): void {
|
|
130
|
+
hover?.setAttribute('visibility', 'hidden');
|
|
131
|
+
if (tip) tip.hidden = true;
|
|
132
|
+
marks?.removeAttribute('data-hovering');
|
|
133
|
+
marks?.querySelectorAll('[data-on]').forEach((el) => el.removeAttribute('data-on'));
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
function at(e: PointerEvent): { i: number; series?: string } {
|
|
137
|
+
const r = layer.getBoundingClientRect();
|
|
138
|
+
const p = ((e.clientX - r.left) / r.width) * 100;
|
|
139
|
+
let i = data.hits.findIndex((h) => p >= h[0] && p <= h[1]);
|
|
140
|
+
if (i < 0) i = p < 50 ? 0 : data.hits.length - 1;
|
|
141
|
+
let series: string | undefined;
|
|
142
|
+
if (isBar && marks && !data.stacked) {
|
|
143
|
+
// The bar nearest the pointer within the band leads the readout.
|
|
144
|
+
let best = Infinity;
|
|
145
|
+
marks.querySelectorAll<SVGGraphicsElement>(`.sinn-chart__bar[data-index="${i}"]:not([data-hidden])`).forEach((bar) => {
|
|
146
|
+
const b = bar.getBoundingClientRect();
|
|
147
|
+
const d = Math.abs(e.clientX - (b.left + b.width / 2));
|
|
148
|
+
if (d < best) (best = d), (series = bar.getAttribute('data-series') ?? undefined);
|
|
149
|
+
});
|
|
150
|
+
} else if (isBar && marks && data.stacked) {
|
|
151
|
+
marks.querySelectorAll<SVGGraphicsElement>(`.sinn-chart__bar[data-index="${i}"]:not([data-hidden])`).forEach((bar) => {
|
|
152
|
+
const b = bar.getBoundingClientRect();
|
|
153
|
+
if (e.clientY >= b.top && e.clientY <= b.bottom) series = bar.getAttribute('data-series') ?? undefined;
|
|
154
|
+
});
|
|
155
|
+
}
|
|
156
|
+
return { i, series };
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
layer.addEventListener('pointermove', (e) => {
|
|
160
|
+
const { i, series } = at(e);
|
|
161
|
+
if (i !== current || series !== currentSeries) show(i, { series });
|
|
162
|
+
});
|
|
163
|
+
layer.addEventListener('pointerdown', (e) => {
|
|
164
|
+
if (e.pointerType !== 'mouse') {
|
|
165
|
+
const { i, series } = at(e);
|
|
166
|
+
show(i, { series });
|
|
167
|
+
}
|
|
168
|
+
});
|
|
169
|
+
// Touch: lifting the finger fires pointerleave, so a tapped readout stays until a tap elsewhere.
|
|
170
|
+
document.addEventListener('pointerdown', (e) => {
|
|
171
|
+
if (current >= 0 && document.activeElement !== layer && !layer.contains(e.target as Node)) {
|
|
172
|
+
hide();
|
|
173
|
+
current = -1;
|
|
174
|
+
}
|
|
175
|
+
});
|
|
176
|
+
layer.addEventListener('pointerleave', (e) => {
|
|
177
|
+
if (e.pointerType === 'mouse' && document.activeElement !== layer) {
|
|
178
|
+
hide();
|
|
179
|
+
current = -1; // keyboard focus later starts from the latest point, not where the pointer left
|
|
180
|
+
}
|
|
181
|
+
});
|
|
182
|
+
layer.addEventListener('focus', () => show(current >= 0 ? current : data.hits.length - 1, { speak: true }));
|
|
183
|
+
layer.addEventListener('blur', hide);
|
|
184
|
+
layer.addEventListener('keydown', (e) => {
|
|
185
|
+
if (e.key === 'Escape') {
|
|
186
|
+
hide();
|
|
187
|
+
return;
|
|
188
|
+
}
|
|
189
|
+
const move = KEYS[e.key];
|
|
190
|
+
if (!move) return;
|
|
191
|
+
e.preventDefault();
|
|
192
|
+
show(move(current < 0 ? data.hits.length - 1 : current, data.hits.length), { speak: true });
|
|
193
|
+
});
|
|
194
|
+
fig?.addEventListener('sinn:series-change', () => {
|
|
195
|
+
if (tip && !tip.hidden && current >= 0) show(current, { series: currentSeries });
|
|
196
|
+
});
|
|
197
|
+
}
|
|
198
|
+
|
|
199
|
+
function setupLegend(legend: HTMLElement): void {
|
|
200
|
+
if (legend.dataset.ready) return;
|
|
201
|
+
legend.dataset.ready = '';
|
|
202
|
+
const fig = legend.closest<HTMLElement>('.sinn-chart');
|
|
203
|
+
if (!fig) return;
|
|
204
|
+
const buttons = [...legend.querySelectorAll<HTMLButtonElement>('[data-sinn-legend-toggle]')];
|
|
205
|
+
const reset = legend.querySelector<HTMLButtonElement>('[data-sinn-legend-reset]');
|
|
206
|
+
const live = legend.querySelector<HTMLElement>('[data-sinn-legend-live]');
|
|
207
|
+
const say = (m: string) => live && (live.textContent = m);
|
|
208
|
+
const name = (b: HTMLButtonElement) => b.querySelector('.sinn-chart-legend__label')?.textContent ?? '';
|
|
209
|
+
|
|
210
|
+
function apply(hidden: Set<string>): void {
|
|
211
|
+
fig!.dataset.hiddenSeries = [...hidden].join(' ');
|
|
212
|
+
for (const b of buttons) b.setAttribute('aria-pressed', String(!hidden.has(b.dataset.sinnLegendToggle!)));
|
|
213
|
+
fig!.querySelectorAll<SVGElement | HTMLElement>('[data-series]').forEach((el) => {
|
|
214
|
+
if (el.closest('.sinn-chart-legend')) return;
|
|
215
|
+
el.toggleAttribute('data-hidden', hidden.has(el.dataset.series!));
|
|
216
|
+
});
|
|
217
|
+
if (reset) reset.hidden = hidden.size === 0;
|
|
218
|
+
fig!.dispatchEvent(new CustomEvent('sinn:series-change', { detail: { hidden: [...hidden] } }));
|
|
219
|
+
}
|
|
220
|
+
|
|
221
|
+
legend.addEventListener('click', (e) => {
|
|
222
|
+
const target = e.target as HTMLElement;
|
|
223
|
+
if (target.closest('[data-sinn-legend-reset]')) {
|
|
224
|
+
apply(new Set());
|
|
225
|
+
say('All series shown.');
|
|
226
|
+
buttons[0]?.focus();
|
|
227
|
+
return;
|
|
228
|
+
}
|
|
229
|
+
const b = target.closest<HTMLButtonElement>('[data-sinn-legend-toggle]');
|
|
230
|
+
if (!b) return;
|
|
231
|
+
const id = b.dataset.sinnLegendToggle!;
|
|
232
|
+
const hidden = hiddenOf(fig);
|
|
233
|
+
if (e.altKey) {
|
|
234
|
+
apply(new Set(buttons.map((x) => x.dataset.sinnLegendToggle!).filter((x) => x !== id)));
|
|
235
|
+
say(`Showing only ${name(b)}.`);
|
|
236
|
+
return;
|
|
237
|
+
}
|
|
238
|
+
if (hidden.has(id)) {
|
|
239
|
+
hidden.delete(id);
|
|
240
|
+
apply(hidden);
|
|
241
|
+
say(`${name(b)} shown.`);
|
|
242
|
+
} else if (hidden.size >= buttons.length - 1) {
|
|
243
|
+
say('At least one series stays visible.');
|
|
244
|
+
} else {
|
|
245
|
+
hidden.add(id);
|
|
246
|
+
apply(hidden);
|
|
247
|
+
say(`${name(b)} hidden.`);
|
|
248
|
+
}
|
|
249
|
+
});
|
|
250
|
+
}
|
|
251
|
+
|
|
252
|
+
function setupSpark(el: HTMLElement): void {
|
|
253
|
+
if (el.dataset.ready) return;
|
|
254
|
+
el.dataset.ready = '';
|
|
255
|
+
let pts: Array<[number, number, string, string] | null> = [];
|
|
256
|
+
try {
|
|
257
|
+
pts = JSON.parse(el.querySelector<HTMLElement>('[data-sinn-spark-data]')?.dataset.sinnSparkData ?? '[]');
|
|
258
|
+
} catch {
|
|
259
|
+
return;
|
|
260
|
+
}
|
|
261
|
+
const idx = pts.map((p, i) => (p ? i : -1)).filter((i) => i >= 0);
|
|
262
|
+
if (!idx.length) return;
|
|
263
|
+
const g = el.querySelector('.sinn-spark__hover');
|
|
264
|
+
const line = el.querySelector('.sinn-spark__crosshair');
|
|
265
|
+
const dot = el.querySelector('.sinn-spark__hover-dot');
|
|
266
|
+
const tip = el.querySelector<HTMLElement>('.sinn-spark__tip');
|
|
267
|
+
const live = el.nextElementSibling?.matches('[data-sinn-chart-live]') ? (el.nextElementSibling as HTMLElement) : null;
|
|
268
|
+
const announce = debounce((m) => live && (live.textContent = m));
|
|
269
|
+
let cur = -1;
|
|
270
|
+
const show = (i: number, speak = false) => {
|
|
271
|
+
const p = pts[i];
|
|
272
|
+
if (!p || !tip) return;
|
|
273
|
+
cur = i;
|
|
274
|
+
g?.setAttribute('visibility', 'visible');
|
|
275
|
+
line?.setAttribute('x1', `${p[0]}%`);
|
|
276
|
+
line?.setAttribute('x2', `${p[0]}%`);
|
|
277
|
+
dot?.setAttribute('cx', `${p[0]}%`);
|
|
278
|
+
dot?.setAttribute('cy', `${p[1]}%`);
|
|
279
|
+
tip.querySelector('strong')!.textContent = p[2];
|
|
280
|
+
tip.querySelector('span')!.textContent = p[3];
|
|
281
|
+
tip.style.left = `${p[0]}%`;
|
|
282
|
+
tip.dataset.edge = p[0] > 50 ? 'end' : 'start';
|
|
283
|
+
tip.hidden = false;
|
|
284
|
+
if (speak) announce(`${p[3]}: ${p[2]}`);
|
|
285
|
+
};
|
|
286
|
+
const hide = () => {
|
|
287
|
+
g?.setAttribute('visibility', 'hidden');
|
|
288
|
+
if (tip) tip.hidden = true;
|
|
289
|
+
};
|
|
290
|
+
const nearest = (e: PointerEvent) => {
|
|
291
|
+
const r = el.getBoundingClientRect();
|
|
292
|
+
const x = ((e.clientX - r.left) / r.width) * 100;
|
|
293
|
+
return idx.reduce((a, b) => (Math.abs(pts[b]![0] - x) < Math.abs(pts[a]![0] - x) ? b : a));
|
|
294
|
+
};
|
|
295
|
+
el.addEventListener('pointermove', (e) => {
|
|
296
|
+
const i = nearest(e);
|
|
297
|
+
if (i !== cur) show(i);
|
|
298
|
+
});
|
|
299
|
+
el.addEventListener('pointerdown', (e) => e.pointerType !== 'mouse' && show(nearest(e)));
|
|
300
|
+
el.addEventListener('pointerleave', (e) => e.pointerType === 'mouse' && document.activeElement !== el && hide());
|
|
301
|
+
document.addEventListener('pointerdown', (e) => {
|
|
302
|
+
if (cur >= 0 && document.activeElement !== el && !el.contains(e.target as Node)) hide();
|
|
303
|
+
});
|
|
304
|
+
el.addEventListener('focus', () => show(cur >= 0 ? cur : idx[idx.length - 1], true));
|
|
305
|
+
el.addEventListener('blur', hide);
|
|
306
|
+
el.addEventListener('keydown', (e) => {
|
|
307
|
+
if (e.key === 'Escape') return hide();
|
|
308
|
+
const move = KEYS[e.key];
|
|
309
|
+
if (!move) return;
|
|
310
|
+
e.preventDefault();
|
|
311
|
+
const pos = Math.max(0, idx.indexOf(cur < 0 ? idx[idx.length - 1] : cur));
|
|
312
|
+
show(idx[move(pos, idx.length)], true);
|
|
313
|
+
});
|
|
314
|
+
}
|
|
315
|
+
|
|
316
|
+
function init(): void {
|
|
317
|
+
document.querySelectorAll<HTMLElement>('[data-sinn-chart-interact]').forEach(setupChart);
|
|
318
|
+
document.querySelectorAll<HTMLElement>('.sinn-chart-legend[data-toggle]').forEach(setupLegend);
|
|
319
|
+
document.querySelectorAll<HTMLElement>('[data-sinn-spark]').forEach(setupSpark);
|
|
320
|
+
}
|
|
321
|
+
init();
|
|
322
|
+
document.addEventListener('astro:page-load', init);
|
|
323
|
+
|
|
324
|
+
export {};
|