@sevtech/kit 20.3.3 → 21.1.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/misc/index.d.ts CHANGED
@@ -60,7 +60,7 @@ type ID = `${number}` | number;
60
60
  type UUID = `${string}-${string}-${string}-${string}-${string}`;
61
61
  /**
62
62
  * Тип конструктора класса
63
- */
63
+ */
64
64
  type ConstructorTypeOf<T> = new (...args: SafeAny[]) => T;
65
65
  /**
66
66
  * Все примитивные типы TypeScript
@@ -81,7 +81,7 @@ type Primitive = string | number | bigint | boolean | symbol | null | undefined;
81
81
  * type T = ExtractType<string[]>; // string
82
82
  * type T = ExtractType<Set<number>>; // number
83
83
  */
84
- type ExtractType<T> = T extends (Array<infer U> | Set<infer U> | Map<PropertyKey, infer U> | WeakMap<WeakKey, infer U> | WeakSet<infer U> | Record<PropertyKey, infer U>) ? U : never;
84
+ type ExtractType<T> = T extends WeakSet<infer U> ? U : T extends Array<infer U> | Set<infer U> | Map<PropertyKey, infer U> | WeakMap<WeakKey, infer U> | Record<PropertyKey, infer U> ? U : never;
85
85
 
86
86
  /**
87
87
  * Допустимые CSS единицы измерения
@@ -166,8 +166,9 @@ type DeepKeys<Object, Separator extends string = '.', MaxDepth extends number =
166
166
  * Рекурсивно делает все свойства объекта опциональными
167
167
  * @example
168
168
  * type T = DeepPartial<{ a: { b: number } }> // { a?: { b?: number } }
169
+ * type T = DeepPartial<{ fn: () => void }> // { fn?: () => void }
169
170
  */
170
- type DeepPartial<T> = T extends object ? {
171
+ type DeepPartial<T> = T extends (...args: never[]) => unknown ? T : T extends readonly unknown[] ? T : T extends object ? {
171
172
  [K in keyof T]?: DeepPartial<T[K]>;
172
173
  } : T;
173
174
  /**
@@ -175,7 +176,7 @@ type DeepPartial<T> = T extends object ? {
175
176
  * @example
176
177
  * type T = DeepRequired<{ a?: { b?: number } }> // { a: { b: number } }
177
178
  */
178
- type DeepRequired<T> = T extends object ? {
179
+ type DeepRequired<T> = T extends (...args: never[]) => unknown ? T : T extends readonly unknown[] ? T : T extends object ? {
179
180
  [K in keyof T]-?: DeepRequired<T[K]>;
180
181
  } : T;
181
182
 
@@ -213,6 +214,43 @@ declare function toBoolean(value: unknown): boolean;
213
214
  * randomNumber(10, 10) // 10
214
215
  */
215
216
  declare function randomNumber(min: number, max: number): number;
217
+ /**
218
+ * Округляет число до заданного количества знаков после запятой
219
+ * @description
220
+ * - `toPrecision` отсекает мусорный хвост double, поэтому нет ошибок вида `1.005 -> 1`
221
+ * - Половинные значения округляются вверх, как в `Math.round`: `roundTo(-1.005, 2) // -1`
222
+ * - Учитываются первые 15 значащих цифр, `NaN` и `Infinity` возвращаются как есть
223
+ * - Для вывода строкой с фиксированным числом знаков нужен `toFixed`, а не эта функция
224
+ *
225
+ * @example
226
+ * roundTo(1234.5678, 2) // 1234.57
227
+ * roundTo(1.005, 2) // 1.01
228
+ * roundTo(2.5) // 3
229
+ */
230
+ declare function roundTo(value: number, precision?: number): number;
231
+ /**
232
+ * Ограничивает число заданным диапазоном
233
+ * @description
234
+ * - `NaN` приводится к `min`
235
+ * - Если `min > max`, побеждает `max`
236
+ *
237
+ * @example
238
+ * clampNumber(5, 0, 10) // 5
239
+ * clampNumber(-3, 0, 10) // 0
240
+ * clampNumber(42, 0, 10) // 10
241
+ */
242
+ declare function clampNumber(value: number, min: number, max: number): number;
243
+ /**
244
+ * Переводит значение в процент от диапазона
245
+ * @description
246
+ * - Значения за границами диапазона дают результат вне 0..100
247
+ * - Вырожденный диапазон (`min === max`) даёт 0
248
+ *
249
+ * @example
250
+ * toPercent(5, 0, 10) // 50
251
+ * toPercent(15, 0, 10) // 150
252
+ */
253
+ declare function toPercent(value: number, min: number, max: number): number;
216
254
  /**
217
255
  * Возвращает случайный элемент массива или null
218
256
  * @example
@@ -235,14 +273,20 @@ declare function coalesce<Arg>(...args: Arg[]): NonNullable<Arg> | null;
235
273
  * safeFnCall(console.log, 'test') // выводит 'test'
236
274
  * safeFnCall(undefined, 'test') // undefined
237
275
  */
238
- declare function safeFnCall<Fn extends ((...args: SafeAny[]) => SafeAny)>(fn: Fn | undefined, ...args: Parameters<Fn>): ReturnType<Fn> | undefined;
276
+ declare function safeFnCall<Fn extends (...args: SafeAny[]) => SafeAny>(fn: Fn | undefined, ...args: Parameters<Fn>): ReturnType<Fn> | undefined;
239
277
  /**
240
278
  * Преобразует значение или массив значений в массив
279
+ * @description
280
+ * - `null` и `undefined` дают пустой массив
281
+ * - Массив возвращается без копирования
282
+ *
241
283
  * @example
242
284
  * toArray(1) // [1]
243
285
  * toArray([1, 2]) // [1, 2]
286
+ * toArray(null) // []
244
287
  */
245
- declare function toArray<T>(value: MaybeArray<T>): T[];
288
+ declare function toArray<T>(value: T[]): T[];
289
+ declare function toArray<T>(value: MaybeArray<T> | Nil): Exclude<T, Nil>[];
246
290
  /**
247
291
  * Возвращаем значение или вызывает функцию для получения значения
248
292
  * @example
@@ -288,27 +332,58 @@ declare function safeParseJSON<ReturnType, Fallback = null>(json: string | null,
288
332
 
289
333
  /**
290
334
  * Типизированная обёртка для Object.keys()
335
+ * @description
336
+ * Возвращает только собственные перечисляемые ключи: унаследованные,
337
+ * неперечисляемые и символьные пропускаются - как в Object.keys().
291
338
  * @example
292
339
  * objectKeys({ a: 1, b: 2 }) // ['a', 'b'] с типом ('a' | 'b')[]
293
340
  * objectKeys([1, 2, 3]) // ['0', '1', '2'] с типом string[]
294
- * objectKeys('test') // [] с типом string[]
295
- * objectKeys(null) // Ошибка типа
341
+ * objectKeys('test') // ['0', '1', '2', '3'] с типом string[]
342
+ * objectKeys(null) // тип never, в рантайме TypeError
296
343
  */
297
344
  declare function objectKeys<T extends Nil>(object: T): never;
298
345
  declare function objectKeys<T extends Primitive | SafeAny[]>(object: T): string[];
299
- declare function objectKeys<T extends Record<PropertyKey, SafeAny>>(object: T): Array<keyof T>;
346
+ declare function objectKeys<T extends Record<PropertyKey, SafeAny>>(object: T): Array<Exclude<keyof T, symbol>>;
347
+ /** Ключи, которые попадают в Object.entries(): символьные пропускаются. */
348
+ type EntryKey<T> = Exclude<keyof T, symbol>;
349
+ /**
350
+ * Пары [ключ, значение] с сохранением связи конкретного ключа с типом его
351
+ * значения. Ключ приводится к строке — Object.entries() возвращает строки.
352
+ */
353
+ type ObjectEntry<T> = {
354
+ [Key in EntryKey<T>]-?: [`${Key}`, T[Key]];
355
+ }[EntryKey<T>];
300
356
  /**
301
357
  * Типизированная обёртка для Object.entries()
358
+ * @description
359
+ * - Сохраняет связь конкретного ключа с типом его значения
360
+ * - Символьные ключи пропускаются, числовые приводятся к строкам - как в Object.entries()
361
+ * - Set и Map возвращают [] - их содержимое не лежит в собственных свойствах
362
+ *
363
+ * Связь ключа и значения доступна при сужении по ключу, но теряется при
364
+ * деструктуризации - это ограничение TypeScript:
365
+ * ```ts
366
+ * for (const entry of objectEntries({ a: 1, b: '2' })) {
367
+ * if (entry[0] === 'a') entry[1]; // number
368
+ * else entry[1]; // string
369
+ * }
370
+ *
371
+ * objectEntries({ a: 1, b: '2' }).map(([key, value]) => value); // string | number
372
+ * ```
373
+ *
302
374
  * @example
303
375
  * objectEntries({ a: 1, b: '2' }) // [['a', 1], ['b', '2']] с типом (['a', number] | ['b', string])[]
376
+ * objectEntries({ 1: 'a' }) // [['1', 'a']] с типом ['1', string][]
304
377
  * objectEntries([10, 20]) // [['0', 10], ['1', 20]] с типом [string, number][]
378
+ * objectEntries('ab') // [['0', 'a'], ['1', 'b']] с типом [string, string][]
305
379
  * objectEntries(new Set([1,2])) // [] с типом []
306
- * objectEntries('test') // [] с типом []
380
+ * objectEntries(null) // тип never, в рантайме TypeError
307
381
  */
308
382
  declare function objectEntries<T extends Nil>(object: T): never;
383
+ declare function objectEntries<T extends string>(object: T): [string, string][];
309
384
  declare function objectEntries<T extends Set<SafeAny> | Map<SafeAny, SafeAny> | Primitive>(object: T): [];
310
- declare function objectEntries<T extends SafeAny[]>(object: T): [string, keyof T][];
311
- declare function objectEntries<T extends Record<Readonly<string>, SafeAny>>(object: T): Array<[keyof T, T[keyof T]]>;
385
+ declare function objectEntries<T extends SafeAny[]>(object: T): [string, T[number]][];
386
+ declare function objectEntries<T extends Record<Readonly<string>, SafeAny>>(object: T): ObjectEntry<T>[];
312
387
  declare function objectEntries<T>(object: Record<string, T> | ArrayLike<T>): [string, T][];
313
388
 
314
389
  /**
@@ -325,6 +400,39 @@ declare function objectEntries<T>(object: Record<string, T> | ArrayLike<T>): [st
325
400
  */
326
401
  declare function pickKey<Object extends Record<string, SafeAny>, Path extends DeepKeys<Object, Separator>, Fallback extends unknown = undefined, Separator extends string = '.'>(object: Object | Nil, path: Path, fallback?: Fallback, separator?: Separator): PickKey<Object, Path> extends Object ? Fallback : PickKey<Object, Path>;
327
402
 
403
+ type InterpolationResolver = (key: string, modifier?: string) => unknown;
404
+ /**
405
+ * Подставляет значения в плейсхолдеры `{{ key }}`
406
+ * @description
407
+ * - Неизвестный ключ остаётся в строке как есть - опечатка видна в выводе
408
+ * - Источником может быть объект или функция: она получает ключ и модификатор
409
+ *
410
+ * @example
411
+ * replaceInterpolation('{{ value }} {{ unit }}', { value: 1.5, unit: 'МБ' }) // '1.5 МБ'
412
+ * replaceInterpolation('{{ count | files }}', (key, modifier) => pluralize(key, modifier))
413
+ */
414
+ declare function replaceInterpolation(template: string, source: Record<string, unknown> | InterpolationResolver): string;
415
+
416
+ /**
417
+ * Приводит значение к CSS-размеру с единицей измерения
418
+ * @description
419
+ * - Число получает единицу, готовый размер проходит как есть
420
+ * - Числовая строка тоже получает единицу: HTML-атрибуты приходят строками
421
+ * - `null` и `undefined` возвращаются как есть, чтобы не подменять «стиль не задан»
422
+ *
423
+ * @example
424
+ * toCssDimension(240) // '240px'
425
+ * toCssDimension(50, '%') // '50%'
426
+ * toCssDimension('1.5rem') // '1.5rem'
427
+ * toCssDimension(null) // null
428
+ *
429
+ * // как transform для сигнального input
430
+ * height = input<CSSDimension | null, number | CSSDimension | null>(null, {
431
+ * transform: toCssDimension,
432
+ * });
433
+ */
434
+ declare function toCssDimension<T extends number | CSSDimension | Nil>(value: T, unit?: CSSUnits): T extends Nil ? T : CSSDimension;
435
+
328
436
  /**
329
437
  * Базовый type guard с возможностью кастомизации проверки.
330
438
  * @example
@@ -396,9 +504,7 @@ declare function isEmptyArray<T>(data: unknown): data is T[];
396
504
  * }
397
505
  */
398
506
  declare function isNonEmptyArray<T>(data: unknown): data is T[];
399
- type PlainObject<T> = [
400
- unknown
401
- ] extends [T] ? Record<PropertyKey, unknown> : T extends object ? T extends Iterable<SafeAny> ? never : T : never;
507
+ type PlainObject<T> = [unknown] extends [T] ? Record<PropertyKey, unknown> : T extends object ? T extends Iterable<SafeAny> ? never : T : never;
402
508
  /**
403
509
  * Проверяет, является ли значение простым объектом (не массивом, не классом)
404
510
  * @example
@@ -427,6 +533,20 @@ declare function isFunction(data: unknown): data is Function;
427
533
  * }
428
534
  */
429
535
  declare function isInstance<T>(target: unknown, constructor: ConstructorTypeOf<T>): target is T;
536
+ /**
537
+ * Проверяет, является ли значение промисом
538
+ * @description
539
+ * Работает с промисами из другого realm (iframe, worker) и сторонними
540
+ * реализациями, для которых `instanceof Promise` даёт `false`.
541
+ * Требует и `then`, и `catch` - легковесные thenable не проходят проверку
542
+ *
543
+ * @example
544
+ * if (isPromise(value)) {
545
+ * // value is Promise<unknown>
546
+ * await value.catch(noop);
547
+ * }
548
+ */
549
+ declare function isPromise<T = unknown>(data: unknown): data is Promise<T>;
430
550
  /**
431
551
  * Проверяет, является ли значение объектом Window
432
552
  * @example
@@ -505,5 +625,5 @@ declare function isDefined<T>(data: T): data is Exclude<T, Nil>;
505
625
  */
506
626
  declare const isValidUUID: (data: unknown) => data is `${string}-${string}-${string}-${string}-${string}`;
507
627
 
508
- export { coalesce, guardFactory, isArray, isBoolean, isDefined, isEmptyArray, isEmptyString, isFunction, isHexColor, isHexWithAlpha, isHexWithoutAlpha, isInstance, isNil, isNonEmptyArray, isNonEmptyString, isNumber, isPlainObject, isString, isTypeWith, isUndefined, isValidUUID, isWindow, noop, objectEntries, objectKeys, parseJSON, pickKey, randomArrayItem, randomNumber, randomUUID, resolveMaybeFn, safeFnCall, safeParseJSON, splitPath, toArray, toBoolean };
628
+ export { clampNumber, coalesce, guardFactory, isArray, isBoolean, isDefined, isEmptyArray, isEmptyString, isFunction, isHexColor, isHexWithAlpha, isHexWithoutAlpha, isInstance, isNil, isNonEmptyArray, isNonEmptyString, isNumber, isPlainObject, isPromise, isString, isTypeWith, isUndefined, isValidUUID, isWindow, noop, objectEntries, objectKeys, parseJSON, pickKey, randomArrayItem, randomNumber, randomUUID, replaceInterpolation, resolveMaybeFn, roundTo, safeFnCall, safeParseJSON, splitPath, toArray, toBoolean, toCssDimension, toPercent };
509
629
  export type { CSSColor, CSSDimension, CSSHexColor, CSSRGBColor, CSSSpecialColor, CSSUnits, CamelCase, ConstructorTypeOf, DeepKeys, DeepPartial, DeepRequired, Empty, ExtractType, ID, MaybeArray, MaybeFunction, Nil, OptionalKeys, PickKey, Primitive, RequiredKeys, SafeAny, SnakeCase, UUID };
@@ -1,8 +1,10 @@
1
1
  import { Observable, Subscriber } from 'rxjs';
2
2
  import { Route } from '@angular/router';
3
- import { ComponentRef, OutputRef, QueryList, InputSignalWithTransform, InjectionToken, ViewContainerRef } from '@angular/core';
3
+ import { ComponentRef, OutputRef, QueryList, InputSignalWithTransform, InjectionToken, TemplateRef, ViewContainerRef, Provider } from '@angular/core';
4
4
  import { FormArray, FormControl, FormGroup, FormRecord } from '@angular/forms';
5
5
  import { NgComponentOutlet } from '@angular/common';
6
+ import { MaybeArray } from '@sevtech/kit/misc';
7
+ export { toCssDimension as cssDimensionAttribute } from '@sevtech/kit/misc';
6
8
 
7
9
  /**
8
10
  * Создаёт Observable который эмитит при изменении размеров элемента
@@ -13,6 +15,25 @@ import { NgComponentOutlet } from '@angular/common';
13
15
  */
14
16
  declare function resizeObservable(element: HTMLElement): Observable<ResizeObserverEntry[]>;
15
17
 
18
+ /**
19
+ * Transform-функция для инпутов CSS-размера: число и числовая строка получают `px`,
20
+ * готовый размер и `Nil` проходят как есть.
21
+ *
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
+ * }
35
+ */
36
+
16
37
  /**
17
38
  * Transform-функция для булевых HTML-атрибутов.
18
39
  * В отличие от `booleanAttribute`, возвращает `true | undefined` вместо `boolean`,
@@ -173,6 +194,20 @@ declare function isFormRecord(data: unknown): data is FormRecord;
173
194
  * }
174
195
  */
175
196
  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
+ */
210
+ declare function isTemplateRef<Context = unknown>(data: unknown): data is TemplateRef<Context>;
176
211
  /**
177
212
  * Проверяет, является ли значение экземпляром ComponentRef
178
213
  * @example
@@ -195,5 +230,32 @@ declare function isComponentRef<Instance>(data: unknown): data is ComponentRef<I
195
230
  */
196
231
  declare function isComponentOutlet(data: unknown): data is NgComponentOutlet;
197
232
 
198
- export { htmlBooleanAttribute, isComponentOutlet, isComponentRef, isFormArray, isFormControl, isFormGroup, isFormRecord, isViewContainer, resizeObservable };
199
- export type { DataRoute, DataRoutes, ExtractAsync, ExtractComponentRef, ExtractFormArray, ExtractFormControl, ExtractFormGroup, ExtractFormRecord, ExtractOutputs, ExtractQueryList, ExtractSignalInputs, ExtractTokenType, MaybeAsync };
233
+ /** Публичный маркер: объект-«фича», возвращаемый withXxx()-функциями. */
234
+ interface KitFeature<TKind extends number = number> {
235
+ readonly ɵkind: TKind;
236
+ readonly ɵproviders: Provider[];
237
+ }
238
+ /**
239
+ * Создаёт withXxx()-функцию: связывает вид фичи с фабрикой её провайдеров.
240
+ * @description Вид задаётся локальным `const enum`, поэтому фича одного
241
+ * модуля не пройдёт в `provide*` другого.
242
+ * @example
243
+ * const enum FeatureKind { Prefix }
244
+ *
245
+ * export const withPrefix = defineKitFeature(
246
+ * FeatureKind.Prefix,
247
+ * (prefix: string) => ({ provide: API_PREFIX, useValue: prefix }),
248
+ * );
249
+ */
250
+ declare function defineKitFeature<Kind extends number, Args extends unknown[]>(kind: Kind, build: (...args: Args) => MaybeArray<Provider>): (...args: Args) => KitFeature<Kind>;
251
+ /** Собирает Provider[] со всех переданных KitFeature-объектов. */
252
+ declare function collectFeatureProviders(...items: unknown[]): Provider[];
253
+ /**
254
+ * Резолвит Provider[] для параметра, который может быть
255
+ * либо «сырым» конфигом, либо уже готовой KitFeature (тогда пропускается —
256
+ * её обработает collectFeatureProviders).
257
+ */
258
+ declare function resolveConfigProviders<TConfig>(config: TConfig, handler: (config: Exclude<TConfig, KitFeature>) => MaybeArray<Provider>): Provider[];
259
+
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 };
package/package.json CHANGED
@@ -1,22 +1,19 @@
1
1
  {
2
2
  "name": "@sevtech/kit",
3
- "version": "20.3.3",
3
+ "version": "21.1.0",
4
4
  "sideEffects": false,
5
- "publishConfig": {
6
- "access": "public"
7
- },
8
5
  "dependencies": {
9
6
  "tslib": "^2.3.0"
10
7
  },
11
8
  "peerDependencies": {
12
- "@angular/common": "^20.0.0",
13
- "@angular/core": "^20.0.0",
14
- "@angular/forms": "^20.0.0",
15
- "@angular/router": "^20.0.0",
16
- "@angular/platform-browser": "^20.0.0",
9
+ "@angular/common": "^20.0.0 || ^21.0.0",
10
+ "@angular/core": "^20.0.0 || ^21.0.0",
11
+ "@angular/forms": "^20.0.0 || ^21.0.0",
12
+ "@angular/cdk": "^20.0.0 || ^21.0.0",
13
+ "@angular/platform-browser": "^20.0.0 || ^21.0.0",
14
+ "@angular/router": "^20.0.0 || ^21.0.0",
17
15
  "@ngx-translate/core": "^17.0.0",
18
16
  "@ngx-translate/http-loader": "17.0.0",
19
- "primeng": "^20.0.0",
20
17
  "rxjs": "^7.8.0"
21
18
  },
22
19
  "peerDependenciesMeta": {
@@ -26,12 +23,15 @@
26
23
  "@angular/core": {
27
24
  "optional": true
28
25
  },
29
- "@angular/platform-browser": {
26
+ "@angular/cdk": {
30
27
  "optional": true
31
28
  },
32
29
  "@angular/forms": {
33
30
  "optional": true
34
31
  },
32
+ "@angular/platform-browser": {
33
+ "optional": true
34
+ },
35
35
  "@angular/router": {
36
36
  "optional": true
37
37
  },
@@ -41,13 +41,13 @@
41
41
  "@ngx-translate/http-loader": {
42
42
  "optional": true
43
43
  },
44
- "primeng": {
45
- "optional": true
46
- },
47
44
  "rxjs": {
48
45
  "optional": true
49
46
  }
50
47
  },
48
+ "publishConfig": {
49
+ "access": "public"
50
+ },
51
51
  "module": "fesm2022/sevtech-kit.mjs",
52
52
  "typings": "index.d.ts",
53
53
  "exports": {
package/ui/index.d.ts CHANGED
@@ -1,8 +1,103 @@
1
1
  import * as i0 from '@angular/core';
2
- import { PipeTransform, Type } from '@angular/core';
3
- import { SafeAny, DeepKeys, PickKey } from '@sevtech/kit/misc';
2
+ import { PipeTransform, EnvironmentProviders, TemplateRef, Type } from '@angular/core';
3
+ import { MaybeFunction, SafeAny, DeepKeys, PickKey } from '@sevtech/kit/misc';
4
4
  import { SafeUrl, SafeHtml, SafeStyle, SafeScript, SafeResourceUrl } from '@angular/platform-browser';
5
5
 
6
+ interface BytesFormat {
7
+ /** Делитель разряда: 1024 для байтов, 1000 для битов и величин СИ */
8
+ base: number;
9
+ /** Знаков после запятой */
10
+ precision: number;
11
+ /** Единицы измерения от младшей к старшей */
12
+ units: readonly string[];
13
+ /** Шаблон вывода: `{{ value }}` - число, `{{ unit }}` - единица измерения */
14
+ template: string;
15
+ /** Что выводить вместо отрицательных, `NaN` и `Infinity` */
16
+ empty: string;
17
+ /** Что выводить вместо нуля; `null` - выводить его как обычное значение */
18
+ zero: string | null;
19
+ }
20
+ interface BytesConfig extends BytesFormat {
21
+ /**
22
+ * Именованные наборы правил для повторяющихся сценариев
23
+ * @example
24
+ * presets: {
25
+ * bitrate: {
26
+ * base: 1000,
27
+ * units: ['бит', 'Кбит', 'Мбит'],
28
+ * template: 'до {{ value }} {{ unit }}/с'
29
+ * }
30
+ *}
31
+ */
32
+ presets: Record<string, Partial<BytesFormat>>;
33
+ }
34
+
35
+ /**
36
+ * Переводит число в человекочитаемый размер с подбором единицы измерения
37
+ * @description
38
+ * Формат берётся из `BYTES_CONFIG`, аргумент перекрывает его именем пресета
39
+ * или объектом. Для отрицательных, `NaN` и `Infinity` выводится `empty`
40
+ *
41
+ * @example
42
+ * {{ file.size | bytes }} // 2 MB
43
+ * {{ speed | bytes: 'bitrate' }} // до 1.5 Мбит/с
44
+ * {{ speed | bytes: { precision: 2 } }}
45
+ */
46
+ declare class BytesPipe implements PipeTransform {
47
+ private readonly config;
48
+ transform(value: number, preset?: string | Partial<BytesFormat>): string;
49
+ static ɵfac: i0.ɵɵFactoryDeclaration<BytesPipe, never>;
50
+ static ɵpipe: i0.ɵɵPipeDeclaration<BytesPipe, "bytes", true>;
51
+ }
52
+
53
+ /**
54
+ * Настраивает `BytesPipe`.
55
+ * @description Задаёт формат по умолчанию и именованные пресеты. `presets`
56
+ * доливаются к уже объявленным, остальные поля перекрываются целиком.
57
+ * Фабрика вызывается в контексте инжектора, поэтому единицы можно взять
58
+ * из переводов.
59
+ * @example
60
+ * provideBytesConfig({
61
+ * precision: 1,
62
+ * presets: {
63
+ * bitrate: {
64
+ * base: 1000,
65
+ * units: ['бит', 'Кбит', 'Мбит', 'Гбит', 'Тбит'],
66
+ * template: 'до {{ value }} {{ unit }}/с',
67
+ * },
68
+ * },
69
+ * });
70
+ */
71
+ declare function provideBytesConfig(config: MaybeFunction<Partial<BytesConfig>>): EnvironmentProviders;
72
+
73
+ /**
74
+ * Оборачивает совпадения в `<mark>` с настраиваемым классом
75
+ * @description
76
+ * - По умолчанию подсвечиваются все совпадения без учёта регистра, флаги регулярки настраиваются
77
+ * - Текст экранируется, разметку добавляет только пайп - результат безопасен для `innerHTML`
78
+ * - Пустой запрос возвращает исходный текст
79
+ * - Класс по умолчанию берётся из `HIGHLIGHT_CLASS`, стилей пакет не поставляет
80
+ *
81
+ * @example
82
+ * <span [innerHTML]="label | highlight: query()"></span>
83
+ * <span [innerHTML]="label | highlight: query() : 'search-match'"></span>
84
+ * <span [innerHTML]="label | highlight: query() : 'search-match' : 'g'"></span> // с учётом регистра
85
+ */
86
+ declare class HighlightPipe implements PipeTransform {
87
+ private readonly defaultClass;
88
+ transform(value: string, search: string, flags?: string, className?: string): string;
89
+ static ɵfac: i0.ɵɵFactoryDeclaration<HighlightPipe, never>;
90
+ static ɵpipe: i0.ɵɵPipeDeclaration<HighlightPipe, "highlight", true>;
91
+ }
92
+
93
+ /**
94
+ * Задаёт css-класс, который `HighlightPipe` вешает на `<mark>`.
95
+ * @description Стилей пакет не поставляет - вид подсветки задаёт приложение.
96
+ * @example
97
+ * provideHighlightClass('search-match');
98
+ */
99
+ declare function provideHighlightClass(className: string): EnvironmentProviders;
100
+
6
101
  declare class PickKeyPipe implements PipeTransform {
7
102
  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>;
8
103
  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>;
@@ -41,6 +136,33 @@ declare class EllipsisDirective {
41
136
  static ɵdir: i0.ɵɵDirectiveDeclaration<EllipsisDirective, "[ellipsis]", ["ellipsis"], { "ellipsis": { "alias": "ellipsis"; "required": false; "isSignal": true; }; "showTitle": { "alias": "showTitle"; "required": false; "isSignal": true; }; }, {}, never, never, true, never>;
42
137
  }
43
138
 
139
+ type ExcludeTemplate<T> = Exclude<T, TemplateRef<unknown>>;
140
+ type ImplicitContext<T> = {
141
+ $implicit: ExcludeTemplate<T>;
142
+ };
143
+ /**
144
+ * Рендерит переданный TemplateRef, либо собственный шаблон с контентом в `$implicit`
145
+ * @example
146
+ * <ng-container *slotOutlet="hintSlot$$() ?? hintMessage(); let-text">
147
+ * <span>{{ text }}</span>
148
+ * </ng-container>
149
+ */
150
+ declare class SlotOutletDirective<T, C = unknown> {
151
+ private readonly viewContainer;
152
+ private readonly fallbackRef;
153
+ private viewRef;
154
+ private renderedRef;
155
+ readonly slotOutlet: i0.InputSignal<T>;
156
+ readonly slotOutletContext: i0.InputSignal<C | null>;
157
+ constructor();
158
+ static ngTemplateContextGuard<T, C>(directive: SlotOutletDirective<T, C>, context: unknown): context is ImplicitContext<T>;
159
+ private render;
160
+ private resolveContext;
161
+ private patchContext;
162
+ static ɵfac: i0.ɵɵFactoryDeclaration<SlotOutletDirective<any, any>, never>;
163
+ static ɵdir: i0.ɵɵDirectiveDeclaration<SlotOutletDirective<any, any>, "[slotOutlet]", ["slotOutlet"], { "slotOutlet": { "alias": "slotOutlet"; "required": true; "isSignal": true; }; "slotOutletContext": { "alias": "slotOutletContext"; "required": false; "isSignal": true; }; }, {}, never, never, true, never>;
164
+ }
165
+
44
166
  declare function withStylesDirective(component: Type<unknown>): undefined;
45
167
 
46
- export { EllipsisDirective, PickKeyPipe, SafePipe, withStylesDirective };
168
+ export { BytesPipe, EllipsisDirective, HighlightPipe, PickKeyPipe, SafePipe, SlotOutletDirective, provideBytesConfig, provideHighlightClass, withStylesDirective };