Skip to content

fix(generate): add support for Expo Router app directory prompts #2905

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 16 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
87 changes: 3 additions & 84 deletions boilerplate/src/app/index.tsx
Original file line number Diff line number Diff line change
@@ -1,86 +1,5 @@
// @mst replace-next-line
import { observer } from "mobx-react-lite"
import { Image, ImageStyle, TextStyle, View, ViewStyle } from "react-native"
import { Screen, Text } from "@/components"
import { isRTL } from "@/i18n"
import { ThemedStyle } from "@/theme"
import { useSafeAreaInsetsStyle } from "@/utils/useSafeAreaInsetsStyle"
import { useAppTheme } from "@/utils/useAppTheme"
import { WelcomeScreen } from '@/screens/WelcomeScreen'

const welcomeLogo = require("../../assets/images/logo.png")
const welcomeFace = require("../../assets/images/welcome-face.png")

// @mst replace-next-line export default function WelcomeScreen() {
export default observer(function WelcomeScreen() {
const $bottomContainerInsets = useSafeAreaInsetsStyle(["bottom"])
const { theme, themed } = useAppTheme()

return (
<Screen safeAreaEdges={["top"]} contentContainerStyle={themed($container)}>
<View style={themed($topContainer)}>
<Image style={themed($welcomeLogo)} source={welcomeLogo} resizeMode="contain" />
<Text
testID="welcome-heading"
style={themed($welcomeHeading)}
tx="welcomeScreen:readyForLaunch"
preset="heading"
/>
<Text tx="welcomeScreen:exciting" preset="subheading" />
<Image
style={$welcomeFace}
source={welcomeFace}
resizeMode="contain"
tintColor={theme.colors.palette.neutral900}
/>
</View>

<View style={[themed($bottomContainer), $bottomContainerInsets]}>
<Text tx="welcomeScreen:postscript" size="md" />
</View>
</Screen>
)
// @mst replace-next-line }
})

const $container: ThemedStyle<ViewStyle> = ({ colors }) => ({
flex: 1,
backgroundColor: colors.background,
})

const $topContainer: ThemedStyle<ViewStyle> = ({ spacing }) => ({
flexShrink: 1,
flexGrow: 1,
flexBasis: "57%",
justifyContent: "center",
paddingHorizontal: spacing.lg,
})

const $bottomContainer: ThemedStyle<ViewStyle> = ({ colors, spacing }) => ({
flexShrink: 1,
flexGrow: 0,
flexBasis: "43%",
backgroundColor: colors.palette.neutral100,
borderTopLeftRadius: 16,
borderTopRightRadius: 16,
paddingHorizontal: spacing.lg,
justifyContent: "space-around",
})

const $welcomeLogo: ThemedStyle<ImageStyle> = ({ spacing }) => ({
height: 88,
width: "100%",
marginBottom: spacing.xxl,
})

const $welcomeFace: ImageStyle = {
height: 169,
width: 269,
position: "absolute",
bottom: -47,
right: -80,
transform: [{ scaleX: isRTL ? -1 : 1 }],
export default function Index() {
return <WelcomeScreen />
}

const $welcomeHeading: ThemedStyle<TextStyle> = ({ spacing }) => ({
marginBottom: spacing.md,
})
86 changes: 86 additions & 0 deletions boilerplate/src/screens/WelcomeScreen.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,86 @@
// @mst replace-next-line
import { observer } from "mobx-react-lite"
import { Image, ImageStyle, TextStyle, View, ViewStyle } from "react-native"
import { Screen, Text } from "@/components"
import { isRTL } from "@/i18n"
import { ThemedStyle } from "@/theme"
import { useSafeAreaInsetsStyle } from "@/utils/useSafeAreaInsetsStyle"
import { useAppTheme } from "@/utils/useAppTheme"

const welcomeLogo = require("../../assets/images/logo.png")
const welcomeFace = require("../../assets/images/welcome-face.png")

// @mst replace-next-line export function WelcomeScreen() {
export const WelcomeScreen = observer(function WelcomeScreen() {
const $bottomContainerInsets = useSafeAreaInsetsStyle(["bottom"])
const { theme, themed } = useAppTheme()

return (
<Screen safeAreaEdges={["top"]} contentContainerStyle={themed($container)}>
<View style={themed($topContainer)}>
<Image style={themed($welcomeLogo)} source={welcomeLogo} resizeMode="contain" />
<Text
testID="welcome-heading"
style={themed($welcomeHeading)}
tx="welcomeScreen:readyForLaunch"
preset="heading"
/>
<Text tx="welcomeScreen:exciting" preset="subheading" />
<Image
style={$welcomeFace}
source={welcomeFace}
resizeMode="contain"
tintColor={theme.colors.palette.neutral900}
/>
</View>

<View style={[themed($bottomContainer), $bottomContainerInsets]}>
<Text tx="welcomeScreen:postscript" size="md" />
</View>
</Screen>
)
// @mst replace-next-line }
})

const $container: ThemedStyle<ViewStyle> = ({ colors }) => ({
flex: 1,
backgroundColor: colors.background,
})

const $topContainer: ThemedStyle<ViewStyle> = ({ spacing }) => ({
flexShrink: 1,
flexGrow: 1,
flexBasis: "57%",
justifyContent: "center",
paddingHorizontal: spacing.lg,
})

const $bottomContainer: ThemedStyle<ViewStyle> = ({ colors, spacing }) => ({
flexShrink: 1,
flexGrow: 0,
flexBasis: "43%",
backgroundColor: colors.palette.neutral100,
borderTopLeftRadius: 16,
borderTopRightRadius: 16,
paddingHorizontal: spacing.lg,
justifyContent: "space-around",
})

const $welcomeLogo: ThemedStyle<ImageStyle> = ({ spacing }) => ({
height: 88,
width: "100%",
marginBottom: spacing.xxl,
})

const $welcomeFace: ImageStyle = {
height: 169,
width: 269,
position: "absolute",
bottom: -47,
right: -80,
transform: [{ scaleX: isRTL ? -1 : 1 }],
}

const $welcomeHeading: ThemedStyle<TextStyle> = ({ spacing }) => ({
marginBottom: spacing.md,
})
64 changes: 60 additions & 4 deletions src/commands/generate.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { GluegunToolbox } from "gluegun"
import { boolFlag } from "../tools/flag"
import { generateFromTemplate, runGenerator } from "../tools/generators"
import { command, heading, p, warning } from "../tools/pretty"
import { frontMatterDirectoryDir, generateFromTemplate, runGenerator } from "../tools/generators"
import { command, heading, p, prettyPrompt, warning } from "../tools/pretty"
import { Options } from "./new"

const SUB_DIR_DELIMITER = "/"
Expand All @@ -16,13 +16,13 @@ module.exports = {
}

async function generate(toolbox: GluegunToolbox) {
const { parameters, strings } = toolbox
const { parameters, strings, filesystem, prompt } = toolbox

// what generator are we running?
const generator = parameters.first.toLowerCase()

// check if we should override front matter dir or default dir
const dir = parameters.options.dir ?? parameters.third
let dir = parameters.options.dir ?? parameters.third

// we need a name for this component
let name = parameters.second
Expand Down Expand Up @@ -52,6 +52,62 @@ async function generate(toolbox: GluegunToolbox) {
pascalName = pascalName.slice(0, -1 * pascalGenerator.length)
command(`npx ignite-cli generate ${generator} ${pascalName}`)
}
/**
* Check if the project uses Expo Router as a dependency in package.json,
* denoting an Expo Router app.
*/
if (generator === "route") {
const packageJson = filesystem.read("package.json", "json")
const isExpoRouterApp = !!packageJson?.dependencies?.["expo-router"]

const isSrcAppStructure = filesystem.exists("src/app") === "dir"
const isAppStructure = filesystem.exists("app") === "dir"
const defaultRouterDir = isSrcAppStructure ? "src/app" : isAppStructure ? "app" : null

if (isExpoRouterApp) {
const directoryDirSetInFrontMatter = frontMatterDirectoryDir("route")
p(directoryDirSetInFrontMatter)

if (directoryDirSetInFrontMatter || dir) {
heading(
`It looks like you're working in a project using Expo Router, determined directory for route from ${dir ? "override" : "template front matter"}`,
)
dir = dir || directoryDirSetInFrontMatter
} else {
const result = await prompt.ask({
type: "input",
name: "dir",
message: `It looks like you're working in a project using Expo Router, please enter the desired directory${defaultRouterDir ? ` (e.g., ${defaultRouterDir})` : ""}:`,
initial: defaultRouterDir,
})

if (result.dir) {
// Validate the directory
const isValidDir = filesystem.exists(result.dir) === "dir"
if (isValidDir) {
dir = result.dir
} else {
const createDirResult = await prompt.ask({
type: "confirm",
name: "createDir",
message: `⚠️ Directory ${result.dir} does not exist. Would you like to create it?`,
initial: true,
format: prettyPrompt.format.boolean,
})

if (createDirResult.createDir) {
filesystem.dir(result.dir)
dir = result.dir
} else {
warning(`⚠️ Placing screen in ${result.dir} root.`)
p()
dir = result.dir
}
}
}
}
}
}

// okay, let's do it!
p()
Expand Down
22 changes: 18 additions & 4 deletions src/commands/new.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,11 +5,13 @@ import {
copyBoilerplate,
renameReactNativeApp,
replaceMaestroBundleIds,
createExpoRouterScreenTemplate,
refactorExpoRouterReactotronCmds,
updateExpoRouterSrcDir,
cleanupExpoRouterConversion,
updatePackagerCommandsInReadme,
createGeneratorTemplate,
EXPO_ROUTER_SCREEN_TEMPLATE,
EXPO_ROUTER_ROUTE_TEMPLATE,
} from "../tools/react-native"
import { packager, PackagerName } from "../tools/packager"
import {
Expand Down Expand Up @@ -860,16 +862,28 @@ module.exports = {
* 1. Move all files from app/ to src/
* 2. Update code refs to app/ with src/
* 3. Refactor Reactotron commands to use `router` instead of refs to react navigation
* 4. Create a screen template that makes sense for Expo Router
* 4. Create screen and route generator templates that makes sense for Expo Router
* 5. Clean up - move ErrorBoundary to proper spot and remove unused files
*/
filesystem
.cwd(targetPath)
.find("app")
.forEach((file) => filesystem.cwd(targetPath).move(file, file.replace("app", "src")))
.forEach((file) => {
// skip copying anything in app/screens but the error screen
if (file.includes("screens") && !file.includes("Error")) {
return
}
filesystem.cwd(targetPath).move(file, file.replace("app", "src"))
})
updateExpoRouterSrcDir(toolbox)
refactorExpoRouterReactotronCmds(toolbox)
createExpoRouterScreenTemplate(toolbox)
const screenTplPath = filesystem.path(
targetPath,
"ignite/templates/screen/NAMEScreen.tsx.ejs",
)
const routerTplPath = filesystem.path(targetPath, "ignite/templates/route/NAME.tsx.ejs")
createGeneratorTemplate(toolbox, screenTplPath, EXPO_ROUTER_SCREEN_TEMPLATE)
createGeneratorTemplate(toolbox, routerTplPath, EXPO_ROUTER_ROUTE_TEMPLATE)
cleanupExpoRouterConversion(toolbox, targetPath)

stopSpinner(expoRouterMsg, "🧭")
Expand Down
24 changes: 24 additions & 0 deletions src/tools/generators.ts
Original file line number Diff line number Diff line change
Expand Up @@ -169,6 +169,11 @@ function igniteDir() {
}

function appDir() {
const routerPath = filesystem.path(cwd(), "src/app")
if (filesystem.exists(routerPath) === "dir") {
return filesystem.path(cwd(), "src")
}

return filesystem.path(cwd(), "app")
}

Expand Down Expand Up @@ -354,6 +359,25 @@ export async function generateFromTemplate(
return { written, exists, overwritten }
}

/**
* Checks a file for a directoryDir in template front matter.
*/
export function frontMatterDirectoryDir(generator: string): string | undefined {
if (!validateGenerator(generator)) {
return undefined
}

const { path } = filesystem

// where are we copying from?
const templateDir = path(templatesDir(), generator)

const fileContents = filesystem.read(`${templateDir}/NAME.tsx.ejs`)
const { data: frontMatterData } = frontMatter(fileContents)

return frontMatterData?.destinationDir
}

/**
* Ignite cli root directory
*/
Expand Down
Loading