@sevtech/kit 20.0.6 → 20.1.1
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/browser/index.d.ts +216 -0
- package/fesm2022/browser.mjs +458 -0
- package/fesm2022/browser.mjs.map +1 -0
- package/fesm2022/http.mjs +5 -5
- package/fesm2022/http.mjs.map +1 -1
- package/fesm2022/sw-ng.mjs +1 -10
- package/fesm2022/sw-ng.mjs.map +1 -1
- package/http/index.d.ts +1 -1
- package/package.json +5 -1
|
@@ -0,0 +1,216 @@
|
|
|
1
|
+
import * as i0 from '@angular/core';
|
|
2
|
+
import { InjectionToken, Signal, Provider, Type } from '@angular/core';
|
|
3
|
+
import { Observable } from 'rxjs';
|
|
4
|
+
import { MaybeFunction } from '@sevtech/kit/misc';
|
|
5
|
+
|
|
6
|
+
/** Безопасный доступ к объекту `Window` через DI. Бросает `Error` если `Window` недоступен (SSR) */
|
|
7
|
+
declare const WINDOW: InjectionToken<Window>;
|
|
8
|
+
|
|
9
|
+
/** Доступ к `window.navigator` через DI */
|
|
10
|
+
declare const NAVIGATOR: InjectionToken<Navigator>;
|
|
11
|
+
|
|
12
|
+
/** `Observable<boolean>` состояния сети. Реагирует на `online`/`offline` события, начальное значение — `navigator.onLine` */
|
|
13
|
+
declare const NETWORK_STATUS: InjectionToken<Observable<boolean>>;
|
|
14
|
+
|
|
15
|
+
/** `Observable<DocumentVisibilityState>` — реагирует на смену видимости вкладки */
|
|
16
|
+
declare const VISIBILITY_CHANGE: InjectionToken<Observable<DocumentVisibilityState>>;
|
|
17
|
+
|
|
18
|
+
/**
|
|
19
|
+
* Обёртка над Cookie Store API с fallback на `document.cookie`.
|
|
20
|
+
* Поддерживает реактивное прослушивание изменений.
|
|
21
|
+
*/
|
|
22
|
+
declare class CookieStoreService {
|
|
23
|
+
private readonly window;
|
|
24
|
+
private readonly document;
|
|
25
|
+
private readonly hasCookieStore;
|
|
26
|
+
private readonly cookieChanges$;
|
|
27
|
+
/** Получить cookie по имени или опциям */
|
|
28
|
+
get(name: string): Promise<Required<CookieListItem> | null>;
|
|
29
|
+
get(options: CookieStoreGetOptions): Promise<Required<CookieListItem> | null>;
|
|
30
|
+
/** Получить все cookies (опционально фильтр по имени) */
|
|
31
|
+
getAll(): Promise<Required<CookieListItem>[]>;
|
|
32
|
+
getAll(name: string): Promise<Required<CookieListItem>[]>;
|
|
33
|
+
getAll(options: CookieStoreGetOptions): Promise<Required<CookieListItem>[]>;
|
|
34
|
+
/** Установить cookie */
|
|
35
|
+
set(name: string, value: string): Promise<void>;
|
|
36
|
+
set(options: CookieInit): Promise<void>;
|
|
37
|
+
/** Удалить cookie */
|
|
38
|
+
delete(name: string): Promise<void>;
|
|
39
|
+
delete(options: CookieStoreDeleteOptions): Promise<void>;
|
|
40
|
+
/** Реактивное прослушивание изменений конкретной cookie */
|
|
41
|
+
listen(name: string): Observable<Required<CookieListItem> | null>;
|
|
42
|
+
private changeObserver;
|
|
43
|
+
static ɵfac: i0.ɵɵFactoryDeclaration<CookieStoreService, never>;
|
|
44
|
+
static ɵprov: i0.ɵɵInjectableDeclaration<CookieStoreService>;
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
type StorageKeys = Extract<keyof StorageSchema, string>;
|
|
48
|
+
type StorageItem<Key extends StorageKeys> = StorageSchema[Key];
|
|
49
|
+
interface StorageEventState<Key, State> {
|
|
50
|
+
key: Key | null;
|
|
51
|
+
old: State | null;
|
|
52
|
+
current: State | null;
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
/**
|
|
56
|
+
* Типобезопасная обёртка над `localStorage` с автоматической сериализацией,
|
|
57
|
+
* реактивным прослушиванием изменений и self-notify для текущей вкладки.
|
|
58
|
+
*
|
|
59
|
+
* Типизация задаётся через глобальный интерфейс `StorageSchema`.
|
|
60
|
+
*/
|
|
61
|
+
declare class LocalStorageService {
|
|
62
|
+
private readonly window;
|
|
63
|
+
private readonly localStorage;
|
|
64
|
+
private readonly storageEvent$$;
|
|
65
|
+
/** Текущий снимок всего хранилища */
|
|
66
|
+
get snapshot(): StorageSchema;
|
|
67
|
+
get length(): number;
|
|
68
|
+
constructor();
|
|
69
|
+
/** Возвращает десериализованное значение по ключу */
|
|
70
|
+
getItem<Key extends StorageKeys>(key: Key): StorageItem<Key> | null;
|
|
71
|
+
getItem(key: string): string | null;
|
|
72
|
+
/**
|
|
73
|
+
* Записывает значение с автоматической сериализацией.
|
|
74
|
+
* @param silentSelf `true` — подавить уведомление в текущей вкладке (другие вкладки получат нативное событие)
|
|
75
|
+
*/
|
|
76
|
+
setItem<Key extends StorageKeys>(key: Key, value: StorageItem<Key>, silentSelf?: boolean): void;
|
|
77
|
+
setItem(key: string, value: string, silentSelf?: boolean): void;
|
|
78
|
+
/** Удаляет значение по ключу
|
|
79
|
+
* @param silentSelf `true` — подавить уведомление в текущей вкладке (другие вкладки получат нативное событие)
|
|
80
|
+
*/
|
|
81
|
+
removeItem<Key extends StorageKeys>(key: Key, silentSelf?: boolean): void;
|
|
82
|
+
removeItem(key: string, silentSelf?: boolean): void;
|
|
83
|
+
/** Поток всех событий `StorageEvent` (сырые строки) */
|
|
84
|
+
listenAll(): Observable<StorageEventState<string, string>>;
|
|
85
|
+
/**
|
|
86
|
+
* Поток изменений конкретного ключа (включая `clear()`).
|
|
87
|
+
* @param includeState `true` — возвращать `StorageEventState` с `old` и `current`
|
|
88
|
+
*/
|
|
89
|
+
listen<Key extends StorageKeys>(key: Key): Observable<StorageItem<Key>>;
|
|
90
|
+
listen<Key extends StorageKeys>(key: Key, includeState: true): Observable<StorageEventState<string, StorageItem<Key>>>;
|
|
91
|
+
listen(key: string): Observable<string | null>;
|
|
92
|
+
listen(key: string, includeState: true): Observable<StorageEventState<string, string>>;
|
|
93
|
+
/** Очищает всё хранилище
|
|
94
|
+
* @param silentSelf `true` — подавить уведомление в текущей вкладке (другие вкладки получат нативное событие)
|
|
95
|
+
*/
|
|
96
|
+
clear(silentSelf?: boolean): void;
|
|
97
|
+
key(index: number): string | null;
|
|
98
|
+
private notifySelf;
|
|
99
|
+
static ɵfac: i0.ɵɵFactoryDeclaration<LocalStorageService, never>;
|
|
100
|
+
static ɵprov: i0.ɵɵInjectableDeclaration<LocalStorageService>;
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
declare global {
|
|
104
|
+
/**
|
|
105
|
+
* Глобальный интерфейс схемы localStorage.
|
|
106
|
+
* Расширяйте через `declare global` для типобезопасного доступа:
|
|
107
|
+
*
|
|
108
|
+
* ```typescript
|
|
109
|
+
* declare global {
|
|
110
|
+
* interface StorageSchema {
|
|
111
|
+
* appConfig: { theme: string; locale: string };
|
|
112
|
+
* token: string;
|
|
113
|
+
* }
|
|
114
|
+
* }
|
|
115
|
+
* ```
|
|
116
|
+
*/
|
|
117
|
+
interface StorageSchema {
|
|
118
|
+
}
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
/**
|
|
122
|
+
* Реактивный {@link PermissionState} для любого {@link PermissionDescriptor} или
|
|
123
|
+
* {@link PermissionName}: сначала
|
|
124
|
+
* `permissions.query`, затем обновления по событию `change` у {@link PermissionStatus}.
|
|
125
|
+
* Одинаковые дескрипторы делят один поток (`shareReplay`).
|
|
126
|
+
*
|
|
127
|
+
* @see https://developer.mozilla.org/docs/Web/API/Permissions_API
|
|
128
|
+
*/
|
|
129
|
+
declare class PermissionStateService {
|
|
130
|
+
private readonly navigator;
|
|
131
|
+
private readonly streams;
|
|
132
|
+
/**
|
|
133
|
+
* @param descriptor - объект дескриптора или имя разрешения (строка)
|
|
134
|
+
* @returns Значения по мере смены состояния, без подряд идущих повторов. Если
|
|
135
|
+
* {@link Navigator.permissions} нет — поток без эмиссий (`EMPTY`), сразу `complete`.
|
|
136
|
+
* Ошибка {@link Permissions.query} не перехватывается и уходит подписчику.
|
|
137
|
+
*/
|
|
138
|
+
watch(descriptor: PermissionDescriptor | PermissionName): Observable<PermissionState>;
|
|
139
|
+
static ɵfac: i0.ɵɵFactoryDeclaration<PermissionStateService, never>;
|
|
140
|
+
static ɵprov: i0.ɵɵInjectableDeclaration<PermissionStateService>;
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
declare const BREAKPOINTS_KEYS: {
|
|
144
|
+
readonly Mobile: "Mobile";
|
|
145
|
+
readonly Tablet: "Tablet";
|
|
146
|
+
readonly Laptop: "Laptop";
|
|
147
|
+
readonly Desktop: "Desktop";
|
|
148
|
+
readonly AllLaptop: "AllLaptop";
|
|
149
|
+
readonly AllMobile: "AllMobile";
|
|
150
|
+
readonly AllTablet: "AllTablet";
|
|
151
|
+
readonly WideDesktop: "WideDesktop";
|
|
152
|
+
readonly LaptopPortrait: "LaptopPortrait";
|
|
153
|
+
readonly MobilePortrait: "MobilePortrait";
|
|
154
|
+
readonly TabletPortrait: "TabletPortrait";
|
|
155
|
+
readonly LaptopLandscape: "LaptopLandscape";
|
|
156
|
+
readonly MobileLandscape: "MobileLandscape";
|
|
157
|
+
readonly TabletLandscape: "TabletLandscape";
|
|
158
|
+
};
|
|
159
|
+
|
|
160
|
+
type Breakpoints = keyof typeof BREAKPOINTS_KEYS | (string & {});
|
|
161
|
+
type BreakpointsMap = Record<Breakpoints, string>;
|
|
162
|
+
interface BreakpointState {
|
|
163
|
+
matches: boolean;
|
|
164
|
+
breakpoints: {
|
|
165
|
+
[p: string]: boolean;
|
|
166
|
+
};
|
|
167
|
+
}
|
|
168
|
+
interface BreakpointsObserver {
|
|
169
|
+
observe(value: string | readonly string[]): Observable<BreakpointState>;
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
/** Сигнал текущего состояния мобильного брейкпоинта */
|
|
173
|
+
declare const IS_MOBILE_BREAKPOINT: InjectionToken<Signal<boolean>>;
|
|
174
|
+
/** Сигнал текущего состояния планшетного брейкпоинта */
|
|
175
|
+
declare const IS_TABLET_BREAKPOINT: InjectionToken<Signal<boolean>>;
|
|
176
|
+
/** Сигнал текущего состояния брейкпоинта ноутбука */
|
|
177
|
+
declare const IS_LAPTOP_BREAKPOINT: InjectionToken<Signal<boolean>>;
|
|
178
|
+
/** Сигнал текущего состояния десктопного брейкпоинта */
|
|
179
|
+
declare const IS_DESKTOP_BREAKPOINT: InjectionToken<Signal<boolean>>;
|
|
180
|
+
/** Сигнал текущего состояния широкого десктопного брейкпоинта */
|
|
181
|
+
declare const IS_WIDE_DESKTOP_BREAKPOINT: InjectionToken<Signal<boolean>>;
|
|
182
|
+
|
|
183
|
+
/**
|
|
184
|
+
* Переопределяет `IS_MOBILE_BREAKPOINT` на уровне компонента через `ResizeObserver`,
|
|
185
|
+
* вместо глобального media-query использует ширину контейнера.
|
|
186
|
+
*/
|
|
187
|
+
declare function provideContainerMobileBreakpoint(boxOptions?: ResizeObserverBoxOptions, width?: number): Provider;
|
|
188
|
+
/** Расширяет или переопределяет набор media-query брейкпоинтов поверх дефолтных. */
|
|
189
|
+
declare function provideBreakpoints(breakpoints: MaybeFunction<Partial<BreakpointsMap>>): Provider;
|
|
190
|
+
/** Предоставляет реализацию `BreakpointsObserver` (например, CDK `BreakpointObserver`). */
|
|
191
|
+
declare function provideBreakpointsObserver(observer: Type<BreakpointsObserver>): Provider;
|
|
192
|
+
|
|
193
|
+
/**
|
|
194
|
+
* Сервис для реактивного отслеживания media-query брейкпоинтов.
|
|
195
|
+
* Использует `BREAKPOINTS_OBSERVER` для наблюдения и `BREAKPOINTS` для конфигурации.
|
|
196
|
+
*
|
|
197
|
+
* @example
|
|
198
|
+
* ```typescript
|
|
199
|
+
* readonly service = inject(BreakpointsService);
|
|
200
|
+
* readonly isMobile$ = this.service.listen('Mobile');
|
|
201
|
+
* ```
|
|
202
|
+
*/
|
|
203
|
+
declare class BreakpointsService {
|
|
204
|
+
private readonly breakpoints;
|
|
205
|
+
private readonly breakpointObserver;
|
|
206
|
+
private readonly breakpointsKeys;
|
|
207
|
+
private readonly cache;
|
|
208
|
+
private readonly matches$;
|
|
209
|
+
/** Возвращает `Observable<boolean>`, отражающий текущее состояние брейкпоинта по ключу. */
|
|
210
|
+
listen<Key extends Breakpoints>(key: Key): Observable<boolean>;
|
|
211
|
+
private buildAllMatched;
|
|
212
|
+
static ɵfac: i0.ɵɵFactoryDeclaration<BreakpointsService, never>;
|
|
213
|
+
static ɵprov: i0.ɵɵInjectableDeclaration<BreakpointsService>;
|
|
214
|
+
}
|
|
215
|
+
|
|
216
|
+
export { BreakpointsService, CookieStoreService, IS_DESKTOP_BREAKPOINT, IS_LAPTOP_BREAKPOINT, IS_MOBILE_BREAKPOINT, IS_TABLET_BREAKPOINT, IS_WIDE_DESKTOP_BREAKPOINT, LocalStorageService, NAVIGATOR, NETWORK_STATUS, PermissionStateService, VISIBILITY_CHANGE, WINDOW, provideBreakpoints, provideBreakpointsObserver, provideContainerMobileBreakpoint };
|
|
@@ -0,0 +1,458 @@
|
|
|
1
|
+
import * as i0 from '@angular/core';
|
|
2
|
+
import { InjectionToken, inject, DOCUMENT, Injectable, ElementRef, DestroyRef, signal } from '@angular/core';
|
|
3
|
+
import { merge, fromEvent, map, startWith, distinctUntilChanged, shareReplay, Observable, filter, EMPTY, from, switchMap, of, finalize } from 'rxjs';
|
|
4
|
+
import { DOCUMENT as DOCUMENT$1 } from '@angular/common';
|
|
5
|
+
import { isString, safeParseJSON, objectKeys, resolveMaybeFn } from '@sevtech/kit/misc';
|
|
6
|
+
import { toSignal } from '@angular/core/rxjs-interop';
|
|
7
|
+
|
|
8
|
+
/** Безопасный доступ к объекту `Window` через DI. Бросает `Error` если `Window` недоступен (SSR) */
|
|
9
|
+
const WINDOW = new InjectionToken('[WINDOW]: Предоставляет безопасный доступ к объекту Window', {
|
|
10
|
+
factory: () => {
|
|
11
|
+
const { defaultView } = inject(DOCUMENT);
|
|
12
|
+
if (!defaultView) {
|
|
13
|
+
throw new Error('Window is not available');
|
|
14
|
+
}
|
|
15
|
+
return defaultView;
|
|
16
|
+
},
|
|
17
|
+
});
|
|
18
|
+
|
|
19
|
+
/** Доступ к `window.navigator` через DI */
|
|
20
|
+
const NAVIGATOR = new InjectionToken('[NAVIGATOR]: предоставляет доступ к window.navigator', {
|
|
21
|
+
factory: () => inject(WINDOW).navigator,
|
|
22
|
+
});
|
|
23
|
+
|
|
24
|
+
/** `Observable<boolean>` состояния сети. Реагирует на `online`/`offline` события, начальное значение — `navigator.onLine` */
|
|
25
|
+
const NETWORK_STATUS = new InjectionToken('[NETWORK_STATUS]: возвращает observable, который изменяется каждый раз при изменении состояния сети', {
|
|
26
|
+
factory: () => {
|
|
27
|
+
const window = inject(WINDOW);
|
|
28
|
+
return merge(fromEvent(window, 'online').pipe(map(() => true)), fromEvent(window, 'offline').pipe(map(() => false))).pipe(startWith(window.navigator.onLine), distinctUntilChanged(), shareReplay({ bufferSize: 1, refCount: true }));
|
|
29
|
+
}
|
|
30
|
+
});
|
|
31
|
+
|
|
32
|
+
/** `Observable<DocumentVisibilityState>` — реагирует на смену видимости вкладки */
|
|
33
|
+
const VISIBILITY_CHANGE = new InjectionToken('[VISIBILITY_CHANGE]: возвращает Observable, который изменяется каждый раз при срабатывает событие visibility change', {
|
|
34
|
+
factory: () => {
|
|
35
|
+
const document = inject(DOCUMENT$1);
|
|
36
|
+
return fromEvent(document, 'visibilitychange').pipe(startWith(true), map(() => document.visibilityState), distinctUntilChanged(), shareReplay({ refCount: true, bufferSize: 1 }));
|
|
37
|
+
},
|
|
38
|
+
});
|
|
39
|
+
|
|
40
|
+
function parseCookies(cookieString) {
|
|
41
|
+
if (!cookieString.trim())
|
|
42
|
+
return [];
|
|
43
|
+
return cookieString.split(';').reduce((cookieList, part) => {
|
|
44
|
+
const index = part.indexOf('=');
|
|
45
|
+
if (index === -1)
|
|
46
|
+
return cookieList;
|
|
47
|
+
const name = safeDecodeURI(part.slice(0, index).trim());
|
|
48
|
+
const value = safeDecodeURI(part.slice(index + 1).trim());
|
|
49
|
+
if (!name)
|
|
50
|
+
return cookieList;
|
|
51
|
+
cookieList.push({
|
|
52
|
+
name,
|
|
53
|
+
value,
|
|
54
|
+
});
|
|
55
|
+
return cookieList;
|
|
56
|
+
}, []);
|
|
57
|
+
}
|
|
58
|
+
function safeDecodeURI(value) {
|
|
59
|
+
try {
|
|
60
|
+
return decodeURIComponent(value ?? '');
|
|
61
|
+
}
|
|
62
|
+
catch {
|
|
63
|
+
return value ?? '';
|
|
64
|
+
}
|
|
65
|
+
}
|
|
66
|
+
function serializeCookie(options) {
|
|
67
|
+
let cookie = `${encodeURIComponent(options.name)}=${encodeURIComponent(options.value)}`;
|
|
68
|
+
if (options.path)
|
|
69
|
+
cookie += `; path=${options.path}`;
|
|
70
|
+
if (options.domain)
|
|
71
|
+
cookie += `; domain=${options.domain}`;
|
|
72
|
+
if (options.expires != null)
|
|
73
|
+
cookie += `; expires=${new Date(options.expires).toUTCString()}`;
|
|
74
|
+
if (options.sameSite)
|
|
75
|
+
cookie += `; samesite=${options.sameSite}`;
|
|
76
|
+
return cookie;
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
/**
|
|
80
|
+
* Обёртка над Cookie Store API с fallback на `document.cookie`.
|
|
81
|
+
* Поддерживает реактивное прослушивание изменений.
|
|
82
|
+
*/
|
|
83
|
+
class CookieStoreService {
|
|
84
|
+
constructor() {
|
|
85
|
+
this.window = inject(WINDOW);
|
|
86
|
+
this.document = inject(DOCUMENT$1);
|
|
87
|
+
this.hasCookieStore = !!this.window.cookieStore;
|
|
88
|
+
this.cookieChanges$ = this.changeObserver().pipe(startWith(this.document.cookie), distinctUntilChanged(), shareReplay({ refCount: true, bufferSize: 1 }));
|
|
89
|
+
}
|
|
90
|
+
get(input) {
|
|
91
|
+
const options = isString(input) ? { name: input } : input;
|
|
92
|
+
if (this.hasCookieStore) {
|
|
93
|
+
return this.window.cookieStore
|
|
94
|
+
.get(options)
|
|
95
|
+
.then((cookie) => cookie ? { name: cookie.name, value: safeDecodeURI(cookie.value) } : null);
|
|
96
|
+
}
|
|
97
|
+
if (!options?.name)
|
|
98
|
+
return Promise.resolve(null);
|
|
99
|
+
return Promise.resolve(parseCookies(this.document.cookie).find((cookie) => cookie.name === options.name) ?? null);
|
|
100
|
+
}
|
|
101
|
+
getAll(input) {
|
|
102
|
+
const options = isString(input) ? { name: input } : input;
|
|
103
|
+
if (this.hasCookieStore) {
|
|
104
|
+
return this.window.cookieStore.getAll(options).then((cookies) => cookies.map((cookie) => ({
|
|
105
|
+
name: cookie.name,
|
|
106
|
+
value: safeDecodeURI(cookie.value),
|
|
107
|
+
})));
|
|
108
|
+
}
|
|
109
|
+
const allCookies = parseCookies(this.document.cookie);
|
|
110
|
+
return Promise.resolve(options?.name ? allCookies.filter((cookie) => cookie.name === options.name) : allCookies);
|
|
111
|
+
}
|
|
112
|
+
set(input, value = '') {
|
|
113
|
+
const options = isString(input) ? { name: input, value } : input;
|
|
114
|
+
if (this.hasCookieStore) {
|
|
115
|
+
return this.window.cookieStore.set(options);
|
|
116
|
+
}
|
|
117
|
+
this.document.cookie = serializeCookie(options);
|
|
118
|
+
return Promise.resolve();
|
|
119
|
+
}
|
|
120
|
+
delete(input) {
|
|
121
|
+
const options = isString(input) ? { name: input } : input;
|
|
122
|
+
if (this.hasCookieStore) {
|
|
123
|
+
return this.window.cookieStore.delete(options);
|
|
124
|
+
}
|
|
125
|
+
this.document.cookie = serializeCookie({
|
|
126
|
+
value: '',
|
|
127
|
+
expires: 0,
|
|
128
|
+
name: options.name,
|
|
129
|
+
domain: options.domain,
|
|
130
|
+
path: options.path ?? '/',
|
|
131
|
+
});
|
|
132
|
+
return Promise.resolve();
|
|
133
|
+
}
|
|
134
|
+
/** Реактивное прослушивание изменений конкретной cookie */
|
|
135
|
+
listen(name) {
|
|
136
|
+
return this.cookieChanges$.pipe(map((cookies) => parseCookies(cookies).find((cookie) => cookie.name === name) ?? null), distinctUntilChanged((a, b) => a?.value === b?.value));
|
|
137
|
+
}
|
|
138
|
+
changeObserver() {
|
|
139
|
+
if (this.hasCookieStore) {
|
|
140
|
+
return new Observable((observer) => {
|
|
141
|
+
const handler = () => observer.next(this.document.cookie);
|
|
142
|
+
this.window.cookieStore.addEventListener('change', handler);
|
|
143
|
+
return () => this.window.cookieStore.removeEventListener('change', handler);
|
|
144
|
+
});
|
|
145
|
+
}
|
|
146
|
+
return new Observable((observer) => {
|
|
147
|
+
const timerId = setInterval(() => observer.next(this.document.cookie), 1000);
|
|
148
|
+
return () => clearInterval(timerId);
|
|
149
|
+
});
|
|
150
|
+
}
|
|
151
|
+
static { this.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "20.3.18", ngImport: i0, type: CookieStoreService, deps: [], target: i0.ɵɵFactoryTarget.Injectable }); }
|
|
152
|
+
static { this.ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "20.3.18", ngImport: i0, type: CookieStoreService, providedIn: 'root' }); }
|
|
153
|
+
}
|
|
154
|
+
i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "20.3.18", ngImport: i0, type: CookieStoreService, decorators: [{
|
|
155
|
+
type: Injectable,
|
|
156
|
+
args: [{
|
|
157
|
+
providedIn: 'root',
|
|
158
|
+
}]
|
|
159
|
+
}] });
|
|
160
|
+
|
|
161
|
+
function serialize(value) {
|
|
162
|
+
return JSON.stringify(value);
|
|
163
|
+
}
|
|
164
|
+
function deserialize(value) {
|
|
165
|
+
return safeParseJSON(value);
|
|
166
|
+
}
|
|
167
|
+
function toEventState(event) {
|
|
168
|
+
return {
|
|
169
|
+
key: event.key,
|
|
170
|
+
old: event.oldValue,
|
|
171
|
+
current: event.newValue,
|
|
172
|
+
};
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
/**
|
|
176
|
+
* Типобезопасная обёртка над `localStorage` с автоматической сериализацией,
|
|
177
|
+
* реактивным прослушиванием изменений и self-notify для текущей вкладки.
|
|
178
|
+
*
|
|
179
|
+
* Типизация задаётся через глобальный интерфейс `StorageSchema`.
|
|
180
|
+
*/
|
|
181
|
+
class LocalStorageService {
|
|
182
|
+
/** Текущий снимок всего хранилища */
|
|
183
|
+
get snapshot() {
|
|
184
|
+
const result = {};
|
|
185
|
+
for (let index = 0; index < this.length; index++) {
|
|
186
|
+
const key = this.key(index);
|
|
187
|
+
if (key) {
|
|
188
|
+
result[key] = this.getItem(key);
|
|
189
|
+
}
|
|
190
|
+
}
|
|
191
|
+
return result;
|
|
192
|
+
}
|
|
193
|
+
get length() {
|
|
194
|
+
return this.localStorage.length;
|
|
195
|
+
}
|
|
196
|
+
constructor() {
|
|
197
|
+
this.window = inject(WINDOW);
|
|
198
|
+
this.localStorage = this.window.localStorage;
|
|
199
|
+
this.storageEvent$$ = fromEvent(this.window, 'storage').pipe(map(toEventState));
|
|
200
|
+
if (!this.localStorage) {
|
|
201
|
+
throw new Error('LocalStorage is not available');
|
|
202
|
+
}
|
|
203
|
+
}
|
|
204
|
+
getItem(key) {
|
|
205
|
+
return deserialize(this.localStorage.getItem(key));
|
|
206
|
+
}
|
|
207
|
+
setItem(key, value, silentSelf = false) {
|
|
208
|
+
const oldValue = this.localStorage.getItem(key);
|
|
209
|
+
const serialized = serialize(value);
|
|
210
|
+
this.localStorage.setItem(key, serialized);
|
|
211
|
+
if (!silentSelf) {
|
|
212
|
+
this.notifySelf(key, serialized, oldValue);
|
|
213
|
+
}
|
|
214
|
+
}
|
|
215
|
+
removeItem(key, silentSelf) {
|
|
216
|
+
const oldValue = this.localStorage.getItem(key);
|
|
217
|
+
this.localStorage.removeItem(key);
|
|
218
|
+
if (!silentSelf) {
|
|
219
|
+
this.notifySelf(key, null, oldValue);
|
|
220
|
+
}
|
|
221
|
+
}
|
|
222
|
+
/** Поток всех событий `StorageEvent` (сырые строки) */
|
|
223
|
+
listenAll() {
|
|
224
|
+
return this.storageEvent$$;
|
|
225
|
+
}
|
|
226
|
+
listen(key, includeState) {
|
|
227
|
+
const filtered$ = this.storageEvent$$.pipe(filter((state) => state.key === null || state.key === key));
|
|
228
|
+
if (includeState) {
|
|
229
|
+
return filtered$.pipe(map((state) => ({
|
|
230
|
+
key: state.key,
|
|
231
|
+
old: deserialize(state.old),
|
|
232
|
+
current: deserialize(state.current),
|
|
233
|
+
})));
|
|
234
|
+
}
|
|
235
|
+
return filtered$.pipe(map((state) => deserialize(state.current)));
|
|
236
|
+
}
|
|
237
|
+
/** Очищает всё хранилище
|
|
238
|
+
* @param silentSelf `true` — подавить уведомление в текущей вкладке (другие вкладки получат нативное событие)
|
|
239
|
+
*/
|
|
240
|
+
clear(silentSelf) {
|
|
241
|
+
this.localStorage.clear();
|
|
242
|
+
if (!silentSelf) {
|
|
243
|
+
this.notifySelf(null, null, null);
|
|
244
|
+
}
|
|
245
|
+
}
|
|
246
|
+
key(index) {
|
|
247
|
+
return this.localStorage.key(index);
|
|
248
|
+
}
|
|
249
|
+
notifySelf(key, newValue, oldValue) {
|
|
250
|
+
const event = new StorageEvent('storage', {
|
|
251
|
+
key,
|
|
252
|
+
newValue,
|
|
253
|
+
oldValue,
|
|
254
|
+
storageArea: this.localStorage,
|
|
255
|
+
url: this.window.location.href,
|
|
256
|
+
});
|
|
257
|
+
this.window.dispatchEvent(event);
|
|
258
|
+
}
|
|
259
|
+
static { this.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "20.3.18", ngImport: i0, type: LocalStorageService, deps: [], target: i0.ɵɵFactoryTarget.Injectable }); }
|
|
260
|
+
static { this.ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "20.3.18", ngImport: i0, type: LocalStorageService, providedIn: 'root' }); }
|
|
261
|
+
}
|
|
262
|
+
i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "20.3.18", ngImport: i0, type: LocalStorageService, decorators: [{
|
|
263
|
+
type: Injectable,
|
|
264
|
+
args: [{
|
|
265
|
+
providedIn: 'root',
|
|
266
|
+
}]
|
|
267
|
+
}], ctorParameters: () => [] });
|
|
268
|
+
|
|
269
|
+
/**
|
|
270
|
+
* Реактивный {@link PermissionState} для любого {@link PermissionDescriptor} или
|
|
271
|
+
* {@link PermissionName}: сначала
|
|
272
|
+
* `permissions.query`, затем обновления по событию `change` у {@link PermissionStatus}.
|
|
273
|
+
* Одинаковые дескрипторы делят один поток (`shareReplay`).
|
|
274
|
+
*
|
|
275
|
+
* @see https://developer.mozilla.org/docs/Web/API/Permissions_API
|
|
276
|
+
*/
|
|
277
|
+
class PermissionStateService {
|
|
278
|
+
constructor() {
|
|
279
|
+
this.navigator = inject(NAVIGATOR);
|
|
280
|
+
this.streams = new Map();
|
|
281
|
+
}
|
|
282
|
+
/**
|
|
283
|
+
* @param descriptor - объект дескриптора или имя разрешения (строка)
|
|
284
|
+
* @returns Значения по мере смены состояния, без подряд идущих повторов. Если
|
|
285
|
+
* {@link Navigator.permissions} нет — поток без эмиссий (`EMPTY`), сразу `complete`.
|
|
286
|
+
* Ошибка {@link Permissions.query} не перехватывается и уходит подписчику.
|
|
287
|
+
*/
|
|
288
|
+
watch(descriptor) {
|
|
289
|
+
const permissions = this.navigator.permissions;
|
|
290
|
+
if (!permissions) {
|
|
291
|
+
return EMPTY;
|
|
292
|
+
}
|
|
293
|
+
const normalized = isString(descriptor)
|
|
294
|
+
? { name: descriptor }
|
|
295
|
+
: descriptor;
|
|
296
|
+
const key = JSON.stringify(normalized);
|
|
297
|
+
let stream = this.streams.get(key);
|
|
298
|
+
if (!stream) {
|
|
299
|
+
stream = from(permissions.query(normalized)).pipe(switchMap((status) => merge(of(status.state), fromEvent(status, 'change').pipe(map(() => status.state)))), distinctUntilChanged(), finalize(() => this.streams.delete(key)), shareReplay({ bufferSize: 1, refCount: true }));
|
|
300
|
+
this.streams.set(key, stream);
|
|
301
|
+
}
|
|
302
|
+
return stream;
|
|
303
|
+
}
|
|
304
|
+
static { this.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "20.3.18", ngImport: i0, type: PermissionStateService, deps: [], target: i0.ɵɵFactoryTarget.Injectable }); }
|
|
305
|
+
static { this.ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "20.3.18", ngImport: i0, type: PermissionStateService, providedIn: 'root' }); }
|
|
306
|
+
}
|
|
307
|
+
i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "20.3.18", ngImport: i0, type: PermissionStateService, decorators: [{
|
|
308
|
+
type: Injectable,
|
|
309
|
+
args: [{
|
|
310
|
+
providedIn: 'root',
|
|
311
|
+
}]
|
|
312
|
+
}] });
|
|
313
|
+
|
|
314
|
+
const MOBILE_WIDTH = 599.98;
|
|
315
|
+
const BREAKPOINTS_KEYS = {
|
|
316
|
+
Mobile: 'Mobile',
|
|
317
|
+
Tablet: 'Tablet',
|
|
318
|
+
Laptop: 'Laptop',
|
|
319
|
+
Desktop: 'Desktop',
|
|
320
|
+
AllLaptop: 'AllLaptop',
|
|
321
|
+
AllMobile: 'AllMobile',
|
|
322
|
+
AllTablet: 'AllTablet',
|
|
323
|
+
WideDesktop: 'WideDesktop',
|
|
324
|
+
LaptopPortrait: 'LaptopPortrait',
|
|
325
|
+
MobilePortrait: 'MobilePortrait',
|
|
326
|
+
TabletPortrait: 'TabletPortrait',
|
|
327
|
+
LaptopLandscape: 'LaptopLandscape',
|
|
328
|
+
MobileLandscape: 'MobileLandscape',
|
|
329
|
+
TabletLandscape: 'TabletLandscape',
|
|
330
|
+
};
|
|
331
|
+
const BREAKPOINTS_QUERY = {
|
|
332
|
+
Mobile: `(max-width: ${MOBILE_WIDTH}px)`,
|
|
333
|
+
WideDesktop: '(min-width: 1920px)',
|
|
334
|
+
Tablet: '(min-width: 600px) and (max-width: 959.98px)',
|
|
335
|
+
Laptop: '(min-width: 960px) and (max-width: 1279.98px)',
|
|
336
|
+
Desktop: '(min-width: 1280px) and (max-width: 1919.98px)',
|
|
337
|
+
LaptopPortrait: '(min-width: 840px) and (orientation: portrait)',
|
|
338
|
+
LaptopLandscape: '(min-width: 1280px) and (orientation: landscape)',
|
|
339
|
+
MobilePortrait: `(max-width: ${MOBILE_WIDTH}px) and (orientation: portrait)`,
|
|
340
|
+
MobileLandscape: '(max-width: 959.98px) and (orientation: landscape)',
|
|
341
|
+
TabletPortrait: '(min-width: 600px) and (max-width: 839.98px) and (orientation: portrait)',
|
|
342
|
+
TabletLandscape: '(min-width: 960px) and (max-width: 1279.98px) and (orientation: landscape)',
|
|
343
|
+
AllLaptop: '(min-width: 840px) and (orientation: portrait), (min-width: 1280px) and (orientation: landscape)',
|
|
344
|
+
AllMobile: `(max-width: ${MOBILE_WIDTH}px) and (orientation: portrait), (max-width: 959.98px) and (orientation: landscape)`,
|
|
345
|
+
AllTablet: '(min-width: 600px) and (max-width: 839.98px) and (orientation: portrait), (min-width: 960px) and (max-width: 1279.98px) and (orientation: landscape)',
|
|
346
|
+
};
|
|
347
|
+
|
|
348
|
+
/**
|
|
349
|
+
* Сервис для реактивного отслеживания media-query брейкпоинтов.
|
|
350
|
+
* Использует `BREAKPOINTS_OBSERVER` для наблюдения и `BREAKPOINTS` для конфигурации.
|
|
351
|
+
*
|
|
352
|
+
* @example
|
|
353
|
+
* ```typescript
|
|
354
|
+
* readonly service = inject(BreakpointsService);
|
|
355
|
+
* readonly isMobile$ = this.service.listen('Mobile');
|
|
356
|
+
* ```
|
|
357
|
+
*/
|
|
358
|
+
class BreakpointsService {
|
|
359
|
+
constructor() {
|
|
360
|
+
this.breakpoints = inject(BREAKPOINTS);
|
|
361
|
+
this.breakpointObserver = inject(BREAKPOINTS_OBSERVER);
|
|
362
|
+
this.breakpointsKeys = objectKeys(this.breakpoints);
|
|
363
|
+
this.cache = new Map();
|
|
364
|
+
this.matches$ = this.breakpointObserver.observe(Object.values(this.breakpoints)).pipe(map((state) => this.buildAllMatched(state.breakpoints)), shareReplay({ bufferSize: 1, refCount: false }));
|
|
365
|
+
}
|
|
366
|
+
/** Возвращает `Observable<boolean>`, отражающий текущее состояние брейкпоинта по ключу. */
|
|
367
|
+
listen(key) {
|
|
368
|
+
let cached = this.cache.get(key);
|
|
369
|
+
if (!cached) {
|
|
370
|
+
cached = this.matches$.pipe(map((data) => data[key] || false), distinctUntilChanged());
|
|
371
|
+
this.cache.set(key, cached);
|
|
372
|
+
}
|
|
373
|
+
return cached;
|
|
374
|
+
}
|
|
375
|
+
buildAllMatched(breakpoints) {
|
|
376
|
+
return Object.fromEntries(this.breakpointsKeys.map((current) => [
|
|
377
|
+
current,
|
|
378
|
+
breakpoints[this.breakpoints[current]] ?? false,
|
|
379
|
+
]));
|
|
380
|
+
}
|
|
381
|
+
static { this.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "20.3.18", ngImport: i0, type: BreakpointsService, deps: [], target: i0.ɵɵFactoryTarget.Injectable }); }
|
|
382
|
+
static { this.ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "20.3.18", ngImport: i0, type: BreakpointsService, providedIn: 'root' }); }
|
|
383
|
+
}
|
|
384
|
+
i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "20.3.18", ngImport: i0, type: BreakpointsService, decorators: [{
|
|
385
|
+
type: Injectable,
|
|
386
|
+
args: [{
|
|
387
|
+
providedIn: 'root',
|
|
388
|
+
}]
|
|
389
|
+
}] });
|
|
390
|
+
|
|
391
|
+
const BREAKPOINTS = new InjectionToken('[BREAKPOINTS]: предоставляет конфиг Breakpoints по умолчанию', {
|
|
392
|
+
factory: () => BREAKPOINTS_QUERY,
|
|
393
|
+
});
|
|
394
|
+
const BREAKPOINTS_OBSERVER = new InjectionToken('[BREAKPOINTS_OBSERVER]: предоставляет реализацию наблюдателя за брейкпоинтами');
|
|
395
|
+
/** Сигнал текущего состояния мобильного брейкпоинта */
|
|
396
|
+
const IS_MOBILE_BREAKPOINT = createBreakpointToken(BREAKPOINTS_KEYS.Mobile, '[IS_MOBILE_BREAKPOINT]: Сигнал, отражающий текущее состояние мобильного брейкпоинта');
|
|
397
|
+
/** Сигнал текущего состояния планшетного брейкпоинта */
|
|
398
|
+
const IS_TABLET_BREAKPOINT = createBreakpointToken(BREAKPOINTS_KEYS.Tablet, '[IS_TABLET_BREAKPOINT]: Сигнал, отражающий текущее состояние планшетного брейкпоинта');
|
|
399
|
+
/** Сигнал текущего состояния брейкпоинта ноутбука */
|
|
400
|
+
const IS_LAPTOP_BREAKPOINT = createBreakpointToken(BREAKPOINTS_KEYS.Laptop, '[IS_LAPTOP_BREAKPOINT]: Сигнал, отражающий текущее состояние брейкпоинта ноутбука');
|
|
401
|
+
/** Сигнал текущего состояния десктопного брейкпоинта */
|
|
402
|
+
const IS_DESKTOP_BREAKPOINT = createBreakpointToken(BREAKPOINTS_KEYS.Desktop, '[IS_DESKTOP_BREAKPOINT]: Сигнал, отражающий текущее состояние десктопного брейкпоинта');
|
|
403
|
+
/** Сигнал текущего состояния широкого десктопного брейкпоинта */
|
|
404
|
+
const IS_WIDE_DESKTOP_BREAKPOINT = createBreakpointToken(BREAKPOINTS_KEYS.WideDesktop, '[IS_WIDE_DESKTOP_BREAKPOINT]: Сигнал, отражающий текущее состояние широкого десктопного брейкпоинта');
|
|
405
|
+
function createBreakpointToken(key, description) {
|
|
406
|
+
return new InjectionToken(description, {
|
|
407
|
+
providedIn: 'root',
|
|
408
|
+
factory: () => {
|
|
409
|
+
const breakpointService = inject(BreakpointsService);
|
|
410
|
+
return toSignal(breakpointService.listen(key), { initialValue: false });
|
|
411
|
+
},
|
|
412
|
+
});
|
|
413
|
+
}
|
|
414
|
+
|
|
415
|
+
/**
|
|
416
|
+
* Переопределяет `IS_MOBILE_BREAKPOINT` на уровне компонента через `ResizeObserver`,
|
|
417
|
+
* вместо глобального media-query использует ширину контейнера.
|
|
418
|
+
*/
|
|
419
|
+
function provideContainerMobileBreakpoint(boxOptions = 'border-box', width = MOBILE_WIDTH) {
|
|
420
|
+
return {
|
|
421
|
+
provide: IS_MOBILE_BREAKPOINT,
|
|
422
|
+
useFactory: (element, destroyReference) => {
|
|
423
|
+
const nativeElement = element.nativeElement;
|
|
424
|
+
const isMobile = signal(nativeElement.getBoundingClientRect().width < width, ...(ngDevMode ? [{ debugName: "isMobile" }] : []));
|
|
425
|
+
const observer = new ResizeObserver(([entry]) => {
|
|
426
|
+
isMobile.set(entry.contentRect.width < width);
|
|
427
|
+
});
|
|
428
|
+
observer.observe(nativeElement, { box: boxOptions });
|
|
429
|
+
destroyReference.onDestroy(() => observer.disconnect());
|
|
430
|
+
return isMobile.asReadonly();
|
|
431
|
+
},
|
|
432
|
+
deps: [ElementRef, DestroyRef],
|
|
433
|
+
};
|
|
434
|
+
}
|
|
435
|
+
/** Расширяет или переопределяет набор media-query брейкпоинтов поверх дефолтных. */
|
|
436
|
+
function provideBreakpoints(breakpoints) {
|
|
437
|
+
return {
|
|
438
|
+
provide: BREAKPOINTS,
|
|
439
|
+
useFactory: () => ({
|
|
440
|
+
...BREAKPOINTS_QUERY,
|
|
441
|
+
...resolveMaybeFn(breakpoints),
|
|
442
|
+
}),
|
|
443
|
+
};
|
|
444
|
+
}
|
|
445
|
+
/** Предоставляет реализацию `BreakpointsObserver` (например, CDK `BreakpointObserver`). */
|
|
446
|
+
function provideBreakpointsObserver(observer) {
|
|
447
|
+
return {
|
|
448
|
+
provide: BREAKPOINTS_OBSERVER,
|
|
449
|
+
useExisting: observer,
|
|
450
|
+
};
|
|
451
|
+
}
|
|
452
|
+
|
|
453
|
+
/**
|
|
454
|
+
* Generated bundle index. Do not edit.
|
|
455
|
+
*/
|
|
456
|
+
|
|
457
|
+
export { BreakpointsService, CookieStoreService, IS_DESKTOP_BREAKPOINT, IS_LAPTOP_BREAKPOINT, IS_MOBILE_BREAKPOINT, IS_TABLET_BREAKPOINT, IS_WIDE_DESKTOP_BREAKPOINT, LocalStorageService, NAVIGATOR, NETWORK_STATUS, PermissionStateService, VISIBILITY_CHANGE, WINDOW, provideBreakpoints, provideBreakpointsObserver, provideContainerMobileBreakpoint };
|
|
458
|
+
//# sourceMappingURL=browser.mjs.map
|