Skip to content
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

feat/upgrades #93

Merged
merged 4 commits into from
Sep 30, 2024
Merged
Show file tree
Hide file tree
Changes from 2 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
2 changes: 1 addition & 1 deletion packages/gluestack-cli/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,7 @@
"@antfu/ni": "^0.21.12",
"@clack/prompts": "^0.6.3",
"@gluestack/ui-project-detector": "^0.1.1",
"chalk": "^5.3.0",
"chalk": "4.1.2",
"commander": "^12.0.0",
"fast-glob": "^3.3.2",
"find-package-json": "^1.2.0",
Expand Down
44 changes: 39 additions & 5 deletions packages/gluestack-cli/src/dependencies.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,15 @@
export interface Dependency {
[key: string]: string;
}
export interface ComponentConfig {
dependencies: Dependency;
devDependencies?: Dependency;
additionalComponents?: string[];
hooks?: string[];
}

export interface Dependencies {
[key: string]: {
dependencies: Dependency;
devDependencies?: Dependency;
};
[key: string]: ComponentConfig;
}

const projectBasedDependencies: Dependencies = {
Expand Down Expand Up @@ -42,6 +46,7 @@ const dependenciesConfig: Dependencies = {
'@gluestack-ui/toast': 'latest',
'@gluestack-ui/nativewind-utils': 'latest',
'react-native-svg': '13.4.0',
nativewind: '4.1.10',
},
devDependencies: {
jscodeshift: '0.15.2',
Expand Down Expand Up @@ -229,6 +234,35 @@ const dependenciesConfig: Dependencies = {
view: { dependencies: {} },
'virtualized-list': { dependencies: {} },
vstack: { dependencies: {} },
grid: {
dependencies: {},
hooks: ['useBreakpointValue'],
},
};

export { dependenciesConfig, projectBasedDependencies };
// Ignore components that are in development or not in supported list
const IgnoredComponents = ['bottomsheet'];

const getComponentDependencies = (componentName: string): ComponentConfig => {
const config = dependenciesConfig[componentName];
if (!config) {
return {
dependencies: {},
devDependencies: {},
additionalComponents: [],
hooks: [],
};
}
return {
dependencies: config.dependencies || {},
devDependencies: config.devDependencies || {},
additionalComponents: config.additionalComponents || [],
hooks: config.hooks || [],
};
};
export {
dependenciesConfig,
projectBasedDependencies,
IgnoredComponents,
getComponentDependencies,
};
65 changes: 40 additions & 25 deletions packages/gluestack-cli/src/util/add/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import { basename, join, parse } from 'path';
import { log, confirm } from '@clack/prompts';
import { config } from '../../config';
import {
checkAdditionalDependencies,
cloneRepositoryAtRoot,
getAllComponents,
installDependencies,
Expand All @@ -21,6 +22,7 @@ const componentAdder = async ({
try {
console.log(`\n\x1b[1mAdding new component...\x1b[0m\n`);
await cloneRepositoryAtRoot(join(_homeDir, config.gluestackDir));
let hooksToAdd: string[] = [];
if (
requestedComponent &&
requestedComponent !== '--all' &&
Expand All @@ -36,6 +38,9 @@ const componentAdder = async ({
? getAllComponents()
: [requestedComponent];

const { hooks } = checkAdditionalDependencies(requestedComponents);
hooksToAdd = Array.from(hooks);

const updatedComponents =
!existingComponentsChecked && showWarning && requestedComponent
? await isComponentInConfig(requestedComponents)
Expand All @@ -49,6 +54,7 @@ const componentAdder = async ({
);

await writeComponent(component, targetPath);
await hookAdder({ requestedHook: hooksToAdd[0] });
})
)
.then(async () => {
Expand Down Expand Up @@ -158,7 +164,11 @@ const confirmOverride = async (
return shouldContinue;
};

const hookAdder = async ({ requestedHook }: { requestedHook: string }) => {
const hookAdder = async ({
requestedHook,
}: {
requestedHook: string | string[];
}) => {
try {
console.log(`\n\x1b[1mAdding new hook...\x1b[0m\n`);
await cloneRepositoryAtRoot(join(_homeDir, config.gluestackDir));
Expand Down Expand Up @@ -192,32 +202,37 @@ const hookFileName = async (hook: string): Promise<string> => {
});
return fileName;
};
const writeHook = async (hook: string) => {
const fileName = await hookFileName(hook);
const utilsPath = join(
projectRootPath,
config.writableComponentsPath,
'utils',
fileName
);
const sourceFilePath = join(
_homeDir,
config.gluestackDir,
config.hooksResourcePath,
fileName
);
if (fs.existsSync(utilsPath)) {
const confirm = await confirmHookOverride(hook);
if (confirm === false) {
processTerminate('Installation aborted');
const writeHook = async (hooks: string | string[]) => {
const hooksArray = Array.isArray(hooks) ? hooks : [hooks];
for (const hook of hooksArray) {
const fileName = await hookFileName(hook);
const utilsPath = join(
projectRootPath,
config.writableComponentsPath,
'utils',
fileName
);
const sourceFilePath = join(
_homeDir,
config.gluestackDir,
config.hooksResourcePath,
fileName
);
if (fs.existsSync(utilsPath)) {
const shouldOverride = await confirmHookOverride(hook);
if (!shouldOverride) {
processTerminate('Installation aborted');
}
}
}

try {
await fs.ensureFile(utilsPath);
fs.copyFileSync(sourceFilePath, utilsPath);
} catch (error) {
log.error(`\x1b[31mError: ${(error as Error).message}\x1b[0m`);
try {
await fs.ensureFile(utilsPath);
await fs.copy(sourceFilePath, utilsPath);
} catch (error) {
log.error(
`\x1b[31mError adding hook ${hook}: ${(error as Error).message}\x1b[0m`
);
}
}
};

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -124,7 +124,7 @@ async function initNatiwindExpoApp(
} --cssPath='${cssPath}' --config='${JSON.stringify(resolvedConfig)}'`
);
execSync(
`npx jscodeshift -t ${BabeltransformerPath} ${resolvedConfig.config.babelConfig} --isSDK50='${resolvedConfig.app.sdk50}'`
`npx jscodeshift -t ${BabeltransformerPath} ${resolvedConfig.config.babelConfig} --config='${JSON.stringify(resolvedConfig)}'`
);
execSync(
`npx jscodeshift -t ${addProviderTransformerPath} ${resolvedConfig.app.entry} --cssImportPath='${cssImportPath}' --componentsPath='${config.writableComponentsPath}'`
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -66,7 +66,7 @@ async function initNatiwindRNApp(
);

execSync(
`npx jscodeshift -t ${BabelTransformerPath} ${resolvedConfig.config.babelConfig}`
`npx jscodeshift -t ${BabelTransformerPath} ${resolvedConfig.config.babelConfig} --config='${JSON.stringify(resolvedConfig)}'`
);
execSync(
`npx jscodeshift -t ${metroTransformerPath} ${resolvedConfig.config.metroConfig}`
Expand Down
39 changes: 36 additions & 3 deletions packages/gluestack-cli/src/util/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,10 +16,11 @@ import {
import {
Dependencies,
Dependency,
IgnoredComponents,
dependenciesConfig,
getComponentDependencies,
projectBasedDependencies,
} from '../dependencies';
import { installNativeWind } from './init';

const homeDir = os.homedir();
const currDir = process.cwd();
Expand All @@ -46,11 +47,43 @@ const getAllComponents = (): string[] => {
(file) =>
!['.tsx', '.ts', '.jsx', '.js', '.json'].includes(
extname(file).toLowerCase()
) && file !== config.providerComponent
) &&
file !== config.providerComponent &&
!IgnoredComponents.includes(file)
);
return componentList;
};

interface AdditionalDependencies {
components: string[];
hooks: string[];
}

function checkAdditionalDependencies(
components: string[]
): AdditionalDependencies {
const additionalDependencies: AdditionalDependencies = {
components: [],
hooks: [],
};

components.forEach((component) => {
const config = getComponentDependencies(component);

// Add additional components
config.additionalComponents?.forEach((additionalComponent) => {
additionalDependencies.components.push(additionalComponent);
});

// Add hooks
config.hooks?.forEach((hook) => {
additionalDependencies.hooks.push(hook);
});
});

return additionalDependencies;
}

const cloneRepositoryAtRoot = async (rootPath: string) => {
try {
const clonedRepoExists = await checkIfFolderExists(rootPath);
Expand Down Expand Up @@ -285,7 +318,6 @@ const installDependencies = async (
);

try {
await installNativeWind(versionManager);
let depResult;
let devDepResult;

Expand Down Expand Up @@ -572,4 +604,5 @@ export {
removeHyphen,
getRelativePath,
ensureFilesPromise,
checkAdditionalDependencies,
};
86 changes: 45 additions & 41 deletions packages/gluestack-cli/src/util/init/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -97,17 +97,7 @@ async function addProvider() {
}
}

function createDefaultTSConfig() {
return {
compilerOptions: {
paths: {
'@/*': ['./*'],
},
},
exclude: ['node_modules'],
};
}

//update tailwind.config.js and codemod
async function updateTailwindConfig(
resolvedConfig: RawConfig,
projectType: string
Expand Down Expand Up @@ -135,47 +125,62 @@ async function updateTailwindConfig(
}
}

async function updateTSConfig(
projectType: string,
configPath: string
): Promise<void> {
//updateConfig helper, create default tsconfig.json
function createDefaultTSConfig() {
return {
compilerOptions: {
paths: {
'@/*': ['./*'],
},
},
exclude: ['node_modules'],
};
}
// updateConfig helper, read tsconfig.json
async function readTSConfig(configPath: string): Promise<TSConfig> {
try {
let tsConfig: TSConfig = {};
try {
tsConfig = JSON.parse(await readFileAsync(configPath, 'utf8'));
} catch {
//write another function if file is empty
tsConfig = createDefaultTSConfig();
}
return JSON.parse(await readFileAsync(configPath, 'utf8'));
} catch {
return createDefaultTSConfig();
}
}
// updateConfig helper, update paths in tsconfig.json
function updatePaths(
paths: Record<string, string[]>,
key: string,
newValues: string[]
): void {
paths[key] = Array.from(new Set([...(paths[key] || []), ...newValues]));
}
//update tsconfig.json
async function updateTSConfig(projectType: string, config: any): Promise<void> {
try {
const configPath = config.config.tsConfig;
let tsConfig: TSConfig = await readTSConfig(configPath);
let tailwindConfig = config.tailwind.config;
const tailwindConfigFileName = tailwindConfig?.split('/').pop();

tsConfig.compilerOptions = tsConfig.compilerOptions || {};
tsConfig.compilerOptions.paths = tsConfig.compilerOptions.paths || {};

// Next.js project specific configuration
if (projectType === config.nextJsProject) {
tsConfig.compilerOptions.jsxImportSource = 'nativewind';
}
if (!tsConfig.compilerOptions.paths) {
// Case 1: Paths do not exist, add new paths
tsConfig.compilerOptions.paths = {
'@/*': ['./*'],
};
} else {
// Case 2 & 3: Paths exist, update them without undoing previous values
const paths = tsConfig.compilerOptions.paths['@/*'];
if (!paths.includes('./*')) {
// If './*' is not included, add it
paths.push('./*');
}
}
updatePaths(tsConfig.compilerOptions.paths, '@/*', ['./*']);
updatePaths(tsConfig.compilerOptions.paths, 'tailwind.config', [
`./${tailwindConfigFileName}`,
]);

await writeFileAsync(configPath, JSON.stringify(tsConfig, null, 2), 'utf8');
} catch (err) {
log.error(
`\x1b[31mError occured while installing dependencies (${
err as Error
})\x1b[0m`
`\x1b[31mError occurred while updating tsconfig.json: ${(err as Error).message}\x1b[0m`
);
}
}

//update global.css
async function updateGlobalCss(resolvedConfig: RawConfig): Promise<void> {
try {
const globalCSSPath = resolvedConfig.tailwind.css;
Expand Down Expand Up @@ -235,8 +240,7 @@ async function commonInitialization(
join(__dirname, `${config.templatesDir}/common/nativewind-env.d.ts`),
join(_currDir, 'nativewind-env.d.ts')
);
permission &&
(await updateTSConfig(projectType, resolvedConfig.config.tsConfig));
permission && (await updateTSConfig(projectType, resolvedConfig));
permission && (await updateGlobalCss(resolvedConfig));
await updateTailwindConfig(resolvedConfig, projectType);

Expand Down Expand Up @@ -387,4 +391,4 @@ ${files
return confirmInput;
}

export { InitializeGlueStack, commonInitialization, installNativeWind };
export { InitializeGlueStack, commonInitialization };
Loading
Loading