Skip to content

Commit

Permalink
feat: build time
Browse files Browse the repository at this point in the history
  • Loading branch information
Mauro Erta committed Jan 17, 2023
1 parent d1db70c commit f62c3a1
Show file tree
Hide file tree
Showing 35 changed files with 2,394 additions and 1 deletion.
4 changes: 4 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -43,13 +43,17 @@
},
"dependencies": {
"csstype": "3.1.1",
"next": "13.1.1",
"react": "18.2.0",
"react-dom": "18.2.0",
"react-native": "0.71.0"
},
"devDependencies": {
"@commitlint/cli": "17.4.2",
"@commitlint/config-lerna-scopes": "17.4.2",
"@babel/preset-env": "7.17.12",
"@babel/preset-react": "7.17.12",
"@babel/preset-typescript": "^7.18.6",
"@testing-library/jest-dom": "5.16.5",
"@testing-library/react": "13.4.0",
"@types/glob": "8.0.0",
Expand Down
25 changes: 25 additions & 0 deletions packages/babel-plugin/LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@

The MIT License (MIT)

Copyright (c) Mauro Erta.

Permission is hereby granted, free of charge, to any person
obtaining a copy of this software and associated documentation
files (the "Software"), to deal in the Software without
restriction, including without limitation the rights to use,
copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following
conditions:

The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE.
11 changes: 11 additions & 0 deletions packages/babel-plugin/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
# @morfeo/babel

![Morfeo logo](https://morfeo.dev/img/morfeo.png)

**@morfeo/babel** is a babel plugin that enables the evaluation at build time of morfeo.

---

[Documentation](https://morfeo.dev) | [API](https://github.com/morfeojs/morfeo) | [Contributing](https://github.com/morfeojs/morfeo/blob/main/CONTRIBUTING.md) | [![Discord](https://badgen.net/badge/icon/discord?icon=discord&label)](https://discord.gg/5hbsKMBRBh)

---
3 changes: 3 additions & 0 deletions packages/babel-plugin/jest.config.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
module.exports = {
testEnvironment: 'jsdom',
};
51 changes: 51 additions & 0 deletions packages/babel-plugin/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
{
"name": "@morfeo/babel-plugin",
"author": {
"name": "Mauro Erta",
"email": "mauro@vlkstudio.com"
},
"private": false,
"version": "0.7.0",
"license": "MIT",
"main": "commonjs/index.js",
"module": "build/index.js",
"types": "build/index",
"typings": "build/index",
"keywords": [
"morfeo",
"morfeo-js",
"babel",
"build-time",
"css-in-js"
],
"scripts": {
"build": "yarn build:esm && yarn build:commonjs",
"build:esm": "rimraf build && tsc",
"build:commonjs": "rimraf commonjs && tsc --module CommonJS --outdir commonjs",
"watch": "tsc -w"
},
"dependencies": {
"@morfeo/jss": "^0.7.0"
},
"peerDependencies": {
"@babel/core": "7.20.5",
"@babel/types": "7.20.5",
"@babel/traverse": "7.20.5"
},
"publishConfig": {
"access": "public"
},
"files": [
"build",
"commonjs"
],
"repository": {
"type": "git",
"url": "https://github.com/morfeojs/morfeo",
"directory": "packages/babel"
},
"homepage": "https://morfeo.dev",
"bugs": {
"url": "https://github.com/morfeojs/morfeo/issues"
}
}
2 changes: 2 additions & 0 deletions packages/babel-plugin/src/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
export type { MorfeoCompilerOptions } from './types';
export { default } from './plugin';
12 changes: 12 additions & 0 deletions packages/babel-plugin/src/plugin.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
import type { ConfigAPI, PluginObj } from '@babel/core';
import getVisitor from './visitor';

export default function morfeoBabelPlugin(
_babel: ConfigAPI,
_options: any,
): PluginObj {
return {
name: '@morfeo/babel-plugin',
visitor: getVisitor(),
};
}
66 changes: 66 additions & 0 deletions packages/babel-plugin/src/toJS.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
/**
* This code has been taken from: https://github.com/hypervillain/ast-to-literal
* and converted to TypeScript.
* Thanks to the author [Hugo Villain](https://github.com/hypervillain)
*/
import * as t from '@babel/types';

const primitiveTypes = ['BooleanLiteral', 'StringLiteral', 'NumericLiteral'];

export function toJS(node: t.Expression): any {
function computeProps(props: t.ObjectExpression['properties']) {
return (props as any[]).reduce((acc, prop) => {
if (prop.type === 'SpreadElement') {
return {
...acc,
...toJS(prop.argument),
};
}

if (prop.type !== 'ObjectMethod') {
const val = toJS(prop.value);
if (val !== undefined) {
return {
...acc,
[prop.key.name || prop.key.value]: val,
};
}
}

return acc;
}, {});
}

if (primitiveTypes.includes(node.type)) {
// @ts-expect-error
return node.value;
}

// @ts-expect-error
if (node.name === 'undefined' && !node.value) {
return undefined;
}

if (t.isNullLiteral(node)) {
return null;
}

if (t.isObjectExpression(node)) {
return computeProps(node.properties);
}

if (t.isArrayExpression(node)) {
return node.elements.reduce((acc, element) => {
if (!element) {
return acc;
}

return [
...acc,
...(element.type === 'SpreadElement'
? toJS(element.argument)
: [toJS(element)]),
];
}, [] as t.ArrayExpression[]);
}
}
35 changes: 35 additions & 0 deletions packages/babel-plugin/src/types.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
export type MorfeoCompilerOptions = {
/**
* A list of paths that links to where the themes are placed
* Available extensions for the themes are: `ts`, `js` and `json`
*
* @example
* {
* "themePaths": ["./src/themes/light.ts", "./src/themes/dark.ts"]
* }
*/
themePaths: string[];
/**
* The directory where the compiler will output the extracted css
*
* For example:
* ```json
* {
* "themePaths": ["./src/themes/light.ts", "./src/themes/dark.ts"]
* "outDir": "./build/css",
* }
* ```
*
* Will produce inside the folder `build/css` the following files
*
* ```console
* build/
* └── css/
* ├── dark.css
* └── light.css
* ```
*
* > Note that the names of the extracted css files could be different.
*/
outDir: string;
};
87 changes: 87 additions & 0 deletions packages/babel-plugin/src/visitor.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,87 @@
import type { NodePath, Visitor } from '@babel/traverse';
import type { CallExpression } from '@babel/types';
import { getStyles } from '@morfeo/jss';
import { toJS } from './toJS';

function isMorfeoParse(path: NodePath<CallExpression>) {
const { callee } = path.node;

return (
// @ts-expect-error
callee.object?.name === 'morfeo' &&
// @ts-expect-error
callee.property.name === 'parse'
);
}

export default function getVisitor(): Visitor {
return {
ImportDeclaration(path) {
const imported = path.get('specifiers');

if (imported.length !== 1 || !imported[0].isImportSpecifier()) {
return;
}

const binding = path.scope.getBinding('morfeo');

if (!binding) {
return;
}

const { references, referencePaths } = binding;

if (references !== 1) {
return;
}

referencePaths.forEach(reference => {
if (
reference.parentPath &&
reference.parentPath.isMemberExpression() &&
reference.parentPath.get('property').isIdentifier({
name: 'parse',
}) &&
reference.parentPath.get('object').isIdentifier({ name: 'morfeo' })
) {
path.remove();
}
});
},
CallExpression: {
enter(callExpressionPath, state: any) {
if (!isMorfeoParse(callExpressionPath)) {
return;
}

callExpressionPath.traverse({
ObjectExpression(path) {
// It should stop at the parent object
path.stop();
const classesStyleObject = toJS(path.node);

const classNames = Object.keys(classesStyleObject);

const { classes, sheet } = getStyles(classesStyleObject);

const classesObject = classNames.reduce(
(acc, curr) => `${acc}\n${curr}: "${classes[curr]}",`,
'',
);

const newCode = `() => ({
${classesObject}
})`;

if (!state.file.metadata.morfeo) {
state.file.metadata.morfeo = '';
}
state.file.metadata.morfeo += sheet.toString();

callExpressionPath.replaceWithSourceString(newCode);
},
});
},
},
};
}
Loading

0 comments on commit f62c3a1

Please sign in to comment.