Skip to content

Commit

Permalink
feat(core): add basic transform function that apply @apply directive
Browse files Browse the repository at this point in the history
  • Loading branch information
TomokiMiyauci committed Mar 30, 2022
1 parent 45e5918 commit 669641e
Show file tree
Hide file tree
Showing 2 changed files with 50 additions and 0 deletions.
1 change: 1 addition & 0 deletions core/mod.ts
Expand Up @@ -11,3 +11,4 @@ export * from "./extract.ts";
export * from "./resolve.ts";
export * from "./types.ts";
export * from "./ast.ts";
export * from "./transform.ts";
49 changes: 49 additions & 0 deletions core/transform.ts
@@ -0,0 +1,49 @@
// This module is browser compatible.

import { postcss, Root } from "./deps.ts";
import { generate, Output } from "./generate.ts";
import type { StaticConfig, StaticContext } from "./types.ts";

// TODO(miyauci): define generic config types
type Config = Partial<StaticConfig & StaticContext>;

export function transform(input: string, config: Readonly<Config>) {
const ast = postcss().process(input).root;

return applyDirective(ast.clone(), (input) => {
return generate(input.split(" "), config);
});
}

export function applyDirective(
ast: Root,
map: (input: string) => Output,
): Output {
let matched = new Set<string>();
let unmatched = new Set<string>();
ast.walkAtRules("apply", (root) => {
const { ast, matched: _matched, unmatched: _unmatched } = map(root.params);
matched = _matched;
unmatched = _unmatched;

if (root.parent?.type === "rule") {
const visit = new Root();
ast.walkDecls((decl) => {
visit.append(decl);
});

root.parent?.append(visit);
}

root.remove();
});

return {
ast,
get css(): string {
return ast.toString();
},
matched,
unmatched,
};
}

0 comments on commit 669641e

Please sign in to comment.