@triflare/fx 2.2.0 → 2.3.0-alpha.1

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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@triflare/fx",
3
- "version": "2.2.0",
3
+ "version": "2.3.0-alpha.1",
4
4
  "description": "Code PenguinMod projects with text.",
5
5
  "type": "module",
6
6
  "license": "Apache-2.0",
package/product.yml CHANGED
@@ -1,7 +1,7 @@
1
1
  # Identity
2
2
  name: "Triflare Fx"
3
3
  command: "fx"
4
- version: "2.2.0"
4
+ version: "2.3.0-alpha.1"
5
5
  tagline: "Code PenguinMod projects with text."
6
6
  author: "Triflare"
7
7
  homepage: "https://github.com/triflare/fx"
@@ -0,0 +1,287 @@
1
+ /**
2
+ * Attach source comments to the AST.
3
+ *
4
+ * Comments are not part of the token stream. After parsing, each comment is
5
+ * resolved to the block-bearing declaration or statement it belongs to:
6
+ *
7
+ * - a comment before an item attaches to that item (`comments` on the node),
8
+ * - a trailing comment on an item's own line attaches to that item,
9
+ * - a comment inside a block body with nothing after it attaches to the
10
+ * enclosing block,
11
+ * - comments that cannot sit on a block (before a sprite, variable, list or
12
+ * property declaration, or in an empty sprite) become standalone workspace
13
+ * comments on the target they belong to.
14
+ *
15
+ * Comments inside `test` declarations are dropped: test files are never part of
16
+ * a built project.
17
+ */
18
+
19
+ /** AST node types that compile to at least one block. */
20
+ const BLOCK_OWNERS = new Set([
21
+ "Assign",
22
+ "BlockCall",
23
+ "Forever",
24
+ "FunctionDecl",
25
+ "HatDecl",
26
+ "If",
27
+ "Repeat",
28
+ "Return",
29
+ "TempVarDecl",
30
+ "While",
31
+ ]);
32
+
33
+ /**
34
+ * Turn a raw `//` or block comment into the text Scratch should display.
35
+ * Block-comment asterisk decorations are removed line by line.
36
+ * @param {string} raw
37
+ * @returns {string}
38
+ */
39
+ export function commentText(raw) {
40
+ const source = raw.replace(/\r\n?/g, "\n");
41
+ if (source.startsWith("//")) return source.slice(2).trim();
42
+ if (source.startsWith("/*") && source.endsWith("*/")) {
43
+ const lines = source
44
+ .slice(2, -2)
45
+ .split("\n")
46
+ .map((line) => line.replace(/^\s*\*?[ \t]?/, "").trimEnd());
47
+ while (lines.length && !lines[0].trim()) lines.shift();
48
+ while (lines.length && !lines[lines.length - 1].trim()) lines.pop();
49
+ return lines.join("\n").trim();
50
+ }
51
+ return source.trim();
52
+ }
53
+
54
+ /**
55
+ * Resolve comment placement for a freshly parsed program.
56
+ * @param {object} ast program node (mutated with attachments)
57
+ * @param {Array} comments lexer comments
58
+ * @param {Array} tokens lexer tokens
59
+ * @param {WeakMap<object, object>} spans body brace tokens per node
60
+ */
61
+ export function attachComments(ast, comments, tokens, spans) {
62
+ const standalone = [];
63
+ if (comments.length > 0) {
64
+ const indexes = new Map();
65
+ tokens.forEach((token, index) => indexes.set(token, index));
66
+
67
+ const programItems = [
68
+ ...(ast.stage ? [ast.stage] : []),
69
+ ...ast.sprites,
70
+ ...ast.topItems,
71
+ ...(ast.tests || []),
72
+ ].filter((item) => indexes.has(item.loc));
73
+
74
+ const scopes = [
75
+ {
76
+ items: programItems,
77
+ open: -1,
78
+ close: tokens.length - 1,
79
+ owner: null,
80
+ target: "Stage",
81
+ stage: true,
82
+ },
83
+ ];
84
+ for (const item of programItems)
85
+ collectScopes(item, scopes, "Stage", true, indexes, spans);
86
+
87
+ for (const comment of comments) {
88
+ const text = commentText(comment.text);
89
+ if (!text) continue;
90
+ placeComment(
91
+ ast,
92
+ innermostScope(scopes, comment.after),
93
+ comment,
94
+ text,
95
+ indexes,
96
+ );
97
+ }
98
+ }
99
+ ast.standaloneComments = standalone;
100
+
101
+ function addStandalone(text, target, stage) {
102
+ // `""` is a valid sprite name, so only a missing target falls back to the
103
+ // stage in the compiler; an empty name must still resolve through byName.
104
+ if (target != null) standalone.push({ text, target, stage });
105
+ }
106
+
107
+ /** Sibling items ordered by source position, built once per scope. */
108
+ function orderedItems(scope, indexes) {
109
+ if (scope.entries) return scope.entries;
110
+ const entries = scope.items
111
+ .map((item) => ({ item, index: indexes.get(item.loc) }))
112
+ .filter((entry) => entry.index !== undefined)
113
+ .sort((a, b) => a.index - b.index);
114
+ // An item ends at the last token before the next item (or the scope's
115
+ // closing brace), so a trailing comment on a multiline item is still on
116
+ // that item's line.
117
+ for (let i = 0; i < entries.length; i++) {
118
+ const end = i + 1 < entries.length ? entries[i + 1].index : scope.close;
119
+ const token = tokens[Math.max(0, end - 1)];
120
+ entries[i].endLine = token ? token.line : entries[i].item.loc.line;
121
+ }
122
+ scope.entries = entries;
123
+ return entries;
124
+ }
125
+
126
+ /** First position in the ordered entries whose token index is >= `index`. */
127
+ function lowerBound(entries, index) {
128
+ let low = 0;
129
+ let high = entries.length;
130
+ while (low < high) {
131
+ const mid = (low + high) >> 1;
132
+ if (entries[mid].index < index) low = mid + 1;
133
+ else high = mid;
134
+ }
135
+ return low;
136
+ }
137
+
138
+ function placeComment(program, scope, comment, text, indexes) {
139
+ // Comments inside a test body are dropped with the rest of the test.
140
+ if (scope.drop) return;
141
+ const entries = orderedItems(scope, indexes);
142
+ const position = lowerBound(entries, comment.after);
143
+
144
+ // A comment after code on the same line belongs to that code, including
145
+ // when the code spans several lines.
146
+ for (let i = position - 1; i >= 0; i--) {
147
+ const entry = entries[i];
148
+ if (entry.endLine !== comment.line) break;
149
+ return place(program, scope, entry.item, text);
150
+ }
151
+
152
+ const next = entries[position];
153
+ if (next) return place(program, scope, next.item, text);
154
+
155
+ // Nothing follows in a block body: the comment describes the block.
156
+ if (scope.owner && BLOCK_OWNERS.has(scope.owner.type))
157
+ return place(program, scope, scope.owner, text);
158
+
159
+ const previous = entries[position - 1];
160
+ if (previous) return place(program, scope, previous.item, text);
161
+
162
+ // An empty body: the comment describes the block or sprite that owns it.
163
+ if (scope.owner) return place(program, scope, scope.owner, text);
164
+ addStandalone(text, scope.target, scope.stage);
165
+ }
166
+
167
+ function place(program, scope, item, text) {
168
+ if (item.type === "TestDecl") return;
169
+ if (BLOCK_OWNERS.has(item.type)) {
170
+ item.comments = item.comments || [];
171
+ item.comments.push(text);
172
+ return;
173
+ }
174
+ if (item.type === "SpriteDecl")
175
+ return addStandalone(text, item.name, false);
176
+ if (item.type === "StageDecl") return addStandalone(text, "Stage", true);
177
+ addStandalone(text, scope.target, scope.stage);
178
+ }
179
+ }
180
+
181
+ function innermostScope(scopes, index) {
182
+ let best = scopes[0];
183
+ for (const scope of scopes) {
184
+ if (index <= scope.open || index > scope.close) continue;
185
+ if (scope.open > best.open) best = scope;
186
+ }
187
+ return best;
188
+ }
189
+
190
+ function collectScopes(item, scopes, target, stage, indexes, spans) {
191
+ if (!item) return;
192
+
193
+ const span = spans.get(item) || {};
194
+ const addScope = (
195
+ body,
196
+ open,
197
+ close,
198
+ owner,
199
+ scopeTarget,
200
+ scopeStage,
201
+ drop = false,
202
+ ) => {
203
+ if (!body || !open || !close) return;
204
+ scopes.push({
205
+ items: body,
206
+ open: indexes.get(open) ?? -1,
207
+ close: indexes.get(close) ?? -1,
208
+ owner,
209
+ target: scopeTarget,
210
+ stage: scopeStage,
211
+ drop,
212
+ });
213
+ };
214
+
215
+ // Test files never reach a built project, so their comments are dropped.
216
+ // Their braces are still registered as a scope so comments inside a test
217
+ // body cannot attach to declarations around it.
218
+ if (item.type === "TestDecl") {
219
+ addScope(
220
+ item.body,
221
+ span.bodyOpen,
222
+ span.bodyClose,
223
+ item,
224
+ target,
225
+ stage,
226
+ true,
227
+ );
228
+ return;
229
+ }
230
+
231
+ switch (item.type) {
232
+ case "SpriteDecl":
233
+ addScope(
234
+ item.body,
235
+ span.bodyOpen,
236
+ span.bodyClose,
237
+ item,
238
+ item.name,
239
+ false,
240
+ );
241
+ for (const child of item.body)
242
+ collectScopes(child, scopes, item.name, false, indexes, spans);
243
+ break;
244
+ case "StageDecl":
245
+ addScope(item.body, span.bodyOpen, span.bodyClose, item, "Stage", true);
246
+ for (const child of item.body)
247
+ collectScopes(child, scopes, "Stage", true, indexes, spans);
248
+ break;
249
+ case "HatDecl":
250
+ case "FunctionDecl":
251
+ addScope(item.body, span.bodyOpen, span.bodyClose, item, target, stage);
252
+ for (const child of item.body)
253
+ collectScopes(child, scopes, target, stage, indexes, spans);
254
+ break;
255
+ case "If":
256
+ addScope(item.then, span.bodyOpen, span.bodyClose, item, target, stage);
257
+ for (const child of item.then)
258
+ collectScopes(child, scopes, target, stage, indexes, spans);
259
+ if (span.elseOpen) {
260
+ addScope(item.else, span.elseOpen, span.elseClose, item, target, stage);
261
+ }
262
+ for (const child of item.else || [])
263
+ collectScopes(child, scopes, target, stage, indexes, spans);
264
+ break;
265
+ case "Repeat":
266
+ case "While":
267
+ case "Forever":
268
+ addScope(item.body, span.bodyOpen, span.bodyClose, item, target, stage);
269
+ for (const child of item.body)
270
+ collectScopes(child, scopes, target, stage, indexes, spans);
271
+ break;
272
+ case "BlockCall":
273
+ if (item.body) {
274
+ addScope(item.body, span.bodyOpen, span.bodyClose, item, target, stage);
275
+ for (const child of item.body)
276
+ collectScopes(child, scopes, target, stage, indexes, spans);
277
+ }
278
+ if (item.else) {
279
+ addScope(item.else, span.elseOpen, span.elseClose, item, target, stage);
280
+ for (const child of item.else)
281
+ collectScopes(child, scopes, target, stage, indexes, spans);
282
+ }
283
+ break;
284
+ default:
285
+ break;
286
+ }
287
+ }
package/src/compiler.js CHANGED
@@ -8,6 +8,7 @@
8
8
  import { CATALOG, LIST_OPS, extensionForOpcode } from "./catalog.js";
9
9
  import { CompileError } from "./errors.js";
10
10
  import { configComment } from "./config.js";
11
+ import { COMMENT_HEIGHT, COMMENT_WIDTH, layoutTarget } from "./layout.js";
11
12
  import { md5hex, imageSize, wavInfo, detectFormat } from "./sb3.js";
12
13
 
13
14
  const HAT_ALIASES = {
@@ -84,19 +85,6 @@ class Context {
84
85
  this.lists = new Map();
85
86
  this.funcs = new Map();
86
87
  this.paramScopes = [];
87
- this.scriptX = 48;
88
- this.scriptY = 48;
89
- }
90
-
91
- nextScriptPosition() {
92
- const x = this.scriptX;
93
- const y = this.scriptY;
94
- this.scriptY += 420;
95
- if (this.scriptY > 3600) {
96
- this.scriptY = 48;
97
- this.scriptX += 500;
98
- }
99
- return { x, y };
100
88
  }
101
89
 
102
90
  resolveValue(name) {
@@ -261,6 +249,22 @@ export class Compiler {
261
249
  // can only be given their mutation once every stack is complete.
262
250
  for (const ctx of contexts) this.applyDynamicNextMutations(ctx);
263
251
 
252
+ // Source comments that could not sit on a block become workspace comments.
253
+ this.emitStandaloneComments(ast, contexts);
254
+
255
+ // The config comment is a workspace comment too. Emit it before layout so
256
+ // it is positioned with the rest instead of floating at its old spot.
257
+ const configText = configComment(this.projectConfig);
258
+ if (configText)
259
+ this.addWorkspaceComment(this.stageCtx, configText, {
260
+ width: 350,
261
+ height: 170,
262
+ });
263
+
264
+ // Pass 4: pack the scripts like the editor's clean up tool. Sizes depend on
265
+ // the complete block tree, so this has to run after every stack exists.
266
+ for (const ctx of contexts) layoutTarget(ctx.target, this.catalog);
267
+
264
268
  this.validateRequiredExtensions();
265
269
 
266
270
  return { project: this.assembleProject(contexts), assets: this.assets };
@@ -601,7 +605,6 @@ export class Compiler {
601
605
  if (!entry || entry.kind !== "hat")
602
606
  this.fail(`Unknown event ${JSON.stringify(short)}`, decl.loc);
603
607
 
604
- const pos = ctx.nextScriptPosition();
605
608
  const fields = {};
606
609
  const inputs = {};
607
610
  const argSpecs = entry.args || [];
@@ -637,9 +640,8 @@ export class Compiler {
637
640
  fields,
638
641
  inputs,
639
642
  topLevel: true,
640
- x: pos.x,
641
- y: pos.y,
642
643
  });
644
+ this.attachNodeComments(ctx, decl, id);
643
645
  // re-parent any inputs that referenced this hat
644
646
  this.reparentInputs(ctx, id, inputs);
645
647
  const first = this.newStack(ctx, decl.body, id);
@@ -649,15 +651,13 @@ export class Compiler {
649
651
 
650
652
  emitFunction(ctx, decl) {
651
653
  const fn = ctx.funcs.get(decl.name);
652
- const pos = ctx.nextScriptPosition();
653
654
  const defId = this.addBlock(ctx, {
654
655
  opcode: fn.returns
655
656
  ? "procedures_definition_return"
656
657
  : "procedures_definition",
657
658
  topLevel: true,
658
- x: pos.x,
659
- y: pos.y,
660
659
  });
660
+ this.attachNodeComments(ctx, decl, defId);
661
661
 
662
662
  const protoId = uid("proto");
663
663
  const protoInputs = {};
@@ -704,6 +704,76 @@ export class Compiler {
704
704
  if (first) ctx.target.blocks[defId].next = first;
705
705
  }
706
706
 
707
+ // ------------------------------------------------------------- comments
708
+
709
+ /**
710
+ * Emit the comments attached to one AST node as a single Scratch block
711
+ * comment. Scratch links a comment from both ends (`block.comment` and
712
+ * `comment.blockId`), so both are written here.
713
+ * @param {Context} ctx
714
+ * @param {{comments?: string[]}} node
715
+ * @param {string} blockId
716
+ */
717
+ attachNodeComments(ctx, node, blockId) {
718
+ if (!node.comments || node.comments.length === 0) return;
719
+ const block = ctx.target.blocks[blockId];
720
+ if (!block) return;
721
+ const id = uid("c");
722
+ block.comment = id;
723
+ ctx.target.comments[id] = {
724
+ blockId,
725
+ // The editor positions attached comments next to their block when both
726
+ // coordinates are missing (`ScratchBlockComment.autoPosition_`).
727
+ x: null,
728
+ y: null,
729
+ width: COMMENT_WIDTH,
730
+ height: COMMENT_HEIGHT,
731
+ minimized: false,
732
+ text: node.comments.join("\n"),
733
+ };
734
+ }
735
+
736
+ /**
737
+ * Add a comment that floats on the target's workspace instead of a block.
738
+ * @param {Context} ctx
739
+ * @param {string} text
740
+ * @param {{width?: number, height?: number}} [size]
741
+ */
742
+ addWorkspaceComment(
743
+ ctx,
744
+ text,
745
+ { width = COMMENT_WIDTH, height = COMMENT_HEIGHT } = {},
746
+ ) {
747
+ const id = uid("c");
748
+ ctx.target.comments[id] = {
749
+ blockId: null,
750
+ x: null,
751
+ y: null,
752
+ width,
753
+ height,
754
+ minimized: false,
755
+ text,
756
+ };
757
+ }
758
+
759
+ /** Place standalone comments in the targets they were declared in. */
760
+ emitStandaloneComments(ast, contexts) {
761
+ const standalone = ast.standaloneComments || [];
762
+ if (standalone.length === 0) return;
763
+ // Sprite comments are routed by name; stage comments carry an explicit
764
+ // flag so a sprite named "Stage" cannot steal them.
765
+ const byName = new Map();
766
+ for (const ctx of contexts) {
767
+ if (!ctx.target.isStage) byName.set(ctx.target.name, ctx);
768
+ }
769
+ for (const comment of standalone) {
770
+ const ctx = comment.stage
771
+ ? this.stageCtx
772
+ : byName.get(comment.target) || this.stageCtx;
773
+ this.addWorkspaceComment(ctx, comment.text);
774
+ }
775
+ }
776
+
707
777
  // --------------------------------------------------------- block utils
708
778
 
709
779
  reparentInputs(ctx, parentId, inputs) {
@@ -750,7 +820,14 @@ export class Compiler {
750
820
  );
751
821
  }
752
822
  const id = this.compileStatement(ctx, statement);
753
- if (id == null) continue;
823
+ if (id == null) {
824
+ // A statement stripped in build mode (run-only block) still carries
825
+ // its notes: keep them on the workspace instead of dropping them.
826
+ if (statement.comments && statement.comments.length)
827
+ this.addWorkspaceComment(ctx, statement.comments.join("\n"));
828
+ continue;
829
+ }
830
+ this.attachNodeComments(ctx, statement, id);
754
831
  if (first == null) {
755
832
  first = id;
756
833
  ctx.target.blocks[id].parent = parentId;
@@ -1797,19 +1874,6 @@ export class Compiler {
1797
1874
  // broadcasts live on the stage
1798
1875
  for (const [name, id] of this.broadcasts) target.broadcasts[id] = name;
1799
1876
  this.ensureStageAssets(target);
1800
- const comment = configComment(this.projectConfig);
1801
- if (comment) {
1802
- const commentId = uid("c");
1803
- target.comments[commentId] = {
1804
- blockId: null,
1805
- x: 50,
1806
- y: 50,
1807
- width: 350,
1808
- height: 170,
1809
- minimized: false,
1810
- text: comment,
1811
- };
1812
- }
1813
1877
  } else {
1814
1878
  this.ensureSpriteAssets(target);
1815
1879
  }
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
+ }
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
  }
package/src/parser.js CHANGED
@@ -5,8 +5,9 @@
5
5
  * Triflare Fx is intentionally context-free: keywords are recognised by shape
6
6
  * (`sprite "..."`, `when <event>`, `let ...`) rather than being reserved words.
7
7
  */
8
- import { tokenize } from "./lexer.js";
8
+ import { tokenizeWithComments } from "./lexer.js";
9
9
  import { ParseError } from "./errors.js";
10
+ import { attachComments } from "./comments.js";
10
11
 
11
12
  const ASSIGN_OPS = new Set(["=", "+=", "-=", "*=", "/="]);
12
13
  const PROPERTY_KEYS = new Set(["layer", "costumes", "sounds"]);
@@ -22,6 +23,15 @@ class Parser {
22
23
  this.source = source;
23
24
  this.file = file;
24
25
  this.pos = 0;
26
+ // Brace tokens for every body, kept out of the AST so comments can be
27
+ // placed by source range without changing the node shapes.
28
+ this.spans = new WeakMap();
29
+ }
30
+
31
+ /** Record the braces surrounding a node's body (and else branch). */
32
+ span(node, bodyOpen, bodyClose, elseOpen = null, elseClose = null) {
33
+ this.spans.set(node, { bodyOpen, bodyClose, elseOpen, elseClose });
34
+ return node;
25
35
  }
26
36
 
27
37
  peek(offset = 0) {
@@ -136,8 +146,8 @@ class Parser {
136
146
  parseTestDecl() {
137
147
  const tok = this.expect("test");
138
148
  const name = this.expectType("string", "a test name string").value;
139
- const body = this.parseBlockBody();
140
- return { type: "TestDecl", name, body, loc: tok };
149
+ const { body, open, close } = this.parseBlockBody(true);
150
+ return this.span({ type: "TestDecl", name, body, loc: tok }, open, close);
141
151
  }
142
152
 
143
153
  /** `expect <expression>[, "message"];` */
@@ -154,23 +164,31 @@ class Parser {
154
164
  parseSprite(partial = false, startTok = null) {
155
165
  const tok = this.expect("sprite");
156
166
  const name = this.expectType("string", "a sprite name string").value;
157
- const { body, open } = this.parseBlockBody(true);
158
- return {
159
- type: "SpriteDecl",
160
- name,
161
- body,
162
- loc: startTok ?? tok,
163
- // Tokens are the brace's position, needed to insert declarations into
164
- // the body when the brace is not on the declaration line.
167
+ const { body, open, close } = this.parseBlockBody(true);
168
+ return this.span(
169
+ {
170
+ type: "SpriteDecl",
171
+ name,
172
+ body,
173
+ loc: startTok ?? tok,
174
+ // Tokens are the brace's position, needed to insert declarations into
175
+ // the body when the brace is not on the declaration line.
176
+ open,
177
+ partial,
178
+ },
165
179
  open,
166
- partial,
167
- };
180
+ close,
181
+ );
168
182
  }
169
183
 
170
184
  parseStage() {
171
185
  const tok = this.expect("stage");
172
- const { body, open } = this.parseBlockBody(true);
173
- return { type: "StageDecl", name: "Stage", body, loc: tok, open };
186
+ const { body, open, close } = this.parseBlockBody(true);
187
+ return this.span(
188
+ { type: "StageDecl", name: "Stage", body, loc: tok, open },
189
+ open,
190
+ close,
191
+ );
174
192
  }
175
193
 
176
194
  /**
@@ -185,8 +203,8 @@ class Parser {
185
203
  this.fail('Unterminated block; expected "}"');
186
204
  items.push(this.parseBodyItem());
187
205
  }
188
- this.expect("}");
189
- return withOpen ? { body: items, open } : items;
206
+ const close = this.expect("}");
207
+ return withOpen ? { body: items, open, close } : items;
190
208
  }
191
209
 
192
210
  parseBodyItem() {
@@ -345,23 +363,19 @@ class Parser {
345
363
  if (!this.eat(",")) break;
346
364
  }
347
365
  this.expect(")");
348
- const body = this.parseBlockBody();
349
- return {
350
- type: "FunctionDecl",
351
- name,
352
- params,
353
- returns,
354
- warp,
355
- body,
356
- loc: tok,
357
- };
366
+ const { body, open, close } = this.parseBlockBody(true);
367
+ return this.span(
368
+ { type: "FunctionDecl", name, params, returns, warp, body, loc: tok },
369
+ open,
370
+ close,
371
+ );
358
372
  }
359
373
 
360
374
  parseHat() {
361
375
  const tok = this.expect("when");
362
376
  const event = this.parseCallOrIdentifier();
363
- const body = this.parseBlockBody();
364
- return { type: "HatDecl", event, body, loc: tok };
377
+ const { body, open, close } = this.parseBlockBody(true);
378
+ return this.span({ type: "HatDecl", event, body, loc: tok }, open, close);
365
379
  }
366
380
 
367
381
  parseProperty() {
@@ -410,17 +424,29 @@ class Parser {
410
424
  } else {
411
425
  cond = this.parseExpression();
412
426
  }
413
- const then = this.parseBlockBody();
427
+ const then = this.parseBlockBody(true);
414
428
  let elseBody = null;
429
+ let elseOpen = null;
430
+ let elseClose = null;
415
431
  if (this.atIdent("else")) {
416
432
  this.next();
417
433
  if (this.atIdent("if")) {
418
434
  elseBody = [this.parseIf()];
419
435
  } else {
420
- elseBody = this.parseBlockBody();
436
+ ({
437
+ body: elseBody,
438
+ open: elseOpen,
439
+ close: elseClose,
440
+ } = this.parseBlockBody(true));
421
441
  }
422
442
  }
423
- return { type: "If", cond, then, else: elseBody, loc: tok };
443
+ return this.span(
444
+ { type: "If", cond, then: then.body, else: elseBody, loc: tok },
445
+ then.open,
446
+ then.close,
447
+ elseOpen,
448
+ elseClose,
449
+ );
424
450
  }
425
451
 
426
452
  parseRepeat() {
@@ -432,8 +458,8 @@ class Parser {
432
458
  } else {
433
459
  count = this.parseExpression();
434
460
  }
435
- const body = this.parseBlockBody();
436
- return { type: "Repeat", count, body, loc: tok };
461
+ const { body, open, close } = this.parseBlockBody(true);
462
+ return this.span({ type: "Repeat", count, body, loc: tok }, open, close);
437
463
  }
438
464
 
439
465
  parseWhile() {
@@ -445,14 +471,14 @@ class Parser {
445
471
  } else {
446
472
  cond = this.parseExpression();
447
473
  }
448
- const body = this.parseBlockBody();
449
- return { type: "While", cond, body, loc: tok };
474
+ const { body, open, close } = this.parseBlockBody(true);
475
+ return this.span({ type: "While", cond, body, loc: tok }, open, close);
450
476
  }
451
477
 
452
478
  parseForever() {
453
479
  const tok = this.expect("forever");
454
- const body = this.parseBlockBody();
455
- return { type: "Forever", body, loc: tok };
480
+ const { body, open, close } = this.parseBlockBody(true);
481
+ return this.span({ type: "Forever", body, loc: tok }, open, close);
456
482
  }
457
483
 
458
484
  parseReturn() {
@@ -486,27 +512,43 @@ class Parser {
486
512
  }
487
513
 
488
514
  let body = null;
515
+ let bodyOpen = null;
516
+ let bodyClose = null;
489
517
  let elseBody = null;
518
+ let elseOpen = null;
519
+ let elseClose = null;
490
520
  if (this.atPunct("{")) {
491
- body = this.parseBlockBody();
521
+ ({ body, open: bodyOpen, close: bodyClose } = this.parseBlockBody(true));
492
522
  if (this.atIdent("else")) {
493
523
  this.next();
494
524
  if (this.atIdent("if")) elseBody = [this.parseIf()];
495
- else elseBody = this.parseBlockBody();
525
+ else {
526
+ ({
527
+ body: elseBody,
528
+ open: elseOpen,
529
+ close: elseClose,
530
+ } = this.parseBlockBody(true));
531
+ }
496
532
  }
497
533
  this.eat(";");
498
534
  } else {
499
535
  this.expect(";");
500
536
  }
501
- return {
502
- type: "BlockCall",
503
- name: name.name,
504
- segments: name.segments,
505
- args,
506
- body,
507
- else: elseBody,
508
- loc: tok,
509
- };
537
+ return this.span(
538
+ {
539
+ type: "BlockCall",
540
+ name: name.name,
541
+ segments: name.segments,
542
+ args,
543
+ body,
544
+ else: elseBody,
545
+ loc: tok,
546
+ },
547
+ bodyOpen,
548
+ bodyClose,
549
+ elseOpen,
550
+ elseClose,
551
+ );
510
552
  }
511
553
 
512
554
  parseCallOrIdentifier() {
@@ -708,7 +750,11 @@ class Parser {
708
750
  * @param {string} [file]
709
751
  */
710
752
  export function parse(source, file = "<input>") {
711
- return parseTokens(tokenize(source, file), source, file);
753
+ const { tokens, comments } = tokenizeWithComments(source, file);
754
+ const parser = new Parser(tokens, source, file);
755
+ const ast = parser.parse();
756
+ attachComments(ast, comments, tokens, parser.spans);
757
+ return ast;
712
758
  }
713
759
 
714
760
  /**
@@ -2,5 +2,5 @@
2
2
  "name": "@penguinmod/packager",
3
3
  "version": "1.9.2",
4
4
  "commit": "53f868b85ec21d2edab9ce00fd2d709da93da6d6",
5
- "builtAt": "2026-11-25T03:05:53.327Z"
5
+ "builtAt": "2026-11-26T05:48:41.391Z"
6
6
  }
@@ -3,5 +3,5 @@
3
3
  "version": "0.2.0",
4
4
  "commit": "3822f284c8cda2c3a0a5c6dd928221dd9ff2cee1",
5
5
  "inputHash": "bb8f99fcce9f4ecdc563f11df5a0510dcc94c25d256c6931c7f1f113e0a1998b",
6
- "builtAt": "2026-11-25T03:06:40.888Z"
6
+ "builtAt": "2026-11-26T05:49:36.222Z"
7
7
  }