Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
feat(core): add basic transform function that apply
@apply
directive
- Loading branch information
1 parent
45e5918
commit 669641e
Showing
2 changed files
with
50 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -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, | ||
}; | ||
} |