@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
@@ -93,10 +93,31 @@ export declare interface SearchInputProps extends Omit<BaseInputProps, 'placehol
93
93
  onSearch?: (value: string) => void
94
94
  loading?: boolean
95
95
  }
96
+ /**
97
+ * A read-only secret such as an API key, masked to its ends (`mapshq_s…c21d`).
98
+ * `value` never leaves the server while masked; reveal and copy fetch it
99
+ * through `src` or `resolve`.
100
+ */
101
+ export declare interface SecretFieldProps {
102
+ value: string
103
+ visiblePrefix?: number
104
+ visibleSuffix?: number
105
+ revealable?: boolean
106
+ copyable?: boolean
107
+ label?: string
108
+ revealTimeout?: number
109
+ src?: string
110
+ resolve?: () => Promise<string | { value: string }> | string
111
+ once?: boolean
112
+ warning?: string
113
+ id?: string
114
+ className?: string
115
+ }
96
116
  /** The text-like input types `TextInput` renders; anything else is served as `text`. */
97
117
  export type TextInputType = 'text' | 'date' | 'time' | 'datetime-local' | 'month' | 'week' | 'url' | 'tel' | 'color' | 'search' | 'email' | 'number' | 'password';
98
118
  export { default as EmailInput } from './EmailInput';
99
119
  export { default as NumberInput } from './NumberInput';
100
120
  export { default as PasswordInput } from './PasswordInput';
101
121
  export { default as SearchInput } from './SearchInput';
122
+ export { default as SecretField } from './SecretField';
102
123
  export { default as TextInput } from './TextInput';
@@ -12,6 +12,8 @@ export declare const initialType: unknown;
12
12
  export declare const initialPosition: unknown;
13
13
  export declare const initialDuration: unknown;
14
14
  export declare const className: unknown;
15
+ // Live, so a parent's `:show="saved()"` shows and hides it after mount, as it
16
+ // does a Tooltip (stacksjs/stx#2327).
15
17
  declare const isVisible: unknown;
16
18
  declare const title: unknown;
17
19
  declare const message: unknown;
@@ -0,0 +1,21 @@
1
+ import type { DefineComponent } from '@stacksjs/stx';
2
+ declare const __dtsx_component__: __DtsxStxComponentType;
3
+ /*
4
+ * <PricingPlan>: one plan as a card (stacksjs/stx#2322). <PricingTable> draws
5
+ * these for its plans; use it alone, or inside a PricingTable's slot to give
6
+ * a plan its own call to action (`<a slot="cta">`).
7
+ *
8
+ * Both intervals' prices are drawn and the stylesheet shows the one the
9
+ * nearest `data-interval` names, so switching needs no re-render. The card
10
+ * sets that attribute itself only when given `interval`; inside a table the
11
+ * table's own toggle decides.
12
+ */
13
+ declare const prepared: unknown;
14
+ export declare const plan: unknown;
15
+ export declare const interval: boolean;
16
+ export declare const className: unknown;
17
+ export declare const headingId: unknown;
18
+ export declare const cardClasses: unknown;
19
+ export declare const ctaClasses: unknown;
20
+ declare type __DtsxStxComponentType = DefineComponent<{ plan?: unknown, features?: unknown, currentPlan?: string, locale?: string, interval?: unknown, className?: string }>;
21
+ export default __dtsx_component__;
@@ -0,0 +1,50 @@
1
+ import type { DefineComponent } from '@stacksjs/stx';
2
+ declare function chooseInterval(next: unknown): undefined;
3
+ declare const __dtsx_component__: __DtsxStxComponentType;
4
+ /*
5
+ * <PricingTable>: plans side by side, from data (stacksjs/stx#2322), so a
6
+ * pricing page renders straight from the billing config instead of drifting
7
+ * from it.
8
+ *
9
+ * <PricingTable :plans="plans" :features="features" interval="month" currentPlan="pro" @select="choose" />
10
+ *
11
+ * Cards on every width, and on a wide screen a feature matrix under them with
12
+ * real row and column headers. Both intervals' prices are rendered and the
13
+ * `data-interval` on the root picks which shows, so the server's HTML is
14
+ * complete and the toggle (a SegmentedControl) only flips an attribute.
15
+ * @defaultValue `['plans', 'features']`
16
+ */
17
+ export declare const serverOnlyProps: string[];
18
+ export declare const locale: unknown;
19
+ export declare const currentPlan: unknown;
20
+ export declare const interval: boolean;
21
+ export declare const label: unknown;
22
+ export declare const showToggle: unknown;
23
+ export declare const showMatrix: unknown;
24
+ export declare const className: unknown;
25
+ export declare const rawPlans: unknown;
26
+ export declare const features: unknown;
27
+ declare const prepared: unknown;
28
+ export declare const plans: unknown;
29
+ export declare const sections: unknown;
30
+ export declare const hasMatrix: boolean;
31
+ export declare const yearlyLabel: boolean;
32
+ /** @defaultValue `[{ value: 'month', label: 'Monthly' }, { value: 'year', label: yearlyLabel }]` */
33
+ export declare const intervalOptions: ({
34
+ /** @defaultValue 'month' */
35
+ value: string;
36
+ /** @defaultValue 'Monthly' */
37
+ label: string
38
+ } | {
39
+ /** @defaultValue 'year' */
40
+ value: string;
41
+ label: typeof yearlyLabel
42
+ })[];
43
+ export declare const tableId: string;
44
+ export declare const gridClasses: string;
45
+ export declare const rootClasses: unknown;
46
+ /* What the `select` event carries: the plan as given, minus anything that is not data. */
47
+ export declare const selectable: ReturnType<typeof JSON.stringify>;
48
+ export declare const planIds: ReturnType<typeof plans.map>;
49
+ declare type __DtsxStxComponentType = DefineComponent<{ locale?: string, currentPlan?: string, interval?: unknown, label?: string, toggle?: unknown, matrix?: unknown, className?: string, plans?: unknown, features?: unknown }> & { readonly __stxEmits?: ["select", "interval-change"], readonly __stxExposed?: { interval: unknown, chooseInterval: typeof chooseInterval } }
50
+ export default __dtsx_component__;
@@ -0,0 +1,38 @@
1
+ import type { PricingInterval, PricingPlanInput, PricingSectionInput } from './pricing';
2
+ export declare interface PricingTableProps {
3
+ plans: PricingPlanInput[]
4
+ features?: PricingSectionInput[]
5
+ interval?: PricingInterval
6
+ currentPlan?: string
7
+ locale?: string
8
+ label?: string
9
+ toggle?: boolean
10
+ matrix?: boolean
11
+ className?: string
12
+ onSelect?: (plan: PricingPlanInput, interval: PricingInterval) => void
13
+ onIntervalChange?: (interval: PricingInterval) => void
14
+ }
15
+ export declare interface PricingPlanProps {
16
+ plan: PricingPlanInput
17
+ features?: PricingSectionInput[]
18
+ interval?: PricingInterval
19
+ currentPlan?: string
20
+ locale?: string
21
+ className?: string
22
+ }
23
+ export { default as PricingPlan } from './PricingPlan';
24
+ export { default as PricingTable } from './PricingTable';
25
+ export {
26
+ type FeatureCell,
27
+ formatFeature,
28
+ formatPrice,
29
+ type PreparedPlan,
30
+ preparePlans,
31
+ type PricedInterval,
32
+ type PricingCta,
33
+ type PricingFeatureInput,
34
+ type PricingInterval,
35
+ type PricingPlanInput,
36
+ type PricingSectionInput,
37
+ yearlySaving,
38
+ } from './pricing';
@@ -0,0 +1,64 @@
1
+ /** The yearly saving as a fraction of twelve monthly payments, or 0. */
2
+ export declare function yearlySaving(prices: PricingPlanInput['prices']): number;
3
+ export declare function formatPrice(plan: PricingPlanInput, interval: PricingInterval, locale?: string): PricedInterval;
4
+ export declare function formatFeature(value: unknown, feature: PricingFeatureInput, locale?: string): FeatureCell;
5
+ /** Sections as given, or one unnamed section of every feature key the plans mention. */
6
+ export declare function normaliseSections(sections: unknown, plans: PricingPlanInput[]): Array<{ section: string, items: PricingFeatureInput[] }>;
7
+ export declare function preparePlans(plansInput: unknown, sectionsInput: unknown, options?: { currentPlan?: string, locale?: string }): { plans: PreparedPlan[], sections: Array<{ section: string, items: PricingFeatureInput[] }>, maxSaving: number };
8
+ export declare interface PricingCta {
9
+ label?: string
10
+ href?: string
11
+ }
12
+ export declare interface PricingPlanInput {
13
+ id?: string
14
+ name: string
15
+ description?: string
16
+ prices?: Partial<Record<PricingInterval, number | null>>
17
+ currency?: string
18
+ features?: Record<string, boolean | number | string | null | undefined>
19
+ highlights?: string[]
20
+ highlighted?: boolean
21
+ badge?: string
22
+ cta?: PricingCta | string
23
+ }
24
+ export declare interface PricingFeatureInput {
25
+ key: string
26
+ label: string
27
+ unit?: string
28
+ }
29
+ export declare interface PricingSectionInput {
30
+ section?: string
31
+ items: PricingFeatureInput[]
32
+ }
33
+ export declare interface PricedInterval {
34
+ interval: PricingInterval
35
+ amount: string
36
+ per: string
37
+ note: string
38
+ spoken: string
39
+ }
40
+ export declare interface FeatureCell {
41
+ kind: 'included' | 'excluded' | 'value'
42
+ text: string
43
+ spoken: string
44
+ }
45
+ export declare interface PreparedPlan {
46
+ id: string
47
+ name: string
48
+ description: string
49
+ highlighted: boolean
50
+ badge: string
51
+ current: boolean
52
+ prices: PricedInterval[]
53
+ saving: string
54
+ highlights: string[]
55
+ ctaLabel: string
56
+ ctaHref: string
57
+ cells: FeatureCell[][]
58
+ }
59
+ /**
60
+ * Plan data for `<PricingTable>` and `<PricingPlan>` (stacksjs/stx#2322):
61
+ * normalising plans written the way a billing config writes them, and the
62
+ * Intl formatting of prices, savings and feature values.
63
+ */
64
+ export type PricingInterval = 'month' | 'year';
@@ -59,6 +59,8 @@ export declare const mac: boolean;
59
59
  */
60
60
  export declare const stateInvalidClasses: 'ring-danger-line text-danger-fg placeholder-danger focus:ring-danger-focus';
61
61
  export declare const stateValidClasses: 'ring-line-strong text-fg placeholder-fg-soft focus:ring-accent';
62
+ export declare const disabledStateClasses: 'opacity-50 cursor-not-allowed bg-surface';
63
+ export declare const enabledStateClasses: 'bg-field cursor-pointer hover:ring-line-hover';
62
64
  export declare const selectClasses: unknown;
63
65
  export declare const labelClasses: unknown;
64
66
  export declare const helperClasses: unknown;
@@ -0,0 +1,42 @@
1
+ import type { DefineComponent } from '@stacksjs/stx';
2
+ declare const __dtsx_component__: __DtsxStxComponentType;
3
+ /*
4
+ * <StatCard>: one headline number for a dashboard (stacksjs/stx#2323).
5
+ *
6
+ * Server-rendered, no client script: the value is formatted here, compactly,
7
+ * with the exact figure in the tooltip and in the phrase a screen reader
8
+ * reads. The visible pieces are aria-hidden and one sr-only phrase carries
9
+ * "Requests: 12,345, up 12.5% vs last week", so the card reads as one
10
+ * sentence rather than as five fragments.
11
+ */
12
+ export declare const label: unknown;
13
+ export declare const format: unknown;
14
+ export declare const unit: unknown;
15
+ export declare const locale: unknown;
16
+ export declare const changeLabel: unknown;
17
+ export declare const trend: unknown;
18
+ export declare const loading: ReturnType<typeof $bool>;
19
+ export declare const href: unknown;
20
+ export declare const className: unknown;
21
+ export declare const loadingText: unknown;
22
+ declare const formatted: unknown;
23
+ export declare const shortValue: unknown;
24
+ export declare const exactValue: unknown;
25
+ export declare const change: unknown;
26
+ export declare const changeClasses: unknown;
27
+ export declare const arrow: unknown;
28
+ declare const spokenChange: unknown;
29
+ export declare const phrase: unknown;
30
+ export declare const cardClasses: unknown;
31
+ export declare const labelClasses: 'block text-sm font-medium leading-5 text-fg-soft truncate';
32
+ export declare const valueClasses: 'block min-w-0 truncate text-3xl font-semibold leading-9 tracking-tight text-fg tabular-nums';
33
+ export declare const valueRowClasses: 'mt-1 flex h-9 items-center justify-between gap-3';
34
+ /*
35
+ * A sparkline beside the value, in the same row as the value, so a card with one is
36
+ * the same height as a card without and as its loading skeleton.
37
+ */
38
+ export declare const series: boolean;
39
+ export declare const sparkColor: boolean;
40
+ export declare const footerClasses: 'mt-1 flex h-5 items-center gap-2';
41
+ declare type __DtsxStxComponentType = DefineComponent<{ label?: string, format?: unknown, unit?: string, locale?: string, changeLabel?: string, trend?: unknown, loading?: unknown, href?: string, className?: string, value?: unknown, change?: unknown, series?: unknown }>;
42
+ export default __dtsx_component__;
@@ -0,0 +1,12 @@
1
+ import type { DefineComponent } from '@stacksjs/stx';
2
+ declare const __dtsx_component__: __DtsxStxComponentType;
3
+ /*
4
+ * <StatGroup>: a responsive grid of <StatCard>s (stacksjs/stx#2323). One
5
+ * column on a phone, two from `sm`, and `columns` (default 4) from `lg`.
6
+ */
7
+ export declare const columns: unknown;
8
+ export declare const label: unknown;
9
+ export declare const className: unknown;
10
+ export declare const groupClasses: unknown;
11
+ declare type __DtsxStxComponentType = DefineComponent<{ columns?: unknown, label?: string, className?: string }>;
12
+ export default __dtsx_component__;
@@ -0,0 +1,37 @@
1
+ export declare function isStatFormat(value: unknown): value is StatFormat;
2
+ /** A number from a prop that may have arrived as a string; NaN when it is not one. */
3
+ export declare function toNumber(value: unknown): number;
4
+ /**
5
+ * Format `value` as `format`. A value that is not a number formats as an em
6
+ * dash, so a missing metric reads as missing rather than as "NaN" or "0".
7
+ */
8
+ export declare function formatStat(value: unknown, format?: StatFormat, options?: StatFormatOptions): FormattedStat;
9
+ /** Describe a relative change (a fraction) in words that do not lean on colour. */
10
+ export declare function formatChange(change: unknown, trend?: StatTrend, locale?: string): FormattedChange | null;
11
+ export declare interface StatFormatOptions {
12
+ locale?: string
13
+ unit?: string
14
+ }
15
+ export declare interface FormattedStat {
16
+ short: string
17
+ exact: string
18
+ }
19
+ export declare interface FormattedChange {
20
+ direction: 'up' | 'down' | 'flat'
21
+ tone: ChangeTone
22
+ text: string
23
+ spoken: string
24
+ }
25
+ /**
26
+ * Number formatting for `<StatCard>` (stacksjs/stx#2323).
27
+ *
28
+ * Every format answers two strings: `short`, the compact headline a card
29
+ * shows (`12.3K`, `1.2 s`, `4.5 MB`), and `exact`, the full value for the
30
+ * tooltip and for assistive technology (`12,345`, `1,234 ms`).
31
+ *
32
+ * Ratios are fractions, as `Intl.NumberFormat` takes them: a `percent` value
33
+ * of 0.0042 is 0.42%, and a `change` of 0.125 is +12.5%.
34
+ */
35
+ export type StatFormat = 'number' | 'percent' | 'duration' | 'bytes' | 'currency';
36
+ export type StatTrend = 'up-good' | 'down-good' | 'neutral';
37
+ export type ChangeTone = 'good' | 'bad' | 'neutral';
@@ -0,0 +1,23 @@
1
+ import type { StatFormat, StatTrend } from './format';
2
+ export declare interface StatCardProps {
3
+ label: string
4
+ value: number | string | null
5
+ format?: StatFormat
6
+ unit?: string
7
+ locale?: string
8
+ change?: number
9
+ changeLabel?: string
10
+ trend?: StatTrend
11
+ loading?: boolean
12
+ series?: number[]
13
+ href?: string
14
+ className?: string
15
+ }
16
+ export declare interface StatGroupProps {
17
+ columns?: number
18
+ label?: string
19
+ className?: string
20
+ }
21
+ export { default as StatCard } from './StatCard';
22
+ export { default as StatGroup } from './StatGroup';
23
+ export { formatChange, formatStat, type FormattedChange, type FormattedStat, type StatFormat, type StatFormatOptions, type StatTrend } from './format';
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@stacksjs/components",
3
3
  "type": "module",
4
- "version": "0.2.991",
4
+ "version": "0.2.997",
5
5
  "description": "A modern component library built with STX, featuring headwind utility classes and TypeScript syntax highlighting.",
6
6
  "author": "Chris Breuer <chris@stacksjs.org>",
7
7
  "license": "MIT",
@@ -144,8 +144,8 @@
144
144
  "dependencies": {
145
145
  "@iconify-json/f7": "^1.2.2",
146
146
  "@stacksjs/ts-css": "^0.3.11",
147
- "@stacksjs/stx": "0.2.991",
148
- "bun-plugin-stx": "0.2.991",
147
+ "@stacksjs/stx": "0.2.997",
148
+ "bun-plugin-stx": "0.2.997",
149
149
  "ts-syntax-highlighter": "^0.2.20",
150
150
  "ts-video-player": "^0.1.11"
151
151
  },
@@ -14,6 +14,9 @@ export const theme = $props.theme || 'auto'
14
14
  export const lineNumbers = $bool($props.lineNumbers, true)
15
15
  export const copyable = $bool($props.copyable, true)
16
16
  export const className = $props.className || ''
17
+ /* The tab name inside a <CodeGroup>, the language when not given; `default` picks the tab shown first. */
18
+ export const label = $props.label || ''
19
+ export const isDefault = $bool($props.default)
17
20
 
18
21
  /*
19
22
  * `lineNumbers` is still not passed on. `highlight()` can number lines now (as
@@ -124,7 +127,7 @@ effect(() => {
124
127
  })
125
128
  </script>
126
129
 
127
- <div class="relative group">
130
+ <div class="relative group" data-stx-code-block data-language="{{ language }}" data-label="{{ label }}" @if(isDefault)data-default@endif>
128
131
  {{-- The server's render, until a bound `code` changes; then the browser's. --}}
129
132
  <div :show="!liveHtml()">{!! highlightedCode !!}</div>
130
133
  <div class="{{ liveClasses }}" :show="liveHtml()" :html="liveHtml()"></div>
@@ -0,0 +1,217 @@
1
+ <script server>
2
+ import { defaultTabIndex, readCodeTabs } from './code-group'
3
+
4
+ /*
5
+ * <CodeGroup>: the same snippet in several languages, as tabs, with the
6
+ * reader's choice remembered and shared (stacksjs/stx#2321).
7
+ *
8
+ * <CodeGroup>
9
+ * <CodeBlock language="bash" label="curl" :code="curl" />
10
+ * <CodeBlock language="typescript" :code="ts" default />
11
+ * <CodeBlock language="python" :code="py" />
12
+ * </CodeGroup>
13
+ *
14
+ * The tabs are read from the children as the server rendered them (each
15
+ * CodeBlock marks its root with its language, label and `default`), so the
16
+ * server draws the tab list, blocks a loop produced included, and shows the
17
+ * default block with no script: the others are hidden
18
+ * by the stylesheet below, keyed on `data-active`. The client then wires the
19
+ * tabs to their panels, restores the stored language and follows every other
20
+ * group with the same `syncKey`. Each CodeBlock keeps its own copy button, and
21
+ * only the visible one can be reached, so a copy is always the active snippet.
22
+ */
23
+ export const syncKey = $props.syncKey || 'code-language'
24
+ export const label = $props.label || 'Code examples'
25
+ export const className = $props.className || ''
26
+ export const groupId = $props.id || `code-group-${$uid}`
27
+
28
+ export const tabs = readCodeTabs($slots.default)
29
+ export const activeIndex = defaultTabIndex(tabs)
30
+ export const tabIdPrefix = `${groupId}-tab`
31
+ export const tabListClasses = 'flex flex-wrap gap-1 border-b border-line px-1'
32
+ export const tabClasses = 'relative -mb-px border-b-2 px-3 py-2 text-sm font-medium focus:outline-none focus-visible:ring-2 focus-visible:ring-accent rounded-t-control'
33
+ export const rootClasses = `rounded-panel ${className}`.trim()
34
+ </script>
35
+
36
+ <script client>
37
+ const groupId = {{ groupId }}
38
+ const syncKey = {{ syncKey }}
39
+ const EVENT = 'stx:code-group-select'
40
+ let root = null
41
+ let onSync = null
42
+ let onStorage = null
43
+
44
+ function tabButtons() { return root ? Array.from(root.querySelectorAll('[data-stx-code-tab]')) : [] }
45
+ function panels() {
46
+ if (!root) return []
47
+ const container = root.querySelector('[data-stx-code-panels]')
48
+ return container ? Array.from(container.querySelectorAll('[data-stx-code-block]')).filter(el => el.closest('[data-stx-code-panels]') === container) : []
49
+ }
50
+
51
+ /*
52
+ * The children as rendered decide in the end. A tab list read from the source
53
+ * cannot see blocks a loop produces, so when the count differs the buttons are
54
+ * rebuilt from the panels' own language and label.
55
+ */
56
+ function reconcile() {
57
+ const list = root.querySelector('[role="tablist"]')
58
+ const blocks = panels()
59
+ if (!list || tabButtons().length === blocks.length) return
60
+ list.textContent = ''
61
+ blocks.forEach((block, index) => {
62
+ const button = document.createElement('button')
63
+ button.type = 'button'
64
+ button.setAttribute('role', 'tab')
65
+ button.setAttribute('data-stx-code-tab', '')
66
+ button.setAttribute('data-index', String(index))
67
+ button.setAttribute('data-language', block.getAttribute('data-language') || '')
68
+ button.className = {{ tabClasses }}
69
+ button.textContent = block.getAttribute('data-label') || block.getAttribute('data-language') || ('Tab ' + (index + 1))
70
+ list.appendChild(button)
71
+ })
72
+ }
73
+
74
+ function select(index, { focus = false, store = false } = {}) {
75
+ const buttons = tabButtons()
76
+ const blocks = panels()
77
+ if (index < 0 || index >= buttons.length) return
78
+ root.setAttribute('data-active', String(index))
79
+ buttons.forEach((button, i) => {
80
+ const on = i === index
81
+ button.setAttribute('aria-selected', on ? 'true' : 'false')
82
+ button.setAttribute('tabindex', on ? '0' : '-1')
83
+ button.setAttribute('data-selected', on ? 'true' : 'false')
84
+ })
85
+ blocks.forEach((block, i) => { block.hidden = i !== index })
86
+ if (focus) buttons[index].focus()
87
+ if (!store) return
88
+ const language = buttons[index].getAttribute('data-language') || ''
89
+ try { window.localStorage?.setItem(syncKey, language) } catch {}
90
+ window.dispatchEvent(new CustomEvent(EVENT, { detail: { key: syncKey, language, source: groupId } }))
91
+ }
92
+
93
+ function selectLanguage(language) {
94
+ const index = tabButtons().findIndex(b => b.getAttribute('data-language') === language)
95
+ if (index >= 0) select(index)
96
+ }
97
+
98
+ function onClick(event) {
99
+ const button = event.target.closest('[data-stx-code-tab]')
100
+ if (!button || !root.contains(button)) return
101
+ select(tabButtons().indexOf(button), { store: true })
102
+ }
103
+
104
+ function onKey(event) {
105
+ const buttons = tabButtons()
106
+ const current = buttons.indexOf(event.target)
107
+ if (current < 0) return
108
+ let next = -1
109
+ if (event.key === 'ArrowRight') next = (current + 1) % buttons.length
110
+ else if (event.key === 'ArrowLeft') next = (current - 1 + buttons.length) % buttons.length
111
+ else if (event.key === 'Home') next = 0
112
+ else if (event.key === 'End') next = buttons.length - 1
113
+ if (next < 0) return
114
+ event.preventDefault()
115
+ select(next, { focus: true, store: true })
116
+ }
117
+
118
+ onMount(() => {
119
+ root = document.getElementById(groupId)
120
+ if (!root) return
121
+ reconcile()
122
+ // Wire each tab to its panel; only possible once the children are on the page.
123
+ const buttons = tabButtons()
124
+ panels().forEach((block, i) => {
125
+ if (!buttons[i]) return
126
+ if (!block.id) block.id = groupId + '-panel-' + i
127
+ block.setAttribute('role', 'tabpanel')
128
+ block.setAttribute('tabindex', '0')
129
+ block.setAttribute('aria-labelledby', buttons[i].id || (buttons[i].id = groupId + '-tab-' + i))
130
+ buttons[i].setAttribute('aria-controls', block.id)
131
+ })
132
+ select(Number(root.getAttribute('data-active')) || 0)
133
+ let stored = null
134
+ try { stored = window.localStorage?.getItem(syncKey) } catch {}
135
+ if (stored) selectLanguage(stored)
136
+
137
+ root.addEventListener('click', onClick)
138
+ root.addEventListener('keydown', onKey)
139
+ onSync = (event) => {
140
+ const detail = event.detail || {}
141
+ if (detail.key === syncKey && detail.source !== groupId) selectLanguage(detail.language)
142
+ }
143
+ onStorage = (event) => {
144
+ if (event.key === syncKey && event.newValue) selectLanguage(event.newValue)
145
+ }
146
+ window.addEventListener(EVENT, onSync)
147
+ window.addEventListener('storage', onStorage)
148
+ })
149
+
150
+ onDestroy(() => {
151
+ if (onSync) window.removeEventListener(EVENT, onSync)
152
+ if (onStorage) window.removeEventListener('storage', onStorage)
153
+ if (root) {
154
+ root.removeEventListener('click', onClick)
155
+ root.removeEventListener('keydown', onKey)
156
+ }
157
+ })
158
+ </script>
159
+
160
+ <div id="{{ groupId }}" class="{{ rootClasses }}" data-stx-code-group data-sync-key="{{ syncKey }}" data-active="{{ activeIndex }}">
161
+ <div class="{{ tabListClasses }}" role="tablist" aria-label="{{ label }}">
162
+ @foreach(tabs as tab)
163
+ <button
164
+ type="button"
165
+ id="{{ tabIdPrefix }}-{{ tab.index }}"
166
+ class="{{ tabClasses }}"
167
+ role="tab"
168
+ data-stx-code-tab
169
+ data-index="{{ tab.index }}"
170
+ data-language="{{ tab.language }}"
171
+ data-selected="{{ tab.index === activeIndex ? 'true' : 'false' }}"
172
+ aria-selected="{{ tab.index === activeIndex ? 'true' : 'false' }}"
173
+ tabindex="{{ tab.index === activeIndex ? '0' : '-1' }}"
174
+ >{{ tab.label }}</button>
175
+ @endforeach
176
+ </div>
177
+ <div class="mt-2" data-stx-code-panels>
178
+ <slot />
179
+ </div>
180
+ </div>
181
+
182
+ <style>
183
+ /*
184
+ * Which block shows before any script runs: the one at `data-active`. Blocks
185
+ * are the panels container's div children (a CodeBlock renders as one div,
186
+ * its scripts beside it), counted by type so those scripts do not shift the
187
+ * count. Written out to twelve tabs; past that the client's `hidden` decides.
188
+ */
189
+ [data-stx-code-group][data-active="0"] [data-stx-code-panels] > div:not(:nth-of-type(1)),
190
+ [data-stx-code-group][data-active="1"] [data-stx-code-panels] > div:not(:nth-of-type(2)),
191
+ [data-stx-code-group][data-active="2"] [data-stx-code-panels] > div:not(:nth-of-type(3)),
192
+ [data-stx-code-group][data-active="3"] [data-stx-code-panels] > div:not(:nth-of-type(4)),
193
+ [data-stx-code-group][data-active="4"] [data-stx-code-panels] > div:not(:nth-of-type(5)),
194
+ [data-stx-code-group][data-active="5"] [data-stx-code-panels] > div:not(:nth-of-type(6)),
195
+ [data-stx-code-group][data-active="6"] [data-stx-code-panels] > div:not(:nth-of-type(7)),
196
+ [data-stx-code-group][data-active="7"] [data-stx-code-panels] > div:not(:nth-of-type(8)),
197
+ [data-stx-code-group][data-active="8"] [data-stx-code-panels] > div:not(:nth-of-type(9)),
198
+ [data-stx-code-group][data-active="9"] [data-stx-code-panels] > div:not(:nth-of-type(10)),
199
+ [data-stx-code-group][data-active="10"] [data-stx-code-panels] > div:not(:nth-of-type(11)),
200
+ [data-stx-code-group][data-active="11"] [data-stx-code-panels] > div:not(:nth-of-type(12)) {
201
+ display: none;
202
+ }
203
+ [data-stx-code-panels] [data-stx-code-block][hidden] {
204
+ display: none;
205
+ }
206
+ [data-stx-code-tab] {
207
+ border-color: transparent;
208
+ color: var(--stx-fg-soft, oklch(55.6% 0 0));
209
+ }
210
+ [data-stx-code-tab]:hover {
211
+ color: var(--stx-fg, oklch(20.5% 0 0));
212
+ }
213
+ [data-stx-code-tab][aria-selected="true"] {
214
+ border-color: var(--stx-accent, oklch(54.6% 0.245 262.881));
215
+ color: var(--stx-fg, oklch(20.5% 0 0));
216
+ }
217
+ </style>
@@ -0,0 +1,57 @@
1
+ /**
2
+ * The tabs of a `<CodeGroup>`, read from its slot (stacksjs/stx#2321).
3
+ *
4
+ * A slot normally arrives rendered, where each CodeBlock's root carries
5
+ * `data-stx-code-block` with `data-language`, `data-label` and
6
+ * `data-default`; reading those also counts blocks a loop produced. A slot
7
+ * that arrives as source is read from its `<CodeBlock>` tags instead.
8
+ * Attributes are read quote-aware, so a `>` inside a value such as
9
+ * `code="a > b"` does not end the tag.
10
+ */
11
+ export interface CodeTab {
12
+ index: number
13
+ language: string
14
+ label: string
15
+ isDefault: boolean
16
+ }
17
+
18
+ const RENDERED = /<[a-z][\w-]*((?:\s+[^\s=>/]+(?:\s*=\s*(?:"[^"]*"|'[^']*'|[^\s>]+))?)*)\s*\/?>/gi
19
+ const TAG = /<CodeBlock\b((?:\s+[^\s=>/]+(?:\s*=\s*(?:"[^"]*"|'[^']*'|[^\s>]+))?)*)\s*\/?>/g
20
+ const ATTR = /([^\s=>/]+)(?:\s*=\s*(?:"([^"]*)"|'([^']*)'|([^\s>]+)))?/g
21
+ const FALSE = new Set(['false', '0', 'no', 'off'])
22
+
23
+ function attributes(text: string): Record<string, string> {
24
+ const out: Record<string, string> = {}
25
+ for (const m of text.matchAll(ATTR))
26
+ out[m[1]!] = m[2] ?? m[3] ?? m[4] ?? ''
27
+ return out
28
+ }
29
+
30
+ export function readCodeTabs(slot: unknown): CodeTab[] {
31
+ const source = typeof slot === 'string' ? slot : ''
32
+ const rendered = [...source.matchAll(RENDERED)]
33
+ .map(m => attributes(m[1] || ''))
34
+ .filter(attrs => 'data-stx-code-block' in attrs)
35
+ if (rendered.length) {
36
+ return rendered.map((attrs, index) => {
37
+ const language = attrs['data-language'] || 'typescript'
38
+ return { index, language, label: attrs['data-label'] || language, isDefault: 'data-default' in attrs }
39
+ })
40
+ }
41
+ return [...source.matchAll(TAG)].map((m, index) => {
42
+ const attrs = attributes(m[1] || '')
43
+ const language = attrs.language || 'typescript'
44
+ return {
45
+ index,
46
+ language,
47
+ label: attrs.label || language,
48
+ isDefault: 'default' in attrs && !FALSE.has(String(attrs.default).toLowerCase()),
49
+ }
50
+ })
51
+ }
52
+
53
+ /** The tab to show first: the one marked `default`, else the first. */
54
+ export function defaultTabIndex(tabs: CodeTab[]): number {
55
+ const chosen = tabs.findIndex(t => t.isDefault)
56
+ return chosen >= 0 ? chosen : 0
57
+ }