menhir 0.1.12 → 0.1.14

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 (50) hide show
  1. package/README.md +1 -1
  2. package/dist/number-field/decrement/NumberFieldDecrement.js +11 -0
  3. package/dist/number-field/increment/NumberFieldIncrement.js +11 -0
  4. package/dist/number-field/index.js +2 -0
  5. package/dist/number-field/index.parts.js +5 -0
  6. package/dist/number-field/input/NumberFieldInput.js +87 -0
  7. package/dist/number-field/parse.js +28 -0
  8. package/dist/number-field/root/NumberFieldRoot.js +169 -0
  9. package/dist/number-field/root/NumberFieldRootContext.js +10 -0
  10. package/dist/number-field/stepButton.js +60 -0
  11. package/dist/slider/index.js +2 -0
  12. package/dist/slider/index.parts.js +5 -0
  13. package/dist/slider/root/SliderRoot.js +123 -0
  14. package/dist/slider/root/SliderRootContext.js +10 -0
  15. package/dist/slider/thumb/SliderThumb.js +119 -0
  16. package/dist/slider/track/SliderTrack.js +65 -0
  17. package/dist/slider/value/SliderValue.js +24 -0
  18. package/dist/source/number-field/decrement/NumberFieldDecrement.d.ts +8 -0
  19. package/dist/source/number-field/decrement/NumberFieldDecrement.jsx +9 -0
  20. package/dist/source/number-field/increment/NumberFieldIncrement.d.ts +8 -0
  21. package/dist/source/number-field/increment/NumberFieldIncrement.jsx +9 -0
  22. package/dist/source/number-field/index.d.ts +1 -0
  23. package/dist/source/number-field/index.js +1 -0
  24. package/dist/source/number-field/index.parts.d.ts +4 -0
  25. package/dist/source/number-field/index.parts.js +4 -0
  26. package/dist/source/number-field/input/NumberFieldInput.d.ts +14 -0
  27. package/dist/source/number-field/input/NumberFieldInput.jsx +103 -0
  28. package/dist/source/number-field/parse.d.ts +11 -0
  29. package/dist/source/number-field/parse.js +46 -0
  30. package/dist/source/number-field/root/NumberFieldRoot.d.ts +49 -0
  31. package/dist/source/number-field/root/NumberFieldRoot.jsx +175 -0
  32. package/dist/source/number-field/root/NumberFieldRootContext.d.ts +35 -0
  33. package/dist/source/number-field/root/NumberFieldRootContext.js +13 -0
  34. package/dist/source/number-field/stepButton.d.ts +12 -0
  35. package/dist/source/number-field/stepButton.jsx +69 -0
  36. package/dist/source/slider/index.d.ts +1 -0
  37. package/dist/source/slider/index.js +1 -0
  38. package/dist/source/slider/index.parts.d.ts +4 -0
  39. package/dist/source/slider/index.parts.js +4 -0
  40. package/dist/source/slider/root/SliderRoot.d.ts +55 -0
  41. package/dist/source/slider/root/SliderRoot.jsx +152 -0
  42. package/dist/source/slider/root/SliderRootContext.d.ts +51 -0
  43. package/dist/source/slider/root/SliderRootContext.js +13 -0
  44. package/dist/source/slider/thumb/SliderThumb.d.ts +13 -0
  45. package/dist/source/slider/thumb/SliderThumb.jsx +91 -0
  46. package/dist/source/slider/track/SliderTrack.d.ts +11 -0
  47. package/dist/source/slider/track/SliderTrack.jsx +79 -0
  48. package/dist/source/slider/value/SliderValue.d.ts +11 -0
  49. package/dist/source/slider/value/SliderValue.jsx +18 -0
  50. package/package.json +11 -1
@@ -0,0 +1,65 @@
1
+ import { mergeElementProps } from "../../core/mergeElementProps.js";
2
+ import { renderElement } from "../../core/renderElement.js";
3
+ import { useSliderRootContext } from "../root/SliderRootContext.js";
4
+ import { spread, template } from "@solidjs/web";
5
+ import { merge, omit } from "solid-js";
6
+ // src/slider/track/SliderTrack.tsx
7
+ var _tmpl$ = /* @__PURE__ */ template(`<div>`);
8
+ /**
9
+ * The track: a `<div>`, the area where a press moves the thumb and a drag
10
+ * follows the pointer. Place the Thumb inside it, inside `Slider.Root`.
11
+ */
12
+ function SliderTrack(props) {
13
+ const root = useSliderRootContext();
14
+ let track;
15
+ let pointer;
16
+ let offset = 0;
17
+ const along = (x, y) => {
18
+ const rect = track.getBoundingClientRect();
19
+ return root.props.orientation === "vertical" ? rect.bottom - y : getComputedStyle(track).direction === "rtl" ? rect.right - x : x - rect.left;
20
+ };
21
+ const move = (event) => {
22
+ const rect = track.getBoundingClientRect();
23
+ const length = root.props.orientation === "vertical" ? rect.height : rect.width;
24
+ root.change(root.min() + (along(event.clientX, event.clientY) - offset) / length * (root.max() - root.min()));
25
+ };
26
+ const end = (event) => {
27
+ if (event.pointerId !== pointer) return;
28
+ pointer = void 0;
29
+ root.end();
30
+ };
31
+ const ownProps = merge(root.attributes, {
32
+ style: { "touch-action": "none" },
33
+ onPointerDown: (event) => {
34
+ if (event.button !== 0 || pointer !== void 0 || root.props.disabled) return;
35
+ event.preventDefault();
36
+ root.input?.focus({ focusVisible: false });
37
+ pointer = event.pointerId;
38
+ track.setPointerCapture(pointer);
39
+ const thumb = root.thumb;
40
+ offset = 0;
41
+ if (thumb?.contains(event.target)) {
42
+ const { left, top, width, height } = thumb.getBoundingClientRect();
43
+ offset = along(event.clientX, event.clientY) - along(left + width / 2, top + height / 2);
44
+ }
45
+ root.begin();
46
+ move(event);
47
+ },
48
+ onPointerMove: (event) => {
49
+ if (event.pointerId === pointer) move(event);
50
+ },
51
+ onPointerUp: end,
52
+ onPointerCancel: end,
53
+ onLostPointerCapture: end,
54
+ ref: (element) => {
55
+ track = element;
56
+ }
57
+ });
58
+ const elementProps = mergeElementProps(ownProps, omit(props, "render"));
59
+ return renderElement(props, elementProps, (p) => (() => {
60
+ var _el$ = _tmpl$();
61
+ spread(_el$, p, false);
62
+ return _el$;
63
+ })());
64
+ }
65
+ export { SliderTrack };
@@ -0,0 +1,24 @@
1
+ import { mergeElementProps } from "../../core/mergeElementProps.js";
2
+ import { renderElement } from "../../core/renderElement.js";
3
+ import { useSliderRootContext } from "../root/SliderRootContext.js";
4
+ import { spread, template } from "@solidjs/web";
5
+ import { merge, omit } from "solid-js";
6
+ // src/slider/value/SliderValue.tsx
7
+ var _tmpl$ = /* @__PURE__ */ template(`<span>`);
8
+ /**
9
+ * The value as text: a `<span>` with the Root's `aria-valuetext`, the value
10
+ * in its `format` and `locale`. Place it inside `Slider.Root`.
11
+ */
12
+ function SliderValue(props) {
13
+ const root = useSliderRootContext();
14
+ const ownProps = merge(root.attributes, { get children() {
15
+ return root.text();
16
+ } });
17
+ const elementProps = mergeElementProps(ownProps, omit(props, "render"));
18
+ return renderElement(props, elementProps, (p) => (() => {
19
+ var _el$ = _tmpl$();
20
+ spread(_el$, p, false);
21
+ return _el$;
22
+ })());
23
+ }
24
+ export { SliderValue };
@@ -0,0 +1,8 @@
1
+ import type { StepButtonProps } from "../stepButton.tsx";
2
+ export type NumberFieldDecrementProps = StepButtonProps;
3
+ /**
4
+ * The button that decreases the number by `step`: a `<button type="button"
5
+ * tabindex="-1">`, repeating while held, disabled at `min`. Give it a
6
+ * name, such as `aria-label="Decrease"`. Place it inside `NumberField.Root`.
7
+ */
8
+ export declare function NumberFieldDecrement(props: NumberFieldDecrementProps): import("@solidjs/web").JSX.Element;
@@ -0,0 +1,9 @@
1
+ import { renderStepButton } from "../stepButton.jsx";
2
+ /**
3
+ * The button that decreases the number by `step`: a `<button type="button"
4
+ * tabindex="-1">`, repeating while held, disabled at `min`. Give it a
5
+ * name, such as `aria-label="Decrease"`. Place it inside `NumberField.Root`.
6
+ */
7
+ export function NumberFieldDecrement(props) {
8
+ return renderStepButton(props, -1, "NumberField.Decrement");
9
+ }
@@ -0,0 +1,8 @@
1
+ import type { StepButtonProps } from "../stepButton.tsx";
2
+ export type NumberFieldIncrementProps = StepButtonProps;
3
+ /**
4
+ * The button that increases the number by `step`: a `<button type="button"
5
+ * tabindex="-1">`, repeating while held, disabled at `max`. Give it a
6
+ * name, such as `aria-label="Increase"`. Place it inside `NumberField.Root`.
7
+ */
8
+ export declare function NumberFieldIncrement(props: NumberFieldIncrementProps): import("@solidjs/web").JSX.Element;
@@ -0,0 +1,9 @@
1
+ import { renderStepButton } from "../stepButton.jsx";
2
+ /**
3
+ * The button that increases the number by `step`: a `<button type="button"
4
+ * tabindex="-1">`, repeating while held, disabled at `max`. Give it a
5
+ * name, such as `aria-label="Increase"`. Place it inside `NumberField.Root`.
6
+ */
7
+ export function NumberFieldIncrement(props) {
8
+ return renderStepButton(props, 1, "NumberField.Increment");
9
+ }
@@ -0,0 +1 @@
1
+ export * as NumberField from "./index.parts.ts";
@@ -0,0 +1 @@
1
+ export * as NumberField from "./index.parts.js";
@@ -0,0 +1,4 @@
1
+ export { NumberFieldRoot as Root } from "./root/NumberFieldRoot.tsx";
2
+ export { NumberFieldInput as Input } from "./input/NumberFieldInput.tsx";
3
+ export { NumberFieldIncrement as Increment } from "./increment/NumberFieldIncrement.tsx";
4
+ export { NumberFieldDecrement as Decrement } from "./decrement/NumberFieldDecrement.tsx";
@@ -0,0 +1,4 @@
1
+ export { NumberFieldRoot as Root } from "./root/NumberFieldRoot.jsx";
2
+ export { NumberFieldInput as Input } from "./input/NumberFieldInput.jsx";
3
+ export { NumberFieldIncrement as Increment } from "./increment/NumberFieldIncrement.jsx";
4
+ export { NumberFieldDecrement as Decrement } from "./decrement/NumberFieldDecrement.jsx";
@@ -0,0 +1,14 @@
1
+ import type { JSX } from "@solidjs/web";
2
+ import type { RenderProp } from "../../core/renderElement.tsx";
3
+ export interface NumberFieldInputProps extends Omit<JSX.InputHTMLAttributes<HTMLInputElement>, "ref" | "id" | "value" | "defaultValue" | "type"> {
4
+ ref?: JSX.Ref<HTMLElement>;
5
+ /** Renders the input with your own component, which must render an `<input>`. Read once. */
6
+ render?: RenderProp;
7
+ }
8
+ /**
9
+ * The spinbutton: an `<input type="text" role="spinbutton">` that shows the
10
+ * number formatted, keeps text as it is typed, and reads it back on blur
11
+ * and on Enter. Up, Down, Page Up, Page Down, Home and End step the number.
12
+ * Takes the Root's `id`; place it inside `NumberField.Root`.
13
+ */
14
+ export declare function NumberFieldInput(props: NumberFieldInputProps): JSX.Element;
@@ -0,0 +1,103 @@
1
+ import { createEffect, merge, omit } from "solid-js";
2
+ import { mergeElementProps } from "../../core/mergeElementProps.js";
3
+ import { renderElement } from "../../core/renderElement.jsx";
4
+ import { useNumberFieldRootContext } from "../root/NumberFieldRootContext.js";
5
+ /**
6
+ * The spinbutton: an `<input type="text" role="spinbutton">` that shows the
7
+ * number formatted, keeps text as it is typed, and reads it back on blur
8
+ * and on Enter. Up, Down, Page Up, Page Down, Home and End step the number.
9
+ * Takes the Root's `id`; place it inside `NumberField.Root`.
10
+ */
11
+ export function NumberFieldInput(props) {
12
+ const root = useNumberFieldRootContext();
13
+ const ownProps = merge(root.attributes, {
14
+ type: "text",
15
+ role: "spinbutton",
16
+ inputmode: "decimal",
17
+ autocomplete: "off",
18
+ get id() {
19
+ return root.inputId();
20
+ },
21
+ // The `value` attribute, not the property: a binding of `value` would
22
+ // write the text again over the user's when any other attribute of the
23
+ // element changes, such as a Field's `aria-invalid`. The attribute is
24
+ // the server's text, and the text a form reset puts back; it leaves an
25
+ // edited input alone.
26
+ get defaultValue() {
27
+ return root.text();
28
+ },
29
+ get disabled() {
30
+ return root.props.disabled;
31
+ },
32
+ get readonly() {
33
+ return root.props.readOnly;
34
+ },
35
+ get "aria-valuenow"() {
36
+ return root.value() ?? undefined;
37
+ },
38
+ get "aria-valuetext"() {
39
+ return root.value() === null ? undefined : root.text();
40
+ },
41
+ get "aria-valuemin"() {
42
+ return root.props.min;
43
+ },
44
+ get "aria-valuemax"() {
45
+ return root.props.max;
46
+ },
47
+ // Solid 2.0 removes an attribute set to false, so spell the value out.
48
+ get "aria-required"() {
49
+ return root.props.required ? "true" : undefined;
50
+ },
51
+ // From a Field around the Root, which is its Control.
52
+ get "aria-describedby"() {
53
+ return root.props["aria-describedby"];
54
+ },
55
+ get "aria-invalid"() {
56
+ return root.props["aria-invalid"];
57
+ },
58
+ onInput: () => {
59
+ root.edited = true;
60
+ },
61
+ onBlur: () => root.commit(),
62
+ onKeyDown: (event) => {
63
+ const { key } = event;
64
+ // Enter commits and goes on, so that a form submits the number. An
65
+ // input method uses Enter to commit its own text.
66
+ if (key === "Enter") {
67
+ if (!event.isComposing)
68
+ root.commit();
69
+ return;
70
+ }
71
+ if (!root.enabled() || event.ctrlKey || event.altKey || event.metaKey)
72
+ return;
73
+ const limit = key === "Home" ? "min" : key === "End" ? "max" : undefined;
74
+ if (key === "ArrowUp" || key === "ArrowDown") {
75
+ // Shift with an arrow selects text.
76
+ if (event.shiftKey)
77
+ return;
78
+ root.step(key === "ArrowUp" ? 1 : -1);
79
+ }
80
+ else if (key === "PageUp" || key === "PageDown") {
81
+ root.step(key === "PageUp" ? 1 : -1, true);
82
+ }
83
+ else if (limit && root.props[limit] !== undefined) {
84
+ root.setLimit(limit);
85
+ }
86
+ else {
87
+ // Every other key edits the text, as the browser does.
88
+ return;
89
+ }
90
+ event.preventDefault();
91
+ },
92
+ ref: (element) => {
93
+ root.input = element;
94
+ },
95
+ });
96
+ // The value changed, by the app or by a step: the input shows its text,
97
+ // over any text the user had typed.
98
+ createEffect(() => root.text(), () => root.sync());
99
+ // Typed for an input; the merge takes any element's attributes.
100
+ const consumerProps = omit(props, "render");
101
+ const elementProps = mergeElementProps(ownProps, consumerProps);
102
+ return renderElement(props, elementProps, (p) => <input {...p}/>);
103
+ }
@@ -0,0 +1,11 @@
1
+ /**
2
+ * Reads text written in a formatter's locale and format back to a number,
3
+ * `NaN` when it is not one (src/number-field/README.md, "Decisions"). Reads
4
+ * the locale's digits, and ASCII digits, its decimal separator, its minus
5
+ * sign and `-`; drops its group separator, whitespace, apostrophes, and the
6
+ * currency, percent sign, unit and literal text the format writes. Any
7
+ * other character makes the text not a number. A percentage is read as the
8
+ * fraction the formatter writes as one: `25%` is `0.25`. Empty text is
9
+ * `NaN` too: the caller reads it as no value.
10
+ */
11
+ export declare function parseNumber(formatter: Intl.NumberFormat, text: string): number;
@@ -0,0 +1,46 @@
1
+ /**
2
+ * Reads text written in a formatter's locale and format back to a number,
3
+ * `NaN` when it is not one (src/number-field/README.md, "Decisions"). Reads
4
+ * the locale's digits, and ASCII digits, its decimal separator, its minus
5
+ * sign and `-`; drops its group separator, whitespace, apostrophes, and the
6
+ * currency, percent sign, unit and literal text the format writes. Any
7
+ * other character makes the text not a number. A percentage is read as the
8
+ * fraction the formatter writes as one: `25%` is `0.25`. Empty text is
9
+ * `NaN` too: the caller reads it as no value.
10
+ */
11
+ export function parseNumber(formatter, text) {
12
+ const { locale, numberingSystem, style } = formatter.resolvedOptions();
13
+ const plain = new Intl.NumberFormat(locale, { numberingSystem });
14
+ // What each character the locale writes stands for.
15
+ const meaning = { "-": "-" };
16
+ for (const { type, value } of plain.formatToParts(-12345.6)) {
17
+ if (type === "decimal")
18
+ meaning[value] = ".";
19
+ if (type === "minusSign")
20
+ meaning[value] = "-";
21
+ if (type === "group")
22
+ meaning[value] = "";
23
+ }
24
+ // The locale's digits, such as Arabic-Indic ones.
25
+ for (let digit = 0; digit < 10; digit++) {
26
+ meaning[plain.format(digit)] = String(digit);
27
+ }
28
+ // The text the format writes around the number.
29
+ for (const { type, value } of [
30
+ ...formatter.formatToParts(-1),
31
+ ...formatter.formatToParts(1),
32
+ ]) {
33
+ if (/^(currency|percentSign|unit|literal|plusSign)$/.test(type)) {
34
+ text = text.split(value).join("");
35
+ }
36
+ }
37
+ let number = "";
38
+ // Whitespace, for a no-break space typed as a space, and either
39
+ // apostrophe, as ICU versions and keyboards differ on de-CH's.
40
+ for (const char of text.replace(/[\s'’]/g, "")) {
41
+ number += /\d/.test(char) ? char : (meaning[char] ?? "!");
42
+ }
43
+ if (!/^-?(\d+\.?\d*|\.\d+)$/.test(number))
44
+ return NaN;
45
+ return style === "percent" ? Number(number) / 100 : Number(number);
46
+ }
@@ -0,0 +1,49 @@
1
+ import type { JSX } from "@solidjs/web";
2
+ import type { RenderProp } from "../../core/renderElement.tsx";
3
+ export interface NumberFieldRootProps extends JSX.HTMLAttributes<HTMLElement> {
4
+ /** The number, when controlled; `null` while the field is empty. */
5
+ value?: number | null;
6
+ /** The number to start with when uncontrolled, and the one a form reset puts back. */
7
+ defaultValue?: number | null;
8
+ /** Called with the new number when the user changes it, and on a form reset. */
9
+ onValueChange?: (value: number | null) => void;
10
+ /** The lowest number the user can set. */
11
+ min?: number;
12
+ /** The highest number the user can set. */
13
+ max?: number;
14
+ /** How much Up, Down and the buttons change the number. Default 1. */
15
+ step?: number;
16
+ /** How much Page Up and Page Down change the number. Default ten steps. */
17
+ largeStep?: number;
18
+ /**
19
+ * How the Input shows the number, as `Intl.NumberFormat` options, such as
20
+ * `{ style: "currency", currency: "EUR" }`. Typed text is read back in
21
+ * the same format.
22
+ */
23
+ format?: Intl.NumberFormatOptions;
24
+ /**
25
+ * The language to format and parse in, else the runtime's default. Pass it
26
+ * when rendering on the server, so that the server and the browser agree.
27
+ */
28
+ locale?: Intl.LocalesArgument;
29
+ /** The name the number is submitted under. */
30
+ name?: string;
31
+ /** The `id` of the form the number belongs to, when the field is not inside it. */
32
+ form?: string;
33
+ /** Whether the form can be submitted only with a number. */
34
+ required?: boolean;
35
+ /** Whether every part ignores the user, and the form submits nothing. */
36
+ disabled?: boolean;
37
+ /** Whether the user can see and select the number, but not change it. */
38
+ readOnly?: boolean;
39
+ /** Renders the Root as another element or component. Read once. */
40
+ render?: RenderProp;
41
+ }
42
+ /**
43
+ * The number field: a `<div>` around its Input and buttons, which holds the
44
+ * value, then a visually hidden `<input type="number">` with the plain
45
+ * number, the form's view of it. Its `id`, `aria-describedby` and
46
+ * `aria-invalid` go on the Input, so it joins a Field as `Field.Control`'s
47
+ * `render`.
48
+ */
49
+ export declare function NumberFieldRoot(props: NumberFieldRootProps): JSX.Element;
@@ -0,0 +1,175 @@
1
+ import { createMemo, createUniqueId, omit, onFlush, onSettled, untrack, } from "solid-js";
2
+ import { createControllableSignal } from "../../core/createControllableSignal.js";
3
+ import { mergeElementProps } from "../../core/mergeElementProps.js";
4
+ import { renderElement } from "../../core/renderElement.jsx";
5
+ import { parseNumber } from "../parse.js";
6
+ import { NumberFieldRootContext } from "./NumberFieldRootContext.js";
7
+ /**
8
+ * The number field: a `<div>` around its Input and buttons, which holds the
9
+ * value, then a visually hidden `<input type="number">` with the plain
10
+ * number, the form's view of it. Its `id`, `aria-describedby` and
11
+ * `aria-invalid` go on the Input, so it joins a Field as `Field.Control`'s
12
+ * `render`.
13
+ */
14
+ export function NumberFieldRoot(props) {
15
+ const [value, setValue, requested] = createControllableSignal({
16
+ get value() {
17
+ return props.value;
18
+ },
19
+ get defaultValue() {
20
+ return props.defaultValue ?? null;
21
+ },
22
+ onChange: (next) => props.onValueChange?.(next),
23
+ });
24
+ const formatter = createMemo(() => new Intl.NumberFormat(props.locale, props.format));
25
+ const format = (number) => number === null ? "" : formatter().format(number);
26
+ const generatedId = createUniqueId();
27
+ let hidden;
28
+ // The number rounded to `digits` decimals, to drop a float error or the
29
+ // digits the format does not show, then clamped to `min` and `max`.
30
+ const roundAndClamp = (number, digits) => Math.min(Math.max(Number(number.toFixed(digits)), props.min ?? -Infinity), props.max ?? Infinity);
31
+ // The number as the form writes it.
32
+ const formValue = (number) => number === null ? "" : String(number);
33
+ // Puts the Input and the hidden input back to the value, once it has
34
+ // settled: a controlled field's consumer may have declined the change,
35
+ // and a commit shows the value formatted, such as `1000` as `1,000`.
36
+ const sync = () => {
37
+ context.edited = false;
38
+ const number = untrack(value);
39
+ const text = untrack(() => format(number));
40
+ if (context.input && context.input.value !== text) {
41
+ context.input.value = text;
42
+ }
43
+ if (hidden)
44
+ hidden.value = formValue(number);
45
+ };
46
+ // A change by the user. The hidden input changes first and fires its
47
+ // native events, as a native control does, so the form's listeners, a
48
+ // Field and a Form see the new number.
49
+ const change = (next) => {
50
+ const before = hidden?.value;
51
+ if (hidden)
52
+ hidden.value = formValue(next);
53
+ setValue(next);
54
+ if (hidden && hidden.value !== before) {
55
+ hidden.dispatchEvent(new Event("input", { bubbles: true }));
56
+ hidden.dispatchEvent(new Event("change", { bubbles: true }));
57
+ }
58
+ onFlush(sync);
59
+ };
60
+ // The number the user's text says, if edited, else the value set last.
61
+ const current = () => {
62
+ if (context.edited && context.input) {
63
+ const parsed = parseNumber(formatter(), context.input.value);
64
+ if (!Number.isNaN(parsed))
65
+ return parsed;
66
+ }
67
+ return requested();
68
+ };
69
+ // Decimal places of a number, to round a step's float error away.
70
+ const places = (number = 0) => (String(number).split(".")[1] ?? "").length;
71
+ const context = {
72
+ props,
73
+ value,
74
+ text: () => format(value()),
75
+ inputId: () => props.id || generatedId,
76
+ attributes: {
77
+ get "data-disabled"() {
78
+ return props.disabled ? "" : undefined;
79
+ },
80
+ get "data-readonly"() {
81
+ return props.readOnly ? "" : undefined;
82
+ },
83
+ get "data-required"() {
84
+ return props.required ? "" : undefined;
85
+ },
86
+ },
87
+ edited: false,
88
+ sync,
89
+ enabled: () => !props.disabled && !props.readOnly,
90
+ canStep: (direction) => {
91
+ const number = value();
92
+ const limit = direction > 0 ? props.max : props.min;
93
+ return (context.enabled() &&
94
+ (number === null ||
95
+ limit === undefined ||
96
+ (direction > 0 ? number < limit : number > limit)));
97
+ },
98
+ step: (direction, large) => {
99
+ const size = props.step ?? 1;
100
+ const amount = large ? (props.largeStep ?? size * 10) : size;
101
+ const origin = props.min ?? 0;
102
+ // From a number off the grid, the grid's next one that way, as
103
+ // `stepUp()` does; from none, 0, as on an empty number input.
104
+ const steps = ((current() ?? 0) - origin) / size;
105
+ const onGrid = direction > 0 ? Math.floor(steps + 1e-9) : Math.ceil(steps - 1e-9);
106
+ const next = origin + onGrid * size + direction * amount;
107
+ change(roundAndClamp(next, Math.max(places(size), places(origin), places(amount))));
108
+ },
109
+ setLimit: (limit) => {
110
+ const number = props[limit];
111
+ if (number !== undefined)
112
+ change(number);
113
+ },
114
+ commit: () => {
115
+ if (!context.edited || !context.input)
116
+ return;
117
+ const text = context.input.value.trim();
118
+ const parsed = text ? parseNumber(formatter(), text) : null;
119
+ // Text that is not a number goes back to the value's.
120
+ if (Number.isNaN(parsed))
121
+ return sync();
122
+ if (parsed === null)
123
+ return change(null);
124
+ // Rounded to the digits the format shows, so the value is what the
125
+ // user sees: a percentage shows two digits fewer than it has.
126
+ const options = formatter().resolvedOptions();
127
+ change(roundAndClamp(parsed, options.maximumFractionDigits +
128
+ (options.style === "percent" ? 2 : 0)));
129
+ },
130
+ };
131
+ // A form reset puts a control back to its default, and so it does this
132
+ // one: through the setter, so that a controlled field asks.
133
+ onSettled(() => {
134
+ const form = hidden?.form;
135
+ if (!form)
136
+ return;
137
+ // A field the reset removes, such as a row of a list going back to its
138
+ // default length, asks for nothing.
139
+ let disposed = false;
140
+ const onReset = (event) => {
141
+ // In a task of its own, not `onFlush`: when the user presses a reset
142
+ // button, the browser runs microtasks as each listener returns,
143
+ // before it resets the controls and before later listeners could
144
+ // cancel the reset (src/input/README.md).
145
+ setTimeout(() => {
146
+ if (disposed || event.defaultPrevented)
147
+ return;
148
+ setValue(props.defaultValue ?? null);
149
+ onFlush(sync);
150
+ });
151
+ };
152
+ form.addEventListener("reset", onReset);
153
+ return () => {
154
+ disposed = true;
155
+ form.removeEventListener("reset", onReset);
156
+ };
157
+ });
158
+ const elementProps = mergeElementProps(context.attributes, omit(props, "render", "value", "defaultValue", "onValueChange", "min", "max", "step", "largeStep", "format", "locale", "name", "form", "required", "disabled", "readOnly", "id", "aria-describedby", "aria-invalid"));
159
+ return (<NumberFieldRootContext value={context}>
160
+ {renderElement(props, elementProps, (p) => (<div {...p}/>))}
161
+ <input type="number" aria-hidden="true" tabindex={-1} style={visuallyHidden} name={props.name} form={props.form} min={props.min} max={props.max}
162
+ // Without a `step`, any number is valid, as a currency's cents
163
+ // are: the field formats decimals by default. The keys still step
164
+ // by 1.
165
+ step={props.step ?? "any"} required={props.required} disabled={props.disabled} readonly={props.readOnly} value={formValue(value())}
166
+ // The browser focuses an invalid input when it blocks a submission.
167
+ // The user knows the Input, not the hidden input.
168
+ onFocus={() => context.input?.focus()} ref={(element) => {
169
+ hidden = element;
170
+ }}/>
171
+ </NumberFieldRootContext>);
172
+ }
173
+ // Hidden from sight but not from the form. Not `display: none`, so the
174
+ // browser can still anchor a validation message to it.
175
+ const visuallyHidden = "position:absolute;width:1px;height:1px;margin:-1px;padding:0;border:0;overflow:hidden;clip-path:inset(50%);white-space:nowrap;pointer-events:none";
@@ -0,0 +1,35 @@
1
+ import type { ElementProps } from "../../core/renderElement.tsx";
2
+ import type { NumberFieldRootProps } from "./NumberFieldRoot.tsx";
3
+ /** What the Root shares with its parts. */
4
+ export interface NumberFieldRootContextValue {
5
+ readonly props: NumberFieldRootProps;
6
+ /** The value, `null` while the field is empty. */
7
+ value(): number | null;
8
+ /** The value as the Input shows it, `""` while `null`. */
9
+ text(): string;
10
+ /** The Input's `id`: the Root's, else a generated one. */
11
+ inputId(): string;
12
+ /** `data-disabled`, `data-readonly` and `data-required`, for every part. */
13
+ readonly attributes: ElementProps;
14
+ /** The Input, once rendered. */
15
+ input?: HTMLInputElement;
16
+ /** Whether the user has edited the text since it last showed the value. */
17
+ edited: boolean;
18
+ /**
19
+ * Puts the Input's text and the hidden input back to the value, and marks
20
+ * the text unedited.
21
+ */
22
+ sync(): void;
23
+ /** Whether the user can change the value: neither disabled nor read-only. */
24
+ enabled(): boolean;
25
+ /** Whether a step that way could change the value. */
26
+ canStep(direction: 1 | -1): boolean;
27
+ /** Steps the value by `step` that way, or by `largeStep` when `large`. */
28
+ step(direction: 1 | -1, large?: boolean): void;
29
+ /** Sets the value to `min` or `max`, for Home and End. */
30
+ setLimit(limit: "min" | "max"): void;
31
+ /** Parses the text the user typed, if edited, into the value. */
32
+ commit(): void;
33
+ }
34
+ export declare const NumberFieldRootContext: import("solid-js").Context<NumberFieldRootContextValue | null>;
35
+ export declare function useNumberFieldRootContext(): NumberFieldRootContextValue;
@@ -0,0 +1,13 @@
1
+ import { createContext, useContext } from "solid-js";
2
+ import { isDev } from "@solidjs/web";
3
+ // `null` outside a Root, so that the part can name what is missing. Solid's
4
+ // own error for a context with no provider and no default does not.
5
+ export const NumberFieldRootContext = createContext(null);
6
+ export function useNumberFieldRootContext() {
7
+ const context = useContext(NumberFieldRootContext);
8
+ // Production builds drop the check, and its message, with `isDev`.
9
+ if (isDev && !context) {
10
+ throw new Error("[menhir] NumberField parts must be placed within <NumberField.Root>.");
11
+ }
12
+ return context;
13
+ }
@@ -0,0 +1,12 @@
1
+ import type { JSX } from "@solidjs/web";
2
+ import type { RenderProp } from "../core/renderElement.tsx";
3
+ export interface StepButtonProps extends JSX.HTMLAttributes<HTMLElement> {
4
+ /** Renders the button with your own component, which must render a `<button>`. Read once. */
5
+ render?: RenderProp;
6
+ }
7
+ /**
8
+ * Increment or Decrement: a `<button type="button" tabindex="-1">` that
9
+ * steps the value that way on a click, and again and again while a pointer
10
+ * holds it. It never takes focus, and is disabled at its limit.
11
+ */
12
+ export declare function renderStepButton(props: StepButtonProps, direction: 1 | -1, part: string): JSX.Element;