@admin-layout/gluestack-ui-mobile 8.5.7-alpha.0 → 8.5.8-alpha.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,1434 @@
1
+ import * as fs from 'fs';
2
+ import path from 'path';
3
+ import prettier from 'prettier';
4
+ import { fileURLToPath } from 'url';
5
+ import { createRequire } from 'module';
6
+ import { exec as execCallback } from 'child_process';
7
+ import { getSortedNavigations } from '@common-stack/client-react/lib/route/react-navigation/get-navigation-utils.js';
8
+ import { getReplacedRouteConfig } from './getReplacedRouteConfig.js';
9
+ const require = createRequire(import.meta.url);
10
+ const __filename = fileURLToPath(import.meta.url);
11
+ const __dirname = path.dirname(__filename);
12
+ const configFilePath = path.join(__dirname, '../layout.json');
13
+ const appNavigationFileName = 'navigation.tsx';
14
+ const mainRoutesFileName = 'main_routes.json';
15
+ const modulesFileName = 'modules.ts';
16
+ const stacksDirPath = 'stack/index.tsx';
17
+ const drawerFilePath = 'drawer/index.tsx';
18
+ const hostDrawerFilePath = 'host_drawer/index.tsx';
19
+ const bottomFilePath = 'bottom/index.tsx';
20
+ const hostBottomFilePath = 'host_bottom/index.tsx';
21
+
22
+ type IGenerateMobileNavigationsProps = {
23
+ appDirPath: string;
24
+ modules: any;
25
+ initialRouteName?: string;
26
+ unauthenticatedComponentPath?: string;
27
+ customTabBarPath?: string;
28
+ customDrawerPath?: string;
29
+ customHeaderPath?: string;
30
+ };
31
+
32
+ export const readJsonFile = (filePath) => {
33
+ return new Promise((resolve, reject) => {
34
+ fs.readFile(filePath, 'utf8', (err, data) => {
35
+ if (err) {
36
+ return reject(err);
37
+ }
38
+ try {
39
+ const jsonData = JSON.parse(data);
40
+ resolve(jsonData);
41
+ } catch (parseErr) {
42
+ reject(parseErr);
43
+ }
44
+ });
45
+ });
46
+ };
47
+
48
+ export const getLayoutConfig = async () => {
49
+ const layoutConfigFileData = await readJsonFile(configFilePath);
50
+ return layoutConfigFileData;
51
+ };
52
+
53
+ export class GenerateMobileNavigations {
54
+ #layoutSettings: any = process.env.LAYOUT_SETTINGS ? JSON.parse(process.env.LAYOUT_SETTINGS) : null;
55
+ #appDirPath: string;
56
+ #modules: any;
57
+ #initialRouteName: string;
58
+ #unauthenticatedComponentPath: string;
59
+ #customTabBarPath: string;
60
+ #customDrawerPath: string;
61
+ #customHeaderPath: string;
62
+
63
+ constructor({
64
+ appDirPath,
65
+ modules,
66
+ initialRouteName = '',
67
+ unauthenticatedComponentPath = null,
68
+ customTabBarPath = null,
69
+ customDrawerPath = null,
70
+ customHeaderPath = null,
71
+ }: IGenerateMobileNavigationsProps) {
72
+ this.#layoutSettings = process.env.LAYOUT_SETTINGS ? JSON.parse(process.env.LAYOUT_SETTINGS) : null;
73
+ this.#appDirPath = appDirPath;
74
+ this.#modules = modules;
75
+ this.#initialRouteName = initialRouteName;
76
+ this.#unauthenticatedComponentPath = unauthenticatedComponentPath;
77
+ this.#customTabBarPath = customTabBarPath;
78
+ this.#customDrawerPath = customDrawerPath;
79
+ this.#customHeaderPath = customHeaderPath;
80
+ }
81
+
82
+ async #readJsonFile(filePath) {
83
+ return readJsonFile(filePath);
84
+ }
85
+
86
+ async #getLayoutConfig() {
87
+ return getLayoutConfig();
88
+ }
89
+
90
+ async #execPromise(command) {
91
+ return new Promise(function (resolve, reject) {
92
+ execCallback(command, (error, stdout, stderr) => {
93
+ if (error) {
94
+ return resolve(false);
95
+ }
96
+ return resolve(true);
97
+ });
98
+ });
99
+ }
100
+
101
+ async #renameFile(file, new_name) {
102
+ return new Promise((resolve) => {
103
+ fs.access(file, fs.constants.F_OK, (err) => {
104
+ if (err) {
105
+ resolve(false);
106
+ }
107
+
108
+ return fs.rename(file, new_name, (err) => {
109
+ if (err) resolve(false);
110
+ resolve(true);
111
+ });
112
+ });
113
+ });
114
+ }
115
+
116
+ async #writeFile(file, content) {
117
+ return new Promise((resolve) => {
118
+ return fs.writeFile(file, content, 'utf-8', (err) => {
119
+ if (err) resolve(false);
120
+ resolve(true);
121
+ });
122
+ });
123
+ }
124
+
125
+ async #makeDir(dirName) {
126
+ return new Promise((resolve) => {
127
+ return fs.mkdir(dirName, { recursive: true }, (err) => {
128
+ if (err) resolve(false);
129
+ resolve(true);
130
+ });
131
+ });
132
+ }
133
+
134
+ async #getModulesRouteConfig({ modules }) {
135
+ const allFilteredRoutes = [];
136
+ for (const pkg of modules) {
137
+ const pkgPath = require.resolve(pkg);
138
+ const pkgDirPath = path.dirname(pkgPath);
139
+ const pkgFile = path.join(pkgDirPath, 'routes.json');
140
+ if (fs.existsSync(pkgFile)) {
141
+ const fileModuleJSON = await import(pkgFile, { assert: { type: 'json' } });
142
+ if (fileModuleJSON.default) {
143
+ allFilteredRoutes.push([...fileModuleJSON.default]);
144
+ }
145
+ }
146
+ }
147
+ return allFilteredRoutes;
148
+ }
149
+
150
+ async #resolveImportPath(routeConfig, importPath) {
151
+ // Remove the '$.' part from the importPath to get the path within the JSON object
152
+ const path = importPath?.replace('$.', '') ?? null;
153
+
154
+ // Split the path into parts for nested property access
155
+ const parts = path?.split('.') ?? [];
156
+
157
+ // Traverse the routeConfig object to get the actual value
158
+ let value = routeConfig;
159
+ for (let part of parts) {
160
+ if (value && Object.prototype.hasOwnProperty.call(value, part)) {
161
+ value = value[part];
162
+ } else {
163
+ // Return null or handle missing path
164
+ return null;
165
+ }
166
+ }
167
+
168
+ return value;
169
+ }
170
+
171
+ async #generateAppRoutesJson({ appDirPath }) {
172
+ const parentDirPath = path.dirname(appDirPath);
173
+ const parentDirName = path.basename(parentDirPath);
174
+ const appDirName = path.basename(appDirPath);
175
+ // const tsFile = 'src/compute.ts';
176
+ // const outputDir = 'src/app';
177
+ const tsFile = `${parentDirName}/compute.ts`;
178
+ const outputDir = `${parentDirName}/${appDirName}`;
179
+ const tscCommand = `tsc ${tsFile} --outDir ${outputDir} --target es6 --module esnext --jsx react --allowSyntheticDefaultImports true --moduleResolution node --esModuleInterop true --forceConsistentCasingInFileNames true --skipLibCheck true`;
180
+ const mainRoutesJsFile = path.join(appDirPath, '/compute.js');
181
+ const mainRoutesMjsFile = path.join(appDirPath, '/compute.mjs');
182
+ const outputFile = path.join(appDirPath, `/${mainRoutesFileName}`);
183
+ const allFilteredRoutes = [];
184
+ try {
185
+ const execResult = await this.#execPromise(tscCommand);
186
+ if (execResult && fs.existsSync(mainRoutesJsFile)) {
187
+ const jsFiledata = fs.readFileSync(mainRoutesJsFile, 'utf8');
188
+ const noCommentsData = jsFiledata
189
+ .replace(/\/\/.*$/gm, '') // Remove single-line comments
190
+ .replace(/\/\*[\s\S]*?\*\//g, ''); // Remove multi-line comments
191
+ const noWhitespaceJsData = noCommentsData.replace(/\s+/g, '');
192
+ if (noWhitespaceJsData?.length == 0) {
193
+ const outPutDirName = path.dirname(outputFile);
194
+ const isDirCreated = await this.#makeDir(outPutDirName);
195
+ if (isDirCreated) {
196
+ const writeFileResponse = await this.#writeFile(outputFile, JSON.stringify(allFilteredRoutes));
197
+ if (writeFileResponse) {
198
+ return true;
199
+ } else return false;
200
+ } else return false;
201
+ } else {
202
+ const newFilePath = mainRoutesJsFile.replace('.js', '.mjs');
203
+ const renameFileResponse = await this.#renameFile(mainRoutesJsFile, newFilePath);
204
+ if (renameFileResponse) {
205
+ if (fs.existsSync(mainRoutesMjsFile)) {
206
+ // Dynamically import the JS file assuming it exports filteredRoutes
207
+ const module = await import(mainRoutesMjsFile); // file is already absolute
208
+ if (module.filteredRoutes) {
209
+ const newRoutes = module.filteredRoutes.map((filteredRoute) => {
210
+ const routConfig: any = Object.values(filteredRoute)[0];
211
+ const importPath = routConfig.component
212
+ .toString()
213
+ .match(/import\(['"](.*)['"]\)/)[1];
214
+ // routConfig.componentPath = `../.${importPath}`;
215
+ routConfig.componentPath = `.${importPath}.js`;
216
+ return { [routConfig.path]: routConfig };
217
+ });
218
+ allFilteredRoutes.push(...newRoutes);
219
+ const writeFileResponse = await this.#writeFile(
220
+ outputFile,
221
+ JSON.stringify(allFilteredRoutes, null, 2),
222
+ );
223
+
224
+ if (writeFileResponse) {
225
+ fs.unlinkSync(mainRoutesMjsFile);
226
+ return true;
227
+ } else return false;
228
+ }
229
+ } else return false;
230
+ } else return false;
231
+ }
232
+ } else {
233
+ const outPutDirName = path.dirname(outputFile);
234
+ const isDirCreated = await this.#makeDir(outPutDirName);
235
+ if (isDirCreated) {
236
+ const writeFileResponse = await this.#writeFile(outputFile, JSON.stringify(allFilteredRoutes));
237
+ if (writeFileResponse) {
238
+ return true;
239
+ } else return false;
240
+ } else return false;
241
+ }
242
+ // return true;
243
+ } catch (error) {
244
+ console.error(`exec error: ${error.message}`);
245
+ const outPutDirName = path.dirname(outputFile);
246
+ const isDirCreated = await this.#makeDir(outPutDirName);
247
+ if (isDirCreated) {
248
+ const writeFileResponse = await this.#writeFile(outputFile, JSON.stringify(allFilteredRoutes));
249
+ if (writeFileResponse) {
250
+ return true;
251
+ } else return false;
252
+ } else return false;
253
+ }
254
+ }
255
+
256
+ async #generateImportStatements({ modules, initialRouteName }) {
257
+ try {
258
+ const layoutSettings = this.#layoutSettings;
259
+ const layoutConfigFileData = await this.#getLayoutConfig();
260
+ const hostRouteConfig = layoutConfigFileData['host-bottom'];
261
+ const hostRouteKey = Object.keys(hostRouteConfig)[1];
262
+ const hostLayout = hostRouteConfig[hostRouteKey];
263
+
264
+ let importStatements = '';
265
+ let moduleNames = '';
266
+ let moduleRouteConfig = '';
267
+ let moduleNumber = 0;
268
+ importStatements += `import React,{useState} from 'react';\n`;
269
+ importStatements += `import {Feature} from '@common-stack/client-react/lib/connector/connector.native.js';\n`;
270
+ importStatements += `import { useSelector, useDispatch } from 'react-redux';\n`;
271
+ importStatements += `import { CHANGE_SETTINGS_ACTION } from '@admin-layout/client';\n`;
272
+ importStatements += `import {layoutRouteConfig,getReplacedRouteConfig } from '@admin-layout/gluestack-ui-mobile';\n`;
273
+ importStatements += `import mainRouteConfig from './main_routes.json';\n`;
274
+
275
+ modules?.forEach((packageName) => {
276
+ moduleNumber++;
277
+ importStatements += `import module${moduleNumber} from '${packageName}';\n`;
278
+ // moduleNames += `${moduleName}, `;
279
+ moduleNames += `module${moduleNumber}, `;
280
+ moduleRouteConfig += `...[module${moduleNumber}?.routeConfig], `;
281
+ });
282
+
283
+ //const layoutSettings = process.env.LAYOUT_SETTINGS ? JSON.parse(process.env.LAYOUT_SETTINGS) : null;
284
+
285
+ let classStructure = `
286
+ const features = new Feature(
287
+ ${moduleNames.trim()}
288
+ );
289
+
290
+ const mainAppRoutes = mainRouteConfig || [];
291
+
292
+ const appRoutes = [...[mainAppRoutes],${moduleRouteConfig}]?.filter((rc)=>rc.length)??[];
293
+
294
+ const featureRouteConfig = appRoutes?.flat(1)??features?.routeConfig;
295
+ features.routeConfig = featureRouteConfig;
296
+
297
+ export function useGetModules(){
298
+ const dispatch = useDispatch();
299
+ const defaultSettings = useSelector((state:any) => state.settings);
300
+ const initialRouteName = '${initialRouteName}';
301
+ const layoutSettings = ${JSON.stringify({ ...layoutSettings, hostLayout: hostLayout.key })}
302
+ const [appRouteConfig, setAppRouteConfig]:any = useState(null);
303
+
304
+ React.useEffect(() => {
305
+ setDefalutSettings();
306
+ }, []);
307
+
308
+
309
+ const setDefalutSettings = React.useCallback(()=>{
310
+ const config: any = {
311
+ ...defaultSettings,
312
+ ...layoutSettings,
313
+ };
314
+ dispatch({
315
+ type: CHANGE_SETTINGS_ACTION,
316
+ payload: config,
317
+ });
318
+ },[]);
319
+
320
+ React.useEffect(() => {
321
+ if (defaultSettings) {
322
+ const settingObj: any = { ...defaultSettings };
323
+ const layoutType: any = settingObj.layout;
324
+ const {replacedConfiguredRouteConfig} = getReplacedRouteConfig({
325
+ layoutType: layoutType,
326
+ routeConfig: appRoutes,
327
+ layoutConfigData: layoutRouteConfig,
328
+ initialRouteName,
329
+ });
330
+ if(replacedConfiguredRouteConfig){
331
+ const moduleRouteConfigObject = Object.assign({}, ...replacedConfiguredRouteConfig?.flat(1)??[]);
332
+ const replacedRouteConfig = Object.fromEntries(Object.entries(moduleRouteConfigObject));
333
+ const appReplacedRouteConfig = replacedRouteConfig ? Object.keys(replacedRouteConfig)?.map((k)=>({[k]:replacedRouteConfig[k]})) : [];
334
+
335
+ if (appReplacedRouteConfig) {
336
+ const hostRouteConfig = appReplacedRouteConfig?.map((obj)=> Object.fromEntries(Object.entries(obj)?.filter(([key,val])=>key === '/' || key.startsWith('//'+layoutSettings.hostLayout))))?.filter(value => Object.keys(value).length !== 0)??[];
337
+ const layoutRouteConfig = appReplacedRouteConfig?.map((obj)=> Object.fromEntries(Object.entries(obj)?.filter(([key,val])=>key === '/' || !key.startsWith('//'+layoutSettings.hostLayout))))?.filter(value => Object.keys(value).length !== 0)??[];
338
+ const featureRouteConfig = defaultSettings?.layout == 'host-bottom' ? hostRouteConfig:layoutRouteConfig;
339
+ // features.routeConfig = featureRouteConfig;
340
+ setAppRouteConfig(featureRouteConfig);
341
+ }
342
+ }
343
+ }
344
+ }, [defaultSettings]);
345
+
346
+ return {appRouteConfig};
347
+ }
348
+
349
+ export default features;
350
+ `.replace(/,(\s*)$/, ''); // Removes trailing comma
351
+
352
+ // Use Prettier to format the code
353
+ classStructure = prettier.format(classStructure, { parser: 'babel' });
354
+
355
+ const appFeatures = importStatements + '\n' + classStructure;
356
+
357
+ return { appFeatures };
358
+ } catch (err) {
359
+ console.error('Error:', err);
360
+ return false;
361
+ }
362
+ }
363
+
364
+ async #generateModulesTsFile({ appDirPath, modules, initialRouteName }) {
365
+ const moduleTsFile = path.join(appDirPath, `/${modulesFileName}`);
366
+ const imports: any = await this.#generateImportStatements({ modules, initialRouteName });
367
+ const { appFeatures } = imports;
368
+ if (appFeatures) {
369
+ const writeFileResponse = await this.#writeFile(moduleTsFile, appFeatures);
370
+ if (writeFileResponse) return true;
371
+ else return false;
372
+ }
373
+ return false;
374
+ }
375
+
376
+ async #generateStackNavigations({ appDirPath, modules, initialRouteName, unauthenticatedComponentPath }) {
377
+ const mainRoutes = path.join(appDirPath, `/${mainRoutesFileName}`);
378
+ const stackDirPath = path.join(appDirPath, `/${stacksDirPath}`);
379
+ const layoutSettings = this.#layoutSettings;
380
+ const layoutConfigFileData = await this.#getLayoutConfig();
381
+ const layoutType = layoutSettings?.layout || 'bottom';
382
+ const layoutRouteConfig = layoutConfigFileData[layoutType];
383
+ const layoutRouteKey = Object.keys(layoutRouteConfig)[1];
384
+ const appLayout = layoutRouteConfig[layoutRouteKey];
385
+ const modulesRouteConfig = await this.#getModulesRouteConfig({ modules: modules });
386
+ const mainRouteConfig = await this.#readJsonFile(mainRoutes);
387
+ const allRoutes = [...[mainRouteConfig ?? []], ...(modulesRouteConfig ?? [])];
388
+
389
+ const { replacedNavigationRouteConfig: routeConfig } = getReplacedRouteConfig({
390
+ layoutType: layoutType,
391
+ routeConfig: allRoutes,
392
+ layoutConfigData: layoutConfigFileData,
393
+ initialRouteName: initialRouteName,
394
+ });
395
+ const keyToReplace = appLayout.key || 'bottom_tab';
396
+ const stackRouteConfig =
397
+ routeConfig
398
+ ?.map(
399
+ (rArray) =>
400
+ rArray
401
+ ?.map((r) => {
402
+ const route = r[Object.keys(r)[0]];
403
+ const path = route.path;
404
+ const isExcluded =
405
+ path === '/' ||
406
+ path.startsWith(`/${keyToReplace}`) ||
407
+ path.startsWith(`/:orgName/${keyToReplace}`) ||
408
+ path.startsWith('/host_tab') ||
409
+ path.startsWith('/:orgName/host_tab');
410
+ return isExcluded ? false : route;
411
+ })
412
+ ?.filter((route) => route !== false) ?? [], // Filter out false values
413
+ )
414
+ ?.filter((subArray) => subArray.length > 0) ?? [];
415
+
416
+ let moduleNumber = 0;
417
+ let importStatements = '';
418
+ let moduleContent = '';
419
+ let moduleRender = '';
420
+ let stackNavigator = '';
421
+ let customHeaderNames = '';
422
+ let customHeaderPaths = '';
423
+ let customUnauthenticatedComponentPaths = '';
424
+ let customUnauthenticatedComponentNames = '';
425
+ const regex = /\.(tsx|ts|jsx|js)$/i;
426
+
427
+ importStatements += `import * as React from 'react';\n`;
428
+ importStatements += `import {AuthWrapper} from '@admin-layout/gluestack-ui-mobile';\n`;
429
+
430
+ if (unauthenticatedComponentPath)
431
+ importStatements += `import UnauthenticatedComponent from '${unauthenticatedComponentPath}';\n`;
432
+
433
+ for (const pkg of stackRouteConfig) {
434
+ moduleContent += `<Stack.Group>`;
435
+ for (const pkgRouteConfig of pkg) {
436
+ moduleNumber++;
437
+ let customHeaderName = null;
438
+ const customHeaderComponentPath = await this.#resolveImportPath(
439
+ pkgRouteConfig,
440
+ pkgRouteConfig?.customHeader?.component,
441
+ );
442
+ if (
443
+ pkgRouteConfig?.customHeader &&
444
+ Object.keys(pkgRouteConfig?.customHeader)?.length &&
445
+ customHeaderComponentPath
446
+ ) {
447
+ customHeaderPaths += `${customHeaderComponentPath},`;
448
+ customHeaderName =
449
+ `${pkgRouteConfig?.customHeader?.name ?? `CustomHeader${moduleNumber}`}` ||
450
+ `CustomHeader${moduleNumber}`;
451
+ customHeaderNames += `${customHeaderName},`;
452
+ }
453
+
454
+ let customUnauthenticatedComponentName = null;
455
+ const customUnauthenticatedComponentPath = await this.#resolveImportPath(
456
+ pkgRouteConfig,
457
+ pkgRouteConfig?.unauthenticatedComponent,
458
+ );
459
+ if (pkgRouteConfig?.unauthenticatedComponent && customUnauthenticatedComponentPath) {
460
+ customUnauthenticatedComponentPaths += `${customUnauthenticatedComponentPath},`;
461
+ customUnauthenticatedComponentName = `UnauthenticatedComponent${moduleNumber}`;
462
+ customUnauthenticatedComponentNames += `${customUnauthenticatedComponentName},`;
463
+ }
464
+
465
+ importStatements += `import Component${moduleNumber} from '${pkgRouteConfig.componentPath}';\n`;
466
+ const options = JSON.stringify({ ...(pkgRouteConfig?.props?.options || {}) });
467
+ moduleContent += `<Stack.Screen
468
+ key="${pkgRouteConfig.key}"
469
+ name="${pkgRouteConfig.name}"
470
+ initialParams={${JSON.stringify(pkgRouteConfig?.props?.initialParams || {})}}
471
+ options={{...${options},...{${
472
+ pkgRouteConfig?.customHeader &&
473
+ Object.keys(pkgRouteConfig.customHeader)?.length &&
474
+ customHeaderComponentPath
475
+ ? `header: (props: any) => <${customHeaderName} {...props} {...${JSON.stringify(
476
+ pkgRouteConfig?.customHeader?.props ?? '',
477
+ )}} />`
478
+ : ''
479
+ }}}}
480
+ >{(props:any) => <AuthWrapper
481
+ auth={${pkgRouteConfig?.props?.initialParams?.auth ?? false}}
482
+ component={<Component${moduleNumber} {...props} />}
483
+ ${
484
+ pkgRouteConfig?.unauthenticatedComponent && customUnauthenticatedComponentPath
485
+ ? `unauthenticatedComponent={<${customUnauthenticatedComponentName}/>}`
486
+ : unauthenticatedComponentPath
487
+ ? 'unauthenticatedComponent={<UnauthenticatedComponent/>}'
488
+ : ''
489
+ }
490
+ ${
491
+ pkgRouteConfig?.withLifeCycle
492
+ ? `withLifeCycle={${JSON.stringify(pkgRouteConfig?.withLifeCycle)}}`
493
+ : ''
494
+ }
495
+ ${
496
+ pkgRouteConfig?.withInteraction
497
+ ? `withInteraction={${JSON.stringify(pkgRouteConfig?.withInteraction)}}`
498
+ : ''
499
+ }
500
+ ${
501
+ pkgRouteConfig?.withLifeCycleInteraction
502
+ ? `withLifeCycleInteraction={${JSON.stringify(
503
+ pkgRouteConfig?.withLifeCycleInteraction,
504
+ )}}`
505
+ : ''
506
+ }
507
+ />}</Stack.Screen>`;
508
+ }
509
+ if (customHeaderPaths && customHeaderPaths?.length) {
510
+ const uniqueHeaderNames = [...new Set(customHeaderNames.split(','))]?.filter((str) => str?.length);
511
+ const uniqueHeaderPaths = [...new Set(customHeaderPaths.split(','))]?.filter((str) => str?.length);
512
+ uniqueHeaderPaths?.forEach(function (hPath, i) {
513
+ const impHeaderName = uniqueHeaderNames?.[i] ?? `customHeader${i}`;
514
+ importStatements += `import ${impHeaderName} from '${hPath}';\n`;
515
+ });
516
+ }
517
+
518
+ if (customUnauthenticatedComponentPaths && customUnauthenticatedComponentPaths?.length) {
519
+ const uniqueUnauthenticatedComponentNames = [
520
+ ...new Set(customUnauthenticatedComponentNames.split(',')),
521
+ ]?.filter((str) => str?.length);
522
+ const uniqueUnauthenticatedComponentPaths = [
523
+ ...new Set(customUnauthenticatedComponentPaths.split(',')),
524
+ ]?.filter((str) => str?.length);
525
+ uniqueUnauthenticatedComponentPaths?.forEach(function (unCompPath, i) {
526
+ const impUnauthenticatedName =
527
+ uniqueUnauthenticatedComponentNames?.[i] ?? `UnauthenticatedComponent${i}`;
528
+ importStatements += `import ${impUnauthenticatedName} from '${unCompPath}';\n`;
529
+ });
530
+ }
531
+
532
+ moduleContent += `</Stack.Group>`;
533
+ moduleRender = `export default ({Stack,...rest}:any) => { return (<>${moduleContent}</>)}`;
534
+ }
535
+ stackNavigator = importStatements + '\n' + moduleRender;
536
+ if (stackNavigator) {
537
+ let stackNavigation = stackNavigator;
538
+ stackNavigation = prettier.format(stackNavigation, { parser: 'babel' });
539
+ const stackDirName = path.dirname(stackDirPath);
540
+ const isDirCreated = await this.#makeDir(stackDirName);
541
+ if (isDirCreated) {
542
+ const writeFileResponse = await this.#writeFile(stackDirPath, stackNavigation);
543
+ if (writeFileResponse) return true;
544
+ else return false;
545
+ } else return false;
546
+ } else return false;
547
+ }
548
+
549
+ async #generateDrawerNavigationsFile({ drawerConfig, unauthenticatedComponentPath, drawerDirPath }) {
550
+ let moduleNumber = 0;
551
+ let importStatements = '';
552
+ let moduleContent = '';
553
+ let moduleRender = '';
554
+ let moduleNavigation = '';
555
+ let icons = '';
556
+ let customHeaderNames = '';
557
+ let customHeaderPaths = '';
558
+ let customUnauthenticatedComponentPaths = '';
559
+ let customUnauthenticatedComponentNames = '';
560
+ const regex = /\.(tsx|ts|jsx|js)$/i;
561
+
562
+ importStatements += `import * as React from 'react';\n`;
563
+ importStatements += `import {AuthWrapper} from '@admin-layout/gluestack-ui-mobile';\n`;
564
+
565
+ if (unauthenticatedComponentPath)
566
+ importStatements += `import UnauthenticatedComponent from '${unauthenticatedComponentPath}';\n`;
567
+
568
+ for (const pkgRouteConfig of drawerConfig) {
569
+ moduleNumber++;
570
+ if (pkgRouteConfig?.icon && Object.keys(pkgRouteConfig.icon)?.length && pkgRouteConfig?.icon?.name) {
571
+ icons += `${pkgRouteConfig?.icon?.name},`;
572
+ }
573
+ let customHeaderName = null;
574
+ const customHeaderComponentPath = await this.#resolveImportPath(
575
+ pkgRouteConfig,
576
+ pkgRouteConfig?.customHeader?.component,
577
+ );
578
+ if (
579
+ pkgRouteConfig?.customHeader &&
580
+ Object.keys(pkgRouteConfig?.customHeader)?.length &&
581
+ customHeaderComponentPath
582
+ ) {
583
+ customHeaderPaths += `${customHeaderComponentPath},`;
584
+ customHeaderName =
585
+ `${pkgRouteConfig?.customHeader?.name ?? `CustomHeader${moduleNumber}`}` ||
586
+ `CustomHeader${moduleNumber}`;
587
+ customHeaderNames += `${customHeaderName},`;
588
+ }
589
+ let customUnauthenticatedComponentName = null;
590
+ const customUnauthenticatedComponentPath = await this.#resolveImportPath(
591
+ pkgRouteConfig,
592
+ pkgRouteConfig?.unauthenticatedComponent,
593
+ );
594
+ if (pkgRouteConfig?.unauthenticatedComponent && customUnauthenticatedComponentPath) {
595
+ customUnauthenticatedComponentPaths += `${customUnauthenticatedComponentPath},`;
596
+ customUnauthenticatedComponentName = `UnauthenticatedComponent${moduleNumber}`;
597
+ customUnauthenticatedComponentNames += `${customUnauthenticatedComponentName},`;
598
+ }
599
+
600
+ const options = JSON.stringify({ ...(pkgRouteConfig?.props?.options || {}) });
601
+ importStatements += `import Component${moduleNumber} from '${pkgRouteConfig.componentPath}';\n`;
602
+ moduleContent += `<Drawer.Screen
603
+ key="${pkgRouteConfig.key}"
604
+ name="${pkgRouteConfig.name}"
605
+ //component={Component${moduleNumber}}
606
+ initialParams={${JSON.stringify(pkgRouteConfig?.props?.initialParams || {})}}
607
+ options={{...${options},...{${
608
+ pkgRouteConfig?.icon && Object.keys(pkgRouteConfig.icon)?.length && pkgRouteConfig?.icon?.name
609
+ ? `drawerIcon: ({ color, size }: { color: any,size:any }) => <${pkgRouteConfig?.icon?.name} name="${
610
+ pkgRouteConfig?.icon?.props?.name ?? 'home'
611
+ }" size={${pkgRouteConfig?.icon?.props?.size ?? `size`}} color={${
612
+ pkgRouteConfig?.icon?.props?.color ?? 'color'
613
+ }} />`
614
+ : ''
615
+ }
616
+ ${
617
+ pkgRouteConfig?.customHeader &&
618
+ Object.keys(pkgRouteConfig.customHeader)?.length &&
619
+ customHeaderComponentPath
620
+ ? `header: (props: any) => <${customHeaderName} {...props} {...${JSON.stringify(
621
+ pkgRouteConfig?.customHeader?.props ?? '',
622
+ )}} />`
623
+ : ''
624
+ }}}}
625
+ >{(props:any) => <AuthWrapper
626
+ auth={${pkgRouteConfig?.props?.initialParams?.auth ?? false}}
627
+ component={<Component${moduleNumber} {...props} />}
628
+ ${
629
+ pkgRouteConfig?.unauthenticatedComponent && customUnauthenticatedComponentPath
630
+ ? `unauthenticatedComponent={<${customUnauthenticatedComponentName}/>}`
631
+ : unauthenticatedComponentPath
632
+ ? 'unauthenticatedComponent={<UnauthenticatedComponent/>}'
633
+ : ''
634
+ }
635
+ ${
636
+ pkgRouteConfig?.withLifeCycle
637
+ ? `withLifeCycle={${JSON.stringify(pkgRouteConfig?.withLifeCycle)}}`
638
+ : ''
639
+ }
640
+ ${
641
+ pkgRouteConfig?.withInteraction
642
+ ? `withInteraction={${JSON.stringify(pkgRouteConfig?.withInteraction)}}`
643
+ : ''
644
+ }
645
+ ${
646
+ pkgRouteConfig?.withLifeCycleInteraction
647
+ ? `withLifeCycleInteraction={${JSON.stringify(
648
+ pkgRouteConfig?.withLifeCycleInteraction,
649
+ )}}`
650
+ : ''
651
+ }
652
+ />}</Drawer.Screen>`;
653
+ }
654
+ if (icons && icons?.length) {
655
+ const uniqueIcons = [...new Set(icons.split(','))].join(',');
656
+ importStatements += `import { ${uniqueIcons} } from '@expo/vector-icons';\n`;
657
+ }
658
+
659
+ if (customHeaderPaths && customHeaderPaths?.length) {
660
+ const uniqueHeaderNames = [...new Set(customHeaderNames.split(','))]?.filter((str) => str?.length);
661
+ const uniqueHeaderPaths = [...new Set(customHeaderPaths.split(','))]?.filter((str) => str?.length);
662
+ uniqueHeaderPaths?.forEach(function (hPath, i) {
663
+ const impHeaderName = uniqueHeaderNames?.[i] ?? `customHeader${i}`;
664
+ importStatements += `import ${impHeaderName} from '${hPath}';\n`;
665
+ });
666
+ }
667
+
668
+ if (customUnauthenticatedComponentPaths && customUnauthenticatedComponentPaths?.length) {
669
+ const uniqueUnauthenticatedComponentNames = [
670
+ ...new Set(customUnauthenticatedComponentNames.split(',')),
671
+ ]?.filter((str) => str?.length);
672
+ const uniqueUnauthenticatedComponentPaths = [
673
+ ...new Set(customUnauthenticatedComponentPaths.split(',')),
674
+ ]?.filter((str) => str?.length);
675
+ uniqueUnauthenticatedComponentPaths?.forEach(function (unCompPath, i) {
676
+ const impUnauthenticatedName =
677
+ uniqueUnauthenticatedComponentNames?.[i] ?? `UnauthenticatedComponent${i}`;
678
+ importStatements += `import ${impUnauthenticatedName} from '${unCompPath}';\n`;
679
+ });
680
+ }
681
+
682
+ moduleRender = `export default ({Drawer,...rest}:any) => { return (<>${moduleContent}</>)}`;
683
+ moduleNavigation = importStatements + '\n' + moduleRender;
684
+
685
+ const drawerNavigator = moduleNavigation;
686
+ if (drawerNavigator) {
687
+ let drawerNavigation = drawerNavigator;
688
+ drawerNavigation = prettier.format(drawerNavigation, { parser: 'babel' });
689
+ const drawerDirName = path.dirname(drawerDirPath);
690
+ const isDirCreated = await this.#makeDir(drawerDirName);
691
+ if (isDirCreated) {
692
+ const writeFileResponse = await this.#writeFile(drawerDirPath, drawerNavigation);
693
+ if (writeFileResponse) return true;
694
+ else return false;
695
+ } else return false;
696
+ }
697
+ return false;
698
+ }
699
+
700
+ async #generateDrawerNavigations({ appDirPath, modules, initialRouteName, unauthenticatedComponentPath }) {
701
+ const mainRoutes = path.join(appDirPath, `/${mainRoutesFileName}`);
702
+ const drawerDirPath = path.join(appDirPath, `/${drawerFilePath}`);
703
+ const hostDirPath = path.join(appDirPath, `/${hostDrawerFilePath}`);
704
+
705
+ const layoutSettings = this.#layoutSettings;
706
+ const layoutConfigFileData = await this.#getLayoutConfig();
707
+ const layoutType = 'side';
708
+ const layoutRouteConfig = layoutConfigFileData[layoutType];
709
+ const layoutRouteKey = Object.keys(layoutRouteConfig)[1];
710
+ const appLayout = layoutRouteConfig[layoutRouteKey];
711
+ const hostRouteConfig = layoutConfigFileData['host-bottom'];
712
+ const hostRouteKey = Object.keys(hostRouteConfig)[1];
713
+ const hostLayout = hostRouteConfig[hostRouteKey];
714
+ const modulesRouteConfig = await this.#getModulesRouteConfig({ modules: modules });
715
+ const mainRouteConfig = await this.#readJsonFile(mainRoutes);
716
+ const allRoutes = [...[mainRouteConfig ?? []], ...(modulesRouteConfig ?? [])];
717
+ const { replacedNavigationRouteConfig: routeConfig } = getReplacedRouteConfig({
718
+ layoutType: layoutType,
719
+ routeConfig: allRoutes,
720
+ layoutConfigData: layoutConfigFileData,
721
+ initialRouteName: initialRouteName,
722
+ });
723
+ const keyToReplace = appLayout.key || 'bottom_tab';
724
+ const keyToReplaceHost = hostLayout.key || 'host_tab';
725
+ const moduleRouteConfigObject = Object.assign({}, ...(routeConfig?.flat(1) ?? []));
726
+ const configuredRoutes = await getSortedNavigations('/', moduleRouteConfigObject);
727
+ const layoutBottomTabRouteConfig = configuredRoutes?.[0]?.children?.filter((r) => r?.key == keyToReplace);
728
+ const hostBottomTabRouteConfig = configuredRoutes?.[0]?.children?.filter((r) => r?.key == keyToReplaceHost);
729
+
730
+ const drawerConfig =
731
+ layoutBottomTabRouteConfig?.[0]?.children?.sort((a, b) => {
732
+ if (a?.props?.options?.priority === undefined) return 1; // Push items with missing 'id' to the end
733
+ if (b?.props?.options?.priority === undefined) return -1;
734
+ return a?.props?.options?.priority - b?.props?.options?.priority;
735
+ }) ?? [];
736
+ const hostDrawerConfig =
737
+ hostBottomTabRouteConfig?.[0]?.children?.sort((a, b) => {
738
+ if (a?.props?.options?.priority === undefined) return 1; // Push items with missing 'id' to the end
739
+ if (b?.props?.options?.priority === undefined) return -1;
740
+ return a?.props?.options?.priority - b?.props?.options?.priority;
741
+ }) ?? [];
742
+
743
+ if (layoutSettings?.layout == 'side') {
744
+ if (drawerConfig) {
745
+ const drawerNavigation = await this.#generateDrawerNavigationsFile({
746
+ drawerConfig: drawerConfig,
747
+ unauthenticatedComponentPath,
748
+ drawerDirPath: drawerDirPath,
749
+ });
750
+ if (drawerNavigation)
751
+ await this.#generateDrawerNavigationsFile({
752
+ drawerConfig: hostDrawerConfig,
753
+ unauthenticatedComponentPath,
754
+ drawerDirPath: hostDirPath,
755
+ });
756
+ return true;
757
+ } else {
758
+ if (hostDrawerConfig) {
759
+ const isDrawerGenerated = await this.#generateDrawerNavigationsFile({
760
+ drawerConfig: hostDrawerConfig,
761
+ unauthenticatedComponentPath,
762
+ drawerDirPath: hostDirPath,
763
+ });
764
+ return isDrawerGenerated;
765
+ } else return false;
766
+ }
767
+ } else return false;
768
+ }
769
+
770
+ async #generateBottomTabNavigationsFile({
771
+ bottomTabConfig,
772
+ unauthenticatedComponentPath,
773
+ bottomDirPath,
774
+ mixLayout = null,
775
+ }) {
776
+ let moduleNumber = 0;
777
+ let importStatements = '';
778
+ let moduleContent = '';
779
+ let moduleRender = '';
780
+ let moduleNavigation = '';
781
+ let icons = '';
782
+ let customHeaderNames = '';
783
+ let customHeaderPaths = '';
784
+ let customUnauthenticatedComponentPaths = '';
785
+ let customUnauthenticatedComponentNames = '';
786
+
787
+ const regex = /\.(tsx|ts|jsx|js)$/i;
788
+
789
+ importStatements += `import * as React from 'react';\n`;
790
+ importStatements += `import {AuthWrapper} from '@admin-layout/gluestack-ui-mobile';\n`;
791
+
792
+ if (unauthenticatedComponentPath)
793
+ importStatements += `import UnauthenticatedComponent from '${unauthenticatedComponentPath}';\n`;
794
+
795
+ for (const pkgRouteConfig of bottomTabConfig) {
796
+ moduleNumber++;
797
+ if (pkgRouteConfig?.icon && Object.keys(pkgRouteConfig.icon)?.length && pkgRouteConfig?.icon?.name) {
798
+ icons += `${pkgRouteConfig?.icon?.name},`;
799
+ }
800
+
801
+ let customHeaderName = null;
802
+ const customHeaderComponentPath = await this.#resolveImportPath(
803
+ pkgRouteConfig,
804
+ pkgRouteConfig?.customHeader?.component,
805
+ );
806
+ if (
807
+ pkgRouteConfig?.customHeader &&
808
+ Object.keys(pkgRouteConfig?.customHeader)?.length &&
809
+ customHeaderComponentPath
810
+ ) {
811
+ customHeaderPaths += `${customHeaderComponentPath},`;
812
+ customHeaderName =
813
+ `${pkgRouteConfig?.customHeader?.name ?? `CustomHeader${moduleNumber}`}` ||
814
+ `CustomHeader${moduleNumber}`;
815
+ customHeaderNames += `${customHeaderName},`;
816
+ }
817
+
818
+ let customUnauthenticatedComponentName = null;
819
+ const customUnauthenticatedComponentPath = await this.#resolveImportPath(
820
+ pkgRouteConfig,
821
+ pkgRouteConfig?.unauthenticatedComponent,
822
+ );
823
+ if (pkgRouteConfig?.unauthenticatedComponent && customUnauthenticatedComponentPath) {
824
+ customUnauthenticatedComponentPaths += `${customUnauthenticatedComponentPath},`;
825
+ customUnauthenticatedComponentName = `UnauthenticatedComponent${moduleNumber}`;
826
+ customUnauthenticatedComponentNames += `${customUnauthenticatedComponentName},`;
827
+ }
828
+
829
+ const options = JSON.stringify(
830
+ {
831
+ ...pkgRouteConfig?.props?.options,
832
+ headerShown: mixLayout ? false : pkgRouteConfig?.props?.options?.headerShown,
833
+ } || { headerShown: mixLayout ? false : true },
834
+ );
835
+ importStatements += `import Component${moduleNumber} from '${pkgRouteConfig.componentPath}';\n`;
836
+ moduleContent += `<Tab.Screen
837
+ key="${pkgRouteConfig.key}"
838
+ name="${pkgRouteConfig.name}"
839
+ //component={Component${moduleNumber}}
840
+ initialParams={${JSON.stringify(pkgRouteConfig?.props?.initialParams || {})}}
841
+ options={{...${options},...{${
842
+ pkgRouteConfig?.icon && Object.keys(pkgRouteConfig.icon)?.length && pkgRouteConfig?.icon?.name
843
+ ? `tabBarIcon: ({ color }: { color: any }) => <${pkgRouteConfig?.icon?.name} name="${
844
+ pkgRouteConfig?.icon?.props?.name ?? 'home'
845
+ }" size={${pkgRouteConfig?.icon?.props?.size ?? 24}} color={${
846
+ pkgRouteConfig?.icon?.props?.color ?? 'color'
847
+ }} />`
848
+ : ''
849
+ }
850
+ ${
851
+ pkgRouteConfig?.customHeader &&
852
+ Object.keys(pkgRouteConfig.customHeader)?.length &&
853
+ customHeaderComponentPath
854
+ ? `,header: (props: any) => <${customHeaderName} {...props} {...${JSON.stringify(
855
+ pkgRouteConfig?.customHeader?.props ?? '',
856
+ )}} />`
857
+ : ''
858
+ }
859
+ }}}
860
+ >{(props:any) => <AuthWrapper
861
+ auth={${pkgRouteConfig?.props?.initialParams?.auth ?? false}}
862
+ component={<Component${moduleNumber} {...props} />}
863
+ ${
864
+ pkgRouteConfig?.unauthenticatedComponent && customUnauthenticatedComponentPath
865
+ ? `unauthenticatedComponent={<${customUnauthenticatedComponentName}/>}`
866
+ : unauthenticatedComponentPath
867
+ ? 'unauthenticatedComponent={<UnauthenticatedComponent/>}'
868
+ : ''
869
+ }
870
+ ${
871
+ pkgRouteConfig?.withLifeCycle
872
+ ? `withLifeCycle={${JSON.stringify(pkgRouteConfig?.withLifeCycle)}}`
873
+ : ''
874
+ }
875
+ ${
876
+ pkgRouteConfig?.withInteraction
877
+ ? `withInteraction={${JSON.stringify(pkgRouteConfig?.withInteraction)}}`
878
+ : ''
879
+ }
880
+ ${
881
+ pkgRouteConfig?.withLifeCycleInteraction
882
+ ? `withLifeCycleInteraction={${JSON.stringify(
883
+ pkgRouteConfig?.withLifeCycleInteraction,
884
+ )}}`
885
+ : ''
886
+ }
887
+ />}
888
+ </Tab.Screen>`;
889
+ }
890
+
891
+ if (icons && icons?.length) {
892
+ const uniqueIcons = [...new Set(icons.split(','))].join(',');
893
+ importStatements += `import { ${uniqueIcons} } from '@expo/vector-icons';\n`;
894
+ }
895
+
896
+ if (customHeaderPaths && customHeaderPaths?.length) {
897
+ const uniqueHeaderNames = [...new Set(customHeaderNames.split(','))]?.filter((str) => str?.length);
898
+ const uniqueHeaderPaths = [...new Set(customHeaderPaths.split(','))]?.filter((str) => str?.length);
899
+ uniqueHeaderPaths?.forEach(function (hPath, i) {
900
+ const impHeaderName = uniqueHeaderNames?.[i] ?? `customHeader${i}`;
901
+ importStatements += `import ${impHeaderName} from '${hPath}';\n`;
902
+ });
903
+ }
904
+
905
+ if (customUnauthenticatedComponentPaths && customUnauthenticatedComponentPaths?.length) {
906
+ const uniqueUnauthenticatedComponentNames = [
907
+ ...new Set(customUnauthenticatedComponentNames.split(',')),
908
+ ]?.filter((str) => str?.length);
909
+ const uniqueUnauthenticatedComponentPaths = [
910
+ ...new Set(customUnauthenticatedComponentPaths.split(',')),
911
+ ]?.filter((str) => str?.length);
912
+ uniqueUnauthenticatedComponentPaths?.forEach(function (unCompPath, i) {
913
+ const impUnauthenticatedName =
914
+ uniqueUnauthenticatedComponentNames?.[i] ?? `UnauthenticatedComponent${i}`;
915
+ importStatements += `import ${impUnauthenticatedName} from '${unCompPath}';\n`;
916
+ });
917
+ }
918
+
919
+ moduleRender = `export default ({Tab,...rest}:any) => { return (<>${moduleContent}</>)}`;
920
+ moduleNavigation = importStatements + '\n' + moduleRender;
921
+ const bottomTabNavigator = moduleNavigation;
922
+ if (bottomTabNavigator) {
923
+ let bottomTabNavigation = bottomTabNavigator;
924
+ bottomTabNavigation = prettier.format(bottomTabNavigation, { parser: 'babel' });
925
+ const bottomDirName = path.dirname(bottomDirPath);
926
+ const isDirCreated = await this.#makeDir(bottomDirName);
927
+ if (isDirCreated) {
928
+ const writeFileResponse = await this.#writeFile(bottomDirPath, bottomTabNavigation);
929
+ if (writeFileResponse) return true;
930
+ else return false;
931
+ } else return false;
932
+ }
933
+ return false;
934
+ }
935
+
936
+ async #generateBottomTabNavigations({ appDirPath, modules, initialRouteName, unauthenticatedComponentPath }) {
937
+ const mainRoutes = path.join(appDirPath, `/${mainRoutesFileName}`);
938
+ const bottomDirPath = path.join(appDirPath, `/${bottomFilePath}`);
939
+ const hostBottomDirPath = path.join(appDirPath, `/${hostBottomFilePath}`);
940
+
941
+ const layoutSettings = this.#layoutSettings;
942
+ const layoutConfigFileData = await this.#getLayoutConfig();
943
+ const layoutType = layoutSettings?.layout ?? 'bottom';
944
+ const layoutRouteConfig = layoutConfigFileData[layoutType];
945
+ const layoutRouteKey = Object.keys(layoutRouteConfig)[1];
946
+ const appLayout = layoutRouteConfig[layoutRouteKey];
947
+ const hostRouteConfig = layoutConfigFileData['host-bottom'];
948
+ const hostRouteKey = Object.keys(hostRouteConfig)[1];
949
+ const hostLayout = hostRouteConfig[hostRouteKey];
950
+ const mixLayoutRouteKey = Object.keys(layoutRouteConfig)?.[2] || null;
951
+ const mixLayout = mixLayoutRouteKey ? layoutRouteConfig[mixLayoutRouteKey] : null;
952
+ const modulesRouteConfig = await this.#getModulesRouteConfig({ modules: modules });
953
+ const mainRouteConfig = await this.#readJsonFile(mainRoutes);
954
+ const allRoutes = [...[mainRouteConfig ?? []], ...(modulesRouteConfig ?? [])];
955
+
956
+ const { replacedNavigationRouteConfig: routeConfig } = getReplacedRouteConfig({
957
+ layoutType: layoutType,
958
+ routeConfig: allRoutes,
959
+ layoutConfigData: layoutConfigFileData,
960
+ initialRouteName: initialRouteName,
961
+ });
962
+ const keyToReplace = appLayout.key || 'bottom_tab';
963
+ const keyToReplaceHost = hostLayout.key || 'host_tab';
964
+ const moduleRouteConfigObject = Object.assign({}, ...(routeConfig?.flat(1) ?? []));
965
+ const configuredRoutes = await getSortedNavigations('/', moduleRouteConfigObject);
966
+ const layoutBottomTabRouteConfig = configuredRoutes?.[0]?.children?.filter((r) => r?.key == keyToReplace);
967
+ const hostBottomTabRouteConfig = configuredRoutes?.[0]?.children?.filter((r) => r?.key == keyToReplaceHost);
968
+
969
+ const bottomTabConfig =
970
+ layoutBottomTabRouteConfig?.[0]?.children?.sort((a, b) => {
971
+ if (a?.props?.options?.priority === undefined) return 1; // Push items with missing 'id' to the end
972
+ if (b?.props?.options?.priority === undefined) return -1;
973
+ return a?.props?.options?.priority - b?.props?.options?.priority;
974
+ }) ?? [];
975
+ const hostBottomTabConfig =
976
+ hostBottomTabRouteConfig?.[0]?.children?.sort((a, b) => {
977
+ if (a?.props?.options?.priority === undefined) return 1; // Push items with missing 'id' to the end
978
+ if (b?.props?.options?.priority === undefined) return -1;
979
+ return a?.props?.options?.priority - b?.props?.options?.priority;
980
+ }) ?? [];
981
+ if (layoutType == 'bottom' || layoutType == 'mixSide') {
982
+ if (bottomTabConfig) {
983
+ const drawerNavigation = await this.#generateBottomTabNavigationsFile({
984
+ bottomTabConfig: bottomTabConfig,
985
+ unauthenticatedComponentPath,
986
+ bottomDirPath: bottomDirPath,
987
+ mixLayout,
988
+ });
989
+ if (drawerNavigation)
990
+ await this.#generateBottomTabNavigationsFile({
991
+ bottomTabConfig: hostBottomTabConfig,
992
+ unauthenticatedComponentPath,
993
+ bottomDirPath: hostBottomDirPath,
994
+ mixLayout,
995
+ });
996
+ return true;
997
+ } else {
998
+ if (hostBottomTabConfig) {
999
+ const isHostGenerated = await this.#generateBottomTabNavigationsFile({
1000
+ bottomTabConfig: hostBottomTabConfig,
1001
+ unauthenticatedComponentPath,
1002
+ bottomDirPath: hostBottomDirPath,
1003
+ mixLayout,
1004
+ });
1005
+ return isHostGenerated;
1006
+ } else return false;
1007
+ }
1008
+ } else return false;
1009
+ }
1010
+
1011
+ async #generateBottomTabDrawerNavigations({ appDirPath, modules, initialRouteName, unauthenticatedComponentPath }) {
1012
+ const mainRoutes = path.join(appDirPath, `/${mainRoutesFileName}`);
1013
+ const bottomDirPath = path.join(appDirPath, `/${bottomFilePath}`);
1014
+ const hostBottomDirPath = path.join(appDirPath, `/${hostBottomFilePath}`);
1015
+ const drawerDirPath = path.join(appDirPath, `/${drawerFilePath}`);
1016
+ const hostDirPath = path.join(appDirPath, `/${hostDrawerFilePath}`);
1017
+
1018
+ const layoutSettings = this.#layoutSettings;
1019
+ const layoutConfigFileData = await this.#getLayoutConfig();
1020
+ const layoutType = layoutSettings?.layout ?? 'bottom';
1021
+ const layoutRouteConfig = layoutConfigFileData[layoutType];
1022
+ const layoutRouteKey = Object.keys(layoutRouteConfig)[1];
1023
+ const appLayout = layoutRouteConfig[layoutRouteKey];
1024
+ const hostRouteConfig = layoutConfigFileData['host-bottom'];
1025
+ const hostRouteKey = Object.keys(hostRouteConfig)[1];
1026
+ const hostLayout = hostRouteConfig[hostRouteKey];
1027
+ const mixLayoutRouteKey = Object.keys(layoutRouteConfig)?.[2] || null;
1028
+ const mixLayout = mixLayoutRouteKey ? layoutRouteConfig[mixLayoutRouteKey] : null;
1029
+ const modulesRouteConfig = await this.#getModulesRouteConfig({ modules: modules });
1030
+ const mainRouteConfig = await this.#readJsonFile(mainRoutes);
1031
+ const allRoutes = [...[mainRouteConfig ?? []], ...(modulesRouteConfig ?? [])];
1032
+
1033
+ const { replacedNavigationRouteConfig: routeConfig } = getReplacedRouteConfig({
1034
+ layoutType: layoutType,
1035
+ routeConfig: allRoutes,
1036
+ layoutConfigData: layoutConfigFileData,
1037
+ initialRouteName: initialRouteName,
1038
+ });
1039
+ const keyToReplace = appLayout.key || 'bottom_tab';
1040
+ const keyToReplaceHost = hostLayout.key || 'host_tab';
1041
+ const moduleRouteConfigObject = Object.assign({}, ...(routeConfig?.flat(1) ?? []));
1042
+ const configuredRoutes = await getSortedNavigations('/', moduleRouteConfigObject);
1043
+ const layoutBottomTabRouteConfig = configuredRoutes?.[0]?.children?.filter((r) => r?.key == keyToReplace);
1044
+ const hostBottomTabRouteConfig = configuredRoutes?.[0]?.children?.filter((r) => r?.key == keyToReplaceHost);
1045
+
1046
+ const bottomTabConfig =
1047
+ layoutBottomTabRouteConfig?.[0]?.children
1048
+ ?.filter((r) => !r?.side)
1049
+ ?.sort((a, b) => {
1050
+ if (a?.props?.options?.priority === undefined) return 1; // Push items with missing 'id' to the end
1051
+ if (b?.props?.options?.priority === undefined) return -1;
1052
+ return a?.props?.options?.priority - b?.props?.options?.priority;
1053
+ }) ?? [];
1054
+ const hostBottomTabConfig =
1055
+ hostBottomTabRouteConfig?.[0]?.children
1056
+ ?.filter((r) => !r?.side)
1057
+ ?.sort((a, b) => {
1058
+ if (a?.props?.options?.priority === undefined) return 1; // Push items with missing 'id' to the end
1059
+ if (b?.props?.options?.priority === undefined) return -1;
1060
+ return a?.props?.options?.priority - b?.props?.options?.priority;
1061
+ }) ?? [];
1062
+
1063
+ const drawerConfig =
1064
+ layoutBottomTabRouteConfig?.[0]?.children
1065
+ ?.filter((r) => r?.side)
1066
+ ?.sort((a, b) => {
1067
+ if (a?.props?.options?.priority === undefined) return 1; // Push items with missing 'id' to the end
1068
+ if (b?.props?.options?.priority === undefined) return -1;
1069
+ return a?.props?.options?.priority - b?.props?.options?.priority;
1070
+ }) ?? [];
1071
+ const hostDrawerConfig =
1072
+ hostBottomTabRouteConfig?.[0]?.children
1073
+ ?.filter((r) => r?.side)
1074
+ ?.sort((a, b) => {
1075
+ if (a?.props?.options?.priority === undefined) return 1; // Push items with missing 'id' to the end
1076
+ if (b?.props?.options?.priority === undefined) return -1;
1077
+ return a?.props?.options?.priority - b?.props?.options?.priority;
1078
+ }) ?? [];
1079
+
1080
+ if (bottomTabConfig) {
1081
+ const drawerNavigation = await this.#generateBottomTabNavigationsFile({
1082
+ bottomTabConfig: bottomTabConfig,
1083
+ unauthenticatedComponentPath,
1084
+ bottomDirPath: bottomDirPath,
1085
+ mixLayout,
1086
+ });
1087
+ if (drawerNavigation)
1088
+ await this.#generateBottomTabNavigationsFile({
1089
+ bottomTabConfig: hostBottomTabConfig,
1090
+ unauthenticatedComponentPath,
1091
+ bottomDirPath: hostBottomDirPath,
1092
+ mixLayout,
1093
+ });
1094
+ if (drawerConfig) {
1095
+ const drawerNavigation = await this.#generateDrawerNavigationsFile({
1096
+ drawerConfig: drawerConfig,
1097
+ unauthenticatedComponentPath,
1098
+ drawerDirPath: drawerDirPath,
1099
+ });
1100
+ if (drawerNavigation)
1101
+ await this.#generateDrawerNavigationsFile({
1102
+ drawerConfig: hostDrawerConfig,
1103
+ unauthenticatedComponentPath,
1104
+ drawerDirPath: hostDirPath,
1105
+ });
1106
+ return true;
1107
+ } else return true;
1108
+ } else return false;
1109
+ }
1110
+
1111
+ async #generateAppNavigationFile({ appDirPath, customTabBarPath, customDrawerPath, customHeaderPath }) {
1112
+ const navigationDirPath = path.join(appDirPath, `/${appNavigationFileName}`);
1113
+ const layoutSettings = this.#layoutSettings;
1114
+ const layoutConfigFileData = await this.#getLayoutConfig();
1115
+ const layoutType = layoutSettings?.layout || 'bottom';
1116
+ const layoutRouteConfig = layoutConfigFileData[layoutType];
1117
+ const layoutRouteKey = Object.keys(layoutRouteConfig)[1];
1118
+ const appLayout = layoutRouteConfig[layoutRouteKey];
1119
+
1120
+ const initialRouteName =
1121
+ layoutType === 'mixSide'
1122
+ ? appLayout?.[appLayout?.key]?.props?.initialRouteName ?? 'MainStack.Layout.Home'
1123
+ : appLayout?.props?.initialRouteName || 'MainStack.Home';
1124
+ const isShowTabs = layoutType === 'mixSide' || layoutType === 'bottom' ? true : false;
1125
+ const isShowDefalutHeader = layoutType === 'mixSide' ? true : false;
1126
+ const defaultHeaderProps = {
1127
+ showToggle: layoutSettings?.topLeftToggle || false,
1128
+ right: layoutSettings?.topRightSettingToggle || false,
1129
+ };
1130
+ const screenOptionsTab =
1131
+ layoutType === 'mixSide'
1132
+ ? { ...(appLayout?.[appLayout?.key]?.props?.screenOptions ?? {}) }
1133
+ : appLayout?.props?.screenOptions || { headerShown: true, title: 'Home', headerTitle: 'Home' };
1134
+ const screenOptions = appLayout?.props?.screenOptions || {
1135
+ headerShown: true,
1136
+ title: 'Home',
1137
+ headerTitle: 'Home',
1138
+ };
1139
+ let importStatements = `
1140
+ import * as React from 'react';
1141
+ import { navigationRef } from '@common-stack/client-react';
1142
+ import { createNativeStackNavigator } from '@react-navigation/native-stack';`;
1143
+ let rootComponent = '';
1144
+ let appComponent = '';
1145
+ let appNavigation = '';
1146
+ if (layoutType == 'side') {
1147
+ if (customDrawerPath) importStatements += `import CustomDrawerContent from '${customDrawerPath}';\n`;
1148
+
1149
+ if (customHeaderPath) importStatements += `import CustomHeader from '${customHeaderPath}';\n`;
1150
+
1151
+ importStatements += `import { createDrawerNavigator } from '@react-navigation/drawer';
1152
+ import { getHeaderTitle } from '@react-navigation/elements';
1153
+ import { useSelector } from 'react-redux';
1154
+ import stackNavigations from './stack';
1155
+ import drawerNavigations from './drawer';
1156
+ import hostDrawerNavigations from './host_drawer';
1157
+ const Stack = createNativeStackNavigator();
1158
+ const Drawer = createDrawerNavigator();
1159
+ `;
1160
+ rootComponent += `
1161
+ const RootComponent = (props:any) => {
1162
+ const settings = useSelector((state: any) => state.settings);
1163
+ const defaultHeaderProps = ${JSON.stringify(defaultHeaderProps || {})};
1164
+ return (
1165
+ <Drawer.Navigator
1166
+ initialRouteName={${JSON.stringify(initialRouteName)}}
1167
+ //screenOptions={${JSON.stringify(screenOptions)}}
1168
+ screenOptions={({ route }) => ({ ...${JSON.stringify(screenOptions)} ,...{
1169
+ ${
1170
+ customHeaderPath
1171
+ ? `header: (props:any) => {
1172
+ const title = getHeaderTitle(props.options, props.route.name);
1173
+ return <CustomHeader {...defaultHeaderProps} {...props} title={title} style={props.options.headerStyle} />;
1174
+ }`
1175
+ : ''
1176
+ }
1177
+ }})}
1178
+ ${customDrawerPath ? 'drawerContent={(props) => <CustomDrawerContent {...props} />}' : ''}
1179
+ >
1180
+ {settings?.layout == 'host-bottom' ? hostDrawerNavigations({ Drawer }) : drawerNavigations({ Drawer })}
1181
+ </Drawer.Navigator>
1182
+ );
1183
+ }
1184
+ `;
1185
+ }
1186
+ if (layoutType == 'bottom') {
1187
+ if (customTabBarPath) importStatements += `import CustomTabBar from '${customTabBarPath}';\n`;
1188
+
1189
+ if (customHeaderPath) importStatements += `import CustomHeader from '${customHeaderPath}';\n`;
1190
+
1191
+ importStatements += `import {Header,Drawer as DefaultDrawer} from '@admin-layout/gluestack-ui-mobile';
1192
+ import { getHeaderTitle } from '@react-navigation/elements';
1193
+ import { useSelector } from 'react-redux';
1194
+ import { createBottomTabNavigator } from '@react-navigation/bottom-tabs';
1195
+ import stackNavigations from './stack';
1196
+ import bottomNavigations from './bottom';
1197
+ import hostBottomNavigations from './host_bottom';
1198
+ const Stack = createNativeStackNavigator();
1199
+ const Tab = createBottomTabNavigator();
1200
+ `;
1201
+ rootComponent += `
1202
+ const RootComponent = (props:any) => {
1203
+ const settings = useSelector((state: any) => state.settings);
1204
+ const initialRouteName = ${JSON.stringify(initialRouteName)};
1205
+ let defaultScreenOptions = ${JSON.stringify(screenOptionsTab)};
1206
+ const defaultHeaderProps = ${JSON.stringify(defaultHeaderProps || {})};
1207
+ const defaultHeader = {${
1208
+ isShowDefalutHeader ? `header:(props:any)=><Header {...defaultHeaderProps} {...props} />` : ''
1209
+ }};
1210
+ return (
1211
+ <Tab.Navigator
1212
+ initialRouteName={initialRouteName}
1213
+ screenOptions={(props:any)=>({...props,...defaultScreenOptions,...{${
1214
+ customHeaderPath
1215
+ ? `header: (props:any) => {
1216
+ const title = getHeaderTitle(props.options, props.route.name);
1217
+ return <CustomHeader {...defaultHeaderProps} {...props} title={title} style={props.options.headerStyle} />;
1218
+ }`
1219
+ : ''
1220
+ }}})}
1221
+ ${
1222
+ customTabBarPath
1223
+ ? 'tabBar={props => <CustomTabBar key={props?.key??"customTabBarKey"} {...props} />}'
1224
+ : ''
1225
+ }
1226
+ >
1227
+ {settings?.layout == 'host-bottom' ? hostBottomNavigations({ Tab }) : bottomNavigations({Tab})}
1228
+ </Tab.Navigator>
1229
+ );
1230
+ }
1231
+ `;
1232
+ }
1233
+ if (layoutType == 'mixSide') {
1234
+ if (customTabBarPath) importStatements += `import CustomTabBar from '${customTabBarPath}';\n`;
1235
+
1236
+ if (customDrawerPath) importStatements += `import CustomDrawerContent from '${customDrawerPath}';\n`;
1237
+
1238
+ if (customHeaderPath) importStatements += `import CustomHeader from '${customHeaderPath}';\n`;
1239
+
1240
+ importStatements += `import {Header,Drawer as DefaultDrawer} from '@admin-layout/gluestack-ui-mobile';
1241
+ import { useSelector } from 'react-redux';
1242
+ import { MaterialIcons } from "@expo/vector-icons";
1243
+ import { getHeaderTitle } from '@react-navigation/elements';
1244
+ import { createDrawerNavigator } from '@react-navigation/drawer';
1245
+ import { createBottomTabNavigator } from '@react-navigation/bottom-tabs';
1246
+ import stackNavigations from './stack';
1247
+ import bottomNavigations from './bottom';
1248
+ import hostBottomNavigations from './host_bottom';
1249
+ import drawerNavigations from './drawer';
1250
+ import hostDrawerNavigations from './host_drawer';
1251
+ const Stack = createNativeStackNavigator();
1252
+ const Drawer = createDrawerNavigator();
1253
+ const Tab = createBottomTabNavigator();
1254
+ `;
1255
+ rootComponent += `
1256
+ const TabNavigator = () => {
1257
+ const settings = useSelector((state: any) => state.settings);
1258
+ const initialRouteName = ${JSON.stringify(initialRouteName)};
1259
+ let defaultScreenOptions = ${JSON.stringify(screenOptionsTab)};
1260
+ const defaultHeaderProps = ${JSON.stringify(defaultHeaderProps || {})};
1261
+ const defaultHeader = {${
1262
+ isShowDefalutHeader ? `header:(props:any)=><Header {...defaultHeaderProps} {...props} />` : ''
1263
+ }};
1264
+
1265
+ return (
1266
+ <Tab.Navigator
1267
+ initialRouteName={initialRouteName}
1268
+ screenOptions={(props:any)=>({...props,...defaultScreenOptions,...{headerShown: false,header:()=>null},})}
1269
+ ${
1270
+ customTabBarPath
1271
+ ? 'tabBar={props => <CustomTabBar key={props?.key??"customTabBarKey"} {...props} />}'
1272
+ : ''
1273
+ }
1274
+ >
1275
+ {settings?.layout == 'host-bottom' ? hostBottomNavigations({ Tab }) : bottomNavigations({Tab})}
1276
+ </Tab.Navigator>
1277
+ )
1278
+ }
1279
+ const RootComponent = (props:any) => {
1280
+ const initialRouteName = ${JSON.stringify(initialRouteName)};
1281
+ const settings = useSelector((state: any) => state.settings);
1282
+ let defaultScreenOptions = ${JSON.stringify(screenOptionsTab)};
1283
+ const defaultHeaderProps = ${JSON.stringify(defaultHeaderProps || {})};
1284
+ const defaultHeader = {${
1285
+ isShowDefalutHeader ? `header:(props:any)=><Header {...defaultHeaderProps} {...props} />` : ''
1286
+ }};
1287
+ return (
1288
+ <Drawer.Navigator
1289
+ initialRouteName={${JSON.stringify(initialRouteName)}}
1290
+ // screenOptions={${JSON.stringify(screenOptions)}}
1291
+ screenOptions={({ route }) => ({ ...${JSON.stringify(
1292
+ screenOptions,
1293
+ )} ,...{headerTitle:navigationRef?.isReady() && navigationRef?.getCurrentRoute()
1294
+ ? navigationRef?.getCurrentOptions()?.title
1295
+ ? navigationRef?.getCurrentOptions()?.headerTitle
1296
+ : navigationRef?.getCurrentRoute()?.route?.name
1297
+ : "Home",
1298
+ ${
1299
+ customHeaderPath
1300
+ ? `header: (props:any) => {
1301
+ const title = getHeaderTitle(props.options, props.route.name);
1302
+ return <CustomHeader {...defaultHeaderProps} {...props} title={title} isMixedLayout={true} style={props.options.headerStyle} />;
1303
+ }`
1304
+ : ''
1305
+ }
1306
+
1307
+ }})}
1308
+ ${
1309
+ customDrawerPath
1310
+ ? 'drawerContent={(props) => <CustomDrawerContent {...props} showDefaultRoutes={true} />}'
1311
+ : ''
1312
+ }
1313
+ >
1314
+ <Drawer.Screen name="Layout" options={{title:"Home", drawerIcon: ({ color, size }: { color: any, size: any }) => (
1315
+ <MaterialIcons name="home" size={24} color={color} />
1316
+ ),}}
1317
+ component={TabNavigator} />
1318
+ {settings?.layout == 'host-bottom' ? hostDrawerNavigations({ Drawer }) : drawerNavigations({ Drawer })}
1319
+ </Drawer.Navigator>
1320
+ );
1321
+ }
1322
+ `;
1323
+ }
1324
+ appComponent += `
1325
+ const AppNavigations = () => {
1326
+ return (
1327
+ <Stack.Navigator initialRouteName="${initialRouteName}">
1328
+ <Stack.Screen
1329
+ name="MainStack"
1330
+ options={{ headerShown: false }}
1331
+ component={RootComponent}
1332
+ />
1333
+ {stackNavigations({ Stack })}
1334
+ </Stack.Navigator>
1335
+ )
1336
+ }
1337
+
1338
+ export default AppNavigations;
1339
+ `;
1340
+ appNavigation = importStatements + '\n' + rootComponent + '\n' + appComponent;
1341
+ appNavigation = prettier.format(appNavigation, { parser: 'babel' });
1342
+ const writeFileResponse = await this.#writeFile(navigationDirPath, appNavigation);
1343
+ if (writeFileResponse) return true;
1344
+ else return false;
1345
+ }
1346
+
1347
+ async #setLayoutAndGenerateNavigation() {
1348
+ const appDirPath = this.#appDirPath;
1349
+ const modules = this.#modules;
1350
+ const initialRouteName = this.#initialRouteName;
1351
+ const unauthenticatedComponentPath = this.#unauthenticatedComponentPath;
1352
+ const customTabBarPath = this.#customTabBarPath;
1353
+ const customDrawerPath = this.#customDrawerPath;
1354
+ const customHeaderPath = this.#customHeaderPath;
1355
+
1356
+ const layoutSettings = this.#layoutSettings;
1357
+ const layoutConfigFileData = await this.#getLayoutConfig();
1358
+ const layoutType = layoutSettings?.layout || 'bottom';
1359
+ const isAppRoutesGenerated = await this.#generateAppRoutesJson({ appDirPath });
1360
+ if (isAppRoutesGenerated) {
1361
+ const isModuleTsFileGenerated = await this.#generateModulesTsFile({
1362
+ appDirPath,
1363
+ modules,
1364
+ initialRouteName,
1365
+ });
1366
+ if (isModuleTsFileGenerated) {
1367
+ const isStackCreated = await this.#generateStackNavigations({
1368
+ appDirPath,
1369
+ modules,
1370
+ initialRouteName,
1371
+ unauthenticatedComponentPath,
1372
+ });
1373
+ if (isStackCreated) {
1374
+ if (layoutType == 'side') {
1375
+ const isDrawerGenerated = await this.#generateDrawerNavigations({
1376
+ appDirPath,
1377
+ modules,
1378
+ initialRouteName,
1379
+ unauthenticatedComponentPath,
1380
+ });
1381
+ if (isDrawerGenerated) {
1382
+ const appNavigationGenerated = await this.#generateAppNavigationFile({
1383
+ appDirPath,
1384
+ customTabBarPath,
1385
+ customDrawerPath,
1386
+ customHeaderPath,
1387
+ });
1388
+ if (appNavigationGenerated) return appNavigationGenerated;
1389
+ else return true;
1390
+ } else return false;
1391
+ } else if (layoutType == 'bottom' || layoutType == 'host-bottom') {
1392
+ const isBottomTabGenerated = await this.#generateBottomTabNavigations({
1393
+ appDirPath,
1394
+ modules,
1395
+ initialRouteName,
1396
+ unauthenticatedComponentPath,
1397
+ });
1398
+ if (isBottomTabGenerated) {
1399
+ const appNavigationGenerated = await this.#generateAppNavigationFile({
1400
+ appDirPath,
1401
+ customTabBarPath,
1402
+ customDrawerPath,
1403
+ customHeaderPath,
1404
+ });
1405
+ if (appNavigationGenerated) return appNavigationGenerated;
1406
+ else return true;
1407
+ } else return false;
1408
+ } else {
1409
+ const isBottomTabDrawerGenerated = await this.#generateBottomTabDrawerNavigations({
1410
+ appDirPath,
1411
+ modules,
1412
+ initialRouteName,
1413
+ unauthenticatedComponentPath,
1414
+ });
1415
+ if (isBottomTabDrawerGenerated) {
1416
+ const appNavigationGenerated = await this.#generateAppNavigationFile({
1417
+ appDirPath,
1418
+ customTabBarPath,
1419
+ customDrawerPath,
1420
+ customHeaderPath,
1421
+ });
1422
+ if (appNavigationGenerated) return appNavigationGenerated;
1423
+ else return true;
1424
+ } else return false;
1425
+ }
1426
+ } else return false;
1427
+ } else return false;
1428
+ } else return false;
1429
+ }
1430
+
1431
+ async generateAppNavigations() {
1432
+ return this.#setLayoutAndGenerateNavigation();
1433
+ }
1434
+ }