@blotch/angular-lynx-native 22.2.14 → 22.2.16

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/README.md CHANGED
@@ -17,9 +17,11 @@ An ejected project (`ios/` or `android/` with a `.angular-lynx-ejected` marker,
17
17
 
18
18
  Both are one full-screen `LynxView` running `main.lynx.bundle`; Angular Router does all navigation inside it. Bundles and assets load from inside the app, so RSpeedy's default asset prefix (`/static/...`) works with no configuration. The `LynxView` fills the screen, under the status bar and the home indicator (`"edgeToEdge": false` in angular.json puts it inside the safe area instead). Lynx's own CSS `env(safe-area-inset-*)` is 0 there: Android never sets it, and the iOS shell creates its `LynxView` before the window is key, where Lynx reads it. The runtime gives every `env(safe-area-inset-*)` the insets the shell sends instead (see `safe-area-insets.ts` in the runtime), so they follow rotation. On Android the activity still pads the page for the keyboard, and the bottom inset is 0 while it's open.
19
19
 
20
- Both send the same global props, which the runtime's services read: `platform`, `theme` (again whenever the phone switches between light and dark), `appLocale` (the phone's language as a BCP 47 tag), `isNotchScreen`, `edgeToEdge`, the safe-area insets `safeAreaTop`, `safeAreaBottom`, `safeAreaLeft` and `safeAreaRight` (again whenever they change), `osVersion` (which Lynx leaves out of the main thread's `SystemInfo`), and the accessibility settings `reduceMotion`, `reduceTransparency` (iOS only) and `increaseContrast`, again whenever the user changes one. Android 12 and later also send `dynamicColors`, the wallpaper's Material 3 color roles in light and dark (`DynamicColors.kt`), again when the user changes their wallpaper or colors. Lynx Explorer sends `theme` and `isNotchScreen` too, but no `appLocale`, `osVersion` or accessibility settings. See [`templates/android/README.md`](templates/android/README.md) for the Android shell's details.
20
+ Both send the same global props, which the runtime's services read: `platform`, `theme` (again whenever the phone switches between light and dark), `appLocale` (the phone's language as a BCP 47 tag), `appTimeZone` (its time zone's IANA name, which the `intl` build option's `Intl.DateTimeFormat` uses), `isNotchScreen`, `edgeToEdge`, the safe-area insets `safeAreaTop`, `safeAreaBottom`, `safeAreaLeft` and `safeAreaRight` (again whenever they change), `osVersion` (which Lynx leaves out of the main thread's `SystemInfo`), and the accessibility settings `reduceMotion`, `reduceTransparency` (iOS only) and `increaseContrast`, again whenever the user changes one. Android 12 and later also send `dynamicColors`, the wallpaper's Material 3 color roles in light and dark (`DynamicColors.kt`), again when the user changes their wallpaper or colors. Lynx Explorer sends `theme` and `isNotchScreen` too, but no `appLocale`, `appTimeZone`, `osVersion` or accessibility settings. See [`templates/android/README.md`](templates/android/README.md) for the Android shell's details.
21
21
 
22
- Both register the native modules the runtime's services call, which Lynx Explorer doesn't have: `AngularLynxWebAuth` (`WebAuthModule.swift`, `WebAuthModule.kt`) opens `LynxWebAuthSession`'s sign-in page, in `ASWebAuthenticationSession` on iOS and a Custom Tab on Android, and returns the URL it redirects to. `AngularLynxLocalStorage` (`LocalStorageModule.swift`, `LocalStorageModule.kt`) keeps `LynxLocalStorage`'s values in a `UserDefaults` suite and a `SharedPreferences` file of their own. `AngularLynxSecureStorage` (`SecureStorageModule.swift`, `SecureStorageModule.kt`) keeps `LynxSecureStorage`'s in the Keychain on iOS and, on Android, in `SharedPreferences`, each value encrypted with AES-GCM by an Android Keystore key, a file Auto Backup leaves out (`res/xml/backup_rules.xml`, `data_extraction_rules.xml`). Android also has `AngularLynxShell`, for the back button.
22
+ Both register the native modules the runtime's services call, which Lynx Explorer doesn't have: `AngularLynxWebAuth` (`WebAuthModule.swift`, `WebAuthModule.kt`) opens `LynxWebAuthSession`'s sign-in page, in `ASWebAuthenticationSession` on iOS and a Custom Tab on Android, and returns the URL it redirects to. `AngularLynxLocalStorage` (`LocalStorageModule.swift`, `LocalStorageModule.kt`) keeps `LynxLocalStorage`'s values in a `UserDefaults` suite and a `SharedPreferences` file of their own. `AngularLynxSecureStorage` (`SecureStorageModule.swift`, `SecureStorageModule.kt`) keeps `LynxSecureStorage`'s in the Keychain on iOS and, on Android, in `SharedPreferences`, each value encrypted with AES-GCM by an Android Keystore key, a file Auto Backup leaves out (`res/xml/backup_rules.xml`, `data_extraction_rules.xml`). `AngularLynxLinking` (`LinkingModule.swift`, `LinkingModule.kt`) opens `LynxLinking`'s links: `openURL` with `UIApplication.open` and an `ACTION_VIEW` intent, `openInApp` in `SFSafariViewController` and a Custom Tab, and `canOpenURL` with `UIApplication.canOpenURL` and `resolveActivity`, which answer only for the schemes the generator writes from angular.json's `canOpenURLSchemes` (with `http`, `https`, `mailto`, `tel` and `sms`) into Info.plist's `LSApplicationQueriesSchemes` and the manifest's `<queries>`. `AngularLynxImagePicker` (`ImagePickerModule.swift`, `ImagePickerModule.kt`) lets the person pick a photo for `LynxImagePicker`, with `PHPickerViewController` on iOS and the Photo Picker on Android, neither of which needs a permission, and calls back with it as base64, re-encoded as an upright JPEG when the app asks for a smaller one or the photo is a format such as HEIC. Android also has `AngularLynxShell`, for the back button.
23
+
24
+ `AngularLynxClipboard` (`ClipboardModule.swift`, `ClipboardModule.kt`) copies `LynxClipboard`'s text to `UIPasteboard.general` on iOS and `ClipboardManager` on Android, and reads it back.
23
25
 
24
26
  Both link Lynx's XElement library, which holds `<input>`, `<textarea>`, `<overlay>`, `<svg>`, `<blur-view>`, `<viewpager>`, `<refresh>`, the `<scroll-coordinator>` family, `<webview>` and `<video>`. Lynx's core doesn't include these, and a host that doesn't register them renders nothing for those tags (on Android, nothing after them either). XElement's AnimaX and Markdown elements are left out: the runtime doesn't support them. On iOS, `<blur-view>` is XElement's with more of UIKit in it (`App/BlurView.swift`): a `blur-material` attribute for UIKit's adaptive blur materials, which the glass components draw their design before iOS 26 on (Lynx's blur-view has only the styles from before iOS 13); Liquid Glass that materializes, dissolves and eases between effects inside a `glass-container`, where Lynx's sets its effect at once; and a `glass-effect-id` attribute that pairs two glass shapes across a change so one morphs into the other (`App/GlassTransitions.swift`).
25
27
 
@@ -2,8 +2,9 @@ import type { PlatformGenerator } from '../generate.ts';
2
2
  import type { ResolvedApp } from '../options.ts';
3
3
  /**
4
4
  * Writes the app options into the Android template: identity goes in
5
- * angular-lynx.properties (which app/build.gradle.kts reads), and permissions
6
- * and deep links go between the manifest's `angular-lynx:*` markers.
5
+ * angular-lynx.properties (which app/build.gradle.kts reads), and permissions,
6
+ * deep links and the apps canOpenURL can see go between the manifest's
7
+ * `angular-lynx:*` markers.
7
8
  */
8
9
  export declare const androidGenerator: PlatformGenerator;
9
10
  /**
@@ -15,6 +16,12 @@ export declare const propertyValue: (value: string) => string;
15
16
  export declare const properties: (app: ResolvedApp) => string;
16
17
  export declare const permissionEntries: (app: ResolvedApp) => string;
17
18
  export declare const deepLinkEntries: (app: ResolvedApp) => string;
19
+ /**
20
+ * The apps LinkingModule's canOpenURL can see from Android 11: those that
21
+ * open a URL with one of the schemes. resolveActivity() finds no other app,
22
+ * though startActivity() still opens one.
23
+ */
24
+ export declare const queriesEntries: (app: ResolvedApp) => string;
18
25
  /** The Android SDK, from the environment or the Android Studio default. */
19
26
  export declare const findAndroidSdk: (env?: NodeJS.ProcessEnv) => string | undefined;
20
27
  //# sourceMappingURL=project.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"project.d.ts","sourceRoot":"","sources":["../../src/android/project.ts"],"names":[],"mappings":"AAIA,OAAO,KAAK,EAAE,iBAAiB,EAAE,MAAM,gBAAgB,CAAC;AACxD,OAAO,KAAK,EAAe,WAAW,EAAE,MAAM,eAAe,CAAC;AAY9D;;;;GAIG;AACH,eAAO,MAAM,gBAAgB,EAAE,iBAc9B,CAAC;AAEF;;;;GAIG;AACH,eAAO,MAAM,aAAa,GAAI,OAAO,MAAM,WAOtC,CAAC;AAEN,eAAO,MAAM,UAAU,GAAI,KAAK,WAAW,KAAG,MAYhC,CAAC;AAEf,eAAO,MAAM,iBAAiB,GAAI,KAAK,WAAW,KAAG,MAiBpD,CAAC;AAEF,eAAO,MAAM,eAAe,GAAI,KAAK,WAAW,KAAG,MAYjC,CAAC;AAEnB,2EAA2E;AAC3E,eAAO,MAAM,cAAc,GACzB,MAAK,MAAM,CAAC,UAAwB,KACnC,MAAM,GAAG,SAaX,CAAC"}
1
+ {"version":3,"file":"project.d.ts","sourceRoot":"","sources":["../../src/android/project.ts"],"names":[],"mappings":"AAIA,OAAO,KAAK,EAAE,iBAAiB,EAAE,MAAM,gBAAgB,CAAC;AACxD,OAAO,KAAK,EAAe,WAAW,EAAE,MAAM,eAAe,CAAC;AAY9D;;;;;GAKG;AACH,eAAO,MAAM,gBAAgB,EAAE,iBAe9B,CAAC;AAEF;;;;GAIG;AACH,eAAO,MAAM,aAAa,GAAI,OAAO,MAAM,WAOtC,CAAC;AAEN,eAAO,MAAM,UAAU,GAAI,KAAK,WAAW,KAAG,MAYhC,CAAC;AAEf,eAAO,MAAM,iBAAiB,GAAI,KAAK,WAAW,KAAG,MAiBpD,CAAC;AAEF,eAAO,MAAM,eAAe,GAAI,KAAK,WAAW,KAAG,MAYjC,CAAC;AAEnB;;;;GAIG;AACH,eAAO,MAAM,cAAc,GAAI,KAAK,WAAW,KAAG,MAUpC,CAAC;AAEf,2EAA2E;AAC3E,eAAO,MAAM,cAAc,GACzB,MAAK,MAAM,CAAC,UAAwB,KACnC,MAAM,GAAG,SAaX,CAAC"}
@@ -11,8 +11,9 @@ const SCREEN_ORIENTATIONS = {
11
11
  };
12
12
  /**
13
13
  * Writes the app options into the Android template: identity goes in
14
- * angular-lynx.properties (which app/build.gradle.kts reads), and permissions
15
- * and deep links go between the manifest's `angular-lynx:*` markers.
14
+ * angular-lynx.properties (which app/build.gradle.kts reads), and permissions,
15
+ * deep links and the apps canOpenURL can see go between the manifest's
16
+ * `angular-lynx:*` markers.
16
17
  */
17
18
  export const androidGenerator = {
18
19
  configure: (dir, app) => {
@@ -24,6 +25,7 @@ export const androidGenerator = {
24
25
  let manifest = readFileSync(manifestPath, 'utf8');
25
26
  manifest = replaceMarker(manifest, 'permissions', permissionEntries(app));
26
27
  manifest = replaceMarker(manifest, 'deep-links', deepLinkEntries(app));
28
+ manifest = replaceMarker(manifest, 'queries', queriesEntries(app));
27
29
  writeFileSync(manifestPath, manifest);
28
30
  },
29
31
  bundleDir: (dir) => path.join(dir, 'app/src/main/assets'),
@@ -70,6 +72,21 @@ export const deepLinkEntries = (app) => app.deepLinkSchemes.length === 0
70
72
  ...app.deepLinkSchemes.map((scheme) => ` <data android:scheme="${escapeXml(scheme)}" />`),
71
73
  '</intent-filter>',
72
74
  ].join('\n');
75
+ /**
76
+ * The apps LinkingModule's canOpenURL can see from Android 11: those that
77
+ * open a URL with one of the schemes. resolveActivity() finds no other app,
78
+ * though startActivity() still opens one.
79
+ */
80
+ export const queriesEntries = (app) => [
81
+ '<queries>',
82
+ ...app.canOpenURLSchemes.flatMap((scheme) => [
83
+ ' <intent>',
84
+ ' <action android:name="android.intent.action.VIEW" />',
85
+ ` <data android:scheme="${escapeXml(scheme)}" />`,
86
+ ' </intent>',
87
+ ]),
88
+ '</queries>',
89
+ ].join('\n');
73
90
  /** The Android SDK, from the environment or the Android Studio default. */
74
91
  export const findAndroidSdk = (env = process.env) => {
75
92
  const candidates = [
@@ -1 +1 @@
1
- {"version":3,"file":"project.d.ts","sourceRoot":"","sources":["../../src/ios/project.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,EAAE,iBAAiB,EAAE,MAAM,gBAAgB,CAAC;AAExD,OAAO,KAAK,EAAe,WAAW,EAAE,MAAM,eAAe,CAAC;AAiB9D;;;;GAIG;AACH,eAAO,MAAM,YAAY,EAAE,iBA6B1B,CAAC;AAQF,eAAO,MAAM,QAAQ,GAAI,KAAK,WAAW,KAAG,MAY9B,CAAC;AAEf,eAAO,MAAM,gBAAgB,GAAI,KAAK,WAAW,KAAG,MA2CnD,CAAC"}
1
+ {"version":3,"file":"project.d.ts","sourceRoot":"","sources":["../../src/ios/project.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,EAAE,iBAAiB,EAAE,MAAM,gBAAgB,CAAC;AAExD,OAAO,KAAK,EAAe,WAAW,EAAE,MAAM,eAAe,CAAC;AAiB9D;;;;GAIG;AACH,eAAO,MAAM,YAAY,EAAE,iBA6B1B,CAAC;AAQF,eAAO,MAAM,QAAQ,GAAI,KAAK,WAAW,KAAG,MAY9B,CAAC;AAEf,eAAO,MAAM,gBAAgB,GAAI,KAAK,WAAW,KAAG,MA+CnD,CAAC"}
@@ -69,6 +69,9 @@ export const infoPlistEntries = (app) => {
69
69
  lines.push(`<key>${key}</key>`, `<string>${escapeXml(reason)}</string>`);
70
70
  }
71
71
  }
72
+ // The schemes LinkingModule's canOpenURL can ask about: iOS answers false
73
+ // for any other. UIApplication.open needs none of them.
74
+ array('LSApplicationQueriesSchemes', app.canOpenURLSchemes);
72
75
  if (app.deepLinkSchemes.length > 0) {
73
76
  lines.push('<key>CFBundleURLTypes</key>', '<array>', '\t<dict>', '\t\t<key>CFBundleURLName</key>', `\t\t<string>${escapeXml(app.id)}</string>`, '\t\t<key>CFBundleURLSchemes</key>', '\t\t<array>', ...app.deepLinkSchemes.map((scheme) => `\t\t\t<string>${escapeXml(scheme)}</string>`), '\t\t</array>', '\t</dict>', '</array>');
74
77
  }
package/dist/options.d.ts CHANGED
@@ -30,6 +30,14 @@ export type NativeAppOptions = {
30
30
  readonly permissions?: Partial<Record<Permission, string>>;
31
31
  /** Custom URL schemes that open the app, e.g. `["myapp"]`. */
32
32
  readonly deepLinkSchemes?: readonly string[];
33
+ /**
34
+ * Other apps' URL schemes `LynxLinking.canOpenURL()` can ask about, e.g.
35
+ * `["whatsapp", "instagram"]`. iOS answers only for the schemes in
36
+ * Info.plist's LSApplicationQueriesSchemes, and Android 11 and later only
37
+ * for the apps the manifest's `<queries>` asks about. `http`, `https`,
38
+ * `mailto`, `tel` and `sms` are always there.
39
+ */
40
+ readonly canOpenURLSchemes?: readonly string[];
33
41
  /** A 1024×1024 PNG without transparency, relative to the project root. */
34
42
  readonly icon?: string;
35
43
  readonly ios?: IosOptions;
@@ -73,6 +81,11 @@ export type ResolvedApp = {
73
81
  readonly edgeToEdge: boolean;
74
82
  readonly permissions: Partial<Record<Permission, string>>;
75
83
  readonly deepLinkSchemes: readonly string[];
84
+ /**
85
+ * {@link NativeAppOptions.canOpenURLSchemes} after
86
+ * {@link ALWAYS_QUERIED_SCHEMES}, in lowercase, each once.
87
+ */
88
+ readonly canOpenURLSchemes: readonly string[];
76
89
  readonly icon?: string;
77
90
  /** `MyApp`: the iOS product (and so .app/.ipa) name. */
78
91
  readonly productName: string;
@@ -83,6 +96,11 @@ export type ResolvedApp = {
83
96
  };
84
97
  export declare class NativeConfigError extends Error {
85
98
  }
99
+ /**
100
+ * The schemes `LynxLinking.canOpenURL()` can always ask about: the web, mail,
101
+ * the phone and messages, which most apps link to.
102
+ */
103
+ export declare const ALWAYS_QUERIED_SCHEMES: readonly string[];
86
104
  /**
87
105
  * Applies defaults and validates the options, so the generators never see a
88
106
  * value that would produce a project Xcode or Gradle rejects later with a
@@ -1 +1 @@
1
- {"version":3,"file":"options.d.ts","sourceRoot":"","sources":["../src/options.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;GAUG;AACH,MAAM,MAAM,gBAAgB,GAAG;IAC7B,6DAA6D;IAC7D,QAAQ,CAAC,OAAO,CAAC,EAAE,MAAM,CAAC;IAC1B,yEAAyE;IACzE,QAAQ,CAAC,KAAK,CAAC,EAAE,MAAM,CAAC;IACxB,0EAA0E;IAC1E,QAAQ,CAAC,OAAO,CAAC,EAAE,MAAM,CAAC;IAC1B,8DAA8D;IAC9D,QAAQ,CAAC,WAAW,CAAC,EAAE,MAAM,CAAC;IAC9B,QAAQ,CAAC,WAAW,CAAC,EAAE,WAAW,CAAC;IACnC;;;;;OAKG;IACH,QAAQ,CAAC,UAAU,CAAC,EAAE,OAAO,CAAC;IAC9B,uEAAuE;IACvE,QAAQ,CAAC,WAAW,CAAC,EAAE,OAAO,CAAC,MAAM,CAAC,UAAU,EAAE,MAAM,CAAC,CAAC,CAAC;IAC3D,8DAA8D;IAC9D,QAAQ,CAAC,eAAe,CAAC,EAAE,SAAS,MAAM,EAAE,CAAC;IAC7C,0EAA0E;IAC1E,QAAQ,CAAC,IAAI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6 +11,19 @@ const VERSION = /^\d+(\.\d+){0,2}$/;
11
11
  const SCHEME = /^[A-Za-z][A-Za-z0-9+.-]*$/;
12
12
  /** Google Play's maximum versionCode. */
13
13
  const MAX_BUILD_NUMBER = 2_100_000_000;
14
+ /**
15
+ * The schemes `LynxLinking.canOpenURL()` can always ask about: the web, mail,
16
+ * the phone and messages, which most apps link to.
17
+ */
18
+ export const ALWAYS_QUERIED_SCHEMES = [
19
+ 'http',
20
+ 'https',
21
+ 'mailto',
22
+ 'tel',
23
+ 'sms',
24
+ ];
25
+ /** The most schemes iOS reads from LSApplicationQueriesSchemes. */
26
+ const MAX_QUERIED_SCHEMES = 50;
14
27
  const PERMISSIONS = [
15
28
  'camera',
16
29
  'microphone',
@@ -64,6 +77,19 @@ export const resolveAppOptions = (rawOptions, defaults) => {
64
77
  throw new NativeConfigError(`deepLinkSchemes entry "${scheme}" is not a valid URL scheme.`);
65
78
  }
66
79
  }
80
+ const userQueriedSchemes = options.canOpenURLSchemes ?? [];
81
+ for (const scheme of userQueriedSchemes) {
82
+ if (!SCHEME.test(scheme)) {
83
+ throw new NativeConfigError(`canOpenURLSchemes entry "${scheme}" is not a valid URL scheme. Give the scheme alone, without "://", e.g. "whatsapp".`);
84
+ }
85
+ }
86
+ // Schemes are case-insensitive, so "WhatsApp" and "whatsapp" are one.
87
+ const canOpenURLSchemes = [
88
+ ...new Set([...ALWAYS_QUERIED_SCHEMES, ...userQueriedSchemes].map((scheme) => scheme.toLowerCase())),
89
+ ];
90
+ if (canOpenURLSchemes.length > MAX_QUERIED_SCHEMES) {
91
+ throw new NativeConfigError(`canOpenURLSchemes lists ${canOpenURLSchemes.length} schemes with the ${ALWAYS_QUERIED_SCHEMES.length} always there (${ALWAYS_QUERIED_SCHEMES.join(', ')}). iOS reads no more than ${MAX_QUERIED_SCHEMES}.`);
92
+ }
67
93
  const productName = name.replace(/[^A-Za-z0-9]/g, '') || 'App';
68
94
  const artifactName = name
69
95
  .toLowerCase()
@@ -78,6 +104,7 @@ export const resolveAppOptions = (rawOptions, defaults) => {
78
104
  edgeToEdge: options.edgeToEdge ?? true,
79
105
  permissions,
80
106
  deepLinkSchemes,
107
+ canOpenURLSchemes,
81
108
  icon: options.icon,
82
109
  productName,
83
110
  artifactName,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@blotch/angular-lynx-native",
3
- "version": "22.2.14",
3
+ "version": "22.2.16",
4
4
  "description": "Builds AngularLynx apps into iOS and Android binaries",
5
5
  "homepage": "https://github.com/Blotch-Smart-Frames/AngularLynx#readme",
6
6
  "bugs": {
@@ -38,6 +38,16 @@ Back is off by default, so it leaves the app like any root screen. The runtime t
38
38
 
39
39
  `NativeModules.AngularLynxWebAuth.start(request, callback)` (`WebAuthModule.kt`, behind the runtime's `LynxWebAuthSession`) opens `request.url` in a Custom Tab (`androidx.browser`). The page's redirect to `request.callbackScheme` comes back as a deep link: the activity is `singleTask`, so the intent reaches the open one in `onNewIntent`, which hands the URL to the callback, and starting it closes the Custom Tab above it. That's why the scheme has to be in the app's `deepLinkSchemes`. Android says nothing when a Custom Tab is closed, so the activity resuming with a session still open, after having gone behind the tab, means the person canceled. iOS's `WebAuthModule.swift` reports the same results through `ASWebAuthenticationSession`.
40
40
 
41
+ ## Links
42
+
43
+ `NativeModules.AngularLynxLinking` (`LinkingModule.kt`, behind the runtime's `LynxLinking`) opens links outside the app. `MainActivity` registers it with itself as the param, since the module starts activities from it and watches its lifecycle.
44
+
45
+ - **`openURL(url, callback)`** starts an `ACTION_VIEW` intent, which the browser, the mail app or the app that claims the URL opens, and calls back with `{}`, or with `{ error, message }` when nothing does.
46
+ - **`openInApp(url, options, callback)`** opens an http(s) URL in a Custom Tab, with `options.toolbarColor` as its toolbar color. Android says nothing when a Custom Tab closes, so the module watches the activity's lifecycle and calls back when it resumes after pausing for the tab: the person closed the tab or came back to the app another way. It doesn't touch `WebAuthModule`'s session, which `MainActivity` tracks on its own.
47
+ - **`canOpenURL(url, callback)`** asks `resolveActivity`, which from Android 11 sees only the apps the manifest's `<queries>` names: one `VIEW` intent per scheme, which the generator writes between the `angular-lynx:queries` markers from angular.json's `canOpenURLSchemes`, after `http`, `https`, `mailto`, `tel` and `sms`. Starting an activity needs no `<queries>`.
48
+
49
+ iOS's `LinkingModule.swift` does the same with `UIApplication.open`, `SFSafariViewController` and `UIApplication.canOpenURL`, which answers only for the schemes in Info.plist's `LSApplicationQueriesSchemes`.
50
+
41
51
  ## Storage
42
52
 
43
53
  `NativeModules.AngularLynxLocalStorage` and `NativeModules.AngularLynxSecureStorage` (`LocalStorageModule.kt` and `SecureStorageModule.kt`, behind the runtime's `LynxLocalStorage` and `LynxSecureStorage`) keep string values, which the runtime stores as JSON, each in a `SharedPreferences` file of its own. Each method calls back once with `{ value }`, `{}` or `{ error }`.
@@ -47,6 +57,16 @@ Back is off by default, so it leaves the app like any root screen. The runtime t
47
57
 
48
58
  iOS's `LocalStorageModule.swift` uses a `UserDefaults` suite and `SecureStorageModule.swift` the Keychain, readable after the first unlock and never moved to another device.
49
59
 
60
+ ## Clipboard
61
+
62
+ `NativeModules.AngularLynxClipboard` (`ClipboardModule.kt`, behind the runtime's `LynxClipboard`) copies text to `ClipboardManager` as a plain-text clip and reads the first item back as text, both on the main thread. `setString` calls back once with `{}` or `{ error }`, `getString` with `{ value }`, `""` when the clipboard holds no text. Android 13 and later show the copied text in a panel of their own and have TalkBack say "Text copied", so the runtime's `LynxClipboard.confirmsCopies` tells the app not to confirm it again. Android 10 and later let only the app in front read the clipboard, and Android 12 and later tell the person when it does. iOS's `ClipboardModule.swift` uses `UIPasteboard.general`.
63
+
64
+ ## Photo picker
65
+
66
+ `NativeModules.AngularLynxImagePicker.pick(options, callback)` (`ImagePickerModule.kt`, behind the runtime's `LynxImagePicker`) has the activity open the Photo Picker (`ActivityResultContracts.PickVisualMedia`, images only), which needs no permission. `MainActivity` registers the launcher as a property, so it's registered as the activity is created, before it starts, as `ActivityResult` launchers must be; the module gets the activity's `ImagePickerModule.Host` as its param. A manifest entry (`com.google.android.gms.metadata.ModuleDependencies`) lets Google Play services install the picker on Android 10 and older, which otherwise open the document picker.
67
+
68
+ The module reads the picked photo on a background thread and calls back once with `{ base64, name, type }`, `{ canceled: true }` or `{ error, message }`. A JPEG, PNG, GIF or WebP goes back as it is unless the app passed `maxDimension` or `quality`; otherwise it's decoded with `BitmapFactory` at the smallest power-of-two reduction that covers the target, scaled, turned upright by its EXIF orientation (AndroidX `ExifInterface`, since `BitmapFactory` ignores it), drawn over white if it has transparency and compressed as a JPEG. iOS's `ImagePickerModule.swift` does the same with `PHPickerViewController` and ImageIO.
69
+
50
70
  ## Canvas and WebGL
51
71
 
52
72
  `<canvas>` (issue #211) is the shell's: `CanvasUI.kt`, a `TextureView` registered as the `canvas` element (`addBehavior(CanvasUI.behavior())`), and `WebGLModule.kt`, the `AngularLynxWebGL` module the runtime's WebGL2 context sends its calls to. `MainActivity` turns on main-thread modules (`setEnableMTSModule(true)`), so the runtime, which runs on Lynx's main thread, calls the module synchronously with `lynx.module(name)`, on the UI thread. Each context (`WebGLContext.kt`) is an EGL context with OpenGL ES 3.0 and an offscreen default framebuffer, which `present` copies into the canvas's surface; `WebGLOps.kt` is generated from the runtime's opcodes (`npm run generate:webgl-ops -w packages/native`). `AssetsModule.kt` (`AngularLynxAssets`) reads a file the app bundles for the main thread's `fetch`, which has no page URL to resolve `/static/...` against.
@@ -66,7 +86,8 @@ Android's GLES has no 2D uploads from a `PIXEL_UNPACK_BUFFER` and no `glGetVerte
66
86
  Pinned in `app/build.gradle.kts`, `build.gradle.kts` and `gradle/wrapper/gradle-wrapper.properties`:
67
87
 
68
88
  - Lynx 4.1.0 and PrimJS 4.1.1 (Maven Central), Fresco 2.3.0 (the version Lynx's image service is built against), OkHttp 4.12.
69
- - `androidx.browser` 1.8.0, for the Custom Tabs `WebAuthModule` opens sign-in pages in.
89
+ - `androidx.browser` 1.8.0, for the Custom Tabs `WebAuthModule` opens sign-in pages in and `LinkingModule` opens `openInApp()`'s pages in.
90
+ - `androidx.exifinterface` 1.4.2, for the orientation `ImagePickerModule` turns a re-encoded photo by.
70
91
  - Lynx's XElement 4.1.0 (`<input>`, `<textarea>`, `<overlay>`, `<svg>`, `<blur-view>`, `<viewpager>`, `<refresh>`, the `<scroll-coordinator>` family, `<webview>`, `<video>`), without its AnimaX and Markdown modules, which the runtime doesn't support. `MainActivity` registers the elements with `XElementBehaviors`. XElement depends on appcompat and material 1.0.0, whose vectordrawable libraries share a namespace that AGP 9 rejects, so appcompat 1.7.1 and material 1.12.0 are pinned.
71
92
  - AGP 9.4.1 with its built-in Kotlin, Gradle 9.6.1 (AGP 9.4's minimum), JDK 17 or newer.
72
93
  - `compileSdk` and `targetSdk` 36, `minSdk` 24. Google Play raises its target API requirement every August; bump `targetSdk` with it.
@@ -122,8 +122,14 @@ android {
122
122
  dependencies {
123
123
  implementation("androidx.activity:activity-ktx:1.10.1")
124
124
  implementation("androidx.core:core-ktx:1.16.0")
125
- // Custom Tabs, which WebAuthModule opens sign-in pages in.
125
+ // Custom Tabs, which WebAuthModule opens sign-in pages in, and
126
+ // LinkingModule the pages of openInApp().
126
127
  implementation("androidx.browser:browser:1.8.0")
128
+ // EXIF orientation, which ImagePickerModule applies to a photo it
129
+ // re-encodes, since BitmapFactory ignores it. The AndroidX one reads it
130
+ // from every format the Photo Picker hands back, the same way on every
131
+ // Android version.
132
+ implementation("androidx.exifinterface:exifinterface:1.4.2")
127
133
 
128
134
  // The Lynx engine, its JavaScript runtime (PrimJS) and its JS SDK.
129
135
  implementation("org.lynxsdk.lynx:lynx:$lynxVersion")
@@ -6,6 +6,12 @@
6
6
  <uses-permission android:name="android.permission.INTERNET" />
7
7
  <!-- angular-lynx:permissions -->
8
8
 
9
+ <!--
10
+ The apps LynxLinking.canOpenURL() can see from Android 11: those that
11
+ open angular.json's canOpenURLSchemes (LinkingModule).
12
+ -->
13
+ <!-- angular-lynx:queries -->
14
+
9
15
  <!--
10
16
  Auto Backup leaves out LynxSecureStorage's file (SecureStorageModule):
11
17
  dataExtractionRules from Android 12, fullBackupContent before.
@@ -40,6 +46,22 @@
40
46
  </intent-filter>
41
47
  <!-- angular-lynx:deep-links -->
42
48
  </activity>
49
+
50
+ <!--
51
+ Lets Google Play services install the Photo Picker that
52
+ LynxImagePicker opens (ImagePickerModule) on Android 10 and older,
53
+ which don't have one. Without it, they open the document picker.
54
+ -->
55
+ <service
56
+ android:name="com.google.android.gms.metadata.ModuleDependencies"
57
+ android:enabled="false"
58
+ android:exported="false"
59
+ tools:ignore="MissingClass">
60
+ <intent-filter>
61
+ <action android:name="com.google.android.gms.metadata.MODULE_DEPENDENCIES" />
62
+ </intent-filter>
63
+ <meta-data android:name="photopicker_activity:0:required" android:value="" />
64
+ </service>
43
65
  </application>
44
66
 
45
67
  </manifest>
@@ -0,0 +1,80 @@
1
+ package dev.angularlynx.shell
2
+
3
+ import android.content.ClipData
4
+ import android.content.ClipboardManager
5
+ import android.content.Context
6
+ import android.os.Handler
7
+ import android.os.Looper
8
+ import com.lynx.jsbridge.LynxMethod
9
+ import com.lynx.jsbridge.LynxModule
10
+ import com.lynx.react.bridge.Callback
11
+ import com.lynx.react.bridge.JavaOnlyMap
12
+
13
+ /**
14
+ * The native module behind the runtime's `LynxClipboard`, which calls it as
15
+ * `NativeModules.AngularLynxClipboard` (from the background thread, where
16
+ * NativeModules lives).
17
+ *
18
+ * Text goes on the system clipboard as a plain-text clip. Each method calls
19
+ * back once: `setString` with `{}` or `{ error }`, `getString` with
20
+ * `{ value }`, as the iOS module does.
21
+ */
22
+ class ClipboardModule(context: Context, param: Any?) : LynxModule(context, param) {
23
+ private val appContext = context.applicationContext
24
+ private val main = Handler(Looper.getMainLooper())
25
+
26
+ private val clipboard: ClipboardManager
27
+ get() = appContext.getSystemService(ClipboardManager::class.java)
28
+
29
+ // Lynx calls modules off the main thread, and the clipboard belongs to
30
+ // the UI: its calls run on the main thread, as the system's own text
31
+ // fields make them.
32
+ //
33
+ // Android 13 and later show the copied text in a panel of their own, and
34
+ // TalkBack says "Text copied": the runtime's `confirmsCopies` tells the
35
+ // app so, which then needn't confirm it again.
36
+ @LynxMethod
37
+ fun setString(text: String, callback: Callback) {
38
+ main.post {
39
+ try {
40
+ // No label: it describes the clip to whoever pastes it, and the
41
+ // text is all the app has to say.
42
+ clipboard.setPrimaryClip(ClipData.newPlainText(null, text))
43
+ callback.invoke(JavaOnlyMap())
44
+ } catch (error: RuntimeException) {
45
+ // A clip larger than the system's binder buffer (about 1 MB)
46
+ // fails to reach the clipboard service.
47
+ callback.invoke(
48
+ JavaOnlyMap.from(
49
+ mapOf("error" to (error.message ?: "The text could not be copied.")),
50
+ ),
51
+ )
52
+ }
53
+ }
54
+ }
55
+
56
+ /**
57
+ * The clipboard's text, or `""` when it holds none. Android 10 and later
58
+ * let only the app in front read it, and Android 12 and later tell the
59
+ * person that the app pasted.
60
+ */
61
+ @LynxMethod
62
+ fun getString(callback: Callback) {
63
+ main.post {
64
+ val clip = clipboard.primaryClip
65
+ val text =
66
+ if (clip != null && clip.itemCount > 0) {
67
+ // Turns a URI or an intent clip into text too, as pasting
68
+ // into a text field does.
69
+ clip.getItemAt(0).coerceToText(appContext)?.toString() ?: ""
70
+ } else {
71
+ ""
72
+ }
73
+ callback.invoke(JavaOnlyMap.from(mapOf("value" to text)))
74
+ }
75
+ }
76
+
77
+ companion object {
78
+ const val NAME = "AngularLynxClipboard"
79
+ }
80
+ }
@@ -0,0 +1,219 @@
1
+ package dev.angularlynx.shell
2
+
3
+ import android.content.Context
4
+ import android.graphics.Bitmap
5
+ import android.graphics.BitmapFactory
6
+ import android.graphics.Canvas
7
+ import android.graphics.Color
8
+ import android.graphics.Matrix
9
+ import android.net.Uri
10
+ import android.os.Handler
11
+ import android.os.Looper
12
+ import android.provider.OpenableColumns
13
+ import android.util.Base64
14
+ import androidx.exifinterface.media.ExifInterface
15
+ import com.lynx.jsbridge.LynxMethod
16
+ import com.lynx.jsbridge.LynxModule
17
+ import com.lynx.react.bridge.Callback
18
+ import com.lynx.react.bridge.JavaOnlyMap
19
+ import com.lynx.react.bridge.ReadableMap
20
+ import java.io.ByteArrayOutputStream
21
+ import java.io.IOException
22
+ import java.util.concurrent.Executors
23
+ import kotlin.math.max
24
+ import kotlin.math.min
25
+ import kotlin.math.roundToInt
26
+
27
+ /**
28
+ * The native module behind the runtime's `LynxImagePicker`, which calls it as
29
+ * `NativeModules.AngularLynxImagePicker` (from the background thread, where
30
+ * NativeModules lives).
31
+ *
32
+ * Lynx has no `<input type="file">`. The activity opens Android's Photo
33
+ * Picker instead (`PickVisualMedia`), which needs no permission: the app reads
34
+ * only the photo picked. Where a phone has no Photo Picker, Android opens its
35
+ * document picker.
36
+ *
37
+ * The image goes back as base64, since the module's callback and the
38
+ * runtime's relay to the main thread carry only what JSON can. Scaling it
39
+ * down here first, with `maxDimension`, keeps that small: a 12-megapixel
40
+ * photo is several megabytes, a 1024-pixel one a few hundred kilobytes.
41
+ */
42
+ class ImagePickerModule(context: Context, param: Any?) : LynxModule(context, param) {
43
+ private val host = param as Host
44
+ private val main = Handler(Looper.getMainLooper())
45
+
46
+ interface Host {
47
+ /**
48
+ * Opens the Photo Picker and calls [done] once with the picked image,
49
+ * or with null when the person closes it. Returns false, without
50
+ * opening it, when it's already open.
51
+ */
52
+ fun pickImage(done: (Uri?) -> Unit): Boolean
53
+ }
54
+
55
+ /**
56
+ * Opens the picker and calls back once with `{ base64, name, type }`,
57
+ * `{ canceled: true }` when the person closes it, or
58
+ * `{ error: "failed", message }`, as the iOS module does.
59
+ */
60
+ @LynxMethod
61
+ fun pick(options: ReadableMap, callback: Callback) {
62
+ // JavaScript numbers can arrive as either, so both are read as doubles.
63
+ val maxDimension = if (options.hasKey("maxDimension")) options.getDouble("maxDimension").toInt() else null
64
+ val quality = if (options.hasKey("quality")) options.getDouble("quality") else null
65
+ // Lynx calls modules off the main thread, and the activity launches
66
+ // the picker.
67
+ main.post {
68
+ val opened = host.pickImage { uri ->
69
+ if (uri == null) {
70
+ callback.invoke(JavaOnlyMap.from(mapOf("canceled" to true)))
71
+ } else {
72
+ // Decoding a 12-megapixel photo takes a moment: off the
73
+ // main thread.
74
+ worker.execute { callback.invoke(prepare(uri, maxDimension, quality)) }
75
+ }
76
+ }
77
+ if (!opened) callback.invoke(failed("A picker is already open."))
78
+ }
79
+ }
80
+
81
+ /**
82
+ * The callback's answer for the picked image: as it was picked, or
83
+ * re-encoded as a JPEG.
84
+ */
85
+ private fun prepare(uri: Uri, maxDimension: Int?, quality: Double?): JavaOnlyMap {
86
+ val resolver = mContext.contentResolver
87
+ val bytes = try {
88
+ resolver.openInputStream(uri)?.use { it.readBytes() }
89
+ } catch (_: IOException) {
90
+ null
91
+ } catch (_: SecurityException) {
92
+ null
93
+ } ?: return failed("The picked image couldn't be read.")
94
+ val type = resolver.getType(uri) ?: "application/octet-stream"
95
+ val name = displayName(uri) ?: "image"
96
+ if (maxDimension == null && quality == null && type in PORTABLE_TYPES) {
97
+ return answer(bytes, name, type)
98
+ }
99
+ val jpeg = try {
100
+ toJpeg(bytes, maxDimension, quality ?: DEFAULT_QUALITY)
101
+ } catch (_: OutOfMemoryError) {
102
+ null
103
+ } ?: return failed("The picked image couldn't be decoded.")
104
+ return answer(jpeg, withExtension(name, "jpg"), "image/jpeg")
105
+ }
106
+
107
+ /** The file name the picker gives the image, such as `PXL_20261106.jpg`. */
108
+ private fun displayName(uri: Uri): String? =
109
+ try {
110
+ mContext.contentResolver.query(uri, arrayOf(OpenableColumns.DISPLAY_NAME), null, null, null)
111
+ ?.use { cursor -> if (cursor.moveToFirst()) cursor.getString(0) else null }
112
+ } catch (_: RuntimeException) {
113
+ null
114
+ }
115
+
116
+ private fun answer(bytes: ByteArray, name: String, type: String) =
117
+ JavaOnlyMap.from(
118
+ mapOf("base64" to Base64.encodeToString(bytes, Base64.NO_WRAP), "name" to name, "type" to type),
119
+ )
120
+
121
+ private fun failed(message: String) =
122
+ JavaOnlyMap.from(mapOf("error" to "failed", "message" to message))
123
+
124
+ companion object {
125
+ const val NAME = "AngularLynxImagePicker"
126
+
127
+ /** What a re-encoded image gets when the app doesn't choose a quality. */
128
+ private const val DEFAULT_QUALITY = 0.9
129
+
130
+ /**
131
+ * The formats other platforms can show, which go back as they were
132
+ * picked unless the app asks for a smaller or re-compressed image.
133
+ * Anything else, such as HEIC photos, is re-encoded as a JPEG.
134
+ */
135
+ private val PORTABLE_TYPES = setOf("image/jpeg", "image/png", "image/gif", "image/webp")
136
+
137
+ /** One thread for decoding, so two picks can't hold two photos at once. */
138
+ private val worker = Executors.newSingleThreadExecutor()
139
+
140
+ /** `photo.heic` → `photo.jpg`. */
141
+ private fun withExtension(name: String, extension: String): String {
142
+ val dot = name.lastIndexOf('.')
143
+ return "${if (dot > 0) name.substring(0, dot) else name}.$extension"
144
+ }
145
+
146
+ /**
147
+ * The image as a JPEG: upright, whichever way the camera stored it
148
+ * (BitmapFactory ignores it), no larger than [maxDimension] on its
149
+ * longest side, and without the original's metadata, such as where it
150
+ * was taken. It's decoded at the smallest power-of-two reduction that
151
+ * still covers the target, so a 12-megapixel photo is never held in
152
+ * memory at full size when it's scaled down.
153
+ */
154
+ private fun toJpeg(bytes: ByteArray, maxDimension: Int?, quality: Double): ByteArray? {
155
+ val bounds = BitmapFactory.Options().apply { inJustDecodeBounds = true }
156
+ BitmapFactory.decodeByteArray(bytes, 0, bytes.size, bounds)
157
+ if (bounds.outWidth <= 0 || bounds.outHeight <= 0) return null
158
+ val longest = max(bounds.outWidth, bounds.outHeight)
159
+ // Never larger than the image.
160
+ val target = min(maxDimension ?: longest, longest)
161
+ var sampleSize = 1
162
+ while (longest / (sampleSize * 2) >= target) sampleSize *= 2
163
+ val decoded = BitmapFactory.decodeByteArray(
164
+ bytes,
165
+ 0,
166
+ bytes.size,
167
+ BitmapFactory.Options().apply { inSampleSize = sampleSize },
168
+ ) ?: return null
169
+ val scale = target.toFloat() / max(decoded.width, decoded.height)
170
+ val matrix = Matrix().apply {
171
+ postScale(scale, scale)
172
+ orient(this, orientation(bytes))
173
+ }
174
+ val upright = Bitmap.createBitmap(decoded, 0, 0, decoded.width, decoded.height, matrix, true)
175
+ // A JPEG has no transparency, and would show it black.
176
+ val opaque = if (upright.hasAlpha()) {
177
+ Bitmap.createBitmap(upright.width, upright.height, Bitmap.Config.ARGB_8888).also {
178
+ Canvas(it).apply {
179
+ drawColor(Color.WHITE)
180
+ drawBitmap(upright, 0f, 0f, null)
181
+ }
182
+ }
183
+ } else {
184
+ upright
185
+ }
186
+ return ByteArrayOutputStream().use { output ->
187
+ opaque.compress(Bitmap.CompressFormat.JPEG, (quality * 100).roundToInt(), output)
188
+ output.toByteArray()
189
+ }
190
+ }
191
+
192
+ private fun orientation(bytes: ByteArray): Int =
193
+ try {
194
+ ExifInterface(bytes.inputStream())
195
+ .getAttributeInt(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_NORMAL)
196
+ } catch (_: IOException) {
197
+ ExifInterface.ORIENTATION_NORMAL
198
+ }
199
+
200
+ /** Turns [matrix] the way the camera's [orientation] tag says the image is stored. */
201
+ private fun orient(matrix: Matrix, orientation: Int) {
202
+ when (orientation) {
203
+ ExifInterface.ORIENTATION_FLIP_HORIZONTAL -> matrix.postScale(-1f, 1f)
204
+ ExifInterface.ORIENTATION_ROTATE_180 -> matrix.postRotate(180f)
205
+ ExifInterface.ORIENTATION_FLIP_VERTICAL -> matrix.postScale(1f, -1f)
206
+ ExifInterface.ORIENTATION_TRANSPOSE -> {
207
+ matrix.postRotate(90f)
208
+ matrix.postScale(-1f, 1f)
209
+ }
210
+ ExifInterface.ORIENTATION_ROTATE_90 -> matrix.postRotate(90f)
211
+ ExifInterface.ORIENTATION_TRANSVERSE -> {
212
+ matrix.postRotate(-90f)
213
+ matrix.postScale(-1f, 1f)
214
+ }
215
+ ExifInterface.ORIENTATION_ROTATE_270 -> matrix.postRotate(270f)
216
+ }
217
+ }
218
+ }
219
+ }