@dxtmisha/functional 1.13.5 → 1.13.7

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.
package/CHANGELOG.md CHANGED
@@ -2,8 +2,17 @@
2
2
 
3
3
  All notable changes to this project will be documented in this file.
4
4
 
5
+ ## [1.13.7] - 2026-06-19
6
+
7
+ ### Added
8
+ - **GeoRef**: Added static reactive `getLocation()`, `getLocationCountry()`, and `getLocationLanguage()` methods returning isolated `ComputedRef<string>` representations of location components.
9
+
10
+ ### Fixed
11
+ - **Tests**: Adjusted test assertions in `GeoRef.test.ts` for `'en-VN'` to expect country `'VN'` and standard `'en-VN'` under the country-first matching priority.
12
+
5
13
  ## [1.13.5] - 2026-06-17
6
14
 
15
+
7
16
  ### Changed / Improved
8
17
  - **GeoRef**: Refactored static getters (`getCountry`, `getLanguage`, `getStandard`, `getFirstDay`) to use request-isolated computed references via `ServerStorage.get`. This isolates their reactive state per request, resolving potential cross-request state pollution during SSR.
9
18
 
@@ -0,0 +1,18 @@
1
+ Core Purpose: A high-level reactive framework for Vue 3 that abstracts complex state, API orchestration, and UI design patterns. It provides a standardized layer for API management (including SSR support), data formatting, list manipulation, and design component architecture.
2
+
3
+ Key Expositions:
4
+ 1. API Management: `useApiRef` (standard reactive fetch), `useApiManagementRef` (orchestrates GET/POST/PUT/DELETE with search/formatting), and SSR-specific versions (`useApiAsyncRef`, `useApiManagementAsyncRef`).
5
+ 2. Design System Components: `DesignConstructorAbstract` and `DesignComponents` for building reactive, theme-aware components; `DesignChanged` for tracking property mutations.
6
+ 3. Geo/Intl Utilities: `GeoIntlRef` (localized formatting for numbers, dates, currency, size), `GeoRef` (locale/country state management), and `GeoFlagRef`.
7
+ 4. Reactive Ref Utilities: `ListDataRef` (complex list management, grouping, selection, navigation), `EventRef` (reactive event listeners), and various composables for `localStorage`/`sessionStorage`/`cookies`.
8
+ 5. Functional Helpers: `executeUse` (singleton management: global/provide/local), `computedAsync`/`computedEternity` (advanced reactivity wrappers).
9
+
10
+ Triggers for Studying ai-types.md:
11
+ - When implementing or consuming API requests with `useApi...` hooks to understand data contracts and error handling.
12
+ - When configuring `executeUse` strategies (global vs provide) for service injection.
13
+ - When defining component properties or structures using `Constr...` types (e.g., `ConstrBind`, `ConstrOptions`).
14
+ - When managing complex lists or search logic requiring `ListDataRef` or `Search...` types.
15
+ - When creating custom design classes inheriting from `DesignConstructorAbstract`.
16
+
17
+ Integration Context:
18
+ This library serves as a middleware layer between raw API responses/browser APIs and Vue components. It is designed to work with `@dxtmisha/functional-basic` (the core utility provider) and relies on Vue's reactivity system. It is meant to be registered as a plugin (`dxtFunctionalPlugin`) to provide global configurations for API clients, translation services, and routing.
package/ai-doc.md ADDED
@@ -0,0 +1,226 @@
1
+ This is the main functional library for the Vue environment (@dxtmisha/functional). It contains Vue-specific utilities, composables, and reactive classes.
2
+
3
+ USAGE RULES:
4
+ 1. When developing in Vue, always use this library for functionality, logic, and composables instead of `@dxtmisha/functional-basic` whenever possible.
5
+ 2. It wraps basic non-reactive logic into Vue's reactivity system. If the required function or composable exists here, it has absolute priority.
6
+ 3. Import utilities from `@dxtmisha/functional` for reactive UI behavior, composables, and state management.
7
+
8
+ WORKING WITH API AND STATE (useApi / executeUse):
9
+ A set of composables is provided for network requests: `useApiGet`, `useApiPost`, `useApiPut`, `useApiDelete`, `useApiRequest`, `useApiRef`, `useApiAsyncRef`, `useApiManagementRef`, `useApiManagementAsyncRef`.
10
+ Strictly follow these rules for their application:
11
+
12
+ 1. DO NOT call these composables directly in the Vue components (SFC).
13
+ 2. Move all API configurations and `useApi*` calls into SEPARATE FILES (services/stores).
14
+ 3. Wrap the API configurations inside the `executeUse` factory (specifically: `executeUseGlobal`, `executeUseProvide`, or `executeUseLocal` from `src/functions/executeUse.ts`). This guarantees the creation of managed singletons (single access point) and prevents duplicated requests and reactive states.
15
+ 4. Perform any additional request processing (e.g., data mapping, preparing structures for skeletons before loading a form) in the same file, inside the `executeUse` callback, and return a fully prepared set of data and methods.
16
+ *Example of correct usage:*
17
+ ```ts
18
+ import { executeUseGlobal } from '@dxtmisha/functional';
19
+ import { useApiManagementRef } from '@dxtmisha/functional';
20
+
21
+ export const useUserManagement = executeUseGlobal(() => {
22
+ return useApiManagementRef(
23
+ { path: '/api/users' }, // GET setup
24
+ { date: (v) => new Date(v).toLocaleString() }, // Formatters
25
+ { columns: ['name', 'email'] }, // Search
26
+ { path: '/api/users' }, // POST
27
+ { path: (o) => `/api/users/${o.id}` }, // PUT
28
+ { path: (o) => `/api/users/${o.id}` } // DELETE
29
+ );
30
+ // Logic for skeletons, additional formatting, etc., should be added here,
31
+ // and then return the extended object.
32
+ });
33
+ ```
34
+ 5. Within the Vue component itself, simply import and call your custom singleton composable: `const { list, loading, sendPost } = useUserManagement();`
35
+
36
+ CHOOSING THE executeUse STRATEGY:
37
+ 1. `executeUseLocal` (PREFERRED):
38
+ - When to use: For most API requests and services.
39
+ - Key Features: Works "lazily" (lazy initialization) — initializes only when first called. The instance persists until the end of the session. This prevents overloading the application start with unnecessary requests.
40
+ 2. `executeUseGlobal`:
41
+ - When to use: When data or a service must be loaded/initialized IMMEDIATELY at application start (e.g., critical settings, SDKs).
42
+ - Key Features: Creates a single instance for the entire application. All global singletons are forcibly initialized via `executeUseGlobalInit()`.
43
+ 3. `executeUseProvide`:
44
+ - When to use: For state shared between a parent and a group of child components (e.g., tabs, complex forms with sub-components).
45
+ - Key Features: Uses provide/inject. The first component in the tree that calls the hook becomes the "provider", others become consumers.
46
+
47
+ =============================================================================
48
+ DEVELOPER GUIDE: USING `@dxtmisha/functional` AS A LIBRARY
49
+ =============================================================================
50
+
51
+ This section contains instructions and code guidelines for AI models on how to import and use the Vue-specific reactive classes, composables, and utility functions provided by this library in Vue 3 / Nuxt applications.
52
+
53
+ ---
54
+
55
+ ### 1. Reactive Storage & State Composables
56
+
57
+ These composables bind browser storages reactively to Vue `Ref` objects, keeping them in sync.
58
+
59
+ #### `useStorageRef` (localStorage)
60
+ Reactively binds a key from `localStorage`.
61
+ ```typescript
62
+ import { useStorageRef } from '@dxtmisha/functional';
63
+
64
+ // Bind to key with optional initial default value
65
+ const theme = useStorageRef<'light' | 'dark'>('theme_key', 'light');
66
+
67
+ // Setting the value triggers an immediate update to localStorage reactively
68
+ theme.value = 'dark';
69
+ ```
70
+
71
+ #### `useSessionRef` (sessionStorage) & `useCookieRef` (Cookies)
72
+ ```typescript
73
+ import { useSessionRef, useCookieRef } from '@dxtmisha/functional';
74
+
75
+ // sessionStorage
76
+ const step = useSessionRef<number>('form_step', 1);
77
+
78
+ // CookieStorage
79
+ const token = useCookieRef<string>('auth_token', '', { secure: true });
80
+ ```
81
+
82
+ #### `useBroadcastValueRef` (Cross-Tab Synchronization)
83
+ Synchronizes a state value reactively across multiple browser tabs under the same origin.
84
+ ```typescript
85
+ import { useBroadcastValueRef } from '@dxtmisha/functional';
86
+
87
+ // Synchronizes the value of the ref across tabs using BroadcastChannel
88
+ const syncState = useBroadcastValueRef<string>('active_channel', 'idle');
89
+ ```
90
+
91
+ #### `useHashRef` (URL Hash)
92
+ Reactively binds Vue state to the URL hash parameters.
93
+ ```typescript
94
+ import { useHashRef } from '@dxtmisha/functional';
95
+
96
+ const hashPage = useHashRef<string>('page', 'home');
97
+ ```
98
+
99
+ ---
100
+
101
+ ### 2. Reactive Geolocation & Internationalization (`GeoRef`, `GeoIntlRef`, `GeoFlagRef`, `useTranslateRef`)
102
+
103
+ Provides reactive integrations for internationalization APIs.
104
+
105
+ #### `GeoRef` & `GeoIntlRef`
106
+ ```typescript
107
+ import { GeoRef, useGeoIntlRef } from '@dxtmisha/functional';
108
+
109
+ // Reactive tracking of user location details
110
+ const currentCountry = GeoRef.getCountry(); // ComputedRef<string>
111
+
112
+ // Reactive i18n formatter hook
113
+ const intl = useGeoIntlRef();
114
+ const formattedPrice = intl.currency(150, 'EUR'); // ComputedRef<string>
115
+ ```
116
+
117
+ #### `useTranslateRef`
118
+ Reactively loads and gets translation tokens.
119
+ ```typescript
120
+ import { useTranslateRef } from '@dxtmisha/functional';
121
+
122
+ const translations = useTranslateRef(['global.save', 'global.cancel']);
123
+ // returns: ShallowRef<Record<string, string>> containing loaded translations
124
+ ```
125
+
126
+ ---
127
+
128
+ ### 3. SEO & Layout Utilities
129
+
130
+ #### `useMeta`
131
+ Manages page metadata reactively. Calling setters will update document headers and tags reactively.
132
+ ```typescript
133
+ import { useMeta } from '@dxtmisha/functional';
134
+
135
+ const metaManager = useMeta();
136
+ metaManager.setTitle('My Product Page');
137
+ metaManager.setDescription('Product details and configurations.');
138
+ ```
139
+
140
+ #### `ScrollbarWidthRef`
141
+ Tracks the scrollbar width reactively to solve layout shift issues.
142
+ ```typescript
143
+ import { ScrollbarWidthRef } from '@dxtmisha/functional';
144
+
145
+ const scrollbar = new ScrollbarWidthRef();
146
+ const width = scrollbar.width; // Ref<number>
147
+ const hasScroll = scrollbar.is; // ComputedRef<boolean>
148
+ ```
149
+
150
+ ---
151
+
152
+ ### 4. Advanced Reactivity Helpers
153
+
154
+ #### `computedAsync`
155
+ Creates a computed property that resolves its value asynchronously. Useful for async tasks inside computed getters.
156
+ ```typescript
157
+ import { computedAsync } from '@dxtmisha/functional';
158
+
159
+ // Performs asynchronous data lookup and reactively returns the result
160
+ const asyncData = computedAsync(async () => {
161
+ return await fetchSomeData(activeId.value);
162
+ }, 'initial_loading_value');
163
+ ```
164
+
165
+ #### `computedEternity`
166
+ Computes an asynchronous value once and caches it indefinitely unless manually refreshed.
167
+ ```typescript
168
+ import { computedEternity } from '@dxtmisha/functional';
169
+
170
+ const cachedData = computedEternity(async () => {
171
+ return await fetchStaticData();
172
+ }, 'loading_state');
173
+ ```
174
+
175
+ ---
176
+
177
+ ### 5. List & Search Orchestration
178
+
179
+ #### `ListDataRef`
180
+ A powerful reactive state orchestrator for managing lists, groups, items, pagination, highlight paths, and selections.
181
+ ```typescript
182
+ import { ListDataRef } from '@dxtmisha/functional';
183
+
184
+ const items = ref([
185
+ { value: 'id1', label: 'First Option' },
186
+ { value: 'id2', label: 'Second Option' },
187
+ ]);
188
+ const selectedId = ref('id1');
189
+
190
+ const listData = new ListDataRef(items, selectedId);
191
+ const isSelected = listData.isSelected; // ComputedRef<boolean>
192
+ const nextItem = listData.getSelectedNext(); // returns next select item
193
+ ```
194
+
195
+ #### `useSearchRef`
196
+ Combines a source list, target fields, search query, and options to reactively search a list with built-in delay and highlight support.
197
+ ```typescript
198
+ import { useSearchRef } from '@dxtmisha/functional';
199
+
200
+ const query = ref('second');
201
+ const { listSearch, loading, length } = useSearchRef(items, ['label'], query);
202
+ ```
203
+
204
+ ---
205
+
206
+ ### 6. DOM & Lazy Rendering
207
+
208
+ #### `EventRef`
209
+ Reactive wrapper for DOM events. Starts and stops event binding cleanly inside Vue component lifecycles (runs setup and teardown hooks automatically).
210
+ ```typescript
211
+ import { EventRef } from '@dxtmisha/functional';
212
+
213
+ // Listens reactively; auto-starts on setup and auto-stops on unmounted
214
+ const keyListener = new EventRef(window, window, 'keydown', (event) => {
215
+ console.log('Key pressed', event.key);
216
+ });
217
+ ```
218
+
219
+ #### `useLazyRef`
220
+ Reactive manager utilizing `IntersectionObserver` to defer rendering of off-screen components.
221
+ ```typescript
222
+ import { useLazyRef } from '@dxtmisha/functional';
223
+
224
+ const lazyManager = useLazyRef();
225
+ const isVisible = lazyManager.addLazyItem(elementRef); // ShallowRef<boolean>
226
+ ```
@@ -16,10 +16,6 @@ The following is the content of "exports" from package.json:
16
16
 
17
17
  // File: src/classes/design/DesignAbstract.d.ts
18
18
  export declare abstract class DesignAbstract<T extends Record<string, any>, C extends Record<string, any>> {
19
- protected readonly props: T;
20
- protected readonly callback?: ((event: C) => void) | undefined;
21
- protected readonly event: C;
22
- protected readonly changed: DesignChanged<T>;
23
19
  constructor(props: T, callback?: ((event: C) => void) | undefined, changed?: string[]);
24
20
  make(compelled?: boolean): this;
25
21
  makeCallback(compelled?: boolean): void;
@@ -35,8 +31,6 @@ export declare abstract class DesignAsyncAbstract<T extends Record<string, any>,
35
31
 
36
32
  // File: src/classes/design/DesignChanged.d.ts
37
33
  export declare class DesignChanged<T extends Record<string, any>> {
38
- protected readonly props: T;
39
- protected readonly watch: string[];
40
34
  constructor(props: T, watch?: string[]);
41
35
  is(name: string | string[]): boolean;
42
36
  isChanged(): boolean;
@@ -49,9 +43,6 @@ export declare class DesignComp<COMP extends ConstrComponent, P extends ConstrIt
49
43
 
50
44
  // File: src/classes/design/DesignComponents.d.ts
51
45
  export declare class DesignComponents<COMP extends ConstrComponent, P extends ConstrItem> {
52
- protected readonly components: COMP;
53
- protected readonly modification?: ConstrComponentMod<P> | undefined;
54
- protected caching: Record<string, ComputedRef<any>>;
55
46
  constructor(components?: COMP, modification?: ConstrComponentMod<P> | undefined);
56
47
  is<K extends keyof COMP>(name: K): name is K;
57
48
  get<K extends keyof COMP>(name: K): COMP[K];
@@ -63,20 +54,6 @@ export declare class DesignComponents<COMP extends ConstrComponent, P extends Co
63
54
 
64
55
  // File: src/classes/design/DesignConstructorAbstract.d.ts
65
56
  export declare abstract class DesignConstructorAbstract<E extends Element, COMP extends ConstrComponent, EMITS extends ConstrItem, EXPOSE extends ConstrItem, SLOTS extends ConstrItem, CLASSES extends ConstrClasses, P extends ConstrItem> {
66
- protected readonly props: Readonly<P>;
67
- protected readonly options?: ConstrOptions<COMP, EMITS, P> | undefined;
68
- protected readonly name: string[];
69
- protected readonly element: Ref<E | undefined, E | undefined>;
70
- protected readonly refs: ToRefs<P>;
71
- protected readonly components: DesignComponents<COMP, P>;
72
- protected readonly emits?: ConstrEmit<EMITS>;
73
- protected readonly classes?: ComputedRef<CLASSES>;
74
- protected classesSub?: ComputedRef<Partial<CLASSES>>;
75
- protected readonly styles?: ComputedRef<ConstrStyles>;
76
- protected stylesSub?: ComputedRef<ConstrStyles>;
77
- protected attrs?: ConstrItem;
78
- protected slots?: SLOTS;
79
- protected dataExpose?: EXPOSE;
80
57
  protected constructor(name: string, props: Readonly<P>, options?: ConstrOptions<COMP, EMITS, P> | undefined);
81
58
  protected init(): this;
82
59
  getName(): string;
@@ -91,24 +68,10 @@ export declare abstract class DesignConstructorAbstract<E extends Element, COMP
91
68
  protected abstract initClasses(): Partial<CLASSES>;
92
69
  protected abstract initStyles(): ConstrStyles;
93
70
  protected abstract initRender(): VNode | (VNode | any)[] | undefined;
94
- protected initSlot<K extends keyof SLOTS>(name: K, children?: any[], props?: ConstrItem): VNode | undefined;
95
- protected toClass(classes?: ConstrClass): ConstrClassObject;
96
- protected toClassName<T extends ConstrItem>(classes?: ConstrItem): T;
97
71
  }
98
72
 
99
73
  // File: src/classes/ref/DatetimeRef.d.ts
100
74
  export declare class DatetimeRef {
101
- protected item: Ref<NumberOrStringOrDate>;
102
- protected type: Ref<GeoDate>;
103
- protected code: Ref<string>;
104
- protected date: Ref<Date>;
105
- protected datetime: Datetime;
106
- protected year: Ref<number, number>;
107
- protected month: Ref<number, number>;
108
- protected day: Ref<number, number>;
109
- protected hour: Ref<number, number>;
110
- protected minute: Ref<number, number>;
111
- protected second: Ref<number, number>;
112
75
  constructor(date: RefOrNormal<NumberOrStringOrDate>, type?: RefOrNormal<GeoDate>, code?: RefOrNormal<string>);
113
76
  getItem(): Ref<NumberOrStringOrDate>;
114
77
  getDate(): Ref<Date>;
@@ -138,7 +101,6 @@ export declare class EventRef<E extends ElementOrWindow, O extends Event, D exte
138
101
 
139
102
  // File: src/classes/ref/GeoFlagRef.d.ts
140
103
  export declare class GeoFlagRef {
141
- protected flag: ComputedRef<GeoFlag>;
142
104
  constructor(code?: RefOrNormal<string | undefined>);
143
105
  getCode(): string;
144
106
  get(code?: RefOrNormal<string>): ComputedRef<GeoFlagItem | undefined>;
@@ -181,25 +143,15 @@ export declare class GeoRef {
181
143
  static getLanguage(): ComputedRef<string>;
182
144
  static getStandard(): ComputedRef<string>;
183
145
  static getFirstDay(): ComputedRef<string>;
146
+ static getLocation(): ComputedRef<string>;
147
+ static getLocationCountry(): ComputedRef<string>;
148
+ static getLocationLanguage(): ComputedRef<string>;
184
149
  static set(code: string): void;
185
150
  static setValueDefault(code?: string | (() => string)): void;
186
151
  }
187
152
 
188
153
  // File: src/classes/ref/ListDataRef.d.ts
189
154
  export declare class ListDataRef {
190
- protected readonly list: RefOrNormal<ListListInput | undefined>;
191
- protected readonly focus?: RefType<ListSelectedItem | undefined> | undefined;
192
- protected readonly highlight?: RefType<string | undefined> | undefined;
193
- protected readonly highlightLengthStart?: RefType<number | undefined> | undefined;
194
- protected readonly filterMode?: RefType<boolean | undefined> | undefined;
195
- protected readonly selected?: RefType<ListSelectedList | undefined> | undefined;
196
- protected readonly keyValue?: RefType<string | undefined> | undefined;
197
- protected readonly keyLabel?: RefType<string | undefined> | undefined;
198
- protected readonly lite?: RefType<number | undefined> | undefined;
199
- protected readonly min: RefOrNormal<number | string | undefined>;
200
- protected readonly max: RefOrNormal<number | string | undefined>;
201
- protected readonly parent?: string | undefined;
202
- protected subList: Record<any, ListDataRef>;
203
155
  constructor(list: RefOrNormal<ListListInput | undefined>, focus?: RefType<ListSelectedItem | undefined> | undefined, highlight?: RefType<string | undefined> | undefined, highlightLengthStart?: RefType<number | undefined> | undefined, filterMode?: RefType<boolean | undefined> | undefined, selected?: RefType<ListSelectedList | undefined> | undefined, keyValue?: RefType<string | undefined> | undefined, keyLabel?: RefType<string | undefined> | undefined, lite?: RefType<number | undefined> | undefined, min?: RefOrNormal<number | string | undefined>, max?: RefOrNormal<number | string | undefined>, parent?: string | undefined);
204
156
  readonly data: ComputedRef<ListList>;
205
157
  readonly liteData: ComputedRef<ListList>;
@@ -415,23 +367,71 @@ export declare const useLazyItemByMarginRef: (element: RefType<HTMLElement | und
415
367
 
416
368
  // File: src/composables/ref/useLazyRef.d.ts
417
369
  export type LazyItem = { status: ShallowRef<boolean>; ratio: ShallowRef<number>; entry: ShallowRef<IntersectionObserverEntry | undefined>; stopWatch: () => void; };
418
- export type LazyList = Record<string, LazyItem>;
419
- export declare const useLazyRef: (options?: IntersectionObserverInit) => { intersectionObserver: IntersectionObserver | undefined; getItem(element: HTMLElement): LazyItem; addLazyItem(element: Ref<HTMLElement | undefined>): ShallowRef<boolean, boolean>; removeLazyItem: (element?: HTMLElement) => void; disconnectLazy: () => void | undefined; };
370
+ export declare const useLazyRef: (options?: IntersectionObserverInit) => {
371
+ intersectionObserver: IntersectionObserver | undefined;
372
+ getItem(element: HTMLElement): LazyItem;
373
+ addLazyItem(element: Ref<HTMLElement | undefined>): ShallowRef<boolean, boolean>;
374
+ removeLazyItem: (element?: HTMLElement) => void;
375
+ disconnectLazy: () => void | undefined;
376
+ };
420
377
 
421
378
  // File: src/composables/ref/useLoadingRef.d.ts
422
379
  export declare function useLoadingRef(): ShallowRef<boolean, boolean>;
423
380
 
424
381
  // File: src/composables/ref/useMeta.d.ts
425
- export declare const useMeta: () => Readonly<{ meta: typeof MetaStatic; title: Ref<string, string>; keyword: Ref<string, string>; description: Ref<string, string>; author: Ref<string, string>; image: Ref<string, string>; canonical: Ref<string, string>; robots: Ref<MetaRobots, MetaRobots>; siteName: Ref<string, string>; getHtmlMeta: () => string; sync: () => void; update: () => void; updateSsr: () => void; setTitle: (value: string) => void; setKeywords: (value: string) => void; setDescription: (value: string) => void; setAuthor: (value: string) => void; setImage: (value: string) => void; setCanonical: (value: string) => void; setRobots: (value: MetaRobots) => void; setSiteName: (value: string) => void; setSuffix: (suffix: string) => typeof MetaStatic; } & { init(): Readonly<any>; destroyExecute?(): void; }>;
382
+ export declare const useMeta: () => Readonly<{
383
+ meta: typeof MetaStatic;
384
+ title: Ref<string, string>;
385
+ keyword: Ref<string, string>;
386
+ description: Ref<string, string>;
387
+ author: Ref<string, string>;
388
+ image: Ref<string, string>;
389
+ canonical: Ref<string, string>;
390
+ robots: Ref<MetaRobots, MetaRobots>;
391
+ siteName: Ref<string, string>;
392
+ getHtmlMeta: () => string;
393
+ sync: () => void;
394
+ update: () => void;
395
+ updateSsr: () => void;
396
+ setTitle: (value: string) => void;
397
+ setKeywords: (value: string) => void;
398
+ setDescription: (value: string) => void;
399
+ setAuthor: (value: string) => void;
400
+ setImage: (value: string) => void;
401
+ setCanonical: (value: string) => void;
402
+ setRobots: (value: MetaRobots) => void;
403
+ setSiteName: (value: string) => void;
404
+ setSuffix: (suffix: string) => typeof MetaStatic;
405
+ } & {
406
+ init(): any;
407
+ destroyExecute?(): void;
408
+ }>;
426
409
 
427
410
  // File: src/composables/ref/useRouterList.d.ts
428
- export declare const useRouterList: <T extends ListDataBasic>(list: RefType<ConstrBind<T>[] | undefined>, selected?: Ref<string> | string, hasTo?: boolean) => { item: ComputedRef<T | undefined>; selected: Ref<string, string>; label: ComputedRef<NumberOrString>; list: ComputedRef<ConstrBind<T>[]>; to: (name?: string) => void; toMain(): void; };
411
+ export declare const useRouterList: <T extends ListDataBasic>(list: RefType<ConstrBind<T>[] | undefined>, selected?: Ref<string> | string, hasTo?: boolean) => {
412
+ item: ComputedRef<T | undefined>;
413
+ selected: Ref<string, string>;
414
+ label: ComputedRef<NumberOrString>;
415
+ list: ComputedRef<ConstrBind<T>[]>;
416
+ to: (name?: string) => void;
417
+ toMain(): void;
418
+ };
429
419
 
430
420
  // File: src/composables/ref/useSearchRef.d.ts
431
- export declare function useSearchRef<T extends SearchItem, K extends SearchColumns<T>>(list: SearchListInput<T>, columns: K, value?: Ref<string>, options?: SearchOptions): { isSearch: ComputedRef<boolean>; search: Ref<string, string>; loading: Ref<boolean, boolean>; listSearch: ComputedRef<SearchFormatList<T, K>>; length: ComputedRef<number>; };
421
+ export declare function useSearchRef<T extends SearchItem, K extends SearchColumns<T>>(list: SearchListInput<T>, columns: K, value?: Ref<string>, options?: SearchOptions): {
422
+ isSearch: ComputedRef<boolean>;
423
+ search: Ref<string, string>;
424
+ loading: Ref<boolean, boolean>;
425
+ listSearch: ComputedRef<SearchFormatList<T, K>>;
426
+ length: ComputedRef<number>;
427
+ };
432
428
 
433
429
  // File: src/composables/ref/useSearchValueRef.d.ts
434
- export declare function useSearchValueRef<T extends SearchItem, K extends SearchColumns<T>>(item: SearchList<T, K>, value?: Ref<string>): { search: Ref<string, string>; searchDelay: Ref<string, string>; loading: Ref<boolean, boolean>; };
430
+ export declare function useSearchValueRef<T extends SearchItem, K extends SearchColumns<T>>(item: SearchList<T, K>, value?: Ref<string>): {
431
+ search: Ref<string, string>;
432
+ searchDelay: Ref<string, string>;
433
+ loading: Ref<boolean, boolean>;
434
+ };
435
435
 
436
436
  // File: src/composables/ref/useSessionRef.d.ts
437
437
  export declare function useSessionRef<T>(name: string, defaultValue?: T | (() => T)): Ref<T | undefined>;
@@ -459,16 +459,25 @@ export declare function computedByLanguage<T, R extends (T | undefined) = T | un
459
459
  export declare function computedEternity<T>(getter: () => Promise<T> | T, initialState?: (() => T) | T): Ref<T, T>;
460
460
 
461
461
  // File: src/functions/dxtFunctionalPlugin.d.ts
462
- export interface FunctionalPluginOptions { api?: ApiConfig; translate?: TranslateConfig; location?: string | (() => string); metaSuffix?: string; icons?: IconsConfig; router?: Router; errorCauses?: ErrorCenterCauseList; errorHandlers?: ErrorCenterHandlerList; }
462
+ export interface FunctionalPluginOptions {
463
+ api?: ApiConfig;
464
+ translate?: TranslateConfig;
465
+ location?: string | (() => string);
466
+ metaSuffix?: string;
467
+ icons?: IconsConfig;
468
+ router?: Router;
469
+ errorCauses?: ErrorCenterCauseList;
470
+ errorHandlers?: ErrorCenterHandlerList;
471
+ }
463
472
  export declare const dxtFunctionalPlugin: Plugin;
464
473
 
465
474
  // File: src/functions/executeUse.d.ts
466
475
  export declare enum ExecuteUseType { global = "global", provide = "provide", local = "local" }
467
476
  export type ExecuteUseReturn<R> = Readonly<R & { init(): Readonly<R>; destroyExecute?(): void; }>;
468
477
  export declare function executeUse<R, O extends any[], RI extends ExecuteUseReturn<R> = ExecuteUseReturn<R>>(callback: (...args: O) => R, type?: ExecuteUseType): ((...args: O) => RI) | (() => RI);
469
- export declare function executeUseGlobal<R>(callback: () => R): (() => Readonly<any>) | (() => Readonly<any>);
470
- export declare function executeUseProvide<R, O extends any[]>(callback: (...args: O) => R): ((...args: O) => Readonly<any>) | (() => Readonly<any>);
471
- export declare function executeUseLocal<R, O extends any[]>(callback: (...args: O) => R): ((...args: O) => Readonly<any>) | (() => Readonly<any>);
478
+ export declare function executeUseGlobal<R>(callback: () => R): any;
479
+ export declare function executeUseProvide<R, O extends any[]>(callback: (...args: O) => R): any;
480
+ export declare function executeUseLocal<R, O extends any[]>(callback: (...args: O) => R): any;
472
481
  export declare function executeUseGlobalInit(): void;
473
482
 
474
483
  // File: src/functions/getInject.d.ts
@@ -513,12 +522,98 @@ export declare function toBind<R extends ItemList = ItemList>(extra: ItemList, v
513
522
  // File: src/functions/toBinds.d.ts
514
523
  export declare function toBinds<R extends ItemList = ItemList>(...values: (ItemList | undefined)[]): ConstrBind<R>;
515
524
 
525
+ // File: src/library.d.ts
526
+ export * from './classes/design/DesignAbstract';
527
+ export * from './classes/design/DesignAsyncAbstract';
528
+ export * from './classes/design/DesignChanged';
529
+ export * from './classes/design/DesignComp';
530
+ export * from './classes/design/DesignComponents';
531
+ export * from './classes/design/DesignConstructorAbstract';
532
+ export * from './classes/ref/DatetimeRef';
533
+ export * from './classes/ref/EffectScopeGlobal';
534
+ export * from './classes/ref/EventRef';
535
+ export * from './classes/ref/GeoFlagRef';
536
+ export * from './classes/ref/GeoIntlRef';
537
+ export * from './classes/ref/GeoRef';
538
+ export * from './classes/ref/ListDataRef';
539
+ export * from './classes/ref/RouterItemRef';
540
+ export * from './classes/ref/ScrollbarWidthRef';
541
+ export * from './composables/ref/useApiAsyncRef';
542
+ export * from './composables/ref/useApiDelete';
543
+ export * from './composables/ref/useApiGet';
544
+ export * from './composables/ref/useApiManagementAsyncRef';
545
+ export * from './composables/ref/useApiManagementRef';
546
+ export * from './composables/ref/useApiPost';
547
+ export * from './composables/ref/useApiPut';
548
+ export * from './composables/ref/useApiRef';
549
+ export * from './composables/ref/useApiRequest';
550
+ export * from './composables/ref/useBroadcastValueRef';
551
+ export * from './composables/ref/useCookieRef';
552
+ export * from './composables/ref/useFormattersRef';
553
+ export * from './composables/ref/useGeoIntlRef';
554
+ export * from './composables/ref/useHashRef';
555
+ export * from './composables/ref/useLazyItemByMarginRef';
556
+ export * from './composables/ref/useLazyRef';
557
+ export * from './composables/ref/useLoadingRef';
558
+ export * from './composables/ref/useMeta';
559
+ export * from './composables/ref/useRouterList';
560
+ export * from './composables/ref/useSearchRef';
561
+ export * from './composables/ref/useSearchValueRef';
562
+ export * from './composables/ref/useSessionRef';
563
+ export * from './composables/ref/useStorageRef';
564
+ export * from './composables/ref/useTranslateRef';
565
+ export * from './functions/basic';
566
+ export * from './functions/computedAsync';
567
+ export * from './functions/computedByLanguage';
568
+ export * from './functions/computedEternity';
569
+ export * from './functions/dxtFunctionalPlugin';
570
+ export * from './functions/executeUse';
571
+ export * from './functions/getInject';
572
+ export * from './functions/getOptions';
573
+ export * from './functions/ref/executeFunctionRef';
574
+ export * from './functions/ref/getApiErrorRef';
575
+ export * from './functions/ref/getBindRef';
576
+ export * from './functions/ref/getRef';
577
+ export * from './functions/ref/render';
578
+ export * from './functions/ref/setRef';
579
+ export * from './functions/ref/toRefItem';
580
+ export * from './functions/render/getBind';
581
+ export * from './functions/render/getClassName';
582
+ export * from './functions/render/getIndexForRender';
583
+ export * from './functions/toBind';
584
+ export * from './functions/toBinds';
585
+ export * from './types/apiTypes';
586
+ export * from './types/constructorTypes';
587
+ export * from './types/listTypes';
588
+ export * from './types/refTypes';
589
+ export * from './types/searchTypes';
590
+
516
591
  // File: src/types/apiTypes.d.ts
517
592
  export type ApiOptions = ApiMethodItem | RefOrNormal<ApiFetch>;
518
593
  export type ApiManagementValue = ApiDefaultValue | ApiDefaultValue[];
519
- export type ApiManagementGet<Return extends ApiManagementValue, Type extends ApiManagementValue = Return> = { path?: RefOrNormal<string | undefined>; options?: ApiOptions; reactivity?: boolean; conditions?: RefType<boolean>; transformation?: (data: Type, isResponseContractValid?: ApiDataValidation) => ApiData<Return>; validateResponseContract?: (data: Type) => ApiDataValidation; errorContract?: ApiErrorStorageList; typeData?: ((data: Return) => boolean) | any; unmounted?: boolean; skeleton?: () => Return; };
594
+ export type ApiManagementGet<Return extends ApiManagementValue, Type extends ApiManagementValue = Return> = {
595
+ path?: RefOrNormal<string | undefined>;
596
+ options?: ApiOptions;
597
+ reactivity?: boolean;
598
+ conditions?: RefType<boolean>;
599
+ transformation?: (data: Type, isResponseContractValid?: ApiDataValidation) => ApiData<Return>;
600
+ validateResponseContract?: (data: Type) => ApiDataValidation;
601
+ errorContract?: ApiErrorStorageList;
602
+ typeData?: ((data: Return) => boolean) | any;
603
+ unmounted?: boolean;
604
+ skeleton?: () => Return;
605
+ };
520
606
  export type ApiManagementSearch<T extends SearchItem, K extends SearchColumns<T>> = { columns: K; value?: Ref<string>; options?: SearchOptions; };
521
- export type ApiManagementRequest<T, Request extends ApiFetch['request'] = ApiFetch['request'], Return extends ApiData<T> = ApiData<T>> = { path?: RefOrNormal<string | undefined>; action?: (data: Return | undefined) => Promise<void> | void; transformation?: (data: T) => Return; validateRequestContract?: (data: Request) => ApiDataValidation & Return; validateResponseContract?: (data: T) => ApiDataValidation & Return; errorContract?: ApiErrorStorageList; toData?: boolean; options?: ApiOptions; };
607
+ export type ApiManagementRequest<T, Request extends ApiFetch['request'] = ApiFetch['request'], Return extends ApiData<T> = ApiData<T>> = {
608
+ path?: RefOrNormal<string | undefined>;
609
+ action?: (data: Return | undefined) => Promise<void> | void;
610
+ transformation?: (data: T) => Return;
611
+ validateRequestContract?: (data: Request) => ApiDataValidation & Return;
612
+ validateResponseContract?: (data: T) => ApiDataValidation & Return;
613
+ errorContract?: ApiErrorStorageList;
614
+ toData?: boolean;
615
+ options?: ApiOptions;
616
+ };
522
617
 
523
618
  // File: src/types/constructorTypes.d.ts
524
619
  export type ConstrItem = Record<string, any>;
@@ -535,8 +630,19 @@ export type ConstrClassList = Record<string, ConstrClass>;
535
630
  export type ConstrClasses = { main: ConstrClass; } & ConstrClassList;
536
631
  export type ConstrStylesItem = string | null;
537
632
  export type ConstrStyles = Record<string, ConstrStylesItem> | ConstrStyles[];
538
- export type ConstrOptions<COMP extends ConstrComponent, EMITS extends ConstrItem, P extends ConstrItem> = { components?: COMP; compMod?: ConstrComponentMod<P>; emits?: ConstrEmit<EMITS>; classes?: RefType<ConstrClasses>; styles?: RefType<ConstrStyles>; };
539
- export type ConstrSetup<E extends Element, CLASSES extends ConstrClasses, SETUP extends ConstrItem> = { name: string; element: Ref<E | undefined>; classes: RefType<CLASSES>; styles: RefType<ConstrStyles>; } & SETUP;
633
+ export type ConstrOptions<COMP extends ConstrComponent, EMITS extends ConstrItem, P extends ConstrItem> = {
634
+ components?: COMP;
635
+ compMod?: ConstrComponentMod<P>;
636
+ emits?: ConstrEmit<EMITS>;
637
+ classes?: RefType<ConstrClasses>;
638
+ styles?: RefType<ConstrStyles>;
639
+ };
640
+ export type ConstrSetup<E extends Element, CLASSES extends ConstrClasses, SETUP extends ConstrItem> = {
641
+ name: string;
642
+ element: Ref<E | undefined>;
643
+ classes: RefType<CLASSES>;
644
+ styles: RefType<ConstrStyles>;
645
+ } & SETUP;
540
646
  export type ConstrRegistration = { flag?: boolean; translate?: Record<string, string>; };
541
647
  export type ConstrBind<T> = T & Record<string, any> & { key?: string; class?: ConstrClass; style?: ConstrStyles; };
542
648
  export type ConstrPropItemOptions<T = any> = { type?: PropType<T>; required?: boolean; default?: any; validator?(value: any, props: any): boolean; };
package/dist/library.js CHANGED
@@ -368,6 +368,15 @@ var Oe = class {
368
368
  static getFirstDay() {
369
369
  return y.get("__ui:geo-ref-first-day__", () => I(() => this.get().value.firstDay));
370
370
  }
371
+ static getLocation() {
372
+ return y.get("__ui:geo-ref-location__", () => I(() => this.get().value.location));
373
+ }
374
+ static getLocationCountry() {
375
+ return y.get("__ui:geo-ref-location-country__", () => I(() => this.get().value.locationCountry));
376
+ }
377
+ static getLocationLanguage() {
378
+ return y.get("__ui:geo-ref-location-language__", () => I(() => this.get().value.locationLanguage));
379
+ }
371
380
  static set(e) {
372
381
  u.set(e, !0), this.get().value = u.getItem();
373
382
  }
@@ -43,6 +43,27 @@ export declare class GeoRef {
43
43
  * реактивная строка, представляющая первый день недели
44
44
  */
45
45
  static getFirstDay(): ComputedRef<string>;
46
+ /**
47
+ * Current location string.
48
+ *
49
+ * Текущее местоположение.
50
+ * @returns reactive string with the current location/ реактивная строка с текущим местоположением
51
+ */
52
+ static getLocation(): ComputedRef<string>;
53
+ /**
54
+ * Current country code from the location.
55
+ *
56
+ * Текущий код страны из местоположения.
57
+ * @returns reactive string with the current country code from location/ реактивная строка с кодом текущей страны из местоположения
58
+ */
59
+ static getLocationCountry(): ComputedRef<string>;
60
+ /**
61
+ * Current language code from the location.
62
+ *
63
+ * Текущий код языка из местоположения.
64
+ * @returns reactive string with the current language code from location/ реактивная строка с кодом текущего языка из местоположения
65
+ */
66
+ static getLocationLanguage(): ComputedRef<string>;
46
67
  /**
47
68
  * Changes the data by the full code.
48
69
  *
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@dxtmisha/functional",
3
3
  "private": false,
4
- "version": "1.13.5",
4
+ "version": "1.13.7",
5
5
  "type": "module",
6
6
  "description": "A comprehensive library of utilities, base classes, and Vue 3 composables for reactive web development. Extends @dxtmisha/functional-basic with Composition API.",
7
7
  "keywords": [
@@ -46,10 +46,9 @@
46
46
  },
47
47
  "files": [
48
48
  "dist",
49
- "ai-description.txt",
50
- "ai-doc.ru.txt",
51
- "ai-doc.txt",
52
- "ai-types.txt",
49
+ "ai-description.md",
50
+ "ai-doc.md",
51
+ "ai-types.md",
53
52
  "CHANGELOG.md",
54
53
  "LICENSE",
55
54
  "package.json",
@@ -1,18 +0,0 @@
1
- This library is a collection of Vue 3-based utility classes and composables designed for building complex, reactive, and SSR-ready interfaces. It provides a standardized framework for API management, component state, geographic/localization data, and dynamic rendering.
2
-
3
- 1. Core Purpose:
4
- An infrastructure-level toolkit for Vue 3 that abstracts asynchronous data fetching, state management, and UI rendering logic. It provides structured classes and composables to handle API lifecycle (GET/POST/PUT/DELETE), reactive data transformations, internationalization (Intl), and component orchestration.
5
-
6
- 2. Usage Scenarios:
7
- - API Orchestration: When building complex forms, data tables, or dashboards requiring integrated state, validation (via @effect/schema compatibility), and SSR support. Use `useApiManagementRef` for unified CRUD handling or `useApiRef` for individual requests.
8
- - Reactive Data Management: When you need synchronized data across browser tabs (`useBroadcastValueRef`) or persistence across reloads (`useStorageRef`, `useCookieRef`).
9
- - Localization & Formatting: When the application needs to dynamically handle geographic data, currency formatting, file sizes, or date manipulation via `GeoIntlRef` and `useGeoIntlRef`.
10
- - Component Design System: When building modular UI components that require consistent prop-to-style/class mapping (`DesignConstructorAbstract`, `DesignComponents`).
11
- - Lifecycle & DOM Utilities: When implementing lazy loading (`useLazyRef`) or global state management using `executeUse` for singletons.
12
-
13
- 3. Integration Context:
14
- - Vue 3 Core: Heavily leverages `Ref`, `ComputedRef`, and `provide/inject`.
15
- - Data Fetching: Acts as a high-level wrapper over an underlying `functional-basic` library.
16
- - Routing: Integrates with `vue-router` via `RouterItemRef` and `useRouterList`.
17
- - SSR: Provides specific `Async` variants (e.g., `useApiAsyncRef`) for server-side pre-fetching.
18
- - Schema Validation: Designed to work with `@effect/schema` for robust API contract validation.
package/ai-doc.ru.txt DELETED
@@ -1,45 +0,0 @@
1
- Это главная функциональная библиотека для среды Vue (@dxtmisha/functional). Здесь собраны утилиты, composables и реактивные классы, заточенные под Vue.
2
-
3
- ПРАВИЛА ИСПОЛЬЗОВАНИЯ:
4
- 1. При разработке на Vue всегда отдавайте приоритет этой библиотеке для работы с логикой и composables, а не `@dxtmisha/functional-basic`.
5
- 2. Библиотека оборачивает базовую нереактивную логику в систему реактивности Vue. Если нужная функция или класс есть здесь, они имеют абсолютный приоритет.
6
- 3. Импортируйте утилиты из `@dxtmisha/functional` для реактивного поведения UI, composables и управления состоянием.
7
-
8
- РАБОТА С API И СОСТОЯНИЕМ (useApi / executeUse):
9
- Для работы с сетевыми запросами в библиотеке предусмотрен набор хуков: `useApiGet`, `useApiPost`, `useApiPut`, `useApiDelete`, `useApiRequest`, `useApiRef`, `useApiAsyncRef`, `useApiManagementRef`, `useApiManagementAsyncRef`.
10
- Строго соблюдайте следующие правила их применения:
11
-
12
- 1. НЕ ВЫЗЫВАЙТЕ эти хуки напрямую в компонентах (SFC).
13
- 2. Выносите всю настройку и вызовы `useApi*` в ОТДЕЛЬНЫЕ ФАЙЛЫ (сервисы / хранилища).
14
- 3. Оборачивайте настройку API в фабрику `executeUse` (а именно: `executeUseGlobal`, `executeUseProvide` или `executeUseLocal` из `src/functions/executeUse.ts`). Это гарантирует создание синглтонов (одна точка доступа) и предотвращает создание дубликатов запросов и хранилищ состояния.
15
- 4. Выполняйте любую дополнительную обработку запросов (например: маппинг данных, подготовка структуры для отображения скелетона перед загрузкой формы) в этом же файле, внутри коллбэка `executeUse`, а наружу возвращайте уже полностью готовый набор данных и методов.
16
- *Пример правильного использования:*
17
- ```ts
18
- import { executeUseGlobal } from '@dxtmisha/functional';
19
- import { useApiManagementRef } from '@dxtmisha/functional';
20
-
21
- export const useUserManagement = executeUseGlobal(() => {
22
- return useApiManagementRef(
23
- { path: '/api/users' }, // GET setup
24
- { date: (v) => new Date(v).toLocaleString() }, // Formatters
25
- { columns: ['name', 'email'] }, // Search
26
- { path: '/api/users' }, // POST
27
- { path: (o) => `/api/users/${o.id}` }, // PUT
28
- { path: (o) => `/api/users/${o.id}` } // DELETE
29
- );
30
- // Здесь же можно добавить логику подготовки скелетонов, форматирования и т.д.
31
- // и затем вернуть расширенный объект
32
- });
33
- ```
34
- 5. В самом Vue-компоненте просто импортируйте и вызывайте созданный синглтон-хук: `const { list, loading, sendPost } = useUserManagement();`
35
-
36
- ВЫБОР СТРАТЕГИИ executeUse:
37
- 1. `executeUseLocal` (ПРЕДПОЧТИТЕЛЬНО):
38
- - Когда использовать: Для большинства API-запросов и сервисов.
39
- - Особенности: Работает «лениво» (lazy) — инициализируется только в момент первого вызова. Экземпляр сохраняется до конца сессии. Это позволяет не перегружать старт приложения лишними запросами.
40
- 2. `executeUseGlobal`:
41
- - Когда использовать: Когда данные или сервис должны быть загружены/инициализированы СРАЗУ при старте приложения (например: критические настройки, SDK).
42
- - Особенности: Создает один экземпляр на всё приложение. Все глобальные синглтоны инициализируются принудительно через `executeUseGlobalInit()`.
43
- 3. `executeUseProvide`:
44
- - Когда использовать: Для состояния, разделяемого между родителем и группой дочерних компонентов (например: табы, сложные формы с подкомпонентами).
45
- - Особенности: Использует provide/inject. Первый компонент в дереве, вызвавший хук, становится «провайдером», остальные — потребителями.
package/ai-doc.txt DELETED
@@ -1,45 +0,0 @@
1
- This is the main functional library for the Vue environment (@dxtmisha/functional). It contains Vue-specific utilities, composables, and reactive classes.
2
-
3
- USAGE RULES:
4
- 1. When developing in Vue, always use this library for functionality, logic, and composables instead of `@dxtmisha/functional-basic` whenever possible.
5
- 2. It wraps basic non-reactive logic into Vue's reactivity system. If the required function or composable exists here, it has absolute priority.
6
- 3. Import utilities from `@dxtmisha/functional` for reactive UI behavior, composables, and state management.
7
-
8
- WORKING WITH API AND STATE (useApi / executeUse):
9
- A set of composables is provided for network requests: `useApiGet`, `useApiPost`, `useApiPut`, `useApiDelete`, `useApiRequest`, `useApiRef`, `useApiAsyncRef`, `useApiManagementRef`, `useApiManagementAsyncRef`.
10
- Strictly follow these rules for their application:
11
-
12
- 1. DO NOT call these composables directly in the Vue components (SFC).
13
- 2. Move all API configurations and `useApi*` calls into SEPARATE FILES (services/stores).
14
- 3. Wrap the API configurations inside the `executeUse` factory (specifically: `executeUseGlobal`, `executeUseProvide`, or `executeUseLocal` from `src/functions/executeUse.ts`). This guarantees the creation of managed singletons (single access point) and prevents duplicated requests and reactive states.
15
- 4. Perform any additional request processing (e.g., data mapping, preparing structures for skeletons before loading a form) in the same file, inside the `executeUse` callback, and return a fully prepared set of data and methods.
16
- *Example of correct usage:*
17
- ```ts
18
- import { executeUseGlobal } from '@dxtmisha/functional';
19
- import { useApiManagementRef } from '@dxtmisha/functional';
20
-
21
- export const useUserManagement = executeUseGlobal(() => {
22
- return useApiManagementRef(
23
- { path: '/api/users' }, // GET setup
24
- { date: (v) => new Date(v).toLocaleString() }, // Formatters
25
- { columns: ['name', 'email'] }, // Search
26
- { path: '/api/users' }, // POST
27
- { path: (o) => `/api/users/${o.id}` }, // PUT
28
- { path: (o) => `/api/users/${o.id}` } // DELETE
29
- );
30
- // Logic for skeletons, additional formatting, etc., should be added here,
31
- // and then return the extended object.
32
- });
33
- ```
34
- 5. Within the Vue component itself, simply import and call your custom singleton composable: `const { list, loading, sendPost } = useUserManagement();`
35
-
36
- CHOOSING THE executeUse STRATEGY:
37
- 1. `executeUseLocal` (PREFERRED):
38
- - When to use: For most API requests and services.
39
- - Key Features: Works "lazily" (lazy initialization) — initializes only when first called. The instance persists until the end of the session. This prevents overloading the application start with unnecessary requests.
40
- 2. `executeUseGlobal`:
41
- - When to use: When data or a service must be loaded/initialized IMMEDIATELY at application start (e.g., critical settings, SDKs).
42
- - Key Features: Creates a single instance for the entire application. All global singletons are forcibly initialized via `executeUseGlobalInit()`.
43
- 3. `executeUseProvide`:
44
- - When to use: For state shared between a parent and a group of child components (e.g., tabs, complex forms with sub-components).
45
- - Key Features: Uses provide/inject. The first component in the tree that calls the hook becomes the "provider", others become consumers.