@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.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Chris Loidolt
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,290 @@
1
- # Temporary Holding Version
1
+ # @loidolt/theme-capacitor
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ [Capacitor](https://capacitorjs.com) adapters that carry the Loidolt theme into native iOS and
4
+ Android apps. The components already render well on a phone; these make them behave like the
5
+ platform around them.
6
+
7
+ - **The chrome matches the theme.** Status bar and navigation bar icons turn light on a dark
8
+ surface and dark on a light one, read from the live colours, so a preset or your own theme
9
+ decides them. The iOS keyboard takes the page's appearance.
10
+ - **Safe areas on every web view.** Android web views before Chromium 140 report
11
+ `env(safe-area-inset-*)` as 0; the stylesheet feeds the theme's `--ldt-safe-*` knobs from the
12
+ values Capacitor injects instead, so `Topbar`, `AppShell`, `TabBar`, `Drawer` and toasts clear
13
+ the bars on both platforms.
14
+ - **Back closes what is open.** The Android back button closes the open dialog, drawer, lightbox
15
+ or menu first, then goes back through history, then backgrounds the app.
16
+ - **The keyboard is part of the layout.** `TabBar` steps aside while typing, the focused field is
17
+ kept in view, and when the keyboard overlays the page the bottom chrome lifts above it.
18
+ - **Haptics in the theme's vocabulary.** Switches, checkboxes, tabs and the tab bar tick; status
19
+ toasts get the matching success, warning or error pattern.
20
+ - **Native storage, native links, native text size.** The theme choice survives iOS evicting
21
+ `localStorage`; links that leave the app open in the in-app browser in the theme's colour; text
22
+ follows Dynamic Type and Android's font scale; copy buttons work on Android.
23
+ - **Share like a native app.** Files, links and text go to the native share sheet, then the
24
+ browser's, then a download or the clipboard — one call, whichever shell it runs in.
25
+ - **Open and save files like a native app.** The system file picker, and saving to the
26
+ device's Documents, with a file input and a download in the browser — `File`s either way.
27
+ - **Inert on the web.** Every adapter checks for a native shell first, so the same root layout
28
+ ships to the browser and to the server unchanged.
29
+
30
+ Plugins are passed in, never imported: install only the ones you want, and each adapter turns on
31
+ when you hand it its plugin. Their typings are checked against the real plugins in this
32
+ repository's test suite.
33
+
34
+ ## Install
35
+
36
+ ```sh
37
+ npm install @loidolt/theme-capacitor @capacitor/core
38
+ ```
39
+
40
+ `@capacitor/core` 8 is a peer dependency. Add whichever plugins you want adapters for:
41
+
42
+ ```sh
43
+ npm install @capacitor/app @capacitor/keyboard @capacitor/haptics @capacitor/preferences @capacitor/splash-screen
44
+ ```
45
+
46
+ | Plugin | Turns on |
47
+ | ----------------------------------- | ------------------------------------------------------------------------ |
48
+ | `@capacitor/core` | Status and navigation bar styling (`SystemBars` is bundled in core) |
49
+ | `@capacitor/app` | Android back button, foreground/background, deep links, text-size resume |
50
+ | `@capacitor/keyboard` | Keyboard tracking and layout, keyboard appearance |
51
+ | `@capacitor/haptics` | Haptics on controls and status toasts |
52
+ | `@capacitor/preferences` | Native persistence for the theme and preset |
53
+ | `@capacitor/splash-screen` | Lifting the splash once the theme and fonts are in |
54
+ | `@capacitor/network` | Reactive connectivity, with offline and back-online toasts |
55
+ | `@capacitor/browser` | External links in the in-app browser |
56
+ | `@capacitor/text-zoom` | Following the system text size |
57
+ | `@capacitor/clipboard` | Copy buttons on Android |
58
+ | `@capacitor/share` | The native share sheet |
59
+ | `@capawesome/capacitor-file-picker` | The native file picker |
60
+ | `@capacitor/filesystem` | Saving files to the device, and sharing a `File` or Blob natively |
61
+ | `@capacitor/status-bar` | Only for Android apps that opt out of edge-to-edge |
62
+
63
+ ## Set up
64
+
65
+ Three pieces: the Capacitor config, the viewport, and one call in the root layout.
66
+
67
+ **1. `capacitor.config.ts`** — the launch background in the theme's colour (no white flash), the
68
+ safe-area variables on, and a splash screen that waits for the theme:
69
+
70
+ ```ts
71
+ import type { CapacitorConfig } from '@capacitor/cli';
72
+ import { withTheme } from '@loidolt/theme-capacitor/config';
73
+
74
+ export default withTheme<CapacitorConfig>({
75
+ appId: 'space.loidolt.topostack',
76
+ appName: 'Topostack',
77
+ webDir: 'build',
78
+ });
79
+ ```
80
+
81
+ Everything you set wins over the theme's defaults, down to single plugin options. `withTheme(config,
82
+ { scheme: 'dark' })` paints the launch dark; `themeConfig()` returns the defaults on their own.
83
+
84
+ The splash screen shows the native launch screen, and its colour is the one thing the config
85
+ cannot set: `SplashScreen`'s `backgroundColor` would paint one fixed colour over it, so the
86
+ theme leaves it out. Give the launch screen the theme's background instead, so it follows the
87
+ system's dark mode:
88
+
89
+ - **iOS**: Capacitor's template fills `LaunchScreen.storyboard` with a white `Splash` image.
90
+ Replace the image view with a plain view whose background is a colour asset (for example
91
+ `LaunchBackground` in `Assets.xcassets`) with the light `background` (`#ebe7dc`) for Any and the
92
+ dark one (`#161814`) for Dark. `examples/capacitor` in this repository does exactly that.
93
+ - **Android**: set `windowSplashScreenBackground` in `values/styles.xml` and `values-night/styles.xml`
94
+ to the same two colours.
95
+
96
+ iOS cannot know the in-app choice before the app runs, so someone who picked dark on a light
97
+ phone sees the light launch colour for a moment, then the dark app — never white.
98
+
99
+ **2. `app.html`** — draw under the bars, and import the stylesheet after the theme's:
100
+
101
+ ```html
102
+ <meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover" />
103
+ ```
104
+
105
+ ```css
106
+ @import '@loidolt/theme-svelte/styles.css';
107
+ @import '@loidolt/theme-capacitor/styles.css';
108
+ ```
109
+
110
+ **3. The root layout:**
111
+
112
+ ```svelte
113
+ <script lang="ts">
114
+ import { App } from '@capacitor/app';
115
+ import { Haptics } from '@capacitor/haptics';
116
+ import { Keyboard } from '@capacitor/keyboard';
117
+ import { Preferences } from '@capacitor/preferences';
118
+ import { SplashScreen } from '@capacitor/splash-screen';
119
+ import { goto } from '$app/navigation';
120
+ import { setupCapacitor } from '@loidolt/theme-capacitor';
121
+ import { theme, toaster } from '$lib/app';
122
+
123
+ const native = setupCapacitor({
124
+ plugins: { App, Haptics, Keyboard, Preferences, SplashScreen },
125
+ theme, // createTheme(): stored natively, restored before the splash lifts
126
+ toaster, // createToaster(): status toasts buzz; use native.toaster to push
127
+ navigate: goto, // deep links
128
+ });
129
+
130
+ let { children } = $props();
131
+ </script>
132
+
133
+ {@render children()}
134
+ ```
135
+
136
+ Any adapter can be switched off (`backButton: false`) or tuned (`backButton: { atRoot: 'exit' }`).
137
+ `native.keyboard`, `native.network` and `native.lifecycle` are reactive state for your own markup,
138
+ and `native.ready` settles once the theme is restored and the splash is gone.
139
+
140
+ ## Adapters
141
+
142
+ Each piece is also exported on its own, for apps that want only one or wire them differently.
143
+ Every one returns a teardown (or a store with `destroy()`), and is a no-op outside a native shell.
144
+
145
+ | Export | Does |
146
+ | ---------------------- | ----------------------------------------------------------------------------------------------------------------------------- |
147
+ | `syncNativeAppearance` | Bar icon styles from the `surface` role (configurable per bar), legacy Android status bar colour, iOS keyboard appearance |
148
+ | `handleBackButton` | Android back: closes the top layer, then `onBack`, then history, then `atRoot` (`minimize`, `exit`, `none`) |
149
+ | `closeTopLayer` | Closes the innermost open overlay the way Escape does; returns whether something took it |
150
+ | `createNativeKeyboard` | `visible` and `height`, `data-keyboard="open"`, `--ldt-keyboard-height` and `--ldt-keyboard-inset` on `<html>` |
151
+ | `createHaptics` | `impact(weight)`, `selection()`, `notify(variant)`, and `install()` for delegated feedback on controls |
152
+ | `withHaptics` | Wraps a toaster so status toasts play the matching notification pattern |
153
+ | `persistTheme` | Restores and mirrors a `createTheme` store through `Preferences`; `ready` settles once restored |
154
+ | `createAppLifecycle` | Reactive `active`; pauses playing media in the background; `onPause` and `onResume` |
155
+ | `handleDeepLinks` | Universal links, app links and custom schemes into the app router (`deepLinkPath` maps the URL) |
156
+ | `createNetworkStatus` | Reactive `connected` and `type`; optional offline and back-online toasts |
157
+ | `openExternalLinks` | Other-origin links open in the in-app browser with a themed toolbar |
158
+ | `hideSplashScreen` | Lifts the splash after `until`, the fonts and a painted frame; no fade under reduced motion |
159
+ | `followSystemTextSize` | Applies the system text size, and re-reads it on resume; on iOS also `--ldt-text-zoom` on `<html>` |
160
+ | `bridgeClipboard` | Routes `navigator.clipboard.writeText` through the Clipboard plugin |
161
+ | `createShare` | `share(content)` through the native sheet, the Web Share API, then a download or the clipboard; `canShare(content?)` |
162
+ | `createFiles` | `pick({ accept, multiple })` resolves `File`s from the native picker or a file input; `save(file)` to Documents or a download |
163
+ | `markNativePlatform` | `data-native-platform="ios"` or `"android"` on `<html>`, for platform-specific CSS |
164
+ | `nativePlatform` | `'ios'`, `'android'` or `null` |
165
+
166
+ ### Back button and overlays
167
+
168
+ `closeTopLayer` sends Escape from the focused element, which every overlay in
169
+ `@loidolt/theme-svelte` — and any Bits UI layer — already closes on. An open layer that refuses
170
+ Escape (a confirmation that must be answered) also stops the back press, so it is never skipped
171
+ past to the page behind. For a surface of your own built with the `escapeKey` attachment, pass
172
+ `preventDefault: true` so the back button can tell it handled the press.
173
+
174
+ ### Keyboard
175
+
176
+ With the default `native` resize mode the web view shrinks for the keyboard and nothing else is
177
+ needed. With `keyboardResize: 'none'` the keyboard draws over the page, and `--ldt-keyboard-inset`
178
+ becomes the bottom safe area, so `AppShell`'s last row, toasts, floating bars and drawers lift
179
+ above it. `--ldt-keyboard-height` is there for anything of your own.
180
+
181
+ ### Haptics
182
+
183
+ `install()` ticks on activation of switches, checkboxes, radios, tabs, toggle buttons, options
184
+ and `TabBar` links — the moments a native control ticks. Plain buttons are left alone on purpose;
185
+ opt one in with `data-haptic` (`data-haptic="medium"` or `"heavy"` for weight). Pass
186
+ `enabled: () => settings.vibration` to honour an in-app setting.
187
+
188
+ ### Sharing
189
+
190
+ `setupCapacitor` returns `native.share`, which works without any plugin: in a browser it is the
191
+ Web Share API, then a fallback. Pass `Share` (and `Filesystem`, to share files) for the native
192
+ sheet in the app:
193
+
194
+ ```ts
195
+ import { Filesystem } from '@capacitor/filesystem';
196
+ import { Share } from '@capacitor/share';
197
+
198
+ const native = setupCapacitor({ plugins: { Share, Filesystem /* … */ }, toaster });
199
+
200
+ const { method, cancelled } = await native.share!.share({
201
+ title: 'Export',
202
+ files: [new File([bytes], 'export.pdf', { type: 'application/pdf' })],
203
+ });
204
+ ```
205
+
206
+ Or on its own: `createShare({ Share, Filesystem, toaster })`. `share(content)` takes any of
207
+ `title`, `text`, `url`, `files` and Android's `dialogTitle`, and tries in turn:
208
+
209
+ 1. **The native share sheet**, in an iOS or Android shell with `Share`. A `File` or a Blob
210
+ (`{ blob, name }`) is written to the cache directory with `Filesystem` first, since the sheet
211
+ only takes file URIs, and the cache is the folder Android shares without extra FileProvider
212
+ paths. The previous share's files are cleared at the start of the next one rather than right
213
+ away, because a receiving app may still be reading them when the sheet closes. A file already
214
+ on the device can be passed as `{ uri }`.
215
+ 2. **The Web Share API**, checked with `navigator.canShare({ files })` for files.
216
+ 3. **A fallback.** Files download (an object URL on a temporary `<a download>`, revoked after).
217
+ A link or text goes to the clipboard — the URL when there is one, otherwise the text — with a
218
+ `copiedLabel` toast (`'Link copied'`) when a toaster is given. `fallback: 'open'` opens the URL
219
+ in a new tab instead; `fallback: false` does nothing.
220
+
221
+ It resolves `{ method, cancelled, activityType? }`: `method` is `'native'`, `'web'`,
222
+ `'download'`, `'clipboard'`, `'open'` or `'none'`. Closing the sheet is `cancelled: true`, never
223
+ a rejection; only a real failure rejects. `canShare(content?)` says whether a share sheet would
224
+ open, to label a button "Share" or "Download". On the server both are no-ops.
225
+
226
+ Files cross the native bridge as base64, so keep them to what fits in memory (Android may need
227
+ `android:largeHeap="true"` for very large ones). `@capacitor/filesystem` needs a privacy
228
+ manifest entry on iOS; see its README.
229
+
230
+ ### Files
231
+
232
+ `setupCapacitor` returns `native.files`, which works without any plugin: in a browser it opens a
233
+ file input and downloads. Pass `FilePicker` from
234
+ [`@capawesome/capacitor-file-picker`](https://capawesome.io/plugins/file-picker/) (Capacitor has
235
+ no official picker) and `Filesystem` for the native versions:
236
+
237
+ ```ts
238
+ import { FilePicker } from '@capawesome/capacitor-file-picker';
239
+ import { Filesystem } from '@capacitor/filesystem';
240
+
241
+ const native = setupCapacitor({ plugins: { FilePicker, Filesystem /* … */ } });
242
+
243
+ const picked = await native.files!.pick({ accept: '.pdf,application/pdf', multiple: true });
244
+ await upload(picked); // the same File[] a FileInput's onFiles gives you, as an array
245
+
246
+ const saved = await native.files!.save(new File([bytes], 'export.pdf'));
247
+ ```
248
+
249
+ Or on its own: `createFiles({ FilePicker, Filesystem, directory })`.
250
+
251
+ **`pick({ accept, multiple })`** resolves `File` objects either way, so the code that handles a
252
+ `FileInput`'s or a drop zone's files handles these too. `accept` is written as for
253
+ `<input accept>` (MIME types, `image/*`, `.pdf`); the native pickers filter by MIME type, so
254
+ extensions are mapped through `EXTENSION_TYPES` (`acceptToMimeTypes` does it), and an extension
255
+ it does not know turns the filter off rather than make the file unpickable — like the attribute,
256
+ it is a hint, not a check. Dismissing the picker resolves `[]`. Picking needs no permission: the
257
+ system draws the picker. Natively each file is read into memory through its web view URL; on
258
+ iOS the picker first copies it into the app's cache, and with `Filesystem` passed `pick` deletes
259
+ that copy once it is read (only paths inside the cache, and a failed delete never fails the pick);
260
+ in a browser the hidden file input must be opened from a click or key handler, like any file input,
261
+ and resolves `[]` on its `cancel` event.
262
+
263
+ **`save(file, { folder, overwrite })`** writes a `File` or `{ blob, name }` with `Filesystem` and
264
+ resolves `{ method: 'filesystem', uri, path, directory }`; in a browser it downloads and resolves
265
+ `{ method: 'download', name }`. A taken name becomes `name (1).ext` unless `overwrite: true`.
266
+ The default directory is `DOCUMENTS`:
267
+
268
+ - **iOS**: the app's Documents folder. It appears in the Files app under the app's name once
269
+ `Info.plist` sets `UIFileSharingEnabled` and `LSSupportsOpeningDocumentsInPlace` to `YES`.
270
+ - **Android**: the shared Documents folder, which every file manager shows. Android 11 and newer
271
+ need no permission for files the app creates there. Android 10 and older need storage access:
272
+ `save` checks and requests it, and rejects with `FilePermissionError` if the user refuses (add
273
+ `WRITE_EXTERNAL_STORAGE` to the manifest, and `requestLegacyExternalStorage` for Android 10).
274
+
275
+ Pass `directory: 'DATA'` (or any `Directory` value) to keep files private to the app instead.
276
+ Files cross the native bridge as base64, so keep them to what fits in memory. Write failures
277
+ reject with the plugin's error; on the server `pick` resolves `[]` and `save` `{ method: 'none' }`.
278
+
279
+ ### Styles
280
+
281
+ `styles.css` is zero-specificity throughout, so your own CSS always wins, and inert in a browser:
282
+
283
+ - `--ldt-safe-*` from Capacitor's injected `--safe-area-inset-*`, then `env()`.
284
+ - Under `data-native-platform`: a fixed strip as tall as the top safe area, in `surface`, so the
285
+ page never scrolls under the clock or the Dynamic Island once `Topbar` has scrolled away.
286
+ Override `body::before` to restyle or remove it.
287
+ - While the keyboard is up: the bottom safe area becomes `--ldt-keyboard-inset`, and `TabBar` is
288
+ hidden.
289
+ - Under `data-native-platform`: no tap highlight, long-pressing a control does not select its
290
+ label or open the link callout, and a double tap does not zoom the page (pinch zoom stays).
@@ -0,0 +1,50 @@
1
+ import { type SemanticRole } from '@loidolt/theme-tokens';
2
+ import type { KeyboardStylePlugin, StatusBarPlugin, SystemBarsPlugin, Teardown } from './types.js';
3
+ /**
4
+ * Capacitor's name for the icon colour of a system bar. Note the inversion: `DARK` is the style
5
+ * for a dark bar, so its icons are light.
6
+ */
7
+ export type SystemBarStyle = 'DARK' | 'LIGHT';
8
+ /**
9
+ * The bar style that keeps the status icons readable over `color`: whichever of black or white
10
+ * ink has the higher contrast against it. Accepts `#rrggbb` (an alpha suffix is ignored).
11
+ */
12
+ export declare function systemBarStyleFor(color: string): SystemBarStyle;
13
+ export interface NativeAppearanceOptions {
14
+ /**
15
+ * The colour role painted under the status bar. Defaults to `surface`, which is what `Topbar`
16
+ * draws there; use `background` for a page with no top bar.
17
+ */
18
+ statusBarRole?: SemanticRole;
19
+ /**
20
+ * The colour role painted under the Android navigation bar and the iOS home indicator.
21
+ * Defaults to `surface`, which is what `TabBar` draws there.
22
+ */
23
+ navigationBarRole?: SemanticRole;
24
+ /** Where the theme is read from. Defaults to `<html>`. */
25
+ element?: () => Element | null | undefined;
26
+ /** Defaults to the `SystemBars` plugin bundled with `@capacitor/core`. */
27
+ SystemBars?: SystemBarsPlugin;
28
+ /**
29
+ * `@capacitor/status-bar`, for an Android app that has opted out of edge-to-edge: the status
30
+ * bar is then a separate native strip, and this paints it the `statusBarRole` colour. Leave it
31
+ * out for edge-to-edge apps, where the page itself draws under the bar.
32
+ */
33
+ StatusBar?: StatusBarPlugin;
34
+ /** `@capacitor/keyboard`, to give the iOS keyboard the dark or light appearance of the page. */
35
+ Keyboard?: KeyboardStylePlugin;
36
+ }
37
+ /**
38
+ * Keeps the native chrome in step with the page theme: status and navigation bar icons light on a
39
+ * dark surface and dark on a light one, and the iOS keyboard in the matching appearance. It reads
40
+ * the live colours, so a preset, a scoped override or an app's own theme decides the icons, and it
41
+ * follows every theme change `createTheme` (or anything else) makes.
42
+ *
43
+ * ```ts
44
+ * import { Keyboard } from '@capacitor/keyboard';
45
+ * syncNativeAppearance({ Keyboard });
46
+ * ```
47
+ *
48
+ * Returns the teardown. A no-op outside a native shell.
49
+ */
50
+ export declare function syncNativeAppearance(options?: NativeAppearanceOptions): Teardown;
@@ -0,0 +1,70 @@
1
+ import { SystemBars } from '@capacitor/core';
2
+ import { colorSchemeOf, observeColorScheme, readRoleColor } from '@loidolt/theme-svelte';
3
+ import { getContrastRatio, resolveRoles } from '@loidolt/theme-tokens';
4
+ import { nativePlatform, noop, quietly } from './platform.js';
5
+ /**
6
+ * The bar style that keeps the status icons readable over `color`: whichever of black or white
7
+ * ink has the higher contrast against it. Accepts `#rrggbb` (an alpha suffix is ignored).
8
+ */
9
+ export function systemBarStyleFor(color) {
10
+ const opaque = color.slice(0, 7);
11
+ return getContrastRatio('#000000', opaque) >= getContrastRatio('#ffffff', opaque)
12
+ ? 'LIGHT'
13
+ : 'DARK';
14
+ }
15
+ /**
16
+ * Keeps the native chrome in step with the page theme: status and navigation bar icons light on a
17
+ * dark surface and dark on a light one, and the iOS keyboard in the matching appearance. It reads
18
+ * the live colours, so a preset, a scoped override or an app's own theme decides the icons, and it
19
+ * follows every theme change `createTheme` (or anything else) makes.
20
+ *
21
+ * ```ts
22
+ * import { Keyboard } from '@capacitor/keyboard';
23
+ * syncNativeAppearance({ Keyboard });
24
+ * ```
25
+ *
26
+ * Returns the teardown. A no-op outside a native shell.
27
+ */
28
+ export function syncNativeAppearance(options = {}) {
29
+ const platform = nativePlatform();
30
+ if (!platform)
31
+ return noop;
32
+ const { statusBarRole = 'surface', navigationBarRole = 'surface', SystemBars: systemBars = SystemBars, StatusBar, Keyboard, } = options;
33
+ const target = () => options.element?.() ?? document.documentElement;
34
+ const colorOf = (element, role) => readRoleColor(element, role) ?? resolveRoles({ role }, colorSchemeOf(element)).role;
35
+ // Only what changed is sent: every theme mutation lands here, most of them irrelevant.
36
+ const last = {};
37
+ const changed = (key, value) => {
38
+ if (last[key] === value)
39
+ return false;
40
+ last[key] = value;
41
+ return true;
42
+ };
43
+ const apply = () => {
44
+ const element = target();
45
+ if (!element)
46
+ return;
47
+ const statusColor = colorOf(element, statusBarRole);
48
+ const status = systemBarStyleFor(statusColor);
49
+ const navigation = systemBarStyleFor(colorOf(element, navigationBarRole));
50
+ const scheme = colorSchemeOf(element);
51
+ if (changed('status', status))
52
+ quietly(systemBars.setStyle({ style: status, bar: 'StatusBar' }));
53
+ if (changed('navigation', navigation)) {
54
+ quietly(systemBars.setStyle({ style: navigation, bar: 'NavigationBar' }));
55
+ }
56
+ if (StatusBar) {
57
+ if (changed('legacy', status))
58
+ quietly(StatusBar.setStyle({ style: status }));
59
+ // iOS has no status bar background to paint; the page shows through.
60
+ if (platform === 'android' && changed('legacyColor', statusColor)) {
61
+ quietly(StatusBar.setBackgroundColor({ color: statusColor.slice(0, 7) }));
62
+ }
63
+ }
64
+ if (Keyboard && changed('keyboard', scheme)) {
65
+ quietly(Keyboard.setStyle({ style: scheme === 'dark' ? 'DARK' : 'LIGHT' }));
66
+ }
67
+ };
68
+ apply();
69
+ return observeColorScheme(apply);
70
+ }
@@ -0,0 +1,41 @@
1
+ import type { BackButtonPlugin, Teardown } from './types.js';
2
+ /**
3
+ * Closes the innermost open layer — a dialog, drawer, lightbox, menu, popover or listbox — the
4
+ * way Escape would, because that is exactly what it does: it sends Escape from the focused
5
+ * element, where every overlay in `@loidolt/theme-svelte` (and any Bits UI layer, and any
6
+ * `escapeKey(…, { preventDefault: true })` surface) already listens. Returns whether something
7
+ * took it.
8
+ */
9
+ export declare function closeTopLayer(doc?: Document): boolean;
10
+ export interface BackButtonEvent {
11
+ /** Whether the web view has history to go back through. */
12
+ canGoBack: boolean;
13
+ }
14
+ export interface BackButtonOptions {
15
+ /** `App` from `@capacitor/app`. */
16
+ App: BackButtonPlugin;
17
+ /**
18
+ * Runs when no overlay took the press, before history. Return `true` once you have handled it
19
+ * — a wizard stepping back, an editor asking to discard — and nothing else happens.
20
+ */
21
+ onBack?: (event: BackButtonEvent) => boolean | void;
22
+ /**
23
+ * What the back press does at the start of history. `minimize` (the default) backgrounds the
24
+ * app with its state intact, as Android's own apps do; `exit` finishes it; `none` ignores it.
25
+ */
26
+ atRoot?: 'minimize' | 'exit' | 'none';
27
+ }
28
+ /**
29
+ * The Android back button (and back gesture), handled the way a native app does: it closes the
30
+ * open dialog, drawer or menu first, then goes back through history, then leaves the app.
31
+ *
32
+ * Without this, Capacitor's default navigates the web view back even with a dialog open, which
33
+ * strands the overlay over the previous page. iOS has no back button, so it is a no-op there and
34
+ * on the web.
35
+ *
36
+ * ```ts
37
+ * import { App } from '@capacitor/app';
38
+ * handleBackButton({ App });
39
+ * ```
40
+ */
41
+ export declare function handleBackButton(options: BackButtonOptions): Teardown;
@@ -0,0 +1,56 @@
1
+ import { nativePlatform, listen, noop, quietly } from './platform.js';
2
+ // Bits UI keeps every open dismissible layer here (dialogs, drawers, menus, popovers, selects).
3
+ const openLayers = () => globalThis.bitsEscapeLayers?.size ?? 0;
4
+ /**
5
+ * Closes the innermost open layer — a dialog, drawer, lightbox, menu, popover or listbox — the
6
+ * way Escape would, because that is exactly what it does: it sends Escape from the focused
7
+ * element, where every overlay in `@loidolt/theme-svelte` (and any Bits UI layer, and any
8
+ * `escapeKey(…, { preventDefault: true })` surface) already listens. Returns whether something
9
+ * took it.
10
+ */
11
+ export function closeTopLayer(doc = document) {
12
+ const layered = openLayers() > 0;
13
+ const event = new KeyboardEvent('keydown', {
14
+ key: 'Escape',
15
+ code: 'Escape',
16
+ bubbles: true,
17
+ cancelable: true,
18
+ composed: true,
19
+ });
20
+ (doc.activeElement ?? doc.body ?? doc.documentElement).dispatchEvent(event);
21
+ // An open Bits layer counts even if it ignored the key: one that refuses Escape (a required
22
+ // confirmation) must not be skipped past to the page behind it.
23
+ return layered || event.defaultPrevented;
24
+ }
25
+ /**
26
+ * The Android back button (and back gesture), handled the way a native app does: it closes the
27
+ * open dialog, drawer or menu first, then goes back through history, then leaves the app.
28
+ *
29
+ * Without this, Capacitor's default navigates the web view back even with a dialog open, which
30
+ * strands the overlay over the previous page. iOS has no back button, so it is a no-op there and
31
+ * on the web.
32
+ *
33
+ * ```ts
34
+ * import { App } from '@capacitor/app';
35
+ * handleBackButton({ App });
36
+ * ```
37
+ */
38
+ export function handleBackButton(options) {
39
+ if (nativePlatform() !== 'android')
40
+ return noop;
41
+ const { App, onBack, atRoot = 'minimize' } = options;
42
+ return listen(App.addListener('backButton', (event) => {
43
+ if (closeTopLayer())
44
+ return;
45
+ if (onBack?.(event) === true)
46
+ return;
47
+ if (event.canGoBack) {
48
+ history.back();
49
+ return;
50
+ }
51
+ if (atRoot === 'minimize')
52
+ quietly(App.minimizeApp());
53
+ else if (atRoot === 'exit')
54
+ quietly(App.exitApp());
55
+ }));
56
+ }
package/dist/blob.d.ts ADDED
@@ -0,0 +1,18 @@
1
+ /** How long a download's object URL is kept: long enough for every browser to start reading it. */
2
+ export declare const REVOKE_AFTER = 40000;
3
+ /**
4
+ * Starts a browser download of `blob` as `name`: an object URL on a temporary `<a download>`,
5
+ * revoked once the browser has had time to read it. Returns whether a download was started —
6
+ * `false` without a DOM.
7
+ */
8
+ export declare function downloadBlob(blob: Blob, name: string): boolean;
9
+ /**
10
+ * The Blob as base64, without the `data:` prefix — what `Filesystem.writeFile` takes on iOS and
11
+ * Android, where it cannot read a Blob itself.
12
+ */
13
+ export declare function blobToBase64(blob: Blob): Promise<string>;
14
+ /**
15
+ * A file name that is safe as the last segment of a path: no separators, no leading dots, no
16
+ * control characters. Falls back to `fallback` when nothing is left.
17
+ */
18
+ export declare function safeFileName(name: string, fallback?: string): string;
package/dist/blob.js ADDED
@@ -0,0 +1,57 @@
1
+ /*
2
+ * Browser plumbing shared by sharing and saving files: handing a Blob to the native bridge, and
3
+ * the download a browser falls back to.
4
+ */
5
+ /** How long a download's object URL is kept: long enough for every browser to start reading it. */
6
+ export const REVOKE_AFTER = 40_000;
7
+ /**
8
+ * Starts a browser download of `blob` as `name`: an object URL on a temporary `<a download>`,
9
+ * revoked once the browser has had time to read it. Returns whether a download was started —
10
+ * `false` without a DOM.
11
+ */
12
+ export function downloadBlob(blob, name) {
13
+ if (typeof document === 'undefined' || typeof URL.createObjectURL !== 'function')
14
+ return false;
15
+ const href = URL.createObjectURL(blob);
16
+ const anchor = document.createElement('a');
17
+ anchor.href = href;
18
+ anchor.download = name;
19
+ anchor.rel = 'noopener';
20
+ anchor.hidden = true;
21
+ document.body.append(anchor);
22
+ try {
23
+ anchor.click();
24
+ }
25
+ finally {
26
+ anchor.remove();
27
+ setTimeout(() => URL.revokeObjectURL(href), REVOKE_AFTER);
28
+ }
29
+ return true;
30
+ }
31
+ /**
32
+ * The Blob as base64, without the `data:` prefix — what `Filesystem.writeFile` takes on iOS and
33
+ * Android, where it cannot read a Blob itself.
34
+ */
35
+ export function blobToBase64(blob) {
36
+ return new Promise((resolve, reject) => {
37
+ const reader = new FileReader();
38
+ reader.onload = () => {
39
+ const url = String(reader.result);
40
+ resolve(url.slice(url.indexOf(',') + 1));
41
+ };
42
+ reader.onerror = () => reject(reader.error ?? new Error('Could not read the file'));
43
+ reader.readAsDataURL(blob);
44
+ });
45
+ }
46
+ /**
47
+ * A file name that is safe as the last segment of a path: no separators, no leading dots, no
48
+ * control characters. Falls back to `fallback` when nothing is left.
49
+ */
50
+ export function safeFileName(name, fallback = 'file') {
51
+ const cleaned = name
52
+ // eslint-disable-next-line no-control-regex
53
+ .replace(/[\u0000-\u001f\u007f/\\:*?"<>|]+/g, '-')
54
+ .replace(/^[.\s]+/, '')
55
+ .trim();
56
+ return cleaned || fallback;
57
+ }