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

withAndroidTabletOrientation.cjs

68 lines2.1 KB

1const { 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 return withMainActivity(config, (nextConfig) => {
38 let contents = nextConfig.modResults.contents;
39 if (nextConfig.modResults.language !== "kt") {
40 throw new Error("withAndroidTabletOrientation: MainActivity must be Kotlin.");
41 }
42 if (contents.includes("SCREEN_ORIENTATION_FULL_USER")) {
43 return nextConfig;
44 }
45​
46 contents = insertAfter(
47 contents,
48 "import android.os.Bundle",
49 "\nimport android.content.pm.ActivityInfo\nimport android.content.res.Configuration",
50 "the android.os.Bundle import",
51 );
52 contents = insertAfter(
53 contents,
54 "class MainActivity : ReactActivity() {",
55 ORIENTATION_METHODS,
56 "the MainActivity class declaration",
57 );
58 contents = insertAfter(
59 contents,
60 "super.onCreate(null)",
61 ORIENTATION_ON_CREATE_CALL,
62 "the super.onCreate call",
63 );
64​
65 nextConfig.modResults.contents = contents;
66 return nextConfig;
67 });
68};