panelui-native 0.36.0 → 0.38.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 (32) hide show
  1. package/README.md +12 -1
  2. package/lib/module/components/combobox/index.js +718 -0
  3. package/lib/module/components/combobox/index.js.map +1 -0
  4. package/lib/module/components/form/use-field.js +18 -0
  5. package/lib/module/components/form/use-field.js.map +1 -1
  6. package/lib/module/components/form/use-form.js +91 -8
  7. package/lib/module/components/form/use-form.js.map +1 -1
  8. package/lib/module/components/input/index.js +10 -3
  9. package/lib/module/components/input/index.js.map +1 -1
  10. package/lib/module/components/select/index.js +116 -15
  11. package/lib/module/components/select/index.js.map +1 -1
  12. package/lib/module/index.js +1 -0
  13. package/lib/module/index.js.map +1 -1
  14. package/lib/module/theme/use-theme.js +1 -1
  15. package/lib/typescript/src/components/combobox/index.d.ts +164 -0
  16. package/lib/typescript/src/components/combobox/index.d.ts.map +1 -0
  17. package/lib/typescript/src/components/form/use-field.d.ts.map +1 -1
  18. package/lib/typescript/src/components/form/use-form.d.ts.map +1 -1
  19. package/lib/typescript/src/components/input/index.d.ts +18 -4
  20. package/lib/typescript/src/components/input/index.d.ts.map +1 -1
  21. package/lib/typescript/src/components/select/index.d.ts +32 -0
  22. package/lib/typescript/src/components/select/index.d.ts.map +1 -1
  23. package/lib/typescript/src/index.d.ts +2 -1
  24. package/lib/typescript/src/index.d.ts.map +1 -1
  25. package/lib/typescript/src/theme/use-theme.d.ts +1 -1
  26. package/package.json +1 -1
  27. package/src/components/combobox/index.tsx +927 -0
  28. package/src/components/form/use-field.ts +23 -0
  29. package/src/components/form/use-form.ts +106 -16
  30. package/src/components/input/index.tsx +21 -7
  31. package/src/components/select/index.tsx +114 -15
  32. package/src/index.ts +10 -0
@@ -47,6 +47,29 @@ export function useField<T extends Record<string, any>, K extends keyof T>(
47
47
  // eslint-disable-next-line react-hooks/exhaustive-deps
48
48
  }, [registerValidator, name, !!validate]);
49
49
 
50
+ /*
51
+ * A name the form never declared is the one mistake this hook cannot
52
+ * recover from: there is no value to hand a validator, so a rule as ordinary
53
+ * as `value.length > 0` throws on a field that was only blurred, and nothing
54
+ * the user types is ever submitted. Both failures point away from the cause,
55
+ * so it is named here instead. Development only — the check costs a key
56
+ * lookup, but the message is for whoever is writing the form.
57
+ */
58
+ const formValues = form.values;
59
+ useEffect(() => {
60
+ if (process.env.NODE_ENV === 'production') return;
61
+ if (name in formValues) return;
62
+ console.warn(
63
+ `[PanelUI] Form field "${String(name)}" is not declared in the form's ` +
64
+ `defaultValues, so its value is undefined and it will not be submitted. ` +
65
+ `Add "${String(name)}" to defaultValues — an empty field is still a ` +
66
+ `declared one ("" for text, false for a toggle).`
67
+ );
68
+ // The declared names come from `defaultValues`, which is read once, so
69
+ // this is a question about the name and nothing else.
70
+ // eslint-disable-next-line react-hooks/exhaustive-deps
71
+ }, [name]);
72
+
50
73
  const { value, error, touched } = form.getFieldState(name);
51
74
 
52
75
  return {
@@ -24,6 +24,12 @@
24
24
  * `defaultValues` is read once, on the first render. If default values
25
25
  * arrive asynchronously, mount the form once you have them (e.g. behind a
26
26
  * loading check) rather than expecting the hook to pick up a later change.
27
+ *
28
+ * It also declares the fields. A field's `name` has to be a key of it —
29
+ * including the empty ones, as `''`, `false`, `null`. A name it does not
30
+ * declare has no value to give a validator and nothing to submit, so
31
+ * `useField` says so in development rather than letting the field quietly do
32
+ * nothing.
27
33
  */
28
34
  import { useCallback, useMemo, useReducer, useRef } from 'react';
29
35
 
@@ -123,6 +129,42 @@ function reducer<T extends Record<string, any>>(
123
129
  }
124
130
  }
125
131
 
132
+ /** Stands in for the message a rule that crashed never got to return. */
133
+ const VALIDATOR_THREW = 'This field could not be validated.';
134
+
135
+ /**
136
+ * Run one field's rule, and survive a rule that throws.
137
+ *
138
+ * A validator is caller code reached from a path nothing awaits — `onBlur`
139
+ * fires and forgets, and `handleSubmit` is wired straight to a press. A throw
140
+ * in there becomes an unhandled rejection: a red box whose message ("cannot
141
+ * read property 'length' of undefined") names neither the field nor the rule,
142
+ * and which takes the screen for one line of one validator.
143
+ *
144
+ * So it is caught, reported against the field by name, and counted as a
145
+ * failure. Counted, rather than waved through: a rule that crashed reached no
146
+ * verdict, and a form that submits past a rule that never ran is the worse of
147
+ * the two outcomes — it puts unchecked values somewhere they cannot be taken
148
+ * back from. The placeholder message is what stands between the two; the
149
+ * console entry beside it is for whoever can fix the rule.
150
+ */
151
+ async function runValidator<T extends Record<string, any>>(
152
+ name: keyof T,
153
+ validator: (value: any, values: T) => string | undefined | Promise<string | undefined>,
154
+ values: T
155
+ ): Promise<string | undefined> {
156
+ try {
157
+ return await validator(values[name], values);
158
+ } catch (error) {
159
+ console.error(
160
+ `[PanelUI] The validator for form field "${String(name)}" threw, so the ` +
161
+ `field is being treated as invalid.`,
162
+ error
163
+ );
164
+ return VALIDATOR_THREW;
165
+ }
166
+ }
167
+
126
168
  export function useForm<T extends Record<string, any>>({
127
169
  defaultValues,
128
170
  validate,
@@ -140,7 +182,22 @@ export function useForm<T extends Record<string, any>>({
140
182
  isSubmitting: false,
141
183
  });
142
184
 
185
+ /*
186
+ * The values as of the last *change*, not as of the last render.
187
+ *
188
+ * Validation runs in the same tick as the edit that triggered it —
189
+ * `validateOn="change"` calls `validateField` immediately after
190
+ * `setFieldValue`, and submit runs from a press handler. React state is a
191
+ * render behind at that point, so a validator reading it would judge the
192
+ * character before the one just typed, and a submit fired straight after an
193
+ * edit would submit the value before it. The ref is written on the way into
194
+ * the dispatch so both see what the user actually entered.
195
+ */
196
+ const valuesRef = useRef(state.values);
197
+ valuesRef.current = state.values;
198
+
143
199
  const setFieldValue = useCallback(<K extends keyof T>(name: K, value: T[K]) => {
200
+ valuesRef.current = { ...valuesRef.current, [name]: value } as T;
144
201
  dispatch({ type: 'SET_VALUE', name, value });
145
202
  }, []);
146
203
 
@@ -175,32 +232,64 @@ export function useForm<T extends Record<string, any>>({
175
232
  [state.values, state.errors, state.touched]
176
233
  );
177
234
 
178
- const validateField = useCallback(
179
- async <K extends keyof T>(name: K) => {
180
- const validator = validatorsRef.current[name];
181
- if (!validator) return true;
182
- const error = await validator(state.values[name], state.values);
183
- dispatch({ type: 'SET_ERROR', name, error });
184
- return !error;
185
- },
186
- [state.values]
187
- );
235
+ const validateField = useCallback(async <K extends keyof T>(name: K) => {
236
+ const validator = validatorsRef.current[name];
237
+ if (!validator) return true;
238
+ const values = valuesRef.current;
239
+ const error = await runValidator(name, validator, values);
240
+ dispatch({ type: 'SET_ERROR', name, error });
241
+ return !error;
242
+ }, []);
188
243
 
189
244
  const handleSubmit = useCallback(async () => {
190
- const names = Object.keys(state.values) as (keyof T)[];
245
+ const values = valuesRef.current;
246
+ /*
247
+ * Every field the form knows of, which is not the same as every key of
248
+ * `defaultValues`: a field can register a validator under a name that was
249
+ * never declared there. Submitting only the declared ones meant such a
250
+ * field was never validated and never blocked anything, so a form of
251
+ * required-but-undeclared fields submitted itself while still empty.
252
+ *
253
+ * It is still a mistake to name a field that `defaultValues` does not
254
+ * declare — its value stays undefined and never reaches `onSubmit` —
255
+ * which is why `useField` says so. Validating it anyway is what turns
256
+ * that mistake into a visible error instead of a silent submit.
257
+ */
258
+ const names = Array.from(
259
+ new Set([...Object.keys(values), ...Object.keys(validatorsRef.current)])
260
+ ) as (keyof T)[];
191
261
  dispatch({ type: 'TOUCH_ALL', names });
192
262
 
193
263
  const fieldErrorEntries = await Promise.all(
194
264
  names.map(async (name) => {
195
265
  const validator = validatorsRef.current[name];
196
266
  const error = validator
197
- ? await validator(state.values[name], state.values)
267
+ ? await runValidator(name, validator, values)
198
268
  : undefined;
199
269
  return [name, error] as const;
200
270
  })
201
271
  );
202
272
 
203
- const formErrors = validate ? await validate(state.values) : {};
273
+ /*
274
+ * Same reasoning as a field's rule, one level up: a cross-field check that
275
+ * throws must not take the screen, and must not let the submit through.
276
+ * It belongs to no single field, so it blocks without marking one — there
277
+ * is no field whose error line would be the honest place to put it.
278
+ */
279
+ let formErrors: FieldErrors<T> = {};
280
+ let formValidateThrew = false;
281
+ if (validate) {
282
+ try {
283
+ formErrors = await validate(values);
284
+ } catch (error) {
285
+ console.error(
286
+ '[PanelUI] The form-level validate() threw, so the form is being ' +
287
+ 'treated as invalid and the submit was not run.',
288
+ error
289
+ );
290
+ formValidateThrew = true;
291
+ }
292
+ }
204
293
 
205
294
  const cleared = Object.fromEntries(names.map((name) => [name, undefined]));
206
295
  const nextErrors: FieldErrors<T> = {
@@ -210,17 +299,18 @@ export function useForm<T extends Record<string, any>>({
210
299
  };
211
300
  dispatch({ type: 'SET_ERRORS', errors: nextErrors });
212
301
 
213
- if (Object.values(nextErrors).some(Boolean)) return;
302
+ if (formValidateThrew || Object.values(nextErrors).some(Boolean)) return;
214
303
 
215
304
  dispatch({ type: 'SUBMIT_START' });
216
305
  try {
217
- await onSubmit(state.values);
306
+ await onSubmit(values);
218
307
  } finally {
219
308
  dispatch({ type: 'SUBMIT_END' });
220
309
  }
221
- }, [state.values, validate, onSubmit]);
310
+ }, [validate, onSubmit]);
222
311
 
223
312
  const reset = useCallback((values: T = defaultsRef.current) => {
313
+ valuesRef.current = values;
224
314
  dispatch({ type: 'RESET', values });
225
315
  }, []);
226
316
 
@@ -27,6 +27,13 @@
27
27
  * field, so anything centred on the component as a whole drifts upward the
28
28
  * moment a label is added.
29
29
  *
30
+ * Both are pressable. A button dropped in there — a clear ✕, a show-password
31
+ * eye — gets its own touches, while the padding around it stays transparent so
32
+ * a tap that misses still lands on the field and puts the caret in it. An icon
33
+ * that is only decoration should say so with `interactiveContent={false}`,
34
+ * which gives the whole field back to the caret and takes the icon out of the
35
+ * accessibility tree.
36
+ *
30
37
  * `InputGroup` is still the right answer for a decorator that is not part of
31
38
  * the field — a button attached to its end, a select bolted to its start, an
32
39
  * addon with its own background. It measures the same way; it just spans a
@@ -155,11 +162,18 @@ export interface InputProps
155
162
  /** Content inside the field, after the text — an icon, a unit, a count. */
156
163
  endContent?: ReactNode;
157
164
  /**
158
- * Let touches reach the content instead of falling through to the field.
165
+ * Whether touches reach the content.
166
+ *
167
+ * On by default, so a button placed in the field — a clear ✕, a
168
+ * show-password eye, a unit picker — is pressable without anything else
169
+ * being passed. Only the content itself takes those touches: the padding
170
+ * around it is transparent, so a tap that misses the button still lands on
171
+ * the field and puts the caret in it.
159
172
  *
160
- * Off by default: an icon is decoration, and a tap anywhere on a field
161
- * should put the caret in it rather than hitting a dead spot. Turn it on for
162
- * content that does something — a clear button, a show-password toggle.
173
+ * Turn it off for pure decoration, where the icon should not be a target at
174
+ * all and every pixel of the field should focus it. That also drops the
175
+ * content from the accessibility tree, which is right for an icon that only
176
+ * restates the label.
163
177
  */
164
178
  interactiveContent?: boolean;
165
179
  /**
@@ -205,7 +219,7 @@ export const Input = forwardRef<TextInput, InputProps>(
205
219
  disabled,
206
220
  startContent,
207
221
  endContent,
208
- interactiveContent = false,
222
+ interactiveContent = true,
209
223
  variant,
210
224
  size,
211
225
  avoidKeyboard = false,
@@ -342,7 +356,7 @@ export const Input = forwardRef<TextInput, InputProps>(
342
356
  {startContent ? (
343
357
  <View
344
358
  onLayout={handleStartLayout}
345
- pointerEvents={interactiveContent ? 'auto' : 'none'}
359
+ pointerEvents={interactiveContent ? 'box-none' : 'none'}
346
360
  accessibilityElementsHidden={!interactiveContent}
347
361
  importantForAccessibility={
348
362
  interactiveContent ? 'auto' : 'no-hide-descendants'
@@ -358,7 +372,7 @@ export const Input = forwardRef<TextInput, InputProps>(
358
372
  {endContent ? (
359
373
  <View
360
374
  onLayout={handleEndLayout}
361
- pointerEvents={interactiveContent ? 'auto' : 'none'}
375
+ pointerEvents={interactiveContent ? 'box-none' : 'none'}
362
376
  accessibilityElementsHidden={!interactiveContent}
363
377
  importantForAccessibility={
364
378
  interactiveContent ? 'auto' : 'no-hide-descendants'
@@ -26,9 +26,16 @@
26
26
  * the option labels. The filter narrows what is *shown* — the declared options
27
27
  * are still the source of truth, so nothing has to be lifted into state to make
28
28
  * it work.
29
+ *
30
+ * A list long enough to need a filter is usually long enough to want dividing,
31
+ * so options can be wrapped in `Select.Group` under a heading. Grouping is
32
+ * presentational — the value is still a flat string — and the filter reaches
33
+ * through it, dropping any group the query empties rather than leaving a
34
+ * heading standing over nothing.
29
35
  */
30
36
  import {
31
37
  Children,
38
+ cloneElement,
32
39
  createContext,
33
40
  isValidElement,
34
41
  useCallback,
@@ -36,6 +43,7 @@ import {
36
43
  useMemo,
37
44
  useRef,
38
45
  useState,
46
+ type ReactElement,
39
47
  type ReactNode,
40
48
  } from 'react';
41
49
  import {
@@ -59,6 +67,7 @@ import { getNativeUI } from '../../native';
59
67
  import { Portal } from '../../primitives/portal';
60
68
  import { Text, textChildren } from '../../primitives/text';
61
69
  import { useBackHandler } from '../../hooks/use-back-handler';
70
+ import { cn } from '../../utils/cn';
62
71
  import { BottomSheet } from '../bottom-sheet';
63
72
  import { InputGroup } from '../input-group';
64
73
 
@@ -74,6 +83,8 @@ const selectVariants = tv({
74
83
  item: 'flex-row items-center gap-2 rounded-lg px-3 py-3',
75
84
  itemLabel: 'flex-1 text-base font-medium text-foreground',
76
85
  itemIndicator: 'h-5 w-5 items-center justify-center',
86
+ group: 'gap-1',
87
+ groupLabel: 'px-3 pb-1 pt-2',
77
88
  },
78
89
  variants: {
79
90
  selected: {
@@ -151,6 +162,96 @@ function SelectItem({ value, label, disabled }: SelectItemProps) {
151
162
  );
152
163
  }
153
164
 
165
+ export interface SelectGroupProps {
166
+ /**
167
+ * Heading over the run of options. Announced as a header, so a screen reader
168
+ * reaching the group is told what it is before walking into it.
169
+ */
170
+ label?: string;
171
+ /** Extra classes for the group wrapper. */
172
+ className?: string;
173
+ /** Extra classes for the heading. */
174
+ labelClassName?: string;
175
+ children: ReactNode;
176
+ }
177
+
178
+ /**
179
+ * A titled run of options.
180
+ *
181
+ * Purely a way of arranging the list: a grouped Select still reports one flat
182
+ * string, and `Select.Item` needs to know nothing about being inside one.
183
+ */
184
+ function SelectGroup({ label, className, labelClassName, children }: SelectGroupProps) {
185
+ const { group, groupLabel } = selectVariants();
186
+
187
+ return (
188
+ <View className={cn(group(), className)}>
189
+ {label ? (
190
+ <View accessibilityRole="header" className={cn(groupLabel(), labelClassName)}>
191
+ <Text size="xs" weight="medium" muted className="uppercase tracking-wide">
192
+ {label}
193
+ </Text>
194
+ </View>
195
+ ) : null}
196
+ {textChildren(children)}
197
+ </View>
198
+ );
199
+ }
200
+
201
+ /**
202
+ * Walk the declared children, visiting every `Select.Item` — including the ones
203
+ * nested inside a `Select.Group`.
204
+ *
205
+ * Grouping is a rendering concern, but the selected label and the native
206
+ * picker's option list both want the flat set, so the tree is flattened once
207
+ * here rather than in each of them.
208
+ */
209
+ function eachOption(children: ReactNode, visit: (option: SelectItemProps) => void) {
210
+ Children.forEach(children, (child) => {
211
+ if (!isValidElement(child)) return;
212
+ if (child.type === SelectGroup) {
213
+ eachOption((child.props as SelectGroupProps).children, visit);
214
+ return;
215
+ }
216
+ if (child.type !== SelectItem) return;
217
+ const { value, label, disabled } = child.props as SelectItemProps;
218
+ visit({ value, label, disabled });
219
+ });
220
+ }
221
+
222
+ /**
223
+ * The children a query leaves standing.
224
+ *
225
+ * A group is rebuilt around whatever survives inside it and dropped when that
226
+ * is nothing — a heading with no options under it reads as a section that
227
+ * failed to load rather than one the filter emptied. Anything that is neither
228
+ * an item nor a group is left alone: a caption or a divider the caller put in
229
+ * the list is not something a filter has an opinion about.
230
+ */
231
+ function filterOptions(children: ReactNode, needle: string): ReactNode[] {
232
+ const kept: ReactNode[] = [];
233
+
234
+ Children.forEach(children, (child) => {
235
+ if (!isValidElement(child)) return;
236
+
237
+ if (child.type === SelectGroup) {
238
+ const props = child.props as SelectGroupProps;
239
+ const inner = filterOptions(props.children, needle);
240
+ if (inner.length) {
241
+ kept.push(cloneElement(child as ReactElement<SelectGroupProps>, {}, inner));
242
+ }
243
+ return;
244
+ }
245
+
246
+ if (child.type === SelectItem) {
247
+ const { label } = child.props as SelectItemProps;
248
+ if (label.toLowerCase().includes(needle)) kept.push(child);
249
+ }
250
+ });
251
+
252
+ return kept;
253
+ }
254
+
154
255
  /** Trigger frame in window coordinates, measured when the list opens. */
155
256
  interface Anchor {
156
257
  x: number;
@@ -242,15 +343,7 @@ function SelectRoot({
242
343
 
243
344
  const options = useMemo(() => {
244
345
  const collected: SelectItemProps[] = [];
245
- Children.forEach(children, (child) => {
246
- if (isValidElement<SelectItemProps>(child)) {
247
- collected.push({
248
- value: child.props.value,
249
- label: child.props.label,
250
- disabled: child.props.disabled,
251
- });
252
- }
253
- });
346
+ eachOption(children, (option) => collected.push(option));
254
347
  return collected;
255
348
  }, [children]);
256
349
 
@@ -269,11 +362,7 @@ function SelectRoot({
269
362
  const needle = searchable ? query.trim().toLowerCase() : '';
270
363
  if (!needle) return null;
271
364
 
272
- return Children.toArray(children).filter(
273
- (child) =>
274
- isValidElement<SelectItemProps>(child) &&
275
- child.props.label.toLowerCase().includes(needle)
276
- );
365
+ return filterOptions(children, needle);
277
366
  }, [children, query, searchable]);
278
367
 
279
368
  const close = useCallback(() => {
@@ -360,7 +449,13 @@ function SelectRoot({
360
449
  const trigger = (
361
450
  <Pressable
362
451
  ref={triggerRef}
363
- accessibilityRole="button"
452
+ /*
453
+ * A trigger that owns a list of options and reports whether that list is
454
+ * open is a combobox, not a button — and `expanded` only means anything
455
+ * on a role that can be expanded. Announced as "collapsed"/"expanded"
456
+ * rather than as a button whose state has nowhere to be read.
457
+ */
458
+ accessibilityRole="combobox"
364
459
  accessibilityState={{ disabled: !!disabled, expanded: open }}
365
460
  disabled={disabled}
366
461
  onPress={toggle}
@@ -566,6 +661,10 @@ function SelectRoot({
566
661
  );
567
662
  }
568
663
 
664
+ SelectItem.displayName = 'Select.Item';
665
+ SelectGroup.displayName = 'Select.Group';
666
+
569
667
  export const Select = Object.assign(SelectRoot, {
570
668
  Item: SelectItem,
669
+ Group: SelectGroup,
571
670
  });
package/src/index.ts CHANGED
@@ -235,6 +235,7 @@ export {
235
235
  Select,
236
236
  type SelectProps,
237
237
  type SelectItemProps,
238
+ type SelectGroupProps,
238
239
  type SelectPresentation,
239
240
  } from './components/select';
240
241
  export {
@@ -304,6 +305,15 @@ export {
304
305
  type ChipVariant,
305
306
  type ChipSize,
306
307
  } from './components/chip';
308
+ export {
309
+ Combobox,
310
+ type ComboboxProps,
311
+ type ComboboxItemProps,
312
+ type ComboboxGroupProps,
313
+ type ComboboxMode,
314
+ type ComboboxSelection,
315
+ type ComboboxPresentation,
316
+ } from './components/combobox';
307
317
  export {
308
318
  Drawer,
309
319
  type DrawerProps,