1import { AndroidConfig, ConfigPlugin, withDangerousMod, XML } from '@expo/config-plugins';
2
3import { SplashScreenConfig } from './getAndroidSplashConfig';
4
5export const withAndroidSplashDrawables: ConfigPlugin<Pick<SplashScreenConfig, 'resizeMode'>> = (
6  config,
7  splash
8) => {
9  return withDangerousMod(config, [
10    'android',
11    async (config) => {
12      if (splash) {
13        await setSplashDrawableAsync(splash, config.modRequest.projectRoot);
14      }
15      return config;
16    },
17  ]);
18};
19
20export async function setSplashDrawableAsync(
21  { resizeMode }: Pick<SplashScreenConfig, 'resizeMode'>,
22  projectRoot: string
23) {
24  const filePath = (await AndroidConfig.Paths.getResourceXMLPathAsync(projectRoot, {
25    name: 'splashscreen',
26    kind: 'drawable',
27  }))!;
28
29  // Nuke and rewrite the splashscreen.xml drawable
30  const xmlContent = {
31    'layer-list': {
32      $: {
33        'xmlns:android': 'http://schemas.android.com/apk/res/android',
34      },
35      item: [
36        {
37          $: {
38            // TODO: Ensure these keys don't get out of sync
39            'android:drawable': '@color/splashscreen_background',
40          },
41        },
42        // Only include the image if resizeMode native is in-use.
43        resizeMode === 'native' && {
44          bitmap: [
45            {
46              $: {
47                'android:gravity': 'center',
48                // TODO: Ensure these keys don't get out of sync
49                'android:src': '@drawable/splashscreen_image',
50              },
51            },
52          ],
53        },
54      ].filter(Boolean),
55    },
56  };
57  await XML.writeXMLAsync({ path: filePath, xml: xmlContent });
58}
59