@astryxdesign/cli 0.7.14-canary.gfb823d9 → 0.7.14
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 +197 -0
- package/api/component/_adapter.d.mts +15 -0
- package/api/component/_adapter.mjs +76 -0
- package/api/component/component.mjs +8 -1
- package/api/search/_named-keywords.d.mts +31 -0
- package/api/search/_named-keywords.mjs +177 -0
- package/api/search/search-index.mjs +8 -1
- package/api/search/search.d.mts +6 -1
- package/api/search/search.mjs +49 -8
- package/api/theme/_adapter.d.mts +33 -0
- package/api/theme/_adapter.mjs +352 -16
- package/api/theme/build/build.mjs +261 -10
- package/api/theme/eject/eject.mjs +13 -1
- package/api/theme/list/list.mjs +11 -2
- package/api/theme/palette/generate/color.d.mts +2 -0
- package/api/theme/palette/generate/color.mjs +1 -1
- package/api/theme/template/template.mjs +139 -6
- package/api/theme/theme.type.d.mts +15 -1
- package/api/theme/theme.type.mjs +9 -3
- package/api/theme/themeAdd.doc.mjs +1 -1
- package/api/theme/themeBuild.doc.mjs +10 -2
- package/api/theme/themeEject.doc.mjs +2 -2
- package/api/theme/themeListAvailable.doc.mjs +1 -1
- package/api/theme/themeRemove.doc.mjs +1 -1
- package/api/theme/themeTemplate.doc.mjs +8 -0
- package/api/theme/themeUse.doc.mjs +1 -1
- package/api/theme-edit/_adapter.d.mts +36 -2
- package/api/theme-edit/_adapter.mjs +340 -12
- package/api/theme-edit/_check.d.mts +28 -25
- package/api/theme-edit/_check.mjs +876 -308
- package/api/theme-edit/_color.d.mts +53 -4
- package/api/theme-edit/_color.mjs +406 -79
- package/api/theme-edit/_compiler.d.mts +14 -6
- package/api/theme-edit/_compiler.mjs +89 -59
- package/api/theme-edit/_context.d.mts +28 -8
- package/api/theme-edit/_context.mjs +142 -19
- package/api/theme-edit/_edit.d.mts +3 -1
- package/api/theme-edit/_edit.mjs +746 -76
- package/api/theme-edit/_how-commands.d.mts +91 -0
- package/api/theme-edit/_how-commands.mjs +269 -0
- package/api/theme-edit/_how-question.d.mts +57 -0
- package/api/theme-edit/_how-question.mjs +2574 -0
- package/api/theme-edit/_how.d.mts +27 -8
- package/api/theme-edit/_how.mjs +776 -175
- package/api/theme-edit/_overview.d.mts +9 -0
- package/api/theme-edit/_overview.mjs +296 -0
- package/api/theme-edit/_palette.d.mts +155 -15
- package/api/theme-edit/_palette.mjs +1446 -262
- package/api/theme-edit/_parts.mjs +61 -5
- package/api/theme-edit/_png.d.mts +18 -6
- package/api/theme-edit/_png.mjs +135 -25
- package/api/theme-edit/_preview-app.d.mts +32 -11
- package/api/theme-edit/_preview-app.mjs +1976 -285
- package/api/theme-edit/_preview.d.mts +39 -8
- package/api/theme-edit/_preview.mjs +367 -41
- package/api/theme-edit/_settings.d.mts +147 -11
- package/api/theme-edit/_settings.mjs +908 -99
- package/api/theme-edit/_tables.d.mts +4 -16
- package/api/theme-edit/_tables.mjs +51 -117
- package/api/theme-edit/theme-edit.type.d.mts +102 -66
- package/api/theme-edit/theme-edit.type.mjs +58 -40
- package/api/theme-edit/themeEditHow.doc.mjs +17 -6
- package/api/theme-edit/themeEditNew.doc.mjs +21 -5
- package/api/theme-edit/themeEditPreviewAdd.doc.mjs +18 -5
- package/api/theme-edit/themeEditPreviewApp.doc.mjs +12 -9
- package/api/theme-edit/themeEditPreviewList.doc.mjs +11 -2
- package/api/theme-edit/themeEditPreviewRemove.doc.mjs +29 -3
- package/api/theme-edit/themeEditSet.doc.mjs +14 -8
- package/api/theme-edit/themeEditShow.doc.mjs +10 -5
- package/api/theme-edit/themeEditUndo.doc.mjs +9 -4
- package/assets/discover/official-packages.json +4 -0
- package/assets/docs/tree/icon-sets.doc.mjs +3 -3
- package/assets/docs.generated.json +1 -0
- package/assets/icons/definitions/bookmarkAdd.doc.mjs +9 -0
- package/assets/icons/definitions/documentSearch.doc.mjs +9 -0
- package/assets/icons/definitions/keyboard.doc.mjs +9 -0
- package/assets/icons/definitions/paintBrush.doc.mjs +9 -0
- package/assets/icons/definitions/wallet.doc.mjs +9 -0
- package/assets/preview-app/gitignore +3 -0
- package/assets/templates/blocks/components/ButtonGroup/ButtonGroupShowcase.doc.mjs +1 -1
- package/assets/templates/blocks/components/Lightbox/LightboxGallery.tsx +1 -1
- package/assets/templates/components.generated.json +1 -0
- package/assets/templates/pages/gallery-hero/page.tsx +8 -2
- package/assets/templates/pages/settings-dialog/template.doc.mjs +3 -3
- package/assets/templates/pages/side-gallery/page.tsx +1 -1
- package/assets/templates/pages/table-filter/template.doc.mjs +2 -2
- package/assets/templates/pages/theme-showcase/template.doc.mjs +1 -1
- package/clients/cli/bin/astryx.mjs +37 -5
- package/clients/cli/commands/experimental/theme.mjs +422 -57
- package/clients/cli/commands/experimental-theme-editor-how.doc.mjs +22 -9
- package/clients/cli/commands/experimental-theme-editor-new.doc.mjs +103 -4
- package/clients/cli/commands/experimental-theme-editor-set.doc.mjs +13 -8
- package/clients/cli/commands/experimental-theme-editor-show.doc.mjs +5 -5
- package/clients/cli/commands/experimental-theme-editor-undo.doc.mjs +5 -5
- package/clients/cli/commands/experimental-theme-editor.doc.mjs +1 -1
- package/clients/cli/commands/experimental-theme-preview-add.doc.mjs +3 -2
- package/clients/cli/commands/experimental-theme-preview-app.doc.mjs +2 -8
- package/clients/cli/commands/experimental-theme-preview-list.doc.mjs +2 -2
- package/clients/cli/commands/experimental-theme-preview-remove.doc.mjs +2 -2
- package/clients/cli/commands/experimental-theme-targets.doc.mjs +1 -1
- package/clients/cli/commands/experimental-theme.doc.mjs +3 -4
- package/clients/cli/commands/theme-build.doc.mjs +1 -1
- package/clients/cli/commands/theme-eject.doc.mjs +3 -3
- package/clients/cli/commands/theme-remove.doc.mjs +2 -2
- package/clients/cli/commands/theme-template.doc.mjs +11 -4
- package/clients/cli/commands/theme.mjs +145 -46
- package/clients/cli/commands.generated.json +1 -0
- package/clients/cli/index.mjs +96 -5
- package/clients/cli/lib/json-shim.mjs +29 -1
- package/foundation/config/project.d.mts +16 -2
- package/foundation/config/project.mjs +40 -6
- package/foundation/config/theme-state.d.mts +9 -0
- package/foundation/config/theme-state.mjs +20 -1
- package/foundation/discovery/template-adapter.d.mts +12 -1
- package/foundation/discovery/template-adapter.mjs +29 -4
- package/foundation/discovery/template-icons.d.mts +13 -0
- package/foundation/discovery/template-icons.mjs +76 -0
- package/foundation/discovery/template-needs.d.mts +7 -0
- package/foundation/discovery/template-needs.mjs +117 -8
- package/foundation/discovery/template-source-tree.d.mts +5 -1
- package/foundation/discovery/template-source-tree.mjs +6 -4
- package/foundation/discovery/theme-discovery.d.mts +14 -3
- package/foundation/discovery/theme-discovery.mjs +45 -12
- package/foundation/doc-compiler/import.mjs +68 -3
- package/foundation/doc-compiler/stored-docs.d.mts +27 -0
- package/foundation/doc-compiler/stored-docs.mjs +65 -0
- package/foundation/fs/fs-error.d.mts +17 -0
- package/foundation/fs/fs-error.mjs +34 -0
- package/foundation/response/error-codes.d.mts +3 -1
- package/foundation/response/error-codes.doc.mjs +13 -1
- package/foundation/response/error-codes.mjs +11 -1
- package/foundation/response/response-types.doc.mjs +6 -6
- package/package.json +6 -7
- package/clients/cli/commands/experimental-theme-palette-generate.doc.mjs +0 -73
- package/clients/cli/commands/experimental-theme-palette.doc.mjs +0 -37
|
@@ -10,20 +10,25 @@
|
|
|
10
10
|
* @position api/theme-edit — storage and compile for the theme commands
|
|
11
11
|
*/
|
|
12
12
|
|
|
13
|
+
import {createHash} from 'node:crypto';
|
|
13
14
|
import * as fs from 'node:fs';
|
|
14
15
|
import * as path from 'node:path';
|
|
15
16
|
import {pathToFileURL} from 'node:url';
|
|
17
|
+
import {cliVersion} from '../../foundation/release/run-context.mjs';
|
|
16
18
|
import {AstryxError} from '../error.mjs';
|
|
17
19
|
import {logger} from '../logger.mjs';
|
|
18
20
|
import {ERROR_CODES} from '../../foundation/response/error-codes.mjs';
|
|
21
|
+
import {levenshteinDistance} from '../../foundation/text/levenshtein.mjs';
|
|
19
22
|
import {themeBuildForReport} from '../theme/build/build.mjs';
|
|
20
23
|
import {
|
|
21
24
|
AUTO_SPREAD,
|
|
22
25
|
CORNERS,
|
|
26
|
+
DIALS,
|
|
23
27
|
FAMILIES,
|
|
24
28
|
FONTS,
|
|
25
29
|
HEADING_TRACKING,
|
|
26
30
|
HEADING_WEIGHTS,
|
|
31
|
+
LIKE,
|
|
27
32
|
OPEN_FONTS,
|
|
28
33
|
P,
|
|
29
34
|
SPACING,
|
|
@@ -33,12 +38,23 @@ import {
|
|
|
33
38
|
TYPE_STYLES,
|
|
34
39
|
familyOf,
|
|
35
40
|
} from './_tables.mjs';
|
|
36
|
-
import {
|
|
41
|
+
import {
|
|
42
|
+
alphaOf,
|
|
43
|
+
compositeOver,
|
|
44
|
+
isColorValue,
|
|
45
|
+
isSafeValue,
|
|
46
|
+
isSize,
|
|
47
|
+
parseColor,
|
|
48
|
+
ratio,
|
|
49
|
+
} from './_color.mjs';
|
|
37
50
|
import {
|
|
38
51
|
PALETTE_DIALS,
|
|
39
|
-
|
|
52
|
+
assertNoPlaceholder,
|
|
53
|
+
paletteImport,
|
|
40
54
|
paletteMapping,
|
|
41
55
|
syncPalette,
|
|
56
|
+
syncPaletteRefs,
|
|
57
|
+
writeWhole,
|
|
42
58
|
} from './_palette.mjs';
|
|
43
59
|
import {MODAL} from './_compiler.mjs';
|
|
44
60
|
import {baseResolved, baseThemeFile} from './_project.mjs';
|
|
@@ -49,7 +65,7 @@ import {baseResolved, baseThemeFile} from './_project.mjs';
|
|
|
49
65
|
* @property {string} thing - A dial, a token (`--color-accent`), or a CSS property.
|
|
50
66
|
* @property {string} value
|
|
51
67
|
* @property {'dial' | 'token' | 'property'} source
|
|
52
|
-
* @property {string} [on] - A part, a
|
|
68
|
+
* @property {string} [on] - A part, a group, or a typography role (font).
|
|
53
69
|
* @property {string} [when] - `<prop>:<value>`.
|
|
54
70
|
* @property {string} [state]
|
|
55
71
|
* @property {'light' | 'dark'} [mode]
|
|
@@ -66,17 +82,30 @@ import {baseResolved, baseThemeFile} from './_project.mjs';
|
|
|
66
82
|
* @property {'both' | 'light-only' | 'dark-only'} mode
|
|
67
83
|
* @property {Setting[]} settings
|
|
68
84
|
* @property {string[]} [lifted] - Variant keys the last build repeated a part setting on.
|
|
85
|
+
* @property {string} [palette] - The hash of the palette.config.json the editor last wrote.
|
|
69
86
|
*/
|
|
70
87
|
|
|
71
|
-
/** @typedef {{project: import('./_project.mjs').ThemeProject, C: import('./_compiler.mjs').Compiler}} Ctx */
|
|
88
|
+
/** @typedef {{project: import('./_project.mjs').ThemeProject, C: import('./_compiler.mjs').Compiler, unchecked?: string | null, wrote?: Map<string, string | null>, base?: {light: Record<string, string>, dark: Record<string, string>}}} Ctx */
|
|
89
|
+
/** @typedef {import('./_parts.mjs').PaintSide} PaintSide */
|
|
90
|
+
/** @typedef {import('./_parts.mjs').TextPair} TextPair */
|
|
72
91
|
|
|
73
|
-
/**
|
|
74
|
-
export const
|
|
92
|
+
/** What a theme name may be, in words. */
|
|
93
|
+
export const NAME_RULE =
|
|
94
|
+
'lowercase letters, digits and dashes, starting with a letter, 64 characters at most';
|
|
95
|
+
|
|
96
|
+
/** A theme name: lowercase letters, digits and dashes, starting with a letter, 64 characters at most. @param {string} s */
|
|
97
|
+
export const slugOk = s =>
|
|
98
|
+
typeof s === 'string' && s.length <= 64 && /^[a-z][a-z0-9-]*$/.test(s);
|
|
75
99
|
/** @param {string} s */
|
|
76
100
|
export const kebab = s =>
|
|
77
101
|
s.replace(/([a-z0-9])([A-Z])/g, '$1-$2').toLowerCase();
|
|
78
|
-
/**
|
|
79
|
-
|
|
102
|
+
/**
|
|
103
|
+
* A theme name as an identifier: each dash goes, and the letter after it is
|
|
104
|
+
* capitalized (`brand-2` → `brand2`, `x--y` → `xY`).
|
|
105
|
+
* @param {string} s
|
|
106
|
+
*/
|
|
107
|
+
export const camel = s =>
|
|
108
|
+
s.replace(/-+([a-z0-9])?/g, (_, c) => (c ? c.toUpperCase() : ''));
|
|
80
109
|
/** Quote a value for a suggested command. @param {unknown} v */
|
|
81
110
|
export const q = v =>
|
|
82
111
|
/[\s"#(]/.test(String(v)) ? `"${String(v).replace(/"/g, '\\"')}"` : String(v);
|
|
@@ -108,24 +137,6 @@ export function themeFiles(cwd, slug) {
|
|
|
108
137
|
export const shown = (cwd, f) =>
|
|
109
138
|
path.relative(cwd, f).split(path.sep).join('/');
|
|
110
139
|
|
|
111
|
-
/** @param {string} a @param {string} b */
|
|
112
|
-
function lev(a, b) {
|
|
113
|
-
const d = Array.from({length: a.length + 1}, (_, i) => [
|
|
114
|
-
i,
|
|
115
|
-
...Array(b.length).fill(0),
|
|
116
|
-
]);
|
|
117
|
-
for (let j = 1; j <= b.length; j++) d[0][j] = j;
|
|
118
|
-
for (let i = 1; i <= a.length; i++) {
|
|
119
|
-
for (let j = 1; j <= b.length; j++)
|
|
120
|
-
d[i][j] = Math.min(
|
|
121
|
-
d[i - 1][j] + 1,
|
|
122
|
-
d[i][j - 1] + 1,
|
|
123
|
-
d[i - 1][j - 1] + (a[i - 1] === b[j - 1] ? 0 : 1),
|
|
124
|
-
);
|
|
125
|
-
}
|
|
126
|
-
return d[a.length][b.length];
|
|
127
|
-
}
|
|
128
|
-
|
|
129
140
|
/**
|
|
130
141
|
* Up to `n` names close to `x`.
|
|
131
142
|
* @param {string} x
|
|
@@ -139,7 +150,7 @@ export function nearest(x, list, n = 3) {
|
|
|
139
150
|
c =>
|
|
140
151
|
/** @type {[string, number]} */ ([
|
|
141
152
|
c,
|
|
142
|
-
c.includes(x) || x.includes(c) ? 1 :
|
|
153
|
+
c.includes(x) || x.includes(c) ? 1 : levenshteinDistance(x, c),
|
|
143
154
|
]),
|
|
144
155
|
)
|
|
145
156
|
.filter(([, s]) => s <= Math.max(2, Math.floor(x.length / 3)))
|
|
@@ -184,15 +195,29 @@ export function refuse(code, message, extra = {}) {
|
|
|
184
195
|
* The settings of a theme, or a refusal naming the command that makes it.
|
|
185
196
|
* @param {string} cwd
|
|
186
197
|
* @param {string} slug
|
|
198
|
+
* @param {string} [skip] the thing a command changes or removes: its value
|
|
199
|
+
* is not checked, so a value made under looser rules can be fixed
|
|
187
200
|
* @returns {ThemeData}
|
|
188
201
|
*/
|
|
189
|
-
export function loadTheme(cwd, slug) {
|
|
190
|
-
if (!slugOk(slug))
|
|
202
|
+
export function loadTheme(cwd, slug, skip = '') {
|
|
203
|
+
if (!slugOk(slug)) {
|
|
204
|
+
// A path or a capital letter typed for a theme that exists names it.
|
|
205
|
+
const plain = String(slug ?? '')
|
|
206
|
+
.toLowerCase()
|
|
207
|
+
.replace(/^.*themes[\\/]/, '')
|
|
208
|
+
.replace(/[\\/].*$/, '');
|
|
209
|
+
const same =
|
|
210
|
+
slugOk(plain) && fs.existsSync(themeFiles(cwd, plain).settings)
|
|
211
|
+
? plain
|
|
212
|
+
: null;
|
|
191
213
|
refuse(
|
|
192
214
|
ERROR_CODES.ERR_INVALID_ARGUMENT,
|
|
193
|
-
`"${slug ?? ''}" is not a theme name (
|
|
194
|
-
|
|
215
|
+
`"${String(slug ?? '').slice(0, 80)}" is not a theme name (${NAME_RULE}).`,
|
|
216
|
+
same
|
|
217
|
+
? {didYouMean: [same], run: [`${P} show ${same}`]}
|
|
218
|
+
: {run: [`${P} new my-theme`]},
|
|
195
219
|
);
|
|
220
|
+
}
|
|
196
221
|
const f = themeFiles(cwd, slug);
|
|
197
222
|
if (!fs.existsSync(f.settings)) {
|
|
198
223
|
const have = fs.existsSync(f.root)
|
|
@@ -200,21 +225,196 @@ export function loadTheme(cwd, slug) {
|
|
|
200
225
|
.readdirSync(f.root)
|
|
201
226
|
.filter(d => fs.existsSync(themeFiles(cwd, d).settings))
|
|
202
227
|
: [];
|
|
228
|
+
// A typed path or case of a theme that exists names that theme.
|
|
229
|
+
const plain = String(slug)
|
|
230
|
+
.toLowerCase()
|
|
231
|
+
.replace(/^.*themes[\\/]/, '')
|
|
232
|
+
.replace(/[\\/].*$/, '');
|
|
233
|
+
const same = have.includes(plain) ? plain : null;
|
|
203
234
|
refuse(
|
|
204
235
|
ERROR_CODES.ERR_UNKNOWN_THEME,
|
|
205
236
|
`There is no theme "${slug}" made by this command (no themes/${slug}/${slug}.settings.json).`,
|
|
206
|
-
{
|
|
237
|
+
{
|
|
238
|
+
didYouMean: same ? [same] : nearest(slug, have),
|
|
239
|
+
run: same ? [`${P} show ${same}`] : [`${P} new ${slug}`],
|
|
240
|
+
},
|
|
207
241
|
);
|
|
208
242
|
}
|
|
243
|
+
refuseLinks(cwd, slug);
|
|
244
|
+
// undo is offered only when there is a step to go back to.
|
|
245
|
+
const steps = readHistory(f.history).steps.length;
|
|
246
|
+
const recover = steps
|
|
247
|
+
? {
|
|
248
|
+
text: `, or step back to the settings before the last change with ${P} undo ${slug} (the last change is then lost)`,
|
|
249
|
+
run: [{name: `${P} undo ${slug}`, reason: 'do this instead'}],
|
|
250
|
+
}
|
|
251
|
+
: {text: '; there is no earlier step to go back to', run: []};
|
|
252
|
+
/** @type {any} */
|
|
253
|
+
let data;
|
|
209
254
|
try {
|
|
210
|
-
|
|
255
|
+
data = JSON.parse(
|
|
256
|
+
fs.readFileSync(f.settings, 'utf8').replace(/^\uFEFF/, ''),
|
|
257
|
+
);
|
|
211
258
|
} catch (e) {
|
|
212
259
|
throw new AstryxError(
|
|
213
|
-
`themes/${slug}/${slug}.settings.json is not valid JSON (${e instanceof Error ? e.message : String(e)}). Fix it by hand
|
|
214
|
-
|
|
260
|
+
`themes/${slug}/${slug}.settings.json is not valid JSON (${e instanceof Error ? e.message : String(e)}). Fix it by hand${recover.text}.`,
|
|
261
|
+
recover.run,
|
|
215
262
|
ERROR_CODES.ERR_THEME_INVALID,
|
|
216
263
|
);
|
|
217
264
|
}
|
|
265
|
+
const problem = settingsProblem(data, skip);
|
|
266
|
+
// A value made under looser rules is not damage: the command that
|
|
267
|
+
// changes or removes that setting still works.
|
|
268
|
+
const bad = problem ? badSetting(data) : null;
|
|
269
|
+
if (problem && bad && settingsProblem(data, bad.thing) !== problem) {
|
|
270
|
+
// A value it takes, for a dial; a color for a color token.
|
|
271
|
+
const example = DIALS[bad.thing]
|
|
272
|
+
? DIALS[bad.thing].values.split('|').find(w => !w.startsWith('<'))
|
|
273
|
+
: bad.thing.startsWith('--color-')
|
|
274
|
+
? '#1f2937'
|
|
275
|
+
: null;
|
|
276
|
+
throw new AstryxError(
|
|
277
|
+
`themes/${slug}/${slug}.settings.json: ${problem}, a value the editor no longer accepts. Remove or change that setting; nothing else needs to change. Nothing was changed.`,
|
|
278
|
+
[
|
|
279
|
+
{name: `${P} undo ${slug} ${undoArgs(bad)}`, reason: 'do this instead'},
|
|
280
|
+
...(example
|
|
281
|
+
? [
|
|
282
|
+
{
|
|
283
|
+
name: `${P} set ${slug} ${undoArgs(bad).replace(bad.thing, `${bad.thing} ${q(example)}`)}`,
|
|
284
|
+
reason: 'or give it a value it takes',
|
|
285
|
+
},
|
|
286
|
+
]
|
|
287
|
+
: []),
|
|
288
|
+
],
|
|
289
|
+
ERROR_CODES.ERR_THEME_INVALID,
|
|
290
|
+
);
|
|
291
|
+
}
|
|
292
|
+
if (problem)
|
|
293
|
+
throw new AstryxError(
|
|
294
|
+
`themes/${slug}/${slug}.settings.json: ${problem}. Fix it by hand${recover.text}. Nothing was changed.`,
|
|
295
|
+
recover.run,
|
|
296
|
+
ERROR_CODES.ERR_THEME_INVALID,
|
|
297
|
+
);
|
|
298
|
+
return data;
|
|
299
|
+
}
|
|
300
|
+
|
|
301
|
+
/**
|
|
302
|
+
* What is wrong with settings data, or null: its shape, and each value with
|
|
303
|
+
* the same rules `set` checks it by (without the installed Core), so a value
|
|
304
|
+
* edited by hand never reaches the build.
|
|
305
|
+
* @param {any} data
|
|
306
|
+
* @param {string} [skip] a thing whose value is not checked (the one a
|
|
307
|
+
* command is about to change or remove)
|
|
308
|
+
* @returns {string | null}
|
|
309
|
+
*/
|
|
310
|
+
export function settingsProblem(data, skip = '') {
|
|
311
|
+
if (!data || typeof data !== 'object' || Array.isArray(data))
|
|
312
|
+
return 'the file is not a settings object';
|
|
313
|
+
if (!['both', 'light-only', 'dark-only'].includes(data.mode))
|
|
314
|
+
return `mode "${data.mode}" is not both, light-only or dark-only`;
|
|
315
|
+
if (data.like != null && !LIKE.includes(data.like))
|
|
316
|
+
return `base "${data.like}" is not a built-in theme (${LIKE.join(', ')})`;
|
|
317
|
+
if (!Array.isArray(data.settings)) return 'settings is not a list';
|
|
318
|
+
const keys = new Set();
|
|
319
|
+
for (const s of data.settings) {
|
|
320
|
+
if (!s || typeof s.thing !== 'string' || typeof s.value !== 'string')
|
|
321
|
+
return 'a setting has no thing or value';
|
|
322
|
+
if (!['dial', 'token', 'property'].includes(s.source))
|
|
323
|
+
return `${s.thing} has no source (dial, token or property)`;
|
|
324
|
+
for (const k of ['on', 'when', 'state'])
|
|
325
|
+
if (s[k] != null && typeof s[k] !== 'string')
|
|
326
|
+
return `${s.thing} has a ${k} that is not a word`;
|
|
327
|
+
if (s.mode != null && s.mode !== 'light' && s.mode !== 'dark')
|
|
328
|
+
return `${s.thing} has mode "${s.mode}"`;
|
|
329
|
+
const key = keyOf(s);
|
|
330
|
+
if (keys.has(key)) return `${describe(s)} is listed twice`;
|
|
331
|
+
keys.add(key);
|
|
332
|
+
if (s.thing === skip) continue;
|
|
333
|
+
const problem = valueProblem(s);
|
|
334
|
+
if (problem) return problem;
|
|
335
|
+
}
|
|
336
|
+
return null;
|
|
337
|
+
}
|
|
338
|
+
|
|
339
|
+
/**
|
|
340
|
+
* The words that name a setting for `undo`.
|
|
341
|
+
* @param {import('./_settings.mjs').Setting} x
|
|
342
|
+
*/
|
|
343
|
+
export function undoArgs(x) {
|
|
344
|
+
return [
|
|
345
|
+
x.thing,
|
|
346
|
+
...(x.on ? [`--on ${x.on}`] : []),
|
|
347
|
+
...(x.when ? [`--when ${x.when}`] : []),
|
|
348
|
+
...(x.state ? [`--state ${x.state}`] : []),
|
|
349
|
+
...(x.mode ? [`--mode ${x.mode}`] : []),
|
|
350
|
+
...(x.only ? ['--only'] : []),
|
|
351
|
+
].join(' ');
|
|
352
|
+
}
|
|
353
|
+
|
|
354
|
+
/**
|
|
355
|
+
* The first setting whose only problem is its value (made under looser
|
|
356
|
+
* rules): `undo <theme> <undoArgs>` removes it.
|
|
357
|
+
* @param {any} data
|
|
358
|
+
* @returns {Setting | null}
|
|
359
|
+
*/
|
|
360
|
+
export function badSetting(data) {
|
|
361
|
+
for (const s of Array.isArray(data?.settings) ? data.settings : [])
|
|
362
|
+
if (s && typeof s.thing === 'string' && valueProblem(s)) return s;
|
|
363
|
+
return null;
|
|
364
|
+
}
|
|
365
|
+
|
|
366
|
+
/**
|
|
367
|
+
* The settings without those whose only problem is their value (made under
|
|
368
|
+
* looser rules), and the ones left out.
|
|
369
|
+
* @param {ThemeData} data
|
|
370
|
+
* @returns {{data: ThemeData, dropped: Setting[]}}
|
|
371
|
+
*/
|
|
372
|
+
export function withoutBadValues(data) {
|
|
373
|
+
const dropped = data.settings.filter(s => valueProblem(s));
|
|
374
|
+
return {
|
|
375
|
+
data: {...data, settings: data.settings.filter(s => !dropped.includes(s))},
|
|
376
|
+
dropped,
|
|
377
|
+
};
|
|
378
|
+
}
|
|
379
|
+
|
|
380
|
+
/**
|
|
381
|
+
* What is wrong with a setting's value, or null.
|
|
382
|
+
* @param {any} s
|
|
383
|
+
* @returns {string | null}
|
|
384
|
+
*/
|
|
385
|
+
function valueProblem(s) {
|
|
386
|
+
{
|
|
387
|
+
const bad = `${s.thing} "${s.value}"`;
|
|
388
|
+
if (!isSafeValue(s.value)) return `${bad} cannot be a CSS value`;
|
|
389
|
+
if (s.source === 'token') {
|
|
390
|
+
if (s.mode && !s.thing.startsWith('--color-'))
|
|
391
|
+
return `${s.thing} is set for ${s.mode} only, but only colors differ by mode`;
|
|
392
|
+
if (new RegExp(`var\\(\\s*${s.thing}\\s*[,)]`, 'i').test(s.value))
|
|
393
|
+
return `${bad} reads itself`;
|
|
394
|
+
}
|
|
395
|
+
if (s.source !== 'dial') return null;
|
|
396
|
+
const d = DIALS[s.thing];
|
|
397
|
+
if (!d) return `${s.thing} is not a dial`;
|
|
398
|
+
const words = d.values.split('|').filter(w => !w.startsWith('<'));
|
|
399
|
+
const ok =
|
|
400
|
+
s.thing === 'corners'
|
|
401
|
+
? words.includes(s.value) || isSize(s.value, '--radius')
|
|
402
|
+
: s.thing === 'text-size'
|
|
403
|
+
? words.includes(s.value) ||
|
|
404
|
+
(/^\d+(\.\d+)?$/.test(s.value) &&
|
|
405
|
+
Number(s.value) >= 10 &&
|
|
406
|
+
Number(s.value) <= 32)
|
|
407
|
+
: s.thing === 'vibrancy'
|
|
408
|
+
? /^\d{1,3}$/.test(s.value) && Number(s.value) <= 100
|
|
409
|
+
: PALETTE_DIALS.includes(s.thing)
|
|
410
|
+
? isColorValue(s.value)
|
|
411
|
+
: s.thing === 'font'
|
|
412
|
+
? s.value.trim() !== ''
|
|
413
|
+
: words.includes(s.value);
|
|
414
|
+
if (!ok || s.value === 'more' || s.value === 'less')
|
|
415
|
+
return `${bad} is not a value ${s.thing} takes (${d.values})`;
|
|
416
|
+
}
|
|
417
|
+
return null;
|
|
218
418
|
}
|
|
219
419
|
|
|
220
420
|
/** The identity of a setting: a new one with the same identity replaces it. @param {Setting} s */
|
|
@@ -238,8 +438,8 @@ export function describe(s) {
|
|
|
238
438
|
}
|
|
239
439
|
|
|
240
440
|
/**
|
|
241
|
-
* The parts a setting styles: the
|
|
242
|
-
*
|
|
441
|
+
* The parts a setting styles: the group when `--on` names one, the whole
|
|
442
|
+
* group of an always-alike member unless `--only`, else the one part.
|
|
243
443
|
* @param {Ctx} ctx
|
|
244
444
|
* @param {Pick<Setting, 'on' | 'only' | 'thing'>} s
|
|
245
445
|
* @returns {string[]}
|
|
@@ -345,6 +545,17 @@ function partDefault(ctx, target, prop, when) {
|
|
|
345
545
|
*/
|
|
346
546
|
export function compileTheme(ctx, data, base) {
|
|
347
547
|
const TOKENS = ctx.project.core.tokenDefaults;
|
|
548
|
+
// The base theme's type scale, read back from its sizes: base text, and
|
|
549
|
+
// the ratio (2xl is three steps above base).
|
|
550
|
+
const rem = (/** @type {string | undefined} */ v) =>
|
|
551
|
+
/^[\d.]+rem$/.test(v ?? '') ? Number.parseFloat(String(v)) : null;
|
|
552
|
+
const [b0, b3] = [
|
|
553
|
+
rem(base.light['--font-size-base']),
|
|
554
|
+
rem(base.light['--font-size-2xl']),
|
|
555
|
+
];
|
|
556
|
+
const baseSize = b0 ? Math.round(b0 * 16) : 14;
|
|
557
|
+
const baseRatio =
|
|
558
|
+
b0 && b3 ? Math.round((b3 / b0) ** (1 / 3) * 100) / 100 : 1.2;
|
|
348
559
|
/** @type {any} */
|
|
349
560
|
const theme = {name: data.name, tokens: {}, components: {}};
|
|
350
561
|
const modeOnly =
|
|
@@ -358,6 +569,11 @@ export function compileTheme(ctx, data, base) {
|
|
|
358
569
|
/** @param {string} name @param {string | [string, string]} v @param {string} [mode] */
|
|
359
570
|
const putTok = (name, v, mode) => {
|
|
360
571
|
const t = (tok[name] ??= {});
|
|
572
|
+
// A one-mode theme writes the value of its mode to both sides.
|
|
573
|
+
if (Array.isArray(v) && modeOnly) {
|
|
574
|
+
t.light = t.dark = v[modeOnly === 'light' ? 0 : 1];
|
|
575
|
+
return;
|
|
576
|
+
}
|
|
361
577
|
if (Array.isArray(v)) {
|
|
362
578
|
if (!mode || mode === 'light') t.light = v[0];
|
|
363
579
|
if (!mode || mode === 'dark') t.dark = v[1];
|
|
@@ -401,10 +617,29 @@ export function compileTheme(ctx, data, base) {
|
|
|
401
617
|
const pal = paletteMapping(ctx.project.cwd, data.name, data, base, TOKENS);
|
|
402
618
|
for (const [k, v] of Object.entries(pal?.tokens ?? {}))
|
|
403
619
|
putTok(k, [v.light.color, v.dark.color]);
|
|
620
|
+
// `headings` owns heading weight and tracking whatever the order: `type`
|
|
621
|
+
// sets them only where no `headings` setting does.
|
|
622
|
+
const headingsAxis = (/** @type {'weight' | 'tracking'} */ axis) =>
|
|
623
|
+
data.settings.some(
|
|
624
|
+
x => x.thing === 'headings' && (x.axis ?? 'weight') === axis,
|
|
625
|
+
);
|
|
404
626
|
const headingWeightTokens = Object.keys(TOKENS).filter(k =>
|
|
405
627
|
/^--text-(heading|display)-\d-weight$/.test(k),
|
|
406
628
|
);
|
|
407
|
-
|
|
629
|
+
// Dials first, then exact tokens and part properties: an exact setting
|
|
630
|
+
// always wins over a dial, whatever the order they were made in.
|
|
631
|
+
// A font for one role (body, heading, code) comes after the whole-theme
|
|
632
|
+
// font, so the role keeps its own font whatever the order.
|
|
633
|
+
const roleFont = (/** @type {Setting} */ x) => x.thing === 'font' && !!x.on;
|
|
634
|
+
const ordered = [
|
|
635
|
+
...data.settings.filter(x => x.source === 'dial' && !roleFont(x)),
|
|
636
|
+
...data.settings.filter(x => x.source === 'dial' && roleFont(x)),
|
|
637
|
+
...data.settings.filter(x => x.source !== 'dial'),
|
|
638
|
+
];
|
|
639
|
+
for (const s of ordered) {
|
|
640
|
+
// A setting for the mode a one-mode theme does not have stays saved but
|
|
641
|
+
// does not apply (maskedSettings names it).
|
|
642
|
+
if (modeOnly && s.mode && s.mode !== modeOnly) continue;
|
|
408
643
|
const parts = partsOf(ctx, s);
|
|
409
644
|
if (s.source === 'dial') {
|
|
410
645
|
if (s.thing === 'corners') {
|
|
@@ -416,7 +651,11 @@ export function compileTheme(ctx, data, base) {
|
|
|
416
651
|
putComp({...s, mode: undefined}, t, 'borderRadius', val(px));
|
|
417
652
|
else {
|
|
418
653
|
putTok('--radius-element', val(px));
|
|
419
|
-
|
|
654
|
+
// A checkbox stays a rounded square next to a round radio.
|
|
655
|
+
putTok(
|
|
656
|
+
'--radius-inner',
|
|
657
|
+
px >= 9999 ? '6px' : val(Math.round(px * 0.6)),
|
|
658
|
+
);
|
|
420
659
|
putTok(
|
|
421
660
|
'--radius-container',
|
|
422
661
|
px >= 9999 ? '24px' : `${Math.round(px * 1.25)}px`,
|
|
@@ -426,7 +665,7 @@ export function compileTheme(ctx, data, base) {
|
|
|
426
665
|
px >= 9999 ? '32px' : `${Math.round(px * 2.5)}px`,
|
|
427
666
|
);
|
|
428
667
|
}
|
|
429
|
-
} else if (PALETTE_DIALS.includes(s.thing)) {
|
|
668
|
+
} else if (PALETTE_DIALS.includes(s.thing) || s.thing === 'vibrancy') {
|
|
430
669
|
// The palette mapping above sets these tokens.
|
|
431
670
|
} else if (s.thing === 'font') {
|
|
432
671
|
const f = fontOf(s.value);
|
|
@@ -468,12 +707,19 @@ export function compileTheme(ctx, data, base) {
|
|
|
468
707
|
} else if (s.thing === 'type') {
|
|
469
708
|
const T = TYPE_STYLES[s.value];
|
|
470
709
|
theme.typography ??= {};
|
|
710
|
+
// The base is text-size's wherever it sits in the settings.
|
|
711
|
+
const size = [...data.settings]
|
|
712
|
+
.reverse()
|
|
713
|
+
.find(x => x.source === 'dial' && x.thing === 'text-size' && !x.on);
|
|
471
714
|
theme.typography.scale = {
|
|
472
|
-
base:
|
|
715
|
+
base: size
|
|
716
|
+
? textPx(size.value)
|
|
717
|
+
: (theme.typography.scale?.base ?? baseSize),
|
|
473
718
|
ratio: T.ratio,
|
|
474
719
|
};
|
|
475
|
-
if (T.weight
|
|
476
|
-
|
|
720
|
+
if (T.weight && !headingsAxis('weight'))
|
|
721
|
+
for (const k of headingWeightTokens) putTok(k, T.weight);
|
|
722
|
+
if (T.tracking && !headingsAxis('tracking'))
|
|
477
723
|
block({...s, mode: undefined}, 'heading').letterSpacing = T.tracking;
|
|
478
724
|
} else if (s.thing === 'headings') {
|
|
479
725
|
if (s.axis === 'tracking')
|
|
@@ -484,15 +730,23 @@ export function compileTheme(ctx, data, base) {
|
|
|
484
730
|
putTok(k, HEADING_WEIGHTS[s.value]);
|
|
485
731
|
} else if (s.thing === 'text-size') {
|
|
486
732
|
theme.typography ??= {};
|
|
733
|
+
// The ratio is type's wherever it sits in the settings.
|
|
734
|
+
const type = [...data.settings]
|
|
735
|
+
.reverse()
|
|
736
|
+
.find(x => x.source === 'dial' && x.thing === 'type');
|
|
487
737
|
theme.typography.scale = {
|
|
488
738
|
base: textPx(s.value),
|
|
489
|
-
ratio:
|
|
739
|
+
ratio: type
|
|
740
|
+
? TYPE_STYLES[type.value].ratio
|
|
741
|
+
: (theme.typography.scale?.ratio ?? baseRatio),
|
|
490
742
|
};
|
|
491
743
|
} else if (s.thing === 'spacing') {
|
|
492
744
|
const f = SPACING.find(([n]) => n === s.value)?.[1] ?? 1;
|
|
493
|
-
|
|
745
|
+
// The rungs scale the spacing the base theme starts from.
|
|
746
|
+
for (const [k, core] of Object.entries(
|
|
494
747
|
/** @type {Record<string, string>} */ (TOKENS),
|
|
495
748
|
)) {
|
|
749
|
+
const v = base.light[k] ?? core;
|
|
496
750
|
let nv = null;
|
|
497
751
|
if (/^--spacing-/.test(k) && /rem$/.test(v))
|
|
498
752
|
nv = `${Number((parseFloat(v) * f).toFixed(3))}rem`;
|
|
@@ -510,16 +764,134 @@ export function compileTheme(ctx, data, base) {
|
|
|
510
764
|
for (const t of parts) putComp(s, t, camel(s.thing), s.value);
|
|
511
765
|
}
|
|
512
766
|
}
|
|
767
|
+
// A scale steeper than the standard one enlarges the headings; the steps
|
|
768
|
+
// below the base text size keep the standard ratio, so small text stays
|
|
769
|
+
// readable. An exact token setting still wins.
|
|
770
|
+
const scale = theme.typography?.scale;
|
|
771
|
+
if (scale && scale.ratio > STANDARD_RATIO)
|
|
772
|
+
for (const [k, step] of SMALL_STEPS)
|
|
773
|
+
if (
|
|
774
|
+
!data.settings.some(x => x.source === 'token' && x.thing === k && !x.on)
|
|
775
|
+
)
|
|
776
|
+
putTok(k, `${Math.round(scale.base * STANDARD_RATIO ** step) / 16}rem`);
|
|
777
|
+
// A scale written here replaces the base theme's: its heading weights
|
|
778
|
+
// stay as the theme sets them (a dial or an exact token first, then the
|
|
779
|
+
// base theme). A base weight is written as the weight token it equals
|
|
780
|
+
// (700 is var(--font-weight-bold)), so an exact weight token still feeds
|
|
781
|
+
// it. The heading role carries them too, since Core expands the scale
|
|
782
|
+
// again for phones from the role's weights.
|
|
783
|
+
if (theme.typography?.scale) {
|
|
784
|
+
const weightTokens = Object.keys(TOKENS).filter(k =>
|
|
785
|
+
/^--font-weight-[a-z]+$/.test(k),
|
|
786
|
+
);
|
|
787
|
+
const asRef = (/** @type {string} */ v) => {
|
|
788
|
+
const named = weightTokens.find(w => (base.light[w] ?? TOKENS[w]) === v);
|
|
789
|
+
return named ? `var(${named})` : v;
|
|
790
|
+
};
|
|
791
|
+
/** @type {Record<string, string>} */
|
|
792
|
+
const heading = {};
|
|
793
|
+
for (const k of headingWeightTokens) {
|
|
794
|
+
const level = /^--text-heading-(\d)-weight$/.exec(k)?.[1];
|
|
795
|
+
const weight =
|
|
796
|
+
tok[k]?.light ?? (base.light[k] != null ? asRef(base.light[k]) : null);
|
|
797
|
+
if (weight == null) continue;
|
|
798
|
+
if (!tok[k]) putTok(k, weight);
|
|
799
|
+
if (level) heading[level] = weight;
|
|
800
|
+
}
|
|
801
|
+
if (Object.keys(heading).length)
|
|
802
|
+
theme.typography.heading = {
|
|
803
|
+
...(theme.typography.heading ?? {}),
|
|
804
|
+
weights: {...(theme.typography.heading?.weights ?? {}), ...heading},
|
|
805
|
+
};
|
|
806
|
+
}
|
|
513
807
|
for (const [k, {light, dark}] of Object.entries(tok)) {
|
|
514
808
|
const l = light ?? base.light[k] ?? TOKENS[k];
|
|
515
809
|
const d = dark ?? base.dark[k] ?? TOKENS[k];
|
|
516
810
|
theme.tokens[k] = l === d ? l : [l, d];
|
|
517
811
|
}
|
|
812
|
+
// Base themes set the type tokens again for phones (a coarse pointer
|
|
813
|
+
// below the lg width); an exact font family is written there too, so it
|
|
814
|
+
// applies on every screen. Sizes are not: phones keep their reading base.
|
|
815
|
+
const phone = Object.fromEntries(
|
|
816
|
+
data.settings
|
|
817
|
+
.filter(
|
|
818
|
+
x =>
|
|
819
|
+
x.source === 'token' &&
|
|
820
|
+
!x.on &&
|
|
821
|
+
!x.mode &&
|
|
822
|
+
// Families only: phones keep their own reading sizes.
|
|
823
|
+
/^--font-family/.test(x.thing) &&
|
|
824
|
+
!(modeOnly && x.mode && x.mode !== modeOnly),
|
|
825
|
+
)
|
|
826
|
+
.map(x => [x.thing, x.value]),
|
|
827
|
+
);
|
|
828
|
+
if (Object.keys(phone).length)
|
|
829
|
+
theme.adaptations = {
|
|
830
|
+
rules: [
|
|
831
|
+
{
|
|
832
|
+
when: {pointer: 'coarse', width: {below: 'lg'}},
|
|
833
|
+
value: {tokens: phone},
|
|
834
|
+
},
|
|
835
|
+
],
|
|
836
|
+
};
|
|
518
837
|
if (!Object.keys(theme.tokens).length) delete theme.tokens;
|
|
519
838
|
if (!Object.keys(theme.components).length) delete theme.components;
|
|
520
839
|
return theme;
|
|
521
840
|
}
|
|
522
841
|
|
|
842
|
+
/** Core's default type scale ratio. */
|
|
843
|
+
const STANDARD_RATIO = 1.2;
|
|
844
|
+
/** The font-size tokens below the base, with their step on the scale. */
|
|
845
|
+
const SMALL_STEPS = /** @type {Array<[string, number]>} */ ([
|
|
846
|
+
['--font-size-sm', -1],
|
|
847
|
+
['--font-size-xs', -2],
|
|
848
|
+
['--font-size-2xs', -3],
|
|
849
|
+
['--font-size-3xs', -4],
|
|
850
|
+
['--font-size-4xs', -5],
|
|
851
|
+
]);
|
|
852
|
+
|
|
853
|
+
/**
|
|
854
|
+
* Settings whose effect a later or stronger setting hides, with why: `type`
|
|
855
|
+
* loses heading weight and tracking to `headings`.
|
|
856
|
+
* @param {ThemeData} data
|
|
857
|
+
* @returns {Map<Setting, string>}
|
|
858
|
+
*/
|
|
859
|
+
export function maskedSettings(data) {
|
|
860
|
+
/** @type {Map<Setting, string>} */
|
|
861
|
+
const out = new Map();
|
|
862
|
+
const axes = new Set(
|
|
863
|
+
data.settings
|
|
864
|
+
.filter(x => x.thing === 'headings')
|
|
865
|
+
.map(x => x.axis ?? 'weight'),
|
|
866
|
+
);
|
|
867
|
+
const only =
|
|
868
|
+
data.mode === 'light-only'
|
|
869
|
+
? 'light'
|
|
870
|
+
: data.mode === 'dark-only'
|
|
871
|
+
? 'dark'
|
|
872
|
+
: null;
|
|
873
|
+
for (const s of data.settings)
|
|
874
|
+
if (only && s.mode && s.mode !== only)
|
|
875
|
+
out.set(
|
|
876
|
+
s,
|
|
877
|
+
`saved for ${s.mode} mode, which a ${data.mode} theme does not have, so it does not apply`,
|
|
878
|
+
);
|
|
879
|
+
for (const s of data.settings) {
|
|
880
|
+
if (s.thing !== 'type' || !axes.size) continue;
|
|
881
|
+
const T = TYPE_STYLES[s.value];
|
|
882
|
+
const hidden = [
|
|
883
|
+
...(T?.weight && axes.has('weight') ? ['weight'] : []),
|
|
884
|
+
...(T?.tracking && axes.has('tracking') ? ['tracking'] : []),
|
|
885
|
+
];
|
|
886
|
+
if (hidden.length)
|
|
887
|
+
out.set(
|
|
888
|
+
s,
|
|
889
|
+
`type still sets the heading sizes and line heights; heading ${hidden.join(' and ')} come${hidden.length > 1 ? '' : 's'} from headings`,
|
|
890
|
+
);
|
|
891
|
+
}
|
|
892
|
+
return out;
|
|
893
|
+
}
|
|
894
|
+
|
|
523
895
|
/**
|
|
524
896
|
* A plain part setting can lose to a more specific rule for the same part
|
|
525
897
|
* and property, such as a base theme's `.astryx-heading[data-level="1"]
|
|
@@ -575,12 +947,26 @@ function settingsSource(slug, data, theme, pal) {
|
|
|
575
947
|
const REF = '@@palette:';
|
|
576
948
|
/** @param {string} family @param {'light' | 'dark'} m @param {import('./_palette.mjs').StopRef} r */
|
|
577
949
|
const refOf = (family, m, r) =>
|
|
578
|
-
|
|
950
|
+
r.family === 'black' || r.family === 'white'
|
|
951
|
+
? `${REF}${r.family}`
|
|
952
|
+
: `${REF}${r.family ?? family}.${m}.${r.stop}${r.alpha ? `+${r.alpha}` : ''}`;
|
|
579
953
|
const out = {...theme, name: `${slug}-settings`};
|
|
954
|
+
const only =
|
|
955
|
+
data.mode === 'light-only'
|
|
956
|
+
? 'light'
|
|
957
|
+
: data.mode === 'dark-only'
|
|
958
|
+
? 'dark'
|
|
959
|
+
: null;
|
|
580
960
|
if (pal && theme.tokens) {
|
|
581
961
|
out.tokens = {...theme.tokens};
|
|
582
962
|
for (const [k, v] of Object.entries(pal.tokens)) {
|
|
583
963
|
const now = theme.tokens[k];
|
|
964
|
+
// A one-mode theme reads one shade, its mode's, on both sides.
|
|
965
|
+
if (only) {
|
|
966
|
+
if (now === v[only].color)
|
|
967
|
+
out.tokens[k] = refOf(v.family, only, v[only]);
|
|
968
|
+
continue;
|
|
969
|
+
}
|
|
584
970
|
const [l, d] = Array.isArray(now) ? now : [now, now];
|
|
585
971
|
if (l !== v.light.color || d !== v.dark.color) continue;
|
|
586
972
|
out.tokens[k] = [
|
|
@@ -591,14 +977,16 @@ function settingsSource(slug, data, theme, pal) {
|
|
|
591
977
|
}
|
|
592
978
|
let usesPalette = false;
|
|
593
979
|
const body = JSON.stringify(out, null, 2).replace(
|
|
594
|
-
/"@@palette:([a-z][a-z0-9-]*)\.(light|dark)\.(\d+)(?:\+([0-9a-f]{2}))?"/g,
|
|
595
|
-
(_, family, m, stop, alpha) => {
|
|
980
|
+
/"@@palette:(?:(black|white)|([a-z][a-z0-9-]*)\.(light|dark)\.(\d+(?:\.\d+)?)(?:\+([0-9a-f]{2}))?)"/g,
|
|
981
|
+
(_, end, family, m, stop, alpha) => {
|
|
596
982
|
usesPalette = true;
|
|
983
|
+
if (end) return `palette.${end}`;
|
|
597
984
|
return `palette${/^[a-z]\w*$/.test(family) ? `.${family}` : `[${JSON.stringify(family)}]`}.${m}[${stop}]${alpha ? ` + '${alpha}'` : ''}`;
|
|
598
985
|
},
|
|
599
986
|
);
|
|
600
987
|
return [
|
|
601
988
|
`// Generated by \`${P}\` from ${slug}.settings.json on every change: do not edit.`,
|
|
989
|
+
`// Built from settings ${settingsStamp(data)}.`,
|
|
602
990
|
`// Change it with \`${P} set ${slug} ...\`; your own changes go in ${slug}.theme.ts.`,
|
|
603
991
|
"import {defineTheme} from '@astryxdesign/core/theme';",
|
|
604
992
|
...(like
|
|
@@ -606,9 +994,7 @@ function settingsSource(slug, data, theme, pal) {
|
|
|
606
994
|
`import {${like}Theme as base} from '@astryxdesign/theme-${like}/built';`,
|
|
607
995
|
]
|
|
608
996
|
: []),
|
|
609
|
-
...(usesPalette
|
|
610
|
-
? [`import {palette} from '${paletteFiles(slug).importPath}';`]
|
|
611
|
-
: []),
|
|
997
|
+
...(usesPalette ? [paletteImport(slug)] : []),
|
|
612
998
|
'',
|
|
613
999
|
`export const ${camel(slug)}Settings = defineTheme({`,
|
|
614
1000
|
...(like ? [' extends: base,'] : []),
|
|
@@ -645,7 +1031,7 @@ function themeModuleSource(slug) {
|
|
|
645
1031
|
* @param {Ctx} ctx
|
|
646
1032
|
* @param {string} slug
|
|
647
1033
|
* @param {ThemeData} data
|
|
648
|
-
* @returns {Promise<{warnings: string[], lifted: string[]}>}
|
|
1034
|
+
* @returns {Promise<{warnings: string[], lifted: string[], notes: string[]}>} `notes`: what the color config kept or replaced of a hand edit
|
|
649
1035
|
*/
|
|
650
1036
|
export async function buildTheme(ctx, slug, data) {
|
|
651
1037
|
const {cwd} = ctx.project;
|
|
@@ -661,10 +1047,18 @@ export async function buildTheme(ctx, slug, data) {
|
|
|
661
1047
|
ctx.project.core.tokenDefaults,
|
|
662
1048
|
);
|
|
663
1049
|
fs.mkdirSync(f.dir, {recursive: true});
|
|
664
|
-
|
|
665
|
-
|
|
666
|
-
|
|
667
|
-
|
|
1050
|
+
// Each write is recorded for a rollback; the time between them is not.
|
|
1051
|
+
/** @type {<T>(fn: () => T) => Promise<Awaited<T>>} */
|
|
1052
|
+
const step = fn => track(f.dir, ctx.wrote ?? new Map(), fn);
|
|
1053
|
+
/** @type {string[]} */
|
|
1054
|
+
let notes = [];
|
|
1055
|
+
await step(() => {
|
|
1056
|
+
notes = syncPalette(cwd, slug, data, base);
|
|
1057
|
+
writeAtomic(f.settingsTs, settingsSource(slug, data, theme, pal));
|
|
1058
|
+
syncPaletteRefs(cwd, slug, fs.readFileSync(f.settingsTs, 'utf8'), pal);
|
|
1059
|
+
if (!fs.existsSync(f.ts)) writeAtomic(f.ts, themeModuleSource(slug));
|
|
1060
|
+
});
|
|
1061
|
+
let receipt = await step(() => runBuild(ctx, slug));
|
|
668
1062
|
const found = findOverrides(fs.readFileSync(f.css, 'utf8'), theme).filter(
|
|
669
1063
|
x => !(theme.components[x.target][x.key] ?? {})[x.prop],
|
|
670
1064
|
);
|
|
@@ -676,9 +1070,15 @@ export async function buildTheme(ctx, slug, data) {
|
|
|
676
1070
|
(t[x.key] ??= {})[x.prop] ??= x.value;
|
|
677
1071
|
lifted.push(`${x.target} ${x.key} ${kebab(x.prop)}`);
|
|
678
1072
|
}
|
|
679
|
-
|
|
680
|
-
|
|
1073
|
+
await step(() => {
|
|
1074
|
+
writeAtomic(f.settingsTs, settingsSource(slug, data, theme, pal));
|
|
1075
|
+
syncPaletteRefs(cwd, slug, fs.readFileSync(f.settingsTs, 'utf8'), pal);
|
|
1076
|
+
});
|
|
1077
|
+
receipt = await step(() => runBuild(ctx, slug));
|
|
681
1078
|
}
|
|
1079
|
+
for (const out of [f.css, f.js])
|
|
1080
|
+
if (fs.existsSync(out))
|
|
1081
|
+
assertNoPlaceholder(shown(cwd, out), fs.readFileSync(out, 'utf8'));
|
|
682
1082
|
// Font notices are reported by the font dial itself, once.
|
|
683
1083
|
const warnings = [
|
|
684
1084
|
...(receipt?.data?.warnings ?? []),
|
|
@@ -686,7 +1086,7 @@ export async function buildTheme(ctx, slug, data) {
|
|
|
686
1086
|
]
|
|
687
1087
|
.map(String)
|
|
688
1088
|
.filter(w => !/^Font "/.test(w));
|
|
689
|
-
return {warnings, lifted};
|
|
1089
|
+
return {warnings, lifted, notes};
|
|
690
1090
|
}
|
|
691
1091
|
|
|
692
1092
|
/** @param {Ctx} ctx @param {string} slug @returns {Promise<any>} */
|
|
@@ -716,9 +1116,41 @@ async function runBuild(ctx, slug) {
|
|
|
716
1116
|
*/
|
|
717
1117
|
export async function resolvedTokens(ctx, slug) {
|
|
718
1118
|
const f = themeFiles(ctx.project.cwd, slug);
|
|
719
|
-
|
|
720
|
-
|
|
721
|
-
|
|
1119
|
+
// The built module is ESM in a .js file, and an app's package.json may not
|
|
1120
|
+
// say "type": "module": an .mjs copy loads as ESM with no Node warning,
|
|
1121
|
+
// and the query keeps it out of the module cache. The copy goes in the
|
|
1122
|
+
// project's cache folder, where package imports still resolve; only a
|
|
1123
|
+
// module with relative imports is copied beside itself. (The shared theme
|
|
1124
|
+
// loader caches a .js module of an ESM app by URL, so a second read in one
|
|
1125
|
+
// command would return the first build.)
|
|
1126
|
+
const source = fs.readFileSync(f.js, 'utf8');
|
|
1127
|
+
// Each copy has its own name, so two commands at once never share one; a
|
|
1128
|
+
// read-only cache folder falls back to the theme folder.
|
|
1129
|
+
const name = `.${slug}.load-${process.pid}-${Math.random().toString(36).slice(2, 8)}.mjs`;
|
|
1130
|
+
let copy = path.join(f.dir, name);
|
|
1131
|
+
// A real relative import (not the usage example in the doc comment).
|
|
1132
|
+
const code = source.replace(/\/\*[\s\S]*?\*\//g, '').replace(/\/\/.*$/gm, '');
|
|
1133
|
+
if (!/^\s*(import|export)\b[^;]*\bfrom\s+['"]\.\.?\//m.test(code))
|
|
1134
|
+
try {
|
|
1135
|
+
fs.mkdirSync(ctx.project.cacheDir, {recursive: true});
|
|
1136
|
+
fs.writeFileSync(path.join(ctx.project.cacheDir, name), source);
|
|
1137
|
+
copy = path.join(ctx.project.cacheDir, name);
|
|
1138
|
+
} catch {
|
|
1139
|
+
// The cache folder is not writable: use the theme folder.
|
|
1140
|
+
}
|
|
1141
|
+
/** @type {Record<string, any>} */
|
|
1142
|
+
let mod;
|
|
1143
|
+
try {
|
|
1144
|
+
if (copy.startsWith(f.dir)) fs.writeFileSync(copy, source);
|
|
1145
|
+
mod = await import(
|
|
1146
|
+
`${pathToFileURL(copy).href}?t=${Date.now()}${Math.random()}`
|
|
1147
|
+
);
|
|
1148
|
+
} catch (e) {
|
|
1149
|
+
if (e instanceof Error) e.message = e.message.split(copy).join(f.js);
|
|
1150
|
+
throw e;
|
|
1151
|
+
} finally {
|
|
1152
|
+
fs.rmSync(copy, {force: true});
|
|
1153
|
+
}
|
|
722
1154
|
const t = Object.values(mod).find(
|
|
723
1155
|
v => v && typeof v === 'object' && typeof v.name === 'string',
|
|
724
1156
|
);
|
|
@@ -740,7 +1172,7 @@ export async function resolvedTokens(ctx, slug) {
|
|
|
740
1172
|
*/
|
|
741
1173
|
export async function contrastProblems(ctx, data, res) {
|
|
742
1174
|
const base = await baseResolved(ctx.project, data.like);
|
|
743
|
-
/** @param {
|
|
1175
|
+
/** @param {PaintSide} side @param {'fg' | 'bg'} which @param {string} m */
|
|
744
1176
|
const override = (side, which, m) => {
|
|
745
1177
|
if (!side.target) return null;
|
|
746
1178
|
const props =
|
|
@@ -758,7 +1190,7 @@ export async function contrastProblems(ctx, data, res) {
|
|
|
758
1190
|
);
|
|
759
1191
|
return hit?.value ?? null;
|
|
760
1192
|
};
|
|
761
|
-
/** @type {(p:
|
|
1193
|
+
/** @type {(p: TextPair, side: 'fg' | 'bg', m: string) => string | null} */
|
|
762
1194
|
const value = (p, side, m) => {
|
|
763
1195
|
const s = p[side];
|
|
764
1196
|
return (
|
|
@@ -768,24 +1200,56 @@ export async function contrastProblems(ctx, data, res) {
|
|
|
768
1200
|
: s.raw)
|
|
769
1201
|
);
|
|
770
1202
|
};
|
|
771
|
-
/** @type {(p:
|
|
1203
|
+
/** @type {(p: TextPair, side: 'fg' | 'bg', m: string) => string | null} */
|
|
772
1204
|
const baseValue = (p, side, m) => {
|
|
773
1205
|
const s = p[side];
|
|
774
1206
|
return s.tokens.length
|
|
775
1207
|
? base[/** @type {'light' | 'dark'} */ (m)][s.tokens[0]]
|
|
776
1208
|
: s.raw;
|
|
777
1209
|
};
|
|
778
|
-
const {problems, unchecked} = ctx.C.contrast(
|
|
1210
|
+
const {problems, more, unchecked} = ctx.C.contrast(
|
|
779
1211
|
value,
|
|
780
1212
|
baseValue,
|
|
781
1213
|
modesOf(data),
|
|
782
|
-
{
|
|
1214
|
+
{
|
|
1215
|
+
parseColor,
|
|
1216
|
+
ratio,
|
|
1217
|
+
alphaOf,
|
|
1218
|
+
compositeOver,
|
|
1219
|
+
page: m =>
|
|
1220
|
+
res[/** @type {'light' | 'dark'} */ (m)]['--color-background-body'],
|
|
1221
|
+
},
|
|
783
1222
|
);
|
|
784
1223
|
return [
|
|
785
1224
|
...problems.map(
|
|
786
1225
|
x =>
|
|
787
1226
|
`text in ${x.part} ("${x.sample}") is ${x.ratio}:1 in ${x.mode} (${x.fg} on ${x.bgPart ?? 'the page'}'s ${x.bg}); text needs 4.5:1`,
|
|
788
1227
|
),
|
|
1228
|
+
...(more
|
|
1229
|
+
? [`and ${more} more text pair${more > 1 ? 's' : ''} below 4.5:1`]
|
|
1230
|
+
: []),
|
|
1231
|
+
// Pairs styled for one variant or state are not measured yet.
|
|
1232
|
+
...(() => {
|
|
1233
|
+
const scoped = data.settings.filter(
|
|
1234
|
+
x =>
|
|
1235
|
+
(x.on &&
|
|
1236
|
+
(x.when || x.state) &&
|
|
1237
|
+
(/^(color|background|background-color)$/.test(x.thing) ||
|
|
1238
|
+
/^--color-/.test(x.thing))) ||
|
|
1239
|
+
// The button style recolors the primary button only.
|
|
1240
|
+
(x.thing === 'buttons' && ['soft', 'outline'].includes(x.value)),
|
|
1241
|
+
);
|
|
1242
|
+
return scoped.length
|
|
1243
|
+
? [
|
|
1244
|
+
`not checked: text contrast for ${scoped
|
|
1245
|
+
.slice(0, 3)
|
|
1246
|
+
.map(describe)
|
|
1247
|
+
.join(
|
|
1248
|
+
'; ',
|
|
1249
|
+
)}${scoped.length > 3 ? ` and ${scoped.length - 3} more` : ''}, set for one variant or state`,
|
|
1250
|
+
]
|
|
1251
|
+
: [];
|
|
1252
|
+
})(),
|
|
789
1253
|
...(unchecked.length
|
|
790
1254
|
? [
|
|
791
1255
|
`not checked: text on or in ${unchecked.slice(0, 3).join(', ')}${unchecked.length > 3 ? ` and ${unchecked.length - 3} more` : ''}, which ${unchecked.length === 1 ? 'is' : 'are'} not a fixed color`,
|
|
@@ -808,6 +1272,260 @@ function parseSettings(text) {
|
|
|
808
1272
|
}
|
|
809
1273
|
}
|
|
810
1274
|
|
|
1275
|
+
/**
|
|
1276
|
+
* Every regular file under `dir` and the hash of its bytes; empty when
|
|
1277
|
+
* there is no folder.
|
|
1278
|
+
* @param {string} dir
|
|
1279
|
+
* @returns {Map<string, string>}
|
|
1280
|
+
*/
|
|
1281
|
+
function hashDir(dir) {
|
|
1282
|
+
/** @type {Map<string, string>} */
|
|
1283
|
+
const out = new Map();
|
|
1284
|
+
if (!fs.lstatSync(dir, {throwIfNoEntry: false})?.isDirectory()) return out;
|
|
1285
|
+
/** @param {string} d */
|
|
1286
|
+
const walk = d => {
|
|
1287
|
+
for (const e of fs.readdirSync(d, {withFileTypes: true})) {
|
|
1288
|
+
const p = path.join(d, e.name);
|
|
1289
|
+
if (e.isDirectory()) walk(p);
|
|
1290
|
+
else if (e.isFile())
|
|
1291
|
+
out.set(
|
|
1292
|
+
p,
|
|
1293
|
+
createHash('sha256').update(fs.readFileSync(p)).digest('hex'),
|
|
1294
|
+
);
|
|
1295
|
+
}
|
|
1296
|
+
};
|
|
1297
|
+
walk(dir);
|
|
1298
|
+
return out;
|
|
1299
|
+
}
|
|
1300
|
+
|
|
1301
|
+
/**
|
|
1302
|
+
* Run `fn`, and record in `wrote` every file under `dir` it created,
|
|
1303
|
+
* replaced or removed, with the hash of what it left (null: removed). Only
|
|
1304
|
+
* these files are ever put back if the change fails.
|
|
1305
|
+
* @template T
|
|
1306
|
+
* @param {string} dir
|
|
1307
|
+
* @param {Map<string, string | null>} wrote
|
|
1308
|
+
* @param {() => T} fn
|
|
1309
|
+
* @returns {Promise<Awaited<T>>}
|
|
1310
|
+
*/
|
|
1311
|
+
async function track(dir, wrote, fn) {
|
|
1312
|
+
const before = hashDir(dir);
|
|
1313
|
+
try {
|
|
1314
|
+
return await fn();
|
|
1315
|
+
} finally {
|
|
1316
|
+
const after = hashDir(dir);
|
|
1317
|
+
for (const [p, h] of after) if (before.get(p) !== h) wrote.set(p, h);
|
|
1318
|
+
for (const p of before.keys()) if (!after.has(p)) wrote.set(p, null);
|
|
1319
|
+
}
|
|
1320
|
+
}
|
|
1321
|
+
|
|
1322
|
+
/**
|
|
1323
|
+
* Put back what this command wrote in this run, and only that: a file it
|
|
1324
|
+
* created goes, and a file it replaced or removed gets the bytes it had.
|
|
1325
|
+
* A file someone else changed since this command wrote it is left as it is
|
|
1326
|
+
* and named. Writes are whole (a new file renamed into place), and one
|
|
1327
|
+
* failure does not stop the rest.
|
|
1328
|
+
* @param {Map<string, Buffer>} was the bytes before, for each file written
|
|
1329
|
+
* @param {Map<string, string | null>} wrote
|
|
1330
|
+
* @returns {{failed: string[], skipped: string[]}}
|
|
1331
|
+
*/
|
|
1332
|
+
function restoreWritten(was, wrote) {
|
|
1333
|
+
/** @type {string[]} */
|
|
1334
|
+
const failed = [];
|
|
1335
|
+
/** @type {string[]} */
|
|
1336
|
+
const skipped = [];
|
|
1337
|
+
for (const [p, h] of wrote) {
|
|
1338
|
+
try {
|
|
1339
|
+
const st = fs.lstatSync(p, {throwIfNoEntry: false});
|
|
1340
|
+
if (st?.isSymbolicLink()) {
|
|
1341
|
+
skipped.push(path.basename(p));
|
|
1342
|
+
continue;
|
|
1343
|
+
}
|
|
1344
|
+
const cur = st?.isFile()
|
|
1345
|
+
? createHash('sha256').update(fs.readFileSync(p)).digest('hex')
|
|
1346
|
+
: null;
|
|
1347
|
+
if (cur !== h) {
|
|
1348
|
+
skipped.push(path.basename(p));
|
|
1349
|
+
continue;
|
|
1350
|
+
}
|
|
1351
|
+
const old = was.get(p);
|
|
1352
|
+
if (old) writeWhole(p, old);
|
|
1353
|
+
else fs.rmSync(p, {force: true});
|
|
1354
|
+
} catch {
|
|
1355
|
+
failed.push(path.basename(p));
|
|
1356
|
+
}
|
|
1357
|
+
}
|
|
1358
|
+
return {failed, skipped};
|
|
1359
|
+
}
|
|
1360
|
+
|
|
1361
|
+
/**
|
|
1362
|
+
* The bytes of every regular file under `dir`, for putting back what a
|
|
1363
|
+
* failed change wrote.
|
|
1364
|
+
* @param {string} dir
|
|
1365
|
+
* @returns {Map<string, Buffer>}
|
|
1366
|
+
*/
|
|
1367
|
+
function snapshotDir(dir) {
|
|
1368
|
+
/** @type {Map<string, Buffer>} */
|
|
1369
|
+
const out = new Map();
|
|
1370
|
+
for (const p of hashDir(dir).keys()) out.set(p, fs.readFileSync(p));
|
|
1371
|
+
return out;
|
|
1372
|
+
}
|
|
1373
|
+
|
|
1374
|
+
/**
|
|
1375
|
+
* Refuse a link anywhere the editor reads or writes a theme: `themes/`, the
|
|
1376
|
+
* theme folder, and every file and folder in it. The editor writes the
|
|
1377
|
+
* theme's own files only, never through a link to somewhere else.
|
|
1378
|
+
* @param {string} cwd
|
|
1379
|
+
* @param {string} slug
|
|
1380
|
+
*/
|
|
1381
|
+
export function refuseLinks(cwd, slug) {
|
|
1382
|
+
const f = themeFiles(cwd, slug);
|
|
1383
|
+
/** @param {string} p */
|
|
1384
|
+
const link = p => {
|
|
1385
|
+
if (fs.lstatSync(p, {throwIfNoEntry: false})?.isSymbolicLink())
|
|
1386
|
+
throw new AstryxError(
|
|
1387
|
+
`${path.relative(cwd, p) || p} is a link; the editor writes a theme's own files only, never through a link. Replace the link with a copy of what it points to. Nothing was changed.`,
|
|
1388
|
+
[
|
|
1389
|
+
{
|
|
1390
|
+
name: `cp -rL ${q(path.relative(cwd, p))} ${q(`${path.relative(cwd, p)}.copy`)}`,
|
|
1391
|
+
reason: 'copy what it points to, then put the copy in its place',
|
|
1392
|
+
},
|
|
1393
|
+
],
|
|
1394
|
+
ERROR_CODES.ERR_THEME_INVALID,
|
|
1395
|
+
);
|
|
1396
|
+
};
|
|
1397
|
+
link(f.root);
|
|
1398
|
+
link(f.dir);
|
|
1399
|
+
/** @param {string} d */
|
|
1400
|
+
const walk = d => {
|
|
1401
|
+
if (!fs.lstatSync(d, {throwIfNoEntry: false})?.isDirectory()) return;
|
|
1402
|
+
for (const e of fs.readdirSync(d, {withFileTypes: true})) {
|
|
1403
|
+
const p = path.join(d, e.name);
|
|
1404
|
+
link(p);
|
|
1405
|
+
if (e.isDirectory()) walk(p);
|
|
1406
|
+
}
|
|
1407
|
+
};
|
|
1408
|
+
walk(f.dir);
|
|
1409
|
+
}
|
|
1410
|
+
|
|
1411
|
+
/**
|
|
1412
|
+
* What a build was made from: the settings and the CLI that built them, so
|
|
1413
|
+
* a build that no longer matches its settings file is found and made again.
|
|
1414
|
+
* @param {ThemeData} data
|
|
1415
|
+
*/
|
|
1416
|
+
export function settingsStamp(data) {
|
|
1417
|
+
const hash = createHash('sha256')
|
|
1418
|
+
.update(
|
|
1419
|
+
JSON.stringify({
|
|
1420
|
+
like: data.like ?? null,
|
|
1421
|
+
mode: data.mode,
|
|
1422
|
+
settings: data.settings,
|
|
1423
|
+
}),
|
|
1424
|
+
)
|
|
1425
|
+
.digest('hex')
|
|
1426
|
+
.slice(0, 16);
|
|
1427
|
+
return `${hash} (CLI ${cliVersion()})`;
|
|
1428
|
+
}
|
|
1429
|
+
|
|
1430
|
+
/**
|
|
1431
|
+
* Whether the theme's build was made, whole, from these settings by this
|
|
1432
|
+
* CLI (a command stopped mid-build, or settings edited by hand, leave it
|
|
1433
|
+
* behind).
|
|
1434
|
+
* @param {string} cwd
|
|
1435
|
+
* @param {string} slug
|
|
1436
|
+
* @param {ThemeData} data
|
|
1437
|
+
*/
|
|
1438
|
+
export function buildCurrent(cwd, slug, data) {
|
|
1439
|
+
return staleBuild(cwd, slug, data) == null;
|
|
1440
|
+
}
|
|
1441
|
+
|
|
1442
|
+
/**
|
|
1443
|
+
* Why the theme's build does not match its settings, in words, or null when
|
|
1444
|
+
* it does: a file missing, another CLI version, settings changed since the
|
|
1445
|
+
* build (a hand edit), or a build left half done (a command stopped).
|
|
1446
|
+
* @param {string} cwd
|
|
1447
|
+
* @param {string} slug
|
|
1448
|
+
* @param {ThemeData} data
|
|
1449
|
+
* @returns {string | null}
|
|
1450
|
+
*/
|
|
1451
|
+
export function staleBuild(cwd, slug, data) {
|
|
1452
|
+
const f = themeFiles(cwd, slug);
|
|
1453
|
+
const missing = [f.js, f.css, f.settingsTs].find(p => !fs.existsSync(p));
|
|
1454
|
+
if (missing) return `${path.basename(missing)} was missing`;
|
|
1455
|
+
const ts = fs.readFileSync(f.settingsTs, 'utf8');
|
|
1456
|
+
const stamp =
|
|
1457
|
+
/\/\/ Built from settings ([0-9a-f]{16}) \(CLI ([^)]+)\)\./.exec(ts);
|
|
1458
|
+
const [hash] = settingsStamp(data).split(' ');
|
|
1459
|
+
if (stamp && stamp[1] === hash && stamp[2] !== cliVersion())
|
|
1460
|
+
return `it was built by CLI ${stamp[2]}, and this is ${cliVersion()}`;
|
|
1461
|
+
if (!stamp || stamp[1] !== hash)
|
|
1462
|
+
return `${slug}.settings.json changed after the build (edited by hand, or by another tool)`;
|
|
1463
|
+
if (
|
|
1464
|
+
!ts.trimEnd().endsWith('});') ||
|
|
1465
|
+
fs.statSync(f.css).mtimeMs < fs.statSync(f.settingsTs).mtimeMs - 1000
|
|
1466
|
+
)
|
|
1467
|
+
return 'the last build did not finish (a command stopped while building)';
|
|
1468
|
+
return null;
|
|
1469
|
+
}
|
|
1470
|
+
|
|
1471
|
+
/** @param {string} dir */
|
|
1472
|
+
function removeIfEmpty(dir) {
|
|
1473
|
+
try {
|
|
1474
|
+
fs.rmdirSync(dir);
|
|
1475
|
+
} catch {
|
|
1476
|
+
// Not empty, or gone already.
|
|
1477
|
+
}
|
|
1478
|
+
}
|
|
1479
|
+
|
|
1480
|
+
/** The undo steps a theme keeps; older ones are dropped. */
|
|
1481
|
+
export const HISTORY_STEPS = 80;
|
|
1482
|
+
|
|
1483
|
+
/**
|
|
1484
|
+
* Write a file whole: a new file beside it, renamed into place.
|
|
1485
|
+
* @param {string} file
|
|
1486
|
+
* @param {string} text
|
|
1487
|
+
*/
|
|
1488
|
+
export function writeAtomic(file, text) {
|
|
1489
|
+
writeWhole(file, text);
|
|
1490
|
+
}
|
|
1491
|
+
|
|
1492
|
+
/**
|
|
1493
|
+
* A theme's undo history: the settings text before each change, oldest
|
|
1494
|
+
* first, and how many damaged steps were dropped. Every step after the
|
|
1495
|
+
* last damaged one is kept.
|
|
1496
|
+
* @param {string} file
|
|
1497
|
+
* @returns {{steps: string[], dropped: number}}
|
|
1498
|
+
*/
|
|
1499
|
+
export function readHistory(file) {
|
|
1500
|
+
if (!fs.existsSync(file)) return {steps: [], dropped: 0};
|
|
1501
|
+
/** @type {unknown} */
|
|
1502
|
+
let h;
|
|
1503
|
+
try {
|
|
1504
|
+
h = JSON.parse(fs.readFileSync(file, 'utf8').replace(/^\uFEFF/, ''));
|
|
1505
|
+
} catch {
|
|
1506
|
+
return {steps: [], dropped: 1};
|
|
1507
|
+
}
|
|
1508
|
+
if (!Array.isArray(h)) return {steps: [], dropped: 1};
|
|
1509
|
+
const ok = (/** @type {unknown} */ x) => {
|
|
1510
|
+
try {
|
|
1511
|
+
return (
|
|
1512
|
+
typeof x === 'string' &&
|
|
1513
|
+
Array.isArray(JSON.parse(x.replace(/^\uFEFF/, '')).settings)
|
|
1514
|
+
);
|
|
1515
|
+
} catch {
|
|
1516
|
+
return false;
|
|
1517
|
+
}
|
|
1518
|
+
};
|
|
1519
|
+
let last = -1;
|
|
1520
|
+
h.forEach((x, i) => {
|
|
1521
|
+
if (!ok(x)) last = i;
|
|
1522
|
+
});
|
|
1523
|
+
return {
|
|
1524
|
+
steps: /** @type {string[]} */ (h.slice(last + 1)),
|
|
1525
|
+
dropped: last + 1,
|
|
1526
|
+
};
|
|
1527
|
+
}
|
|
1528
|
+
|
|
811
1529
|
/**
|
|
812
1530
|
* Write the settings, build, and on a failed build put back what was there.
|
|
813
1531
|
* Returns what changed in the resolved tokens and the lifted keys that are
|
|
@@ -815,70 +1533,161 @@ function parseSettings(text) {
|
|
|
815
1533
|
* @param {Ctx} ctx
|
|
816
1534
|
* @param {string} slug
|
|
817
1535
|
* @param {ThemeData} data
|
|
818
|
-
* @param {{history: boolean}} options
|
|
1536
|
+
* @param {{history: boolean, historyAfter?: string[]}} options
|
|
1537
|
+
* `historyAfter`: the history to write with the change (a step back pops it)
|
|
819
1538
|
*/
|
|
820
|
-
export async function commitTheme(ctx, slug, data, {history}) {
|
|
1539
|
+
export async function commitTheme(ctx, slug, data, {history, historyAfter}) {
|
|
821
1540
|
const {cwd} = ctx.project;
|
|
822
1541
|
const f = themeFiles(cwd, slug);
|
|
1542
|
+
refuseLinks(cwd, slug);
|
|
823
1543
|
const snapBefore = fs.existsSync(f.settings)
|
|
824
1544
|
? fs.readFileSync(f.settings, 'utf8')
|
|
825
1545
|
: null;
|
|
1546
|
+
/** @type {string[]} */
|
|
1547
|
+
const notes = [];
|
|
1548
|
+
// The history is read and checked before anything is written.
|
|
1549
|
+
const read = history ? readHistory(f.history) : {steps: [], dropped: 0};
|
|
1550
|
+
const past = read.steps;
|
|
1551
|
+
if (read.dropped && !past.length)
|
|
1552
|
+
notes.push(
|
|
1553
|
+
`${path.basename(f.history)} was damaged, so a new undo history starts with this change (earlier steps cannot be undone)`,
|
|
1554
|
+
);
|
|
1555
|
+
else if (read.dropped)
|
|
1556
|
+
notes.push(
|
|
1557
|
+
`${read.dropped} damaged step${read.dropped > 1 ? 's' : ''} in ${path.basename(f.history)} ${read.dropped > 1 ? 'were' : 'was'} dropped; the ${past.length} after ${read.dropped > 1 ? 'them' : 'it'} can still be undone`,
|
|
1558
|
+
);
|
|
1559
|
+
// A change that leaves the settings as they were builds nothing and adds
|
|
1560
|
+
// no undo step.
|
|
1561
|
+
const same = (/** @type {ThemeData | null} */ a) =>
|
|
1562
|
+
a != null &&
|
|
1563
|
+
JSON.stringify({...a, lifted: undefined}) ===
|
|
1564
|
+
JSON.stringify({...data, lifted: undefined});
|
|
1565
|
+
if (history && same(parseSettings(snapBefore)) && fs.existsSync(f.js))
|
|
1566
|
+
return {
|
|
1567
|
+
changed: [],
|
|
1568
|
+
res: {light: {}, dark: {}},
|
|
1569
|
+
problems: [],
|
|
1570
|
+
warnings: [],
|
|
1571
|
+
lifted: [],
|
|
1572
|
+
notes,
|
|
1573
|
+
unchanged: true,
|
|
1574
|
+
};
|
|
826
1575
|
const resBefore =
|
|
827
1576
|
snapBefore && fs.existsSync(f.js)
|
|
828
1577
|
? await resolvedTokens(ctx, slug).catch(() => null)
|
|
829
1578
|
: null;
|
|
830
1579
|
const before = parseSettings(snapBefore);
|
|
831
1580
|
const liftedBefore = new Set(before?.lifted ?? []);
|
|
1581
|
+
// What this run writes is recorded as it writes it, so a failed change
|
|
1582
|
+
// puts back exactly that and nothing else.
|
|
1583
|
+
const rootMade = !fs.existsSync(f.root);
|
|
1584
|
+
const dirMade = !fs.existsSync(f.dir);
|
|
1585
|
+
const was = snapshotDir(f.dir);
|
|
1586
|
+
/** @type {Map<string, string | null>} */
|
|
1587
|
+
const wrote = new Map();
|
|
1588
|
+
ctx.wrote = wrote;
|
|
832
1589
|
fs.mkdirSync(f.dir, {recursive: true});
|
|
833
|
-
/** @type {{warnings: string[], lifted: string[]}} */
|
|
1590
|
+
/** @type {{warnings: string[], lifted: string[], notes: string[]}} */
|
|
834
1591
|
let built;
|
|
835
1592
|
try {
|
|
836
1593
|
built = await buildTheme(ctx, slug, data);
|
|
1594
|
+
data.lifted = built.lifted;
|
|
1595
|
+
// The undo step and the settings are part of the change: written whole,
|
|
1596
|
+
// inside the rollback, the history before the settings.
|
|
1597
|
+
await track(f.dir, wrote, () => {
|
|
1598
|
+
if (historyAfter)
|
|
1599
|
+
writeAtomic(
|
|
1600
|
+
f.history,
|
|
1601
|
+
JSON.stringify(historyAfter.slice(-HISTORY_STEPS)),
|
|
1602
|
+
);
|
|
1603
|
+
else if (snapBefore && history)
|
|
1604
|
+
writeAtomic(
|
|
1605
|
+
f.history,
|
|
1606
|
+
JSON.stringify([...past, snapBefore].slice(-HISTORY_STEPS)),
|
|
1607
|
+
);
|
|
1608
|
+
writeAtomic(f.settings, `${JSON.stringify(data, null, 2)}\n`);
|
|
1609
|
+
});
|
|
837
1610
|
} catch (e) {
|
|
838
|
-
|
|
839
|
-
|
|
840
|
-
|
|
841
|
-
|
|
842
|
-
if (
|
|
1611
|
+
const {failed, skipped} = restoreWritten(was, wrote);
|
|
1612
|
+
removeIfEmpty(path.join(f.dir, 'tokens'));
|
|
1613
|
+
if (dirMade) removeIfEmpty(f.dir);
|
|
1614
|
+
if (rootMade) removeIfEmpty(f.root);
|
|
1615
|
+
if (failed.length || skipped.length)
|
|
1616
|
+
throw new AstryxError(
|
|
1617
|
+
`The change failed (${e instanceof Error ? e.message.split('\n')[0] : String(e)}). ${failed.length ? `These files could not be put back: ${failed.join(', ')}. ` : ''}${skipped.length ? `These files changed while it ran, so they were left as they are: ${skipped.join(', ')}. ` : ''}Run ${P} show ${slug} to rebuild from the settings.`,
|
|
1618
|
+
[{name: `${P} show ${slug}`, reason: 'do this next'}],
|
|
1619
|
+
ERROR_CODES.ERR_WRITE_FAILED,
|
|
1620
|
+
);
|
|
1621
|
+
const code = /** @type {any} */ (e)?.code;
|
|
1622
|
+
if (['EACCES', 'EPERM', 'ENOSPC', 'EROFS', 'EIO', 'EISDIR'].includes(code))
|
|
1623
|
+
throw new AstryxError(
|
|
1624
|
+
`Could not write the theme files (${code}), so the change was undone. Free space or fix the permission, then run the command again.`,
|
|
1625
|
+
[],
|
|
1626
|
+
ERROR_CODES.ERR_WRITE_FAILED,
|
|
1627
|
+
);
|
|
1628
|
+
// The color config's own refusals already name the file and the fix.
|
|
1629
|
+
if (
|
|
1630
|
+
e instanceof AstryxError &&
|
|
1631
|
+
(e.code === ERROR_CODES.ERR_UNKNOWN_THEME ||
|
|
1632
|
+
e.code === ERROR_CODES.ERR_THEME_INVALID ||
|
|
1633
|
+
e.code === ERROR_CODES.ERR_PALETTE_GENERATION)
|
|
1634
|
+
)
|
|
843
1635
|
throw e;
|
|
844
|
-
const why = e instanceof Error ? e.message : String(e)
|
|
1636
|
+
const why = (e instanceof Error ? e.message : String(e))
|
|
1637
|
+
.split(`${cwd}${path.sep}`)
|
|
1638
|
+
.join('')
|
|
1639
|
+
.replace(/\s*Make sure all imports[^|]*$/s, '')
|
|
1640
|
+
.split('\n')
|
|
1641
|
+
.slice(0, 3)
|
|
1642
|
+
.join(' | ');
|
|
1643
|
+
const own = why.includes(path.basename(f.ts));
|
|
845
1644
|
throw new AstryxError(
|
|
846
|
-
`The theme did not build, so the change was undone: ${why
|
|
847
|
-
[
|
|
1645
|
+
`The theme did not build, so the change was undone: ${why}${own ? ` (${shown(cwd, f.ts)} is your own file: fix it, then run the command again)` : ''}`,
|
|
1646
|
+
[
|
|
1647
|
+
{
|
|
1648
|
+
name: `${P} show ${slug}`,
|
|
1649
|
+
reason: 'do this instead: see the settings as they are',
|
|
1650
|
+
},
|
|
1651
|
+
],
|
|
848
1652
|
ERROR_CODES.ERR_THEME_INVALID,
|
|
849
1653
|
);
|
|
850
1654
|
}
|
|
851
|
-
|
|
852
|
-
|
|
853
|
-
|
|
854
|
-
|
|
855
|
-
|
|
856
|
-
: [];
|
|
857
|
-
h.push(snapBefore);
|
|
858
|
-
fs.writeFileSync(f.history, JSON.stringify(h.slice(-80)));
|
|
859
|
-
}
|
|
860
|
-
const res = await resolvedTokens(ctx, slug);
|
|
1655
|
+
notes.push(...built.notes);
|
|
1656
|
+
// The change is saved from here on: a failure to check it is reported
|
|
1657
|
+
// as "saved, not checked", never as a failed change.
|
|
1658
|
+
/** @type {Record<'light' | 'dark', Record<string, string>>} */
|
|
1659
|
+
let res = {light: {}, dark: {}};
|
|
861
1660
|
/** @type {string[]} */
|
|
862
1661
|
const changed = [];
|
|
863
|
-
|
|
864
|
-
|
|
865
|
-
|
|
866
|
-
|
|
867
|
-
|
|
868
|
-
|
|
869
|
-
|
|
870
|
-
|
|
871
|
-
|
|
872
|
-
|
|
1662
|
+
/** @type {string[]} */
|
|
1663
|
+
let problems = [];
|
|
1664
|
+
try {
|
|
1665
|
+
res = await resolvedTokens(ctx, slug);
|
|
1666
|
+
const modes = modesOf(data);
|
|
1667
|
+
if (resBefore) {
|
|
1668
|
+
for (const m of modes) {
|
|
1669
|
+
for (const k of Object.keys(res[m])) {
|
|
1670
|
+
if (resBefore[m][k] === res[m][k]) continue;
|
|
1671
|
+
const modal = MODAL.has(ctx.C.typeOf(k));
|
|
1672
|
+
if (!modal && m === 'dark' && modes.length > 1) continue;
|
|
1673
|
+
changed.push(
|
|
1674
|
+
`${k}${modal && modes.length > 1 ? ` (${m})` : ''}: ${resBefore[m][k]} -> ${res[m][k]}`,
|
|
1675
|
+
);
|
|
1676
|
+
}
|
|
873
1677
|
}
|
|
874
1678
|
}
|
|
1679
|
+
problems = await contrastProblems(ctx, data, res);
|
|
1680
|
+
} catch (e) {
|
|
1681
|
+
ctx.unchecked ??= `checking it failed: ${e instanceof Error ? e.message : String(e)}`;
|
|
875
1682
|
}
|
|
876
1683
|
return {
|
|
877
1684
|
changed,
|
|
878
1685
|
res,
|
|
879
|
-
problems
|
|
1686
|
+
problems,
|
|
880
1687
|
warnings: built.warnings,
|
|
881
1688
|
lifted: built.lifted.filter(x => !liftedBefore.has(x)),
|
|
1689
|
+
notes,
|
|
1690
|
+
unchanged: false,
|
|
882
1691
|
};
|
|
883
1692
|
}
|
|
884
1693
|
|