@aerogel/core 0.0.0-next.7f6ed5a1f91688a86bf5ede2adc465e4fd6cfdea → 0.0.0-next.b58141fee5d2fe7d25debdbca6b1d2bf1c13e48e

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 (85) hide show
  1. package/dist/aerogel-core.cjs.js +1 -1
  2. package/dist/aerogel-core.cjs.js.map +1 -1
  3. package/dist/aerogel-core.d.ts +711 -79
  4. package/dist/aerogel-core.esm.js +1 -1
  5. package/dist/aerogel-core.esm.js.map +1 -1
  6. package/dist/virtual.d.ts +11 -0
  7. package/noeldemartin.config.js +4 -1
  8. package/package.json +7 -9
  9. package/src/bootstrap/bootstrap.test.ts +0 -56
  10. package/src/bootstrap/index.ts +9 -25
  11. package/src/bootstrap/options.ts +5 -1
  12. package/src/components/AGAppModals.vue +15 -0
  13. package/src/components/AGAppOverlays.vue +5 -7
  14. package/src/components/AGAppSnackbars.vue +13 -0
  15. package/src/components/basic/AGErrorMessage.vue +16 -0
  16. package/src/components/basic/AGLink.vue +9 -0
  17. package/src/components/basic/AGMarkdown.vue +21 -5
  18. package/src/components/basic/index.ts +3 -1
  19. package/src/components/constants.ts +8 -0
  20. package/src/components/forms/AGButton.vue +36 -3
  21. package/src/components/forms/AGCheckbox.vue +35 -0
  22. package/src/components/forms/AGInput.vue +8 -4
  23. package/src/components/forms/index.ts +2 -1
  24. package/src/components/headless/forms/AGHeadlessButton.vue +7 -7
  25. package/src/components/headless/forms/AGHeadlessInput.ts +2 -2
  26. package/src/components/headless/forms/AGHeadlessInput.vue +5 -5
  27. package/src/components/headless/forms/AGHeadlessInputError.vue +9 -5
  28. package/src/components/headless/forms/AGHeadlessInputInput.vue +20 -4
  29. package/src/components/headless/forms/AGHeadlessInputLabel.vue +16 -0
  30. package/src/components/headless/forms/index.ts +6 -4
  31. package/src/components/headless/index.ts +1 -0
  32. package/src/components/headless/modals/AGHeadlessModal.vue +5 -1
  33. package/src/components/headless/modals/AGHeadlessModalPanel.vue +10 -2
  34. package/src/components/headless/snackbars/AGHeadlessSnackbar.vue +10 -0
  35. package/src/components/headless/snackbars/index.ts +25 -0
  36. package/src/components/index.ts +4 -1
  37. package/src/components/modals/AGAlertModal.vue +12 -2
  38. package/src/components/modals/AGConfirmModal.vue +30 -0
  39. package/src/components/modals/AGErrorReportModal.ts +20 -0
  40. package/src/components/modals/AGErrorReportModal.vue +62 -0
  41. package/src/components/modals/AGErrorReportModalButtons.vue +109 -0
  42. package/src/components/modals/AGErrorReportModalTitle.vue +25 -0
  43. package/src/components/modals/AGLoadingModal.vue +19 -0
  44. package/src/components/modals/AGModal.ts +4 -0
  45. package/src/components/modals/AGModal.vue +23 -4
  46. package/src/components/modals/AGModalTitle.vue +9 -0
  47. package/src/components/modals/index.ts +20 -2
  48. package/src/components/snackbars/AGSnackbar.vue +42 -0
  49. package/src/components/snackbars/index.ts +3 -0
  50. package/src/directives/index.ts +19 -4
  51. package/src/errors/Errors.state.ts +31 -0
  52. package/src/errors/Errors.ts +183 -0
  53. package/src/errors/index.ts +59 -0
  54. package/src/forms/Form.test.ts +21 -0
  55. package/src/forms/Form.ts +38 -16
  56. package/src/forms/utils.ts +17 -0
  57. package/src/lang/Lang.ts +47 -8
  58. package/src/lang/index.ts +17 -76
  59. package/src/lang/utils.ts +4 -0
  60. package/src/main.ts +2 -0
  61. package/src/plugins/Plugin.ts +7 -0
  62. package/src/plugins/index.ts +7 -0
  63. package/src/services/App.state.ts +16 -0
  64. package/src/services/App.ts +15 -0
  65. package/src/services/Service.ts +157 -29
  66. package/src/services/index.ts +32 -7
  67. package/src/services/store.ts +27 -0
  68. package/src/types/virtual.d.ts +11 -0
  69. package/src/types/vite.d.ts +0 -2
  70. package/src/ui/UI.state.ts +12 -6
  71. package/src/ui/UI.ts +72 -10
  72. package/src/ui/index.ts +24 -14
  73. package/src/utils/composition/forms.ts +11 -0
  74. package/src/utils/composition/hooks.ts +9 -0
  75. package/src/utils/index.ts +3 -0
  76. package/src/utils/markdown.ts +11 -2
  77. package/src/utils/vue.ts +2 -0
  78. package/tsconfig.json +2 -10
  79. package/vite.config.ts +3 -6
  80. package/src/bootstrap/hooks.ts +0 -19
  81. package/src/lang/helpers.ts +0 -5
  82. package/src/models/index.ts +0 -18
  83. package/src/routing/index.ts +0 -33
  84. package/src/testing/stubs/lang/en.yaml +0 -1
  85. package/src/testing/stubs/models/User.ts +0 -3
@@ -34,4 +34,25 @@ describe('Form', () => {
34
34
  expect(form.errors.name).toEqual(['required']);
35
35
  });
36
36
 
37
+ it('resets form', () => {
38
+ // Arrange
39
+ const form = useForm({
40
+ name: {
41
+ type: FormFieldTypes.String,
42
+ rules: 'required',
43
+ },
44
+ });
45
+
46
+ form.name = 'Foo bar';
47
+ form.submit();
48
+
49
+ // Act
50
+ form.reset();
51
+
52
+ // Assert
53
+ expect(form.valid).toBe(true);
54
+ expect(form.submitted).toBe(false);
55
+ expect(form.name).toBeNull();
56
+ });
57
+
37
58
  });
package/src/forms/Form.ts CHANGED
@@ -1,11 +1,12 @@
1
1
  import { MagicObject } from '@noeldemartin/utils';
2
- import { reactive, readonly, ref } from 'vue';
2
+ import { computed, reactive, readonly, ref } from 'vue';
3
3
  import type { ObjectValues } from '@noeldemartin/utils';
4
- import type { DeepReadonly, Ref, UnwrapNestedRefs } from 'vue';
4
+ import type { ComputedRef, DeepReadonly, Ref, UnwrapNestedRefs } from 'vue';
5
5
 
6
6
  export const FormFieldTypes = {
7
7
  String: 'string',
8
8
  Number: 'number',
9
+ Boolean: 'boolean',
9
10
  } as const;
10
11
 
11
12
  export interface FormFieldDefinition<TType extends FormFieldType = FormFieldType, TRules extends string = string> {
@@ -18,7 +19,7 @@ export type FormFieldDefinitions = Record<string, FormFieldDefinition>;
18
19
  export type FormFieldType = ObjectValues<typeof FormFieldTypes>;
19
20
 
20
21
  export type FormData<T> = {
21
- [k in keyof T]: T[k] extends FormFieldDefinition<infer TType, infer TRules>
22
+ -readonly [k in keyof T]: T[k] extends FormFieldDefinition<infer TType, infer TRules>
22
23
  ? TRules extends 'required'
23
24
  ? GetFormFieldValue<TType>
24
25
  : GetFormFieldValue<TType> | null
@@ -33,6 +34,8 @@ export type GetFormFieldValue<TType> = TType extends typeof FormFieldTypes.Strin
33
34
  ? string
34
35
  : TType extends typeof FormFieldTypes.Number
35
36
  ? number
37
+ : TType extends typeof FormFieldTypes.Boolean
38
+ ? boolean
36
39
  : never;
37
40
 
38
41
  export default class Form<Fields extends FormFieldDefinitions = FormFieldDefinitions> extends MagicObject {
@@ -41,7 +44,7 @@ export default class Form<Fields extends FormFieldDefinitions = FormFieldDefinit
41
44
 
42
45
  private _fields: Fields;
43
46
  private _data: FormData<Fields>;
44
- private _valid: Ref<boolean>;
47
+ private _valid: ComputedRef<boolean>;
45
48
  private _submitted: Ref<boolean>;
46
49
  private _errors: FormErrors<Fields>;
47
50
 
@@ -50,9 +53,9 @@ export default class Form<Fields extends FormFieldDefinitions = FormFieldDefinit
50
53
 
51
54
  this._fields = fields;
52
55
  this._submitted = ref(false);
53
- this._valid = ref(true);
54
56
  this._data = this.getInitialData(fields);
55
57
  this._errors = this.getInitialErrors(fields);
58
+ this._valid = computed(() => !Object.values(this._errors).some((error) => error !== null));
56
59
 
57
60
  this.errors = readonly(this._errors);
58
61
  }
@@ -78,15 +81,22 @@ export default class Form<Fields extends FormFieldDefinitions = FormFieldDefinit
78
81
  }
79
82
 
80
83
  public validate(): boolean {
81
- const errors = Object.entries(this._fields).reduce((errors, [name, definition]) => {
82
- errors[name] = this.getFieldErrors(name, definition);
84
+ const errors = Object.entries(this._fields).reduce((formErrors, [name, definition]) => {
85
+ formErrors[name] = this.getFieldErrors(name, definition);
83
86
 
84
- return errors;
87
+ return formErrors;
85
88
  }, {} as Record<string, string[] | null>);
86
89
 
87
- Object.assign(this._errors, errors);
90
+ this.resetErrors(errors);
88
91
 
89
- return (this._valid.value = !Object.values(errors).some((error) => error !== null));
92
+ return this.valid;
93
+ }
94
+
95
+ public reset(options: { keepData?: boolean; keepErrors?: boolean } = {}): void {
96
+ this._submitted.value = false;
97
+
98
+ options.keepData || this.resetData();
99
+ options.keepErrors || this.resetErrors();
90
100
  }
91
101
 
92
102
  public submit(): boolean {
@@ -128,10 +138,10 @@ export default class Form<Fields extends FormFieldDefinitions = FormFieldDefinit
128
138
  return {} as FormData<Fields>;
129
139
  }
130
140
 
131
- const data = Object.entries(fields).reduce((data, [name, definition]) => {
132
- data[name as keyof Fields] = (definition.default ?? null) as FormData<Fields>[keyof Fields];
141
+ const data = Object.entries(fields).reduce((formData, [name, definition]) => {
142
+ formData[name as keyof Fields] = (definition.default ?? null) as FormData<Fields>[keyof Fields];
133
143
 
134
- return data;
144
+ return formData;
135
145
  }, {} as FormData<Fields>);
136
146
 
137
147
  return reactive(data) as FormData<Fields>;
@@ -142,13 +152,25 @@ export default class Form<Fields extends FormFieldDefinitions = FormFieldDefinit
142
152
  return {} as FormErrors<Fields>;
143
153
  }
144
154
 
145
- const errors = Object.keys(fields).reduce((errors, name) => {
146
- errors[name as keyof Fields] = null;
155
+ const errors = Object.keys(fields).reduce((formErrors, name) => {
156
+ formErrors[name as keyof Fields] = null;
147
157
 
148
- return errors;
158
+ return formErrors;
149
159
  }, {} as FormErrors<Fields>);
150
160
 
151
161
  return reactive(errors) as FormErrors<Fields>;
152
162
  }
153
163
 
164
+ private resetData(): void {
165
+ for (const [name, field] of Object.entries(this._fields)) {
166
+ this._data[name as keyof Fields] = (field.default ?? null) as FormData<Fields>[keyof Fields];
167
+ }
168
+ }
169
+
170
+ private resetErrors(errors?: Record<string, string[] | null>): void {
171
+ Object.keys(this._errors).forEach((key) => delete this._errors[key as keyof Fields]);
172
+
173
+ errors && Object.assign(this._errors, errors);
174
+ }
175
+
154
176
  }
@@ -1,6 +1,23 @@
1
1
  import { FormFieldTypes } from './Form';
2
2
  import type { FormFieldDefinition } from './Form';
3
3
 
4
+ export function booleanInput(defaultValue?: boolean): FormFieldDefinition<typeof FormFieldTypes.Boolean> {
5
+ return {
6
+ default: defaultValue,
7
+ type: FormFieldTypes.Boolean,
8
+ };
9
+ }
10
+
11
+ export function requiredBooleanInput(
12
+ defaultValue?: boolean,
13
+ ): FormFieldDefinition<typeof FormFieldTypes.Boolean, 'required'> {
14
+ return {
15
+ default: defaultValue,
16
+ type: FormFieldTypes.Boolean,
17
+ rules: 'required',
18
+ };
19
+ }
20
+
4
21
  export function requiredNumberInput(
5
22
  defaultValue?: number,
6
23
  ): FormFieldDefinition<typeof FormFieldTypes.Number, 'required'> {
package/src/lang/Lang.ts CHANGED
@@ -1,19 +1,58 @@
1
- import { useI18n } from 'vue-i18n';
2
- import { facade } from '@noeldemartin/utils';
3
- import type { Composer } from 'vue-i18n';
1
+ import { facade, toString } from '@noeldemartin/utils';
4
2
 
3
+ import App from '@/services/App';
5
4
  import Service from '@/services/Service';
6
5
 
6
+ export interface LangProvider {
7
+ translate(key: string, parameters?: Record<string, unknown>): string;
8
+ }
9
+
7
10
  export class LangService extends Service {
8
11
 
9
- private i18n?: Composer;
12
+ private provider: LangProvider;
13
+
14
+ constructor() {
15
+ super();
16
+
17
+ this.provider = {
18
+ translate: (key) => {
19
+ // eslint-disable-next-line no-console
20
+ App.development && console.warn('Lang provider is missing');
21
+
22
+ return key;
23
+ },
24
+ };
25
+ }
10
26
 
11
- public setup(): void {
12
- this.i18n = useI18n();
27
+ public setProvider(provider: LangProvider): void {
28
+ this.provider = provider;
13
29
  }
14
30
 
15
- public translate(key: string, parameters: Record<string, unknown> = {}): string {
16
- return this.i18n?.t(key, parameters) ?? key;
31
+ public translate(key: string, parameters?: Record<string, unknown>): string {
32
+ return this.provider.translate(key, parameters) ?? key;
33
+ }
34
+
35
+ public translateWithDefault(key: string, defaultMessage: string): string;
36
+ public translateWithDefault(key: string, parameters: Record<string, unknown>, defaultMessage: string): string;
37
+ public translateWithDefault(
38
+ key: string,
39
+ defaultMessageOrParameters?: string | Record<string, unknown>,
40
+ defaultMessage?: string,
41
+ ): string {
42
+ defaultMessage ??= defaultMessageOrParameters as string;
43
+
44
+ const parameters = typeof defaultMessageOrParameters === 'string' ? {} : defaultMessageOrParameters ?? {};
45
+ const message = this.provider.translate(key, parameters) ?? key;
46
+
47
+ if (message === key) {
48
+ return Object.entries(parameters).reduce(
49
+ (renderedMessage, [name, value]) =>
50
+ renderedMessage.replace(new RegExp(`\\{\\s*${name}\\s*\\}`, 'g'), toString(value)),
51
+ defaultMessage,
52
+ );
53
+ }
54
+
55
+ return message;
17
56
  }
18
57
 
19
58
  }
package/src/lang/index.ts CHANGED
@@ -1,89 +1,30 @@
1
- import { createI18n } from 'vue-i18n';
2
- import { fail, stringMatch } from '@noeldemartin/utils';
3
- import type { I18nOptions } from 'vue-i18n';
4
- import type { Plugin } from 'vue';
5
-
6
- import { defineBootstrapHook, onAppMounted } from '@/bootstrap/hooks';
7
1
  import { bootServices } from '@/services';
8
- import type { BootstrapOptions } from '@/bootstrap/options';
9
-
10
- import Lang from './Lang';
11
-
12
- const services = { $lang: Lang };
13
-
14
- function getLangOptions(options: BootstrapOptions): LangOptions | null {
15
- if (options.lang) {
16
- return options.lang;
17
- }
18
-
19
- if (options.langMessages) {
20
- return { messages: options.langMessages };
21
- }
22
-
23
- return null;
24
- }
2
+ import { definePlugin } from '@/plugins';
25
3
 
26
- function getMessageLoaders(messageLoaders: Record<string, unknown>): Record<string, LazyMessages> {
27
- return Object.entries(messageLoaders).reduce((loaders, [fileName, loader]) => {
28
- const locale = stringMatch<2>(fileName, /.*\/lang\/(.+)\.yaml/)?.[1];
4
+ import Lang, { LangProvider } from './Lang';
5
+ import { translate, translateWithDefault } from './utils';
29
6
 
30
- if (locale) {
31
- loaders[locale] = () =>
32
- (loader as () => Promise<{ default: Record<string, unknown> }>)().then(
33
- ({ default: messages }) => messages,
34
- );
35
- }
7
+ export { Lang, LangProvider, translate, translateWithDefault };
36
8
 
37
- return loaders;
38
- }, {} as Record<string, LazyMessages>);
39
- }
40
-
41
- async function createAppI18n(options: LangOptions): Promise<Plugin> {
42
- const locale = options.defaultLocale ?? 'en';
43
- const fallbackLocale = options.fallbackLocale ?? 'en';
44
- const messageLoaders = getMessageLoaders(options.messages);
45
- const lazyMessages = messageLoaders[locale] ?? fail<LazyMessages>(`Missing messages for '${locale}' locale`);
46
- const messages = { [locale]: await lazyMessages() } as I18nOptions['messages'];
47
-
48
- return createI18n({ locale, fallbackLocale, messages });
49
- }
9
+ const services = { $lang: Lang };
50
10
 
51
11
  export type LangServices = typeof services;
52
12
 
53
- export type LazyMessages = () => Promise<Record<string, unknown>>;
54
-
55
- export interface LangOptions {
56
- messages: Record<string, unknown>;
57
- defaultLocale?: string;
58
- fallbackLocale?: string;
59
- }
60
-
61
- export * from './helpers';
62
- export { Lang };
63
-
64
- export default defineBootstrapHook(async (app, options) => {
65
- const langOptions = getLangOptions(options);
66
-
67
- if (!langOptions) {
68
- return;
69
- }
70
-
71
- onAppMounted(() => Lang.setup());
72
-
73
- const plugin = await createAppI18n(langOptions);
13
+ export default definePlugin({
14
+ async install(app) {
15
+ app.config.globalProperties.$t ??= translate;
16
+ app.config.globalProperties.$td = translateWithDefault;
74
17
 
75
- app.use(plugin);
76
-
77
- await bootServices(app, services);
18
+ await bootServices(app, services);
19
+ },
78
20
  });
79
21
 
80
- declare module '@/bootstrap/options' {
81
- interface BootstrapOptions {
82
- lang?: LangOptions;
83
- langMessages?: Record<string, unknown>;
84
- }
22
+ declare module '@/services' {
23
+ export interface Services extends LangServices {}
85
24
  }
86
25
 
87
- declare module '@/services' {
88
- interface Services extends LangServices {}
26
+ declare module '@vue/runtime-core' {
27
+ interface ComponentCustomProperties {
28
+ $td: typeof translateWithDefault;
29
+ }
89
30
  }
@@ -0,0 +1,4 @@
1
+ import Lang from './Lang';
2
+
3
+ export const translate = Lang.translate.bind(Lang);
4
+ export const translateWithDefault = Lang.translateWithDefault.bind(Lang);
package/src/main.ts CHANGED
@@ -1,7 +1,9 @@
1
1
  export * from './bootstrap';
2
2
  export * from './components';
3
+ export * from './errors';
3
4
  export * from './forms';
4
5
  export * from './lang';
6
+ export * from './plugins';
5
7
  export * from './services';
6
8
  export * from './ui';
7
9
  export * from './utils';
@@ -0,0 +1,7 @@
1
+ import type { App } from 'vue';
2
+
3
+ import type { AerogelOptions } from '@/bootstrap/options';
4
+
5
+ export interface Plugin {
6
+ install(app: App, options: AerogelOptions): void | Promise<void>;
7
+ }
@@ -0,0 +1,7 @@
1
+ import type { Plugin } from './Plugin';
2
+
3
+ export * from './Plugin';
4
+
5
+ export function definePlugin<T extends Plugin>(plugin: T): T {
6
+ return plugin;
7
+ }
@@ -0,0 +1,16 @@
1
+ import Build from 'virtual:aerogel';
2
+
3
+ import { defineServiceState } from '@/services/Service';
4
+
5
+ export default defineServiceState({
6
+ name: 'app',
7
+ initialState: {
8
+ environment: Build.environment,
9
+ sourceUrl: Build.sourceUrl,
10
+ isMounted: false,
11
+ },
12
+ computed: {
13
+ development: (state) => state.environment === 'development',
14
+ testing: (state) => state.environment === 'testing',
15
+ },
16
+ });
@@ -0,0 +1,15 @@
1
+ import { facade } from '@noeldemartin/utils';
2
+
3
+ import Events from '@/services/Events';
4
+
5
+ import Service from './App.state';
6
+
7
+ export class AppService extends Service {
8
+
9
+ protected async boot(): Promise<void> {
10
+ Events.once('application-mounted', () => this.setState({ isMounted: true }));
11
+ }
12
+
13
+ }
14
+
15
+ export default facade(new AppService());
@@ -1,50 +1,100 @@
1
- import { MagicObject, PromisedValue } from '@noeldemartin/utils';
2
- import { reactive } from 'vue';
1
+ import { MagicObject, PromisedValue, Storage, isEmpty, objectDeepClone, objectOnly } from '@noeldemartin/utils';
3
2
  import type { Constructor } from '@noeldemartin/utils';
3
+ import type { Store } from 'pinia';
4
4
 
5
5
  import ServiceBootError from '@/errors/ServiceBootError';
6
+ import { defineServiceStore } from '@/services/store';
6
7
 
7
8
  export type ServiceState = Record<string, any>; // eslint-disable-line @typescript-eslint/no-explicit-any
8
- export type DefaultServiceState = {};
9
+ export type DefaultServiceState = any; // eslint-disable-line @typescript-eslint/no-explicit-any
9
10
  export type ServiceConstructor<T extends Service = Service> = Constructor<T> & typeof Service;
10
11
 
11
- export function defineServiceState<State extends ServiceState>(options: {
12
+ export type ComputedStateDefinition<TState extends ServiceState, TComputedState extends ServiceState> = {
13
+ [K in keyof TComputedState]: (state: TState) => TComputedState[K];
14
+ } & ThisType<{
15
+ readonly [K in keyof TComputedState]: TComputedState[K];
16
+ }>;
17
+
18
+ export function defineServiceState<
19
+ State extends ServiceState = ServiceState,
20
+ ComputedState extends ServiceState = {}
21
+ >(options: {
22
+ name: string;
12
23
  initialState: State;
13
- }): Constructor<State> & ServiceConstructor {
14
- return class extends Service<State> {
24
+ persist?: (keyof State)[];
25
+ computed?: ComputedStateDefinition<State, ComputedState>;
26
+ serialize?: (state: Partial<State>) => Partial<State>;
27
+ }): Constructor<State> & Constructor<ComputedState> & Constructor<Service<State, ComputedState, Partial<State>>> {
28
+ return class extends Service<State, ComputedState> {
29
+
30
+ public static persist = (options.persist as string[]) ?? [];
31
+
32
+ protected usesStore(): boolean {
33
+ return true;
34
+ }
35
+
36
+ protected getName(): string | null {
37
+ return options.name ?? null;
38
+ }
15
39
 
16
40
  protected getInitialState(): State {
17
41
  return options.initialState;
18
42
  }
43
+
44
+ protected getComputedStateDefinition(): ComputedStateDefinition<State, ComputedState> {
45
+ return options.computed ?? ({} as ComputedStateDefinition<State, ComputedState>);
46
+ }
47
+
48
+ protected serializePersistedState(state: Partial<State>): Partial<State> {
49
+ return options.serialize?.(state) ?? state;
50
+ }
19
51
 
20
- } as unknown as Constructor<State> & ServiceConstructor;
52
+ } as unknown as Constructor<State> &
53
+ Constructor<ComputedState> &
54
+ Constructor<Service<State, ComputedState, Partial<State>>>;
21
55
  }
22
56
 
23
- export default class Service<State extends ServiceState = DefaultServiceState> extends MagicObject {
57
+ export default class Service<
58
+ State extends ServiceState = DefaultServiceState,
59
+ ComputedState extends ServiceState = {},
60
+ ServiceStorage extends Partial<State> = Partial<State>
61
+ > extends MagicObject {
24
62
 
25
- protected _namespace: string;
63
+ public static persist: string[] = [];
64
+
65
+ protected _name: string;
26
66
  private _booted: PromisedValue<void>;
27
- private _state: State;
67
+ private _computedStateKeys: Set<keyof State>;
68
+ private _store?: Store | false;
28
69
 
29
70
  constructor() {
30
71
  super();
31
72
 
32
- this._namespace = new.target.name;
73
+ const getters = this.getComputedStateDefinition();
74
+
75
+ this._name = this.getName() ?? new.target.name;
33
76
  this._booted = new PromisedValue();
34
- this._state = reactive(this.getInitialState());
77
+ this._computedStateKeys = new Set(Object.keys(getters));
78
+ this._store =
79
+ this.usesStore() &&
80
+ defineServiceStore(this._name, {
81
+ state: () => this.getInitialState(),
82
+
83
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
84
+ getters: getters as any,
85
+ });
35
86
  }
36
87
 
37
88
  public get booted(): PromisedValue<void> {
38
89
  return this._booted;
39
90
  }
40
91
 
41
- public launch(namespace?: string): Promise<void> {
42
- const handleError = (error: unknown) => this._booted.reject(new ServiceBootError(this._namespace, error));
43
-
44
- this._namespace = namespace ?? this._namespace;
92
+ public launch(): Promise<void> {
93
+ const handleError = (error: unknown) => this._booted.reject(new ServiceBootError(this._name, error));
45
94
 
46
95
  try {
47
- this.boot()
96
+ this.frameworkBoot()
97
+ .then(() => this.boot())
48
98
  .then(() => this._booted.resolve())
49
99
  .catch(handleError);
50
100
  } catch (error) {
@@ -54,38 +104,116 @@ export default class Service<State extends ServiceState = DefaultServiceState> e
54
104
  return this._booted;
55
105
  }
56
106
 
107
+ public hasState<P extends keyof State>(property: P): boolean {
108
+ if (!this._store) {
109
+ return false;
110
+ }
111
+
112
+ return property in this._store.$state || this._computedStateKeys.has(property);
113
+ }
114
+
115
+ public getState(): State;
116
+ public getState<P extends keyof State>(property: P): State[P];
117
+ public getState<P extends keyof State>(property?: P): State | State[P] {
118
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
119
+ const store = this._store as any;
120
+
121
+ if (property) {
122
+ return store ? store[property] : undefined;
123
+ }
124
+
125
+ return store ? store : {};
126
+ }
127
+
128
+ public setState<P extends keyof State>(property: P, value: State[P]): void;
129
+ public setState(state: Partial<State>): void;
130
+ public setState<P extends keyof State>(stateOrProperty: P | Partial<State>, value?: State[P]): void {
131
+ if (!this._store) {
132
+ return;
133
+ }
134
+
135
+ const state = (
136
+ typeof stateOrProperty === 'string' ? { [stateOrProperty]: value } : stateOrProperty
137
+ ) as Partial<State>;
138
+
139
+ Object.assign(this._store.$state, state);
140
+
141
+ this.onStateUpdated(state);
142
+ }
143
+
57
144
  protected __get(property: string): unknown {
58
- if (!this.hasState(property)) {
59
- return super.__get(property);
145
+ if (this.hasState(property)) {
146
+ return this.getState(property);
60
147
  }
61
148
 
62
- return this.getState(property);
149
+ return super.__get(property);
63
150
  }
64
151
 
65
152
  protected __set(property: string, value: unknown): void {
66
153
  this.setState({ [property]: value } as Partial<State>);
67
154
  }
68
155
 
69
- protected hasState<P extends keyof State>(property: P): boolean {
70
- return property in this._state;
156
+ protected onStateUpdated(state: Partial<State>): void {
157
+ // TODO fix this.static()
158
+ const persist = (this.constructor as unknown as { persist: string[] }).persist;
159
+ const persisted = objectOnly(state, persist);
160
+
161
+ if (isEmpty(persisted)) {
162
+ return;
163
+ }
164
+
165
+ const storage = Storage.require<ServiceStorage>(this._name);
166
+
167
+ Storage.set(this._name, {
168
+ ...storage,
169
+ ...this.serializePersistedState(objectDeepClone(persisted) as Partial<State>),
170
+ });
71
171
  }
72
172
 
73
- protected getState(): State;
74
- protected getState<P extends keyof State>(property: P): State[P];
75
- protected getState<P extends keyof State>(property?: P): State | State[P] {
76
- return property ? this._state[property] : this._state;
173
+ protected usesStore(): boolean {
174
+ return false;
77
175
  }
78
176
 
79
- protected setState(state: Partial<State>): void {
80
- Object.assign(this._state, state);
177
+ protected getName(): string | null {
178
+ return null;
81
179
  }
82
180
 
83
181
  protected getInitialState(): State {
84
182
  return {} as State;
85
183
  }
86
184
 
185
+ protected getComputedStateDefinition(): ComputedStateDefinition<State, ComputedState> {
186
+ return {} as ComputedStateDefinition<State, ComputedState>;
187
+ }
188
+
189
+ protected serializePersistedState(state: Partial<State>): Partial<State> {
190
+ return state;
191
+ }
192
+
193
+ protected async frameworkBoot(): Promise<void> {
194
+ this.restorePersistedState();
195
+ }
196
+
87
197
  protected async boot(): Promise<void> {
88
- //
198
+ // Override.
199
+ }
200
+
201
+ protected restorePersistedState(): void {
202
+ // TODO fix this.static()
203
+ const persist = (this.constructor as unknown as { persist: string[] }).persist;
204
+
205
+ if (!this.usesStore() || isEmpty(persist)) {
206
+ return;
207
+ }
208
+
209
+ if (Storage.has(this._name)) {
210
+ const persisted = Storage.require<ServiceStorage>(this._name);
211
+ this.setState(persisted);
212
+
213
+ return;
214
+ }
215
+
216
+ Storage.set(this._name, objectOnly(this.getState(), persist));
89
217
  }
90
218
 
91
219
  }