Skip to content

Commit

Permalink
extract metadataplugin to another file to use in the custom plugin it…
Browse files Browse the repository at this point in the history
…self, fix loc issues, hide esmodule config for now, add parser plugins, show a white background for unknown plugins, put custom plugin under a flag
  • Loading branch information
hzoo committed Aug 28, 2020
1 parent 7e5649d commit 009ddff
Show file tree
Hide file tree
Showing 6 changed files with 213 additions and 171 deletions.
109 changes: 3 additions & 106 deletions babel.config.js
Expand Up @@ -6,6 +6,8 @@ function normalize(src) {
return src.replace(/\//, path.sep);
}

const metadataPlugin = require("./sandbox/src/metadataPlugin");

module.exports = function (api) {
const env = api.env();

Expand Down Expand Up @@ -132,112 +134,7 @@ module.exports = function (api) {
overrides: [
{
test: [/(babel-plugin|babel-helper)-/],
plugins: [
function (babel) {
const { types: t, template } = babel;

return {
name: "babel-internal-modify-replacewith",
visitor: {
// + replaceWithMultiple
// path.replaceWith(a) -> path.replaceWith(a, "name")
// TODO: handle nested MemberExpression like a.b.replaceWith
CallExpression(path, state) {
if (
path.node.callee.type === "MemberExpression" &&
path.node.callee.property.type === "Identifier" &&
[
"replaceWith",
"replaceWithMultiple",
"insertAfter",
"insertBefore",
"addHelper",
].some(a => a === path.node.callee.property.name)
) {
const pluginName = normalize(state.filename).match(
/babel-(plugin|helper)-((\w+-?)+)/
)[2];
/*
Allow specifying a node to get correct start/end
(instead of defaulting to this.node).
// node: rest
target.insertBefore(loop);
*/
const hasComment = path.parentPath.node.leadingComments;
let comment;
if (hasComment) {
comment = hasComment[0].value.match(/node: (.*)/);
if (comment) {
comment = template.expression(comment[1])();
}
}
// "C:\\Users\\babel\\packages\\babel-plugin-proposal-unicode-property-regex\\src\\index.js".match(/babel-(plugin|helper)-((\w+-?)+)/)
// {
// name: "unicode-property-regex",
// file: "babel-plugin-proposal-unicode-property-regex\\src\\index.js",
// start: 0,
// end: 1,
// }
const props = [
t.objectProperty(
t.identifier("name"),
t.stringLiteral(pluginName)
),
t.objectProperty(
t.identifier("file"),
t.stringLiteral(
`${normalize(state.filename).substr(
normalize(state.filename).indexOf(pluginName)
)} (${path.node.loc.start.line}:${
path.node.loc.start.column
})`
)
),
];
const start = comment
? t.objectProperty(
t.identifier("start"),
t.memberExpression(comment, t.identifier("start"))
)
: path.scope.hasBinding("path")
? t.objectProperty(
t.identifier("start"),
t.memberExpression(
t.memberExpression(
t.identifier("path"),
t.identifier("node")
),
t.identifier("start")
)
)
: null;
if (start) props.push(start);
const end = comment
? t.objectProperty(
t.identifier("end"),
t.memberExpression(comment, t.identifier("end"))
)
: path.scope.hasBinding("path")
? t.objectProperty(
t.identifier("end"),
t.memberExpression(
t.memberExpression(
t.identifier("path"),
t.identifier("node")
),
t.identifier("end")
)
)
: null;
if (end) props.push(end);
path.node.arguments.push(t.objectExpression(props));
}
},
},
};
},
],
plugins: [metadataPlugin],
},
{
test: [
Expand Down
11 changes: 5 additions & 6 deletions packages/babel-traverse/src/path/index.js
Expand Up @@ -225,18 +225,17 @@ Object.assign(

NodePath.prototype.addMetadata = function (node, metaData) {
if (!metaData) return;
const { name, file, start, end } = metaData;
const { start, end, ...other } = metaData;
const newNode = {
name,
file,
...other,
start:
node.start ||
this.node.start ||
this.node?.start ||
this.node?.babelPlugin?.[0].start ||
start,
end: node.end || this.node.end || this.node?.babelPlugin?.[0].end || end,
end: node.end || this.node?.end || this.node?.babelPlugin?.[0].end || end,
};
if (!this?.node.babelPlugin) {
if (!this?.node?.babelPlugin) {
node.babelPlugin = [newNode];
} else {
node.babelPlugin = this.node.babelPlugin.concat(newNode);
Expand Down
69 changes: 38 additions & 31 deletions sandbox/src/components/App.js
Expand Up @@ -71,6 +71,16 @@ let proposalMap = {
"transform-arrow-functions": "background: rgba(42, 187, 155, 0.5)",
"transform-destructuring": "background: rgba(42, 187, 155, 0.1)",
"transform-typescript": "background: rgba(42, 187, 155, 0.4)",
"module-imports": "background: rgba(42, 187, 155, 0.2)",
"proposal-object-rest-spread": "background: rgba(42, 187, 155, 0.3)",
"proposal-nullish-coalescing-operator": "background: rgba(233, 212, 96, 0.3)",
"transform-block-scoping": "background: rgba(21, 132, 196, 0.3)",
"builder-binary-assignment-operator-visitor":
"background: rgba(255, 0, 0, 0.3)",
"proposal-optional-catch-binding": "background: rgba(255, 0, 0, 0.4)",
"proposal-logical-assignment-operators": "background: rgba(255, 0, 0, 0.5)",
"create-class-features-plugin": "background: rgba(0, 255, 0, 0.2)",
"wrap-function": "background: rgba(0, 255, 0, 0.3)",
};

function CompiledOutput({
Expand Down Expand Up @@ -115,14 +125,21 @@ function CompiledOutput({
useEffect(() => {
if (!outputEditor || !compiled.nodes) return;
for (let node of compiled.nodes) {
console.log(JSON.stringify(node.babelPlugin));
console.log(node.babelPlugin);
let highlightColor = proposalMap[node.babelPlugin[0]?.name];
if (highlightColor) {
outputEditor.doc.markText(
fixLoc(node.loc.start),
fixLoc(node.loc.end),
{ css: highlightColor }
);
} else {
console.log(node.babelPlugin[0].name);
outputEditor.doc.markText(
fixLoc(node.loc.start),
fixLoc(node.loc.end),
{ css: "background: rgba(255, 255, 255, 0.2)" }
);
}
}
}, [outputEditor, compiled.nodes]);
Expand All @@ -134,7 +151,7 @@ function CompiledOutput({
source,
processOptions(config, debouncedPlugin)
);
let newAST = Babel.parse(code);
let newAST = Babel.parse(code, processOptions(config, debouncedPlugin));
mergeLoc(ast, newAST, (value, loc) => {
let node = { ...value, loc };
let added = nodes.some((existingNode, i) => {
Expand Down Expand Up @@ -210,7 +227,11 @@ function CompiledOutput({
);
}

export const App = ({ defaultSource, defaultBabelConfig, defCustomPlugin }) => {
export default function App({
defaultSource,
defaultBabelConfig,
defCustomPlugin,
}) {
const [source, setSource] = React.useState(defaultSource);
const [enableCustomPlugin, toggleCustomPlugin] = React.useState(false);
const [customPlugin, setCustomPlugin] = React.useState(defCustomPlugin);
Expand Down Expand Up @@ -259,17 +280,7 @@ export const App = ({ defaultSource, defaultBabelConfig, defCustomPlugin }) => {
return (
<Root>
<Section>
{/* buttons */}

{/* <Actions>
<label>
<input
checked={enableCustomPlugin}
onChange={() => toggleCustomPlugin(!enableCustomPlugin)}
type="checkbox"
/>
<span>Custom Plugin</span>
</label>
<button
onClick={() =>
setBabelConfig(configs => [
Expand All @@ -282,8 +293,16 @@ export const App = ({ defaultSource, defaultBabelConfig, defCustomPlugin }) => {
</button>
</Actions> */}

{/* input section */}

{enableCustomPlugin && (
<Column>
<Code
value={customPlugin}
onChange={val => setCustomPlugin(val)}
docName="plugin.js"
/>
<Toggle onClick={() => toggleCustomPlugin(false)} />
</Column>
)}
<Column>
<div style={{ textAlign: "center" }}>Source</div>
<Code
Expand All @@ -296,28 +315,16 @@ export const App = ({ defaultSource, defaultBabelConfig, defCustomPlugin }) => {
/>
<FileSize>
{size}b, {gzip}b
<button onClick={() => toggleCustomPlugin(!enableCustomPlugin)}>
CUSTOM
</button>
</FileSize>
{/* <AST source={source}></AST> */}
</Column>

{/* custom plugin section */}

{enableCustomPlugin && (
<Wrapper>
<Code
value={customPlugin}
onChange={val => setCustomPlugin(val)}
docName="plugin.js"
/>
<Toggle onClick={() => toggleCustomPlugin(false)} />
</Wrapper>
)}
{/* output code and config section*/}
{results}
</Section>
</Root>
);
};
}

// UTILS

Expand Down
57 changes: 29 additions & 28 deletions sandbox/src/index.js
@@ -1,6 +1,6 @@
import React from "react";
import ReactDOM from "react-dom";
import { App } from "./components/App";
import App from "./components/App";

const SOURCE = `const foo = (...a) => \`\${a?.b}\`;
enum Direction {
Expand Down Expand Up @@ -45,38 +45,39 @@ const CONFIG = [
],
plugins: [["@babel/plugin-transform-runtime", { useESModules: true }]],
},
{
presets: [
[
"@babel/preset-env",
{
loose: true,
modules: false,
shippedProposals: true,
targets: { esmodules: true },
bugfixes: true,
},
],
"@babel/preset-react",
[
"@babel/preset-typescript",
{
isTSX: true,
allExtensions: true,
allowDeclareFields: true,
allowNamespaces: true,
onlyRemoveTypeImports: true,
},
],
],
plugins: [["@babel/plugin-transform-runtime", { useESModules: true }]],
},
// {
// presets: [
// [
// "@babel/preset-env",
// {
// loose: true,
// modules: false,
// shippedProposals: true,
// targets: { esmodules: true },
// bugfixes: true,
// },
// ],
// "@babel/preset-react",
// [
// "@babel/preset-typescript",
// {
// isTSX: true,
// allExtensions: true,
// allowDeclareFields: true,
// allowNamespaces: true,
// onlyRemoveTypeImports: true,
// },
// ],
// ],
// plugins: [["@babel/plugin-transform-runtime", { useESModules: true }]],
// },
];
const PLUGIN = `export default function customPlugin(babel) {
return {
visitor: {
Identifier(path) {
// console.log(path.node.name);
// path.addMetadata(path.node, "test-plugin");
// path.node.name = path.node.name + 'zz';
}
}
};
Expand Down

0 comments on commit 009ddff

Please sign in to comment.