import chalk from 'chalk'; import * as Eta from 'eta'; import fs from 'fs'; import path from 'path'; import { fileLogger } from '@loggers/fileLogger'; import { getTextCase } from '@utils/getTextCase'; import { getPathOnSrc } from '@utils/path'; import { prettierString } from '@utils/prettier'; export class GeneratorByEta { eta: typeof Eta; commonTemplatePath = getPathOnSrc('templates', 'screen'); definedTemplate = { Index: { name: 'Index', path: path.resolve(this.commonTemplatePath, 'index.template.eta'), }, NativeComponent: { name: 'NativeComponent', path: path.resolve(this.commonTemplatePath, 'component.template.eta'), }, } as const; constructor() { this.eta = { ...Eta }; this.init(); } init() { Object.keys(this.definedTemplate).forEach((key) => { const { name, path: templatePath } = this.definedTemplate[key as keyof typeof this.definedTemplate]; this.defineByPath({ name, templatePath }); }); return this; } defineByPath({ name, templatePath }: { name: string; templatePath: string }) { const template = fs.readFileSync(templatePath, { encoding: 'utf-8' }); this.eta.templates.define(name, this.eta.compile(template)); this.definedTemplate = { ...this.definedTemplate, // [name]: { name, path: templatePath }, }; return this; } async renderDefinedEta( name: T, options: TemplateProps[T], ) { return this.eta.render( `<%~ include("${name}",${JSON.stringify(options)})%>`, {}, ); } async generate({ view, // output, }: { view: string; output: string; }) { const { dir } = path.parse(output); fs.mkdirSync(dir, { recursive: true }); fs.writeFileSync(output, await prettierString(view), 'utf-8'); fileLogger.generate(output); } async generateFileByEta({ template, // output, config, }: { template: string; output: string; config: any; }) { const view = (await this.eta.renderFile(template, { ...config, // utils: { getTextCase, ...config.utils }, definedTemplate: this.definedTemplate, })) || ''; this.generate({ view, output }); return this; } async generateIndexFile({ config, output, }: { config: TemplateProps['Index']; output: string; }) { const { Index } = this.definedTemplate; const view = (await this.renderDefinedEta(Index.name, config)) || ''; this.generate({ view, output }); } async generateNativeComponentFile({ config, output, }: { config: TemplateProps['NativeComponent']; output: string; }) { const { NativeComponent } = this.definedTemplate; const view = (await this.renderDefinedEta(NativeComponent.name, config)) || ''; this.generate({ view, output }); } }