stripe / stripe-react-native

React Native library for Stripe.
https://stripe.dev/stripe-react-native
MIT License
1.29k stars 263 forks source link

Android custom fonts with expo #1758

Open kjossendal opened 1 month ago

kjossendal commented 1 month ago

Is your feature request related to a problem? Please describe. Expo stores font assets /assets/fonts while in order to use custom fonts in the appearance property of initPaymentSheet, font files need to be available in /android/app/src/main/res/font.

Describe the solution you'd like It would be nice if this just worked with expo and the sdk could read fonts from /assets/fonts without ejecting.

Describe alternatives you've considered I've made a config plugin that copies assets at build time as a temporary fix

Additional context Add any other context or screenshots about the feature request here.

kjossendal commented 1 month ago

The plugin is as follows and copies and transforms fonts to the required place. Use at your own risk.

const { withDangerousMod } = require("@expo/config-plugins");
const fs = require("fs-extra");
const path = require("path");

const FONT_ASSETS_PATH = "assets/fonts"; // The folder where Expo stores fonts
const ANDROID_RES_FONT_PATH = "android/app/src/main/res/font"; // Target folder in Android

const copyFontsToAndroidRes = (projectRoot) => {
  const fontsSourcePath = path.resolve(projectRoot, FONT_ASSETS_PATH);
  const fontsTargetPath = path.resolve(projectRoot, ANDROID_RES_FONT_PATH);

  // Check if fonts folder exists
  if (!fs.existsSync(fontsSourcePath)) {
    console.warn(`No fonts found at: ${fontsSourcePath}`);
    return;
  }

  // Ensure target directory exists
  fs.ensureDirSync(fontsTargetPath);

  // Read all font files from the source directory
  const fontFiles = fs.readdirSync(fontsSourcePath).filter((file) => file.endsWith(".ttf"));

  // Copy and transform each font file
  fontFiles.forEach((file) => {
    const transformedFileName = file.toLowerCase().replace(/[_-]/g, "");
    const sourceFilePath = path.join(fontsSourcePath, file);
    const targetFilePath = path.join(fontsTargetPath, transformedFileName);

    fs.copySync(sourceFilePath, targetFilePath, { overwrite: true });
  });

  console.log(`Fonts copied to: ${fontsTargetPath}`);
};

module.exports = function withCustomStripeFontsPlugin(config) {
  // Use withDangerousMod to hook into the Android build process
  // but only to access projectRoot so it should be pretty safe
  return withDangerousMod(config, [
    "android",
    async (config) => {
      const projectRoot = config.modRequest.projectRoot;
      // Copy fonts to Android res/font folder
      copyFontsToAndroidRes(projectRoot);

      return config;
    },
  ]);
};
MPJHorner commented 5 days ago

Any newer/better fix for this?