@spark-ui/theme-utils 1.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md ADDED
@@ -0,0 +1,14 @@
1
+ # Change Log
2
+
3
+ All notable changes to this project will be documented in this file.
4
+ See [Conventional Commits](https://conventionalcommits.org) for commit guidelines.
5
+
6
+ # [1.1.0](https://github.com/adevinta/spark/compare/@spark-ui/theme-utils@0.0.1...@spark-ui/theme-utils@1.1.0) (2023-02-10)
7
+
8
+ ### Features
9
+
10
+ - **theme-utils:** force first release ([77122ff](https://github.com/adevinta/spark/commit/77122ffea409244b8268c1e90096e60beedbcd86))
11
+
12
+ ## 0.0.1 (2023-02-09)
13
+
14
+ **Note:** Version bump only for package @spark-ui/theme-utils
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) Meta Platforms, Inc. and affiliates.
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,101 @@
1
+ import { appendFileSync, existsSync, mkdirSync } from 'fs'
2
+ import hexRgb from 'hex-rgb'
3
+ import parentModule from 'parent-module'
4
+ import { join } from 'path'
5
+
6
+ import type { Theme } from './types.mjs'
7
+ import {
8
+ buildFilePath,
9
+ isHex,
10
+ isStringOrNumber,
11
+ objectEntries,
12
+ objectKeys,
13
+ toKebabCase,
14
+ } from './utils.mjs'
15
+
16
+ /* eslint-disable-next-line @typescript-eslint/ban-types */
17
+ type FlattenedTheme = Record<'className' | (string & {}), string | number>
18
+ type NestedObj = Record<string, string | number | Record<string, string | number>>
19
+
20
+ function flattenTheme(theme: Theme, className: string): FlattenedTheme {
21
+ const flattenedTheme = {} as FlattenedTheme
22
+
23
+ function flatten(obj: Theme, path?: string) {
24
+ objectEntries(obj as unknown as NestedObj).forEach(([key, value]) => {
25
+ if (value !== null && typeof value === 'object') {
26
+ const formattedPath = path ? `--${path}-${key}` : `--${key}`
27
+ flatten(value as unknown as Theme, toKebabCase(formattedPath.replace(/-{3,}/, '--')))
28
+
29
+ return
30
+ }
31
+
32
+ if (isStringOrNumber(value)) {
33
+ const getFormattedValue = () => {
34
+ if (isHex(value)) {
35
+ const { red, green, blue } = hexRgb(value)
36
+
37
+ return `${red} ${green} ${blue}`
38
+ }
39
+
40
+ return value
41
+ }
42
+
43
+ flattenedTheme[`${path}-${toKebabCase(key as string)}`] = getFormattedValue()
44
+ }
45
+ })
46
+ }
47
+
48
+ flatten(theme)
49
+
50
+ return {
51
+ ...flattenedTheme,
52
+ className,
53
+ }
54
+ }
55
+
56
+ const toStringifiedTheme = (theme: Record<string, string | number>) =>
57
+ Object.entries(theme)
58
+ .map(([k, v]) => `${k}:${v}`)
59
+ .join(';')
60
+
61
+ const getStringifiedThemes = (themeRecord: Record<string, Theme>) =>
62
+ objectKeys(themeRecord).map(key => {
63
+ const { className, ...rest } = flattenTheme(themeRecord[key] as Theme, key)
64
+
65
+ return key === 'default'
66
+ ? `:root{${toStringifiedTheme(rest)}}`
67
+ : `.${className}{${toStringifiedTheme(rest)}}`
68
+ })
69
+
70
+ export function createCSSTokensFile(path: string, themeRecord: Record<string, Theme>) {
71
+ const { filepath, rootPath } = buildFilePath(join(parentModule() || '', path))
72
+
73
+ const folders = filepath.split('/').slice(0, -1)
74
+ folders.reduce((acc, folder) => {
75
+ const folderPath = acc + folder + '/'
76
+ if (!existsSync(folderPath)) {
77
+ mkdirSync(folderPath)
78
+ }
79
+
80
+ return folderPath
81
+ }, rootPath)
82
+
83
+ try {
84
+ appendFileSync(
85
+ rootPath + filepath,
86
+ `
87
+ @tailwind base;
88
+ @tailwind components;
89
+ @tailwind utilities;
90
+ @layer base {${getStringifiedThemes(themeRecord).join('')}}
91
+ `,
92
+ {
93
+ flag: 'w',
94
+ }
95
+ )
96
+
97
+ console.log(`✨ CSS tokens file has been created 👉 ${path}`)
98
+ } catch (error) {
99
+ console.error(error)
100
+ }
101
+ }
@@ -0,0 +1,76 @@
1
+ import { existsSync, mkdirSync, writeFileSync } from 'fs'
2
+ import parentModule from 'parent-module'
3
+ import { join } from 'path'
4
+
5
+ import { defaultTheme } from './defaultTheme.mjs'
6
+ import type { Theme } from './types.mjs'
7
+ import {
8
+ buildFilePath,
9
+ isHex,
10
+ isStringOrNumber,
11
+ objectEntries,
12
+ toKebabCase,
13
+ toKebabCaseKeys,
14
+ } from './utils.mjs'
15
+
16
+ type NestedObj = Record<string, string | number | Record<string, string | number>>
17
+ type TailwindConfig = Record<string, Theme[keyof Theme]>
18
+
19
+ function toTailwindConfig(theme: Theme): TailwindConfig {
20
+ const themeCpy: Theme = JSON.parse(JSON.stringify(theme))
21
+
22
+ function flatten(obj: Theme, path?: string) {
23
+ objectEntries(obj as unknown as NestedObj).forEach(([key, value]) => {
24
+ if (value !== null && typeof value === 'object') {
25
+ const formattedPath = path ? `--${path}-${key}` : `--${key}`
26
+ flatten(value as unknown as Theme, toKebabCase(formattedPath.replace(/-{3,}/, '--')))
27
+
28
+ return
29
+ }
30
+
31
+ /* eslint-disable */
32
+ if (isStringOrNumber(value)) {
33
+ const formattedPath =
34
+ /--colors/.test(path || '') && isHex(value)
35
+ ? `rgb(var(${path}-${toKebabCase(key as string)}) / <alpha-value>)`
36
+ : `var(${path}-${toKebabCase(key as string)})`
37
+
38
+ /* @ts-ignore */
39
+ obj[key as any] = formattedPath
40
+ /* eslint-enable */
41
+ }
42
+ })
43
+ }
44
+
45
+ flatten(themeCpy)
46
+
47
+ return toKebabCaseKeys(themeCpy)
48
+ }
49
+
50
+ export function createTailwindConfigFile(path: string) {
51
+ const { filepath, rootPath } = buildFilePath(join(parentModule() || '', path))
52
+
53
+ const folders = filepath.split('/').slice(0, -1)
54
+ folders.reduce((acc, folder) => {
55
+ const folderPath = acc + folder + '/'
56
+ if (!existsSync(folderPath)) {
57
+ mkdirSync(folderPath)
58
+ }
59
+
60
+ return folderPath
61
+ }, rootPath)
62
+
63
+ try {
64
+ writeFileSync(
65
+ rootPath + filepath,
66
+ `module.exports = ${JSON.stringify(toTailwindConfig(defaultTheme))}`,
67
+ {
68
+ flag: 'w',
69
+ }
70
+ )
71
+
72
+ console.log(`✨ Tailwind theme config file has been created 👉 ${path}`)
73
+ } catch (error) {
74
+ console.error(error)
75
+ }
76
+ }
@@ -0,0 +1,9 @@
1
+ import deepMerge from 'deepmerge'
2
+ import { PartialDeep } from 'type-fest'
3
+
4
+ import { defaultTheme } from './defaultTheme.mjs'
5
+ import type { Theme } from './types.mjs'
6
+
7
+ export function createTheme(theme: PartialDeep<Theme> = {}): Theme {
8
+ return deepMerge<Theme, PartialDeep<Theme>>(defaultTheme, theme)
9
+ }
@@ -0,0 +1,106 @@
1
+ import type { Theme } from './types.mjs'
2
+
3
+ export const defaultTheme: Theme = {
4
+ screens: {
5
+ sm: '640px',
6
+ md: '768px',
7
+ lg: '1024px',
8
+ xl: '1280px',
9
+ '2xl': '1536px',
10
+ },
11
+ borderWidth: {
12
+ none: '0',
13
+ xs: '0.1rem',
14
+ s: '0.2rem',
15
+ m: '0.4rem',
16
+ },
17
+ colors: {
18
+ transparent: 'transparent',
19
+ bg: {
20
+ primary: '#f28133',
21
+ primaryAccent: '#ad4c07',
22
+ primarySubtle: '#fba56c',
23
+ secondary: '#3481f2',
24
+ secondaryAccent: '#074aad',
25
+ secondarySubtle: '#4c93f7',
26
+ body: '#fff',
27
+ },
28
+ bd: {
29
+ primary: '#f28133',
30
+ secondary: '#3481f2',
31
+ },
32
+ fg: {
33
+ default: '#334155',
34
+ accent: '#1161d7',
35
+ cta: '#000',
36
+ ctaInverse: '#fff',
37
+ },
38
+ },
39
+ fontFamily: {
40
+ openSans:
41
+ 'ui-sans-serif,system-ui,-apple-system,BlinkMacSystemFont,Segoe UI,Roboto,Helvetica Neue,Arial,Noto Sans,sans-serif,"Apple Color Emoji","Segoe UI Emoji",Segoe UI Symbol,"Noto Color Emoji"',
42
+ },
43
+ fontSize: {
44
+ xs: '1rem',
45
+ s: '1.2rem',
46
+ m: '1.4rem',
47
+ l: '1.6rem',
48
+ xl: '1.8rem',
49
+ '2xl': '2rem',
50
+ '3xl': '2.4rem',
51
+ },
52
+ fontWeight: {
53
+ regular: 400,
54
+ semibold: 600,
55
+ bold: 700,
56
+ },
57
+ lineHeight: {
58
+ xs: '1.4rem',
59
+ s: '1.7rem',
60
+ m: '1.9rem',
61
+ l: '2.2rem',
62
+ xl: '2.4rem',
63
+ '2xl': '2.6rem',
64
+ '3xl': '2.8rem',
65
+ },
66
+ width: {
67
+ pageMin: '320px',
68
+ pageMax: '1066px',
69
+ },
70
+ borderRadius: {
71
+ none: '0',
72
+ xs: '0.4rem',
73
+ s: '0.8rem',
74
+ m: '1.6rem',
75
+ l: '2.4rem',
76
+ full: '100%',
77
+ },
78
+ boxShadow: {
79
+ none: 'none',
80
+ normal: '0 -1px 4px 0 rgba(26, 26, 26, 0.08), 0 4px 8px 0 rgba(26, 26, 26, 0.12)',
81
+ highlighted: '0 -1px 8px 0 rgba(26, 26, 26, 0.12), 0 4px 8px 0 rgba(0, 0, 0, 0.14)',
82
+ },
83
+ spacing: {
84
+ auto: 'auto',
85
+ none: '0',
86
+ xs: '0.4rem',
87
+ s: '0.8rem',
88
+ m: '1.6rem',
89
+ l: '2.4rem',
90
+ xl: '3.2rem',
91
+ xxl: '4rem',
92
+ },
93
+ zIndex: {
94
+ hide: -1,
95
+ base: 0,
96
+ raised: 1,
97
+ dropdown: 1000,
98
+ sticky: 1100,
99
+ overlay: 1300,
100
+ modal: 1400,
101
+ popover: 1500,
102
+ skipLink: 1600,
103
+ toast: 1700,
104
+ tooltip: 1800,
105
+ },
106
+ }
package/index.mts ADDED
@@ -0,0 +1,6 @@
1
+ export { createTheme } from './createTheme.mjs'
2
+ export { createTailwindConfigFile } from './createTailwindConfigFile.mjs'
3
+ export { createCSSTokensFile } from './createCSSTokensFile.mjs'
4
+ export { defaultTheme } from './defaultTheme.mjs'
5
+
6
+ export type { Theme } from './types.mjs'
package/package.json ADDED
@@ -0,0 +1,21 @@
1
+ {
2
+ "name": "@spark-ui/theme-utils",
3
+ "version": "1.1.0",
4
+ "description": "Theme configuration",
5
+ "publishConfig": {
6
+ "access": "public"
7
+ },
8
+ "main": "./dist/index.js",
9
+ "module": "./dist/index.mjs",
10
+ "types": "./dist/index.d.mts",
11
+ "scripts": {
12
+ "build": "vite build"
13
+ },
14
+ "devDependencies": {
15
+ "deepmerge": "4.3.0",
16
+ "hex-rgb": "5.0.0",
17
+ "parent-module": "3.0.0",
18
+ "type-fest": "3.5.6"
19
+ },
20
+ "gitHead": "807a2fbdf384a277d4110cff7dbb549bb9ab4563"
21
+ }
package/tsconfig.json ADDED
@@ -0,0 +1,10 @@
1
+ {
2
+ "extends": "../../../tsconfig.json",
3
+ "compilerOptions": {
4
+ "baseUrl": ".",
5
+ "rootDir": "./",
6
+ "outDir": "./dist",
7
+ "declaration": true,
8
+ },
9
+ "include": ["**/*", "../../global.d.ts"]
10
+ }
package/types.mts ADDED
@@ -0,0 +1,103 @@
1
+ export interface Theme {
2
+ screens: {
3
+ sm: string
4
+ md: string
5
+ lg: string
6
+ xl: string
7
+ '2xl': string
8
+ }
9
+ borderWidth: {
10
+ none: string
11
+ xs: string
12
+ s: string
13
+ m: string
14
+ }
15
+ colors: {
16
+ transparent: string
17
+ bg: {
18
+ body: string
19
+ primary: string
20
+ primaryAccent: string
21
+ primarySubtle: string
22
+ secondary: string
23
+ secondaryAccent: string
24
+ secondarySubtle: string
25
+ }
26
+ fg: {
27
+ default: string
28
+ accent: string
29
+ cta: string
30
+ ctaInverse: string
31
+ }
32
+ bd: {
33
+ primary: string
34
+ secondary: string
35
+ }
36
+ }
37
+ fontFamily: {
38
+ openSans: string
39
+ }
40
+ fontSize: {
41
+ xs: string
42
+ s: string
43
+ m: string
44
+ l: string
45
+ xl: string
46
+ '2xl': string
47
+ '3xl': string
48
+ }
49
+ fontWeight: {
50
+ regular: number
51
+ semibold: number
52
+ bold: number
53
+ }
54
+ lineHeight: {
55
+ xs: string
56
+ s: string
57
+ m: string
58
+ l: string
59
+ xl: string
60
+ '2xl': string
61
+ '3xl': string
62
+ }
63
+ width: {
64
+ pageMin: string
65
+ pageMax: string
66
+ }
67
+ borderRadius: {
68
+ none: string
69
+ xs: string
70
+ s: string
71
+ m: string
72
+ l: string
73
+ full: string
74
+ }
75
+ boxShadow: {
76
+ none: string
77
+ normal: string
78
+ highlighted: string
79
+ }
80
+ spacing: {
81
+ auto: string
82
+ none: string
83
+ xs: string
84
+ s: string
85
+ m: string
86
+ l: string
87
+ xl: string
88
+ xxl: string
89
+ }
90
+ zIndex: {
91
+ hide: number
92
+ base: number
93
+ raised: number
94
+ dropdown: number
95
+ sticky: number
96
+ overlay: number
97
+ modal: number
98
+ popover: number
99
+ skipLink: number
100
+ toast: number
101
+ tooltip: number
102
+ }
103
+ }
package/utils.mts ADDED
@@ -0,0 +1,71 @@
1
+ function objectKeys<T extends Record<string | number, unknown>>(obj: T): (keyof T)[] {
2
+ return Object.keys(obj) as (keyof T)[]
3
+ }
4
+
5
+ function objectEntries<T extends Record<string | number, unknown>>(
6
+ obj: T
7
+ ): [keyof T, T[keyof T]][] {
8
+ return Object.entries(obj) as [keyof T, T[keyof T]][]
9
+ }
10
+
11
+ function toKebabCase(v: string) {
12
+ return v.replace(/[A-Z]/g, e => `-${e.toLocaleLowerCase()}`)
13
+ }
14
+
15
+ function isHex(value: string | number): value is string {
16
+ if (typeof value === 'number') {
17
+ return false
18
+ }
19
+
20
+ const regexp = /^#[0-9a-fA-F]+$/
21
+
22
+ return regexp.test(value)
23
+ }
24
+
25
+ function isStringOrNumber(value: unknown): value is string | number {
26
+ return typeof value === 'string' || typeof value === 'number'
27
+ }
28
+
29
+ // eslint-disable-next-line @typescript-eslint/ban-types
30
+ function toKebabCaseKeys<T extends Object>(obj: T, level = 1): Record<string, T[keyof T]> {
31
+ const result: any = {}
32
+ for (const key in obj) {
33
+ const value =
34
+ typeof obj[key] === 'object' ? toKebabCaseKeys(obj[key] as T, level + 1) : obj[key]
35
+ result[level > 1 ? key.replace(/([a-z])([A-Z])/g, '$1-$2').toLowerCase() : key] = value
36
+ }
37
+
38
+ return result
39
+ }
40
+
41
+ function getFormattedPath(input: string) {
42
+ const preFormat = input.slice(input.indexOf(':') + 1)
43
+ const extensionRegex = /\/([^/]+)\.(jsx|js|tsx|ts|mjs|mts|cjs|cts)(?!$)/g
44
+
45
+ return preFormat.replace(preFormat.match(extensionRegex)?.at(0) || '', '')
46
+ }
47
+
48
+ function buildFilePath(path: string) {
49
+ let filepath = getFormattedPath(path).replace(/\\/g, '/')
50
+
51
+ let rootPath = ''
52
+ if (filepath[0] === '/') {
53
+ rootPath = '/'
54
+ filepath = filepath.slice(1)
55
+ } else if (filepath[1] === ':') {
56
+ rootPath = filepath.slice(0, 3)
57
+ filepath = filepath.slice(3)
58
+ }
59
+
60
+ return { filepath, rootPath }
61
+ }
62
+
63
+ export {
64
+ objectKeys,
65
+ objectEntries,
66
+ toKebabCase,
67
+ isHex,
68
+ toKebabCaseKeys,
69
+ buildFilePath,
70
+ isStringOrNumber,
71
+ }
package/vite.config.ts ADDED
@@ -0,0 +1,24 @@
1
+ import path from 'path'
2
+ import { terser } from 'rollup-plugin-terser'
3
+ import typescript from '@rollup/plugin-typescript'
4
+
5
+ const pkg = require(path.resolve(__dirname, './package.json'))
6
+
7
+ const deps = Object.keys(pkg.dependencies || {})
8
+ const devDeps = Object.keys(pkg.devDependencies || {})
9
+
10
+ export default {
11
+ build: {
12
+ target: 'es2015',
13
+ lib: {
14
+ entry: 'index.mts',
15
+ formats: ['es', 'cjs'],
16
+ fileName: 'index',
17
+ },
18
+ rollupOptions: {
19
+ external: [...deps, ...devDeps, 'path', 'fs'],
20
+ preserveModules: false,
21
+ plugins: [terser(), typescript({ cacheDir: './dist' })],
22
+ },
23
+ },
24
+ }