@sevtech/kit 21.2.0 → 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.
@@ -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 { ComponentRef, OutputRef, QueryList, InputSignalWithTransform, InjectionToken, TemplateRef, ViewContainerRef, Provider } from '@angular/core';
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
- * Создаёт Observable который эмитит при изменении размеров элемента
23
+ * Двусторонний сигнал, связанный с query-параметром текущего роута:
24
+ * чтение отражает URL, запись обновляет URL через `router.navigate`
25
+ * без гонки с другими `linkedQueryParam` на той же странице.
26
+ *
11
27
  * @example
12
- * resizeObservable(elementRef.nativeElement).subscribe(entries => {
13
- * console.log(entries[0].contentRect.width);
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
- * @description Псевдоним `toCssDimension` - имя единообразно с остальными transform-функциями.
23
- * Для единицы, отличной от `px`, вызывайте `toCssDimension` напрямую:
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
- * В отличие от `booleanAttribute`, возвращает `true | undefined` вместо `boolean`,
40
- * что позволяет корректно использовать атрибут в шаблоне — атрибут либо присутствует, либо отсутствует.
55
+ * Transform-функция для булевых HTML-атрибутов. В отличие от `booleanAttribute`, отдаёт
56
+ * `true | undefined` вместо `boolean` — атрибут либо присутствует в шаблоне, либо нет.
41
57
  *
42
58
  * @example
43
- * class MyComponent {
44
- * disabled = input(undefined, { transform: htmlBooleanAttribute });
45
- * // <my-component disabled /> → true
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
- * Синхронное или асинхронное значение (Promise/Observable)
65
+ * Transform-функция для инпутов даты: `Date`, строка и timestamp приводятся к `Date`,
66
+ * невалидное значение и `Nil` — к `fallbackValue`.
67
+ *
53
68
  * @example
54
- * async function fetchData(source: MaybeAsync<string>): Promise<Data> {
55
- * if (source instanceof Observable) {
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
- * Извлекает тип значения из асинхронных оберток (Observable, Promise)
77
+ * Извлекает тип значения из `Observable`, `Subscriber` или `Promise`.
64
78
  * @example
65
- * type T = ExtractAsync<Observable<string>>; // string
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
- * const TOKEN = new InjectionToken<AppConfig>('app.config');
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
- * Извлекает все input-свойства компонента с сигналами
110
- * @template Component - Тип Angular компонента
111
- *
103
+ * Собирает все `input()`-свойства компонента в объектный тип.
112
104
  * @example
113
- * class MyComponent {
114
- * title = input.required<string>();
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
- * @description Вид задаётся локальным `const enum`, поэтому фича одного
241
- * модуля не пройдёт в `provide*` другого.
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
- export { collectFeatureProviders, defineKitFeature, htmlBooleanAttribute, isComponentOutlet, isComponentRef, isFormArray, isFormControl, isFormGroup, isFormRecord, isTemplateRef, isViewContainer, resizeObservable, resolveConfigProviders };
261
- export type { DataRoute, DataRoutes, ExtractAsync, ExtractComponentRef, ExtractFormArray, ExtractFormControl, ExtractFormGroup, ExtractFormRecord, ExtractOutputs, ExtractQueryList, ExtractSignalInputs, ExtractTokenType, KitFeature, MaybeAsync };
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,6 +1,6 @@
1
1
  {
2
2
  "name": "@sevtech/kit",
3
- "version": "21.2.0",
3
+ "version": "21.3.0",
4
4
  "sideEffects": false,
5
5
  "dependencies": {
6
6
  "tslib": "^2.3.0"