Skip to content

Commit

Permalink
Merge pull request #18 from wpdas/feat/modules-files
Browse files Browse the repository at this point in the history
Feature: local modules files
  • Loading branch information
wpdas authored Apr 29, 2024
2 parents 4711bcf + 2b7e9da commit a3d59d2
Show file tree
Hide file tree
Showing 28 changed files with 1,251 additions and 218 deletions.
2 changes: 1 addition & 1 deletion lib/actions/handleNames.js
Original file line number Diff line number Diff line change
Expand Up @@ -313,7 +313,7 @@ const checkIfItemExistInContent = (content, itemName) => {
* @param {{filePath: string, toImport: string[], content: string}[]} fileSchemas
*/
const handleNames = (fileSchemas) => {
reset_name_counter();
// reset_name_counter();
let tempBundle = "";

/**
Expand Down
40 changes: 30 additions & 10 deletions lib/actions/loadFilesContent.js
Original file line number Diff line number Diff line change
@@ -1,16 +1,13 @@
const parseAlemFeatures = require("../config/parseAlemFeatures");
const { scapeBacktick } = require("../helpers");
const transformSchemaToWidget = require("./transformSchemaToWidget");

/**
* Load the "componentCodes" from all Widgets based on file schemas
* @param {{filePath: string, toImport: string[], content: string}[]} fileSchemas
* @param {*} additionalFileSchemas FileSchemas to be added to the list of main fileSchemas. It's going to be added first before
* the process starts. This is util to inject previous schema files like Além importable items.
*/
const loadComponentCodesObjectByFileSchemas = (
fileSchemas,
additionalFileSchemas,
) => {
const loadComponentCodesObjectByFileSchemas = (fileSchemas) => {
let componentsCodes = "";

/**
Expand All @@ -22,18 +19,39 @@ const loadComponentCodesObjectByFileSchemas = (
fileSchemas = fileSchemas.reverse();

// Get Normal js files & Widget files (components transformed to BOS Widgets)
const completeFileSchemas = transformSchemaToWidget(
fileSchemas,
additionalFileSchemas,
);
const completeFileSchemas = transformSchemaToWidget(fileSchemas);

// Processa também os módulos
let modulesCodes = "";

completeFileSchemas.fileSchemas.forEach((fileSchema) => {
if (fileSchema.widgetName && !fileSchema.isModule) {
// Prepare Widgets (stateful components)
if (fileSchema.widgetName && !fileSchema.isStateless) {
componentsCodes += `
${fileSchema.widgetName}: \`${scapeBacktick(fileSchema.finalFileBundle)}\`,
`;
}

// Prepare modules
if (fileSchema.isModule) {
// let modulesValues = "{";
// const valuesEntries = Object.entries(fileSchema.moduleProps.values);
// valuesEntries.forEach((entrie) => {
// modulesValues += `
// ${entrie[0]}: ${scapeBacktick(entrie[1])},
// `;
// });
// modulesValues += "}";

// modulesCodes += `
// "${fileSchema.moduleProps.name}": ${parseAlemFeatures(modulesValues)},
// `;

modulesCodes += `
"${fileSchema.moduleProps.name}": ${parseAlemFeatures(scapeBacktick(fileSchema.moduleProps.module))},
`;
}

if (fileSchema.widgetName === "App") {
appComponentFinalBundle = fileSchema.finalFileBundle;
}
Expand All @@ -42,6 +60,8 @@ const loadComponentCodesObjectByFileSchemas = (
return {
/** Código final de todos os componentes do projeto */
componentsCodes,
/** Código final de todos os módulos. Eles serão inseridos no escopo global e disponível para todos os subcomponents */
modulesCodes,
/** Código final do componente App de entrada do projet apenas. (src/index.tsx | .jsx) */
appComponentFinalBundle,
/** Esquema final de todos os arquivos processados */
Expand Down
23 changes: 21 additions & 2 deletions lib/actions/loadFilesInfo.js
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,8 @@ const { removeImports } = require("../parse");
const filesContentCache = require("../config/filesContentCache");
const replaceRegexWithReferences = require("../parsers/regex-parser/convertRegexToStringLiteral");
const regexObjects = require("../parsers/regex-parser/regexObjects");
const prepareAlemDependencies = require("./prepareAlemDependencies");
// const extractTopLevelDeclarations = require("../parsers/extractTopLevelDeclarations");
/**
* Transform statefull components references to JSX (this applies for stateful and stateless components)
* Troca referencias de stateful components para JSX. Accesse o arquivo "transformComponentReferenceToJSX" para saber mais.
Expand Down Expand Up @@ -131,6 +133,12 @@ const processFileSchema = (filePath, processOnlyThisFile) => {
}

fileContent = removeCommentsResult.code;

// Processa as dependencias de Além
const alemStuff = prepareAlemDependencies(fileContent);
fileContent = alemStuff.updatedFileContent;

// INFO: Caminho dos imports
const fileImportsPath = helpers.getImportsPath(fileContent);

let currentFileSchema = {
Expand All @@ -140,7 +148,10 @@ const processFileSchema = (filePath, processOnlyThisFile) => {
nextFilesToLoad: [],
toImport: [],
content: fileContent,
isModule: false,
moduleProps: {},
};

fileImportsPath.forEach((importPath) => {
// console.log("Check import Path:", importPath);

Expand All @@ -149,13 +160,19 @@ const processFileSchema = (filePath, processOnlyThisFile) => {
importPath = importPath.replaceAll("/", "\\");
}

let importedFileContentPath = "";
let importedFileContentPath = importPath;

// Replace path aliases
// Check if its has path alias
if (compilerOptions.hasPathAlias(importPath)) {
importedFileContentPath = compilerOptions.replacePathAlias(importPath);
} else {

// INFO: Se incluir um caminho relativo de um recurso Além, não precisa relacionar com o componente pai
// já que o diretório está pronto para acessar o arquivo
} else if (
!importPath.includes("node_modules/alem") && // unix
!importPath.includes("node_modules\\alem") // win
) {
// Usa src para inicio ou o caminho do pai do arquivo sendo processado atualmente
importedFileContentPath = path.join(parentFolder, importPath);
}
Expand Down Expand Up @@ -222,6 +239,8 @@ const loadFilesInfo = (entryFile) => {
filePath: item.filePath,
toImport: item.toImport,
content: item.content,
// isModule: item.isModule,
// moduleProps: item.moduleProps,
};
delete newItem.filesToImport;
return newItem;
Expand Down
53 changes: 53 additions & 0 deletions lib/actions/prepareAlemDependencies.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
const {
getFileImportsElements,
getImportedElementFileSource,
} = require("../helpers");
const transformImports = require("../parsers/transformImports");
const importableFiles = require("../config/importableFiles");

/**
* Caso tenha dependencias do Alem (inportable items), prepara eles para serem injetados.
*
* Remove os elementos da chave em que está e coloca em uma nova linha contendo seu caminho
* até a lib alem-vm/importable/item...
* @param {{filePath: string, toImport: string[], content: string, finalFileBundle: string, componentImportItems:[], componentParamsItems:[], componentComponentItems: [], widgetName?: string, htmlElementsProps: {}}} fileSchema
*/
const prepareAlemDependencies = (originalFileContent) => {
const importItems = getFileImportsElements(originalFileContent);

let updatedFileContent = originalFileContent;
const alemDependencies = []; // Lista de dependencias Além (diretorio dos arquivos)

importItems.forEach((item) => {
// TODO: [Alem items: Routes, Link, etc] Checar se esta dando conflito com items do projeto

const importStatementFileSource = getImportedElementFileSource(
updatedFileContent,
item,
);

// Se o item estiver vindo de um destino que contenha "alem-vm" ou "alem"
// logo é um item do Além.
if (
/\balem-vm\b/.test(importStatementFileSource) ||
/\balem\b/.test(importStatementFileSource)
) {
const alemImportElement = importableFiles[item];

// Se for um elemento importavel do Além e estiver presente no importableFiles do Além, então
// insere a nova linha no arquivo pedindo para importar o elemento.
if (alemImportElement) {
alemDependencies.push(alemImportElement);
updatedFileContent = transformImports(
updatedFileContent,
item,
alemImportElement,
);
}
}
});

return { updatedFileContent, alemDependencies };
};

module.exports = prepareAlemDependencies;
2 changes: 1 addition & 1 deletion lib/actions/processChildrenWidget.js
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,7 @@ const processChildrenWidget = (htmlContent, fileSchemas) => {

// Processa o arquivo como Widget apenas se for achado na lista de schemas e
// for um componente stateful
if (componentSchema && !componentSchema.isModule) {
if (componentSchema && !componentSchema.isStateless) {
const extractPropsResult = extractPropsFromJSX(htmlElement);
let childProps = extractPropsResult.keyValueProps;
const childSpreads = extractPropsResult.spreads;
Expand Down
Loading

0 comments on commit a3d59d2

Please sign in to comment.