@astryxdesign/cli 0.7.14-canary.gfdb9213 → 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.
Files changed (95) hide show
  1. package/CHANGELOG.md +197 -0
  2. package/api/theme/_adapter.d.mts +33 -0
  3. package/api/theme/_adapter.mjs +352 -16
  4. package/api/theme/build/build.mjs +261 -10
  5. package/api/theme/eject/eject.mjs +13 -1
  6. package/api/theme/list/list.mjs +11 -2
  7. package/api/theme/template/template.mjs +139 -6
  8. package/api/theme/theme.type.d.mts +15 -1
  9. package/api/theme/theme.type.mjs +9 -3
  10. package/api/theme/themeAdd.doc.mjs +1 -1
  11. package/api/theme/themeBuild.doc.mjs +10 -2
  12. package/api/theme/themeEject.doc.mjs +2 -2
  13. package/api/theme/themeListAvailable.doc.mjs +1 -1
  14. package/api/theme/themeRemove.doc.mjs +1 -1
  15. package/api/theme/themeTemplate.doc.mjs +8 -0
  16. package/api/theme/themeUse.doc.mjs +1 -1
  17. package/api/theme-edit/_adapter.d.mts +10 -2
  18. package/api/theme-edit/_adapter.mjs +52 -31
  19. package/api/theme-edit/_check.d.mts +28 -25
  20. package/api/theme-edit/_check.mjs +586 -548
  21. package/api/theme-edit/_color.d.mts +28 -2
  22. package/api/theme-edit/_color.mjs +306 -68
  23. package/api/theme-edit/_compiler.d.mts +8 -4
  24. package/api/theme-edit/_compiler.mjs +30 -27
  25. package/api/theme-edit/_context.d.mts +10 -4
  26. package/api/theme-edit/_context.mjs +21 -4
  27. package/api/theme-edit/_edit.mjs +300 -43
  28. package/api/theme-edit/_how-commands.d.mts +91 -0
  29. package/api/theme-edit/_how-commands.mjs +269 -0
  30. package/api/theme-edit/_how-question.d.mts +57 -0
  31. package/api/theme-edit/_how-question.mjs +2574 -0
  32. package/api/theme-edit/_how.d.mts +25 -17
  33. package/api/theme-edit/_how.mjs +727 -305
  34. package/api/theme-edit/_palette.d.mts +127 -19
  35. package/api/theme-edit/_palette.mjs +1313 -399
  36. package/api/theme-edit/_parts.mjs +36 -3
  37. package/api/theme-edit/_png.d.mts +18 -6
  38. package/api/theme-edit/_png.mjs +135 -25
  39. package/api/theme-edit/_preview-app.d.mts +26 -7
  40. package/api/theme-edit/_preview-app.mjs +1611 -280
  41. package/api/theme-edit/_preview.d.mts +4 -2
  42. package/api/theme-edit/_preview.mjs +18 -7
  43. package/api/theme-edit/_settings.d.mts +56 -5
  44. package/api/theme-edit/_settings.mjs +197 -49
  45. package/api/theme-edit/_tables.d.mts +0 -12
  46. package/api/theme-edit/_tables.mjs +24 -97
  47. package/api/theme-edit/theme-edit.type.d.mts +22 -5
  48. package/api/theme-edit/theme-edit.type.mjs +17 -6
  49. package/api/theme-edit/themeEditHow.doc.mjs +13 -3
  50. package/api/theme-edit/themeEditNew.doc.mjs +2 -1
  51. package/api/theme-edit/themeEditPreviewAdd.doc.mjs +16 -4
  52. package/api/theme-edit/themeEditPreviewApp.doc.mjs +12 -4
  53. package/api/theme-edit/themeEditPreviewList.doc.mjs +9 -1
  54. package/api/theme-edit/themeEditPreviewRemove.doc.mjs +27 -2
  55. package/api/theme-edit/themeEditUndo.doc.mjs +1 -1
  56. package/assets/docs.generated.json +1 -0
  57. package/assets/preview-app/gitignore +3 -0
  58. package/assets/templates/components.generated.json +1 -0
  59. package/clients/cli/bin/astryx.mjs +37 -5
  60. package/clients/cli/commands/experimental/theme.mjs +231 -31
  61. package/clients/cli/commands/experimental-theme-editor-how.doc.mjs +14 -5
  62. package/clients/cli/commands/experimental-theme-editor-new.doc.mjs +0 -1
  63. package/clients/cli/commands/experimental-theme-editor-undo.doc.mjs +1 -1
  64. package/clients/cli/commands/experimental-theme-preview-add.doc.mjs +3 -2
  65. package/clients/cli/commands/experimental-theme-preview-app.doc.mjs +2 -2
  66. package/clients/cli/commands/experimental-theme-preview-list.doc.mjs +2 -2
  67. package/clients/cli/commands/experimental-theme-preview-remove.doc.mjs +2 -2
  68. package/clients/cli/commands/experimental-theme-targets.doc.mjs +1 -1
  69. package/clients/cli/commands/experimental-theme.doc.mjs +2 -2
  70. package/clients/cli/commands/theme-build.doc.mjs +1 -1
  71. package/clients/cli/commands/theme-eject.doc.mjs +3 -3
  72. package/clients/cli/commands/theme-remove.doc.mjs +2 -2
  73. package/clients/cli/commands/theme-template.doc.mjs +11 -4
  74. package/clients/cli/commands/theme.mjs +104 -40
  75. package/clients/cli/commands.generated.json +1 -0
  76. package/clients/cli/index.mjs +96 -4
  77. package/clients/cli/lib/json-shim.mjs +29 -1
  78. package/foundation/config/project.d.mts +16 -2
  79. package/foundation/config/project.mjs +40 -6
  80. package/foundation/config/theme-state.d.mts +9 -0
  81. package/foundation/config/theme-state.mjs +20 -1
  82. package/foundation/discovery/template-adapter.d.mts +12 -1
  83. package/foundation/discovery/template-adapter.mjs +24 -1
  84. package/foundation/discovery/template-needs.d.mts +7 -0
  85. package/foundation/discovery/template-needs.mjs +117 -8
  86. package/foundation/discovery/template-source-tree.d.mts +5 -1
  87. package/foundation/discovery/template-source-tree.mjs +6 -4
  88. package/foundation/discovery/theme-discovery.d.mts +14 -3
  89. package/foundation/discovery/theme-discovery.mjs +45 -12
  90. package/foundation/doc-compiler/import.mjs +68 -3
  91. package/foundation/doc-compiler/stored-docs.d.mts +27 -0
  92. package/foundation/doc-compiler/stored-docs.mjs +65 -0
  93. package/foundation/fs/fs-error.d.mts +17 -0
  94. package/foundation/fs/fs-error.mjs +34 -0
  95. package/package.json +6 -6
@@ -107,7 +107,27 @@ export const renderDir = project =>
107
107
  */
108
108
  export async function renderGenerated(project, file, source, extra = []) {
109
109
  const dir = renderDir(project);
110
+ // A lookup in an app with no themes must not leave a themes/ folder.
111
+ const themes = path.dirname(dir);
112
+ // A themes/ folder that holds only other renders was made by another
113
+ // lookup running beside this one, so it is ours to remove too.
114
+ const madeThemes =
115
+ !fs.existsSync(themes) ||
116
+ (() => {
117
+ const names = fs.readdirSync(themes);
118
+ return (
119
+ names.length > 0 && names.every(n => n.startsWith('.astryx-render-'))
120
+ );
121
+ })();
110
122
  fs.mkdirSync(dir, {recursive: true});
123
+ // Stopped by a signal, the render folder still goes.
124
+ const cleanup = () => fs.rmSync(dir, {recursive: true, force: true});
125
+ const onSignal = (/** @type {NodeJS.Signals} */ sig) => {
126
+ cleanup();
127
+ process.kill(process.pid, sig);
128
+ };
129
+ process.once('SIGINT', onSignal);
130
+ process.once('SIGTERM', onSignal);
111
131
  const entry = path.join(dir, file);
112
132
  fs.writeFileSync(entry, source);
113
133
  for (const x of extra) {
@@ -136,10 +156,15 @@ export async function renderGenerated(project, file, source, extra = []) {
136
156
  // it, so a render running beside this one keeps its own.
137
157
  for (const f of [entry, ...extra.map(x => path.join(dir, x.name))])
138
158
  fs.rmSync(f, {force: true});
139
- removeEmpty(dir);
159
+ removeEmpty(madeThemes ? themes : dir);
160
+ process.removeListener('SIGINT', onSignal);
161
+ process.removeListener('SIGTERM', onSignal);
140
162
  }
141
163
  }
142
164
 
165
+ /** @param {unknown} v @returns {v is Record<string, unknown>} */
166
+ const isRecord = v => typeof v === 'object' && v !== null && !Array.isArray(v);
167
+
143
168
  /**
144
169
  * Remove `dir` and the folders under it when no file is left in them.
145
170
  * @param {string} dir
@@ -164,9 +189,14 @@ export async function partData(project) {
164
189
  const file = path.join(project.cacheDir, 'parts.json');
165
190
  try {
166
191
  const cached = JSON.parse(fs.readFileSync(file, 'utf8'));
192
+ // A file that parses but has the wrong shape (a hand edit, a cut-off
193
+ // write) is built again, as a file that does not parse is.
167
194
  if (
168
195
  cached.version === PART_DATA_VERSION &&
169
- cached.coreKey === project.coreKey
196
+ cached.coreKey === project.coreKey &&
197
+ isRecord(cached.map) &&
198
+ Object.values(cached.map).every(isRecord) &&
199
+ Array.isArray(cached.pairs)
170
200
  )
171
201
  return cached;
172
202
  } catch {
@@ -175,7 +205,10 @@ export async function partData(project) {
175
205
  const data = await buildPartData(project);
176
206
  try {
177
207
  fs.mkdirSync(project.cacheDir, {recursive: true});
178
- fs.writeFileSync(file, JSON.stringify(data));
208
+ // Write beside it and rename, so a reader never sees half a file.
209
+ const part = `${file}.${RUN}`;
210
+ fs.writeFileSync(part, JSON.stringify(data));
211
+ fs.renameSync(part, file);
179
212
  } catch {
180
213
  // A read-only node_modules: build it again next time.
181
214
  }
@@ -3,27 +3,32 @@
3
3
 
4
4
  /** @typedef {{width: number, height: number, rgba: Uint8Array}} Picture */
5
5
  /**
6
- * Decode a PNG file's bytes. Interlaced pictures are refused.
6
+ * Decode a PNG file's bytes. Interlaced pictures are refused, and so is
7
+ * any file whose header, chunks or pixel data do not match the PNG format.
7
8
  * @param {Buffer} bytes
8
9
  * @returns {Picture}
9
10
  */
10
11
  export function decodePng(bytes: Buffer): Picture;
11
12
  /**
12
- * The exact color at each point.
13
+ * The exact color at each point, with its alpha (0 is fully see-through,
14
+ * 1 fully opaque). Every point must be inside the picture.
13
15
  * @param {Picture} pic
14
16
  * @param {Array<{x: number, y: number}>} points
15
- * @returns {Array<{at: string, color: string | null}>}
17
+ * @returns {Array<{at: string, color: string, alpha: number}>}
16
18
  */
17
19
  export function colorsAt(pic: Picture, points: Array<{
18
20
  x: number;
19
21
  y: number;
20
22
  }>): Array<{
21
23
  at: string;
22
- color: string | null;
24
+ color: string;
25
+ alpha: number;
23
26
  }>;
24
27
  /**
25
- * The main colors of a picture: every second pixel bucketed to 5 bits per
26
- * channel, biggest share first, each with where it sits.
28
+ * The main colors of a picture: every pixel (on a grid past 4 million)
29
+ * bucketed to 5 bits per channel, biggest share first, each with where it sits. A fully
30
+ * see-through pixel shows no color, so it is skipped; a partly see-through
31
+ * one counts as it looks over white.
27
32
  * @param {Picture} pic
28
33
  * @param {number} count
29
34
  * @returns {Array<{color: string, share: number, where: string}>}
@@ -33,6 +38,13 @@ export function mainColors(pic: Picture, count: number): Array<{
33
38
  share: number;
34
39
  where: string;
35
40
  }>;
41
+ /**
42
+ * The most pixels a picture may have: about a 6K screen. A bigger header is
43
+ * refused before any memory is taken for it.
44
+ */
45
+ export const MAX_PIXELS: 40000000;
46
+ /** A 16-bit picture takes twice the memory per pixel, so half as many. */
47
+ export const MAX_PIXELS_16: 20000000;
36
48
  export type Picture = {
37
49
  width: number;
38
50
  height: number;
@@ -1,9 +1,10 @@
1
1
  // Copyright (c) Meta Platforms, Inc. and affiliates.
2
2
 
3
3
  /**
4
- * @file Read a PNG in plain Node: decompress with zlib, undo the row
5
- * filters, and give RGBA pixels. Then the main colors of a picture, or the
6
- * exact color at given points.
4
+ * @file Read a PNG in plain Node: check the header and size before taking
5
+ * memory, decompress with zlib to exactly the size the header names, undo
6
+ * the row filters, and give RGBA pixels. Then the main colors of a picture,
7
+ * or the exact color and alpha at given points.
7
8
  * @position api/theme-edit — pure helpers for `experimental theme editor how <picture.png>`
8
9
  */
9
10
 
@@ -11,10 +12,39 @@ import * as zlib from 'node:zlib';
11
12
 
12
13
  const SIGNATURE = Buffer.from([137, 80, 78, 71, 13, 10, 26, 10]);
13
14
 
15
+ /**
16
+ * The most pixels a picture may have: about a 6K screen. A bigger header is
17
+ * refused before any memory is taken for it.
18
+ */
19
+ export const MAX_PIXELS = 40_000_000;
20
+
21
+ /** A 16-bit picture takes twice the memory per pixel, so half as many. */
22
+ export const MAX_PIXELS_16 = 20_000_000;
23
+
24
+ /** The most pixels the main colors read one by one; past it they stride. */
25
+ const SAMPLE_BUDGET = 4_000_000;
26
+
27
+ /** The bit depths each PNG color type allows. */
28
+ const DEPTHS = /** @type {Record<number, number[]>} */ ({
29
+ 0: [1, 2, 4, 8, 16],
30
+ 2: [8, 16],
31
+ 3: [1, 2, 4, 8],
32
+ 4: [8, 16],
33
+ 6: [8, 16],
34
+ });
35
+ const CHANNELS = /** @type {Record<number, number>} */ ({
36
+ 0: 1,
37
+ 2: 3,
38
+ 3: 1,
39
+ 4: 2,
40
+ 6: 4,
41
+ });
42
+
14
43
  /** @typedef {{width: number, height: number, rgba: Uint8Array}} Picture */
15
44
 
16
45
  /**
17
- * Decode a PNG file's bytes. Interlaced pictures are refused.
46
+ * Decode a PNG file's bytes. Interlaced pictures are refused, and so is
47
+ * any file whose header, chunks or pixel data do not match the PNG format.
18
48
  * @param {Buffer} bytes
19
49
  * @returns {Picture}
20
50
  */
@@ -27,6 +57,7 @@ export function decodePng(bytes) {
27
57
  let depth = 0;
28
58
  let colorType = 0;
29
59
  let interlace = 0;
60
+ let header = false;
30
61
  /** @type {Buffer | null} */
31
62
  let palette = null;
32
63
  /** @type {Buffer | null} */
@@ -36,31 +67,68 @@ export function decodePng(bytes) {
36
67
  while (pos + 8 <= bytes.length) {
37
68
  const length = bytes.readUInt32BE(pos);
38
69
  const type = bytes.toString('latin1', pos + 4, pos + 8);
70
+ if (pos + 12 + length > bytes.length)
71
+ throw new Error(`the ${type} chunk is cut off`);
39
72
  const body = bytes.subarray(pos + 8, pos + 8 + length);
40
73
  pos += 12 + length;
41
74
  if (type === 'IHDR') {
75
+ if (length !== 13) throw new Error('the PNG header is damaged');
42
76
  width = body.readUInt32BE(0);
43
77
  height = body.readUInt32BE(4);
44
78
  depth = body[8];
45
79
  colorType = body[9];
46
80
  interlace = body[12];
81
+ header = true;
47
82
  } else if (type === 'PLTE') palette = body;
48
83
  else if (type === 'tRNS') alpha = body;
49
84
  else if (type === 'IDAT') data.push(body);
50
85
  else if (type === 'IEND') break;
51
86
  }
52
- if (!width || !height) throw new Error('the PNG has no header');
87
+ if (!header) throw new Error('the PNG has no header');
88
+ if (!width || !height)
89
+ throw new Error(
90
+ `the picture is ${width}x${height} pixels, so it has no colors`,
91
+ );
53
92
  if (interlace) throw new Error('interlaced PNG files are not supported');
54
- const channels = {0: 1, 2: 3, 3: 1, 4: 2, 6: 4}[colorType];
55
- if (!channels || ![1, 2, 4, 8, 16].includes(depth))
56
- throw new Error('unsupported PNG color format');
57
- const raw = zlib.inflateSync(Buffer.concat(data));
93
+ if (!DEPTHS[colorType]?.includes(depth))
94
+ throw new Error(
95
+ `color type ${colorType} at bit depth ${depth} is not a valid PNG format`,
96
+ );
97
+ const cap = depth === 16 ? MAX_PIXELS_16 : MAX_PIXELS;
98
+ if (width * height > cap)
99
+ throw new Error(
100
+ `the picture is ${width}x${height}${depth === 16 ? ' at 16 bits per channel' : ''}, more than ${cap / 1e6} million pixels; crop or scale it down${depth === 16 ? ', or save it at 8 bits' : ''}`,
101
+ );
102
+ if (colorType === 3 && !palette)
103
+ throw new Error('the PNG uses a palette but has none');
104
+ if (!data.length) throw new Error('the PNG has no pixel data');
105
+ const channels = CHANNELS[colorType];
58
106
  const bitsPerPixel = channels * depth;
59
107
  const stride = Math.ceil((width * bitsPerPixel) / 8);
108
+ const expected = (stride + 1) * height;
109
+ /** @type {Buffer} */
110
+ let raw;
111
+ try {
112
+ raw = zlib.inflateSync(Buffer.concat(data), {maxOutputLength: expected});
113
+ } catch (e) {
114
+ // Node reports output past the limit as a RangeError.
115
+ throw new Error(
116
+ e instanceof RangeError
117
+ ? 'the pixel data is longer than the header says'
118
+ : 'the pixel data is damaged',
119
+ {cause: e},
120
+ );
121
+ }
122
+ if (raw.length < expected)
123
+ throw new Error(
124
+ `the pixel data is cut off: ${raw.length} of ${expected} bytes`,
125
+ );
60
126
  const bpp = Math.max(1, bitsPerPixel >> 3);
61
127
  const rows = Buffer.alloc(stride * height);
62
128
  for (let y = 0; y < height; y++) {
63
129
  const filter = raw[y * (stride + 1)];
130
+ if (filter > 4)
131
+ throw new Error(`row ${y} has an unknown filter type ${filter}`);
64
132
  const line = raw.subarray(y * (stride + 1) + 1, (y + 1) * (stride + 1));
65
133
  const out = rows.subarray(y * stride, (y + 1) * stride);
66
134
  const prev = y > 0 ? rows.subarray((y - 1) * stride, y * stride) : null;
@@ -94,25 +162,55 @@ export function decodePng(bytes) {
94
162
  const v = (byte >> (8 - depth - (bit & 7))) & max;
95
163
  return colorType === 3 ? v : Math.round((v * 255) / max);
96
164
  };
165
+ const entries = palette ? Math.floor(palette.length / 3) : 0;
166
+ /** A sample as stored, before scaling to 0-255. @param {number} y @param {number} i */
167
+ const raw16 = (y, i) => {
168
+ const row = y * stride;
169
+ if (depth === 16) return (rows[row + i * 2] << 8) | rows[row + i * 2 + 1];
170
+ if (depth === 8) return rows[row + i];
171
+ const bit = i * depth;
172
+ return (rows[row + (bit >> 3)] >> (8 - depth - (bit & 7))) & max;
173
+ };
174
+ // tRNS for gray and RGB pictures names one color that is fully
175
+ // see-through.
176
+ const key =
177
+ alpha && colorType === 0 && alpha.length >= 2
178
+ ? [alpha.readUInt16BE(0)]
179
+ : alpha && colorType === 2 && alpha.length >= 6
180
+ ? [alpha.readUInt16BE(0), alpha.readUInt16BE(2), alpha.readUInt16BE(4)]
181
+ : null;
97
182
  for (let y = 0; y < height; y++) {
98
183
  for (let x = 0; x < width; x++) {
99
184
  const o = (y * width + x) * 4;
100
185
  const s = x * channels;
101
186
  if (colorType === 3) {
102
187
  const idx = sample(y, s);
103
- rgba[o] = palette?.[idx * 3] ?? 0;
104
- rgba[o + 1] = palette?.[idx * 3 + 1] ?? 0;
105
- rgba[o + 2] = palette?.[idx * 3 + 2] ?? 0;
188
+ if (idx >= entries)
189
+ throw new Error(`a pixel names palette entry ${idx} of ${entries}`);
190
+ const pal = /** @type {Buffer} */ (palette);
191
+ rgba[o] = pal[idx * 3];
192
+ rgba[o + 1] = pal[idx * 3 + 1];
193
+ rgba[o + 2] = pal[idx * 3 + 2];
106
194
  rgba[o + 3] = alpha && idx < alpha.length ? alpha[idx] : 255;
107
195
  } else if (colorType === 0 || colorType === 4) {
108
196
  const g = sample(y, s);
109
197
  rgba[o] = rgba[o + 1] = rgba[o + 2] = g;
110
- rgba[o + 3] = colorType === 4 ? sample(y, s + 1) : 255;
198
+ rgba[o + 3] =
199
+ colorType === 4
200
+ ? sample(y, s + 1)
201
+ : key && raw16(y, s) === key[0]
202
+ ? 0
203
+ : 255;
111
204
  } else {
112
205
  rgba[o] = sample(y, s);
113
206
  rgba[o + 1] = sample(y, s + 1);
114
207
  rgba[o + 2] = sample(y, s + 2);
115
- rgba[o + 3] = colorType === 6 ? sample(y, s + 3) : 255;
208
+ rgba[o + 3] =
209
+ colorType === 6
210
+ ? sample(y, s + 3)
211
+ : key && key.every((k, n) => raw16(y, s + n) === k)
212
+ ? 0
213
+ : 255;
116
214
  }
117
215
  }
118
216
  }
@@ -123,26 +221,28 @@ export function decodePng(bytes) {
123
221
  const hx = v => Math.round(v).toString(16).padStart(2, '0');
124
222
 
125
223
  /**
126
- * The exact color at each point.
224
+ * The exact color at each point, with its alpha (0 is fully see-through,
225
+ * 1 fully opaque). Every point must be inside the picture.
127
226
  * @param {Picture} pic
128
227
  * @param {Array<{x: number, y: number}>} points
129
- * @returns {Array<{at: string, color: string | null}>}
228
+ * @returns {Array<{at: string, color: string, alpha: number}>}
130
229
  */
131
230
  export function colorsAt(pic, points) {
132
231
  return points.map(({x, y}) => {
133
- if (x < 0 || y < 0 || x >= pic.width || y >= pic.height)
134
- return {at: `${x},${y}`, color: null};
135
232
  const i = (y * pic.width + x) * 4;
136
233
  return {
137
234
  at: `${x},${y}`,
138
235
  color: `#${hx(pic.rgba[i])}${hx(pic.rgba[i + 1])}${hx(pic.rgba[i + 2])}`,
236
+ alpha: Number((pic.rgba[i + 3] / 255).toFixed(2)),
139
237
  };
140
238
  });
141
239
  }
142
240
 
143
241
  /**
144
- * The main colors of a picture: every second pixel bucketed to 5 bits per
145
- * channel, biggest share first, each with where it sits.
242
+ * The main colors of a picture: every pixel (on a grid past 4 million)
243
+ * bucketed to 5 bits per channel, biggest share first, each with where it sits. A fully
244
+ * see-through pixel shows no color, so it is skipped; a partly see-through
245
+ * one counts as it looks over white.
146
246
  * @param {Picture} pic
147
247
  * @param {number} count
148
248
  * @returns {Array<{color: string, share: number, where: string}>}
@@ -150,12 +250,22 @@ export function colorsAt(pic, points) {
150
250
  export function mainColors(pic, count) {
151
251
  /** @type {Map<number, {n: number, r: number, g: number, b: number, x: number, y: number}>} */
152
252
  const buckets = new Map();
153
- for (let y = 0; y < pic.height; y += 2) {
154
- for (let x = 0; x < pic.width; x += 2) {
253
+ // Every pixel up to a budget, so a 1-pixel line is never skipped; a
254
+ // bigger picture is read on an even grid.
255
+ const step = Math.max(
256
+ 1,
257
+ Math.ceil(Math.sqrt((pic.width * pic.height) / SAMPLE_BUDGET)),
258
+ );
259
+ for (let y = 0; y < pic.height; y += step) {
260
+ for (let x = 0; x < pic.width; x += step) {
155
261
  const i = (y * pic.width + x) * 4;
156
- const r = pic.rgba[i];
157
- const g = pic.rgba[i + 1];
158
- const b = pic.rgba[i + 2];
262
+ const a = pic.rgba[i + 3] / 255;
263
+ if (a === 0) continue;
264
+ const over = (/** @type {number} */ c) =>
265
+ Math.round(c * a + 255 * (1 - a));
266
+ const r = over(pic.rgba[i]);
267
+ const g = over(pic.rgba[i + 1]);
268
+ const b = over(pic.rgba[i + 2]);
159
269
  const k = ((r >> 3) << 10) | ((g >> 3) << 5) | (b >> 3);
160
270
  let e = buckets.get(k);
161
271
  if (!e) {
@@ -6,19 +6,26 @@
6
6
  * a font package installed after `set` loads on the next change or `show`,
7
7
  * and its Colors page, so it names the shades the tokens use now.
8
8
  * The preview in the usual place (app/ or src/app/theme-preview) and every
9
- * preview added with --path for the theme are kept this way.
9
+ * preview added with --path for the theme are kept this way. A damaged
10
+ * preview, and a file changed by hand, are left as they are.
10
11
  * @param {string} cwd
11
12
  * @param {string} slug
12
- * @returns {Promise<boolean>} whether the route or the Colors page was rewritten
13
+ * @returns {Promise<{changed: boolean, stale: string[]}>} `changed`: the
14
+ * route or the Colors page was rewritten; `stale`: preview files changed by
15
+ * hand, which keep showing the theme as it was
13
16
  */
14
- export function refreshPreviewRoute(cwd: string, slug: string): Promise<boolean>;
17
+ export function refreshPreviewRoute(cwd: string, slug: string): Promise<{
18
+ changed: boolean;
19
+ stale: string[];
20
+ }>;
15
21
  /**
16
22
  * Add pages to the in-app theme preview, and write the preview route the
17
23
  * first time. With a description, the build ranking picks the template
18
24
  * pages that fit it best (`top` of them); `template` names one instead.
19
25
  * With neither, the default pages: the sample app page, every component,
20
26
  * and the theme's generated colors when it has any.
21
- * Every check runs before the first write, so a refusal changes nothing.
27
+ * Every check runs before the first write, so a refusal changes nothing;
28
+ * the files are staged and renamed into place together.
22
29
  * @experimental
23
30
  * @param {string} [description]
24
31
  * @param {import('./theme-edit.type.mjs').ThemeEditPreviewAddOptions} [options]
@@ -39,7 +46,8 @@ export function themeEditPreviewAdd(description?: string, options?: import("./th
39
46
  export function themeEditPreviewApp(dir: string, options?: import("./theme-edit.type.mjs").ThemeEditPreviewAppOptions): Promise<import("./theme-edit.type.mjs").ThemeEditPreviewAppResponse>;
40
47
  /**
41
48
  * The pages of the in-app theme preview. With no preview, and with no
42
- * routes folder for one, the list is empty.
49
+ * routes folder for one, the list is empty; a damaged theme-preview.json is
50
+ * refused, naming the file.
43
51
  * @experimental
44
52
  * @param {import('./theme-edit.type.mjs').ThemeEditPreviewListOptions} [options]
45
53
  * @returns {Promise<import('./theme-edit.type.mjs').ThemeEditPreviewListResponse>}
@@ -47,8 +55,9 @@ export function themeEditPreviewApp(dir: string, options?: import("./theme-edit.
47
55
  export function themeEditPreviewList(options?: import("./theme-edit.type.mjs").ThemeEditPreviewListOptions): Promise<import("./theme-edit.type.mjs").ThemeEditPreviewListResponse>;
48
56
  /**
49
57
  * Remove one page from the in-app theme preview, or with no page the whole
50
- * preview: only the files it wrote are deleted, and only inside the route
51
- * folder.
58
+ * preview. Only files the preview wrote are deleted, only inside the route
59
+ * folder, and never one changed by hand since: those are kept and named.
60
+ * Every check, the theme included, runs before the first delete.
52
61
  * @experimental
53
62
  * @param {string} [page]
54
63
  * @param {import('./theme-edit.type.mjs').ThemeEditPreviewListOptions} [options]
@@ -60,9 +69,19 @@ export type PreviewPage = {
60
69
  label: string;
61
70
  file: string;
62
71
  };
72
+ /**
73
+ * `hashes`: a short hash of each file as the preview wrote it, so a file
74
+ * changed by hand is never replaced or deleted
75
+ */
63
76
  export type PreviewData = {
64
77
  version: 1;
65
78
  theme: string | null;
66
79
  pages: PreviewPage[];
67
80
  files: string[];
81
+ hashes?: Record<string, string>;
68
82
  };
83
+ /**
84
+ * the command again, with
85
+ * this --path (null: none)
86
+ */
87
+ export type Retry = (path: string | null) => string;