@stacksjs/components 0.2.582 → 0.2.584

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.
@@ -133,7 +133,11 @@ const emit = defineEmits()
133
133
  *
134
134
  * See stacksjs/stx#1997.
135
135
  */
136
- const labelText = useReactiveProp('label', {{ label }}, { parse: value => value == null ? '' : String(value) })
136
+ const labelProp = useReactiveProp('label', {{ label }}, { parse: value => value == null ? '' : String(value) })
137
+ // Preserve native Button's text prop when the same shared file is selected.
138
+ // Read it as a prop, not a root text binding that would erase icons/spinners.
139
+ const textProp = useReactiveProp('text', '', { parse: value => value == null ? '' : String(value) })
140
+ const labelText = derived(() => labelProp() || textProp())
137
141
  const isLoading = useReactiveProp('loading', {{ loading }})
138
142
  const disabledProp = useReactiveProp('disabled', {{ disabled }})
139
143
 
@@ -54,18 +54,18 @@ export const form = $props.form || ''
54
54
  </script>
55
55
 
56
56
  <script client>
57
- const emit = defineEmits()
57
+ const emit = defineEmits(['change'])
58
58
  // Validity is live, for the same reason `disabled` is: a form posted with
59
59
  // fetch learns it after the submit, and nothing re-renders (#2047).
60
60
  const isError = useReactiveProp('error', {{ error }})
61
- const isDisabled = {{ disabled }}
62
- const isIndeterminate = {{ indeterminate }}
61
+ const isDisabled = useReactiveProp('disabled', {{ disabled }})
62
+ const isIndeterminate = useReactiveProp('indeterminate', {{ indeterminate }})
63
63
  // Reactive prop binding so the parent can drive `checked` via signals.
64
64
  // See stacksjs/stx#1704.
65
65
  const isChecked = useReactiveProp('checked', {{ checked }})
66
66
 
67
67
  function onInputChange(event) {
68
- if (isDisabled) {
68
+ if (isDisabled()) {
69
69
  event.target.checked = isChecked()
70
70
  return
71
71
  }
@@ -73,13 +73,6 @@ function onInputChange(event) {
73
73
  emit('change', isChecked())
74
74
  }
75
75
 
76
- onMount(() => {
77
- if (isIndeterminate) {
78
- const el = document.getElementById({{ inputId }})
79
- if (el) el.indeterminate = true
80
- }
81
- })
82
-
83
76
  defineExpose({ isChecked })
84
77
  </script>
85
78
 
@@ -100,12 +93,14 @@ defineExpose({ isChecked })
100
93
  @if(checked)checked@endif
101
94
  :checked="isChecked()"
102
95
  @if(disabled)disabled@endif
96
+ :disabled="isDisabled()"
97
+ :indeterminate="isIndeterminate()"
103
98
  @if(required)required@endif
104
99
  class="{{ checkboxClasses }}"
105
100
  @change="onInputChange($event)"
106
101
  aria-invalid="{{ error ? 'true' : 'false' }}"
107
102
  :aria-invalid="isError() ? 'true' : 'false'"
108
- :class="{ '{{ stateInvalidClasses }}': isError() }"
103
+ :class="{ '{{ stateInvalidClasses }}': isError(), 'opacity-50 cursor-not-allowed': isDisabled(), 'cursor-pointer': !isDisabled() }"
109
104
  @if(description)aria-describedby="{{ descriptionId }}"@endif
110
105
  />
111
106
  </div>
@@ -113,7 +108,7 @@ defineExpose({ isChecked })
113
108
  @if(label || description)
114
109
  <div class="ml-3 text-sm leading-6">
115
110
  @if(label)
116
- <label for="{{ inputId }}" class="{{ labelClasses }}">
111
+ <label for="{{ inputId }}" class="{{ labelClasses }}" :class="{ 'opacity-50 cursor-not-allowed': isDisabled(), 'cursor-pointer': !isDisabled() }">
117
112
  {{ label }}
118
113
  @if(required)
119
114
  <span class="text-danger ml-1">*</span>
@@ -42,6 +42,20 @@ const dialogInstanceId = {{ dialogInstanceId }}
42
42
  // and isOpen flips. See stacksjs/stx#1704.
43
43
  const isOpen = useReactiveProp('open', {{ open }})
44
44
  const rootRef = useRef('rootRef')
45
+ const tree = window.stx._host
46
+
47
+ function closestMarker(node, marker) {
48
+ for (let current = node; current; current = tree.parent(current)) {
49
+ if (tree.getAttribute(current, marker) != null) return current
50
+ }
51
+ return null
52
+ }
53
+
54
+ function ownPart(marker) {
55
+ const root = rootRef.value
56
+ if (!root) return null
57
+ return tree.descendants(root).find(node => tree.getAttribute(node, marker) != null && closestMarker(node, 'data-stx-dialog') === root) || null
58
+ }
45
59
 
46
60
  /*
47
61
  * Whether hydration has run.
@@ -71,11 +85,12 @@ onMount(() => {
71
85
  function labelFromTitle() {
72
86
  const root = rootRef.value
73
87
  if (!root) return
74
- if (root.getAttribute('aria-label') || root.getAttribute('aria-labelledby')) return
75
- const heading = root.querySelector('[data-stx-dialog-title]')
88
+ if (tree.getAttribute(root, 'aria-label') || tree.getAttribute(root, 'aria-labelledby')) return
89
+ const heading = ownPart('data-stx-dialog-title')
76
90
  if (!heading) return
77
- if (!heading.id) heading.id = `${dialogInstanceId}-title`
78
- root.setAttribute('aria-labelledby', heading.id)
91
+ const headingId = tree.getAttribute(heading, 'id') || `${dialogInstanceId}-title`
92
+ tree.setAttribute(heading, 'id', headingId)
93
+ tree.setAttribute(root, 'aria-labelledby', headingId)
79
94
  }
80
95
 
81
96
  const closeOnEscape = {{ closeOnEscape }}
@@ -90,7 +105,7 @@ function close() {
90
105
  function panelEl() {
91
106
  const root = rootRef.value
92
107
  if (!root) return null
93
- return root.querySelector('[data-stx-dialog-panel]') || root
108
+ return ownPart('data-stx-dialog-panel') || root
94
109
  }
95
110
 
96
111
  /*
@@ -106,7 +121,7 @@ function panelEl() {
106
121
  function onRootClick(event) {
107
122
  if (!closeOnBackdrop || !window.stx.overlays.isTop(dialogInstanceId)) return
108
123
  const target = event.target
109
- if (target && target.closest && target.closest('[data-stx-dialog-backdrop]')) close()
124
+ if (closestMarker(target, 'data-stx-dialog-backdrop') && closestMarker(target, 'data-stx-dialog') === rootRef.value) close()
110
125
  }
111
126
 
112
127
  /*
@@ -128,6 +143,7 @@ effect(() => {
128
143
  panel: panelEl,
129
144
  root: rootRef.value,
130
145
  onEscape: closeOnEscape ? close : null,
146
+ onBackdrop: closeOnBackdrop ? close : null,
131
147
  })
132
148
  }
133
149
  else {
@@ -149,6 +165,7 @@ defineExpose({
149
165
  </script>
150
166
 
151
167
  <div
168
+ data-native="Modal"
152
169
  x-ref="rootRef"
153
170
  :show="isOpen()"
154
171
  class="{{ dialogClasses }}"
@@ -125,6 +125,10 @@ const drawerInstanceId = {{ drawerInstanceId }}
125
125
  // (`:open="drawerOpen()"`) instead of the prop being captured once.
126
126
  // See stacksjs/stx#1704.
127
127
  const isOpen = useReactiveProp('open', {{ open }})
128
+ const rootRef = useRef('rootRef')
129
+ const panelRef = useRef('panelRef')
130
+ const mounted = state(false)
131
+ onMount(() => mounted.set(true))
128
132
 
129
133
  const closeOnEscape = {{ closeOnEscape }}
130
134
  const closeOnBackdrop = {{ closeOnBackdrop }}
@@ -139,7 +143,7 @@ function onBackdropClick() {
139
143
  }
140
144
 
141
145
  function panelEl() {
142
- return document.querySelector(`[data-stx-drawer-panel="${drawerInstanceId}"]`)
146
+ return panelRef.value
143
147
  }
144
148
 
145
149
  /*
@@ -152,10 +156,13 @@ function panelEl() {
152
156
  * dialog over it together (stacksjs/stx#2057).
153
157
  */
154
158
  effect(() => {
159
+ if (!mounted()) return
155
160
  if (isOpen()) {
156
161
  window.stx.overlays.open(drawerInstanceId, {
157
162
  panel: panelEl,
163
+ root: rootRef.value,
158
164
  onEscape: closeOnEscape ? close : null,
165
+ onBackdrop: closeOnBackdrop ? close : null,
159
166
  })
160
167
  }
161
168
  else {
@@ -174,7 +181,7 @@ defineExpose({
174
181
  })
175
182
  </script>
176
183
 
177
- <div :show="isOpen()">
184
+ <div x-ref="rootRef" data-native="Modal" data-stx-drawer="{{ drawerInstanceId }}" :show="isOpen()">
178
185
  <div
179
186
  class="fixed inset-0 z-50 {{ backdropClass }} transition-opacity duration-500"
180
187
  style="animation: fadeIn 0.5s ease-in-out"
@@ -189,6 +196,7 @@ defineExpose({
189
196
  class="{{ panelClasses }}"
190
197
  style="animation: {{ slideAnimation }} 0.5s ease-in-out"
191
198
  data-stx-drawer-panel="{{ drawerInstanceId }}"
199
+ x-ref="panelRef"
192
200
  role="dialog"
193
201
  aria-modal="true"
194
202
  aria-label="{{ title }}"
@@ -14,8 +14,9 @@ export const errorClasses = `mt-1 text-sm text-danger`.trim()
14
14
  </script>
15
15
 
16
16
  <script client>
17
- const emit = defineEmits()
18
- const validationSchema = {{ validationSchema }}
17
+ const emit = defineEmits(['submit', 'error'])
18
+ const validationSchema = useReactiveProp('validationSchema', {{ validationSchema }})
19
+ const formRoot = useRef('formRoot')
19
20
  const initialValues = {{ initialValues }}
20
21
  const validateOnChange = {{ validateOnChange }}
21
22
  const validateOnBlur = {{ validateOnBlur }}
@@ -28,7 +29,7 @@ const submitCount = state(0)
28
29
  const values = state({ ...initialValues })
29
30
 
30
31
  function validateField(name, value, allValues) {
31
- const schema = validationSchema[name]
32
+ const schema = validationSchema()[name]
32
33
  if (!schema) return null
33
34
  if (schema.required && !value) {
34
35
  return schema.requiredMessage || `${name} is required`
@@ -55,7 +56,7 @@ function validateField(name, value, allValues) {
55
56
  // Single field, used by the change/blur paths so one bad field does not wipe the
56
57
  // errors of the others the way a full validateForm() would.
57
58
  function validateOne(name, value) {
58
- if (!validationSchema[name]) return
59
+ if (!validationSchema()[name]) return
59
60
  const err = validateField(name, value, values())
60
61
  const next = { ...errors() }
61
62
  if (err) next[name] = err
@@ -66,23 +67,28 @@ function validateOne(name, value) {
66
67
  // Delegated on the <form> rather than bound per input: the children arrive
67
68
  // through <slot />, so the component never sees them individually. `input` and
68
69
  // `focusout` both bubble (`blur` does not, which is why focusout is used).
70
+ function fieldValue(target) {
71
+ return (target.type === 'checkbox' || target.type === 'radio') && !target.checked ? undefined : target.value
72
+ }
73
+
69
74
  function onFieldInput(event) {
70
75
  const name = event.target?.name
71
76
  if (!name) return
72
- values.set({ ...values(), [name]: event.target.value })
73
- if (validateOnChange) validateOne(name, event.target.value)
77
+ const value = fieldValue(event.target)
78
+ values.set({ ...values(), [name]: value })
79
+ if (validateOnChange) validateOne(name, value)
74
80
  }
75
81
 
76
82
  function onFieldBlur(event) {
77
83
  const name = event.target?.name
78
84
  if (!name) return
79
- if (validateOnBlur) validateOne(name, event.target.value)
85
+ if (validateOnBlur) validateOne(name, fieldValue(event.target))
80
86
  }
81
87
 
82
88
  function validateForm(values) {
83
89
  const next = {}
84
90
  let valid = true
85
- for (const name of Object.keys(validationSchema)) {
91
+ for (const name of Object.keys(validationSchema())) {
86
92
  const err = validateField(name, values[name], values)
87
93
  if (err) {
88
94
  next[name] = err
@@ -129,12 +135,23 @@ function setValues(next) {
129
135
  values.set({ ...values(), ...next })
130
136
  }
131
137
 
132
- function reset(form) {
138
+ function resetState() {
133
139
  errors.set({})
134
140
  isSubmitting.set(false)
135
141
  submitCount.set(0)
136
142
  values.set({ ...initialValues })
137
- if (form?.reset) form.reset()
143
+ }
144
+
145
+ function onReset(event) {
146
+ // A caller can cancel reset after this listener runs. Match the host's
147
+ // decision before discarding validation and submission state.
148
+ queueMicrotask(() => { if (!event.defaultPrevented) resetState() })
149
+ }
150
+
151
+ function reset(form) {
152
+ const target = form || formRoot()
153
+ if (target?.reset) target.reset()
154
+ else resetState()
138
155
  }
139
156
 
140
157
  // FormHelpers named setValues/resetForm; the component exposed setErrors/reset
@@ -151,12 +168,14 @@ defineExpose({ errors, values, isSubmitting, submitCount, setErrors, setValues,
151
168
  </script>
152
169
 
153
170
  <form
171
+ x-ref="formRoot"
154
172
  class="{{ formClasses }}"
155
173
  @if(action)action="{{ action }}"@endif
156
174
  method="{{ method }}"
157
175
  @submit="onSubmit($event)"
158
176
  @input="onFieldInput($event)"
159
177
  @focusout="onFieldBlur($event)"
178
+ @reset="onReset($event)"
160
179
  novalidate
161
180
  >
162
181
  <slot />
@@ -34,13 +34,13 @@ const sizeConfig = {
34
34
  export const config = sizeConfig[size] || sizeConfig.md
35
35
 
36
36
  export const trackBaseClasses = 'relative inline-flex shrink-0 cursor-pointer border-2 border-transparent rounded-full transition-colors duration-200 ease-in-out focus:outline-none focus-visible:ring-2 focus-visible:ring-accent focus-visible:ring-offset-2 focus-visible:ring-offset-panel'
37
- export const trackDisabledClasses = disabled ? 'opacity-50 cursor-not-allowed pointer-events-none' : ''
37
+ export const trackDisabledClasses = 'opacity-50 cursor-not-allowed pointer-events-none'
38
38
  export const thumbBaseClasses = 'pointer-events-none inline-block transform rounded-full bg-white shadow-lg ring-0 transition duration-200 ease-in-out'
39
39
  </script>
40
40
 
41
41
  <script client>
42
- const emit = defineEmits()
43
- const isDisabled = {{ disabled }}
42
+ const emit = defineEmits(['change'])
43
+ const isDisabled = useReactiveProp('disabled', {{ disabled }})
44
44
  const config = {{ config }}
45
45
  const trackBase = {{ trackBaseClasses }}
46
46
  const trackDisabled = {{ trackDisabledClasses }}
@@ -50,7 +50,7 @@ const extraClass = {{ className }}
50
50
  const isChecked = useModel('checked', { default: {{ checked }} })
51
51
 
52
52
  function toggle() {
53
- if (isDisabled) return
53
+ if (isDisabled()) return
54
54
  isChecked.set(!isChecked())
55
55
  emit('change', isChecked())
56
56
  }
@@ -59,7 +59,7 @@ function trackClasses() {
59
59
  const stateClass = isChecked()
60
60
  ? 'bg-accent-solid'
61
61
  : 'bg-neutral-400 dark:bg-neutral-600'
62
- return `${trackBase} ${stateClass} ${trackDisabled} ${config.track} ${extraClass}`.trim()
62
+ return `${trackBase} ${stateClass} ${isDisabled() ? trackDisabled : ''} ${config.track} ${extraClass}`.trim()
63
63
  }
64
64
 
65
65
  function thumbClasses() {
@@ -85,6 +85,8 @@ defineExpose({ isChecked, toggle })
85
85
  <input
86
86
  type="hidden"
87
87
  name="{{ name }}"
88
+ @if(disabled)disabled@endif
89
+ :disabled="isDisabled()"
88
90
  @if(form)form="{{ form }}"@endif
89
91
  value="{{ checked ? checkedValue : uncheckedValue }}"
90
92
  :value="isChecked() ? '{{ checkedValue }}' : '{{ uncheckedValue }}'"
@@ -97,6 +99,8 @@ defineExpose({ isChecked, toggle })
97
99
  :aria-checked="isChecked() ? 'true' : 'false'"
98
100
  :class="trackClasses()"
99
101
  @if(disabled)disabled aria-disabled="true"@endif
102
+ :disabled="isDisabled()"
103
+ :aria-disabled="isDisabled() ? 'true' : 'false'"
100
104
  @click="toggle()"
101
105
  >
102
106
  <span class="sr-only">@if(label){{ label }}@else Toggle switch@endif</span>
@@ -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 !!}