Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

withAndroidTabletOrientation.cjs

77 lines2.7 KB

1const { AndroidConfig, withAndroidManifest, withMainActivity } = require("expo/config-plugins");
2​
3// FULL_USER respects rotation lock. Foldables change smallestScreenWidthDp without recreating the activity.
4​
5const ORIENTATION_METHODS = `
6 // Applied in onCreate and re-applied on fold/unfold; added by
7 // withAndroidTabletOrientation.
8 override fun onConfigurationChanged(newConfig: Configuration) {
9 super.onConfigurationChanged(newConfig)
10 applyTabletOrientation()
11 }
12​
13 private fun applyTabletOrientation() {
14 requestedOrientation = if (resources.configuration.smallestScreenWidthDp >= 600) {
15 ActivityInfo.SCREEN_ORIENTATION_FULL_USER
16 } else {
17 ActivityInfo.SCREEN_ORIENTATION_PORTRAIT
18 }
19 }
20`;
21​
22const ORIENTATION_ON_CREATE_CALL = `
23 applyTabletOrientation()`;
24​
25function insertAfter(contents, anchor, insertion, description) {
26 const index = contents.indexOf(anchor);
27 if (index === -1) {
28 throw new Error(
29 `withAndroidTabletOrientation: could not find ${description} in MainActivity — the Expo template changed; update the plugin anchors.`,
30 );
31 }
32 const end = index + anchor.length;
33 return contents.slice(0, end) + insertion + contents.slice(end);
35​
36module.exports = function withAndroidTabletOrientation(config) {
37 config = withAndroidManifest(config, (nextConfig) => {
38 const mainActivity = AndroidConfig.Manifest.getMainActivityOrThrow(nextConfig.modResults);
39 delete mainActivity.$["android:screenOrientation"];
40 return nextConfig;
41 });
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 contents = insertAfter(
49 contents,
50 "import android.os.Bundle",
51 "\nimport android.content.pm.ActivityInfo\nimport android.content.res.Configuration",
52 "the android.os.Bundle import",
53 );
54 contents = insertAfter(
55 contents,
56 "class MainActivity : ReactActivity() {",
57 ORIENTATION_METHODS,
58 "the MainActivity class declaration",
59 );
60 }
61​
62 // Relocate the call in existing native projects too, before splash setup and React content.
63 contents = contents.replace(
64 /override fun onCreate\(savedInstanceState: Bundle\?\) \{[\s\S]*?\n \}/,
65 (onCreate) => onCreate.replace(/\n[ \t]*applyTabletOrientation\(\)/g, ""),
66 );
67 contents = insertAfter(
68 contents,
69 "override fun onCreate(savedInstanceState: Bundle?) {",
70 ORIENTATION_ON_CREATE_CALL,
71 "the onCreate declaration",
72 );
73​
74 nextConfig.modResults.contents = contents;
75 return nextConfig;
76 });
77};