@stacksjs/components 0.2.917 → 0.2.921

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.
@@ -0,0 +1,137 @@
1
+ <script server>
2
+ /*
3
+ * <RenderSurface>: a box shared TypeScript draws into, frame by frame, with
4
+ * no WebView (stacksjs/stx#2108, craft-native/craft#578).
5
+ *
6
+ * <RenderSurface class="flex-1" filter="nearest"
7
+ * @ready="loop = startRenderLoop($event.surface, paint)"
8
+ * @restored="loop.wake()" @error="report($event)" />
9
+ *
10
+ * On a native screen it is the host's RenderSurface, drawn with Metal; in a
11
+ * browser it is a <canvas>. Frames go in through `presentFrame` or
12
+ * `startRenderLoop` from `@stacksjs/components/render-surface`, by the name
13
+ * `ready` carries.
14
+ *
15
+ * Props:
16
+ * - `surface`: the name frames are given to. Unique on the screen; when it is
17
+ * left out each instance gets its own. A second live surface of a name
18
+ * already taken stays blank and reports `DUPLICATE`.
19
+ * - `filter`: `nearest` (the default, for pixel art) or `linear`, used when a
20
+ * frame's size differs from the box's pixels.
21
+ * - `opaque`: true by default. A surface that is not opaque takes
22
+ * premultiplied alpha.
23
+ * - `label`: what a screen reader says for it.
24
+ * - `unavailableText`: what shows in its place where nothing can draw one.
25
+ *
26
+ * Events:
27
+ * - `ready` the first time it has a size, then `resize` on each change, both
28
+ * `{ surface, width, height, scale, pixelWidth, pixelHeight }`;
29
+ * - `lost` (`{ surface, reason }`) when the app goes to the background on a
30
+ * phone, and `restored` (the metrics again) when it returns: nothing is
31
+ * kept across a loss, so draw a whole frame again;
32
+ * - `error` with `{ surface, code, message }`: `UNAVAILABLE` where this device
33
+ * cannot draw one (the box then says so rather than staying blank), or
34
+ * `DUPLICATE`.
35
+ */
36
+ export const surface = $props.surface || `surface-${$uid}`
37
+ export const filter = $props.filter === 'linear' ? 'linear' : 'nearest'
38
+ export const opaque = $bool($props.opaque, true)
39
+ export const className = $props.className || $props.class || ''
40
+ export const label = $props.label || ''
41
+ export const unavailableText = $props.unavailableText || 'This device cannot draw this view.'
42
+ </script>
43
+
44
+ <script client>
45
+ import { claimCanvasSurface, renderSurfaceHost } from './render-surface'
46
+
47
+ const emit = defineEmits(['ready', 'resize', 'lost', 'restored', 'error'])
48
+ const name = {{ surface }}
49
+ const filter = {{ filter }}
50
+ const opaque = {{ opaque }}
51
+ const nativeHost = !!window.stx._host.isNative
52
+ const canvasRef = useRef('canvasRef')
53
+ const unavailable = state(false)
54
+ let claim = null
55
+ let observer = null
56
+ let sized = false
57
+
58
+ // A host event carries its payload as nativeEvent; the shared runtime may
59
+ // also hand it over as it is.
60
+ function payload(event) {
61
+ return (event && event.nativeEvent) || event || {}
62
+ }
63
+
64
+ function metrics(event) {
65
+ const m = payload(event)
66
+ return { surface: name, width: m.width, height: m.height, scale: m.scale, pixelWidth: m.pixelWidth, pixelHeight: m.pixelHeight }
67
+ }
68
+
69
+ function fail(error) {
70
+ if (error.code === 'UNAVAILABLE') unavailable.set(true)
71
+ // Reported, never swallowed: a DUPLICATE is a page mistake, and the box
72
+ // stays blank until it is fixed.
73
+ emit('error', { surface: name, code: String(error.code || 'ERROR'), message: String(error.message || '') })
74
+ }
75
+
76
+ function hostReady(event) { emit('ready', metrics(event)) }
77
+ function hostResize(event) { emit('resize', metrics(event)) }
78
+ function hostLost(event) { emit('lost', { surface: name, reason: String(payload(event).reason || 'background') }) }
79
+ function hostRestored(event) { emit('restored', metrics(event)) }
80
+ function hostError(event) { fail(payload(event)) }
81
+
82
+ // A browser has no surface events of its own. The canvas's size stands in
83
+ // for them: its first size is `ready`, each change after it `resize`.
84
+ function measure() {
85
+ const canvas = canvasRef.value
86
+ if (!canvas || !claim || claim.error) return
87
+ const box = canvas.getBoundingClientRect()
88
+ if (box.width <= 0 || box.height <= 0) return
89
+ const scale = window.devicePixelRatio || 1
90
+ const detail = { surface: name, width: box.width, height: box.height, scale, pixelWidth: Math.round(box.width * scale), pixelHeight: Math.round(box.height * scale) }
91
+ emit(sized ? 'resize' : 'ready', detail)
92
+ sized = true
93
+ }
94
+
95
+ onMount(() => {
96
+ // Per mount: an :if can take the surface away and bring it back with the
97
+ // same setup, and coming back is a new surface with a ready of its own.
98
+ sized = false
99
+ if (nativeHost) {
100
+ // The host also says UNAVAILABLE once at mount; knowing it here shows the
101
+ // fallback without waiting for that.
102
+ if (renderSurfaceHost() === 'none') unavailable.set(true)
103
+ return
104
+ }
105
+ const canvas = canvasRef.value
106
+ if (!canvas) return
107
+ canvas.style.imageRendering = filter === 'nearest' ? 'pixelated' : 'auto'
108
+ claim = claimCanvasSurface(name, canvas, { opaque })
109
+ if (claim.error) { fail(claim.error); return }
110
+ // The observer's first answer, after layout, is the ready. Measured here
111
+ // instead, a surface mounted again under an :if said ready before the
112
+ // page's listener was back on it, and the page never heard.
113
+ if (typeof ResizeObserver === 'function') {
114
+ observer = new ResizeObserver(() => measure())
115
+ observer.observe(canvas)
116
+ }
117
+ else setTimeout(measure, 0)
118
+ })
119
+
120
+ onDestroy(() => {
121
+ sized = false
122
+ if (observer) observer.disconnect()
123
+ observer = null
124
+ if (claim && claim.release) claim.release()
125
+ claim = null
126
+ })
127
+
128
+ defineExpose({ surface: name, unavailable })
129
+ </script>
130
+
131
+ {{-- data-stx-layout-root: a phone has no display:contents, so the scope around
132
+ this root is a real box there, and an unsized one left the surface 0
133
+ points wide in a row: the host never said ready. --}}
134
+ <div class="relative flex flex-col min-h-0 min-w-0 {{ className }}" data-render-surface data-stx-layout-root>
135
+ <canvas data-native="RenderSurface" ref="canvasRef" surface="{{ surface }}" filter="{{ filter }}" :opaque="{{ opaque }}" role="img" @if(label) aria-label="{{ label }}" @endif class="flex-1 block w-full min-h-0 min-w-0" @ready="hostReady($event)" @resize="hostResize($event)" @lost="hostLost($event)" @restored="hostRestored($event)" @error="hostError($event)"></canvas>
136
+ <div :show="unavailable()" role="status" class="absolute inset-0 flex items-center justify-center p-4 text-center text-sm text-fg-muted">{{ unavailableText }}</div>
137
+ </div>
@@ -5,6 +5,7 @@ export const delay = $num($props.delay) || 0
5
5
  export const className = $props.className || ''
6
6
  export const show = $bool($props.show)
7
7
  export const disabled = $bool($props.disabled)
8
+ export const pressToToggle = $bool($props.pressToToggle)
8
9
 
9
10
  /*
10
11
  * The id that makes the tooltip reachable from its trigger.
@@ -55,7 +56,7 @@ export const arrowClass = `absolute w-0 h-0 border-4 border-transparent ${arrowC
55
56
  </script>
56
57
 
57
58
  <script client>
58
- import { measureTooltipPosition, trackNativePopup } from '../../utils/tooltip-position'
59
+ import { measureTooltipPosition, trackBrowserPopup, trackNativePopup } from '../../utils/tooltip-position'
59
60
  import { portalElement } from '../../utils/element-portal'
60
61
  const nativePopup = !!window.stx._host.isNative
61
62
  const mounted = state(false)
@@ -76,9 +77,11 @@ const arrowStyle = state('')
76
77
  // fallback duplicated this entire setup for every different hint on a page.
77
78
  const tooltipContent = useReactiveProp('content', '')
78
79
  const isDisabled = useReactiveProp('disabled', {{ disabled }})
80
+ const pressToToggle = useReactiveProp('pressToToggle', {{ pressToToggle }})
79
81
  // Reactive prop binding — parent can drive `show` via signals. See #1704.
80
82
  const isVisible = useReactiveProp('show', {{ show }})
81
83
  let timeoutId = null
84
+ let pointerExitTimeout = null
82
85
  let positionGeneration = 0
83
86
  let destroyed = false
84
87
 
@@ -110,35 +113,52 @@ async function positionTooltip() {
110
113
  arrowStyle.set('transform:none;translate:none;border-color:transparent;' + arrows[point.side] + ';')
111
114
  }
112
115
 
113
- // Measurement follows rendering. Reposition on scroll, including scrolling
114
- // ancestors, and resize; the composable removes these listeners on teardown.
115
- effect(() => {
116
- ++positionGeneration
117
- if (!nativePopup && isVisible() && !isDisabled()) nextTick(positionTooltip)
118
- })
119
- useEventListener('resize', positionTooltip)
120
- useEventListener('scroll', positionTooltip, { capture: true, passive: true })
121
-
122
116
  function showTooltip() {
123
- if (isDisabled()) return
117
+ if (isDisabled() || pressToToggle()) return
118
+ cancelPointerExit()
119
+ if (isVisible()) return
124
120
  if (timeoutId) clearTimeout(timeoutId)
125
121
  if (delay > 0) {
126
- timeoutId = setTimeout(() => { if (!destroyed && !isDisabled()) isVisible.set(true) }, delay)
122
+ timeoutId = setTimeout(() => {
123
+ timeoutId = null
124
+ if (!destroyed && !isDisabled() && !pressToToggle()) isVisible.set(true)
125
+ }, delay)
127
126
  }
128
127
  else {
129
128
  isVisible.set(true)
130
129
  }
131
130
  }
132
131
 
132
+ function cancelPointerExit() {
133
+ if (pointerExitTimeout === null) return
134
+ clearTimeout(pointerExitTimeout)
135
+ pointerExitTimeout = null
136
+ }
137
+
138
+ function leaveTooltip() {
139
+ if (pressToToggle()) return
140
+ if (!isVisible()) { hideTooltip(); return }
141
+ cancelPointerExit()
142
+ // A portaled panel has an eight-pixel gap from its trigger. Let a pointer
143
+ // cross that gap without losing the text it was approaching to read.
144
+ pointerExitTimeout = setTimeout(hideTooltip, 160)
145
+ }
146
+
133
147
  function toggleTouch(event) {
134
148
  // A shared Button emits click before the original press bubbles here.
135
149
  // Only the physical press toggles; otherwise one tap opens then closes.
136
150
  if (event && Array.isArray(event.__stx_emit_args)) return
137
- if (nativePopup) isVisible() ? hideTooltip() : showTooltip()
151
+ if (isDisabled()) return
152
+ if (pressToToggle()) {
153
+ if (isVisible()) hideTooltip()
154
+ else isVisible.set(true)
155
+ }
156
+ else if (nativePopup) isVisible() ? hideTooltip() : showTooltip()
138
157
  }
139
158
 
140
159
  function hideTooltip() {
141
160
  ++positionGeneration
161
+ cancelPointerExit()
142
162
  if (timeoutId) {
143
163
  clearTimeout(timeoutId)
144
164
  timeoutId = null
@@ -146,16 +166,6 @@ function hideTooltip() {
146
166
  isVisible.set(false)
147
167
  }
148
168
 
149
- /*
150
- * Escape dismisses it (WCAG 2.1 SC 1.4.13).
151
- *
152
- * The rule is that content shown on hover or focus can be dismissed WITHOUT
153
- * moving the pointer or the focus -- so a keyboard listener on the trigger is
154
- * not enough when the tooltip was opened by hovering and focus is somewhere
155
- * else entirely. The listener is global for that reason, and does nothing
156
- * unless this tooltip is the one showing. useEventListener drops it on
157
- * teardown, so a page of tooltips does not leak one apiece.
158
- */
159
169
  /*
160
170
  * While it shows, the tooltip is a popup layer on the page's overlay stack, so
161
171
  * Escape dismisses it first: a tooltip over a dialog's field goes, and the
@@ -165,13 +175,17 @@ function hideTooltip() {
165
175
  let stopPositioning = null
166
176
  effect(() => {
167
177
  if (!mounted()) return
178
+ ++positionGeneration
168
179
  if (stopPositioning) { stopPositioning(); stopPositioning = null }
169
180
  if (isVisible() && !isDisabled()) {
170
181
  try {
171
182
  if (nativePopup && !window.craft?.capabilities?.viewMeasure)
172
183
  throw new Error('Native Tooltip requires viewMeasure support')
173
184
  window.stx.overlays.open(activeTooltipId, { modal: false, root: nativePopup ? panelRef.value : null, panel: null, onEscape: hideTooltip, onBackdrop: hideTooltip })
174
- if (nativePopup) stopPositioning = trackNativePopup(triggerRef.value, panelRef.value, preferredSide, style => panelStyle.set(style))
185
+ const trigger = triggerRef.value
186
+ const panel = panelRef.value
187
+ if (nativePopup) stopPositioning = trackNativePopup(trigger, panel, preferredSide, style => panelStyle.set(style))
188
+ else if (trigger && panel) stopPositioning = trackBrowserPopup(trigger, panel, positionTooltip)
175
189
  }
176
190
  catch (error) {
177
191
  console.warn('[stx:tooltip] ' + ((error && error.message) || String(error)))
@@ -184,6 +198,7 @@ effect(() => {
184
198
  onDestroy(() => {
185
199
  destroyed = true
186
200
  ++positionGeneration
201
+ cancelPointerExit()
187
202
  if (timeoutId) clearTimeout(timeoutId)
188
203
  if (stopPositioning) stopPositioning()
189
204
  window.stx.overlays.close(activeTooltipId)
@@ -211,9 +226,9 @@ onDestroy(() => {
211
226
  function describeTrigger() {
212
227
  const wrapper = triggerRef.value
213
228
  if (!wrapper) return
214
- // The control, or the wrapper itself when the trigger is bare text and
215
- // there is nothing better to carry it.
216
- const target = wrapper.firstElementChild || wrapper
229
+ // A slotted component can wrap its actual control in a scope element.
230
+ const control = !nativePopup && wrapper.querySelector('button, a[href], input:not([type="hidden"]), select, textarea, summary, [role="button"], [role="link"], [tabindex]')
231
+ const target = control || wrapper.firstElementChild || wrapper
217
232
  // A repeated trigger can inherit the template instance's description. Replace
218
233
  // only our own previous id, preserving descriptions supplied by the caller.
219
234
  const previous = target.getAttribute('data-stx-tooltip-description')
@@ -241,7 +256,11 @@ onMount(() => {
241
256
  // its reactive bindings and refs, unlike passing them through another scope.
242
257
  nextTick(() => {
243
258
  const panel = panelRef.value
244
- if (!nativePopup && !destroyed && panel && panel.isConnected) restorePanel = portalElement(panel, panel.ownerDocument.body)
259
+ if (nativePopup || destroyed || !panel?.isConnected) return
260
+ // Keep a tooltip opened in a modal with that modal. The shared overlay
261
+ // stack makes its body siblings inert, including a panel portaled there.
262
+ const modal = triggerRef.value?.closest('dialog, [aria-modal="true"]')
263
+ restorePanel = portalElement(panel, modal || panel.ownerDocument.body)
245
264
  })
246
265
  })
247
266
  onDestroy(() => { if (restorePanel) restorePanel() })
@@ -258,7 +277,7 @@ onDestroy(() => { if (restorePanel) restorePanel() })
258
277
  x-ref="triggerRef"
259
278
  @click="toggleTouch($event)"
260
279
  @mouseenter="showTooltip()"
261
- @mouseleave="hideTooltip()"
280
+ @mouseleave="leaveTooltip()"
262
281
  @focusin="showTooltip()"
263
282
  @focusout="hideTooltip()"
264
283
  >
@@ -276,7 +295,7 @@ onDestroy(() => { if (restorePanel) restorePanel() })
276
295
  class="{{ tooltipClasses }}"
277
296
  role="tooltip"
278
297
  @mouseenter="showTooltip()"
279
- @mouseleave="hideTooltip()"
298
+ @mouseleave="leaveTooltip()"
280
299
  >
281
300
  <span class="block" style="max-height:calc(100vh - 32px);overflow-y:auto;" :text="tooltipContent">{{ content }}</span>
282
301
  <span :show="!nativePopup" class="{{ arrowClass }}" :style="arrowStyle"></span>
package/dist/index.d.ts CHANGED
@@ -86,6 +86,7 @@ export * from './ui/preview-frame/index';
86
86
  export * from './ui/progress/index';
87
87
  export * from './ui/radio/index';
88
88
  export * from './ui/radio-group/index';
89
+ export * from './ui/render-surface/index';
89
90
  export * from './ui/segmented-control/index';
90
91
  export * from './ui/select/index';
91
92
  export * from './ui/settings/index';