@triflare/fx 2.2.0 → 2.3.0-alpha.2

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/src/layout.js ADDED
@@ -0,0 +1,402 @@
1
+ /**
2
+ * Workspace layout for compiled scripts.
3
+ *
4
+ * Mimics Scratch's built-in "Clean up Blocks" command: every top-level script
5
+ * is stacked in a single vertical column, starting half a grid cell in from
6
+ * the corner. Each script is placed one `MIN_BLOCK_Y` below the bottom of the
7
+ * previous script, in source order. Unlike the enhanced clean up tool in
8
+ * Scratch Addons, no columns are created and scripts are never reordered.
9
+ *
10
+ * A generated project has no previous arrangement to preserve, so source order
11
+ * is the natural order for the column. Rendered sizes are estimated from the
12
+ * block tree with the same row metrics scratch-blocks uses. Scratch draws
13
+ * extension blocks one grid unit taller than core blocks, so those are
14
+ * accounted for as well.
15
+ *
16
+ * Measurement reads both project JSON (inputs are `[type, value]` arrays) and
17
+ * the shape scratch-vm's `Blocks` keeps after loading a project (inputs are
18
+ * `{name, block, shadow}` objects), so tests can measure the workspace the VM
19
+ * actually deserialized.
20
+ */
21
+
22
+ /**
23
+ * Scratch-gui's workspace grid spacing (`grid.spacing` in blocks.jsx). The
24
+ * clean up command itself does not snap, but half a cell is a comfortable
25
+ * margin for the column.
26
+ */
27
+ export const GRID_SIZE = 40;
28
+
29
+ /** Half a grid cell, used as the workspace margin. */
30
+ export const GRID_OFFSET = GRID_SIZE / 2;
31
+
32
+ /** Default size of a Scratch comment bubble. */
33
+ export const COMMENT_WIDTH = 200;
34
+ export const COMMENT_HEIGHT = 100;
35
+
36
+ // scratch-blocks metrics, in pixels (GRID_UNIT is 4 there; these are the
37
+ // derived values from block_render_svg_vertical.js).
38
+ const NOTCH_HEIGHT = 8;
39
+
40
+ /** Height of one block row, and the gap left between packed scripts. */
41
+ export const MIN_BLOCK_Y = 48;
42
+ const MIN_STATEMENT_INPUT_HEIGHT = 24;
43
+ const EXTRA_STATEMENT_ROW_Y = 32;
44
+ const STATEMENT_INDENT = 56;
45
+
46
+ /** Scratch draws blocks from extensions one grid unit taller. */
47
+ const EXTENSION_ROW_EXTRA = 8;
48
+
49
+ // Width estimates. Scratch renders block labels in a bold 12pt face, which
50
+ // averages a little under 10px per character at the editor's scale.
51
+ const CHAR_WIDTH = 9;
52
+ const BLOCK_PADDING_X = 16;
53
+ const ELEMENT_GAP = 8;
54
+ const MIN_FIELD_WIDTH = 40;
55
+ const MIN_INPUT_WIDTH = 40;
56
+ const MIN_SCRIPT_WIDTH = 96;
57
+ const DROPDOWN_ARROW_WIDTH = 24;
58
+
59
+ /** Placeholders a custom block's proccode uses for its arguments. */
60
+ const PROCODE_PLACEHOLDER = /%[0-9]+|%[snb]/g;
61
+
62
+ /** Opcode labels are cached per catalog, which is stable for a whole build. */
63
+ const labelMaps = new WeakMap();
64
+
65
+ /** Opcodes provided by extensions, which scratch-blocks renders taller. */
66
+ const extensionSets = new WeakMap();
67
+
68
+ function extensionsFor(catalog) {
69
+ const known = extensionSets.get(catalog);
70
+ if (known) return known;
71
+ const extensions = new Set();
72
+ for (const entry of Object.values(catalog)) {
73
+ if (entry && entry.opcode && entry.extension) extensions.add(entry.opcode);
74
+ }
75
+ extensionSets.set(catalog, extensions);
76
+ return extensions;
77
+ }
78
+
79
+ /** Opcode -> catalog entry, so layout can read an input's declared type. */
80
+ const entrySets = new WeakMap();
81
+
82
+ function entriesFor(catalog) {
83
+ const known = entrySets.get(catalog);
84
+ if (known) return known;
85
+ const entries = new Map();
86
+ for (const entry of Object.values(catalog)) {
87
+ if (entry && entry.opcode) entries.set(entry.opcode, entry);
88
+ }
89
+ entrySets.set(catalog, entries);
90
+ return entries;
91
+ }
92
+
93
+ /**
94
+ * Build an opcode -> human label map from the catalog. The Fx name is the
95
+ * closest thing a compiler has to the block's rendered text (`motion.moveSteps`
96
+ * reads "move steps").
97
+ */
98
+ function labelsFor(catalog) {
99
+ const known = labelMaps.get(catalog);
100
+ if (known) return known;
101
+ const labels = new Map();
102
+ for (const [name, entry] of Object.entries(catalog)) {
103
+ if (entry && entry.opcode) labels.set(entry.opcode, labelWords(name));
104
+ }
105
+ labelMaps.set(catalog, labels);
106
+ return labels;
107
+ }
108
+
109
+ /** Turn `motion.switchCostumeTo` into "switch costume to". */
110
+ function labelWords(name) {
111
+ const short = name.slice(name.lastIndexOf(".") + 1);
112
+ return short
113
+ .replace(/([a-z0-9])([A-Z])/g, "$1 $2")
114
+ .replace(/[_-]+/g, " ")
115
+ .replace(/\s+/g, " ")
116
+ .trim()
117
+ .toLowerCase();
118
+ }
119
+
120
+ /** The text a block renders before its fields and inputs. */
121
+ function blockLabel(block, labels) {
122
+ // A definition's row is just the prototype block it contains.
123
+ if (
124
+ block.opcode === "procedures_definition" ||
125
+ block.opcode === "procedures_definition_return"
126
+ ) {
127
+ return "";
128
+ }
129
+ if (
130
+ block.opcode === "procedures_call" ||
131
+ block.opcode === "procedures_prototype"
132
+ ) {
133
+ const proccode = block.mutation && block.mutation.proccode;
134
+ if (proccode) return String(proccode).replace(PROCODE_PLACEHOLDER, " ");
135
+ }
136
+ const known = labels.get(block.opcode);
137
+ if (known) return known;
138
+ // Unknown (usually extension) opcodes still have readable words: the first
139
+ // segment is the extension or category id.
140
+ return labelWords(block.opcode.replace(/^[^_]+_/, ""));
141
+ }
142
+
143
+ function textWidth(text) {
144
+ return String(text ?? "").length * CHAR_WIDTH;
145
+ }
146
+
147
+ /** A field is a `[value, id]` array in JSON and a `{value}` object in the VM. */
148
+ function fieldValue(field) {
149
+ if (Array.isArray(field)) return field[0];
150
+ if (field && typeof field === "object") return field.value;
151
+ return field;
152
+ }
153
+
154
+ function fieldWidth(value) {
155
+ return Math.max(MIN_FIELD_WIDTH, textWidth(value) + DROPDOWN_ARROW_WIDTH);
156
+ }
157
+
158
+ /**
159
+ * Whether an input holds a nested statement stack. Project JSON uses the same
160
+ * `[2, id]` shape for any block-valued input, so the catalog's input descriptor
161
+ * is the reliable marker; extension blocks may name the stack anything (such as
162
+ * `BODY`). Fall back to scratch-blocks' `SUBSTACK*` naming when the catalog has
163
+ * no descriptor for the input.
164
+ */
165
+ function isStatementInput(name, entry) {
166
+ const spec = entry && entry.inputs && entry.inputs[name];
167
+ if (spec) return spec.type === "substack";
168
+ return String(name).startsWith("SUBSTACK");
169
+ }
170
+
171
+ /** The first block of a statement input, if one is connected. */
172
+ function statementBlockId(input) {
173
+ if (Array.isArray(input))
174
+ return typeof input[1] === "string" ? input[1] : null;
175
+ return input && typeof input.block === "string" ? input.block : null;
176
+ }
177
+
178
+ /**
179
+ * The value an input holds: a compressed `[shadowType, text]` primitive, a
180
+ * reporter block id, or a shadow block id in the VM's representation.
181
+ */
182
+ function inputBlockId(input) {
183
+ if (Array.isArray(input)) return input[1] ?? null;
184
+ return input ? (input.block ?? null) : null;
185
+ }
186
+
187
+ /** Width of a shadow primitive block (text box, number, menu, ...). */
188
+ function shadowWidth(block) {
189
+ if (block.opcode === "colour_picker") return MIN_FIELD_WIDTH + 8;
190
+ const text = Object.values(block.fields || {})
191
+ .map(fieldValue)
192
+ .join(" ");
193
+ return Math.max(MIN_INPUT_WIDTH, textWidth(text) + 16);
194
+ }
195
+
196
+ /**
197
+ * Width of one value input, following a reporter into its own inputs when one
198
+ * is plugged in.
199
+ */
200
+ function inputWidth(blocks, input, labels, entries) {
201
+ const value = inputBlockId(input);
202
+ if (Array.isArray(value)) {
203
+ // Compressed primitive: [shadowType, value]. Colour pickers are fixed size.
204
+ if (value[0] === 9) return MIN_FIELD_WIDTH + 8;
205
+ return Math.max(MIN_INPUT_WIDTH, textWidth(value[1]) + 16);
206
+ }
207
+ if (typeof value !== "string") return MIN_INPUT_WIDTH;
208
+ const child = blocks[value];
209
+ if (!child) return MIN_INPUT_WIDTH;
210
+ // The VM expands primitives into shadow blocks. Reporters and procedure
211
+ // prototypes are real blocks and are measured as such.
212
+ if (child.shadow && !child.mutation) return shadowWidth(child);
213
+ return rowWidth(blocks, child, labels, entries);
214
+ }
215
+
216
+ /**
217
+ * Width of a block's own row (labels, fields and value inputs), before any
218
+ * nested statement stacks widen it.
219
+ */
220
+ function rowWidth(blocks, block, labels, entries) {
221
+ const entry = entries.get(block.opcode);
222
+ let width = BLOCK_PADDING_X + textWidth(blockLabel(block, labels));
223
+ for (const [name, input] of Object.entries(block.inputs || {})) {
224
+ if (isStatementInput(name, entry)) continue;
225
+ width += ELEMENT_GAP + inputWidth(blocks, input, labels, entries);
226
+ }
227
+ for (const field of Object.values(block.fields || {})) {
228
+ width += ELEMENT_GAP + fieldWidth(fieldValue(field));
229
+ }
230
+ return Math.max(width, MIN_SCRIPT_WIDTH);
231
+ }
232
+
233
+ /** Width of a block, including the statement stacks nested inside it. */
234
+ function blockWidth(blocks, block, labels, entries) {
235
+ const entry = entries.get(block.opcode);
236
+ const own = rowWidth(blocks, block, labels, entries);
237
+ let nested = 0;
238
+ for (const [name, input] of Object.entries(block.inputs || {})) {
239
+ if (!isStatementInput(name, entry)) continue;
240
+ const first = statementBlockId(input);
241
+ if (first && blocks[first]) {
242
+ nested = Math.max(nested, stackWidth(blocks, first, labels, entries));
243
+ }
244
+ }
245
+ return nested ? Math.max(own, nested + STATEMENT_INDENT) : own;
246
+ }
247
+
248
+ function stackWidth(blocks, firstId, labels, entries) {
249
+ let width = 0;
250
+ let block = blocks[firstId];
251
+ while (block) {
252
+ width = Math.max(width, blockWidth(blocks, block, labels, entries));
253
+ block = block.next ? blocks[block.next] : null;
254
+ }
255
+ return width;
256
+ }
257
+
258
+ /**
259
+ * Whether an input subtree contains a block from an extension. Walks pending
260
+ * reporters with an explicit work list so long chains cannot exhaust the call
261
+ * stack.
262
+ */
263
+ function hasExtensionBlock(blocks, input, extensions) {
264
+ const seen = new Set();
265
+ const pending = [inputBlockId(input)];
266
+ while (pending.length) {
267
+ const id = pending.pop();
268
+ if (typeof id !== "string" || seen.has(id)) continue;
269
+ seen.add(id);
270
+ const block = blocks[id];
271
+ if (!block) continue;
272
+ if (extensions.has(block.opcode)) return true;
273
+ for (const child of Object.values(block.inputs || {})) {
274
+ const childId = inputBlockId(child);
275
+ if (typeof childId === "string" && !seen.has(childId))
276
+ pending.push(childId);
277
+ }
278
+ }
279
+ return false;
280
+ }
281
+
282
+ /**
283
+ * Height of a block's own row plus every statement stack nested inside it.
284
+ * Mirrors scratch-blocks' row metrics: a row is MIN_BLOCK_Y tall, a statement
285
+ * input is at least MIN_STATEMENT_INPUT_HEIGHT, every statement input adds the
286
+ * EXTRA_STATEMENT_ROW_Y divider or bottom bar below it, extension blocks are
287
+ * one grid unit taller, and a next-statement notch is part of the block's
288
+ * height. Hats are drawn above the block's origin, so they add no height.
289
+ */
290
+ function blockHeight(blocks, block, extensions, entries) {
291
+ const entry = entries.get(block.opcode);
292
+ let height = MIN_BLOCK_Y;
293
+
294
+ // Extension statement blocks render their inline row one grid unit taller,
295
+ // and so do rows holding an extension reporter.
296
+ let inlineRow = extensions.has(block.opcode) && block.parent != null;
297
+ for (const [name, input] of Object.entries(block.inputs || {})) {
298
+ if (!isStatementInput(name, entry)) {
299
+ inlineRow ||= hasExtensionBlock(blocks, input, extensions);
300
+ }
301
+ }
302
+ if (inlineRow) height += EXTENSION_ROW_EXTRA;
303
+
304
+ let statements = 0;
305
+ for (const [name, input] of Object.entries(block.inputs || {})) {
306
+ if (!isStatementInput(name, entry)) continue;
307
+ statements += 1;
308
+ const first = statementBlockId(input);
309
+ const inner =
310
+ first && blocks[first]
311
+ ? stackHeight(blocks, first, extensions, entries)
312
+ : 0;
313
+ height += Math.max(MIN_STATEMENT_INPUT_HEIGHT, inner - NOTCH_HEIGHT);
314
+ }
315
+
316
+ height += statements * EXTRA_STATEMENT_ROW_Y;
317
+ // Stacked blocks overlap the notch above them, so the notch simply becomes
318
+ // part of each block's own height.
319
+ return height + NOTCH_HEIGHT;
320
+ }
321
+
322
+ function stackHeight(blocks, firstId, extensions, entries) {
323
+ let height = 0;
324
+ let first = true;
325
+ let block = blocks[firstId];
326
+ while (block) {
327
+ const own = blockHeight(blocks, block, extensions, entries);
328
+ height += first ? own : own - NOTCH_HEIGHT;
329
+ first = false;
330
+ block = block.next ? blocks[block.next] : null;
331
+ }
332
+ return height;
333
+ }
334
+
335
+ /** Height only, for layout: widths are not needed to stack scripts. */
336
+ function measureHeight(blocks, firstId, catalog) {
337
+ return stackHeight(
338
+ blocks,
339
+ firstId,
340
+ extensionsFor(catalog),
341
+ entriesFor(catalog),
342
+ );
343
+ }
344
+
345
+ /**
346
+ * Estimated rendered size of the script starting at `firstId`.
347
+ *
348
+ * @param {Record<string, object>} blocks project JSON or scratch-vm blocks map
349
+ * @param {string} firstId id of the script's top-level block
350
+ * @param {Record<string, object>} catalog block catalog used for label widths
351
+ * @returns {{width: number, height: number}}
352
+ */
353
+ export function measureScript(blocks, firstId, catalog) {
354
+ const labels = labelsFor(catalog);
355
+ return {
356
+ width: stackWidth(blocks, firstId, labels, entriesFor(catalog)),
357
+ height: measureHeight(blocks, firstId, catalog),
358
+ };
359
+ }
360
+
361
+ /**
362
+ * Position every top-level script on a target like Scratch's built-in clean up
363
+ * command: one vertical column, each script one block row below the previous
364
+ * script's bottom. Attached comments keep their auto-positioning; standalone
365
+ * workspace comments follow the column.
366
+ *
367
+ * @param {object} target project target whose blocks are already serialized
368
+ * @param {Record<string, object>} catalog block catalog used for label widths
369
+ */
370
+ export function layoutTarget(target, catalog) {
371
+ const scripts = Object.entries(target.blocks).filter(
372
+ ([, block]) => block.topLevel,
373
+ );
374
+
375
+ let cursorY = GRID_OFFSET;
376
+ for (const [id, block] of scripts) {
377
+ const height = measureHeight(target.blocks, id, catalog);
378
+ block.x = GRID_OFFSET;
379
+ block.y = cursorY;
380
+ cursorY = block.y + height + MIN_BLOCK_Y;
381
+ }
382
+
383
+ layoutWorkspaceComments(target, cursorY);
384
+ }
385
+
386
+ /**
387
+ * Place unpositioned workspace comments (`blockId: null`, no x/y) below the
388
+ * scripts in the same column. The config comment already has a position and is
389
+ * left alone.
390
+ */
391
+ function layoutWorkspaceComments(target, startY) {
392
+ const comments = Object.values(target.comments || {}).filter(
393
+ (comment) => comment.blockId == null && comment.x == null,
394
+ );
395
+
396
+ let cursorY = startY;
397
+ for (const comment of comments) {
398
+ comment.x = GRID_OFFSET;
399
+ comment.y = cursorY;
400
+ cursorY += (comment.height || COMMENT_HEIGHT) + MIN_BLOCK_Y;
401
+ }
402
+ }
@@ -3,8 +3,9 @@
3
3
  *
4
4
  * The full config loader (`src/config.js`) needs `node:fs` to search for the
5
5
  * file, so editors that only have the file's text use this instead. It reads
6
- * the settings lint diagnostics depend on — `fx.partialSprites`, `fx.lint` and
7
- * the declared extension names — and ignores everything else.
6
+ * the settings lint diagnostics depend on — `fx.features` (with the older
7
+ * `fx.<name>` keys as fallbacks), `fx.lint`, and the declared extension names —
8
+ * and ignores everything else.
8
9
  */
9
10
 
10
11
  import * as yaml from "js-yaml";
@@ -98,20 +99,40 @@ export function parseProjectConfigText(text) {
98
99
  }
99
100
  }
100
101
 
102
+ // `fx.features` is the canonical switch; older `fx.<name>` settings still
103
+ // apply when the new key does not name that feature.
104
+ const features =
105
+ fx.features &&
106
+ typeof fx.features === "object" &&
107
+ !Array.isArray(fx.features)
108
+ ? fx.features
109
+ : {};
110
+ const setting = (name) =>
111
+ Object.hasOwn(features, name) ? features[name] : fx[name];
112
+
101
113
  const patternOf = (value, fallback) => {
102
114
  if (value === true) return fallback;
103
115
  if (value && typeof value === "object" && !Array.isArray(value)) {
116
+ if (value.enabled === false) return null;
104
117
  if (value.pattern === undefined) return fallback;
105
118
  if (typeof value.pattern === "string" && value.pattern.trim())
106
119
  return value.pattern.trim();
107
120
  }
108
121
  return null;
109
122
  };
110
- const testPattern = patternOf(fx.tests, DEFAULT_TEST_PATTERN);
111
- const runPattern = patternOf(fx.run, DEFAULT_RUN_PATTERN);
123
+ const testPattern = patternOf(setting("tests"), DEFAULT_TEST_PATTERN);
124
+ const runPattern = patternOf(setting("run"), DEFAULT_RUN_PATTERN);
125
+ const partial = setting("partialSprites");
112
126
 
113
127
  return {
114
- config: { fx: { partialSprites: Boolean(fx.partialSprites) } },
128
+ config: {
129
+ fx: {
130
+ partialSprites:
131
+ partial != null && typeof partial === "object"
132
+ ? partial.enabled !== false
133
+ : Boolean(partial),
134
+ },
135
+ },
115
136
  lintConfig,
116
137
  declaredExtensions: [...declaredExtensions],
117
138
  testPattern,
package/src/merge.js CHANGED
@@ -39,10 +39,14 @@ export function mergePrograms(
39
39
  ) {
40
40
  let stage = null;
41
41
  const topItems = [];
42
+ const standaloneComments = [];
42
43
  /** @type {Map<string, {name: string, loc: object, base: object|null, fragments: object[], files: string[]}>} */
43
44
  const groups = new Map();
44
45
 
45
46
  for (const { ast, file } of entries) {
47
+ if (ast.standaloneComments)
48
+ for (const comment of ast.standaloneComments)
49
+ standaloneComments.push(comment);
46
50
  if (ast.tests && ast.tests.length > 0)
47
51
  throw new ParseError(
48
52
  `Test ${JSON.stringify(ast.tests[0].name)} is declared in a project source. ` +
@@ -112,5 +116,5 @@ export function mergePrograms(
112
116
  };
113
117
  });
114
118
 
115
- return { type: "Program", stage, sprites, topItems };
119
+ return { type: "Program", stage, sprites, topItems, standaloneComments };
116
120
  }