@milktop/react-ui 0.3.5 → 0.3.7

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.
@@ -1,9 +1,16 @@
1
1
  /**
2
- * A button. Other attributes (onClick, aria-label, form…) go on the <button>.
2
+ * A button, or a link that looks like one. Other attributes (onClick,
3
+ * aria-label, form…) go on the <button> or link.
3
4
  *
4
5
  * <Button variant="primary" icon="lucide:save" loading={saving}>Save</Button>
6
+ * <Button href="/students">Students</Button>
7
+ * <Button variant="link" link={<Link to="/students" />}>Students</Button>
5
8
  *
6
9
  * - `variant`: 'default', 'primary', 'danger', 'soft', 'ghost' or 'link'
10
+ * - `href`: where it goes, as an <a>; a disabled or loading one stays a <button>,
11
+ * as a link can't be disabled
12
+ * - `link`: your router's link element in place of the <a> (`<Link to="…" />`);
13
+ * it gets the button's props and content
7
14
  * - `size`: 'sm', 'md' (matching the inputs' height) or 'lg'
8
15
  * - `icon`, `iconEnd`: Iconify names; with no text it is an icon button, so give it an aria-label
9
16
  * - `loading`: a spinner in place of the icon; also disables it
@@ -17,7 +24,7 @@
17
24
  * - `countLabel`: what the count is, for assistive tech ('new': "Inbox, 3 new")
18
25
  * - `type`: 'button' by default (pass 'submit' for forms)
19
26
  */
20
- import type { ComponentProps } from 'react';
27
+ import { type ComponentProps, type ReactElement } from 'react';
21
28
  import '../icons.js';
22
29
  import { type Classes } from '../utils.js';
23
30
  import '../theme.css';
@@ -25,6 +32,8 @@ import './button.css';
25
32
  export type ButtonProps = ComponentProps<'button'> & {
26
33
  variant?: 'default' | 'primary' | 'danger' | 'soft' | 'ghost' | 'link';
27
34
  size?: 'sm' | 'md' | 'lg';
35
+ href?: string | null;
36
+ link?: ReactElement | null;
28
37
  icon?: string | null;
29
38
  iconEnd?: string | null;
30
39
  loading?: boolean;
@@ -38,4 +47,4 @@ export type ButtonProps = ComponentProps<'button'> & {
38
47
  countLabel?: string;
39
48
  classes?: Classes<'root' | 'spinner' | 'icon' | 'badge' | 'spoken'>;
40
49
  };
41
- export declare function Button({ variant, size, icon, iconEnd, loading, round, block, count, max, dot, pulse, countColor, countLabel: countLabelProp, type, disabled, className, classes, children, ...rest }: ButtonProps): import("react").JSX.Element;
50
+ export declare function Button({ variant, size, href, link, icon, iconEnd, loading, round, block, count, max, dot, pulse, countColor, countLabel: countLabelProp, type, disabled, className, classes, children, ...rest }: ButtonProps): import("react").JSX.Element;
@@ -1,10 +1,37 @@
1
1
  import { jsx as _jsx, jsxs as _jsxs, Fragment as _Fragment } from "react/jsx-runtime";
2
+ /**
3
+ * A button, or a link that looks like one. Other attributes (onClick,
4
+ * aria-label, form…) go on the <button> or link.
5
+ *
6
+ * <Button variant="primary" icon="lucide:save" loading={saving}>Save</Button>
7
+ * <Button href="/students">Students</Button>
8
+ * <Button variant="link" link={<Link to="/students" />}>Students</Button>
9
+ *
10
+ * - `variant`: 'default', 'primary', 'danger', 'soft', 'ghost' or 'link'
11
+ * - `href`: where it goes, as an <a>; a disabled or loading one stays a <button>,
12
+ * as a link can't be disabled
13
+ * - `link`: your router's link element in place of the <a> (`<Link to="…" />`);
14
+ * it gets the button's props and content
15
+ * - `size`: 'sm', 'md' (matching the inputs' height) or 'lg'
16
+ * - `icon`, `iconEnd`: Iconify names; with no text it is an icon button, so give it an aria-label
17
+ * - `loading`: a spinner in place of the icon; also disables it
18
+ * - `round`: a circle for icon buttons, a pill with text
19
+ * - `block`: full width
20
+ * - `count`: a badge on the corner (hidden at 0 or null), "99+" past `max`
21
+ * - `dot`: a small dot there instead, for "something new"
22
+ * - `pulse`: a ring ripples out from the badge or dot (not when the system asks for less motion)
23
+ * - `countColor`: 'danger', 'accent', 'success', 'warning' or 'neutral', for the
24
+ * dot too; or set `--ui-button-count-bg` and `--ui-button-count-text` in CSS for any other
25
+ * - `countLabel`: what the count is, for assistive tech ('new': "Inbox, 3 new")
26
+ * - `type`: 'button' by default (pass 'submit' for forms)
27
+ */
28
+ import { cloneElement } from 'react';
2
29
  import '../icons.js';
3
30
  import { cx, partsOf } from '../utils.js';
4
31
  import { useMessages } from '../format/LocaleProvider.js';
5
32
  import '../theme.css';
6
33
  import './button.css';
7
- export function Button({ variant = 'default', size = 'md', icon = null, iconEnd = null, loading = false, round = false, block = false, count = null, max = 99, dot = false, pulse = false, countColor = 'danger', countLabel: countLabelProp, type = 'button', disabled = false, className, classes, children, ...rest }) {
34
+ export function Button({ variant = 'default', size = 'md', href = null, link = null, icon = null, iconEnd = null, loading = false, round = false, block = false, count = null, max = 99, dot = false, pulse = false, countColor = 'danger', countLabel: countLabelProp, type = 'button', disabled = false, className, classes, children, ...rest }) {
8
35
  const t = useMessages();
9
36
  const countLabel = countLabelProp ?? t.button.countLabel;
10
37
  const part = partsOf('button', classes);
@@ -13,7 +40,20 @@ export function Button({ variant = 'default', size = 'md', icon = null, iconEnd
13
40
  const spoken = count && count > 0 ? `${count} ${countLabel}` : dot ? countLabel : '';
14
41
  // An aria-label hides the button's text from assistive tech, so the count joins the label.
15
42
  const label = rest['aria-label'] && spoken ? `${rest['aria-label']}, ${spoken}` : rest['aria-label'];
16
- return (_jsxs("button", { ...rest, ...part('root'), className: cx(className, classes?.root), type: type, disabled: disabled || loading, "aria-label": label, "aria-busy": loading || undefined, "data-variant": variant, "data-size": size, "data-round": round || undefined, "data-block": block || undefined, "data-loading": loading || undefined, "data-icon-only": (children == null && !(icon && iconEnd)) || undefined, children: [loading
43
+ const props = {
44
+ ...rest, ...part('root'), className: cx(className, classes?.root),
45
+ 'aria-label': label, 'aria-busy': loading || undefined,
46
+ 'data-variant': variant, 'data-size': size, 'data-round': round || undefined, 'data-block': block || undefined,
47
+ 'data-loading': loading || undefined, 'data-icon-only': (children == null && !(icon && iconEnd)) || undefined,
48
+ };
49
+ const content = _jsxs(_Fragment, { children: [loading
17
50
  ? _jsx("span", { ...part('spinner'), "aria-hidden": "true" })
18
- : icon && _jsx("iconify-icon", { ...part('icon'), icon: icon, "aria-hidden": "true" }), children, iconEnd && _jsx("iconify-icon", { ...part('icon'), icon: iconEnd, "aria-hidden": "true" }), badge != null && _jsxs(_Fragment, { children: [_jsx("span", { ...part('badge'), "aria-hidden": "true", "data-dot": badge === '' || undefined, "data-pulse": pulse || undefined, "data-color": countColor, children: badge }), !rest['aria-label'] && _jsxs("span", { ...part('spoken'), children: [", ", spoken] })] })] }));
51
+ : icon && _jsx("iconify-icon", { ...part('icon'), icon: icon, "aria-hidden": "true" }), children, iconEnd && _jsx("iconify-icon", { ...part('icon'), icon: iconEnd, "aria-hidden": "true" }), badge != null && _jsxs(_Fragment, { children: [_jsx("span", { ...part('badge'), "aria-hidden": "true", "data-dot": badge === '' || undefined, "data-pulse": pulse || undefined, "data-color": countColor, children: badge }), !rest['aria-label'] && _jsxs("span", { ...part('spoken'), children: [", ", spoken] })] })] });
52
+ if (!disabled && !loading) {
53
+ if (link)
54
+ return cloneElement(link, props, content);
55
+ if (href)
56
+ return _jsx("a", { ...props, href: href, children: content });
57
+ }
58
+ return _jsx("button", { ...props, type: type, disabled: disabled || loading, children: content });
19
59
  }
@@ -21,8 +21,9 @@
21
21
  &:hover { filter: brightness(0.97); } }
22
22
  &[data-variant=ghost] { background: transparent; border-color: transparent;
23
23
  &:hover { background: var(--ui-hover); } }
24
- /* Looks like a link, behaves as a button. */
24
+ /* Reads as part of the text around it, so it wraps and takes that text's type. */
25
25
  &[data-variant=link] { height: auto; padding: 0; background: transparent; border-color: transparent; color: var(--ui-accent);
26
+ font-size: inherit; font-weight: inherit; line-height: inherit; white-space: normal; text-align: start;
26
27
  &:hover { background: transparent; text-decoration: underline; }
27
28
  &:active { translate: none; } }
28
29
 
@@ -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
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@milktop/react-ui",
3
- "version": "0.3.5",
3
+ "version": "0.3.7",
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",