@sevtech/kit 21.4.1 → 21.5.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/browser/index.d.ts +109 -4
- package/fesm2022/browser.mjs +346 -5
- package/fesm2022/browser.mjs.map +1 -1
- package/fesm2022/localization.mjs +3 -3
- package/fesm2022/localization.mjs.map +1 -1
- package/fesm2022/ng-misc.mjs +16 -3
- package/fesm2022/ng-misc.mjs.map +1 -1
- package/misc/index.d.ts +3 -1
- package/ng-misc/index.d.ts +12 -3
- package/package.json +1 -1
package/browser/index.d.ts
CHANGED
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
import * as i0 from '@angular/core';
|
|
2
2
|
import { InjectionToken, Signal, EnvironmentProviders, Type, Provider } from '@angular/core';
|
|
3
3
|
import { Observable } from 'rxjs';
|
|
4
|
-
import { MaybeFunction } from '@sevtech/kit/misc';
|
|
5
|
-
import { KitFeature } from '@sevtech/kit/ng-misc';
|
|
4
|
+
import { MaybeFunction, MaybePromise } from '@sevtech/kit/misc';
|
|
5
|
+
import { KitFeature, MaybeAsync } from '@sevtech/kit/ng-misc';
|
|
6
6
|
|
|
7
7
|
/** Безопасный доступ к объекту `Window` через DI. Бросает `Error` если `Window` недоступен (SSR) */
|
|
8
8
|
declare const WINDOW: InjectionToken<Window>;
|
|
@@ -126,6 +126,8 @@ declare global {
|
|
|
126
126
|
* Одинаковые дескрипторы делят один поток (`shareReplay`).
|
|
127
127
|
*
|
|
128
128
|
* @see https://developer.mozilla.org/docs/Web/API/Permissions_API
|
|
129
|
+
*
|
|
130
|
+
* @deprecated Используйте {@link injectPermissions}: без Permissions API он отдаёт ошибку, а не `EMPTY`.
|
|
129
131
|
*/
|
|
130
132
|
declare class PermissionStateService {
|
|
131
133
|
private readonly navigator;
|
|
@@ -141,6 +143,22 @@ declare class PermissionStateService {
|
|
|
141
143
|
static ɵprov: i0.ɵɵInjectableDeclaration<PermissionStateService>;
|
|
142
144
|
}
|
|
143
145
|
|
|
146
|
+
type Descriptor<T extends PermissionName = PermissionName> = {
|
|
147
|
+
name: T;
|
|
148
|
+
[key: string]: unknown;
|
|
149
|
+
};
|
|
150
|
+
/**
|
|
151
|
+
* Возвращает поток состояния разрешения. Вызывается в инжекционном контексте.
|
|
152
|
+
* Ошибка, если Permissions API нет или разрешение неизвестно браузеру.
|
|
153
|
+
*
|
|
154
|
+
* @see https://developer.mozilla.org/docs/Web/API/Permissions_API
|
|
155
|
+
*/
|
|
156
|
+
declare function injectPermissions<T extends PermissionName>(permission: T): Observable<PermissionState>;
|
|
157
|
+
/** То же по дескриптору с параметрами, например `{ name: 'midi', sysex: true }`. */
|
|
158
|
+
declare function injectPermissions<T extends PermissionName>(descriptor: Descriptor<T>): Observable<PermissionState>;
|
|
159
|
+
/** Потоки нескольких разрешений объектом по именам: `{ camera, microphone }`. */
|
|
160
|
+
declare function injectPermissions<T extends PermissionName>(permission: T, ...permissions: [T, ...T[]]): Record<T, Observable<PermissionState>>;
|
|
161
|
+
|
|
144
162
|
declare const BREAKPOINTS_KEYS: {
|
|
145
163
|
readonly Mobile: "Mobile";
|
|
146
164
|
readonly Tablet: "Tablet";
|
|
@@ -256,5 +274,92 @@ declare class BreakpointsService {
|
|
|
256
274
|
static ɵprov: i0.ɵɵInjectableDeclaration<BreakpointsService>;
|
|
257
275
|
}
|
|
258
276
|
|
|
259
|
-
|
|
260
|
-
|
|
277
|
+
interface CopyApi {
|
|
278
|
+
copy(text: string): MaybePromise<boolean | null>;
|
|
279
|
+
}
|
|
280
|
+
type CopyHandler = MaybeAsync<CopyApi | null>;
|
|
281
|
+
type CopyFn = (text: string) => Promise<boolean>;
|
|
282
|
+
|
|
283
|
+
/** Предоставляет возможность переопределить браузерное апи копирования на свое решение */
|
|
284
|
+
declare function provideCopy(handler: MaybeFunction<CopyHandler>): EnvironmentProviders;
|
|
285
|
+
|
|
286
|
+
/**
|
|
287
|
+
* Возвращает функцию копирования текста в буфер обмена. Вызывается в инжекционном контексте.
|
|
288
|
+
*
|
|
289
|
+
* Своя реализация из {@link provideCopy}, иначе `navigator.clipboard.writeText`, а без него —
|
|
290
|
+
* `document.execCommand('copy')`. Вызывать прямо из обработчика клика: веб-ветке нужен жест пользователя.
|
|
291
|
+
*/
|
|
292
|
+
declare function injectCopy(): CopyFn;
|
|
293
|
+
|
|
294
|
+
interface ShareApi {
|
|
295
|
+
share(payload: SharePayload): MaybePromise<ShareResult | boolean | null>;
|
|
296
|
+
}
|
|
297
|
+
interface SharePayload {
|
|
298
|
+
text: string;
|
|
299
|
+
url: string;
|
|
300
|
+
title?: string;
|
|
301
|
+
}
|
|
302
|
+
type ShareResult = 'shared' | 'copied' | 'cancelled' | 'unsupported';
|
|
303
|
+
type ShareHandler = MaybeAsync<ShareApi | null>;
|
|
304
|
+
type ShareFn = (payload: SharePayload) => Promise<ShareResult>;
|
|
305
|
+
|
|
306
|
+
/** Предоставляет возможность переопределить браузерное апи шеринга на свое решение */
|
|
307
|
+
declare function provideShare(handler: MaybeFunction<ShareHandler>): EnvironmentProviders;
|
|
308
|
+
|
|
309
|
+
/**
|
|
310
|
+
* Возвращает функцию шеринга. Вызывается в инжекционном контексте.
|
|
311
|
+
*
|
|
312
|
+
* Своя реализация из {@link provideShare}, иначе Web Share API, а без него — копирование ссылки.
|
|
313
|
+
* Вызывать прямо из обработчика клика: веб-ветке нужен жест пользователя.
|
|
314
|
+
*/
|
|
315
|
+
declare function injectShare(): ShareFn;
|
|
316
|
+
|
|
317
|
+
interface VibrationApi {
|
|
318
|
+
vibrate(pattern: VibrationConfig['pattern']): MaybePromise<void | null>;
|
|
319
|
+
}
|
|
320
|
+
type VibrateFn = (pattern?: VibrationConfig['pattern']) => void;
|
|
321
|
+
type VibrationHandler = MaybeAsync<VibrationApi | null>;
|
|
322
|
+
type VibrationConfig = {
|
|
323
|
+
pattern: VibratePattern;
|
|
324
|
+
};
|
|
325
|
+
|
|
326
|
+
declare const enum Features {
|
|
327
|
+
CustomHandler = 0
|
|
328
|
+
}
|
|
329
|
+
/** Предоставляет возможность переопределить браузерное апи вибраций на свое решение */
|
|
330
|
+
declare const withCustomVibration: (factory: MaybeFunction<VibrationHandler>) => KitFeature<Features>;
|
|
331
|
+
/**
|
|
332
|
+
* Настраивает вибрацию: паттерн по умолчанию и фичи. Без провайдера {@link injectVibration} работает
|
|
333
|
+
* на `navigator.vibrate` с паттерном `100`.
|
|
334
|
+
*/
|
|
335
|
+
declare function provideVibration(...features: KitFeature<Features>[]): EnvironmentProviders;
|
|
336
|
+
declare function provideVibration(config: MaybeFunction<Partial<VibrationConfig>>, ...features: KitFeature<Features>[]): EnvironmentProviders;
|
|
337
|
+
|
|
338
|
+
/**
|
|
339
|
+
* Возвращает функцию вибрации. Вызывается в инжекционном контексте.
|
|
340
|
+
*
|
|
341
|
+
* Своя реализация из {@link withCustomVibration}, иначе `navigator.vibrate`.
|
|
342
|
+
*/
|
|
343
|
+
declare function injectVibration(): VibrateFn;
|
|
344
|
+
|
|
345
|
+
type Axis = 'portrait' | 'landscape';
|
|
346
|
+
type OrientationLock = 'natural' | Axis | `${Axis}-primary` | `${Axis}-secondary`;
|
|
347
|
+
type OrientationRestore = OrientationLock | 'unlock' | 'keep';
|
|
348
|
+
type OrientationLockOptions = {
|
|
349
|
+
watchOnly: true;
|
|
350
|
+
restoreTo?: never;
|
|
351
|
+
when?: never;
|
|
352
|
+
} | {
|
|
353
|
+
watchOnly?: false;
|
|
354
|
+
restoreTo?: OrientationRestore;
|
|
355
|
+
when?: Signal<boolean>;
|
|
356
|
+
};
|
|
357
|
+
|
|
358
|
+
/**
|
|
359
|
+
* Блокирует ориентацию экрана до уничтожения вызывающего и возвращает сигнал «ориентация подходит».
|
|
360
|
+
* Вызывается в инжекционном контексте.
|
|
361
|
+
*/
|
|
362
|
+
declare function orientationLock(orientation: OrientationLock, options?: OrientationLockOptions): Signal<boolean>;
|
|
363
|
+
|
|
364
|
+
export { BREAKPOINTS_KEYS as BREAKPOINTS, 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, injectBreakpoint, injectCopy, injectCurrentBreakpoint, injectPermissions, injectShare, injectVibration, orientationLock, provideBreakpoints, provideBreakpointsObserver, provideCopy, provideShare, provideVibration, withContainerBreakpoint, withCustomObserver, withCustomVibration, withPriorityKeys };
|
|
365
|
+
export type { BreakpointsObserver, CopyApi, CopyFn, OrientationLock, OrientationLockOptions, OrientationRestore, ShareApi, ShareFn, SharePayload, ShareResult, VibrateFn, VibrationApi, VibrationConfig };
|
package/fesm2022/browser.mjs
CHANGED
|
@@ -1,11 +1,11 @@
|
|
|
1
1
|
import * as i0 from '@angular/core';
|
|
2
|
-
import { InjectionToken, inject, DOCUMENT, Injectable, ElementRef, DestroyRef, signal, makeEnvironmentProviders } from '@angular/core';
|
|
3
|
-
import { merge, fromEvent, map, startWith, distinctUntilChanged, shareReplay, Observable, filter, EMPTY, from, switchMap, of, finalize } from 'rxjs';
|
|
2
|
+
import { InjectionToken, inject, DOCUMENT, Injectable, ElementRef, DestroyRef, signal, makeEnvironmentProviders, provideAppInitializer, effect } from '@angular/core';
|
|
3
|
+
import { merge, fromEvent, map, startWith, distinctUntilChanged, shareReplay, Observable, filter, EMPTY, from, switchMap, of, finalize, throwError, defer } from 'rxjs';
|
|
4
4
|
import { DOCUMENT as DOCUMENT$1 } from '@angular/common';
|
|
5
|
-
import { isString, safeParseJSON, objectKeys, resolveMaybeFn } from '@sevtech/kit/misc';
|
|
5
|
+
import { isString, safeParseJSON, objectKeys, resolveMaybeFn, isFunction, isTypeWith, isPromise } from '@sevtech/kit/misc';
|
|
6
6
|
import { toSignal } from '@angular/core/rxjs-interop';
|
|
7
7
|
import { BreakpointObserver } from '@angular/cdk/layout';
|
|
8
|
-
import { defineKitFeature, resolveConfigProviders, collectFeatureProviders } from '@sevtech/kit/ng-misc';
|
|
8
|
+
import { defineKitFeature, resolveConfigProviders, collectFeatureProviders, fromMaybeAsync, safeCatchError } from '@sevtech/kit/ng-misc';
|
|
9
9
|
|
|
10
10
|
/** Безопасный доступ к объекту `Window` через DI. Бросает `Error` если `Window` недоступен (SSR) */
|
|
11
11
|
const WINDOW = new InjectionToken('[WINDOW]: Предоставляет безопасный доступ к объекту Window', {
|
|
@@ -275,6 +275,8 @@ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "20.3.18", ngImpo
|
|
|
275
275
|
* Одинаковые дескрипторы делят один поток (`shareReplay`).
|
|
276
276
|
*
|
|
277
277
|
* @see https://developer.mozilla.org/docs/Web/API/Permissions_API
|
|
278
|
+
*
|
|
279
|
+
* @deprecated Используйте {@link injectPermissions}: без Permissions API он отдаёт ошибку, а не `EMPTY`.
|
|
278
280
|
*/
|
|
279
281
|
class PermissionStateService {
|
|
280
282
|
constructor() {
|
|
@@ -313,6 +315,37 @@ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "20.3.18", ngImpo
|
|
|
313
315
|
}]
|
|
314
316
|
}] });
|
|
315
317
|
|
|
318
|
+
const cache = new Map();
|
|
319
|
+
function injectPermissions(permission, ...permissions) {
|
|
320
|
+
const api = inject(NAVIGATOR).permissions;
|
|
321
|
+
const descriptors = [permission, ...permissions].map(toDescriptor);
|
|
322
|
+
if (descriptors.length === 1)
|
|
323
|
+
return watchPermission(api, descriptors[0]);
|
|
324
|
+
return Object.fromEntries(descriptors.map((descriptor) => [descriptor.name, watchPermission(api, descriptor)]));
|
|
325
|
+
}
|
|
326
|
+
function watchPermission(permissions, descriptor) {
|
|
327
|
+
if (!permissions)
|
|
328
|
+
return throwError(() => new Error('Permissions API is not supported'));
|
|
329
|
+
const key = toKey(descriptor);
|
|
330
|
+
const cached = cache.get(key);
|
|
331
|
+
if (cached)
|
|
332
|
+
return cached;
|
|
333
|
+
const stream = defer(() => permissions.query(descriptor)).pipe(switchMap((status) => fromEvent(status, 'change').pipe(startWith(null), map(() => status.state))), distinctUntilChanged(), finalize(() => {
|
|
334
|
+
if (cache.get(key) === stream)
|
|
335
|
+
cache.delete(key);
|
|
336
|
+
}), shareReplay({ bufferSize: 1, refCount: true }));
|
|
337
|
+
cache.set(key, stream);
|
|
338
|
+
return stream;
|
|
339
|
+
}
|
|
340
|
+
function toDescriptor(permission) {
|
|
341
|
+
return isString(permission) ? { name: permission } : permission;
|
|
342
|
+
}
|
|
343
|
+
function toKey(descriptor) {
|
|
344
|
+
return JSON.stringify(objectKeys(descriptor)
|
|
345
|
+
.sort()
|
|
346
|
+
.map((key) => [key, descriptor[key]]));
|
|
347
|
+
}
|
|
348
|
+
|
|
316
349
|
const MOBILE_WIDTH = 599.98;
|
|
317
350
|
const WIDE_DESKTOP_WIDTH = 1920;
|
|
318
351
|
const BREAKPOINTS_KEYS = {
|
|
@@ -540,9 +573,317 @@ function provideBreakpointsObserver(observer) {
|
|
|
540
573
|
return makeEnvironmentProviders([withCustomObserver(observer).ɵproviders]);
|
|
541
574
|
}
|
|
542
575
|
|
|
576
|
+
const COPY_HANDLER = new InjectionToken('[COPY_HANDLER]');
|
|
577
|
+
const COPY_API = new InjectionToken('[COPY_API]', {
|
|
578
|
+
factory: () => {
|
|
579
|
+
const handler = inject(COPY_HANDLER, { optional: true });
|
|
580
|
+
return toSignal(fromMaybeAsync(handler).pipe(safeCatchError()), { initialValue: null });
|
|
581
|
+
},
|
|
582
|
+
});
|
|
583
|
+
|
|
584
|
+
/** Предоставляет возможность переопределить браузерное апи копирования на свое решение */
|
|
585
|
+
function provideCopy(handler) {
|
|
586
|
+
return makeEnvironmentProviders([
|
|
587
|
+
{
|
|
588
|
+
provide: COPY_HANDLER,
|
|
589
|
+
useFactory: () => resolveMaybeFn(handler),
|
|
590
|
+
},
|
|
591
|
+
provideAppInitializer(() => void inject(COPY_API)),
|
|
592
|
+
]);
|
|
593
|
+
}
|
|
594
|
+
|
|
595
|
+
/**
|
|
596
|
+
* @internal
|
|
597
|
+
* Вызывает свою реализацию. Нет api или вызов бросил исключение — `null`,
|
|
598
|
+
* как и явный отказ реализации: вызывающий уходит в веб-ветку синхронно, с жестом пользователя.
|
|
599
|
+
*/
|
|
600
|
+
function callApi(api, call) {
|
|
601
|
+
if (!api)
|
|
602
|
+
return null;
|
|
603
|
+
try {
|
|
604
|
+
return call(api);
|
|
605
|
+
}
|
|
606
|
+
catch {
|
|
607
|
+
return null;
|
|
608
|
+
}
|
|
609
|
+
}
|
|
610
|
+
|
|
611
|
+
/**
|
|
612
|
+
* Возвращает функцию копирования текста в буфер обмена. Вызывается в инжекционном контексте.
|
|
613
|
+
*
|
|
614
|
+
* Своя реализация из {@link provideCopy}, иначе `navigator.clipboard.writeText`, а без него —
|
|
615
|
+
* `document.execCommand('copy')`. Вызывать прямо из обработчика клика: веб-ветке нужен жест пользователя.
|
|
616
|
+
*/
|
|
617
|
+
function injectCopy() {
|
|
618
|
+
const navigator = inject(NAVIGATOR);
|
|
619
|
+
const document = inject(DOCUMENT);
|
|
620
|
+
const api$$ = inject(COPY_API);
|
|
621
|
+
return async (text) => {
|
|
622
|
+
const fallback = () => copyByWebApi(navigator.clipboard, document, text);
|
|
623
|
+
const result = callApi(api$$(), (api) => api.copy(text));
|
|
624
|
+
if (result === null)
|
|
625
|
+
return fallback();
|
|
626
|
+
return Promise.resolve(result).then((resolved) => (resolved === null ? fallback() : resolved), () => fallback());
|
|
627
|
+
};
|
|
628
|
+
}
|
|
629
|
+
async function copyByWebApi(clipboard, document, text) {
|
|
630
|
+
if (!isFunction(clipboard?.writeText))
|
|
631
|
+
return execCommandCopy(document, text);
|
|
632
|
+
try {
|
|
633
|
+
await clipboard.writeText(text);
|
|
634
|
+
return true;
|
|
635
|
+
}
|
|
636
|
+
catch {
|
|
637
|
+
return execCommandCopy(document, text);
|
|
638
|
+
}
|
|
639
|
+
}
|
|
640
|
+
function execCommandCopy(document, text) {
|
|
641
|
+
const active = document.activeElement;
|
|
642
|
+
const area = document.createElement('textarea');
|
|
643
|
+
area.value = text;
|
|
644
|
+
area.setAttribute('readonly', '');
|
|
645
|
+
area.setAttribute('aria-hidden', 'true');
|
|
646
|
+
area.style.position = 'fixed';
|
|
647
|
+
area.style.top = '0';
|
|
648
|
+
area.style.left = '-9999px';
|
|
649
|
+
area.style.opacity = '0';
|
|
650
|
+
area.style.pointerEvents = 'none';
|
|
651
|
+
try {
|
|
652
|
+
document.body.appendChild(area);
|
|
653
|
+
area.select();
|
|
654
|
+
return document.execCommand('copy');
|
|
655
|
+
}
|
|
656
|
+
catch {
|
|
657
|
+
return false;
|
|
658
|
+
}
|
|
659
|
+
finally {
|
|
660
|
+
area.remove();
|
|
661
|
+
if (active instanceof HTMLElement)
|
|
662
|
+
active.focus();
|
|
663
|
+
}
|
|
664
|
+
}
|
|
665
|
+
|
|
666
|
+
const SHARE_HANDLER = new InjectionToken('[SHARE_HANDLER]');
|
|
667
|
+
const SHARE_API = new InjectionToken('[SHARE_API]', {
|
|
668
|
+
factory: () => {
|
|
669
|
+
const handler = inject(SHARE_HANDLER, { optional: true });
|
|
670
|
+
return toSignal(fromMaybeAsync(handler).pipe(safeCatchError()), { initialValue: null });
|
|
671
|
+
},
|
|
672
|
+
});
|
|
673
|
+
|
|
674
|
+
/** Предоставляет возможность переопределить браузерное апи шеринга на свое решение */
|
|
675
|
+
function provideShare(handler) {
|
|
676
|
+
return makeEnvironmentProviders([
|
|
677
|
+
{
|
|
678
|
+
provide: SHARE_HANDLER,
|
|
679
|
+
useFactory: () => resolveMaybeFn(handler),
|
|
680
|
+
},
|
|
681
|
+
provideAppInitializer(() => void inject(SHARE_API)),
|
|
682
|
+
]);
|
|
683
|
+
}
|
|
684
|
+
|
|
685
|
+
/**
|
|
686
|
+
* Возвращает функцию шеринга. Вызывается в инжекционном контексте.
|
|
687
|
+
*
|
|
688
|
+
* Своя реализация из {@link provideShare}, иначе Web Share API, а без него — копирование ссылки.
|
|
689
|
+
* Вызывать прямо из обработчика клика: веб-ветке нужен жест пользователя.
|
|
690
|
+
*/
|
|
691
|
+
function injectShare() {
|
|
692
|
+
const navigator = inject(NAVIGATOR);
|
|
693
|
+
const api$$ = inject(SHARE_API);
|
|
694
|
+
const copy = injectCopy();
|
|
695
|
+
return (payload) => {
|
|
696
|
+
const fallback = () => shareByWebApi(navigator, copy, payload);
|
|
697
|
+
const result = callApi(api$$(), (api) => api.share(payload));
|
|
698
|
+
if (result === null)
|
|
699
|
+
return fallback();
|
|
700
|
+
return Promise.resolve(result).then((resolved) => (resolved === null ? fallback() : toShareResult(resolved)), () => copy(payload.url).then(toShareCopyResult));
|
|
701
|
+
};
|
|
702
|
+
}
|
|
703
|
+
async function shareByWebApi(navigator, copy, payload) {
|
|
704
|
+
if (!canShare(navigator, payload))
|
|
705
|
+
return toShareCopyResult(await copy(payload.url));
|
|
706
|
+
try {
|
|
707
|
+
await navigator.share(payload);
|
|
708
|
+
return 'shared';
|
|
709
|
+
}
|
|
710
|
+
catch (error) {
|
|
711
|
+
return isAbortError(error) ? 'cancelled' : toShareCopyResult(await copy(payload.url));
|
|
712
|
+
}
|
|
713
|
+
}
|
|
714
|
+
function toShareResult(result) {
|
|
715
|
+
if (isString(result))
|
|
716
|
+
return result;
|
|
717
|
+
return result ? 'shared' : 'cancelled';
|
|
718
|
+
}
|
|
719
|
+
function toShareCopyResult(copied) {
|
|
720
|
+
return copied ? 'copied' : 'unsupported';
|
|
721
|
+
}
|
|
722
|
+
function canShare(navigator, payload) {
|
|
723
|
+
return (isFunction(navigator.share) && (!isFunction(navigator.canShare) || navigator.canShare(payload)));
|
|
724
|
+
}
|
|
725
|
+
function isAbortError(error) {
|
|
726
|
+
return isTypeWith(error) && error.name === 'AbortError';
|
|
727
|
+
}
|
|
728
|
+
|
|
729
|
+
const VIBRATION_HANDLER = new InjectionToken('[VIBRATION_HANDLER]');
|
|
730
|
+
const VIBRATION_API = new InjectionToken('[VIBRATION_API]', {
|
|
731
|
+
factory: () => {
|
|
732
|
+
const handler = inject(VIBRATION_HANDLER, { optional: true });
|
|
733
|
+
return toSignal(fromMaybeAsync(handler).pipe(safeCatchError()), {
|
|
734
|
+
initialValue: null,
|
|
735
|
+
});
|
|
736
|
+
},
|
|
737
|
+
});
|
|
738
|
+
const DEFAULT_CONFIG = {
|
|
739
|
+
pattern: 100,
|
|
740
|
+
};
|
|
741
|
+
const VIBRATION_CONFIG = new InjectionToken('[VIBRATION_CONFIG]', {
|
|
742
|
+
factory: () => DEFAULT_CONFIG,
|
|
743
|
+
});
|
|
744
|
+
|
|
745
|
+
/** Предоставляет возможность переопределить браузерное апи вибраций на свое решение */
|
|
746
|
+
const withCustomVibration = defineKitFeature(0 /* Features.CustomHandler */, (factory) => ({
|
|
747
|
+
provide: VIBRATION_HANDLER,
|
|
748
|
+
useFactory: () => resolveMaybeFn(factory),
|
|
749
|
+
}));
|
|
750
|
+
function provideVibration(config, ...features) {
|
|
751
|
+
const providers = resolveConfigProviders(config, (item) => ({
|
|
752
|
+
provide: VIBRATION_CONFIG,
|
|
753
|
+
useFactory: () => ({
|
|
754
|
+
...DEFAULT_CONFIG,
|
|
755
|
+
...resolveMaybeFn(item),
|
|
756
|
+
}),
|
|
757
|
+
}));
|
|
758
|
+
return makeEnvironmentProviders([
|
|
759
|
+
...providers,
|
|
760
|
+
...collectFeatureProviders(config, ...features),
|
|
761
|
+
provideAppInitializer(() => void inject(VIBRATION_API)),
|
|
762
|
+
]);
|
|
763
|
+
}
|
|
764
|
+
|
|
765
|
+
/**
|
|
766
|
+
* Возвращает функцию вибрации. Вызывается в инжекционном контексте.
|
|
767
|
+
*
|
|
768
|
+
* Своя реализация из {@link withCustomVibration}, иначе `navigator.vibrate`.
|
|
769
|
+
*/
|
|
770
|
+
function injectVibration() {
|
|
771
|
+
const navigator = inject(NAVIGATOR);
|
|
772
|
+
const config = inject(VIBRATION_CONFIG);
|
|
773
|
+
const api$$ = inject(VIBRATION_API);
|
|
774
|
+
return (pattern = config.pattern) => {
|
|
775
|
+
const fallback = () => vibrateByWebApi(navigator, pattern);
|
|
776
|
+
const result = callApi(api$$(), (api) => api.vibrate(pattern));
|
|
777
|
+
if (result === null)
|
|
778
|
+
return fallback();
|
|
779
|
+
if (!isPromise(result))
|
|
780
|
+
return;
|
|
781
|
+
void result.then((resolved) => {
|
|
782
|
+
if (resolved === null)
|
|
783
|
+
fallback();
|
|
784
|
+
}, () => fallback());
|
|
785
|
+
};
|
|
786
|
+
}
|
|
787
|
+
function vibrateByWebApi(navigator, pattern) {
|
|
788
|
+
if (!isFunction(navigator.vibrate))
|
|
789
|
+
return;
|
|
790
|
+
navigator.vibrate(pattern);
|
|
791
|
+
}
|
|
792
|
+
|
|
793
|
+
class OrientationService {
|
|
794
|
+
constructor() {
|
|
795
|
+
this.window = inject(WINDOW);
|
|
796
|
+
this.stack = [];
|
|
797
|
+
}
|
|
798
|
+
get screenOrientation() {
|
|
799
|
+
return this.window?.screen.orientation;
|
|
800
|
+
}
|
|
801
|
+
lock(orientation, restoreTo) {
|
|
802
|
+
const request = { orientation, restoreTo };
|
|
803
|
+
this.stack.push(request);
|
|
804
|
+
this.apply(orientation);
|
|
805
|
+
return request;
|
|
806
|
+
}
|
|
807
|
+
unlock(request) {
|
|
808
|
+
const index = this.stack.indexOf(request);
|
|
809
|
+
if (index === -1)
|
|
810
|
+
return;
|
|
811
|
+
this.stack.splice(index, 1);
|
|
812
|
+
const previous = this.stack.length > 0 ? this.stack[this.stack.length - 1] : null;
|
|
813
|
+
const target = previous ? previous.orientation : request.restoreTo;
|
|
814
|
+
if (target === 'keep')
|
|
815
|
+
return;
|
|
816
|
+
if (target === 'unlock')
|
|
817
|
+
return this.reset();
|
|
818
|
+
return this.apply(target);
|
|
819
|
+
}
|
|
820
|
+
apply(orientation) {
|
|
821
|
+
void this.screenOrientation?.lock?.(orientation).catch(() => undefined);
|
|
822
|
+
}
|
|
823
|
+
reset() {
|
|
824
|
+
try {
|
|
825
|
+
this.screenOrientation?.unlock();
|
|
826
|
+
}
|
|
827
|
+
catch { }
|
|
828
|
+
}
|
|
829
|
+
static { this.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "20.3.18", ngImport: i0, type: OrientationService, deps: [], target: i0.ɵɵFactoryTarget.Injectable }); }
|
|
830
|
+
static { this.ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "20.3.18", ngImport: i0, type: OrientationService, providedIn: 'root' }); }
|
|
831
|
+
}
|
|
832
|
+
i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "20.3.18", ngImport: i0, type: OrientationService, decorators: [{
|
|
833
|
+
type: Injectable,
|
|
834
|
+
args: [{
|
|
835
|
+
providedIn: 'root',
|
|
836
|
+
}]
|
|
837
|
+
}] });
|
|
838
|
+
|
|
839
|
+
function watchOrientation(orientation, view, destroyRef) {
|
|
840
|
+
const axis = toAxis(orientation);
|
|
841
|
+
if (!axis || !view)
|
|
842
|
+
return signal(true).asReadonly();
|
|
843
|
+
const query = view.matchMedia(`(orientation: ${axis}), (pointer: fine)`);
|
|
844
|
+
const state = signal(query.matches, ...(ngDevMode ? [{ debugName: "state" }] : []));
|
|
845
|
+
const sync = () => state.set(query.matches);
|
|
846
|
+
query.addEventListener('change', sync);
|
|
847
|
+
destroyRef.onDestroy(() => query.removeEventListener('change', sync));
|
|
848
|
+
return state.asReadonly();
|
|
849
|
+
}
|
|
850
|
+
function toAxis(orientation) {
|
|
851
|
+
if (orientation.startsWith('portrait'))
|
|
852
|
+
return 'portrait';
|
|
853
|
+
if (orientation.startsWith('landscape'))
|
|
854
|
+
return 'landscape';
|
|
855
|
+
return null;
|
|
856
|
+
}
|
|
857
|
+
/**
|
|
858
|
+
* Блокирует ориентацию экрана до уничтожения вызывающего и возвращает сигнал «ориентация подходит».
|
|
859
|
+
* Вызывается в инжекционном контексте.
|
|
860
|
+
*/
|
|
861
|
+
function orientationLock(orientation, options = {}) {
|
|
862
|
+
const service = inject(OrientationService);
|
|
863
|
+
const destroyRef = inject(DestroyRef);
|
|
864
|
+
const view = inject(WINDOW);
|
|
865
|
+
if (!options.watchOnly) {
|
|
866
|
+
const restoreTo = options.restoreTo ?? 'keep';
|
|
867
|
+
const when = options.when;
|
|
868
|
+
if (when) {
|
|
869
|
+
effect((onCleanup) => {
|
|
870
|
+
if (!when())
|
|
871
|
+
return;
|
|
872
|
+
const request = service.lock(orientation, restoreTo);
|
|
873
|
+
onCleanup(() => service.unlock(request));
|
|
874
|
+
});
|
|
875
|
+
}
|
|
876
|
+
else {
|
|
877
|
+
const request = service.lock(orientation, restoreTo);
|
|
878
|
+
destroyRef.onDestroy(() => service.unlock(request));
|
|
879
|
+
}
|
|
880
|
+
}
|
|
881
|
+
return watchOrientation(orientation, view, destroyRef);
|
|
882
|
+
}
|
|
883
|
+
|
|
543
884
|
/**
|
|
544
885
|
* Generated bundle index. Do not edit.
|
|
545
886
|
*/
|
|
546
887
|
|
|
547
|
-
export { BREAKPOINTS_KEYS as BREAKPOINTS, 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, injectBreakpoint, injectCurrentBreakpoint, provideBreakpoints, provideBreakpointsObserver, withContainerBreakpoint, withCustomObserver, withPriorityKeys };
|
|
888
|
+
export { BREAKPOINTS_KEYS as BREAKPOINTS, 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, injectBreakpoint, injectCopy, injectCurrentBreakpoint, injectPermissions, injectShare, injectVibration, orientationLock, provideBreakpoints, provideBreakpointsObserver, provideCopy, provideShare, provideVibration, withContainerBreakpoint, withCustomObserver, withCustomVibration, withPriorityKeys };
|
|
548
889
|
//# sourceMappingURL=browser.mjs.map
|