@stacksjs/components 0.2.583 → 0.2.585

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 (32) hide show
  1. package/dist/{Button-bpjmfkq6.stx → Button-55ahz0j6.stx} +5 -1
  2. package/dist/{Checkbox-kepzk3h5.stx → Checkbox-etjvbbxq.stx} +8 -13
  3. package/dist/{Dialog-pdq8rxvy.stx → Dialog-v79kqbbz.stx} +23 -6
  4. package/dist/{Drawer-nmq100vy.stx → Drawer-4rqfcg4f.stx} +10 -2
  5. package/dist/SegmentedControl-z2p70zps.stx +124 -0
  6. package/dist/{Switch-acwd7n07.stx → Switch-j1jf0mtn.stx} +9 -5
  7. package/dist/{TabList-76bpx5fp.stx → TabList-5xwk2zmz.stx} +26 -17
  8. package/dist/{Tabs-1swcxmfb.stx → Tabs-bp03efe6.stx} +69 -38
  9. package/dist/{Tooltip-rg1c2zrc.stx → Tooltip-4fv809dm.stx} +23 -11
  10. package/dist/index.d.ts +1 -0
  11. package/dist/index.js +7 -7
  12. package/dist/ui/button/index.d.ts +2 -0
  13. package/dist/ui/checkbox/Checkbox.d.ts +1 -1
  14. package/dist/ui/segmented-control/SegmentedControl.d.ts +70 -0
  15. package/dist/ui/segmented-control/index.d.ts +23 -0
  16. package/dist/ui/switch/Switch.d.ts +2 -2
  17. package/dist/ui/tabs/Tabs.d.ts +1 -1
  18. package/dist/utils/tooltip-position.d.ts +16 -0
  19. package/package.json +3 -3
  20. package/src/index.ts +1 -0
  21. package/src/ui/button/Button.stx +5 -1
  22. package/src/ui/button/index.ts +5 -0
  23. package/src/ui/checkbox/Checkbox.stx +8 -13
  24. package/src/ui/dialog/Dialog.stx +23 -6
  25. package/src/ui/drawer/Drawer.stx +10 -2
  26. package/src/ui/segmented-control/SegmentedControl.stx +124 -0
  27. package/src/ui/segmented-control/index.ts +29 -0
  28. package/src/ui/switch/Switch.stx +9 -5
  29. package/src/ui/tabs/TabList.stx +26 -17
  30. package/src/ui/tabs/Tabs.stx +69 -38
  31. package/src/ui/tooltip/Tooltip.stx +23 -11
  32. package/src/utils/tooltip-position.ts +40 -0
@@ -42,20 +42,29 @@ const emit = defineEmits()
42
42
  const orientation = {{ orientation }}
43
43
  const selected = useModel('value', { default: {{ value }}, parse: v => v == null ? '' : String(v) })
44
44
  const listRef = useRef('listRef')
45
+ const tree = window.stx._host
45
46
  const mounted = state(false)
46
- let observer = null
47
+ let stopObserving = null
48
+
49
+ function closestRole(node, role) {
50
+ for (let current = node; current; current = tree.parent(current)) {
51
+ if (tree.getAttribute(current, 'role') === role) return current
52
+ }
53
+ return null
54
+ }
47
55
 
48
56
  /** This list's own tabs: not a nested list's, and not a disabled one. */
49
57
  function ownTabs(includeDisabled) {
50
58
  const root = listRef.value
51
59
  if (!root) return []
52
- return Array.from(root.querySelectorAll('[role="tab"]')).filter(tab =>
53
- tab.closest('[role="tablist"]') === root
54
- && (includeDisabled || (!tab.hasAttribute('disabled') && tab.getAttribute('aria-disabled') !== 'true')))
60
+ return tree.descendants(root).filter(tab =>
61
+ tree.getAttribute(tab, 'role') === 'tab'
62
+ && closestRole(tab, 'tablist') === root
63
+ && (includeDisabled || (tree.getAttribute(tab, 'disabled') == null && tree.getAttribute(tab, 'aria-disabled') !== 'true')))
55
64
  }
56
65
 
57
66
  function valueOf(tab, index) {
58
- const value = tab.getAttribute('data-value')
67
+ const value = tree.getAttribute(tab, 'data-value')
59
68
  return value == null ? String(index) : value
60
69
  }
61
70
 
@@ -72,12 +81,12 @@ function sync() {
72
81
  tabs.forEach((tab, index) => {
73
82
  const on = valueOf(tab, index) === current
74
83
  if (on) any = true
75
- tab.setAttribute('aria-selected', on ? 'true' : 'false')
76
- tab.setAttribute('tabindex', on ? '0' : '-1')
84
+ tree.setAttribute(tab, 'aria-selected', on ? 'true' : 'false')
85
+ tree.setAttribute(tab, 'tabindex', on ? '0' : '-1')
77
86
  })
78
87
  if (!any) {
79
88
  const first = ownTabs(false)[0]
80
- if (first) first.setAttribute('tabindex', '0')
89
+ if (first) tree.setAttribute(first, 'tabindex', '0')
81
90
  }
82
91
  }
83
92
 
@@ -90,7 +99,7 @@ function select(tab) {
90
99
  }
91
100
 
92
101
  function onClick(event) {
93
- const tab = event.target && event.target.closest ? event.target.closest('[role="tab"]') : null
102
+ const tab = closestRole(event.target, 'tab')
94
103
  if (!tab || !ownTabs(false).includes(tab)) return
95
104
  select(tab)
96
105
  }
@@ -101,7 +110,7 @@ function onClick(event) {
101
110
  */
102
111
  function onKey(event) {
103
112
  const tabs = ownTabs(false)
104
- const from = event.target && event.target.closest ? event.target.closest('[role="tab"]') : null
113
+ const from = closestRole(event.target, 'tab')
105
114
  const index = tabs.indexOf(from)
106
115
  if (index === -1) return
107
116
  const forward = orientation === 'vertical' ? 'ArrowDown' : 'ArrowRight'
@@ -113,7 +122,10 @@ function onKey(event) {
113
122
  else if (event.key === 'End') next = tabs.length - 1
114
123
  if (next === -1) return
115
124
  event.preventDefault()
116
- tabs[next].focus()
125
+ // Native touch selection does not need keyboard focus. Until the native
126
+ // host provides that capability, do not silently pretend it moved focus.
127
+ if (typeof tabs[next].focus === 'function') tabs[next].focus()
128
+ else console.warn('[stx:TabList] This host cannot move keyboard focus; touch selection is supported.')
117
129
  select(tabs[next])
118
130
  }
119
131
 
@@ -126,15 +138,12 @@ onMount(() => {
126
138
  mounted.set(true)
127
139
  sync()
128
140
  const root = listRef.value
129
- if (root && typeof MutationObserver !== 'undefined') {
130
- observer = new MutationObserver(() => sync())
131
- observer.observe(root, { childList: true, subtree: true })
132
- }
141
+ if (root) stopObserving = tree.observeChildren(root, sync)
133
142
  })
134
143
 
135
144
  onDestroy(() => {
136
- if (observer) observer.disconnect()
137
- observer = null
145
+ if (stopObserving) stopObserving()
146
+ stopObserving = null
138
147
  })
139
148
 
140
149
  defineExpose({ selected })
@@ -39,7 +39,7 @@ export const containerClasses = `flex ${orientationClasses[orientation] || orien
39
39
  export const tabListClasses = `flex ${tabListOrientationClasses[orientation] || tabListOrientationClasses.horizontal} ${variantClasses[variant] || variantClasses.line}`.trim()
40
40
  export const tabPanelClasses = `p-4 focus:outline-none`.trim()
41
41
  // True when the parent passes a non-empty `tabs` array — switches to the
42
- // legacy render path so existing snapshots stay byte-identical.
42
+ // legacy render path, preserving the existing prop-array API.
43
43
  export const hasPropTabs = Array.isArray(tabs) && tabs.length > 0
44
44
  </script>
45
45
 
@@ -56,6 +56,10 @@ const hasPropTabs = {{ hasPropTabs }}
56
56
  // the list stayed empty, and the component rendered nothing.
57
57
  // stacksjs/stx#1979
58
58
  const containerRef = useRef('containerRef')
59
+ const tree = window.stx._host
60
+ const panelKeys = new WeakMap()
61
+ let nextPanelKey = 0
62
+ let stopObserving = null
59
63
  // In slot mode, `discoveredTabs` is populated from child <TabPanel> data
60
64
  // attributes on mount. In prop mode, it mirrors the `tabs` prop so the
61
65
  // rendering loop works the same in both modes.
@@ -75,41 +79,64 @@ const activeTab = state({{ defaultTab }})
75
79
  const mounted = state(false)
76
80
 
77
81
 
78
- // Walk only direct descendants of THIS container (not nested Tabs').
82
+ function owner(node) {
83
+ for (let current = node; current; current = tree.parent(current)) {
84
+ if (tree.getAttribute(current, 'data-stx-tabs') != null) return current
85
+ }
86
+ return null
87
+ }
88
+
89
+ // Walk [data-stx-tab-panel] descendants of THIS container, not nested Tabs'.
79
90
  function findOwnPanels() {
80
91
  const root = containerRef.value
81
92
  if (!root) return []
82
- // Closest ancestor with data-stx-tabs must be this container's root —
83
- // protects against nested <Tabs> contamination.
84
- return Array.from(root.querySelectorAll('[data-stx-tab-panel]'))
85
- .filter(p => p.closest('[data-stx-tabs]') === root)
93
+ return tree.descendants(root).filter(panel =>
94
+ tree.getAttribute(panel, 'data-stx-tab-panel') != null && owner(panel) === root)
86
95
  }
87
96
 
88
- onMount(() => {
89
- if (hasPropTabs) return // legacy mode: prop array already in discoveredTabs
97
+ function syncPanels() {
90
98
  const panels = findOwnPanels()
91
- /*
92
- * Give each panel an id and hand it to its tab, so the tab can point at it.
93
- *
94
- * Prop mode numbers both sides itself (`tab-N` / `tab-panel-N`), but in slot
95
- * mode the panels are the consumer's own markup and may carry no id at all --
96
- * so the tab button rendered with role="tab" and no aria-controls, and a
97
- * screen reader had no way to get from the tab to the panel it controls
98
- * (WCAG 4.1.2). Only assigned when the panel has no id of its own.
99
- */
100
- const list = panels.map((p, i) => {
101
- if (!p.id) p.id = `${tabsInstanceId}-panel-${i}`
102
- const tabId = `${tabsInstanceId}-tab-${i}`
103
- p.setAttribute('aria-labelledby', tabId)
99
+ const previous = discoveredTabs()
100
+ const selectedId = previous[activeTab()]?.panelId
101
+ const list = panels.map(panel => {
102
+ // Keys belong to panel identity, not its current index. Inserting a panel
103
+ // before the selected one must not recreate its tab or change selection.
104
+ if (!panelKeys.has(panel)) panelKeys.set(panel, nextPanelKey++)
105
+ const key = panelKeys.get(panel)
106
+ const panelId = tree.getAttribute(panel, 'id') || `${tabsInstanceId}-panel-${key}`
107
+ const tabId = `${tabsInstanceId}-tab-${key}`
108
+ if (tree.getAttribute(panel, 'id') !== panelId) tree.setAttribute(panel, 'id', panelId)
109
+ if (tree.getAttribute(panel, 'aria-labelledby') !== tabId) tree.setAttribute(panel, 'aria-labelledby', tabId)
104
110
  return {
105
- label: p.dataset.label || '',
106
- icon: p.dataset.icon || '',
107
- panelId: p.id,
111
+ label: tree.getAttribute(panel, 'data-label') || '',
112
+ icon: tree.getAttribute(panel, 'data-icon') || '',
113
+ panelId,
108
114
  tabId,
109
115
  }
110
116
  })
111
- discoveredTabs.set(list)
117
+ // Our own tab loop also changes the child tree. Do not feed those changes
118
+ // back into another render when the discovered panels are unchanged.
119
+ if (list.length === previous.length && list.every((tab, i) =>
120
+ tab.panelId === previous[i].panelId && tab.tabId === previous[i].tabId
121
+ && tab.label === previous[i].label && tab.icon === previous[i].icon)) return
122
+ const retained = list.findIndex(tab => tab.panelId === selectedId)
123
+ batch(() => {
124
+ activeTab.set(retained >= 0 ? retained : Math.max(0, Math.min(activeTab(), list.length - 1)))
125
+ discoveredTabs.set(list)
126
+ })
127
+ }
128
+
129
+ onMount(() => {
130
+ if (hasPropTabs) return
131
+ syncPanels()
112
132
  mounted.set(true)
133
+ if (containerRef.value) stopObserving = tree.observeChildren(containerRef.value, syncPanels)
134
+ })
135
+
136
+ onDestroy(() => {
137
+ if (stopObserving) stopObserving()
138
+ stopObserving = null
139
+ mounted.set(false)
113
140
  })
114
141
 
115
142
  // In slot mode, toggle each panel's `hidden` attribute as activeTab changes.
@@ -117,11 +144,13 @@ onMount(() => {
117
144
  effect(() => {
118
145
  if (hasPropTabs) return
119
146
  if (!mounted()) return
147
+ discoveredTabs()
120
148
  const panels = findOwnPanels()
121
149
  const idx = activeTab()
122
150
  panels.forEach((p, i) => {
123
- if (i === idx) p.removeAttribute('hidden')
124
- else p.setAttribute('hidden', '')
151
+ if (i === idx) tree.removeAttribute(p, 'hidden')
152
+ else tree.setAttribute(p, 'hidden', '')
153
+ tree.setVisible(p, i === idx)
125
154
  })
126
155
  })
127
156
 
@@ -154,6 +183,7 @@ function getTabClasses(index) {
154
183
 
155
184
  function onTabKey(event, index) {
156
185
  const tabCount = discoveredTabs().length
186
+ if (!tabCount) return
157
187
  let next = index
158
188
  if (orientation === 'horizontal') {
159
189
  if (event.key === 'ArrowRight') { event.preventDefault(); next = (index + 1) % tabCount }
@@ -167,10 +197,12 @@ function onTabKey(event, index) {
167
197
  else if (event.key === 'End') { event.preventDefault(); next = tabCount - 1 }
168
198
  if (next !== index) {
169
199
  selectTab(next)
170
- // Slot mode numbers its tabs per instance; `tab-N` is the prop mode's id,
171
- // so arrowing in slot mode moved the selection and left focus behind.
172
- const id = hasPropTabs ? `tab-${next}` : discoveredTabs()[next]?.tabId
173
- if (id) document.getElementById(id)?.focus()
200
+ // Both modes number tabs per instance. Search only this component's tree
201
+ // so another tab set cannot receive the focus intended for this one.
202
+ const id = hasPropTabs ? `${tabsInstanceId}-tab-${next}` : discoveredTabs()[next]?.tabId
203
+ const tab = tree.descendants(containerRef.value).find(node => tree.getAttribute(node, 'id') === id)
204
+ if (tab && typeof tab.focus === 'function') tab.focus()
205
+ else if (tab) console.warn('[stx:Tabs] This host cannot move keyboard focus; touch selection is supported. Native focus requires craft-native/craft#373.')
174
206
  }
175
207
  }
176
208
 
@@ -185,16 +217,15 @@ defineExpose({ activeTab, selectTab })
185
217
  >
186
218
  @if(hasPropTabs)
187
219
  {{-- Legacy mode: server-side iterate the prop tabs array. Buttons --}}
188
- {{-- get static class names so existing visual snapshots stay --}}
189
- {{-- byte-identical. --}}
220
+ {{-- retain their original prop-driven classes and content. --}}
190
221
  @foreach(tab in tabs)
191
222
  <button
192
223
  type="button"
193
224
  :class="getTabClasses({{ $loop.index }})"
194
225
  role="tab"
195
226
  :aria-selected="isActive({{ $loop.index }}) ? 'true' : 'false'"
196
- aria-controls="tab-panel-{{ $loop.index }}"
197
- id="tab-{{ $loop.index }}"
227
+ aria-controls="{{ tabsInstanceId }}-panel-{{ $loop.index }}"
228
+ id="{{ tabsInstanceId }}-tab-{{ $loop.index }}"
198
229
  :tabindex="isActive({{ $loop.index }}) ? '0' : '-1'"
199
230
  @click="selectTab({{ $loop.index }})"
200
231
  @keydown="onTabKey($event, {{ $loop.index }})"
@@ -214,7 +245,7 @@ defineExpose({ activeTab, selectTab })
214
245
  {{-- discoveredTabs() which is populated in onMount. --}}
215
246
  <button
216
247
  :for="(tab, idx) in discoveredTabs()"
217
- :key="idx"
248
+ :key="tab.tabId"
218
249
  type="button"
219
250
  x-class="getTabClasses(idx)"
220
251
  role="tab"
@@ -235,10 +266,10 @@ defineExpose({ activeTab, selectTab })
235
266
  @foreach(tab in tabs)
236
267
  <div
237
268
  :show="isActive({{ $loop.index }})"
238
- id="tab-panel-{{ $loop.index }}"
269
+ id="{{ tabsInstanceId }}-panel-{{ $loop.index }}"
239
270
  class="{{ tabPanelClasses }}"
240
271
  role="tabpanel"
241
- aria-labelledby="tab-{{ $loop.index }}"
272
+ aria-labelledby="{{ tabsInstanceId }}-tab-{{ $loop.index }}"
242
273
  tabindex="0"
243
274
  >
244
275
  {!! tab.content !!}
@@ -55,7 +55,7 @@ export const arrowClass = `absolute w-0 h-0 border-4 border-transparent ${arrowC
55
55
  </script>
56
56
 
57
57
  <script client>
58
- import { tooltipPosition } from '../../utils/tooltip-position'
58
+ import { measureTooltipPosition } from '../../utils/tooltip-position'
59
59
  import { portalElement } from '../../utils/element-portal'
60
60
  const delay = {{ delay }}
61
61
  // A live prop: a tooltip is commonly suppressed by state the page only learns
@@ -74,21 +74,26 @@ const isDisabled = useReactiveProp('disabled', {{ disabled }})
74
74
  // Reactive prop binding — parent can drive `show` via signals. See #1704.
75
75
  const isVisible = useReactiveProp('show', {{ show }})
76
76
  let timeoutId = null
77
+ let positionGeneration = 0
78
+ let destroyed = false
77
79
 
78
80
  // Use the actual offset parent, so a tooltip inside a modal or a transformed
79
81
  // container still gets viewport bounds rather than assuming document origin.
80
- function positionTooltip() {
81
- if (!isVisible()) return
82
+ async function positionTooltip() {
83
+ const generation = ++positionGeneration
84
+ if (destroyed || !isVisible() || isDisabled()) return
82
85
  const trigger = triggerRef.value
83
86
  const panel = panelRef.value
84
87
  if (!trigger || !panel) return
85
- const rect = panel.getBoundingClientRect()
86
- if (!rect.width || !rect.height) return
87
- const origin = panel.offsetParent ? panel.offsetParent.getBoundingClientRect() : { left: 0, top: 0 }
88
- const viewport = trigger.ownerDocument.defaultView
89
- if (!viewport) return
90
- const point = tooltipPosition(trigger.getBoundingClientRect(), rect, { width: viewport.innerWidth, height: viewport.innerHeight }, preferredSide)
91
- panelStyle.set(panelLimits + 'left:' + (point.left - origin.left) + 'px;top:' + (point.top - origin.top) + 'px;right:auto;bottom:auto;transform:none;translate:none;')
88
+ let point
89
+ try { point = await measureTooltipPosition(trigger, panel, preferredSide) }
90
+ catch (error) {
91
+ if (!destroyed && generation === positionGeneration && isVisible() && !isDisabled())
92
+ console.warn('[stx:tooltip] Could not measure popup: ' + ((error && error.message) || String(error)))
93
+ return
94
+ }
95
+ if (!point || destroyed || generation !== positionGeneration || !isVisible() || isDisabled()) return
96
+ panelStyle.set(panelLimits + 'left:' + point.left + 'px;top:' + point.top + 'px;right:auto;bottom:auto;transform:none;translate:none;')
92
97
  const color = 'var(--color-inverse, #0f172a)'
93
98
  const arrows = {
94
99
  top: 'top:auto;bottom:-8px;left:' + (point.arrowX - 4) + 'px;right:auto;border-top-color:' + color,
@@ -101,7 +106,10 @@ function positionTooltip() {
101
106
 
102
107
  // Measurement follows rendering. Reposition on scroll, including scrolling
103
108
  // ancestors, and resize; the composable removes these listeners on teardown.
104
- effect(() => { if (isVisible()) nextTick(positionTooltip) })
109
+ effect(() => {
110
+ ++positionGeneration
111
+ if (isVisible() && !isDisabled()) nextTick(positionTooltip)
112
+ })
105
113
  useEventListener('resize', positionTooltip)
106
114
  useEventListener('scroll', positionTooltip, { capture: true, passive: true })
107
115
 
@@ -116,6 +124,7 @@ function showTooltip() {
116
124
  }
117
125
 
118
126
  function hideTooltip() {
127
+ ++positionGeneration
119
128
  if (timeoutId) {
120
129
  clearTimeout(timeoutId)
121
130
  timeoutId = null
@@ -145,6 +154,9 @@ effect(() => {
145
154
  })
146
155
 
147
156
  onDestroy(() => {
157
+ destroyed = true
158
+ ++positionGeneration
159
+ if (timeoutId) clearTimeout(timeoutId)
148
160
  window.stx.overlays.close(tooltipId)
149
161
  })
150
162
 
@@ -1,6 +1,46 @@
1
1
  export interface TooltipAnchor { left: number, top: number, right: number, bottom: number }
2
2
  export type TooltipSide = 'top' | 'bottom' | 'left' | 'right'
3
3
 
4
+ interface NativeTooltipBounds {
5
+ x: number
6
+ y: number
7
+ width: number
8
+ height: number
9
+ viewportWidth: number
10
+ viewportHeight: number
11
+ unit: 'points' | 'dp'
12
+ coordinateSpace: 'screenViewport'
13
+ }
14
+ interface NativeTooltipView {
15
+ measure: () => Promise<NativeTooltipBounds>
16
+ parentElement?: NativeTooltipView | null
17
+ }
18
+
19
+ /** Read real host bounds, returning coordinates relative to the panel's positioning parent. */
20
+ export async function measureTooltipPosition(trigger: HTMLElement | NativeTooltipView, panel: HTMLElement | NativeTooltipView, preferred: TooltipSide = 'top') {
21
+ if ('measure' in trigger) {
22
+ if (!('measure' in panel)) throw new Error('Tooltip panel requires native viewMeasure support')
23
+ const [anchor, bounds, origin] = await Promise.all([
24
+ trigger.measure(), panel.measure(), panel.parentElement?.measure(),
25
+ ])
26
+ for (const box of [bounds, origin]) {
27
+ if (box && (box.unit !== anchor.unit || box.coordinateSpace !== anchor.coordinateSpace
28
+ || box.viewportWidth !== anchor.viewportWidth || box.viewportHeight !== anchor.viewportHeight))
29
+ throw new Error('Tooltip measurements must share viewport dimensions, coordinates, and units')
30
+ }
31
+ if (!bounds.width || !bounds.height) return null
32
+ const point = tooltipPosition({ left: anchor.x, top: anchor.y, right: anchor.x + anchor.width, bottom: anchor.y + anchor.height }, bounds, { width: anchor.viewportWidth, height: anchor.viewportHeight }, preferred)
33
+ return { ...point, left: point.left - (origin?.x ?? 0), top: point.top - (origin?.y ?? 0) }
34
+ }
35
+ if (!('getBoundingClientRect' in panel)) throw new Error('Tooltip panel requires browser layout measurements')
36
+ const rect = panel.getBoundingClientRect()
37
+ const viewport = trigger.ownerDocument.defaultView
38
+ if (!rect.width || !rect.height || !viewport) return null
39
+ const origin = panel.offsetParent?.getBoundingClientRect()
40
+ const point = tooltipPosition(trigger.getBoundingClientRect(), rect, { width: viewport.innerWidth, height: viewport.innerHeight }, preferred)
41
+ return { ...point, left: point.left - (origin?.left ?? 0), top: point.top - (origin?.top ?? 0) }
42
+ }
43
+
4
44
  /** Position in viewport coordinates; flip when possible, then keep every edge readable. */
5
45
  export function tooltipPosition(anchor: TooltipAnchor, panel: { width: number, height: number }, viewport: { width: number, height: number }, preferred: TooltipSide = 'top') {
6
46
  const gap = 8