@cdx-ui/utils 0.0.1-beta.9 → 0.0.1-beta.90

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 (53) hide show
  1. package/README.md +47 -23
  2. package/lib/commonjs/common/mergeRefs.js +39 -1
  3. package/lib/commonjs/common/mergeRefs.js.map +1 -1
  4. package/lib/commonjs/context/createContext.js +7 -3
  5. package/lib/commonjs/context/createContext.js.map +1 -1
  6. package/lib/commonjs/form-control/index.js +6 -0
  7. package/lib/commonjs/form-control/index.js.map +1 -1
  8. package/lib/commonjs/form-control/useFormControl.js +33 -0
  9. package/lib/commonjs/form-control/useFormControl.js.map +1 -1
  10. package/lib/commonjs/style/index.js +0 -11
  11. package/lib/commonjs/style/index.js.map +1 -1
  12. package/lib/module/common/mergeRefs.js +39 -1
  13. package/lib/module/common/mergeRefs.js.map +1 -1
  14. package/lib/module/context/createContext.js +7 -3
  15. package/lib/module/context/createContext.js.map +1 -1
  16. package/lib/module/form-control/index.js +1 -1
  17. package/lib/module/form-control/index.js.map +1 -1
  18. package/lib/module/form-control/useFormControl.js +33 -0
  19. package/lib/module/form-control/useFormControl.js.map +1 -1
  20. package/lib/module/style/index.js +0 -1
  21. package/lib/module/style/index.js.map +1 -1
  22. package/lib/typescript/common/mergeRefs.d.ts +8 -0
  23. package/lib/typescript/common/mergeRefs.d.ts.map +1 -1
  24. package/lib/typescript/context/createContext.d.ts +16 -1
  25. package/lib/typescript/context/createContext.d.ts.map +1 -1
  26. package/lib/typescript/form-control/index.d.ts +1 -1
  27. package/lib/typescript/form-control/index.d.ts.map +1 -1
  28. package/lib/typescript/form-control/useFormControl.d.ts +28 -3
  29. package/lib/typescript/form-control/useFormControl.d.ts.map +1 -1
  30. package/lib/typescript/style/index.d.ts +0 -1
  31. package/lib/typescript/style/index.d.ts.map +1 -1
  32. package/package.json +4 -2
  33. package/src/common/accessibilityUtils.test.ts +12 -0
  34. package/src/common/cn.test.ts +19 -0
  35. package/src/common/composeEventHandlers.test.ts +35 -0
  36. package/src/common/getSpacedChild.test.tsx +64 -0
  37. package/src/common/mergeRefs.test.ts +148 -0
  38. package/src/common/mergeRefs.ts +45 -2
  39. package/src/common/useControllableState.test.tsx +90 -0
  40. package/src/context/createContext.test.tsx +31 -0
  41. package/src/context/createContext.tsx +21 -4
  42. package/src/form-control/index.ts +2 -0
  43. package/src/form-control/useFormControl.test.tsx +214 -0
  44. package/src/form-control/useFormControl.tsx +48 -4
  45. package/src/style/context/index.test.tsx +31 -0
  46. package/src/style/index.tsx +0 -1
  47. package/lib/commonjs/style/withStyleContext/index.js +0 -33
  48. package/lib/commonjs/style/withStyleContext/index.js.map +0 -1
  49. package/lib/module/style/withStyleContext/index.js +0 -28
  50. package/lib/module/style/withStyleContext/index.js.map +0 -1
  51. package/lib/typescript/style/withStyleContext/index.d.ts +0 -6
  52. package/lib/typescript/style/withStyleContext/index.d.ts.map +0 -1
  53. package/src/style/withStyleContext/index.tsx +0 -36
@@ -1,6 +1,17 @@
1
1
  import React from 'react';
2
- import { type TextInput } from 'react-native';
3
2
  type HTMLProps = Record<string, unknown>;
3
+ /**
4
+ * Minimal contract for any control registered on `FormControlContextValue.inputRef`.
5
+ *
6
+ * `Field.Label` / `focusInput()` only need to call `.focus()` on the registered node;
7
+ * narrower control-specific shapes (`TextInput`, `HTMLInputElement`, custom focus
8
+ * bridges like `Select.Trigger`'s) all satisfy this contract. Consumers that need
9
+ * more (e.g. reading `.value`) should cast locally — keeping the context type
10
+ * minimal avoids a typed lie when a non-input bridge is registered.
11
+ */
12
+ export interface Focusable {
13
+ focus(): void;
14
+ }
4
15
  export interface FormControlState {
5
16
  isRequired: boolean;
6
17
  isInvalid: boolean;
@@ -21,9 +32,16 @@ export interface FormControlContextValue extends FormControlState {
21
32
  /**
22
33
  * @platform native — set by `Input.Field` / `Select.Trigger` for label press-to-focus.
23
34
  * On web, use `<label htmlFor>` with a labelable control (`input`, `button`, `select`, …).
35
+ *
36
+ * Typed as `Focusable` so any control (TextInput, HTMLInputElement, custom focus
37
+ * bridge) can register without a cast at the assignment site. Consumers that need
38
+ * the narrower shape cast locally.
24
39
  */
25
- inputRef?: React.RefObject<TextInput | null>;
40
+ inputRef?: React.RefObject<Focusable | null>;
26
41
  focusInput?: () => void;
42
+ /** True when the primary child control is focused or (for Select) open — drives `Field.Label` styling. */
43
+ isLabelFocused?: boolean;
44
+ setIsLabelFocused?: React.Dispatch<React.SetStateAction<boolean>>;
27
45
  }
28
46
  export declare const FormControlContext: React.Context<Partial<FormControlContextValue>>;
29
47
  export interface FormControlFieldProps extends Partial<FormControlState> {
@@ -49,14 +67,21 @@ export interface FormControlRootReturn {
49
67
  feedbackId: string;
50
68
  helpTextId: string;
51
69
  htmlProps: HTMLProps;
52
- inputRef?: React.RefObject<TextInput | null>;
70
+ inputRef?: React.RefObject<Focusable | null>;
53
71
  focusInput?: () => void;
72
+ isLabelFocused: boolean;
73
+ setIsLabelFocused: React.Dispatch<React.SetStateAction<boolean>>;
54
74
  }
55
75
  /**
56
76
  * Builds state and ids for a `Form` primitive root (`createFormRoot`). Pass the returned object
57
77
  * (minus `htmlProps`) to `FormControlContext.Provider` — this is not a React context consumer hook.
58
78
  */
59
79
  export declare function useFormControlRoot(props: FormControlRootProps): FormControlRootReturn;
80
+ /**
81
+ * Reports focus/active state from `Input` / `Select.Trigger` to the parent `Field` for label styling.
82
+ * No-ops outside a `Field` (no `setIsLabelFocused` on context).
83
+ */
84
+ export declare function useReportFormControlLabelFocus(isActive: boolean): void;
60
85
  /**
61
86
  * Hook that merges local field props with the nearest form field context
62
87
  * and returns normalised HTML / ARIA attributes for input elements.
@@ -1 +1 @@
1
- {"version":3,"file":"useFormControl.d.ts","sourceRoot":"","sources":["../../../src/form-control/useFormControl.tsx"],"names":[],"mappings":"AAAA,OAAO,KAAK,MAAM,OAAO,CAAC;AAC1B,OAAO,EAAY,KAAK,SAAS,EAAE,MAAM,cAAc,CAAC;AAGxD,KAAK,SAAS,G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AAC;IACpB,eAAe,EAAE,OAAO,CAAC;IACzB,kBAAkB,EAAE,KAAK,CAAC,QAAQ,CAAC,KAAK,CAAC,cAAc,CAAC,OAAO,CAAC,CAAC,CAAC;IAClE,WAAW,EAAE,OAAO,CAAC;IACrB,cAAc,EAAE,KAAK,CAAC,QAAQ,CAAC,KAAK,CAAC,cAAc,CAAC,OAAO,CAAC,CAAC,CAAC;IAC9D,IAAI,CAAC,EAAE,MAAM,CAAC;IACd,EAAE,EAAE,MAAM,CAAC;IACX,OAAO,EAAE,MAAM,CAAC;IAChB,UAAU,EAAE,MAAM,CAAC;IACnB,UAAU,EAAE,MAAM,CAAC;IACnB,SAAS,EAAE,SAAS,CAAC;IACrB,QAAQ,CAAC,EAAE,KAAK,CAAC,SAAS,CAAC,SAAS,GAAG,IAAI,CAAC,CAAC;IAC7C,UAAU,CAAC,EAAE,MAAM,IAAI,CAAC;IACxB,cAAc,EAAE,OAAO,CAAC;IACxB,iBAAiB,EAAE,KAAK,CAAC,QAAQ,CAAC,KAAK,CAAC,cAAc,CAAC,OAAO,CAAC,CAAC,CAAC;CAClE;AAED;;;GAGG;AACH,wBAAgB,kBAAkB,CAAC,KAAK,EAAE,oBAAoB,GAAG,qBAAqB,CAsDrF;AAED;;;GAGG;AACH,wBAAgB,8BAA8B,CAAC,QAAQ,EAAE,OAAO,QAY/D;AAED;;;GAGG;AACH,wBAAgB,cAAc,CAAC,KAAK,EAAE,qBAAqB;;;;;;;;;;;EA4B1D;AAED,eAAO,MAAM,qBAAqB,wCAEjC,CAAC"}
@@ -1,3 +1,2 @@
1
1
  export * from './context';
2
- export * from './withStyleContext';
3
2
  //# sourceMappingURL=index.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../src/style/index.tsx"],"names":[],"mappings":"AAAA,cAAc,WAAW,CAAC;AAC1B,cAAc,oBAAoB,CAAC"}
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../src/style/index.tsx"],"names":[],"mappings":"AAAA,cAAc,WAAW,CAAC"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@cdx-ui/utils",
3
- "version": "0.0.1-beta.9",
3
+ "version": "0.0.1-beta.90",
4
4
  "main": "lib/commonjs/index.js",
5
5
  "module": "lib/module/index.js",
6
6
  "react-native": "src/index.ts",
@@ -22,6 +22,7 @@
22
22
  "react-native-builder-bob": {
23
23
  "source": "src",
24
24
  "output": "lib",
25
+ "exclude": "**/{__tests__/**,__fixtures__/**,__mocks__/**,*.test.ts,*.test.tsx,*.spec.ts,*.spec.tsx}",
25
26
  "targets": [
26
27
  "commonjs",
27
28
  "module",
@@ -67,6 +68,7 @@
67
68
  },
68
69
  "scripts": {
69
70
  "build": "bob build",
70
- "lint": "eslint src/"
71
+ "lint": "eslint src/",
72
+ "test": "jest --config ../../jest.config.js --selectProjects utils"
71
73
  }
72
74
  }
@@ -0,0 +1,12 @@
1
+ import { ariaAttr } from './accessibilityUtils';
2
+
3
+ describe('ariaAttr', () => {
4
+ it('returns true when condition is true', () => {
5
+ expect(ariaAttr(true)).toBe(true);
6
+ });
7
+
8
+ it('returns undefined when condition is false or undefined', () => {
9
+ expect(ariaAttr(false)).toBeUndefined();
10
+ expect(ariaAttr(undefined)).toBeUndefined();
11
+ });
12
+ });
@@ -0,0 +1,19 @@
1
+ import { cn } from './cn';
2
+
3
+ describe('cn', () => {
4
+ it('merges conflicting Tailwind classes', () => {
5
+ expect(cn('px-2', 'px-4')).toBe('px-4');
6
+ });
7
+
8
+ it('joins non-conflicting classes', () => {
9
+ expect(cn('px-2', 'py-1')).toBe('px-2 py-1');
10
+ });
11
+
12
+ it('ignores falsy inputs', () => {
13
+ expect(cn('foo', undefined, null, false, '')).toBe('foo');
14
+ });
15
+
16
+ it('returns empty string when called with no inputs', () => {
17
+ expect(cn()).toBe('');
18
+ });
19
+ });
@@ -0,0 +1,35 @@
1
+ import { composeEventHandlers } from './composeEventHandlers';
2
+
3
+ describe('composeEventHandlers', () => {
4
+ it('calls handlers in order', () => {
5
+ const order: number[] = [];
6
+ const first = jest.fn(() => {
7
+ order.push(1);
8
+ });
9
+ const second = jest.fn(() => {
10
+ order.push(2);
11
+ });
12
+
13
+ composeEventHandlers(first, second)({ type: 'press' });
14
+
15
+ expect(order).toEqual([1, 2]);
16
+ expect(first).toHaveBeenCalledWith({ type: 'press' });
17
+ expect(second).toHaveBeenCalledWith({ type: 'press' });
18
+ });
19
+
20
+ it('skips null and undefined handlers', () => {
21
+ const handler = jest.fn();
22
+
23
+ composeEventHandlers(null, undefined, handler)({});
24
+
25
+ expect(handler).toHaveBeenCalledTimes(1);
26
+ });
27
+
28
+ it('returns a no-op when no handlers are provided', () => {
29
+ const handleEvent = composeEventHandlers();
30
+
31
+ expect(() => {
32
+ handleEvent({});
33
+ }).not.toThrow();
34
+ });
35
+ });
@@ -0,0 +1,64 @@
1
+ import React, { isValidElement } from 'react';
2
+ import { Text } from 'react-native';
3
+ import { flattenChildren } from './getSpacedChild';
4
+
5
+ describe('flattenChildren', () => {
6
+ it('flattens fragment children', () => {
7
+ const result = flattenChildren(
8
+ <>
9
+ <Text key="a">A</Text>
10
+ <Text key="b">B</Text>
11
+ </>,
12
+ );
13
+
14
+ expect(result).toHaveLength(2);
15
+ expect(isValidElement(result[0]) && result[0].type).toBe(Text);
16
+ expect(isValidElement(result[1]) && result[1].type).toBe(Text);
17
+ });
18
+
19
+ it('assigns composite keys to nested fragment children', () => {
20
+ const result = flattenChildren(
21
+ <React.Fragment key="group">
22
+ <Text key="child">Child</Text>
23
+ </React.Fragment>,
24
+ );
25
+
26
+ expect(result).toHaveLength(1);
27
+ const key = isValidElement(result[0]) ? String(result[0].key) : '';
28
+ expect(key).toContain('group');
29
+ expect(key).toContain('child');
30
+ });
31
+
32
+ it('passes through non-element children', () => {
33
+ const result = flattenChildren(['plain', <Text key="t">T</Text>]);
34
+
35
+ expect(result).toHaveLength(2);
36
+ expect(result[0]).toBe('plain');
37
+ });
38
+
39
+ it('preserves explicit element keys', () => {
40
+ const result = flattenChildren(<Text key="explicit">Label</Text>);
41
+
42
+ expect(result).toHaveLength(1);
43
+ const key = isValidElement(result[0]) ? String(result[0].key) : '';
44
+ expect(key).toContain('explicit');
45
+ });
46
+
47
+ it('uses index keys when fragment and child keys are missing', () => {
48
+ const result = flattenChildren(
49
+ <>
50
+ <Text>First</Text>
51
+ <React.Fragment>
52
+ <Text>Nested</Text>
53
+ </React.Fragment>
54
+ </>,
55
+ );
56
+
57
+ expect(result).toHaveLength(2);
58
+ const firstKey = isValidElement(result[0]) ? String(result[0].key) : '';
59
+ const secondKey = isValidElement(result[1]) ? String(result[1].key) : '';
60
+ expect(firstKey).toContain('0');
61
+ expect(secondKey).toContain('1');
62
+ expect(secondKey).toContain('0');
63
+ });
64
+ });
@@ -0,0 +1,148 @@
1
+ import { createRef } from 'react';
2
+ import { mergeRefs } from './mergeRefs';
3
+
4
+ describe('mergeRefs', () => {
5
+ it('assigns value to object refs', () => {
6
+ const refA = createRef<string>();
7
+ const refB = createRef<string>();
8
+
9
+ mergeRefs(refA, refB)('value');
10
+
11
+ expect(refA.current).toBe('value');
12
+ expect(refB.current).toBe('value');
13
+ });
14
+
15
+ it('invokes callback refs', () => {
16
+ const callback = jest.fn();
17
+
18
+ mergeRefs(callback)('value');
19
+
20
+ expect(callback).toHaveBeenCalledWith('value');
21
+ });
22
+
23
+ it('skips undefined refs and assigns null', () => {
24
+ const ref = createRef<string | null>();
25
+
26
+ mergeRefs(undefined, ref)(null);
27
+
28
+ expect(ref.current).toBeNull();
29
+ });
30
+
31
+ it('updates callback and object refs together', () => {
32
+ const callback = jest.fn();
33
+ const objectRef = createRef<string | null>();
34
+
35
+ mergeRefs(callback, objectRef)('shared');
36
+
37
+ expect(callback).toHaveBeenCalledWith('shared');
38
+ expect(objectRef.current).toBe('shared');
39
+ });
40
+
41
+ describe('React 19 ref-cleanup semantics', () => {
42
+ it('returns a cleanup function when called with a non-null value', () => {
43
+ const ref = createRef<string>();
44
+ const merged = mergeRefs(ref);
45
+
46
+ const cleanup = merged('value');
47
+
48
+ expect(typeof cleanup).toBe('function');
49
+ });
50
+
51
+ it('does not return a cleanup when called with null', () => {
52
+ const ref = createRef<string>();
53
+ const merged = mergeRefs(ref);
54
+
55
+ const result = merged(null);
56
+
57
+ expect(result).toBeUndefined();
58
+ });
59
+
60
+ it('cleanup nulls object refs', () => {
61
+ const refA = createRef<string>();
62
+ const refB = createRef<string>();
63
+ const merged = mergeRefs(refA, refB);
64
+
65
+ const cleanup = merged('value') as () => void;
66
+ expect(refA.current).toBe('value');
67
+ expect(refB.current).toBe('value');
68
+
69
+ cleanup();
70
+ expect(refA.current).toBeNull();
71
+ expect(refB.current).toBeNull();
72
+ });
73
+
74
+ it('cleanup calls callback refs with null when they did not return a cleanup', () => {
75
+ const callback = jest.fn();
76
+ const merged = mergeRefs(callback);
77
+
78
+ const cleanup = merged('value') as () => void;
79
+ expect(callback).toHaveBeenCalledWith('value');
80
+
81
+ callback.mockClear();
82
+ cleanup();
83
+ expect(callback).toHaveBeenCalledWith(null);
84
+ });
85
+
86
+ it('cleanup invokes the inner cleanup instead of calling ref(null) for refs that returned one', () => {
87
+ const innerCleanup = jest.fn();
88
+ const callbackWithCleanup = jest.fn().mockReturnValue(innerCleanup);
89
+ const merged = mergeRefs(callbackWithCleanup);
90
+
91
+ const cleanup = merged('element') as () => void;
92
+ expect(callbackWithCleanup).toHaveBeenCalledWith('element');
93
+
94
+ callbackWithCleanup.mockClear();
95
+ cleanup();
96
+ expect(innerCleanup).toHaveBeenCalledTimes(1);
97
+ expect(callbackWithCleanup).not.toHaveBeenCalled();
98
+ });
99
+
100
+ it('handles mixed refs: object, callback with cleanup, callback without cleanup', () => {
101
+ const objectRef = createRef<string>();
102
+ const innerCleanup = jest.fn();
103
+ const callbackWithCleanup = jest.fn().mockReturnValue(innerCleanup);
104
+ const callbackNoCleanup = jest.fn();
105
+
106
+ const merged = mergeRefs(objectRef, callbackWithCleanup, callbackNoCleanup);
107
+ const cleanup = merged('node') as () => void;
108
+
109
+ expect(objectRef.current).toBe('node');
110
+ expect(callbackWithCleanup).toHaveBeenCalledWith('node');
111
+ expect(callbackNoCleanup).toHaveBeenCalledWith('node');
112
+
113
+ callbackWithCleanup.mockClear();
114
+ callbackNoCleanup.mockClear();
115
+ cleanup();
116
+
117
+ expect(objectRef.current).toBeNull();
118
+ expect(innerCleanup).toHaveBeenCalledTimes(1);
119
+ expect(callbackWithCleanup).not.toHaveBeenCalled();
120
+ expect(callbackNoCleanup).toHaveBeenCalledWith(null);
121
+ });
122
+
123
+ it('null-call path still works for React 18 compat (calls all refs with null)', () => {
124
+ const objectRef = createRef<string>();
125
+ const callback = jest.fn();
126
+ const merged = mergeRefs(objectRef, callback);
127
+
128
+ merged('value');
129
+ callback.mockClear();
130
+
131
+ merged(null);
132
+
133
+ expect(objectRef.current).toBeNull();
134
+ expect(callback).toHaveBeenCalledWith(null);
135
+ });
136
+
137
+ it('skips undefined entries in cleanup', () => {
138
+ const objectRef = createRef<string>();
139
+ const merged = mergeRefs(undefined, objectRef, undefined);
140
+
141
+ const cleanup = merged('value') as () => void;
142
+ expect(objectRef.current).toBe('value');
143
+
144
+ cleanup();
145
+ expect(objectRef.current).toBeNull();
146
+ });
147
+ });
148
+ });
@@ -1,13 +1,56 @@
1
1
  import type { Ref, RefCallback } from 'react';
2
2
 
3
+ type CleanupFn = () => void;
4
+
5
+ /**
6
+ * Merges multiple refs (object or callback) into a single callback ref.
7
+ *
8
+ * Supports React 19 ref-cleanup semantics: if an inner callback ref returns a
9
+ * cleanup function, that cleanup is captured and invoked when the merged ref is
10
+ * detached — either via the returned cleanup (React 19) or via a subsequent
11
+ * call with `null` (React 18 backward-compat path).
12
+ */
3
13
  export function mergeRefs<T>(...refs: (Ref<T> | undefined)[]): RefCallback<T> {
4
- return (value: T | null) => {
14
+ return (value: T | null): CleanupFn | undefined => {
15
+ if (value === null) {
16
+ for (const ref of refs) {
17
+ if (typeof ref === 'function') {
18
+ ref(null);
19
+ } else if (ref != null) {
20
+ ref.current = null;
21
+ }
22
+ }
23
+ return undefined;
24
+ }
25
+
26
+ const cleanups: (CleanupFn | undefined)[] = [];
5
27
  for (const ref of refs) {
6
28
  if (typeof ref === 'function') {
7
- ref(value);
29
+ cleanups.push(ref(value) as CleanupFn | undefined);
8
30
  } else if (ref != null) {
9
31
  ref.current = value;
32
+ cleanups.push(undefined);
33
+ } else {
34
+ cleanups.push(undefined);
10
35
  }
11
36
  }
37
+
38
+ return () => {
39
+ for (let i = 0; i < refs.length; i++) {
40
+ const ref = refs[i];
41
+ if (ref == null) continue;
42
+
43
+ if (typeof ref === 'function') {
44
+ const refCleanup = cleanups[i];
45
+ if (typeof refCleanup === 'function') {
46
+ refCleanup();
47
+ } else {
48
+ ref(null);
49
+ }
50
+ } else {
51
+ ref.current = null;
52
+ }
53
+ }
54
+ };
12
55
  };
13
56
  }
@@ -0,0 +1,90 @@
1
+ import { act, renderHook } from '@testing-library/react-native';
2
+ import { useControllableState } from './useControllableState';
3
+
4
+ describe('useControllableState', () => {
5
+ it('manages uncontrolled state from defaultProp', () => {
6
+ const onChange = jest.fn();
7
+ const { result } = renderHook(() => useControllableState({ defaultProp: 'initial', onChange }));
8
+
9
+ expect(result.current[0]).toBe('initial');
10
+
11
+ act(() => {
12
+ result.current[1]('next');
13
+ });
14
+
15
+ expect(result.current[0]).toBe('next');
16
+ expect(onChange).toHaveBeenCalledWith('next');
17
+ });
18
+
19
+ it('uses prop value in controlled mode and notifies onChange', () => {
20
+ const onChange = jest.fn();
21
+ const { result } = renderHook(() => useControllableState({ prop: 'controlled', onChange }));
22
+
23
+ expect(result.current[0]).toBe('controlled');
24
+
25
+ act(() => {
26
+ result.current[1]('updated');
27
+ });
28
+
29
+ expect(onChange).toHaveBeenCalledWith('updated');
30
+ expect(result.current[0]).toBe('controlled');
31
+ });
32
+
33
+ it('supports function updaters in uncontrolled mode', () => {
34
+ const { result } = renderHook(() => useControllableState({ defaultProp: 1 }));
35
+
36
+ act(() => {
37
+ result.current[1]((prev: number | undefined) => (prev ?? 0) + 1);
38
+ });
39
+
40
+ expect(result.current[0]).toBe(2);
41
+ });
42
+
43
+ it('follows prop updates in controlled mode', () => {
44
+ const { result, rerender } = renderHook(({ value }) => useControllableState({ prop: value }), {
45
+ initialProps: { value: 'a' },
46
+ });
47
+
48
+ rerender({ value: 'b' });
49
+
50
+ expect(result.current[0]).toBe('b');
51
+ });
52
+
53
+ it('supports function updaters in controlled mode', () => {
54
+ const onChange = jest.fn();
55
+ const { result } = renderHook(() => useControllableState({ prop: 2, onChange }));
56
+
57
+ act(() => {
58
+ result.current[1]((prev: number | undefined) => (prev ?? 0) + 3);
59
+ });
60
+
61
+ expect(onChange).toHaveBeenCalledWith(5);
62
+ expect(result.current[0]).toBe(2);
63
+ });
64
+
65
+ it('does not notify onChange when controlled value is unchanged', () => {
66
+ const onChange = jest.fn();
67
+ const { result } = renderHook(() => useControllableState({ prop: 'same', onChange }));
68
+
69
+ act(() => {
70
+ result.current[1]('same');
71
+ });
72
+
73
+ expect(onChange).not.toHaveBeenCalled();
74
+ });
75
+
76
+ it('switches from uncontrolled to controlled when prop is provided', () => {
77
+ const { result, rerender } = renderHook(
78
+ (props: { prop?: string; defaultProp?: string }) => useControllableState(props),
79
+ { initialProps: { defaultProp: 'internal' } },
80
+ );
81
+
82
+ act(() => {
83
+ result.current[1]('internal');
84
+ });
85
+
86
+ rerender({ prop: 'external' });
87
+
88
+ expect(result.current[0]).toBe('external');
89
+ });
90
+ });
@@ -0,0 +1,31 @@
1
+ import type { ReactNode } from 'react';
2
+ import { renderHook } from '@testing-library/react-native';
3
+ import { createContext } from './createContext';
4
+
5
+ describe('createContext', () => {
6
+ it('provides value through Provider and consumer hook', () => {
7
+ const [Provider, useTestContext] = createContext<{ label: string }>('Test');
8
+
9
+ const wrapper = ({ children }: { children: ReactNode }) => (
10
+ <Provider value={{ label: 'hello' }}>{children}</Provider>
11
+ );
12
+
13
+ const { result } = renderHook(() => useTestContext(), { wrapper });
14
+
15
+ expect(result.current).toEqual({ label: 'hello' });
16
+ });
17
+
18
+ it('throws when consumer is used outside Provider', () => {
19
+ const [, useTestContext] = createContext<{ label: string }>('Test');
20
+
21
+ expect(() => {
22
+ renderHook(() => useTestContext());
23
+ }).toThrow('useTest must be used within a TestProvider');
24
+ });
25
+
26
+ it('names the Provider from the display name argument', () => {
27
+ const [Provider] = createContext<{ label: string }>('Field');
28
+
29
+ expect(Provider.displayName).toBe('FieldProvider');
30
+ });
31
+ });
@@ -5,8 +5,25 @@ import {
5
5
  useContext,
6
6
  } from 'react';
7
7
 
8
- export function createContext<T>(displayName: string) {
9
- const Context = createReactContext<T | undefined>(undefined);
8
+ interface CreateContextOptions<T> {
9
+ /**
10
+ * Value returned by the consumer hook when no matching provider is mounted.
11
+ * Only meaningful when `strict` is `false`; when omitted the hook returns `undefined`.
12
+ */
13
+ defaultValue?: T;
14
+ /**
15
+ * When `true` (default) the consumer hook throws if used outside its provider.
16
+ * Set to `false` to allow the hook to run without a provider, returning
17
+ * `defaultValue` (or `undefined`) instead of throwing.
18
+ * @default true
19
+ */
20
+ strict?: boolean;
21
+ }
22
+
23
+ export function createContext<T>(displayName: string, options?: CreateContextOptions<T>) {
24
+ const { defaultValue, strict = true } = options ?? {};
25
+
26
+ const Context = createReactContext<T | undefined>(defaultValue);
10
27
 
11
28
  const Provider: ComponentType<{ children: ReactNode; value: T }> = (props) => {
12
29
  const { children, value } = props;
@@ -17,10 +34,10 @@ export function createContext<T>(displayName: string) {
17
34
 
18
35
  function useC(): T {
19
36
  const context = useContext(Context);
20
- if (context === undefined) {
37
+ if (context === undefined && strict) {
21
38
  throw new Error(`use${displayName} must be used within a ${displayName}Provider`);
22
39
  }
23
- return context;
40
+ return context as T;
24
41
  }
25
42
 
26
43
  return [Provider, useC] as const;
@@ -1,4 +1,5 @@
1
1
  export {
2
+ type Focusable,
2
3
  type FormControlContextValue,
3
4
  type FormControlFieldProps,
4
5
  type FormControlRootProps,
@@ -8,4 +9,5 @@ export {
8
9
  useFormControl,
9
10
  useFormControlContext,
10
11
  useFormControlRoot,
12
+ useReportFormControlLabelFocus,
11
13
  } from './useFormControl';