@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,450 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* defineChart — turns data into a ChartModel: scales, ticks, mark positions (as percentages, so
|
|
3
|
+
* the SVG is responsive without JavaScript), tooltip rows, a screen-reader summary and the table.
|
|
4
|
+
* Every Chart* component renders from the same model:
|
|
5
|
+
*
|
|
6
|
+
* ---
|
|
7
|
+
* const chart = defineChart({ type: 'line', x: months, series: [{ label: 'Visits', values }], yFormat: 'integer' });
|
|
8
|
+
* ---
|
|
9
|
+
* <ChartContainer chart={chart} title="Site visits per month">
|
|
10
|
+
* <ChartAxis chart={chart} axis="y" /> <ChartAxis chart={chart} axis="x" />
|
|
11
|
+
* <ChartSeries chart={chart} /> <ChartTooltip chart={chart} />
|
|
12
|
+
* </ChartContainer>
|
|
13
|
+
*
|
|
14
|
+
* Pure: no DOM, no Astro. Tested directly.
|
|
15
|
+
*/
|
|
16
|
+
import { formatValue } from '../../primitives/utils';
|
|
17
|
+
import type { ValueFormat } from '../../primitives/types';
|
|
18
|
+
import { dataGranularity, niceDomain, timeFullLabel, timeTickLabel, timeTicks, xPct as xp, yPct as yp } from './scale';
|
|
19
|
+
|
|
20
|
+
export type ChartType = 'line' | 'area' | 'bar';
|
|
21
|
+
export type SeriesSlot = 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8;
|
|
22
|
+
|
|
23
|
+
export interface SeriesInput {
|
|
24
|
+
/** Stable id (used for colors, toggles and DOM). Defaults to a slug of the label. */
|
|
25
|
+
id?: string;
|
|
26
|
+
label: string;
|
|
27
|
+
/** One value per x position; null/undefined is a gap. */
|
|
28
|
+
values: Array<number | null | undefined>;
|
|
29
|
+
/**
|
|
30
|
+
* Color slot 1–8 from the validated categorical palette. Defaults to the series' position, so a
|
|
31
|
+
* series keeps its color when others are filtered out only if you pass `slot` explicitly.
|
|
32
|
+
*/
|
|
33
|
+
slot?: SeriesSlot;
|
|
34
|
+
/** De-emphasize (gray): for "Other", targets, or everything but the series the story is about. */
|
|
35
|
+
muted?: boolean;
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
export interface ChartInput {
|
|
39
|
+
type: ChartType;
|
|
40
|
+
/** Categories ("Q1", "Fort Worth") or dates (Date, ISO string, or timestamp). */
|
|
41
|
+
x: Array<string | number | Date>;
|
|
42
|
+
/** `time` positions points by date; `category` spaces them evenly. Auto: time for dates on line/area. */
|
|
43
|
+
xType?: 'category' | 'time';
|
|
44
|
+
xTitle?: string;
|
|
45
|
+
yTitle?: string;
|
|
46
|
+
series: SeriesInput[];
|
|
47
|
+
/** How values print on the axis, tooltip and table. */
|
|
48
|
+
yFormat?: ValueFormat;
|
|
49
|
+
/** Force the y range (otherwise nice bounds around the data). */
|
|
50
|
+
yMin?: number;
|
|
51
|
+
yMax?: number;
|
|
52
|
+
/** Include zero in the y range. Default: always for bars; for lines when the data is near zero. */
|
|
53
|
+
yZero?: boolean;
|
|
54
|
+
/** About how many y ticks (default 5). */
|
|
55
|
+
yTicks?: number;
|
|
56
|
+
/** Stack bars or areas. */
|
|
57
|
+
stacked?: boolean;
|
|
58
|
+
locale?: string;
|
|
59
|
+
/** DOM id prefix (stable ids for aria references). */
|
|
60
|
+
id?: string;
|
|
61
|
+
/** What the chart shows ("site visits"), used in the screen-reader summary. */
|
|
62
|
+
subject?: string;
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
export interface XTick {
|
|
66
|
+
pct: number;
|
|
67
|
+
label: string;
|
|
68
|
+
/** Largest power of two (≤16) dividing this tick's index: lets CSS thin labels by density. */
|
|
69
|
+
tier: 1 | 2 | 4 | 8 | 16;
|
|
70
|
+
anchor: 'start' | 'middle' | 'end';
|
|
71
|
+
}
|
|
72
|
+
export interface YTick {
|
|
73
|
+
pct: number;
|
|
74
|
+
value: number;
|
|
75
|
+
label: string;
|
|
76
|
+
}
|
|
77
|
+
export interface PointModel {
|
|
78
|
+
index: number;
|
|
79
|
+
xPct: number;
|
|
80
|
+
yPct: number;
|
|
81
|
+
value: number;
|
|
82
|
+
display: string;
|
|
83
|
+
}
|
|
84
|
+
export interface BarModel {
|
|
85
|
+
index: number;
|
|
86
|
+
/** Band center, percent from the left. */
|
|
87
|
+
xPct: number;
|
|
88
|
+
topPct: number;
|
|
89
|
+
bottomPct: number;
|
|
90
|
+
/** Which end is rounded (the data end); `none` for inner stacked segments. */
|
|
91
|
+
rounded: 'top' | 'bottom' | 'none';
|
|
92
|
+
/** Position within a group: -1.5 … 1.5 bar widths from the band center ("0" when stacked). */
|
|
93
|
+
offset: string;
|
|
94
|
+
value: number;
|
|
95
|
+
display: string;
|
|
96
|
+
}
|
|
97
|
+
export interface SeriesModel {
|
|
98
|
+
id: string;
|
|
99
|
+
label: string;
|
|
100
|
+
slot: SeriesSlot;
|
|
101
|
+
muted: boolean;
|
|
102
|
+
points: Array<PointModel | null>;
|
|
103
|
+
/** Paths in a 0–1000 viewBox (drawn with non-scaling strokes). */
|
|
104
|
+
linePath: string;
|
|
105
|
+
areaPath: string;
|
|
106
|
+
bars: BarModel[];
|
|
107
|
+
last?: PointModel;
|
|
108
|
+
}
|
|
109
|
+
export interface HitModel {
|
|
110
|
+
index: number;
|
|
111
|
+
/** Hit band, percent from the left. */
|
|
112
|
+
fromPct: number;
|
|
113
|
+
toPct: number;
|
|
114
|
+
/** Crosshair / band center. */
|
|
115
|
+
xPct: number;
|
|
116
|
+
label: string;
|
|
117
|
+
rows: Array<{ series: string; label: string; slot: SeriesSlot; display: string; yPct?: number }>;
|
|
118
|
+
total?: string;
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
export interface ChartModel {
|
|
122
|
+
id: string;
|
|
123
|
+
type: ChartType;
|
|
124
|
+
stacked: boolean;
|
|
125
|
+
xType: 'category' | 'time';
|
|
126
|
+
xTitle?: string;
|
|
127
|
+
yTitle?: string;
|
|
128
|
+
locale: string;
|
|
129
|
+
yMin: number;
|
|
130
|
+
yMax: number;
|
|
131
|
+
baselinePct: number;
|
|
132
|
+
xTicks: XTick[];
|
|
133
|
+
/** Show every Nth label at each container size (xs <24rem, sm <36rem, md <52rem, lg). */
|
|
134
|
+
xSteps: { xs: number; sm: number; md: number; lg: number };
|
|
135
|
+
yTicks: YTick[];
|
|
136
|
+
/** Width of the y-axis label column, in ch. */
|
|
137
|
+
yLabelCh: number;
|
|
138
|
+
series: SeriesModel[];
|
|
139
|
+
/** Max bar thickness as a % of the plot width (CSS caps it at 24px). */
|
|
140
|
+
barPct: number;
|
|
141
|
+
hits: HitModel[];
|
|
142
|
+
summary: string;
|
|
143
|
+
table: { headers: string[]; rows: string[][]; csv: string };
|
|
144
|
+
warnings: string[];
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
const slugify = (s: string) =>
|
|
148
|
+
s
|
|
149
|
+
.toLowerCase()
|
|
150
|
+
.normalize('NFKD')
|
|
151
|
+
.replace(/[̀-ͯ]/g, '')
|
|
152
|
+
.replace(/[^a-z0-9]+/g, '-')
|
|
153
|
+
.replace(/^-|-$/g, '') || 's';
|
|
154
|
+
let counter = 0;
|
|
155
|
+
const r2 = (v: number) => Math.round(v * 100) / 100;
|
|
156
|
+
|
|
157
|
+
function toTime(v: string | number | Date): number | undefined {
|
|
158
|
+
if (v instanceof Date) return v.getTime();
|
|
159
|
+
if (typeof v === 'number') return v;
|
|
160
|
+
if (/^\d{4}-\d{2}(-\d{2})?([T ][\d:.]+(Z|[+-]\d{2}:?\d{2})?)?$/.test(v)) {
|
|
161
|
+
const t = Date.parse(v.length === 7 ? `${v}-01` : v);
|
|
162
|
+
return Number.isFinite(t) ? t : undefined;
|
|
163
|
+
}
|
|
164
|
+
return undefined;
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
const TIERS = [16, 8, 4, 2, 1] as const;
|
|
168
|
+
const tierOf = (i: number): XTick['tier'] => (i === 0 ? 16 : TIERS.find((k) => i % k === 0) ?? 1);
|
|
169
|
+
/** Plot widths (px) assumed for each container size when thinning x labels. */
|
|
170
|
+
const PLOT_WIDTH = { xs: 240, sm: 380, md: 600, lg: 880 } as const;
|
|
171
|
+
|
|
172
|
+
export function defineChart(input: ChartInput): ChartModel {
|
|
173
|
+
const warnings: string[] = [];
|
|
174
|
+
const locale = input.locale ?? 'en-US';
|
|
175
|
+
const type = input.type;
|
|
176
|
+
const stacked = Boolean(input.stacked) && type !== 'line';
|
|
177
|
+
const n = input.x.length;
|
|
178
|
+
const id = input.id ?? `sinn-chart-${++counter}`;
|
|
179
|
+
// Values (tooltip, table, summary) are exact: never compact, and whole-dollar data shows no cents,
|
|
180
|
+
// so one column never mixes "$9,000.00" with "$23.4K". Only the axis abbreviates (see tickSpec).
|
|
181
|
+
const exactSpec: ValueFormat = (() => {
|
|
182
|
+
const base = input.yFormat ?? 'number';
|
|
183
|
+
const spec = (typeof base === 'string' ? { kind: base } : { ...base }) as ValueFormat & { kind: string; compact?: unknown; digits?: number };
|
|
184
|
+
if (spec.compact !== true) spec.compact = false;
|
|
185
|
+
if (spec.kind === 'compact' && spec.compact === false) spec.kind = 'number';
|
|
186
|
+
const allWhole = input.series.every((s) => s.values.every((v) => v === null || v === undefined || Number.isInteger(v)));
|
|
187
|
+
if (spec.kind === 'currency' && spec.digits === undefined && allWhole) spec.digits = 0;
|
|
188
|
+
return spec;
|
|
189
|
+
})();
|
|
190
|
+
const fmtY = (v: number | null | undefined, spec: ValueFormat = exactSpec) => formatValue(v, spec, locale);
|
|
191
|
+
|
|
192
|
+
// ---------- x ----------
|
|
193
|
+
const times = input.x.map(toTime);
|
|
194
|
+
const canTime = type !== 'bar' && times.every((t) => t !== undefined);
|
|
195
|
+
const xType = input.xType === 'category' ? 'category' : input.xType === 'time' || canTime ? (canTime ? 'time' : 'category') : 'category';
|
|
196
|
+
if (input.xType === 'time' && !canTime) warnings.push('xType "time" needs dates for every x value (or bars, which are always categories); using categories.');
|
|
197
|
+
const granularity = xType === 'time' ? dataGranularity(times as number[]) : undefined;
|
|
198
|
+
const tMin = xType === 'time' ? Math.min(...(times as number[])) : 0;
|
|
199
|
+
const tMax = xType === 'time' ? Math.max(...(times as number[])) : 0;
|
|
200
|
+
const xLabelFull = (i: number) => (xType === 'time' ? timeFullLabel(times[i]!, granularity!, locale) : String(input.x[i]));
|
|
201
|
+
const xPos = (i: number) => {
|
|
202
|
+
if (type === 'bar') return r2(((i + 0.5) / n) * 100);
|
|
203
|
+
if (xType === 'time') return xp(times[i]!, tMin, tMax);
|
|
204
|
+
return n === 1 ? 50 : r2((i / (n - 1)) * 100);
|
|
205
|
+
};
|
|
206
|
+
|
|
207
|
+
// ---------- series ----------
|
|
208
|
+
if (input.series.length > 8) warnings.push(`${input.series.length} series: past 8 the palette can't keep them apart. Fold the smallest into "Other".`);
|
|
209
|
+
const usedIds = new Set<string>();
|
|
210
|
+
const series = input.series.map((s, i) => {
|
|
211
|
+
let sid = s.id ?? slugify(s.label);
|
|
212
|
+
while (usedIds.has(sid)) sid += '-2';
|
|
213
|
+
usedIds.add(sid);
|
|
214
|
+
if (s.values.length !== n) warnings.push(`Series "${s.label}" has ${s.values.length} values for ${n} x positions.`);
|
|
215
|
+
const slot = (s.slot ?? (((i % 8) + 1) as SeriesSlot)) as SeriesSlot;
|
|
216
|
+
return { ...s, id: sid, slot, muted: Boolean(s.muted), values: Array.from({ length: n }, (_, k) => (typeof s.values[k] === 'number' && Number.isFinite(s.values[k]) ? (s.values[k] as number) : null)) };
|
|
217
|
+
});
|
|
218
|
+
const slots = series.filter((s) => !s.muted).map((s) => s.slot);
|
|
219
|
+
if (new Set(slots).size !== slots.length) warnings.push('Two series share a color slot.');
|
|
220
|
+
|
|
221
|
+
// ---------- y domain ----------
|
|
222
|
+
let lo = Infinity;
|
|
223
|
+
let hi = -Infinity;
|
|
224
|
+
if (stacked) {
|
|
225
|
+
for (let k = 0; k < n; k++) {
|
|
226
|
+
let pos = 0;
|
|
227
|
+
let neg = 0;
|
|
228
|
+
for (const s of series) {
|
|
229
|
+
const v = s.values[k];
|
|
230
|
+
if (v === null) continue;
|
|
231
|
+
if (v >= 0) pos += v;
|
|
232
|
+
else neg += v;
|
|
233
|
+
}
|
|
234
|
+
hi = Math.max(hi, pos);
|
|
235
|
+
lo = Math.min(lo, neg);
|
|
236
|
+
}
|
|
237
|
+
} else {
|
|
238
|
+
for (const s of series) for (const v of s.values) if (v !== null) (lo = Math.min(lo, v)), (hi = Math.max(hi, v));
|
|
239
|
+
}
|
|
240
|
+
if (!Number.isFinite(lo)) {
|
|
241
|
+
lo = 0;
|
|
242
|
+
hi = 1;
|
|
243
|
+
warnings.push('No numeric values to plot.');
|
|
244
|
+
}
|
|
245
|
+
const includeZero = input.yZero ?? (type !== 'line' || lo <= 0 || lo < hi * 0.35);
|
|
246
|
+
if (type === 'bar' && input.yZero === false) warnings.push('Bars must start at zero (their length is the value); ignoring yZero: false.');
|
|
247
|
+
if (type !== 'line' || includeZero) {
|
|
248
|
+
lo = Math.min(lo, 0);
|
|
249
|
+
hi = Math.max(hi, 0);
|
|
250
|
+
}
|
|
251
|
+
const dom = niceDomain(input.yMin ?? lo, input.yMax ?? hi, input.yTicks ?? 5);
|
|
252
|
+
const yMin = input.yMin ?? dom.min;
|
|
253
|
+
const yMax = input.yMax ?? dom.max;
|
|
254
|
+
const axisCompact = Math.max(Math.abs(yMin), Math.abs(yMax)) >= 10_000;
|
|
255
|
+
const tickSpec: ValueFormat = (() => {
|
|
256
|
+
const base = input.yFormat ?? 'number';
|
|
257
|
+
const spec = typeof base === 'string' ? { kind: base } : { ...base };
|
|
258
|
+
if (spec.kind === 'number' || spec.kind === 'integer' || spec.kind === 'currency' || spec.kind === 'compact') (spec as { compact?: boolean }).compact = axisCompact;
|
|
259
|
+
if (spec.kind === 'integer') spec.kind = 'number';
|
|
260
|
+
// Fewest decimals that keep every tick exact: "$400K", "2.5K", "$1.25M" (never "$400.0K").
|
|
261
|
+
if ((spec as { digits?: number }).digits === undefined && (axisCompact || spec.kind === 'number' || spec.kind === 'currency')) {
|
|
262
|
+
const need = (v: number) => {
|
|
263
|
+
const a = Math.abs(v);
|
|
264
|
+
const unit = axisCompact && a >= 1000 ? 1000 ** Math.floor(Math.log10(a) / 3) : 1;
|
|
265
|
+
const r = Math.round((a / unit) * 100) / 100;
|
|
266
|
+
return r === Math.round(r) ? 0 : Math.round(r * 10) === r * 10 ? 1 : 2;
|
|
267
|
+
};
|
|
268
|
+
(spec as { digits?: number }).digits = Math.max(0, ...dom.ticks.map(need));
|
|
269
|
+
}
|
|
270
|
+
return spec as ValueFormat;
|
|
271
|
+
})();
|
|
272
|
+
const yTicks: YTick[] = dom.ticks.filter((v) => v >= yMin - 1e-9 && v <= yMax + 1e-9).map((v) => ({ value: v, pct: yp(v, yMin, yMax), label: fmtY(v, tickSpec) }));
|
|
273
|
+
const baseline = Math.min(Math.max(0, yMin), yMax);
|
|
274
|
+
const baselinePct = yp(baseline, yMin, yMax);
|
|
275
|
+
const Y = (v: number) => yp(v, yMin, yMax);
|
|
276
|
+
|
|
277
|
+
// ---------- marks ----------
|
|
278
|
+
const visibleCount = series.length;
|
|
279
|
+
const groupSize = type === 'bar' && !stacked ? visibleCount : 1;
|
|
280
|
+
const band = 100 / Math.max(1, n);
|
|
281
|
+
const barPct = Math.max(1, Math.min(60, Math.floor((band * 0.72) / Math.max(1, groupSize))));
|
|
282
|
+
const stackPos = new Array(n).fill(0);
|
|
283
|
+
const stackNeg = new Array(n).fill(0);
|
|
284
|
+
const offsets = ['-1.5', '-1', '-0.5', '0', '0.5', '1', '1.5'];
|
|
285
|
+
if (groupSize > 4) warnings.push('More than 4 grouped bars per category: consider stacking or small multiples.');
|
|
286
|
+
|
|
287
|
+
const models: SeriesModel[] = series.map((s, si) => {
|
|
288
|
+
const points: Array<PointModel | null> = [];
|
|
289
|
+
const bars: BarModel[] = [];
|
|
290
|
+
const base: number[] = [];
|
|
291
|
+
for (let k = 0; k < n; k++) {
|
|
292
|
+
const v = s.values[k];
|
|
293
|
+
if (v === null) {
|
|
294
|
+
points.push(null);
|
|
295
|
+
base.push(NaN);
|
|
296
|
+
continue;
|
|
297
|
+
}
|
|
298
|
+
let top = v;
|
|
299
|
+
let bottom = 0;
|
|
300
|
+
if (stacked) {
|
|
301
|
+
if (v >= 0) {
|
|
302
|
+
bottom = stackPos[k];
|
|
303
|
+
top = stackPos[k] += v;
|
|
304
|
+
} else {
|
|
305
|
+
bottom = stackNeg[k];
|
|
306
|
+
top = stackNeg[k] += v;
|
|
307
|
+
}
|
|
308
|
+
}
|
|
309
|
+
base.push(stacked ? bottom : baseline);
|
|
310
|
+
points.push({ index: k, xPct: xPos(k), yPct: Y(top), value: v, display: fmtY(v) });
|
|
311
|
+
if (type === 'bar') {
|
|
312
|
+
const offset = stacked ? '0' : offsets[Math.max(0, Math.min(6, Math.round((si - (groupSize - 1) / 2) * 2) + 3))];
|
|
313
|
+
bars.push({ index: k, xPct: xPos(k), topPct: Y(Math.max(top, bottom)), bottomPct: Y(Math.min(top, bottom)), rounded: 'none', offset, value: v, display: fmtY(v) });
|
|
314
|
+
}
|
|
315
|
+
}
|
|
316
|
+
// Lines/areas: break at gaps.
|
|
317
|
+
let linePath = '';
|
|
318
|
+
let areaPath = '';
|
|
319
|
+
let run: Array<[number, number, number]> = [];
|
|
320
|
+
const flush = () => {
|
|
321
|
+
if (!run.length) return;
|
|
322
|
+
linePath += run.map(([x, y], j) => `${j ? 'L' : 'M'}${r2(x * 10)} ${r2(y * 10)}`).join('');
|
|
323
|
+
const back = [...run].reverse().map(([x, , b]) => `L${r2(x * 10)} ${r2(Y(b) * 10)}`).join('');
|
|
324
|
+
areaPath += `M${r2(run[0][0] * 10)} ${r2(run[0][1] * 10)}${run.slice(1).map(([x, y]) => `L${r2(x * 10)} ${r2(y * 10)}`).join('')}${back}Z`;
|
|
325
|
+
run = [];
|
|
326
|
+
};
|
|
327
|
+
points.forEach((p, k) => (p ? run.push([p.xPct, p.yPct, base[k]]) : flush()));
|
|
328
|
+
flush();
|
|
329
|
+
const last = [...points].reverse().find(Boolean) ?? undefined;
|
|
330
|
+
return { id: s.id, label: s.label, slot: s.slot, muted: s.muted, points, linePath, areaPath, bars, last: last ?? undefined };
|
|
331
|
+
});
|
|
332
|
+
|
|
333
|
+
// Rounded data ends: grouped bars each; stacked bars only the outermost segment per side.
|
|
334
|
+
if (type === 'bar') {
|
|
335
|
+
for (let k = 0; k < n; k++) {
|
|
336
|
+
if (!stacked) {
|
|
337
|
+
for (const m of models) {
|
|
338
|
+
const b = m.bars.find((x) => x.index === k);
|
|
339
|
+
if (b) b.rounded = b.value >= 0 ? 'top' : 'bottom';
|
|
340
|
+
}
|
|
341
|
+
} else {
|
|
342
|
+
const segs = models.map((m) => m.bars.find((x) => x.index === k)).filter(Boolean) as BarModel[];
|
|
343
|
+
const posTop = segs.filter((b) => b.value > 0).sort((a, b) => a.topPct - b.topPct)[0];
|
|
344
|
+
const negBot = segs.filter((b) => b.value < 0).sort((a, b) => b.bottomPct - a.bottomPct)[0];
|
|
345
|
+
if (posTop) posTop.rounded = 'top';
|
|
346
|
+
if (negBot) negBot.rounded = 'bottom';
|
|
347
|
+
}
|
|
348
|
+
}
|
|
349
|
+
}
|
|
350
|
+
|
|
351
|
+
// ---------- x ticks ----------
|
|
352
|
+
let xTicks: XTick[];
|
|
353
|
+
if (xType === 'time') {
|
|
354
|
+
const { ticks, unit } = timeTicks(tMin, tMax, 8);
|
|
355
|
+
xTicks = ticks.map((t, i) => ({ pct: xp(t, tMin, tMax), label: timeTickLabel(t, unit, locale, ticks[i - 1]), tier: tierOf(i), anchor: 'middle' as const }));
|
|
356
|
+
} else {
|
|
357
|
+
xTicks = input.x.map((v, i) => ({ pct: xPos(i), label: String(v), tier: tierOf(i), anchor: 'middle' as const }));
|
|
358
|
+
}
|
|
359
|
+
// Labels at the very edges would hang outside the plot: anchor them inward. Lines: at the ends.
|
|
360
|
+
// Narrow bar bands (many categories): the first/last label starts/ends at the plot edge, still
|
|
361
|
+
// under its own band, instead of spilling into the y-axis gutter on small screens.
|
|
362
|
+
for (const t of xTicks) {
|
|
363
|
+
if (type !== 'bar' && t.pct <= 1) t.anchor = 'start';
|
|
364
|
+
if (type !== 'bar' && t.pct >= 99) t.anchor = 'end';
|
|
365
|
+
if (type === 'bar' && t.pct < 5) Object.assign(t, { anchor: 'start', pct: 0 });
|
|
366
|
+
if (type === 'bar' && t.pct > 95) Object.assign(t, { anchor: 'end', pct: 100 });
|
|
367
|
+
}
|
|
368
|
+
const maxChars = Math.max(1, ...xTicks.map((t) => t.label.length));
|
|
369
|
+
const labelPx = maxChars * 7 + 14;
|
|
370
|
+
const stepFor = (w: number) => [1, 2, 4, 8, 16].find((k) => Math.ceil(xTicks.length / k) * labelPx <= w) ?? 16;
|
|
371
|
+
const xSteps = { xs: stepFor(PLOT_WIDTH.xs), sm: stepFor(PLOT_WIDTH.sm), md: stepFor(PLOT_WIDTH.md), lg: stepFor(PLOT_WIDTH.lg) };
|
|
372
|
+
|
|
373
|
+
// ---------- hits (tooltip bands) ----------
|
|
374
|
+
const hits: HitModel[] = [];
|
|
375
|
+
for (let k = 0; k < n; k++) {
|
|
376
|
+
const x = xPos(k);
|
|
377
|
+
let fromPct: number;
|
|
378
|
+
let toPct: number;
|
|
379
|
+
if (type === 'bar') {
|
|
380
|
+
fromPct = r2(k * band);
|
|
381
|
+
toPct = r2((k + 1) * band);
|
|
382
|
+
} else {
|
|
383
|
+
const prev = k > 0 ? xPos(k - 1) : x;
|
|
384
|
+
const next = k < n - 1 ? xPos(k + 1) : x;
|
|
385
|
+
fromPct = k === 0 ? 0 : r2((prev + x) / 2);
|
|
386
|
+
toPct = k === n - 1 ? 100 : r2((x + next) / 2);
|
|
387
|
+
}
|
|
388
|
+
const rows = models
|
|
389
|
+
.map((m) => ({ series: m.id, label: m.label, slot: m.slot, display: fmtY(series.find((s) => s.id === m.id)!.values[k]), yPct: m.points[k]?.yPct }))
|
|
390
|
+
.filter((r) => r.display !== '—' || type !== 'bar');
|
|
391
|
+
const vals = series.map((s) => s.values[k]).filter((v): v is number => v !== null);
|
|
392
|
+
hits.push({ index: k, fromPct, toPct, xPct: x, label: xLabelFull(k), rows, total: stacked && vals.length > 1 ? fmtY(vals.reduce((a, b) => a + b, 0)) : undefined });
|
|
393
|
+
}
|
|
394
|
+
|
|
395
|
+
// ---------- summary ----------
|
|
396
|
+
const kind = type === 'bar' ? (stacked ? 'Stacked bar chart' : 'Bar chart') : type === 'area' ? (stacked ? 'Stacked area chart' : 'Area chart') : 'Line chart';
|
|
397
|
+
const names = series.map((s) => s.label);
|
|
398
|
+
const list = names.length <= 1 ? names.join('') : `${names.slice(0, -1).join(', ')} and ${names.at(-1)}`;
|
|
399
|
+
const range = n ? `${xLabelFull(0)} to ${xLabelFull(n - 1)}` : '';
|
|
400
|
+
const parts = [`${kind}${input.subject ? ` of ${input.subject}` : list ? ` of ${list}` : ''}${n > 1 ? `, ${range}` : ''}.`];
|
|
401
|
+
for (const s of series.slice(0, 4)) {
|
|
402
|
+
const idx = s.values.map((v, k) => [v, k] as const).filter(([v]) => v !== null) as Array<readonly [number, number]>;
|
|
403
|
+
if (!idx.length) continue;
|
|
404
|
+
const max = idx.reduce((a, b) => (b[0] > a[0] ? b : a));
|
|
405
|
+
const min = idx.reduce((a, b) => (b[0] < a[0] ? b : a));
|
|
406
|
+
const lastP = idx[idx.length - 1];
|
|
407
|
+
const who = series.length > 1 ? `${s.label}: ` : '';
|
|
408
|
+
const cap = (t: string) => (who ? t : t.charAt(0).toUpperCase() + t.slice(1));
|
|
409
|
+
parts.push(
|
|
410
|
+
type === 'bar'
|
|
411
|
+
? `${who}${cap('highest')} ${xLabelFull(max[1])} (${fmtY(max[0])}), lowest ${xLabelFull(min[1])} (${fmtY(min[0])}).`
|
|
412
|
+
: `${who}${cap('from')} ${fmtY(idx[0][0])} to ${fmtY(lastP[0])}; high ${fmtY(max[0])} (${xLabelFull(max[1])}), low ${fmtY(min[0])} (${xLabelFull(min[1])}).`,
|
|
413
|
+
);
|
|
414
|
+
}
|
|
415
|
+
if (series.length > 4) parts.push(`${series.length - 4} more series in the data table.`);
|
|
416
|
+
|
|
417
|
+
// ---------- table ----------
|
|
418
|
+
const xHeader = input.xTitle ?? (xType === 'time' ? 'Date' : 'Category');
|
|
419
|
+
const headers = [xHeader, ...series.map((s) => s.label)];
|
|
420
|
+
const rows = Array.from({ length: n }, (_, k) => [xLabelFull(k), ...series.map((s) => fmtY(s.values[k]))]);
|
|
421
|
+
const csvCell = (v: string) => (/[",\n]/.test(v) ? `"${v.replace(/"/g, '""')}"` : v);
|
|
422
|
+
const rawX = (k: number) => (xType === 'time' ? new Date(times[k]!).toISOString().slice(0, granularity === 'day' ? 10 : granularity === 'month' ? 7 : 4) : String(input.x[k]));
|
|
423
|
+
const csv = [headers.map(csvCell).join(','), ...Array.from({ length: n }, (_, k) => [csvCell(rawX(k)), ...series.map((s) => (s.values[k] === null ? '' : String(s.values[k])))].join(','))].join('\n');
|
|
424
|
+
|
|
425
|
+
// Gutter width in `ch` (digit widths): wide glyphs (%, letters, minus) count for more, separators less.
|
|
426
|
+
const glyphCh = (c: string) => (/[0-9 ]/.test(c) ? 1 : /[.,:'’]/.test(c) ? 0.45 : c === '%' ? 1.6 : /[A-ZÀ-Ý$€£¥−\-+]/.test(c) ? 1.25 : 1.1);
|
|
427
|
+
const yLabelCh = Math.min(14, Math.max(2, ...yTicks.map((t) => Math.ceil([...t.label].reduce((a, c) => a + glyphCh(c), 0)))));
|
|
428
|
+
return {
|
|
429
|
+
id,
|
|
430
|
+
type,
|
|
431
|
+
stacked,
|
|
432
|
+
xType,
|
|
433
|
+
xTitle: input.xTitle,
|
|
434
|
+
yTitle: input.yTitle,
|
|
435
|
+
locale,
|
|
436
|
+
yMin,
|
|
437
|
+
yMax,
|
|
438
|
+
baselinePct,
|
|
439
|
+
xTicks,
|
|
440
|
+
xSteps,
|
|
441
|
+
yTicks,
|
|
442
|
+
yLabelCh,
|
|
443
|
+
series: models,
|
|
444
|
+
barPct,
|
|
445
|
+
hits,
|
|
446
|
+
summary: parts.join(' '),
|
|
447
|
+
table: { headers, rows, csv },
|
|
448
|
+
warnings,
|
|
449
|
+
};
|
|
450
|
+
}
|
|
@@ -0,0 +1,219 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* HTML for every chart piece, as strings. The .astro components render these with set:html, so
|
|
3
|
+
* the markup tested in the browser is exactly the markup that ships. All text is escaped.
|
|
4
|
+
*
|
|
5
|
+
* Responsive without JavaScript and CSP-safe: positions are SVG percentage attributes (allowed
|
|
6
|
+
* under a strict CSP, unlike style attributes); lines live in a nested 0–1000 viewBox with
|
|
7
|
+
* non-scaling strokes; text stays at its real size. Bar thickness, grouping and label density
|
|
8
|
+
* come from generated CSS keyed by data attributes.
|
|
9
|
+
*/
|
|
10
|
+
import type { ChartModel, HitModel } from './chart';
|
|
11
|
+
import type { SparklineModel } from './sparkline';
|
|
12
|
+
|
|
13
|
+
export const esc = (v: unknown) =>
|
|
14
|
+
String(v ?? '').replace(/[&<>"']/g, (c) => ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' })[c]!);
|
|
15
|
+
const pct = (v: number) => `${Math.round(v * 100) / 100}%`;
|
|
16
|
+
const attrs = (a: Record<string, string | number | boolean | undefined>) =>
|
|
17
|
+
Object.entries(a)
|
|
18
|
+
.filter(([, v]) => v !== undefined && v !== false)
|
|
19
|
+
.map(([k, v]) => (v === true ? ` ${k}` : ` ${k}="${esc(v)}"`))
|
|
20
|
+
.join('');
|
|
21
|
+
|
|
22
|
+
// ---------------- Axes ----------------
|
|
23
|
+
|
|
24
|
+
export interface AxisOptions {
|
|
25
|
+
/** Draw gridlines across the plot (y: horizontal lines at each tick; x: vertical lines). */
|
|
26
|
+
grid?: boolean;
|
|
27
|
+
/** Axis title (defaults to the chart's xTitle / yTitle). */
|
|
28
|
+
title?: string;
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
/** Y axis: tick labels in their own column, optional title above it, and horizontal gridlines. */
|
|
32
|
+
export function renderYAxis(m: ChartModel, o: AxisOptions = {}): string {
|
|
33
|
+
const grid = o.grid ?? true;
|
|
34
|
+
const title = o.title ?? m.yTitle;
|
|
35
|
+
const labels = m.yTicks.map((t) => `<text x="100%" dx="-8" y="${pct(t.pct)}" dy="0.32em">${esc(t.label)}</text>`).join('');
|
|
36
|
+
const lines = grid ? m.yTicks.map((t) => `<line x1="0" x2="100%" y1="${pct(t.pct)}" y2="${pct(t.pct)}"></line>`).join('') : '';
|
|
37
|
+
return (
|
|
38
|
+
(title ? `<p class="sinn-chart__axis-title" data-axis="y" aria-hidden="true">${esc(title)}</p>` : '') +
|
|
39
|
+
`<div class="sinn-chart__y-axis" aria-hidden="true"><svg class="sinn-chart__ticks" width="100%" height="100%">${labels}</svg></div>` +
|
|
40
|
+
(grid ? `<svg class="sinn-chart__layer sinn-chart__grid" aria-hidden="true" width="100%" height="100%">${lines}</svg>` : '')
|
|
41
|
+
);
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
/** X axis: the baseline, tick labels thinned by container width, optional vertical gridlines. */
|
|
45
|
+
export function renderXAxis(m: ChartModel, o: AxisOptions = {}): string {
|
|
46
|
+
const title = o.title ?? m.xTitle;
|
|
47
|
+
const labels = m.xTicks
|
|
48
|
+
.map((t) => `<text${attrs({ x: pct(t.pct), y: '1.1em', 'text-anchor': t.anchor, 'data-tier': t.tier })}>${esc(t.label)}</text>`)
|
|
49
|
+
.join('');
|
|
50
|
+
const vlines = o.grid ? m.xTicks.map((t) => `<line${attrs({ x1: pct(t.pct), x2: pct(t.pct), y1: '0', y2: '100%', 'data-tier': t.tier })}></line>`).join('') : '';
|
|
51
|
+
const steps = attrs({ 'data-step-xs': m.xSteps.xs, 'data-step-sm': m.xSteps.sm, 'data-step-md': m.xSteps.md, 'data-step-lg': m.xSteps.lg });
|
|
52
|
+
const base = `<line class="sinn-chart__baseline" x1="0" x2="100%" y1="${pct(m.baselinePct)}" y2="${pct(m.baselinePct)}"></line>`;
|
|
53
|
+
return (
|
|
54
|
+
`<svg class="sinn-chart__layer sinn-chart__grid" data-axis="x" aria-hidden="true" width="100%" height="100%"${steps}>${vlines}${base}</svg>` +
|
|
55
|
+
`<div class="sinn-chart__x-axis" aria-hidden="true"${steps}><svg class="sinn-chart__ticks" width="100%" height="100%">${labels}</svg></div>` +
|
|
56
|
+
(title ? `<p class="sinn-chart__axis-title" data-axis="x" aria-hidden="true">${esc(title)}</p>` : '')
|
|
57
|
+
);
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
// ---------------- Marks ----------------
|
|
61
|
+
|
|
62
|
+
export function renderSeries(m: ChartModel, o: { endDots?: boolean } = {}): string {
|
|
63
|
+
const endDots = o.endDots ?? m.type !== 'bar';
|
|
64
|
+
let out = '';
|
|
65
|
+
if (m.type === 'bar') {
|
|
66
|
+
for (const s of m.series) {
|
|
67
|
+
for (const b of s.bars) {
|
|
68
|
+
const h = b.bottomPct - b.topPct;
|
|
69
|
+
const a = { 'data-series': s.id, 'data-slot': s.muted ? 'muted' : s.slot, 'data-index': b.index, 'data-offset': b.offset };
|
|
70
|
+
// One square rect; CSS clips a 4px round onto the data end only (clip-path inset … round), so
|
|
71
|
+
// the baseline end stays square with no second shape and no seam. Without clip-path support
|
|
72
|
+
// the bar is simply square.
|
|
73
|
+
out += `<rect class="sinn-chart__bar"${attrs({ ...a, 'data-round': b.rounded === 'none' ? undefined : b.rounded, x: pct(b.xPct), y: pct(b.topPct), height: pct(h), width: 24 })}></rect>`;
|
|
74
|
+
}
|
|
75
|
+
}
|
|
76
|
+
if (m.stacked) {
|
|
77
|
+
// 2px surface gaps at every inner segment edge (the gap, not a stroke, separates them).
|
|
78
|
+
const byIndex = new Map<number, Array<{ topPct: number; bottomPct: number; xPct: number }>>();
|
|
79
|
+
for (const s of m.series) for (const b of s.bars) byIndex.set(b.index, [...(byIndex.get(b.index) ?? []), b]);
|
|
80
|
+
for (const [index, segs] of byIndex) {
|
|
81
|
+
const outerTop = Math.min(...segs.map((b) => b.topPct));
|
|
82
|
+
const outerBottom = Math.max(...segs.map((b) => b.bottomPct));
|
|
83
|
+
const edges = new Set<number>();
|
|
84
|
+
for (const b of segs) for (const e of [b.topPct, b.bottomPct]) if (Math.abs(e - m.baselinePct) > 0.01 && Math.abs(e - outerTop) > 0.01 && Math.abs(e - outerBottom) > 0.01) edges.add(Math.round(e * 100) / 100);
|
|
85
|
+
for (const e of edges) out += `<rect class="sinn-chart__gap"${attrs({ 'data-index': index, 'data-offset': '0', x: pct(segs[0].xPct), y: pct(e), height: 2, width: 24 })}></rect>`;
|
|
86
|
+
}
|
|
87
|
+
}
|
|
88
|
+
} else {
|
|
89
|
+
const areas = m.type === 'area' ? m.series.map((s) => `<path class="sinn-chart__area"${attrs({ 'data-series': s.id, 'data-slot': s.muted ? 'muted' : s.slot, d: s.areaPath })}></path>`).join('') : '';
|
|
90
|
+
const lines = m.series.map((s) => `<path class="sinn-chart__line"${attrs({ 'data-series': s.id, 'data-slot': s.muted ? 'muted' : s.slot, d: s.linePath, 'vector-effect': 'non-scaling-stroke' })}></path>`).join('');
|
|
91
|
+
out += `<svg class="sinn-chart__paths" viewBox="0 0 1000 1000" preserveAspectRatio="none" width="100%" height="100%" overflow="visible">${areas}${lines}</svg>`;
|
|
92
|
+
// Isolated points (a value between two gaps) would be invisible as a line: draw a dot.
|
|
93
|
+
for (const s of m.series)
|
|
94
|
+
s.points.forEach((p, i) => {
|
|
95
|
+
if (p && !s.points[i - 1] && !s.points[i + 1] && !(endDots && s.last === p))
|
|
96
|
+
out += `<circle class="sinn-chart__dot"${attrs({ 'data-series': s.id, 'data-slot': s.muted ? 'muted' : s.slot, cx: pct(p.xPct), cy: pct(p.yPct), r: 4 })}></circle>`;
|
|
97
|
+
});
|
|
98
|
+
if (endDots)
|
|
99
|
+
for (const s of m.series)
|
|
100
|
+
if (s.last)
|
|
101
|
+
out += `<circle class="sinn-chart__dot sinn-chart__end"${attrs({ 'data-series': s.id, 'data-slot': s.muted ? 'muted' : s.slot, cx: pct(s.last.xPct), cy: pct(s.last.yPct), r: 4 })}></circle>`;
|
|
102
|
+
}
|
|
103
|
+
return `<svg class="sinn-chart__layer sinn-chart__marks" aria-hidden="true" width="100%" height="100%" overflow="visible"${attrs({ 'data-type': m.type, 'data-stacked': m.stacked || undefined })}>${out}</svg>`;
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
// ---------------- Tooltip / interaction layer ----------------
|
|
107
|
+
|
|
108
|
+
export interface TooltipOptions {
|
|
109
|
+
/** Accessible name of the interactive layer. */
|
|
110
|
+
label?: string;
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
/** Compact hit data for the script: [from, to, x, label, rows[[series, display, yPct]], total]. */
|
|
114
|
+
function hitData(h: HitModel) {
|
|
115
|
+
return [h.fromPct, h.toPct, h.xPct, h.label, h.rows.map((r) => [r.series, r.display, r.yPct ?? null]), h.total ?? null];
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
export function renderTooltip(m: ChartModel, o: TooltipOptions = {}): string {
|
|
119
|
+
const names = Object.fromEntries(m.series.map((s) => [s.id, [s.label, s.muted ? 'muted' : s.slot]]));
|
|
120
|
+
const data = JSON.stringify({ type: m.type, stacked: m.stacked, series: names, hits: m.hits.map(hitData) });
|
|
121
|
+
const dots = m.type === 'bar' ? '' : m.series.map((s) => `<circle class="sinn-chart__hover-dot"${attrs({ 'data-series': s.id, 'data-slot': s.muted ? 'muted' : s.slot, cx: '0', cy: '0', r: 4 })}></circle>`).join('');
|
|
122
|
+
const label = o.label ?? 'Chart values. Use the left and right arrow keys to move between points.';
|
|
123
|
+
return (
|
|
124
|
+
`<div class="sinn-chart__layer sinn-chart__interact" tabindex="0" role="group" aria-roledescription="interactive chart"${attrs({ 'aria-label': label, 'data-sinn-chart-interact': '', 'data-chart': data })}>` +
|
|
125
|
+
`<svg class="sinn-chart__hover" aria-hidden="true" width="100%" height="100%" overflow="visible" visibility="hidden">` +
|
|
126
|
+
(m.type === 'bar' ? `<rect class="sinn-chart__band" x="0" y="0" width="0" height="100%"></rect>` : `<line class="sinn-chart__crosshair" x1="0" x2="0" y1="0" y2="100%"></line>`) +
|
|
127
|
+
dots +
|
|
128
|
+
`</svg>` +
|
|
129
|
+
`<div class="sinn-chart-tooltip" aria-hidden="true" hidden><p class="sinn-chart-tooltip__title"></p><ul class="sinn-chart-tooltip__rows" role="list"></ul><p class="sinn-chart-tooltip__total" hidden></p></div>` +
|
|
130
|
+
`<p class="sinn-sr-only" aria-live="polite" data-sinn-chart-live></p>` +
|
|
131
|
+
`</div>`
|
|
132
|
+
);
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
// ---------------- Legend ----------------
|
|
136
|
+
|
|
137
|
+
export interface LegendOptions {
|
|
138
|
+
/** Buttons that show/hide each series (needs the chart script). Default true. */
|
|
139
|
+
toggle?: boolean;
|
|
140
|
+
/** Render even for a single series (by default one series needs no legend: the title names it). */
|
|
141
|
+
force?: boolean;
|
|
142
|
+
/** Group label for assistive tech. */
|
|
143
|
+
label?: string;
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
export function renderLegend(m: ChartModel, o: LegendOptions = {}): string {
|
|
147
|
+
if (m.series.length < 2 && !o.force) return '';
|
|
148
|
+
const toggle = o.toggle ?? true;
|
|
149
|
+
const key = m.type === 'line' ? 'line' : 'rect';
|
|
150
|
+
const items = m.series
|
|
151
|
+
.map((s) => {
|
|
152
|
+
const swatch = `<span class="sinn-chart-legend__key"${attrs({ 'data-key': key, 'data-slot': s.muted ? 'muted' : s.slot, 'aria-hidden': 'true' })}></span>`;
|
|
153
|
+
const body = `${swatch}<span class="sinn-chart-legend__label">${esc(s.label)}</span>`;
|
|
154
|
+
return toggle
|
|
155
|
+
? `<li><button type="button" class="sinn-chart-legend__item"${attrs({ 'aria-pressed': 'true', 'data-sinn-legend-toggle': s.id })}>${body}</button></li>`
|
|
156
|
+
: `<li class="sinn-chart-legend__item">${body}</li>`;
|
|
157
|
+
})
|
|
158
|
+
.join('');
|
|
159
|
+
const label = o.label ?? (toggle ? 'Series. Press a series to show or hide it.' : 'Series');
|
|
160
|
+
return (
|
|
161
|
+
`<div class="sinn-chart-legend"${attrs({ role: 'group', 'aria-label': label, 'data-toggle': toggle || undefined })}>` +
|
|
162
|
+
`<ul class="sinn-chart-legend__list" role="list">${items}</ul>` +
|
|
163
|
+
(toggle ? `<button type="button" class="sinn-chart-legend__reset" data-sinn-legend-reset hidden>Show all</button><p class="sinn-sr-only" aria-live="polite" data-sinn-legend-live></p>` : '') +
|
|
164
|
+
`</div>`
|
|
165
|
+
);
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
// ---------------- Table ----------------
|
|
169
|
+
|
|
170
|
+
export interface TableOptions {
|
|
171
|
+
caption?: string;
|
|
172
|
+
/** Offer a CSV download of the raw values (file name without extension). */
|
|
173
|
+
download?: string | false;
|
|
174
|
+
/** Hide the caption visually (the chart title already shows). */
|
|
175
|
+
hideCaption?: boolean;
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
export function renderTable(m: ChartModel, o: TableOptions = {}): string {
|
|
179
|
+
const head = m.table.headers.map((h, i) => `<th scope="col"${i ? ' data-numeric' : ''}>${esc(h)}</th>`).join('');
|
|
180
|
+
const body = m.table.rows.map((r) => `<tr>${r.map((c, i) => (i ? `<td data-numeric>${esc(c)}</td>` : `<th scope="row">${esc(c)}</th>`)).join('')}</tr>`).join('');
|
|
181
|
+
const caption = o.caption ? `<caption${o.hideCaption ? ' class="sinn-sr-only"' : ''}>${esc(o.caption)}</caption>` : '';
|
|
182
|
+
const dl = o.download
|
|
183
|
+
? `<a class="sinn-chart-table__download" download="${esc(o.download)}.csv" href="data:text/csv;charset=utf-8,${encodeURIComponent(`${m.table.csv}`)}">Download CSV</a>`
|
|
184
|
+
: '';
|
|
185
|
+
return `<div class="sinn-chart-table"><div class="sinn-chart-table__scroll" tabindex="0" role="region"${attrs({ 'aria-label': o.caption ? `${o.caption} (table)` : 'Chart data (table)' })}><table>${caption}<thead><tr>${head}</tr></thead><tbody>${body}</tbody></table></div>${dl}</div>`;
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
// ---------------- Sparkline ----------------
|
|
189
|
+
|
|
190
|
+
export interface SparklineRenderOptions {
|
|
191
|
+
interactive?: boolean;
|
|
192
|
+
/** Slot color for the line (default: the de-emphasis gray, with the accent highlight dot). */
|
|
193
|
+
slot?: number | 'muted';
|
|
194
|
+
}
|
|
195
|
+
|
|
196
|
+
export function renderSparkline(s: SparklineModel, o: SparklineRenderOptions = {}): string {
|
|
197
|
+
const slot = o.slot ?? 'muted';
|
|
198
|
+
let marks = '';
|
|
199
|
+
if (s.referencePct !== undefined) marks += `<line class="sinn-spark__ref" x1="0" x2="100%" y1="${pct(s.referencePct)}" y2="${pct(s.referencePct)}"></line>`;
|
|
200
|
+
if (s.type === 'bar') {
|
|
201
|
+
for (const b of s.bars) marks += `<rect class="sinn-spark__bar"${attrs({ x: pct(b.xPct - b.widthPct / 2), width: pct(b.widthPct), y: pct(b.topPct), height: pct(b.heightPct), 'data-highlight': b.highlight || undefined, rx: 1 })}></rect>`;
|
|
202
|
+
} else {
|
|
203
|
+
marks +=
|
|
204
|
+
`<svg class="sinn-spark__paths" viewBox="0 0 1000 1000" preserveAspectRatio="none" width="100%" height="100%" overflow="visible">` +
|
|
205
|
+
(s.type === 'area' ? `<path class="sinn-spark__area" d="${s.areaPath}"></path>` : '') +
|
|
206
|
+
`<path class="sinn-spark__line" vector-effect="non-scaling-stroke" d="${s.linePath}"></path></svg>`;
|
|
207
|
+
if (s.highlight) marks += `<circle class="sinn-spark__dot" cx="${pct(s.highlight.xPct)}" cy="${pct(s.highlight.yPct)}" r="3.5"></circle>`;
|
|
208
|
+
}
|
|
209
|
+
const interactive = o.interactive && s.points.some(Boolean);
|
|
210
|
+
const data = interactive ? JSON.stringify(s.points.map((p) => (p ? [p.xPct, p.yPct, p.display, p.label] : null))) : undefined;
|
|
211
|
+
const hover = interactive
|
|
212
|
+
? `<g class="sinn-spark__hover" visibility="hidden"><line class="sinn-spark__crosshair" x1="0" x2="0" y1="0" y2="100%"></line><circle class="sinn-spark__hover-dot" cx="0" cy="0" r="3.5"></circle></g>`
|
|
213
|
+
: '';
|
|
214
|
+
return (
|
|
215
|
+
`<svg class="sinn-spark__svg"${attrs({ width: '100%', height: '100%', overflow: 'visible', 'aria-hidden': 'true', 'data-slot': slot })}>${marks}${hover}</svg>` +
|
|
216
|
+
(interactive ? `<span class="sinn-chart-tooltip sinn-spark__tip" aria-hidden="true" hidden><strong></strong> <span></span></span>` : '') +
|
|
217
|
+
(data ? `<span hidden data-sinn-spark-data="${esc(data)}"></span>` : '')
|
|
218
|
+
);
|
|
219
|
+
}
|