@sevtech/kit 21.1.1 → 21.3.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/fesm2022/misc.mjs +175 -248
- package/fesm2022/misc.mjs.map +1 -1
- package/fesm2022/ng-misc.mjs +183 -94
- package/fesm2022/ng-misc.mjs.map +1 -1
- package/fesm2022/ui-yoda.mjs +55 -9
- package/fesm2022/ui-yoda.mjs.map +1 -1
- package/fesm2022/ui.mjs +180 -17
- package/fesm2022/ui.mjs.map +1 -1
- package/misc/index.d.ts +190 -399
- package/ng-misc/index.d.ts +117 -171
- package/package.json +5 -5
- package/ui/index.d.ts +119 -9
- package/ui/yoda/index.d.ts +63 -51
package/ng-misc/index.d.ts
CHANGED
|
@@ -1,17 +1,45 @@
|
|
|
1
|
+
import { WritableSignal, ComponentRef, OutputRef, QueryList, InputSignalWithTransform, InjectionToken, TemplateRef, ViewContainerRef, Provider, DestroyRef } from '@angular/core';
|
|
1
2
|
import { Observable, Subscriber } from 'rxjs';
|
|
2
3
|
import { Route } from '@angular/router';
|
|
3
|
-
import {
|
|
4
|
-
import { FormArray, FormControl, FormGroup, FormRecord } from '@angular/forms';
|
|
4
|
+
import { FormArray, FormControl, FormGroup, FormRecord, AbstractControl, AsyncValidatorFn, ValidatorFn } from '@angular/forms';
|
|
5
5
|
import { NgComponentOutlet } from '@angular/common';
|
|
6
6
|
import { MaybeArray } from '@sevtech/kit/misc';
|
|
7
7
|
export { toCssDimension as cssDimensionAttribute } from '@sevtech/kit/misc';
|
|
8
8
|
|
|
9
|
+
interface LinkedQueryParamOptions<T = string | undefined> {
|
|
10
|
+
/** Сырое значение параметра в значение сигнала; `null` — параметра нет в URL. */
|
|
11
|
+
transform: (raw: string | null) => T;
|
|
12
|
+
/** Значение сигнала в строку; `null` удаляет параметр из URL. */
|
|
13
|
+
serialize?: (value: T) => string | null;
|
|
14
|
+
/** Задержка перед записью в URL после изменения сигнала. По умолчанию — без задержки. */
|
|
15
|
+
debounce?: number;
|
|
16
|
+
/**
|
|
17
|
+
* Обновлять URL через `replaceState` (без записи в history) или через
|
|
18
|
+
* `pushState`. По умолчанию `true` (`replaceState`).
|
|
19
|
+
*/
|
|
20
|
+
replaceUrl?: boolean;
|
|
21
|
+
}
|
|
9
22
|
/**
|
|
10
|
-
*
|
|
23
|
+
* Двусторонний сигнал, связанный с query-параметром текущего роута:
|
|
24
|
+
* чтение отражает URL, запись обновляет URL через `router.navigate`
|
|
25
|
+
* без гонки с другими `linkedQueryParam` на той же странице.
|
|
26
|
+
*
|
|
11
27
|
* @example
|
|
12
|
-
*
|
|
13
|
-
*
|
|
14
|
-
*
|
|
28
|
+
* class MyComponent {
|
|
29
|
+
* search = linkedQueryParam('q', { debounce: 300 });
|
|
30
|
+
* page = linkedQueryParam('page', {
|
|
31
|
+
* transform: (raw) => Number(raw) || 1,
|
|
32
|
+
* serialize: (value) => (value > 1 ? String(value) : null),
|
|
33
|
+
* });
|
|
34
|
+
* }
|
|
35
|
+
*/
|
|
36
|
+
declare function linkedQueryParam<T>(key: string, options: LinkedQueryParamOptions<T>): WritableSignal<T>;
|
|
37
|
+
declare function linkedQueryParam(key: string, options?: Omit<LinkedQueryParamOptions, 'transform' | 'serialize'>): WritableSignal<string | undefined>;
|
|
38
|
+
|
|
39
|
+
/**
|
|
40
|
+
* Эмитит при изменении размеров элемента; отписка снимает наблюдение.
|
|
41
|
+
* @example
|
|
42
|
+
* resizeObservable(host).subscribe((entries) => entries[0].contentRect.width);
|
|
15
43
|
*/
|
|
16
44
|
declare function resizeObservable(element: HTMLElement): Observable<ResizeObserverEntry[]>;
|
|
17
45
|
|
|
@@ -19,215 +47,93 @@ declare function resizeObservable(element: HTMLElement): Observable<ResizeObserv
|
|
|
19
47
|
* Transform-функция для инпутов CSS-размера: число и числовая строка получают `px`,
|
|
20
48
|
* готовый размер и `Nil` проходят как есть.
|
|
21
49
|
*
|
|
22
|
-
*
|
|
23
|
-
* Для
|
|
24
|
-
* `transform: (value) => toCssDimension(value, 'rem')`
|
|
25
|
-
*
|
|
26
|
-
* @example
|
|
27
|
-
* class MyComponent {
|
|
28
|
-
* height = input<CSSDimension | null, number | CSSDimension | null>(null, {
|
|
29
|
-
* transform: cssDimensionAttribute,
|
|
30
|
-
* });
|
|
31
|
-
* // [height]="200" → '200px'
|
|
32
|
-
* // height="50%" → '50%'
|
|
33
|
-
* // [height]="null" → null
|
|
34
|
-
* }
|
|
50
|
+
* Псевдоним `toCssDimension` — имя единообразно с остальными transform-функциями.
|
|
51
|
+
* Для другой единицы вызывайте его напрямую: `(value) => toCssDimension(value, 'rem')`.
|
|
35
52
|
*/
|
|
36
53
|
|
|
37
54
|
/**
|
|
38
|
-
* Transform-функция для булевых HTML-атрибутов.
|
|
39
|
-
*
|
|
40
|
-
* что позволяет корректно использовать атрибут в шаблоне — атрибут либо присутствует, либо отсутствует.
|
|
55
|
+
* Transform-функция для булевых HTML-атрибутов. В отличие от `booleanAttribute`, отдаёт
|
|
56
|
+
* `true | undefined` вместо `boolean` — атрибут либо присутствует в шаблоне, либо нет.
|
|
41
57
|
*
|
|
42
58
|
* @example
|
|
43
|
-
*
|
|
44
|
-
*
|
|
45
|
-
*
|
|
46
|
-
* // <my-component /> → undefined
|
|
47
|
-
* }
|
|
59
|
+
* disabled = input(undefined, { transform: htmlBooleanAttribute });
|
|
60
|
+
* // <my-component disabled /> → true
|
|
61
|
+
* // <my-component /> → undefined
|
|
48
62
|
*/
|
|
49
63
|
declare function htmlBooleanAttribute(value: unknown): true | undefined;
|
|
50
|
-
|
|
51
64
|
/**
|
|
52
|
-
*
|
|
65
|
+
* Transform-функция для инпутов даты: `Date`, строка и timestamp приводятся к `Date`,
|
|
66
|
+
* невалидное значение и `Nil` — к `fallbackValue`.
|
|
67
|
+
*
|
|
53
68
|
* @example
|
|
54
|
-
*
|
|
55
|
-
*
|
|
56
|
-
* return firstValueFrom(source.pipe(map(parseData)));
|
|
57
|
-
* }
|
|
58
|
-
* // ... обработка Promise и синхронного значения
|
|
59
|
-
* }
|
|
69
|
+
* startDate = input<Date | null, unknown>(null, { transform: dateAttribute });
|
|
70
|
+
* // свой дефолт: transform: (value) => dateAttribute(value, new Date())
|
|
60
71
|
*/
|
|
72
|
+
declare function dateAttribute(value: unknown, fallbackValue?: Date | null): Date | null;
|
|
73
|
+
|
|
74
|
+
/** Синхронное или асинхронное значение: `T | Observable<T> | Promise<T>`. */
|
|
61
75
|
type MaybeAsync<T> = T | Observable<T> | Promise<T>;
|
|
62
76
|
/**
|
|
63
|
-
* Извлекает тип значения из
|
|
77
|
+
* Извлекает тип значения из `Observable`, `Subscriber` или `Promise`.
|
|
64
78
|
* @example
|
|
65
|
-
*
|
|
66
|
-
* type T = ExtractAsync<Promise<number>>; // number
|
|
79
|
+
* ExtractAsync<Observable<string>> // string
|
|
67
80
|
*/
|
|
68
81
|
type ExtractAsync<T> = T extends Subscriber<infer U> ? U : T extends Observable<infer U> ? U : Awaited<T>;
|
|
69
82
|
/**
|
|
70
|
-
* Извлекает тип значения из InjectionToken
|
|
83
|
+
* Извлекает тип значения из `InjectionToken`.
|
|
71
84
|
* @example
|
|
72
|
-
*
|
|
73
|
-
* type T = ExtractToken<typeof TOKEN>; // AppConfig
|
|
85
|
+
* ExtractTokenType<typeof TOKEN> // AppConfig
|
|
74
86
|
*/
|
|
75
87
|
type ExtractTokenType<T> = T extends InjectionToken<infer U> ? U : never;
|
|
76
|
-
/**
|
|
77
|
-
* Извлекает тип компонента из ComponentRef
|
|
78
|
-
* @example
|
|
79
|
-
* const ref: ComponentRef<AppComponent>;
|
|
80
|
-
* type T = ExtractComponentRef<typeof ref>; // AppComponent
|
|
81
|
-
*/
|
|
88
|
+
/** Извлекает тип компонента из `ComponentRef`. */
|
|
82
89
|
type ExtractComponentRef<T> = T extends ComponentRef<infer U> ? U : never;
|
|
83
|
-
/**
|
|
84
|
-
* Извлекает тип значения FormControl
|
|
85
|
-
*/
|
|
90
|
+
/** Извлекает тип значения `FormControl`. */
|
|
86
91
|
type ExtractFormControl<T> = T extends FormControl<infer U> ? U : never;
|
|
87
|
-
/**
|
|
88
|
-
* Извлекает тип элементов FormArray
|
|
89
|
-
*/
|
|
92
|
+
/** Извлекает тип элементов `FormArray`. */
|
|
90
93
|
type ExtractFormArray<T> = T extends FormArray<infer U> ? U : never;
|
|
91
|
-
/**
|
|
92
|
-
* Извлекает тип значения FormGroup
|
|
93
|
-
*/
|
|
94
|
+
/** Извлекает тип значения `FormGroup`. */
|
|
94
95
|
type ExtractFormGroup<T> = T extends FormGroup<infer U> ? U : never;
|
|
95
|
-
/**
|
|
96
|
-
* Извлекает тип значения FormRecord
|
|
97
|
-
*/
|
|
96
|
+
/** Извлекает тип значения `FormRecord`. */
|
|
98
97
|
type ExtractFormRecord<T> = T extends FormRecord<infer U> ? U : never;
|
|
99
|
-
/**
|
|
100
|
-
* Извлекает тип элементов QueryList
|
|
101
|
-
* @example
|
|
102
|
-
* const items!: QueryList<ItemComponent>;
|
|
103
|
-
* type ItemsType = ExtractQueryList<typeof this.items>; // ItemComponent
|
|
104
|
-
*/
|
|
98
|
+
/** Извлекает тип элементов `QueryList`. */
|
|
105
99
|
type ExtractQueryList<T> = T extends QueryList<infer U> ? U : never;
|
|
106
100
|
type ExtractSignalInputKey<Component, Key extends keyof Component> = Component[Key] extends InputSignalWithTransform<infer _, infer TransformFn> ? Key : never;
|
|
107
101
|
type ExtractSignalInputType<Signal> = Signal extends InputSignalWithTransform<infer Data, infer _> ? Data : never;
|
|
108
102
|
/**
|
|
109
|
-
*
|
|
110
|
-
* @template Component - Тип Angular компонента
|
|
111
|
-
*
|
|
103
|
+
* Собирает все `input()`-свойства компонента в объектный тип.
|
|
112
104
|
* @example
|
|
113
|
-
*
|
|
114
|
-
*
|
|
115
|
-
* active = input<boolean>(true);
|
|
116
|
-
* protected template = input<string>('');
|
|
117
|
-
* }
|
|
118
|
-
*
|
|
119
|
-
* type Inputs = ExtractSignalInputs<MyComponent>; // { title: string; active: boolean }
|
|
105
|
+
* // title = input.required<string>(); active = input(true);
|
|
106
|
+
* ExtractSignalInputs<MyComponent> // { title: string; active: boolean }
|
|
120
107
|
*/
|
|
121
108
|
type ExtractSignalInputs<Component> = {
|
|
122
109
|
[Key in keyof Component as ExtractSignalInputKey<Component, Key>]: ExtractSignalInputType<Component[Key]>;
|
|
123
110
|
};
|
|
124
|
-
/**
|
|
125
|
-
* Извлекает все output-свойства компонента
|
|
126
|
-
* @example
|
|
127
|
-
* class MyComponent {
|
|
128
|
-
* clicked = output<string>();
|
|
129
|
-
* }
|
|
130
|
-
*
|
|
131
|
-
* type Outputs = ExtractOutputs<MyComponent>; // { clicked: OutputRef<Event> }
|
|
132
|
-
*/
|
|
111
|
+
/** Собирает все `output()`-свойства компонента в объектный тип. */
|
|
133
112
|
type ExtractOutputs<T> = {
|
|
134
113
|
[K in keyof T as T[K] extends OutputRef<infer _> ? K : never]: T[K];
|
|
135
114
|
};
|
|
136
|
-
/**
|
|
137
|
-
* @extends {Route}
|
|
138
|
-
*/
|
|
115
|
+
/** `Route` с типизированным `data`. */
|
|
139
116
|
interface DataRoute<Data extends Record<string | symbol, unknown>> extends Route {
|
|
140
117
|
data: Data;
|
|
141
118
|
}
|
|
142
|
-
/**
|
|
143
|
-
* @extends {Routes}
|
|
144
|
-
*/
|
|
119
|
+
/** Массив роутов, где `data` типизирован через {@link DataRoute}. */
|
|
145
120
|
type DataRoutes<Data extends Record<string | symbol, unknown>> = (DataRoute<Data> | Route)[];
|
|
146
121
|
|
|
147
|
-
/**
|
|
148
|
-
* Проверяет, является ли значение экземпляром FormControl
|
|
149
|
-
* @example
|
|
150
|
-
* const control = new FormControl<string>('');
|
|
151
|
-
* if (isFormControl<string>(control)) {
|
|
152
|
-
* // control is FormControl<string>
|
|
153
|
-
* }
|
|
154
|
-
*/
|
|
122
|
+
/** Проверяет, что значение — `FormControl`. */
|
|
155
123
|
declare function isFormControl<T = unknown>(data: unknown): data is FormControl<T>;
|
|
156
|
-
/**
|
|
157
|
-
* Проверяет, является ли значение экземпляром FormGroup
|
|
158
|
-
* @example
|
|
159
|
-
* const group = new FormGroup({ name: new FormControl('') });
|
|
160
|
-
* if (isFormGroup(group)) {
|
|
161
|
-
* // group is FormGroup
|
|
162
|
-
* }
|
|
163
|
-
*/
|
|
124
|
+
/** Проверяет, что значение — `FormGroup`. */
|
|
164
125
|
declare function isFormGroup(data: unknown): data is FormGroup;
|
|
165
|
-
/**
|
|
166
|
-
* Проверяет, является ли значение экземпляром FormArray
|
|
167
|
-
* @example
|
|
168
|
-
* const array = new FormArray([new FormControl('')]);
|
|
169
|
-
* if (isFormArray(array)) {
|
|
170
|
-
* // array is FormArray
|
|
171
|
-
* }
|
|
172
|
-
*/
|
|
126
|
+
/** Проверяет, что значение — `FormArray`. */
|
|
173
127
|
declare function isFormArray(data: unknown): data is FormArray;
|
|
174
|
-
/**
|
|
175
|
-
* Проверяет, является ли значение экземпляром FormRecord
|
|
176
|
-
* @example
|
|
177
|
-
* const record = new FormRecord({ field: new FormControl('') });
|
|
178
|
-
* if (isFormRecord(record)) {
|
|
179
|
-
* // record is FormRecord
|
|
180
|
-
* }
|
|
181
|
-
*/
|
|
128
|
+
/** Проверяет, что значение — `FormRecord`. */
|
|
182
129
|
declare function isFormRecord(data: unknown): data is FormRecord;
|
|
183
|
-
/**
|
|
184
|
-
* Проверяет, является ли значение экземпляром ViewContainerRef
|
|
185
|
-
* @example
|
|
186
|
-
* class MyComponent {
|
|
187
|
-
* constructor(public vcr: ViewContainerRef) {}
|
|
188
|
-
*
|
|
189
|
-
* checkType() {
|
|
190
|
-
* if (isViewContainer(this.vcr)) {
|
|
191
|
-
* // this.vcr is ViewContainerRef
|
|
192
|
-
* }
|
|
193
|
-
* }
|
|
194
|
-
* }
|
|
195
|
-
*/
|
|
130
|
+
/** Проверяет, что значение — `ViewContainerRef`. */
|
|
196
131
|
declare function isViewContainer(data: unknown): data is ViewContainerRef;
|
|
197
|
-
/**
|
|
198
|
-
* Проверяет, является ли значение экземпляром TemplateRef
|
|
199
|
-
* @example
|
|
200
|
-
* class MyComponent {
|
|
201
|
-
* readonly slot = input<TemplateRef<unknown> | string>('');
|
|
202
|
-
*
|
|
203
|
-
* checkType() {
|
|
204
|
-
* if (isTemplateRef(this.slot())) {
|
|
205
|
-
* // this.slot() is TemplateRef<unknown>
|
|
206
|
-
* }
|
|
207
|
-
* }
|
|
208
|
-
* }
|
|
209
|
-
*/
|
|
132
|
+
/** Проверяет, что значение — `TemplateRef`. Полезно для инпутов вида `TemplateRef | string`. */
|
|
210
133
|
declare function isTemplateRef<Context = unknown>(data: unknown): data is TemplateRef<Context>;
|
|
211
|
-
/**
|
|
212
|
-
* Проверяет, является ли значение экземпляром ComponentRef
|
|
213
|
-
* @example
|
|
214
|
-
* const componentRef = this.componentFactory.create(injector);
|
|
215
|
-
* if (isComponentRef<MyComponent>(componentRef)) {
|
|
216
|
-
* // componentRef is ComponentRef<MyComponent>
|
|
217
|
-
* }
|
|
218
|
-
*/
|
|
134
|
+
/** Проверяет, что значение — `ComponentRef`. */
|
|
219
135
|
declare function isComponentRef<Instance>(data: unknown): data is ComponentRef<Instance>;
|
|
220
|
-
/**
|
|
221
|
-
* Проверяет, является ли значение экземпляром NgComponentOutlet
|
|
222
|
-
* @example
|
|
223
|
-
* class HostComponent {
|
|
224
|
-
* checkOutlet(outlet: unknown) {
|
|
225
|
-
* if (isComponentOutlet(outlet)) {
|
|
226
|
-
* // outlet is NgComponentOutlet
|
|
227
|
-
* }
|
|
228
|
-
* }
|
|
229
|
-
* }
|
|
230
|
-
*/
|
|
136
|
+
/** Проверяет, что значение — `NgComponentOutlet`. */
|
|
231
137
|
declare function isComponentOutlet(data: unknown): data is NgComponentOutlet;
|
|
232
138
|
|
|
233
139
|
/** Публичный маркер: объект-«фича», возвращаемый withXxx()-функциями. */
|
|
@@ -237,8 +143,9 @@ interface KitFeature<TKind extends number = number> {
|
|
|
237
143
|
}
|
|
238
144
|
/**
|
|
239
145
|
* Создаёт withXxx()-функцию: связывает вид фичи с фабрикой её провайдеров.
|
|
240
|
-
*
|
|
241
|
-
*
|
|
146
|
+
* Вид задаётся локальным `const enum`, поэтому фича одного модуля не пройдёт
|
|
147
|
+
* в `provide*` другого.
|
|
148
|
+
*
|
|
242
149
|
* @example
|
|
243
150
|
* const enum FeatureKind { Prefix }
|
|
244
151
|
*
|
|
@@ -257,5 +164,44 @@ declare function collectFeatureProviders(...items: unknown[]): Provider[];
|
|
|
257
164
|
*/
|
|
258
165
|
declare function resolveConfigProviders<TConfig>(config: TConfig, handler: (config: Exclude<TConfig, KitFeature>) => MaybeArray<Provider>): Provider[];
|
|
259
166
|
|
|
260
|
-
|
|
261
|
-
|
|
167
|
+
/**
|
|
168
|
+
* Применяет `validators`, когда `condition` вернул `true`, и `otherwise` — когда `false`.
|
|
169
|
+
* Ветка без валидаторов считается валидной.
|
|
170
|
+
*
|
|
171
|
+
* Если `condition` зависит не от значения своего контрола — нужен {@link revalidateOn}.
|
|
172
|
+
*
|
|
173
|
+
* @example
|
|
174
|
+
* new FormControl('', ifValidator(isCourier, [Validators.required, Validators.maxLength(200)]));
|
|
175
|
+
* new FormControl('', ifValidator(isCourier, Validators.required, mustBeEmpty));
|
|
176
|
+
*/
|
|
177
|
+
declare function ifValidator(condition: (control: AbstractControl) => boolean, validators: ValidatorFn | ValidatorFn[], otherwise?: ValidatorFn | ValidatorFn[]): ValidatorFn;
|
|
178
|
+
/** Асинхронный вариант {@link ifValidator} — в невыбранной ветке запрос не уходит вовсе. */
|
|
179
|
+
declare function ifAsyncValidator(condition: (control: AbstractControl) => boolean, validators: AsyncValidatorFn | AsyncValidatorFn[], otherwise?: AsyncValidatorFn | AsyncValidatorFn[]): AsyncValidatorFn;
|
|
180
|
+
interface RevalidateOnOptions {
|
|
181
|
+
/**
|
|
182
|
+
* Эмитить ли `valueChanges`/`statusChanges` целей. По умолчанию `true`.
|
|
183
|
+
* `false` спасает от ложного автосохранения, но глушит `statusChanges` и рвёт
|
|
184
|
+
* цепочки перевалидации. Статусы пересчитываются в обоих случаях.
|
|
185
|
+
*/
|
|
186
|
+
emitEvent?: boolean;
|
|
187
|
+
/** Для вызова вне injection context — как в `takeUntilDestroyed`. */
|
|
188
|
+
destroyRef?: DestroyRef;
|
|
189
|
+
}
|
|
190
|
+
/**
|
|
191
|
+
* Перевалидирует `targets` при изменении `source` — и один раз сразу, чтобы закрыть
|
|
192
|
+
* первый проход, на котором `control.parent` ещё не проставлен.
|
|
193
|
+
*
|
|
194
|
+
* Нужен валидаторам, зависящим не от значения своего контрола: reactive forms
|
|
195
|
+
* перезапускают их только на изменение собственного значения.
|
|
196
|
+
*
|
|
197
|
+
* @example
|
|
198
|
+
* constructor() {
|
|
199
|
+
* const { delivery, address, entrance } = this.form.controls;
|
|
200
|
+
*
|
|
201
|
+
* revalidateOn(delivery, [address, entrance]);
|
|
202
|
+
* }
|
|
203
|
+
*/
|
|
204
|
+
declare function revalidateOn(source: AbstractControl | Observable<unknown>, targets: MaybeArray<AbstractControl>, options?: RevalidateOnOptions): void;
|
|
205
|
+
|
|
206
|
+
export { collectFeatureProviders, dateAttribute, defineKitFeature, htmlBooleanAttribute, ifAsyncValidator, ifValidator, isComponentOutlet, isComponentRef, isFormArray, isFormControl, isFormGroup, isFormRecord, isTemplateRef, isViewContainer, linkedQueryParam, resizeObservable, resolveConfigProviders, revalidateOn };
|
|
207
|
+
export type { DataRoute, DataRoutes, ExtractAsync, ExtractComponentRef, ExtractFormArray, ExtractFormControl, ExtractFormGroup, ExtractFormRecord, ExtractOutputs, ExtractQueryList, ExtractSignalInputs, ExtractTokenType, KitFeature, LinkedQueryParamOptions, MaybeAsync, RevalidateOnOptions };
|
package/package.json
CHANGED
|
@@ -1,15 +1,15 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@sevtech/kit",
|
|
3
|
-
"version": "21.
|
|
3
|
+
"version": "21.3.0",
|
|
4
4
|
"sideEffects": false,
|
|
5
5
|
"dependencies": {
|
|
6
6
|
"tslib": "^2.3.0"
|
|
7
7
|
},
|
|
8
8
|
"peerDependencies": {
|
|
9
|
+
"@angular/cdk": "^20.0.0 || ^21.0.0",
|
|
9
10
|
"@angular/common": "^20.0.0 || ^21.0.0",
|
|
10
11
|
"@angular/core": "^20.0.0 || ^21.0.0",
|
|
11
12
|
"@angular/forms": "^20.0.0 || ^21.0.0",
|
|
12
|
-
"@angular/cdk": "^20.0.0 || ^21.0.0",
|
|
13
13
|
"@angular/platform-browser": "^20.0.0 || ^21.0.0",
|
|
14
14
|
"@angular/router": "^20.0.0 || ^21.0.0",
|
|
15
15
|
"@ngx-translate/core": "^17.0.0",
|
|
@@ -17,13 +17,13 @@
|
|
|
17
17
|
"rxjs": "^7.8.0"
|
|
18
18
|
},
|
|
19
19
|
"peerDependenciesMeta": {
|
|
20
|
-
"@angular/
|
|
20
|
+
"@angular/cdk": {
|
|
21
21
|
"optional": true
|
|
22
22
|
},
|
|
23
|
-
"@angular/
|
|
23
|
+
"@angular/common": {
|
|
24
24
|
"optional": true
|
|
25
25
|
},
|
|
26
|
-
"@angular/
|
|
26
|
+
"@angular/core": {
|
|
27
27
|
"optional": true
|
|
28
28
|
},
|
|
29
29
|
"@angular/forms": {
|
package/ui/index.d.ts
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import * as i0 from '@angular/core';
|
|
2
2
|
import { PipeTransform, EnvironmentProviders, TemplateRef, Type } from '@angular/core';
|
|
3
|
-
import { MaybeFunction, SafeAny, DeepKeys, PickKey } from '@sevtech/kit/misc';
|
|
3
|
+
import { MaybeFunction, Nil, SafeAny, DeepKeys, PickKey } from '@sevtech/kit/misc';
|
|
4
4
|
import { SafeUrl, SafeHtml, SafeStyle, SafeScript, SafeResourceUrl } from '@angular/platform-browser';
|
|
5
5
|
|
|
6
6
|
interface BytesFormat {
|
|
@@ -70,6 +70,70 @@ declare class BytesPipe implements PipeTransform {
|
|
|
70
70
|
*/
|
|
71
71
|
declare function provideBytesConfig(config: MaybeFunction<Partial<BytesConfig>>): EnvironmentProviders;
|
|
72
72
|
|
|
73
|
+
type RangeValue = string | number | Nil;
|
|
74
|
+
type Range = [RangeValue, RangeValue];
|
|
75
|
+
type RangePreset = string | Partial<RangeFormat>;
|
|
76
|
+
interface RangeFormat {
|
|
77
|
+
/** Обе границы: `{{ min }}` - нижняя, `{{ max }}` - верхняя */
|
|
78
|
+
between: string;
|
|
79
|
+
/** Только нижняя граница: `{{ value }}` */
|
|
80
|
+
from: string;
|
|
81
|
+
/** Только верхняя граница: `{{ value }}` */
|
|
82
|
+
to: string;
|
|
83
|
+
/** Что выводить, когда обеих границ нет */
|
|
84
|
+
empty: string;
|
|
85
|
+
}
|
|
86
|
+
interface RangeConfig extends RangeFormat {
|
|
87
|
+
/**
|
|
88
|
+
* Именованные наборы шаблонов под разные величины
|
|
89
|
+
* @example
|
|
90
|
+
* presets: {
|
|
91
|
+
* price: { from: 'от {{ value }} ₽', to: 'до {{ value }} ₽' },
|
|
92
|
+
* time: { between: 'с {{ min }} до {{ max }}' }
|
|
93
|
+
* }
|
|
94
|
+
*/
|
|
95
|
+
presets: Record<string, Partial<RangeFormat>>;
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
/**
|
|
99
|
+
* Собирает подпись диапазона из двух границ
|
|
100
|
+
* @description
|
|
101
|
+
* Границы принимаются парой или двумя аргументами, пропущенная даёт
|
|
102
|
+
* одностороннюю формулировку, отсутствие обеих - `empty`. Шаблоны берутся
|
|
103
|
+
* из `RANGE_CONFIG`, последний аргумент перекрывает их именем пресета или объектом
|
|
104
|
+
*
|
|
105
|
+
* @example
|
|
106
|
+
* {{ [priceFrom, priceTo] | range }} // 10 … 20
|
|
107
|
+
* {{ priceFrom | range: priceTo : 'price' }} // от 10 до 20 ₽
|
|
108
|
+
* {{ null | range: priceTo }} // до 20
|
|
109
|
+
* {{ [from, to] | range: { empty: 'весь период' } }}
|
|
110
|
+
*/
|
|
111
|
+
declare class RangePipe implements PipeTransform {
|
|
112
|
+
private readonly config;
|
|
113
|
+
transform(range: Range | Nil, preset?: RangePreset): string;
|
|
114
|
+
transform(min: RangeValue, max: RangeValue, preset?: RangePreset): string;
|
|
115
|
+
static ɵfac: i0.ɵɵFactoryDeclaration<RangePipe, never>;
|
|
116
|
+
static ɵpipe: i0.ɵɵPipeDeclaration<RangePipe, "range", true>;
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
/**
|
|
120
|
+
* Настраивает `RangePipe`.
|
|
121
|
+
* @description Задаёт шаблоны по умолчанию и именованные пресеты. `presets`
|
|
122
|
+
* доливаются к уже объявленным, остальные поля перекрываются целиком.
|
|
123
|
+
* Фабрика вызывается в контексте инжектора, поэтому предлоги можно взять
|
|
124
|
+
* из переводов.
|
|
125
|
+
* @example
|
|
126
|
+
* provideRangeConfig({
|
|
127
|
+
* from: 'от {{ value }}',
|
|
128
|
+
* to: 'до {{ value }}',
|
|
129
|
+
* presets: {
|
|
130
|
+
* price: { to: 'до {{ value }} ₽' },
|
|
131
|
+
* time: { between: 'с {{ min }} до {{ max }}' },
|
|
132
|
+
* },
|
|
133
|
+
* });
|
|
134
|
+
*/
|
|
135
|
+
declare function provideRangeConfig(config: MaybeFunction<Partial<RangeConfig>>): EnvironmentProviders;
|
|
136
|
+
|
|
73
137
|
/**
|
|
74
138
|
* Оборачивает совпадения в `<mark>` с настраиваемым классом
|
|
75
139
|
* @description
|
|
@@ -98,13 +162,18 @@ declare class HighlightPipe implements PipeTransform {
|
|
|
98
162
|
*/
|
|
99
163
|
declare function provideHighlightClass(className: string): EnvironmentProviders;
|
|
100
164
|
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
165
|
+
/**
|
|
166
|
+
* Помечает строку доверенной для выбранного контекста безопасности
|
|
167
|
+
* @description
|
|
168
|
+
* - Снимает санитайзинг Angular, поэтому значение должно быть своим, а не пользовательским
|
|
169
|
+
* - Контекст выбирает метод `DomSanitizer`, тип результата выводится по нему
|
|
170
|
+
* - Для чужой разметки используйте `highlight` или санитайзинг, а не этот пайп
|
|
171
|
+
*
|
|
172
|
+
* @example
|
|
173
|
+
* <iframe [src]="videoUrl | safe: 'resourceUrl'"></iframe>
|
|
174
|
+
* <div [innerHTML]="template | safe: 'html'"></div>
|
|
175
|
+
* <div [style]="theme | safe: 'style'"></div>
|
|
176
|
+
*/
|
|
108
177
|
declare class SafePipe implements PipeTransform {
|
|
109
178
|
private readonly sanitizer;
|
|
110
179
|
transform(value: string, context: 'url'): SafeUrl;
|
|
@@ -116,6 +185,47 @@ declare class SafePipe implements PipeTransform {
|
|
|
116
185
|
static ɵpipe: i0.ɵɵPipeDeclaration<SafePipe, "safe", true>;
|
|
117
186
|
}
|
|
118
187
|
|
|
188
|
+
/**
|
|
189
|
+
* Дополняет массив до нужной длины или собирает его из числа
|
|
190
|
+
* @description
|
|
191
|
+
* - Ничего не обрезает: массив длиннее указанного возвращается как есть
|
|
192
|
+
* - Без фабрики недостающие элементы заполняются индексами
|
|
193
|
+
* - Пропущенная и нечисловая длина трактуются как ноль, данные при этом не теряются
|
|
194
|
+
*
|
|
195
|
+
* @example
|
|
196
|
+
* @for (cell of 5 | items; track $index) {} // [0, 1, 2, 3, 4]
|
|
197
|
+
* @for (row of rows | items: 10; track $index) {} // строки и индексы вместо дырок
|
|
198
|
+
* @for (row of rows | items: 10 : emptyRow; track $index) {} // дырки собирает фабрика
|
|
199
|
+
*/
|
|
200
|
+
declare class ItemsPipe implements PipeTransform {
|
|
201
|
+
transform(source: number): number[];
|
|
202
|
+
transform<T>(source: number, factory: (index: number) => T): T[];
|
|
203
|
+
transform(source: readonly number[], length: number): number[];
|
|
204
|
+
transform<T>(source: readonly T[], length: number, factory: (index: number) => T): T[];
|
|
205
|
+
private fill;
|
|
206
|
+
static ɵfac: i0.ɵɵFactoryDeclaration<ItemsPipe, never>;
|
|
207
|
+
static ɵpipe: i0.ɵɵPipeDeclaration<ItemsPipe, "items", true>;
|
|
208
|
+
}
|
|
209
|
+
|
|
210
|
+
/**
|
|
211
|
+
* Достаёт значение из объекта по строковому пути
|
|
212
|
+
* @description
|
|
213
|
+
* - Путь и результат типизированы: опечатка в ключе видна на этапе компиляции
|
|
214
|
+
* - Оборванный путь и `undefined` в конце дают `fallback`, исключения не бросаются
|
|
215
|
+
* - Разделитель настраивается четвёртым аргументом, по умолчанию точка
|
|
216
|
+
*
|
|
217
|
+
* @example
|
|
218
|
+
* {{ user | pickKey: 'address.city' }}
|
|
219
|
+
* {{ user | pickKey: 'address.city' : 'не указан' }}
|
|
220
|
+
* {{ user | pickKey: 'address/city' : null : '/' }}
|
|
221
|
+
*/
|
|
222
|
+
declare class PickKeyPipe implements PipeTransform {
|
|
223
|
+
transform<const Object extends Record<string, SafeAny>, const Path extends DeepKeys<Object>, const Fallback extends unknown>(object: Object, path: Path, fallback?: Fallback): PickKey<Object, Path> extends Object ? Fallback : PickKey<Object, Path>;
|
|
224
|
+
transform<const Object extends Record<string, SafeAny>, const Path extends DeepKeys<Object, Separator>, const Separator extends string, const Fallback extends unknown>(object: Object, path: Path, fallback?: Fallback, separator?: Separator): PickKey<Object, Path> extends Object ? Fallback : PickKey<Object, Path>;
|
|
225
|
+
static ɵfac: i0.ɵɵFactoryDeclaration<PickKeyPipe, never>;
|
|
226
|
+
static ɵpipe: i0.ɵɵPipeDeclaration<PickKeyPipe, "pickKey", true>;
|
|
227
|
+
}
|
|
228
|
+
|
|
119
229
|
declare class EllipsisDirective {
|
|
120
230
|
private readonly destroyRef;
|
|
121
231
|
private readonly element;
|
|
@@ -165,4 +275,4 @@ declare class SlotOutletDirective<T, C = unknown> {
|
|
|
165
275
|
|
|
166
276
|
declare function withStylesDirective(component: Type<unknown>): undefined;
|
|
167
277
|
|
|
168
|
-
export { BytesPipe, EllipsisDirective, HighlightPipe, PickKeyPipe, SafePipe, SlotOutletDirective, provideBytesConfig, provideHighlightClass, withStylesDirective };
|
|
278
|
+
export { BytesPipe, EllipsisDirective, HighlightPipe, ItemsPipe, PickKeyPipe, RangePipe, SafePipe, SlotOutletDirective, provideBytesConfig, provideHighlightClass, provideRangeConfig, withStylesDirective };
|