├── .github
└── workflows
│ └── node.js.yml
├── .gitignore
├── CODE_OF_CONDUCT.md
├── CONTRIBUTING.md
├── LICENSE
├── README.md
├── index.d.ts
├── index.js
├── index.test.js
├── package-lock.json
├── package.json
├── props.test.css
└── props.test.empty.css
/.github/workflows/node.js.yml:
--------------------------------------------------------------------------------
1 | name: Unit Tests
2 | on: [push, pull_request]
3 |
4 | jobs:
5 | build:
6 | runs-on: ubuntu-latest
7 | strategy:
8 | matrix:
9 | node-version: [14.x]
10 | steps:
11 | - uses: actions/checkout@v2
12 | - name: Use Node.js ${{ matrix.node-version }}
13 | uses: actions/setup-node@v2
14 | with:
15 | node-version: ${{ matrix.node-version }}
16 | cache: 'npm'
17 | - run: npm ci
18 | - run: npm test
19 |
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | coverage/
2 | node_modules/
3 | .DS_Store
--------------------------------------------------------------------------------
/CODE_OF_CONDUCT.md:
--------------------------------------------------------------------------------
1 | # Contributor Covenant Code of Conduct
2 |
3 | ## Our Pledge
4 |
5 | In the interest of fostering an open and welcoming environment, we as contributors and maintainers pledge to making participation in our project and our community a harassment-free experience for everyone, regardless of age, body size, disability, ethnicity, sex characteristics, gender identity and expression, level of experience, education, socio-economic status, nationality, personal appearance, race, religion, or sexual identity and orientation.
6 |
7 | ## Our Standards
8 |
9 | Examples of behavior that contributes to creating a positive environment include:
10 |
11 | - Using welcoming and inclusive language
12 | - Being respectful of differing viewpoints and experiences
13 | - Gracefully accepting constructive criticism
14 | - Focusing on what is best for the community
15 | - Showing empathy towards other community members
16 |
17 | Examples of unacceptable behavior by participants include:
18 |
19 | - The use of sexualized language or imagery and unwelcome sexual attention or advances
20 | - Trolling, insulting/derogatory comments, and personal or political attacks
21 | - Public or private harassment
22 | - Publishing others' private information, such as a physical or electronic address, without explicit permission
23 | - Other conduct which could reasonably be considered inappropriate in a professional setting
24 |
25 | ## Our Responsibilities
26 |
27 | Project maintainers are responsible for clarifying the standards of acceptable behavior and are expected to take appropriate and fair corrective action in response to any instances of unacceptable behavior.
28 |
29 | Project maintainers have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct, or to ban temporarily or permanently any contributor for other behaviors that they deem inappropriate, threatening, offensive, or harmful.
30 |
31 | ## Scope
32 |
33 | This Code of Conduct applies both within project spaces and in public spaces when an individual is representing the project or its community. Examples of representing a project or community include using an official project e-mail address, posting via an official social media account, or acting as an appointed representative at an online or offline event. Representation of a project may be further defined and clarified by project maintainers.
34 |
35 | ## Enforcement
36 |
37 | Instances of abusive, harassing, or otherwise unacceptable behavior may be reported by contacting the project team. All complaints will be reviewed and investigated and will result in a response that is deemed necessary and appropriate to the circumstances. The project team is obligated to maintain confidentiality with regard to the reporter of an incident. Further details of specific enforcement policies may be posted separately.
38 |
39 | Project maintainers who do not follow or enforce the Code of Conduct in good faith may face temporary or permanent repercussions as determined by other members of the project's leadership.
40 |
41 | ## Attribution
42 |
43 | This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4, available at https://www.contributor-covenant.org/version/1/4/code-of-conduct.html
44 |
45 | [homepage]: https://www.contributor-covenant.org
46 |
47 | For answers to common questions about this code of conduct, see https://www.contributor-covenant.org/faq
48 |
--------------------------------------------------------------------------------
/CONTRIBUTING.md:
--------------------------------------------------------------------------------
1 | Want to contribute? Great! First, read this page (including the small print at the end).
2 |
3 | ### Before you contribute
4 | Before we can use your code, you must sign the
5 | [Google Individual Contributor License Agreement]
6 | (https://cla.developers.google.com/about/google-individual)
7 | (CLA), which you can do online. The CLA is necessary mainly because you own the
8 | copyright to your changes, even after your contribution becomes part of our
9 | codebase, so we need your permission to use and distribute your code. We also
10 | need to be sure of various other things—for instance that you'll tell us if you
11 | know that your code infringes on other people's patents. You don't have to sign
12 | the CLA until after you've submitted your code for review and a member has
13 | approved it, but you must do it before we can put your code into our codebase.
14 | Before you start working on a larger contribution, you should get in touch with
15 | us first through the issue tracker with your idea so that we can help out and
16 | possibly guide you. Coordinating up front makes it much easier to avoid
17 | frustration later on.
18 |
19 | ### Code reviews
20 | All submissions, including submissions by project members, require review. We
21 | use Github pull requests for this purpose.
22 |
23 | ### The small print
24 | Contributions made by corporations are covered by a different agreement than
25 | the one above, the
26 | [Software Grant and Corporate Contributor License Agreement]
27 | (https://cla.developers.google.com/about/google-corporate).
28 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 |
2 | Apache License
3 | Version 2.0, January 2004
4 | http://www.apache.org/licenses/
5 |
6 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7 |
8 | 1. Definitions.
9 |
10 | "License" shall mean the terms and conditions for use, reproduction,
11 | and distribution as defined by Sections 1 through 9 of this document.
12 |
13 | "Licensor" shall mean the copyright owner or entity authorized by
14 | the copyright owner that is granting the License.
15 |
16 | "Legal Entity" shall mean the union of the acting entity and all
17 | other entities that control, are controlled by, or are under common
18 | control with that entity. For the purposes of this definition,
19 | "control" means (i) the power, direct or indirect, to cause the
20 | direction or management of such entity, whether by contract or
21 | otherwise, or (ii) ownership of fifty percent (50%) or more of the
22 | outstanding shares, or (iii) beneficial ownership of such entity.
23 |
24 | "You" (or "Your") shall mean an individual or Legal Entity
25 | exercising permissions granted by this License.
26 |
27 | "Source" form shall mean the preferred form for making modifications,
28 | including but not limited to software source code, documentation
29 | source, and configuration files.
30 |
31 | "Object" form shall mean any form resulting from mechanical
32 | transformation or translation of a Source form, including but
33 | not limited to compiled object code, generated documentation,
34 | and conversions to other media types.
35 |
36 | "Work" shall mean the work of authorship, whether in Source or
37 | Object form, made available under the License, as indicated by a
38 | copyright notice that is included in or attached to the work
39 | (an example is provided in the Appendix below).
40 |
41 | "Derivative Works" shall mean any work, whether in Source or Object
42 | form, that is based on (or derived from) the Work and for which the
43 | editorial revisions, annotations, elaborations, or other modifications
44 | represent, as a whole, an original work of authorship. For the purposes
45 | of this License, Derivative Works shall not include works that remain
46 | separable from, or merely link (or bind by name) to the interfaces of,
47 | the Work and Derivative Works thereof.
48 |
49 | "Contribution" shall mean any work of authorship, including
50 | the original version of the Work and any modifications or additions
51 | to that Work or Derivative Works thereof, that is intentionally
52 | submitted to Licensor for inclusion in the Work by the copyright owner
53 | or by an individual or Legal Entity authorized to submit on behalf of
54 | the copyright owner. For the purposes of this definition, "submitted"
55 | means any form of electronic, verbal, or written communication sent
56 | to the Licensor or its representatives, including but not limited to
57 | communication on electronic mailing lists, source code control systems,
58 | and issue tracking systems that are managed by, or on behalf of, the
59 | Licensor for the purpose of discussing and improving the Work, but
60 | excluding communication that is conspicuously marked or otherwise
61 | designated in writing by the copyright owner as "Not a Contribution."
62 |
63 | "Contributor" shall mean Licensor and any individual or Legal Entity
64 | on behalf of whom a Contribution has been received by Licensor and
65 | subsequently incorporated within the Work.
66 |
67 | 2. Grant of Copyright License. Subject to the terms and conditions of
68 | this License, each Contributor hereby grants to You a perpetual,
69 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70 | copyright license to reproduce, prepare Derivative Works of,
71 | publicly display, publicly perform, sublicense, and distribute the
72 | Work and such Derivative Works in Source or Object form.
73 |
74 | 3. Grant of Patent License. Subject to the terms and conditions of
75 | this License, each Contributor hereby grants to You a perpetual,
76 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77 | (except as stated in this section) patent license to make, have made,
78 | use, offer to sell, sell, import, and otherwise transfer the Work,
79 | where such license applies only to those patent claims licensable
80 | by such Contributor that are necessarily infringed by their
81 | Contribution(s) alone or by combination of their Contribution(s)
82 | with the Work to which such Contribution(s) was submitted. If You
83 | institute patent litigation against any entity (including a
84 | cross-claim or counterclaim in a lawsuit) alleging that the Work
85 | or a Contribution incorporated within the Work constitutes direct
86 | or contributory patent infringement, then any patent licenses
87 | granted to You under this License for that Work shall terminate
88 | as of the date such litigation is filed.
89 |
90 | 4. Redistribution. You may reproduce and distribute copies of the
91 | Work or Derivative Works thereof in any medium, with or without
92 | modifications, and in Source or Object form, provided that You
93 | meet the following conditions:
94 |
95 | (a) You must give any other recipients of the Work or
96 | Derivative Works a copy of this License; and
97 |
98 | (b) You must cause any modified files to carry prominent notices
99 | stating that You changed the files; and
100 |
101 | (c) You must retain, in the Source form of any Derivative Works
102 | that You distribute, all copyright, patent, trademark, and
103 | attribution notices from the Source form of the Work,
104 | excluding those notices that do not pertain to any part of
105 | the Derivative Works; and
106 |
107 | (d) If the Work includes a "NOTICE" text file as part of its
108 | distribution, then any Derivative Works that You distribute must
109 | include a readable copy of the attribution notices contained
110 | within such NOTICE file, excluding those notices that do not
111 | pertain to any part of the Derivative Works, in at least one
112 | of the following places: within a NOTICE text file distributed
113 | as part of the Derivative Works; within the Source form or
114 | documentation, if provided along with the Derivative Works; or,
115 | within a display generated by the Derivative Works, if and
116 | wherever such third-party notices normally appear. The contents
117 | of the NOTICE file are for informational purposes only and
118 | do not modify the License. You may add Your own attribution
119 | notices within Derivative Works that You distribute, alongside
120 | or as an addendum to the NOTICE text from the Work, provided
121 | that such additional attribution notices cannot be construed
122 | as modifying the License.
123 |
124 | You may add Your own copyright statement to Your modifications and
125 | may provide additional or different license terms and conditions
126 | for use, reproduction, or distribution of Your modifications, or
127 | for any such Derivative Works as a whole, provided Your use,
128 | reproduction, and distribution of the Work otherwise complies with
129 | the conditions stated in this License.
130 |
131 | 5. Submission of Contributions. Unless You explicitly state otherwise,
132 | any Contribution intentionally submitted for inclusion in the Work
133 | by You to the Licensor shall be under the terms and conditions of
134 | this License, without any additional terms or conditions.
135 | Notwithstanding the above, nothing herein shall supersede or modify
136 | the terms of any separate license agreement you may have executed
137 | with Licensor regarding such Contributions.
138 |
139 | 6. Trademarks. This License does not grant permission to use the trade
140 | names, trademarks, service marks, or product names of the Licensor,
141 | except as required for reasonable and customary use in describing the
142 | origin of the Work and reproducing the content of the NOTICE file.
143 |
144 | 7. Disclaimer of Warranty. Unless required by applicable law or
145 | agreed to in writing, Licensor provides the Work (and each
146 | Contributor provides its Contributions) on an "AS IS" BASIS,
147 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148 | implied, including, without limitation, any warranties or conditions
149 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150 | PARTICULAR PURPOSE. You are solely responsible for determining the
151 | appropriateness of using or redistributing the Work and assume any
152 | risks associated with Your exercise of permissions under this License.
153 |
154 | 8. Limitation of Liability. In no event and under no legal theory,
155 | whether in tort (including negligence), contract, or otherwise,
156 | unless required by applicable law (such as deliberate and grossly
157 | negligent acts) or agreed to in writing, shall any Contributor be
158 | liable to You for damages, including any direct, indirect, special,
159 | incidental, or consequential damages of any character arising as a
160 | result of this License or out of the use or inability to use the
161 | Work (including but not limited to damages for loss of goodwill,
162 | work stoppage, computer failure or malfunction, or any and all
163 | other commercial damages or losses), even if such Contributor
164 | has been advised of the possibility of such damages.
165 |
166 | 9. Accepting Warranty or Additional Liability. While redistributing
167 | the Work or Derivative Works thereof, You may choose to offer,
168 | and charge a fee for, acceptance of support, warranty, indemnity,
169 | or other liability obligations and/or rights consistent with this
170 | License. However, in accepting such obligations, You may act only
171 | on Your own behalf and on Your sole responsibility, not on behalf
172 | of any other Contributor, and only if You agree to indemnify,
173 | defend, and hold each Contributor harmless for any liability
174 | incurred by, or claims asserted against, such Contributor by reason
175 | of your accepting any such warranty or additional liability.
176 |
177 | END OF TERMS AND CONDITIONS
178 |
179 | APPENDIX: How to apply the Apache License to your work.
180 |
181 | To apply the Apache License to your work, attach the following
182 | boilerplate notice, with the fields enclosed by brackets "[]"
183 | replaced with your own identifying information. (Don't include
184 | the brackets!) The text should be enclosed in the appropriate
185 | comment syntax for the file format. We also recommend that a
186 | file or class name and description of purpose be included on the
187 | same "printed page" as the copyright notice for easier
188 | identification within third-party archives.
189 |
190 | Copyright [yyyy] [name of copyright owner]
191 |
192 | Licensed under the Apache License, Version 2.0 (the "License");
193 | you may not use this file except in compliance with the License.
194 | You may obtain a copy of the License at
195 |
196 | http://www.apache.org/licenses/LICENSE-2.0
197 |
198 | Unless required by applicable law or agreed to in writing, software
199 | distributed under the License is distributed on an "AS IS" BASIS,
200 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201 | See the License for the specific language governing permissions and
202 | limitations under the License.
203 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # PostCSS (Just In Time) Props
2 |
3 | > Only ship used variables! A CSS custom property helper based on PostCSS
4 |
5 | [](https://www.npmjs.com/package/postcss-jit-props)
6 | [](https://postcss.org/)
7 | [](https://github.com/GoogleChromeLabs/postcss-jit-props/actions/workflows/node.js.yml)
8 |
9 |
10 |
11 | `postcss-jit-props` watches for CSS variables and ensures a value entry exists in the stylesheet. [Try in browser](https://stackblitz.com/edit/jit-open-props?file=postcss.config.js)
12 |
13 | This lets you **provide a huge pool of properties** for development and design, and rather than try and purge unused variables, **only adds what was used**.
14 |
15 |
16 |
17 | ## Example
18 |
19 | CSS Before / During Development:
20 | ```css
21 | .foo {
22 | color: var(--brand-1);
23 | padding: var(--size-1) var(--size-2);
24 | margin-block-start: var(--size-2);
25 | animation: var(--fade-in);
26 | }
27 |
28 | @media (--dark) {
29 | .foo {
30 | color: white;
31 | }
32 | }
33 | ```
34 |
35 | CSS After / Result of Plugin:
36 | ```diff
37 | + @custom-media --dark (prefers-color-scheme: dark);
38 |
39 | + :root {
40 | + --brand-1: #81A1C1;
41 | + --size-1: 1rem;
42 | + --size-2: 2rem;
43 | + --fade-in: fade-in .5s ease;
44 | + }
45 |
46 | .foo {
47 | color: var(--brand-1);
48 | padding: var(--size-1) var(--size-2);
49 | margin-block-start: var(--size-2);
50 | animation: var(--fade-in);
51 | }
52 |
53 | @media (--dark) {
54 | .foo {
55 | color: white;
56 | }
57 | }
58 |
59 | + @keyframes fade-in {
60 | + to { opacity: 1; }
61 | + }
62 | ```
63 |
64 |
65 |
66 | ## Usage
67 |
68 | **Step 1:** Install plugin:
69 |
70 | ```sh
71 | npm install --save-dev postcss-jit-props
72 | ```
73 |
74 |
75 |
76 | **Step 2:** Add the plugin to plugins in `postcss.config.js` and **pass it your props (CSS || JS || JSON)**.
77 |
78 | Pass JS objects:
79 | ```js
80 | module.exports = {
81 | plugins: [
82 | require('postcss-jit-props')({
83 | '--brand-1': '#81A1C1',
84 | '--size-1': '1rem',
85 | '--size-2': '2rem',
86 | '--fade-in': 'fade-in .5s ease',
87 | '--fade-in-@': '@keyframes fade-in {to { opacity: 1 }}',
88 | '--dark': '@custom-media --dark (prefers-color-scheme: dark);',
89 | '--text': 'white',
90 | '--text-@media:dark': 'black',
91 | }),
92 | require('autoprefixer'),
93 | ]
94 | }
95 | ```
96 |
97 | or pass CSS files
98 |
99 | ```js
100 | module.exports = {
101 | plugins: [
102 | require('postcss-jit-props')({files: ['./props.css']}),
103 | require('autoprefixer'),
104 | ]
105 | }
106 | ```
107 |
108 | or JSON ✨
109 |
110 | > Javascript and JSON must use the `-@` suffix on their custom property name in order for jit-props to find associated `@keyframes`
111 |
112 | Configure where the selector the props are pushed to. Some CSS Module environments, for example, don't want the props in `:root`, so we can configure the plugin to push them where it's acceptable for the environment, like `:global`:
113 |
114 | ```js
115 | module.exports = {
116 | plugins: [
117 | require('postcss-jit-props')({
118 | ...MyProps,
119 | custom_selector: ':global'
120 | }),
121 | require('autoprefixer'),
122 | ]
123 | }
124 | ```
125 |
126 | Configure the `@layer` the props are pushed to. :
127 |
128 | ```js
129 | module.exports = {
130 | plugins: [
131 | require('postcss-jit-props')({
132 | ...MyProps,
133 | layer: 'design.system'
134 | }),
135 | require('autoprefixer'),
136 | ]
137 | }
138 | ```
139 |
--------------------------------------------------------------------------------
/index.d.ts:
--------------------------------------------------------------------------------
1 | import { PluginCreator } from "postcss";
2 |
3 | export interface Options {
4 | /**
5 | * Wraps the entire rule inside `@layer` syntax.
6 | */
7 | layer?: string;
8 |
9 | /**
10 | * Where to search for css props, globbing allowed.
11 | */
12 | files?: string[];
13 |
14 | /**
15 | * Selector where the props are pushed to instead of `:root`.
16 | */
17 | custom_selector?: string;
18 | }
19 |
20 | type Props = Record;
21 |
22 | export type PostcssJitPropsOptions = Options & Props;
23 | declare const postcssJitProps: PluginCreator;
24 |
25 | export default postcssJitProps;
26 |
--------------------------------------------------------------------------------
/index.js:
--------------------------------------------------------------------------------
1 | /**
2 | * Copyright 2020 Google Inc. All Rights Reserved.
3 | * Licensed under the Apache License, Version 2.0 (the "License");
4 | * you may not use this file except in compliance with the License.
5 | * You may obtain a copy of the License at
6 | * http://www.apache.org/licenses/LICENSE-2.0
7 | * Unless required by applicable law or agreed to in writing, software
8 | * distributed under the License is distributed on an "AS IS" BASIS,
9 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
10 | * See the License for the specific language governing permissions and
11 | * limitations under the License.
12 | */
13 |
14 | const fs = require('fs');
15 | const crypto = require('crypto');
16 |
17 | const glob = require('tiny-glob/sync');
18 |
19 | const processed = new WeakSet();
20 |
21 | const getAdaptivePropSelector = (selector) => {
22 | return (prop) => {
23 | if (!selector) {
24 | return `${prop}-@media:dark`
25 | }
26 |
27 | return `${prop}${selector}`
28 | }
29 | }
30 |
31 | /** @type { import('postcss').PluginCreator }*/
32 | module.exports = (options) => {
33 | const {
34 | files,
35 | adaptive_prop_selector,
36 | custom_selector,
37 | custom_selector_dark,
38 | layer, ...props
39 | } = options
40 |
41 | const FilePropsCache = new Map();
42 |
43 | return {
44 | postcssPlugin: 'postcss-jit-props',
45 | prepare() {
46 | const UserProps = { ...props }
47 |
48 | const STATE = {
49 | mapped: null, // track prepended props
50 | mapped_dark: null, // track dark mode prepended props
51 |
52 | target_layer: null, // layer for props
53 | target_rule: null, // :root for props
54 | target_rule_dark: null, // :root for dark props
55 | target_ss: null, // stylesheet for keyframes/MQs
56 | target_media_dark: null, // dark media query props
57 | }
58 |
59 | const adaptivePropSelector = getAdaptivePropSelector(adaptive_prop_selector)
60 |
61 | return {
62 | Once(node, { parse, result, Rule, AtRule }) {
63 | let target_selector = custom_selector || ':root'
64 | let target_selector_dark = custom_selector_dark || custom_selector || ':root'
65 |
66 | if (!files && !Object.keys(props).length) {
67 | return console.warn('postcss-jit-props: Variable source(s) not passed.')
68 | }
69 |
70 | if (files?.length) {
71 |
72 | const globs = files
73 | .map((file) => glob(file))
74 | .reduce((flattenedFileList, files) => flattenedFileList.concat(files), [])
75 |
76 | globs.map(file => {
77 | result.messages.push({
78 | type: 'dependency',
79 | plugin: 'postcss-jit-props',
80 | file: file,
81 | parent: node.source?.input?.file,
82 | });
83 |
84 | let data = fs.readFileSync(file, 'utf8')
85 |
86 | const hashSum = crypto.createHash('sha256')
87 | hashSum.update(file)
88 | hashSum.update(data)
89 | const fileCacheKey = hashSum.digest('hex')
90 |
91 | if (FilePropsCache.has(fileCacheKey)) {
92 | const fileProps = FilePropsCache.get(fileCacheKey)
93 | for (const [key, value] of fileProps) {
94 | UserProps[key] = value
95 | }
96 |
97 | return
98 | }
99 |
100 | const fileProps = new Map()
101 | FilePropsCache.set(fileCacheKey, fileProps)
102 |
103 | let dependencyResult = parse(data, { from: file })
104 |
105 | dependencyResult.walkDecls(decl => {
106 | if (!decl.variable) return
107 | UserProps[decl.prop] = decl.value
108 | fileProps.set(decl.prop, decl.value)
109 | })
110 |
111 | dependencyResult.walkAtRules(atrule => {
112 | if (atrule.name === 'custom-media') {
113 | let media = atrule.params.slice(0, atrule.params.indexOf(' '))
114 | UserProps[media] = `@custom-media ${atrule.params};`
115 | fileProps.set(media, `@custom-media ${atrule.params};`)
116 | }
117 | else if (atrule.name === 'keyframes') {
118 | let keyframeName = `--${atrule.params}-@`
119 | let keyframes = atrule.source.input.css.slice(atrule.source.start.offset, atrule.source.end.offset + 1)
120 | UserProps[keyframeName] = keyframes
121 | fileProps.set(keyframeName, keyframes)
122 | }
123 | })
124 | })
125 | }
126 |
127 | STATE.mapped = new Set()
128 | STATE.mapped_dark = new Set()
129 |
130 | if (node.first) {
131 | STATE.target_rule = new Rule({ selector: target_selector, source: node.first.source })
132 | STATE.target_rule_dark = new Rule({ selector: target_selector_dark, source: node.first.source })
133 | STATE.target_media_dark = new AtRule({ name: 'media', params: '(prefers-color-scheme: dark)', source: node.first.source })
134 | }
135 |
136 | if (layer && node.first) {
137 | STATE.target_layer = new AtRule({ name: 'layer', params: layer, source: node.first.source })
138 | node.root().prepend(STATE.target_layer)
139 | STATE.target_ss = STATE.target_layer
140 | }
141 | else
142 | STATE.target_ss = node.root()
143 | },
144 |
145 | AtRule: {
146 | media: (atrule, { parse }) => {
147 | // bail early if possible
148 | if (processed.has(atrule)) return
149 |
150 | // extract prop from atrule params
151 | let prop = atrule.params.replace(/[( )]+/g, '');
152 |
153 | // bail if media prop already prepended
154 | if (STATE.mapped.has(prop)) return
155 |
156 | // create :root {} context just in time
157 | if (STATE.mapped.size === 0)
158 | STATE.target_ss.prepend(STATE.target_rule)
159 |
160 | // lookup prop value from pool
161 | let value = UserProps[prop] || null
162 |
163 | // warn if media prop not resolved
164 | if (!value) {
165 | return
166 | }
167 |
168 | // prepend the custom media
169 | const customMedia = parse(value).first
170 | customMedia.source = atrule.source
171 | STATE.target_ss.prepend(customMedia)
172 |
173 | // track work to prevent duplication
174 | processed.add(atrule)
175 | STATE.mapped.add(prop)
176 | }
177 | },
178 |
179 | Declaration(node, { Declaration, parse }) {
180 | // bail early
181 | if (processed.has(node) || !node.value) return
182 | // console.log(node)
183 | let matches = node.value.match(/var\(\s*(--[\w\d-_]+)/g)
184 |
185 | if (!matches) return
186 |
187 | // create :root {} context just in time
188 | if (STATE.mapped.size === 0)
189 | STATE.target_ss.prepend(STATE.target_rule)
190 |
191 | let props = matches.map(v => v.replace('var(', '').trim())
192 |
193 | for (let prop of props) {
194 | // bail prepending this prop if it's already been done
195 | if (STATE.mapped.has(prop)) continue
196 |
197 | // lookup prop from options object
198 | let value = UserProps[prop] || null
199 |
200 | // warn if props won't resolve from plugin
201 | if (!value) {
202 | continue
203 | }
204 |
205 | // create and append prop to :root
206 | let decl = new Declaration({ prop, value, source: node.source })
207 | STATE.target_rule.append(decl)
208 | STATE.mapped.add(prop)
209 |
210 | // lookup keyframes for the prop and append if found
211 | let keyframes = UserProps[`${prop}-@`]
212 | if (keyframes) {
213 | const keyframesNode = parse(keyframes).first
214 | keyframesNode.source = node.source
215 | keyframesNode.walk((x) => x.source = node.source)
216 | STATE.target_ss.append(keyframesNode)
217 | }
218 |
219 | // lookup dark adaptive prop and append if found
220 | let adaptive = UserProps[adaptivePropSelector(prop)]
221 | if (adaptive && !STATE.mapped_dark.has(prop)) {
222 | // create @media ... { :root {} } context just in time
223 | if (STATE.mapped_dark.size === 0) {
224 | STATE.target_media_dark.append(STATE.target_rule_dark)
225 | STATE.target_ss.append(STATE.target_media_dark)
226 | }
227 |
228 | if (adaptive.includes('@keyframes')) {
229 | const adaptiveNode = parse(adaptive).first
230 | adaptiveNode.source = node.source
231 | adaptiveNode.walk((x) => x.source = node.source)
232 | STATE.target_media_dark.append(adaptiveNode)
233 | }
234 | else {
235 | // append adaptive prop definition to dark media query
236 | let darkdecl = new Declaration({ prop, value: adaptive, source: node.source })
237 | STATE.target_rule_dark.append(darkdecl)
238 | STATE.mapped_dark.add(prop)
239 | }
240 | }
241 |
242 | // track work to prevent duplicative processing
243 | processed.add(node)
244 | }
245 | }
246 | }
247 | }
248 | }
249 | }
250 |
251 | module.exports.postcss = true
252 |
--------------------------------------------------------------------------------
/index.test.js:
--------------------------------------------------------------------------------
1 | /**
2 | * Copyright 2020 Google Inc. All Rights Reserved.
3 | * Licensed under the Apache License, Version 2.0 (the "License");
4 | * you may not use this file except in compliance with the License.
5 | * You may obtain a copy of the License at
6 | * http://www.apache.org/licenses/LICENSE-2.0
7 | * Unless required by applicable law or agreed to in writing, software
8 | * distributed under the License is distributed on an "AS IS" BASIS,
9 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
10 | * See the License for the specific language governing permissions and
11 | * limitations under the License.
12 | */
13 |
14 | const postcss = require('postcss')
15 | const plugin = require('./')
16 |
17 | const MockProps = {
18 | '--red': '#f00',
19 | '--pink': '#ffc0cb',
20 | '--h': 200,
21 | '--s': '50%',
22 | '--l': '50%',
23 | '--size-1': '1rem',
24 | '--size-2': '2rem',
25 | '--fade-in': 'fade-in .5s ease',
26 | '--fade-in-@': '@keyframes fade-in {to { opacity: 1 }}',
27 | '--adaptive-fade': 'adaptive-fade .5s ease',
28 | '--adaptive-fade-@': '@keyframes adaptive-fade {to { background: white }}',
29 | '--adaptive-fade-@media:dark': '@keyframes adaptive-fade {to { background: black }}',
30 | '--dark': '@custom-media --dark (prefers-color-scheme: dark);',
31 | '--text': 'white',
32 | '--text-@media:dark': 'black',
33 | }
34 |
35 | const MockPropsWithCustomAdaptiveProp = {
36 | '--text': 'white',
37 | '--text-dark': 'black',
38 | }
39 |
40 | async function run (input, output, options = { }) {
41 | let result = await postcss([plugin(options)]).process(input, { from: 'input.css', to: 'output.css', map: { inline: false } })
42 | expect(result.css.replace('\n/*# sourceMappingURL=output.css.map */', '')).toEqual(output)
43 | expect(result.warnings()).toHaveLength(0)
44 |
45 | if (options.files?.length) {
46 | expect(result.messages.filter(x => x.type === 'dependency')).toHaveLength(options.files?.length)
47 | }
48 |
49 | const map = result.map.toJSON()
50 | expect(map.sources).toEqual(['input.css'])
51 | }
52 |
53 | it('Can jit a single prop', async () => {
54 | await run(
55 | `a {
56 | color: var(--red);
57 | }`,
58 | `:root {
59 | --red: #f00;
60 | }
61 | a {
62 | color: var(--red);
63 | }`,
64 | MockProps
65 | )
66 | })
67 |
68 | it('Can jit a single prop with spaces', async () => {
69 | await run(
70 | `a {
71 | color: var( --red );
72 | }`,
73 | `:root {
74 | --red: #f00;
75 | }
76 | a {
77 | color: var( --red );
78 | }`,
79 | MockProps
80 | )
81 | })
82 |
83 | it('Can jit a single prop that has fallbacks', async () => {
84 | await run(
85 | `a {
86 | color: var(--red, hotpink);
87 | }`,
88 | `:root {
89 | --red: #f00;
90 | }
91 | a {
92 | color: var(--red, hotpink);
93 | }`,
94 | MockProps
95 | )
96 | })
97 |
98 | it('Can jit a single prop with spaces that has fallbacks', async () => {
99 | await run(
100 | `a {
101 | color: var( --red, hotpink);
102 | }`,
103 | `:root {
104 | --red: #f00;
105 | }
106 | a {
107 | color: var( --red, hotpink);
108 | }`,
109 | MockProps
110 | )
111 | })
112 |
113 | it('Can jit a single prop that has fallbacks and nested props', async () => {
114 | await run(
115 | `a {
116 | color: var(--red, var(--pink), hotpink);
117 | }`,
118 | `:root {
119 | --red: #f00;
120 | --pink: #ffc0cb;
121 | }
122 | a {
123 | color: var(--red, var(--pink), hotpink);
124 | }`,
125 | MockProps
126 | )
127 | })
128 |
129 | it('Can jit a single, undefined prop that has fallbacks and nested props', async () => {
130 | await run(
131 | `a {
132 | color: var(--orange, var(--pink), hotpink);
133 | }`,
134 | `:root {
135 | --pink: #ffc0cb;
136 | }
137 | a {
138 | color: var(--orange, var(--pink), hotpink);
139 | }`,
140 | MockProps
141 | )
142 | })
143 |
144 |
145 | it('Can jit a single prop with spaces that has fallbacks and nested props', async () => {
146 | await run(
147 | `a {
148 | color: var( --red, var( --pink ), hotpink);
149 | }`,
150 | `:root {
151 | --red: #f00;
152 | --pink: #ffc0cb;
153 | }
154 | a {
155 | color: var( --red, var( --pink ), hotpink);
156 | }`,
157 | MockProps
158 | )
159 | })
160 |
161 | it('Can jit multiple props', async () => {
162 | await run(
163 | `a {
164 | color: var(--red);
165 | border-color: var(--pink);
166 | padding-block-start: var( --size-1 );
167 | }`,
168 | `:root {
169 | --red: #f00;
170 | --pink: #ffc0cb;
171 | --size-1: 1rem;
172 | }
173 | a {
174 | color: var(--red);
175 | border-color: var(--pink);
176 | padding-block-start: var( --size-1 );
177 | }`,
178 | MockProps
179 | )
180 | })
181 |
182 | it('Can jit multiple props from shorthand', async () => {
183 | await run(
184 | `a {
185 | padding-block: var(--size-1) var( --size-2 );
186 | }`,
187 | `:root {
188 | --size-1: 1rem;
189 | --size-2: 2rem;
190 | }
191 | a {
192 | padding-block: var(--size-1) var( --size-2 );
193 | }`,
194 | MockProps
195 | )
196 | })
197 |
198 | it('Can jit props from inside functions', async () => {
199 | await run(
200 | `a {
201 | color: hsl(var(--h) var(--s) var( --l ));
202 | }`,
203 | `:root {
204 | --h: 200;
205 | --s: 50%;
206 | --l: 50%;
207 | }
208 | a {
209 | color: hsl(var(--h) var(--s) var( --l ));
210 | }`,
211 | MockProps
212 | )
213 | })
214 |
215 | it('Only adds a prop one time to :root', async () => {
216 | await run(
217 | `a {
218 | color: var(--red);
219 | border-color: var(--red );
220 | }`,
221 | `:root {
222 | --red: #f00;
223 | }
224 | a {
225 | color: var(--red);
226 | border-color: var(--red );
227 | }`,
228 | MockProps
229 | )
230 | })
231 |
232 | it('Can jit props into a layer', async () => {
233 | await run(
234 | `a {
235 | color: hsl(var(--h) var(--s) var( --l ));
236 | }`,
237 | `@layer test {
238 | :root {
239 | --h: 200;
240 | --s: 50%;
241 | --l: 50%;
242 | }
243 | }
244 | a {
245 | color: hsl(var(--h) var(--s) var( --l ));
246 | }`,
247 | {
248 | ... MockProps,
249 | layer: 'test',
250 | }
251 | )
252 | })
253 |
254 | it('Can jit a keyframe animation', async () => {
255 | await run(
256 | `a {
257 | animation: var(--fade-in);
258 | }`,
259 | `:root {
260 | --fade-in: fade-in .5s ease;
261 | }a {
262 | animation: var(--fade-in);
263 | }@keyframes fade-in {to { opacity: 1 }}`,
264 | MockProps
265 | )
266 | })
267 |
268 | it('Can jit an adaptive keyframe animation', async () => {
269 | await run(
270 | `a {
271 | animation: var(--adaptive-fade);
272 | }`,
273 | `:root {
274 | --adaptive-fade: adaptive-fade .5s ease;
275 | }a {
276 | animation: var(--adaptive-fade);
277 | }@keyframes adaptive-fade {to { background: white }}@media (prefers-color-scheme: dark) {:root {}@keyframes adaptive-fade {to { background: black }}
278 | }`,
279 | MockProps
280 | )
281 | })
282 |
283 | it('Can jit @custom-media', async () => {
284 | await run(
285 | `@media (--dark) {
286 | a {
287 | color: white;
288 | }
289 | }`,
290 | `@custom-media --dark (prefers-color-scheme: dark);
291 | :root{}
292 | @media (--dark) {
293 | a {
294 | color: white;
295 | }
296 | }`,
297 | MockProps
298 | )
299 | })
300 |
301 | it('Can jit @custom-media with spaces', async () => {
302 | await run(
303 | `@media ( --dark ) {
304 | a {
305 | color: white;
306 | }
307 | }`,
308 | `@custom-media --dark (prefers-color-scheme: dark);
309 | :root{}
310 | @media ( --dark ) {
311 | a {
312 | color: white;
313 | }
314 | }`,
315 | MockProps
316 | )
317 | })
318 |
319 | it('Can jit props from JSON', async () => {
320 | await run(
321 | `a {
322 | color: var(--red);
323 | border-color: var( --pink );
324 | }`,
325 | `:root {
326 | --red: #f00;
327 | --pink: #ffc0cb;
328 | }
329 | a {
330 | color: var(--red);
331 | border-color: var( --pink );
332 | }`,
333 | MockProps
334 | )
335 | })
336 |
337 | it('Can jit props from a CSS file', async () => {
338 | await run(
339 | `@media (--dark) {
340 | a {
341 | color: var(--red);
342 | border-color: var( --pink );
343 | animation: var(--fade-in);
344 | }
345 | }`,
346 | `@custom-media --dark (prefers-color-scheme: dark);
347 | :root{
348 | --red: #f00;
349 | --pink: #ffc0cb;
350 | --fade-in: fade-in .5s ease;
351 | }
352 | @media (--dark) {
353 | a {
354 | color: var(--red);
355 | border-color: var( --pink );
356 | animation: var(--fade-in);
357 | }
358 | }
359 | @keyframes fade-in {to { opacity: 1 }}`,
360 | { files: ['./props.test.css']}
361 | )
362 | })
363 |
364 | it('Can jit props from a CSS file via glob', async () => {
365 | await run(
366 | `@media (--dark) {
367 | a {
368 | color: var(--red);
369 | border-color: var( --pink );
370 | animation: var(--fade-in);
371 | }
372 | }`,
373 | `@custom-media --dark (prefers-color-scheme: dark);
374 | :root{
375 | --red: #f00;
376 | --pink: #ffc0cb;
377 | --fade-in: fade-in .5s ease;
378 | }
379 | @media (--dark) {
380 | a {
381 | color: var(--red);
382 | border-color: var( --pink );
383 | animation: var(--fade-in);
384 | }
385 | }
386 | @keyframes fade-in {to { opacity: 1 }}`,
387 | { files: ['./*.test.css']}
388 | )
389 | })
390 |
391 | it('Can fail without srcProps options gracefully', async () => {
392 | console.warn = jest.fn()
393 | await postcss([plugin({})]).process(``, { from: undefined })
394 |
395 | expect(console.warn).toHaveBeenCalledWith('postcss-jit-props: Variable source(s) not passed.')
396 | })
397 |
398 | it('Can jit props to a custom selector', async () => {
399 | await run(
400 | `a {
401 | color: var(--red);
402 | }`,
403 | `:global {
404 | --red: #f00;
405 | }
406 | a {
407 | color: var(--red);
408 | }`,
409 | {
410 | ... MockProps,
411 | custom_selector: ':global',
412 | }
413 | )
414 | })
415 |
416 | it('Can jit light and dark props to a custom selector', async () => {
417 | await run(
418 | `a {
419 | color: var(--text);
420 | }`,
421 | `:global {
422 | --text: white;
423 | }
424 | a {
425 | color: var(--text);
426 | }
427 | @media (prefers-color-scheme: dark) {
428 | :global {
429 | --text: black;
430 | }
431 | }`,
432 | {
433 | ... MockProps,
434 | custom_selector: ':global',
435 | }
436 | )
437 | })
438 |
439 | it('Can jit light & dark props to a custom selector for use with a client side switch', async () => {
440 | await run(
441 | `a {
442 | color: var(--text);
443 | }`,
444 | `.light {
445 | --text: white;
446 | }
447 | a {
448 | color: var(--text);
449 | }
450 | @media (prefers-color-scheme: dark) {
451 | .dark {
452 | --text: black;
453 | }
454 | }`,
455 | {
456 | ... MockProps,
457 | custom_selector: '.light',
458 | custom_selector_dark: '.dark',
459 | }
460 | )
461 | })
462 |
463 | it('Wont create a :root {} context unless props are found', async () => {
464 | await run(
465 | `a {
466 | color: red;
467 | }`,
468 | `a {
469 | color: red;
470 | }`,
471 | {
472 | ... MockProps
473 | }
474 | )
475 | })
476 |
477 | it('Can jit a light and dark adaptive prop', async () => {
478 | await run(
479 | `p {
480 | color: var(--text);
481 | }`,
482 | `:root {
483 | --text: white;
484 | }
485 | p {
486 | color: var(--text);
487 | }
488 | @media (prefers-color-scheme: dark) {
489 | :root {
490 | --text: black;
491 | }
492 | }`,
493 | MockProps
494 | )
495 | })
496 |
497 | it('Can jit a light and dark color with a custom adaptive prop parameter', async () => {
498 | await run(
499 | `p {
500 | color: var(--text);
501 | }`,
502 | `:root {
503 | --text: white;
504 | }
505 | p {
506 | color: var(--text);
507 | }
508 | @media (prefers-color-scheme: dark) {
509 | :root {
510 | --text: black;
511 | }
512 | }`,
513 | {
514 | ...MockPropsWithCustomAdaptiveProp,
515 | adaptive_prop_selector: '-dark'
516 | }
517 | )
518 | })
519 |
520 | it('Supports parallel runners', async () => {
521 | const pluginInstance = plugin({
522 | '--red': '#f00',
523 | '--pink': '#ffc0cb',
524 | });
525 |
526 | let [resultA, resultB, resultC, resultD] = await Promise.all([
527 | postcss([pluginInstance]).process(`a { color: var(--red); }`, { from: undefined }),
528 | postcss([pluginInstance]).process(`a { color: var(--pink); }`, { from: undefined }),
529 | postcss([pluginInstance]).process(`a { color: var(--red); }`, { from: undefined }),
530 | postcss([pluginInstance]).process(`a { color: var(--pink); }`, { from: undefined }),
531 | ])
532 |
533 | let resultE = await postcss([pluginInstance]).process(`a { color: green; }`, { from: undefined })
534 |
535 | expect(resultA.css).toEqual(':root { --red: #f00; }\na { color: var(--red); }')
536 | expect(resultA.warnings()).toHaveLength(0)
537 |
538 | expect(resultB.css).toEqual(':root { --pink: #ffc0cb; }\na { color: var(--pink); }')
539 | expect(resultB.warnings()).toHaveLength(0)
540 |
541 | expect(resultC.css).toEqual(':root { --red: #f00; }\na { color: var(--red); }')
542 | expect(resultC.warnings()).toHaveLength(0)
543 |
544 | expect(resultD.css).toEqual(':root { --pink: #ffc0cb; }\na { color: var(--pink); }')
545 | expect(resultD.warnings()).toHaveLength(0)
546 |
547 | expect(resultE.css).toEqual('a { color: green; }')
548 | expect(resultE.warnings()).toHaveLength(0)
549 | })
550 |
551 | it('Supports parallel runners when reading from a file', async () => {
552 | const pluginInstance = plugin({ files: ['./props.test.css'] });
553 |
554 | let [resultA, resultB, resultC, resultD] = await Promise.all([
555 | postcss([pluginInstance]).process(`a { color: var(--red); }`, { from: undefined }),
556 | postcss([pluginInstance]).process(`a { color: var(--pink); }`, { from: undefined }),
557 | postcss([pluginInstance]).process(`a { color: var(--red); }`, { from: undefined }),
558 | postcss([pluginInstance]).process(`a { color: var(--pink); }`, { from: undefined }),
559 | ])
560 |
561 | let resultE = await postcss([pluginInstance]).process(`a { color: green; }`, { from: undefined })
562 |
563 | expect(resultA.css).toEqual(':root { --red: #f00; }\na { color: var(--red); }')
564 | expect(resultA.warnings()).toHaveLength(0)
565 |
566 | expect(resultB.css).toEqual(':root { --pink: #ffc0cb; }\na { color: var(--pink); }')
567 | expect(resultB.warnings()).toHaveLength(0)
568 |
569 | expect(resultC.css).toEqual(':root { --red: #f00; }\na { color: var(--red); }')
570 | expect(resultC.warnings()).toHaveLength(0)
571 |
572 | expect(resultD.css).toEqual(':root { --pink: #ffc0cb; }\na { color: var(--pink); }')
573 | expect(resultD.warnings()).toHaveLength(0)
574 |
575 | expect(resultE.css).toEqual('a { color: green; }')
576 | expect(resultE.warnings()).toHaveLength(0)
577 | })
578 |
579 | // situation encountered when using postcs-jit-props for Open Props
580 | // together with having @nuxt/fonts module with no global font definition
581 | // it still creates an empty .nuxt/nuxt-fonts-global.css file
582 | // and postcs-jit-props started to fail trying to parse it
583 | // --
584 | // fixed by adding "node.first" null check into parsing method
585 | // (lines 130 and 136 in index.js)
586 |
587 | it('Parses an empty file and rule', async () => {
588 | const pluginInstance = plugin({ files: ['./props.test.empty.css'] });
589 | let result = await postcss([pluginInstance]).process('');
590 | expect(result.css).toEqual("");
591 | expect(result.warnings()).toHaveLength(0);
592 | })
593 |
--------------------------------------------------------------------------------
/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "postcss-jit-props",
3 | "version": "1.0.16",
4 | "description": "PostCSS plugin to insert variables from a data source based on discovered usage",
5 | "keywords": [
6 | "postcss",
7 | "css",
8 | "postcss-plugin",
9 | "css-vars",
10 | "css-custom-properties"
11 | ],
12 | "types": "index.d.ts",
13 | "scripts": {
14 | "test": "jest --coverage && eslint .",
15 | "dev": "jest --coverage --watch",
16 | "lint": "eslint ."
17 | },
18 | "author": "Adam Argyle ",
19 | "license": "Apache-2.0",
20 | "repository": {
21 | "type": "git",
22 | "url": "git+https://github.com/GoogleChromeLabs/postcss-jit-props.git"
23 | },
24 | "engines": {
25 | "node": ">=10.0.0"
26 | },
27 | "peerDependencies": {
28 | "postcss": "^8.2.8"
29 | },
30 | "devDependencies": {
31 | "clean-publish": "^2.1.0",
32 | "eslint": "^7.21.0",
33 | "eslint-plugin-jest": "^24.2.1",
34 | "jest": "^26.6.3",
35 | "lint-staged": "^10.5.4",
36 | "postcss": "^8.2.8",
37 | "simple-git-hooks": "^2.0.2"
38 | },
39 | "simple-git-hooks": {
40 | "pre-commit": "npx lint-staged"
41 | },
42 | "lint-staged": {
43 | "*.js": "eslint --fix"
44 | },
45 | "eslintConfig": {
46 | "parserOptions": {
47 | "ecmaVersion": 2020
48 | },
49 | "env": {
50 | "node": true,
51 | "es6": true
52 | },
53 | "extends": [
54 | "eslint:recommended",
55 | "plugin:jest/recommended"
56 | ],
57 | "rules": {
58 | "jest/expect-expect": "off"
59 | }
60 | },
61 | "jest": {
62 | "testEnvironment": "node",
63 | "coverageThreshold": {
64 | "global": {
65 | "statements": 90
66 | }
67 | }
68 | },
69 | "dependencies": {
70 | "tiny-glob": "^0.2.9"
71 | }
72 | }
73 |
--------------------------------------------------------------------------------
/props.test.css:
--------------------------------------------------------------------------------
1 | @custom-media --dark (prefers-color-scheme: dark);
2 |
3 | :root {
4 | --red: #f00;
5 | --pink: #ffc0cb;
6 | --h: 200;
7 | --s: 50%;
8 | --l: 50%;
9 | --size-1: 1rem;
10 | --size-2: 2rem;
11 | --fade-in: fade-in .5s ease;
12 | }
13 |
14 | @keyframes fade-in {to { opacity: 1 }}
--------------------------------------------------------------------------------
/props.test.empty.css:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/GoogleChromeLabs/postcss-jit-props/4099bde8a8d77a7c66957014042d006c79fe6961/props.test.empty.css
--------------------------------------------------------------------------------