@aerogel/core 0.0.0-next.a68f133e2c9a1ae9ba84b4e2e42df909289e5fba → 0.0.0-next.abea39863ad0f7c484b8b1f365870e43e9bdd0ba

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 (210) hide show
  1. package/dist/aerogel-core.css +1 -0
  2. package/dist/aerogel-core.d.ts +2197 -1605
  3. package/dist/aerogel-core.js +3575 -0
  4. package/dist/aerogel-core.js.map +1 -0
  5. package/package.json +32 -37
  6. package/src/bootstrap/bootstrap.test.ts +4 -8
  7. package/src/bootstrap/index.ts +26 -16
  8. package/src/bootstrap/options.ts +1 -1
  9. package/src/components/AppLayout.vue +14 -0
  10. package/src/components/{AGAppModals.vue → AppModals.vue} +3 -4
  11. package/src/components/AppOverlays.vue +9 -0
  12. package/src/components/AppToasts.vue +16 -0
  13. package/src/components/contracts/AlertModal.ts +19 -0
  14. package/src/components/contracts/Button.ts +16 -0
  15. package/src/components/contracts/ConfirmModal.ts +48 -0
  16. package/src/components/contracts/DropdownMenu.ts +25 -0
  17. package/src/components/contracts/ErrorReportModal.ts +33 -0
  18. package/src/components/contracts/Input.ts +26 -0
  19. package/src/components/contracts/LoadingModal.ts +26 -0
  20. package/src/components/contracts/Modal.ts +21 -0
  21. package/src/components/contracts/PromptModal.ts +34 -0
  22. package/src/components/contracts/Select.ts +45 -0
  23. package/src/components/contracts/Toast.ts +15 -0
  24. package/src/components/contracts/index.ts +11 -0
  25. package/src/components/headless/HeadlessButton.vue +51 -0
  26. package/src/components/headless/HeadlessInput.vue +59 -0
  27. package/src/components/headless/HeadlessInputDescription.vue +27 -0
  28. package/src/components/headless/{forms/AGHeadlessInputError.vue → HeadlessInputError.vue} +4 -8
  29. package/src/components/headless/HeadlessInputInput.vue +75 -0
  30. package/src/components/headless/{forms/AGHeadlessInputLabel.vue → HeadlessInputLabel.vue} +3 -7
  31. package/src/components/headless/HeadlessInputTextArea.vue +40 -0
  32. package/src/components/headless/HeadlessModal.vue +57 -0
  33. package/src/components/headless/HeadlessModalContent.vue +30 -0
  34. package/src/components/headless/HeadlessModalDescription.vue +12 -0
  35. package/src/components/headless/HeadlessModalOverlay.vue +12 -0
  36. package/src/components/headless/HeadlessModalTitle.vue +12 -0
  37. package/src/components/headless/HeadlessSelect.vue +120 -0
  38. package/src/components/headless/{forms/AGHeadlessSelectError.vue → HeadlessSelectError.vue} +5 -6
  39. package/src/components/headless/HeadlessSelectLabel.vue +25 -0
  40. package/src/components/headless/HeadlessSelectOption.vue +34 -0
  41. package/src/components/headless/HeadlessSelectOptions.vue +42 -0
  42. package/src/components/headless/HeadlessSelectTrigger.vue +22 -0
  43. package/src/components/headless/HeadlessSelectValue.vue +18 -0
  44. package/src/components/headless/HeadlessSwitch.vue +96 -0
  45. package/src/components/headless/HeadlessToast.vue +18 -0
  46. package/src/components/headless/HeadlessToastAction.vue +13 -0
  47. package/src/components/headless/index.ts +20 -3
  48. package/src/components/index.ts +6 -9
  49. package/src/components/ui/AdvancedOptions.vue +18 -0
  50. package/src/components/ui/AlertModal.vue +17 -0
  51. package/src/components/ui/Button.vue +115 -0
  52. package/src/components/ui/Checkbox.vue +56 -0
  53. package/src/components/ui/ConfirmModal.vue +50 -0
  54. package/src/components/ui/DropdownMenu.vue +32 -0
  55. package/src/components/ui/DropdownMenuOption.vue +22 -0
  56. package/src/components/ui/DropdownMenuOptions.vue +44 -0
  57. package/src/components/ui/EditableContent.vue +82 -0
  58. package/src/components/ui/ErrorLogs.vue +19 -0
  59. package/src/components/ui/ErrorLogsModal.vue +48 -0
  60. package/src/components/ui/ErrorMessage.vue +15 -0
  61. package/src/components/ui/ErrorReportModal.vue +73 -0
  62. package/src/components/{modals/AGErrorReportModalButtons.vue → ui/ErrorReportModalButtons.vue} +34 -27
  63. package/src/components/ui/ErrorReportModalTitle.vue +24 -0
  64. package/src/components/ui/Form.vue +24 -0
  65. package/src/components/ui/Input.vue +56 -0
  66. package/src/components/ui/Link.vue +12 -0
  67. package/src/components/ui/LoadingModal.vue +34 -0
  68. package/src/components/ui/Markdown.vue +97 -0
  69. package/src/components/ui/Modal.vue +131 -0
  70. package/src/components/ui/ModalContext.vue +31 -0
  71. package/src/components/ui/ProgressBar.vue +51 -0
  72. package/src/components/ui/PromptModal.vue +38 -0
  73. package/src/components/ui/Select.vue +27 -0
  74. package/src/components/ui/SelectLabel.vue +21 -0
  75. package/src/components/ui/SelectOption.vue +29 -0
  76. package/src/components/ui/SelectOptions.vue +35 -0
  77. package/src/components/ui/SelectTrigger.vue +29 -0
  78. package/src/components/ui/SettingsModal.vue +15 -0
  79. package/src/components/{lib/AGStartupCrash.vue → ui/StartupCrash.vue} +8 -8
  80. package/src/components/ui/Switch.vue +11 -0
  81. package/src/components/ui/Toast.vue +46 -0
  82. package/src/components/ui/index.ts +33 -0
  83. package/src/directives/index.ts +11 -5
  84. package/src/directives/measure.ts +41 -7
  85. package/src/errors/Errors.state.ts +1 -1
  86. package/src/errors/Errors.ts +36 -41
  87. package/src/errors/JobCancelledError.ts +3 -0
  88. package/src/errors/index.ts +16 -8
  89. package/src/errors/settings/Debug.vue +39 -0
  90. package/src/errors/settings/index.ts +10 -0
  91. package/src/errors/utils.ts +35 -0
  92. package/src/forms/FormController.test.ts +110 -0
  93. package/src/forms/FormController.ts +246 -0
  94. package/src/forms/index.ts +3 -2
  95. package/src/forms/utils.ts +51 -20
  96. package/src/forms/validation.ts +19 -0
  97. package/src/index.css +73 -0
  98. package/src/{main.ts → index.ts} +3 -0
  99. package/src/jobs/Job.ts +147 -0
  100. package/src/jobs/index.ts +10 -0
  101. package/src/jobs/listeners.ts +3 -0
  102. package/src/jobs/status.ts +4 -0
  103. package/src/lang/DefaultLangProvider.ts +46 -0
  104. package/src/lang/Lang.state.ts +11 -0
  105. package/src/lang/Lang.ts +43 -28
  106. package/src/lang/index.ts +12 -6
  107. package/src/lang/settings/Language.vue +48 -0
  108. package/src/lang/settings/index.ts +10 -0
  109. package/src/plugins/Plugin.ts +1 -1
  110. package/src/plugins/index.ts +10 -7
  111. package/src/services/App.state.ts +36 -3
  112. package/src/services/App.ts +19 -3
  113. package/src/services/Cache.ts +43 -0
  114. package/src/services/Events.test.ts +39 -0
  115. package/src/services/Events.ts +109 -35
  116. package/src/services/Service.ts +129 -54
  117. package/src/services/Storage.ts +20 -0
  118. package/src/services/index.ts +18 -7
  119. package/src/services/utils.ts +18 -0
  120. package/src/testing/index.ts +30 -0
  121. package/src/testing/setup.ts +11 -0
  122. package/src/ui/UI.state.ts +14 -12
  123. package/src/ui/UI.ts +252 -120
  124. package/src/ui/index.ts +28 -28
  125. package/src/ui/utils.ts +16 -0
  126. package/src/utils/classes.ts +41 -0
  127. package/src/utils/composition/events.ts +4 -6
  128. package/src/utils/composition/forms.ts +20 -4
  129. package/src/utils/composition/persistent.test.ts +33 -0
  130. package/src/utils/composition/persistent.ts +11 -0
  131. package/src/utils/composition/state.test.ts +47 -0
  132. package/src/utils/composition/state.ts +33 -0
  133. package/src/utils/index.ts +5 -1
  134. package/src/utils/markdown.test.ts +50 -0
  135. package/src/utils/markdown.ts +53 -6
  136. package/src/utils/types.ts +3 -0
  137. package/src/utils/vue.ts +38 -132
  138. package/dist/aerogel-core.cjs.js +0 -2
  139. package/dist/aerogel-core.cjs.js.map +0 -1
  140. package/dist/aerogel-core.esm.js +0 -2
  141. package/dist/aerogel-core.esm.js.map +0 -1
  142. package/histoire.config.ts +0 -7
  143. package/noeldemartin.config.js +0 -5
  144. package/postcss.config.js +0 -6
  145. package/src/assets/histoire.css +0 -3
  146. package/src/components/AGAppLayout.vue +0 -16
  147. package/src/components/AGAppOverlays.vue +0 -41
  148. package/src/components/AGAppSnackbars.vue +0 -13
  149. package/src/components/constants.ts +0 -8
  150. package/src/components/forms/AGButton.vue +0 -44
  151. package/src/components/forms/AGCheckbox.vue +0 -41
  152. package/src/components/forms/AGForm.vue +0 -26
  153. package/src/components/forms/AGInput.vue +0 -38
  154. package/src/components/forms/AGSelect.story.vue +0 -46
  155. package/src/components/forms/AGSelect.vue +0 -60
  156. package/src/components/forms/index.ts +0 -5
  157. package/src/components/headless/forms/AGHeadlessButton.vue +0 -51
  158. package/src/components/headless/forms/AGHeadlessInput.ts +0 -28
  159. package/src/components/headless/forms/AGHeadlessInput.vue +0 -57
  160. package/src/components/headless/forms/AGHeadlessInputInput.vue +0 -45
  161. package/src/components/headless/forms/AGHeadlessSelect.ts +0 -42
  162. package/src/components/headless/forms/AGHeadlessSelect.vue +0 -77
  163. package/src/components/headless/forms/AGHeadlessSelectButton.vue +0 -24
  164. package/src/components/headless/forms/AGHeadlessSelectLabel.vue +0 -24
  165. package/src/components/headless/forms/AGHeadlessSelectOption.ts +0 -4
  166. package/src/components/headless/forms/AGHeadlessSelectOption.vue +0 -39
  167. package/src/components/headless/forms/AGHeadlessSelectOptions.ts +0 -3
  168. package/src/components/headless/forms/index.ts +0 -14
  169. package/src/components/headless/modals/AGHeadlessModal.ts +0 -34
  170. package/src/components/headless/modals/AGHeadlessModal.vue +0 -86
  171. package/src/components/headless/modals/AGHeadlessModalPanel.vue +0 -28
  172. package/src/components/headless/modals/AGHeadlessModalTitle.vue +0 -13
  173. package/src/components/headless/modals/index.ts +0 -4
  174. package/src/components/headless/snackbars/AGHeadlessSnackbar.vue +0 -10
  175. package/src/components/headless/snackbars/index.ts +0 -40
  176. package/src/components/lib/AGErrorMessage.vue +0 -16
  177. package/src/components/lib/AGLink.vue +0 -9
  178. package/src/components/lib/AGMarkdown.vue +0 -36
  179. package/src/components/lib/AGMeasured.vue +0 -15
  180. package/src/components/lib/index.ts +0 -5
  181. package/src/components/modals/AGAlertModal.ts +0 -15
  182. package/src/components/modals/AGAlertModal.vue +0 -14
  183. package/src/components/modals/AGConfirmModal.ts +0 -27
  184. package/src/components/modals/AGConfirmModal.vue +0 -26
  185. package/src/components/modals/AGErrorReportModal.ts +0 -46
  186. package/src/components/modals/AGErrorReportModal.vue +0 -54
  187. package/src/components/modals/AGErrorReportModalTitle.vue +0 -25
  188. package/src/components/modals/AGLoadingModal.ts +0 -23
  189. package/src/components/modals/AGLoadingModal.vue +0 -15
  190. package/src/components/modals/AGModal.ts +0 -10
  191. package/src/components/modals/AGModal.vue +0 -39
  192. package/src/components/modals/AGModalContext.ts +0 -8
  193. package/src/components/modals/AGModalContext.vue +0 -22
  194. package/src/components/modals/AGModalTitle.vue +0 -9
  195. package/src/components/modals/AGPromptModal.ts +0 -30
  196. package/src/components/modals/AGPromptModal.vue +0 -34
  197. package/src/components/modals/index.ts +0 -17
  198. package/src/components/snackbars/AGSnackbar.vue +0 -36
  199. package/src/components/snackbars/index.ts +0 -3
  200. package/src/components/utils.ts +0 -10
  201. package/src/directives/initial-focus.ts +0 -11
  202. package/src/forms/Form.test.ts +0 -58
  203. package/src/forms/Form.ts +0 -185
  204. package/src/forms/composition.ts +0 -6
  205. package/src/main.histoire.ts +0 -1
  206. package/src/utils/tailwindcss.test.ts +0 -26
  207. package/src/utils/tailwindcss.ts +0 -7
  208. package/tailwind.config.js +0 -4
  209. package/tsconfig.json +0 -11
  210. package/vite.config.ts +0 -14
@@ -1,12 +1,18 @@
1
- import type { App } from 'vue';
1
+ import type { App as AppInstance } from 'vue';
2
2
 
3
- import { bootServices } from '@/services';
4
- import { definePlugin } from '@/plugins';
3
+ import App from '@aerogel/core/services/App';
4
+ import { bootServices } from '@aerogel/core/services';
5
+ import { definePlugin } from '@aerogel/core/plugins';
5
6
 
6
7
  import Errors from './Errors';
7
- import { ErrorReport, ErrorReportLog, ErrorSource } from './Errors.state';
8
+ import settings from './settings';
9
+ import type { ErrorReport, ErrorReportLog, ErrorSource } from './Errors.state';
8
10
 
9
- export { Errors, ErrorSource, ErrorReport, ErrorReportLog };
11
+ export * from './utils';
12
+ export { Errors };
13
+ export { default as JobCancelledError } from './JobCancelledError';
14
+ export { default as ServiceBootError } from './ServiceBootError';
15
+ export type { ErrorSource, ErrorReport, ErrorReportLog };
10
16
 
11
17
  const services = { $errors: Errors };
12
18
  const frameworkHandler: ErrorHandler = (error) => {
@@ -15,7 +21,7 @@ const frameworkHandler: ErrorHandler = (error) => {
15
21
  return true;
16
22
  };
17
23
 
18
- function setUpErrorHandler(app: App, baseHandler: ErrorHandler = () => false): void {
24
+ function setUpErrorHandler(app: AppInstance, baseHandler: ErrorHandler = () => false): void {
19
25
  const errorHandler: ErrorHandler = (error) => baseHandler(error) || frameworkHandler(error);
20
26
 
21
27
  app.config.errorHandler = errorHandler;
@@ -30,16 +36,18 @@ export default definePlugin({
30
36
  async install(app, options) {
31
37
  setUpErrorHandler(app, options.handleError);
32
38
 
39
+ settings.forEach((setting) => App.addSetting(setting));
40
+
33
41
  await bootServices(app, services);
34
42
  },
35
43
  });
36
44
 
37
- declare module '@/bootstrap/options' {
45
+ declare module '@aerogel/core/bootstrap/options' {
38
46
  export interface AerogelOptions {
39
47
  handleError?(error: ErrorSource): boolean;
40
48
  }
41
49
  }
42
50
 
43
- declare module '@/services' {
51
+ declare module '@aerogel/core/services' {
44
52
  export interface Services extends ErrorsServices {}
45
53
  }
@@ -0,0 +1,39 @@
1
+ <template>
2
+ <div class="mt-4 flex flex-row">
3
+ <div class="flex-grow">
4
+ <h3 id="debug-setting" class="text-base font-semibold">
5
+ {{ $td('settings.debug', 'Debugging') }}
6
+ </h3>
7
+ <Markdown
8
+ lang-key="settings.debugDescription"
9
+ lang-default="Enable debugging with [Eruda](https://eruda.liriliri.io/)."
10
+ class="mt-1 text-sm text-gray-500"
11
+ />
12
+ </div>
13
+
14
+ <Switch v-model="enabled" aria-labelledby="debug-setting" />
15
+ </div>
16
+ </template>
17
+
18
+ <script setup lang="ts">
19
+ import { ref, watchEffect } from 'vue';
20
+ import type Eruda from 'eruda';
21
+
22
+ import Switch from '@aerogel/core/components/ui/Switch.vue';
23
+ import Markdown from '@aerogel/core/components/ui/Markdown.vue';
24
+
25
+ let eruda: typeof Eruda | null = null;
26
+ const enabled = ref(false);
27
+
28
+ watchEffect(async () => {
29
+ if (!enabled.value) {
30
+ eruda?.destroy();
31
+
32
+ return;
33
+ }
34
+
35
+ eruda ??= (await import('eruda')).default;
36
+
37
+ eruda.init();
38
+ });
39
+ </script>
@@ -0,0 +1,10 @@
1
+ import { defineSettings } from '@aerogel/core/services';
2
+
3
+ import Debug from './Debug.vue';
4
+
5
+ export default defineSettings([
6
+ {
7
+ priority: 10,
8
+ component: Debug,
9
+ },
10
+ ]);
@@ -0,0 +1,35 @@
1
+ import { JSError, isObject, toString } from '@noeldemartin/utils';
2
+ import { translateWithDefault } from '@aerogel/core/lang/utils';
3
+ import type { ErrorSource } from './Errors.state';
4
+
5
+ const handlers: ErrorHandler[] = [];
6
+
7
+ export type ErrorHandler = (error: ErrorSource) => string | undefined;
8
+
9
+ export function registerErrorHandler(handler: ErrorHandler): void {
10
+ handlers.push(handler);
11
+ }
12
+
13
+ export function getErrorMessage(error: ErrorSource): string {
14
+ for (const handler of handlers) {
15
+ const result = handler(error);
16
+
17
+ if (result) {
18
+ return result;
19
+ }
20
+ }
21
+
22
+ if (typeof error === 'string') {
23
+ return error;
24
+ }
25
+
26
+ if (error instanceof Error || error instanceof JSError) {
27
+ return error.message;
28
+ }
29
+
30
+ if (isObject(error)) {
31
+ return toString(error['message'] ?? error['description'] ?? 'Unknown error object');
32
+ }
33
+
34
+ return translateWithDefault('errors.unknown', 'Unknown Error');
35
+ }
@@ -0,0 +1,110 @@
1
+ import { describe, expect, expectTypeOf, it } from 'vitest';
2
+ import { tt } from '@noeldemartin/testing';
3
+ import type { Equals } from '@noeldemartin/utils';
4
+ import type { Expect } from '@noeldemartin/testing';
5
+
6
+ import {
7
+ numberInput,
8
+ objectInput,
9
+ requiredObjectInput,
10
+ requiredStringInput,
11
+ stringInput,
12
+ } from '@aerogel/core/forms/utils';
13
+ import { useForm } from '@aerogel/core/utils/composition/forms';
14
+
15
+ describe('FormController', () => {
16
+
17
+ it('defines magic fields', () => {
18
+ const form = useForm({
19
+ name: requiredStringInput(),
20
+ age: numberInput(),
21
+ });
22
+
23
+ expectTypeOf(form.name).toEqualTypeOf<string>();
24
+ expectTypeOf(form.age).toEqualTypeOf<number | null>();
25
+ });
26
+
27
+ it('validates required fields', () => {
28
+ // Arrange
29
+ const form = useForm({
30
+ name: {
31
+ type: 'string',
32
+ rules: 'required',
33
+ },
34
+ });
35
+
36
+ // Act
37
+ form.submit();
38
+
39
+ // Assert
40
+ expect(form.valid).toBe(false);
41
+ expect(form.submitted).toBe(true);
42
+ expect(form.errors.name).toEqual(['required']);
43
+ });
44
+
45
+ it('resets form', () => {
46
+ // Arrange
47
+ const form = useForm({
48
+ name: {
49
+ type: 'string',
50
+ rules: 'required',
51
+ },
52
+ });
53
+
54
+ form.name = 'Foo bar';
55
+ form.submit();
56
+
57
+ // Act
58
+ form.reset();
59
+
60
+ // Assert
61
+ expect(form.valid).toBe(true);
62
+ expect(form.submitted).toBe(false);
63
+ expect(form.name).toBeNull();
64
+ });
65
+
66
+ it('trims values', () => {
67
+ // Arrange
68
+ const form = useForm({
69
+ trimmed: {
70
+ type: 'string',
71
+ rules: 'required',
72
+ },
73
+ untrimmed: {
74
+ type: 'string',
75
+ rules: 'required',
76
+ trim: false,
77
+ },
78
+ });
79
+
80
+ // Act
81
+ form.trimmed = ' ';
82
+ form.untrimmed = ' ';
83
+
84
+ form.submit();
85
+
86
+ // Assert
87
+ expect(form.valid).toBe(false);
88
+ expect(form.submitted).toBe(true);
89
+ expect(form.trimmed).toEqual('');
90
+ expect(form.untrimmed).toEqual(' ');
91
+ expect(form.errors).toEqual({ trimmed: ['required'], untrimmed: null });
92
+ });
93
+
94
+ it('infers field types', () => {
95
+ const form = useForm({
96
+ one: stringInput(),
97
+ two: requiredStringInput(),
98
+ three: objectInput(),
99
+ four: requiredObjectInput<{ foo: string; bar?: number }>(),
100
+ });
101
+
102
+ tt<
103
+ | Expect<Equals<typeof form.one, string | null>>
104
+ | Expect<Equals<typeof form.two, string>>
105
+ | Expect<Equals<typeof form.three, object | null>>
106
+ | Expect<Equals<typeof form.four, { foo: string; bar?: number }>>
107
+ >();
108
+ });
109
+
110
+ });
@@ -0,0 +1,246 @@
1
+ import { computed, nextTick, reactive, readonly, ref } from 'vue';
2
+ import { MagicObject, arrayRemove, fail, toString } from '@noeldemartin/utils';
3
+ import type { ComputedRef, DeepReadonly, Ref, UnwrapNestedRefs } from 'vue';
4
+
5
+ import { validate } from './validation';
6
+
7
+ export const __objectType: unique symbol = Symbol();
8
+
9
+ export interface FormFieldDefinition<
10
+ TType extends FormFieldType = FormFieldType,
11
+ TRules extends string = string,
12
+ TObjectType = object,
13
+ > {
14
+ type: TType;
15
+ trim?: boolean;
16
+ default?: GetFormFieldValue<TType>;
17
+ rules?: TRules;
18
+ [__objectType]?: TObjectType;
19
+ }
20
+
21
+ export type FormFieldType = 'string' | 'number' | 'boolean' | 'object' | 'date';
22
+ export type FormFieldValue = GetFormFieldValue<FormFieldType>;
23
+ export type FormFieldDefinitions = Record<string, FormFieldDefinition>;
24
+
25
+ export type FormData<T> = {
26
+ -readonly [k in keyof T]: T[k] extends FormFieldDefinition<infer TType, infer TRules, infer TObjectType>
27
+ ? TRules extends 'required'
28
+ ? GetFormFieldValue<TType, TObjectType>
29
+ : GetFormFieldValue<TType, TObjectType> | null
30
+ : never;
31
+ };
32
+
33
+ export type FormErrors<T> = {
34
+ [k in keyof T]: string[] | null;
35
+ };
36
+
37
+ export type GetFormFieldValue<TType, TObjectType = object> = TType extends 'string'
38
+ ? string
39
+ : TType extends 'number'
40
+ ? number
41
+ : TType extends 'boolean'
42
+ ? boolean
43
+ : TType extends 'object'
44
+ ? TObjectType extends object
45
+ ? TObjectType
46
+ : object
47
+ : TType extends 'date'
48
+ ? Date
49
+ : never;
50
+
51
+ const validForms: WeakMap<FormController, ComputedRef<boolean>> = new WeakMap();
52
+
53
+ export type SubmitFormListener = () => unknown;
54
+ export type FocusFormListener = (input: string) => unknown;
55
+
56
+ export default class FormController<Fields extends FormFieldDefinitions = FormFieldDefinitions> extends MagicObject {
57
+
58
+ public errors: DeepReadonly<UnwrapNestedRefs<FormErrors<Fields>>>;
59
+
60
+ private _fields: Fields;
61
+ private _data: FormData<Fields>;
62
+ private _submitted: Ref<boolean>;
63
+ private _errors: FormErrors<Fields>;
64
+ private _listeners: { focus?: FocusFormListener[]; submit?: SubmitFormListener[] } = {};
65
+
66
+ constructor(fields: Fields) {
67
+ super();
68
+
69
+ this._fields = fields;
70
+ this._submitted = ref(false);
71
+ this._data = this.getInitialData(fields);
72
+ this._errors = this.getInitialErrors(fields);
73
+
74
+ validForms.set(
75
+ this,
76
+ computed(() => !Object.values(this._errors).some((error) => error !== null)),
77
+ );
78
+
79
+ this.errors = readonly(this._errors);
80
+ }
81
+
82
+ public get valid(): boolean {
83
+ return !!validForms.get(this)?.value;
84
+ }
85
+
86
+ public get submitted(): boolean {
87
+ return this._submitted.value;
88
+ }
89
+
90
+ public setFieldValue<T extends keyof Fields>(field: T, value: FormData<Fields>[T]): void {
91
+ const definition =
92
+ this._fields[field] ?? fail<FormFieldDefinition>(`Trying to set undefined '${toString(field)}' field`);
93
+
94
+ this._data[field] =
95
+ definition.type === 'string' && (definition.trim ?? true)
96
+ ? (toString(value).trim() as FormData<Fields>[T])
97
+ : value;
98
+
99
+ if (this._submitted.value) {
100
+ this.validate();
101
+ }
102
+ }
103
+
104
+ public getFieldValue<T extends keyof Fields>(field: T): GetFormFieldValue<Fields[T]['type']> {
105
+ return this._data[field] as unknown as GetFormFieldValue<Fields[T]['type']>;
106
+ }
107
+
108
+ public getFieldRules<T extends keyof Fields>(field: T): string[] {
109
+ return this._fields[field]?.rules?.split('|') ?? [];
110
+ }
111
+
112
+ public data(): FormData<Fields> {
113
+ return { ...this._data };
114
+ }
115
+
116
+ public validate(): boolean {
117
+ const errors = Object.entries(this._fields).reduce(
118
+ (formErrors, [name, definition]) => {
119
+ formErrors[name] = this.getFieldErrors(name, definition);
120
+
121
+ return formErrors;
122
+ },
123
+ {} as Record<string, string[] | null>,
124
+ );
125
+
126
+ this.resetErrors(errors);
127
+
128
+ return this.valid;
129
+ }
130
+
131
+ public reset(options: { keepData?: boolean; keepErrors?: boolean } = {}): void {
132
+ this._submitted.value = false;
133
+
134
+ options.keepData || this.resetData();
135
+ options.keepErrors || this.resetErrors();
136
+ }
137
+
138
+ public submit(): boolean {
139
+ this._submitted.value = true;
140
+
141
+ const valid = this.validate();
142
+
143
+ valid && this._listeners['submit']?.forEach((listener) => listener());
144
+
145
+ return valid;
146
+ }
147
+
148
+ public on(event: 'focus', listener: FocusFormListener): () => void;
149
+ public on(event: 'submit', listener: SubmitFormListener): () => void;
150
+ public on(event: 'focus' | 'submit', listener: FocusFormListener | SubmitFormListener): () => void {
151
+ this._listeners[event] ??= [];
152
+
153
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
154
+ this._listeners[event]?.push(listener as any);
155
+
156
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
157
+ return () => this.off(event as any, listener);
158
+ }
159
+
160
+ public off(event: 'focus', listener: FocusFormListener): void;
161
+ public off(event: 'submit', listener: SubmitFormListener): void;
162
+ public off(event: 'focus' | 'submit', listener: FocusFormListener | SubmitFormListener): void {
163
+ arrayRemove(this._listeners[event] ?? [], listener);
164
+ }
165
+
166
+ public async focus(input: string): Promise<void> {
167
+ await nextTick();
168
+
169
+ this._listeners['focus']?.forEach((listener) => listener(input));
170
+ }
171
+
172
+ protected override __get(property: string): unknown {
173
+ if (!(property in this._fields)) {
174
+ return super.__get(property);
175
+ }
176
+
177
+ return this.getFieldValue(property);
178
+ }
179
+
180
+ protected override __set(property: string, value: unknown): void {
181
+ if (!(property in this._fields)) {
182
+ super.__set(property, value);
183
+
184
+ return;
185
+ }
186
+
187
+ this.setFieldValue(property, value as FormData<Fields>[string]);
188
+ }
189
+
190
+ private getFieldErrors(name: keyof Fields, definition: FormFieldDefinition): string[] | null {
191
+ const errors = [];
192
+ const value = this._data[name];
193
+ const rules = definition.rules?.split('|') ?? [];
194
+
195
+ for (const rule of rules) {
196
+ if (rule !== 'required' && (value === null || value === undefined)) {
197
+ continue;
198
+ }
199
+
200
+ errors.push(...validate(value, rule));
201
+ }
202
+
203
+ return errors.length > 0 ? errors : null;
204
+ }
205
+
206
+ private getInitialData(fields: Fields): FormData<Fields> {
207
+ if (this.static().isConjuring()) {
208
+ return {} as FormData<Fields>;
209
+ }
210
+
211
+ const data = Object.entries(fields).reduce((initialData, [name, definition]) => {
212
+ initialData[name as keyof Fields] = (definition.default ?? null) as FormData<Fields>[keyof Fields];
213
+
214
+ return initialData;
215
+ }, {} as FormData<Fields>);
216
+
217
+ return reactive(data) as FormData<Fields>;
218
+ }
219
+
220
+ private getInitialErrors(fields: Fields): FormErrors<Fields> {
221
+ if (this.static().isConjuring()) {
222
+ return {} as FormErrors<Fields>;
223
+ }
224
+
225
+ const errors = Object.keys(fields).reduce((formErrors, name) => {
226
+ formErrors[name as keyof Fields] = null;
227
+
228
+ return formErrors;
229
+ }, {} as FormErrors<Fields>);
230
+
231
+ return reactive(errors) as FormErrors<Fields>;
232
+ }
233
+
234
+ private resetData(): void {
235
+ for (const [name, field] of Object.entries(this._fields)) {
236
+ this._data[name as keyof Fields] = (field.default ?? null) as FormData<Fields>[keyof Fields];
237
+ }
238
+ }
239
+
240
+ private resetErrors(errors?: Record<string, string[] | null>): void {
241
+ Object.keys(this._errors).forEach((key) => delete this._errors[key as keyof Fields]);
242
+
243
+ errors && Object.assign(this._errors, errors);
244
+ }
245
+
246
+ }
@@ -1,3 +1,4 @@
1
- export * from './Form';
2
- export * from './composition';
1
+ export * from './FormController';
3
2
  export * from './utils';
3
+ export * from './validation';
4
+ export { default as FormController } from './FormController';
@@ -1,53 +1,84 @@
1
- import { FormFieldTypes } from './Form';
2
- import type { FormFieldDefinition } from './Form';
1
+ import type { FormFieldDefinition } from './FormController';
3
2
 
4
- export function booleanInput(defaultValue?: boolean): FormFieldDefinition<typeof FormFieldTypes.Boolean> {
3
+ export function booleanInput(defaultValue?: boolean, options: { rules?: string } = {}): FormFieldDefinition<'boolean'> {
5
4
  return {
6
5
  default: defaultValue,
7
- type: FormFieldTypes.Boolean,
6
+ type: 'boolean',
7
+ rules: options.rules,
8
8
  };
9
9
  }
10
10
 
11
- export function requiredBooleanInput(
12
- defaultValue?: boolean,
13
- ): FormFieldDefinition<typeof FormFieldTypes.Boolean, 'required'> {
11
+ export function dateInput(defaultValue?: Date, options: { rules?: string } = {}): FormFieldDefinition<'date'> {
14
12
  return {
15
13
  default: defaultValue,
16
- type: FormFieldTypes.Boolean,
14
+ type: 'date',
15
+ rules: options.rules,
16
+ };
17
+ }
18
+
19
+ export function requiredBooleanInput(defaultValue?: boolean): FormFieldDefinition<'boolean', 'required'> {
20
+ return {
21
+ default: defaultValue,
22
+ type: 'boolean',
23
+ rules: 'required',
24
+ };
25
+ }
26
+
27
+ export function requiredDateInput(defaultValue?: Date): FormFieldDefinition<'date', 'required'> {
28
+ return {
29
+ default: defaultValue,
30
+ type: 'date',
17
31
  rules: 'required',
18
32
  };
19
33
  }
20
34
 
21
- export function requiredNumberInput(
22
- defaultValue?: number,
23
- ): FormFieldDefinition<typeof FormFieldTypes.Number, 'required'> {
35
+ export function requiredNumberInput(defaultValue?: number): FormFieldDefinition<'number', 'required'> {
24
36
  return {
25
37
  default: defaultValue,
26
- type: FormFieldTypes.Number,
38
+ type: 'number',
27
39
  rules: 'required',
28
40
  };
29
41
  }
30
42
 
31
- export function requiredStringInput(
32
- defaultValue?: string,
33
- ): FormFieldDefinition<typeof FormFieldTypes.String, 'required'> {
43
+ export function requiredObjectInput<T extends object>(defaultValue?: T): FormFieldDefinition<'object', 'required', T> {
34
44
  return {
35
45
  default: defaultValue,
36
- type: FormFieldTypes.String,
46
+ type: 'object',
37
47
  rules: 'required',
38
48
  };
39
49
  }
40
50
 
41
- export function numberInput(defaultValue?: number): FormFieldDefinition<typeof FormFieldTypes.Number> {
51
+ export function requiredStringInput(defaultValue?: string): FormFieldDefinition<'string', 'required'> {
52
+ return {
53
+ default: defaultValue,
54
+ type: 'string',
55
+ rules: 'required',
56
+ };
57
+ }
58
+
59
+ export function numberInput(defaultValue?: number, options: { rules?: string } = {}): FormFieldDefinition<'number'> {
60
+ return {
61
+ default: defaultValue,
62
+ type: 'number',
63
+ rules: options.rules,
64
+ };
65
+ }
66
+
67
+ export function objectInput<T extends object>(
68
+ defaultValue?: T,
69
+ options: { rules?: string } = {},
70
+ ): FormFieldDefinition<'object', string, T> {
42
71
  return {
43
72
  default: defaultValue,
44
- type: FormFieldTypes.Number,
73
+ type: 'object',
74
+ rules: options.rules,
45
75
  };
46
76
  }
47
77
 
48
- export function stringInput(defaultValue?: string): FormFieldDefinition<typeof FormFieldTypes.String> {
78
+ export function stringInput(defaultValue?: string, options: { rules?: string } = {}): FormFieldDefinition<'string'> {
49
79
  return {
50
80
  default: defaultValue,
51
- type: FormFieldTypes.String,
81
+ type: 'string',
82
+ rules: options.rules,
52
83
  };
53
84
  }
@@ -0,0 +1,19 @@
1
+ import { arrayFrom } from '@noeldemartin/utils';
2
+
3
+ const builtInRules: Record<string, FormFieldValidator> = {
4
+ required: (value) => (value ? undefined : 'required'),
5
+ };
6
+
7
+ export type FormFieldValidator<T = unknown> = (value: T) => string | string[] | undefined;
8
+
9
+ export const validators: Record<string, FormFieldValidator> = { ...builtInRules };
10
+
11
+ export function defineFormValidationRule<T>(rule: string, validator: FormFieldValidator<T>): void {
12
+ validators[rule] = validator as FormFieldValidator;
13
+ }
14
+
15
+ export function validate(value: unknown, rule: string): string[] {
16
+ const errors = validators[rule]?.(value);
17
+
18
+ return errors ? arrayFrom(errors) : [];
19
+ }