@rock555/frontend-core 2.0.2 → 3.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +95 -95
- package/package.json +98 -98
- package/src/components/GlobalPendingBar.vue +85 -85
- package/src/components/SearchPicker.vue +84 -84
- package/src/components/filters/DateRangeField.vue +692 -692
- package/src/components/filters/{ExportCsvButton.vue → ExportButton.vue} +62 -60
- package/src/components/filters/FiltersBar.vue +150 -150
- package/src/components/filters/MonthField.vue +309 -309
- package/src/components/filters/SortControl.vue +162 -162
- package/src/components/filters/SortControlPanel.vue +242 -242
- package/src/components/filters/sortControl.types.ts +25 -25
- package/src/components/modals/ConfirmModal.vue +58 -58
- package/src/components/modals/ImageViewerModal.vue +200 -200
- package/src/components/tables/MultiSortHeader.vue +126 -126
- package/src/components/tables/TableBodyRow.vue +62 -62
- package/src/components/tables/TableFooterRow.vue +54 -54
- package/src/components/tables/TableHeaderRow.vue +75 -75
- package/src/components/tables/TableLoadedCount.vue +61 -61
- package/src/components/tables/TableLoadedFooter.vue +44 -44
- package/src/components/tables/TableSkeletonRows.vue +40 -40
- package/src/components/tables/TableVirtualPad.vue +16 -16
- package/src/components/tables/cells/BoolBadgeCell.vue +32 -32
- package/src/components/tables/multiSortHeader.types.ts +16 -16
- package/src/components/ui/FilterCheckbox.vue +1 -1
- package/src/components/ui/FilterSelect.vue +2 -0
- package/src/components/ui/UiActionTiles.vue +92 -92
- package/src/components/ui/UiBackLink.vue +39 -39
- package/src/components/ui/UiBadge.vue +60 -60
- package/src/components/ui/UiButton.vue +126 -126
- package/src/components/ui/UiCard.vue +88 -88
- package/src/components/ui/UiCount.vue +35 -35
- package/src/components/ui/UiKpiGrid.vue +144 -142
- package/src/components/ui/UiPopover.vue +62 -62
- package/src/components/ui/UiSearchInput.vue +102 -102
- package/src/components/ui/UiSegmented.vue +145 -145
- package/src/components/ui/UiTableCard.vue +116 -116
- package/src/components/ui/inputs/DateFormInput.vue +2 -2
- package/src/components/ui/inputs/FileInput.vue +5 -0
- package/src/components/ui/inputs/RadioSegmentFormInput.vue +0 -1
- package/src/components/ui/inputs/SelectFormInput.vue +1 -2
- package/src/components/ui/inputs/SmartField.vue +15 -13
- package/src/components/ui/inputs/TextareaFormInput.vue +2 -2
- package/src/components/ui/uiActionTiles.types.ts +10 -10
- package/src/components/ui/uiBadge.types.ts +11 -11
- package/src/components/ui/uiKpi.types.ts +19 -17
- package/src/composables/useAppForm.ts +67 -67
- package/src/composables/useConfirm.ts +21 -21
- package/src/composables/useFilterState.ts +70 -70
- package/src/composables/useServerList.ts +348 -348
- package/src/composables/useServerTable.ts +117 -117
- package/src/composables/useSharedAsync.ts +51 -51
- package/src/composables/useVirtualTable.ts +77 -77
- package/src/config.ts +156 -155
- package/src/errors/actionCancelled.ts +9 -9
- package/src/errors/apiError.helper.ts +161 -161
- package/src/errors/useHandleError.ts +33 -33
- package/src/helpers/calendarRange.helper.ts +74 -74
- package/src/helpers/month.helper.ts +63 -63
- package/src/helpers/periodLabel.helper.ts +70 -70
- package/src/helpers/periodPresets.helper.ts +76 -76
- package/src/helpers/sort.helper.ts +57 -57
- package/src/helpers/tableFields.helper.ts +205 -205
- package/src/helpers/urlParams.helper.ts +99 -99
- package/src/helpers/urlSchema.helper.ts +296 -296
- package/src/plugins/modals.plugin.ts +253 -253
- package/src/plugins/table.plugin.ts +173 -173
|
@@ -1,253 +1,253 @@
|
|
|
1
|
-
import {ref, markRaw, Component, shallowRef, InjectionKey, inject, Ref, onScopeDispose} from 'vue';
|
|
2
|
-
import { v4 as uuidv4 } from 'uuid';
|
|
3
|
-
import {ExtractComponentPublicProps, ExtractModalResult, ModalResult} from "../types/vue-utils";
|
|
4
|
-
|
|
5
|
-
export interface IActiveModal<TName = any, TRes = any, TProps = any> {
|
|
6
|
-
id: string;
|
|
7
|
-
uid: string;
|
|
8
|
-
isSubmitting: Ref<boolean>;
|
|
9
|
-
|
|
10
|
-
name: TName;
|
|
11
|
-
props: TProps;
|
|
12
|
-
component: Component;
|
|
13
|
-
|
|
14
|
-
resolve: (val: TRes) => void;
|
|
15
|
-
/** Закрити з волі людини (×, Esc, «Скасувати»): `wait` отримає `undefined`. */
|
|
16
|
-
close: () => void;
|
|
17
|
-
/** Перевірки «є незбережене введене» — їх питає `close()` перед закриттям. */
|
|
18
|
-
dirtyChecks: Set<() => boolean>;
|
|
19
|
-
/** Текст питання й вага перевірки (`useModalDirtyGuard(check, options)`). */
|
|
20
|
-
dirtyOptions: WeakMap<() => boolean, DirtyGuardOptions>;
|
|
21
|
-
/** Поки будь-яка повертає true, вікно не закривається (`useModalCloseBlocker`). */
|
|
22
|
-
closeBlockers: Set<() => boolean>;
|
|
23
|
-
/** Що віддати в `wait`, коли вікно закрили без `resolve` (`setCloseResult`). */
|
|
24
|
-
closeResult: (() => TRes | undefined) | null;
|
|
25
|
-
}
|
|
26
|
-
|
|
27
|
-
export interface DirtyGuardOptions {
|
|
28
|
-
/** Текст питання для `confirmDiscard`; без нього — текст проєкту за замовчуванням. */
|
|
29
|
-
message?: string;
|
|
30
|
-
/** Кілька незбережених станів: питаємо про той, у кого вага вища. За замовчуванням 0. */
|
|
31
|
-
priority?: number;
|
|
32
|
-
}
|
|
33
|
-
|
|
34
|
-
/**
|
|
35
|
-
* Реєстр: кожен ключ — компонент модалки. Не `Record<string, …>`: так реєстром
|
|
36
|
-
* може бути й інтерфейс, який проєкт доповнює declaration merging (а інтерфейс
|
|
37
|
-
* неявного індексного підпису не має).
|
|
38
|
-
*/
|
|
39
|
-
export type ModalRegistryShape<R> = { [K in keyof R]: Component & ModalResult<any> }
|
|
40
|
-
|
|
41
|
-
export class ModalsHelper {
|
|
42
|
-
/**
|
|
43
|
-
* Запис реєстру: `reg<boolean>()(Modal)` — тип результату явно, тип компонента
|
|
44
|
-
* виводиться. Не `reg<boolean>(Modal)`: явний перший дженерик вимикав виведення
|
|
45
|
-
* другого, і компонент ставав голим `Component` — пропси в `show()` були `any`.
|
|
46
|
-
* Без результату — `reg(Modal)`.
|
|
47
|
-
*/
|
|
48
|
-
static reg<TOrigRes = any>(): <T extends Component>(component: T) => T & ModalResult<TOrigRes>;
|
|
49
|
-
static reg<T extends Component>(component: T): T & ModalResult<any>;
|
|
50
|
-
static reg(component?: Component) {
|
|
51
|
-
return component === undefined
|
|
52
|
-
? <T extends Component>(target: T) => target as T & ModalResult<unknown>
|
|
53
|
-
: component;
|
|
54
|
-
}
|
|
55
|
-
|
|
56
|
-
/**
|
|
57
|
-
* @param options.confirmDiscard — чи можна закрити вікно з незбереженим
|
|
58
|
-
* введеним (текст питання — справа проєкту). Без нього закривається одразу.
|
|
59
|
-
* Може повертати Promise — щоб питати власною модалкою, а не window.confirm.
|
|
60
|
-
*/
|
|
61
|
-
static createService<R extends ModalRegistryShape<R>>(
|
|
62
|
-
registry: R,
|
|
63
|
-
options: { confirmDiscard?: (message?: string) => boolean | Promise<boolean> } = {},
|
|
64
|
-
) {
|
|
65
|
-
const confirmDiscard = options.confirmDiscard ?? (() => true);
|
|
66
|
-
|
|
67
|
-
// Используем shallowRef, пушто сами объекты модалок не меняются
|
|
68
|
-
const stack = shallowRef<IActiveModal<keyof R>[]>([]);
|
|
69
|
-
function _close(uid: string) {
|
|
70
|
-
stack.value = stack.value.filter(m => m.uid !== uid);
|
|
71
|
-
}
|
|
72
|
-
|
|
73
|
-
class ModalContext<K extends keyof R> implements IActiveModal<K, ExtractModalResult<R[K]>, ExtractComponentPublicProps<R[K]>> {
|
|
74
|
-
isSubmitting = ref(false);
|
|
75
|
-
|
|
76
|
-
constructor(
|
|
77
|
-
public uid: string,
|
|
78
|
-
public name: K,
|
|
79
|
-
public component: Component,
|
|
80
|
-
public props: ExtractComponentPublicProps<R[K]>,
|
|
81
|
-
) {
|
|
82
|
-
}
|
|
83
|
-
|
|
84
|
-
get id() {
|
|
85
|
-
return `${String(this.name)}-${this.uid}}`;
|
|
86
|
-
}
|
|
87
|
-
|
|
88
|
-
public onResolve: ((val: any) => void) | null = null;
|
|
89
|
-
|
|
90
|
-
dirtyChecks = new Set<() => boolean>();
|
|
91
|
-
dirtyOptions = new WeakMap<() => boolean, DirtyGuardOptions>();
|
|
92
|
-
closeBlockers = new Set<() => boolean>();
|
|
93
|
-
closeResult: (() => any) | null = null;
|
|
94
|
-
|
|
95
|
-
// Результат — це вже збережене, тож питати «закрити без збереження?» нема про що.
|
|
96
|
-
resolve(value: any) {
|
|
97
|
-
this.settle(value);
|
|
98
|
-
}
|
|
99
|
-
|
|
100
|
-
// Без `undefined` у `wait` той, хто чекає відповіді (підтвердження дубля
|
|
101
|
-
// посеред сабміту), висів би вічно, а його форма — з вічним спінером.
|
|
102
|
-
close(): void | Promise<void> {
|
|
103
|
-
if ([...this.closeBlockers].some(isBlocked => isBlocked())) return;
|
|
104
|
-
|
|
105
|
-
// Питаємо про найважливіше незбережене: його текст точніший за загальний.
|
|
106
|
-
const dirty = [...this.dirtyChecks]
|
|
107
|
-
.filter(check => check())
|
|
108
|
-
.map(check => this.dirtyOptions.get(check) ?? {})
|
|
109
|
-
.sort((a, b) => (b.priority ?? 0) - (a.priority ?? 0));
|
|
110
|
-
|
|
111
|
-
if (!dirty.length) return this.settle(this.closeResult?.());
|
|
112
|
-
|
|
113
|
-
const answer = confirmDiscard(dirty[0].message);
|
|
114
|
-
// Синхронна відповідь (window.confirm) лишається синхронною — як і було.
|
|
115
|
-
if (typeof answer === 'boolean') {
|
|
116
|
-
if (answer) this.settle(this.closeResult?.());
|
|
117
|
-
return;
|
|
118
|
-
}
|
|
119
|
-
return answer.then(ok => {
|
|
120
|
-
if (ok) this.settle(this.closeResult?.());
|
|
121
|
-
});
|
|
122
|
-
}
|
|
123
|
-
|
|
124
|
-
private settle(value: any) {
|
|
125
|
-
const onResolve = this.onResolve;
|
|
126
|
-
|
|
127
|
-
this.onResolve = null;
|
|
128
|
-
onResolve?.(value);
|
|
129
|
-
_close(this.uid);
|
|
130
|
-
}
|
|
131
|
-
}
|
|
132
|
-
|
|
133
|
-
interface ShowResult<K extends keyof R> {
|
|
134
|
-
modal: ModalContext<K>;
|
|
135
|
-
/** `undefined` — вікно закрили без відповіді. */
|
|
136
|
-
wait: Promise<{ [P in K]: ExtractModalResult<R[P]> }[K] | undefined>;
|
|
137
|
-
}
|
|
138
|
-
|
|
139
|
-
type ShowConfig<K extends keyof R> = {
|
|
140
|
-
props: ExtractComponentPublicProps<R[K]>;
|
|
141
|
-
};
|
|
142
|
-
|
|
143
|
-
type ShowArgs<K extends keyof R> = K extends any
|
|
144
|
-
? object extends ExtractComponentPublicProps<R[K]> // ПРОВЕРКА НА ОБЯЗАТЕЛЬНЫЕ ПРОПСЫ
|
|
145
|
-
? [config?: Partial<ShowConfig<K>>]
|
|
146
|
-
: [config: ShowConfig<K>]
|
|
147
|
-
: never;
|
|
148
|
-
|
|
149
|
-
// Если пропсов нет, делаем ВЕСЬ конфиг необязательным
|
|
150
|
-
function _show<K extends keyof R = keyof R>(
|
|
151
|
-
name: K,
|
|
152
|
-
...args: ShowArgs<K>
|
|
153
|
-
): ShowResult<K> {
|
|
154
|
-
const {props} = args[0] || {};
|
|
155
|
-
const uid = uuidv4();
|
|
156
|
-
|
|
157
|
-
const newModal = new ModalContext<K>(
|
|
158
|
-
uid,
|
|
159
|
-
name,
|
|
160
|
-
markRaw(registry[name] as Component),
|
|
161
|
-
(props ?? {}) as ExtractComponentPublicProps<R[K]>,
|
|
162
|
-
);
|
|
163
|
-
|
|
164
|
-
return {
|
|
165
|
-
modal: newModal,
|
|
166
|
-
wait: new Promise((resolve) => {
|
|
167
|
-
newModal.onResolve = resolve;
|
|
168
|
-
stack.value = [...stack.value, newModal];
|
|
169
|
-
})
|
|
170
|
-
};
|
|
171
|
-
}
|
|
172
|
-
|
|
173
|
-
return {
|
|
174
|
-
stack,
|
|
175
|
-
show: _show
|
|
176
|
-
};
|
|
177
|
-
}
|
|
178
|
-
|
|
179
|
-
static createComposable<R extends ModalRegistryShape<R>>(getRegistry: () => R) {
|
|
180
|
-
return {
|
|
181
|
-
useModal: <K extends keyof R = keyof R>(name: K) => {
|
|
182
|
-
getRegistry(); // просто для передали аргумент и для приличия вызвали
|
|
183
|
-
const context = inject(ModalContextKey, null) as IActiveModal<K, ExtractModalResult<R[K]>, ExtractComponentPublicProps<R[K]>> | null;
|
|
184
|
-
|
|
185
|
-
if (!context) throw new Error('useModal must be called inside the modal component');
|
|
186
|
-
if (name !== context.name) throw new Error('useModal must be called inside the modal component');
|
|
187
|
-
|
|
188
|
-
// Тостів тут немає: `toast` з vue-sonner — глобальний синглтон, його
|
|
189
|
-
// імпортують там, де показують.
|
|
190
|
-
return {
|
|
191
|
-
context,
|
|
192
|
-
uid: context.uid,
|
|
193
|
-
name: context.name,
|
|
194
|
-
props: context.props,
|
|
195
|
-
isSubmitting: context.isSubmitting,
|
|
196
|
-
resolve: context.resolve.bind(context),
|
|
197
|
-
close: context.close.bind(context),
|
|
198
|
-
/** Що віддати в `wait`, коли вікно закрили без `resolve` (пароль уже показано → true). */
|
|
199
|
-
setCloseResult: (result: () => ExtractModalResult<R[K]> | undefined) => {
|
|
200
|
-
context.closeResult = result;
|
|
201
|
-
},
|
|
202
|
-
};
|
|
203
|
-
}
|
|
204
|
-
}
|
|
205
|
-
}
|
|
206
|
-
}
|
|
207
|
-
|
|
208
|
-
export type ModalService<RegistryType extends Record<string, any>> = ReturnType<typeof ModalsHelper.createService<RegistryType>>;
|
|
209
|
-
export type UntypedModalService = ModalService<Record<string, any>>;
|
|
210
|
-
export const ModalContextKey: InjectionKey<IActiveModal> = Symbol('ModalContext');
|
|
211
|
-
|
|
212
|
-
/**
|
|
213
|
-
* Усередині модалки, що не знає свого ключа в реєстрі проєкту (модалки ядра:
|
|
214
|
-
* `ConfirmModal`, `ImageViewerModal`).
|
|
215
|
-
*/
|
|
216
|
-
export function useCurrentModal<TResult = unknown>() {
|
|
217
|
-
const context = inject(ModalContextKey, null) as IActiveModal<string, TResult> | null;
|
|
218
|
-
|
|
219
|
-
if (!context) throw new Error('useCurrentModal must be called inside the modal component');
|
|
220
|
-
|
|
221
|
-
return {
|
|
222
|
-
resolve: context.resolve.bind(context),
|
|
223
|
-
close: context.close.bind(context),
|
|
224
|
-
};
|
|
225
|
-
}
|
|
226
|
-
|
|
227
|
-
/**
|
|
228
|
-
* «Тут є незбережене» для найближчої модалки: закриття (×, Esc, «Скасувати»)
|
|
229
|
-
* спершу перепитає. Форми `useMyForm` реєструються самі; руками — лише стан
|
|
230
|
-
* поза формою (файли, вибрані рядки). Поза модалкою нічого не робить.
|
|
231
|
-
*/
|
|
232
|
-
export function useModalDirtyGuard(isDirty: () => boolean, options?: DirtyGuardOptions): void {
|
|
233
|
-
const context = inject(ModalContextKey, null);
|
|
234
|
-
|
|
235
|
-
if (!context) return;
|
|
236
|
-
|
|
237
|
-
context.dirtyChecks.add(isDirty);
|
|
238
|
-
if (options) context.dirtyOptions.set(isDirty, options);
|
|
239
|
-
onScopeDispose(() => context.dirtyChecks.delete(isDirty));
|
|
240
|
-
}
|
|
241
|
-
|
|
242
|
-
/**
|
|
243
|
-
* Поки `isBlocked()` true, найближча модалка не закривається ні ×, ні Esc,
|
|
244
|
-
* ні «Скасувати» — напр. іде завантаження файлів. Поза модалкою нічого не робить.
|
|
245
|
-
*/
|
|
246
|
-
export function useModalCloseBlocker(isBlocked: () => boolean): void {
|
|
247
|
-
const context = inject(ModalContextKey, null);
|
|
248
|
-
|
|
249
|
-
if (!context) return;
|
|
250
|
-
|
|
251
|
-
context.closeBlockers.add(isBlocked);
|
|
252
|
-
onScopeDispose(() => context.closeBlockers.delete(isBlocked));
|
|
253
|
-
}
|
|
1
|
+
import {ref, markRaw, Component, shallowRef, InjectionKey, inject, Ref, onScopeDispose} from 'vue';
|
|
2
|
+
import { v4 as uuidv4 } from 'uuid';
|
|
3
|
+
import {ExtractComponentPublicProps, ExtractModalResult, ModalResult} from "../types/vue-utils";
|
|
4
|
+
|
|
5
|
+
export interface IActiveModal<TName = any, TRes = any, TProps = any> {
|
|
6
|
+
id: string;
|
|
7
|
+
uid: string;
|
|
8
|
+
isSubmitting: Ref<boolean>;
|
|
9
|
+
|
|
10
|
+
name: TName;
|
|
11
|
+
props: TProps;
|
|
12
|
+
component: Component;
|
|
13
|
+
|
|
14
|
+
resolve: (val: TRes) => void;
|
|
15
|
+
/** Закрити з волі людини (×, Esc, «Скасувати»): `wait` отримає `undefined`. */
|
|
16
|
+
close: () => void;
|
|
17
|
+
/** Перевірки «є незбережене введене» — їх питає `close()` перед закриттям. */
|
|
18
|
+
dirtyChecks: Set<() => boolean>;
|
|
19
|
+
/** Текст питання й вага перевірки (`useModalDirtyGuard(check, options)`). */
|
|
20
|
+
dirtyOptions: WeakMap<() => boolean, DirtyGuardOptions>;
|
|
21
|
+
/** Поки будь-яка повертає true, вікно не закривається (`useModalCloseBlocker`). */
|
|
22
|
+
closeBlockers: Set<() => boolean>;
|
|
23
|
+
/** Що віддати в `wait`, коли вікно закрили без `resolve` (`setCloseResult`). */
|
|
24
|
+
closeResult: (() => TRes | undefined) | null;
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
export interface DirtyGuardOptions {
|
|
28
|
+
/** Текст питання для `confirmDiscard`; без нього — текст проєкту за замовчуванням. */
|
|
29
|
+
message?: string;
|
|
30
|
+
/** Кілька незбережених станів: питаємо про той, у кого вага вища. За замовчуванням 0. */
|
|
31
|
+
priority?: number;
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
/**
|
|
35
|
+
* Реєстр: кожен ключ — компонент модалки. Не `Record<string, …>`: так реєстром
|
|
36
|
+
* може бути й інтерфейс, який проєкт доповнює declaration merging (а інтерфейс
|
|
37
|
+
* неявного індексного підпису не має).
|
|
38
|
+
*/
|
|
39
|
+
export type ModalRegistryShape<R> = { [K in keyof R]: Component & ModalResult<any> }
|
|
40
|
+
|
|
41
|
+
export class ModalsHelper {
|
|
42
|
+
/**
|
|
43
|
+
* Запис реєстру: `reg<boolean>()(Modal)` — тип результату явно, тип компонента
|
|
44
|
+
* виводиться. Не `reg<boolean>(Modal)`: явний перший дженерик вимикав виведення
|
|
45
|
+
* другого, і компонент ставав голим `Component` — пропси в `show()` були `any`.
|
|
46
|
+
* Без результату — `reg(Modal)`.
|
|
47
|
+
*/
|
|
48
|
+
static reg<TOrigRes = any>(): <T extends Component>(component: T) => T & ModalResult<TOrigRes>;
|
|
49
|
+
static reg<T extends Component>(component: T): T & ModalResult<any>;
|
|
50
|
+
static reg(component?: Component) {
|
|
51
|
+
return component === undefined
|
|
52
|
+
? <T extends Component>(target: T) => target as T & ModalResult<unknown>
|
|
53
|
+
: component;
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
/**
|
|
57
|
+
* @param options.confirmDiscard — чи можна закрити вікно з незбереженим
|
|
58
|
+
* введеним (текст питання — справа проєкту). Без нього закривається одразу.
|
|
59
|
+
* Може повертати Promise — щоб питати власною модалкою, а не window.confirm.
|
|
60
|
+
*/
|
|
61
|
+
static createService<R extends ModalRegistryShape<R>>(
|
|
62
|
+
registry: R,
|
|
63
|
+
options: { confirmDiscard?: (message?: string) => boolean | Promise<boolean> } = {},
|
|
64
|
+
) {
|
|
65
|
+
const confirmDiscard = options.confirmDiscard ?? (() => true);
|
|
66
|
+
|
|
67
|
+
// Используем shallowRef, пушто сами объекты модалок не меняются
|
|
68
|
+
const stack = shallowRef<IActiveModal<keyof R>[]>([]);
|
|
69
|
+
function _close(uid: string) {
|
|
70
|
+
stack.value = stack.value.filter(m => m.uid !== uid);
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
class ModalContext<K extends keyof R> implements IActiveModal<K, ExtractModalResult<R[K]>, ExtractComponentPublicProps<R[K]>> {
|
|
74
|
+
isSubmitting = ref(false);
|
|
75
|
+
|
|
76
|
+
constructor(
|
|
77
|
+
public uid: string,
|
|
78
|
+
public name: K,
|
|
79
|
+
public component: Component,
|
|
80
|
+
public props: ExtractComponentPublicProps<R[K]>,
|
|
81
|
+
) {
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
get id() {
|
|
85
|
+
return `${String(this.name)}-${this.uid}}`;
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
public onResolve: ((val: any) => void) | null = null;
|
|
89
|
+
|
|
90
|
+
dirtyChecks = new Set<() => boolean>();
|
|
91
|
+
dirtyOptions = new WeakMap<() => boolean, DirtyGuardOptions>();
|
|
92
|
+
closeBlockers = new Set<() => boolean>();
|
|
93
|
+
closeResult: (() => any) | null = null;
|
|
94
|
+
|
|
95
|
+
// Результат — це вже збережене, тож питати «закрити без збереження?» нема про що.
|
|
96
|
+
resolve(value: any) {
|
|
97
|
+
this.settle(value);
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
// Без `undefined` у `wait` той, хто чекає відповіді (підтвердження дубля
|
|
101
|
+
// посеред сабміту), висів би вічно, а його форма — з вічним спінером.
|
|
102
|
+
close(): void | Promise<void> {
|
|
103
|
+
if ([...this.closeBlockers].some(isBlocked => isBlocked())) return;
|
|
104
|
+
|
|
105
|
+
// Питаємо про найважливіше незбережене: його текст точніший за загальний.
|
|
106
|
+
const dirty = [...this.dirtyChecks]
|
|
107
|
+
.filter(check => check())
|
|
108
|
+
.map(check => this.dirtyOptions.get(check) ?? {})
|
|
109
|
+
.sort((a, b) => (b.priority ?? 0) - (a.priority ?? 0));
|
|
110
|
+
|
|
111
|
+
if (!dirty.length) return this.settle(this.closeResult?.());
|
|
112
|
+
|
|
113
|
+
const answer = confirmDiscard(dirty[0].message);
|
|
114
|
+
// Синхронна відповідь (window.confirm) лишається синхронною — як і було.
|
|
115
|
+
if (typeof answer === 'boolean') {
|
|
116
|
+
if (answer) this.settle(this.closeResult?.());
|
|
117
|
+
return;
|
|
118
|
+
}
|
|
119
|
+
return answer.then(ok => {
|
|
120
|
+
if (ok) this.settle(this.closeResult?.());
|
|
121
|
+
});
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
private settle(value: any) {
|
|
125
|
+
const onResolve = this.onResolve;
|
|
126
|
+
|
|
127
|
+
this.onResolve = null;
|
|
128
|
+
onResolve?.(value);
|
|
129
|
+
_close(this.uid);
|
|
130
|
+
}
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
interface ShowResult<K extends keyof R> {
|
|
134
|
+
modal: ModalContext<K>;
|
|
135
|
+
/** `undefined` — вікно закрили без відповіді. */
|
|
136
|
+
wait: Promise<{ [P in K]: ExtractModalResult<R[P]> }[K] | undefined>;
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
type ShowConfig<K extends keyof R> = {
|
|
140
|
+
props: ExtractComponentPublicProps<R[K]>;
|
|
141
|
+
};
|
|
142
|
+
|
|
143
|
+
type ShowArgs<K extends keyof R> = K extends any
|
|
144
|
+
? object extends ExtractComponentPublicProps<R[K]> // ПРОВЕРКА НА ОБЯЗАТЕЛЬНЫЕ ПРОПСЫ
|
|
145
|
+
? [config?: Partial<ShowConfig<K>>]
|
|
146
|
+
: [config: ShowConfig<K>]
|
|
147
|
+
: never;
|
|
148
|
+
|
|
149
|
+
// Если пропсов нет, делаем ВЕСЬ конфиг необязательным
|
|
150
|
+
function _show<K extends keyof R = keyof R>(
|
|
151
|
+
name: K,
|
|
152
|
+
...args: ShowArgs<K>
|
|
153
|
+
): ShowResult<K> {
|
|
154
|
+
const {props} = args[0] || {};
|
|
155
|
+
const uid = uuidv4();
|
|
156
|
+
|
|
157
|
+
const newModal = new ModalContext<K>(
|
|
158
|
+
uid,
|
|
159
|
+
name,
|
|
160
|
+
markRaw(registry[name] as Component),
|
|
161
|
+
(props ?? {}) as ExtractComponentPublicProps<R[K]>,
|
|
162
|
+
);
|
|
163
|
+
|
|
164
|
+
return {
|
|
165
|
+
modal: newModal,
|
|
166
|
+
wait: new Promise((resolve) => {
|
|
167
|
+
newModal.onResolve = resolve;
|
|
168
|
+
stack.value = [...stack.value, newModal];
|
|
169
|
+
})
|
|
170
|
+
};
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
return {
|
|
174
|
+
stack,
|
|
175
|
+
show: _show
|
|
176
|
+
};
|
|
177
|
+
}
|
|
178
|
+
|
|
179
|
+
static createComposable<R extends ModalRegistryShape<R>>(getRegistry: () => R) {
|
|
180
|
+
return {
|
|
181
|
+
useModal: <K extends keyof R = keyof R>(name: K) => {
|
|
182
|
+
getRegistry(); // просто для передали аргумент и для приличия вызвали
|
|
183
|
+
const context = inject(ModalContextKey, null) as IActiveModal<K, ExtractModalResult<R[K]>, ExtractComponentPublicProps<R[K]>> | null;
|
|
184
|
+
|
|
185
|
+
if (!context) throw new Error('useModal must be called inside the modal component');
|
|
186
|
+
if (name !== context.name) throw new Error('useModal must be called inside the modal component');
|
|
187
|
+
|
|
188
|
+
// Тостів тут немає: `toast` з vue-sonner — глобальний синглтон, його
|
|
189
|
+
// імпортують там, де показують.
|
|
190
|
+
return {
|
|
191
|
+
context,
|
|
192
|
+
uid: context.uid,
|
|
193
|
+
name: context.name,
|
|
194
|
+
props: context.props,
|
|
195
|
+
isSubmitting: context.isSubmitting,
|
|
196
|
+
resolve: context.resolve.bind(context),
|
|
197
|
+
close: context.close.bind(context),
|
|
198
|
+
/** Що віддати в `wait`, коли вікно закрили без `resolve` (пароль уже показано → true). */
|
|
199
|
+
setCloseResult: (result: () => ExtractModalResult<R[K]> | undefined) => {
|
|
200
|
+
context.closeResult = result;
|
|
201
|
+
},
|
|
202
|
+
};
|
|
203
|
+
}
|
|
204
|
+
}
|
|
205
|
+
}
|
|
206
|
+
}
|
|
207
|
+
|
|
208
|
+
export type ModalService<RegistryType extends Record<string, any>> = ReturnType<typeof ModalsHelper.createService<RegistryType>>;
|
|
209
|
+
export type UntypedModalService = ModalService<Record<string, any>>;
|
|
210
|
+
export const ModalContextKey: InjectionKey<IActiveModal> = Symbol('ModalContext');
|
|
211
|
+
|
|
212
|
+
/**
|
|
213
|
+
* Усередині модалки, що не знає свого ключа в реєстрі проєкту (модалки ядра:
|
|
214
|
+
* `ConfirmModal`, `ImageViewerModal`).
|
|
215
|
+
*/
|
|
216
|
+
export function useCurrentModal<TResult = unknown>() {
|
|
217
|
+
const context = inject(ModalContextKey, null) as IActiveModal<string, TResult> | null;
|
|
218
|
+
|
|
219
|
+
if (!context) throw new Error('useCurrentModal must be called inside the modal component');
|
|
220
|
+
|
|
221
|
+
return {
|
|
222
|
+
resolve: context.resolve.bind(context),
|
|
223
|
+
close: context.close.bind(context),
|
|
224
|
+
};
|
|
225
|
+
}
|
|
226
|
+
|
|
227
|
+
/**
|
|
228
|
+
* «Тут є незбережене» для найближчої модалки: закриття (×, Esc, «Скасувати»)
|
|
229
|
+
* спершу перепитає. Форми `useMyForm` реєструються самі; руками — лише стан
|
|
230
|
+
* поза формою (файли, вибрані рядки). Поза модалкою нічого не робить.
|
|
231
|
+
*/
|
|
232
|
+
export function useModalDirtyGuard(isDirty: () => boolean, options?: DirtyGuardOptions): void {
|
|
233
|
+
const context = inject(ModalContextKey, null);
|
|
234
|
+
|
|
235
|
+
if (!context) return;
|
|
236
|
+
|
|
237
|
+
context.dirtyChecks.add(isDirty);
|
|
238
|
+
if (options) context.dirtyOptions.set(isDirty, options);
|
|
239
|
+
onScopeDispose(() => context.dirtyChecks.delete(isDirty));
|
|
240
|
+
}
|
|
241
|
+
|
|
242
|
+
/**
|
|
243
|
+
* Поки `isBlocked()` true, найближча модалка не закривається ні ×, ні Esc,
|
|
244
|
+
* ні «Скасувати» — напр. іде завантаження файлів. Поза модалкою нічого не робить.
|
|
245
|
+
*/
|
|
246
|
+
export function useModalCloseBlocker(isBlocked: () => boolean): void {
|
|
247
|
+
const context = inject(ModalContextKey, null);
|
|
248
|
+
|
|
249
|
+
if (!context) return;
|
|
250
|
+
|
|
251
|
+
context.closeBlockers.add(isBlocked);
|
|
252
|
+
onScopeDispose(() => context.closeBlockers.delete(isBlocked));
|
|
253
|
+
}
|