@stacksjs/components 0.2.991 → 0.2.997

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.
Files changed (93) hide show
  1. package/dist/ApiOperation-369y1zgt.stx +114 -0
  2. package/dist/ApiReference-ww45jj32.stx +92 -0
  3. package/dist/ApiSchema-dsx4tsv4.stx +47 -0
  4. package/dist/AreaChart-8fy34adp.stx +77 -0
  5. package/dist/BarChart-4xdrjhhn.stx +77 -0
  6. package/dist/{Combobox-9n04ec5w.stx → Combobox-fgbpxbty.stx} +174 -5
  7. package/dist/ComboboxOptions-sfkc98a9.stx +36 -0
  8. package/dist/{CommandPalette-cj6pe5ph.stx → CommandPalette-sf03s7b2.stx} +3 -1
  9. package/dist/LineChart-ctebkkm8.stx +77 -0
  10. package/dist/{Notification-ke5vw4k8.stx → Notification-1pvt347q.stx} +11 -3
  11. package/dist/{Popover-jjt7p7sn.stx → Popover-gntg33xd.stx} +1 -1
  12. package/dist/PricingPlan-h7jt2696.stx +67 -0
  13. package/dist/PricingTable-v3vdn6av.stx +149 -0
  14. package/dist/SecretField-q2xgth94.stx +219 -0
  15. package/dist/{Select-36s22z6d.stx → Select-yhmtvqcx.stx} +7 -4
  16. package/dist/Sparkline-gp859n4h.stx +29 -0
  17. package/dist/StatCard-gff0yx6b.stx +93 -0
  18. package/dist/StatGroup-e0d5dmt7.stx +17 -0
  19. package/dist/components/CodeBlock.d.ts +4 -1
  20. package/dist/components/CodeGroup.d.ts +34 -0
  21. package/dist/components/code-group.d.ts +19 -0
  22. package/dist/components/index.d.ts +2 -0
  23. package/dist/index.d.ts +13 -0
  24. package/dist/index.js +25 -22
  25. package/dist/ui/api-reference/ApiOperation.d.ts +17 -0
  26. package/dist/ui/api-reference/ApiReference.d.ts +28 -0
  27. package/dist/ui/api-reference/ApiSchema.d.ts +17 -0
  28. package/dist/ui/api-reference/index.d.ts +30 -0
  29. package/dist/ui/api-reference/openapi.d.ts +137 -0
  30. package/dist/ui/chart/AreaChart.d.ts +33 -0
  31. package/dist/ui/chart/BarChart.d.ts +33 -0
  32. package/dist/ui/chart/LineChart.d.ts +33 -0
  33. package/dist/ui/chart/Sparkline.d.ts +19 -0
  34. package/dist/ui/chart/core.d.ts +111 -0
  35. package/dist/ui/chart/index.d.ts +51 -0
  36. package/dist/ui/chart/interaction.d.ts +11 -0
  37. package/dist/ui/combobox/Combobox.d.ts +10 -1
  38. package/dist/ui/combobox/ComboboxOptions.d.ts +6 -0
  39. package/dist/ui/combobox/index.d.ts +7 -0
  40. package/dist/ui/command-palette/CommandPalette.d.ts +2 -0
  41. package/dist/ui/input/SecretField.d.ts +56 -0
  42. package/dist/ui/input/index.d.ts +21 -0
  43. package/dist/ui/notification/Notification.d.ts +2 -0
  44. package/dist/ui/pricing/PricingPlan.d.ts +21 -0
  45. package/dist/ui/pricing/PricingTable.d.ts +50 -0
  46. package/dist/ui/pricing/index.d.ts +38 -0
  47. package/dist/ui/pricing/pricing.d.ts +64 -0
  48. package/dist/ui/select/Select.d.ts +2 -0
  49. package/dist/ui/stat/StatCard.d.ts +42 -0
  50. package/dist/ui/stat/StatGroup.d.ts +12 -0
  51. package/dist/ui/stat/format.d.ts +37 -0
  52. package/dist/ui/stat/index.d.ts +23 -0
  53. package/package.json +3 -3
  54. package/src/components/CodeBlock.stx +4 -1
  55. package/src/components/CodeGroup.stx +217 -0
  56. package/src/components/code-group.ts +57 -0
  57. package/src/components/index.ts +2 -0
  58. package/src/index.ts +18 -0
  59. package/src/ui/api-reference/ApiOperation.stx +114 -0
  60. package/src/ui/api-reference/ApiReference.stx +92 -0
  61. package/src/ui/api-reference/ApiSchema.stx +47 -0
  62. package/src/ui/api-reference/README.md +44 -0
  63. package/src/ui/api-reference/index.ts +35 -0
  64. package/src/ui/api-reference/openapi.ts +825 -0
  65. package/src/ui/chart/AreaChart.stx +77 -0
  66. package/src/ui/chart/BarChart.stx +77 -0
  67. package/src/ui/chart/LineChart.stx +77 -0
  68. package/src/ui/chart/README.md +97 -0
  69. package/src/ui/chart/Sparkline.stx +29 -0
  70. package/src/ui/chart/core.ts +730 -0
  71. package/src/ui/chart/index.ts +71 -0
  72. package/src/ui/chart/interaction.ts +175 -0
  73. package/src/ui/combobox/Combobox.stx +174 -5
  74. package/src/ui/combobox/ComboboxOptions.stx +20 -0
  75. package/src/ui/combobox/README.md +41 -0
  76. package/src/ui/combobox/index.ts +13 -0
  77. package/src/ui/command-palette/CommandPalette.stx +3 -1
  78. package/src/ui/input/SecretField.stx +219 -0
  79. package/src/ui/input/index.ts +32 -0
  80. package/src/ui/notification/Notification.stx +11 -3
  81. package/src/ui/popover/Popover.stx +1 -1
  82. package/src/ui/pricing/PricingPlan.stx +67 -0
  83. package/src/ui/pricing/PricingTable.stx +149 -0
  84. package/src/ui/pricing/README.md +74 -0
  85. package/src/ui/pricing/index.ts +49 -0
  86. package/src/ui/pricing/pricing.ts +177 -0
  87. package/src/ui/select/Select.stx +7 -4
  88. package/src/ui/stat/README.md +60 -0
  89. package/src/ui/stat/StatCard.stx +93 -0
  90. package/src/ui/stat/StatGroup.stx +17 -0
  91. package/src/ui/stat/format.ts +147 -0
  92. package/src/ui/stat/index.ts +38 -0
  93. package/dist/ComboboxOptions-zhr9b6rx.stx +0 -16
@@ -0,0 +1,177 @@
1
+ /**
2
+ * Plan data for `<PricingTable>` and `<PricingPlan>` (stacksjs/stx#2322):
3
+ * normalising plans written the way a billing config writes them, and the
4
+ * Intl formatting of prices, savings and feature values.
5
+ */
6
+
7
+ export type PricingInterval = 'month' | 'year'
8
+
9
+ export interface PricingCta {
10
+ label?: string
11
+ href?: string
12
+ }
13
+
14
+ export interface PricingPlanInput {
15
+ id?: string
16
+ name: string
17
+ description?: string
18
+ /** Price per interval in major units: `{ month: 29, year: 290 }`. `0` is free; `null` or absent is "Custom". */
19
+ prices?: Partial<Record<PricingInterval, number | null>>
20
+ currency?: string
21
+ /** Feature values by key: `true` included, `false` excluded, a number or string is the value shown. */
22
+ features?: Record<string, boolean | number | string | null | undefined>
23
+ /** Short lines for the card; defaults to the included features. */
24
+ highlights?: string[]
25
+ highlighted?: boolean
26
+ /** A badge on a highlighted plan. Default "Most popular". */
27
+ badge?: string
28
+ cta?: PricingCta | string
29
+ }
30
+
31
+ export interface PricingFeatureInput {
32
+ key: string
33
+ label: string
34
+ /** Appended to a number value: `requests`. */
35
+ unit?: string
36
+ }
37
+
38
+ export interface PricingSectionInput {
39
+ section?: string
40
+ items: PricingFeatureInput[]
41
+ }
42
+
43
+ export interface PricedInterval {
44
+ interval: PricingInterval
45
+ /** `$29`, `Free` or `Custom`. */
46
+ amount: string
47
+ /** `/month`, `/year`, or empty for free and custom. */
48
+ per: string
49
+ /** For a yearly price: the monthly equivalent, `$24/month billed yearly`. */
50
+ note: string
51
+ spoken: string
52
+ }
53
+
54
+ export interface FeatureCell {
55
+ kind: 'included' | 'excluded' | 'value'
56
+ text: string
57
+ spoken: string
58
+ }
59
+
60
+ export interface PreparedPlan {
61
+ id: string
62
+ name: string
63
+ description: string
64
+ highlighted: boolean
65
+ badge: string
66
+ current: boolean
67
+ prices: PricedInterval[]
68
+ /** Yearly saving against twelve months, `Save 17%`, or empty. */
69
+ saving: string
70
+ highlights: string[]
71
+ ctaLabel: string
72
+ ctaHref: string
73
+ cells: FeatureCell[][]
74
+ }
75
+
76
+ const INTERVALS: PricingInterval[] = ['month', 'year']
77
+
78
+ function slug(value: string): string {
79
+ return value.toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/^-|-$/g, '') || 'plan'
80
+ }
81
+
82
+ function money(amount: number, currency: string, locale: string): string {
83
+ const whole = Number.isInteger(amount)
84
+ try {
85
+ return new Intl.NumberFormat(locale, { style: 'currency', currency, minimumFractionDigits: whole ? 0 : 2, maximumFractionDigits: 2 }).format(amount)
86
+ }
87
+ catch {
88
+ return new Intl.NumberFormat('en-US', { style: 'currency', currency: 'USD', minimumFractionDigits: whole ? 0 : 2 }).format(amount)
89
+ }
90
+ }
91
+
92
+ /** The yearly saving as a fraction of twelve monthly payments, or 0. */
93
+ export function yearlySaving(prices: PricingPlanInput['prices']): number {
94
+ const month = prices?.month
95
+ const year = prices?.year
96
+ if (typeof month !== 'number' || typeof year !== 'number' || month <= 0 || year <= 0)
97
+ return 0
98
+ const saving = 1 - year / (month * 12)
99
+ return saving > 0.005 ? saving : 0
100
+ }
101
+
102
+ export function formatPrice(plan: PricingPlanInput, interval: PricingInterval, locale = 'en-US'): PricedInterval {
103
+ const currency = (plan.currency || 'USD').toUpperCase()
104
+ const value = plan.prices?.[interval]
105
+ if (value === null || value === undefined || !Number.isFinite(Number(value)))
106
+ return { interval, amount: 'Custom', per: '', note: '', spoken: `${plan.name}: custom pricing` }
107
+ const n = Number(value)
108
+ if (n === 0)
109
+ return { interval, amount: 'Free', per: '', note: '', spoken: `${plan.name}: free` }
110
+ const amount = money(n, currency, locale)
111
+ const note = interval === 'year' ? `${money(Math.round((n / 12) * 100) / 100, currency, locale)}/month billed yearly` : ''
112
+ return { interval, amount, per: `/${interval}`, note, spoken: `${plan.name}: ${amount} per ${interval}` }
113
+ }
114
+
115
+ export function formatFeature(value: unknown, feature: PricingFeatureInput, locale = 'en-US'): FeatureCell {
116
+ if (value === true)
117
+ return { kind: 'included', text: '', spoken: 'Included' }
118
+ if (value === false || value === null || value === undefined || value === '')
119
+ return { kind: 'excluded', text: '', spoken: 'Not included' }
120
+ const text = typeof value === 'number'
121
+ ? `${new Intl.NumberFormat(locale).format(value)}${feature.unit ? ` ${feature.unit}` : ''}`
122
+ : String(value)
123
+ return { kind: 'value', text, spoken: text }
124
+ }
125
+
126
+ /** Sections as given, or one unnamed section of every feature key the plans mention. */
127
+ export function normaliseSections(sections: unknown, plans: PricingPlanInput[]): Array<{ section: string, items: PricingFeatureInput[] }> {
128
+ if (Array.isArray(sections) && sections.length) {
129
+ return sections
130
+ .filter((s): s is PricingSectionInput => !!s && Array.isArray((s as PricingSectionInput).items))
131
+ .map(s => ({ section: s.section || '', items: s.items.filter(i => i && typeof i.key === 'string').map(i => ({ ...i, label: i.label || i.key })) }))
132
+ }
133
+ const keys: string[] = []
134
+ for (const plan of plans) {
135
+ for (const key of Object.keys(plan.features || {})) {
136
+ if (!keys.includes(key))
137
+ keys.push(key)
138
+ }
139
+ }
140
+ return keys.length ? [{ section: '', items: keys.map(key => ({ key, label: key })) }] : []
141
+ }
142
+
143
+ export function preparePlans(plansInput: unknown, sectionsInput: unknown, options: { currentPlan?: string, locale?: string } = {}): { plans: PreparedPlan[], sections: Array<{ section: string, items: PricingFeatureInput[] }>, maxSaving: number } {
144
+ const locale = options.locale || 'en-US'
145
+ const list = (Array.isArray(plansInput) ? plansInput : []).filter((p): p is PricingPlanInput => !!p && typeof p === 'object' && typeof (p as PricingPlanInput).name === 'string')
146
+ const sections = normaliseSections(sectionsInput, list)
147
+ const features = sections.flatMap(s => s.items)
148
+ let maxSaving = 0
149
+ const plans = list.map((plan) => {
150
+ const id = plan.id || slug(plan.name)
151
+ const current = !!options.currentPlan && options.currentPlan === id
152
+ const saving = yearlySaving(plan.prices)
153
+ maxSaving = Math.max(maxSaving, saving)
154
+ const cta = typeof plan.cta === 'string' ? { label: plan.cta } : (plan.cta || {})
155
+ const highlights = Array.isArray(plan.highlights) && plan.highlights.length
156
+ ? plan.highlights.map(String)
157
+ : features
158
+ .map(f => ({ f, cell: formatFeature(plan.features?.[f.key], f, locale) }))
159
+ .filter(({ cell }) => cell.kind !== 'excluded')
160
+ .map(({ f, cell }) => cell.kind === 'value' ? `${f.label}: ${cell.text}` : f.label)
161
+ return {
162
+ id,
163
+ name: plan.name,
164
+ description: plan.description || '',
165
+ highlighted: plan.highlighted === true,
166
+ badge: plan.highlighted ? (plan.badge || 'Most popular') : '',
167
+ current,
168
+ prices: INTERVALS.map(interval => formatPrice(plan, interval, locale)),
169
+ saving: saving ? `Save ${Math.round(saving * 100)}%` : '',
170
+ highlights,
171
+ ctaLabel: current ? 'Current plan' : (cta.label || (plan.prices?.month === null ? 'Contact sales' : 'Get started')),
172
+ ctaHref: current ? '' : (cta.href || ''),
173
+ cells: sections.map(s => s.items.map(f => formatFeature(plan.features?.[f.key], f, locale))),
174
+ }
175
+ })
176
+ return { plans, sections, maxSaving }
177
+ }
@@ -74,9 +74,9 @@ const baseClasses = 'block w-full border-0 rounded-control shadow-sm ring-1 ring
74
74
  export const stateInvalidClasses = 'ring-danger-line text-danger-fg placeholder-danger focus:ring-danger-focus'
75
75
  export const stateValidClasses = 'ring-line-strong text-fg placeholder-fg-soft focus:ring-accent'
76
76
  const stateClasses = error ? stateInvalidClasses : stateValidClasses
77
- const disabledClasses = disabled
78
- ? 'opacity-50 cursor-not-allowed bg-surface'
79
- : 'bg-field cursor-pointer hover:ring-line-hover'
77
+ export const disabledStateClasses = 'opacity-50 cursor-not-allowed bg-surface'
78
+ export const enabledStateClasses = 'bg-field cursor-pointer hover:ring-line-hover'
79
+ const disabledClasses = disabled ? disabledStateClasses : enabledStateClasses
80
80
 
81
81
  export const selectClasses = `${baseClasses} ${sizeClasses[size] || sizeClasses.md} ${stateClasses} ${disabledClasses} ${className}`.trim()
82
82
  export const labelClasses = `block text-sm font-medium leading-6 ${error ? 'text-danger' : 'text-fg'}`.trim()
@@ -172,6 +172,7 @@ const nativeItems = derived(() => {
172
172
  })
173
173
 
174
174
  function onChange(event) {
175
+ if (isDisabled()) return
175
176
  selectedValue.set(event.target.value)
176
177
  emit('change', selectedValue())
177
178
  }
@@ -231,6 +232,7 @@ defineExpose({ value: selectedValue, options: optionList })
231
232
  class="stx-mac-popup-select {{ className }}"
232
233
  :value="selectedValue()"
233
234
  @if(disabled)disabled@endif
235
+ :disabled="isDisabled()"
234
236
  @if(required)required@endif
235
237
  @change="onChange($event)"
236
238
  aria-invalid="{{ error ? 'true' : 'false' }}"
@@ -289,11 +291,12 @@ defineExpose({ value: selectedValue, options: optionList })
289
291
  class="{{ selectClasses }}"
290
292
  :value="selectedValue()"
291
293
  @if(disabled)disabled@endif
294
+ :disabled="isDisabled()"
292
295
  @if(required)required@endif
293
296
  @change="onChange($event)"
294
297
  aria-invalid="{{ error ? 'true' : 'false' }}"
295
298
  :aria-invalid="isError() ? 'true' : 'false'"
296
- :class="{ '{{ stateInvalidClasses }}': isError(), '{{ stateValidClasses }}': !isError() }"
299
+ :class="{ '{{ stateInvalidClasses }}': isError(), '{{ stateValidClasses }}': !isError(), '{{ disabledStateClasses }}': isDisabled(), '{{ enabledStateClasses }}': !isDisabled() }"
297
300
  @if(helperText)aria-describedby="{{ helperId }}"@endif
298
301
  >
299
302
  @if(placeholder)
@@ -0,0 +1,60 @@
1
+ # Stat
2
+
3
+ Headline numbers for a dashboard: `<StatCard>` shows one value with its label, an optional change indicator and a loading skeleton; `<StatGroup>` lays cards out in a responsive grid.
4
+
5
+ ## Usage
6
+
7
+ ```stx
8
+ <StatGroup label="Usage this month">
9
+ <StatCard label="Requests" :value="1284330" :change="0.125" changeLabel="vs last month" href="/usage" />
10
+ <StatCard label="Sessions" :value="48210" :change="-0.031" changeLabel="vs last month" />
11
+ <StatCard label="Error rate" :value="0.0042" format="percent" :change="-0.2" trend="down-good" />
12
+ <StatCard label="p95 latency" :value="182" format="duration" :change="0.04" trend="down-good" :series="[170, 175, 168, 182]" />
13
+ </StatGroup>
14
+
15
+ <StatCard label="Spend" :value="spend" format="currency" unit="EUR" :loading="spend === null" />
16
+ ```
17
+
18
+ ## Props
19
+
20
+ ### StatCard
21
+ | Prop | Type | Default | Description |
22
+ |------|------|---------|-------------|
23
+ | `label` | `string` | - | What the number is |
24
+ | `value` | `number` | - | The number; a missing one renders as `—` |
25
+ | `format` | `'number' \| 'percent' \| 'duration' \| 'bytes' \| 'currency'` | `'number'` | How to format `value` |
26
+ | `unit` | `string` | - | Appended to a `number` (`req/s`); the ISO currency for `currency` (default `USD`) |
27
+ | `locale` | `string` | `'en-US'` | Locale for `Intl.NumberFormat` |
28
+ | `change` | `number` | - | Relative change as a fraction: `0.125` is +12.5% |
29
+ | `changeLabel` | `string` | - | What the change compares against, e.g. `vs last week` |
30
+ | `trend` | `'up-good' \| 'down-good' \| 'neutral'` | `'up-good'` | Which direction is good news (colour only) |
31
+ | `loading` | `boolean` | `false` | Render a skeleton with the loaded card's dimensions |
32
+ | `series` | `number[]` | - | Recent values, oldest first, drawn as a `Sparkline` beside the value (coloured by the change's tone) |
33
+ | `href` | `string` | - | Make the whole card a link |
34
+ | `className` | `string` | `''` | Additional classes |
35
+
36
+ ### StatGroup
37
+ | Prop | Type | Default | Description |
38
+ |------|------|---------|-------------|
39
+ | `columns` | `number` | `4` | Columns from the `lg` breakpoint (1 to 6); one column on phones, two from `sm` |
40
+ | `label` | `string` | - | Accessible name for the group |
41
+ | `className` | `string` | `''` | Additional classes |
42
+
43
+ ## Formats
44
+
45
+ | `format` | Input | Shown | Exact (tooltip) |
46
+ |---|---|---|---|
47
+ | `number` | `12345` | `12.3K` | `12,345` |
48
+ | `percent` | `0.0042` (a fraction) | `0.42%` | `0.42%` |
49
+ | `duration` | `1234` (milliseconds) | `1.2 s` | `1,234 ms` |
50
+ | `bytes` | `1536` | `1.5 KB` (SI units) | `1,536 bytes` |
51
+ | `currency` | `12345.5` | `$12.3K` | `$12,345.50` |
52
+
53
+ `formatStat(value, format, { locale, unit })` and `formatChange(change, trend)` are exported for use outside the card.
54
+
55
+ ## Accessibility
56
+
57
+ - The card reads as one phrase, "Requests: 12,345, up 12.5% vs last month", from a visually hidden span; the visible fragments are `aria-hidden` so nothing is read twice.
58
+ - A change is shown as an arrow and a percentage, never by colour alone. `trend` decides only whether it is coloured as good (`text-success`) or bad (`text-danger`).
59
+ - The exact value is in the value's tooltip and in the spoken phrase.
60
+ - Colours come from the role tokens, so the card follows dark mode and an app's palette. The skeleton pulses only under `prefers-reduced-motion: no-preference`.
@@ -0,0 +1,93 @@
1
+ <script server cache>
2
+ import { formatChange, formatStat, isStatFormat } from './format'
3
+
4
+ /*
5
+ * <StatCard>: one headline number for a dashboard (stacksjs/stx#2323).
6
+ *
7
+ * Server-rendered, no client script: the value is formatted here, compactly,
8
+ * with the exact figure in the tooltip and in the phrase a screen reader
9
+ * reads. The visible pieces are aria-hidden and one sr-only phrase carries
10
+ * "Requests: 12,345, up 12.5% vs last week", so the card reads as one
11
+ * sentence rather than as five fragments.
12
+ */
13
+ export const label = $props.label || ''
14
+ export const format = isStatFormat($props.format) ? $props.format : 'number'
15
+ export const unit = $props.unit || ''
16
+ export const locale = $props.locale || 'en-US'
17
+ export const changeLabel = $props.changeLabel || ''
18
+ export const trend = ['up-good', 'down-good', 'neutral'].includes($props.trend) ? $props.trend : 'up-good'
19
+ export const loading = $bool($props.loading)
20
+ export const href = $props.href || ''
21
+ export const className = $props.className || ''
22
+ export const loadingText = label ? `Loading ${label}` : 'Loading'
23
+
24
+ const formatted = formatStat($props.value, format, { locale, unit })
25
+ export const shortValue = formatted.short
26
+ export const exactValue = formatted.exact
27
+ export const change = formatChange($num($props.change, Number.NaN), trend, locale)
28
+
29
+ const toneClasses = { good: 'text-success', bad: 'text-danger', neutral: 'text-fg-soft' }
30
+ export const changeClasses = `inline-flex items-center gap-1 text-sm font-medium ${change ? toneClasses[change.tone] : ''}`.trim()
31
+ export const arrow = change ? (change.direction === 'up' ? '▲' : change.direction === 'down' ? '▼' : '–') : ''
32
+
33
+ const spokenChange = change ? (changeLabel ? `${change.spoken} ${changeLabel}` : change.spoken) : ''
34
+ export const phrase = [`${label || 'Value'}: ${exactValue}`, spokenChange].filter(Boolean).join(', ')
35
+
36
+ const base = 'block rounded-panel border border-line bg-panel p-5'
37
+ const linkClasses = href ? 'transition-colors hover:border-line-hover focus:outline-none focus-visible:ring-2 focus-visible:ring-accent' : ''
38
+ export const cardClasses = `${base} ${linkClasses} ${className}`.trim()
39
+ export const labelClasses = 'block text-sm font-medium leading-5 text-fg-soft truncate'
40
+ export const valueClasses = 'block min-w-0 truncate text-3xl font-semibold leading-9 tracking-tight text-fg tabular-nums'
41
+ export const valueRowClasses = 'mt-1 flex h-9 items-center justify-between gap-3'
42
+ /*
43
+ * A sparkline beside the value, in the same row as the value, so a card with one is
44
+ * the same height as a card without and as its loading skeleton.
45
+ */
46
+ export const series = Array.isArray($props.series) && $props.series.length > 1 ? $props.series : null
47
+ export const sparkColor = change && change.tone === 'bad' ? 'var(--stx-danger, #dc2626)' : change && change.tone === 'good' ? 'var(--stx-success, #16a34a)' : 'var(--stx-accent, #2563eb)'
48
+ export const footerClasses = 'mt-1 flex h-5 items-center gap-2'
49
+ </script>
50
+
51
+ @if(loading)
52
+ <div class="{{ cardClasses }}" data-stx-stat-card data-loading="true" aria-busy="true">
53
+ <span class="sr-only">{{ loadingText }}</span>
54
+ {{-- The same three lines as the loaded card, at the same heights. --}}
55
+ <div class="flex h-5 items-center" aria-hidden="true"><Skeleton width="45%" className="h-3.5" /></div>
56
+ <div class="mt-1 flex h-9 items-center" aria-hidden="true"><Skeleton variant="rect" width="60%" className="h-7" /></div>
57
+ <div class="mt-1 flex h-5 items-center" aria-hidden="true"><Skeleton width="35%" className="h-3.5" /></div>
58
+ </div>
59
+ @elseif(href)
60
+ <a href="{{ href }}" class="{{ cardClasses }}" data-stx-stat-card>
61
+ <span class="sr-only">{{ phrase }}</span>
62
+ <span class="{{ labelClasses }}" aria-hidden="true">{{ label }}</span>
63
+ <span class="{{ valueRowClasses }}" aria-hidden="true">
64
+ <span class="{{ valueClasses }}" title="{{ exactValue }}" data-stx-stat-value>{{ shortValue }}</span>
65
+ @if(series)
66
+ <Sparkline :data="series" :height="36" :colors="[sparkColor]" area className="w-24 shrink-0" />
67
+ @endif
68
+ </span>
69
+ <span class="{{ footerClasses }}" aria-hidden="true">
70
+ @if(change)
71
+ <span class="{{ changeClasses }}" data-stx-stat-change="{{ change.direction }}" data-tone="{{ change.tone }}"><span class="text-xs">{{ arrow }}</span>{{ change.text }}</span>
72
+ @endif
73
+ @if(changeLabel)<span class="text-sm text-fg-soft">{{ changeLabel }}</span>@endif
74
+ </span>
75
+ </a>
76
+ @else
77
+ <div class="{{ cardClasses }}" data-stx-stat-card role="group" aria-label="{{ label }}">
78
+ <span class="sr-only">{{ phrase }}</span>
79
+ <span class="{{ labelClasses }}" aria-hidden="true">{{ label }}</span>
80
+ <span class="{{ valueRowClasses }}" aria-hidden="true">
81
+ <span class="{{ valueClasses }}" title="{{ exactValue }}" data-stx-stat-value>{{ shortValue }}</span>
82
+ @if(series)
83
+ <Sparkline :data="series" :height="36" :colors="[sparkColor]" area className="w-24 shrink-0" />
84
+ @endif
85
+ </span>
86
+ <span class="{{ footerClasses }}" aria-hidden="true">
87
+ @if(change)
88
+ <span class="{{ changeClasses }}" data-stx-stat-change="{{ change.direction }}" data-tone="{{ change.tone }}"><span class="text-xs">{{ arrow }}</span>{{ change.text }}</span>
89
+ @endif
90
+ @if(changeLabel)<span class="text-sm text-fg-soft">{{ changeLabel }}</span>@endif
91
+ </span>
92
+ </div>
93
+ @endif
@@ -0,0 +1,17 @@
1
+ <script server cache>
2
+ /*
3
+ * <StatGroup>: a responsive grid of <StatCard>s (stacksjs/stx#2323). One
4
+ * column on a phone, two from `sm`, and `columns` (default 4) from `lg`.
5
+ */
6
+ export const columns = Math.min(6, Math.max(1, $num($props.columns, 4)))
7
+ export const label = $props.label || ''
8
+ export const className = $props.className || ''
9
+
10
+ const lgColumns = { 1: 'lg:grid-cols-1', 2: 'lg:grid-cols-2', 3: 'lg:grid-cols-3', 4: 'lg:grid-cols-4', 5: 'lg:grid-cols-5', 6: 'lg:grid-cols-6' }
11
+ const smColumns = columns === 1 ? 'sm:grid-cols-1' : 'sm:grid-cols-2'
12
+ export const groupClasses = `grid grid-cols-1 gap-4 ${smColumns} ${lgColumns[columns]} ${className}`.trim()
13
+ </script>
14
+
15
+ <div class="{{ groupClasses }}" data-stx-stat-group @if(label)role="group" aria-label="{{ label }}"@endif>
16
+ <slot />
17
+ </div>
@@ -0,0 +1,147 @@
1
+ /**
2
+ * Number formatting for `<StatCard>` (stacksjs/stx#2323).
3
+ *
4
+ * Every format answers two strings: `short`, the compact headline a card
5
+ * shows (`12.3K`, `1.2 s`, `4.5 MB`), and `exact`, the full value for the
6
+ * tooltip and for assistive technology (`12,345`, `1,234 ms`).
7
+ *
8
+ * Ratios are fractions, as `Intl.NumberFormat` takes them: a `percent` value
9
+ * of 0.0042 is 0.42%, and a `change` of 0.125 is +12.5%.
10
+ */
11
+
12
+ export type StatFormat = 'number' | 'percent' | 'duration' | 'bytes' | 'currency'
13
+ export type StatTrend = 'up-good' | 'down-good' | 'neutral'
14
+
15
+ export interface StatFormatOptions {
16
+ /** BCP 47 locale. Default `en-US`. */
17
+ locale?: string
18
+ /** A unit appended to a `number` (`req/s`), or the ISO currency for `currency` (default `USD`). */
19
+ unit?: string
20
+ }
21
+
22
+ export interface FormattedStat {
23
+ short: string
24
+ exact: string
25
+ }
26
+
27
+ const STAT_FORMATS: readonly StatFormat[] = ['number', 'percent', 'duration', 'bytes', 'currency']
28
+
29
+ export function isStatFormat(value: unknown): value is StatFormat {
30
+ return typeof value === 'string' && (STAT_FORMATS as readonly string[]).includes(value)
31
+ }
32
+
33
+ /** A number from a prop that may have arrived as a string; NaN when it is not one. */
34
+ export function toNumber(value: unknown): number {
35
+ if (typeof value === 'number')
36
+ return value
37
+ if (typeof value === 'string' && value.trim() !== '')
38
+ return Number(value)
39
+ return Number.NaN
40
+ }
41
+
42
+ function nf(locale: string, options: Intl.NumberFormatOptions): Intl.NumberFormat {
43
+ try {
44
+ return new Intl.NumberFormat(locale, options)
45
+ }
46
+ catch {
47
+ return new Intl.NumberFormat('en-US', options)
48
+ }
49
+ }
50
+
51
+ function withUnit(text: string, unit: string): string {
52
+ return unit ? `${text} ${unit}` : text
53
+ }
54
+
55
+ const DURATION_STEPS: Array<{ limit: number, divisor: number, unit: string }> = [
56
+ { limit: 1000, divisor: 1, unit: 'ms' },
57
+ { limit: 60_000, divisor: 1000, unit: 's' },
58
+ { limit: 3_600_000, divisor: 60_000, unit: 'min' },
59
+ { limit: 86_400_000, divisor: 3_600_000, unit: 'h' },
60
+ { limit: Number.POSITIVE_INFINITY, divisor: 86_400_000, unit: 'd' },
61
+ ]
62
+
63
+ const BYTE_UNITS = ['B', 'KB', 'MB', 'GB', 'TB', 'PB']
64
+
65
+ /**
66
+ * Format `value` as `format`. A value that is not a number formats as an em
67
+ * dash, so a missing metric reads as missing rather than as "NaN" or "0".
68
+ */
69
+ export function formatStat(value: unknown, format: StatFormat = 'number', options: StatFormatOptions = {}): FormattedStat {
70
+ const locale = options.locale || 'en-US'
71
+ const unit = options.unit || ''
72
+ const n = toNumber(value)
73
+ if (!Number.isFinite(n))
74
+ return { short: '—', exact: '—' }
75
+
76
+ switch (format) {
77
+ case 'percent': {
78
+ return {
79
+ short: nf(locale, { style: 'percent', maximumFractionDigits: Math.abs(n) < 0.1 ? 2 : 1 }).format(n),
80
+ exact: nf(locale, { style: 'percent', maximumFractionDigits: 4 }).format(n),
81
+ }
82
+ }
83
+ case 'duration': {
84
+ // Milliseconds in, the largest unit that keeps the number at least 1.
85
+ const abs = Math.abs(n)
86
+ const step = DURATION_STEPS.find(s => abs < s.limit) || DURATION_STEPS[DURATION_STEPS.length - 1]!
87
+ const scaled = n / step.divisor
88
+ const digits = step.unit === 'ms' ? 0 : 1
89
+ return {
90
+ short: `${nf(locale, { maximumFractionDigits: digits }).format(scaled)} ${step.unit}`,
91
+ exact: `${nf(locale, { maximumFractionDigits: 3 }).format(n)} ms`,
92
+ }
93
+ }
94
+ case 'bytes': {
95
+ // Decimal (SI) units, so "KB" means 1000 bytes as it says.
96
+ const abs = Math.abs(n)
97
+ let index = 0
98
+ while (index < BYTE_UNITS.length - 1 && abs >= 1000 ** (index + 1))
99
+ index++
100
+ const scaled = n / 1000 ** index
101
+ return {
102
+ short: `${nf(locale, { maximumFractionDigits: index === 0 ? 0 : 1 }).format(scaled)} ${BYTE_UNITS[index]}`,
103
+ exact: `${nf(locale, { maximumFractionDigits: 0 }).format(n)} bytes`,
104
+ }
105
+ }
106
+ case 'currency': {
107
+ const currency = (unit || 'USD').toUpperCase()
108
+ return {
109
+ short: nf(locale, { style: 'currency', currency, notation: 'compact', maximumFractionDigits: 1 }).format(n),
110
+ exact: nf(locale, { style: 'currency', currency }).format(n),
111
+ }
112
+ }
113
+ default: {
114
+ return {
115
+ short: withUnit(nf(locale, { notation: 'compact', maximumFractionDigits: 1 }).format(n), unit),
116
+ exact: withUnit(nf(locale, { maximumFractionDigits: 6 }).format(n), unit),
117
+ }
118
+ }
119
+ }
120
+ }
121
+
122
+ export type ChangeTone = 'good' | 'bad' | 'neutral'
123
+
124
+ export interface FormattedChange {
125
+ /** `up`, `down` or `flat`. */
126
+ direction: 'up' | 'down' | 'flat'
127
+ /** Whether the movement is good news, by `trend`. Decides colour only. */
128
+ tone: ChangeTone
129
+ /** The magnitude, `12.5%`. */
130
+ text: string
131
+ /** The phrase for assistive technology, `up 12.5%`. */
132
+ spoken: string
133
+ }
134
+
135
+ /** Describe a relative change (a fraction) in words that do not lean on colour. */
136
+ export function formatChange(change: unknown, trend: StatTrend = 'up-good', locale = 'en-US'): FormattedChange | null {
137
+ const n = toNumber(change)
138
+ if (!Number.isFinite(n))
139
+ return null
140
+ const direction = n > 0 ? 'up' : n < 0 ? 'down' : 'flat'
141
+ const text = nf(locale, { style: 'percent', maximumFractionDigits: 1 }).format(Math.abs(n))
142
+ let tone: ChangeTone = 'neutral'
143
+ if (direction !== 'flat' && trend !== 'neutral')
144
+ tone = (direction === 'up') === (trend === 'up-good') ? 'good' : 'bad'
145
+ const spoken = direction === 'flat' ? `unchanged, ${text}` : `${direction} ${text}`
146
+ return { direction, tone, text, spoken }
147
+ }
@@ -0,0 +1,38 @@
1
+ import type { StatFormat, StatTrend } from './format'
2
+
3
+ export { default as StatCard } from './StatCard.stx'
4
+ export { default as StatGroup } from './StatGroup.stx'
5
+ export { formatChange, formatStat, type FormattedChange, type FormattedStat, type StatFormat, type StatFormatOptions, type StatTrend } from './format'
6
+
7
+ export interface StatCardProps {
8
+ label: string
9
+ /** The number. A value that is not one renders as an em dash. */
10
+ value: number | string | null
11
+ /** Default `number`. `percent` takes a fraction (0.0042 is 0.42%); `duration` takes milliseconds; `bytes` uses SI units. */
12
+ format?: StatFormat
13
+ /** Appended to a `number` (`req/s`); the ISO currency for `currency` (default `USD`). */
14
+ unit?: string
15
+ /** BCP 47 locale for formatting. Default `en-US`. */
16
+ locale?: string
17
+ /** Relative change as a fraction: 0.125 is +12.5%. */
18
+ change?: number
19
+ /** What the change is measured against, e.g. `vs last week`. */
20
+ changeLabel?: string
21
+ /** Which direction is good news; decides colour only. Default `up-good`. */
22
+ trend?: StatTrend
23
+ /** Render a skeleton with the loaded card's dimensions. */
24
+ loading?: boolean
25
+ /** Recent values, oldest first, drawn as a sparkline beside the value. */
26
+ series?: number[]
27
+ /** Make the whole card a link. */
28
+ href?: string
29
+ className?: string
30
+ }
31
+
32
+ export interface StatGroupProps {
33
+ /** Columns from the `lg` breakpoint, 1 to 6. Default 4. */
34
+ columns?: number
35
+ /** An accessible name for the group. */
36
+ label?: string
37
+ className?: string
38
+ }
@@ -1,16 +0,0 @@
1
- <script server>
2
- export const className = $props.className || ''
3
- export const as = $props.as || 'ul'
4
-
5
- const baseClasses = 'absolute z-10 mt-1 max-h-60 w-full overflow-auto rounded-panel bg-panel py-1 text-base shadow-lg ring-1 ring-line focus:outline-none'
6
- export const optionsClasses = `${baseClasses} ${className}`.trim()
7
- </script>
8
-
9
- <component
10
- :is="{{ as }}"
11
- class="{{ optionsClasses }}"
12
- data-stx-combobox-options
13
- role="listbox"
14
- >
15
- <slot />
16
- </component>