Skip to content

Commit 617bb1d

Browse files
fix(mobile): verify Android window density lifecycle generation
1 parent de398f8 commit 617bb1d

3 files changed

Lines changed: 114 additions & 45 deletions

File tree

‎apps/mobile/app.config.ts‎

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -459,8 +459,7 @@ const config: ExpoConfig = {
459459
"./plugins/withAndroidModernPopupMenu.cjs",
460460
"./plugins/withAndroidModernAlertDialog.cjs",
461461
"./plugins/withAndroidPredictiveBackCompat.cjs",
462-
// Listed before withAndroidTabletOrientation so its MainActivity mod runs
463-
// after that one's and extends the onConfigurationChanged override it adds.
462+
// MainActivity mods run in reverse order; extend the tablet-orientation override.
464463
"./plugins/withAndroidWindowDisplayMetrics.cjs",
465464
"./plugins/withAndroidTabletOrientation.cjs",
466465
...(isIosPersonalTeamBuild ? ["./plugins/withoutIosPersonalTeamCapabilities.cjs"] : []),

‎apps/mobile/plugins/withAndroidWindowDisplayMetrics.cjs‎

Lines changed: 20 additions & 43 deletions
Original file line numberDiff line numberDiff line change
@@ -1,22 +1,12 @@
11
const { withMainActivity } = require("expo/config-plugins");
22

3-
// React Native converts dp/sp to pixels (PixelUtil, text measurement) with the
4-
// density in DisplayMetricsHolder, which it fills from the application context:
5-
// `defaultDisplay.getRealMetrics()` there is always the built-in screen. When the
6-
// activity runs on an external display (Pixel Desktop, Samsung DeX), Fabric
7-
// lays the surface out with the window's density but measures text with the
8-
// phone's, so text gets line boxes sized for a different density and is clipped
9-
// and overlapped. Re-point the holder at the activity's own display after React
10-
// Native fills it. The root view's constructor re-reads it from the application
11-
// context, and Expo's delegate builds that view after onCreate returns, so bind
12-
// when the view is handed to setContentView (before the first JS commit can
13-
// measure text), and again after every configuration change, where ReactHost
14-
// re-reads it too. On the built-in screen the two are the same metrics, so this
15-
// is a no-op there.
16-
17-
const BIND_METHOD = `
18-
// Keeps React Native on this window's display density; added by
19-
// withAndroidWindowDisplayMetrics.
3+
// React Native measures text with application-display density, which differs
4+
// from the activity on external displays. Expo constructs its root after
5+
// onCreate, resetting those metrics; ReactHost resets them on configuration
6+
// changes too. Rebind after both, before text is measured.
7+
const DISPLAY_METRICS_METHODS = `
8+
// Keep deprecated APIs to match React Native screen metrics on Android 24+.
9+
// Physical display metrics omit the configured font scale.
2010
@Suppress("DEPRECATION")
2111
private fun bindWindowDisplayMetrics() {
2212
val windowMetrics = resources.displayMetrics
@@ -26,33 +16,14 @@ const BIND_METHOD = `
2616
metrics.scaledDensity = windowMetrics.scaledDensity
2717
DisplayMetricsHolder.setScreenDisplayMetrics(metrics)
2818
}
29-
`;
30-
31-
const CONFIGURATION_CHANGED_METHOD = `
32-
// Re-binds after ReactHost re-reads display metrics; added by
33-
// withAndroidWindowDisplayMetrics.
34-
override fun onConfigurationChanged(newConfig: Configuration) {
35-
super.onConfigurationChanged(newConfig)
36-
bindWindowDisplayMetrics()
37-
}
38-
`;
3919
40-
const SET_CONTENT_VIEW_METHOD = `
41-
// React Native's root view re-reads display metrics when it is constructed,
42-
// just before it is set as the content view; added by
43-
// withAndroidWindowDisplayMetrics.
20+
// Expo constructs the root view after onCreate; its constructor resets metrics.
4421
override fun setContentView(view: View?) {
4522
super.setContentView(view)
4623
bindWindowDisplayMetrics()
4724
}
4825
`;
4926

50-
const CONFIGURATION_CHANGED_SIGNATURE =
51-
"override fun onConfigurationChanged(newConfig: Configuration) {";
52-
53-
const BIND_CALL = `
54-
bindWindowDisplayMetrics()`;
55-
5627
function insertAfter(contents, anchor, insertion, description) {
5728
const index = contents.indexOf(anchor);
5829
if (index === -1) {
@@ -92,27 +63,33 @@ module.exports = function withAndroidWindowDisplayMetrics(config) {
9263
contents = insertAfter(
9364
contents,
9465
"class MainActivity : ReactActivity() {",
95-
BIND_METHOD + SET_CONTENT_VIEW_METHOD,
66+
DISPLAY_METRICS_METHODS,
9667
"the MainActivity class declaration",
9768
);
98-
// Another plugin (withAndroidTabletOrientation) may already override
99-
// onConfigurationChanged; extend it rather than declaring a second override.
100-
const overrideStart = contents.indexOf(CONFIGURATION_CHANGED_SIGNATURE);
69+
// Extend the tablet-orientation override, after ReactHost resets metrics.
70+
const overrideStart = contents.indexOf(
71+
"override fun onConfigurationChanged(newConfig: Configuration) {",
72+
);
10173
if (overrideStart !== -1) {
10274
contents =
10375
contents.slice(0, overrideStart) +
10476
insertAfter(
10577
contents.slice(overrideStart),
10678
"super.onConfigurationChanged(newConfig)",
107-
BIND_CALL,
79+
"\n bindWindowDisplayMetrics()",
10880
"the super call in the onConfigurationChanged override",
10981
);
11082
} else {
11183
contents = addImport(contents, "import android.content.res.Configuration");
11284
contents = insertAfter(
11385
contents,
11486
"class MainActivity : ReactActivity() {",
115-
CONFIGURATION_CHANGED_METHOD,
87+
`
88+
override fun onConfigurationChanged(newConfig: Configuration) {
89+
super.onConfigurationChanged(newConfig)
90+
bindWindowDisplayMetrics()
91+
}
92+
`,
11693
"the MainActivity class declaration",
11794
);
11895
}
Lines changed: 93 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,93 @@
1+
import * as NodeChildProcess from "node:child_process";
2+
import * as NodeFS from "node:fs";
3+
import * as NodeModule from "node:module";
4+
import * as NodeOS from "node:os";
5+
import * as NodePath from "node:path";
6+
import { afterEach, describe, expect, it } from "vite-plus/test";
7+
8+
const require = NodeModule.createRequire(import.meta.url);
9+
const { compileModsAsync } = require("expo/config-plugins");
10+
const { getConfig } = require("expo/config");
11+
const template = NodeChildProcess.execFileSync(
12+
"tar",
13+
[
14+
"-xOf",
15+
NodePath.join(NodePath.dirname(require.resolve("expo/package.json")), "template.tgz"),
16+
"package/android/app/src/main/java/com/helloworld/MainActivity.kt",
17+
],
18+
{ encoding: "utf8" },
19+
);
20+
const projectRoots = [];
21+
22+
afterEach(() => {
23+
for (const root of projectRoots.splice(0)) NodeFS.rmSync(root, { recursive: true, force: true });
24+
});
25+
26+
async function prebuildMainActivity(contents) {
27+
const projectRoot = NodeFS.mkdtempSync(NodePath.join(NodeOS.tmpdir(), "display-metrics-plugin-"));
28+
projectRoots.push(projectRoot);
29+
const activityPath = NodePath.join(
30+
projectRoot,
31+
"android/app/src/main/java/com/helloworld/MainActivity.kt",
32+
);
33+
NodeFS.mkdirSync(NodePath.dirname(activityPath), { recursive: true });
34+
NodeFS.writeFileSync(activityPath, contents);
35+
const { exp } = getConfig(NodePath.resolve(import.meta.dirname, ".."), {
36+
isModdedConfig: true,
37+
});
38+
// Keep the app's registration order: Expo executes same-type mods in reverse.
39+
// Unrelated native-file mods need the rest of a complete prebuild project.
40+
const mainActivity = exp.mods?.android?.mainActivity;
41+
await compileModsAsync(
42+
{ ...exp, mods: { android: mainActivity ? { mainActivity } : {} } },
43+
{ projectRoot, platforms: ["android"] },
44+
);
45+
return NodeFS.readFileSync(activityPath, "utf8");
46+
}
47+
48+
function methodBody(contents, name) {
49+
const methods = [
50+
...contents.matchAll(
51+
new RegExp(`^ (?:override|private) fun ${name}\\([^]*?\\) \\{\\n([^]*?)^ \\}`, "gm"),
52+
),
53+
];
54+
expect(methods, `exactly one ${name} declaration`).toHaveLength(1);
55+
return methods[0][1].trim();
56+
}
57+
58+
describe("withAndroidWindowDisplayMetrics", () => {
59+
it("rebinds the generated activity after root installation and configuration changes, preserving orientation", async () => {
60+
const result = await prebuildMainActivity(template);
61+
62+
expect(methodBody(result, "setContentView")).toMatch(
63+
/^super\.setContentView\(view\)\s+bindWindowDisplayMetrics\(\)$/,
64+
);
65+
expect(methodBody(result, "onConfigurationChanged")).toMatch(
66+
/^super\.onConfigurationChanged\(newConfig\)\s+bindWindowDisplayMetrics\(\)\s+applyTabletOrientation\(\)$/,
67+
);
68+
const onCreate = methodBody(result, "onCreate");
69+
expect(onCreate).toContain("applyTabletOrientation()");
70+
expect(onCreate).not.toContain("bindWindowDisplayMetrics()");
71+
expect(methodBody(result, "applyTabletOrientation")).toMatch(
72+
/requestedOrientation = if \(resources\.configuration\.smallestScreenWidthDp >= 600\) \{\s+ActivityInfo\.SCREEN_ORIENTATION_FULL_USER\s+\} else \{\s+ActivityInfo\.SCREEN_ORIENTATION_PORTRAIT\s+\}/,
73+
);
74+
75+
const binding = methodBody(result, "bindWindowDisplayMetrics");
76+
expect(binding).toContain("val windowMetrics = resources.displayMetrics");
77+
expect(binding).toMatch(
78+
/metrics\.setTo\(windowMetrics\)\s+windowManager\.defaultDisplay\.getRealMetrics\(metrics\)\s+metrics\.scaledDensity = windowMetrics\.scaledDensity\s+DisplayMetricsHolder\.setScreenDisplayMetrics\(metrics\)/,
79+
);
80+
expect(result).toContain("import android.view.View");
81+
expect(result).toContain("import android.util.DisplayMetrics");
82+
expect(result).toContain("import com.facebook.react.uimanager.DisplayMetricsHolder");
83+
expect(result.match(/^import android\.content\.res\.Configuration$/gm)).toHaveLength(1);
84+
});
85+
86+
it("leaves the composed activity unchanged when prebuild runs again", async () => {
87+
const once = await prebuildMainActivity(template);
88+
const twice = await prebuildMainActivity(once);
89+
90+
expect(methodBody(once, "setContentView")).toContain("bindWindowDisplayMetrics()");
91+
expect(twice).toBe(once);
92+
});
93+
});

0 commit comments

Comments
 (0)