Skip to content

Commit

Permalink
Merge pull request #17 from wpdas/feature/core-improvement-beta-27
Browse files Browse the repository at this point in the history
Feature: Core Improvement Beta 27
  • Loading branch information
wpdas authored Apr 23, 2024
2 parents 475d3f8 + 193789d commit 74bb9ff
Show file tree
Hide file tree
Showing 8 changed files with 123 additions and 72 deletions.
6 changes: 6 additions & 0 deletions lib/actions/loadFilesInfo.js
Original file line number Diff line number Diff line change
Expand Up @@ -74,6 +74,12 @@ const processFileSchema = (filePath, processOnlyThisFile) => {

// Verifica cada arquivo jsx e ts para ver se estão quebrados ou não.
hasError = checkSyntaxError(filePath);

if (hasError) {
log.error(hasError);
return;
}

hasError = checkForWildcardImports(filePath);

if (hasError) {
Expand Down
7 changes: 3 additions & 4 deletions lib/actions/processChildrenWidget.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,6 @@ const {
} = require("../helpers");
const extractJSXChildren = require("../parsers/extractJSXChildren");
const extractPropsFromJSX = require("../parsers/extractPropsFromJSX");
const extractSpreadsFromJSX = require("../parsers/extractSpreadsFromJSX");
const extractTopLevelJSXElements = require("../parsers/extractTopLevelJSXElements");
const replaceJSXElement = require("../parsers/replaceJSXElement");

Expand Down Expand Up @@ -49,14 +48,14 @@ 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) {
let childProps = extractPropsFromJSX(htmlElement);
const childSpreads = extractSpreadsFromJSX(htmlElement);
const extractPropsResult = extractPropsFromJSX(htmlElement);
let childProps = extractPropsResult.keyValueProps;
const childSpreads = extractPropsResult.spreads;

let childChildren = extractJSXChildren(htmlElement);
// INFO: Se tiver child dentro deste child (childChildren), chama essa mesma função recursivamente?
// ja esta sendo feito pelo "transformSchemaToWidgets"
if (childChildren) {
// childChildren = processChildrenWidget(childChildren, fileSchemas);
childProps = { ...childProps, children: childChildren };
}

Expand Down
18 changes: 4 additions & 14 deletions lib/actions/transformSchemaToWidget.js
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,6 @@ const analyzeFunctionSignature = require("../parsers/analyzeFunctionSignature");
const removeFunctionParams = require("../parsers/removeFunctionParams");
const transformAsyncAwait = require("../parsers/transformAsyncAwait");
const compilerOptions = require("./compilerOptions");
const extractSpreadsFromJSX = require("../parsers/extractSpreadsFromJSX");

let processError = null;

Expand Down Expand Up @@ -391,8 +390,10 @@ const swapComponentsForStatelessFiles = (fileSchemas, fileSchema) => {
.replaceAll(LINE_BREAKS, "")
.replaceAll(MORE_THAN_ONE_SPACE, " ");

let childProps = extractPropsFromJSX(htmlElementString);
const childSpreads = extractSpreadsFromJSX(htmlElementString);
const extractPropsResult = extractPropsFromJSX(htmlElementString);
let childProps = extractPropsResult.keyValueProps;

const childSpreads = extractPropsResult.spreads;

// get the children
let childChildren = extractJSXChildren(htmlElementString);
Expand Down Expand Up @@ -630,17 +631,6 @@ const transformSchemaToWidget = (fileSchemas, additionalFileSchemas) => {
// Reset error state
processError = null;

// Tag alem files (INFO: Isso não está servindo pra nada atualmente)
// TODO: Checar para ver se remove nas versoes posteriores caso não tenha utilidade isso aqui
fileSchemas.forEach((fileSchema, fileSchemaIndex) => {
const isAlemImportableFile = fileSchema.filePath.includes(
"lib/alem-vm/importable/",
);

fileSchema.isAlemFile = isAlemImportableFile;
fileSchemas[fileSchemaIndex] = fileSchema;
});

// 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...
Expand Down
59 changes: 59 additions & 0 deletions lib/config/cache-plugins/stateless_renamePropsTo__props__.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
const parser = require("@babel/parser");
const traverse = require("@babel/traverse").default;
const t = require("@babel/types");
const hasWidgetPropsCheck = require("../../actions/hasWidgetPropsCheck");
const generate = require("@babel/generator").default;

/**
* Troca o nome de objeto global "props" para "__props__" para que as props do Widget parent não seja sobrescrevido.
* @param {*} code
* @returns
*/
function stateless_renamePropsTo__props__(code) {
// Stateless components only
if (!hasWidgetPropsCheck(code)) {
const ast = parser.parse(code, {
sourceType: "module",
plugins: ["jsx", "typescript"],
});

traverse(ast, {
ArrowFunctionExpression(path) {
// Procura por parâmetros chamados 'props'
path.node.params.forEach((param) => {
if (t.isIdentifier(param) && param.name === "props") {
// Renomeia para '__props__'
param.name = "__props__";
// Renomeia todas as referências dentro do escopo da função
const binding = path.scope.getBinding("props");
if (binding) {
binding.referencePaths.forEach((refPath) => {
refPath.node.name = "__props__";
});
}
}
});
},
FunctionDeclaration(path) {
// Similar ao ArrowFunctionExpression
path.node.params.forEach((param) => {
if (t.isIdentifier(param) && param.name === "props") {
param.name = "__props__";
const binding = path.scope.getBinding("props");
if (binding) {
binding.referencePaths.forEach((refPath) => {
refPath.node.name = "__props__";
});
}
}
});
},
});

return generate(ast, { retainLines: true, concise: false }).code;
}

return code;
}

module.exports = stateless_renamePropsTo__props__;
17 changes: 17 additions & 0 deletions lib/config/filesContentCache.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,9 +4,16 @@
*/

const fs = require("fs");
const stateless_renamePropsTo__props__ = require("./cache-plugins/stateless_renamePropsTo__props__");

const filesContentCache = {};

// TODO: usar esse processo para processar os arquivos apenas uma vez
const runPlugins = (code) => {
code = stateless_renamePropsTo__props__(code);
return code;
};

const getFileContent = (filePath) => {
// First, try to return the cached content
if (filesContentCache[filePath]) {
Expand All @@ -15,6 +22,11 @@ const getFileContent = (filePath) => {

// If there's no cache, read file, save cache and return the file content
let fileContent = fs.readFileSync(filePath, "utf8");

// Run plugins
fileContent = runPlugins(fileContent);

// Store
filesContentCache[filePath] = fileContent;

return fileContent;
Expand All @@ -23,6 +35,11 @@ const getFileContent = (filePath) => {
const updateFileContent = (filePath) => {
// Read file and save in cache
let fileContent = fs.readFileSync(filePath, "utf8");

// Run plugins
fileContent = runPlugins(fileContent);

// Store
filesContentCache[filePath] = fileContent;
};

Expand Down
45 changes: 33 additions & 12 deletions lib/parsers/extractPropsFromJSX.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,8 @@ function extractPropsFromJSX(jsxString) {
// V2
let propsObject = {};

let spreads = [];

const ast = babel.parse(jsxString, {
presets: [presetReactPath],
});
Expand All @@ -28,25 +30,44 @@ function extractPropsFromJSX(jsxString) {
: true;
}
propsObject[key] = value;
} else if (babel.types.isJSXSpreadAttribute(attr)) {
// Trata a propagação de objetos
if (babel.types.isObjectExpression(attr.argument)) {
attr.argument.properties.forEach((prop) => {
if (babel.types.isObjectProperty(prop)) {
const key = prop.key.name || prop.key.value; // Suporta tanto propriedades identificadas por nome quanto por valor
const value = generate(prop.value, { concise: true }).code;
propsObject[key] = value;
}
});
}
}
// } else if (babel.types.isJSXSpreadAttribute(attr)) {
// // Trata a propagação de objetos
// if (babel.types.isObjectExpression(attr.argument)) {
// attr.argument.properties.forEach((prop) => {
// if (babel.types.isObjectProperty(prop)) {
// const key = prop.key.name || prop.key.value; // Suporta tanto propriedades identificadas por nome quanto por valor
// const value = generate(prop.value, { concise: true }).code;
// propsObject[key] = value;
// }
// });
// }
// }

// Extrais os spreads da estrutura
if (babel.types.isJSXSpreadAttribute(attr)) {
// Handles spread attributes
const spreadCode = `...${
generate(attr.argument, { concise: true }).code
}`;
spreads.push(spreadCode);
}
});

path.stop(); // Interrompe após o primeiro elemento JSX
},
});

return propsObject;
return {
/**
* Propriedades que contem chave: valor
*/
keyValueProps: propsObject,
/**
* Spreads achados
*/
spreads,
};
}

module.exports = extractPropsFromJSX;
41 changes: 0 additions & 41 deletions lib/parsers/extractSpreadsFromJSX.js

This file was deleted.

2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
{
"name": "alem",
"description": "Create web3 applications for NEAR BOS with a focus on performance and friendly development.",
"version": "1.0.0-beta.26",
"version": "1.0.0-beta.27",
"main": "main.js",
"types": "index.d.ts",
"author": "Wenderson Pires - wendersonpires.near",
Expand Down

0 comments on commit 74bb9ff

Please sign in to comment.