@milktop/react-ui 0.3.4 → 0.3.6

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.
@@ -11,7 +11,10 @@
11
11
  * - `span`: columns (of 12) to take inside Fields
12
12
  * - without children it renders an Input, and the other props (value,
13
13
  * onValueChange, type, placeholder, icon, suffix…) pass on to it; with
14
- * type="number" a NumberInput (value a number or null, min, max, step…)
14
+ * type="number" a NumberInput (value a number or null, min, max, step…);
15
+ * with type="phone" a PhoneInput (country, countries, showType, picker…)
16
+ * - a control can report a problem of its own (PhoneInput's "too short"):
17
+ * it shows like an error while `error` is empty
15
18
  *
16
19
  * <Field label="Rate" type="number" min={0} prefix="£" value={rate} onValueChange={setRate} />
17
20
  *
@@ -23,10 +26,11 @@
23
26
  * <Field.ErrorText>{error}</Field.ErrorText>
24
27
  * </Field.Root>
25
28
  */
26
- import type { ComponentProps, ReactNode } from 'react';
29
+ import { type ComponentProps, type CSSProperties, type ReactNode } from 'react';
27
30
  import { Field as Ark } from '@ark-ui/react/field';
28
31
  import { type InputProps } from '../input/Input.js';
29
32
  import { type NumberInputProps } from '../number-input/NumberInput.js';
33
+ import { type PhoneInputProps } from '../phone-input/PhoneInput.js';
30
34
  import { type Classes } from '../utils.js';
31
35
  import '../theme.css';
32
36
  import './field.css';
@@ -35,6 +39,8 @@ type Control = DistributiveOmit<Exclude<InputProps, {
35
39
  type: 'number';
36
40
  }>, 'label' | 'classes' | 'children'> | (Omit<NumberInputProps, 'label' | 'classes' | 'children'> & {
37
41
  type: 'number';
42
+ }) | (Omit<PhoneInputProps, 'label' | 'classes'> & {
43
+ type: 'phone';
38
44
  });
39
45
  export type FieldProps = Control & {
40
46
  label?: ReactNode;
@@ -43,6 +49,7 @@ export type FieldProps = Control & {
43
49
  required?: boolean;
44
50
  disabled?: boolean;
45
51
  span?: number;
52
+ style?: CSSProperties;
46
53
  classes?: Classes<'root' | 'label' | 'requiredIndicator' | 'helperText' | 'errorText'>;
47
54
  children?: ReactNode;
48
55
  };
@@ -1,18 +1,54 @@
1
1
  import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
2
+ /**
3
+ * A form field: a label, hint and error around one control, wired up for
4
+ * assistive tech. Controls inside it (Input, Select, Checkbox…) skip their
5
+ * own label and point at its.
6
+ *
7
+ * <Field label="Student" error={errors.student}>
8
+ * <Select items={students} value={student} onValueChange={setStudent} />
9
+ * </Field>
10
+ *
11
+ * - `label`, `hint`, `error` (shown instead of the hint), `required`
12
+ * - `span`: columns (of 12) to take inside Fields
13
+ * - without children it renders an Input, and the other props (value,
14
+ * onValueChange, type, placeholder, icon, suffix…) pass on to it; with
15
+ * type="number" a NumberInput (value a number or null, min, max, step…);
16
+ * with type="phone" a PhoneInput (country, countries, showType, picker…)
17
+ * - a control can report a problem of its own (PhoneInput's "too short"):
18
+ * it shows like an error while `error` is empty
19
+ *
20
+ * <Field label="Rate" type="number" min={0} prefix="£" value={rate} onValueChange={setRate} />
21
+ *
22
+ * By hand, with Ark's Field parts:
23
+ *
24
+ * <Field.Root invalid={!!error}>
25
+ * <Field.Label>Email <Field.RequiredIndicator /></Field.Label>
26
+ * <Input />
27
+ * <Field.ErrorText>{error}</Field.ErrorText>
28
+ * </Field.Root>
29
+ */
30
+ import { useState } from 'react';
2
31
  import { Field as Ark } from '@ark-ui/react/field';
3
32
  import { Input } from '../input/Input.js';
4
33
  import { NumberInput } from '../number-input/NumberInput.js';
34
+ import { PhoneInput } from '../phone-input/PhoneInput.js';
35
+ import { FieldReport } from './report.js';
5
36
  import { cx, partsOf, withParts } from '../utils.js';
6
37
  import '../theme.css';
7
38
  import './field.css';
8
39
  function FieldShortcut({ label = null, hint = null, error = null, required = false, disabled = false, span = 12, className, classes, style, children, ...inputProps }) {
9
40
  const part = partsOf('field', classes);
10
- return (_jsxs(Ark.Root, { ...part('root'), className: cx(className, classes?.root), style: { '--span': span, ...style }, invalid: !!error, required: required, disabled: disabled, children: [label && _jsxs(Ark.Label, { ...part('label'), children: [label, _jsx(Ark.RequiredIndicator, { ...part('required-indicator'), "aria-hidden": "true", children: " *" })] }), children ?? control(inputProps), error ? _jsx(Ark.ErrorText, { ...part('error-text'), children: error })
41
+ // A control's own problem (PhoneInput's "too short"), shown while there's no `error`
42
+ const [reported, setReported] = useState(null);
43
+ const message = error || reported;
44
+ return (_jsxs(Ark.Root, { ...part('root'), className: cx(className, classes?.root), style: { '--span': span, ...style }, invalid: !!message, required: required, disabled: disabled, children: [label && _jsxs(Ark.Label, { ...part('label'), children: [label, _jsx(Ark.RequiredIndicator, { ...part('required-indicator'), "aria-hidden": "true", children: " *" })] }), _jsx(FieldReport.Provider, { value: setReported, children: children ?? control(inputProps) }), message ? _jsx(Ark.ErrorText, { ...part('error-text'), children: message })
11
45
  : hint && _jsx(Ark.HelperText, { ...part('helper-text'), children: hint })] }));
12
46
  }
13
47
  function control({ type, ...props }) {
14
48
  if (type === 'number')
15
49
  return _jsx(NumberInput, { ...props });
50
+ if (type === 'phone')
51
+ return _jsx(PhoneInput, { ...props });
16
52
  return _jsx(Input, { type: type, ...props });
17
53
  }
18
54
  export const Field = withParts(FieldShortcut, {
@@ -0,0 +1,2 @@
1
+ export declare const FieldReport: import("react").Context<((problem: string | null) => void) | null>;
2
+ export declare const useFieldReport: () => ((problem: string | null) => void) | null;
@@ -0,0 +1,5 @@
1
+ import { createContext, useContext } from 'react';
2
+ // A control's own problem (a phone number too short), shown by its Field while
3
+ // it has no `error`; null clears it.
4
+ export const FieldReport = createContext(null);
5
+ export const useFieldReport = () => useContext(FieldReport);
@@ -140,6 +140,16 @@ export type Messages = {
140
140
  down: string;
141
141
  same: string;
142
142
  };
143
+ phoneInput: {
144
+ country: string;
145
+ search: string;
146
+ noMatch: string;
147
+ mobile: string;
148
+ landline: string;
149
+ tooShort: string;
150
+ tooLong: string;
151
+ invalid: string;
152
+ };
143
153
  themeToggle: {
144
154
  label: string;
145
155
  light: string;
@@ -35,6 +35,10 @@ export const en = {
35
35
  actionBar: { label: 'Selection actions' },
36
36
  chart: { label: 'Chart', total: 'Total' },
37
37
  stat: { up: 'Up', down: 'Down', same: 'No change' },
38
+ phoneInput: {
39
+ country: 'Country', search: 'Search countries', noMatch: 'No country found', mobile: 'Mobile', landline: 'Landline',
40
+ tooShort: 'This number is too short', tooLong: 'This number is too long', invalid: 'This isn’t a phone number',
41
+ },
38
42
  themeToggle: { label: 'Colour scheme', light: 'Light', dark: 'Dark', system: 'System' },
39
43
  appearance: {
40
44
  label: 'Appearance', mode: 'Mode', accent: 'Colour', sidebar: 'Sidebar', lightOnly: 'in light mode',
@@ -120,6 +124,10 @@ export const fr = {
120
124
  actionBar: { label: 'Actions sur la sélection' },
121
125
  chart: { label: 'Graphique', total: 'Total' },
122
126
  stat: { up: 'Hausse', down: 'Baisse', same: 'Stable' },
127
+ phoneInput: {
128
+ country: 'Pays', search: 'Rechercher un pays', noMatch: 'Aucun pays trouvé', mobile: 'Mobile', landline: 'Fixe',
129
+ tooShort: 'Numéro trop court', tooLong: 'Numéro trop long', invalid: 'Numéro de téléphone invalide',
130
+ },
123
131
  themeToggle: { label: 'Thème', light: 'Clair', dark: 'Sombre', system: 'Système' },
124
132
  appearance: {
125
133
  label: 'Apparence', mode: 'Mode', accent: 'Couleur', sidebar: 'Barre latérale', lightOnly: 'en mode clair',
package/dist/index.d.ts CHANGED
@@ -11,12 +11,14 @@ export { EmptyState } from './empty-state/EmptyState.js';
11
11
  export { Input } from './input/Input.js';
12
12
  export { Textarea } from './textarea/Textarea.js';
13
13
  export { PasswordInput } from './password-input/PasswordInput.js';
14
+ export { PhoneInput } from './phone-input/PhoneInput.js';
14
15
  export { NumberInput } from './number-input/NumberInput.js';
15
16
  export { PinInput } from './pin-input/PinInput.js';
16
17
  export { TagsInput } from './tags-input/TagsInput.js';
17
18
  export { Slider } from './slider/Slider.js';
18
19
  export { FileUpload } from './file-upload/FileUpload.js';
19
20
  export { Field, Fields } from './field/Field.js';
21
+ export { useFieldReport } from './field/report.js';
20
22
  export { Select, Combobox, createListCollection } from './select/Select.js';
21
23
  export { DatePicker, parseDate } from './date-picker/DatePicker.js';
22
24
  export { Checkbox } from './checkbox/Checkbox.js';
package/dist/index.js CHANGED
@@ -12,12 +12,14 @@ export { EmptyState } from './empty-state/EmptyState.js';
12
12
  export { Input } from './input/Input.js';
13
13
  export { Textarea } from './textarea/Textarea.js';
14
14
  export { PasswordInput } from './password-input/PasswordInput.js';
15
+ export { PhoneInput } from './phone-input/PhoneInput.js';
15
16
  export { NumberInput } from './number-input/NumberInput.js';
16
17
  export { PinInput } from './pin-input/PinInput.js';
17
18
  export { TagsInput } from './tags-input/TagsInput.js';
18
19
  export { Slider } from './slider/Slider.js';
19
20
  export { FileUpload } from './file-upload/FileUpload.js';
20
21
  export { Field, Fields } from './field/Field.js';
22
+ export { useFieldReport } from './field/report.js';
21
23
  export { Select, Combobox, createListCollection } from './select/Select.js';
22
24
  export { DatePicker, parseDate } from './date-picker/DatePicker.js';
23
25
  export { Checkbox } from './checkbox/Checkbox.js';
@@ -0,0 +1,55 @@
1
+ /**
2
+ * A phone number input: the number, and a flag that is also a country picker.
3
+ *
4
+ * <PhoneInput label="Phone" country="FR" countries={['FR', 'BE', 'GB']} showType value={phone} onValueChange={setPhone} />
5
+ * <Field label="Phone" type="phone" countries={['FR', 'BE']} value={phone} onValueChange={setPhone} />
6
+ *
7
+ * - `value`, `defaultValue`: the number in E.164 ('+33612345678') once it's
8
+ * valid, else the text as typed, so a form can still reject it
9
+ * - `onValueChange`: called as it's typed; `onValueCommit`: when it's left or
10
+ * a country is picked (the number then shows formatted)
11
+ * - `country`: the country of numbers typed without a "+" (default: the
12
+ * locale's region, e.g. FR for 'fr-FR')
13
+ * - `countries`: countries listed first in the picker, e.g. ['FR', 'BE', 'GB']
14
+ * - `showType`: a mobile or landline icon after a valid number (its word as a
15
+ * tooltip and label)
16
+ * - `picker`: 'search' (a list searched by name, code or dialling code) or
17
+ * 'native' (the browser's own select); by default native on touch screens
18
+ * - `label`: a label above it (skipped inside a Field); `locale`: for the
19
+ * countries' names (the LocaleProvider's by default)
20
+ * - `name`, `placeholder`, `autoComplete` ('tel'), `required`, `disabled`: as
21
+ * on an input
22
+ *
23
+ * It shows a number in national format when it's in `country`, international
24
+ * otherwise. The flag follows the number ("+44…" shows the UK's); picking one
25
+ * reads a number typed without "+" as that country's; Backspace in the empty
26
+ * input goes back to `country`. A number left invalid says why once the input
27
+ * loses focus (too short, too long, not a number), in its Field when it has
28
+ * one; an `error` given to the Field wins.
29
+ */
30
+ import { type ReactNode } from 'react';
31
+ import '../icons.js';
32
+ import { type Classes } from '../utils.js';
33
+ import '../theme.css';
34
+ import '../popover/popover.css';
35
+ import './phone-input.css';
36
+ export type PhoneInputProps = {
37
+ value?: string | null;
38
+ defaultValue?: string | null;
39
+ onValueChange?: (value: string) => void;
40
+ onValueCommit?: (value: string) => void;
41
+ country?: string | null;
42
+ countries?: string[];
43
+ showType?: boolean;
44
+ picker?: 'search' | 'native' | null;
45
+ label?: ReactNode;
46
+ locale?: string;
47
+ name?: string;
48
+ placeholder?: string;
49
+ autoComplete?: string;
50
+ required?: boolean;
51
+ disabled?: boolean;
52
+ className?: string;
53
+ classes?: Classes<'root' | 'label' | 'control' | 'country' | 'flag' | 'picker' | 'input' | 'type' | 'countries' | 'search' | 'list' | 'option' | 'empty'>;
54
+ };
55
+ export declare function PhoneInput({ value, defaultValue, onValueChange, onValueCommit, country, countries, showType, picker, label, locale: localeProp, name, placeholder, autoComplete, required, disabled, className, classes, }: PhoneInputProps): import("react").JSX.Element;
@@ -0,0 +1,210 @@
1
+ import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
2
+ /**
3
+ * A phone number input: the number, and a flag that is also a country picker.
4
+ *
5
+ * <PhoneInput label="Phone" country="FR" countries={['FR', 'BE', 'GB']} showType value={phone} onValueChange={setPhone} />
6
+ * <Field label="Phone" type="phone" countries={['FR', 'BE']} value={phone} onValueChange={setPhone} />
7
+ *
8
+ * - `value`, `defaultValue`: the number in E.164 ('+33612345678') once it's
9
+ * valid, else the text as typed, so a form can still reject it
10
+ * - `onValueChange`: called as it's typed; `onValueCommit`: when it's left or
11
+ * a country is picked (the number then shows formatted)
12
+ * - `country`: the country of numbers typed without a "+" (default: the
13
+ * locale's region, e.g. FR for 'fr-FR')
14
+ * - `countries`: countries listed first in the picker, e.g. ['FR', 'BE', 'GB']
15
+ * - `showType`: a mobile or landline icon after a valid number (its word as a
16
+ * tooltip and label)
17
+ * - `picker`: 'search' (a list searched by name, code or dialling code) or
18
+ * 'native' (the browser's own select); by default native on touch screens
19
+ * - `label`: a label above it (skipped inside a Field); `locale`: for the
20
+ * countries' names (the LocaleProvider's by default)
21
+ * - `name`, `placeholder`, `autoComplete` ('tel'), `required`, `disabled`: as
22
+ * on an input
23
+ *
24
+ * It shows a number in national format when it's in `country`, international
25
+ * otherwise. The flag follows the number ("+44…" shows the UK's); picking one
26
+ * reads a number typed without "+" as that country's; Backspace in the empty
27
+ * input goes back to `country`. A number left invalid says why once the input
28
+ * loses focus (too short, too long, not a number), in its Field when it has
29
+ * one; an `error` given to the Field wins.
30
+ */
31
+ import { useEffect, useId, useMemo, useRef, useState } from 'react';
32
+ import { Field as ArkField, useFieldContext } from '@ark-ui/react/field';
33
+ import { Popover } from '@ark-ui/react/popover';
34
+ import { AsYouType, getCountries, getCountryCallingCode, parsePhoneNumberFromString, validatePhoneNumberLength, } from 'libphonenumber-js/max';
35
+ import '../icons.js';
36
+ import { cx, partsOf, useControllable } from '../utils.js';
37
+ import { useLocale, useMessages } from '../format/LocaleProvider.js';
38
+ import { useFieldReport } from '../field/report.js';
39
+ import '../theme.css';
40
+ import '../popover/popover.css';
41
+ import './phone-input.css';
42
+ const types = { MOBILE: 'mobile', FIXED_LINE: 'landline' };
43
+ const reasons = { TOO_SHORT: 'tooShort', TOO_LONG: 'tooLong' };
44
+ const flagOf = (country) => country ? String.fromCodePoint(...[...country].map((letter) => 127397 + letter.charCodeAt(0))) : '🌐';
45
+ const fold = (text) => text.normalize('NFD').replace(/[̀-ͯ]/g, '').toLowerCase();
46
+ function regionOf(locale) {
47
+ try {
48
+ return locale ? new Intl.Locale(locale).maximize().region ?? null : null;
49
+ }
50
+ catch {
51
+ return null;
52
+ }
53
+ }
54
+ const parse = (text, region) => parsePhoneNumberFromString(text, region);
55
+ const valid = (text, region) => {
56
+ const parsed = parse(text, region);
57
+ return parsed?.isValid() ? parsed : null;
58
+ };
59
+ // The number as shown: national in the home country, international elsewhere
60
+ function display(value, home) {
61
+ const parsed = valid(value ?? '', home);
62
+ if (!parsed)
63
+ return value ?? '';
64
+ return parsed.country === home ? parsed.formatNational() : parsed.formatInternational();
65
+ }
66
+ const touchScreen = () => typeof matchMedia !== 'undefined' && matchMedia('(pointer: coarse)').matches;
67
+ function useCountries(locale, countries) {
68
+ return useMemo(() => {
69
+ const names = new Intl.DisplayNames([locale], { type: 'region' });
70
+ const item = (code) => {
71
+ const name = names.of(code) ?? code;
72
+ return { code, name, dial: getCountryCallingCode(code), words: fold(name) };
73
+ };
74
+ const all = getCountries().map(item).sort((a, b) => a.name.localeCompare(b.name));
75
+ const known = new Set(getCountries());
76
+ const first = countries.map((code) => code.toUpperCase()).filter((code) => known.has(code)).map((code) => item(code));
77
+ return { first, all };
78
+ }, [locale, countries.join()]); // eslint-disable-line react-hooks/exhaustive-deps
79
+ }
80
+ // `countries` first. A search matches a name's words (accents ignored), the
81
+ // code, or the dialling code; names starting with it next.
82
+ function search({ first, all }, query) {
83
+ const text = fold(query.trim());
84
+ const place = (item) => first.findIndex((top) => top.code === item.code);
85
+ const rank = (item) => (place(item) >= 0 ? 0 : item.words.startsWith(text) ? 1 : 2);
86
+ const hits = all.filter((item) => {
87
+ if (!text)
88
+ return true;
89
+ if (/^\+?[\d\s]+$/.test(text))
90
+ return item.dial.startsWith(text.replace(/\D/g, ''));
91
+ return item.code.toLowerCase() === text || item.words.split(/[\s'’-]+/).some((word) => word.startsWith(text));
92
+ });
93
+ return hits.sort((a, b) => rank(a) - rank(b) || place(a) - place(b));
94
+ }
95
+ export function PhoneInput({ value, defaultValue, onValueChange, onValueCommit, country = null, countries = [], showType = false, picker = null, label = null, locale: localeProp, name, placeholder = '', autoComplete = 'tel', required = false, disabled = false, className, classes, }) {
96
+ const t = useMessages().phoneInput;
97
+ const field = useFieldContext();
98
+ const report = useFieldReport();
99
+ const part = partsOf('phone-input', classes);
100
+ const ambient = useLocale();
101
+ const locale = localeProp ?? ambient ?? 'en-GB';
102
+ const ownId = useId();
103
+ const listId = `${ownId}-countries`;
104
+ const input = useRef(null);
105
+ const home = ((country ?? regionOf(locale) ?? 'FR').toUpperCase());
106
+ const [current, setCurrent] = useControllable(value, defaultValue ?? null, undefined);
107
+ const [entry, setEntry] = useState(() => display(current, home));
108
+ // Numbers typed without "+" are read as this country's
109
+ const [picked, setPicked] = useState(null);
110
+ const [touched, setTouched] = useState(false);
111
+ const region = picked ?? home;
112
+ // A value changed from outside replaces what's shown
113
+ const [shown, setShown] = useState(current);
114
+ if (current !== shown) {
115
+ setShown(current);
116
+ setEntry(display(current, home));
117
+ setPicked(null);
118
+ setTouched(false);
119
+ }
120
+ const number = valid(entry, region);
121
+ const type = number ? types[number.getType() ?? ''] ?? null : null;
122
+ const flagCountry = number?.country ?? (entry.trim().startsWith('+')
123
+ ? (() => { const typing = new AsYouType(region); typing.input(entry); return typing.getCountry(); })()
124
+ : region);
125
+ // Why the number isn't valid, once the input has lost focus
126
+ const problem = touched && entry.trim() && !number ? t[reasons[validatePhoneNumberLength(entry, region) ?? ''] ?? 'invalid'] : null;
127
+ const invalid = !!(field?.invalid || problem);
128
+ const locked = disabled || !!field?.disabled;
129
+ useEffect(() => {
130
+ input.current?.setCustomValidity(problem ?? '');
131
+ report?.(problem);
132
+ }, [problem, report]);
133
+ useEffect(() => () => report?.(null), [report]);
134
+ function emit(text, from) {
135
+ const next = valid(text, from)?.number ?? text.trim();
136
+ setShown(next);
137
+ setCurrent(next);
138
+ onValueChange?.(next);
139
+ return next;
140
+ }
141
+ function settle(text, from, next) {
142
+ const parsed = valid(text, from);
143
+ if (parsed)
144
+ setEntry(display(parsed.number, home));
145
+ setTouched(true);
146
+ onValueCommit?.(next);
147
+ }
148
+ function typed(text) {
149
+ setEntry(text);
150
+ emit(text, region);
151
+ }
152
+ // Backspace with nothing left to delete drops a picked country
153
+ function erase(event) {
154
+ if (event.key === 'Backspace' && !entry && picked)
155
+ setPicked(null);
156
+ }
157
+ function choose(code) {
158
+ const parsed = parse(entry, region);
159
+ const text = parsed && entry.trim().startsWith('+') ? parsed.nationalNumber : entry;
160
+ setPicked(code);
161
+ setEntry(text);
162
+ const next = emit(text, code);
163
+ if (text.trim())
164
+ settle(text, code, next);
165
+ // After the popover has handed focus back to its trigger
166
+ setTimeout(() => input.current?.focus(), 0);
167
+ }
168
+ const searching = picker ? picker === 'search' : !touchScreen();
169
+ const list = useCountries(locale, countries);
170
+ return (_jsxs("div", { ...part('root'), className: cx(className, classes?.root), "data-invalid": invalid || undefined, "data-disabled": locked || undefined, children: [label && !field && _jsx("label", { ...part('label'), htmlFor: `${ownId}-input`, children: label }), _jsxs("div", { ...part('control'), children: [searching
171
+ ? _jsx(CountrySearch, { list: list, flagCountry: flagCountry, listId: listId, disabled: locked, part: part, onChoose: choose })
172
+ : (_jsxs("span", { ...part('country'), children: [_jsx("span", { ...part('flag'), "aria-hidden": "true", children: flagOf(flagCountry) }), _jsxs("select", { ...part('picker'), "aria-label": t.country, disabled: locked, value: flagCountry ?? '', onChange: (event) => choose(event.target.value), children: [_jsx("option", { value: "", disabled: true, hidden: true, children: "\uD83C\uDF10" }), list.first.map((item) => _jsxs("option", { value: item.code, children: [flagOf(item.code), " ", item.name, " +", item.dial] }, `first-${item.code}`)), list.first.length > 0 && _jsx("option", { disabled: true, children: "\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500" }), list.all.map((item) => _jsxs("option", { value: item.code, children: [flagOf(item.code), " ", item.name, " +", item.dial] }, item.code))] })] })), _jsx(ArkField.Input, { ref: input, ...part('input'), id: field ? undefined : `${ownId}-input`, type: "tel", name: name, placeholder: placeholder, autoComplete: autoComplete, required: required, disabled: locked, value: entry, "aria-invalid": invalid || undefined, onChange: (event) => typed(event.target.value), onKeyDown: erase, onBlur: () => settle(entry, region, current ?? '') }), showType && type && (_jsx("span", { ...part('type'), title: t[type], "aria-label": t[type], children: _jsx("iconify-icon", { icon: type === 'mobile' ? 'lucide:smartphone' : 'lucide:phone', "aria-hidden": "true" }) }))] })] }));
173
+ }
174
+ // The flag as a button opening a searchable list of countries
175
+ function CountrySearch({ list, flagCountry, listId, disabled, part, onChoose }) {
176
+ const t = useMessages().phoneInput;
177
+ const [open, setOpen] = useState(false);
178
+ const [query, setQuery] = useState('');
179
+ const [active, setActive] = useState(0);
180
+ const matches = useMemo(() => search(list, query), [list, query]);
181
+ const highlighted = matches[active];
182
+ // The highlighted country stays in view
183
+ useEffect(() => {
184
+ if (open)
185
+ document.getElementById(`${listId}-${highlighted?.code}`)?.scrollIntoView({ block: 'nearest' });
186
+ }, [open, highlighted, listId]);
187
+ function toggle(next) {
188
+ setOpen(next);
189
+ if (!next)
190
+ return;
191
+ setQuery('');
192
+ setActive(Math.max(0, search(list, '').findIndex((item) => item.code === flagCountry)));
193
+ }
194
+ function choose(code) {
195
+ setOpen(false);
196
+ onChoose(code);
197
+ }
198
+ function navigate(event) {
199
+ if (event.key === 'ArrowDown' || event.key === 'ArrowUp') {
200
+ event.preventDefault();
201
+ setActive((index) => Math.min(matches.length - 1, Math.max(0, index + (event.key === 'ArrowDown' ? 1 : -1))));
202
+ }
203
+ else if (event.key === 'Enter') {
204
+ event.preventDefault();
205
+ if (highlighted)
206
+ choose(highlighted.code);
207
+ }
208
+ }
209
+ return (_jsxs(Popover.Root, { open: open, onOpenChange: (details) => toggle(details.open), positioning: { placement: 'bottom-start', strategy: 'fixed' }, children: [_jsx(Popover.Trigger, { ...part('country'), type: "button", disabled: disabled, "aria-label": t.country, children: _jsx("span", { ...part('flag'), "aria-hidden": "true", children: flagOf(flagCountry) }) }), _jsx(Popover.Positioner, { "data-scope": "popover", "data-part": "positioner", children: _jsx(Popover.Content, { "data-scope": "popover", "data-part": "content", "data-flush": "", children: _jsxs("div", { ...part('countries'), children: [_jsx("input", { ...part('search'), type: "search", placeholder: t.search, "aria-label": t.search, autoComplete: "off", role: "combobox", "aria-expanded": "true", "aria-controls": listId, "aria-activedescendant": highlighted ? `${listId}-${highlighted.code}` : undefined, value: query, onChange: (event) => { setQuery(event.target.value); setActive(0); }, onKeyDown: navigate }), _jsxs("div", { ...part('list'), id: listId, role: "listbox", "aria-label": t.country, children: [matches.map((item, index) => (_jsxs("div", { ...part('option'), id: `${listId}-${item.code}`, role: "option", "aria-selected": item.code === flagCountry, "data-highlighted": index === active || undefined, onPointerDown: (event) => event.preventDefault(), onClick: () => choose(item.code), onPointerMove: () => index !== active && setActive(index), children: [_jsx("span", { ...part('flag'), "aria-hidden": "true", children: flagOf(item.code) }), _jsx("span", { "data-scope": "phone-input", "data-part": "name", children: item.name }), _jsxs("span", { "data-scope": "phone-input", "data-part": "dial", children: ["+", item.dial] })] }, item.code))), !matches.length && _jsx("div", { ...part('empty'), children: t.noMatch })] })] }) }) })] }));
210
+ }
@@ -0,0 +1,44 @@
1
+ @layer ui {
2
+ [data-scope=phone-input][data-part=root] { display: block; min-width: 0; color: var(--ui-text); font-family: var(--ui-font); }
3
+ [data-scope=phone-input][data-part=label] { display: block; font-size: 14px; font-weight: 500; margin-bottom: 0.375rem; }
4
+ [data-scope=phone-input][data-part=control] {
5
+ display: flex; align-items: center; gap: 0.25rem; min-width: 0; box-sizing: border-box;
6
+ height: var(--ui-control-height); padding: 0 0.5rem 0 0.25rem;
7
+ background: var(--ui-field-bg); border: 1px solid var(--ui-field-border); border-radius: var(--ui-radius); font-size: 14px;
8
+ &:hover { border-color: var(--ui-field-border-hover); }
9
+ &:focus-within { border-color: var(--ui-ring); outline: 2px solid var(--ui-ring-soft); }
10
+ &:has(input:autofill) { background: var(--ui-field-autofill-bg); }
11
+ [data-invalid] > & { border-color: var(--ui-danger); }
12
+ [data-disabled] > & { opacity: 0.5; }
13
+ }
14
+ /* The flag: a button opening the search, or a native select laid over it */
15
+ [data-scope=phone-input][data-part=country] { position: relative; display: flex; align-items: center; justify-content: center; flex-shrink: 0;
16
+ height: 1.75rem; padding: 0 0.375rem; margin: 0; border: none; background: transparent; border-radius: 4px; color: inherit; cursor: pointer;
17
+ &:hover { background: var(--ui-hover); }
18
+ &:focus-visible, &:focus-within { outline: 2px solid var(--ui-ring-soft); } }
19
+ [data-scope=phone-input][data-part=flag] { font-size: 16px; line-height: 1; }
20
+ [data-scope=phone-input][data-part=picker] { position: absolute; inset: 0; width: 100%; height: 100%; margin: 0; opacity: 0; cursor: pointer; font-size: 16px; }
21
+ [data-scope=phone-input][data-part=input] { flex: 1; min-width: 0; padding: 0; border: none; background: transparent; outline: none;
22
+ color: inherit; font: inherit;
23
+ &::placeholder { color: var(--ui-muted); }
24
+ &:autofill { transition-property: background-color, color; transition-delay: 600000s; -webkit-text-fill-color: var(--ui-text); caret-color: var(--ui-text); } }
25
+ [data-scope=phone-input][data-part=type] { display: flex; align-items: center; flex-shrink: 0; color: var(--ui-muted);
26
+ iconify-icon { display: block; width: 1em; height: 1em; font-size: 16px; } }
27
+
28
+ /* The list of countries, in a popover without its padding */
29
+ [data-scope=popover][data-part=content][data-flush] { padding: 0; }
30
+ [data-scope=phone-input][data-part=countries] { display: flex; flex-direction: column; }
31
+ [data-scope=phone-input][data-part=search] { margin: 0.5rem 0.5rem 0.25rem; padding: 0 0.625rem; height: 2rem; box-sizing: border-box;
32
+ background: var(--ui-field-bg); border: 1px solid var(--ui-field-border); border-radius: var(--ui-radius);
33
+ color: inherit; font: inherit; font-size: 14px; outline: none;
34
+ &:focus { border-color: var(--ui-ring); outline: 2px solid var(--ui-ring-soft); }
35
+ &::placeholder { color: var(--ui-muted); } }
36
+ [data-scope=phone-input][data-part=list] { max-height: 16rem; overflow-y: auto; padding: 0 0.25rem 0.25rem; }
37
+ [data-scope=phone-input][data-part=option] { display: flex; align-items: center; gap: 0.5rem; padding: 0.375rem 0.5rem; border-radius: 4px;
38
+ font-size: 14px; cursor: pointer;
39
+ &[data-highlighted] { background: var(--ui-hover); }
40
+ &[aria-selected=true] { font-weight: 500; } }
41
+ [data-scope=phone-input][data-part=name] { flex: 1; min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
42
+ [data-scope=phone-input][data-part=dial] { flex-shrink: 0; color: var(--ui-muted); font-size: 12px; }
43
+ [data-scope=phone-input][data-part=empty] { padding: 0.75rem 0.5rem; color: var(--ui-muted); font-size: 14px; text-align: center; }
44
+ }
@@ -14,6 +14,9 @@
14
14
  * - `size`: 'sm', 'md' (default) or 'lg': the width (or height for top and bottom)
15
15
  * - `open`, `defaultOpen`, `onOpenChange`, `trigger`, `heading`, `description`,
16
16
  * `footer`, `closable`, `alert`: as for Dialog
17
+ * - `modal`: false keeps the page usable beside it (no backdrop, no focus
18
+ * trap, the page still scrolls, a click outside doesn't close it), for
19
+ * looking something up while working on the page
17
20
  *
18
21
  * Or composed from Sheet.Header (heading, description), Sheet.Body and
19
22
  * Sheet.Footer, with a Sheet.Trigger child, as Dialog is. By hand, Dialog's
@@ -35,6 +38,7 @@ export type SheetProps = Omit<Ark.ContentProps, 'children'> & {
35
38
  heading?: ReactNode;
36
39
  description?: ReactNode;
37
40
  alert?: boolean;
41
+ modal?: boolean;
38
42
  closable?: boolean;
39
43
  trigger?: ReactElement | null;
40
44
  footer?: ReactNode;
@@ -46,7 +50,7 @@ type HeaderProps = ComponentProps<'div'> & {
46
50
  description?: ReactNode;
47
51
  };
48
52
  declare function Header({ heading, description, children, ...rest }: HeaderProps): import("react").JSX.Element;
49
- declare function SheetShortcut({ open, defaultOpen, onOpenChange, side, size, heading, description, alert, closable, trigger, footer, className, classes, children, ...rest }: SheetProps): import("react").JSX.Element;
53
+ declare function SheetShortcut({ open, defaultOpen, onOpenChange, side, size, heading, description, alert, modal, closable, trigger, footer, className, classes, children, ...rest }: SheetProps): import("react").JSX.Element;
50
54
  export declare const Sheet: typeof SheetShortcut & {
51
55
  Header: typeof Header;
52
56
  Body: {
@@ -15,6 +15,9 @@ import { jsx as _jsx, jsxs as _jsxs, Fragment as _Fragment } from "react/jsx-run
15
15
  * - `size`: 'sm', 'md' (default) or 'lg': the width (or height for top and bottom)
16
16
  * - `open`, `defaultOpen`, `onOpenChange`, `trigger`, `heading`, `description`,
17
17
  * `footer`, `closable`, `alert`: as for Dialog
18
+ * - `modal`: false keeps the page usable beside it (no backdrop, no focus
19
+ * trap, the page still scrolls, a click outside doesn't close it), for
20
+ * looking something up while working on the page
18
21
  *
19
22
  * Or composed from Sheet.Header (heading, description), Sheet.Body and
20
23
  * Sheet.Footer, with a Sheet.Trigger child, as Dialog is. By hand, Dialog's
@@ -43,14 +46,14 @@ const withScope = (Part, name) => {
43
46
  Scoped.displayName = `Sheet.${name}`;
44
47
  return Scoped;
45
48
  };
46
- function SheetShortcut({ open, defaultOpen, onOpenChange, side = 'right', size = 'md', heading = null, description = null, alert = false, closable = true, trigger = null, footer = null, className, classes, children, ...rest }) {
49
+ function SheetShortcut({ open, defaultOpen, onOpenChange, side = 'right', size = 'md', heading = null, description = null, alert = false, modal = true, closable = true, trigger = null, footer = null, className, classes, children, ...rest }) {
47
50
  const t = useMessages();
48
51
  const part = partsOf('sheet', classes);
49
52
  const nodes = Children.toArray(children);
50
53
  const composed = nodes.some((node) => isValidElement(node) && layout.includes(node.type));
51
54
  const triggers = nodes.filter((node) => isValidElement(node) && node.type === Ark.Trigger);
52
55
  const content = composed ? nodes.filter((node) => !triggers.includes(node)) : children;
53
- return (_jsxs(Ark.Root, { ...(open !== undefined && { open }), ...(defaultOpen !== undefined && { defaultOpen }), ...on('onOpenChange', onOpenChange, (details) => details.open), role: alert ? 'alertdialog' : 'dialog', closeOnInteractOutside: !alert, lazyMount: true, unmountOnExit: true, children: [trigger && _jsx(Ark.Trigger, { asChild: true, children: trigger }), composed && triggers, _jsxs(Portal, { children: [_jsx(Ark.Backdrop, { ...part('backdrop') }), _jsx(Ark.Positioner, { ...part('positioner'), "data-side": side, children: _jsxs(Ark.Content, { ...rest, ...part('content'), className: cx(className, classes?.content), "data-side": side, "data-size": size, children: [closable && _jsx(Ark.CloseTrigger, { ...part('close-trigger'), "aria-label": t.common.close, children: _jsx("iconify-icon", { icon: "lucide:x" }) }), composed ? content : _jsxs(_Fragment, { children: [(heading || description) && (_jsxs("div", { ...part('header'), children: [heading && _jsx(Ark.Title, { ...part('title'), children: heading }), description && _jsx(Ark.Description, { ...part('description'), children: description })] })), _jsx("div", { ...part('body'), children: children }), footer && _jsx("div", { ...part('footer'), children: footer })] })] }) })] })] }));
56
+ return (_jsxs(Ark.Root, { ...(open !== undefined && { open }), ...(defaultOpen !== undefined && { defaultOpen }), ...on('onOpenChange', onOpenChange, (details) => details.open), role: alert ? 'alertdialog' : 'dialog', modal: modal, trapFocus: modal, preventScroll: modal, closeOnInteractOutside: modal && !alert, lazyMount: true, unmountOnExit: true, children: [trigger && _jsx(Ark.Trigger, { asChild: true, children: trigger }), composed && triggers, _jsxs(Portal, { children: [modal && _jsx(Ark.Backdrop, { ...part('backdrop') }), _jsx(Ark.Positioner, { ...part('positioner'), "data-side": side, children: _jsxs(Ark.Content, { ...rest, ...part('content'), className: cx(className, classes?.content), "data-side": side, "data-size": size, children: [closable && _jsx(Ark.CloseTrigger, { ...part('close-trigger'), "aria-label": t.common.close, children: _jsx("iconify-icon", { icon: "lucide:x" }) }), composed ? content : _jsxs(_Fragment, { children: [(heading || description) && (_jsxs("div", { ...part('header'), children: [heading && _jsx(Ark.Title, { ...part('title'), children: heading }), description && _jsx(Ark.Description, { ...part('description'), children: description })] })), _jsx("div", { ...part('body'), children: children }), footer && _jsx("div", { ...part('footer'), children: footer })] })] }) })] })] }));
54
57
  }
55
58
  export const Sheet = withParts(SheetShortcut, {
56
59
  Header, Body, Footer,
@@ -14,6 +14,8 @@
14
14
  * - `variant`: 'line' (default, an underline) or 'pills'
15
15
  * - `counts`: where the tabs' counts sit: 'inline' (default, after the label)
16
16
  * or 'corner' (top right, like a button's)
17
+ * - `iconOnly`: tabs with an icon show just the icon, their label in a
18
+ * tooltip (and still read out); tabs without one keep their label
17
19
  * - `renderTrigger`: a tab's content, given the tab's props; its count still follows
18
20
  *
19
21
  * By hand, with Ark's parts (data-variant on the root picks the look):
@@ -68,10 +70,11 @@ export type TabsProps = Omit<Ark.RootProps, 'value' | 'defaultValue' | 'onValueC
68
70
  onValueChange?: (value: Value | null, details: TabsValueChangeDetails) => void;
69
71
  variant?: 'line' | 'pills';
70
72
  counts?: 'inline' | 'corner';
73
+ iconOnly?: boolean;
71
74
  renderTrigger?: (tab: TabProps) => ReactNode;
72
- classes?: Classes<'root' | 'list' | 'trigger' | 'icon' | 'count' | 'indicator' | 'panels' | 'content'>;
75
+ classes?: Classes<'root' | 'list' | 'trigger' | 'tipTarget' | 'icon' | 'count' | 'indicator' | 'panels' | 'content'>;
73
76
  };
74
- declare function TabsShortcut({ value, defaultValue, onValueChange, variant, counts, renderTrigger, className, classes, children, ...rest }: TabsProps): import("react").JSX.Element;
77
+ declare function TabsShortcut({ value, defaultValue, onValueChange, variant, counts, iconOnly, renderTrigger, className, classes, children, ...rest }: TabsProps): import("react").JSX.Element;
75
78
  export declare const Tabs: typeof TabsShortcut & {
76
79
  Tab: typeof Tab;
77
80
  Root: import("react").ForwardRefExoticComponent<Ark.RootProps & import("react").RefAttributes<HTMLDivElement>>;
package/dist/tabs/Tabs.js CHANGED
@@ -15,6 +15,8 @@ import { jsx as _jsx, Fragment as _Fragment, jsxs as _jsxs } from "react/jsx-run
15
15
  * - `variant`: 'line' (default, an underline) or 'pills'
16
16
  * - `counts`: where the tabs' counts sit: 'inline' (default, after the label)
17
17
  * or 'corner' (top right, like a button's)
18
+ * - `iconOnly`: tabs with an icon show just the icon, their label in a
19
+ * tooltip (and still read out); tabs without one keep their label
18
20
  * - `renderTrigger`: a tab's content, given the tab's props; its count still follows
19
21
  *
20
22
  * By hand, with Ark's parts (data-variant on the root picks the look):
@@ -32,6 +34,7 @@ import { jsx as _jsx, Fragment as _Fragment, jsxs as _jsxs } from "react/jsx-run
32
34
  import { Children, isValidElement, useEffect } from 'react';
33
35
  import { Tabs as Ark } from '@ark-ui/react/tabs';
34
36
  import '../icons.js';
37
+ import { Tooltip } from '../tooltip/Tooltip.js';
35
38
  import { cx, partOf, partsOf, useControllable, withParts } from '../utils.js';
36
39
  import '../theme.css';
37
40
  import './tabs.css';
@@ -52,7 +55,7 @@ import './tabs.css';
52
55
  export function Tab({ value, label: _label, icon: _icon, disabled: _disabled, count: _count, max: _max, dot: _dot, pulse: _pulse, countColor: _countColor, countLabel: _countLabel, className, ...rest }) {
53
56
  return _jsx(Ark.Content, { ...rest, value: String(value), "data-scope": "tabs", "data-part": "content", className: className });
54
57
  }
55
- function TabsShortcut({ value, defaultValue, onValueChange, variant = 'line', counts = 'inline', renderTrigger, className, classes, children, ...rest }) {
58
+ function TabsShortcut({ value, defaultValue, onValueChange, variant = 'line', counts = 'inline', iconOnly = false, renderTrigger, className, classes, children, ...rest }) {
56
59
  const part = partsOf('tabs', classes);
57
60
  const tabs = Children.toArray(children).filter((child) => isValidElement(child) && child.type === Tab);
58
61
  // With no value, the first enabled tab.
@@ -76,7 +79,8 @@ function TabsShortcut({ value, defaultValue, onValueChange, variant = 'line', co
76
79
  const { count, max = 99, dot, pulse, countColor = 'neutral', countLabel = '' } = tab;
77
80
  const badge = count && count > 0 ? (count > max ? `${max}+` : String(count)) : dot ? '' : null;
78
81
  const spoken = count && count > 0 ? [count, countLabel].filter(Boolean).join(' ') : dot ? countLabel : '';
79
- return (_jsxs(Ark.Trigger, { value: String(tab.value), disabled: !!tab.disabled, ...part('trigger'), children: [renderTrigger ? renderTrigger(tab) : _jsxs(_Fragment, { children: [tab.icon && _jsx("iconify-icon", { ...part('icon'), icon: tab.icon, "aria-hidden": "true" }), _jsx("span", { children: tab.label })] }), badge != null && _jsxs(_Fragment, { children: [_jsx("span", { ...part('count'), "aria-hidden": "true", "data-dot": badge === '' || undefined, "data-pulse": pulse || undefined, "data-color": countColor, children: badge }), spoken && _jsxs("span", { ...part('sr-only'), children: [", ", spoken] })] })] }, String(tab.value)));
82
+ const bare = iconOnly && !!tab.icon;
83
+ return (_jsxs(Ark.Trigger, { value: String(tab.value), disabled: !!tab.disabled, ...part('trigger'), "data-icon-only": bare || undefined, children: [renderTrigger ? renderTrigger(tab) : bare ? _jsxs(_Fragment, { children: [_jsx(Tooltip, { content: tab.label, placement: "bottom", children: _jsx("span", { ...part('tip-target'), children: _jsx("iconify-icon", { ...part('icon'), icon: tab.icon, "aria-hidden": "true" }) }) }), _jsx("span", { ...part('sr-only'), children: tab.label })] }) : _jsxs(_Fragment, { children: [tab.icon && _jsx("iconify-icon", { ...part('icon'), icon: tab.icon, "aria-hidden": "true" }), _jsx("span", { children: tab.label })] }), badge != null && _jsxs(_Fragment, { children: [_jsx("span", { ...part('count'), "aria-hidden": "true", "data-dot": badge === '' || undefined, "data-pulse": pulse || undefined, "data-color": countColor, children: badge }), spoken && _jsxs("span", { ...part('sr-only'), children: [", ", spoken] })] })] }, String(tab.value)));
80
84
  }), _jsx(Ark.Indicator, { ...part('indicator') })] }), _jsx("div", { ...part('panels'), children: children })] }));
81
85
  }
82
86
  export const Tabs = withParts(TabsShortcut, {
@@ -40,6 +40,11 @@
40
40
  /* A tab with a corner count makes room for it on the right. */
41
41
  [data-counts=corner] [data-scope=tabs][data-part=trigger]:has(> [data-part=count]) { padding-right: 1.375rem;
42
42
  &:has(> [data-dot]) { padding-right: 1.125rem; } }
43
+ /* Icon only: the tooltip's target fills the tab, so its whole width shows the label on hover. */
44
+ [data-scope=tabs][data-part=trigger][data-icon-only] { padding: 0;
45
+ [data-counts=corner] &:has(> [data-part=count]) { padding-right: 0; }
46
+ [data-counts=inline] & > [data-part=count] { margin: 0 0.75rem 0 -0.375rem; } }
47
+ [data-scope=tabs][data-part=tip-target] { display: grid; place-items: center; align-self: stretch; padding: 0 0.75rem; }
43
48
  [data-scope=tabs][data-part=sr-only] { position: absolute; width: 1px; height: 1px; overflow: hidden; clip: rect(0 0 0 0); white-space: nowrap; }
44
49
  @keyframes ui-ping { from { scale: 1; opacity: 0.7; } 75%, to { scale: 2.2; opacity: 0; } }
45
50
  @media (prefers-reduced-motion: reduce) { [data-scope=tabs][data-part=count]::after { animation: none; } }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@milktop/react-ui",
3
- "version": "0.3.4",
3
+ "version": "0.3.6",
4
4
  "description": "React components on Ark UI (Zag state machines), with imba-ui's API and design",
5
5
  "license": "MIT",
6
6
  "author": "André Goldstein",
@@ -79,7 +79,8 @@
79
79
  "@zag-js/file-utils": "^1.45.0",
80
80
  "d3-scale": "^4.0.2",
81
81
  "d3-shape": "^3.2.0",
82
- "iconify-icon": "^3.0.3"
82
+ "iconify-icon": "^3.0.3",
83
+ "libphonenumber-js": "^1.13.15"
83
84
  },
84
85
  "devDependencies": {
85
86
  "@fontsource-variable/dm-sans": "^5.3.0",