@timmo001/groundwork-mobile 0.0.0-stage → 0.0.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/LICENSE ADDED
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
package/README.md CHANGED
@@ -1,3 +1,32 @@
1
- # Temporary Holding Version
1
+ # @timmo001/groundwork-mobile
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
+ The page side of Groundwork's Android shell, a small Kotlin app around the
4
+ system WebView. It works out whether the page runs in the shell, talks to the
5
+ shell over a typed bridge when it does, and falls back to
6
+ `@timmo001/groundwork-pwa` when it doesn't, so one app runs in both.
7
+
8
+ ```ts
9
+ import { connectMobile } from "@timmo001/groundwork-mobile/view";
10
+
11
+ import mobileConfig from "../mobile.config.ts";
12
+ import pwaConfig from "../pwa.config.ts";
13
+
14
+ const mobile = await connectMobile(mobileConfig, {
15
+ pwa: pwaConfig,
16
+ onShare: (share) => openDraft(share),
17
+ onDeepLink: (url) => route(url),
18
+ });
19
+ ```
20
+
21
+ - `.` defines the app's mobile config, which the shell also reads as JSON
22
+ when it's built: a hosted `url`, extra `origins`, and which of shares,
23
+ notifications, push, deep links, downloads and the rest it keeps.
24
+ - `./view` connects the page: notifications, push, shares, deep links, the
25
+ phone's dynamic color, and the app's own requests to its Kotlin handlers.
26
+ - `./bridge` is the bridge's message shapes and the Schema for each of the
27
+ shell's requests and messages.
28
+
29
+ The Kotlin shell itself is the Gradle library in `packages/mobile/android`,
30
+ taken into an app by Groundwork's sync rather than from npm. The docs are at
31
+ [groundwork.timmo.dev/phones/shell](https://groundwork.timmo.dev/phones/shell),
32
+ and `templates/android-app` is a starting point.
package/package.json CHANGED
@@ -1,6 +1,48 @@
1
1
  {
2
2
  "name": "@timmo001/groundwork-mobile",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.0.0",
4
+ "description": "The page side of Groundwork's Android shell: the app config, the typed bridge to the shell, and a fallback to the PWA outside it",
5
+ "license": "Apache-2.0",
6
+ "type": "module",
7
+ "exports": {
8
+ ".": "./src/config.ts",
9
+ "./bridge": "./src/bridge.ts",
10
+ "./view": "./src/view.ts"
11
+ },
12
+ "files": [
13
+ "src",
14
+ "!src/**/*.test.ts",
15
+ "README.md",
16
+ "LICENSE"
17
+ ],
18
+ "publishConfig": {
19
+ "access": "public"
20
+ },
21
+ "repository": {
22
+ "type": "git",
23
+ "url": "git+https://github.com/timmo001/groundwork.git",
24
+ "directory": "packages/mobile"
25
+ },
26
+ "scripts": {
27
+ "check": "bun run --parallel --no-exit-on-error lint typecheck format:check",
28
+ "test": "bun test",
29
+ "lint": "oxlint .",
30
+ "typecheck": "tsc",
31
+ "format": "prettier --write .",
32
+ "format:check": "prettier --check ."
33
+ },
34
+ "dependencies": {
35
+ "@timmo001/groundwork-pwa": "0.0.0",
36
+ "@timmo001/groundwork-tokens": "0.12.1",
37
+ "effect": "4.1.2"
38
+ },
39
+ "devDependencies": {
40
+ "@oxlint/plugins": "1.92.0",
41
+ "@timmo001/oxlint-rules": "0.6.4",
42
+ "@types/bun": "1.4.4",
43
+ "oxlint": "1.92.0",
44
+ "oxlint-tsgolint": "7.0.2006",
45
+ "prettier": "3.9.10",
46
+ "typescript": "7.0.2"
47
+ }
48
+ }
package/src/bridge.ts ADDED
@@ -0,0 +1,204 @@
1
+ /**
2
+ * The messages between the Android shell and its view, mirroring the
3
+ * desktop's requests and messages. They travel as JSON text over the object
4
+ * the shell injects with `WebViewCompat.addWebMessageListener`, each with a
5
+ * `type`, so the Kotlin side reads them without a schema library. Every
6
+ * reply and message is parsed here as it comes in. An app adds its own
7
+ * requests and messages beside these, with its own schemas.
8
+ */
9
+ import { Option, Schema } from "effect";
10
+
11
+ /** The name of the object the shell injects into allowed pages. */
12
+ export const bridgeObjectName = "groundworkShell";
13
+
14
+ /** A notification for the shell to show, or a notice in the app without one. */
15
+ export const Notice = Schema.Struct({
16
+ heading: Schema.String,
17
+ body: Schema.optionalKey(Schema.String),
18
+ tone: Schema.optionalKey(
19
+ Schema.Literals(["neutral", "info", "success", "warning", "danger"]),
20
+ ),
21
+ /** Like notices share a tag, so a new one replaces the last. */
22
+ tag: Schema.optionalKey(Schema.String),
23
+ /** Opens this page, relative to the app, on a tap. */
24
+ link: Schema.optionalKey(Schema.String),
25
+ });
26
+
27
+ export interface Notice extends Schema.Schema.Type<typeof Notice> {}
28
+
29
+ /** A share from another app, the same shape the PWA's share target gives. */
30
+ export const ShellShare = Schema.Struct({
31
+ title: Schema.optionalKey(Schema.String),
32
+ text: Schema.optionalKey(Schema.String),
33
+ url: Schema.optionalKey(Schema.String),
34
+ });
35
+
36
+ export const DeepLink = Schema.Struct({ url: Schema.String });
37
+
38
+ export interface DeepLink extends Schema.Schema.Type<typeof DeepLink> {}
39
+
40
+ /** One mode's Material roles, as `androidTheme` in the tokens reads them. */
41
+ export const AndroidSchemeColors = Schema.Struct({
42
+ surface: Schema.optionalKey(Schema.String),
43
+ surfaceContainerLowest: Schema.optionalKey(Schema.String),
44
+ surfaceContainer: Schema.optionalKey(Schema.String),
45
+ surfaceContainerHigh: Schema.optionalKey(Schema.String),
46
+ onSurface: Schema.optionalKey(Schema.String),
47
+ onSurfaceVariant: Schema.optionalKey(Schema.String),
48
+ outlineVariant: Schema.optionalKey(Schema.String),
49
+ primary: Schema.optionalKey(Schema.String),
50
+ error: Schema.optionalKey(Schema.String),
51
+ });
52
+
53
+ /** The phone's dynamic color, or `null` where there's none or it's off. */
54
+ export const AndroidThemeMessage = Schema.Struct({
55
+ colors: Schema.NullOr(
56
+ Schema.Struct({ light: AndroidSchemeColors, dark: AndroidSchemeColors }),
57
+ ),
58
+ });
59
+
60
+ export interface AndroidThemeMessage extends Schema.Schema.Type<
61
+ typeof AndroidThemeMessage
62
+ > {}
63
+
64
+ /** Where push stands, as the PWA's `pushState` reports it. */
65
+ export const ShellPushState = Schema.Literals([
66
+ "unsupported",
67
+ "default",
68
+ "denied",
69
+ "subscribed",
70
+ ]);
71
+
72
+ export type ShellPushState = Schema.Schema.Type<typeof ShellPushState>;
73
+
74
+ /** What the shell reports about itself. */
75
+ export const ShellInfo = Schema.Struct({
76
+ /** True in debug builds. */
77
+ dev: Schema.Boolean,
78
+ /** The shell's version, from the synced copy. */
79
+ version: Schema.String,
80
+ });
81
+
82
+ export interface ShellInfo extends Schema.Schema.Type<typeof ShellInfo> {}
83
+
84
+ /**
85
+ * Whether the app may reach the local network: `granted` (or not gated,
86
+ * before Android 17), `denied`, or `undeclared` when the app's manifest
87
+ * lacks ACCESS_LOCAL_NETWORK.
88
+ */
89
+ export const LocalNetworkState = Schema.Literals([
90
+ "granted",
91
+ "denied",
92
+ "undeclared",
93
+ ]);
94
+
95
+ export type LocalNetworkState = Schema.Schema.Type<typeof LocalNetworkState>;
96
+
97
+ /** One mDNS service, resolved. */
98
+ export const DiscoveredService = Schema.Struct({
99
+ /** The instance name, such as `Office PC`. */
100
+ name: Schema.String,
101
+ type: Schema.String,
102
+ /** The `.local` hostname, on Android 17 and up. */
103
+ hostname: Schema.NullOr(Schema.String),
104
+ /** An address ready for a URL, IPv4 first, IPv6 in brackets. */
105
+ host: Schema.NullOr(Schema.String),
106
+ addresses: Schema.Array(Schema.String),
107
+ port: Schema.Number,
108
+ /** The TXT record's attributes, `null` for one with no value. */
109
+ txt: Schema.Record(Schema.String, Schema.NullOr(Schema.String)),
110
+ });
111
+
112
+ export interface DiscoveredService extends Schema.Schema.Type<
113
+ typeof DiscoveredService
114
+ > {}
115
+
116
+ /**
117
+ * How `discoverServices` finds them: `picker` asks the person to choose one
118
+ * in the system's picker, which grants the app that device alone; `browse`
119
+ * lists every service, asking for the local network permission first. Left
120
+ * out, it browses when it may and shows the picker otherwise.
121
+ */
122
+ export const DiscoveryMode = Schema.Literals(["picker", "browse"]);
123
+
124
+ export type DiscoveryMode = Schema.Schema.Type<typeof DiscoveryMode>;
125
+
126
+ /**
127
+ * The shell's requests, each with the schema its reply is read with. The
128
+ * Kotlin side answers the same names.
129
+ */
130
+ export const mobileRequests = {
131
+ info: ShellInfo,
132
+ /** Opens a URL in the browser or the app that handles it. */
133
+ openExternal: Schema.Boolean,
134
+ /** A system notification when the config turns them on, otherwise false. */
135
+ notify: Schema.Boolean,
136
+ /** The phone's dynamic color, when the config passes it on. */
137
+ androidTheme: AndroidThemeMessage,
138
+ /** Registers for UnifiedPush and posts the endpoint through the push contract. */
139
+ subscribePush: ShellPushState,
140
+ unsubscribePush: Schema.Boolean,
141
+ pushState: ShellPushState,
142
+ /** Asks for local network access where Android gates it. */
143
+ localNetwork: LocalNetworkState,
144
+ /** Finds mDNS services of a type, such as `_http._tcp`. */
145
+ discoverServices: Schema.Array(DiscoveredService),
146
+ /** Scans a QR code with the camera: its text, or `null` when cancelled. */
147
+ scanQr: Schema.NullOr(Schema.String),
148
+ } as const;
149
+
150
+ /** The shell's messages, each with the schema its data is read with. */
151
+ export const mobileMessages = {
152
+ notice: Notice,
153
+ /** A deep link or App Link the app was opened with. */
154
+ deepLink: DeepLink,
155
+ /** A share from another app. */
156
+ share: ShellShare,
157
+ /** The phone's dynamic color changed, such as with a new wallpaper. */
158
+ androidTheme: AndroidThemeMessage,
159
+ } as const;
160
+
161
+ /**
162
+ * The wire format. The view sends `request`; the shell answers each with a
163
+ * `reply` carrying its `id`, and sends `message` whenever it has news.
164
+ */
165
+ export const BridgeRequest = Schema.Struct({
166
+ type: Schema.Literal("request"),
167
+ id: Schema.Number,
168
+ name: Schema.String,
169
+ params: Schema.optionalKey(Schema.Json),
170
+ });
171
+
172
+ export interface BridgeRequest extends Schema.Schema.Type<
173
+ typeof BridgeRequest
174
+ > {}
175
+
176
+ export const BridgeReply = Schema.Struct({
177
+ type: Schema.Literal("reply"),
178
+ id: Schema.Number,
179
+ ok: Schema.Boolean,
180
+ value: Schema.optionalKey(Schema.Json),
181
+ error: Schema.optionalKey(Schema.String),
182
+ });
183
+
184
+ export interface BridgeReply extends Schema.Schema.Type<typeof BridgeReply> {}
185
+
186
+ export const BridgeMessage = Schema.Struct({
187
+ type: Schema.Literal("message"),
188
+ name: Schema.String,
189
+ data: Schema.optionalKey(Schema.Json),
190
+ });
191
+
192
+ export interface BridgeMessage extends Schema.Schema.Type<
193
+ typeof BridgeMessage
194
+ > {}
195
+
196
+ const decodeIncoming = Schema.decodeUnknownOption(
197
+ Schema.fromJsonString(Schema.Union([BridgeReply, BridgeMessage])),
198
+ );
199
+
200
+ /** Reads what the shell sent, or `undefined` when it isn't bridge JSON. */
201
+ export const decodeIncomingText = (
202
+ text: string,
203
+ ): BridgeReply | BridgeMessage | undefined =>
204
+ Option.getOrUndefined(decodeIncoming(text));
package/src/config.ts ADDED
@@ -0,0 +1,109 @@
1
+ /**
2
+ * An app's `mobile.config`: every default the Android shell gives a
3
+ * Groundwork app, each on unless the config turns it off, so an empty config
4
+ * gives all of them. Shared by the view and, as JSON, the Kotlin shell.
5
+ */
6
+
7
+ /** The text the shell's defaults show, for an app in another language. */
8
+ export interface MobileLabels {
9
+ /** The notification channel for the app's notices. Defaults to `Notifications`. */
10
+ readonly notifications?: string;
11
+ /** The channel for ongoing work. Defaults to `Ongoing`. */
12
+ readonly ongoing?: string;
13
+ /** Defaults to `Download finished`. */
14
+ readonly downloadFinished?: string;
15
+ }
16
+
17
+ export type ResolvedMobileLabels = Required<MobileLabels>;
18
+
19
+ export interface MobileConfig {
20
+ /**
21
+ * A hosted page to open instead of the bundled build, such as a service's
22
+ * own web UI, for an app that's a remote for a service elsewhere. Its
23
+ * origin may use the bridge. Without it the shell opens the bundled build.
24
+ */
25
+ readonly url?: string;
26
+ /**
27
+ * Origins besides the app's own whose pages may use the bridge, such as a
28
+ * paired service. The bundled app's origin is always allowed.
29
+ */
30
+ readonly origins?: readonly string[];
31
+ /** Shares from other apps, delivered as a `gw-share` event. */
32
+ readonly shares?: boolean;
33
+ /** System notifications from the view and from pushes. */
34
+ readonly notifications?: boolean;
35
+ /** Pushes through UnifiedPush, with the embedded FCM distributor as the fallback. */
36
+ readonly push?: boolean;
37
+ /** Passes the app's deep links and App Links to the view. */
38
+ readonly deepLinks?: boolean;
39
+ /** Links outside the allowed origins open in the browser. */
40
+ readonly externalLinks?: boolean;
41
+ /** Schemes besides http(s) that open outside the app. Defaults to `mailto` and `tel`. */
42
+ readonly externalSchemes?: readonly string[];
43
+ /** Back steps through the page's history before leaving the app. */
44
+ readonly back?: boolean;
45
+ /** Downloads go to the system's Downloads, with a notice when they finish. */
46
+ readonly downloads?: boolean;
47
+ /** The camera and microphone, when the page asks and the person allows it. */
48
+ readonly media?: boolean;
49
+ /** The file chooser for `<input type="file">`. */
50
+ readonly files?: boolean;
51
+ /**
52
+ * Passes the phone's dynamic color to the view, and every change.
53
+ * `pageTheme` offers it and uses it once it's picked.
54
+ */
55
+ readonly androidTheme?: boolean;
56
+ /** The WebView's dev tools through Chrome, in debug builds only. */
57
+ readonly devTools?: boolean;
58
+ /** The text the defaults show. English by default. */
59
+ readonly labels?: MobileLabels;
60
+ }
61
+
62
+ /** Every option filled in. */
63
+ export interface ResolvedMobileConfig {
64
+ readonly url: string | null;
65
+ readonly origins: readonly string[];
66
+ readonly shares: boolean;
67
+ readonly notifications: boolean;
68
+ readonly push: boolean;
69
+ readonly deepLinks: boolean;
70
+ readonly externalLinks: boolean;
71
+ readonly externalSchemes: readonly string[];
72
+ readonly back: boolean;
73
+ readonly downloads: boolean;
74
+ readonly media: boolean;
75
+ readonly files: boolean;
76
+ readonly androidTheme: boolean;
77
+ readonly devTools: boolean;
78
+ readonly labels: ResolvedMobileLabels;
79
+ }
80
+
81
+ /** Types a config in the app's `mobile.config.ts`. */
82
+ export const defineMobileConfig = (config: MobileConfig = {}): MobileConfig =>
83
+ config;
84
+
85
+ /** Fills in the defaults. */
86
+ export const resolveConfig = (
87
+ config: MobileConfig = {},
88
+ ): ResolvedMobileConfig => ({
89
+ url: config.url ?? null,
90
+ origins: config.origins ?? [],
91
+ shares: config.shares ?? true,
92
+ notifications: config.notifications ?? true,
93
+ push: config.push ?? true,
94
+ deepLinks: config.deepLinks ?? true,
95
+ externalLinks: config.externalLinks ?? true,
96
+ externalSchemes: config.externalSchemes ?? ["mailto", "tel"],
97
+ back: config.back ?? true,
98
+ downloads: config.downloads ?? true,
99
+ media: config.media ?? true,
100
+ files: config.files ?? true,
101
+ androidTheme: config.androidTheme ?? true,
102
+ devTools: config.devTools ?? true,
103
+ labels: {
104
+ notifications: "Notifications",
105
+ ongoing: "Ongoing",
106
+ downloadFinished: "Download finished",
107
+ ...config.labels,
108
+ },
109
+ });
package/src/view.ts ADDED
@@ -0,0 +1,399 @@
1
+ /**
2
+ * The view half of `@timmo001/groundwork-mobile`: connects the page to the
3
+ * Android shell over the bridge the shell injects, and falls back to the
4
+ * PWA floor's web APIs without one, so one app runs in both. Shares arrive
5
+ * as `gw-share` and deep links as `gw-deep-link` either way.
6
+ *
7
+ * import mobileConfig from "../mobile.config.ts";
8
+ * import pwaConfig from "../pwa.config.ts";
9
+ *
10
+ * const mobile = await connectMobile(mobileConfig, {
11
+ * pwa: pwaConfig,
12
+ * onShare: (share) => openDraft(share),
13
+ * onAndroidTheme: (colors) => void page.setAndroidTheme(colors),
14
+ * });
15
+ *
16
+ * // The app's own request, answered by its own Kotlin handler
17
+ * const battery = await mobile.call("battery", Schema.Number);
18
+ */
19
+ import {
20
+ connectPwa,
21
+ pushState,
22
+ subscribePush,
23
+ unsubscribePush,
24
+ type Pwa,
25
+ type PwaConfig,
26
+ type Share,
27
+ } from "@timmo001/groundwork-pwa/view";
28
+ import { Option, Schema } from "effect";
29
+
30
+ import {
31
+ AndroidThemeMessage,
32
+ bridgeObjectName,
33
+ decodeIncomingText,
34
+ DeepLink,
35
+ mobileRequests,
36
+ Notice,
37
+ ShellShare,
38
+ type BridgeMessage,
39
+ type DiscoveredService,
40
+ type DiscoveryMode,
41
+ type LocalNetworkState,
42
+ type ShellInfo,
43
+ type ShellPushState,
44
+ } from "./bridge.ts";
45
+ import {
46
+ resolveConfig,
47
+ type MobileConfig,
48
+ type ResolvedMobileConfig,
49
+ } from "./config.ts";
50
+
51
+ export * from "./bridge.ts";
52
+
53
+ export * from "./config.ts";
54
+
55
+ /** The object `WebViewCompat.addWebMessageListener` injects. */
56
+ export interface ShellObject {
57
+ readonly postMessage: (text: string) => void;
58
+ onmessage: ((event: { readonly data: string }) => void) | null;
59
+ }
60
+
61
+ declare global {
62
+ var groundworkShell: ShellObject | undefined;
63
+ }
64
+
65
+ /** Where the app subscribes to a service's pushes, in the shell or as a PWA. */
66
+ export interface MobilePushOptions {
67
+ readonly service: string;
68
+ readonly client: {
69
+ readonly id: string;
70
+ readonly name: string;
71
+ readonly platform: "web" | "android";
72
+ };
73
+ readonly headers?: Readonly<Record<string, string>>;
74
+ }
75
+
76
+ /** What `connectMobile` sets up. */
77
+ export interface ConnectMobileOptions {
78
+ /** The PWA config, for the floor's service worker, install and share target. */
79
+ readonly pwa?: PwaConfig;
80
+ /** Called with each share, from the shell or the share target. */
81
+ readonly onShare?: (share: Share) => void;
82
+ /** Called with each deep link the shell opens the app with. */
83
+ readonly onDeepLink?: (url: string) => void;
84
+ /**
85
+ * Called with the phone's dynamic color once connected and on every
86
+ * change, or `null` where there's none. Pass it to `pageTheme`'s
87
+ * `setAndroidTheme`.
88
+ */
89
+ readonly onAndroidTheme?: (colors: AndroidThemeMessage["colors"]) => void;
90
+ /** Called with a notice the shell sends, or one that can't be a notification. */
91
+ readonly onNotice?: (notice: Notice) => void;
92
+ /**
93
+ * Called with each message the app's own Kotlin sends, by name, with its
94
+ * JSON data for the app to parse with its own schema.
95
+ */
96
+ readonly onMessage?: (name: string, data: Schema.Json) => void;
97
+ }
98
+
99
+ /** The page's connection, to the shell or the PWA floor. */
100
+ export interface Mobile {
101
+ /** True inside the Android shell, false as a PWA or in a browser. */
102
+ readonly shell: boolean;
103
+ readonly config: ResolvedMobileConfig;
104
+ /** What the shell reports, or `undefined` outside it. */
105
+ readonly info: ShellInfo | undefined;
106
+ /** The PWA connection, when the app runs without the shell. */
107
+ readonly pwa: Pwa | undefined;
108
+ /**
109
+ * Calls one of the app's own Kotlin handlers and reads the reply with
110
+ * `reply`. Rejects outside the shell, or when the handler fails.
111
+ */
112
+ readonly call: <S extends Schema.ConstraintDecoder<unknown>>(
113
+ name: string,
114
+ reply: S,
115
+ params?: Schema.Json,
116
+ ) => Promise<S["Type"]>;
117
+ /** Opens a URL in the browser or the app that handles it. */
118
+ readonly openExternal: (url: string) => Promise<void>;
119
+ /** A system notification, or `onNotice` where there can't be one. */
120
+ readonly notify: (notice: Notice) => Promise<void>;
121
+ /** Subscribes to a service's pushes: UnifiedPush in the shell, Web Push outside. */
122
+ readonly subscribePush: (
123
+ options: MobilePushOptions,
124
+ ) => Promise<ShellPushState>;
125
+ readonly unsubscribePush: (options: MobilePushOptions) => Promise<void>;
126
+ readonly pushState: () => Promise<ShellPushState>;
127
+ /**
128
+ * Asks for local network access where Android gates it. Always `granted`
129
+ * outside the shell, where the browser decides.
130
+ */
131
+ readonly localNetwork: () => Promise<LocalNetworkState>;
132
+ /**
133
+ * Finds mDNS services of `type`, such as `_http._tcp`, for
134
+ * `timeoutMs` (3 seconds by default) when it browses. Rejects outside the shell.
135
+ */
136
+ readonly discoverServices: (options: {
137
+ readonly type: string;
138
+ readonly mode?: DiscoveryMode;
139
+ readonly timeoutMs?: number;
140
+ }) => Promise<readonly DiscoveredService[]>;
141
+ /**
142
+ * Scans a QR code with the shell's scanner, which needs no Google Play
143
+ * services: its text, or `undefined` when the person cancels. Rejects
144
+ * outside the shell, where `scanPairingLink` scans in the page.
145
+ */
146
+ readonly scanQr: (options?: {
147
+ readonly hint?: string;
148
+ }) => Promise<string | undefined>;
149
+ }
150
+
151
+ interface Waiting {
152
+ readonly resolve: (value: Schema.Json) => void;
153
+ readonly reject: (error: Error) => void;
154
+ }
155
+
156
+ /** The `discoverServices` request's params; a type so it stays JSON. */
157
+ type DiscoveryParams = {
158
+ type: string;
159
+ mode?: DiscoveryMode;
160
+ timeoutMs?: number;
161
+ };
162
+
163
+ /** The `scanQr` request's params. */
164
+ type ScanParams = { hint?: string };
165
+
166
+ const read = <S extends Schema.ConstraintDecoder<unknown>>(
167
+ schema: S,
168
+ value: Schema.Json,
169
+ ): S["Type"] | undefined =>
170
+ Option.getOrUndefined(Schema.decodeUnknownOption(schema)(value));
171
+
172
+ const noticeJson = Schema.encodeSync(Schema.toCodecJson(Notice));
173
+
174
+ const pushParams = ({ service, client, headers = {} }: MobilePushOptions) => ({
175
+ service,
176
+ client: { id: client.id, name: client.name, platform: client.platform },
177
+ headers: { ...headers },
178
+ });
179
+
180
+ const dispatchShare = (share: Share) =>
181
+ window.dispatchEvent(new CustomEvent("gw-share", { detail: share }));
182
+
183
+ const dispatchDeepLink = (link: DeepLink) =>
184
+ window.dispatchEvent(new CustomEvent("gw-deep-link", { detail: link }));
185
+
186
+ /** The PWA floor, for a page outside the shell. */
187
+ const connectFloor = (
188
+ config: ResolvedMobileConfig,
189
+ options: ConnectMobileOptions,
190
+ ): Mobile => {
191
+ const pwa =
192
+ options.pwa === undefined
193
+ ? undefined
194
+ : connectPwa(options.pwa, {
195
+ onShare: (share) => options.onShare?.(share),
196
+ });
197
+
198
+ const registration = async () => pwa?.worker;
199
+
200
+ return {
201
+ shell: false,
202
+ config,
203
+ info: undefined,
204
+ pwa,
205
+ call: async () => {
206
+ throw new Error(`There's no ${bridgeObjectName} outside the shell`);
207
+ },
208
+ openExternal: async (url) => {
209
+ window.open(url, "_blank", "noopener");
210
+ },
211
+ notify: async (notice) => {
212
+ const worker = await registration();
213
+
214
+ if (
215
+ !config.notifications ||
216
+ worker === undefined ||
217
+ Notification.permission !== "granted"
218
+ ) {
219
+ options.onNotice?.(notice);
220
+
221
+ return;
222
+ }
223
+
224
+ const shown: NotificationOptions = { data: { link: notice.link } };
225
+
226
+ if (notice.body !== undefined) shown.body = notice.body;
227
+
228
+ if (notice.tag !== undefined) shown.tag = notice.tag;
229
+
230
+ await worker.showNotification(notice.heading, shown);
231
+ },
232
+ subscribePush: async (push) => subscribePush(await registration(), push),
233
+ unsubscribePush: async (push) =>
234
+ unsubscribePush(await registration(), push),
235
+ pushState: async () => pushState(await registration()),
236
+ localNetwork: async () => "granted",
237
+ discoverServices: async () => {
238
+ throw new Error("Service discovery needs the Android shell");
239
+ },
240
+ scanQr: async () => {
241
+ throw new Error("The QR scanner needs the Android shell");
242
+ },
243
+ };
244
+ };
245
+
246
+ /**
247
+ * Connects to the shell when the page runs in it, or sets up the PWA floor
248
+ * with `options.pwa` when it doesn't.
249
+ */
250
+ export const connectMobile = async (
251
+ mobileConfig: MobileConfig = {},
252
+ options: ConnectMobileOptions = {},
253
+ ): Promise<Mobile> => {
254
+ const config = resolveConfig(mobileConfig);
255
+ const shell = globalThis.groundworkShell;
256
+
257
+ if (shell === undefined) return connectFloor(config, options);
258
+
259
+ const pending = new Map<number, Waiting>();
260
+ let next = 0;
261
+
262
+ const send = (name: string, params?: Schema.Json) =>
263
+ new Promise<Schema.Json>((resolve, reject) => {
264
+ next += 1;
265
+ pending.set(next, { resolve, reject });
266
+ shell.postMessage(
267
+ JSON.stringify({ type: "request", id: next, name, params }),
268
+ );
269
+ });
270
+
271
+ const call = async <S extends Schema.ConstraintDecoder<unknown>>(
272
+ name: string,
273
+ reply: S,
274
+ params?: Schema.Json,
275
+ ): Promise<S["Type"]> =>
276
+ Schema.decodeUnknownPromise(reply)(await send(name, params));
277
+
278
+ const onMessage = ({ name, data = null }: BridgeMessage) => {
279
+ switch (name) {
280
+ case "notice": {
281
+ const notice = read(Notice, data);
282
+
283
+ if (notice !== undefined) options.onNotice?.(notice);
284
+
285
+ return;
286
+ }
287
+
288
+ case "deepLink": {
289
+ const link = read(DeepLink, data);
290
+
291
+ if (link === undefined) return;
292
+
293
+ options.onDeepLink?.(link.url);
294
+ dispatchDeepLink(link);
295
+
296
+ return;
297
+ }
298
+
299
+ case "share": {
300
+ const share = read(ShellShare, data);
301
+
302
+ if (share === undefined) return;
303
+
304
+ options.onShare?.(share);
305
+ dispatchShare(share);
306
+
307
+ return;
308
+ }
309
+
310
+ case "androidTheme": {
311
+ const theme = read(AndroidThemeMessage, data);
312
+
313
+ if (theme !== undefined) options.onAndroidTheme?.(theme.colors);
314
+
315
+ return;
316
+ }
317
+
318
+ default:
319
+ options.onMessage?.(name, data);
320
+ }
321
+ };
322
+
323
+ shell.onmessage = ({ data }) => {
324
+ const incoming = decodeIncomingText(data);
325
+
326
+ if (incoming === undefined) return;
327
+
328
+ if (incoming.type === "message") {
329
+ onMessage(incoming);
330
+
331
+ return;
332
+ }
333
+
334
+ const waiting = pending.get(incoming.id);
335
+
336
+ pending.delete(incoming.id);
337
+
338
+ if (incoming.ok) waiting?.resolve(incoming.value ?? null);
339
+ else
340
+ waiting?.reject(
341
+ new Error(incoming.error ?? "The shell refused the request"),
342
+ );
343
+ };
344
+
345
+ const info = await call("info", mobileRequests.info);
346
+
347
+ if (config.androidTheme && options.onAndroidTheme !== undefined) {
348
+ const { onAndroidTheme } = options;
349
+
350
+ void call("androidTheme", mobileRequests.androidTheme).then(({ colors }) =>
351
+ onAndroidTheme(colors),
352
+ );
353
+ }
354
+
355
+ return {
356
+ shell: true,
357
+ config,
358
+ info,
359
+ pwa: undefined,
360
+ call,
361
+ openExternal: async (url) => {
362
+ await call("openExternal", mobileRequests.openExternal, { url });
363
+ },
364
+ notify: async (notice) => {
365
+ const shown =
366
+ config.notifications &&
367
+ (await call("notify", mobileRequests.notify, noticeJson(notice)));
368
+
369
+ if (!shown) options.onNotice?.(notice);
370
+ },
371
+ subscribePush: (push) =>
372
+ call("subscribePush", mobileRequests.subscribePush, pushParams(push)),
373
+ unsubscribePush: async (push) => {
374
+ await call(
375
+ "unsubscribePush",
376
+ mobileRequests.unsubscribePush,
377
+ pushParams(push),
378
+ );
379
+ },
380
+ pushState: () => call("pushState", mobileRequests.pushState),
381
+ localNetwork: () => call("localNetwork", mobileRequests.localNetwork),
382
+ discoverServices: ({ type, mode, timeoutMs }) => {
383
+ const params: DiscoveryParams = { type };
384
+
385
+ if (mode !== undefined) params["mode"] = mode;
386
+
387
+ if (timeoutMs !== undefined) params["timeoutMs"] = timeoutMs;
388
+
389
+ return call("discoverServices", mobileRequests.discoverServices, params);
390
+ },
391
+ scanQr: async ({ hint } = {}) => {
392
+ const params: ScanParams = {};
393
+
394
+ if (hint !== undefined) params["hint"] = hint;
395
+
396
+ return (await call("scanQr", mobileRequests.scanQr, params)) ?? undefined;
397
+ },
398
+ };
399
+ };