@humanonlyweb/ui 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (144) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +45 -2
  3. package/dist/components/accordion/Accordion.js +60 -0
  4. package/dist/components/accordion/Accordion.vue.d.ts +28 -0
  5. package/dist/components/accordion/AccordionItem.js +102 -0
  6. package/dist/components/accordion/AccordionItem.vue.d.ts +33 -0
  7. package/dist/components/avatar/Avatar.js +52 -0
  8. package/dist/components/avatar/Avatar.vue.d.ts +26 -0
  9. package/dist/components/avatar/AvatarGroup.js +48 -0
  10. package/dist/components/avatar/AvatarGroup.vue.d.ts +16 -0
  11. package/dist/components/button/Button.js +95 -0
  12. package/dist/components/button/Button.vue.d.ts +74 -0
  13. package/dist/components/button/IconButton.js +47 -0
  14. package/dist/components/button/IconButton.vue.d.ts +115 -0
  15. package/dist/components/checkbox/Checkbox.js +93 -0
  16. package/dist/components/checkbox/Checkbox.vue.d.ts +43 -0
  17. package/dist/components/combobox/Combobox.js +294 -0
  18. package/dist/components/combobox/Combobox.vue.d.ts +80 -0
  19. package/dist/components/context-menu/ContextMenu.js +170 -0
  20. package/dist/components/context-menu/ContextMenu.vue.d.ts +38 -0
  21. package/dist/components/dialog/ConfirmDialog.js +103 -0
  22. package/dist/components/dialog/ConfirmDialog.vue.d.ts +46 -0
  23. package/dist/components/dialog/Dialog.js +160 -0
  24. package/dist/components/dialog/Dialog.vue.d.ts +54 -0
  25. package/dist/components/field/FieldMessage.js +31 -0
  26. package/dist/components/input/Input.js +111 -0
  27. package/dist/components/input/Input.vue.d.ts +50 -0
  28. package/dist/components/kbd/Kbd.js +48 -0
  29. package/dist/components/kbd/Kbd.vue.d.ts +24 -0
  30. package/dist/components/menu/Menu.js +124 -0
  31. package/dist/components/menu/Menu.vue.d.ts +41 -0
  32. package/dist/components/otp-input/OtpInput.js +179 -0
  33. package/dist/components/otp-input/OtpInput.vue.d.ts +48 -0
  34. package/dist/components/popover/Popover.js +83 -0
  35. package/dist/components/popover/Popover.vue.d.ts +37 -0
  36. package/dist/components/radio-group/RadioGroup.js +125 -0
  37. package/dist/components/radio-group/RadioGroup.vue.d.ts +45 -0
  38. package/dist/components/segmented/Segmented.js +110 -0
  39. package/dist/components/segmented/Segmented.vue.d.ts +41 -0
  40. package/dist/components/select/Select.js +231 -0
  41. package/dist/components/select/Select.vue.d.ts +59 -0
  42. package/dist/components/slider/Slider.js +196 -0
  43. package/dist/components/slider/Slider.vue.d.ts +49 -0
  44. package/dist/components/spin-button/SpinButton.js +231 -0
  45. package/dist/components/spin-button/SpinButton.vue.d.ts +48 -0
  46. package/dist/components/split-button/SplitButton.js +69 -0
  47. package/dist/components/split-button/SplitButton.vue.d.ts +38 -0
  48. package/dist/components/switch/Switch.js +95 -0
  49. package/dist/components/switch/Switch.vue.d.ts +42 -0
  50. package/dist/components/table/Table.js +173 -0
  51. package/dist/components/table/Table.vue.d.ts +45 -0
  52. package/dist/components/tabs/Tabs.js +99 -0
  53. package/dist/components/tabs/Tabs.vue.d.ts +39 -0
  54. package/dist/components/textarea/Textarea.js +118 -0
  55. package/dist/components/textarea/Textarea.vue.d.ts +34 -0
  56. package/dist/components/toast/ToastItem.js +91 -0
  57. package/dist/components/toast/ToastItem.vue.d.ts +29 -0
  58. package/dist/components/toast/ToastViewport.js +56 -0
  59. package/dist/components/toast/ToastViewport.vue.d.ts +25 -0
  60. package/dist/components/toolbar/Toolbar.js +91 -0
  61. package/dist/components/toolbar/Toolbar.vue.d.ts +21 -0
  62. package/dist/components/tooltip/Tooltip.js +85 -0
  63. package/dist/components/tooltip/Tooltip.vue.d.ts +25 -0
  64. package/dist/composables/internal/env.js +5 -0
  65. package/dist/composables/internal/is-equal.js +14 -0
  66. package/dist/composables/internal/on-click-outside.js +18 -0
  67. package/dist/composables/internal/standard-schema.d.ts +38 -0
  68. package/dist/composables/internal/use-document-visibility.js +16 -0
  69. package/dist/composables/internal/use-event-listener.js +24 -0
  70. package/dist/composables/internal/use-interval-fn.js +21 -0
  71. package/dist/composables/internal/use-resize-observer.js +21 -0
  72. package/dist/composables/internal/use-timeout-fn.js +25 -0
  73. package/dist/composables/use-accordion.d.ts +9 -0
  74. package/dist/composables/use-accordion.js +10 -0
  75. package/dist/composables/use-combobox.d.ts +44 -0
  76. package/dist/composables/use-combobox.js +185 -0
  77. package/dist/composables/use-field.d.ts +17 -0
  78. package/dist/composables/use-field.js +27 -0
  79. package/dist/composables/use-form.d.ts +44 -0
  80. package/dist/composables/use-form.js +146 -0
  81. package/dist/composables/use-menu.d.ts +26 -0
  82. package/dist/composables/use-menu.js +117 -0
  83. package/dist/composables/use-platform.d.ts +17 -0
  84. package/dist/composables/use-platform.js +126 -0
  85. package/dist/composables/use-popover.d.ts +35 -0
  86. package/dist/composables/use-popover.js +49 -0
  87. package/dist/composables/use-roving-selection.d.ts +22 -0
  88. package/dist/composables/use-roving-selection.js +65 -0
  89. package/dist/composables/use-select.d.ts +31 -0
  90. package/dist/composables/use-select.js +169 -0
  91. package/dist/composables/use-slide-indicator.d.ts +24 -0
  92. package/dist/composables/use-slide-indicator.js +52 -0
  93. package/dist/composables/use-toast.d.ts +23 -0
  94. package/dist/composables/use-toast.js +51 -0
  95. package/dist/config.d.ts +40 -0
  96. package/dist/config.js +35 -0
  97. package/dist/docs/README.md +44 -0
  98. package/dist/docs/changelog.md +14 -0
  99. package/dist/docs/components/accordion.md +100 -0
  100. package/dist/docs/components/avatar-group.md +58 -0
  101. package/dist/docs/components/avatar.md +40 -0
  102. package/dist/docs/components/button.md +109 -0
  103. package/dist/docs/components/checkbox.md +123 -0
  104. package/dist/docs/components/combobox.md +207 -0
  105. package/dist/docs/components/confirm-dialog.md +107 -0
  106. package/dist/docs/components/context-menu.md +98 -0
  107. package/dist/docs/components/dialog.md +127 -0
  108. package/dist/docs/components/icon-button.md +47 -0
  109. package/dist/docs/components/input.md +89 -0
  110. package/dist/docs/components/kbd.md +41 -0
  111. package/dist/docs/components/menu.md +112 -0
  112. package/dist/docs/components/otp-input.md +92 -0
  113. package/dist/docs/components/popover.md +72 -0
  114. package/dist/docs/components/radio-group.md +114 -0
  115. package/dist/docs/components/segmented.md +96 -0
  116. package/dist/docs/components/select.md +129 -0
  117. package/dist/docs/components/slider.md +105 -0
  118. package/dist/docs/components/spin-button.md +73 -0
  119. package/dist/docs/components/split-button.md +64 -0
  120. package/dist/docs/components/switch.md +71 -0
  121. package/dist/docs/components/table.md +241 -0
  122. package/dist/docs/components/tabs.md +106 -0
  123. package/dist/docs/components/textarea.md +46 -0
  124. package/dist/docs/components/toast.md +135 -0
  125. package/dist/docs/components/toolbar.md +71 -0
  126. package/dist/docs/components/tooltip.md +57 -0
  127. package/dist/docs/forms.md +182 -0
  128. package/dist/docs/index.md +11 -0
  129. package/dist/docs/installation.md +73 -0
  130. package/dist/docs/localisation.md +40 -0
  131. package/dist/docs/ssr.md +24 -0
  132. package/dist/docs/styling.md +66 -0
  133. package/dist/index.d.ts +46 -0
  134. package/dist/index.js +44 -0
  135. package/dist/nuxt/module.d.ts +15 -0
  136. package/dist/nuxt/module.js +72 -0
  137. package/dist/nuxt/runtime/plugin.d.ts +4 -0
  138. package/dist/nuxt/runtime/plugin.js +24 -0
  139. package/dist/package.js +4 -0
  140. package/dist/styles/core.css +284 -0
  141. package/dist/translations.d.ts +71 -0
  142. package/dist/translations.js +55 -0
  143. package/dist/types.d.ts +61 -0
  144. package/package.json +93 -4
@@ -0,0 +1,10 @@
1
+ import { inject } from "vue";
2
+ //#region src/composables/use-accordion.ts
3
+ const ACCORDION_KEY = Symbol("humanonlyweb-ui-accordion");
4
+ function useAccordionItem() {
5
+ const context = inject(ACCORDION_KEY, null);
6
+ if (!context) throw new Error("[@humanonlyweb/ui] <AccordionItem> must be inside <Accordion>.");
7
+ return context;
8
+ }
9
+ //#endregion
10
+ export { ACCORDION_KEY, useAccordionItem };
@@ -0,0 +1,44 @@
1
+ import { SelectOption, SelectValue } from "../types.js";
2
+ import { Ref } from "vue";
3
+ //#region src/composables/use-combobox.d.ts
4
+ export type ComboboxFilter<T extends SelectValue> = (option: SelectOption<T>, query: string) => boolean;
5
+ interface UseComboboxOptions<T extends SelectValue> {
6
+ options: () => SelectOption<T>[];
7
+ model: Ref<T | T[] | undefined>;
8
+ query: Ref<string>;
9
+ multiple: () => boolean;
10
+ disabled: () => boolean;
11
+ /** Custom match; without one, labels are ranked exact, prefix, then substring. */
12
+ filter: () => ComboboxFilter<T> | undefined;
13
+ /** Show `options` as given, e.g. when they come from a search request. */
14
+ ignoreFilter: () => boolean;
15
+ creatable: () => boolean;
16
+ onCreate: (query: string) => void;
17
+ baseId: () => string;
18
+ input: Readonly<Ref<HTMLInputElement | null>>;
19
+ control: Readonly<Ref<HTMLElement | null>>;
20
+ listbox: Readonly<Ref<HTMLElement | null>>;
21
+ }
22
+ /**
23
+ * APG editable combobox with list autocomplete: typing filters, focus stays in the
24
+ * input, and the active option is conveyed with `aria-activedescendant`.
25
+ */
26
+ export declare function useCombobox<T extends SelectValue>({ options, model, query, multiple, disabled, filter, ignoreFilter, creatable, onCreate, baseId, input, control, listbox }: UseComboboxOptions<T>): {
27
+ isOpen: Ref<boolean, boolean>;
28
+ activeIndex: Ref<number, number>;
29
+ activeId: import("vue").ComputedRef<string | undefined>;
30
+ optionId: (index: number) => string;
31
+ results: import("vue").ComputedRef<SelectOption<T>[]>;
32
+ selectedOptions: import("vue").ComputedRef<SelectOption<T>[]>;
33
+ isSelected: (value: T) => boolean;
34
+ canCreate: import("vue").ComputedRef<boolean>;
35
+ open: () => void;
36
+ close: () => void;
37
+ setActive: (index: number) => void;
38
+ selectOption: (option: SelectOption<T>) => void;
39
+ remove: (value: T) => void;
40
+ onInput: () => void;
41
+ onKeydown: (event: KeyboardEvent) => void;
42
+ };
43
+ //#endregion
44
+ export {};
@@ -0,0 +1,185 @@
1
+ import { onClickOutside } from "./internal/on-click-outside.js";
2
+ import { computed, nextTick, ref, watch } from "vue";
3
+ //#region src/composables/use-combobox.ts
4
+ function rank(label, query) {
5
+ const text = label.toLowerCase();
6
+ if (text === query) return 0;
7
+ if (text.startsWith(query)) return 1;
8
+ if (text.includes(query)) return 2;
9
+ return -1;
10
+ }
11
+ /**
12
+ * APG editable combobox with list autocomplete: typing filters, focus stays in the
13
+ * input, and the active option is conveyed with `aria-activedescendant`.
14
+ */
15
+ function useCombobox({ options, model, query, multiple, disabled, filter, ignoreFilter, creatable, onCreate, baseId, input, control, listbox }) {
16
+ const isOpen = ref(false);
17
+ const activeIndex = ref(-1);
18
+ const selectedValues = computed(() => {
19
+ const value = model.value;
20
+ if (multiple()) return Array.isArray(value) ? value : [];
21
+ if (value == null || Array.isArray(value)) return [];
22
+ return [value];
23
+ });
24
+ const isSelected = (value) => selectedValues.value.includes(value);
25
+ const selectedOptions = computed(() => selectedValues.value.map((value) => options().find((o) => o.value === value)).filter((o) => Boolean(o)));
26
+ const selectedLabel = () => multiple() ? "" : selectedOptions.value[0]?.label ?? "";
27
+ const searchTerm = computed(() => {
28
+ const term = query.value.trim().toLowerCase();
29
+ return !multiple() && query.value === selectedLabel() ? "" : term;
30
+ });
31
+ const results = computed(() => {
32
+ const term = searchTerm.value;
33
+ const custom = filter();
34
+ if (!term || ignoreFilter()) return options();
35
+ if (custom) return options().filter((option) => custom(option, term));
36
+ return options().map((option) => ({
37
+ option,
38
+ score: rank(option.label, term)
39
+ })).filter((entry) => entry.score >= 0).toSorted((a, b) => a.score - b.score).map((entry) => entry.option);
40
+ });
41
+ const optionId = (index) => `${baseId()}-opt-${index}`;
42
+ const activeId = computed(() => isOpen.value && activeIndex.value >= 0 && activeIndex.value < results.value.length ? optionId(activeIndex.value) : void 0);
43
+ /** Whether Enter would offer to create the typed value. */
44
+ const canCreate = computed(() => {
45
+ const term = query.value.trim();
46
+ if (!creatable() || !term) return false;
47
+ return !options().some((o) => o.label.toLowerCase() === term.toLowerCase());
48
+ });
49
+ function enabledFrom(start, dir) {
50
+ const list = results.value;
51
+ for (let i = start; i >= 0 && i < list.length; i += dir) if (!list[i]?.disabled) return i;
52
+ return -1;
53
+ }
54
+ async function scrollActiveIntoView() {
55
+ if (activeIndex.value < 0) return;
56
+ await nextTick();
57
+ listbox.value?.querySelector(`#${CSS.escape(optionId(activeIndex.value))}`)?.scrollIntoView({ block: "nearest" });
58
+ }
59
+ function setActive(index) {
60
+ if (index === activeIndex.value) return;
61
+ activeIndex.value = index;
62
+ scrollActiveIntoView();
63
+ }
64
+ function open() {
65
+ if (disabled() || isOpen.value) return;
66
+ isOpen.value = true;
67
+ const selected = results.value.findIndex((o) => isSelected(o.value));
68
+ setActive(selected >= 0 ? selected : enabledFrom(0, 1));
69
+ }
70
+ function close() {
71
+ if (!isOpen.value) return;
72
+ isOpen.value = false;
73
+ activeIndex.value = -1;
74
+ if (!multiple()) query.value = selectedLabel();
75
+ }
76
+ function selectOption(option) {
77
+ if (option.disabled) return;
78
+ if (multiple()) {
79
+ const current = selectedValues.value;
80
+ model.value = current.includes(option.value) ? current.filter((v) => v !== option.value) : [...current, option.value];
81
+ query.value = "";
82
+ input.value?.focus();
83
+ return;
84
+ }
85
+ model.value = option.value;
86
+ query.value = option.label;
87
+ isOpen.value = false;
88
+ activeIndex.value = -1;
89
+ }
90
+ function remove(value) {
91
+ if (!multiple() || disabled()) return;
92
+ model.value = selectedValues.value.filter((v) => v !== value);
93
+ input.value?.focus();
94
+ }
95
+ function move(dir) {
96
+ if (!isOpen.value) {
97
+ open();
98
+ return;
99
+ }
100
+ const length = results.value.length;
101
+ const next = enabledFrom(activeIndex.value < 0 ? dir === 1 ? -1 : length : activeIndex.value + dir, dir);
102
+ setActive(next >= 0 ? next : enabledFrom(dir === 1 ? 0 : length - 1, dir));
103
+ }
104
+ function onInput() {
105
+ if (!isOpen.value) open();
106
+ nextTick(() => setActive(enabledFrom(0, 1)));
107
+ }
108
+ function onKeydown(event) {
109
+ if (disabled()) return;
110
+ switch (event.key) {
111
+ case "ArrowDown":
112
+ event.preventDefault();
113
+ if (event.altKey) open();
114
+ else move(1);
115
+ break;
116
+ case "ArrowUp":
117
+ event.preventDefault();
118
+ move(-1);
119
+ break;
120
+ case "Enter": {
121
+ const option = results.value[activeIndex.value];
122
+ if (isOpen.value && option) {
123
+ event.preventDefault();
124
+ selectOption(option);
125
+ } else if (canCreate.value) {
126
+ event.preventDefault();
127
+ onCreate(query.value.trim());
128
+ if (multiple()) query.value = "";
129
+ }
130
+ break;
131
+ }
132
+ case "Escape":
133
+ if (isOpen.value) {
134
+ event.preventDefault();
135
+ close();
136
+ } else if (query.value) {
137
+ event.preventDefault();
138
+ query.value = "";
139
+ if (!multiple()) model.value = void 0;
140
+ }
141
+ break;
142
+ case "Backspace":
143
+ if (multiple() && !query.value && selectedValues.value.length) remove(selectedValues.value.at(-1));
144
+ break;
145
+ case "Tab": close();
146
+ }
147
+ }
148
+ watch(() => results.value.length, (length) => {
149
+ if (activeIndex.value >= length) activeIndex.value = enabledFrom(0, 1);
150
+ });
151
+ if (!multiple() && !query.value) query.value = selectedLabel();
152
+ watch(selectedLabel, (label) => {
153
+ if (!multiple() && !isOpen.value) query.value = label;
154
+ });
155
+ watch(isOpen, (opened) => {
156
+ const el = listbox.value;
157
+ if (!el?.isConnected) return;
158
+ const shown = el.matches(":popover-open");
159
+ if (opened && !shown) el.showPopover();
160
+ else if (!opened && shown) el.hidePopover();
161
+ }, { flush: "post" });
162
+ onClickOutside(control, () => close(), {
163
+ ignore: [listbox],
164
+ active: () => isOpen.value
165
+ });
166
+ return {
167
+ isOpen,
168
+ activeIndex,
169
+ activeId,
170
+ optionId,
171
+ results,
172
+ selectedOptions,
173
+ isSelected,
174
+ canCreate,
175
+ open,
176
+ close,
177
+ setActive,
178
+ selectOption,
179
+ remove,
180
+ onInput,
181
+ onKeydown
182
+ };
183
+ }
184
+ //#endregion
185
+ export { useCombobox };
@@ -0,0 +1,17 @@
1
+ import { MaybeRefOrGetter } from "vue";
2
+ //#region src/composables/use-field.d.ts
3
+ export interface FieldSource {
4
+ id: MaybeRefOrGetter<string | undefined>;
5
+ hint: MaybeRefOrGetter<string | undefined>;
6
+ error: MaybeRefOrGetter<string | boolean | undefined>;
7
+ }
8
+ /** Ids and ARIA wiring shared by every labelled form control. */
9
+ export declare function useField(source: FieldSource): {
10
+ id: import("vue").ComputedRef<string>;
11
+ hintId: import("vue").ComputedRef<string>;
12
+ errorId: import("vue").ComputedRef<string>;
13
+ isError: import("vue").ComputedRef<boolean>;
14
+ errorMessage: import("vue").ComputedRef<string | undefined>;
15
+ describedBy: import("vue").ComputedRef<string | undefined>;
16
+ };
17
+ //#endregion
@@ -0,0 +1,27 @@
1
+ import { computed, toValue, useId } from "vue";
2
+ //#region src/composables/use-field.ts
3
+ /** Ids and ARIA wiring shared by every labelled form control. */
4
+ function useField(source) {
5
+ const uid = useId();
6
+ const id = computed(() => toValue(source.id) ?? uid);
7
+ const hintId = computed(() => `${id.value}-hint`);
8
+ const errorId = computed(() => `${id.value}-error`);
9
+ const isError = computed(() => Boolean(toValue(source.error)));
10
+ const errorMessage = computed(() => {
11
+ const error = toValue(source.error);
12
+ return typeof error === "string" ? error : void 0;
13
+ });
14
+ return {
15
+ id,
16
+ hintId,
17
+ errorId,
18
+ isError,
19
+ errorMessage,
20
+ describedBy: computed(() => {
21
+ if (errorMessage.value) return errorId.value;
22
+ if (toValue(source.hint)) return hintId.value;
23
+ })
24
+ };
25
+ }
26
+ //#endregion
27
+ export { useField };
@@ -0,0 +1,44 @@
1
+ import { StandardSchemaV1 } from "./internal/standard-schema.js";
2
+ import { Ref } from "vue";
3
+ //#region src/composables/use-form.d.ts
4
+ /** Any object shape, including `interface`s (which aren't assignable to `Record`). */
5
+ export type FormValues = object;
6
+ /**
7
+ * Errors keyed by field path: top-level fields by name (`"email"`), nested ones
8
+ * dot-joined (`"address.city"`). Inputs are matched by their `name` attribute.
9
+ */
10
+ export type FormErrors = Partial<Record<string, string>>;
11
+ type Input<S extends StandardSchemaV1> = StandardSchemaV1.InferInput<S> & FormValues;
12
+ type Output<S extends StandardSchemaV1> = StandardSchemaV1.InferOutput<S>;
13
+ export interface UseFormOptions<S extends StandardSchemaV1> {
14
+ /** Any Standard Schema validator: zod 4, valibot, arktype, … */
15
+ schema: S;
16
+ initialValues: Input<S>;
17
+ onSubmit: (values: Output<S>) => void | Promise<void>;
18
+ /**
19
+ * Turns a thrown submit error into field errors (e.g. a 422 from the API). Return
20
+ * `undefined` for errors that aren't about fields.
21
+ */
22
+ mapError?: (error: unknown) => FormErrors | undefined;
23
+ /** Called with any error `onSubmit` throws. Without it, non-field errors rethrow. */
24
+ onError?: (error: unknown) => void;
25
+ /** The `<form>` element; enables blur/input tracking and focusing the first invalid field. */
26
+ formRef?: Readonly<Ref<HTMLElement | null>>;
27
+ /** When a field's error becomes visible. Every error shows after the first submit. */
28
+ validateOn?: "blur" | "input" | "submit";
29
+ }
30
+ export declare function useForm<S extends StandardSchemaV1>({ schema, initialValues, onSubmit, mapError, onError, formRef, validateOn }: UseFormOptions<S>): {
31
+ form: import("vue").Reactive<Input<S>>;
32
+ errors: import("vue").ComputedRef<Partial<Record<string, string>>>;
33
+ processing: Ref<boolean, boolean>;
34
+ validating: Ref<boolean, boolean>;
35
+ isValid: import("vue").ComputedRef<boolean>;
36
+ isDirty: import("vue").ComputedRef<boolean>;
37
+ submit: (event?: Event) => Promise<void>;
38
+ reset: () => void;
39
+ touch: (field: string) => void;
40
+ setErrors: (fields: FormErrors) => void;
41
+ setValues: (values: Partial<Input<S>>) => void;
42
+ };
43
+ //#endregion
44
+ export type { StandardSchemaV1 };
@@ -0,0 +1,146 @@
1
+ import { useEventListener } from "./internal/use-event-listener.js";
2
+ import { isEqual } from "./internal/is-equal.js";
3
+ import { computed, nextTick, reactive, ref, shallowRef, toRaw, watch } from "vue";
4
+ //#region src/composables/use-form.ts
5
+ const clone = (values) => structuredClone(toRaw(values));
6
+ function pathKey(path) {
7
+ if (!path?.length) return void 0;
8
+ return path.map((segment) => String(typeof segment === "object" ? segment.key : segment)).join(".");
9
+ }
10
+ function issuesToErrors(issues) {
11
+ const errors = {};
12
+ for (const issue of issues) {
13
+ const key = pathKey(issue.path);
14
+ if (key && !(key in errors)) errors[key] = issue.message;
15
+ }
16
+ return errors;
17
+ }
18
+ function fieldNameOf(event) {
19
+ const target = event.target;
20
+ if (!(target instanceof HTMLElement)) return void 0;
21
+ if ((target instanceof HTMLInputElement || target instanceof HTMLTextAreaElement || target instanceof HTMLSelectElement || target instanceof HTMLButtonElement) && target.name) return target.name;
22
+ return target.closest("[data-field-name]")?.dataset.fieldName || void 0;
23
+ }
24
+ function useForm({ schema, initialValues, onSubmit, mapError, onError, formRef, validateOn = "blur" }) {
25
+ const baseline = shallowRef(clone(initialValues));
26
+ const form = reactive(clone(initialValues));
27
+ const touched = reactive(/* @__PURE__ */ new Set());
28
+ const schemaErrors = shallowRef({});
29
+ const serverErrors = shallowRef({});
30
+ const processing = ref(false);
31
+ const submitted = ref(false);
32
+ const validating = ref(false);
33
+ let run = 0;
34
+ async function validate() {
35
+ const current = ++run;
36
+ validating.value = true;
37
+ try {
38
+ const result = await schema["~standard"].validate(clone(form));
39
+ if (current === run) schemaErrors.value = result.issues ? issuesToErrors(result.issues) : {};
40
+ return result;
41
+ } finally {
42
+ if (current === run) validating.value = false;
43
+ }
44
+ }
45
+ watch(form, () => void validate(), {
46
+ deep: true,
47
+ immediate: true
48
+ });
49
+ const errors = computed(() => {
50
+ const visible = {};
51
+ for (const [key, message] of Object.entries(schemaErrors.value)) if (submitted.value || touched.has(key)) visible[key] = message;
52
+ return {
53
+ ...visible,
54
+ ...serverErrors.value
55
+ };
56
+ });
57
+ const isValid = computed(() => Object.keys(schemaErrors.value).length === 0);
58
+ const isDirty = computed(() => !isEqual(form, baseline.value));
59
+ function clearServerError(field) {
60
+ if (!(field in serverErrors.value)) return;
61
+ const { [field]: _removed, ...rest } = serverErrors.value;
62
+ serverErrors.value = rest;
63
+ }
64
+ if (formRef) {
65
+ useEventListener(formRef, "input", (event) => {
66
+ const field = fieldNameOf(event);
67
+ if (!field) return;
68
+ clearServerError(field);
69
+ if (validateOn === "input") touched.add(field);
70
+ });
71
+ if (validateOn === "blur") useEventListener(formRef, "focusout", (event) => {
72
+ const field = fieldNameOf(event);
73
+ if (field) touched.add(field);
74
+ });
75
+ }
76
+ async function focusFirstError() {
77
+ await nextTick();
78
+ formRef?.value?.querySelector("[aria-invalid=\"true\"]")?.focus();
79
+ }
80
+ function setErrors(fields) {
81
+ serverErrors.value = { ...fields };
82
+ submitted.value = true;
83
+ }
84
+ /** Marks a field touched so its error shows, e.g. for custom controls without a `name`. */
85
+ function touch(field) {
86
+ touched.add(field);
87
+ }
88
+ /** Replaces values and makes them the new baseline for `isDirty` and `reset()`. */
89
+ function setValues(values) {
90
+ Object.assign(form, clone(values));
91
+ baseline.value = clone(form);
92
+ touched.clear();
93
+ serverErrors.value = {};
94
+ submitted.value = false;
95
+ }
96
+ function reset() {
97
+ Object.assign(form, clone(baseline.value));
98
+ touched.clear();
99
+ serverErrors.value = {};
100
+ submitted.value = false;
101
+ processing.value = false;
102
+ }
103
+ let submitting = false;
104
+ async function submit(event) {
105
+ event?.preventDefault();
106
+ if (submitting) return;
107
+ submitting = true;
108
+ submitted.value = true;
109
+ serverErrors.value = {};
110
+ try {
111
+ const result = await validate();
112
+ if (result.issues) {
113
+ await focusFirstError();
114
+ return;
115
+ }
116
+ processing.value = true;
117
+ await onSubmit(result.value);
118
+ } catch (error) {
119
+ const fields = mapError?.(error);
120
+ if (fields) {
121
+ setErrors(fields);
122
+ await focusFirstError();
123
+ }
124
+ if (onError) onError(error);
125
+ else if (!fields) throw error;
126
+ } finally {
127
+ processing.value = false;
128
+ submitting = false;
129
+ }
130
+ }
131
+ return {
132
+ form,
133
+ errors,
134
+ processing,
135
+ validating,
136
+ isValid,
137
+ isDirty,
138
+ submit,
139
+ reset,
140
+ touch,
141
+ setErrors,
142
+ setValues
143
+ };
144
+ }
145
+ //#endregion
146
+ export { useForm };
@@ -0,0 +1,26 @@
1
+ import { MenuEntry, MenuSeparator } from "../types.js";
2
+ import { Ref } from "vue";
3
+ //#region src/composables/use-menu.d.ts
4
+ interface UseMenuOptions {
5
+ trigger: () => HTMLElement | null | undefined;
6
+ panel: Readonly<Ref<HTMLElement | null>>;
7
+ open: Ref<boolean>;
8
+ itemCount: () => number;
9
+ /** Disabled items and separators are skipped. */
10
+ isDisabled: (index: number) => boolean;
11
+ /** For typeahead; separators have none. */
12
+ labelAt: (index: number) => string | undefined;
13
+ onActivate: (index: number) => void;
14
+ }
15
+ export declare const isMenuSeparator: (entry: MenuEntry | undefined) => entry is MenuSeparator;
16
+ /** APG menu button: arrow/Home/End navigation, typeahead, focus moves onto items. */
17
+ export declare function useMenu({ trigger, panel, open, itemCount, isDisabled, labelAt, onActivate }: UseMenuOptions): {
18
+ activeIndex: Ref<number, number>;
19
+ setActive: (index: number) => void;
20
+ activate: (index: number) => void;
21
+ close: (refocus?: boolean) => void;
22
+ onTriggerKeydown: (event: KeyboardEvent) => void;
23
+ onMenuKeydown: (event: KeyboardEvent) => void;
24
+ };
25
+ //#endregion
26
+ export {};
@@ -0,0 +1,117 @@
1
+ import { usePopoverState } from "./use-popover.js";
2
+ import { useTimeoutFn } from "./internal/use-timeout-fn.js";
3
+ import { nextTick, ref, watch } from "vue";
4
+ //#region src/composables/use-menu.ts
5
+ const TYPEAHEAD_RESET = 500;
6
+ const isMenuSeparator = (entry) => Boolean(entry && "separator" in entry && entry.separator);
7
+ /** APG menu button: arrow/Home/End navigation, typeahead, focus moves onto items. */
8
+ function useMenu({ trigger, panel, open, itemCount, isDisabled, labelAt, onActivate }) {
9
+ const activeIndex = ref(-1);
10
+ let openEdge = "first";
11
+ function enabledFrom(start, dir) {
12
+ for (let i = start; i >= 0 && i < itemCount(); i += dir) if (!isDisabled(i)) return i;
13
+ return -1;
14
+ }
15
+ const firstEnabled = () => enabledFrom(0, 1);
16
+ const lastEnabled = () => enabledFrom(itemCount() - 1, -1);
17
+ function focusActive() {
18
+ nextTick(() => {
19
+ panel.value?.querySelector(`[data-menu-index="${activeIndex.value}"]`)?.focus();
20
+ });
21
+ }
22
+ usePopoverState({
23
+ panel,
24
+ open,
25
+ onShow: () => {
26
+ activeIndex.value = openEdge === "last" ? lastEnabled() : firstEnabled();
27
+ openEdge = "first";
28
+ focusActive();
29
+ },
30
+ onHide: () => {
31
+ activeIndex.value = -1;
32
+ }
33
+ });
34
+ function show(edge = "first") {
35
+ if (!itemCount()) return;
36
+ openEdge = edge;
37
+ open.value = true;
38
+ }
39
+ function close(refocus = true) {
40
+ open.value = false;
41
+ if (refocus) trigger()?.focus();
42
+ }
43
+ function setActive(index) {
44
+ if (index < 0) return;
45
+ activeIndex.value = index;
46
+ focusActive();
47
+ }
48
+ function move(dir) {
49
+ const next = enabledFrom(activeIndex.value < 0 ? dir === 1 ? -1 : itemCount() : activeIndex.value + dir, dir);
50
+ setActive(next >= 0 ? next : dir === 1 ? firstEnabled() : lastEnabled());
51
+ }
52
+ function activate(index) {
53
+ if (index < 0 || isDisabled(index)) return;
54
+ onActivate(index);
55
+ close();
56
+ }
57
+ function onTriggerKeydown(event) {
58
+ if (event.key !== "ArrowDown" && event.key !== "ArrowUp") return;
59
+ event.preventDefault();
60
+ const up = event.key === "ArrowUp";
61
+ if (open.value) move(up ? -1 : 1);
62
+ else show(up ? "last" : "first");
63
+ }
64
+ let typeahead = "";
65
+ const resetTypeahead = useTimeoutFn(() => typeahead = "", TYPEAHEAD_RESET);
66
+ function onType(char) {
67
+ typeahead += char.toLowerCase();
68
+ resetTypeahead.start();
69
+ const count = itemCount();
70
+ const single = typeahead.length > 1 && typeahead.replaceAll(typeahead[0], "") === "";
71
+ const needle = single ? typeahead[0] : typeahead;
72
+ const start = single ? activeIndex.value : activeIndex.value - 1;
73
+ for (let step = 1; step <= count; step++) {
74
+ const i = ((start + step) % count + count) % count;
75
+ if (!isDisabled(i) && labelAt(i)?.toLowerCase().startsWith(needle)) {
76
+ setActive(i);
77
+ return;
78
+ }
79
+ }
80
+ }
81
+ function onMenuKeydown(event) {
82
+ const actions = {
83
+ ArrowDown: () => move(1),
84
+ ArrowUp: () => move(-1),
85
+ Home: () => setActive(firstEnabled()),
86
+ End: () => setActive(lastEnabled()),
87
+ Escape: () => close()
88
+ };
89
+ if (event.key === "Tab") {
90
+ close(false);
91
+ return;
92
+ }
93
+ const action = actions[event.key];
94
+ if (action) {
95
+ event.preventDefault();
96
+ action();
97
+ return;
98
+ }
99
+ if (event.key.length === 1 && event.key !== " " && !event.metaKey && !event.ctrlKey && !event.altKey) {
100
+ event.preventDefault();
101
+ onType(event.key);
102
+ }
103
+ }
104
+ watch(itemCount, (len) => {
105
+ if (activeIndex.value >= len) activeIndex.value = firstEnabled();
106
+ });
107
+ return {
108
+ activeIndex,
109
+ setActive,
110
+ activate,
111
+ close,
112
+ onTriggerKeydown,
113
+ onMenuKeydown
114
+ };
115
+ }
116
+ //#endregion
117
+ export { isMenuSeparator, useMenu };
@@ -0,0 +1,17 @@
1
+ import { Platform } from "../types.js";
2
+ import { UiTranslations } from "../translations.js";
3
+ import { Ref } from "vue";
4
+ //#region src/composables/use-platform.d.ts
5
+ /** From a user agent or a `Sec-CH-UA-Platform` client hint. */
6
+ export declare function platformFrom(agentOrHint: string | null | undefined): Platform;
7
+ export declare function usePlatform(): Readonly<Ref<Platform>>;
8
+ export interface KeyCap {
9
+ glyph: string;
10
+ label: string;
11
+ }
12
+ /**
13
+ * "mod+shift+k" or "shift enter" → key caps, with `mod` as ⌘ on Apple and Ctrl
14
+ * elsewhere. `names` are the spoken key names, e.g. the app's `keys` translations.
15
+ */
16
+ export declare function parseChord(chord: string, platform: Platform, names?: UiTranslations["keys"]): KeyCap[];
17
+ //#endregion