@fullstackunicorn/style 1.0.13 → 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/index.dep.js CHANGED
@@ -3,6 +3,7 @@ export { fss, fsa } from '@fullstackunicorn/filesystem'
3
3
 
4
4
  // NODE BUILT IN
5
5
  export { default as path } from 'path'
6
+ export { readFile, realpath } from 'node:fs/promises'
6
7
 
7
8
  // PACKAGES
8
9
  export { glob } from 'glob'
package/index.js CHANGED
File without changes
@@ -0,0 +1,181 @@
1
+ import { path, readFile, realpath } from '#@/index.dep.js'
2
+ import { style } from '#@/modules/engine/style.js'
3
+
4
+ class Geometry {
5
+
6
+ constructor(basePath) {
7
+ this.filename = path.resolve(basePath, 'configure/geometry.js')
8
+ }
9
+
10
+ invalid = message => {
11
+ throw new Error(`Invalid Geometry: ${message} (${this.filename})`)
12
+ }
13
+
14
+ safe = name => {
15
+ if (['__proto__', 'prototype', 'constructor'].includes(name)) this.invalid(`unsafe property ${name}`)
16
+ return name
17
+ }
18
+
19
+ read = async () => {
20
+ if (!this.pending) this.pending = this.load()
21
+ return this.pending
22
+ }
23
+
24
+ load = async () => {
25
+ let source
26
+ try {
27
+ this.filename = await realpath(this.filename)
28
+ source = await readFile(this.filename, 'utf8')
29
+ } catch (error) {
30
+ throw new Error(`Cannot read Geometry (${this.filename})`, { cause: error })
31
+ }
32
+
33
+ const tokens = []
34
+ let offset = 0
35
+ let newline = false
36
+ while (offset < source.length) {
37
+ const remaining = source.slice(offset)
38
+ const skipped = remaining.match(/^(?:\s+|\/\/[^\n]*(?:\n|$)|\/\*[\s\S]*?\*\/)/)
39
+ if (skipped) {
40
+ newline ||= skipped[0].includes('\n')
41
+ offset += skipped[0].length
42
+ continue
43
+ }
44
+ const match = remaining.match(/^(?:"(?:[^"\\\r\n]|\\["\\nrt])*"|'(?:[^'\\\r\n]|\\['\\nrt])*'|(?:0|[1-9]\d*)(?:\.\d+)?(?:[eE][+-]?\d+)?|[A-Za-z_$][\w$]*|[{}[\].,:;=+-])/)
45
+ if (!match) this.invalid(`unsupported syntax at line ${source.slice(0, offset).split('\n').length}`)
46
+ tokens.push({ value: match[0], newline })
47
+ offset += match[0].length
48
+ newline = false
49
+ }
50
+
51
+ const variables = Object.create(null)
52
+ let position = 0
53
+ let exported = false
54
+ const current = () => tokens[position]?.value
55
+ const take = expected => {
56
+ const value = current()
57
+ if (expected && value !== expected) this.invalid(`expected ${expected}, received ${value ?? 'end of file'}`)
58
+ position++
59
+ return value
60
+ }
61
+ const name = () => {
62
+ const value = take()
63
+ if (!/^[A-Za-z_$][\w$]*$/.test(value ?? '')) this.invalid('expected a property name')
64
+ return this.safe(value)
65
+ }
66
+ const member = (object, key) => {
67
+ if (!object || typeof object !== 'object' || !Object.hasOwn(object, key)) this.invalid(`unknown property ${key}`)
68
+ return object[key]
69
+ }
70
+ const string = token => token.slice(1, -1).replace(/\\(["'\\nrt])/g, (_, value) => ({ n: '\n', r: '\r', t: '\t' }[value] ?? value))
71
+ const value = () => {
72
+ const token = current()
73
+ if (token === '{') {
74
+ take('{')
75
+ const object = Object.create(null)
76
+ while (current() !== '}') {
77
+ const key = name()
78
+ if (Object.hasOwn(object, key)) this.invalid(`duplicate property ${key}`)
79
+ object[key] = current() === ':' ? (take(':'), value()) : member(variables, key)
80
+ if (current() !== ',') break
81
+ take(',')
82
+ }
83
+ take('}')
84
+ return object
85
+ }
86
+ if (token === '[') {
87
+ take('[')
88
+ const array = []
89
+ while (current() !== ']') {
90
+ array.push(value())
91
+ if (current() !== ',') break
92
+ take(',')
93
+ }
94
+ take(']')
95
+ return array
96
+ }
97
+ if (token?.startsWith('"') || token?.startsWith("'")) return string(take())
98
+ if (token === 'true' || token === 'false' || token === 'null') return JSON.parse(take())
99
+ if (/^(?:\d|[+-]$)/.test(token ?? '')) {
100
+ const sign = token === '-' || token === '+' ? take() : ''
101
+ const number = Number(sign + take())
102
+ if (!Number.isFinite(number)) this.invalid('expected a finite number')
103
+ return number
104
+ }
105
+ let reference = member(variables, name())
106
+ while (current() === '.') {
107
+ take('.')
108
+ reference = member(reference, name())
109
+ }
110
+ return reference
111
+ }
112
+
113
+ while (position < tokens.length) {
114
+ if (current() === 'const') {
115
+ take('const')
116
+ const key = name()
117
+ if (Object.hasOwn(variables, key)) this.invalid(`duplicate declaration ${key}`)
118
+ take('=')
119
+ variables[key] = value()
120
+ } else if (current() === 'export') {
121
+ if (exported) this.invalid('duplicate export')
122
+ take('export')
123
+ take('{')
124
+ take('geometry')
125
+ if (current() === ',') take(',')
126
+ take('}')
127
+ exported = true
128
+ } else {
129
+ let object = member(variables, name())
130
+ take('.')
131
+ let key = name()
132
+ while (current() === '.') {
133
+ object = member(object, key)
134
+ take('.')
135
+ key = name()
136
+ }
137
+ if (!object || typeof object !== 'object' || Array.isArray(object)) this.invalid(`cannot assign ${key}`)
138
+ take('=')
139
+ object[key] = value()
140
+ }
141
+ if (current() === ';') take(';')
142
+ else if (position < tokens.length && !tokens[position].newline) this.invalid(`unexpected ${current()}`)
143
+ }
144
+
145
+ const geometry = variables.geometry
146
+ if (!exported || !geometry || typeof geometry !== 'object' || Array.isArray(geometry)) this.invalid('expected named export { geometry } with an object value')
147
+ return geometry
148
+ }
149
+
150
+ classes = async (source, filename) => {
151
+ const classes = []
152
+ const expression = /\bs\s*\[/g
153
+ let match
154
+ while ((match = expression.exec(source)) !== null) {
155
+ const literal = source.slice(expression.lastIndex).match(/^\s*(['"`])([^\\]*?)\1\s*\]/)
156
+ if (!literal) this.invalid(`unsupported computed style in ${filename}`)
157
+ expression.lastIndex += literal[0].length
158
+ let item = literal[2]
159
+ const dynamic = literal[1] === '`' && item.includes('${')
160
+ if (literal[1] === '`') {
161
+ const geometry = dynamic ? await this.read() : null
162
+ item = item.replace(/\$\{([^}]+)\}/g, (_, lookup) => {
163
+ if (!/^geometry(?:\.[A-Za-z_$][\w$]*)+$/.test(lookup.trim())) this.invalid(`unsupported computed style ${lookup} in ${filename}`)
164
+ let resolved = geometry
165
+ for (const key of lookup.trim().split('.').slice(1)) {
166
+ this.safe(key)
167
+ resolved = resolved && typeof resolved === 'object' && Object.hasOwn(resolved, key) ? resolved[key] : undefined
168
+ }
169
+ if ((typeof resolved !== 'number' || !Number.isFinite(resolved)) && typeof resolved !== 'string') this.invalid(`${lookup} is not a Style value in ${filename}`)
170
+ return String(resolved)
171
+ })
172
+ }
173
+ const parsed = style.parseItem(item)
174
+ if (!/^\w+$/.test(item) || (dynamic && parsed.value?.valueKind === 'keyword') || style.getContents([parsed], {}, false, false).missing.length) this.invalid(`unknown computed style ${item} in ${filename}`)
175
+ classes.push(item)
176
+ }
177
+ return classes
178
+ }
179
+ }
180
+
181
+ export const geometry = basePath => new Geometry(basePath)
@@ -1,11 +1,19 @@
1
1
  import { fsa, glob } from '#@/index.dep.js'
2
+ import { geometry } from '#@/modules/engine/geometry.js'
2
3
 
3
4
  class Parse {
4
5
 
5
- project = async () => {
6
+ project = async (sourcePaths = [process.env.BASE_PATH], basePath = sourcePaths?.[0]) => {
6
7
 
7
- const files = await glob(`${process.env.BASE_PATH}/**/*.js`, {
8
- ignore: [`${process.env.BASE_PATH}/node_modules/**`, `${process.env.BASE_PATH}/@*/**` ]})
8
+ if (!Array.isArray(sourcePaths) || !sourcePaths.length || sourcePaths.some(value => typeof value !== 'string' || !value.trim())) {
9
+ throw new Error('SOURCE_PATHS must be a non-empty array of paths')
10
+ }
11
+
12
+ const projectGeometry = geometry(basePath)
13
+
14
+ const files = [...new Set((await Promise.all(sourcePaths.map(sourcePath => glob(`${sourcePath}/**/*.js`, {
15
+ ignore: [`${sourcePath}/node_modules/**`, `${sourcePath}/@*/**`]
16
+ })))).flat())]
9
17
 
10
18
  const s_raw = []
11
19
  const c_raw = []
@@ -21,7 +29,7 @@ class Parse {
21
29
  const c_regex = /\bc\.(\w+)/g
22
30
  const f_regex = /\bf\.(\w+)/g
23
31
 
24
- const s_matches = []
32
+ const s_matches = isStyle ? await projectGeometry.classes(data, file) : []
25
33
  const c_matches = []
26
34
  const f_matches = []
27
35
 
@@ -50,4 +58,4 @@ class Parse {
50
58
  }
51
59
  }
52
60
 
53
- export const parse = new Parse()
61
+ export const parse = new Parse()
package/modules/run.js CHANGED
@@ -35,7 +35,7 @@ export const run = async (setup) => {
35
35
  'line' // border-color
36
36
  ]
37
37
 
38
- const parsed = await parse.project()
38
+ const parsed = await parse.project(setup.SOURCE_PATHS || [setup.BASE_PATH], setup.BASE_PATH)
39
39
 
40
40
  const fontList = parsed.f
41
41
  const styleList = style.getList(parsed.s)
@@ -80,4 +80,4 @@ export const run = async (setup) => {
80
80
  logs.prepare( fontContents.fonts, colorContents, styleContents, parsed)
81
81
  logs.toConsole()
82
82
  logs.toMarkdown(setup.LOGS_PATH)
83
- }
83
+ }
package/package.json CHANGED
@@ -1,54 +1,52 @@
1
1
  {
2
- "version": "1.0.13",
3
- "name": "@fullstackunicorn/style",
4
- "author": "lucanigido (https://fullstackunicorn.dev/author/lucanigido)",
5
- "description": "A development utility for generating responsive web and native styles (CSS, SCSS, JS, RN) from a declarative style.config.js file.",
6
- "license": "MIT",
7
- "type": "module",
8
- "private": false,
9
- "readme": "package.md",
10
- "main": "index.js",
11
- "files": [
12
- "index.js",
13
- "index.dep.js",
14
- "modules/"
15
- ],
16
- "bin": {
17
- "style": "./index.cmd.js"
18
- },
19
- "repository": {
20
- "type": "git",
21
- "url": "https://gitlab.com/fullstackunicorn/style.git"
22
- },
23
- "keywords": [
24
- "style-generator",
25
- "scss",
26
- "react-native",
27
- "css",
28
- "design-system",
29
- "utilities",
30
- "responsive-design",
31
- "fullstackunicorn"
32
- ],
33
- "sideEffects": [
34
- "index.cmd.js"
35
- ],
36
- "imports": {
37
- "#@": "./",
38
- "#@/*": "./*"
39
- },
40
- "scripts": {
41
- "cmd": "chmod +x ./config.cmd.sh && ./config.cmd.sh",
42
- "test": "exit 1"
43
- },
44
- "dependencies": {
45
- "@fullstackunicorn/filesystem": "^1.0.4",
46
- "@fullstackunicorn/initialize": "^1.0.7",
47
- "glob": "^13.0.0",
48
- "sass": "^1.96.0"
49
- },
50
- "devDependencies": {
51
- "@fullstackunicorn/cli": "^1.0.3",
52
- "@fullstackunicorn/reduce": "^1.0.19"
53
- }
54
- }
2
+ "version": "1.1.0",
3
+ "name": "@fullstackunicorn/style",
4
+ "author": "lucanigido (https://fullstackunicorn.dev/author/lucanigido)",
5
+ "description": "A development utility for generating responsive web and native styles (CSS, SCSS, JS, RN) from a declarative style.config.js file.",
6
+ "license": "MIT",
7
+ "type": "module",
8
+ "packageManager": "yarn@4.18.1",
9
+ "readme": "package.md",
10
+ "main": "index.js",
11
+ "files": [
12
+ "index.js",
13
+ "index.dep.js",
14
+ "modules/",
15
+ "package.md"
16
+ ],
17
+ "bin": "./index.cmd.js",
18
+ "repository": {
19
+ "type": "git",
20
+ "url": "https://gitlab.com/fullstackunicorn/style.git"
21
+ },
22
+ "keywords": [
23
+ "style-generator",
24
+ "scss",
25
+ "react-native",
26
+ "css",
27
+ "design-system",
28
+ "utilities",
29
+ "responsive-design",
30
+ "fullstackunicorn"
31
+ ],
32
+ "sideEffects": [
33
+ "index.cmd.js"
34
+ ],
35
+ "imports": {
36
+ "#@": "./",
37
+ "#@/*": "./*"
38
+ },
39
+ "scripts": {
40
+ "test": "node --test tests/*.test.js"
41
+ },
42
+ "dependencies": {
43
+ "@fullstackunicorn/filesystem": "^1.0.4",
44
+ "@fullstackunicorn/initialize": "^1.0.7",
45
+ "glob": "^13.0.0",
46
+ "sass": "^1.96.0"
47
+ },
48
+ "devDependencies": {
49
+ "@fullstackunicorn/cli": "^1.0.3",
50
+ "@fullstackunicorn/reduce": "^1.0.19"
51
+ }
52
+ }
package/package.md ADDED
@@ -0,0 +1,261 @@
1
+ # @fullstackunicorn/style
2
+
3
+ `SOURCE_PATHS` optionally adds explicit source roots to the normal project scan. This is used when shared components live in an installed package; nested dependencies remain excluded.
4
+
5
+ Version 1.1.0 also resolves computed utility keys such as
6
+ ``s[`paddingX${geometry.page.padding}`]`` from the project's
7
+ `configure/geometry.js`. `BASE_PATH` identifies that project even when
8
+ `SOURCE_PATHS` includes installed shared components. The static leaf declares
9
+ objects and literal values with `const` and property assignments, then exports
10
+ `{ geometry }`; imports, calls and environment-dependent expressions are rejected.
11
+ It is parsed once per project scan, without executing application code. Existing
12
+ literal utility classes continue to work without a Geometry file.
13
+
14
+ Computed keys must resolve to an existing Style utility exactly. Missing paths,
15
+ unsupported expressions and unknown keys fail the build. Decimal and negative
16
+ utility tokens retain their existing spelling, such as `2d5` and `4n`; the parser
17
+ does not silently rewrite a numeric interpolation into a different runtime key.
18
+
19
+ A cross‑platform styling engine for Web and React Native.
20
+ It generates unified utility classes, directional rules, responsive ratios, color‑mode styles, and typography maps — all from a single configuration file.
21
+
22
+ Designed for use inside FullstackUnicorn projects, but fully usable as a standalone styling system.
23
+
24
+ ## 📦 Installation
25
+
26
+ ```bash
27
+ yarn add @fullstackunicorn/style
28
+ ```
29
+
30
+ ## 🧩 Usage
31
+
32
+ Create a `style.config.js` file in the root folder of the project:
33
+
34
+ ```js
35
+ export default {
36
+
37
+ // BASE PATH:
38
+ BASE_PATH: './',
39
+
40
+ // PLATFORM:
41
+ isWeb: true,
42
+ isNative: false,
43
+
44
+ // SATURATION: 0 16 32 48 64 80 96 112 128 144 160 176 192 208 224 240 255
45
+ saturation: 128,
46
+
47
+ // HUES: ONE channel must be ZERO
48
+ hues: {
49
+ C1: { R: 0, G: 128, B: 256, name: 'blue' },
50
+ C2: { R: 256, G: 128, B: 0, name: 'orange' },
51
+ C3: { R: 256, G: 0, B: 128, name: 'pink' },
52
+ },
53
+
54
+ // STATIC HUES NOT AFFECTED BY SATURATION
55
+ staticHues: {
56
+ RR: { R: 256, G: 0, B: 0, name: 'error' },
57
+ OR: { R: 256, G: 128, B: 0, name: 'warning' },
58
+ },
59
+
60
+ // SET THE DEFAULTS FONTS FOR EACH PLATFORM
61
+ // SET THE FONTS FOR EACH ALPHABET
62
+ // ANY FONT MENTIONED IN THE ALPHABETH (es. f1, m1) MUST HAVE A DEFAULT (fallback)
63
+ fontFamily: {
64
+ html: `html { font-family: 'sans-serif'; font-weight: 400; };`,
65
+ defaults: {
66
+ f1: {
67
+ ios: 'System',
68
+ android: 'sans-serif',
69
+ web: 'sans-serif'
70
+ },
71
+ m1: {
72
+ ios: 'Courier New',
73
+ android: 'monospace',
74
+ web: 'monospace'
75
+ }
76
+ },
77
+ fonts: {
78
+ latin: {
79
+ f1: 'OpenSans',
80
+ m1: 'Inconsolata'
81
+ },
82
+ cyrillic: {
83
+ f1: 'OpenSans',
84
+ },
85
+ greek: {
86
+ f1: 'OpenSans',
87
+ },
88
+ arabic: {
89
+ f1: 'OpenSans',
90
+ },
91
+ chinese: {
92
+ f1: 'OpenSans',
93
+ },
94
+ japanese: {
95
+ f1: 'OpenSans',
96
+ },
97
+ }
98
+ },
99
+
100
+ // DEFAULT SASS
101
+ defaultSass:
102
+ `* {
103
+ padding:0;
104
+ margin:0;
105
+ border:0;
106
+ outline:none;
107
+ background-color:unset;
108
+ text-decoration:none;
109
+ box-sizing:border-box;
110
+ cursor:default;
111
+ // user-select: none;
112
+ };
113
+
114
+ html, body { max-width:100vw; overflow-x:hidden }
115
+
116
+ body { margin:0; padding:0 }
117
+
118
+ img { overflow-clip-margin:border-box; overflow:clip }
119
+
120
+ a {
121
+ &:link {color:unset; text-decoration: none}
122
+ &:visited {color:unset; text-decoration: none}
123
+ &:link:active {color:unset; text-decoration: none}
124
+ &:visited:active {color:unset; text-decoration: none}
125
+ };
126
+
127
+ h1, h2, h3, h4, h5, h6, p, a, span, input, textarea, option, button {
128
+ margin-block-start: 0;
129
+ margin-block-end: 0;
130
+ margin-inline-start: 0;
131
+ margin-inline-end: 0;
132
+ };`
133
+
134
+ }
135
+ ```
136
+
137
+ Generate styles:
138
+
139
+ ```bash
140
+ yarn style
141
+ ```
142
+
143
+ This will output a `/style/` folder containing:
144
+
145
+ ```
146
+ /style
147
+ ├── @use.js
148
+ ├── @use.scss
149
+ ├── web_styles.scss
150
+ ├── native_styles.js
151
+ ├── fonts.js
152
+ └── ...
153
+ ```
154
+
155
+ ## 🖥 Web and React Native Integration
156
+
157
+ Ensure you create in the root folder of the project the templates folder and index.js
158
+
159
+ ```
160
+ /templates
161
+ ├── index.js
162
+ └── ...
163
+ ```
164
+
165
+ You can add as many blocks of styles you wish and later reuse it
166
+
167
+ ```js
168
+
169
+ export const templates = (s, c, t) => {
170
+
171
+ t.server = getServer(s,c,t)
172
+
173
+ t.page = {} // create a template for the pages
174
+ t.page.home = [s.col, s.XYc]
175
+ t.page.fluid = [s.col, s.XYc]
176
+ t.page.fixed = [s.col_cXsY, s.Yc, s.Xx, s.Xmax540, s.paddingX16]
177
+ t.page.docs = [s.col_cXsY, s.Yc, s.Xx, s.Xmax540, s.paddingX16, s.marginT16]
178
+ t.page.card = [s.col_cX, s.Yc, s.paddingX16]
179
+
180
+ return t
181
+ }
182
+ ```
183
+
184
+ In each component import useStyle
185
+
186
+ ```js
187
+ import { useStyle } from '#@/style/@use.js'
188
+ import { View } from '#@/imports/core/View.js'
189
+
190
+ export const BoxPod = ({ children }) => {
191
+
192
+ const { s, c, f, t, F, B, S, I, H } = useStyle()
193
+
194
+ S.box = [t.page.home, s.marginB16, c.base_C1_W600]
195
+
196
+ return (
197
+ <View classes={S.box}>
198
+ {children}
199
+ </View>
200
+ )
201
+ }
202
+ ```
203
+
204
+ The View component should have the same interface for Web and Native, but in Native environment the Native component will be rendered and in Web environments the Web component will be rendered
205
+
206
+ Web Component
207
+ ```js
208
+ export const View = ({
209
+ classes = [], inline = {}, children,
210
+ viewRef = null, setIsHover = () => { } }) => {
211
+ return (
212
+ <div className={classes.join(' ')} style={inline}
213
+ ref={viewRef}
214
+ onMouseEnter={() => setIsHover(true)}
215
+ onMouseLeave={() => setIsHover(false)}
216
+ >
217
+ {children}
218
+ </div>
219
+ )
220
+ }
221
+ ```
222
+
223
+ Native Component
224
+ ```js
225
+ import { View as NativeView, Pressable as NativePressable, Platform } from 'react-native'
226
+
227
+ export const View = ({ classes = [], inline = {}, children, viewRef, setIsHover }) => {
228
+
229
+ const props = {}
230
+ props.style = [...classes, inline]
231
+ props.ref = viewRef
232
+
233
+ if (F3.isFnc(setIsHover)) {
234
+
235
+ props.onPressIn = () => setIsHover(true);
236
+ props.onPressOut = () => setIsHover(false);
237
+ return <NativePressable {...props}>{children}</NativePressable>
238
+ }
239
+
240
+ return <NativeView {...props}>{children}</NativeView>
241
+
242
+ }
243
+ ```
244
+
245
+ ## 🧪 Generated Classes
246
+
247
+ ### Example utilities
248
+
249
+ | Utility | Meaning |
250
+ |--------|----------|
251
+ | `s.margin16` | margin 16 |
252
+ | `s.padding8` | padding 8 |
253
+ | `s.row` | display flex, flex-direction row |
254
+ | `s.gap12` | gap 12 |
255
+ | `s.radius4` | border-radius 4 |
256
+ | `s.ratio1` | 1/1 square ratio |
257
+ | `s.ratio_X16Y9` | 16/9 layout ratio |
258
+
259
+ ## 🪪 License
260
+
261
+ MIT © fullstackunicorn.dev