@astryxdesign/cli 0.7.14 → 0.7.15-canary.g06b7e61

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.
Files changed (203) hide show
  1. package/CHANGELOG.md +3 -3
  2. package/README.md +63 -63
  3. package/api/build/_adapter.d.mts +4 -0
  4. package/api/build/_adapter.mjs +28 -2
  5. package/api/build/blocks/blocks.d.mts +10 -1
  6. package/api/build/blocks/blocks.mjs +84 -7
  7. package/api/build/build.mjs +6 -1
  8. package/api/build/tree.d.mts +4 -0
  9. package/api/build/tree.mjs +9 -2
  10. package/api/doctor/_adapter.d.mts +3 -1
  11. package/api/doctor/_adapter.mjs +14 -1
  12. package/api/doctor/_authoring-audit.d.mts +42 -0
  13. package/api/doctor/_authoring-audit.mjs +106 -0
  14. package/api/doctor/doctor.d.mts +7 -0
  15. package/api/doctor/doctor.mjs +24 -39
  16. package/api/doctor/theme-checks.mjs +56 -21
  17. package/api/integration/add-helpers.mjs +5 -0
  18. package/api/integration/add-theme.mjs +15 -110
  19. package/api/integration/validate-integration.mjs +17 -3
  20. package/api/integration/validateIntegration.doc.mjs +1 -1
  21. package/api/search/_adapter.mjs +124 -3
  22. package/api/search/_candidate-score.mjs +63 -9
  23. package/api/search/_entries.d.mts +10 -0
  24. package/api/search/_entries.mjs +68 -1
  25. package/api/search/_gather-templates.d.mts +11 -0
  26. package/api/search/_gather-templates.mjs +22 -2
  27. package/api/search/_words.mjs +26 -6
  28. package/api/swizzle/copy/copy.mjs +1 -1
  29. package/api/theme/_adapter.d.mts +37 -5
  30. package/api/theme/_adapter.mjs +381 -57
  31. package/api/theme/_fork.d.mts +90 -0
  32. package/api/theme/_fork.mjs +246 -0
  33. package/api/theme/build/build.d.mts +40 -2
  34. package/api/theme/build/build.mjs +477 -66
  35. package/api/theme/eject/eject.mjs +36 -15
  36. package/api/theme/list/list.mjs +3 -6
  37. package/api/theme/palette/generate/generator.d.mts +13 -0
  38. package/api/theme/palette/generate/generator.mjs +32 -2
  39. package/api/theme/targets/targets.d.mts +8 -0
  40. package/api/theme/targets/targets.mjs +24 -4
  41. package/api/theme/template/template.mjs +48 -2
  42. package/api/theme/theme.type.d.mts +8 -0
  43. package/api/theme/theme.type.mjs +5 -1
  44. package/api/theme/themeBuild.doc.mjs +7 -4
  45. package/api/theme/themeEject.doc.mjs +3 -3
  46. package/api/theme/themeRemove.doc.mjs +5 -2
  47. package/api/theme/themeTargets.doc.mjs +1 -1
  48. package/api/theme/themeTemplate.doc.mjs +2 -2
  49. package/api/theme/themeUse.doc.mjs +8 -2
  50. package/api/theme-edit/_adapter.d.mts +46 -3
  51. package/api/theme-edit/_adapter.mjs +496 -112
  52. package/api/theme-edit/_catalog.d.mts +1 -6
  53. package/api/theme-edit/_catalog.mjs +5 -268
  54. package/api/theme-edit/_check.d.mts +9 -4
  55. package/api/theme-edit/_check.mjs +1232 -229
  56. package/api/theme-edit/_color.d.mts +19 -0
  57. package/api/theme-edit/_color.mjs +280 -34
  58. package/api/theme-edit/_compiler.d.mts +3 -1
  59. package/api/theme-edit/_compiler.mjs +52 -13
  60. package/api/theme-edit/_context.d.mts +4 -1
  61. package/api/theme-edit/_context.mjs +126 -13
  62. package/api/theme-edit/_css.d.mts +84 -0
  63. package/api/theme-edit/_css.mjs +700 -0
  64. package/api/theme-edit/_edit.d.mts +9 -3
  65. package/api/theme-edit/_edit.mjs +806 -103
  66. package/api/theme-edit/_how-commands.d.mts +38 -7
  67. package/api/theme-edit/_how-commands.mjs +64 -45
  68. package/api/theme-edit/_how-question.d.mts +33 -0
  69. package/api/theme-edit/_how-question.mjs +2553 -381
  70. package/api/theme-edit/_how.mjs +402 -31
  71. package/api/theme-edit/_overview.mjs +2 -7
  72. package/api/theme-edit/_palette.d.mts +60 -13
  73. package/api/theme-edit/_palette.mjs +826 -295
  74. package/api/theme-edit/_parts.d.mts +42 -10
  75. package/api/theme-edit/_parts.mjs +280 -69
  76. package/api/theme-edit/_png.d.mts +4 -4
  77. package/api/theme-edit/_png.mjs +4 -2
  78. package/api/theme-edit/_preview-app.d.mts +14 -0
  79. package/api/theme-edit/_preview-app.mjs +1675 -235
  80. package/api/theme-edit/_preview.d.mts +7 -16
  81. package/api/theme-edit/_preview.mjs +79 -86
  82. package/api/theme-edit/_project.d.mts +32 -2
  83. package/api/theme-edit/_project.mjs +80 -19
  84. package/api/theme-edit/_settings.d.mts +199 -52
  85. package/api/theme-edit/_settings.mjs +1422 -217
  86. package/api/theme-edit/_tables.d.mts +19 -6
  87. package/api/theme-edit/_tables.mjs +150 -92
  88. package/api/theme-edit/theme-edit.type.d.mts +20 -1
  89. package/api/theme-edit/theme-edit.type.mjs +6 -3
  90. package/api/theme-edit/themeEditHow.doc.mjs +6 -0
  91. package/api/theme-edit/themeEditNew.doc.mjs +1 -1
  92. package/api/theme-edit/themeEditPreviewAdd.doc.mjs +1 -1
  93. package/api/theme-edit/themeEditPreviewApp.doc.mjs +1 -1
  94. package/api/theme-edit/themeEditPreviewList.doc.mjs +2 -2
  95. package/api/theme-edit/themeEditPreviewRemove.doc.mjs +5 -1
  96. package/api/theme-edit/themeEditSet.doc.mjs +1 -1
  97. package/api/theme-edit/themeEditUndo.doc.mjs +1 -1
  98. package/api/upgrade/_adapter.d.mts +1 -0
  99. package/assets/codemods/run-codemod.mjs +61 -0
  100. package/assets/codemods/runner.mjs +5 -4
  101. package/assets/codemods/transforms/v0.0.14/rename-status-variants.mjs +3 -0
  102. package/assets/codemods/transforms/v0.1.8/rename-avatar-size-scale.mjs +5 -1
  103. package/assets/codemods/transforms/v0.6.4/migrate-native-picker-to-presentation.mjs +3 -0
  104. package/assets/codemods/transforms/v0.7.0/migrate-deprecated-theme-surface.mjs +4 -0
  105. package/assets/codemods/transforms/v0.7.0/rename-empty-search-results-text.mjs +17 -12
  106. package/assets/codemods/transforms/v0.7.2/migrate-list-edge-compensation-to-edge.mjs +3 -0
  107. package/assets/codemods/transforms/v0.7.5/migrate-codeblock-tokenizer-to-language.mjs +3 -0
  108. package/assets/codemods/transforms/v0.7.8/promote-tokenizer-presentation.mjs +3 -0
  109. package/assets/docs/tree/calendars.doc.mjs +1 -3
  110. package/assets/docs/tree/checks.doc.mjs +22 -1
  111. package/assets/docs/tree/publishing.doc.mjs +1 -0
  112. package/assets/docs/tree/tokens-and-setup.doc.mjs +39 -3
  113. package/assets/docs.generated.json +2 -1
  114. package/assets/preview-app/next.config.mjs +7 -1
  115. package/assets/self-audit.generated.json +1 -0
  116. package/assets/templates/blocks/components/Theme/useThemeNameHookUsage.doc.mjs +14 -0
  117. package/assets/templates/blocks/components/Theme/useThemeNameHookUsage.tsx +31 -0
  118. package/assets/templates/components.generated.json +1 -1
  119. package/authoring/integration/integration.doc.mjs +8 -0
  120. package/authoring/integration/schema.d.mts +8 -0
  121. package/authoring/integration/schema.mjs +1 -0
  122. package/authoring/integration/type.ts +9 -0
  123. package/clients/cli/bin/astryx.mjs +19 -15
  124. package/clients/cli/build-id.generated.json +1 -0
  125. package/clients/cli/commands/ensure-core-built.mjs +12 -5
  126. package/clients/cli/commands/experimental/index.mjs +10 -10
  127. package/clients/cli/commands/experimental/theme.mjs +200 -81
  128. package/clients/cli/commands/experimental-theme-compile.doc.mjs +3 -3
  129. package/clients/cli/commands/experimental-theme-editor-how.doc.mjs +1 -1
  130. package/clients/cli/commands/experimental-theme-editor-new.doc.mjs +3 -3
  131. package/clients/cli/commands/experimental-theme-editor-set.doc.mjs +1 -2
  132. package/clients/cli/commands/experimental-theme-editor-show.doc.mjs +1 -1
  133. package/clients/cli/commands/experimental-theme-editor-undo.doc.mjs +2 -2
  134. package/clients/cli/commands/experimental-theme-editor.doc.mjs +1 -1
  135. package/clients/cli/commands/experimental-theme-eject.doc.mjs +3 -3
  136. package/clients/cli/commands/experimental-theme-preview-add.doc.mjs +1 -1
  137. package/clients/cli/commands/experimental-theme-preview-app.doc.mjs +1 -1
  138. package/clients/cli/commands/experimental-theme-preview-list.doc.mjs +1 -1
  139. package/clients/cli/commands/experimental-theme-preview-remove.doc.mjs +1 -1
  140. package/clients/cli/commands/experimental-theme-remove.doc.mjs +1 -1
  141. package/clients/cli/commands/experimental-theme-template.doc.mjs +4 -3
  142. package/clients/cli/commands/integration.mjs +8 -0
  143. package/clients/cli/commands/manifest.mjs +5 -2
  144. package/clients/cli/commands/theme-build.doc.mjs +2 -2
  145. package/clients/cli/commands/theme-list.doc.mjs +1 -1
  146. package/clients/cli/commands/theme-template.doc.mjs +1 -1
  147. package/clients/cli/commands/theme.mjs +439 -66
  148. package/clients/cli/index.mjs +27 -6
  149. package/clients/cli/lib/cli-error.mjs +118 -3
  150. package/clients/cli/lib/manifest.mjs +37 -0
  151. package/clients/cli/lib/resolve-theme.mjs +2 -1
  152. package/clients/cli/manifest.generated.json +1 -0
  153. package/foundation/config/project.mjs +34 -8
  154. package/foundation/config/theme-state.d.mts +16 -0
  155. package/foundation/config/theme-state.mjs +84 -13
  156. package/foundation/discovery/module-exports.mjs +16 -2
  157. package/foundation/discovery/stored-self-audit.d.mts +31 -0
  158. package/foundation/discovery/stored-self-audit.mjs +119 -0
  159. package/foundation/discovery/template-adapter.d.mts +48 -2
  160. package/foundation/discovery/template-adapter.mjs +51 -19
  161. package/foundation/discovery/template-needs.d.mts +19 -0
  162. package/foundation/discovery/template-needs.mjs +50 -16
  163. package/foundation/discovery/template-source-tree.d.mts +7 -0
  164. package/foundation/discovery/template-source-tree.mjs +15 -0
  165. package/foundation/discovery/theme-discovery.d.mts +2 -1
  166. package/foundation/discovery/theme-discovery.mjs +16 -10
  167. package/foundation/discovery/theme-imports.d.mts +16 -0
  168. package/foundation/discovery/theme-imports.mjs +30 -2
  169. package/foundation/discovery/theme-module-extensions.d.mts +18 -0
  170. package/foundation/discovery/theme-module-extensions.mjs +30 -0
  171. package/foundation/doc-compiler/import.mjs +22 -15
  172. package/foundation/doc-compiler/stored-docs.d.mts +18 -12
  173. package/foundation/doc-compiler/stored-docs.mjs +52 -19
  174. package/foundation/env/private-dir.d.mts +17 -0
  175. package/foundation/env/private-dir.mjs +42 -0
  176. package/foundation/fs/gather-cache.d.mts +108 -0
  177. package/foundation/fs/gather-cache.mjs +783 -0
  178. package/foundation/fs/jiti-cache.d.mts +21 -0
  179. package/foundation/fs/jiti-cache.mjs +66 -0
  180. package/foundation/fs/module-loader.mjs +14 -3
  181. package/foundation/fs/read-record.d.mts +31 -1
  182. package/foundation/fs/read-record.mjs +100 -7
  183. package/foundation/integrations/autolink.d.mts +1 -24
  184. package/foundation/integrations/autolink.mjs +7 -60
  185. package/foundation/integrations/declared-dependencies.d.mts +27 -0
  186. package/foundation/integrations/declared-dependencies.mjs +73 -0
  187. package/foundation/integrations/integrations.d.mts +8 -0
  188. package/foundation/integrations/integrations.mjs +4 -0
  189. package/foundation/integrations/may-have-integrations.d.mts +8 -0
  190. package/foundation/integrations/may-have-integrations.mjs +47 -0
  191. package/foundation/integrations/validate-contributions.d.mts +62 -1
  192. package/foundation/integrations/validate-contributions.mjs +476 -40
  193. package/foundation/release/cache.d.mts +32 -4
  194. package/foundation/release/cache.mjs +105 -16
  195. package/foundation/release/folder-lock.d.mts +28 -0
  196. package/foundation/release/folder-lock.mjs +205 -0
  197. package/foundation/release/lock-lease.d.mts +2 -1
  198. package/foundation/release/lock-lease.mjs +7 -2
  199. package/foundation/response/error-codes.doc.mjs +1 -1
  200. package/foundation/response/response-types.doc.mjs +5 -5
  201. package/package.json +8 -6
  202. package/api/theme-edit/_css-properties.d.mts +0 -10
  203. package/api/theme-edit/_css-properties.mjs +0 -556
@@ -10,11 +10,14 @@
10
10
  */
11
11
 
12
12
  import * as fs from 'node:fs';
13
+ import * as path from 'node:path';
13
14
  import {AstryxError} from '../error.mjs';
14
15
  import {
15
16
  AUTO_SPREAD,
17
+ CORNERS,
16
18
  DIALS,
17
19
  FAMILIES,
20
+ FONT_ROLES,
18
21
  KEY_TOKENS,
19
22
  LIKE,
20
23
  P,
@@ -26,6 +29,8 @@ import {
26
29
  commitTheme,
27
30
  compileTheme,
28
31
  cornerPx,
32
+ radiusAt,
33
+ radiusTokenOf,
29
34
  contrastProblems,
30
35
  describe,
31
36
  keyOf,
@@ -33,9 +38,7 @@ import {
33
38
  maskedSettings,
34
39
  modesOf,
35
40
  nearest,
36
- partDefault,
37
41
  partsOf,
38
- q,
39
42
  undoArgs,
40
43
  withoutBadValues,
41
44
  NAME_RULE,
@@ -48,19 +51,33 @@ import {
48
51
  themeFiles,
49
52
  buildTheme,
50
53
  staleBuild,
54
+ EDITOR_SUFFIXES,
55
+ madeByEditor,
56
+ NEW_MARKER,
57
+ clearNewMarker,
58
+ refuseThemeSource,
59
+ settingsShapeOk,
60
+ slugFor,
61
+ themeSource,
62
+ themeSourceProblem,
51
63
  } from './_settings.mjs';
52
- import {checkSetting, exampleOf, storedTokenProblem} from './_check.mjs';
64
+ import {checkSetting, exampleOf, storedProblems} from './_check.mjs';
53
65
  import {MODAL} from './_compiler.mjs';
54
66
  import {
55
67
  PALETTE_DIALS,
56
68
  VIBRANCY_DEFAULT,
57
69
  paletteFiles,
58
70
  paletteMapping,
71
+ paletteDialOf,
59
72
  paletteNotes,
73
+ lockHeld,
74
+ refuseIfLockLost,
75
+ writeWhole,
60
76
  } from './_palette.mjs';
61
77
  import {renderPreview, renderSheet} from './_preview.mjs';
62
78
  import {refreshPreviewRoute} from './_preview-app.mjs';
63
- import {baseResolved} from './_project.mjs';
79
+ import {baseResolved, installLine} from './_project.mjs';
80
+ import {reactMissing} from './_parts.mjs';
64
81
  import {
65
82
  requireProject,
66
83
  context,
@@ -71,12 +88,95 @@ import {
71
88
  checkSection,
72
89
  } from './_context.mjs';
73
90
  import {ERROR_CODES} from '../../foundation/response/error-codes.mjs';
91
+ import {quoteCommandArgument} from '../../foundation/env/package-manager.mjs';
74
92
 
75
93
  const E = ERROR_CODES;
76
94
 
77
95
  /**
78
96
  * @typedef {import('./theme-edit.type.mjs').ThemeEditChangeOptions} ChangeOptions
79
97
  */
98
+ /** The marker a `new` writes first and removes last. */
99
+
100
+ /** Files a system or a tool puts in any folder; a folder of only these is empty. */
101
+ const FOLDER_JUNK = new Set(['.DS_Store', '.gitkeep', 'Thumbs.db']);
102
+
103
+ /**
104
+ * A folder the editor made but that has no settings: a stopped `new` left
105
+ * its marker, or the settings were removed beside the editor's generated
106
+ * module. `clear` is what `new` makes again (the files the editor writes
107
+ * for that name, the source only exactly as it writes it); `keep` is every
108
+ * other file, which is never touched. Null when the editor did not make
109
+ * the folder. System files (.DS_Store) are in neither.
110
+ * @param {string} dir
111
+ * @param {string} slug
112
+ * @param {boolean} [damaged] its settings are there but not valid JSON
113
+ * @returns {{clear: string[], keep: string[]} | null}
114
+ */
115
+ function editorLeftovers(dir, slug, damaged = false) {
116
+ // The editor made this folder: a stopped `new` left its marker, the
117
+ // generated settings module (which carries the editor's header) is there
118
+ // without its settings, or its settings are there but damaged (kept
119
+ // aside by `new`, so neither cleared nor kept here).
120
+ const marked = fs.existsSync(path.join(dir, NEW_MARKER));
121
+ if (
122
+ !marked &&
123
+ !damaged &&
124
+ !madeByEditor(path.join(dir, `${slug}.settings.ts`))
125
+ )
126
+ return null;
127
+ /** @type {string[]} */
128
+ const clear = [];
129
+ /** @type {string[]} */
130
+ const keep = [];
131
+ const named = (/** @type {string} */ n) =>
132
+ n === NEW_MARKER ||
133
+ EDITOR_SUFFIXES.some(x => n === `${slug}.${x}`) ||
134
+ /^(preview(-[a-z]+)?\.(html|png)|sheet(-[a-z-]+)?\.(html|png)|palette\.config\.json)$/.test(
135
+ n,
136
+ ) ||
137
+ // The editor's temp names: `.<name>.astryx-<pid>-<rand>.tmp`, and the
138
+ // build's `.<name>.tmp-<id>`.
139
+ /^\..+\.(astryx-\d+-[a-z0-9]+\.tmp|tmp-[\w-]+)$/.test(n);
140
+ for (const e of fs.readdirSync(dir, {withFileTypes: true})) {
141
+ const p = path.join(dir, e.name);
142
+ if (FOLDER_JUNK.has(e.name)) continue;
143
+ if (damaged && e.name === `${slug}.settings.json`) continue;
144
+ if (e.isDirectory() && e.name === 'tokens') {
145
+ for (const t of fs.readdirSync(p, {withFileTypes: true}))
146
+ (t.isFile() && t.name.startsWith(`${slug}.palette`)
147
+ ? clear
148
+ : keep
149
+ ).push(path.join(p, t.name));
150
+ continue;
151
+ }
152
+ // The source as the editor writes it is made again; one changed by hand
153
+ // is the user's, and stays. The history stays too when the settings were
154
+ // removed, so `undo` can step back to them.
155
+ const mine =
156
+ e.isFile() &&
157
+ (e.name === `${slug}.theme.ts`
158
+ ? fs.readFileSync(p, 'utf8') === themeSource(slug)
159
+ : // A `new` writes no history: one here is from later commands,
160
+ // and always stays.
161
+ e.name === `${slug}.history.json`
162
+ ? false
163
+ : named(e.name));
164
+ (mine ? clear : keep).push(p);
165
+ }
166
+ return {clear, keep};
167
+ }
168
+
169
+ /** Whether a settings file parses, in the shape the editor reads. @param {string} file */
170
+ function readableJson(file) {
171
+ try {
172
+ return settingsShapeOk(
173
+ JSON.parse(fs.readFileSync(file, 'utf8').replace(/^\uFEFF/, '')),
174
+ );
175
+ } catch {
176
+ return false;
177
+ }
178
+ }
179
+
80
180
  /**
81
181
  * Start a theme in themes/<name>/, optionally on a built-in theme, with any
82
182
  * dial settings applied in the same build. Each setting is checked as `set`
@@ -87,44 +187,66 @@ const E = ERROR_CODES;
87
187
  * @returns {Promise<import('./theme-edit.type.mjs').ThemeEditNewResponse>}
88
188
  */
89
189
  export async function themeEditNew(name, options = {}) {
90
- const {cwd = process.cwd(), like, png = false, settings = {}} = options;
190
+ const {cwd = process.cwd(), png = false, settings = {}} = options;
191
+ // `--like none` builds on no base, as `set <theme> base none` does.
192
+ const like = options.like === 'none' ? undefined : options.like;
91
193
  requireProject(cwd);
92
194
  if (!slugOk(name)) {
93
- const fixed =
94
- String(name ?? '')
95
- .normalize('NFKD')
96
- .replace(/[\u0300-\u036f]/g, '')
97
- .toLowerCase()
98
- .replace(/[^a-z0-9-]+/g, '-')
99
- .replace(/^[^a-z]+/, '')
100
- .replace(/-+$/, '')
101
- .slice(0, 64) || 'my-theme';
195
+ const fixed = slugFor(name);
196
+ // The name as typed may be a theme that exists in another case.
197
+ const exists = fs.existsSync(themeFiles(cwd, fixed).settings);
102
198
  refuse(
103
199
  E.ERR_INVALID_ARGUMENT,
104
- `"${String(name ?? '').slice(0, 80)}" is not a theme name (${NAME_RULE}).`,
105
- {run: [`${P} new ${fixed}`]},
200
+ `"${String(name ?? '').slice(0, 80)}" is not a theme name (${NAME_RULE})${exists ? `; ${fixed} is a theme here already` : ''}.`,
201
+ {run: exists ? [`${P} show ${fixed}`] : [`${P} new ${fixed}`]},
106
202
  );
107
203
  }
204
+ // A built-in theme's name would collide with the theme of that name the
205
+ // app may also use.
206
+ if (LIKE.includes(name))
207
+ refuse(
208
+ E.ERR_FILE_EXISTS,
209
+ `${name} is a built-in theme; an editor theme needs a name of its own. To start from ${name}, build on it.`,
210
+ {run: [`${P} new my-${name} --like ${name}`]},
211
+ );
108
212
  const f = themeFiles(cwd, name);
109
213
  // A link or a file where the theme goes is never written through or
110
214
  // replaced.
111
- for (const [p, what] of /** @type {const} */ ([
112
- [f.root, 'themes/'],
113
- [f.dir, `themes/${name}`],
114
- ])) {
115
- const st = fs.lstatSync(p, {throwIfNoEntry: false});
116
- if (st && (st.isSymbolicLink() || !st.isDirectory()))
117
- refuse(
118
- E.ERR_FILE_EXISTS,
119
- `${what} is ${st.isSymbolicLink() ? 'a link' : 'a file'}, so a theme is not made there.`,
120
- {run: [`${P} new ${name}-copy`]},
121
- );
122
- }
123
- if (fs.existsSync(f.settings))
215
+ // themes/ itself in the way blocks every name: say so, and how to fix it.
216
+ const rootSt = fs.lstatSync(f.root, {throwIfNoEntry: false});
217
+ if (rootSt && (rootSt.isSymbolicLink() || !rootSt.isDirectory()))
218
+ refuse(
219
+ E.ERR_FILE_EXISTS,
220
+ `themes in this app is ${rootSt.isSymbolicLink() ? `a link (to ${fs.readlinkSync(f.root)})` : 'a file'}, not a folder, so no editor theme can be made: every theme goes in themes/<name>/. Rename or move it, then run new again.`,
221
+ // A look that changes nothing: the themes the app can use now.
222
+ {run: ['astryx theme list']},
223
+ );
224
+ const dirSt = fs.lstatSync(f.dir, {throwIfNoEntry: false});
225
+ if (dirSt && (dirSt.isSymbolicLink() || !dirSt.isDirectory()))
226
+ refuse(
227
+ E.ERR_FILE_EXISTS,
228
+ `themes/${name} is ${dirSt.isSymbolicLink() ? 'a link' : 'a file'}, so a theme is not made there.`,
229
+ {run: [`${P} new ${name}-copy`]},
230
+ );
231
+ // Settings that are not valid JSON are kept aside, and the theme is
232
+ // made again beside them.
233
+ const damaged = fs.existsSync(f.settings) && !readableJson(f.settings);
234
+ if (fs.existsSync(f.settings) && !damaged)
124
235
  refuse(E.ERR_FILE_EXISTS, `Theme "${name}" already exists.`, {
125
236
  run: [`${P} show ${name}`, `${P} set ${name} base neutral`],
126
237
  });
127
- if (fs.existsSync(f.dir) && fs.readdirSync(f.dir).length)
238
+ // A `new` stopped part way (killed, out of memory) leaves its own marker
239
+ // beside the files it wrote: only such a folder is cleared, and only
240
+ // after every argument is checked. Anything else in the folder, or a
241
+ // folder without the marker, is never touched.
242
+ const left = fs.existsSync(f.dir)
243
+ ? editorLeftovers(f.dir, name, damaged)
244
+ : null;
245
+ const holdsOther =
246
+ fs.existsSync(f.dir) &&
247
+ !left &&
248
+ fs.readdirSync(f.dir).some(n => !FOLDER_JUNK.has(n));
249
+ if (holdsOther)
128
250
  refuse(
129
251
  E.ERR_FILE_EXISTS,
130
252
  `themes/${name}/ already holds files this command did not make; choose another name.`,
@@ -146,13 +268,125 @@ export async function themeEditNew(name, options = {}) {
146
268
  ctx.project,
147
269
  data.like,
148
270
  );
271
+ // Every check comes before the first change to the folder: the settings,
272
+ // and a source of the user's own kept from before (it must still extend
273
+ // the settings, or the build fails after the folder was cleared).
149
274
  applyNewSettings(ctx, name, data, settings);
150
- const r = await commitTheme(ctx, name, data, {history: false});
275
+ if (left?.keep.some(p => path.basename(p) === `${name}.theme.ts`))
276
+ refuseThemeSource(cwd, name);
277
+ /** @type {string[]} */
278
+ const keptNotes = [];
279
+ /** @type {string[]} */
280
+ const leftNotes = [];
281
+ const ownKept = (left?.keep ?? []).filter(
282
+ p => path.basename(p) !== `${name}.history.json`,
283
+ );
284
+ if (ownKept.length)
285
+ leftNotes.push(
286
+ `kept your own files in themes/${name}/: ${ownKept
287
+ .slice(0, 4)
288
+ .map(p => path.relative(f.dir, p))
289
+ .join(', ')}${ownKept.length > 4 ? ', …' : ''}`,
290
+ );
291
+ if (left?.keep.some(p => path.basename(p) === `${name}.history.json`))
292
+ leftNotes.push(
293
+ `the earlier settings are kept in ${name}.history.json: \`${P} undo ${name}\` steps back to them`,
294
+ );
295
+ // The marker goes first and comes off last: a `new` stopped between
296
+ // leaves a folder the next `new` can prove it made. The damaged settings
297
+ // are moved aside after it, and back on a failure.
298
+ const dirMade = !fs.existsSync(f.dir);
299
+ fs.mkdirSync(f.dir, {recursive: true});
300
+ const marker = path.join(f.dir, NEW_MARKER);
301
+ // Fenced like every write under the theme lock.
302
+ writeWhole(marker, JSON.stringify({pid: process.pid, started: Date.now()}));
303
+ /** @type {string | null} */
304
+ let aside = null;
305
+ if (damaged) {
306
+ let n = 1;
307
+ const at = (/** @type {number} */ k) =>
308
+ path.join(f.dir, `${name}.settings.damaged${k > 1 ? `-${k}` : ''}.json`);
309
+ while (fs.existsSync(at(n))) n++;
310
+ aside = at(n);
311
+ refuseIfLockLost();
312
+ fs.renameSync(f.settings, aside);
313
+ keptNotes.push(
314
+ `${name}.settings.json was damaged: it is kept as ${path.basename(aside)}, and the theme was made again`,
315
+ );
316
+ }
317
+ // A file this build writes again is newer than this moment.
318
+ const before = new Map(
319
+ (left?.clear ?? []).map(p => [
320
+ p,
321
+ fs.statSync(p, {throwIfNoEntry: false})?.mtimeMs ?? null,
322
+ ]),
323
+ );
324
+ /** @type {Awaited<ReturnType<typeof commitTheme>>} */
325
+ let r;
326
+ try {
327
+ r = await commitTheme(ctx, name, data, {history: false});
328
+ } catch (e) {
329
+ // A command that lost its lock owns none of these files now: it puts
330
+ // nothing back and removes nothing.
331
+ if (/** @type {any} */ (e)?.lockLost || !lockHeld()) refuseIfLockLost();
332
+ if (aside && !fs.existsSync(f.settings)) fs.renameSync(aside, f.settings);
333
+ fs.rmSync(marker, {force: true});
334
+ if (dirMade)
335
+ try {
336
+ fs.rmdirSync(f.dir);
337
+ } catch {
338
+ // It holds something else now.
339
+ }
340
+ throw e;
341
+ }
342
+ // Only after the theme is made: the editor's old files this build did not
343
+ // write again go (old pictures, a stopped run's temp files).
344
+ if (left && left.clear.length) {
345
+ // The build's own outputs are its now; the rest (old pictures, a
346
+ // stopped run's temp files and history) goes when this build did not
347
+ // write it again.
348
+ const outputs = [
349
+ 'css',
350
+ 'js',
351
+ 'd.ts',
352
+ 'css.d.ts',
353
+ 'settings.ts',
354
+ // The source exactly as the editor writes it, which the build keeps.
355
+ 'theme.ts',
356
+ ].map(x => `${name}.${x}`);
357
+ const gone = left.clear.filter(p => {
358
+ if (path.basename(p) === NEW_MARKER) return false;
359
+ if (outputs.includes(path.basename(p))) return false;
360
+ const now = fs.statSync(p, {throwIfNoEntry: false})?.mtimeMs;
361
+ return now != null && now === before.get(p);
362
+ });
363
+ refuseIfLockLost();
364
+ for (const p of gone) fs.rmSync(p, {force: true});
365
+ try {
366
+ fs.rmdirSync(path.join(f.dir, 'tokens'));
367
+ } catch {
368
+ // Not there, or it holds something else.
369
+ }
370
+ const stopped = left.clear.some(p => path.basename(p) === NEW_MARKER);
371
+ const shownLeft = left.clear.filter(p => path.basename(p) !== NEW_MARKER);
372
+ leftNotes.unshift(
373
+ `made the theme again over ${shownLeft.length} file${shownLeft.length === 1 ? '' : 's'} ${stopped ? 'a stopped `new` left' : 'the editor had left'} in themes/${name}/ (${shownLeft
374
+ .slice(0, 4)
375
+ .map(p => path.relative(f.dir, p))
376
+ .join(', ')}${shownLeft.length > 4 ? ', …' : ''})`,
377
+ );
378
+ }
379
+ refuseIfLockLost();
380
+ fs.rmSync(marker, {force: true});
151
381
  const p = await previewAndRoute(ctx, name, data, png);
152
382
  /** @type {string[]} */
153
- const notes = data.settings.some(s => s.thing === 'font')
154
- ? fontNotes(ctx, data)
155
- : [];
383
+ const notes = [
384
+ ...keptNotes,
385
+ ...leftNotes,
386
+ ...(data.settings.some(s => s.thing === 'font')
387
+ ? fontNotes(ctx, data)
388
+ : []),
389
+ ];
156
390
  return {
157
391
  type: 'themeEdit.new',
158
392
  data: {
@@ -225,7 +459,11 @@ function applyNewSettings(ctx, slug, data, settings) {
225
459
  refuse(
226
460
  E.ERR_INVALID_ARGUMENT,
227
461
  `--${thing} was given two values for the same thing (${data.settings[same].value}, ${s.value}); give one.`,
228
- {run: [`${P} new ${slug} --${thing} ${q(s.value)}`]},
462
+ {
463
+ run: [
464
+ `${P} new ${slug} --${thing} ${quoteCommandArgument(s.value)}`,
465
+ ],
466
+ },
229
467
  );
230
468
  data.settings.push(s);
231
469
  }
@@ -245,7 +483,7 @@ function asNewRefusal(e, slug, settings) {
245
483
  const flags = Object.entries(settings)
246
484
  .filter(([, v]) => v != null)
247
485
  .flatMap(([k, v]) => (Array.isArray(v) ? v : [v]).map(x => [k, x]))
248
- .map(([k, v]) => `--${k} ${q(v)}`);
486
+ .map(([k, v]) => `--${k} ${quoteCommandArgument(String(v))}`);
249
487
  const setPrefix = `${P} set ${slug} `;
250
488
  e.suggestions = (e.suggestions ?? []).map(s => {
251
489
  if (s.name === `${P} set --help`) return {...s, name: `${P} new --help`};
@@ -317,18 +555,30 @@ export async function themeEditSet(theme, thing, value, options = {}) {
317
555
  * @param {string} [skip]
318
556
  */
319
557
  function refuseStoredTokens(ctx, slug, data, skip) {
320
- const bad = storedTokenProblem(ctx, slug, data, skip);
321
- if (bad)
322
- refuse(
323
- E.ERR_THEME_INVALID,
324
- `themes/${slug}/${slug}.settings.json: ${describe(bad.setting)} holds a value the editor no longer accepts (${bad.why}).`,
325
- {
326
- run: [
327
- `${P} undo ${slug} ${undoArgs(bad.setting)}`,
328
- `${P} set ${slug} ${bad.setting.thing} ${q(exampleOf(ctx.C.typeOf(bad.setting.thing), bad.setting.thing))}`,
329
- ],
330
- },
331
- );
558
+ const bad = storedProblems(ctx, slug, data, skip);
559
+ if (!bad.length) return;
560
+ const one = bad.length === 1 ? bad[0] : null;
561
+ refuse(
562
+ E.ERR_THEME_INVALID,
563
+ `themes/${slug}/${slug}.settings.json: ${bad
564
+ .map(
565
+ b =>
566
+ `${describe(b.setting)} ${b.scope ? 'applies where the editor does not accept it' : 'holds a value the editor no longer accepts'} (${b.why})`,
567
+ )
568
+ .join('; ')}.`,
569
+ {
570
+ // Each undo runs while the others are still saved: an undo of one
571
+ // setting is never refused for another.
572
+ run: [
573
+ ...bad.slice(0, 5).map(b => `${P} undo ${slug} ${undoArgs(b.setting)}`),
574
+ ...(one && !one.scope
575
+ ? [
576
+ `${P} set ${slug} ${one.setting.thing} ${quoteCommandArgument(exampleOf(ctx.C.typeOf(one.setting.thing), one.setting.thing))}`,
577
+ ]
578
+ : []),
579
+ ],
580
+ },
581
+ );
332
582
  }
333
583
 
334
584
  /**
@@ -363,9 +613,37 @@ function extremeSteps(res) {
363
613
  async function change(sub, slug, thing, value, options) {
364
614
  const {cwd = process.cwd(), png = false} = options;
365
615
  requireProject(cwd);
366
- const data = loadTheme(cwd, slug, thing);
616
+ // The setting this command changes or removes may be the bad one; any
617
+ // other bad setting still refuses (or is left out when this fixes one).
618
+ const target = /** @type {Partial<import('./_settings.mjs').Setting>} */ ({
619
+ thing,
620
+ on: options.on,
621
+ when: options.when,
622
+ state: options.state,
623
+ mode: options.mode,
624
+ });
625
+ const data = loadTheme(cwd, slug, target);
626
+ /** @type {string[]} */
627
+ const fieldNotes = [];
628
+ if (sub === 'set' && (thing === 'base' || thing === 'mode')) {
629
+ // The other field, when it is damaged too, goes back to its default,
630
+ // so the theme loads again.
631
+ if (
632
+ thing !== 'mode' &&
633
+ !['both', 'light-only', 'dark-only'].includes(data.mode)
634
+ ) {
635
+ data.mode = 'both';
636
+ fieldNotes.push('mode was missing or damaged, so it is both again');
637
+ }
638
+ if (thing !== 'base' && data.like != null && !LIKE.includes(data.like)) {
639
+ delete data.like;
640
+ fieldNotes.push('base was not a built-in theme, so it is none again');
641
+ }
642
+ }
367
643
  const ctx = await context(cwd);
368
- refuseStoredTokens(ctx, slug, data, thing);
644
+ // An undo of one setting only removes it, so it never waits on the
645
+ // others being fixed.
646
+ if (sub !== 'undo') refuseStoredTokens(ctx, slug, data, thing);
369
647
  const flags = {
370
648
  on: options.on,
371
649
  when: options.when,
@@ -404,13 +682,67 @@ async function change(sub, slug, thing, value, options) {
404
682
  (x.mode ?? null) === (flags.mode ?? null),
405
683
  )
406
684
  : null;
407
- if (!stored) throw e;
685
+ if (!stored) {
686
+ // An undo is told what it can undo, never a `set`: the settings of
687
+ // what it named (or of the dial its refusal names), else the last
688
+ // step.
689
+ if (sub === 'undo' && e instanceof AstryxError) {
690
+ const named = new Set([
691
+ thing,
692
+ ...(e.suggestions ?? [])
693
+ .map(x => new RegExp(` set ${slug} (\\S+)`).exec(x.name)?.[1])
694
+ .filter(Boolean),
695
+ ]);
696
+ const matches = data.settings.filter(x => named.has(x.thing));
697
+ const steps = readHistory(themeFiles(cwd, slug).history).steps.length;
698
+ throw new AstryxError(
699
+ e.message,
700
+ matches.length
701
+ ? matches.slice(0, 5).map(x => ({
702
+ name: `${P} undo ${slug} ${undoArgs(x)}`,
703
+ reason: 'do this instead',
704
+ }))
705
+ : [
706
+ steps
707
+ ? {name: `${P} undo ${slug}`, reason: 'step back one change'}
708
+ : {name: `${P} show ${slug}`, reason: 'see what it sets'},
709
+ ],
710
+ e.code,
711
+ );
712
+ }
713
+ throw e;
714
+ }
408
715
  s = stored;
409
716
  }
410
717
  // undo <thing> <value> removes the setting only when that is its value.
411
718
  if (sub === 'undo' && value != null && value !== '') {
719
+ // A word that names a part with a setting of this thing meant --on.
720
+ const onPart = data.settings.find(
721
+ x => x.thing === s.thing && x.on === value.trim() && !s.on,
722
+ );
723
+ if (onPart)
724
+ refuse(
725
+ E.ERR_THEME_NOT_SET,
726
+ `${value.trim()} is a part: ${describe(onPart)} is set; name the part with --on.`,
727
+ {run: [`${P} undo ${slug} ${undoArgs(onPart)}`]},
728
+ );
412
729
  const held = data.settings.find(x => keyOf(x) === keyOf(s));
413
- if (held && held.value !== value.trim())
730
+ // `headings weight|tracking` names a half, not a value; a value is
731
+ // compared as `set` reads it (case, spacing and quotes aside).
732
+ const norm = (/** @type {string} */ x) =>
733
+ x
734
+ .trim()
735
+ .toLowerCase()
736
+ .replace(/\s+/g, ' ')
737
+ .replace(/^["']|["']$/g, '');
738
+ const half =
739
+ s.thing === 'headings' && ['weight', 'tracking'].includes(norm(value));
740
+ if (
741
+ held &&
742
+ !half &&
743
+ norm(held.value) !== norm(value) &&
744
+ norm(held.value) !== norm(s.value ?? '')
745
+ )
414
746
  refuse(
415
747
  E.ERR_THEME_NOT_SET,
416
748
  `The theme sets ${describe(held)}, not ${value}.`,
@@ -446,8 +778,13 @@ async function change(sub, slug, thing, value, options) {
446
778
  ...(r.unchanged
447
779
  ? [`no change: ${s.thing} is already ${s.value}`]
448
780
  : []),
781
+ ...fieldNotes,
449
782
  ...r.notes,
450
- `your ${data.settings.length} settings are kept`,
783
+ ...(data.settings.length
784
+ ? [
785
+ `your ${data.settings.length} setting${data.settings.length === 1 ? ' is' : 's are'} kept`,
786
+ ]
787
+ : []),
451
788
  ...otherModeNotes(data),
452
789
  // The colors are made again for the new base or mode: their
453
790
  // shade notes follow.
@@ -516,7 +853,19 @@ async function change(sub, slug, thing, value, options) {
516
853
  data.settings.splice(v, 1)[0]?.value
517
854
  );
518
855
  }
519
- } else if (prev && JSON.stringify(prev) === JSON.stringify(s)) {
856
+ } else if (
857
+ prev &&
858
+ JSON.stringify(prev) === JSON.stringify(s) &&
859
+ // A later setting that covers the same parts hides it: set again, it
860
+ // moves last and wins.
861
+ !data.settings
862
+ .slice(prevIdx + 1)
863
+ .some(
864
+ x =>
865
+ x.thing === s.thing &&
866
+ partsOf(ctx, x).some(t => partsOf(ctx, s).includes(t)),
867
+ )
868
+ ) {
520
869
  // The same setting again: nothing moves.
521
870
  } else {
522
871
  // A changed setting goes last, so it wins over what came before it.
@@ -543,19 +892,100 @@ async function change(sub, slug, thing, value, options) {
543
892
  x.on === s.on &&
544
893
  x.when === s.when &&
545
894
  x.state === s.state &&
546
- x.thing.startsWith(`${s.thing}-`),
895
+ x.thing.startsWith(`${s.thing}-`) &&
896
+ // Not part of border: its radius, collapse and spacing.
897
+ !/^border-(radius|collapse|spacing)$|^border-[a-z]+-radius$/.test(
898
+ x.thing,
899
+ ),
900
+ )
901
+ : [];
902
+ // A group setting covers part settings made before it for its members.
903
+ const covers =
904
+ sub === 'set' && s.source === 'dial' && s.on && FAMILIES[s.on]
905
+ ? data.settings.filter(
906
+ x =>
907
+ x !== s &&
908
+ x.thing === s.thing &&
909
+ x.on &&
910
+ FAMILIES[/** @type {string} */ (s.on)].includes(x.on) &&
911
+ (x.when ?? '') === (s.when ?? '') &&
912
+ (x.state ?? '') === (s.state ?? ''),
547
913
  )
548
914
  : [];
549
915
  const r = await commitTheme(ctx, slug, data, {history: true});
550
916
  const styled = styledChanges(compiledBefore, compileTheme(ctx, data, base));
551
917
  const parts = partsOf(ctx, s);
918
+ // Exact whole-theme tokens that win over what this dial writes: the dial
919
+ // changes them only in a theme without them.
920
+ /** @param {import('./_settings.mjs').Setting[]} list */
921
+ const dialsOnly = list => ({
922
+ ...data,
923
+ settings: list.filter(x => x.source === 'dial'),
924
+ });
925
+ /** @type {import('./_settings.mjs').Setting[]} */
926
+ let exactWins = [];
927
+ if (sub === 'set' && s.source === 'dial' && !s.on) {
928
+ const withDial = compileTheme(ctx, dialsOnly(data.settings), base);
929
+ const without = compileTheme(
930
+ ctx,
931
+ dialsOnly(data.settings.filter(x => x !== s)),
932
+ base,
933
+ );
934
+ const differs = (/** @type {unknown} */ a, /** @type {unknown} */ b) =>
935
+ JSON.stringify(a) !== JSON.stringify(b);
936
+ const touched = new Set(
937
+ [
938
+ ...Object.keys(withDial.tokens ?? {}),
939
+ ...Object.keys(without.tokens ?? {}),
940
+ ].filter(k => differs(withDial.tokens?.[k], without.tokens?.[k])),
941
+ );
942
+ for (const r of FONT_ROLES)
943
+ if (differs(withDial.typography?.[r], without.typography?.[r]))
944
+ touched.add(`--font-family-${r}`);
945
+ if (differs(withDial.typography?.scale, without.typography?.scale))
946
+ for (const k of Object.keys(ctx.project.core.tokenDefaults ?? {}))
947
+ if (/^--font-size-/.test(k)) touched.add(k);
948
+ exactWins = data.settings.filter(
949
+ x => x.source === 'token' && !x.on && !x.when && touched.has(x.thing),
950
+ );
951
+ }
552
952
  const kept =
553
953
  sub === 'set' && s.source === 'dial' && !s.on
554
- ? data.settings.filter(x => x.thing === s.thing && x.on).map(describe)
954
+ ? [
955
+ ...data.settings.filter(x => x.thing === s.thing && x.on),
956
+ ...exactWins,
957
+ ].map(describe)
555
958
  : [];
959
+ // The exact property a dial on a part competes with there.
960
+ const DIAL_PROPERTY = /** @type {Record<string, RegExp>} */ ({
961
+ corners: /radius$/,
962
+ spacing: /^(padding|gap)(-|$)/,
963
+ });
964
+ const exactOver =
965
+ sub === 'set' && s.source === 'dial' && s.on && DIAL_PROPERTY[s.thing]
966
+ ? (data.settings.find(
967
+ x =>
968
+ x.source === 'property' &&
969
+ DIAL_PROPERTY[s.thing].test(x.thing) &&
970
+ x.on &&
971
+ partsOf(ctx, x).some(t => partsOf(ctx, s).includes(t)) &&
972
+ (x.when ?? '') === (s.when ?? '') &&
973
+ (x.state ?? '') === (s.state ?? ''),
974
+ ) ?? null)
975
+ : null;
556
976
  /** @type {string[]} */
557
977
  const notes = [
558
978
  ...(covered.length ? [`replaces ${covered.map(describe).join(', ')}`] : []),
979
+ ...(exactWins.length
980
+ ? [
981
+ `keeps your exact ${exactWins.map(describe).join(', ')}: an exact setting wins over a dial, so ${exactWins.length > 1 ? 'those do' : 'that does'} not change`,
982
+ ]
983
+ : []),
984
+ ...(covers.length
985
+ ? [
986
+ `comes after ${covers.map(describe).join(', ')}, so ${covers.length > 1 ? 'those parts show' : `${covers[0].on} shows`} this value now; set ${covers.length > 1 ? 'one' : 'it'} again to make it win`,
987
+ ]
988
+ : []),
559
989
  // Phones keep the base theme's reading sizes (a coarse pointer below
560
990
  // the lg width), so a size change says where it applies.
561
991
  ...(sub === 'set' &&
@@ -570,8 +1000,17 @@ async function change(sub, slug, thing, value, options) {
570
1000
  ...(sub === 'set' && ['text-size', 'type'].includes(s.thing)
571
1001
  ? extremeSteps(r.res.light)
572
1002
  : []),
1003
+ // An exact property on the same part wins over a dial there.
1004
+ ...(exactOver
1005
+ ? [
1006
+ `${describe(exactOver)} is an exact property and wins over ${s.thing} there, so this shows only after \`${P} undo ${slug} ${undoArgs(exactOver)}\``,
1007
+ ]
1008
+ : []),
573
1009
  // An accepted change that the theme already showed says so.
574
1010
  ...(sub === 'set' &&
1011
+ !exactOver &&
1012
+ // With the last build unreadable, nothing was compared.
1013
+ !r.notes.some(n => n.includes('could not be read')) &&
575
1014
  !r.unchanged &&
576
1015
  !r.changed.length &&
577
1016
  !styled.length &&
@@ -609,6 +1048,27 @@ async function change(sub, slug, thing, value, options) {
609
1048
  modesOf(data),
610
1049
  ),
611
1050
  );
1051
+ // An exact color the mapping reads (a fill, a tint, text on a fill)
1052
+ // changes what it picks around it: say what, as the dial does.
1053
+ const dialOfToken =
1054
+ s.source === 'token' && !s.on && !s.when && !s.state
1055
+ ? paletteDialOf(s.thing)
1056
+ : null;
1057
+ if (dialOfToken && sub === 'set') {
1058
+ const pal = paletteMapping(
1059
+ cwd,
1060
+ slug,
1061
+ data,
1062
+ base,
1063
+ ctx.project.core.tokenDefaults,
1064
+ );
1065
+ if (pal?.families.some(x => x.dial === dialOfToken))
1066
+ notes.push(
1067
+ ...paletteNotes(pal, dialOfToken, slug, modesOf(data)).filter(
1068
+ n => !n.startsWith('the generated colors are in '),
1069
+ ),
1070
+ );
1071
+ }
612
1072
  if (PALETTE_DIALS.includes(s.thing) && sub === 'undo')
613
1073
  notes.push(
614
1074
  `the ${s.thing} color is no longer generated, and the tokens it fed go back to the base theme's values`,
@@ -628,8 +1088,8 @@ async function change(sub, slug, thing, value, options) {
628
1088
  notes.push(
629
1089
  `the page background stays the base theme's${pages.length ? ` (${pages.join(', ')})` : ''}${
630
1090
  modes.includes('light')
631
- ? `; for a white or off-white page: ${P} set ${slug} --color-background-body "#ffffff"${modes.length > 1 ? ' --mode light' : ''}`
632
- : `; for another page color: ${P} set ${slug} --color-background-body "<color>"`
1091
+ ? `; for a white or off-white page: ${P} set ${slug} --color-background-body ${quoteCommandArgument('#ffffff')}${modes.length > 1 ? ' --mode light' : ''}`
1092
+ : `; for another page color: ${P} set ${slug} --color-background-body ${quoteCommandArgument('#f8fafc')}`
633
1093
  }`,
634
1094
  );
635
1095
  }
@@ -650,7 +1110,18 @@ async function change(sub, slug, thing, value, options) {
650
1110
  notes.push(
651
1111
  'text below the base size keeps its standard sizes, so small text stays readable',
652
1112
  );
653
- const p = await previewAndRoute(ctx, slug, data, png);
1113
+ // A change that changed nothing writes nothing, the preview included.
1114
+ const f0 = themeFiles(cwd, slug);
1115
+ const p =
1116
+ r.unchanged && !png && fs.existsSync(f0.preview)
1117
+ ? {
1118
+ preview: shown(cwd, f0.preview),
1119
+ pictures: [],
1120
+ pictureProblem: null,
1121
+ notChecked: null,
1122
+ previewStale: [],
1123
+ }
1124
+ : await previewAndRoute(ctx, slug, data, png);
654
1125
  return {
655
1126
  type: sub === 'set' ? 'themeEdit.set' : 'themeEdit.undo',
656
1127
  data: {
@@ -664,7 +1135,10 @@ async function change(sub, slug, thing, value, options) {
664
1135
  ...(sub === 'undo' && prev
665
1136
  ? {removed: prev, now: nowApplies(ctx, data, prev, base)}
666
1137
  : {}),
667
- replaced: sub === 'set' ? prev : null,
1138
+ // A plain value that replaced per-mode ones names the first of them;
1139
+ // the notes name them all.
1140
+ replaced:
1141
+ sub === 'set' ? (prev ?? covered[0] ?? longhands[0] ?? null) : null,
668
1142
  // A whole-theme dial names the value it replaced, as base and mode do.
669
1143
  was:
670
1144
  sub === 'set' && prev && prev.source === 'dial' && !prev.on
@@ -713,7 +1187,10 @@ function unsetColorNotes(data, base, slug) {
713
1187
  if (!unset.length) return [];
714
1188
  return [
715
1189
  `${unset.join(', ')} ${unset.length > 1 ? 'are' : 'is'} not set by this theme, so ${unset.length > 1 ? 'they keep' : 'it keeps'} the base theme's colors at any vibrancy${unset.includes('info') ? ', and so do surfaces tinted with info, such as colored cards' : ''}. To include ${unset.length > 1 ? 'them' : 'it'}: ${unset
716
- .map(d => `${P} set ${slug} ${d} "${base.light[word[d]] ?? '<color>'}"`)
1190
+ .map(
1191
+ d =>
1192
+ `${P} set ${slug} ${d} ${quoteCommandArgument(base.light[word[d]] ?? '#1f2937')}`,
1193
+ )
717
1194
  .join('; ')}`,
718
1195
  ];
719
1196
  }
@@ -728,18 +1205,59 @@ function unsetColorNotes(data, base, slug) {
728
1205
  */
729
1206
  export async function themeEditShow(theme, options = {}) {
730
1207
  const {cwd = process.cwd(), png = false} = options;
1208
+ // Without the theme lock (it cannot be taken), show writes nothing: it
1209
+ // reports the last build as it is.
1210
+ const readOnly = Boolean(/** @type {any} */ (options).readOnly);
731
1211
  requireProject(cwd);
732
1212
  const section = checkSection(options.section, theme);
733
1213
  const data = loadTheme(cwd, theme);
734
1214
  const ctx = await context(cwd);
735
1215
  refuseStoredTokens(ctx, theme, data);
1216
+ // Without React, show still lists the settings and builds the theme, as
1217
+ // set does; only the pages, pictures and the checks that render are
1218
+ // skipped, and the result says how to fix it.
1219
+ const noReact =
1220
+ !readOnly &&
1221
+ (reactMissing(cwd).length > 0 ||
1222
+ ctx.uncheckedCode === 'ERR_RENDER_MISSING_DEPENDENCY');
1223
+ const noPages = readOnly || noReact;
1224
+ // Any other render failure (two copies of React, a component that
1225
+ // throws) is refused, and nothing is written.
1226
+ if (ctx.unchecked && !readOnly && !noReact)
1227
+ refuse(
1228
+ E.ERR_RENDER_FAILED,
1229
+ `${theme} cannot be shown: ${ctx.unchecked} Nothing was written.`,
1230
+ {
1231
+ // Only a missing React is fixed by installing it; two copies or a
1232
+ // component that throws are named in the message.
1233
+ run:
1234
+ ctx.uncheckedCode === 'ERR_RENDER_MISSING_DEPENDENCY'
1235
+ ? [installLine(cwd, ['react', 'react-dom'])]
1236
+ : // Two copies of React and other install problems are named by
1237
+ // doctor; the same show would fail the same way.
1238
+ ['astryx doctor'],
1239
+ },
1240
+ );
736
1241
  const f = themeFiles(cwd, theme);
737
1242
  // A build that does not match the settings (a command stopped mid-build,
738
1243
  // a hand edit, another CLI) is made again from the settings, and said.
739
1244
  const stale = staleBuild(cwd, theme, data);
740
- if (stale) await buildTheme(ctx, theme, data);
741
- const res = await resolvedTokens(ctx, theme);
742
- const problems = await contrastProblems(ctx, data, res);
1245
+ const brokenSource = themeSourceProblem(cwd, theme);
1246
+ if (stale && !brokenSource && !readOnly) await buildTheme(ctx, theme, data);
1247
+ // The settings loaded whole: a `new` marker beside them is stale.
1248
+ if (!readOnly) clearNewMarker(f.dir);
1249
+ // A built module that cannot be read (damaged by hand) is built again.
1250
+ /** @type {string | null} */
1251
+ let unreadable = null;
1252
+ const res = await resolvedTokens(ctx, theme).catch(async e => {
1253
+ if (e instanceof AstryxError || readOnly) throw e;
1254
+ unreadable = `${theme}.js could not be read (${e instanceof Error ? e.message.split('\n')[0] : String(e)}), so it was built again from the settings`;
1255
+ await buildTheme(ctx, theme, data);
1256
+ return resolvedTokens(ctx, theme);
1257
+ });
1258
+ const checked = await contrastProblems(ctx, data, res);
1259
+ // What cannot be measured is a note, not a problem.
1260
+ const problems = checked.filter(x => !x.startsWith('not checked'));
743
1261
  const pal = paletteMapping(
744
1262
  cwd,
745
1263
  theme,
@@ -747,20 +1265,31 @@ export async function themeEditShow(theme, options = {}) {
747
1265
  await baseResolved(ctx.project, data.like),
748
1266
  ctx.project.core.tokenDefaults,
749
1267
  );
750
- const preview = await renderPreview(ctx, theme, data);
751
- const previewStale = await keepPreviewRoute(ctx, theme);
752
- const sheet = await renderSheet(ctx, theme, data, {group: section});
1268
+ const preview = noPages
1269
+ ? shown(cwd, f.preview)
1270
+ : await renderPreview(ctx, theme, data);
1271
+ const previewStale = noPages ? [] : await keepPreviewRoute(ctx, theme);
1272
+ const sheet = noPages
1273
+ ? {file: shown(cwd, f.sheet), components: 0, skipped: []}
1274
+ : await renderSheet(ctx, theme, data, {group: section});
753
1275
  const modes = modesOf(data);
754
- const shots = png
755
- ? await pictures(
756
- ctx.project,
757
- [
758
- {html: f.preview, png: f.previewPng},
759
- {html: f.sheet, png: f.sheetPng},
760
- ],
761
- modes,
762
- )
763
- : {files: [], problem: null};
1276
+ const shots =
1277
+ png && !noPages
1278
+ ? await pictures(
1279
+ ctx.project,
1280
+ [
1281
+ {html: f.preview, png: f.previewPng},
1282
+ // A section is photographed from its own sheet.
1283
+ section
1284
+ ? {
1285
+ html: path.join(f.dir, `sheet-${section}.html`),
1286
+ png: path.join(f.dir, `sheet-${section}.png`),
1287
+ }
1288
+ : {html: f.sheet, png: f.sheetPng},
1289
+ ],
1290
+ modes,
1291
+ )
1292
+ : {files: [], problem: null};
764
1293
  return {
765
1294
  type: 'themeEdit.show',
766
1295
  data: {
@@ -772,11 +1301,27 @@ export async function themeEditShow(theme, options = {}) {
772
1301
  return {...s, parts: partsOf(ctx, s), ...(masked ? {masked} : {})};
773
1302
  }),
774
1303
  notes: [
775
- ...(stale
1304
+ ...(noReact
776
1305
  ? [
777
- `the build did not match ${theme}.settings.json (${stale}), so it was built again from the settings`,
1306
+ `react and react-dom cannot be found from this app, so the pages and pictures were not made again and the checks that render components were skipped; install them (${installLine(cwd, ['react', 'react-dom'])}), then run show again`,
778
1307
  ]
779
1308
  : []),
1309
+ ...(readOnly
1310
+ ? [
1311
+ `the theme lock could not be taken, so nothing was written: this is the last build as it is${stale ? ` (it does not match the settings: ${stale})` : ''}, and the pages were not made again`,
1312
+ ]
1313
+ : stale
1314
+ ? [
1315
+ `the build did not match ${theme}.settings.json (${stale}), so it was built again from the settings`,
1316
+ ]
1317
+ : []),
1318
+ ...(unreadable ? [unreadable] : []),
1319
+ ...(brokenSource
1320
+ ? [
1321
+ `${brokenSource}, so settings cannot take effect; put back the import, extends and name lines in ${theme}.theme.ts`,
1322
+ ]
1323
+ : []),
1324
+ ...checked.filter(x => x.startsWith('not checked')),
780
1325
  ...fontNotes(ctx, data),
781
1326
  ],
782
1327
  // A size, number or font is the same in both modes: one value.
@@ -788,7 +1333,12 @@ export async function themeEditShow(theme, options = {}) {
788
1333
  : (res[modes[0]][k] ?? null),
789
1334
  ]),
790
1335
  ),
791
- partValues: partValues(ctx, data, res, modes[0]),
1336
+ partValues: partValues(
1337
+ Object.assign(ctx, {base: await baseResolved(ctx.project, data.like)}),
1338
+ data,
1339
+ res,
1340
+ modes[0],
1341
+ ),
792
1342
  ...colorsReport(pal, data),
793
1343
  problems,
794
1344
  preview,
@@ -832,6 +1382,56 @@ function nowApplies(ctx, data, removed, base) {
832
1382
  : describe(d);
833
1383
  }
834
1384
  }
1385
+ // What still reaches where the removed setting applied: on a part, the
1386
+ // same thing set plainly on it, on its group, or for the whole theme; an
1387
+ // exact property on the part that this dial would have competed with.
1388
+ if (removed.on) {
1389
+ const fam = familyOf(removed.on);
1390
+ const reaches = [...data.settings]
1391
+ .reverse()
1392
+ .find(
1393
+ x =>
1394
+ x.thing === removed.thing &&
1395
+ x !== removed &&
1396
+ (!x.mode || x.mode === removed.mode) &&
1397
+ ((x.on === removed.on && !x.when && !x.state) ||
1398
+ (fam && x.on === fam && !x.when && !x.state)),
1399
+ );
1400
+ if (reaches) return describe(reaches);
1401
+ const DIAL_PROPERTY = /** @type {Record<string, RegExp>} */ ({
1402
+ corners: /radius$/,
1403
+ spacing: /^(padding|gap)(-|$)/,
1404
+ });
1405
+ const exact =
1406
+ removed.source === 'dial' && DIAL_PROPERTY[removed.thing]
1407
+ ? data.settings.find(
1408
+ x =>
1409
+ x.source === 'property' &&
1410
+ x.on === removed.on &&
1411
+ DIAL_PROPERTY[removed.thing].test(x.thing),
1412
+ )
1413
+ : null;
1414
+ if (exact) return describe(exact);
1415
+ // A removed exact property leaves the dial that writes it: on the part,
1416
+ // its group, or the whole theme.
1417
+ if (removed.source === 'property') {
1418
+ const dial = Object.entries(DIAL_PROPERTY).find(([, re]) =>
1419
+ re.test(removed.thing),
1420
+ )?.[0];
1421
+ const fromDial = dial
1422
+ ? [...data.settings]
1423
+ .reverse()
1424
+ .find(
1425
+ x =>
1426
+ x.thing === dial &&
1427
+ (x.on === removed.on || (fam && x.on === fam) || !x.on) &&
1428
+ (x.when ?? '') === (removed.when ?? '') &&
1429
+ (x.state ?? '') === (removed.state ?? ''),
1430
+ )
1431
+ : undefined;
1432
+ if (fromDial) return describe(fromDial);
1433
+ }
1434
+ }
835
1435
  const whole =
836
1436
  removed.on || removed.when || removed.state || removed.mode
837
1437
  ? [...data.settings]
@@ -881,12 +1481,30 @@ function otherModeNotes(data) {
881
1481
  * @returns {string[]}
882
1482
  */
883
1483
  function partValues(ctx, data, res, mode) {
1484
+ const masked = maskedSettings(data);
884
1485
  return data.settings
885
1486
  .filter(
886
1487
  s =>
887
1488
  s.source === 'dial' && s.on && ['corners', 'spacing'].includes(s.thing),
888
1489
  )
889
1490
  .map(s => {
1491
+ // A setting a later group setting covers shows that one's value.
1492
+ const hidden = masked.get(s);
1493
+ if (hidden) return `${describe(s)} -> not shown: ${hidden}`;
1494
+ // An exact property on the part wins over the dial there.
1495
+ const exact = data.settings.find(
1496
+ x =>
1497
+ x.source === 'property' &&
1498
+ x.on &&
1499
+ (s.thing === 'corners'
1500
+ ? x.thing === 'border-radius'
1501
+ : /^(padding|gap)(-|$)/.test(x.thing)) &&
1502
+ partsOf(ctx, x).some(t => partsOf(ctx, s).includes(t)) &&
1503
+ (x.when ?? '') === (s.when ?? '') &&
1504
+ (x.state ?? '') === (s.state ?? ''),
1505
+ );
1506
+ if (exact)
1507
+ return `${describe(s)} -> not shown: ${describe(exact)} is an exact property and wins there`;
890
1508
  const parts = partsOf(ctx, s);
891
1509
  const listed = `${parts.slice(0, 4).join(', ')}${parts.length > 4 ? `, and ${parts.length - 4} more` : ''}`;
892
1510
  if (s.thing === 'corners') {
@@ -900,17 +1518,7 @@ function partValues(ctx, data, res, mode) {
900
1518
  /** @type {Map<string, string[]>} */
901
1519
  const byToken = new Map();
902
1520
  for (const t of parts) {
903
- const token =
904
- /var\((--[\w-]+)\)/.exec(
905
- partDefault(ctx, t, 'borderRadius', undefined) ?? '',
906
- )?.[1] ??
907
- // Every variant reads it (none is the resting one).
908
- ctx.C.partReads(t, 'corners').find(x =>
909
- x.props.includes('border-radius'),
910
- )?.token ??
911
- (['containers', 'menus'].includes(familyOf(t) ?? '')
912
- ? '--radius-container'
913
- : 'unknown');
1521
+ const token = radiusTokenOf(ctx, t);
914
1522
  byToken.set(token, [...(byToken.get(token) ?? []), t]);
915
1523
  }
916
1524
  const whole = [...byToken]
@@ -919,7 +1527,21 @@ function partValues(ctx, data, res, mode) {
919
1527
  `${token === 'unknown' ? 'unknown' : `${token} ${res[mode][token] ?? 'unset'}`}${byToken.size > 1 ? ` for ${ts.join(', ')}` : ''}`,
920
1528
  )
921
1529
  .join('; ');
922
- return `${describe(s)} -> border-radius ${px >= 9999 ? 'fully round' : `${px}px`} on ${listed} (whole theme: ${whole})`;
1530
+ // What the build writes on each part: a rung by the radius token
1531
+ // the part reads, an exact size as given.
1532
+ const rung = CORNERS.some(([n]) => n === s.value) || px >= 1000;
1533
+ const built = [...byToken]
1534
+ .map(([token, ts]) => {
1535
+ const v =
1536
+ rung && token !== 'unknown' && ctx.base
1537
+ ? radiusAt(ctx.base, s.value, token)
1538
+ : px >= 1000
1539
+ ? 9999
1540
+ : px;
1541
+ return `${v >= 9999 ? 'fully round' : `${v}px`}${byToken.size > 1 ? ` on ${ts.join(', ')}` : ''}`;
1542
+ })
1543
+ .join('; ');
1544
+ return `${describe(s)} -> border-radius ${built}${byToken.size > 1 ? '' : ` on ${listed}`} (whole theme: ${whole})`;
923
1545
  }
924
1546
  const f = SPACING.find(([n]) => n === s.value)?.[1] ?? 1;
925
1547
  return `${describe(s)} -> spacing x${f} inside ${listed} (whole theme: --spacing-4 ${res[mode]['--spacing-4'] ?? 'unset'})`;
@@ -1013,16 +1635,29 @@ function colorFiles(slug) {
1013
1635
  */
1014
1636
  export async function themeEditUndo(theme, options = {}) {
1015
1637
  const {cwd = process.cwd(), png = false, thing} = options;
1016
- // base and mode are not settings in the list: undoing one sets it back to
1017
- // its default.
1018
- if (thing === 'base' || thing === 'mode')
1019
- return change(
1020
- 'set',
1021
- theme,
1022
- thing,
1023
- thing === 'base' ? 'none' : 'both',
1024
- options,
1025
- );
1638
+ // base and mode are not settings in the list: undoing one goes back to
1639
+ // what the theme was made with (the oldest step the history keeps).
1640
+ if (thing === 'base' || thing === 'mode') {
1641
+ requireProject(cwd);
1642
+ const now = loadTheme(cwd, theme, thing);
1643
+ const [first] = readHistory(themeFiles(cwd, theme).history).steps;
1644
+ /** @type {any} */
1645
+ let made = now;
1646
+ try {
1647
+ if (first) made = JSON.parse(first.replace(/^\uFEFF/, ''));
1648
+ } catch {
1649
+ made = now;
1650
+ }
1651
+ const of = (/** @type {any} */ d) =>
1652
+ thing === 'base' ? (d?.like ?? 'none') : (d?.mode ?? 'both');
1653
+ if (of(made) === of(now))
1654
+ refuse(
1655
+ E.ERR_THEME_NOT_SET,
1656
+ `${thing} was never changed: it is ${of(now)}, as ${theme} was made.`,
1657
+ {run: [`${P} show ${theme}`]},
1658
+ );
1659
+ return change('set', theme, thing, of(made), options);
1660
+ }
1026
1661
  if (thing != null)
1027
1662
  return change('undo', theme, thing, options.value, options);
1028
1663
  requireProject(cwd);
@@ -1082,6 +1717,35 @@ export async function themeEditUndo(theme, options = {}) {
1082
1717
  `Nothing to undo: ${theme} has no earlier change.`,
1083
1718
  {run: [`${P} show ${theme}`]},
1084
1719
  );
1720
+ // A top step equal to the settings now (left by an undo stopped between
1721
+ // its two writes) changes nothing: skip it.
1722
+ const nowText = fs.readFileSync(f.settings, 'utf8');
1723
+ const same = (/** @type {string} */ a, /** @type {string} */ b) => {
1724
+ try {
1725
+ return (
1726
+ JSON.stringify({
1727
+ ...JSON.parse(a.replace(/^\uFEFF/, '')),
1728
+ lifted: 0,
1729
+ built: 0,
1730
+ }) ===
1731
+ JSON.stringify({
1732
+ ...JSON.parse(b.replace(/^\uFEFF/, '')),
1733
+ lifted: 0,
1734
+ built: 0,
1735
+ })
1736
+ );
1737
+ } catch {
1738
+ return false;
1739
+ }
1740
+ };
1741
+ while (history.length && same(history[history.length - 1], nowText))
1742
+ history.pop();
1743
+ if (!history.length)
1744
+ refuse(
1745
+ E.ERR_THEME_NOTHING_TO_UNDO,
1746
+ `Nothing to undo: ${theme} has no earlier change (the last step equals the settings now).`,
1747
+ {run: [`${P} show ${theme}`]},
1748
+ );
1085
1749
  const ctx = await context(cwd);
1086
1750
  const prevText = /** @type {string} */ (history.pop());
1087
1751
  let prev = /** @type {import('./_settings.mjs').ThemeData} */ (
@@ -1089,6 +1753,23 @@ export async function themeEditUndo(theme, options = {}) {
1089
1753
  );
1090
1754
  // A step always restores into this theme, whatever name it holds.
1091
1755
  prev.name = theme;
1756
+ // What the step's build showed is restored with it, not saved as a
1757
+ // setting.
1758
+ const built = /** @type {any} */ (prev).built;
1759
+ delete (/** @type {any} */ (prev).built);
1760
+ const radii =
1761
+ built?.radii && typeof built.radii === 'object'
1762
+ ? /** @type {Record<string, string>} */ (
1763
+ Object.fromEntries(
1764
+ Object.entries(built.radii).filter(
1765
+ ([k, v]) =>
1766
+ /^--radius-(element|inner|container|page)$/.test(k) &&
1767
+ typeof v === 'string' &&
1768
+ /^\d+(\.\d+)?px$/.test(v),
1769
+ ),
1770
+ )
1771
+ )
1772
+ : null;
1092
1773
  // The step it goes back to is checked like the settings file itself. A
1093
1774
  // value the editor no longer accepts is left out of that step (with a
1094
1775
  // note); a step whose shape is broken is refused.
@@ -1110,7 +1791,11 @@ export async function themeEditUndo(theme, options = {}) {
1110
1791
  leftOut = repaired.dropped;
1111
1792
  }
1112
1793
  // The popped history is written with the change, inside its rollback.
1113
- await commitTheme(ctx, theme, prev, {history: false, historyAfter: history});
1794
+ const committed = await commitTheme(ctx, theme, prev, {
1795
+ history: false,
1796
+ historyAfter: history,
1797
+ radii,
1798
+ });
1114
1799
  /** @type {string[]} */
1115
1800
  const undone = current
1116
1801
  ? []
@@ -1132,6 +1817,8 @@ export async function themeEditUndo(theme, options = {}) {
1132
1817
  if (current)
1133
1818
  for (const [k, s] of now)
1134
1819
  if (!was.has(k)) undone.push(`put back ${describe(s)}`);
1820
+ // What the build kept, such as a color file edited by hand.
1821
+ undone.push(...committed.notes);
1135
1822
  if (current && (current.like ?? 'none') !== (prev.like ?? 'none'))
1136
1823
  undone.push(
1137
1824
  `base ${current.like ?? 'none'} is back to ${prev.like ?? 'none'}`,
@@ -1147,7 +1834,23 @@ export async function themeEditUndo(theme, options = {}) {
1147
1834
  undone,
1148
1835
  settings: prev.settings.length,
1149
1836
  stepsLeft: history.length,
1837
+ // What the step back changed, as a change reports it.
1838
+ changedTokens: committed.changed,
1839
+ problems: committed.problems,
1150
1840
  ...p,
1151
1841
  },
1152
1842
  };
1153
1843
  }
1844
+
1845
+ /**
1846
+ * Why an editor theme's build is not current, or null: the editor's own
1847
+ * staleness check (the settings it was built from, the CLI and packages it
1848
+ * was built with), for `compile --check`.
1849
+ * @param {string} cwd
1850
+ * @param {string} slug
1851
+ * @returns {Promise<string | null>}
1852
+ */
1853
+ export async function editorStale(cwd, slug) {
1854
+ const data = loadTheme(cwd, slug);
1855
+ return staleBuild(cwd, slug, data) || null;
1856
+ }