@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 +21 -0
- package/README.md +289 -2
- package/dist/appearance.d.ts +50 -0
- package/dist/appearance.js +70 -0
- package/dist/back-button.d.ts +41 -0
- package/dist/back-button.js +56 -0
- package/dist/blob.d.ts +18 -0
- package/dist/blob.js +57 -0
- package/dist/config/index.d.ts +67 -0
- package/dist/config/index.js +62 -0
- package/dist/deep-links.d.ts +17 -0
- package/dist/deep-links.js +29 -0
- package/dist/files.d.ts +101 -0
- package/dist/files.js +259 -0
- package/dist/haptics.d.ts +57 -0
- package/dist/haptics.js +110 -0
- package/dist/index.d.ts +29 -0
- package/dist/index.js +14 -0
- package/dist/keyboard.svelte.d.ts +36 -0
- package/dist/keyboard.svelte.js +75 -0
- package/dist/lifecycle.svelte.d.ts +25 -0
- package/dist/lifecycle.svelte.js +49 -0
- package/dist/links.d.ts +28 -0
- package/dist/links.js +49 -0
- package/dist/network.svelte.d.ts +30 -0
- package/dist/network.svelte.js +66 -0
- package/dist/platform.d.ts +28 -0
- package/dist/platform.js +77 -0
- package/dist/setup.d.ts +105 -0
- package/dist/setup.js +112 -0
- package/dist/share.d.ts +89 -0
- package/dist/share.js +171 -0
- package/dist/styles.css +76 -0
- package/dist/system.d.ts +49 -0
- package/dist/system.js +107 -0
- package/dist/theme-storage.svelte.d.ts +33 -0
- package/dist/theme-storage.svelte.js +59 -0
- package/dist/types.d.ts +207 -0
- package/dist/types.js +7 -0
- package/package.json +133 -4
|
@@ -0,0 +1,67 @@
|
|
|
1
|
+
export interface ThemeConfigOptions {
|
|
2
|
+
/**
|
|
3
|
+
* Which reference theme the launch is painted in: the colour behind the web view before its
|
|
4
|
+
* first frame. Match the theme most people will see — `light` (the default) for a light-first
|
|
5
|
+
* app. The splash screen itself is the native launch screen's (see the README).
|
|
6
|
+
*/
|
|
7
|
+
scheme?: 'light' | 'dark';
|
|
8
|
+
/** A colour of your own instead of the theme's `background`. */
|
|
9
|
+
backgroundColor?: string;
|
|
10
|
+
/**
|
|
11
|
+
* How the web view makes room for the keyboard. `native` (the default) shrinks it, which the
|
|
12
|
+
* theme handles with no further help; `none` overlays the page, and `createNativeKeyboard` then
|
|
13
|
+
* lifts the bottom chrome by the keyboard's height.
|
|
14
|
+
*/
|
|
15
|
+
keyboardResize?: 'native' | 'body' | 'ionic' | 'none';
|
|
16
|
+
}
|
|
17
|
+
/** The slice of `CapacitorConfig` this touches — structurally, so `@capacitor/cli` is not needed. */
|
|
18
|
+
export interface ThemeConfig {
|
|
19
|
+
backgroundColor: string;
|
|
20
|
+
ios: {
|
|
21
|
+
backgroundColor: string;
|
|
22
|
+
};
|
|
23
|
+
android: {
|
|
24
|
+
backgroundColor: string;
|
|
25
|
+
};
|
|
26
|
+
plugins: {
|
|
27
|
+
SystemBars: {
|
|
28
|
+
insetsHandling: 'css';
|
|
29
|
+
};
|
|
30
|
+
SplashScreen: {
|
|
31
|
+
launchAutoHide: false;
|
|
32
|
+
};
|
|
33
|
+
Keyboard: {
|
|
34
|
+
resize: NonNullable<ThemeConfigOptions['keyboardResize']>;
|
|
35
|
+
};
|
|
36
|
+
};
|
|
37
|
+
}
|
|
38
|
+
/**
|
|
39
|
+
* The Capacitor settings the theme expects:
|
|
40
|
+
*
|
|
41
|
+
* - The launch background in the theme's colour, so there is no white flash before a dark app's
|
|
42
|
+
* first frame (or the reverse).
|
|
43
|
+
* - `SystemBars` injecting the safe-area variables `styles.css` reads on older Android web views.
|
|
44
|
+
* - A splash screen that waits for `hideSplashScreen` (or `setupCapacitor`), which lifts it once
|
|
45
|
+
* the stored theme and the fonts are in. Its colour is left to the native launch screen: the
|
|
46
|
+
* plugin's `backgroundColor` would paint one fixed colour over it, and on iOS hide a launch
|
|
47
|
+
* colour that follows dark mode.
|
|
48
|
+
* - The keyboard resize mode.
|
|
49
|
+
*/
|
|
50
|
+
export declare function themeConfig(options?: ThemeConfigOptions): ThemeConfig;
|
|
51
|
+
/**
|
|
52
|
+
* Your config with {@link themeConfig} underneath it: everything you set wins, down to single
|
|
53
|
+
* plugin options, and everything you leave out comes from the theme.
|
|
54
|
+
*
|
|
55
|
+
* ```ts
|
|
56
|
+
* // capacitor.config.ts
|
|
57
|
+
* import type { CapacitorConfig } from '@capacitor/cli';
|
|
58
|
+
* import { withTheme } from '@loidolt/theme-capacitor/config';
|
|
59
|
+
*
|
|
60
|
+
* export default withTheme<CapacitorConfig>({
|
|
61
|
+
* appId: 'space.loidolt.topostack',
|
|
62
|
+
* appName: 'Topostack',
|
|
63
|
+
* webDir: 'build',
|
|
64
|
+
* });
|
|
65
|
+
* ```
|
|
66
|
+
*/
|
|
67
|
+
export declare function withTheme<C extends object>(config: C, options?: ThemeConfigOptions): C;
|
|
@@ -0,0 +1,62 @@
|
|
|
1
|
+
/*
|
|
2
|
+
* `@loidolt/theme-capacitor/config` — for `capacitor.config.ts`, which the Capacitor CLI runs in
|
|
3
|
+
* Node. Plain data from the tokens: no DOM, no Svelte, no Capacitor runtime.
|
|
4
|
+
*/
|
|
5
|
+
import { darkSemantic, semantic } from '@loidolt/theme-tokens';
|
|
6
|
+
/**
|
|
7
|
+
* The Capacitor settings the theme expects:
|
|
8
|
+
*
|
|
9
|
+
* - The launch background in the theme's colour, so there is no white flash before a dark app's
|
|
10
|
+
* first frame (or the reverse).
|
|
11
|
+
* - `SystemBars` injecting the safe-area variables `styles.css` reads on older Android web views.
|
|
12
|
+
* - A splash screen that waits for `hideSplashScreen` (or `setupCapacitor`), which lifts it once
|
|
13
|
+
* the stored theme and the fonts are in. Its colour is left to the native launch screen: the
|
|
14
|
+
* plugin's `backgroundColor` would paint one fixed colour over it, and on iOS hide a launch
|
|
15
|
+
* colour that follows dark mode.
|
|
16
|
+
* - The keyboard resize mode.
|
|
17
|
+
*/
|
|
18
|
+
export function themeConfig(options = {}) {
|
|
19
|
+
const { scheme = 'light', keyboardResize = 'native' } = options;
|
|
20
|
+
const backgroundColor = options.backgroundColor ?? (scheme === 'dark' ? darkSemantic : semantic).background;
|
|
21
|
+
return {
|
|
22
|
+
backgroundColor,
|
|
23
|
+
ios: { backgroundColor },
|
|
24
|
+
android: { backgroundColor },
|
|
25
|
+
plugins: {
|
|
26
|
+
SystemBars: { insetsHandling: 'css' },
|
|
27
|
+
SplashScreen: { launchAutoHide: false },
|
|
28
|
+
Keyboard: { resize: keyboardResize },
|
|
29
|
+
},
|
|
30
|
+
};
|
|
31
|
+
}
|
|
32
|
+
/**
|
|
33
|
+
* Your config with {@link themeConfig} underneath it: everything you set wins, down to single
|
|
34
|
+
* plugin options, and everything you leave out comes from the theme.
|
|
35
|
+
*
|
|
36
|
+
* ```ts
|
|
37
|
+
* // capacitor.config.ts
|
|
38
|
+
* import type { CapacitorConfig } from '@capacitor/cli';
|
|
39
|
+
* import { withTheme } from '@loidolt/theme-capacitor/config';
|
|
40
|
+
*
|
|
41
|
+
* export default withTheme<CapacitorConfig>({
|
|
42
|
+
* appId: 'space.loidolt.topostack',
|
|
43
|
+
* appName: 'Topostack',
|
|
44
|
+
* webDir: 'build',
|
|
45
|
+
* });
|
|
46
|
+
* ```
|
|
47
|
+
*/
|
|
48
|
+
export function withTheme(config, options = {}) {
|
|
49
|
+
const theme = themeConfig(options);
|
|
50
|
+
const own = config;
|
|
51
|
+
const plugins = { ...own.plugins };
|
|
52
|
+
for (const [name, defaults] of Object.entries(theme.plugins)) {
|
|
53
|
+
plugins[name] = { ...defaults, ...own.plugins?.[name] };
|
|
54
|
+
}
|
|
55
|
+
return {
|
|
56
|
+
...config,
|
|
57
|
+
backgroundColor: own.backgroundColor ?? theme.backgroundColor,
|
|
58
|
+
ios: { ...theme.ios, ...own.ios },
|
|
59
|
+
android: { ...theme.android, ...own.android },
|
|
60
|
+
plugins,
|
|
61
|
+
};
|
|
62
|
+
}
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
import type { AppUrlPlugin, Teardown } from './types.js';
|
|
2
|
+
/**
|
|
3
|
+
* The in-app path for a URL that opened the app. An `https://` universal or app link keeps its
|
|
4
|
+
* path; a custom scheme has no host in the usual sense, so `myapp://projects/42` becomes
|
|
5
|
+
* `/projects/42`. Query and hash are kept.
|
|
6
|
+
*/
|
|
7
|
+
export declare function deepLinkPath(url: string): string | null;
|
|
8
|
+
export interface DeepLinkOptions {
|
|
9
|
+
/** `App` from `@capacitor/app`. */
|
|
10
|
+
App: AppUrlPlugin;
|
|
11
|
+
/** Your router's navigation — `goto` in SvelteKit. */
|
|
12
|
+
navigate: (path: string) => void;
|
|
13
|
+
/** Turns the opening URL into an in-app path, or `null` to ignore it. Defaults to {@link deepLinkPath}. */
|
|
14
|
+
resolve?: (url: string) => string | null;
|
|
15
|
+
}
|
|
16
|
+
/** Routes universal links, app links and custom-scheme URLs into the app's own router. */
|
|
17
|
+
export declare function handleDeepLinks(options: DeepLinkOptions): Teardown;
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
import { listen, nativePlatform } from './platform.js';
|
|
2
|
+
/**
|
|
3
|
+
* The in-app path for a URL that opened the app. An `https://` universal or app link keeps its
|
|
4
|
+
* path; a custom scheme has no host in the usual sense, so `myapp://projects/42` becomes
|
|
5
|
+
* `/projects/42`. Query and hash are kept.
|
|
6
|
+
*/
|
|
7
|
+
export function deepLinkPath(url) {
|
|
8
|
+
let parsed;
|
|
9
|
+
try {
|
|
10
|
+
parsed = new URL(url);
|
|
11
|
+
}
|
|
12
|
+
catch {
|
|
13
|
+
return null;
|
|
14
|
+
}
|
|
15
|
+
const web = parsed.protocol === 'http:' || parsed.protocol === 'https:';
|
|
16
|
+
const path = web ? parsed.pathname : `/${parsed.host}${parsed.pathname}`.replace(/\/{2,}/g, '/');
|
|
17
|
+
return `${path || '/'}${parsed.search}${parsed.hash}`;
|
|
18
|
+
}
|
|
19
|
+
/** Routes universal links, app links and custom-scheme URLs into the app's own router. */
|
|
20
|
+
export function handleDeepLinks(options) {
|
|
21
|
+
if (!nativePlatform())
|
|
22
|
+
return () => { };
|
|
23
|
+
const { App, navigate, resolve = deepLinkPath } = options;
|
|
24
|
+
return listen(App.addListener('appUrlOpen', ({ url }) => {
|
|
25
|
+
const path = resolve(url);
|
|
26
|
+
if (path !== null)
|
|
27
|
+
navigate(path);
|
|
28
|
+
}));
|
|
29
|
+
}
|
package/dist/files.d.ts
ADDED
|
@@ -0,0 +1,101 @@
|
|
|
1
|
+
import type { FilePickerPlugin, FilesystemPlugin } from './types.js';
|
|
2
|
+
/** The part of `@capacitor/filesystem` saving, and clearing up after picking, use. */
|
|
3
|
+
type FilesSystemPlugin = Pick<FilesystemPlugin, 'writeFile' | 'stat' | 'checkPermissions' | 'requestPermissions' | 'getUri' | 'deleteFile' | 'rmdir'>;
|
|
4
|
+
export interface PickOptions {
|
|
5
|
+
/**
|
|
6
|
+
* What may be picked, written as for `<input accept>`: MIME types (`application/pdf`), wildcards
|
|
7
|
+
* (`image/*`) and extensions (`.pdf`), comma-separated. Like the attribute it is a filter for the
|
|
8
|
+
* picker, not a guarantee about what comes back.
|
|
9
|
+
*/
|
|
10
|
+
accept?: string;
|
|
11
|
+
/** Allow more than one file. Defaults to `false`. */
|
|
12
|
+
multiple?: boolean;
|
|
13
|
+
}
|
|
14
|
+
/** A file to save: a `File`, or a Blob with the name it should be saved under. */
|
|
15
|
+
export type SaveableFile = File | {
|
|
16
|
+
blob: Blob;
|
|
17
|
+
name: string;
|
|
18
|
+
};
|
|
19
|
+
export interface SaveOptions {
|
|
20
|
+
/** A folder inside the directory, created when missing (`'Exports'`). */
|
|
21
|
+
folder?: string;
|
|
22
|
+
/**
|
|
23
|
+
* Replace a file of the same name. Defaults to `false`: the new one is saved as
|
|
24
|
+
* `name (1).ext`, `name (2).ext`, … instead.
|
|
25
|
+
*/
|
|
26
|
+
overwrite?: boolean;
|
|
27
|
+
}
|
|
28
|
+
/**
|
|
29
|
+
* Where a saved file went: written to the device with `Filesystem` (with its URI and the path
|
|
30
|
+
* inside `directory`), handed to the browser as a download, or nowhere (on the server).
|
|
31
|
+
*/
|
|
32
|
+
export type SaveOutcome = {
|
|
33
|
+
method: 'filesystem';
|
|
34
|
+
uri: string;
|
|
35
|
+
path: string;
|
|
36
|
+
directory: string;
|
|
37
|
+
} | {
|
|
38
|
+
method: 'download';
|
|
39
|
+
name: string;
|
|
40
|
+
} | {
|
|
41
|
+
method: 'none';
|
|
42
|
+
};
|
|
43
|
+
export interface NativeFilesOptions {
|
|
44
|
+
/** `FilePicker` from `@capawesome/capacitor-file-picker`. Without it, the browser's picker. */
|
|
45
|
+
FilePicker?: FilePickerPlugin;
|
|
46
|
+
/**
|
|
47
|
+
* `Filesystem` from `@capacitor/filesystem`. Needed to save in a native shell; with it, `pick`
|
|
48
|
+
* also removes the copies the native picker leaves in the app's cache once they are read.
|
|
49
|
+
*/
|
|
50
|
+
Filesystem?: FilesSystemPlugin;
|
|
51
|
+
/**
|
|
52
|
+
* The `Directory` files are saved to. Defaults to `'DOCUMENTS'`: on iOS the app's Documents
|
|
53
|
+
* folder, which the Files app shows once the app opts in (see the README); on Android the
|
|
54
|
+
* shared Documents folder, which every file manager shows.
|
|
55
|
+
*/
|
|
56
|
+
directory?: string;
|
|
57
|
+
}
|
|
58
|
+
export interface NativeFiles {
|
|
59
|
+
/**
|
|
60
|
+
* Lets the user pick files — the native picker in an app, the browser's elsewhere — and resolves
|
|
61
|
+
* them as `File`s, the same objects a `FileInput` hands you, so one upload path serves both.
|
|
62
|
+
* Resolves `[]` when the picker is dismissed. In a browser, call it from a click or key handler,
|
|
63
|
+
* as for any file input.
|
|
64
|
+
*/
|
|
65
|
+
pick(options?: PickOptions): Promise<File[]>;
|
|
66
|
+
/**
|
|
67
|
+
* Saves a file to the device with `Filesystem` in a native shell (asking for storage access on
|
|
68
|
+
* the Android versions that need it), or downloads it in a browser.
|
|
69
|
+
*/
|
|
70
|
+
save(file: SaveableFile, options?: SaveOptions): Promise<SaveOutcome>;
|
|
71
|
+
}
|
|
72
|
+
/** The user refused storage access, so the file could not be saved. */
|
|
73
|
+
export declare class FilePermissionError extends Error {
|
|
74
|
+
name: string;
|
|
75
|
+
constructor(message?: string);
|
|
76
|
+
}
|
|
77
|
+
/** Common extensions in `accept` and the MIME types the native pickers filter by. */
|
|
78
|
+
export declare const EXTENSION_TYPES: Readonly<Record<string, string>>;
|
|
79
|
+
/**
|
|
80
|
+
* An `accept` string as the MIME types a native picker filters by. `undefined` means "anything":
|
|
81
|
+
* no `accept`, or an extension with no known type — rather than make those files unpickable.
|
|
82
|
+
*/
|
|
83
|
+
export declare function acceptToMimeTypes(accept: string | undefined): string[] | undefined;
|
|
84
|
+
/**
|
|
85
|
+
* Opening and saving files the same way in a native shell and in a browser. Picking uses
|
|
86
|
+
* `@capawesome/capacitor-file-picker` in the app and a file input elsewhere, and resolves `File`s
|
|
87
|
+
* either way; saving writes to the device's Documents with `@capacitor/filesystem`, or downloads.
|
|
88
|
+
*
|
|
89
|
+
* ```ts
|
|
90
|
+
* import { FilePicker } from '@capawesome/capacitor-file-picker';
|
|
91
|
+
* import { Filesystem } from '@capacitor/filesystem';
|
|
92
|
+
*
|
|
93
|
+
* const files = createFiles({ FilePicker, Filesystem });
|
|
94
|
+
* const [pdf] = await files.pick({ accept: '.pdf' });
|
|
95
|
+
* await files.save(new File([bytes], 'export.pdf'));
|
|
96
|
+
* ```
|
|
97
|
+
*
|
|
98
|
+
* On the server `pick` resolves `[]` and `save` resolves `{ method: 'none' }`.
|
|
99
|
+
*/
|
|
100
|
+
export declare function createFiles(options?: NativeFilesOptions): NativeFiles;
|
|
101
|
+
export {};
|
package/dist/files.js
ADDED
|
@@ -0,0 +1,259 @@
|
|
|
1
|
+
import { Capacitor } from '@capacitor/core';
|
|
2
|
+
import { blobToBase64, downloadBlob, safeFileName } from './blob.js';
|
|
3
|
+
import { nativePlatform } from './platform.js';
|
|
4
|
+
/** The user refused storage access, so the file could not be saved. */
|
|
5
|
+
export class FilePermissionError extends Error {
|
|
6
|
+
name = 'FilePermissionError';
|
|
7
|
+
constructor(message = 'Storage access was denied') {
|
|
8
|
+
super(message);
|
|
9
|
+
}
|
|
10
|
+
}
|
|
11
|
+
/** Common extensions in `accept` and the MIME types the native pickers filter by. */
|
|
12
|
+
export const EXTENSION_TYPES = {
|
|
13
|
+
'.avif': 'image/avif',
|
|
14
|
+
'.csv': 'text/csv',
|
|
15
|
+
'.doc': 'application/msword',
|
|
16
|
+
'.docx': 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
|
|
17
|
+
'.epub': 'application/epub+zip',
|
|
18
|
+
'.gif': 'image/gif',
|
|
19
|
+
'.heic': 'image/heic',
|
|
20
|
+
'.htm': 'text/html',
|
|
21
|
+
'.html': 'text/html',
|
|
22
|
+
'.jpeg': 'image/jpeg',
|
|
23
|
+
'.jpg': 'image/jpeg',
|
|
24
|
+
'.json': 'application/json',
|
|
25
|
+
'.m4a': 'audio/mp4',
|
|
26
|
+
'.md': 'text/markdown',
|
|
27
|
+
'.mov': 'video/quicktime',
|
|
28
|
+
'.mp3': 'audio/mpeg',
|
|
29
|
+
'.mp4': 'video/mp4',
|
|
30
|
+
'.odt': 'application/vnd.oasis.opendocument.text',
|
|
31
|
+
'.pdf': 'application/pdf',
|
|
32
|
+
'.png': 'image/png',
|
|
33
|
+
'.ppt': 'application/vnd.ms-powerpoint',
|
|
34
|
+
'.pptx': 'application/vnd.openxmlformats-officedocument.presentationml.presentation',
|
|
35
|
+
'.rtf': 'application/rtf',
|
|
36
|
+
'.svg': 'image/svg+xml',
|
|
37
|
+
'.txt': 'text/plain',
|
|
38
|
+
'.wav': 'audio/wav',
|
|
39
|
+
'.webp': 'image/webp',
|
|
40
|
+
'.xls': 'application/vnd.ms-excel',
|
|
41
|
+
'.xlsx': 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
|
|
42
|
+
'.xml': 'application/xml',
|
|
43
|
+
'.zip': 'application/zip',
|
|
44
|
+
};
|
|
45
|
+
/**
|
|
46
|
+
* An `accept` string as the MIME types a native picker filters by. `undefined` means "anything":
|
|
47
|
+
* no `accept`, or an extension with no known type — rather than make those files unpickable.
|
|
48
|
+
*/
|
|
49
|
+
export function acceptToMimeTypes(accept) {
|
|
50
|
+
const tokens = (accept ?? '')
|
|
51
|
+
.split(',')
|
|
52
|
+
.map((token) => token.trim().toLowerCase())
|
|
53
|
+
.filter(Boolean);
|
|
54
|
+
if (tokens.length === 0 || tokens.includes('*/*'))
|
|
55
|
+
return undefined;
|
|
56
|
+
const types = new Set();
|
|
57
|
+
for (const token of tokens) {
|
|
58
|
+
const type = token.startsWith('.') ? EXTENSION_TYPES[token] : token.includes('/') && token;
|
|
59
|
+
if (!type)
|
|
60
|
+
return undefined;
|
|
61
|
+
types.add(type);
|
|
62
|
+
}
|
|
63
|
+
return [...types];
|
|
64
|
+
}
|
|
65
|
+
const isCancel = (error) => error instanceof Error && /cancel/i.test(error.message);
|
|
66
|
+
const nameOf = (file) => safeFileName(file.name);
|
|
67
|
+
const blobOf = (file) => (file instanceof Blob ? file : file.blob);
|
|
68
|
+
/** A picked native file as a `File`, read through the web view's file URL. */
|
|
69
|
+
async function toFile(picked) {
|
|
70
|
+
let blob = picked.blob;
|
|
71
|
+
if (!blob) {
|
|
72
|
+
const src = picked.webPath ?? (picked.path ? Capacitor.convertFileSrc(picked.path) : null);
|
|
73
|
+
if (!src)
|
|
74
|
+
throw new Error(`The picked file ${picked.name} has no path to read it from`);
|
|
75
|
+
const response = await fetch(src);
|
|
76
|
+
if (!response.ok)
|
|
77
|
+
throw new Error(`Could not read the picked file ${picked.name}`);
|
|
78
|
+
blob = await response.blob();
|
|
79
|
+
}
|
|
80
|
+
return new File([blob], picked.name, {
|
|
81
|
+
type: picked.mimeType || blob.type,
|
|
82
|
+
lastModified: picked.modifiedAt,
|
|
83
|
+
});
|
|
84
|
+
}
|
|
85
|
+
/**
|
|
86
|
+
* The path of a picked file inside the app's cache directory, as `Filesystem` takes it with
|
|
87
|
+
* `directory: 'CACHE'`, or `null` when it lies anywhere else (or cannot be told).
|
|
88
|
+
*/
|
|
89
|
+
function cachePath(path, cacheUri) {
|
|
90
|
+
const root = cacheUri.replace(/\/+$/, '');
|
|
91
|
+
if (!path || !root || !path.startsWith(`${root}/`))
|
|
92
|
+
return null;
|
|
93
|
+
let segments;
|
|
94
|
+
try {
|
|
95
|
+
segments = path
|
|
96
|
+
.slice(root.length + 1)
|
|
97
|
+
.split('/')
|
|
98
|
+
.map(decodeURIComponent);
|
|
99
|
+
}
|
|
100
|
+
catch {
|
|
101
|
+
return null;
|
|
102
|
+
}
|
|
103
|
+
if (segments.some((segment) => !segment || segment === '.' || segment === '..'))
|
|
104
|
+
return null;
|
|
105
|
+
return segments.join('/');
|
|
106
|
+
}
|
|
107
|
+
/**
|
|
108
|
+
* Removes the copy the native picker left in the cache directory (iOS copies every picked file
|
|
109
|
+
* into `Library/Caches/<uuid>/`), and the folder it made for it when that is empty now. Files
|
|
110
|
+
* outside the cache are the user's own and are left alone. Failures are ignored: the file has
|
|
111
|
+
* been read already, and the cache is the system's to clear.
|
|
112
|
+
*/
|
|
113
|
+
async function removePickedCopy(fs, path, cacheUri) {
|
|
114
|
+
const inCache = cachePath(path, cacheUri);
|
|
115
|
+
if (!inCache)
|
|
116
|
+
return;
|
|
117
|
+
try {
|
|
118
|
+
await fs.deleteFile({ path: inCache, directory: 'CACHE' });
|
|
119
|
+
const folder = inCache.slice(0, inCache.lastIndexOf('/'));
|
|
120
|
+
// Not recursive: the folder goes only when nothing else is in it.
|
|
121
|
+
if (folder)
|
|
122
|
+
await fs.rmdir({ path: folder, directory: 'CACHE', recursive: false });
|
|
123
|
+
}
|
|
124
|
+
catch {
|
|
125
|
+
// Left for the system to clear.
|
|
126
|
+
}
|
|
127
|
+
}
|
|
128
|
+
/** The browser's own picker: a hidden file input, opened and removed again. */
|
|
129
|
+
function pickInBrowser({ accept, multiple = false }) {
|
|
130
|
+
return new Promise((resolve) => {
|
|
131
|
+
const input = document.createElement('input');
|
|
132
|
+
input.type = 'file';
|
|
133
|
+
input.hidden = true;
|
|
134
|
+
input.multiple = multiple;
|
|
135
|
+
if (accept)
|
|
136
|
+
input.accept = accept;
|
|
137
|
+
const done = (files) => {
|
|
138
|
+
input.remove();
|
|
139
|
+
resolve(files);
|
|
140
|
+
};
|
|
141
|
+
input.addEventListener('change', () => done(Array.from(input.files ?? [])), { once: true });
|
|
142
|
+
// Every current browser fires `cancel` when the picker is dismissed.
|
|
143
|
+
input.addEventListener('cancel', () => done([]), { once: true });
|
|
144
|
+
document.body.append(input);
|
|
145
|
+
input.click();
|
|
146
|
+
});
|
|
147
|
+
}
|
|
148
|
+
/** `name (n).ext`. */
|
|
149
|
+
function numbered(name, n) {
|
|
150
|
+
const dot = name.lastIndexOf('.');
|
|
151
|
+
return dot > 0 ? `${name.slice(0, dot)} (${n})${name.slice(dot)}` : `${name} (${n})`;
|
|
152
|
+
}
|
|
153
|
+
/**
|
|
154
|
+
* Opening and saving files the same way in a native shell and in a browser. Picking uses
|
|
155
|
+
* `@capawesome/capacitor-file-picker` in the app and a file input elsewhere, and resolves `File`s
|
|
156
|
+
* either way; saving writes to the device's Documents with `@capacitor/filesystem`, or downloads.
|
|
157
|
+
*
|
|
158
|
+
* ```ts
|
|
159
|
+
* import { FilePicker } from '@capawesome/capacitor-file-picker';
|
|
160
|
+
* import { Filesystem } from '@capacitor/filesystem';
|
|
161
|
+
*
|
|
162
|
+
* const files = createFiles({ FilePicker, Filesystem });
|
|
163
|
+
* const [pdf] = await files.pick({ accept: '.pdf' });
|
|
164
|
+
* await files.save(new File([bytes], 'export.pdf'));
|
|
165
|
+
* ```
|
|
166
|
+
*
|
|
167
|
+
* On the server `pick` resolves `[]` and `save` resolves `{ method: 'none' }`.
|
|
168
|
+
*/
|
|
169
|
+
export function createFiles(options = {}) {
|
|
170
|
+
const { FilePicker, Filesystem, directory = 'DOCUMENTS' } = options;
|
|
171
|
+
/** Android 10 and older need storage access for the shared folders; it is asked for here. */
|
|
172
|
+
const ensureAccess = async (fs) => {
|
|
173
|
+
if (nativePlatform() !== 'android')
|
|
174
|
+
return;
|
|
175
|
+
if (directory !== 'DOCUMENTS' && directory !== 'EXTERNAL_STORAGE')
|
|
176
|
+
return;
|
|
177
|
+
if ((await fs.checkPermissions()).publicStorage === 'granted')
|
|
178
|
+
return;
|
|
179
|
+
if ((await fs.requestPermissions()).publicStorage !== 'granted') {
|
|
180
|
+
throw new FilePermissionError();
|
|
181
|
+
}
|
|
182
|
+
};
|
|
183
|
+
const exists = (fs, path) => fs.stat({ path, directory }).then(() => true, () => false);
|
|
184
|
+
const freePath = async (fs, folder, name) => {
|
|
185
|
+
const at = (file) => (folder ? `${folder}/${file}` : file);
|
|
186
|
+
if (!(await exists(fs, at(name))))
|
|
187
|
+
return at(name);
|
|
188
|
+
for (let n = 1; n < 1000; n++) {
|
|
189
|
+
const candidate = at(numbered(name, n));
|
|
190
|
+
if (!(await exists(fs, candidate)))
|
|
191
|
+
return candidate;
|
|
192
|
+
}
|
|
193
|
+
throw new Error(`Too many files named ${name}`);
|
|
194
|
+
};
|
|
195
|
+
return {
|
|
196
|
+
async pick(pickOptions = {}) {
|
|
197
|
+
if (typeof document === 'undefined')
|
|
198
|
+
return [];
|
|
199
|
+
if (!FilePicker || !nativePlatform())
|
|
200
|
+
return pickInBrowser(pickOptions);
|
|
201
|
+
let picked;
|
|
202
|
+
try {
|
|
203
|
+
({ files: picked } = await FilePicker.pickFiles({
|
|
204
|
+
types: acceptToMimeTypes(pickOptions.accept),
|
|
205
|
+
limit: pickOptions.multiple ? 0 : 1,
|
|
206
|
+
}));
|
|
207
|
+
}
|
|
208
|
+
catch (error) {
|
|
209
|
+
if (isCancel(error))
|
|
210
|
+
return [];
|
|
211
|
+
throw error;
|
|
212
|
+
}
|
|
213
|
+
if (!Filesystem)
|
|
214
|
+
return Promise.all(picked.map(toFile));
|
|
215
|
+
const cacheUri = picked.some((file) => file.path)
|
|
216
|
+
? Filesystem.getUri({ path: '', directory: 'CACHE' }).then(({ uri }) => uri, () => '')
|
|
217
|
+
: Promise.resolve('');
|
|
218
|
+
return Promise.all(picked.map(async (file) => {
|
|
219
|
+
try {
|
|
220
|
+
return await toFile(file);
|
|
221
|
+
}
|
|
222
|
+
finally {
|
|
223
|
+
if (file.path)
|
|
224
|
+
await removePickedCopy(Filesystem, file.path, await cacheUri);
|
|
225
|
+
}
|
|
226
|
+
}));
|
|
227
|
+
},
|
|
228
|
+
async save(file, saveOptions = {}) {
|
|
229
|
+
if (typeof document === 'undefined')
|
|
230
|
+
return { method: 'none' };
|
|
231
|
+
const name = nameOf(file);
|
|
232
|
+
if (!nativePlatform()) {
|
|
233
|
+
downloadBlob(blobOf(file), name);
|
|
234
|
+
return { method: 'download', name };
|
|
235
|
+
}
|
|
236
|
+
if (!Filesystem) {
|
|
237
|
+
// A web view has no download manager of its own; a download would go nowhere.
|
|
238
|
+
throw new Error('Saving a file in a native shell needs Filesystem from @capacitor/filesystem');
|
|
239
|
+
}
|
|
240
|
+
await ensureAccess(Filesystem);
|
|
241
|
+
const folder = (saveOptions.folder ?? '')
|
|
242
|
+
.split('/')
|
|
243
|
+
// `..` and `.` come out empty, so a folder cannot climb out of the directory.
|
|
244
|
+
.map((segment) => safeFileName(segment, ''))
|
|
245
|
+
.filter(Boolean)
|
|
246
|
+
.join('/');
|
|
247
|
+
const path = saveOptions.overwrite
|
|
248
|
+
? [folder, name].filter(Boolean).join('/')
|
|
249
|
+
: await freePath(Filesystem, folder, name);
|
|
250
|
+
const { uri } = await Filesystem.writeFile({
|
|
251
|
+
path,
|
|
252
|
+
data: await blobToBase64(blobOf(file)),
|
|
253
|
+
directory,
|
|
254
|
+
recursive: true,
|
|
255
|
+
});
|
|
256
|
+
return { method: 'filesystem', uri, path, directory };
|
|
257
|
+
},
|
|
258
|
+
};
|
|
259
|
+
}
|
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
import type { StatusVariant, Toaster } from '@loidolt/theme-svelte';
|
|
2
|
+
import type { HapticsPlugin, Teardown } from './types.js';
|
|
3
|
+
export type ImpactWeight = 'light' | 'medium' | 'heavy';
|
|
4
|
+
/**
|
|
5
|
+
* Controls whose activation changes a value — the moments a native control ticks. Disabled ones
|
|
6
|
+
* are skipped. Buttons are left out on purpose: iOS and Android buttons do not buzz, and a buzz
|
|
7
|
+
* on every press soon reads as noise. Opt one in with `data-haptic`.
|
|
8
|
+
*/
|
|
9
|
+
export declare const SELECTION_TARGETS: string;
|
|
10
|
+
export interface HapticsOptions {
|
|
11
|
+
/** `Haptics` from `@capacitor/haptics`. */
|
|
12
|
+
Haptics: HapticsPlugin;
|
|
13
|
+
/**
|
|
14
|
+
* Read before every buzz, so an in-app "Vibration" setting can turn them off without
|
|
15
|
+
* reinstalling anything. Defaults to always on.
|
|
16
|
+
*/
|
|
17
|
+
enabled?: () => boolean;
|
|
18
|
+
}
|
|
19
|
+
export interface InstallHapticsOptions {
|
|
20
|
+
/** What ticks on activation. Defaults to {@link SELECTION_TARGETS}. */
|
|
21
|
+
selection?: string;
|
|
22
|
+
}
|
|
23
|
+
export interface NativeHaptics {
|
|
24
|
+
/** A physical tap: `light` for a small control, `heavy` for a drop or a snap. */
|
|
25
|
+
impact(weight?: ImpactWeight): void;
|
|
26
|
+
/** One tick of a selection changing — a switch flipping, a tab changing. */
|
|
27
|
+
selection(): void;
|
|
28
|
+
/** The outcome pattern for a status: success, warning or error. `info` has none. */
|
|
29
|
+
notify(variant: StatusVariant | undefined): void;
|
|
30
|
+
/**
|
|
31
|
+
* Gives the page's controls their native feel with one delegated listener: a selection tick
|
|
32
|
+
* for every `selection` target, and an impact for any element with `data-haptic`
|
|
33
|
+
* (`data-haptic="medium"` picks the weight).
|
|
34
|
+
*/
|
|
35
|
+
install(options?: InstallHapticsOptions): Teardown;
|
|
36
|
+
}
|
|
37
|
+
/**
|
|
38
|
+
* Haptic feedback through `@capacitor/haptics`, in the theme's vocabulary. Silent in a browser,
|
|
39
|
+
* even one that can vibrate: a web page that buzzes is a surprise, a native app that does not is
|
|
40
|
+
* a disappointment.
|
|
41
|
+
*
|
|
42
|
+
* ```ts
|
|
43
|
+
* import { Haptics } from '@capacitor/haptics';
|
|
44
|
+
* export const haptics = createHaptics({ Haptics });
|
|
45
|
+
* haptics.install();
|
|
46
|
+
* ```
|
|
47
|
+
*/
|
|
48
|
+
export declare function createHaptics(options: HapticsOptions): NativeHaptics;
|
|
49
|
+
/**
|
|
50
|
+
* The same toaster, with the matching notification pattern on every status toast — a success
|
|
51
|
+
* tap, a warning or error buzz — so feedback lands even when the screen is not being watched.
|
|
52
|
+
*
|
|
53
|
+
* ```ts
|
|
54
|
+
* export const toaster = withHaptics(createToaster(), haptics);
|
|
55
|
+
* ```
|
|
56
|
+
*/
|
|
57
|
+
export declare function withHaptics(toaster: Toaster, haptics: Pick<NativeHaptics, 'notify'>): Toaster;
|