@moku-labs/native 0.3.9 → 0.3.11

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
@@ -108,7 +108,7 @@ Each `build.run({ target })` walks the phase pipeline `scaffold → codegen →
108
108
  |---|---|
109
109
  | `display.setFrameRate(fps \| null)` / `display.maxHz` | Picks the slowest display mode at or above `fps` at the current resolution (`null` restores the default); `maxHz` is the panel's top rate. |
110
110
  | `thermal.read()` | Thermal status and ADPF headroom; a `moku-native:thermal` event on `window` on every status change. |
111
- | `insets.current` | Safe-area insets in CSS px, mirrored to `--moku-safe-top/right/bottom/left` on `<html>`, with a `moku-native:insets` event on `window`. |
111
+ | `insets.current` | Safe-area insets in CSS px, mirrored to `--moku-device-safe-top/right/bottom/left` on `<html>` (a page's own `--moku-safe-*` wins over them), with a `moku-native:insets` event on `window`. |
112
112
  | `device`, `ready` | Model, manufacturer and SDK level, filled in once `ready` resolves (it never rejects). |
113
113
  | `build` | `{ profile: "release" \| "debug", id }` — baked in at generate time. |
114
114
  | `share(file)` | Debug builds only: writes the bytes to the app cache and opens the share sheet. |
@@ -177,7 +177,7 @@ The substantive surface is **global** `Config` — every plugin reads it via `ct
177
177
  | `app.category` | `string?` | unset | Store category → `bundle.category`. |
178
178
  | `app.buildNumber` | `string?` | unset | Store build number → `bundle.{iOS,macOS}.bundleVersion`. |
179
179
  | `app.orientation` | `"portrait" \| "landscape" \| "any"` | unset (= `"any"`) | Build-time mobile orientation lock → `UISupportedInterfaceOrientations` (+ `~ipad`, `UIRequiresFullScreen`) in `Info.ios.plist`, `android:screenOrientation` on the Android main activity. No runtime lock. |
180
- | `app.backgroundColor` | `string?` | unset | Hex window colour (`"#10161d"`, `"#10161dff"`) → `app.windows[0].backgroundColor`. Shows during launch and behind any gap the page does not cover. Android status bar icons follow it: light on a dark colour, dark on a light one. |
180
+ | `app.backgroundColor` | `string?` | unset | Hex window colour (`"#10161d"`, `"#10161dff"`) → `app.windows[0].backgroundColor`. Shows during launch and behind any gap the page does not cover. On Android it also paints the activity window and the Android 12+ icon splash, so no dark frame shows between the icon splash and the page's first paint; the status bar icons follow it: light on a dark colour, dark on a light one. |
181
181
  | `app.adaptiveIconInset` | `number?` | unset | Android adaptive icon inset, percent per side of the 108 dp canvas (`0 < n ≤ 30`, validated at composition). Wraps the launcher foreground in an `<inset>` so full-bleed art survives the mask; `19.44` keeps it inside the 66 dp safe zone. Re-applied after `tauri icon` on every Android build; unset leaves the icon untouched. |
182
182
  | `web.build` | `string` | `"bun run build"` | Runs before a build, in `web.cwd`. |
183
183
  | `web.devCommand` | `string` | `"bun run dev"` | Runs before `dev`, in `web.cwd`. |
package/dist/index.cjs CHANGED
@@ -1765,13 +1765,17 @@ const CONTRACT_BODY = String.raw` var MAX_SHARE_BYTES = 32 * 1024 * 1024;
1765
1765
  g.dispatchEvent(new g.CustomEvent(type, { detail: detail }));
1766
1766
  }
1767
1767
 
1768
+ // The system insets go in --moku-device-safe-*, never in --moku-safe-*: an inline property on
1769
+ // the root beats every stylesheet rule, so a page that sets --moku-safe-* from the insets (a gap
1770
+ // added to them) would lose its rule. A page reads them as
1771
+ // var(--moku-safe-top, var(--moku-device-safe-top, env(safe-area-inset-top))).
1768
1772
  function paintInsets() {
1769
1773
  var root = g.document && g.document.documentElement;
1770
1774
  if (!root) return false;
1771
- root.style.setProperty("--moku-safe-top", state.insets.top + "px");
1772
- root.style.setProperty("--moku-safe-right", state.insets.right + "px");
1773
- root.style.setProperty("--moku-safe-bottom", state.insets.bottom + "px");
1774
- root.style.setProperty("--moku-safe-left", state.insets.left + "px");
1775
+ root.style.setProperty("--moku-device-safe-top", state.insets.top + "px");
1776
+ root.style.setProperty("--moku-device-safe-right", state.insets.right + "px");
1777
+ root.style.setProperty("--moku-device-safe-bottom", state.insets.bottom + "px");
1778
+ root.style.setProperty("--moku-device-safe-left", state.insets.left + "px");
1775
1779
  return true;
1776
1780
  }
1777
1781
 
@@ -2727,6 +2731,21 @@ async function androidMainActivityFiles(genDirectory) {
2727
2731
  return (await collectFiles(androidJavaDirectory(genDirectory), (name) => name === MAIN_ACTIVITY_FILE)).toSorted();
2728
2732
  }
2729
2733
  /**
2734
+ * Returns the directory `tauri android init` writes the app's resources into, where the
2735
+ * window background patch finds every `values*\/themes.xml`.
2736
+ *
2737
+ * @param genDirectory - The `src-tauri/gen/android` directory.
2738
+ * @returns The `app/src/main/res` directory of that tree.
2739
+ * @example
2740
+ * ```ts
2741
+ * androidResourceDirectory("/repo/.moku/tauri/src-tauri/gen/android");
2742
+ * // "/repo/.moku/tauri/src-tauri/gen/android/app/src/main/res"
2743
+ * ```
2744
+ */
2745
+ function androidResourceDirectory(genDirectory) {
2746
+ return node_path.default.join(genDirectory, ...ANDROID_RESOURCE_SEGMENTS);
2747
+ }
2748
+ /**
2730
2749
  * Returns the app's string resources, where the debug profile renames the app.
2731
2750
  *
2732
2751
  * @param genDirectory - The `src-tauri/gen/android` directory.
@@ -4482,6 +4501,204 @@ async function patchAndroidSystemBars(projectDirectory, genDirectory, background
4482
4501
  };
4483
4502
  }
4484
4503
  //#endregion
4504
+ //#region src/plugins/project/mobile/window-background.ts
4505
+ /**
4506
+ * @file project plugin — the Android window background patch. The generated app theme
4507
+ * (`Theme.Material3.DayNight.NoActionBar`) sets no window background, so between the
4508
+ * system's icon splash and the WebView's first paint the activity window shows the theme's
4509
+ * default, dark in night mode: a dark flash at every launch. When `app.backgroundColor` is
4510
+ * set, this patch writes that colour as a moku-owned colour resource and points the app
4511
+ * theme's `android:windowBackground` and `android:windowSplashScreenBackground` (the
4512
+ * Android 12+ icon splash) at it, in every `res/values*\/themes.xml` that holds the theme.
4513
+ *
4514
+ * Every line and file this patch writes carries {@link MARKER}, so a pass first strips its
4515
+ * own lines and then writes them again: a second pass is a no-op, other bytes (line endings
4516
+ * included) survive, and unsetting the colour restores the generated files.
4517
+ */
4518
+ /** Marks every line and file this patch owns. */
4519
+ const MARKER = "<!-- moku:native window background -->";
4520
+ /** The colour resource the theme items point at. */
4521
+ const COLOUR_NAME = "moku_window_background";
4522
+ /** The unqualified resource directory: the day theme and the colour resource live there. */
4523
+ const VALUES_DIRECTORY = "values";
4524
+ /** The theme file `tauri android init` writes per resource qualifier. */
4525
+ const THEMES_FILE = "themes.xml";
4526
+ /** `#rrggbb` or `#rrggbbaa`: the colour and the optional alpha, captured apart. */
4527
+ const HEX_COLOUR_PATTERN$1 = /^#([\da-f]{6})([\da-f]{2})?$/i;
4528
+ /** The prefix `android:theme` names the app theme with. */
4529
+ const STYLE_REFERENCE_PREFIX = "@style/";
4530
+ /** The theme items, in the order they are written: window first, then the icon splash. */
4531
+ const THEME_ITEMS = [`<item name="android:windowBackground">@color/${COLOUR_NAME}</item>`, `<item name="android:windowSplashScreenBackground" tools:targetApi="31">@color/${COLOUR_NAME}</item>`];
4532
+ /** One level of indentation, for a style with no child line to copy it from. */
4533
+ const INDENT_STEP = " ";
4534
+ /** The leading spaces and tabs of a line. */
4535
+ const INDENT_PATTERN$1 = /^[\t ]*/;
4536
+ /**
4537
+ * Builds the `[native]` error for a generated file this patch needs and cannot use.
4538
+ *
4539
+ * @param problem - What is wrong, starting with the file path.
4540
+ * @returns A formatted `[native] ...` error.
4541
+ * @example
4542
+ * ```ts
4543
+ * throw initError("/repo/.moku/tauri/src-tauri/gen/android/app/src/main/res/values/themes.xml not found");
4544
+ * ```
4545
+ */
4546
+ function initError(problem) {
4547
+ return /* @__PURE__ */ new Error(`[native] ${problem}.\n Re-run the mobile init pass (tauri android init), or unset app.backgroundColor.`);
4548
+ }
4549
+ /**
4550
+ * Converts `app.backgroundColor` to Android's colour notation, which puts the alpha first.
4551
+ *
4552
+ * @param colour - `#rrggbb` or `#rrggbbaa`.
4553
+ * @returns `#rrggbb` unchanged, or `#aarrggbb`.
4554
+ * @throws {Error} `[native]` when the value is not a hex colour.
4555
+ * @example
4556
+ * ```ts
4557
+ * androidColour("#10161d"); // "#10161d"
4558
+ * androidColour("#10161d80"); // "#8010161d"
4559
+ * ```
4560
+ */
4561
+ function androidColour(colour) {
4562
+ const match = HEX_COLOUR_PATTERN$1.exec(colour);
4563
+ if (!match) throw new Error(`[native] app.backgroundColor "${colour}" is not a valid colour.\n Use a hex colour such as "#10161d".`);
4564
+ const [, rgb = "", alpha = ""] = match;
4565
+ return `#${alpha}${rgb}`;
4566
+ }
4567
+ /**
4568
+ * Sets or clears the window background items of one `themes.xml`. The patch's own lines are
4569
+ * removed first; when enabled, the items go right after the start tag of the named style,
4570
+ * at the indentation of the line that follows it.
4571
+ *
4572
+ * @param source - The `themes.xml` content.
4573
+ * @param styleName - The app theme, as `android:theme` names it without `@style/`.
4574
+ * @param enabled - Whether `app.backgroundColor` is set.
4575
+ * @param filePath - The `themes.xml` path, named in the error.
4576
+ * @returns The content with the items applied.
4577
+ * @throws {Error} `[native]` when enabled and the file holds no such style.
4578
+ * @example
4579
+ * ```ts
4580
+ * applyWindowBackground('<resources>\n <style name="Theme.app" parent="P">\n </style>\n</resources>\n', "Theme.app", true, "themes.xml");
4581
+ * // the same file with the window and splash items as the style's first two lines
4582
+ * ```
4583
+ */
4584
+ function applyWindowBackground(source, styleName, enabled, filePath) {
4585
+ const lines = source.split("\n").filter((line) => !line.includes(MARKER));
4586
+ if (!enabled) return lines.join("\n");
4587
+ const index = lines.findIndex((line) => line.includes(`<style name="${styleName}"`));
4588
+ if (index === -1) throw initError(`${filePath} has no <style name="${styleName}"> to set the window background in`);
4589
+ const styleIndent = INDENT_PATTERN$1.exec(lines[index] ?? "")?.[0] ?? "";
4590
+ const nextIndent = INDENT_PATTERN$1.exec(lines[index + 1] ?? "")?.[0] ?? "";
4591
+ const indent = nextIndent.length > styleIndent.length ? nextIndent : styleIndent + INDENT_STEP;
4592
+ const carriageReturn = source.includes("\r\n") ? "\r" : "";
4593
+ const items = THEME_ITEMS.map((item) => `${indent}${item} ${MARKER}${carriageReturn}`);
4594
+ return [
4595
+ ...lines.slice(0, index + 1),
4596
+ ...items,
4597
+ ...lines.slice(index + 1)
4598
+ ].join("\n");
4599
+ }
4600
+ /**
4601
+ * Builds the moku-owned colour resource file.
4602
+ *
4603
+ * @param colour - The colour in Android notation.
4604
+ * @returns The `moku_window_background.xml` content.
4605
+ * @example
4606
+ * ```ts
4607
+ * colourResource("#10161d"); // a <resources> file with <color name="moku_window_background">#10161d</color>
4608
+ * ```
4609
+ */
4610
+ function colourResource(colour) {
4611
+ return [
4612
+ "<?xml version=\"1.0\" encoding=\"utf-8\"?>",
4613
+ MARKER,
4614
+ "<resources>",
4615
+ ` <color name="${COLOUR_NAME}">${colour}</color>`,
4616
+ "</resources>",
4617
+ ""
4618
+ ].join("\n");
4619
+ }
4620
+ /**
4621
+ * Lists every `res/values*\/themes.xml` of the tree, sorted, so `values` comes first.
4622
+ *
4623
+ * @param resourceDirectory - The `app/src/main/res` directory.
4624
+ * @returns The theme files found, possibly none.
4625
+ */
4626
+ async function themeFiles(resourceDirectory) {
4627
+ if (!(0, node_fs.existsSync)(resourceDirectory)) return [];
4628
+ return (await (0, node_fs_promises.readdir)(resourceDirectory, { withFileTypes: true })).filter((entry) => entry.isDirectory() && entry.name.startsWith(VALUES_DIRECTORY)).map((entry) => entry.name).toSorted().map((name) => node_path.default.join(resourceDirectory, name, THEMES_FILE)).filter((file) => (0, node_fs.existsSync)(file));
4629
+ }
4630
+ /**
4631
+ * Reads the app theme's style name from the manifest's `<application android:theme>`.
4632
+ *
4633
+ * @param genDirectory - The `src-tauri/gen/android` directory.
4634
+ * @returns The style name without `@style/`.
4635
+ * @throws {Error} `[native]` when the manifest is missing or names no style.
4636
+ */
4637
+ async function appThemeName(genDirectory) {
4638
+ const manifestPath = androidManifestPath(genDirectory);
4639
+ if (!(0, node_fs.existsSync)(manifestPath)) throw initError(`${manifestPath} not found`);
4640
+ const theme = applicationAttribute(await (0, node_fs_promises.readFile)(manifestPath, "utf8"), "android:theme");
4641
+ if (!theme?.startsWith(STYLE_REFERENCE_PREFIX)) throw initError(`${manifestPath} names no android:theme on <application> to set the window background in`);
4642
+ return theme.slice(7);
4643
+ }
4644
+ /**
4645
+ * Writes or removes the moku-owned colour resource. A file without the marker is someone
4646
+ * else's and is never touched.
4647
+ *
4648
+ * @param projectDirectory - The Tauri project root.
4649
+ * @param colourPath - The `res/values/moku_window_background.xml` path.
4650
+ * @param colour - The colour in Android notation, or undefined to remove the file.
4651
+ * @param result - The lists the path is recorded in.
4652
+ * @returns Resolves once the file is in place or gone.
4653
+ */
4654
+ async function syncColourFile(projectDirectory, colourPath, colour, result) {
4655
+ if (colour !== void 0) {
4656
+ (await writeIfChanged(colourPath, colourResource(colour), projectDirectory) === "written" ? result.patched : result.unchanged).push(colourPath);
4657
+ return;
4658
+ }
4659
+ if (!(0, node_fs.existsSync)(colourPath)) return;
4660
+ if (!(await (0, node_fs_promises.readFile)(colourPath, "utf8")).includes(MARKER)) return;
4661
+ await (0, node_fs_promises.rm)(colourPath, { force: true });
4662
+ result.patched.push(colourPath);
4663
+ }
4664
+ /**
4665
+ * Sets the Android window and icon-splash background from `app.backgroundColor`, through
4666
+ * the write-if-changed writer: the colour resource, then every `themes.xml` in sorted order.
4667
+ * Without a colour the patch's own lines and file are removed, and a tree it never touched
4668
+ * is left as it is.
4669
+ *
4670
+ * @param projectDirectory - The Tauri project root.
4671
+ * @param genDirectory - The `src-tauri/gen/android` directory.
4672
+ * @param backgroundColor - `app.backgroundColor`, or undefined when unset.
4673
+ * @returns The colour file and theme files, patched or unchanged.
4674
+ * @throws {Error} `[native]` when a colour is set and the manifest names no app theme, the
4675
+ * `res/values/themes.xml` is missing, or it lacks the app theme.
4676
+ * @example
4677
+ * ```ts
4678
+ * // First pass on the generated tree; a second pass lists every file under `unchanged`.
4679
+ * await patchAndroidWindowBackground(".moku/tauri", ".moku/tauri/src-tauri/gen/android", "#10161d");
4680
+ * // { patched: [".../values/moku_window_background.xml", ".../values/themes.xml", ".../values-night/themes.xml"], unchanged: [] }
4681
+ * ```
4682
+ */
4683
+ async function patchAndroidWindowBackground(projectDirectory, genDirectory, backgroundColor) {
4684
+ const colour = backgroundColor === void 0 ? void 0 : androidColour(backgroundColor);
4685
+ const resourceDirectory = androidResourceDirectory(genDirectory);
4686
+ const dayThemes = node_path.default.join(resourceDirectory, VALUES_DIRECTORY, THEMES_FILE);
4687
+ const styleName = colour === void 0 ? "" : await appThemeName(genDirectory);
4688
+ if (colour !== void 0 && !(0, node_fs.existsSync)(dayThemes)) throw initError(`${dayThemes} not found`);
4689
+ const result = {
4690
+ patched: [],
4691
+ unchanged: []
4692
+ };
4693
+ await syncColourFile(projectDirectory, node_path.default.join(resourceDirectory, VALUES_DIRECTORY, `${COLOUR_NAME}.xml`), colour, result);
4694
+ for (const file of await themeFiles(resourceDirectory)) {
4695
+ const source = await (0, node_fs_promises.readFile)(file, "utf8");
4696
+ const holdsTheme = file === dayThemes || source.includes(`<style name="${styleName}"`);
4697
+ (await writeIfChanged(file, applyWindowBackground(source, styleName, colour !== void 0 && holdsTheme, file), projectDirectory) === "written" ? result.patched : result.unchanged).push(file);
4698
+ }
4699
+ return result;
4700
+ }
4701
+ //#endregion
4485
4702
  //#region src/plugins/project/mobile/xcode-settings.ts
4486
4703
  /**
4487
4704
  * @file project plugin — the Xcode build-settings patch that makes an iOS REBUILD work.
@@ -4803,7 +5020,8 @@ async function patchXcodeSettings(projectDirectory, genDirectory) {
4803
5020
  * `profile.ts` (the Android build-profile patches), `signing.ts` (the Android
4804
5021
  * release-signing block), `manifest.ts` (the Android main activity's attributes, such as
4805
5022
  * the orientation lock), `system-bars.ts` (the Android status bar icon style from
4806
- * `app.backgroundColor`), `runner.ts` (the Xcode / Android-Studio runner command) and
5023
+ * `app.backgroundColor`), `window-background.ts` (the Android window and icon-splash
5024
+ * background from the same colour), `runner.ts` (the Xcode / Android-Studio runner command) and
4807
5025
  * `xcode-settings.ts` (the iOS entitlements-modification setting that makes a REBUILD work).
4808
5026
  */
4809
5027
  /** The profile of a pass whose caller names none: the store profile, warnings dropped. */
@@ -4851,8 +5069,8 @@ async function patchIos(projectDirectory, genDirectory, runner) {
4851
5069
  }
4852
5070
  /**
4853
5071
  * The Android half of {@link patchMobile}: the build-profile patches, the release signing
4854
- * block, the main activity's manifest attributes, the status bar style, then the runner
4855
- * command when the caller supplies a runner.
5072
+ * block, the main activity's manifest attributes, the status bar style, the window
5073
+ * background, then the runner command when the caller supplies a runner.
4856
5074
  *
4857
5075
  * @param options - What to patch.
4858
5076
  * @param options.projectDirectory - The Tauri project root.
@@ -4860,7 +5078,8 @@ async function patchIos(projectDirectory, genDirectory, runner) {
4860
5078
  * @param options.runner - The absolute Node/tauri.js runner pair, or undefined to keep it.
4861
5079
  * @param options.signing - The full signing config (only `.android` is consulted).
4862
5080
  * @param options.manifest - Android manifest entries for the main activity.
4863
- * @param options.backgroundColor - `app.backgroundColor`, which the status bar icons follow.
5081
+ * @param options.backgroundColor - `app.backgroundColor`, which the status bar icons and the
5082
+ * window background follow.
4864
5083
  * @param options.profile - The Android build profile.
4865
5084
  * @returns The paths patched vs. left unchanged, merged over every patch.
4866
5085
  * @throws {Error} When the `gen/android` tree (or its `app/build.gradle.kts`) is missing, the
@@ -4880,7 +5099,8 @@ async function patchAndroid(options) {
4880
5099
  }),
4881
5100
  await patchAndroidSigning(projectDirectory, genDirectory, options.signing.android ?? {}, debugKeystore),
4882
5101
  await patchAndroidManifest(projectDirectory, genDirectory, options.manifest),
4883
- await patchAndroidSystemBars(projectDirectory, genDirectory, options.backgroundColor)
5102
+ await patchAndroidSystemBars(projectDirectory, genDirectory, options.backgroundColor),
5103
+ await patchAndroidWindowBackground(projectDirectory, genDirectory, options.backgroundColor)
4884
5104
  ];
4885
5105
  if (!runner) return mergePatchResults(...androidResults);
4886
5106
  const runnerResult = await patchRunner(projectDirectory, genDirectory, {
@@ -4892,9 +5112,10 @@ async function patchAndroid(options) {
4892
5112
  /**
4893
5113
  * Deterministic, idempotent post-init patch pass over an existing complete gen/ tree.
4894
5114
  * Android gets, in this order, its build-profile patches, its release signing block, the
4895
- * main activity's manifest attributes, the system bar style in MainActivity.kt, then the
4896
- * runner command. The profile patches run before signing so that the store profile cuts
4897
- * its Gradle block out byte for byte, wherever the signing block sits. iOS gets the Xcode
5115
+ * main activity's manifest attributes, the system bar style in MainActivity.kt, the window
5116
+ * and icon-splash background in the app theme, then the runner command. The profile
5117
+ * patches run before signing so that the store profile cuts its Gradle block out byte for
5118
+ * byte, wherever the signing block sits. iOS gets the Xcode
4898
5119
  * entitlements-modification setting (without it the SECOND build of the same tree fails),
4899
5120
  * then the runner command. The runner rewrite runs only when the caller supplies a
4900
5121
  * `runner`. iOS takes no manifest entries, no background colour and no profile: its
@@ -4905,14 +5126,15 @@ async function patchAndroid(options) {
4905
5126
  * @param opts - The mobile platform, and optionally the absolute Node/tauri.js runner pair.
4906
5127
  * @param signing - The full signing config (only `.android` is consulted).
4907
5128
  * @param manifest - Android manifest entries for the main activity (ignored on iOS).
4908
- * @param backgroundColor - `app.backgroundColor`; the Android status bar icons follow it
4909
- * (ignored on iOS).
5129
+ * @param backgroundColor - `app.backgroundColor`; the Android status bar icons, window
5130
+ * background and icon-splash background follow it (ignored on iOS).
4910
5131
  * @param profile - The Android build profile; the store profile when omitted.
4911
5132
  * @returns The paths patched vs. left unchanged, one merged report over every patch.
4912
5133
  * @throws {Error} When the Android `gen/android` tree (or its `app/build.gradle.kts`) is
4913
5134
  * missing, the debug keystore is missing in the debug profile (before anything is
4914
5135
  * written), manifest entries meet a missing manifest or an unclear main activity, or a
4915
- * background colour meets a tree without exactly one MainActivity.kt to style.
5136
+ * background colour meets a tree without exactly one MainActivity.kt to style or without
5137
+ * the app theme to set the window background in.
4916
5138
  */
4917
5139
  async function patchMobile(projectDirectory, opts, signing, manifest = [], backgroundColor, profile = STORE_PROFILE) {
4918
5140
  const genDirectory = genDirectoryPath(projectDirectory, opts.target);
@@ -5529,7 +5751,8 @@ function createProjectApi(ctx) {
5529
5751
  };
5530
5752
  /**
5531
5753
  * Implements {@link Api.patchMobile}: hands Android its build profile, its manifest
5532
- * entries and `app.backgroundColor` (the status bar icons follow it), then logs.
5754
+ * entries and `app.backgroundColor` (the status bar icons and the window background
5755
+ * follow it), then logs.
5533
5756
  *
5534
5757
  * @param opts - See {@link Api.patchMobile}.
5535
5758
  * @returns See {@link Api.patchMobile}.
package/dist/index.d.cts CHANGED
@@ -173,8 +173,10 @@ type Config = {
173
173
  /**
174
174
  * Hex window colour (`"#10161d"`, or `"#10161dff"` with alpha) →
175
175
  * `app.windows[0].backgroundColor`. Shows during launch and behind any gap the page
176
- * does not cover. Android status bar icons follow it: light icons on a dark colour,
177
- * dark icons on a light one. Unset leaves the platform default (white in light mode).
176
+ * does not cover. On Android it also paints the activity window and the icon splash,
177
+ * so no dark frame shows before the page's first paint, and the status bar icons follow
178
+ * it: light icons on a dark colour, dark icons on a light one. Unset leaves the
179
+ * platform default (white in light mode).
178
180
  */
179
181
  backgroundColor?: string;
180
182
  /**
package/dist/index.d.mts CHANGED
@@ -174,8 +174,10 @@ type Config = {
174
174
  /**
175
175
  * Hex window colour (`"#10161d"`, or `"#10161dff"` with alpha) →
176
176
  * `app.windows[0].backgroundColor`. Shows during launch and behind any gap the page
177
- * does not cover. Android status bar icons follow it: light icons on a dark colour,
178
- * dark icons on a light one. Unset leaves the platform default (white in light mode).
177
+ * does not cover. On Android it also paints the activity window and the icon splash,
178
+ * so no dark frame shows before the page's first paint, and the status bar icons follow
179
+ * it: light icons on a dark colour, dark icons on a light one. Unset leaves the
180
+ * platform default (white in light mode).
179
181
  */
180
182
  backgroundColor?: string;
181
183
  /**
package/dist/index.mjs CHANGED
@@ -1738,13 +1738,17 @@ const CONTRACT_BODY = String.raw` var MAX_SHARE_BYTES = 32 * 1024 * 1024;
1738
1738
  g.dispatchEvent(new g.CustomEvent(type, { detail: detail }));
1739
1739
  }
1740
1740
 
1741
+ // The system insets go in --moku-device-safe-*, never in --moku-safe-*: an inline property on
1742
+ // the root beats every stylesheet rule, so a page that sets --moku-safe-* from the insets (a gap
1743
+ // added to them) would lose its rule. A page reads them as
1744
+ // var(--moku-safe-top, var(--moku-device-safe-top, env(safe-area-inset-top))).
1741
1745
  function paintInsets() {
1742
1746
  var root = g.document && g.document.documentElement;
1743
1747
  if (!root) return false;
1744
- root.style.setProperty("--moku-safe-top", state.insets.top + "px");
1745
- root.style.setProperty("--moku-safe-right", state.insets.right + "px");
1746
- root.style.setProperty("--moku-safe-bottom", state.insets.bottom + "px");
1747
- root.style.setProperty("--moku-safe-left", state.insets.left + "px");
1748
+ root.style.setProperty("--moku-device-safe-top", state.insets.top + "px");
1749
+ root.style.setProperty("--moku-device-safe-right", state.insets.right + "px");
1750
+ root.style.setProperty("--moku-device-safe-bottom", state.insets.bottom + "px");
1751
+ root.style.setProperty("--moku-device-safe-left", state.insets.left + "px");
1748
1752
  return true;
1749
1753
  }
1750
1754
 
@@ -2700,6 +2704,21 @@ async function androidMainActivityFiles(genDirectory) {
2700
2704
  return (await collectFiles(androidJavaDirectory(genDirectory), (name) => name === MAIN_ACTIVITY_FILE)).toSorted();
2701
2705
  }
2702
2706
  /**
2707
+ * Returns the directory `tauri android init` writes the app's resources into, where the
2708
+ * window background patch finds every `values*\/themes.xml`.
2709
+ *
2710
+ * @param genDirectory - The `src-tauri/gen/android` directory.
2711
+ * @returns The `app/src/main/res` directory of that tree.
2712
+ * @example
2713
+ * ```ts
2714
+ * androidResourceDirectory("/repo/.moku/tauri/src-tauri/gen/android");
2715
+ * // "/repo/.moku/tauri/src-tauri/gen/android/app/src/main/res"
2716
+ * ```
2717
+ */
2718
+ function androidResourceDirectory(genDirectory) {
2719
+ return path.join(genDirectory, ...ANDROID_RESOURCE_SEGMENTS);
2720
+ }
2721
+ /**
2703
2722
  * Returns the app's string resources, where the debug profile renames the app.
2704
2723
  *
2705
2724
  * @param genDirectory - The `src-tauri/gen/android` directory.
@@ -4455,6 +4474,204 @@ async function patchAndroidSystemBars(projectDirectory, genDirectory, background
4455
4474
  };
4456
4475
  }
4457
4476
  //#endregion
4477
+ //#region src/plugins/project/mobile/window-background.ts
4478
+ /**
4479
+ * @file project plugin — the Android window background patch. The generated app theme
4480
+ * (`Theme.Material3.DayNight.NoActionBar`) sets no window background, so between the
4481
+ * system's icon splash and the WebView's first paint the activity window shows the theme's
4482
+ * default, dark in night mode: a dark flash at every launch. When `app.backgroundColor` is
4483
+ * set, this patch writes that colour as a moku-owned colour resource and points the app
4484
+ * theme's `android:windowBackground` and `android:windowSplashScreenBackground` (the
4485
+ * Android 12+ icon splash) at it, in every `res/values*\/themes.xml` that holds the theme.
4486
+ *
4487
+ * Every line and file this patch writes carries {@link MARKER}, so a pass first strips its
4488
+ * own lines and then writes them again: a second pass is a no-op, other bytes (line endings
4489
+ * included) survive, and unsetting the colour restores the generated files.
4490
+ */
4491
+ /** Marks every line and file this patch owns. */
4492
+ const MARKER = "<!-- moku:native window background -->";
4493
+ /** The colour resource the theme items point at. */
4494
+ const COLOUR_NAME = "moku_window_background";
4495
+ /** The unqualified resource directory: the day theme and the colour resource live there. */
4496
+ const VALUES_DIRECTORY = "values";
4497
+ /** The theme file `tauri android init` writes per resource qualifier. */
4498
+ const THEMES_FILE = "themes.xml";
4499
+ /** `#rrggbb` or `#rrggbbaa`: the colour and the optional alpha, captured apart. */
4500
+ const HEX_COLOUR_PATTERN$1 = /^#([\da-f]{6})([\da-f]{2})?$/i;
4501
+ /** The prefix `android:theme` names the app theme with. */
4502
+ const STYLE_REFERENCE_PREFIX = "@style/";
4503
+ /** The theme items, in the order they are written: window first, then the icon splash. */
4504
+ const THEME_ITEMS = [`<item name="android:windowBackground">@color/${COLOUR_NAME}</item>`, `<item name="android:windowSplashScreenBackground" tools:targetApi="31">@color/${COLOUR_NAME}</item>`];
4505
+ /** One level of indentation, for a style with no child line to copy it from. */
4506
+ const INDENT_STEP = " ";
4507
+ /** The leading spaces and tabs of a line. */
4508
+ const INDENT_PATTERN$1 = /^[\t ]*/;
4509
+ /**
4510
+ * Builds the `[native]` error for a generated file this patch needs and cannot use.
4511
+ *
4512
+ * @param problem - What is wrong, starting with the file path.
4513
+ * @returns A formatted `[native] ...` error.
4514
+ * @example
4515
+ * ```ts
4516
+ * throw initError("/repo/.moku/tauri/src-tauri/gen/android/app/src/main/res/values/themes.xml not found");
4517
+ * ```
4518
+ */
4519
+ function initError(problem) {
4520
+ return /* @__PURE__ */ new Error(`[native] ${problem}.\n Re-run the mobile init pass (tauri android init), or unset app.backgroundColor.`);
4521
+ }
4522
+ /**
4523
+ * Converts `app.backgroundColor` to Android's colour notation, which puts the alpha first.
4524
+ *
4525
+ * @param colour - `#rrggbb` or `#rrggbbaa`.
4526
+ * @returns `#rrggbb` unchanged, or `#aarrggbb`.
4527
+ * @throws {Error} `[native]` when the value is not a hex colour.
4528
+ * @example
4529
+ * ```ts
4530
+ * androidColour("#10161d"); // "#10161d"
4531
+ * androidColour("#10161d80"); // "#8010161d"
4532
+ * ```
4533
+ */
4534
+ function androidColour(colour) {
4535
+ const match = HEX_COLOUR_PATTERN$1.exec(colour);
4536
+ if (!match) throw new Error(`[native] app.backgroundColor "${colour}" is not a valid colour.\n Use a hex colour such as "#10161d".`);
4537
+ const [, rgb = "", alpha = ""] = match;
4538
+ return `#${alpha}${rgb}`;
4539
+ }
4540
+ /**
4541
+ * Sets or clears the window background items of one `themes.xml`. The patch's own lines are
4542
+ * removed first; when enabled, the items go right after the start tag of the named style,
4543
+ * at the indentation of the line that follows it.
4544
+ *
4545
+ * @param source - The `themes.xml` content.
4546
+ * @param styleName - The app theme, as `android:theme` names it without `@style/`.
4547
+ * @param enabled - Whether `app.backgroundColor` is set.
4548
+ * @param filePath - The `themes.xml` path, named in the error.
4549
+ * @returns The content with the items applied.
4550
+ * @throws {Error} `[native]` when enabled and the file holds no such style.
4551
+ * @example
4552
+ * ```ts
4553
+ * applyWindowBackground('<resources>\n <style name="Theme.app" parent="P">\n </style>\n</resources>\n', "Theme.app", true, "themes.xml");
4554
+ * // the same file with the window and splash items as the style's first two lines
4555
+ * ```
4556
+ */
4557
+ function applyWindowBackground(source, styleName, enabled, filePath) {
4558
+ const lines = source.split("\n").filter((line) => !line.includes(MARKER));
4559
+ if (!enabled) return lines.join("\n");
4560
+ const index = lines.findIndex((line) => line.includes(`<style name="${styleName}"`));
4561
+ if (index === -1) throw initError(`${filePath} has no <style name="${styleName}"> to set the window background in`);
4562
+ const styleIndent = INDENT_PATTERN$1.exec(lines[index] ?? "")?.[0] ?? "";
4563
+ const nextIndent = INDENT_PATTERN$1.exec(lines[index + 1] ?? "")?.[0] ?? "";
4564
+ const indent = nextIndent.length > styleIndent.length ? nextIndent : styleIndent + INDENT_STEP;
4565
+ const carriageReturn = source.includes("\r\n") ? "\r" : "";
4566
+ const items = THEME_ITEMS.map((item) => `${indent}${item} ${MARKER}${carriageReturn}`);
4567
+ return [
4568
+ ...lines.slice(0, index + 1),
4569
+ ...items,
4570
+ ...lines.slice(index + 1)
4571
+ ].join("\n");
4572
+ }
4573
+ /**
4574
+ * Builds the moku-owned colour resource file.
4575
+ *
4576
+ * @param colour - The colour in Android notation.
4577
+ * @returns The `moku_window_background.xml` content.
4578
+ * @example
4579
+ * ```ts
4580
+ * colourResource("#10161d"); // a <resources> file with <color name="moku_window_background">#10161d</color>
4581
+ * ```
4582
+ */
4583
+ function colourResource(colour) {
4584
+ return [
4585
+ "<?xml version=\"1.0\" encoding=\"utf-8\"?>",
4586
+ MARKER,
4587
+ "<resources>",
4588
+ ` <color name="${COLOUR_NAME}">${colour}</color>`,
4589
+ "</resources>",
4590
+ ""
4591
+ ].join("\n");
4592
+ }
4593
+ /**
4594
+ * Lists every `res/values*\/themes.xml` of the tree, sorted, so `values` comes first.
4595
+ *
4596
+ * @param resourceDirectory - The `app/src/main/res` directory.
4597
+ * @returns The theme files found, possibly none.
4598
+ */
4599
+ async function themeFiles(resourceDirectory) {
4600
+ if (!existsSync(resourceDirectory)) return [];
4601
+ return (await readdir(resourceDirectory, { withFileTypes: true })).filter((entry) => entry.isDirectory() && entry.name.startsWith(VALUES_DIRECTORY)).map((entry) => entry.name).toSorted().map((name) => path.join(resourceDirectory, name, THEMES_FILE)).filter((file) => existsSync(file));
4602
+ }
4603
+ /**
4604
+ * Reads the app theme's style name from the manifest's `<application android:theme>`.
4605
+ *
4606
+ * @param genDirectory - The `src-tauri/gen/android` directory.
4607
+ * @returns The style name without `@style/`.
4608
+ * @throws {Error} `[native]` when the manifest is missing or names no style.
4609
+ */
4610
+ async function appThemeName(genDirectory) {
4611
+ const manifestPath = androidManifestPath(genDirectory);
4612
+ if (!existsSync(manifestPath)) throw initError(`${manifestPath} not found`);
4613
+ const theme = applicationAttribute(await readFile(manifestPath, "utf8"), "android:theme");
4614
+ if (!theme?.startsWith(STYLE_REFERENCE_PREFIX)) throw initError(`${manifestPath} names no android:theme on <application> to set the window background in`);
4615
+ return theme.slice(7);
4616
+ }
4617
+ /**
4618
+ * Writes or removes the moku-owned colour resource. A file without the marker is someone
4619
+ * else's and is never touched.
4620
+ *
4621
+ * @param projectDirectory - The Tauri project root.
4622
+ * @param colourPath - The `res/values/moku_window_background.xml` path.
4623
+ * @param colour - The colour in Android notation, or undefined to remove the file.
4624
+ * @param result - The lists the path is recorded in.
4625
+ * @returns Resolves once the file is in place or gone.
4626
+ */
4627
+ async function syncColourFile(projectDirectory, colourPath, colour, result) {
4628
+ if (colour !== void 0) {
4629
+ (await writeIfChanged(colourPath, colourResource(colour), projectDirectory) === "written" ? result.patched : result.unchanged).push(colourPath);
4630
+ return;
4631
+ }
4632
+ if (!existsSync(colourPath)) return;
4633
+ if (!(await readFile(colourPath, "utf8")).includes(MARKER)) return;
4634
+ await rm(colourPath, { force: true });
4635
+ result.patched.push(colourPath);
4636
+ }
4637
+ /**
4638
+ * Sets the Android window and icon-splash background from `app.backgroundColor`, through
4639
+ * the write-if-changed writer: the colour resource, then every `themes.xml` in sorted order.
4640
+ * Without a colour the patch's own lines and file are removed, and a tree it never touched
4641
+ * is left as it is.
4642
+ *
4643
+ * @param projectDirectory - The Tauri project root.
4644
+ * @param genDirectory - The `src-tauri/gen/android` directory.
4645
+ * @param backgroundColor - `app.backgroundColor`, or undefined when unset.
4646
+ * @returns The colour file and theme files, patched or unchanged.
4647
+ * @throws {Error} `[native]` when a colour is set and the manifest names no app theme, the
4648
+ * `res/values/themes.xml` is missing, or it lacks the app theme.
4649
+ * @example
4650
+ * ```ts
4651
+ * // First pass on the generated tree; a second pass lists every file under `unchanged`.
4652
+ * await patchAndroidWindowBackground(".moku/tauri", ".moku/tauri/src-tauri/gen/android", "#10161d");
4653
+ * // { patched: [".../values/moku_window_background.xml", ".../values/themes.xml", ".../values-night/themes.xml"], unchanged: [] }
4654
+ * ```
4655
+ */
4656
+ async function patchAndroidWindowBackground(projectDirectory, genDirectory, backgroundColor) {
4657
+ const colour = backgroundColor === void 0 ? void 0 : androidColour(backgroundColor);
4658
+ const resourceDirectory = androidResourceDirectory(genDirectory);
4659
+ const dayThemes = path.join(resourceDirectory, VALUES_DIRECTORY, THEMES_FILE);
4660
+ const styleName = colour === void 0 ? "" : await appThemeName(genDirectory);
4661
+ if (colour !== void 0 && !existsSync(dayThemes)) throw initError(`${dayThemes} not found`);
4662
+ const result = {
4663
+ patched: [],
4664
+ unchanged: []
4665
+ };
4666
+ await syncColourFile(projectDirectory, path.join(resourceDirectory, VALUES_DIRECTORY, `${COLOUR_NAME}.xml`), colour, result);
4667
+ for (const file of await themeFiles(resourceDirectory)) {
4668
+ const source = await readFile(file, "utf8");
4669
+ const holdsTheme = file === dayThemes || source.includes(`<style name="${styleName}"`);
4670
+ (await writeIfChanged(file, applyWindowBackground(source, styleName, colour !== void 0 && holdsTheme, file), projectDirectory) === "written" ? result.patched : result.unchanged).push(file);
4671
+ }
4672
+ return result;
4673
+ }
4674
+ //#endregion
4458
4675
  //#region src/plugins/project/mobile/xcode-settings.ts
4459
4676
  /**
4460
4677
  * @file project plugin — the Xcode build-settings patch that makes an iOS REBUILD work.
@@ -4776,7 +4993,8 @@ async function patchXcodeSettings(projectDirectory, genDirectory) {
4776
4993
  * `profile.ts` (the Android build-profile patches), `signing.ts` (the Android
4777
4994
  * release-signing block), `manifest.ts` (the Android main activity's attributes, such as
4778
4995
  * the orientation lock), `system-bars.ts` (the Android status bar icon style from
4779
- * `app.backgroundColor`), `runner.ts` (the Xcode / Android-Studio runner command) and
4996
+ * `app.backgroundColor`), `window-background.ts` (the Android window and icon-splash
4997
+ * background from the same colour), `runner.ts` (the Xcode / Android-Studio runner command) and
4780
4998
  * `xcode-settings.ts` (the iOS entitlements-modification setting that makes a REBUILD work).
4781
4999
  */
4782
5000
  /** The profile of a pass whose caller names none: the store profile, warnings dropped. */
@@ -4824,8 +5042,8 @@ async function patchIos(projectDirectory, genDirectory, runner) {
4824
5042
  }
4825
5043
  /**
4826
5044
  * The Android half of {@link patchMobile}: the build-profile patches, the release signing
4827
- * block, the main activity's manifest attributes, the status bar style, then the runner
4828
- * command when the caller supplies a runner.
5045
+ * block, the main activity's manifest attributes, the status bar style, the window
5046
+ * background, then the runner command when the caller supplies a runner.
4829
5047
  *
4830
5048
  * @param options - What to patch.
4831
5049
  * @param options.projectDirectory - The Tauri project root.
@@ -4833,7 +5051,8 @@ async function patchIos(projectDirectory, genDirectory, runner) {
4833
5051
  * @param options.runner - The absolute Node/tauri.js runner pair, or undefined to keep it.
4834
5052
  * @param options.signing - The full signing config (only `.android` is consulted).
4835
5053
  * @param options.manifest - Android manifest entries for the main activity.
4836
- * @param options.backgroundColor - `app.backgroundColor`, which the status bar icons follow.
5054
+ * @param options.backgroundColor - `app.backgroundColor`, which the status bar icons and the
5055
+ * window background follow.
4837
5056
  * @param options.profile - The Android build profile.
4838
5057
  * @returns The paths patched vs. left unchanged, merged over every patch.
4839
5058
  * @throws {Error} When the `gen/android` tree (or its `app/build.gradle.kts`) is missing, the
@@ -4853,7 +5072,8 @@ async function patchAndroid(options) {
4853
5072
  }),
4854
5073
  await patchAndroidSigning(projectDirectory, genDirectory, options.signing.android ?? {}, debugKeystore),
4855
5074
  await patchAndroidManifest(projectDirectory, genDirectory, options.manifest),
4856
- await patchAndroidSystemBars(projectDirectory, genDirectory, options.backgroundColor)
5075
+ await patchAndroidSystemBars(projectDirectory, genDirectory, options.backgroundColor),
5076
+ await patchAndroidWindowBackground(projectDirectory, genDirectory, options.backgroundColor)
4857
5077
  ];
4858
5078
  if (!runner) return mergePatchResults(...androidResults);
4859
5079
  const runnerResult = await patchRunner(projectDirectory, genDirectory, {
@@ -4865,9 +5085,10 @@ async function patchAndroid(options) {
4865
5085
  /**
4866
5086
  * Deterministic, idempotent post-init patch pass over an existing complete gen/ tree.
4867
5087
  * Android gets, in this order, its build-profile patches, its release signing block, the
4868
- * main activity's manifest attributes, the system bar style in MainActivity.kt, then the
4869
- * runner command. The profile patches run before signing so that the store profile cuts
4870
- * its Gradle block out byte for byte, wherever the signing block sits. iOS gets the Xcode
5088
+ * main activity's manifest attributes, the system bar style in MainActivity.kt, the window
5089
+ * and icon-splash background in the app theme, then the runner command. The profile
5090
+ * patches run before signing so that the store profile cuts its Gradle block out byte for
5091
+ * byte, wherever the signing block sits. iOS gets the Xcode
4871
5092
  * entitlements-modification setting (without it the SECOND build of the same tree fails),
4872
5093
  * then the runner command. The runner rewrite runs only when the caller supplies a
4873
5094
  * `runner`. iOS takes no manifest entries, no background colour and no profile: its
@@ -4878,14 +5099,15 @@ async function patchAndroid(options) {
4878
5099
  * @param opts - The mobile platform, and optionally the absolute Node/tauri.js runner pair.
4879
5100
  * @param signing - The full signing config (only `.android` is consulted).
4880
5101
  * @param manifest - Android manifest entries for the main activity (ignored on iOS).
4881
- * @param backgroundColor - `app.backgroundColor`; the Android status bar icons follow it
4882
- * (ignored on iOS).
5102
+ * @param backgroundColor - `app.backgroundColor`; the Android status bar icons, window
5103
+ * background and icon-splash background follow it (ignored on iOS).
4883
5104
  * @param profile - The Android build profile; the store profile when omitted.
4884
5105
  * @returns The paths patched vs. left unchanged, one merged report over every patch.
4885
5106
  * @throws {Error} When the Android `gen/android` tree (or its `app/build.gradle.kts`) is
4886
5107
  * missing, the debug keystore is missing in the debug profile (before anything is
4887
5108
  * written), manifest entries meet a missing manifest or an unclear main activity, or a
4888
- * background colour meets a tree without exactly one MainActivity.kt to style.
5109
+ * background colour meets a tree without exactly one MainActivity.kt to style or without
5110
+ * the app theme to set the window background in.
4889
5111
  */
4890
5112
  async function patchMobile(projectDirectory, opts, signing, manifest = [], backgroundColor, profile = STORE_PROFILE) {
4891
5113
  const genDirectory = genDirectoryPath(projectDirectory, opts.target);
@@ -5502,7 +5724,8 @@ function createProjectApi(ctx) {
5502
5724
  };
5503
5725
  /**
5504
5726
  * Implements {@link Api.patchMobile}: hands Android its build profile, its manifest
5505
- * entries and `app.backgroundColor` (the status bar icons follow it), then logs.
5727
+ * entries and `app.backgroundColor` (the status bar icons and the window background
5728
+ * follow it), then logs.
5506
5729
  *
5507
5730
  * @param opts - See {@link Api.patchMobile}.
5508
5731
  * @returns See {@link Api.patchMobile}.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@moku-labs/native",
3
- "version": "0.3.9",
3
+ "version": "0.3.11",
4
4
  "description": "Node-only native packager framework for Moku — generates a gitignored Tauri project, codegens capabilities/Info.plist/AndroidManifest from composed system plugins, and runs tauri build.",
5
5
  "license": "MIT",
6
6
  "type": "module",