menhir 0.1.7 → 0.1.9

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 (35) hide show
  1. package/README.md +1 -1
  2. package/dist/field/control/FieldControl.js +39 -0
  3. package/dist/field/description/FieldDescription.js +25 -0
  4. package/dist/field/error/FieldError.js +45 -0
  5. package/dist/field/index.js +2 -0
  6. package/dist/field/index.parts.js +6 -0
  7. package/dist/field/label/FieldLabel.js +23 -0
  8. package/dist/field/root/FieldRoot.js +113 -0
  9. package/dist/field/root/FieldRootContext.js +10 -0
  10. package/dist/input/index.js +2 -0
  11. package/dist/input/index.parts.js +1 -0
  12. package/dist/input/root/InputRoot.js +55 -0
  13. package/dist/source/field/control/FieldControl.d.ts +20 -0
  14. package/dist/source/field/control/FieldControl.jsx +36 -0
  15. package/dist/source/field/description/FieldDescription.d.ts +12 -0
  16. package/dist/source/field/description/FieldDescription.jsx +19 -0
  17. package/dist/source/field/error/FieldError.d.ts +19 -0
  18. package/dist/source/field/error/FieldError.jsx +39 -0
  19. package/dist/source/field/index.d.ts +1 -0
  20. package/dist/source/field/index.js +1 -0
  21. package/dist/source/field/index.parts.d.ts +5 -0
  22. package/dist/source/field/index.parts.js +5 -0
  23. package/dist/source/field/label/FieldLabel.d.ts +11 -0
  24. package/dist/source/field/label/FieldLabel.jsx +19 -0
  25. package/dist/source/field/root/FieldRoot.d.ts +25 -0
  26. package/dist/source/field/root/FieldRoot.jsx +133 -0
  27. package/dist/source/field/root/FieldRootContext.d.ts +50 -0
  28. package/dist/source/field/root/FieldRootContext.js +13 -0
  29. package/dist/source/input/index.d.ts +1 -0
  30. package/dist/source/input/index.js +1 -0
  31. package/dist/source/input/index.parts.d.ts +1 -0
  32. package/dist/source/input/index.parts.js +1 -0
  33. package/dist/source/input/root/InputRoot.d.ts +29 -0
  34. package/dist/source/input/root/InputRoot.jsx +67 -0
  35. package/package.json +11 -1
package/README.md CHANGED
@@ -62,7 +62,7 @@ For everything else, go to the docs:
62
62
 
63
63
  Early 0.x versions: the API may change between minor versions. The form components come next; the plan and roadmap are in the [repository](https://github.com/j13n/menhir). Built so far:
64
64
 
65
- - Components: Accordion, Alert Dialog, Autocomplete, Checkbox, Collapsible, Combobox, Context Menu, Dialog, Menu, Menubar, Meter, Navigation Menu, Popover, Progress, Select, Separator, Switch, Tabs, Toggle, Toggle Group and Tooltip.
65
+ - Components: Accordion, Alert Dialog, Autocomplete, Checkbox, Collapsible, Combobox, Context Menu, Dialog, Field, Input, Menu, Menubar, Meter, Navigation Menu, Popover, Progress, Select, Separator, Switch, Tabs, Toggle, Toggle Group and Tooltip.
66
66
  - Utilities: color scheme and theme, each with local-storage and cookie storage.
67
67
 
68
68
  ## Licence
@@ -0,0 +1,39 @@
1
+ import { mergeElementProps } from "../../core/mergeElementProps.js";
2
+ import { renderElement } from "../../core/renderElement.js";
3
+ import { useFieldRootContext } from "../root/FieldRootContext.js";
4
+ import { spread, template } from "@solidjs/web";
5
+ import { merge, omit } from "solid-js";
6
+ // src/field/control/FieldControl.tsx
7
+ var _tmpl$ = /* @__PURE__ */ template(`<input>`);
8
+ /**
9
+ * The field's control: an `<input>`, or what `render` renders, with the
10
+ * field's `id`, which the Label names, its `name` and `disabled`, and
11
+ * `aria-describedby` naming the Description and the rendered Error. Takes
12
+ * no `id`: the Root generates it. Place it inside `Field.Root`.
13
+ */
14
+ function FieldControl(props) {
15
+ const root = useFieldRootContext();
16
+ const ownProps = merge(root.attributes, {
17
+ id: root.controlId,
18
+ get name() {
19
+ return root.name();
20
+ },
21
+ get disabled() {
22
+ return root.disabled();
23
+ },
24
+ get "aria-invalid"() {
25
+ return root.showsError() ? "true" : void 0;
26
+ },
27
+ get "aria-describedby"() {
28
+ return props["aria-describedby"] ?? root.describedBy();
29
+ }
30
+ });
31
+ const consumerProps = omit(props, "render", "id", "aria-describedby");
32
+ const elementProps = mergeElementProps(ownProps, consumerProps);
33
+ return renderElement(props, elementProps, (p) => (() => {
34
+ var _el$ = _tmpl$();
35
+ spread(_el$, p, false);
36
+ return _el$;
37
+ })());
38
+ }
39
+ export { FieldControl };
@@ -0,0 +1,25 @@
1
+ import { mergeElementProps } from "../../core/mergeElementProps.js";
2
+ import { renderElement } from "../../core/renderElement.js";
3
+ import { useFieldRootContext } from "../root/FieldRootContext.js";
4
+ import { spread, template } from "@solidjs/web";
5
+ import { merge, omit, onSettled } from "solid-js";
6
+ // src/field/description/FieldDescription.tsx
7
+ var _tmpl$ = /* @__PURE__ */ template(`<p>`);
8
+ /**
9
+ * What the control is for, or what it takes, which describes the control
10
+ * in `aria-describedby`: a `<p>`. Its `id` is the Root's, so the server
11
+ * HTML links it before hydration; it takes none from the consumer. Place
12
+ * it inside `Field.Root`.
13
+ */
14
+ function FieldDescription(props) {
15
+ const root = useFieldRootContext();
16
+ onSettled(() => root.registerDescription());
17
+ const ownProps = merge(root.attributes, { id: root.descriptionId });
18
+ const elementProps = mergeElementProps(ownProps, omit(props, "render", "id"));
19
+ return renderElement(props, elementProps, (p) => (() => {
20
+ var _el$ = _tmpl$();
21
+ spread(_el$, p, false);
22
+ return _el$;
23
+ })());
24
+ }
25
+ export { FieldDescription };
@@ -0,0 +1,45 @@
1
+ import { mergeElementProps } from "../../core/mergeElementProps.js";
2
+ import { renderElement } from "../../core/renderElement.js";
3
+ import { useFieldRootContext } from "../root/FieldRootContext.js";
4
+ import { createComponent, spread, template } from "@solidjs/web";
5
+ import { Show, createUniqueId, merge, omit, onSettled } from "solid-js";
6
+ // src/field/error/FieldError.tsx
7
+ var _tmpl$ = /* @__PURE__ */ template(`<p>`);
8
+ /**
9
+ * The field's error message: a `<p>`, rendered only while the field shows
10
+ * an error, which the control names in `aria-describedby` while it is
11
+ * rendered. Without children it shows the error from outside, else the
12
+ * browser's message. Place it inside `Field.Root`.
13
+ */
14
+ function FieldError(props) {
15
+ const root = useFieldRootContext();
16
+ const generated = createUniqueId();
17
+ const id = () => props.id ?? generated;
18
+ const shown = () => root.showsError() && (props.match === void 0 || !!root.validity()?.[props.match]) && ("children" in props || !!root.message());
19
+ onSettled(() => root.registerError({
20
+ id,
21
+ shown
22
+ }));
23
+ const ownProps = merge(root.attributes, {
24
+ get id() {
25
+ return id();
26
+ },
27
+ get children() {
28
+ return props.children ?? root.message();
29
+ }
30
+ });
31
+ const elementProps = mergeElementProps(ownProps, omit(props, "render", "id", "match", "children"));
32
+ return createComponent(Show, {
33
+ get when() {
34
+ return shown();
35
+ },
36
+ get children() {
37
+ return renderElement(props, elementProps, (p) => (() => {
38
+ var _el$ = _tmpl$();
39
+ spread(_el$, p, false);
40
+ return _el$;
41
+ })());
42
+ }
43
+ });
44
+ }
45
+ export { FieldError };
@@ -0,0 +1,2 @@
1
+ import * as Field from "./index.parts.js";
2
+ export { Field };
@@ -0,0 +1,6 @@
1
+ import { FieldRoot } from "./root/FieldRoot.js";
2
+ import { FieldLabel } from "./label/FieldLabel.js";
3
+ import { FieldControl } from "./control/FieldControl.js";
4
+ import { FieldDescription } from "./description/FieldDescription.js";
5
+ import { FieldError } from "./error/FieldError.js";
6
+ export { FieldControl as Control, FieldDescription as Description, FieldError as Error, FieldLabel as Label, FieldRoot as Root };
@@ -0,0 +1,23 @@
1
+ import { mergeElementProps } from "../../core/mergeElementProps.js";
2
+ import { renderElement } from "../../core/renderElement.js";
3
+ import { useFieldRootContext } from "../root/FieldRootContext.js";
4
+ import { spread, template } from "@solidjs/web";
5
+ import { merge, omit } from "solid-js";
6
+ // src/field/label/FieldLabel.tsx
7
+ var _tmpl$ = /* @__PURE__ */ template(`<label>`);
8
+ /**
9
+ * The control's label: a `<label>` whose `for` is the control's `id`, which
10
+ * the Root generates, so the server HTML is labelled before hydration.
11
+ * Place it inside `Field.Root`.
12
+ */
13
+ function FieldLabel(props) {
14
+ const root = useFieldRootContext();
15
+ const ownProps = merge(root.attributes, { for: root.controlId });
16
+ const elementProps = mergeElementProps(ownProps, omit(props, "render"));
17
+ return renderElement(props, elementProps, (p) => (() => {
18
+ var _el$ = _tmpl$();
19
+ spread(_el$, p, false);
20
+ return _el$;
21
+ })());
22
+ }
23
+ export { FieldLabel };
@@ -0,0 +1,113 @@
1
+ import { mergeElementProps } from "../../core/mergeElementProps.js";
2
+ import { renderElement } from "../../core/renderElement.js";
3
+ import { FieldRootContext } from "./FieldRootContext.js";
4
+ import { createComponent, spread, template } from "@solidjs/web";
5
+ import { createSignal, createUniqueId, merge, omit, onFlush, onSettled } from "solid-js";
6
+ // src/field/root/FieldRoot.tsx
7
+ var _tmpl$ = /* @__PURE__ */ template(`<div>`);
8
+ var controlSelector = "input,select,textarea";
9
+ /**
10
+ * The field: a `<div>` that holds a control's label, description and error,
11
+ * and its validity. It generates the control's `id` and the Description's,
12
+ * and tracks whether the field was touched.
13
+ */
14
+ function FieldRoot(props) {
15
+ const controlId = createUniqueId();
16
+ const descriptionId = createUniqueId();
17
+ const [touched, setTouched] = createSignal(false);
18
+ const [invalidControl, setInvalidControl] = createSignal(void 0, { equals: false });
19
+ const [settled, setSettled] = createSignal(false);
20
+ const [descriptions, setDescriptions] = createSignal(0);
21
+ const [errors, setErrors] = createSignal([]);
22
+ let root;
23
+ const readValidity = () => {
24
+ if (!root) return void 0;
25
+ for (const control of root.querySelectorAll(controlSelector)) if (control.willValidate && !control.validity.valid) return control;
26
+ };
27
+ const update = (touch) => onFlush(() => {
28
+ setInvalidControl(readValidity());
29
+ if (touch !== void 0) setTouched(touch);
30
+ });
31
+ const invalid = () => !!props.invalid || !!props.error || invalidControl() !== void 0;
32
+ const showsError = () => touched() && invalid();
33
+ const attributes = {
34
+ get "data-invalid"() {
35
+ return showsError() ? "" : void 0;
36
+ },
37
+ get "data-touched"() {
38
+ return touched() ? "" : void 0;
39
+ },
40
+ get "data-disabled"() {
41
+ return props.disabled ? "" : void 0;
42
+ }
43
+ };
44
+ const context = {
45
+ controlId,
46
+ descriptionId,
47
+ name: () => props.name,
48
+ disabled: () => props.disabled,
49
+ showsError,
50
+ message: () => props.error || invalidControl()?.validationMessage,
51
+ validity: () => invalidControl()?.validity,
52
+ describedBy() {
53
+ const ids = [];
54
+ if (!settled() || descriptions() > 0) ids.push(descriptionId);
55
+ for (const error of errors()) {
56
+ const id = error.shown() && error.id();
57
+ if (id) ids.push(id);
58
+ }
59
+ return ids.join(" ") || void 0;
60
+ },
61
+ registerDescription() {
62
+ setDescriptions((count) => count + 1);
63
+ return () => setDescriptions((count) => count - 1);
64
+ },
65
+ registerError(entry) {
66
+ setErrors((list) => [...list, entry]);
67
+ return () => setErrors((list) => list.filter((e) => e !== entry));
68
+ },
69
+ attributes
70
+ };
71
+ const touch = () => update(true);
72
+ onSettled(() => {
73
+ setSettled(true);
74
+ const form = root?.querySelector(controlSelector)?.form ?? root?.closest("form");
75
+ if (!form) return;
76
+ const onReset = (event) => onFlush(() => {
77
+ if (!event.defaultPrevented) update(false);
78
+ });
79
+ form.addEventListener("submit", touch);
80
+ form.addEventListener("invalid", touch, true);
81
+ form.addEventListener("reset", onReset);
82
+ return () => {
83
+ form.removeEventListener("submit", touch);
84
+ form.removeEventListener("invalid", touch, true);
85
+ form.removeEventListener("reset", onReset);
86
+ };
87
+ });
88
+ const ownProps = merge(attributes, {
89
+ onFocusOut: (event) => {
90
+ const to = event.relatedTarget;
91
+ const left = to ? !root?.contains(to) : document.activeElement !== event.target;
92
+ update(left || void 0);
93
+ },
94
+ onChange: touch,
95
+ onInput: () => update(),
96
+ ref: (element) => {
97
+ root = element;
98
+ element.addEventListener("invalid", touch, true);
99
+ }
100
+ });
101
+ const elementProps = mergeElementProps(ownProps, omit(props, "render", "name", "disabled", "invalid", "error"));
102
+ return createComponent(FieldRootContext, {
103
+ value: context,
104
+ get children() {
105
+ return renderElement(props, elementProps, (p) => (() => {
106
+ var _el$ = _tmpl$();
107
+ spread(_el$, p, false);
108
+ return _el$;
109
+ })());
110
+ }
111
+ });
112
+ }
113
+ export { FieldRoot };
@@ -0,0 +1,10 @@
1
+ import { isDev } from "@solidjs/web";
2
+ import { createContext, useContext } from "solid-js";
3
+ // src/field/root/FieldRootContext.ts
4
+ var FieldRootContext = createContext(null);
5
+ function useFieldRootContext() {
6
+ const context = useContext(FieldRootContext);
7
+ if (isDev && !context) throw new Error("[menhir] Field parts must be placed within <Field.Root>.");
8
+ return context;
9
+ }
10
+ export { FieldRootContext, useFieldRootContext };
@@ -0,0 +1,2 @@
1
+ import * as Input from "./index.parts.js";
2
+ export { Input };
@@ -0,0 +1 @@
1
+ export { InputRoot as Root } from "./root/InputRoot.js";
@@ -0,0 +1,55 @@
1
+ import { mergeElementProps } from "../../core/mergeElementProps.js";
2
+ import { renderElement } from "../../core/renderElement.js";
3
+ import { spread, template } from "@solidjs/web";
4
+ import { merge, omit, onFlush, onSettled, untrack } from "solid-js";
5
+ // src/input/root/InputRoot.tsx
6
+ var _tmpl$ = /* @__PURE__ */ template(`<input>`);
7
+ /**
8
+ * A text input: a native `<input>`, or what `render` renders. Name it with a
9
+ * `<label>`, or place it in `Field.Control`'s `render`.
10
+ */
11
+ function InputRoot(props) {
12
+ let element;
13
+ const restoreValue = () => {
14
+ const value = untrack(() => props.value);
15
+ if (element && value !== void 0 && element.value !== value) element.value = value;
16
+ };
17
+ onSettled(() => {
18
+ const form = element?.form;
19
+ if (!form) return;
20
+ const onReset = (event) => {
21
+ const text = element.value;
22
+ const defaultText = untrack(() => props.defaultValue) ?? "";
23
+ if (untrack(() => props.value) !== void 0) element.defaultValue = text;
24
+ setTimeout(() => {
25
+ if (event.defaultPrevented || text === defaultText) return;
26
+ props.onValueChange?.(defaultText, {
27
+ reason: "reset",
28
+ event
29
+ });
30
+ onFlush(restoreValue);
31
+ });
32
+ };
33
+ form.addEventListener("reset", onReset);
34
+ return () => form.removeEventListener("reset", onReset);
35
+ });
36
+ const elementProps = merge(mergeElementProps({
37
+ onInput: (event) => {
38
+ props.onValueChange?.(element.value, {
39
+ reason: "input-change",
40
+ event
41
+ });
42
+ if (!event.isComposing) onFlush(restoreValue);
43
+ },
44
+ onCompositionEnd: () => onFlush(restoreValue),
45
+ ref: (el) => {
46
+ element = el;
47
+ }
48
+ }, omit(props, "render", "value", "onValueChange")), () => props.value === void 0 ? {} : { value: props.value });
49
+ return renderElement(props, elementProps, (p) => (() => {
50
+ var _el$ = _tmpl$();
51
+ spread(_el$, p, false);
52
+ return _el$;
53
+ })());
54
+ }
55
+ export { InputRoot };
@@ -0,0 +1,20 @@
1
+ import type { JSX } from "@solidjs/web";
2
+ import type { RenderProp } from "../../core/renderElement.tsx";
3
+ export interface FieldControlProps extends Omit<JSX.InputHTMLAttributes<HTMLInputElement>, "id" | "ref"> {
4
+ /** Typed for any element, since `render` may render a `<textarea>` or a `<select>`. */
5
+ ref?: JSX.Ref<HTMLElement>;
6
+ /**
7
+ * Renders the control as another element or component, such as a
8
+ * `<textarea>`, a `<select>` or `Switch.Root`, which gets the field's
9
+ * `id`, `name`, `disabled`, `aria-describedby`, `aria-invalid` and
10
+ * `data-*` attributes. Read once.
11
+ */
12
+ render?: RenderProp;
13
+ }
14
+ /**
15
+ * The field's control: an `<input>`, or what `render` renders, with the
16
+ * field's `id`, which the Label names, its `name` and `disabled`, and
17
+ * `aria-describedby` naming the Description and the rendered Error. Takes
18
+ * no `id`: the Root generates it. Place it inside `Field.Root`.
19
+ */
20
+ export declare function FieldControl(props: FieldControlProps): JSX.Element;
@@ -0,0 +1,36 @@
1
+ import { merge, omit } from "solid-js";
2
+ import { mergeElementProps } from "../../core/mergeElementProps.js";
3
+ import { renderElement } from "../../core/renderElement.jsx";
4
+ import { useFieldRootContext } from "../root/FieldRootContext.js";
5
+ /**
6
+ * The field's control: an `<input>`, or what `render` renders, with the
7
+ * field's `id`, which the Label names, its `name` and `disabled`, and
8
+ * `aria-describedby` naming the Description and the rendered Error. Takes
9
+ * no `id`: the Root generates it. Place it inside `Field.Root`.
10
+ */
11
+ export function FieldControl(props) {
12
+ const root = useFieldRootContext();
13
+ const ownProps = merge(root.attributes, {
14
+ id: root.controlId,
15
+ get name() {
16
+ return root.name();
17
+ },
18
+ get disabled() {
19
+ return root.disabled();
20
+ },
21
+ // Solid 2.0 removes an attribute set to false, so spell the value out.
22
+ get "aria-invalid"() {
23
+ return root.showsError() ? "true" : undefined;
24
+ },
25
+ // The consumer's wins. Kept out of the merge, where a wrapper's
26
+ // `aria-describedby={undefined}` would remove the Field's ("`undefined`
27
+ // is a value", PLAN.md section 8).
28
+ get "aria-describedby"() {
29
+ return props["aria-describedby"] ?? root.describedBy();
30
+ },
31
+ });
32
+ const consumerProps = omit(props, "render", "id", "aria-describedby");
33
+ // Typed for an input; the merge takes any element's attributes.
34
+ const elementProps = mergeElementProps(ownProps, consumerProps);
35
+ return renderElement(props, elementProps, (p) => <input {...p}/>);
36
+ }
@@ -0,0 +1,12 @@
1
+ import type { JSX } from "@solidjs/web";
2
+ import type { RenderProp } from "../../core/renderElement.tsx";
3
+ export interface FieldDescriptionProps extends Omit<JSX.HTMLAttributes<HTMLElement>, "id"> {
4
+ render?: RenderProp;
5
+ }
6
+ /**
7
+ * What the control is for, or what it takes, which describes the control
8
+ * in `aria-describedby`: a `<p>`. Its `id` is the Root's, so the server
9
+ * HTML links it before hydration; it takes none from the consumer. Place
10
+ * it inside `Field.Root`.
11
+ */
12
+ export declare function FieldDescription(props: FieldDescriptionProps): JSX.Element;
@@ -0,0 +1,19 @@
1
+ import { merge, omit, onSettled } from "solid-js";
2
+ import { mergeElementProps } from "../../core/mergeElementProps.js";
3
+ import { renderElement } from "../../core/renderElement.jsx";
4
+ import { useFieldRootContext } from "../root/FieldRootContext.js";
5
+ /**
6
+ * What the control is for, or what it takes, which describes the control
7
+ * in `aria-describedby`: a `<p>`. Its `id` is the Root's, so the server
8
+ * HTML links it before hydration; it takes none from the consumer. Place
9
+ * it inside `Field.Root`.
10
+ */
11
+ export function FieldDescription(props) {
12
+ const root = useFieldRootContext();
13
+ // Counted once mounted, so that a Field without a Description names none
14
+ // (README, "Decisions").
15
+ onSettled(() => root.registerDescription());
16
+ const ownProps = merge(root.attributes, { id: root.descriptionId });
17
+ const elementProps = mergeElementProps(ownProps, omit(props, "render", "id"));
18
+ return renderElement(props, elementProps, (p) => <p {...p}/>);
19
+ }
@@ -0,0 +1,19 @@
1
+ import type { JSX } from "@solidjs/web";
2
+ import type { RenderProp } from "../../core/renderElement.tsx";
3
+ /** A flag of the browser's validity, such as `"valueMissing"`. */
4
+ export type ValidityFlag = Exclude<keyof ValidityState, "valid">;
5
+ export interface FieldErrorProps extends JSX.HTMLAttributes<HTMLElement> {
6
+ /**
7
+ * Shows the Error only while the browser's validity has this flag, such
8
+ * as `"valueMissing"`, so each state gets its own message.
9
+ */
10
+ match?: ValidityFlag;
11
+ render?: RenderProp;
12
+ }
13
+ /**
14
+ * The field's error message: a `<p>`, rendered only while the field shows
15
+ * an error, which the control names in `aria-describedby` while it is
16
+ * rendered. Without children it shows the error from outside, else the
17
+ * browser's message. Place it inside `Field.Root`.
18
+ */
19
+ export declare function FieldError(props: FieldErrorProps): JSX.Element;
@@ -0,0 +1,39 @@
1
+ import { Show, createUniqueId, merge, omit, onSettled } from "solid-js";
2
+ import { mergeElementProps } from "../../core/mergeElementProps.js";
3
+ import { renderElement } from "../../core/renderElement.jsx";
4
+ import { useFieldRootContext } from "../root/FieldRootContext.js";
5
+ /**
6
+ * The field's error message: a `<p>`, rendered only while the field shows
7
+ * an error, which the control names in `aria-describedby` while it is
8
+ * rendered. Without children it shows the error from outside, else the
9
+ * browser's message. Place it inside `Field.Root`.
10
+ */
11
+ export function FieldError(props) {
12
+ const root = useFieldRootContext();
13
+ const generated = createUniqueId();
14
+ // The consumer's `id`, else the generated one. Kept out of the merge,
15
+ // where a wrapper's `id={undefined}` would remove it ("`undefined` is a
16
+ // value", PLAN.md section 8).
17
+ const id = () => props.id ?? generated;
18
+ // Without children, an Error with no message to show is not rendered,
19
+ // so the control never names an empty element. Whether children were
20
+ // passed is fixed by the JSX, so the key is checked, not their value.
21
+ const shown = () => root.showsError() &&
22
+ (props.match === undefined || !!root.validity()?.[props.match]) &&
23
+ ("children" in props || !!root.message());
24
+ // Registered once mounted, as a popup's Title is, so that the control
25
+ // names it only while it is rendered, and in the same update.
26
+ onSettled(() => root.registerError({ id, shown }));
27
+ const ownProps = merge(root.attributes, {
28
+ get id() {
29
+ return id();
30
+ },
31
+ get children() {
32
+ return props.children ?? root.message();
33
+ },
34
+ });
35
+ const elementProps = mergeElementProps(ownProps, omit(props, "render", "id", "match", "children"));
36
+ return (<Show when={shown()}>
37
+ {renderElement(props, elementProps, (p) => (<p {...p}/>))}
38
+ </Show>);
39
+ }
@@ -0,0 +1 @@
1
+ export * as Field from "./index.parts.ts";
@@ -0,0 +1 @@
1
+ export * as Field from "./index.parts.js";
@@ -0,0 +1,5 @@
1
+ export { FieldRoot as Root } from "./root/FieldRoot.tsx";
2
+ export { FieldLabel as Label } from "./label/FieldLabel.tsx";
3
+ export { FieldControl as Control } from "./control/FieldControl.tsx";
4
+ export { FieldDescription as Description } from "./description/FieldDescription.tsx";
5
+ export { FieldError as Error } from "./error/FieldError.tsx";
@@ -0,0 +1,5 @@
1
+ export { FieldRoot as Root } from "./root/FieldRoot.jsx";
2
+ export { FieldLabel as Label } from "./label/FieldLabel.jsx";
3
+ export { FieldControl as Control } from "./control/FieldControl.jsx";
4
+ export { FieldDescription as Description } from "./description/FieldDescription.jsx";
5
+ export { FieldError as Error } from "./error/FieldError.jsx";
@@ -0,0 +1,11 @@
1
+ import type { JSX } from "@solidjs/web";
2
+ import type { RenderProp } from "../../core/renderElement.tsx";
3
+ export interface FieldLabelProps extends JSX.HTMLAttributes<HTMLElement> {
4
+ render?: RenderProp;
5
+ }
6
+ /**
7
+ * The control's label: a `<label>` whose `for` is the control's `id`, which
8
+ * the Root generates, so the server HTML is labelled before hydration.
9
+ * Place it inside `Field.Root`.
10
+ */
11
+ export declare function FieldLabel(props: FieldLabelProps): JSX.Element;
@@ -0,0 +1,19 @@
1
+ import { merge, omit } from "solid-js";
2
+ import { mergeElementProps } from "../../core/mergeElementProps.js";
3
+ import { renderElement } from "../../core/renderElement.jsx";
4
+ import { useFieldRootContext } from "../root/FieldRootContext.js";
5
+ /**
6
+ * The control's label: a `<label>` whose `for` is the control's `id`, which
7
+ * the Root generates, so the server HTML is labelled before hydration.
8
+ * Place it inside `Field.Root`.
9
+ */
10
+ export function FieldLabel(props) {
11
+ const root = useFieldRootContext();
12
+ // `for` is a label's attribute, which `ElementProps`, typed for any
13
+ // element, does not list.
14
+ const ownProps = merge(root.attributes, {
15
+ for: root.controlId,
16
+ });
17
+ const elementProps = mergeElementProps(ownProps, omit(props, "render"));
18
+ return renderElement(props, elementProps, (p) => <label {...p}/>);
19
+ }
@@ -0,0 +1,25 @@
1
+ import type { JSX } from "@solidjs/web";
2
+ import type { RenderProp } from "../../core/renderElement.tsx";
3
+ export interface FieldRootProps extends JSX.HTMLAttributes<HTMLElement> {
4
+ /** The control's `name`, which the form submits it under. */
5
+ name?: string;
6
+ /** Whether the control is disabled. Every part gets `data-disabled`. */
7
+ disabled?: boolean;
8
+ /**
9
+ * Whether the field is invalid, from outside: a schema, a server's
10
+ * answer, the app's own form state. Shown once the field is touched.
11
+ */
12
+ invalid?: boolean;
13
+ /**
14
+ * The error message from outside, which makes the field invalid. An Error
15
+ * without children shows it, over the browser's message.
16
+ */
17
+ error?: string;
18
+ render?: RenderProp;
19
+ }
20
+ /**
21
+ * The field: a `<div>` that holds a control's label, description and error,
22
+ * and its validity. It generates the control's `id` and the Description's,
23
+ * and tracks whether the field was touched.
24
+ */
25
+ export declare function FieldRoot(props: FieldRootProps): JSX.Element;
@@ -0,0 +1,133 @@
1
+ import { createSignal, createUniqueId, merge, omit, onFlush, onSettled, } from "solid-js";
2
+ import { mergeElementProps } from "../../core/mergeElementProps.js";
3
+ import { renderElement } from "../../core/renderElement.jsx";
4
+ import { FieldRootContext } from "./FieldRootContext.js";
5
+ const controlSelector = "input,select,textarea";
6
+ /**
7
+ * The field: a `<div>` that holds a control's label, description and error,
8
+ * and its validity. It generates the control's `id` and the Description's,
9
+ * and tracks whether the field was touched.
10
+ */
11
+ export function FieldRoot(props) {
12
+ const controlId = createUniqueId();
13
+ const descriptionId = createUniqueId();
14
+ const [touched, setTouched] = createSignal(false);
15
+ // The first control inside the Root that the browser finds invalid. Set
16
+ // again on each event, even to the same element, whose message may have
17
+ // changed.
18
+ const [invalidControl, setInvalidControl] = createSignal(undefined, { equals: false });
19
+ // False in the server HTML and the first render, when the control names
20
+ // the Description before it is rendered (README, "Decisions").
21
+ const [settled, setSettled] = createSignal(false);
22
+ const [descriptions, setDescriptions] = createSignal(0);
23
+ const [errors, setErrors] = createSignal([]);
24
+ let root;
25
+ const readValidity = () => {
26
+ if (!root)
27
+ return undefined;
28
+ for (const control of root.querySelectorAll(controlSelector)) {
29
+ if (control.willValidate && !control.validity.valid)
30
+ return control;
31
+ }
32
+ return undefined;
33
+ };
34
+ // Reads the controls' validity again, and sets touched if given. The
35
+ // Field's own state is written after the event's flush, so async work the
36
+ // event starts does not hold it (PLAN.md section 8, "API conventions").
37
+ // By then a form reset has reset the controls too.
38
+ const update = (touch) => onFlush(() => {
39
+ setInvalidControl(readValidity());
40
+ if (touch !== undefined)
41
+ setTouched(touch);
42
+ });
43
+ const invalid = () => !!props.invalid || !!props.error || invalidControl() !== undefined;
44
+ const showsError = () => touched() && invalid();
45
+ const attributes = {
46
+ get "data-invalid"() {
47
+ return showsError() ? "" : undefined;
48
+ },
49
+ get "data-touched"() {
50
+ return touched() ? "" : undefined;
51
+ },
52
+ get "data-disabled"() {
53
+ return props.disabled ? "" : undefined;
54
+ },
55
+ };
56
+ const context = {
57
+ controlId,
58
+ descriptionId,
59
+ name: () => props.name,
60
+ disabled: () => props.disabled,
61
+ showsError,
62
+ message: () => props.error || invalidControl()?.validationMessage,
63
+ validity: () => invalidControl()?.validity,
64
+ describedBy() {
65
+ const ids = [];
66
+ if (!settled() || descriptions() > 0)
67
+ ids.push(descriptionId);
68
+ for (const error of errors()) {
69
+ const id = error.shown() && error.id();
70
+ if (id)
71
+ ids.push(id);
72
+ }
73
+ return ids.join(" ") || undefined;
74
+ },
75
+ registerDescription() {
76
+ setDescriptions((count) => count + 1);
77
+ return () => setDescriptions((count) => count - 1);
78
+ },
79
+ registerError(entry) {
80
+ setErrors((list) => [...list, entry]);
81
+ return () => setErrors((list) => list.filter((e) => e !== entry));
82
+ },
83
+ attributes,
84
+ };
85
+ // A submission attempt, or a control found invalid: `invalid` does not
86
+ // bubble, so the Root and the form listen in the capture phase.
87
+ const touch = () => update(true);
88
+ onSettled(() => {
89
+ setSettled(true);
90
+ // A submission attempt touches every Field of the form, by its submit
91
+ // event or an `invalid` event of any control in it, and a reset clears
92
+ // it.
93
+ const form = root?.querySelector(controlSelector)?.form ??
94
+ root?.closest("form");
95
+ if (!form)
96
+ return;
97
+ // A reset the app cancels, after this listener, keeps it touched.
98
+ const onReset = (event) => onFlush(() => {
99
+ if (!event.defaultPrevented)
100
+ update(false);
101
+ });
102
+ form.addEventListener("submit", touch);
103
+ form.addEventListener("invalid", touch, true);
104
+ form.addEventListener("reset", onReset);
105
+ return () => {
106
+ form.removeEventListener("submit", touch);
107
+ form.removeEventListener("invalid", touch, true);
108
+ form.removeEventListener("reset", onReset);
109
+ };
110
+ });
111
+ const ownProps = merge(attributes, {
112
+ onFocusOut: (event) => {
113
+ const to = event.relatedTarget;
114
+ // Focus moving to nothing while the control keeps it is the window
115
+ // losing focus, to another window or tab, not the user leaving the
116
+ // field; a press on the page moves focus to the body.
117
+ const left = to
118
+ ? !root?.contains(to)
119
+ : document.activeElement !== event.target;
120
+ update(left || undefined);
121
+ },
122
+ onChange: touch,
123
+ onInput: () => update(),
124
+ ref: (element) => {
125
+ root = element;
126
+ element.addEventListener("invalid", touch, true);
127
+ },
128
+ });
129
+ const elementProps = mergeElementProps(ownProps, omit(props, "render", "name", "disabled", "invalid", "error"));
130
+ return (<FieldRootContext value={context}>
131
+ {renderElement(props, elementProps, (p) => (<div {...p}/>))}
132
+ </FieldRootContext>);
133
+ }
@@ -0,0 +1,50 @@
1
+ /**
2
+ * The field's state as `data-*` attributes, each `""` when it applies and
3
+ * absent otherwise. Every part merges the same object, so its getters are
4
+ * read where each element uses them.
5
+ */
6
+ export type FieldStateAttributes = {
7
+ readonly "data-invalid": "" | undefined;
8
+ readonly "data-touched": "" | undefined;
9
+ readonly "data-disabled": "" | undefined;
10
+ };
11
+ /** An Error part, as it registers with the Root once mounted. */
12
+ export interface FieldErrorEntry {
13
+ /** Its `id`, which the control names while it is rendered. */
14
+ id(): string | false;
15
+ /** Whether it is rendered. */
16
+ shown(): boolean;
17
+ }
18
+ /** What the Root shares with its parts. */
19
+ export interface FieldRootContextValue {
20
+ /** The control's `id`, generated by the Root. */
21
+ readonly controlId: string;
22
+ /** The Description's `id`, generated by the Root. */
23
+ readonly descriptionId: string;
24
+ /** The field's `name`, for the control. */
25
+ name(): string | undefined;
26
+ /** Whether the field is disabled, for the control. */
27
+ disabled(): boolean | undefined;
28
+ /** Whether the field shows an error: invalid, and touched. */
29
+ showsError(): boolean;
30
+ /** The message an Error without children shows. */
31
+ message(): string | undefined;
32
+ /** The browser's validity of the first invalid control, if any. */
33
+ validity(): ValidityState | undefined;
34
+ /** The `id`s the control names in `aria-describedby`, if any. */
35
+ describedBy(): string | undefined;
36
+ /**
37
+ * Counts a mounted Description, so the control names it. Returns what
38
+ * uncounts it, for the Description's disposal.
39
+ */
40
+ registerDescription(): () => void;
41
+ /**
42
+ * Registers a mounted Error. Returns what unregisters it, for the
43
+ * Error's disposal.
44
+ */
45
+ registerError(entry: FieldErrorEntry): () => void;
46
+ /** The `data-*` attributes every part carries. */
47
+ readonly attributes: FieldStateAttributes;
48
+ }
49
+ export declare const FieldRootContext: import("solid-js").Context<FieldRootContextValue | null>;
50
+ export declare function useFieldRootContext(): FieldRootContextValue;
@@ -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 FieldRootContext = createContext(null);
6
+ export function useFieldRootContext() {
7
+ const context = useContext(FieldRootContext);
8
+ // Production builds drop the check, and its message, with `isDev`.
9
+ if (isDev && !context) {
10
+ throw new Error("[menhir] Field parts must be placed within <Field.Root>.");
11
+ }
12
+ return context;
13
+ }
@@ -0,0 +1 @@
1
+ export * as Input from "./index.parts.ts";
@@ -0,0 +1 @@
1
+ export * as Input from "./index.parts.js";
@@ -0,0 +1 @@
1
+ export { InputRoot as Root } from "./root/InputRoot.tsx";
@@ -0,0 +1 @@
1
+ export { InputRoot as Root } from "./root/InputRoot.jsx";
@@ -0,0 +1,29 @@
1
+ import type { JSX } from "@solidjs/web";
2
+ import type { RenderProp } from "../../core/renderElement.tsx";
3
+ /** Why the text changed. */
4
+ export type InputValueChangeReason = "input-change" | "reset";
5
+ /** The second argument of `onValueChange`. */
6
+ export interface InputValueChangeDetails {
7
+ readonly reason: InputValueChangeReason;
8
+ /** The `input` event of an edit, or the form's `reset` event. */
9
+ readonly event: Event;
10
+ }
11
+ export interface InputRootProps extends Omit<JSX.InputHTMLAttributes<HTMLInputElement>, "ref" | "value" | "defaultValue"> {
12
+ /** Typed for any element, since `render` may render a `<textarea>`. */
13
+ ref?: JSX.Ref<HTMLElement>;
14
+ /** The text, when controlled. */
15
+ value?: string;
16
+ /** The text to start with when uncontrolled, and the text a form reset puts back. */
17
+ defaultValue?: string;
18
+ /**
19
+ * Called with the new text, and why, on each edit and on a form reset.
20
+ */
21
+ onValueChange?: (value: string, details: InputValueChangeDetails) => void;
22
+ /** Renders the input as another element or component, such as a `<textarea>`. Read once. */
23
+ render?: RenderProp;
24
+ }
25
+ /**
26
+ * A text input: a native `<input>`, or what `render` renders. Name it with a
27
+ * `<label>`, or place it in `Field.Control`'s `render`.
28
+ */
29
+ export declare function InputRoot(props: InputRootProps): JSX.Element;
@@ -0,0 +1,67 @@
1
+ import { merge, omit, onFlush, onSettled, untrack } from "solid-js";
2
+ import { mergeElementProps } from "../../core/mergeElementProps.js";
3
+ import { renderElement } from "../../core/renderElement.jsx";
4
+ /**
5
+ * A text input: a native `<input>`, or what `render` renders. Name it with a
6
+ * `<label>`, or place it in `Field.Control`'s `render`.
7
+ */
8
+ export function InputRoot(props) {
9
+ // An `<input>`, or a `<textarea>` rendered through `render`.
10
+ let element;
11
+ // Puts the element back to a controlled `value` once the consumer has
12
+ // had its say: Solid writes `value` only when it changes, so a declined
13
+ // edit would stay. Only when the two differ, since a write moves the
14
+ // caret to the end.
15
+ const restoreValue = () => {
16
+ const value = untrack(() => props.value);
17
+ if (element && value !== undefined && element.value !== value) {
18
+ element.value = value;
19
+ }
20
+ };
21
+ // A form reset puts a control back to its default, and so it does an
22
+ // Input: through `onValueChange`, so that a controlled one asks.
23
+ onSettled(() => {
24
+ const form = element?.form;
25
+ if (!form)
26
+ return;
27
+ const onReset = (event) => {
28
+ const text = element.value;
29
+ const defaultText = untrack(() => props.defaultValue) ?? "";
30
+ // The browser resets the element to its `value` attribute after this
31
+ // event. A controlled Input keeps its text through it, by making that
32
+ // its attribute, so that the element never shows a text its consumer
33
+ // does not hold; its consumer then decides.
34
+ if (untrack(() => props.value) !== undefined) {
35
+ element.defaultValue = text;
36
+ }
37
+ // In a task of its own, not `onFlush`: when the user presses a reset
38
+ // button, the browser runs microtasks as each listener returns,
39
+ // before later listeners could cancel the reset.
40
+ setTimeout(() => {
41
+ if (event.defaultPrevented || text === defaultText)
42
+ return;
43
+ props.onValueChange?.(defaultText, { reason: "reset", event });
44
+ onFlush(restoreValue);
45
+ });
46
+ };
47
+ form.addEventListener("reset", onReset);
48
+ return () => form.removeEventListener("reset", onReset);
49
+ });
50
+ const ownProps = {
51
+ onInput: (event) => {
52
+ props.onValueChange?.(element.value, { reason: "input-change", event });
53
+ // A write while an input method composes would end the composition.
54
+ if (!event.isComposing)
55
+ onFlush(restoreValue);
56
+ },
57
+ onCompositionEnd: () => onFlush(restoreValue),
58
+ ref: (el) => {
59
+ element = el;
60
+ },
61
+ };
62
+ const elementProps = merge(mergeElementProps(ownProps, omit(props, "render", "value", "onValueChange")),
63
+ // Solid writes `""` for a `value` of `undefined`, which would hide
64
+ // `defaultValue`: the key is there only while controlled.
65
+ () => (props.value === undefined ? {} : { value: props.value }));
66
+ return renderElement(props, elementProps, (p) => <input {...p}/>);
67
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "menhir",
3
- "version": "0.1.7",
3
+ "version": "0.1.9",
4
4
  "description": "Unstyled, accessible UI primitives for SolidJS 2.0, with small and measurable bundles",
5
5
  "keywords": [
6
6
  "solid",
@@ -74,6 +74,16 @@
74
74
  "solid": "./dist/source/dialog/index.js",
75
75
  "import": "./dist/dialog/index.js"
76
76
  },
77
+ "./field": {
78
+ "types": "./dist/source/field/index.d.ts",
79
+ "solid": "./dist/source/field/index.js",
80
+ "import": "./dist/field/index.js"
81
+ },
82
+ "./input": {
83
+ "types": "./dist/source/input/index.d.ts",
84
+ "solid": "./dist/source/input/index.js",
85
+ "import": "./dist/input/index.js"
86
+ },
77
87
  "./menu": {
78
88
  "types": "./dist/source/menu/index.d.ts",
79
89
  "solid": "./dist/source/menu/index.js",