Open History to see the last commit
1const { withMainActivity } = require("expo/config-plugins");
2
3// FULL_USER allows all four orientations while still respecting the user's
4// auto-rotate lock, matching iPad behavior. Foldables change smallestScreenWidthDp on
5// fold/unfold without recreating the activity (smallestScreenSize is in the
6// manifest's configChanges), so the policy is re-evaluated in onConfigurationChanged:
7// unfolding past the tablet breakpoint unlocks rotation, and folding back restores
8// the portrait lock.
9
10const ORIENTATION_METHODS = `
11 // Applied in onCreate and re-applied on fold/unfold; added by
12 // withAndroidTabletOrientation.
13 override fun onConfigurationChanged(newConfig: Configuration) {
14 super.onConfigurationChanged(newConfig)
15 applyTabletOrientation()
16 }
17
18 private fun applyTabletOrientation() {
19 requestedOrientation = if (resources.configuration.smallestScreenWidthDp >= 600) {
20 ActivityInfo.SCREEN_ORIENTATION_FULL_USER
21 } else {
22 ActivityInfo.SCREEN_ORIENTATION_PORTRAIT
23 }
24 }
25`;
26
27const ORIENTATION_ON_CREATE_CALL = `
28 applyTabletOrientation()`;
29
30function insertAfter(contents, anchor, insertion, description) {
31 const index = contents.indexOf(anchor);
32 if (index === -1) {
33 throw new Error(
34 `withAndroidTabletOrientation: could not find ${description} in MainActivity — the Expo template changed; update the plugin anchors.`,
35 );
36 }
37 const end = index + anchor.length;
38 return contents.slice(0, end) + insertion + contents.slice(end);
39}
40
41module.exports = function withAndroidTabletOrientation(config) {
42 return withMainActivity(config, (nextConfig) => {
43 let contents = nextConfig.modResults.contents;
44 if (nextConfig.modResults.language !== "kt") {
45 throw new Error("withAndroidTabletOrientation: MainActivity must be Kotlin.");
46 }
47 if (contents.includes("SCREEN_ORIENTATION_FULL_USER")) {
48 return nextConfig;
49 }
50
51 contents = insertAfter(
52 contents,
53 "import android.os.Bundle",
54 "\nimport android.content.pm.ActivityInfo\nimport android.content.res.Configuration",
55 "the android.os.Bundle import",
56 );
57 contents = insertAfter(
58 contents,
59 "class MainActivity : ReactActivity() {",
60 ORIENTATION_METHODS,
61 "the MainActivity class declaration",
62 );
63 contents = insertAfter(
64 contents,
65 "super.onCreate(null)",
66 ORIENTATION_ON_CREATE_CALL,
67 "the super.onCreate call",
68 );
69
70 nextConfig.modResults.contents = contents;
71 return nextConfig;
72 });
73};