@knitui/components 0.12.2 → 0.14.0

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 (60) hide show
  1. package/lib/commonjs/Avatar/Avatar.js +4 -0
  2. package/lib/commonjs/Avatar/Avatar.js.map +1 -1
  3. package/lib/commonjs/Card/Card.js +8 -3
  4. package/lib/commonjs/Card/Card.js.map +1 -1
  5. package/lib/commonjs/Image/Image.js +197 -22
  6. package/lib/commonjs/Image/Image.js.map +1 -1
  7. package/lib/commonjs/Image/Image.native.js +41 -0
  8. package/lib/commonjs/Image/Image.native.js.map +1 -0
  9. package/lib/commonjs/Image/createImage.js +76 -2
  10. package/lib/commonjs/Image/createImage.js.map +1 -1
  11. package/lib/commonjs/Input/shared.js +12 -10
  12. package/lib/commonjs/Input/shared.js.map +1 -1
  13. package/lib/commonjs/PinInput/PinInput.js +14 -5
  14. package/lib/commonjs/PinInput/PinInput.js.map +1 -1
  15. package/lib/commonjs/SimpleGrid/SimpleGrid.js +47 -27
  16. package/lib/commonjs/SimpleGrid/SimpleGrid.js.map +1 -1
  17. package/lib/commonjs/Tabs/Tabs.js +56 -11
  18. package/lib/commonjs/Tabs/Tabs.js.map +1 -1
  19. package/lib/module/Avatar/Avatar.js +4 -0
  20. package/lib/module/Avatar/Avatar.js.map +1 -1
  21. package/lib/module/Card/Card.js +8 -3
  22. package/lib/module/Card/Card.js.map +1 -1
  23. package/lib/module/Image/Image.js +195 -23
  24. package/lib/module/Image/Image.js.map +1 -1
  25. package/lib/module/Image/Image.native.js +38 -0
  26. package/lib/module/Image/Image.native.js.map +1 -0
  27. package/lib/module/Image/createImage.js +75 -1
  28. package/lib/module/Image/createImage.js.map +1 -1
  29. package/lib/module/Input/shared.js +13 -11
  30. package/lib/module/Input/shared.js.map +1 -1
  31. package/lib/module/PinInput/PinInput.js +15 -6
  32. package/lib/module/PinInput/PinInput.js.map +1 -1
  33. package/lib/module/SimpleGrid/SimpleGrid.js +48 -28
  34. package/lib/module/SimpleGrid/SimpleGrid.js.map +1 -1
  35. package/lib/module/Tabs/Tabs.js +56 -11
  36. package/lib/module/Tabs/Tabs.js.map +1 -1
  37. package/lib/typescript/Avatar/Avatar.d.ts.map +1 -1
  38. package/lib/typescript/Card/Card.d.ts.map +1 -1
  39. package/lib/typescript/Image/Image.d.ts +38 -52
  40. package/lib/typescript/Image/Image.d.ts.map +1 -1
  41. package/lib/typescript/Image/Image.native.d.ts +395 -0
  42. package/lib/typescript/Image/Image.native.d.ts.map +1 -0
  43. package/lib/typescript/Image/createImage.d.ts.map +1 -1
  44. package/lib/typescript/Input/shared.d.ts +7 -7
  45. package/lib/typescript/Input/shared.d.ts.map +1 -1
  46. package/lib/typescript/PinInput/PinInput.d.ts +9 -0
  47. package/lib/typescript/PinInput/PinInput.d.ts.map +1 -1
  48. package/lib/typescript/SimpleGrid/SimpleGrid.d.ts +10 -4
  49. package/lib/typescript/SimpleGrid/SimpleGrid.d.ts.map +1 -1
  50. package/lib/typescript/Tabs/Tabs.d.ts.map +1 -1
  51. package/package.json +4 -4
  52. package/src/Avatar/Avatar.tsx +4 -0
  53. package/src/Card/Card.tsx +12 -5
  54. package/src/Image/Image.native.tsx +36 -0
  55. package/src/Image/Image.tsx +240 -23
  56. package/src/Image/createImage.tsx +88 -1
  57. package/src/Input/shared.tsx +13 -11
  58. package/src/PinInput/PinInput.tsx +23 -2
  59. package/src/SimpleGrid/SimpleGrid.tsx +42 -20
  60. package/src/Tabs/Tabs.tsx +67 -13
@@ -9,6 +9,7 @@ import {
9
9
  View,
10
10
  withStaticProperties,
11
11
  } from "@knitui/core";
12
+ import { useCallbackRef, useMergedRef } from "@knitui/hooks";
12
13
 
13
14
  import { slotStyles, type SlotStyles } from "../internal/styles";
14
15
  import {
@@ -201,6 +202,86 @@ export const resolveRadiusValue = (
201
202
  return Number.isFinite(numericValue) ? numericValue : undefined;
202
203
  };
203
204
 
205
+ /** Frames `useWebCachedImageLoad` waits for the backend to put its `<img>` in the DOM. */
206
+ const CACHED_LOAD_MAX_FRAMES = 10;
207
+
208
+ /**
209
+ * Find the rendered `<img>` behind a backend instance on web: the instance itself
210
+ * (a plain `<img>` backend), or the backend's container element — the kit's web
211
+ * `Image` wrapper, or expo-image's `containerViewRef` — whose LAST `<img>` is the
212
+ * current source (a placeholder node, when any, comes first).
213
+ */
214
+ const findWebImg = (instance: unknown): HTMLImageElement | null => {
215
+ if (typeof HTMLElement === "undefined" || instance == null) return null;
216
+ if (instance instanceof HTMLImageElement) return instance;
217
+ const container =
218
+ instance instanceof HTMLElement
219
+ ? instance
220
+ : (instance as { containerViewRef?: { current?: unknown } }).containerViewRef?.current;
221
+ if (container instanceof HTMLElement) {
222
+ const imgs = container.querySelectorAll("img");
223
+ return imgs.length ? imgs[imgs.length - 1]! : null;
224
+ }
225
+ return null;
226
+ };
227
+
228
+ const sourceKey = (source: unknown): unknown =>
229
+ source && typeof source === "object" && "uri" in source
230
+ ? (source as { uri?: unknown }).uri
231
+ : source;
232
+
233
+ /**
234
+ * Web only: report an image the browser already had as loaded.
235
+ *
236
+ * A cached image fires `load` as soon as React creates its `<img>`, which in a
237
+ * concurrent render can land before the commit; React then drops the event.
238
+ * expo-image's web fade holds the `<img>` at `opacity: 0` until that `onLoad`, so
239
+ * the image stayed loaded and invisible for good. After mount (and on each new
240
+ * source) this checks the committed `<img>`: when it is `complete` with a
241
+ * `naturalWidth` and no `load` reached us, it re-dispatches `load` on the element
242
+ * so the backend (and the consumer's `onLoad`) hear it once.
243
+ */
244
+ function useWebCachedImageLoad(
245
+ forwardedRef: React.ForwardedRef<unknown>,
246
+ onLoad: ((...args: unknown[]) => void) | undefined,
247
+ source: unknown,
248
+ ) {
249
+ const instanceRef = React.useRef<unknown>(null);
250
+ const ref = useMergedRef(forwardedRef, instanceRef);
251
+ const loadedRef = React.useRef(false);
252
+ const latestOnLoad = useCallbackRef(onLoad);
253
+ const key = sourceKey(source);
254
+
255
+ const handleLoad = React.useCallback(
256
+ (...args: unknown[]) => {
257
+ loadedRef.current = true;
258
+ latestOnLoad(...args);
259
+ },
260
+ [latestOnLoad],
261
+ );
262
+
263
+ React.useEffect(() => {
264
+ if (!isWeb || typeof requestAnimationFrame === "undefined") return;
265
+ loadedRef.current = false;
266
+ let frame = 0;
267
+ let handle = 0;
268
+ const check = () => {
269
+ if (loadedRef.current) return;
270
+ const img = findWebImg(instanceRef.current);
271
+ if (img) {
272
+ if (img.complete && img.naturalWidth > 0) img.dispatchEvent(new Event("load"));
273
+ return;
274
+ }
275
+ if (frame++ < CACHED_LOAD_MAX_FRAMES) handle = requestAnimationFrame(check);
276
+ };
277
+ // The backend may add its `<img>` from its own effect, so look one frame on.
278
+ handle = requestAnimationFrame(check);
279
+ return () => cancelAnimationFrame(handle);
280
+ }, [key]);
281
+
282
+ return { ref, onLoad: isWeb && onLoad ? handleLoad : onLoad };
283
+ }
284
+
204
285
  /** Resolve a `$size`-token dimension to its numeric value, passing others through. */
205
286
  const resolveDimension = (value: ImageDimension): ImageDimension =>
206
287
  typeof value === "string" && value[0] === "$"
@@ -305,10 +386,16 @@ export function createImage<C extends ComponentType<Record<string, unknown>>>(
305
386
  Record<string, unknown>
306
387
  >(function ImageBackendAdapter(backendProps, backendRef) {
307
388
  const { [TRANSITION_INLINE_ALIAS]: transitionValue, ...backendRest } = backendProps;
389
+ const { ref, onLoad } = useWebCachedImageLoad(
390
+ backendRef,
391
+ backendRest.onLoad as ((...args: unknown[]) => void) | undefined,
392
+ backendRest.source,
393
+ );
308
394
  return React.createElement(Component, {
309
395
  ...backendRest,
310
396
  ...(transitionValue !== undefined && { transition: transitionValue }),
311
- ref: backendRef,
397
+ ...(onLoad && { onLoad }),
398
+ ref,
312
399
  });
313
400
  }) as unknown as ComponentType<Record<string, unknown>>;
314
401
 
@@ -1,7 +1,7 @@
1
1
  import * as React from "react";
2
2
 
3
3
  import type { GetProps, TamaguiElement } from "@knitui/core";
4
- import { getLineHeight, getTokenValue, styled, Theme } from "@knitui/core";
4
+ import { getTokenValue, styled, Theme } from "@knitui/core";
5
5
  import { useCallbackRef, useId } from "@knitui/hooks";
6
6
 
7
7
  import { Box } from "../Box";
@@ -185,49 +185,51 @@ export const getTextareaPaddingVertical = (size: InputSize | undefined): number
185
185
  // field grows. Without it Tamagui's font pairing resolves the SAME line height
186
186
  // (the `md` step, 27px) for every `fontSize` token, so changing `size` only changed
187
187
  // the text size while the box height stayed put — i.e. `size` looked ignored on web.
188
- // The values match the native host's `getNativeLineHeight` (`round(fontSize × ratio)`
189
- // off the same clamped per-size `fontSize`), so a textarea row is the same height on
190
- // web, iOS and Android.
188
+ // It names the line-height TOKEN of the same step as the clamped per-size
189
+ // `fontSize` (the value `getLineHeight` computes, `round(fontSize × ratio)`), so it
190
+ // matches the native host's `getNativeLineHeight` and a textarea row is the same
191
+ // height on web, iOS and Android — and, being a token, it is `rem` on the web, so
192
+ // browser text zoom grows the line box together with the text.
191
193
  const textareaHostSizeVariant = {
192
194
  xxs: {
193
195
  fontSize: M.xxs.fontSize,
194
- lineHeight: getLineHeight(M.xxs.fontSize),
196
+ lineHeight: M.xxs.fontSize,
195
197
  paddingHorizontal: M.xxs.paddingHorizontal,
196
198
  paddingVertical: TEXTAREA_INSET_TOKEN.xxs,
197
199
  },
198
200
  xs: {
199
201
  fontSize: M.xs.fontSize,
200
- lineHeight: getLineHeight(M.xs.fontSize),
202
+ lineHeight: M.xs.fontSize,
201
203
  paddingHorizontal: M.xs.paddingHorizontal,
202
204
  paddingVertical: TEXTAREA_INSET_TOKEN.xs,
203
205
  },
204
206
  sm: {
205
207
  fontSize: M.sm.fontSize,
206
- lineHeight: getLineHeight(M.sm.fontSize),
208
+ lineHeight: M.sm.fontSize,
207
209
  paddingHorizontal: M.sm.paddingHorizontal,
208
210
  paddingVertical: TEXTAREA_INSET_TOKEN.sm,
209
211
  },
210
212
  md: {
211
213
  fontSize: M.md.fontSize,
212
- lineHeight: getLineHeight(M.md.fontSize),
214
+ lineHeight: M.md.fontSize,
213
215
  paddingHorizontal: M.md.paddingHorizontal,
214
216
  paddingVertical: TEXTAREA_INSET_TOKEN.md,
215
217
  },
216
218
  lg: {
217
219
  fontSize: M.lg.fontSize,
218
- lineHeight: getLineHeight(M.lg.fontSize),
220
+ lineHeight: M.lg.fontSize,
219
221
  paddingHorizontal: M.lg.paddingHorizontal,
220
222
  paddingVertical: TEXTAREA_INSET_TOKEN.lg,
221
223
  },
222
224
  xl: {
223
225
  fontSize: M.xl.fontSize,
224
- lineHeight: getLineHeight(M.xl.fontSize),
226
+ lineHeight: M.xl.fontSize,
225
227
  paddingHorizontal: M.xl.paddingHorizontal,
226
228
  paddingVertical: TEXTAREA_INSET_TOKEN.xl,
227
229
  },
228
230
  xxl: {
229
231
  fontSize: M.xxl.fontSize,
230
- lineHeight: getLineHeight(M.xxl.fontSize),
232
+ lineHeight: M.xxl.fontSize,
231
233
  paddingHorizontal: M.xxl.paddingHorizontal,
232
234
  paddingVertical: TEXTAREA_INSET_TOKEN.xxl,
233
235
  },
@@ -5,6 +5,7 @@ import { useCallbackRef, useId, useMergedRef, useUncontrolled } from "@knitui/ho
5
5
 
6
6
  import { Box } from "../Box";
7
7
  import { Input, type InputProps, type InputSize } from "../Input";
8
+ import { HiddenInput } from "../internal/hidden-input";
8
9
  import { gapVariant, type SizeKey, squareSizeVariant } from "../internal/style-props";
9
10
  import { slotStyles, type SlotStyles } from "../internal/styles";
10
11
 
@@ -175,6 +176,17 @@ export interface PinInputProps extends Omit<
175
176
  /** Base id used to generate per-input ids. */
176
177
  id?: string;
177
178
 
179
+ /**
180
+ * Web only: form field name. When set, one `<input type="hidden">` carries the
181
+ * joined code, so a surrounding `<form>` (and password managers / one-time-code
182
+ * autofill, which look for a single named field) see the whole value. The
183
+ * per-character boxes themselves stay nameless. Ignored on native.
184
+ */
185
+ name?: string;
186
+
187
+ /** Web only: id of the `<form>` the hidden `name` input belongs to. */
188
+ form?: string;
189
+
178
190
  /** Props applied to each input, by index. */
179
191
  getInputProps?: (index: number) => Partial<InputProps>;
180
192
 
@@ -188,8 +200,9 @@ export interface PinInputProps extends Omit<
188
200
  * (`mask` → `type="password"` → native `secureTextEntry`) and focus advance work
189
201
  * cross-platform. Accent/theme comes from the Tamagui `theme` prop + palette ramp.
190
202
  *
191
- * Web-form parity (`name`/`form` hidden input) and multi-field paste distribution
192
- * are deferred; single-field paste of a full code is handled.
203
+ * Web forms: `name` (and `form`) render one hidden input carrying the joined code.
204
+ * Multi-field paste distribution is deferred; single-field paste of a full code is
205
+ * handled.
193
206
  */
194
207
  const PinInputComponent = PinInputRow.styleable<PinInputProps>(function PinInput(props, ref) {
195
208
  const {
@@ -214,6 +227,8 @@ const PinInputComponent = PinInputRow.styleable<PinInputProps>(function PinInput
214
227
  oneTimeCode = true,
215
228
  ariaLabel = "PinInput",
216
229
  id,
230
+ name,
231
+ form,
217
232
  getInputProps,
218
233
  styles,
219
234
  ...others
@@ -407,6 +422,12 @@ const PinInputComponent = PinInputRow.styleable<PinInputProps>(function PinInput
407
422
  }}
408
423
  />
409
424
  ))}
425
+ <HiddenInput
426
+ name={name}
427
+ form={form}
428
+ disabled={disabled}
429
+ value={currentValue.join("").trim()}
430
+ />
410
431
  </PinInputRow>
411
432
  );
412
433
  });
@@ -1,6 +1,6 @@
1
1
  import * as React from "react";
2
2
 
3
- import { type GetProps, getTokenValue, type SpaceTokens, styled } from "@knitui/core";
3
+ import { type GetProps, getTokenValue, isWeb, type SpaceTokens, styled } from "@knitui/core";
4
4
 
5
5
  import { Box, type BoxProps } from "../Box";
6
6
  import { slotStyles, type SlotStyles } from "../internal/styles";
@@ -34,12 +34,18 @@ const resolveSpacing = (spacing: SimpleGridSpacing): number => {
34
34
  * Equal-width column grid — mirrors Mantine's `SimpleGrid` (every column the same
35
35
  * width, unlike `Grid`'s 12-column spans). Cross-platform: there is no CSS grid on
36
36
  * native, so each child is wrapped in a cell `Box` and laid out with a flex-wrap
37
- * row + a negative-margin gap track (the same border-box technique as `Grid`).
37
+ * row. Rows are spaced with `rowGap`. The grid never reaches past its own box (no
38
+ * negative-margin track), so it cannot overflow a fixed-width scrolling parent.
38
39
  *
39
40
  * Two modes:
40
- * - default `cols` mode — N equal columns (`width: 100/cols %`).
41
- * - `minColWidth` mode — columns auto-fill at ≥ that width (`flexBasis`/`minWidth`),
42
- * a cross-platform approximation of CSS `repeat(auto-fill/fit, minmax(min, 1fr))`.
41
+ * - default `cols` mode — N equal columns (`width: 100/cols %`). The column gap
42
+ * is split across each cell's inline padding by column index (column `c` of
43
+ * `N` gets `c·g/N` before and `(N-1-c)·g/N` after), so every column's content
44
+ * is equally wide, adjacent columns sit exactly `g` apart, and the outer
45
+ * columns are flush with the grid's edges.
46
+ * - `minColWidth` mode — columns auto-fill at ≥ that width (`flexBasis`/`minWidth`
47
+ * less one gap, plus `columnGap`), a cross-platform approximation of CSS
48
+ * `repeat(auto-fill/fit, minmax(min, 1fr))`.
43
49
  *
44
50
  * Responsive per-breakpoint values are intentionally deferred (single values only),
45
51
  * matching `Grid`. Accent/theme is inherited; no Mantine `color` prop.
@@ -93,9 +99,20 @@ const SIMPLE_GRID_SLOT_KEYS = ["cell"] as const satisfies readonly (keyof Simple
93
99
  /** Cell layout narrowed to the exact Box style props it targets. */
94
100
  type CellLayout = Pick<
95
101
  BoxProps,
96
- "width" | "flexBasis" | "flexGrow" | "minWidth" | "paddingHorizontal" | "paddingVertical"
102
+ "width" | "flexBasis" | "flexGrow" | "minWidth" | "paddingLeft" | "paddingRight"
97
103
  >;
98
104
 
105
+ /**
106
+ * `minColWidth` less one column gap, so a cell plus its trailing gap packs like
107
+ * the old half-gap-padded cell did (same column count and content width).
108
+ */
109
+ const minLessGap = (min: number | string, gap: number): BoxProps["flexBasis"] => {
110
+ if (typeof min === "number") return Math.max(0, min - gap);
111
+ if (!gap) return min as BoxProps["flexBasis"];
112
+ // Web resolves the subtraction in CSS; native takes the string as given.
113
+ return (isWeb ? `calc(${min} - ${gap}px)` : min) as BoxProps["flexBasis"];
114
+ };
115
+
99
116
  export const SimpleGrid = SimpleGridFrame.styleable<SimpleGridProps>(
100
117
  function SimpleGrid(props, ref) {
101
118
  const {
@@ -116,31 +133,36 @@ export const SimpleGrid = SimpleGridFrame.styleable<SimpleGridProps>(
116
133
  const sx = resolveSpacing(spacing);
117
134
  const sy = resolveSpacing(verticalSpacing ?? spacing);
118
135
 
119
- const cell: CellLayout = {
120
- paddingHorizontal: sx / 2,
121
- paddingVertical: sy / 2,
136
+ const minMode = minColWidth !== undefined;
137
+ const cellLayout = (index: number): CellLayout => {
138
+ if (minMode) {
139
+ const basis = minLessGap(minColWidth, sx);
140
+ return {
141
+ flexBasis: basis,
142
+ minWidth: basis as BoxProps["minWidth"],
143
+ flexGrow: autoFlow === "auto-fit" ? 1 : 0,
144
+ };
145
+ }
146
+ const column = index % cols;
147
+ return {
148
+ width: `${100 / cols}%` as BoxProps["width"],
149
+ paddingLeft: (column * sx) / cols,
150
+ paddingRight: ((cols - 1 - column) * sx) / cols,
151
+ };
122
152
  };
123
- if (minColWidth !== undefined) {
124
- cell.flexBasis = minColWidth as BoxProps["flexBasis"];
125
- cell.minWidth = minColWidth as BoxProps["minWidth"];
126
- cell.flexGrow = autoFlow === "auto-fit" ? 1 : 0;
127
- } else {
128
- cell.width = `${100 / cols}%` as BoxProps["width"];
129
- }
130
153
 
131
154
  const cells = React.Children.toArray(children)
132
155
  .filter(Boolean)
133
156
  .map((child, index) => (
134
- // `styles.cell` is lower-precedence sugar; the computed `cell` layout
157
+ // `styles.cell` is lower-precedence sugar; the computed cell layout
135
158
  // (width/flexBasis/gap padding) is owned by `SimpleGrid` and wins.
136
- <Box key={index} {...s.get("cell")} {...cell}>
159
+ <Box key={index} {...s.get("cell")} {...cellLayout(index)}>
137
160
  {child}
138
161
  </Box>
139
162
  ));
140
163
 
141
164
  return (
142
- // Negative-margin track cancels the cells' half-gap padding so outer edges align.
143
- <SimpleGridFrame ref={ref} marginHorizontal={-sx / 2} marginVertical={-sy / 2} {...rest}>
165
+ <SimpleGridFrame ref={ref} rowGap={sy} {...(minMode && { columnGap: sx })} {...rest}>
144
166
  {cells}
145
167
  </SimpleGridFrame>
146
168
  );
package/src/Tabs/Tabs.tsx CHANGED
@@ -59,6 +59,40 @@ const TabsContext = React.createContext<TabsContextValue>({
59
59
  id: "",
60
60
  });
61
61
 
62
+ /**
63
+ * Which panels are mounted right now. A `Tabs.Panel` registers its value while it
64
+ * renders; a `Tabs.Tab` points `aria-controls` at its panel only while that panel
65
+ * exists, so a strip without panels (a segmented switcher) or a panel unmounted by
66
+ * `keepMounted={false}` leaves no dangling id reference. Kept apart from
67
+ * `TabsContext` so a registration re-renders only the tabs.
68
+ */
69
+ interface TabsPanelRegistry {
70
+ mounted: ReadonlyMap<string, number>;
71
+ register: (value: string) => () => void;
72
+ }
73
+
74
+ const TabsPanelRegistryContext = React.createContext<TabsPanelRegistry>({
75
+ mounted: new Map(),
76
+ register: () => () => {},
77
+ });
78
+
79
+ function useTabsPanelRegistry(): TabsPanelRegistry {
80
+ const [mounted, setMounted] = React.useState<ReadonlyMap<string, number>>(() => new Map());
81
+ const register = React.useCallback((value: string) => {
82
+ const bump = (delta: number) =>
83
+ setMounted((prev) => {
84
+ const next = new Map(prev);
85
+ const count = (next.get(value) ?? 0) + delta;
86
+ if (count > 0) next.set(value, count);
87
+ else next.delete(value);
88
+ return next;
89
+ });
90
+ bump(1);
91
+ return () => bump(-1);
92
+ }, []);
93
+ return React.useMemo(() => ({ mounted, register }), [mounted, register]);
94
+ }
95
+
62
96
  const TabsStyleContext = createStyledContext<{
63
97
  size: TabsSize;
64
98
  variant: TabsVariant;
@@ -391,10 +425,20 @@ const TabsTab = TabTabFrame.styleable<TabsTabProps>(function TabsTab(props, ref)
391
425
  const press = usePressScale();
392
426
  const { value, children, leftSection, rightSection, disabled, ...rest } = props;
393
427
  const ctx = React.useContext(TabsContext);
428
+ const panels = React.useContext(TabsPanelRegistryContext);
394
429
  const s = useTabsSlots();
395
430
  const isActive = ctx.value === value;
396
431
  const panelId = `${ctx.id}-panel-${value}`;
397
432
  const tabId = `${ctx.id}-tab-${value}`;
433
+ // Point at the panel only while it is mounted (an id reference to a missing
434
+ // element is invalid ARIA); a caller's own `aria-controls` wins either way.
435
+ const restProps = rest as typeof rest & { "aria-controls"?: string };
436
+ const ariaControls =
437
+ "aria-controls" in restProps
438
+ ? restProps["aria-controls"]
439
+ : panels.mounted.has(value)
440
+ ? panelId
441
+ : undefined;
398
442
 
399
443
  const handlePress = React.useCallback(() => {
400
444
  if (disabled) return;
@@ -475,7 +519,7 @@ const TabsTab = TabTabFrame.styleable<TabsTabProps>(function TabsTab(props, ref)
475
519
  id={tabId}
476
520
  aria-selected={isActive}
477
521
  aria-disabled={disabled || undefined}
478
- aria-controls={panelId}
522
+ aria-controls={ariaControls}
479
523
  {...keyboardProps}
480
524
  >
481
525
  {leftSection ? <TabSection {...s.get("section")}>{leftSection}</TabSection> : null}
@@ -506,6 +550,7 @@ export interface TabsPanelProps extends GetProps<typeof TabsPanelFrame> {
506
550
  const TabsPanel = TabsPanelFrame.styleable<TabsPanelProps>(function TabsPanel(props, ref) {
507
551
  const { value, children, keepMounted: keepMountedProp, ...rest } = props;
508
552
  const ctx = React.useContext(TabsContext);
553
+ const { register } = React.useContext(TabsPanelRegistryContext);
509
554
  const s = useTabsSlots();
510
555
 
511
556
  const isActive = ctx.value === value;
@@ -513,6 +558,12 @@ const TabsPanel = TabsPanelFrame.styleable<TabsPanelProps>(function TabsPanel(pr
513
558
  const tabId = `${ctx.id}-tab-${value}`;
514
559
  const panelId = `${ctx.id}-panel-${value}`;
515
560
 
561
+ // Tell the tabs this panel exists, so its tab may name it in `aria-controls`.
562
+ React.useLayoutEffect(
563
+ () => (shouldMount ? register(value) : undefined),
564
+ [register, shouldMount, value],
565
+ );
566
+
516
567
  if (!shouldMount) return null;
517
568
 
518
569
  return (
@@ -634,6 +685,7 @@ const TabsComponent = TabsFrame.styleable<TabsProps>(function Tabs(props, ref) {
634
685
  } = props;
635
686
 
636
687
  const autoId = useId(id);
688
+ const panelRegistry = useTabsPanelRegistry();
637
689
 
638
690
  const [currentValue, setCurrentValue] = useUncontrolled<string | null>({
639
691
  value,
@@ -686,18 +738,20 @@ const TabsComponent = TabsFrame.styleable<TabsProps>(function Tabs(props, ref) {
686
738
 
687
739
  return (
688
740
  <TabsContext.Provider value={ctx}>
689
- <TabsSlotStylesContext.Provider value={styles}>
690
- <TabsFrame
691
- ref={ref}
692
- orientation={orientation}
693
- variant={variant}
694
- size={size}
695
- flexDirection={flexDirection}
696
- {...rest}
697
- >
698
- {children}
699
- </TabsFrame>
700
- </TabsSlotStylesContext.Provider>
741
+ <TabsPanelRegistryContext.Provider value={panelRegistry}>
742
+ <TabsSlotStylesContext.Provider value={styles}>
743
+ <TabsFrame
744
+ ref={ref}
745
+ orientation={orientation}
746
+ variant={variant}
747
+ size={size}
748
+ flexDirection={flexDirection}
749
+ {...rest}
750
+ >
751
+ {children}
752
+ </TabsFrame>
753
+ </TabsSlotStylesContext.Provider>
754
+ </TabsPanelRegistryContext.Provider>
701
755
  </TabsContext.Provider>
702
756
  );
703
757
  });