@loidolt/theme-capacitor 0.0.0-stage → 0.12.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.
@@ -0,0 +1,110 @@
1
+ import { nativePlatform, quietly } from './platform.js';
2
+ /**
3
+ * Controls whose activation changes a value — the moments a native control ticks. Disabled ones
4
+ * are skipped. Buttons are left out on purpose: iOS and Android buttons do not buzz, and a buzz
5
+ * on every press soon reads as noise. Opt one in with `data-haptic`.
6
+ */
7
+ export const SELECTION_TARGETS = [
8
+ '[role="switch"]',
9
+ '[role="checkbox"]',
10
+ '[role="radio"]',
11
+ '[role="tab"]',
12
+ '[role="menuitemcheckbox"]',
13
+ '[role="menuitemradio"]',
14
+ '[role="option"]',
15
+ 'input[type="checkbox"]',
16
+ 'input[type="radio"]',
17
+ '.ldt-tab-bar__item',
18
+ '[aria-pressed]',
19
+ ].join(', ');
20
+ const IMPACT = { light: 'LIGHT', medium: 'MEDIUM', heavy: 'HEAVY' };
21
+ const NOTIFY = { success: 'SUCCESS', warning: 'WARNING', error: 'ERROR' };
22
+ const isWeight = (value) => value === 'light' || value === 'medium' || value === 'heavy';
23
+ /**
24
+ * Haptic feedback through `@capacitor/haptics`, in the theme's vocabulary. Silent in a browser,
25
+ * even one that can vibrate: a web page that buzzes is a surprise, a native app that does not is
26
+ * a disappointment.
27
+ *
28
+ * ```ts
29
+ * import { Haptics } from '@capacitor/haptics';
30
+ * export const haptics = createHaptics({ Haptics });
31
+ * haptics.install();
32
+ * ```
33
+ */
34
+ export function createHaptics(options) {
35
+ const { Haptics, enabled = () => true } = options;
36
+ const live = () => nativePlatform() !== null && enabled();
37
+ const impact = (weight = 'light') => {
38
+ if (live())
39
+ quietly(Haptics.impact({ style: IMPACT[weight] }));
40
+ };
41
+ const selection = () => {
42
+ if (!live())
43
+ return;
44
+ // A one-off tick is the whole start/changed/end sequence; started alone, Android stays silent.
45
+ quietly(Haptics.selectionStart()
46
+ .then(() => Haptics.selectionChanged())
47
+ .then(() => Haptics.selectionEnd()));
48
+ };
49
+ const notify = (variant) => {
50
+ if (!live() || !variant || variant === 'info')
51
+ return;
52
+ quietly(Haptics.notification({ type: NOTIFY[variant] }));
53
+ };
54
+ const install = (installOptions = {}) => {
55
+ if (typeof document === 'undefined')
56
+ return () => { };
57
+ const { selection: selector = SELECTION_TARGETS } = installOptions;
58
+ const onClick = (event) => {
59
+ const target = event.target instanceof Element ? event.target : null;
60
+ if (!target)
61
+ return;
62
+ const opted = target.closest('[data-haptic]');
63
+ const control = opted ?? target.closest(selector);
64
+ if (!control || control.matches(':disabled, [aria-disabled="true"]'))
65
+ return;
66
+ if (opted) {
67
+ const weight = opted.dataset.haptic;
68
+ impact(isWeight(weight) ? weight : 'light');
69
+ }
70
+ else
71
+ selection();
72
+ };
73
+ document.addEventListener('click', onClick);
74
+ return () => document.removeEventListener('click', onClick);
75
+ };
76
+ return { impact, selection, notify, install };
77
+ }
78
+ /**
79
+ * The same toaster, with the matching notification pattern on every status toast — a success
80
+ * tap, a warning or error buzz — so feedback lands even when the screen is not being watched.
81
+ *
82
+ * ```ts
83
+ * export const toaster = withHaptics(createToaster(), haptics);
84
+ * ```
85
+ */
86
+ export function withHaptics(toaster, haptics) {
87
+ const buzz = (variant, call) => {
88
+ return (...args) => {
89
+ const id = call(...args);
90
+ haptics.notify(typeof variant === 'function' ? variant(...args) : variant);
91
+ return id;
92
+ };
93
+ };
94
+ return {
95
+ get toasts() {
96
+ return toaster.toasts;
97
+ },
98
+ push: buzz((toast) => toast.variant, toaster.push),
99
+ update: toaster.update,
100
+ success: buzz('success', toaster.success),
101
+ info: buzz('info', toaster.info),
102
+ warning: buzz('warning', toaster.warning),
103
+ error: buzz('error', toaster.error),
104
+ dismiss: toaster.dismiss,
105
+ clear: toaster.clear,
106
+ pause: toaster.pause,
107
+ resume: toaster.resume,
108
+ destroy: toaster.destroy,
109
+ };
110
+ }
@@ -0,0 +1,29 @@
1
+ export { isNativePlatform, markNativePlatform, nativePlatform } from './platform.js';
2
+ export type { NativePlatform } from './platform.js';
3
+ export { setupCapacitor } from './setup.js';
4
+ export type { CapacitorPlugins, CapacitorSetup, SetupCapacitorOptions } from './setup.js';
5
+ export { syncNativeAppearance, systemBarStyleFor } from './appearance.js';
6
+ export type { NativeAppearanceOptions, SystemBarStyle } from './appearance.js';
7
+ export { closeTopLayer, handleBackButton } from './back-button.js';
8
+ export type { BackButtonEvent, BackButtonOptions } from './back-button.js';
9
+ export { createNativeKeyboard } from './keyboard.svelte.js';
10
+ export type { NativeKeyboard, NativeKeyboardOptions } from './keyboard.svelte.js';
11
+ export { createHaptics, SELECTION_TARGETS, withHaptics } from './haptics.js';
12
+ export type { HapticsOptions, ImpactWeight, InstallHapticsOptions, NativeHaptics, } from './haptics.js';
13
+ export { persistTheme } from './theme-storage.svelte.js';
14
+ export type { PersistedTheme, PersistThemeOptions } from './theme-storage.svelte.js';
15
+ export { createAppLifecycle, pauseAllMedia } from './lifecycle.svelte.js';
16
+ export type { AppLifecycle, AppLifecycleOptions } from './lifecycle.svelte.js';
17
+ export { deepLinkPath, handleDeepLinks } from './deep-links.js';
18
+ export type { DeepLinkOptions } from './deep-links.js';
19
+ export { createNetworkStatus } from './network.svelte.js';
20
+ export type { NetworkStatus, NetworkStatusOptions } from './network.svelte.js';
21
+ export { openExternalLinks } from './links.js';
22
+ export type { ExternalLinksOptions } from './links.js';
23
+ export { createShare, SHARE_CACHE_PATH } from './share.js';
24
+ export type { NativeShare, ShareableFile, ShareContent, ShareMethod, NativeShareOptions, ShareOutcome, } from './share.js';
25
+ export { acceptToMimeTypes, createFiles, EXTENSION_TYPES, FilePermissionError } from './files.js';
26
+ export type { NativeFiles, NativeFilesOptions, PickOptions, SaveableFile, SaveOptions, SaveOutcome, } from './files.js';
27
+ export { bridgeClipboard, followSystemTextSize, hideSplashScreen } from './system.js';
28
+ export type { HideSplashOptions, SystemTextSizeOptions } from './system.js';
29
+ export type { AppResumePlugin, AppStatePlugin, AppUrlPlugin, BackButtonPlugin, BrowserPlugin, ClipboardPlugin, FilePickerPlugin, FilesystemPlugin, HapticsPlugin, KeyboardPlugin, KeyboardStylePlugin, NetworkPlugin, PickedNativeFile, PluginListenerHandle, PreferencesPlugin, SharePlugin, SplashScreenPlugin, StatusBarPlugin, SystemBarsPlugin, Teardown, TextZoomPlugin, } from './types.js';
package/dist/index.js ADDED
@@ -0,0 +1,14 @@
1
+ export { isNativePlatform, markNativePlatform, nativePlatform } from './platform.js';
2
+ export { setupCapacitor } from './setup.js';
3
+ export { syncNativeAppearance, systemBarStyleFor } from './appearance.js';
4
+ export { closeTopLayer, handleBackButton } from './back-button.js';
5
+ export { createNativeKeyboard } from './keyboard.svelte.js';
6
+ export { createHaptics, SELECTION_TARGETS, withHaptics } from './haptics.js';
7
+ export { persistTheme } from './theme-storage.svelte.js';
8
+ export { createAppLifecycle, pauseAllMedia } from './lifecycle.svelte.js';
9
+ export { deepLinkPath, handleDeepLinks } from './deep-links.js';
10
+ export { createNetworkStatus } from './network.svelte.js';
11
+ export { openExternalLinks } from './links.js';
12
+ export { createShare, SHARE_CACHE_PATH } from './share.js';
13
+ export { acceptToMimeTypes, createFiles, EXTENSION_TYPES, FilePermissionError } from './files.js';
14
+ export { bridgeClipboard, followSystemTextSize, hideSplashScreen } from './system.js';
@@ -0,0 +1,36 @@
1
+ import type { KeyboardPlugin } from './types.js';
2
+ export interface NativeKeyboardOptions {
3
+ /** `Keyboard` from `@capacitor/keyboard`. */
4
+ Keyboard: KeyboardPlugin;
5
+ /**
6
+ * Whether the keyboard draws over the page rather than shrinking it — the `none` resize mode.
7
+ * Then its height becomes the bottom safe area, so the last row, toasts, floating bars and
8
+ * drawers lift above it. `auto` (the default) asks the plugin for its resize mode.
9
+ */
10
+ overlays?: boolean | 'auto';
11
+ /** Scroll the focused field into view once the keyboard is up. Defaults to `true`. */
12
+ revealFocused?: boolean;
13
+ /** Where the attribute and variables are written. Defaults to `<html>`. */
14
+ element?: HTMLElement;
15
+ }
16
+ export interface NativeKeyboard {
17
+ /** Whether the software keyboard is up (or on its way). Reactive. */
18
+ readonly visible: boolean;
19
+ /** Its height in CSS pixels; 0 while hidden. Reactive. */
20
+ readonly height: number;
21
+ /** Removes the listeners and clears the attribute. Automatic for a component-scoped instance. */
22
+ destroy(): void;
23
+ }
24
+ /**
25
+ * Tracks the software keyboard and tells the stylesheet about it:
26
+ *
27
+ * - `data-keyboard="open"` on `<html>` while it is up — `@loidolt/theme-capacitor/styles.css`
28
+ * hides the `TabBar` then, as native apps do, so it does not ride up on top of the keys.
29
+ * - `--ldt-keyboard-height`, its height, for anything of your own that should sit above it.
30
+ * - `--ldt-keyboard-inset`, the part of that height the page has to clear itself: the full
31
+ * height when the keyboard overlays the page, 0 when the web view shrinks for it.
32
+ *
33
+ * The keyboard events fire before the animation, so layout moves with the keys rather than after.
34
+ * A no-op outside a native shell: `visible` stays `false`.
35
+ */
36
+ export declare function createNativeKeyboard(options: NativeKeyboardOptions): NativeKeyboard;
@@ -0,0 +1,75 @@
1
+ import { onDestroy } from 'svelte';
2
+ import { combine, listen, nativePlatform } from './platform.js';
3
+ /**
4
+ * Tracks the software keyboard and tells the stylesheet about it:
5
+ *
6
+ * - `data-keyboard="open"` on `<html>` while it is up — `@loidolt/theme-capacitor/styles.css`
7
+ * hides the `TabBar` then, as native apps do, so it does not ride up on top of the keys.
8
+ * - `--ldt-keyboard-height`, its height, for anything of your own that should sit above it.
9
+ * - `--ldt-keyboard-inset`, the part of that height the page has to clear itself: the full
10
+ * height when the keyboard overlays the page, 0 when the web view shrinks for it.
11
+ *
12
+ * The keyboard events fire before the animation, so layout moves with the keys rather than after.
13
+ * A no-op outside a native shell: `visible` stays `false`.
14
+ */
15
+ export function createNativeKeyboard(options) {
16
+ const { Keyboard, overlays = 'auto', revealFocused = true } = options;
17
+ let visible = $state(false);
18
+ let height = $state(0);
19
+ let teardown = () => { };
20
+ const root = options.element ?? (typeof document === 'undefined' ? null : document.documentElement);
21
+ if (nativePlatform() && root) {
22
+ let overlaid = overlays === true;
23
+ const write = () => {
24
+ if (visible)
25
+ root.dataset.keyboard = 'open';
26
+ else
27
+ delete root.dataset.keyboard;
28
+ root.style.setProperty('--ldt-keyboard-height', `${height}px`);
29
+ root.style.setProperty('--ldt-keyboard-inset', `${overlaid ? height : 0}px`);
30
+ };
31
+ if (overlays === 'auto') {
32
+ Keyboard.getResizeMode().then(({ mode }) => {
33
+ overlaid = mode === 'none';
34
+ if (visible)
35
+ write();
36
+ }, () => { });
37
+ }
38
+ teardown = combine(listen(Keyboard.addListener('keyboardWillShow', (info) => {
39
+ visible = true;
40
+ height = Math.max(0, info.keyboardHeight);
41
+ write();
42
+ })), listen(Keyboard.addListener('keyboardDidShow', () => {
43
+ if (!revealFocused)
44
+ return;
45
+ const focused = root.ownerDocument.activeElement;
46
+ if (focused instanceof HTMLElement && focused !== root.ownerDocument.body) {
47
+ focused.scrollIntoView({ block: 'nearest' });
48
+ }
49
+ })), listen(Keyboard.addListener('keyboardWillHide', () => {
50
+ visible = false;
51
+ height = 0;
52
+ write();
53
+ })), () => {
54
+ delete root.dataset.keyboard;
55
+ root.style.removeProperty('--ldt-keyboard-height');
56
+ root.style.removeProperty('--ldt-keyboard-inset');
57
+ });
58
+ }
59
+ const destroy = () => teardown();
60
+ try {
61
+ onDestroy(destroy);
62
+ }
63
+ catch {
64
+ /* module scope: the caller owns `destroy()` */
65
+ }
66
+ return {
67
+ get visible() {
68
+ return visible;
69
+ },
70
+ get height() {
71
+ return height;
72
+ },
73
+ destroy,
74
+ };
75
+ }
@@ -0,0 +1,25 @@
1
+ import type { AppStatePlugin } from './types.js';
2
+ export interface AppLifecycleOptions {
3
+ /** `App` from `@capacitor/app`. */
4
+ App: AppStatePlugin;
5
+ /**
6
+ * Pause every playing `<video>` and `<audio>` when the app goes to the background — the player
7
+ * components included. Native players stop there too; nothing restarts on its own when the app
8
+ * returns. Defaults to `true`.
9
+ */
10
+ pauseMedia?: boolean;
11
+ onPause?: () => void;
12
+ onResume?: () => void;
13
+ }
14
+ export interface AppLifecycle {
15
+ /** Whether the app is in the foreground. Reactive; always `true` in a browser. */
16
+ readonly active: boolean;
17
+ destroy(): void;
18
+ }
19
+ /** Pauses every playing media element in the document. Returns how many it stopped. */
20
+ export declare function pauseAllMedia(doc?: Document): number;
21
+ /**
22
+ * Foreground and background, as reactive state — so a dashboard can stop polling while nobody is
23
+ * looking — and the native rule that media stops when the app leaves the screen.
24
+ */
25
+ export declare function createAppLifecycle(options: AppLifecycleOptions): AppLifecycle;
@@ -0,0 +1,49 @@
1
+ import { onDestroy } from 'svelte';
2
+ import { listen, nativePlatform } from './platform.js';
3
+ /** Pauses every playing media element in the document. Returns how many it stopped. */
4
+ export function pauseAllMedia(doc = document) {
5
+ let paused = 0;
6
+ for (const media of doc.querySelectorAll('video, audio')) {
7
+ if (media.paused)
8
+ continue;
9
+ media.pause();
10
+ paused += 1;
11
+ }
12
+ return paused;
13
+ }
14
+ /**
15
+ * Foreground and background, as reactive state — so a dashboard can stop polling while nobody is
16
+ * looking — and the native rule that media stops when the app leaves the screen.
17
+ */
18
+ export function createAppLifecycle(options) {
19
+ const { App, pauseMedia = true, onPause, onResume } = options;
20
+ let active = $state(true);
21
+ let teardown = () => { };
22
+ if (nativePlatform()) {
23
+ teardown = listen(App.addListener('appStateChange', ({ isActive }) => {
24
+ if (isActive === active)
25
+ return;
26
+ active = isActive;
27
+ if (isActive)
28
+ onResume?.();
29
+ else {
30
+ if (pauseMedia)
31
+ pauseAllMedia();
32
+ onPause?.();
33
+ }
34
+ }));
35
+ }
36
+ const destroy = () => teardown();
37
+ try {
38
+ onDestroy(destroy);
39
+ }
40
+ catch {
41
+ /* module scope: the caller owns `destroy()` */
42
+ }
43
+ return {
44
+ get active() {
45
+ return active;
46
+ },
47
+ destroy,
48
+ };
49
+ }
@@ -0,0 +1,28 @@
1
+ import { type SemanticRole } from '@loidolt/theme-tokens';
2
+ import type { BrowserPlugin, Teardown } from './types.js';
3
+ export interface ExternalLinksOptions {
4
+ /** `Browser` from `@capacitor/browser`. */
5
+ Browser: BrowserPlugin;
6
+ /**
7
+ * Whether a link leaves the app. Defaults to any `http(s)` URL on another origin — the web
8
+ * view's own origin is the app.
9
+ */
10
+ isExternal?: (url: URL, anchor: HTMLAnchorElement) => boolean;
11
+ /**
12
+ * The colour role the in-app browser's toolbar takes, read live so it matches the current
13
+ * theme. Defaults to `surface`, the colour of `Topbar`; `null` leaves the system default.
14
+ */
15
+ toolbarRole?: SemanticRole | null;
16
+ /** iOS only: `popover` opens a sheet rather than covering the app. Defaults to `fullscreen`. */
17
+ presentationStyle?: 'fullscreen' | 'popover';
18
+ }
19
+ /**
20
+ * Opens links that leave the app in the system's in-app browser (SFSafariViewController, Chrome
21
+ * Custom Tabs) instead of navigating the web view away from the app — which on iOS has no way
22
+ * back. The toolbar takes the theme's colour.
23
+ *
24
+ * It is one delegated listener, so it covers every link, rendered Markdown included. A click
25
+ * your own code has already handled (`preventDefault`), a modified click and a `download` link
26
+ * are left alone. A no-op outside a native shell.
27
+ */
28
+ export declare function openExternalLinks(options: ExternalLinksOptions): Teardown;
package/dist/links.js ADDED
@@ -0,0 +1,49 @@
1
+ import { colorSchemeOf, readRoleColor } from '@loidolt/theme-svelte';
2
+ import { resolveRoles } from '@loidolt/theme-tokens';
3
+ import { nativePlatform, quietly } from './platform.js';
4
+ const defaultIsExternal = (url) => (url.protocol === 'http:' || url.protocol === 'https:') && url.origin !== location.origin;
5
+ /**
6
+ * Opens links that leave the app in the system's in-app browser (SFSafariViewController, Chrome
7
+ * Custom Tabs) instead of navigating the web view away from the app — which on iOS has no way
8
+ * back. The toolbar takes the theme's colour.
9
+ *
10
+ * It is one delegated listener, so it covers every link, rendered Markdown included. A click
11
+ * your own code has already handled (`preventDefault`), a modified click and a `download` link
12
+ * are left alone. A no-op outside a native shell.
13
+ */
14
+ export function openExternalLinks(options) {
15
+ if (!nativePlatform())
16
+ return () => { };
17
+ const { Browser, isExternal = defaultIsExternal, toolbarRole = 'surface', presentationStyle = 'fullscreen', } = options;
18
+ const toolbarColor = () => {
19
+ if (toolbarRole === null)
20
+ return undefined;
21
+ const root = document.documentElement;
22
+ const color = readRoleColor(root, toolbarRole) ??
23
+ resolveRoles({ role: toolbarRole }, colorSchemeOf(root)).role;
24
+ return color.slice(0, 7);
25
+ };
26
+ const onClick = (event) => {
27
+ if (event.defaultPrevented || event.button !== 0)
28
+ return;
29
+ if (event.metaKey || event.ctrlKey || event.shiftKey || event.altKey)
30
+ return;
31
+ const target = event.target instanceof Element ? event.target : null;
32
+ const anchor = target?.closest('a[href]');
33
+ if (!anchor || anchor.hasAttribute('download'))
34
+ return;
35
+ let url;
36
+ try {
37
+ url = new URL(anchor.href, location.href);
38
+ }
39
+ catch {
40
+ return;
41
+ }
42
+ if (!isExternal(url, anchor))
43
+ return;
44
+ event.preventDefault();
45
+ quietly(Browser.open({ url: url.href, toolbarColor: toolbarColor(), presentationStyle }));
46
+ };
47
+ document.addEventListener('click', onClick);
48
+ return () => document.removeEventListener('click', onClick);
49
+ }
@@ -0,0 +1,30 @@
1
+ import type { Toaster } from '@loidolt/theme-svelte';
2
+ import type { NetworkPlugin } from './types.js';
3
+ export interface NetworkStatusOptions {
4
+ /** `Network` from `@capacitor/network`. */
5
+ Network: NetworkPlugin;
6
+ /**
7
+ * Announce going offline and coming back through this toaster. The offline toast stays until
8
+ * the connection returns, then gives way to a brief "back online".
9
+ */
10
+ toaster?: Pick<Toaster, 'warning' | 'success' | 'dismiss'>;
11
+ /** Toast wording. */
12
+ labels?: {
13
+ offline?: string;
14
+ offlineDescription?: string;
15
+ online?: string;
16
+ };
17
+ }
18
+ export interface NetworkStatus {
19
+ /** Whether any connection is up. Reactive. */
20
+ readonly connected: boolean;
21
+ /** `wifi`, `cellular`, `none` or `unknown`. Reactive. */
22
+ readonly type: string;
23
+ destroy(): void;
24
+ }
25
+ /**
26
+ * Connectivity as reactive state. The native plugin knows sooner and better than
27
+ * `navigator.onLine`, which in a web view often reports `true` with no route out at all. Outside
28
+ * a native shell it follows `navigator.onLine` and the `online`/`offline` events instead.
29
+ */
30
+ export declare function createNetworkStatus(options: NetworkStatusOptions): NetworkStatus;
@@ -0,0 +1,66 @@
1
+ import { onDestroy } from 'svelte';
2
+ import { listen, nativePlatform } from './platform.js';
3
+ /**
4
+ * Connectivity as reactive state. The native plugin knows sooner and better than
5
+ * `navigator.onLine`, which in a web view often reports `true` with no route out at all. Outside
6
+ * a native shell it follows `navigator.onLine` and the `online`/`offline` events instead.
7
+ */
8
+ export function createNetworkStatus(options) {
9
+ const { Network, toaster, labels = {} } = options;
10
+ const { offline: offlineTitle = 'You are offline', offlineDescription = 'Changes will sync when the connection returns.', online: onlineTitle = 'Back online', } = labels;
11
+ const browser = typeof navigator !== 'undefined';
12
+ let connected = $state(browser ? navigator.onLine !== false : true);
13
+ let type = $state('unknown');
14
+ let offlineToast = null;
15
+ let teardown = () => { };
16
+ const update = (next, nextType) => {
17
+ type = nextType;
18
+ if (next === connected)
19
+ return;
20
+ connected = next;
21
+ if (!toaster)
22
+ return;
23
+ if (!next) {
24
+ offlineToast = toaster.warning(offlineTitle, {
25
+ description: offlineDescription,
26
+ duration: 0,
27
+ });
28
+ }
29
+ else {
30
+ if (offlineToast !== null)
31
+ toaster.dismiss(offlineToast);
32
+ offlineToast = null;
33
+ toaster.success(onlineTitle, { duration: 4000 });
34
+ }
35
+ };
36
+ if (nativePlatform()) {
37
+ Network.getStatus().then((status) => update(status.connected, status.connectionType), () => { });
38
+ teardown = listen(Network.addListener('networkStatusChange', (status) => update(status.connected, status.connectionType)));
39
+ }
40
+ else if (typeof window !== 'undefined') {
41
+ const online = () => update(true, 'unknown');
42
+ const offline = () => update(false, 'none');
43
+ window.addEventListener('online', online);
44
+ window.addEventListener('offline', offline);
45
+ teardown = () => {
46
+ window.removeEventListener('online', online);
47
+ window.removeEventListener('offline', offline);
48
+ };
49
+ }
50
+ const destroy = () => teardown();
51
+ try {
52
+ onDestroy(destroy);
53
+ }
54
+ catch {
55
+ /* module scope: the caller owns `destroy()` */
56
+ }
57
+ return {
58
+ get connected() {
59
+ return connected;
60
+ },
61
+ get type() {
62
+ return type;
63
+ },
64
+ destroy,
65
+ };
66
+ }
@@ -0,0 +1,28 @@
1
+ import type { PluginListenerHandle, Teardown } from './types.js';
2
+ export type NativePlatform = 'ios' | 'android';
3
+ export declare const noop: Teardown;
4
+ /**
5
+ * The native shell the page runs in, or `null` in a browser and on the server. Every adapter
6
+ * checks this first, so the same app code ships to the web untouched.
7
+ */
8
+ export declare function nativePlatform(): NativePlatform | null;
9
+ /** Whether the page runs inside a Capacitor iOS or Android shell. */
10
+ export declare const isNativePlatform: () => boolean;
11
+ /**
12
+ * Writes `data-native-platform="ios"` (or `"android"`) on `<html>`, which `styles.css` keys its
13
+ * native touch manners to and which your own CSS can use for a platform-specific tweak. Returns
14
+ * the teardown. A no-op in a browser.
15
+ */
16
+ export declare function markNativePlatform(element?: HTMLElement): Teardown;
17
+ /**
18
+ * Plugin calls are cosmetic here — a status bar tint, a buzz. A rejection (a plugin missing from
19
+ * the native project, a method one platform lacks) must never surface as an unhandled error.
20
+ */
21
+ export declare function quietly(result: unknown): void;
22
+ /**
23
+ * Turns `addListener`'s promised handle into a synchronous teardown. A teardown that runs before
24
+ * the handle arrives still removes the listener once it does.
25
+ */
26
+ export declare function listen(pending: Promise<PluginListenerHandle> | PluginListenerHandle): Teardown;
27
+ /** One teardown for several. */
28
+ export declare function combine(...teardowns: Array<Teardown | undefined>): Teardown;
@@ -0,0 +1,77 @@
1
+ import { Capacitor } from '@capacitor/core';
2
+ export const noop = () => { };
3
+ /**
4
+ * The native shell the page runs in, or `null` in a browser and on the server. Every adapter
5
+ * checks this first, so the same app code ships to the web untouched.
6
+ */
7
+ export function nativePlatform() {
8
+ if (typeof document === 'undefined')
9
+ return null;
10
+ try {
11
+ if (!Capacitor.isNativePlatform())
12
+ return null;
13
+ const platform = Capacitor.getPlatform();
14
+ return platform === 'ios' || platform === 'android' ? platform : null;
15
+ }
16
+ catch {
17
+ return null;
18
+ }
19
+ }
20
+ /** Whether the page runs inside a Capacitor iOS or Android shell. */
21
+ export const isNativePlatform = () => nativePlatform() !== null;
22
+ /**
23
+ * Writes `data-native-platform="ios"` (or `"android"`) on `<html>`, which `styles.css` keys its
24
+ * native touch manners to and which your own CSS can use for a platform-specific tweak. Returns
25
+ * the teardown. A no-op in a browser.
26
+ */
27
+ export function markNativePlatform(element) {
28
+ const platform = nativePlatform();
29
+ const root = element ?? (typeof document === 'undefined' ? null : document.documentElement);
30
+ if (!platform || !root)
31
+ return noop;
32
+ root.dataset.nativePlatform = platform;
33
+ return () => {
34
+ delete root.dataset.nativePlatform;
35
+ };
36
+ }
37
+ /**
38
+ * Plugin calls are cosmetic here — a status bar tint, a buzz. A rejection (a plugin missing from
39
+ * the native project, a method one platform lacks) must never surface as an unhandled error.
40
+ */
41
+ export function quietly(result) {
42
+ if (result && typeof result.catch === 'function') {
43
+ result.catch(() => { });
44
+ }
45
+ }
46
+ /**
47
+ * Turns `addListener`'s promised handle into a synchronous teardown. A teardown that runs before
48
+ * the handle arrives still removes the listener once it does.
49
+ */
50
+ export function listen(pending) {
51
+ let removed = false;
52
+ let handle;
53
+ Promise.resolve(pending).then((resolved) => {
54
+ if (removed)
55
+ quietly(resolved.remove());
56
+ else
57
+ handle = resolved;
58
+ }, () => { });
59
+ return () => {
60
+ if (removed)
61
+ return;
62
+ removed = true;
63
+ if (handle)
64
+ quietly(handle.remove());
65
+ };
66
+ }
67
+ /** One teardown for several. */
68
+ export function combine(...teardowns) {
69
+ let done = false;
70
+ return () => {
71
+ if (done)
72
+ return;
73
+ done = true;
74
+ for (const teardown of teardowns)
75
+ teardown?.();
76
+ };
77
+ }