summaryrefslogtreecommitdiff
path: root/src/optimize/styles.ts
diff options
context:
space:
mode:
authorGravatar Matthew Phillips <matthew@matthewphillips.info> 2021-03-18 16:39:17 -0400
committerGravatar GitHub <noreply@github.com> 2021-03-18 16:39:17 -0400
commitd27bd74b055b23a6eb455969755b3ee7f687fd61 (patch)
tree2905ac29ca5bc1f9337799b08182d2daa9f086ae /src/optimize/styles.ts
parent5661b289149761106585abe7695f3ccc2a7a4045 (diff)
downloadastro-d27bd74b055b23a6eb455969755b3ee7f687fd61.tar.gz
astro-d27bd74b055b23a6eb455969755b3ee7f687fd61.tar.zst
astro-d27bd74b055b23a6eb455969755b3ee7f687fd61.zip
Refactor to enable optimizer modules (#8)
* Refactor to enable optimizer modules This refactors HMX compilation into steps: 1. Parse - Turn HMX string into an AST. 2. Optimize - Walk the AST making modifications. 3. Codegen - Turn the AST into hyperscript function calls. There's still more logic in (3) than we probably want. The nice there here is it gives a Visitor API that you can implement to do optimizations. See src/optimize/styles.ts for an example. * Allow multiple visitors per optimizer
Diffstat (limited to 'src/optimize/styles.ts')
-rw-r--r--src/optimize/styles.ts51
1 files changed, 51 insertions, 0 deletions
diff --git a/src/optimize/styles.ts b/src/optimize/styles.ts
new file mode 100644
index 000000000..b654ca7d1
--- /dev/null
+++ b/src/optimize/styles.ts
@@ -0,0 +1,51 @@
+import type { Ast, TemplateNode } from '../compiler/interfaces';
+import type { Optimizer } from './types'
+import { transformStyle } from '../style.js';
+
+export default function({ filename, fileID }: { filename: string, fileID: string }): Optimizer {
+ const classNames: Set<string> = new Set();
+ let stylesPromises: any[] = [];
+
+ return {
+ visitors: {
+ html: {
+ Element: {
+ enter(node) {
+ for(let attr of node.attributes) {
+ if(attr.name === 'class') {
+ for(let value of attr.value) {
+ if(value.type === 'Text') {
+ const classes = value.data.split(' ');
+ for(const className in classes) {
+ classNames.add(className);
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+ },
+ css: {
+ Style: {
+ enter(node: TemplateNode) {
+ const code = node.content.styles;
+ const typeAttr = node.attributes && node.attributes.find(({ name }: { name: string }) => name === 'type');
+ stylesPromises.push(
+ transformStyle(code, {
+ type: (typeAttr.value[0] && typeAttr.value[0].raw) || undefined,
+ classNames,
+ filename,
+ fileID,
+ })
+ ); // TODO: styles needs to go in <head>
+ }
+ }
+ }
+ },
+ async finalize() {
+ const styles = await Promise.all(stylesPromises); // TODO: clean this up
+ console.log({ styles });
+ }
+ };
+} \ No newline at end of file