@stacksjs/components 0.2.990 → 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 (95) 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/{List-5ey6k813.stx → List-mjkged1z.stx} +1 -1
  11. package/dist/{Notification-b3cz24f0.stx → Notification-1pvt347q.stx} +16 -4
  12. package/dist/{Popover-jjt7p7sn.stx → Popover-gntg33xd.stx} +1 -1
  13. package/dist/PricingPlan-h7jt2696.stx +67 -0
  14. package/dist/PricingTable-v3vdn6av.stx +149 -0
  15. package/dist/SecretField-q2xgth94.stx +219 -0
  16. package/dist/{Select-36s22z6d.stx → Select-yhmtvqcx.stx} +7 -4
  17. package/dist/Sparkline-gp859n4h.stx +29 -0
  18. package/dist/StatCard-gff0yx6b.stx +93 -0
  19. package/dist/StatGroup-e0d5dmt7.stx +17 -0
  20. package/dist/components/CodeBlock.d.ts +4 -1
  21. package/dist/components/CodeGroup.d.ts +34 -0
  22. package/dist/components/code-group.d.ts +19 -0
  23. package/dist/components/index.d.ts +2 -0
  24. package/dist/index.d.ts +13 -0
  25. package/dist/index.js +25 -22
  26. package/dist/ui/api-reference/ApiOperation.d.ts +17 -0
  27. package/dist/ui/api-reference/ApiReference.d.ts +28 -0
  28. package/dist/ui/api-reference/ApiSchema.d.ts +17 -0
  29. package/dist/ui/api-reference/index.d.ts +30 -0
  30. package/dist/ui/api-reference/openapi.d.ts +137 -0
  31. package/dist/ui/chart/AreaChart.d.ts +33 -0
  32. package/dist/ui/chart/BarChart.d.ts +33 -0
  33. package/dist/ui/chart/LineChart.d.ts +33 -0
  34. package/dist/ui/chart/Sparkline.d.ts +19 -0
  35. package/dist/ui/chart/core.d.ts +111 -0
  36. package/dist/ui/chart/index.d.ts +51 -0
  37. package/dist/ui/chart/interaction.d.ts +11 -0
  38. package/dist/ui/combobox/Combobox.d.ts +10 -1
  39. package/dist/ui/combobox/ComboboxOptions.d.ts +6 -0
  40. package/dist/ui/combobox/index.d.ts +7 -0
  41. package/dist/ui/command-palette/CommandPalette.d.ts +2 -0
  42. package/dist/ui/input/SecretField.d.ts +56 -0
  43. package/dist/ui/input/index.d.ts +21 -0
  44. package/dist/ui/notification/Notification.d.ts +2 -0
  45. package/dist/ui/pricing/PricingPlan.d.ts +21 -0
  46. package/dist/ui/pricing/PricingTable.d.ts +50 -0
  47. package/dist/ui/pricing/index.d.ts +38 -0
  48. package/dist/ui/pricing/pricing.d.ts +64 -0
  49. package/dist/ui/select/Select.d.ts +2 -0
  50. package/dist/ui/stat/StatCard.d.ts +42 -0
  51. package/dist/ui/stat/StatGroup.d.ts +12 -0
  52. package/dist/ui/stat/format.d.ts +37 -0
  53. package/dist/ui/stat/index.d.ts +23 -0
  54. package/package.json +3 -3
  55. package/src/components/CodeBlock.stx +4 -1
  56. package/src/components/CodeGroup.stx +217 -0
  57. package/src/components/code-group.ts +57 -0
  58. package/src/components/index.ts +2 -0
  59. package/src/index.ts +18 -0
  60. package/src/ui/api-reference/ApiOperation.stx +114 -0
  61. package/src/ui/api-reference/ApiReference.stx +92 -0
  62. package/src/ui/api-reference/ApiSchema.stx +47 -0
  63. package/src/ui/api-reference/README.md +44 -0
  64. package/src/ui/api-reference/index.ts +35 -0
  65. package/src/ui/api-reference/openapi.ts +825 -0
  66. package/src/ui/chart/AreaChart.stx +77 -0
  67. package/src/ui/chart/BarChart.stx +77 -0
  68. package/src/ui/chart/LineChart.stx +77 -0
  69. package/src/ui/chart/README.md +97 -0
  70. package/src/ui/chart/Sparkline.stx +29 -0
  71. package/src/ui/chart/core.ts +730 -0
  72. package/src/ui/chart/index.ts +71 -0
  73. package/src/ui/chart/interaction.ts +175 -0
  74. package/src/ui/combobox/Combobox.stx +174 -5
  75. package/src/ui/combobox/ComboboxOptions.stx +20 -0
  76. package/src/ui/combobox/README.md +41 -0
  77. package/src/ui/combobox/index.ts +13 -0
  78. package/src/ui/command-palette/CommandPalette.stx +3 -1
  79. package/src/ui/input/SecretField.stx +219 -0
  80. package/src/ui/input/index.ts +32 -0
  81. package/src/ui/list/List.stx +1 -1
  82. package/src/ui/notification/Notification.stx +16 -4
  83. package/src/ui/popover/Popover.stx +1 -1
  84. package/src/ui/pricing/PricingPlan.stx +67 -0
  85. package/src/ui/pricing/PricingTable.stx +149 -0
  86. package/src/ui/pricing/README.md +74 -0
  87. package/src/ui/pricing/index.ts +49 -0
  88. package/src/ui/pricing/pricing.ts +177 -0
  89. package/src/ui/select/Select.stx +7 -4
  90. package/src/ui/stat/README.md +60 -0
  91. package/src/ui/stat/StatCard.stx +93 -0
  92. package/src/ui/stat/StatGroup.stx +17 -0
  93. package/src/ui/stat/format.ts +147 -0
  94. package/src/ui/stat/index.ts +38 -0
  95. package/dist/ComboboxOptions-zhr9b6rx.stx +0 -16
@@ -0,0 +1,219 @@
1
+ <script server>
2
+ /*
3
+ * <SecretField>: a read-only field for a secret such as an API key
4
+ * (stacksjs/stx#2320). It shows a recognisable prefix and suffix,
5
+ * `mapshq_sk_3f9a…c21d`, and keeps the middle off the page.
6
+ *
7
+ * `value` is listed in `serverOnlyProps`, so it is NOT serialized into the
8
+ * page for the client the way every other prop is: the server reads it to
9
+ * draw the mask and nothing else carries it. That is also why revealing and
10
+ * copying a masked key need a way to ask for it -- `src` (a URL answering the
11
+ * key as text or `{ value }`) or `:resolve` (a client function) -- and why
12
+ * neither button is drawn without one. A key shown `once`, at creation, is on
13
+ * the page in full by design, and copies from there.
14
+ */
15
+ export const serverOnlyProps = ['value']
16
+
17
+ const secret = $props.value == null ? '' : String($props.value)
18
+ export const once = $bool($props.once)
19
+ export const visiblePrefix = Math.max(0, $num($props.visiblePrefix, 8))
20
+ export const visibleSuffix = Math.max(0, $num($props.visibleSuffix, 4))
21
+ export const revealTimeout = Math.max(0, $num($props.revealTimeout, 30))
22
+ export const label = $props.label || ''
23
+ export const src = typeof $props.src === 'string' ? $props.src : ''
24
+ export const className = $props.className || ''
25
+ export const warning = $props.warning || 'Copy this key now. It will not be shown again.'
26
+ export const fieldId = $props.id || `secret-field-${$uid}`
27
+ export const labelId = `${fieldId}-label`
28
+ export const warningId = `${fieldId}-warning`
29
+
30
+ /*
31
+ * The mask. A value too short to keep both ends AND hide something is masked
32
+ * whole: showing 8 + 4 characters of a 12-character key is showing the key.
33
+ */
34
+ const keepsBoth = secret.length > visiblePrefix + visibleSuffix
35
+ export const masked = !secret
36
+ ? ''
37
+ : keepsBoth
38
+ ? `${secret.slice(0, visiblePrefix)}…${visibleSuffix ? secret.slice(secret.length - visibleSuffix) : ''}`
39
+ : '•'.repeat(Math.min(secret.length, 12))
40
+ /* Only `once` puts the whole value in the markup. */
41
+ export const initialText = once ? secret : masked
42
+
43
+ /*
44
+ * A bound `:resolve` is a client function and never reaches the server, so
45
+ * whether one exists is only known in the browser; the buttons are rendered
46
+ * and the client hides what it cannot do. `src` is known here.
47
+ */
48
+ export const revealable = !once && $bool($props.revealable, true)
49
+ export const copyable = $bool($props.copyable, true)
50
+ export const hasSource = !!src
51
+
52
+ const name = label || 'secret'
53
+ export const revealLabel = `Show ${name}`
54
+ export const hideLabel = `Hide ${name}`
55
+ export const copyLabel = `Copy ${name}`
56
+
57
+ export const wrapperClasses = `${className}`.trim()
58
+ export const fieldClasses = 'flex items-center gap-1 w-full rounded-control bg-surface ring-1 ring-inset ring-line-strong px-3 py-1.5'
59
+ export const valueClasses = 'flex-1 min-w-0 truncate font-mono text-sm text-fg select-all'
60
+ export const buttonClasses = 'inline-flex items-center justify-center shrink-0 h-8 w-8 rounded-control text-fg-soft hover:text-fg hover:bg-accent-soft focus:outline-none focus-visible:ring-2 focus-visible:ring-accent disabled:opacity-50 disabled:cursor-not-allowed'
61
+ export const labelClasses = 'block text-sm font-medium leading-6 mb-2 text-fg'
62
+ export const warningClasses = 'mt-2 text-sm text-warning'
63
+ </script>
64
+
65
+ <script client>
66
+ const emit = defineEmits(['reveal', 'hide', 'copy', 'error'])
67
+ const once = {{ once }}
68
+ const masked = {{ masked }}
69
+ const src = {{ src }}
70
+ const revealTimeoutMs = {{ revealTimeout }} * 1000
71
+ const revealLabel = {{ revealLabel }}
72
+ const hideLabel = {{ hideLabel }}
73
+ const fieldId = {{ fieldId }}
74
+ const liveResolve = useReactiveProp('resolve', null, { parse: v => v })
75
+
76
+ /* The secret lives here, in memory, and in the DOM only while revealed. */
77
+ const secret = state('')
78
+ const revealed = state(false)
79
+ const busy = state(false)
80
+ const status = state('')
81
+ let remaskTimer = null
82
+
83
+ const shownText = derived(() => revealed() ? secret() : masked)
84
+ const toggleLabel = derived(() => revealed() ? hideLabel : revealLabel)
85
+ /* A masked key can only be revealed or copied if there is a way to ask for it. */
86
+ const canFetch = () => !!src || typeof liveResolve() === 'function'
87
+ const canReveal = derived(() => !once && canFetch())
88
+ const canCopy = derived(() => once || canFetch())
89
+
90
+ async function fetchSecret() {
91
+ const resolve = liveResolve()
92
+ if (typeof resolve === 'function') {
93
+ const out = await resolve()
94
+ return out == null ? '' : String(typeof out === 'object' && 'value' in out ? out.value : out)
95
+ }
96
+ const response = await fetch(src, { headers: { Accept: 'application/json, text/plain' }, credentials: 'same-origin' })
97
+ if (!response.ok) throw new Error('Could not load the secret (' + response.status + ')')
98
+ const type = response.headers.get('content-type') || ''
99
+ if (type.includes('json')) {
100
+ const data = await response.json()
101
+ return data == null ? '' : String(typeof data === 'object' ? (data.value ?? '') : data)
102
+ }
103
+ return (await response.text()).trim()
104
+ }
105
+
106
+ function onceValue() {
107
+ const el = document.getElementById(fieldId)
108
+ return el ? (el.textContent || '').trim() : ''
109
+ }
110
+
111
+ function clearTimer() {
112
+ if (remaskTimer) { clearTimeout(remaskTimer); remaskTimer = null }
113
+ }
114
+
115
+ function hide() {
116
+ if (!revealed()) return
117
+ clearTimer()
118
+ revealed.set(false)
119
+ // Re-masking drops it from memory too; the next reveal asks again.
120
+ secret.set('')
121
+ emit('hide')
122
+ }
123
+
124
+ async function reveal() {
125
+ if (once || revealed() || busy()) return
126
+ busy.set(true)
127
+ try {
128
+ secret.set(await fetchSecret())
129
+ revealed.set(true)
130
+ emit('reveal')
131
+ if (revealTimeoutMs > 0) remaskTimer = setTimeout(hide, revealTimeoutMs)
132
+ }
133
+ catch (error) {
134
+ status.set('The secret could not be loaded.')
135
+ emit('error', error)
136
+ }
137
+ finally {
138
+ busy.set(false)
139
+ }
140
+ }
141
+
142
+ function toggle() {
143
+ if (revealed()) hide()
144
+ else reveal()
145
+ }
146
+
147
+ async function copy() {
148
+ if (busy()) return
149
+ busy.set(true)
150
+ try {
151
+ const text = once ? onceValue() : (revealed() ? secret() : await fetchSecret())
152
+ if (!navigator.clipboard || !navigator.clipboard.writeText) throw new Error('Clipboard API not available')
153
+ await navigator.clipboard.writeText(text)
154
+ status.set('Copied to clipboard.')
155
+ if (window.toast && window.toast.success) window.toast.success('Copied to clipboard')
156
+ emit('copy')
157
+ }
158
+ catch (error) {
159
+ status.set('Copy failed.')
160
+ emit('error', error)
161
+ }
162
+ finally {
163
+ busy.set(false)
164
+ }
165
+ }
166
+
167
+ onDestroy(clearTimer)
168
+
169
+ defineExpose({ reveal, hide, copy, revealed })
170
+ </script>
171
+
172
+ <div class="{{ wrapperClasses }}" data-stx-secret-field>
173
+ @if(label)
174
+ <span id="{{ labelId }}" class="{{ labelClasses }}">{{ label }}</span>
175
+ @endif
176
+ <div class="{{ fieldClasses }}" role="group" @if(label)aria-labelledby="{{ labelId }}"@endif @if(once)aria-describedby="{{ warningId }}"@endif>
177
+ @if(once)
178
+ <code id="{{ fieldId }}" class="{{ valueClasses }}" data-stx-secret-value>{{ initialText }}</code>
179
+ @else
180
+ <code id="{{ fieldId }}" class="{{ valueClasses }}" data-stx-secret-value x-text="shownText()">{{ initialText }}</code>
181
+ @endif
182
+ @if(revealable)
183
+ <button
184
+ type="button"
185
+ class="{{ buttonClasses }}"
186
+ data-stx-secret-reveal
187
+ aria-controls="{{ fieldId }}"
188
+ :aria-pressed="revealed() ? 'true' : 'false'"
189
+ :aria-label="toggleLabel()"
190
+ :hidden="!canReveal()"
191
+ :disabled="busy()"
192
+ @if(!hasSource)hidden@endif
193
+ aria-label="{{ revealLabel }}"
194
+ @click="toggle()"
195
+ >
196
+ <svg :if="!revealed()" class="h-4 w-4" aria-hidden="true" viewBox="0 0 20 20" fill="currentColor"><path d="M10 12.5a2.5 2.5 0 100-5 2.5 2.5 0 000 5z" /><path fill-rule="evenodd" d="M.664 10.59a1.651 1.651 0 010-1.186A10.004 10.004 0 0110 3c4.257 0 7.893 2.66 9.336 6.41.147.381.146.804 0 1.186A10.004 10.004 0 0110 17c-4.257 0-7.893-2.66-9.336-6.41zM14 10a4 4 0 11-8 0 4 4 0 018 0z" clip-rule="evenodd" /></svg>
197
+ <svg :if="revealed()" class="h-4 w-4" aria-hidden="true" viewBox="0 0 20 20" fill="currentColor"><path fill-rule="evenodd" d="M3.28 2.22a.75.75 0 00-1.06 1.06l14.5 14.5a.75.75 0 101.06-1.06l-1.745-1.745a10.029 10.029 0 003.3-4.38 1.651 1.651 0 000-1.185A10.004 10.004 0 009.999 3a9.956 9.956 0 00-4.744 1.194L3.28 2.22zM7.752 6.69l1.092 1.092a2.5 2.5 0 013.374 3.373l1.091 1.092a4 4 0 00-5.557-5.557z" clip-rule="evenodd" /><path d="M10.748 13.93l2.523 2.523a9.987 9.987 0 01-3.27.547c-4.258 0-7.894-2.66-9.337-6.41a1.651 1.651 0 010-1.186A10.007 10.007 0 012.839 6.02L6.07 9.252a4 4 0 004.678 4.678z" /></svg>
198
+ </button>
199
+ @endif
200
+ @if(copyable)
201
+ <button
202
+ type="button"
203
+ class="{{ buttonClasses }}"
204
+ data-stx-secret-copy
205
+ aria-label="{{ copyLabel }}"
206
+ :hidden="!canCopy()"
207
+ :disabled="busy()"
208
+ @if(!once && !hasSource)hidden@endif
209
+ @click="copy()"
210
+ >
211
+ <svg class="h-4 w-4" aria-hidden="true" viewBox="0 0 20 20" fill="currentColor"><path d="M7 3.5A1.5 1.5 0 018.5 2h3.879a1.5 1.5 0 011.06.44l3.122 3.12A1.5 1.5 0 0117 6.622V12.5a1.5 1.5 0 01-1.5 1.5h-1v-3.379a3 3 0 00-.879-2.121L10.5 5.379A3 3 0 008.379 4.5H7v-1z" /><path d="M4.5 6A1.5 1.5 0 003 7.5v9A1.5 1.5 0 004.5 18h7a1.5 1.5 0 001.5-1.5v-5.879a1.5 1.5 0 00-.44-1.06L9.44 6.439A1.5 1.5 0 008.378 6H4.5z" /></svg>
212
+ </button>
213
+ @endif
214
+ </div>
215
+ @if(once)
216
+ <p id="{{ warningId }}" class="{{ warningClasses }}" role="note" data-stx-secret-warning>{{ warning }}</p>
217
+ @endif
218
+ <span class="sr-only" role="status" aria-live="polite" x-text="status()"></span>
219
+ </div>
@@ -5,6 +5,7 @@ export { default as EmailInput } from './EmailInput.stx'
5
5
  export { default as NumberInput } from './NumberInput.stx'
6
6
  export { default as PasswordInput } from './PasswordInput.stx'
7
7
  export { default as SearchInput } from './SearchInput.stx'
8
+ export { default as SecretField } from './SecretField.stx'
8
9
  export { default as TextInput } from './TextInput.stx'
9
10
 
10
11
  export interface BaseInputProps {
@@ -210,3 +211,34 @@ export const validateNumberInputProps: (props: Record<string, unknown>) => Valid
210
211
  * Validate SearchInput component props
211
212
  */
212
213
  export const validateSearchInputProps: (props: Record<string, unknown>) => ValidationResult = createPropValidator('SearchInput', searchInputPropSchema)
214
+
215
+ /**
216
+ * A read-only secret such as an API key, masked to its ends (`mapshq_s…c21d`).
217
+ * `value` never leaves the server while masked; reveal and copy fetch it
218
+ * through `src` or `resolve`.
219
+ */
220
+ export interface SecretFieldProps {
221
+ /** The secret. Read on the server to draw the mask; not serialized into the page. */
222
+ value: string
223
+ /** Characters shown at the start. Default 8. */
224
+ visiblePrefix?: number
225
+ /** Characters shown at the end. Default 4. */
226
+ visibleSuffix?: number
227
+ /** Draw the reveal toggle. Default true; needs `src` or `resolve`. */
228
+ revealable?: boolean
229
+ /** Draw the copy button. Default true; needs `src` or `resolve` unless `once`. */
230
+ copyable?: boolean
231
+ label?: string
232
+ /** Seconds before a revealed secret is masked again; 0 keeps it shown. Default 30. */
233
+ revealTimeout?: number
234
+ /** A URL answering the secret as text or `{ value }`, asked on reveal or copy. */
235
+ src?: string
236
+ /** A client function answering the secret, asked on reveal or copy. Bind it: `:resolve="fn"`. */
237
+ resolve?: () => Promise<string | { value: string }> | string
238
+ /** A newly created key: shown in full, once, with `warning`. */
239
+ once?: boolean
240
+ /** The `once` warning. Default "Copy this key now. It will not be shown again." */
241
+ warning?: string
242
+ id?: string
243
+ className?: string
244
+ }
@@ -76,7 +76,7 @@ onMount(() => {
76
76
  return () => { stop(); changes.disconnect(); observer.disconnect() }
77
77
  })
78
78
  </script>
79
- <div data-native="FlatList" ref="listRef" role="list" class="{{ viewportClasses }} {{ className }}" :horizontal="horizontal()" :contentContainerStyle="contentStyle()" :style="nativeHost ? {} : webPadding()" :data-stx-list-direction="horizontal ? 'horizontal' : 'vertical'" data-stx-list data-stx-layout-root @end-reached="reachedEnd()" @refresh="emit('refresh')">
79
+ <div data-native="FlatList" ref="listRef" role="list" class="{{ viewportClasses }} {{ className }}" :horizontal="horizontal()" :contentContainerStyle="contentStyle()" :style="nativeHost ? {} : webPadding()" :data-stx-list-direction="horizontal() ? 'horizontal' : 'vertical'" data-stx-list data-stx-layout-root @end-reached="reachedEnd()" @refresh="emit('refresh')">
80
80
  <slot />
81
81
  @if(!nativeHost)
82
82
  <div ref="endRef" aria-hidden="true" style="height:1px;width:1px;flex-shrink:0"></div>
@@ -14,7 +14,9 @@ export const className = $props.className || ''
14
14
  <script client>
15
15
  const emit = defineEmits()
16
16
 
17
- const isVisible = state({{ initialShow }})
17
+ // Live, so a parent's `:show="saved()"` shows and hides it after mount, as it
18
+ // does a Tooltip (stacksjs/stx#2327).
19
+ const isVisible = useReactiveProp('show', {{ initialShow }})
18
20
  const title = state({{ initialTitle }})
19
21
  const message = state({{ initialMessage }})
20
22
  const type = state({{ initialType }})
@@ -38,7 +40,7 @@ const positions = {
38
40
  }
39
41
 
40
42
  const baseClasses = 'fixed z-50 m-4 max-w-md w-full pointer-events-auto rounded-panel p-4 shadow-lg ring-1 ring-line transition-all'
41
- const extraClassName = {{ JSON.stringify(className) }}
43
+ const extraClassName = {{ className }}
42
44
 
43
45
  const notificationClasses = derived(() => {
44
46
  const color = typeColors[type()] || typeColors.info
@@ -79,8 +81,18 @@ function open(opts) {
79
81
  scheduleAutoHide()
80
82
  }
81
83
 
82
- onMount(() => {
83
- if (isVisible()) scheduleAutoHide()
84
+ // However it became visible, by `open()` or by the parent's `:show`, it
85
+ // hides itself after `duration`.
86
+ let wasVisible = false
87
+ effect(() => {
88
+ const visible = isVisible()
89
+ if (visible && !wasVisible) scheduleAutoHide()
90
+ if (!visible) clearAutoHide()
91
+ wasVisible = visible
92
+ })
93
+
94
+ onDestroy(() => {
95
+ clearAutoHide()
84
96
  })
85
97
 
86
98
  defineExpose({
@@ -41,7 +41,7 @@ function syncExpanded() {
41
41
  if (!rootEl) return
42
42
  const trigger = ownPart('data-stx-popover-button')
43
43
  if (!trigger) return
44
- trigger.setAttribute('aria-expanded', isOpen() ? 'true' : 'false')
44
+ tree.setAttribute(trigger, 'aria-expanded', isOpen() ? 'true' : 'false')
45
45
  const panel = ownPart('data-stx-popover-panel')
46
46
  if (!panel) return
47
47
  const panelId = tree.getAttribute(panel, 'id') || 'stx-popover-panel-' + popoverInstanceId
@@ -0,0 +1,67 @@
1
+ <script server cache>
2
+ import { preparePlans } from './pricing'
3
+
4
+ /*
5
+ * <PricingPlan>: one plan as a card (stacksjs/stx#2322). <PricingTable> draws
6
+ * these for its plans; use it alone, or inside a PricingTable's slot to give
7
+ * a plan its own call to action (`<a slot="cta">`).
8
+ *
9
+ * Both intervals' prices are drawn and the stylesheet shows the one the
10
+ * nearest `data-interval` names, so switching needs no re-render. The card
11
+ * sets that attribute itself only when given `interval`; inside a table the
12
+ * table's own toggle decides.
13
+ */
14
+ const prepared = preparePlans([$props.plan], $props.features, { currentPlan: $props.currentPlan || '', locale: $props.locale || 'en-US' })
15
+ export const plan = prepared.plans[0] || null
16
+ export const interval = $props.interval === 'year' ? 'year' : $props.interval === 'month' ? 'month' : ''
17
+ export const className = $props.className || ''
18
+ export const headingId = plan ? `pricing-plan-${plan.id}-${$uid}` : ''
19
+ const ring = plan && plan.highlighted ? 'ring-2 ring-accent' : 'ring-1 ring-line'
20
+ export const cardClasses = `relative flex flex-col rounded-panel bg-panel p-6 ${ring} ${className}`.trim()
21
+ const ctaBase = 'mt-6 inline-flex w-full items-center justify-center rounded-control px-4 py-2 text-sm font-semibold focus:outline-none focus-visible:ring-2 focus-visible:ring-accent focus-visible:ring-offset-2 focus-visible:ring-offset-panel disabled:cursor-not-allowed disabled:opacity-60'
22
+ export const ctaClasses = plan && plan.highlighted && !plan.current
23
+ ? `${ctaBase} bg-accent-solid text-accent-ink hover:bg-accent-solid-hover`
24
+ : `${ctaBase} bg-surface-raised text-fg ring-1 ring-inset ring-line hover:bg-surface-raised-hover`
25
+ </script>
26
+
27
+ @if(plan)
28
+ <article class="{{ cardClasses }}" data-stx-pricing-plan="{{ plan.id }}" aria-labelledby="{{ headingId }}" @if(interval)data-interval="{{ interval }}"@endif @if(plan.current)data-current="true"@endif>
29
+ @if(plan.badge)
30
+ <p class="absolute -top-3 left-6 rounded-full bg-accent-solid px-3 py-0.5 text-xs font-semibold text-accent-ink">{{ plan.badge }}</p>
31
+ @endif
32
+ <h3 id="{{ headingId }}" class="text-lg font-semibold text-fg">{{ plan.name }}@if(plan.current) <span class="ml-2 rounded-full bg-success-soft px-2 py-0.5 align-middle text-xs font-medium text-success-soft-ink">Current plan</span>@endif</h3>
33
+ @if(plan.description)
34
+ <p class="mt-1 text-sm text-fg-soft">{{ plan.description }}</p>
35
+ @endif
36
+ @foreach(plan.prices as price)
37
+ <div class="mt-4" data-price-interval="{{ price.interval }}">
38
+ <p class="flex items-baseline gap-1"><span class="text-3xl font-semibold tracking-tight text-fg tabular-nums">{{ price.amount }}</span>@if(price.per)<span class="text-sm text-fg-soft">{{ price.per }}</span>@endif</p>
39
+ @if(price.note)<p class="mt-1 text-xs text-fg-soft">{{ price.note }}</p>@endif
40
+ @if(price.interval === 'year' && plan.saving)<p class="mt-1 text-xs font-medium text-success">{{ plan.saving }}</p>@endif
41
+ </div>
42
+ @endforeach
43
+ <slot name="cta">
44
+ @if(plan.ctaHref)
45
+ <a href="{{ plan.ctaHref }}" class="{{ ctaClasses }}" data-pricing-cta="{{ plan.id }}">{{ plan.ctaLabel }}</a>
46
+ @else
47
+ <button type="button" class="{{ ctaClasses }}" data-pricing-cta="{{ plan.id }}" @if(plan.current)disabled aria-disabled="true"@endif>{{ plan.ctaLabel }}</button>
48
+ @endif
49
+ </slot>
50
+ @if(plan.highlights.length)
51
+ <ul class="mt-6 space-y-2 text-sm text-fg" role="list">
52
+ @foreach(plan.highlights as line)
53
+ <li class="flex gap-2"><svg class="mt-0.5 h-4 w-4 shrink-0 text-success" aria-hidden="true" viewBox="0 0 20 20" fill="currentColor"><path fill-rule="evenodd" d="M16.704 4.153a.75.75 0 01.143 1.052l-8 10.5a.75.75 0 01-1.127.075l-4.5-4.5a.75.75 0 011.06-1.06l3.894 3.893 7.48-9.817a.75.75 0 011.05-.143z" clip-rule="evenodd" /></svg><span>{{ line }}</span></li>
54
+ @endforeach
55
+ </ul>
56
+ @endif
57
+ </article>
58
+ @endif
59
+
60
+ <style>
61
+ [data-interval="month"] [data-price-interval="year"],
62
+ [data-interval="year"] [data-price-interval="month"],
63
+ [data-interval="month"][data-stx-pricing-plan] [data-price-interval="year"],
64
+ [data-interval="year"][data-stx-pricing-plan] [data-price-interval="month"] {
65
+ display: none;
66
+ }
67
+ </style>
@@ -0,0 +1,149 @@
1
+ <script server>
2
+ import { preparePlans } from './pricing'
3
+
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
+ */
16
+ export const serverOnlyProps = ['plans', 'features']
17
+ export const locale = $props.locale || 'en-US'
18
+ export const currentPlan = $props.currentPlan || ''
19
+ export const interval = $props.interval === 'year' ? 'year' : 'month'
20
+ export const label = $props.label || 'Plans'
21
+ export const showToggle = $bool($props.toggle, true)
22
+ export const showMatrix = $bool($props.matrix, true)
23
+ export const className = $props.className || ''
24
+ export const rawPlans = Array.isArray($props.plans) ? $props.plans : []
25
+ export const features = $props.features || null
26
+ const prepared = preparePlans(rawPlans, features, { currentPlan, locale })
27
+ export const plans = prepared.plans
28
+ export const sections = prepared.sections
29
+ export const hasMatrix = showMatrix && sections.some(s => s.items.length > 0) && plans.length > 0
30
+ export const yearlyLabel = prepared.maxSaving > 0 ? `Yearly (save up to ${Math.round(prepared.maxSaving * 100)}%)` : 'Yearly'
31
+ export const intervalOptions = [{ value: 'month', label: 'Monthly' }, { value: 'year', label: yearlyLabel }]
32
+ export const tableId = `pricing-${$uid}`
33
+ const columns = Math.min(4, Math.max(1, plans.length))
34
+ const gridColumns = { 1: 'md:grid-cols-1', 2: 'md:grid-cols-2', 3: 'md:grid-cols-3', 4: 'md:grid-cols-2 xl:grid-cols-4' }
35
+ export const gridClasses = `grid grid-cols-1 gap-6 ${gridColumns[columns]}`
36
+ export const rootClasses = `${className}`.trim()
37
+ /* What the `select` event carries: the plan as given, minus anything that is not data. */
38
+ export const selectable = JSON.stringify(rawPlans.map(p => ({ ...p, id: p.id || undefined })))
39
+ .replace(/</g, '\\u003c').replace(/>/g, '\\u003e').replace(/&/g, '\\u0026')
40
+ export const planIds = plans.map(p => p.id)
41
+ </script>
42
+
43
+ <script client>
44
+ const emit = defineEmits(['select', 'interval-change'])
45
+ const tableId = {{ tableId }}
46
+ const plansData = {!! selectable !!}
47
+ const planIds = {{ planIds }}
48
+ const current = state({{ interval }})
49
+
50
+ function root() { return document.getElementById(tableId) }
51
+
52
+ function chooseInterval(next) {
53
+ const value = next === 'year' ? 'year' : 'month'
54
+ if (value === current()) return
55
+ current.set(value)
56
+ const el = root()
57
+ if (el) el.setAttribute('data-interval', value)
58
+ emit('interval-change', value)
59
+ }
60
+
61
+ function onClick(event) {
62
+ const cta = event.target.closest('[data-pricing-cta]')
63
+ const el = root()
64
+ if (!cta || !el || !el.contains(cta)) return
65
+ if (cta.disabled || cta.getAttribute('aria-disabled') === 'true') return
66
+ const index = planIds.indexOf(cta.getAttribute('data-pricing-cta'))
67
+ emit('select', index >= 0 ? plansData[index] : { id: cta.getAttribute('data-pricing-cta') }, current())
68
+ }
69
+
70
+ onMount(() => {
71
+ const el = root()
72
+ if (el) el.addEventListener('click', onClick)
73
+ })
74
+
75
+ onDestroy(() => {
76
+ const el = root()
77
+ if (el) el.removeEventListener('click', onClick)
78
+ })
79
+
80
+ defineExpose({ interval: current, chooseInterval })
81
+ </script>
82
+
83
+ <section id="{{ tableId }}" class="{{ rootClasses }}" data-stx-pricing data-interval="{{ interval }}" aria-label="{{ label }}">
84
+ @if(showToggle)
85
+ <div class="mb-8 flex justify-center">
86
+ <SegmentedControl :options="intervalOptions" :value="interval" label="Billing period" @change="chooseInterval" />
87
+ </div>
88
+ @endif
89
+
90
+ @if($slots.default)
91
+ <div class="{{ gridClasses }}"><slot /></div>
92
+ @else
93
+ <div class="{{ gridClasses }}" data-stx-pricing-cards>
94
+ @foreach(rawPlans as raw)
95
+ <PricingPlan :plan="raw" :features="features" :currentPlan="currentPlan" :locale="locale" />
96
+ @endforeach
97
+ </div>
98
+ @endif
99
+
100
+ @if(hasMatrix)
101
+ <div class="mt-12 hidden overflow-x-auto lg:block" data-stx-pricing-matrix>
102
+ <table class="w-full table-fixed border-collapse text-left text-sm">
103
+ <caption class="sr-only">Features by plan</caption>
104
+ <thead>
105
+ <tr>
106
+ <td class="w-1/3 py-3"></td>
107
+ @foreach(plans as plan)
108
+ <th scope="col" class="px-4 py-3 text-base font-semibold text-fg">{{ plan.name }}@if(plan.current)<span class="sr-only"> (current plan)</span>@endif</th>
109
+ @endforeach
110
+ </tr>
111
+ </thead>
112
+ @foreach(sections as sectionIndex => section)
113
+ <tbody>
114
+ @if(section.section)
115
+ <tr>
116
+ <th scope="colgroup" colspan="{{ plans.length + 1 }}" class="border-b border-line pb-2 pt-6 text-sm font-semibold text-fg">{{ section.section }}</th>
117
+ </tr>
118
+ @endif
119
+ @foreach(section.items as featureIndex => feature)
120
+ <tr class="border-b border-line">
121
+ <th scope="row" class="py-3 pr-4 font-normal text-fg-soft">{{ feature.label }}</th>
122
+ @foreach(plans as plan)
123
+ @if(plan.cells[sectionIndex][featureIndex].kind === 'included')
124
+ <td class="px-4 py-3 text-success"><svg class="h-5 w-5" aria-hidden="true" viewBox="0 0 20 20" fill="currentColor"><path fill-rule="evenodd" d="M16.704 4.153a.75.75 0 01.143 1.052l-8 10.5a.75.75 0 01-1.127.075l-4.5-4.5a.75.75 0 011.06-1.06l3.894 3.893 7.48-9.817a.75.75 0 011.05-.143z" clip-rule="evenodd" /></svg><span class="sr-only">Included</span></td>
125
+ @elseif(plan.cells[sectionIndex][featureIndex].kind === 'excluded')
126
+ <td class="px-4 py-3 text-fg-muted"><span aria-hidden="true">—</span><span class="sr-only">Not included</span></td>
127
+ @else
128
+ <td class="px-4 py-3 text-fg tabular-nums">{{ plan.cells[sectionIndex][featureIndex].text }}</td>
129
+ @endif
130
+ @endforeach
131
+ </tr>
132
+ @endforeach
133
+ </tbody>
134
+ @endforeach
135
+ </table>
136
+ </div>
137
+ @endif
138
+
139
+ @if($slots.footnotes)
140
+ <div class="mt-8 text-xs text-fg-soft" data-stx-pricing-footnotes><slot name="footnotes" /></div>
141
+ @endif
142
+ </section>
143
+
144
+ <style>
145
+ [data-stx-pricing][data-interval="month"] [data-price-interval="year"],
146
+ [data-stx-pricing][data-interval="year"] [data-price-interval="month"] {
147
+ display: none;
148
+ }
149
+ </style>
@@ -0,0 +1,74 @@
1
+ # Pricing
2
+
3
+ Plans side by side, from data: `<PricingTable>` renders a card per plan and, on wide screens, a feature matrix; `<PricingPlan>` is one card. Render them straight from your billing config so the pricing page cannot drift from what you charge.
4
+
5
+ ## Usage
6
+
7
+ ```stx
8
+ <script server>
9
+ import saas from '~/config/saas'
10
+
11
+ const plans = saas.plans.map(plan => ({
12
+ id: plan.productName.toLowerCase(),
13
+ name: plan.productName,
14
+ description: plan.description,
15
+ prices: {
16
+ month: plan.pricing.find(p => p.interval === 'month')?.price / 100,
17
+ year: plan.pricing.find(p => p.interval === 'year')?.price / 100,
18
+ },
19
+ features: plan.features, // { requests: 100000, sso: true, support: 'Email' }
20
+ highlighted: plan.productName === 'Pro',
21
+ }))
22
+
23
+ const features = [
24
+ { section: 'Usage', items: [{ key: 'requests', label: 'Requests per month', unit: 'requests' }, { key: 'keys', label: 'API keys' }] },
25
+ { section: 'Security and support', items: [{ key: 'sso', label: 'Single sign-on' }, { key: 'support', label: 'Support' }] },
26
+ ]
27
+ </script>
28
+
29
+ <PricingTable :plans="plans" :features="features" :currentPlan="team.plan" @select="startCheckout" @interval-change="track">
30
+ <p slot="footnotes">Prices exclude VAT. Yearly plans are billed once a year.</p>
31
+ </PricingTable>
32
+ ```
33
+
34
+ ## Plans
35
+
36
+ | Field | Type | Description |
37
+ |-------|------|-------------|
38
+ | `id` | `string` | Matched against `currentPlan`; defaults to the name as a slug |
39
+ | `name` | `string` | Required |
40
+ | `description` | `string` | One line under the name |
41
+ | `prices` | `{ month?, year? }` | In major units. `0` renders "Free"; `null` or absent renders "Custom" |
42
+ | `currency` | `string` | ISO code, default `USD` |
43
+ | `features` | `Record<string, boolean \| number \| string>` | `true` included, `false` excluded, a number or string is the value shown (`100,000 requests`) |
44
+ | `highlights` | `string[]` | Lines on the card; default the included features |
45
+ | `highlighted` | `boolean` | Ring the card and show `badge` ("Most popular") |
46
+ | `cta` | `string \| { label, href }` | The call to action; a link when it has `href` |
47
+
48
+ ## Props
49
+
50
+ ### PricingTable
51
+ | Prop | Type | Default | Description |
52
+ |------|------|---------|-------------|
53
+ | `plans` | `Plan[]` | - | The plans |
54
+ | `features` | `{ section, items: { key, label, unit }[] }[]` | every key the plans use | The matrix rows, grouped by section |
55
+ | `interval` | `'month' \| 'year'` | `'month'` | Interval shown first |
56
+ | `currentPlan` | `string` | - | Marks that plan and disables its call to action ("Current plan") |
57
+ | `locale` | `string` | `'en-US'` | Locale for prices and numbers (`Intl`) |
58
+ | `toggle` | `boolean` | `true` | Show the monthly/yearly SegmentedControl, labelled with the best yearly saving |
59
+ | `matrix` | `boolean` | `true` | Show the feature matrix on wide screens |
60
+ | `label` | `string` | `'Plans'` | Accessible name of the section |
61
+
62
+ Slots: the default slot replaces the generated cards (use `<PricingPlan>` children to give a plan its own call to action), and `footnotes`.
63
+
64
+ Events: `select` (plan, interval) when a call to action is chosen; `interval-change` (interval).
65
+
66
+ ### PricingPlan
67
+ `plan`, `features`, `interval` (pins the card to one interval; inside a table the toggle decides), `currentPlan`, `locale`, `className`. A `cta` slot replaces the call to action.
68
+
69
+ ## Layout and accessibility
70
+
71
+ - Cards stack on narrow screens and sit in up to four columns on wide ones; the matrix appears from the `lg` breakpoint, under the cards.
72
+ - Both intervals' prices are in the server's HTML, and the root's `data-interval` decides which is shown, so the page is complete without script.
73
+ - The matrix is a real table: plan names are column headers, features are row headers, sections are `colgroup` headers, and included or excluded cells say so in words for a screen reader.
74
+ - Colours come from the role tokens (`panel`, `accent`, `success`, `line`), so dark mode and an app's palette follow.
@@ -0,0 +1,49 @@
1
+ import type { PricingInterval, PricingPlanInput, PricingSectionInput } from './pricing'
2
+
3
+ export { default as PricingPlan } from './PricingPlan.stx'
4
+ export { default as PricingTable } from './PricingTable.stx'
5
+ export {
6
+ type FeatureCell,
7
+ formatFeature,
8
+ formatPrice,
9
+ type PreparedPlan,
10
+ preparePlans,
11
+ type PricedInterval,
12
+ type PricingCta,
13
+ type PricingFeatureInput,
14
+ type PricingInterval,
15
+ type PricingPlanInput,
16
+ type PricingSectionInput,
17
+ yearlySaving,
18
+ } from './pricing'
19
+
20
+ export interface PricingTableProps {
21
+ plans: PricingPlanInput[]
22
+ /** The feature matrix, grouped by section. Default: every feature key the plans mention. */
23
+ features?: PricingSectionInput[]
24
+ /** The interval shown first. Default `month`. */
25
+ interval?: PricingInterval
26
+ /** The id (or name slug) of the plan the customer is on: marked, and its call to action disabled. */
27
+ currentPlan?: string
28
+ /** Locale for prices and numbers. Default `en-US`. */
29
+ locale?: string
30
+ /** Accessible name of the section. Default `Plans`. */
31
+ label?: string
32
+ /** Show the monthly/yearly toggle. Default true. */
33
+ toggle?: boolean
34
+ /** Show the feature matrix on wide screens. Default true. */
35
+ matrix?: boolean
36
+ className?: string
37
+ onSelect?: (plan: PricingPlanInput, interval: PricingInterval) => void
38
+ onIntervalChange?: (interval: PricingInterval) => void
39
+ }
40
+
41
+ export interface PricingPlanProps {
42
+ plan: PricingPlanInput
43
+ features?: PricingSectionInput[]
44
+ /** Pin the card to one interval; inside a PricingTable the table's toggle decides. */
45
+ interval?: PricingInterval
46
+ currentPlan?: string
47
+ locale?: string
48
+ className?: string
49
+ }