Skip to content

Commit 7a4e544

Browse files
feat: add default value
Adds ability to define a default value using "__default", to use as a base value. Co-authored-by: Timo Bechtel <[email protected]>
1 parent e3976af commit 7a4e544

File tree

3 files changed

+29
-2
lines changed

3 files changed

+29
-2
lines changed

README.md

Lines changed: 9 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -65,7 +65,11 @@ import cssVars from 'css-vars-from-json';
6565
const theme = cssVars({
6666
colors: {
6767
primary: 'red',
68-
secondary: 'blue',
68+
secondary: {
69+
__default: 'blue',
70+
// base value, will be rendered as --colors-secondary: blue
71+
light: 'lightblue',
72+
},
6973
},
7074
shadows: {
7175
main: 'box-shadow: 1px 1px black',
@@ -80,11 +84,13 @@ const theme = cssVars({
8084
document.body.setAttribute('style', theme);
8185

8286
console.log(theme);
83-
// => "--colors-primary: red;--colors-secondary: blue;--shadows-main: box-shadow: 1px 1px black;--font-family-primary: Arial;"
87+
// => "--colors-primary: red;--colors-secondary: blue;--colors-secondary-light: lightblue;--shadows-main: box-shadow: 1px 1px black;--font-family-primary: Arial;"
8488
```
8589

8690
### Svelte example
91+
8792
ThemeProvider.svelte
93+
8894
```html
8995
<script>
9096
import { theme } from './my-design-system';
@@ -99,6 +105,7 @@ ThemeProvider.svelte
99105
```
100106

101107
App.svelte
108+
102109
```html
103110
<script>
104111
import ThemeProvider from './ThemeProvider.svelte';

src/index.ts

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -22,5 +22,8 @@ function generateVariables(path: string, object: JsonObject): string {
2222

2323
function join(path: string, key: string): string {
2424
if (!path) return key;
25+
// ignore __default property and use root key instead
26+
// e.g. blue: { default: "blue", light: "lightblue" } => --blue: blue; --blue-light: lightblue;
27+
if (key === '__default') return path;
2528
return `${path}-${key}`;
2629
}

test/generateVariables.test.ts

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -22,3 +22,20 @@ test('generate variables string from json object', () => {
2222
'--colors-primary: red;--colors-secondary: blue;--shadows-main: box-shadow: 1px 1px black;--font-family-primary: Arial;'
2323
);
2424
});
25+
26+
test('ignores __default property and use its value as base value', () => {
27+
const theme = {
28+
colors: {
29+
primary: {
30+
__default: 'blue',
31+
light: 'lightblue',
32+
},
33+
},
34+
};
35+
36+
const style = cssVars(theme);
37+
38+
expect(style).toBe(
39+
'--colors-primary: blue;--colors-primary-light: lightblue;'
40+
);
41+
});

0 commit comments

Comments
 (0)