@kubohiroya/turbowarp-bubble 0.8.0 → 0.10.0

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.
@@ -31,7 +31,7 @@
31
31
  }) : target, mod));
32
32
  //#endregion
33
33
  //#region src/config.ts
34
- var extensionConfig = {
34
+ var extensionConfig$1 = {
35
35
  id: "kubohiroyabubble",
36
36
  slug: "turbowarp-bubble",
37
37
  name: "Bubble",
@@ -47,7 +47,7 @@
47
47
  "opcode": "defineBubbleStyle",
48
48
  "blockType": "COMMAND",
49
49
  "text": "define bubble style [STYLE] using text style [TEXT_STYLE]",
50
- "description": "Defines or replaces a bubble style and references a named SVG Text layout style.",
50
+ "description": "Defines or replaces a bubble style. The default text style without further settings uses the Scratch-compatible basic profile.",
51
51
  "arguments": {
52
52
  "STYLE": {
53
53
  "type": "STRING",
@@ -59,6 +59,31 @@
59
59
  }
60
60
  }
61
61
  },
62
+ {
63
+ "opcode": "defineBubbleClosePolicy",
64
+ "blockType": "COMMAND",
65
+ "text": "define bubble close policy [POLICY] trigger [TRIGGER] condition [CONDITION] timeout [TIMEOUT] seconds",
66
+ "description": "Defines or replaces a named close policy. The trigger explicitly selects a condition, a timeout, or whichever happens first.",
67
+ "arguments": {
68
+ "POLICY": {
69
+ "type": "STRING",
70
+ "defaultValue": "advance-or-timeout"
71
+ },
72
+ "TRIGGER": {
73
+ "type": "STRING",
74
+ "defaultValue": "condition-or-timeout",
75
+ "menu": "closePolicyTrigger"
76
+ },
77
+ "CONDITION": {
78
+ "type": "STRING",
79
+ "defaultValue": "input == \"pressed\""
80
+ },
81
+ "TIMEOUT": {
82
+ "type": "NUMBER",
83
+ "defaultValue": 10
84
+ }
85
+ }
86
+ },
62
87
  {
63
88
  "opcode": "setBubblePlacement",
64
89
  "blockType": "COMMAND",
@@ -145,7 +170,7 @@
145
170
  "opcode": "setBubbleVisualStyle",
146
171
  "blockType": "COMMAND",
147
172
  "text": "set bubble visual style [VISUAL_STYLE] for bubble style [STYLE]",
148
- "description": "Sets the SVG body shape used by this bubble style.",
173
+ "description": "Sets the inseparable SVG body and tail or trail shape pair used by this bubble style.",
149
174
  "arguments": {
150
175
  "VISUAL_STYLE": {
151
176
  "type": "STRING",
@@ -474,11 +499,48 @@
474
499
  }
475
500
  }
476
501
  },
502
+ {
503
+ "opcode": "say",
504
+ "blockType": "COMMAND",
505
+ "text": "say [MESSAGE]",
506
+ "description": "Shows or replaces this sprite's Scratch-compatible default say bubble. An empty message closes it.",
507
+ "arguments": { "MESSAGE": {
508
+ "type": "STRING",
509
+ "defaultValue": "Hello!"
510
+ } }
511
+ },
512
+ {
513
+ "opcode": "think",
514
+ "blockType": "COMMAND",
515
+ "text": "think [MESSAGE]",
516
+ "description": "Shows or replaces this sprite's Scratch-compatible default think bubble. An empty message closes it.",
517
+ "arguments": { "MESSAGE": {
518
+ "type": "STRING",
519
+ "defaultValue": "Hmm..."
520
+ } }
521
+ },
522
+ {
523
+ "opcode": "showWithBubbleStyle",
524
+ "blockType": "COMMAND",
525
+ "text": "show [MESSAGE] with bubble style [STYLE]",
526
+ "description": "Shows or replaces this sprite's Bubble. The selected style determines the complete body and tail or trail shape.",
527
+ "arguments": {
528
+ "MESSAGE": {
529
+ "type": "STRING",
530
+ "defaultValue": "Hello!"
531
+ },
532
+ "STYLE": {
533
+ "type": "STRING",
534
+ "defaultValue": "say"
535
+ }
536
+ }
537
+ },
477
538
  {
478
539
  "opcode": "sayWithBubbleStyle",
479
540
  "blockType": "COMMAND",
480
541
  "text": "say [MESSAGE] with bubble style [STYLE]",
481
- "description": "Shows or replaces this sprite's layered say bubble in talking animation mode.",
542
+ "description": "Shows or replaces this sprite's say bubble in talking animation mode. An empty message closes the basic profile.",
543
+ "hideFromPalette": true,
482
544
  "arguments": {
483
545
  "MESSAGE": {
484
546
  "type": "STRING",
@@ -494,7 +556,8 @@
494
556
  "opcode": "thinkWithBubbleStyle",
495
557
  "blockType": "COMMAND",
496
558
  "text": "think [MESSAGE] with bubble style [STYLE]",
497
- "description": "Shows or replaces this sprite's layered think bubble in talking animation mode.",
559
+ "description": "Shows or replaces this sprite's think bubble in talking animation mode. An empty message closes the basic profile.",
560
+ "hideFromPalette": true,
498
561
  "arguments": {
499
562
  "MESSAGE": {
500
563
  "type": "STRING",
@@ -533,6 +596,16 @@
533
596
  }
534
597
  }
535
598
  },
599
+ {
600
+ "opcode": "waitAndCloseBubbleWithPolicy",
601
+ "blockType": "COMMAND",
602
+ "text": "wait and close this bubble using close policy [POLICY]",
603
+ "description": "Snapshots the named close policy, waits for its trigger, then closes this sprite's bubble and releases its resources.",
604
+ "arguments": { "POLICY": {
605
+ "type": "STRING",
606
+ "defaultValue": "advance-or-timeout"
607
+ } }
608
+ },
536
609
  {
537
610
  "opcode": "closeBubble",
538
611
  "blockType": "COMMAND",
@@ -549,6 +622,14 @@
549
622
  }
550
623
  ],
551
624
  menus: {
625
+ "closePolicyTrigger": {
626
+ "acceptReporters": true,
627
+ "items": [
628
+ "condition",
629
+ "timeout",
630
+ "condition-or-timeout"
631
+ ]
632
+ },
552
633
  "portraitPlacement": {
553
634
  "acceptReporters": true,
554
635
  "items": [
@@ -6005,7 +6086,18 @@
6005
6086
  "NARRATION",
6006
6087
  "NO_BUBBLE"
6007
6088
  ]);
6008
- function escapeXml(value) {
6089
+ var cloudBodyMinimumSize = Object.freeze({
6090
+ height: 96,
6091
+ width: 176
6092
+ });
6093
+ var emptyBodyMinimumSize = Object.freeze({
6094
+ height: 0,
6095
+ width: 0
6096
+ });
6097
+ function bubbleBodyMinimumSize(...styles) {
6098
+ return styles.some((style) => style === "THINKING" || style === "DREAMING") ? cloudBodyMinimumSize : emptyBodyMinimumSize;
6099
+ }
6100
+ function escapeXml$2(value) {
6009
6101
  return value.replaceAll("&", "&amp;").replaceAll("<", "&lt;").replaceAll(">", "&gt;").replaceAll("\"", "&quot;").replaceAll("'", "&apos;");
6010
6102
  }
6011
6103
  function requireDimension(value, fallback) {
@@ -6196,22 +6288,56 @@
6196
6288
  if (!outer) throw new Error("JSClipper returned an empty Bubble outline.");
6197
6289
  return `<path d="${polygonPath(outer)}" fill="${fill}" stroke="${border}" stroke-width="3" stroke-linejoin="round" data-boolean-operation="union" data-tail-base-on-border="true" ${extra}/>`;
6198
6290
  }
6291
+ function smoothClosedPath(points) {
6292
+ const first = points[0];
6293
+ if (!first || points.length < 3) throw new TypeError("Smooth Bubble path requires at least three points.");
6294
+ const format = (value) => value.toFixed(4);
6295
+ const segments = points.map((current, index) => {
6296
+ const previous = points[(index - 1 + points.length) % points.length];
6297
+ const next = points[(index + 1) % points.length];
6298
+ const afterNext = points[(index + 2) % points.length];
6299
+ if (!previous || !next || !afterNext) throw new Error("Smooth Bubble path is invalid.");
6300
+ const firstControl = {
6301
+ x: current.x + (next.x - previous.x) / 6,
6302
+ y: current.y + (next.y - previous.y) / 6
6303
+ };
6304
+ const secondControl = {
6305
+ x: next.x - (afterNext.x - current.x) / 6,
6306
+ y: next.y - (afterNext.y - current.y) / 6
6307
+ };
6308
+ return `C ${format(firstControl.x)} ${format(firstControl.y)} ${format(secondControl.x)} ${format(secondControl.y)} ${format(next.x)} ${format(next.y)}`;
6309
+ });
6310
+ return `M ${format(first.x)} ${format(first.y)} ${segments.join(" ")} Z`;
6311
+ }
6199
6312
  function cloudBody(width, height, fill, border) {
6313
+ const x = 24;
6200
6314
  const y = 24;
6201
6315
  const right = width - 24;
6202
6316
  const bottom = height - 24;
6203
- const midX = width / 2;
6204
- const midY = height / 2;
6205
- return `<path d="M 42 ${midY}
6206
- C 22 ${midY - 20}, 32 42, 60 44
6207
- C 68 22, ${midX - 18} 19, ${midX} 37
6208
- C ${midX + 24} 16, ${right - 28} ${y}, ${right - 30} 48
6209
- C ${right + 2} 42, ${right + 7} ${midY - 3}, ${right - 3} ${midY + 15}
6210
- C ${right + 8} ${bottom - 10}, ${right - 20} ${bottom + 7}, ${right - 42} ${bottom - 7}
6211
- C ${right - 55} ${bottom + 12}, ${midX + 12} ${bottom + 7}, ${midX} ${bottom - 7}
6212
- C ${midX - 24} ${bottom + 12}, 66 ${bottom + 7}, 62 ${bottom - 12}
6213
- C 31 ${bottom + 2}, 17 ${midY + 20}, 42 ${midY} Z"
6214
- fill="${fill}" stroke="${border}" stroke-width="3" stroke-linejoin="round"/>`;
6317
+ const bodyWidth = right - x;
6318
+ const bodyHeight = bottom - y;
6319
+ const point = (xRatio, yRatio) => ({
6320
+ x: x + bodyWidth * xRatio,
6321
+ y: y + bodyHeight * yRatio
6322
+ });
6323
+ return `<path d="${smoothClosedPath([
6324
+ point(0, .5),
6325
+ point(.03, .3),
6326
+ point(.18, .2),
6327
+ point(.28, .04),
6328
+ point(.5, .16),
6329
+ point(.68, .03),
6330
+ point(.84, .18),
6331
+ point(.98, .3),
6332
+ point(1, .52),
6333
+ point(.95, .7),
6334
+ point(.82, .82),
6335
+ point(.68, .97),
6336
+ point(.5, .84),
6337
+ point(.32, .97),
6338
+ point(.18, .82),
6339
+ point(.03, .7)
6340
+ ])}" fill="${fill}" stroke="${border}" stroke-width="3" stroke-linejoin="round"/>`;
6215
6341
  }
6216
6342
  function thoughtTrail(body, bodyCenter, tip, fill, border, dreaming) {
6217
6343
  const tipVector = subtract(tip, bodyCenter);
@@ -6306,8 +6432,9 @@
6306
6432
  return roundedRectanglePoints(width, height);
6307
6433
  }
6308
6434
  function bubbleBodyCenterOffset(input) {
6309
- const width = requireDimension(input.width, 220);
6310
- const height = requireDimension(input.height, 112);
6435
+ const minimumSize = bubbleBodyMinimumSize(input.style);
6436
+ const width = Math.max(requireDimension(input.width, 220), minimumSize.width);
6437
+ const height = Math.max(requireDimension(input.height, 112), minimumSize.height);
6311
6438
  const direction = normalizeDirection(input.tailDirection);
6312
6439
  if (direction === null) throw new TypeError("Bubble body center offset requires a tail direction.");
6313
6440
  const tailLength = normalizeSvgTailLength(input.tailLength ?? svgDefaultTailLength);
@@ -6364,8 +6491,8 @@
6364
6491
  function renderBubbleSvg(input) {
6365
6492
  if (!bubbleVisualStyles.includes(input.style)) throw new TypeError(`Unsupported Bubble visual style: ${String(input.style)}`);
6366
6493
  if (!Array.isArray(input.lines) || input.lines.some((line) => typeof line !== "string")) throw new TypeError("lines must be an array of strings.");
6367
- const width = requireDimension(input.width, 220);
6368
- const height = requireDimension(input.height, 112);
6494
+ const requestedWidth = requireDimension(input.width, 220);
6495
+ const requestedHeight = requireDimension(input.height, 112);
6369
6496
  const fontSize = requireDimension(input.fontSize, 15);
6370
6497
  const direction = normalizeDirection(input.tailDirection);
6371
6498
  const tailLength = normalizeSvgTailLength(input.tailLength ?? svgDefaultTailLength);
@@ -6374,6 +6501,9 @@
6374
6501
  if (shapeTransition !== void 0) {
6375
6502
  if (!bubbleVisualStyles.includes(shapeTransition.from) || !bubbleVisualStyles.includes(shapeTransition.to) || !Number.isFinite(shapeTransition.progress) || shapeTransition.progress < 0 || shapeTransition.progress > 1) throw new TypeError("Bubble shape transition is invalid.");
6376
6503
  }
6504
+ const minimumSize = bubbleBodyMinimumSize(input.style, ...shapeTransition === void 0 ? [] : [shapeTransition.from, shapeTransition.to]);
6505
+ const width = Math.max(requestedWidth, minimumSize.width);
6506
+ const height = Math.max(requestedHeight, minimumSize.height);
6377
6507
  const fill = input.fillColor ?? "#fff4cc";
6378
6508
  const border = input.borderColor ?? "#6f5b45";
6379
6509
  const textColor = input.textColor ?? "#25283a";
@@ -6385,11 +6515,11 @@
6385
6515
  x: width / 2,
6386
6516
  y: height / 2
6387
6517
  } : transformedBodyGeometry(roundedRectanglePoints(width, height), width, height, direction, tailLength, offset).bodyCenter;
6388
- const text = input.lines.map((line, index) => `<text x="${textCenter.x}" y="${textCenter.y + (firstBaseline + index * lineHeight - height / 2) * textScale}" text-anchor="middle" fill="${escapeXml(textColor)}" font-family="${escapeXml(fontFamily)}" font-size="${fontSize * textScale}">${escapeXml(line)}</text>`).join("");
6518
+ const text = input.lines.map((line, index) => `<text x="${textCenter.x}" y="${textCenter.y + (firstBaseline + index * lineHeight - height / 2) * textScale}" text-anchor="middle" fill="${escapeXml$2(textColor)}" font-family="${escapeXml$2(fontFamily)}" font-size="${fontSize * textScale}">${escapeXml$2(line)}</text>`).join("");
6389
6519
  const body = shapeTransition === void 0 ? renderBody(input.style, width, height, direction, fill, border, tailLength, offset) : `<g opacity="${(1 - shapeTransition.progress).toFixed(4)}">${renderBody(shapeTransition.from, width, height, direction, fill, border, tailLength, offset)}</g><g opacity="${shapeTransition.progress.toFixed(4)}">${renderBody(shapeTransition.to, width, height, direction, fill, border, tailLength, offset)}</g>`;
6390
- const title = escapeXml(input.title ?? `${input.style} bubble`);
6520
+ const title = escapeXml$2(input.title ?? `${input.style} bubble`);
6391
6521
  const transitionAttributes = shapeTransition === void 0 ? "" : ` data-bubble-shape-transition-from="${shapeTransition.from}" data-bubble-shape-transition-to="${shapeTransition.to}" data-bubble-shape-transition-progress="${shapeTransition.progress.toFixed(4)}"`;
6392
- return `<svg xmlns="http://www.w3.org/2000/svg" width="${width}" height="${height}" viewBox="0 0 ${width} ${height}" role="img" data-bubble-renderer="canonical" data-bubble-style="${input.style}"${transitionAttributes}><title>${title}</title>${body}${text}</svg>`;
6522
+ return `<svg xmlns="http://www.w3.org/2000/svg" width="${width}" height="${height}" viewBox="0 0 ${width} ${height}" role="img" data-bubble-renderer="canonical" data-bubble-style="${input.style}" data-bubble-body-width="${width}" data-bubble-body-height="${height}"${transitionAttributes}><title>${title}</title>${body}${text}</svg>`;
6393
6523
  }
6394
6524
  //#endregion
6395
6525
  //#region node_modules/.pnpm/@cto.af+unicode-trie-runtime@3.2.9/node_modules/@cto.af/unicode-trie-runtime/constants.js
@@ -8480,6 +8610,144 @@
8480
8610
  if (typeof value !== "number" || !Number.isFinite(value) || value < 0) throw new TypeError("Bubble portrait corner radius must be zero or greater.");
8481
8611
  return value;
8482
8612
  }
8613
+ var scratchDefaultOptionalStyleKeys = Object.freeze([
8614
+ "placement",
8615
+ "maxWidth",
8616
+ "textLocale",
8617
+ "distance",
8618
+ "tailLength",
8619
+ "offset",
8620
+ "visualStyle",
8621
+ "portrait",
8622
+ "continueIndicator",
8623
+ "reveal",
8624
+ "audio",
8625
+ "showAnimation",
8626
+ "hideAnimation"
8627
+ ]);
8628
+ function isRecord$6(value) {
8629
+ return typeof value === "object" && value !== null && !Array.isArray(value);
8630
+ }
8631
+ /**
8632
+ * The block-level basic style is intentionally narrow. Any explicit layout,
8633
+ * body, media, reveal, or motion option selects the existing custom renderer.
8634
+ */
8635
+ function bubbleLayoutProfileForStyleInput(value) {
8636
+ if (!isRecord$6(value)) return "custom";
8637
+ if (typeof value.textStyle !== "string" || value.textStyle.trim() !== "default") return "custom";
8638
+ return scratchDefaultOptionalStyleKeys.every((key) => value[key] === void 0) ? "scratch-default" : "custom";
8639
+ }
8640
+ function isScratchDefaultBubbleStyleInput(value) {
8641
+ return bubbleLayoutProfileForStyleInput(value) === "scratch-default";
8642
+ }
8643
+ /** Matches the numeric presentation and length limit used by say/think. */
8644
+ function formatScratchBubbleArgument(value) {
8645
+ let formatted = value;
8646
+ if (typeof value === "number" && Math.abs(value) >= .01 && value % 1 !== 0) formatted = value.toFixed(2);
8647
+ return String(formatted).slice(0, 330);
8648
+ }
8649
+ function estimatedHelveticaWidth(text) {
8650
+ let units = 0;
8651
+ for (const character of text) {
8652
+ if (/\p{Mark}/u.test(character)) continue;
8653
+ if (/\s/u.test(character)) {
8654
+ units += .35;
8655
+ continue;
8656
+ }
8657
+ units += (character.codePointAt(0) ?? 0) <= 127 ? .62 : 1;
8658
+ }
8659
+ return units * 14;
8660
+ }
8661
+ function layoutScratchBubbleText(value, measureText = estimatedHelveticaWidth) {
8662
+ const text = value.slice(0, 330);
8663
+ const measured = (candidate) => {
8664
+ let width;
8665
+ try {
8666
+ width = measureText(candidate);
8667
+ } catch {
8668
+ return estimatedHelveticaWidth(candidate);
8669
+ }
8670
+ return Number.isFinite(width) && width >= 0 ? width : estimatedHelveticaWidth(candidate);
8671
+ };
8672
+ const wrapped = wrapText({
8673
+ text,
8674
+ maxWidth: 170,
8675
+ measureText: measured
8676
+ });
8677
+ const lines = Object.freeze(wrapped.lines.map((line) => Object.freeze({
8678
+ text: line.text,
8679
+ width: line.width
8680
+ })));
8681
+ return Object.freeze({
8682
+ lines,
8683
+ maxLineWidth: Math.max(0, ...lines.map((line) => line.width)),
8684
+ text: lines.map((line) => line.text).join("\n")
8685
+ });
8686
+ }
8687
+ function scratchBubbleMetrics(layout) {
8688
+ const lineCount = Math.max(1, layout.lines.length);
8689
+ const paddedWidth = Math.max(layout.maxLineWidth, 50) + 20;
8690
+ const paddedHeight = 16 * lineCount + 20;
8691
+ return Object.freeze({
8692
+ bodyHeight: paddedHeight + 4,
8693
+ bodyWidth: paddedWidth + 4,
8694
+ height: paddedHeight + 4 + 12,
8695
+ paddedHeight,
8696
+ paddedWidth,
8697
+ width: paddedWidth + 4
8698
+ });
8699
+ }
8700
+ function positionScratchBubble(input) {
8701
+ const stageLeft = -input.stageWidth / 2;
8702
+ const stageRight = input.stageWidth / 2;
8703
+ const stageTop = input.stageHeight / 2;
8704
+ let pointsLeft = input.pointsLeft;
8705
+ if (!pointsLeft && input.width + input.bounds.right > stageRight && input.bounds.left - input.width > stageLeft) pointsLeft = true;
8706
+ else if (pointsLeft && input.bounds.left - input.width < stageLeft && input.width + input.bounds.right < stageRight) pointsLeft = false;
8707
+ const left = pointsLeft ? Math.min(stageRight - input.width, Math.max(stageLeft, input.bounds.left - input.width)) : Math.max(stageLeft, Math.min(stageRight - input.width, input.bounds.right));
8708
+ const top = Math.min(stageTop, input.bounds.bottom + input.height);
8709
+ return Object.freeze({
8710
+ centerX: left + input.width / 2,
8711
+ centerY: top - input.height / 2,
8712
+ left,
8713
+ pointsLeft,
8714
+ top
8715
+ });
8716
+ }
8717
+ function escapeXml$1(value) {
8718
+ return value.replaceAll("&", "&amp;").replaceAll("<", "&lt;").replaceAll(">", "&gt;").replaceAll("\"", "&quot;").replaceAll("'", "&apos;");
8719
+ }
8720
+ function scratchBodyPath(metrics) {
8721
+ const { paddedHeight: height, paddedWidth: width } = metrics;
8722
+ const radius = Math.min(16, width / 2, height / 2);
8723
+ return [
8724
+ `M ${radius} ${height}`,
8725
+ `Q 0 ${height} 0 ${height - radius}`,
8726
+ `L 0 ${radius}`,
8727
+ `Q 0 0 ${radius} 0`,
8728
+ `L ${width - radius} 0`,
8729
+ `Q ${width} 0 ${width} ${radius}`,
8730
+ `L ${width} ${height - radius}`,
8731
+ `Q ${width} ${height} ${width - radius} ${height}`
8732
+ ].join(" ");
8733
+ }
8734
+ function scratchSayBody(metrics) {
8735
+ const { paddedHeight: height, paddedWidth: width } = metrics;
8736
+ return `<path d="${`${scratchBodyPath(metrics)} C ${width - 16} ${height + 4} ${width - 12} ${height + 8} ${width - 12} ${height + 10} Q ${width - 12} ${height + 12} ${width - 14} ${height + 12} C ${width - 17} ${height + 12} ${width - 27} ${height + 8} ${width - 32} ${height} Z`}" fill="white" stroke="rgba(0, 0, 0, 0.15)" stroke-width="4" stroke-linejoin="round" paint-order="stroke fill"/>`;
8737
+ }
8738
+ function scratchThinkBody(metrics) {
8739
+ const { paddedHeight: height, paddedWidth: width } = metrics;
8740
+ return `<path d="${`${scratchBodyPath(metrics)} L ${width - 28} ${height} A 4 4 0 0 1 ${width - 36} ${height} Z`}" fill="white" stroke="rgba(0, 0, 0, 0.15)" stroke-width="4" stroke-linejoin="round" paint-order="stroke fill"/><circle cx="${width - 25.25}" cy="${height + 7.25}" r="2.25" fill="white" stroke="rgba(0, 0, 0, 0.15)" stroke-width="4" paint-order="stroke fill"/><circle cx="${width - 17.5}" cy="${height + 9.5}" r="1.5" fill="white" stroke="rgba(0, 0, 0, 0.15)" stroke-width="4" paint-order="stroke fill"/>`;
8741
+ }
8742
+ function renderScratchBubbleSvg(input) {
8743
+ const metrics = scratchBubbleMetrics(input.layout);
8744
+ const body = input.kind === "say" ? scratchSayBody(metrics) : scratchThinkBody(metrics);
8745
+ const bodyTransform = input.pointsLeft ? `translate(2 2)` : `translate(${metrics.width} 0) scale(-1 1) translate(2 2)`;
8746
+ const firstBaseline = 24.6;
8747
+ const text = input.layout.lines.map((line, index) => `<text x="12" y="${firstBaseline + 16 * index}" fill="#575E75" font-family="Helvetica, sans-serif" font-size="14" xml:space="preserve">${escapeXml$1(line.text)}</text>`).join("");
8748
+ const title = escapeXml$1(input.title ?? `${input.kind} bubble`);
8749
+ return `<svg xmlns="http://www.w3.org/2000/svg" width="${metrics.width}" height="${metrics.height}" viewBox="0 0 ${metrics.width} ${metrics.height}" role="img" data-bubble-profile="scratch-default" data-bubble-kind="${input.kind}"><title>${title}</title><g transform="${bodyTransform}">${body}</g>${text}</svg>`;
8750
+ }
8483
8751
  //#endregion
8484
8752
  //#region src/composition.ts
8485
8753
  var BubbleCompositionError = class extends Error {
@@ -8515,7 +8783,7 @@
8515
8783
  "easeOut",
8516
8784
  "easeInOut"
8517
8785
  ]);
8518
- function isRecord$4(value) {
8786
+ function isRecord$5(value) {
8519
8787
  return typeof value === "object" && value !== null && !Array.isArray(value);
8520
8788
  }
8521
8789
  function requireExactKeys$1(value, required, optional, label) {
@@ -8533,7 +8801,7 @@
8533
8801
  return value;
8534
8802
  }
8535
8803
  function normalizeAnimation(value, label, minimumFrames) {
8536
- if (!isRecord$4(value)) throw new BubbleCompositionError("BUBBLE-COMPOSITION-001", `${label} must be an object.`);
8804
+ if (!isRecord$5(value)) throw new BubbleCompositionError("BUBBLE-COMPOSITION-001", `${label} must be an object.`);
8537
8805
  requireExactKeys$1(value, ["frames", "frameIntervalSeconds"], [], label);
8538
8806
  if (!Array.isArray(value.frames) || value.frames.length < minimumFrames) throw new BubbleCompositionError("BUBBLE-COMPOSITION-001", `${label}.frames must contain at least ${minimumFrames} image asset name${minimumFrames === 1 ? "" : "s"}.`);
8539
8807
  const frames = Object.freeze(value.frames.map((frame, index) => requireAssetName(frame, `${label}.frames[${index}]`)));
@@ -8545,7 +8813,7 @@
8545
8813
  });
8546
8814
  }
8547
8815
  function normalizePortrait(value) {
8548
- if (!isRecord$4(value)) throw new BubbleCompositionError("BUBBLE-COMPOSITION-001", "Bubble portrait must be an object.");
8816
+ if (!isRecord$5(value)) throw new BubbleCompositionError("BUBBLE-COMPOSITION-001", "Bubble portrait must be an object.");
8549
8817
  requireExactKeys$1(value, ["base"], [
8550
8818
  "blink",
8551
8819
  "lipSync",
@@ -8575,7 +8843,7 @@
8575
8843
  });
8576
8844
  }
8577
8845
  function normalizeMotion(value, label) {
8578
- if (!isRecord$4(value)) throw new BubbleCompositionError("BUBBLE-COMPOSITION-001", `${label} must be an object.`);
8846
+ if (!isRecord$5(value)) throw new BubbleCompositionError("BUBBLE-COMPOSITION-001", `${label} must be an object.`);
8579
8847
  requireExactKeys$1(value, ["name"], [
8580
8848
  "durationSeconds",
8581
8849
  "ease",
@@ -8615,7 +8883,7 @@
8615
8883
  }
8616
8884
  function normalizeAudio(value) {
8617
8885
  if (value === void 0) return void 0;
8618
- if (!isRecord$4(value)) throw new BubbleCompositionError("BUBBLE-COMPOSITION-001", "Bubble audio must be an object.");
8886
+ if (!isRecord$5(value)) throw new BubbleCompositionError("BUBBLE-COMPOSITION-001", "Bubble audio must be an object.");
8619
8887
  requireExactKeys$1(value, [], [
8620
8888
  "voice",
8621
8889
  "reveal",
@@ -8633,7 +8901,7 @@
8633
8901
  return Object.freeze(result);
8634
8902
  }
8635
8903
  function normalizeStyle(value) {
8636
- if (!isRecord$4(value)) throw new BubbleCompositionError("BUBBLE-COMPOSITION-001", "Bubble style must be an object.");
8904
+ if (!isRecord$5(value)) throw new BubbleCompositionError("BUBBLE-COMPOSITION-001", "Bubble style must be an object.");
8637
8905
  requireExactKeys$1(value, ["name", "textStyle"], [
8638
8906
  "placement",
8639
8907
  "maxWidth",
@@ -8684,9 +8952,11 @@
8684
8952
  maxWidth = value.maxWidth;
8685
8953
  }
8686
8954
  const textLocale = value.textLocale === void 0 ? void 0 : requireName$1(value.textLocale, "Bubble style text locale");
8955
+ const layoutProfile = bubbleLayoutProfileForStyleInput(value);
8687
8956
  return Object.freeze({
8688
8957
  name: requireName$1(value.name, "Bubble style name"),
8689
8958
  textStyle: requireName$1(value.textStyle, "Bubble text style name"),
8959
+ layoutProfile,
8690
8960
  ...maxWidth === void 0 ? {} : { maxWidth },
8691
8961
  ...textLocale === void 0 ? {} : { textLocale },
8692
8962
  placement,
@@ -8704,12 +8974,12 @@
8704
8974
  }
8705
8975
  function validateImageResolver(value) {
8706
8976
  if (value === void 0) return void 0;
8707
- if (!isRecord$4(value) || typeof value.applyToTarget !== "function" || typeof value.getMimeType !== "function" || typeof value.isRegistered !== "function") throw new TypeError("Bubble image capability must provide applyToTarget, getMimeType, and isRegistered.");
8977
+ if (!isRecord$5(value) || typeof value.applyToTarget !== "function" || typeof value.getMimeType !== "function" || typeof value.isRegistered !== "function") throw new TypeError("Bubble image capability must provide applyToTarget, getMimeType, and isRegistered.");
8708
8978
  return value;
8709
8979
  }
8710
8980
  function validateAudioCapability(value) {
8711
8981
  if (value === void 0) return void 0;
8712
- if (!isRecord$4(value) || typeof value.playSound !== "function") throw new TypeError("Bubble audio capability must provide playSound.");
8982
+ if (!isRecord$5(value) || typeof value.playSound !== "function") throw new TypeError("Bubble audio capability must provide playSound.");
8713
8983
  if (value.isRegistered !== void 0 && typeof value.isRegistered !== "function") throw new TypeError("Bubble audio capability isRegistered must be a function.");
8714
8984
  if (value.getMimeType !== void 0 && typeof value.getMimeType !== "function") throw new TypeError("Bubble audio capability getMimeType must be a function.");
8715
8985
  return value;
@@ -8719,7 +8989,7 @@
8719
8989
  return value;
8720
8990
  }
8721
8991
  function validateTextCapability(value) {
8722
- if (!isRecord$4(value) || typeof value.setText !== "function" || typeof value.releaseTarget !== "function") throw new TypeError("Bubble text capability must provide setText and releaseTarget.");
8992
+ if (!isRecord$5(value) || typeof value.setText !== "function" || typeof value.releaseTarget !== "function") throw new TypeError("Bubble text capability must provide setText and releaseTarget.");
8723
8993
  return value;
8724
8994
  }
8725
8995
  function defaultScheduler() {
@@ -8729,11 +8999,11 @@
8729
8999
  });
8730
9000
  }
8731
9001
  function validateScheduler(value) {
8732
- if (!isRecord$4(value) || typeof value.setTimeout !== "function" || typeof value.clearTimeout !== "function") throw new TypeError("Bubble scheduler must provide setTimeout and clearTimeout.");
9002
+ if (!isRecord$5(value) || typeof value.setTimeout !== "function" || typeof value.clearTimeout !== "function") throw new TypeError("Bubble scheduler must provide setTimeout and clearTimeout.");
8733
9003
  return value;
8734
9004
  }
8735
9005
  function validateAssetTarget(value, label) {
8736
- if (!isRecord$4(value) || typeof value.id !== "string" || value.id.length === 0 || typeof value.isStage !== "boolean") throw new BubbleCompositionError("BUBBLE-COMPOSITION-004", `${label} must provide id and isStage.`);
9006
+ if (!isRecord$5(value) || typeof value.id !== "string" || value.id.length === 0 || typeof value.isStage !== "boolean") throw new BubbleCompositionError("BUBBLE-COMPOSITION-004", `${label} must provide id and isStage.`);
8737
9007
  return value;
8738
9008
  }
8739
9009
  function validateTextTarget(value) {
@@ -8741,7 +9011,7 @@
8741
9011
  return value;
8742
9012
  }
8743
9013
  function validateSurface(value, style) {
8744
- if (!isRecord$4(value) || !isRecord$4(value.targets) || typeof value.setLayerVisible !== "function" || typeof value.updateStyle !== "function" || typeof value.show !== "function" || typeof value.hide !== "function" || typeof value.dispose !== "function") throw new BubbleCompositionError("BUBBLE-COMPOSITION-004", "Bubble surface is invalid.");
9014
+ if (!isRecord$5(value) || !isRecord$5(value.targets) || typeof value.setLayerVisible !== "function" || typeof value.updateStyle !== "function" || typeof value.show !== "function" || typeof value.hide !== "function" || typeof value.dispose !== "function") throw new BubbleCompositionError("BUBBLE-COMPOSITION-004", "Bubble surface is invalid.");
8745
9015
  const targets = value.targets;
8746
9016
  validateTextTarget(targets.text);
8747
9017
  const assetTargetIds = /* @__PURE__ */ new Set();
@@ -8777,6 +9047,10 @@
8777
9047
  ], ...style.continueIndicator?.frames ?? []];
8778
9048
  }
8779
9049
  function formatBubbleText(text, style, textCapability) {
9050
+ if (style.layoutProfile === "scratch-default") return layoutScratchBubbleText(text, (candidate) => typeof textCapability.measureText === "function" ? textCapability.measureText({
9051
+ styleName: style.textStyle,
9052
+ text: candidate
9053
+ }) : NaN).text;
8780
9054
  if (style.maxWidth === void 0) return text;
8781
9055
  if (typeof textCapability.measureText !== "function") throw new BubbleCompositionError("BUBBLE-COMPOSITION-007", "Bubble style maxWidth requires the text capability measureText method.");
8782
9056
  return wrapText({
@@ -8852,7 +9126,7 @@
8852
9126
  });
8853
9127
  }
8854
9128
  function normalizeShowInput(value) {
8855
- if (!isRecord$4(value)) throw new BubbleCompositionError("BUBBLE-COMPOSITION-001", "Show bubble input must be an object.");
9129
+ if (!isRecord$5(value)) throw new BubbleCompositionError("BUBBLE-COMPOSITION-001", "Show bubble input must be an object.");
8856
9130
  requireExactKeys$1(value, [
8857
9131
  "actor",
8858
9132
  "actorKey",
@@ -8881,7 +9155,7 @@
8881
9155
  };
8882
9156
  }
8883
9157
  function createBubbleComposition(options) {
8884
- if (!isRecord$4(options)) throw new TypeError("Bubble composition options must be an object.");
9158
+ if (!isRecord$5(options)) throw new TypeError("Bubble composition options must be an object.");
8885
9159
  const imageResolver = validateImageResolver(options.imageResolver);
8886
9160
  const audio = validateAudioCapability(options.audio);
8887
9161
  const textCapability = validateTextCapability(options.textCapability);
@@ -8911,6 +9185,7 @@
8911
9185
  let activeStyle = style;
8912
9186
  if (input.reveal !== void 0) activeStyle = Object.freeze({
8913
9187
  ...style,
9188
+ layoutProfile: "custom",
8914
9189
  reveal: input.reveal
8915
9190
  });
8916
9191
  let currentText = input.text;
@@ -8998,21 +9273,34 @@
8998
9273
  kind: input.kind,
8999
9274
  style: activeStyle
9000
9275
  })), activeStyle);
9001
- const fullText = formatBubbleText(input.text, activeStyle, textCapability);
9276
+ const applySurfaceText = async (rawText, nextStyle = activeStyle) => {
9277
+ if (nextStyle.layoutProfile === "scratch-default" && surface?.renderScratchText) {
9278
+ const layout = layoutScratchBubbleText(rawText, (candidate) => typeof textCapability.measureText === "function" ? textCapability.measureText({
9279
+ styleName: nextStyle.textStyle,
9280
+ text: candidate
9281
+ }) : NaN);
9282
+ await surface.renderScratchText(layout);
9283
+ return;
9284
+ }
9285
+ if (!surface) return;
9286
+ textCapability.setText({
9287
+ styleName: nextStyle.textStyle,
9288
+ target: surface.targets.text,
9289
+ text: formatBubbleText(rawText, nextStyle, textCapability)
9290
+ });
9291
+ textOwned = true;
9292
+ };
9002
9293
  if (reveal?.layout === "RESERVED") {
9294
+ const fullText = formatBubbleText(input.text, activeStyle, textCapability);
9003
9295
  textCapability.setText({
9004
9296
  styleName: activeStyle.textStyle,
9005
9297
  target: surface.targets.text,
9006
9298
  text: fullText
9007
9299
  });
9300
+ textOwned = true;
9008
9301
  surface.captureTextLayout?.();
9009
9302
  }
9010
- textCapability.setText({
9011
- styleName: activeStyle.textStyle,
9012
- target: surface.targets.text,
9013
- text: formatBubbleText(reveal ? revealedBubbleText(revealChunks, revealedCount) : input.text, activeStyle, textCapability)
9014
- });
9015
- textOwned = true;
9303
+ await applySurfaceText(reveal ? revealedBubbleText(revealChunks, revealedCount) : input.text);
9016
9304
  await primeStyleImages(activeStyle, styleImageResolver, surface);
9017
9305
  createStyleLoops(activeStyle, styleImageResolver, surface);
9018
9306
  let currentAnimationMode = "idle";
@@ -9021,11 +9309,7 @@
9021
9309
  const renderVisibleText = async () => {
9022
9310
  if (!surface) return;
9023
9311
  const visible = reveal ? revealedBubbleText(revealChunks, revealedCount) : currentText;
9024
- textCapability.setText({
9025
- styleName: activeStyle.textStyle,
9026
- target: surface.targets.text,
9027
- text: formatBubbleText(visible, activeStyle, textCapability)
9028
- });
9312
+ await applySurfaceText(visible);
9029
9313
  await surface.show();
9030
9314
  };
9031
9315
  const stopRevealTimer = () => {
@@ -9102,6 +9386,7 @@
9102
9386
  target: surface.targets.text,
9103
9387
  text: formatBubbleText(text, activeStyle, textCapability)
9104
9388
  });
9389
+ textOwned = true;
9105
9390
  surface.captureTextLayout?.();
9106
9391
  }
9107
9392
  await renderVisibleText();
@@ -9146,13 +9431,10 @@
9146
9431
  target: surface.targets.text,
9147
9432
  text: formatBubbleText(currentText, nextStyle, textCapability)
9148
9433
  });
9434
+ textOwned = true;
9149
9435
  surface.captureTextLayout?.();
9150
9436
  }
9151
- textCapability.setText({
9152
- styleName: nextStyle.textStyle,
9153
- target: surface.targets.text,
9154
- text: formatBubbleText(currentText, nextStyle, textCapability)
9155
- });
9437
+ await applySurfaceText(currentText, nextStyle);
9156
9438
  createStyleLoops(nextStyle, nextImageResolver, surface);
9157
9439
  await Promise.all([
9158
9440
  surface.setLayerVisible("portraitBase", nextStyle.portrait !== void 0),
@@ -9214,6 +9496,7 @@
9214
9496
  target: surface.targets.text,
9215
9497
  text: formatBubbleText(currentText, activeStyle, textCapability)
9216
9498
  });
9499
+ textOwned = true;
9217
9500
  surface.captureTextLayout?.();
9218
9501
  }
9219
9502
  }
@@ -9276,10 +9559,19 @@
9276
9559
  }
9277
9560
  transitionTail = transitionTail.then(async () => {
9278
9561
  if (normalized.name === "animateBubbleShape" && normalized.visualStyle) {
9279
- const nextStyle = Object.freeze({
9562
+ const transitionStyle = Object.freeze({
9280
9563
  ...activeStyle,
9564
+ layoutProfile: "custom"
9565
+ });
9566
+ const nextStyle = Object.freeze({
9567
+ ...transitionStyle,
9281
9568
  visualStyle: normalized.visualStyle
9282
9569
  });
9570
+ if (activeStyle.layoutProfile === "scratch-default") {
9571
+ await surface?.updateStyle(transitionStyle);
9572
+ await applySurfaceText(currentText, transitionStyle);
9573
+ await surface?.show();
9574
+ }
9283
9575
  await surface?.animate?.(normalized);
9284
9576
  activeStyle = nextStyle;
9285
9577
  await surface?.updateStyle(activeStyle);
@@ -9389,7 +9681,7 @@
9389
9681
  });
9390
9682
  }
9391
9683
  //#endregion
9392
- //#region node_modules/.pnpm/@kubohiroya+turbowarp-svg-text@0.8.0/node_modules/@kubohiroya/turbowarp-svg-text/dist/composition.js
9684
+ //#region node_modules/.pnpm/@kubohiroya+turbowarp-svg-text@0.8.1/node_modules/@kubohiroya/turbowarp-svg-text/dist/composition.js
9393
9685
  var block_definitions_default = {
9394
9686
  extensionName: "SVG Text",
9395
9687
  blocks: [{
@@ -9449,6 +9741,15 @@
9449
9741
  ]
9450
9742
  } }
9451
9743
  };
9744
+ var extensionConfig = {
9745
+ id: "kubohiroyasvgtext",
9746
+ slug: "svg-text",
9747
+ name: "SVG Text",
9748
+ description: "Responsive named-style SVG text actors for TurboWarp.",
9749
+ author: "Hiroya Kubo",
9750
+ license: "MPL-2.0",
9751
+ unsandboxed: true
9752
+ };
9452
9753
  var baseStageWidth = 480;
9453
9754
  var baseStageHeight = 360;
9454
9755
  var defaultFontPercent$1 = 100;
@@ -9657,6 +9958,21 @@
9657
9958
  width
9658
9959
  });
9659
9960
  }
9961
+ function renderSvgTextLayout(layout) {
9962
+ const textAnchor = layout.style.alignment === "center" ? "middle" : layout.style.alignment === "right" ? "end" : "start";
9963
+ const text = layout.lines.map((line) => line.text).join("\n");
9964
+ const tspans = layout.lines.map((line) => `<tspan x="${formatSvgNumber(line.x)}" y="${formatSvgNumber(line.baseline)}">${escapeXml(line.text)}</tspan>`).join("");
9965
+ const whitespaceAttribute = layout.preserveWhitespace ? " xml:space=\"preserve\"" : "";
9966
+ return `<svg xmlns="http://www.w3.org/2000/svg" width="${layout.width}" height="${layout.height}" viewBox="0 0 ${layout.width} ${layout.height}" role="img"><title>${escapeXml(text)}</title><rect width="${layout.width}" height="${layout.height}" rx="${formatSvgNumber(layout.style.cornerRadius)}" fill="${escapeXml(layout.style.backgroundColor)}"/><text${whitespaceAttribute} fill="${escapeXml(layout.style.textColor)}" font-family="${escapeXml(layout.style.font)}" font-size="${formatSvgNumber(layout.style.fontSize)}" text-anchor="${textAnchor}">${tspans}</text></svg>`;
9967
+ }
9968
+ function renderSvgTextRichLayout(layout) {
9969
+ const tspans = layout.lines.flatMap((line) => line.fragments.flatMap((fragment) => {
9970
+ if (fragment.type === "text") return [`<tspan x="${formatSvgNumber(fragment.x)}" y="${formatSvgNumber(fragment.baseline)}" font-size="${formatSvgNumber(layout.style.fontSize)}">${escapeXml(fragment.text)}</tspan>`];
9971
+ return [`<tspan x="${formatSvgNumber(fragment.reading.x)}" y="${formatSvgNumber(fragment.reading.baseline)}" font-size="${formatSvgNumber(fragment.reading.fontSize)}">${escapeXml(fragment.reading.text)}</tspan>`, `<tspan x="${formatSvgNumber(fragment.base.x)}" y="${formatSvgNumber(fragment.base.baseline)}" font-size="${formatSvgNumber(fragment.base.fontSize)}">${escapeXml(fragment.base.text)}</tspan>`];
9972
+ })).join("");
9973
+ const whitespaceAttribute = layout.preserveWhitespace ? " xml:space=\"preserve\"" : "";
9974
+ return `<svg xmlns="http://www.w3.org/2000/svg" width="${layout.width}" height="${layout.height}" viewBox="0 0 ${layout.width} ${layout.height}" role="img"><title>${escapeXml(layout.plainText)}</title><rect width="${layout.width}" height="${layout.height}" rx="${formatSvgNumber(layout.style.cornerRadius)}" fill="${escapeXml(layout.style.backgroundColor)}"/><text${whitespaceAttribute} fill="${escapeXml(layout.style.textColor)}" font-family="${escapeXml(layout.style.font)}" text-anchor="start">${tspans}</text></svg>`;
9975
+ }
9660
9976
  function normalizeSvgTextColor(value, fallback) {
9661
9977
  const color = value.trim();
9662
9978
  if (color === "") return fallback;
@@ -9743,9 +10059,211 @@
9743
10059
  }
9744
10060
  return units * fontSize;
9745
10061
  }
9746
- block_definitions_default.blocks;
9747
- block_definitions_default.menus;
9748
- `${encodeURIComponent("<svg xmlns=\"http://www.w3.org/2000/svg\" viewBox=\"0 0 64 64\"><g fill=\"none\" stroke=\"#fff\" stroke-width=\"5\" stroke-linecap=\"round\" stroke-linejoin=\"round\"><path d=\"M13 23V12h11M40 12h11v11M13 41v11h11M40 52h11V41M22 23h20M32 23v23\"/></g></svg>")}`;
10062
+ function escapeXml(value) {
10063
+ return value.replace(/[&<>"']/gu, (character) => {
10064
+ switch (character) {
10065
+ case "&": return "&amp;";
10066
+ case "<": return "&lt;";
10067
+ case ">": return "&gt;";
10068
+ case "\"": return "&quot;";
10069
+ default: return "&apos;";
10070
+ }
10071
+ });
10072
+ }
10073
+ function formatSvgNumber(value) {
10074
+ return String(Math.round(value * 1e3) / 1e3);
10075
+ }
10076
+ var blockDefinitions$1 = block_definitions_default.blocks;
10077
+ var definitionMenus$1 = block_definitions_default.menus;
10078
+ var EXTENSION_DOCS_URI$1 = "https://kubohiroya.github.io/turbowarp-svg-text/";
10079
+ var defaultStyleName$1 = "default";
10080
+ var defaultFontPercent = 100;
10081
+ var defaultRubyFontPercent = 50;
10082
+ var defaultRubyGap = 1;
10083
+ var minimumFontPercent = 1;
10084
+ var maximumFontPercent = 1e3;
10085
+ var minimumRubyFontPercent = 10;
10086
+ var maximumRubyFontPercent = 100;
10087
+ var minimumRubyGap = 0;
10088
+ var maximumRubyGap = 100;
10089
+ var BLOCK_ICON_URI$1 = `data:image/svg+xml,${encodeURIComponent("<svg xmlns=\"http://www.w3.org/2000/svg\" viewBox=\"0 0 64 64\"><g fill=\"none\" stroke=\"#fff\" stroke-width=\"5\" stroke-linecap=\"round\" stroke-linejoin=\"round\"><path d=\"M13 23V12h11M40 12h11v11M13 41v11h11M40 52h11V41M22 23h20M32 23v23\"/></g></svg>")}`;
10090
+ var SvgTextExtension = class {
10091
+ constructor(runtime = Scratch.vm?.runtime, options = {}) {
10092
+ this.styles = /* @__PURE__ */ new Map([[defaultStyleName$1, DEFAULT_SVG_TEXT_RICH_STYLE]]);
10093
+ this.textActors = /* @__PURE__ */ new Map();
10094
+ if (!runtime) throw new Error("SVG Text requires the TurboWarp VM.");
10095
+ this.runtime = runtime;
10096
+ this.castToString = options.castToString ?? Scratch.Cast.toString;
10097
+ if (options.listenForRuntimeEvents ?? true) this.runtime.on("STAGE_SIZE_CHANGED", () => {
10098
+ this.restyleTextActors();
10099
+ });
10100
+ }
10101
+ getInfo() {
10102
+ return {
10103
+ id: extensionConfig.id,
10104
+ name: Scratch.translate(block_definitions_default.extensionName),
10105
+ docsURI: EXTENSION_DOCS_URI$1,
10106
+ blockIconURI: BLOCK_ICON_URI$1,
10107
+ color1: "#9966ff",
10108
+ blocks: blockDefinitions$1.map((block) => this.toScratchBlock(block)),
10109
+ menus: definitionMenus$1
10110
+ };
10111
+ }
10112
+ defineStyle(args) {
10113
+ const styleName = this.normalizeStyleName(args.STYLE);
10114
+ this.styles.set(styleName, {
10115
+ alignment: this.normalizeAlignment(args.ALIGN),
10116
+ backgroundColor: this.normalizeColor(args.BACKGROUND, DEFAULT_SVG_TEXT_STYLE.backgroundColor),
10117
+ font: this.normalizeFont(args.FONT),
10118
+ fontPercent: this.normalizeFontPercent(args.SIZE),
10119
+ rubyFontPercent: this.normalizeRubyFontPercent(args.RUBY_SIZE),
10120
+ rubyGap: this.normalizeRubyGap(args.RUBY_GAP),
10121
+ textColor: this.normalizeColor(args.TEXT_COLOR, DEFAULT_SVG_TEXT_STYLE.textColor)
10122
+ });
10123
+ this.restyleTextActors(styleName);
10124
+ }
10125
+ setText(args, util) {
10126
+ this.applyTextActor(util.target, {
10127
+ kind: "plain",
10128
+ text: this.normalizeMessage(args.TEXT)
10129
+ }, this.resolveStyle(args.STYLE));
10130
+ }
10131
+ measureText(styleName, text) {
10132
+ const selection = this.resolveStyle(styleName);
10133
+ const layout = createSvgTextLayout(this.normalizeMessage(text), selection.definition, this.getNativeSize());
10134
+ return Math.max(0, ...layout.lines.map((line) => line.width));
10135
+ }
10136
+ /**
10137
+ * Exposes the stock named-style registry through a skin-free layout contract.
10138
+ * Consumers receive current layout data without access to the mutable registry.
10139
+ */
10140
+ getLayoutCapability() {
10141
+ this.layoutCapabilityValue ?? (this.layoutCapabilityValue = Object.freeze({ layoutText: (input) => {
10142
+ if (typeof input !== "object" || input === null || typeof input.styleName !== "string" || typeof input.text !== "string") throw new TypeError("SVG Text layout capability input is invalid.");
10143
+ const nativeSize = this.requireLayoutNativeSize(input.nativeSize);
10144
+ const selection = this.resolveStyle(input.styleName);
10145
+ return createSvgTextLayout(this.normalizeMessage(input.text), selection.definition, nativeSize);
10146
+ } }));
10147
+ return this.layoutCapabilityValue;
10148
+ }
10149
+ setCompositionText(styleName, render, target) {
10150
+ const content = Object.freeze({
10151
+ kind: "composition",
10152
+ render
10153
+ });
10154
+ this.applyTextActor(target, content, this.resolveStyle(styleName));
10155
+ }
10156
+ releaseTextActor(target) {
10157
+ const state = this.textActors.get(target);
10158
+ if (!state) return false;
10159
+ this.textActors.delete(target);
10160
+ this.runtime.renderer?.destroySkin?.(state.skinId);
10161
+ this.runtime.requestRedraw?.();
10162
+ return true;
10163
+ }
10164
+ toScratchBlock(block) {
10165
+ return {
10166
+ opcode: block.opcode,
10167
+ blockType: Scratch.BlockType[block.blockType],
10168
+ text: Scratch.translate(block.text),
10169
+ hideFromPalette: block.hideFromPalette ?? false,
10170
+ arguments: Object.fromEntries(Object.entries(block.arguments).map(([name, argument]) => [name, {
10171
+ type: Scratch.ArgumentType[argument.type],
10172
+ defaultValue: argument.defaultValue,
10173
+ ...argument.menu === void 0 ? {} : { menu: argument.menu }
10174
+ }]))
10175
+ };
10176
+ }
10177
+ normalizeStyleName(value) {
10178
+ return this.castToString(value).trim() || defaultStyleName$1;
10179
+ }
10180
+ normalizeFontPercent(value) {
10181
+ if (typeof value === "string" && value.trim() === "") return defaultFontPercent;
10182
+ const numericValue = Number(value);
10183
+ if (!Number.isFinite(numericValue)) return defaultFontPercent;
10184
+ return Math.min(maximumFontPercent, Math.max(minimumFontPercent, numericValue));
10185
+ }
10186
+ normalizeRubyFontPercent(value) {
10187
+ if (typeof value === "string" && value.trim() === "") return defaultRubyFontPercent;
10188
+ const numericValue = Number(value);
10189
+ if (!Number.isFinite(numericValue)) return defaultRubyFontPercent;
10190
+ return Math.min(maximumRubyFontPercent, Math.max(minimumRubyFontPercent, numericValue));
10191
+ }
10192
+ normalizeRubyGap(value) {
10193
+ if (typeof value === "string" && value.trim() === "") return defaultRubyGap;
10194
+ const numericValue = Number(value);
10195
+ if (!Number.isFinite(numericValue)) return defaultRubyGap;
10196
+ return Math.min(maximumRubyGap, Math.max(minimumRubyGap, numericValue));
10197
+ }
10198
+ normalizeMessage(value) {
10199
+ return this.castToString(value).replace(/\\r\\n|\\n|\\r/gu, "\n");
10200
+ }
10201
+ normalizeAlignment(value) {
10202
+ const alignment = this.castToString(value).trim().toLowerCase();
10203
+ if (alignment === "center" || alignment === "right") return alignment;
10204
+ return "left";
10205
+ }
10206
+ normalizeColor(value, fallback) {
10207
+ return normalizeSvgTextColor(this.castToString(value), fallback);
10208
+ }
10209
+ normalizeFont(value) {
10210
+ return normalizeSvgTextFont(this.castToString(value));
10211
+ }
10212
+ getNativeSize() {
10213
+ const nativeSize = this.runtime.renderer?.getNativeSize?.();
10214
+ if (!Array.isArray(nativeSize) || nativeSize.length < 2) return [480, 360];
10215
+ const width = Number(nativeSize[0]);
10216
+ const height = Number(nativeSize[1]);
10217
+ if (!Number.isFinite(width) || !Number.isFinite(height) || width <= 0 || height <= 0) return [480, 360];
10218
+ return [width, height];
10219
+ }
10220
+ requireLayoutNativeSize(value) {
10221
+ if (!Array.isArray(value) || value.length !== 2 || value.some((dimension) => typeof dimension !== "number" || !Number.isFinite(dimension) || dimension <= 0)) throw new TypeError("SVG Text layout capability nativeSize must contain two positive finite numbers.");
10222
+ return value;
10223
+ }
10224
+ createTextActorSvg(content, definition) {
10225
+ if (content.kind === "composition") return content.render(definition, this.getNativeSize());
10226
+ return renderSvgTextLayout(createSvgTextLayout(content.text, definition, this.getNativeSize()));
10227
+ }
10228
+ applyTextActor(target, content, selection) {
10229
+ const renderer = this.runtime.renderer;
10230
+ if (typeof target.drawableID !== "number" || typeof renderer?.createSVGSkin !== "function" || typeof renderer.updateDrawableSkinId !== "function") throw new Error("SVG Text requires SVG skin APIs from TurboWarp.");
10231
+ const skinId = renderer.createSVGSkin(this.createTextActorSvg(content, selection.definition));
10232
+ if (!Number.isInteger(skinId) || skinId < 0) throw new Error("TurboWarp did not create an SVG text skin.");
10233
+ try {
10234
+ renderer.updateDrawableSkinId(target.drawableID, skinId);
10235
+ } catch (error) {
10236
+ renderer.destroySkin?.(skinId);
10237
+ throw error;
10238
+ }
10239
+ const previous = this.textActors.get(target);
10240
+ this.textActors.set(target, {
10241
+ content,
10242
+ skinId,
10243
+ styleName: selection.styleName
10244
+ });
10245
+ if (previous && previous.skinId !== skinId) renderer.destroySkin?.(previous.skinId);
10246
+ this.runtime.requestRedraw?.();
10247
+ }
10248
+ resolveStyle(value) {
10249
+ const requestedName = this.normalizeStyleName(value);
10250
+ const definition = this.styles.get(requestedName);
10251
+ if (definition) return {
10252
+ definition,
10253
+ styleName: requestedName
10254
+ };
10255
+ return {
10256
+ definition: this.styles.get(defaultStyleName$1) ?? DEFAULT_SVG_TEXT_RICH_STYLE,
10257
+ styleName: defaultStyleName$1
10258
+ };
10259
+ }
10260
+ restyleTextActors(styleName) {
10261
+ for (const [target, state] of [...this.textActors]) {
10262
+ if (styleName !== void 0 && state.styleName !== styleName) continue;
10263
+ this.applyTextActor(target, state.content, this.resolveStyle(state.styleName));
10264
+ }
10265
+ }
10266
+ };
9749
10267
  var defaultStyleName = "default";
9750
10268
  var maximumContentCharacters = 1e5;
9751
10269
  var maximumContentLines = 1e3;
@@ -9754,7 +10272,7 @@
9754
10272
  var maximumLayoutWidth = 1e5;
9755
10273
  var maximumRubyBaseCharacters = 256;
9756
10274
  var maximumRubyReadingCharacters = 512;
9757
- function isRecord$3(value) {
10275
+ function isRecord$4(value) {
9758
10276
  return typeof value === "object" && value !== null && !Array.isArray(value);
9759
10277
  }
9760
10278
  function compositionError(code, message) {
@@ -9770,11 +10288,27 @@
9770
10288
  if (typeof value !== "string" || value.trim().length === 0) throw compositionError("SVG-TEXT-COMPOSITION-001", `${label} must be a non-empty string.`);
9771
10289
  return value.trim();
9772
10290
  }
10291
+ function validateRuntime(value) {
10292
+ if (!isRecord$4(value) || !isRecord$4(value.renderer)) throw new TypeError("SVG Text composition runtime must provide a renderer.");
10293
+ const renderer = value.renderer;
10294
+ const methods = [
10295
+ "createSVGSkin",
10296
+ "destroySkin",
10297
+ "updateDrawableSkinId"
10298
+ ];
10299
+ if (methods.some((method) => typeof renderer[method] !== "function")) throw new TypeError(`SVG Text composition renderer must provide ${methods.join(", ")}.`);
10300
+ if (value.requestRedraw !== void 0 && typeof value.requestRedraw !== "function") throw new TypeError("SVG Text composition requestRedraw must be a function.");
10301
+ return value;
10302
+ }
10303
+ function validateTarget(value) {
10304
+ if (!isRecord$4(value) || typeof value.drawableID !== "number" || !Number.isInteger(value.drawableID) || value.drawableID < 0) throw compositionError("SVG-TEXT-COMPOSITION-002", "SVG Text target must provide a non-negative integer drawableID.");
10305
+ return value;
10306
+ }
9773
10307
  function validateOptionalString(value, label) {
9774
10308
  if (value !== void 0 && (typeof value !== "string" || value.length === 0)) throw compositionError("SVG-TEXT-COMPOSITION-001", `${label} must be a non-empty string when provided.`);
9775
10309
  }
9776
10310
  function validateStyle(value) {
9777
- if (!isRecord$3(value)) throw compositionError("SVG-TEXT-COMPOSITION-001", "SVG Text style must be an object.");
10311
+ if (!isRecord$4(value)) throw compositionError("SVG-TEXT-COMPOSITION-001", "SVG Text style must be an object.");
9778
10312
  requireExactKeys(value, ["name"], [
9779
10313
  "alignment",
9780
10314
  "backgroundColor",
@@ -9812,6 +10346,14 @@
9812
10346
  if (!Array.isArray(value) || value.length !== 2 || value.some((dimension) => typeof dimension !== "number" || !Number.isFinite(dimension) || dimension <= 0)) throw compositionError("SVG-TEXT-COMPOSITION-001", "SVG Text nativeSize must be [width, height] with two positive finite numbers.");
9813
10347
  return value;
9814
10348
  }
10349
+ function getRuntimeNativeSize(renderer) {
10350
+ const value = renderer.getNativeSize?.();
10351
+ if (!Array.isArray(value) || value.length < 2) return [480, 360];
10352
+ const width = Number(value[0]);
10353
+ const height = Number(value[1]);
10354
+ if (!Number.isFinite(width) || !Number.isFinite(height) || width <= 0 || height <= 0) return [480, 360];
10355
+ return [width, height];
10356
+ }
9815
10357
  function normalizeText(value) {
9816
10358
  return value.replace(/\\r\\n|\\n|\\r/gu, "\n");
9817
10359
  }
@@ -9828,7 +10370,7 @@
9828
10370
  let fragmentCount = 0;
9829
10371
  let lineCount = 1;
9830
10372
  const runs = value.map((candidate, runIndex) => {
9831
- if (!isRecord$3(candidate)) throw compositionError("SVG-TEXT-COMPOSITION-001", `SVG Text rich content run ${runIndex} must be an object.`);
10373
+ if (!isRecord$4(candidate)) throw compositionError("SVG-TEXT-COMPOSITION-001", `SVG Text rich content run ${runIndex} must be an object.`);
9832
10374
  if (candidate.type === "text") {
9833
10375
  requireExactKeys(candidate, ["type", "text"], [], `SVG Text rich content run ${runIndex}`);
9834
10376
  if (typeof candidate.text !== "string") throw compositionError("SVG-TEXT-COMPOSITION-001", `SVG Text rich content run ${runIndex} text must be a string.`);
@@ -9874,7 +10416,7 @@
9874
10416
  return value;
9875
10417
  }
9876
10418
  function layoutTextFromStyles(styles, input) {
9877
- if (!isRecord$3(input)) throw compositionError("SVG-TEXT-COMPOSITION-001", "SVG Text layout input is invalid.");
10419
+ if (!isRecord$4(input)) throw compositionError("SVG-TEXT-COMPOSITION-001", "SVG Text layout input is invalid.");
9878
10420
  requireExactKeys(input, [
9879
10421
  "styleName",
9880
10422
  "text",
@@ -9887,7 +10429,7 @@
9887
10429
  return createSvgTextLayout(normalizeText(input.text), definition, validateNativeSize(input.nativeSize));
9888
10430
  }
9889
10431
  function layoutRichTextFromStyles(styles, input) {
9890
- if (!isRecord$3(input)) throw compositionError("SVG-TEXT-COMPOSITION-001", "SVG Text rich layout input is invalid.");
10432
+ if (!isRecord$4(input)) throw compositionError("SVG-TEXT-COMPOSITION-001", "SVG Text rich layout input is invalid.");
9891
10433
  requireExactKeys(input, [
9892
10434
  "styleName",
9893
10435
  "runs",
@@ -9916,17 +10458,141 @@
9916
10458
  }
9917
10459
  });
9918
10460
  }
10461
+ function createSvgTextComposition(options) {
10462
+ if (!isRecord$4(options)) throw new TypeError("SVG Text composition options must be an object.");
10463
+ const runtime = validateRuntime(options.runtime);
10464
+ const extension = new SvgTextExtension(runtime, {
10465
+ castToString: (value) => String(value),
10466
+ listenForRuntimeEvents: false
10467
+ });
10468
+ const styles = /* @__PURE__ */ new Map([[defaultStyleName, DEFAULT_SVG_TEXT_RICH_STYLE]]);
10469
+ const targets = /* @__PURE__ */ new Set();
10470
+ let disposed = false;
10471
+ function ensureActive() {
10472
+ if (disposed) throw compositionError("SVG-TEXT-COMPOSITION-004", "SVG Text composition has been released.");
10473
+ }
10474
+ return Object.freeze({
10475
+ defineStyle(input) {
10476
+ ensureActive();
10477
+ const style = validateStyle(input);
10478
+ extension.defineStyle({
10479
+ ALIGN: style.alignment ?? "",
10480
+ BACKGROUND: style.backgroundColor ?? "",
10481
+ FONT: style.font ?? "",
10482
+ RUBY_GAP: style.rubyGap ?? "",
10483
+ RUBY_SIZE: style.rubyFontPercent ?? "",
10484
+ SIZE: style.fontPercent ?? "",
10485
+ STYLE: style.name,
10486
+ TEXT_COLOR: style.textColor ?? ""
10487
+ });
10488
+ styles.set(style.name, createStyleDefinition(style));
10489
+ },
10490
+ layoutRichText(input) {
10491
+ ensureActive();
10492
+ return layoutRichTextFromStyles(styles, input);
10493
+ },
10494
+ layoutText(input) {
10495
+ ensureActive();
10496
+ return layoutTextFromStyles(styles, input);
10497
+ },
10498
+ measureText(input) {
10499
+ ensureActive();
10500
+ if (!isRecord$4(input)) throw compositionError("SVG-TEXT-COMPOSITION-001", "SVG Text measure input is invalid.");
10501
+ requireExactKeys(input, ["styleName", "text"], [], "SVG Text measure input");
10502
+ const styleName = requireName(input.styleName, "SVG Text styleName");
10503
+ if (!styles.has(styleName)) throw compositionError("SVG-TEXT-COMPOSITION-003", `SVG Text style is not defined: ${styleName}`);
10504
+ if (typeof input.text !== "string") throw compositionError("SVG-TEXT-COMPOSITION-001", "SVG Text text must be a string.");
10505
+ return extension.measureText(styleName, input.text);
10506
+ },
10507
+ measureRichText(input) {
10508
+ ensureActive();
10509
+ if (!isRecord$4(input)) throw compositionError("SVG-TEXT-COMPOSITION-001", "SVG Text rich measure input is invalid.");
10510
+ requireExactKeys(input, ["styleName", "runs"], ["maxWidth"], "SVG Text rich measure input");
10511
+ const styleName = requireName(input.styleName, "SVG Text styleName");
10512
+ const definition = styles.get(styleName);
10513
+ if (!definition) throw compositionError("SVG-TEXT-COMPOSITION-003", `SVG Text style is not defined: ${styleName}`);
10514
+ const runs = validateContentRuns(input.runs);
10515
+ const maxWidth = validateMaxWidth(input.maxWidth);
10516
+ const nativeSize = getRuntimeNativeSize(runtime.renderer);
10517
+ const layout = maxWidth === void 0 ? createSvgTextRichLayout(runs, definition, nativeSize) : createSvgTextRichLayout(runs, definition, nativeSize, maxWidth);
10518
+ return Math.max(0, ...layout.lines.map((line) => line.width));
10519
+ },
10520
+ setRichText(input) {
10521
+ ensureActive();
10522
+ if (!isRecord$4(input)) throw compositionError("SVG-TEXT-COMPOSITION-001", "SVG Text rich actor input is invalid.");
10523
+ requireExactKeys(input, [
10524
+ "styleName",
10525
+ "target",
10526
+ "runs"
10527
+ ], ["maxWidth"], "SVG Text rich actor input");
10528
+ const target = validateTarget(input.target);
10529
+ const styleName = requireName(input.styleName, "SVG Text styleName");
10530
+ if (!styles.has(styleName)) throw compositionError("SVG-TEXT-COMPOSITION-003", `SVG Text style is not defined: ${styleName}`);
10531
+ const runs = validateContentRuns(input.runs);
10532
+ const maxWidth = validateMaxWidth(input.maxWidth);
10533
+ extension.setCompositionText(styleName, (definition, nativeSize) => {
10534
+ return renderSvgTextRichLayout(maxWidth === void 0 ? createSvgTextRichLayout(runs, definition, nativeSize) : createSvgTextRichLayout(runs, definition, nativeSize, maxWidth));
10535
+ }, target);
10536
+ targets.add(target);
10537
+ },
10538
+ setText(input) {
10539
+ ensureActive();
10540
+ if (!isRecord$4(input)) throw compositionError("SVG-TEXT-COMPOSITION-001", "SVG Text actor input is invalid.");
10541
+ requireExactKeys(input, [
10542
+ "styleName",
10543
+ "target",
10544
+ "text"
10545
+ ], [], "SVG Text actor input");
10546
+ const target = validateTarget(input.target);
10547
+ const styleName = requireName(input.styleName, "SVG Text styleName");
10548
+ if (!styles.has(styleName)) throw compositionError("SVG-TEXT-COMPOSITION-003", `SVG Text style is not defined: ${styleName}`);
10549
+ if (typeof input.text !== "string") throw compositionError("SVG-TEXT-COMPOSITION-001", "SVG Text text must be a string.");
10550
+ extension.setText({
10551
+ STYLE: styleName,
10552
+ TEXT: input.text
10553
+ }, { target });
10554
+ targets.add(target);
10555
+ },
10556
+ releaseTarget(value) {
10557
+ ensureActive();
10558
+ const target = validateTarget(value);
10559
+ if (!targets.delete(target)) throw compositionError("SVG-TEXT-COMPOSITION-005", "SVG Text target is not owned by this composition.");
10560
+ if (!extension.releaseTextActor(target)) throw compositionError("SVG-TEXT-COMPOSITION-005", "SVG Text target ownership is inconsistent.");
10561
+ },
10562
+ releaseAll() {
10563
+ if (disposed) return;
10564
+ disposed = true;
10565
+ const errors = [];
10566
+ for (const target of targets) try {
10567
+ extension.releaseTextActor(target);
10568
+ } catch (error) {
10569
+ errors.push(error);
10570
+ }
10571
+ targets.clear();
10572
+ styles.clear();
10573
+ if (errors.length > 0) {
10574
+ const error = compositionError("SVG-TEXT-COMPOSITION-006", "SVG Text composition failed to release one or more skins.");
10575
+ Object.defineProperty(error, "errors", { value: Object.freeze([...errors]) });
10576
+ throw error;
10577
+ }
10578
+ }
10579
+ });
10580
+ }
9919
10581
  //#endregion
9920
10582
  //#region src/turbowarp-svg-text-adapter.ts
9921
- function isRecord$2(value) {
10583
+ function isRecord$3(value) {
9922
10584
  return typeof value === "object" && value !== null && !Array.isArray(value);
9923
10585
  }
9924
10586
  function validateExtension(value) {
9925
- if (!isRecord$2(value) || typeof value.setText !== "function" || typeof value.releaseTextActor !== "function") throw new TypeError("TurboWarp SVG Text adapter requires setText and releaseTextActor.");
10587
+ if (!isRecord$3(value) || typeof value.setText !== "function" || typeof value.releaseTextActor !== "function") throw new TypeError("TurboWarp SVG Text adapter requires setText and releaseTextActor.");
10588
+ return value;
10589
+ }
10590
+ function validateComposition(value) {
10591
+ if (!isRecord$3(value) || typeof value.setText !== "function" || typeof value.releaseTarget !== "function") throw new TypeError("SVG Text composition adapter requires setText and releaseTarget.");
9926
10592
  return value;
9927
10593
  }
9928
10594
  function validateLayoutComposition(value) {
9929
- if (!isRecord$2(value) || typeof value.layoutText !== "function") throw new TypeError("SVG Text overlay adapter requires the layoutText composition API.");
10595
+ if (!isRecord$3(value) || typeof value.layoutText !== "function") throw new TypeError("SVG Text overlay adapter requires the layoutText composition API.");
9930
10596
  return value;
9931
10597
  }
9932
10598
  function requireFiniteNumber(value, label) {
@@ -9935,14 +10601,14 @@
9935
10601
  return result;
9936
10602
  }
9937
10603
  function adaptSvgTextLayout(value) {
9938
- if (!isRecord$2(value) || !isRecord$2(value.style) || !Array.isArray(value.lines)) throw new TypeError("SVG Text layout result is invalid.");
10604
+ if (!isRecord$3(value) || !isRecord$3(value.style) || !Array.isArray(value.lines)) throw new TypeError("SVG Text layout result is invalid.");
9939
10605
  const style = value.style;
9940
10606
  const alignment = style.alignment;
9941
10607
  if (alignment !== "left" && alignment !== "center" && alignment !== "right") throw new TypeError("SVG Text layout alignment is invalid.");
9942
10608
  const width = requireFiniteNumber(value.width, "SVG Text layout width");
9943
10609
  const height = requireFiniteNumber(value.height, "SVG Text layout height");
9944
10610
  const lines = Object.freeze(value.lines.map((line) => {
9945
- if (!isRecord$2(line) || typeof line.text !== "string") throw new TypeError("SVG Text layout line is invalid.");
10611
+ if (!isRecord$3(line) || typeof line.text !== "string") throw new TypeError("SVG Text layout line is invalid.");
9946
10612
  return Object.freeze({
9947
10613
  baseline: requireFiniteNumber(line.baseline, "SVG Text line baseline") - height / 2,
9948
10614
  text: line.text,
@@ -9986,6 +10652,30 @@
9986
10652
  });
9987
10653
  }
9988
10654
  /**
10655
+ * Adapt the SVG Text package's composition API to Bubble's text capability.
10656
+ * This helper keeps the core package independent from SVG Text's target type.
10657
+ */
10658
+ function createSvgTextCompositionCapability(compositionInput) {
10659
+ const composition = validateComposition(compositionInput);
10660
+ const capability = {
10661
+ setText({ styleName, target, text }) {
10662
+ composition.setText({
10663
+ styleName,
10664
+ target,
10665
+ text
10666
+ });
10667
+ },
10668
+ releaseTarget(target) {
10669
+ composition.releaseTarget(target);
10670
+ }
10671
+ };
10672
+ if (typeof composition.measureText === "function") capability.measureText = ({ styleName, text }) => composition.measureText?.({
10673
+ styleName,
10674
+ text
10675
+ }) ?? 0;
10676
+ return Object.freeze(capability);
10677
+ }
10678
+ /**
9989
10679
  * Adapt SVG Text's host-neutral layout composition to Bubble's SVG overlay.
9990
10680
  * The adapter preserves SVG Text's line coordinates without creating skins.
9991
10681
  */
@@ -10009,6 +10699,76 @@
10009
10699
  }
10010
10700
  });
10011
10701
  }
10702
+ /**
10703
+ * Adapts the stock SVG Text extension's shared named-style layout registry.
10704
+ */
10705
+ function createTurboWarpSvgTextOverlayTextCapability(extensionInput) {
10706
+ if (!isRecord$3(extensionInput) || typeof extensionInput.getLayoutCapability !== "function") throw new TypeError("TurboWarp SVG Text overlay adapter requires SVG Text 0.8.1 getLayoutCapability().");
10707
+ return createSvgTextOverlayTextCapability(extensionInput.getLayoutCapability());
10708
+ }
10709
+ //#endregion
10710
+ //#region src/asset-manager-image-adapter.ts
10711
+ var supportedMimeTypes = /* @__PURE__ */ new Set([
10712
+ "image/avif",
10713
+ "image/gif",
10714
+ "image/jpeg",
10715
+ "image/png",
10716
+ "image/svg+xml",
10717
+ "image/webp"
10718
+ ]);
10719
+ function isRecord$2(value) {
10720
+ return typeof value === "object" && value !== null && !Array.isArray(value);
10721
+ }
10722
+ function normalizeMimeType(value) {
10723
+ const mimeType = value.split(";", 1)[0]?.trim().toLowerCase() ?? "";
10724
+ if (mimeType === "image/jpg" || mimeType === "image/pjpeg") return "image/jpeg";
10725
+ if (mimeType === "image/x-png") return "image/png";
10726
+ return mimeType;
10727
+ }
10728
+ function isSupportedMimeType(value) {
10729
+ return supportedMimeTypes.has(normalizeMimeType(value));
10730
+ }
10731
+ function requireAssetManagerResource(value) {
10732
+ if (!isRecord$2(value) || typeof value.url !== "string" || !value.url.startsWith("blob:") || typeof value.mimeType !== "string" || !isSupportedMimeType(value.mimeType) || typeof value.width !== "number" || !Number.isFinite(value.width) || value.width <= 0 || typeof value.height !== "number" || !Number.isFinite(value.height) || value.height <= 0 || typeof value.release !== "function") throw new TypeError("Asset Manager DOM image resources must provide a supported MIME type, positive intrinsic dimensions, a blob URL, and release().");
10733
+ return value;
10734
+ }
10735
+ /**
10736
+ * Adapts Asset Manager's host-neutral DOM resource API to Bubble's SVG overlay contract.
10737
+ * Asset Manager owns byte validation and SVG sanitization; Bubble owns its capability shape.
10738
+ */
10739
+ function createAssetManagerSvgOverlayImageCapability(capabilityInput) {
10740
+ if (!isRecord$2(capabilityInput) || typeof capabilityInput.isRegistered !== "function" || typeof capabilityInput.getMimeType !== "function" || typeof capabilityInput.resolveDOMImageResource !== "function") throw new TypeError("Asset Manager DOM image capability is invalid.");
10741
+ const capability = capabilityInput;
10742
+ return Object.freeze({
10743
+ isRegistered(name) {
10744
+ return capability.isRegistered(name) && isSupportedMimeType(capability.getMimeType(name));
10745
+ },
10746
+ getMimeType(name) {
10747
+ return normalizeMimeType(capability.getMimeType(name));
10748
+ },
10749
+ async resolveImage(name) {
10750
+ const declaredMimeType = normalizeMimeType(capability.getMimeType(name));
10751
+ if (!capability.isRegistered(name) || !isSupportedMimeType(declaredMimeType)) throw new TypeError("Asset Manager image is not registered with a Bubble-compatible MIME type.");
10752
+ const resource = await capability.resolveDOMImageResource(name);
10753
+ try {
10754
+ requireAssetManagerResource(resource);
10755
+ const mimeType = normalizeMimeType(resource.mimeType);
10756
+ if (mimeType !== declaredMimeType) throw new TypeError("Asset Manager DOM image resource MIME type changed during resolution.");
10757
+ return Object.freeze({
10758
+ height: resource.height,
10759
+ mimeType,
10760
+ src: resource.url,
10761
+ width: resource.width,
10762
+ release: () => resource.release(),
10763
+ ...mimeType === "image/svg+xml" ? { svgSecurity: "sanitized" } : {}
10764
+ });
10765
+ } catch (error) {
10766
+ resource?.release?.();
10767
+ throw error;
10768
+ }
10769
+ }
10770
+ });
10771
+ }
10012
10772
  //#endregion
10013
10773
  //#region src/surface-motion.ts
10014
10774
  function clampMotionProgress(value) {
@@ -10442,6 +11202,7 @@
10442
11202
  "g",
10443
11203
  "path",
10444
11204
  "rect",
11205
+ "text",
10445
11206
  "title"
10446
11207
  ]);
10447
11208
  var allowedBodyAttributes = /* @__PURE__ */ new Set([
@@ -10452,8 +11213,11 @@
10452
11213
  "data-tail-base-on-border",
10453
11214
  "fill",
10454
11215
  "fill-rule",
11216
+ "font-family",
11217
+ "font-size",
10455
11218
  "height",
10456
11219
  "opacity",
11220
+ "paint-order",
10457
11221
  "r",
10458
11222
  "rx",
10459
11223
  "stroke",
@@ -10462,6 +11226,7 @@
10462
11226
  "stroke-width",
10463
11227
  "transform",
10464
11228
  "width",
11229
+ "xml:space",
10465
11230
  "x",
10466
11231
  "y"
10467
11232
  ]);
@@ -10475,7 +11240,7 @@
10475
11240
  if (/javascript:|url\s*\(/iu.test(value)) throw new TypeError("Bubble body SVG contains an unsafe attribute value.");
10476
11241
  result.setAttribute(attribute, value);
10477
11242
  }
10478
- if (name === "title") result.textContent = source.textContent ?? "";
11243
+ if (name === "title" || name === "text") result.textContent = source.textContent ?? "";
10479
11244
  for (const child of Array.from(source.children)) result.appendChild(copyAllowedBodyNode(child, document));
10480
11245
  return result;
10481
11246
  }
@@ -10497,7 +11262,7 @@
10497
11262
  target.setDisplaySize(size);
10498
11263
  return size;
10499
11264
  }
10500
- function createSvgOverlaySurface(manager, actor, actorKey, style, scheduler) {
11265
+ function createSvgOverlaySurface(manager, actor, actorKey, kind, style, scheduler) {
10501
11266
  const { document, renderer } = manager;
10502
11267
  const sequence = overlaySurfaceSequence;
10503
11268
  overlaySurfaceSequence += 1;
@@ -10550,6 +11315,8 @@
10550
11315
  let motionOpacity = 1;
10551
11316
  let center = [0, 0];
10552
11317
  let shapeTransition;
11318
+ let scratchTextLayout;
11319
+ let scratchPointsLeft = false;
10553
11320
  const applyMotionTransform = (native = manager.updateNativeSize()) => {
10554
11321
  const centerX = native.width / 2 + center[0];
10555
11322
  const centerY = native.height / 2 - center[1];
@@ -10567,15 +11334,53 @@
10567
11334
  const updateVisibility = (nativeSize) => {
10568
11335
  const actorVisible = currentStyle.placement.basis === "background" || actor.visible !== false;
10569
11336
  const visible = surfaceVisible && actorVisible && motionOpacity > 0;
11337
+ const scratchDefaultRendered = currentStyle.layoutProfile === "scratch-default" && scratchTextLayout !== void 0;
10570
11338
  surfaceGroup.setAttribute("visibility", visible ? "visible" : "hidden");
10571
- bodyGroup.setAttribute("visibility", visible && currentStyle.visualStyle !== "NO_BUBBLE" ? "visible" : "hidden");
10572
- textGroup.setAttribute("visibility", visible ? "visible" : "hidden");
11339
+ bodyGroup.setAttribute("visibility", visible && (scratchDefaultRendered || currentStyle.visualStyle !== "NO_BUBBLE") ? "visible" : "hidden");
11340
+ textGroup.setAttribute("visibility", visible && !scratchDefaultRendered ? "visible" : "hidden");
10573
11341
  for (const [layer, target] of layerTargets) target.setVisible(visible && layerAllowedByStyle(layer) && (layerVisibility.get(layer) ?? false));
10574
11342
  applyMotionTransform(nativeSize);
10575
11343
  };
10576
11344
  const position = () => {
10577
11345
  if (disposed) return;
10578
11346
  const native = manager.updateNativeSize();
11347
+ if (currentStyle.layoutProfile === "scratch-default" && scratchTextLayout !== void 0) {
11348
+ const metrics = scratchBubbleMetrics(scratchTextLayout);
11349
+ const nextPosition = positionScratchBubble({
11350
+ bounds: targetBounds$1(actor),
11351
+ height: metrics.height,
11352
+ pointsLeft: scratchPointsLeft,
11353
+ stageHeight: native.height,
11354
+ stageWidth: native.width,
11355
+ width: metrics.width
11356
+ });
11357
+ scratchPointsLeft = nextPosition.pointsLeft;
11358
+ center = [nextPosition.centerX, nextPosition.centerY];
11359
+ const nextBodySignature = JSON.stringify({
11360
+ kind,
11361
+ layout: scratchTextLayout,
11362
+ pointsLeft: scratchPointsLeft
11363
+ });
11364
+ if (nextBodySignature !== bodySignature) {
11365
+ replaceBodyFromCanonicalSvg(bodyGroup, renderScratchBubbleSvg({
11366
+ kind,
11367
+ layout: scratchTextLayout,
11368
+ pointsLeft: scratchPointsLeft,
11369
+ title: `${currentStyle.name} ${kind} Bubble`
11370
+ }), document);
11371
+ bodySignature = nextBodySignature;
11372
+ }
11373
+ bodyGroup.setAttribute("data-bubble-style", "SCRATCH_DEFAULT");
11374
+ bodyGroup.setAttribute("data-bubble-profile", "scratch-default");
11375
+ bodyGroup.setAttribute("data-bubble-kind", kind);
11376
+ bodyGroup.setAttribute("data-bubble-body-width", String(metrics.width));
11377
+ bodyGroup.setAttribute("data-bubble-body-height", String(metrics.height));
11378
+ bodyGroup.setAttribute("transform", `translate(${native.width / 2 + nextPosition.left} ${native.height / 2 - nextPosition.top})`);
11379
+ updateVisibility(native);
11380
+ return;
11381
+ }
11382
+ bodyGroup.removeAttribute("data-bubble-profile");
11383
+ bodyGroup.removeAttribute("data-bubble-kind");
10579
11384
  const scaleMultiplier = currentStyle.placement.basis === "actor" ? currentStyle.offset.scalePercent / 100 : 1;
10580
11385
  const nativeTextSize = text.getCapturedSize() ?? text.getSize();
10581
11386
  const textSize = {
@@ -10592,8 +11397,11 @@
10592
11397
  const indicatorSize = fitImage(continueIndicator, indicatorBoxSize$1, scaleMultiplier);
10593
11398
  const totalWidth = portraitSize.width + (hasPortrait ? contentGap$1 * scaleMultiplier : 0) + textSize.width;
10594
11399
  const contentHeight = Math.max(portraitSize.height, textSize.height);
10595
- const baseBubbleWidth = totalWidth / scaleMultiplier + 48;
10596
- const baseBubbleHeight = contentHeight / scaleMultiplier + 48;
11400
+ const minimumBodySize = bubbleBodyMinimumSize(currentStyle.visualStyle, ...shapeTransition === void 0 ? [] : [shapeTransition.from, shapeTransition.to]);
11401
+ const baseBubbleWidth = Math.max(totalWidth / scaleMultiplier + 48, minimumBodySize.width);
11402
+ const baseBubbleHeight = Math.max(contentHeight / scaleMultiplier + 48, minimumBodySize.height);
11403
+ const bubbleWidth = Math.max(totalWidth, (baseBubbleWidth - 48) * scaleMultiplier);
11404
+ const bubbleHeight = Math.max(contentHeight, (baseBubbleHeight - 48) * scaleMultiplier);
10597
11405
  const stageLeft = -native.width / 2;
10598
11406
  const stageRight = native.width / 2;
10599
11407
  const stageTop = native.height / 2;
@@ -10602,14 +11410,14 @@
10602
11410
  let centerY;
10603
11411
  if (currentStyle.placement.basis === "background") {
10604
11412
  centerX = 0;
10605
- if (currentStyle.placement.region === "HEADER_LIKE") centerY = stageTop - stageSafeMargin$1 - contentHeight / 2;
10606
- else if (currentStyle.placement.region === "FOOTER_LIKE") centerY = stageBottom + stageSafeMargin$1 + contentHeight / 2;
11413
+ if (currentStyle.placement.region === "HEADER_LIKE") centerY = stageTop - stageSafeMargin$1 - bubbleHeight / 2;
11414
+ else if (currentStyle.placement.region === "FOOTER_LIKE") centerY = stageBottom + stageSafeMargin$1 + bubbleHeight / 2;
10607
11415
  else centerY = 0;
10608
11416
  } else {
10609
11417
  const nextCenter = actorRelativeBubbleCenter({
10610
11418
  bounds: targetBounds$1(actor),
10611
- bubbleWidth: totalWidth,
10612
- bubbleHeight: contentHeight,
11419
+ bubbleWidth,
11420
+ bubbleHeight,
10613
11421
  direction: currentStyle.placement.direction,
10614
11422
  distance: currentStyle.distance,
10615
11423
  tailLength: currentStyle.tailLength,
@@ -10618,8 +11426,8 @@
10618
11426
  centerX = nextCenter.x;
10619
11427
  centerY = nextCenter.y;
10620
11428
  }
10621
- centerX = clamp$1(centerX, stageLeft + totalWidth / 2, stageRight - totalWidth / 2);
10622
- centerY = clamp$1(centerY, stageBottom + contentHeight / 2, stageTop - contentHeight / 2);
11429
+ centerX = clamp$1(centerX, stageLeft + bubbleWidth / 2, stageRight - bubbleWidth / 2);
11430
+ centerY = clamp$1(centerY, stageBottom + bubbleHeight / 2, stageTop - bubbleHeight / 2);
10623
11431
  center = [centerX, centerY];
10624
11432
  const tailDirection = currentStyle.placement.basis === "actor" ? tailDirectionForPlacement$1(currentStyle.placement.direction) : null;
10625
11433
  const bodyOffset = currentStyle.placement.basis === "actor" ? [
@@ -10666,6 +11474,8 @@
10666
11474
  bodySignature = nextBodySignature;
10667
11475
  }
10668
11476
  bodyGroup.setAttribute("data-bubble-style", currentStyle.visualStyle);
11477
+ bodyGroup.setAttribute("data-bubble-body-width", String(baseBubbleWidth));
11478
+ bodyGroup.setAttribute("data-bubble-body-height", String(baseBubbleHeight));
10669
11479
  if (shapeTransition === void 0) {
10670
11480
  bodyGroup.removeAttribute("data-bubble-shape-transition-from");
10671
11481
  bodyGroup.removeAttribute("data-bubble-shape-transition-to");
@@ -10732,8 +11542,14 @@
10732
11542
  layerVisibility.set(layer, visible);
10733
11543
  updateVisibility();
10734
11544
  },
10735
- updateStyle(nextStyle) {
11545
+ async updateStyle(nextStyle) {
10736
11546
  if (disposed) return;
11547
+ const removedTargets = [...nextStyle.portrait === void 0 ? [
11548
+ portraitBase,
11549
+ portraitBlink,
11550
+ portraitLipSync
11551
+ ] : [...nextStyle.portrait.blink === void 0 ? [portraitBlink] : [], ...nextStyle.portrait.lipSync === void 0 ? [portraitLipSync] : []], ...nextStyle.continueIndicator === void 0 ? [continueIndicator] : []];
11552
+ await Promise.all(removedTargets.map((target) => target.release()));
10737
11553
  const wasActorRelative = currentStyle.placement.basis === "actor";
10738
11554
  currentStyle = nextStyle;
10739
11555
  motionTranslation = [0, 0];
@@ -10757,6 +11573,12 @@
10757
11573
  text.clearCapturedLayout();
10758
11574
  position();
10759
11575
  },
11576
+ renderScratchText(layout) {
11577
+ if (disposed) return;
11578
+ scratchTextLayout = layout;
11579
+ bodySignature = "";
11580
+ position();
11581
+ },
10760
11582
  async animate(motion) {
10761
11583
  if (disposed) return;
10762
11584
  const durationSeconds = Math.max(0, motion.durationSeconds ?? 0);
@@ -10962,10 +11784,44 @@
10962
11784
  return composition.layoutText(input);
10963
11785
  } }));
10964
11786
  }
11787
+ function createDefaultScratchRenderTextCapability(runtime) {
11788
+ const composition = createSvgTextComposition({ runtime });
11789
+ const definedStyles = /* @__PURE__ */ new Set();
11790
+ const defineStyle = (name) => {
11791
+ composition.defineStyle({
11792
+ name,
11793
+ backgroundColor: "transparent"
11794
+ });
11795
+ definedStyles.add(name);
11796
+ };
11797
+ const ensureStyle = (name) => {
11798
+ if (!definedStyles.has(name)) defineStyle(name);
11799
+ };
11800
+ defineStyle("default");
11801
+ return createSvgTextCompositionCapability(Object.freeze({
11802
+ setText(input) {
11803
+ ensureStyle(input.styleName);
11804
+ composition.setText(input);
11805
+ },
11806
+ releaseTarget(target) {
11807
+ composition.releaseTarget(target);
11808
+ },
11809
+ measureText(input) {
11810
+ ensureStyle(input.styleName);
11811
+ return composition.measureText(input);
11812
+ }
11813
+ }));
11814
+ }
10965
11815
  function requireAssetManager(value) {
10966
11816
  if (!isRecord(value) || typeof value.isLoaded !== "function" || typeof value.getAssetMimeType !== "function" || typeof value.resolveSkin !== "function") throw new BubbleRuntimeAdapterError("BUBBLE-RUNTIME-002", "Bubble image assets require an imageResolver capability. Load @kubohiroya/turbowarp-asset-manager or provide options.imageResolver before using image features.");
10967
11817
  return value;
10968
11818
  }
11819
+ function requireAssetManagerDOMImageCapability(value) {
11820
+ if (!isRecord(value) || typeof value.getDOMImageCapability !== "function") throw new BubbleRuntimeAdapterError("BUBBLE-RUNTIME-002", "Bubble SVG overlay image assets require @kubohiroya/turbowarp-asset-manager 0.12.1 or a host-provided options.svgOverlayImageCapability.");
11821
+ const capability = value.getDOMImageCapability();
11822
+ if (!isRecord(capability) || typeof capability.isRegistered !== "function" || typeof capability.getMimeType !== "function" || typeof capability.resolveDOMImageResource !== "function") throw new BubbleRuntimeAdapterError("BUBBLE-RUNTIME-002", "Asset Manager did not provide a valid DOM image capability.");
11823
+ return capability;
11824
+ }
10969
11825
  function targetBounds(target) {
10970
11826
  try {
10971
11827
  const bounds = target.getBoundsForBubble?.();
@@ -11030,7 +11886,7 @@
11030
11886
  const vector = bubbleDirectionVector(direction);
11031
11887
  return (Math.atan2(-vector.x, -vector.y) * 180 / Math.PI % 360 + 360) % 360;
11032
11888
  }
11033
- function createSurface(runtime, actor, actorKey, style, scheduler) {
11889
+ function createSurface(runtime, actor, actorKey, kind, style, scheduler) {
11034
11890
  const renderer = runtime.renderer;
11035
11891
  const sequence = surfaceSequence;
11036
11892
  surfaceSequence += 1;
@@ -11083,6 +11939,8 @@
11083
11939
  let motionScaleMultiplier = 1;
11084
11940
  let motionOpacity = 1;
11085
11941
  let shapeTransition;
11942
+ let scratchTextLayout;
11943
+ let scratchPointsLeft = false;
11086
11944
  const applyMotionTransforms = () => {
11087
11945
  for (const target of drawables) {
11088
11946
  const basePosition = layoutPositions.get(target.drawableID);
@@ -11094,8 +11952,9 @@
11094
11952
  };
11095
11953
  const updateVisibility = () => {
11096
11954
  const actorVisible = currentStyle.placement.basis === "background" || actor.visible !== false;
11097
- renderer.updateDrawableVisible(body.drawableID, surfaceVisible && actorVisible && currentStyle.visualStyle !== "NO_BUBBLE" && (renderer.updateDrawableEffect !== void 0 || motionOpacity > 0));
11098
- renderer.updateDrawableVisible(text.drawableID, surfaceVisible && actorVisible && (renderer.updateDrawableEffect !== void 0 || motionOpacity > 0));
11955
+ const scratchDefaultRendered = currentStyle.layoutProfile === "scratch-default" && scratchTextLayout !== void 0;
11956
+ renderer.updateDrawableVisible(body.drawableID, surfaceVisible && actorVisible && (scratchDefaultRendered || currentStyle.visualStyle !== "NO_BUBBLE") && (renderer.updateDrawableEffect !== void 0 || motionOpacity > 0));
11957
+ renderer.updateDrawableVisible(text.drawableID, surfaceVisible && actorVisible && !scratchDefaultRendered && (renderer.updateDrawableEffect !== void 0 || motionOpacity > 0));
11099
11958
  for (const [layer, target] of layerTargets) renderer.updateDrawableVisible(target.drawableID, surfaceVisible && actorVisible && (layerVisibility.get(layer) ?? false) && (renderer.updateDrawableEffect !== void 0 || motionOpacity > 0));
11100
11959
  if (portraitMask) renderer.updateDrawableVisible(portraitMask.drawableID, surfaceVisible && actorVisible && currentStyle.portrait !== void 0 && currentStyle.portrait.cornerRadius > 0 && currentStyle.visualStyle !== "NO_BUBBLE" && (layerVisibility.get("portraitBase") ?? false) && (renderer.updateDrawableEffect !== void 0 || motionOpacity > 0));
11101
11960
  applyMotionTransforms();
@@ -11103,6 +11962,51 @@
11103
11962
  };
11104
11963
  const position = () => {
11105
11964
  if (disposed) return;
11965
+ if (currentStyle.layoutProfile === "scratch-default" && scratchTextLayout !== void 0) {
11966
+ const nativeSize = renderer.getNativeSize();
11967
+ const stageWidth = Array.isArray(nativeSize) && Number(nativeSize[0]) > 0 ? Number(nativeSize[0]) : 480;
11968
+ const stageHeight = Array.isArray(nativeSize) && Number(nativeSize[1]) > 0 ? Number(nativeSize[1]) : 360;
11969
+ const metrics = scratchBubbleMetrics(scratchTextLayout);
11970
+ const nextPosition = positionScratchBubble({
11971
+ bounds: targetBounds(actor),
11972
+ height: metrics.height,
11973
+ pointsLeft: scratchPointsLeft,
11974
+ stageHeight,
11975
+ stageWidth,
11976
+ width: metrics.width
11977
+ });
11978
+ scratchPointsLeft = nextPosition.pointsLeft;
11979
+ const nextBodySkinSignature = JSON.stringify({
11980
+ kind,
11981
+ layout: scratchTextLayout,
11982
+ pointsLeft: scratchPointsLeft
11983
+ });
11984
+ if (nextBodySkinSignature !== cachedBodySkinSignature) {
11985
+ const nextSkinId = renderer.createSVGSkin(renderScratchBubbleSvg({
11986
+ kind,
11987
+ layout: scratchTextLayout,
11988
+ pointsLeft: scratchPointsLeft,
11989
+ title: `${currentStyle.name} ${kind} Bubble`
11990
+ }));
11991
+ if (!Number.isInteger(nextSkinId) || nextSkinId < 0) throw new BubbleRuntimeAdapterError("BUBBLE-RUNTIME-001", "TurboWarp did not create the Scratch-compatible Bubble SVG skin.");
11992
+ try {
11993
+ renderer.updateDrawableSkinId(body.drawableID, nextSkinId);
11994
+ } catch (error) {
11995
+ renderer.destroySkin(nextSkinId);
11996
+ throw error;
11997
+ }
11998
+ const previousBodySkinId = bodySkinId;
11999
+ bodySkinId = nextSkinId;
12000
+ cachedBodySkinSignature = nextBodySkinSignature;
12001
+ if (previousBodySkinId !== void 0) renderer.destroySkin(previousBodySkinId);
12002
+ }
12003
+ renderer.updateDrawableScale(body.drawableID, [100, 100]);
12004
+ renderer.updateDrawablePosition(body.drawableID, [nextPosition.centerX, nextPosition.centerY]);
12005
+ layoutPositions.set(body.drawableID, [nextPosition.centerX, nextPosition.centerY]);
12006
+ layoutScales.set(body.drawableID, [100, 100]);
12007
+ updateVisibility();
12008
+ return;
12009
+ }
11106
12010
  const scaleMultiplier = currentStyle.placement.basis === "actor" ? currentStyle.offset.scalePercent / 100 : 1;
11107
12011
  const nativeTextSize = reservedTextSize ?? readSize(renderer, text, {
11108
12012
  width: 180,
@@ -11133,10 +12037,11 @@
11133
12037
  };
11134
12038
  const totalWidth = portraitSize.width + (hasPortrait ? contentGap * scaleMultiplier : 0) + textSize.width;
11135
12039
  const contentHeight = Math.max(portraitSize.height, textSize.height);
11136
- const baseBubbleWidth = totalWidth / scaleMultiplier + 48;
11137
- const baseBubbleHeight = contentHeight / scaleMultiplier + 48;
11138
- const bubbleWidth = totalWidth;
11139
- const bubbleHeight = contentHeight;
12040
+ const minimumBodySize = bubbleBodyMinimumSize(currentStyle.visualStyle, ...shapeTransition === void 0 ? [] : [shapeTransition.from, shapeTransition.to]);
12041
+ const baseBubbleWidth = Math.max(totalWidth / scaleMultiplier + 48, minimumBodySize.width);
12042
+ const baseBubbleHeight = Math.max(contentHeight / scaleMultiplier + 48, minimumBodySize.height);
12043
+ const bubbleWidth = Math.max(totalWidth, (baseBubbleWidth - 48) * scaleMultiplier);
12044
+ const bubbleHeight = Math.max(contentHeight, (baseBubbleHeight - 48) * scaleMultiplier);
11140
12045
  const nativeSize = renderer.getNativeSize();
11141
12046
  const stageWidth = Array.isArray(nativeSize) && Number(nativeSize[0]) > 0 ? Number(nativeSize[0]) : 480;
11142
12047
  const stageHeight = Array.isArray(nativeSize) && Number(nativeSize[1]) > 0 ? Number(nativeSize[1]) : 360;
@@ -11309,7 +12214,9 @@
11309
12214
  originalVisualChange?.(changedTarget);
11310
12215
  position();
11311
12216
  };
12217
+ const nativeSizeHook = () => position();
11312
12218
  if (currentStyle.placement.basis === "actor") actor.onTargetVisualChange = visualChangeHook;
12219
+ renderer.on?.("NativeSizeChanged", nativeSizeHook);
11313
12220
  return Object.freeze({
11314
12221
  targets,
11315
12222
  setLayerVisible(layer, visible) {
@@ -11344,6 +12251,12 @@
11344
12251
  reservedTextSize = void 0;
11345
12252
  position();
11346
12253
  },
12254
+ renderScratchText(layout) {
12255
+ if (disposed) return;
12256
+ scratchTextLayout = layout;
12257
+ cachedBodySkinSignature = "";
12258
+ position();
12259
+ },
11347
12260
  async animate(motion) {
11348
12261
  if (disposed) return;
11349
12262
  const durationSeconds = Math.max(0, motion.durationSeconds ?? 0);
@@ -11466,6 +12379,7 @@
11466
12379
  dispose() {
11467
12380
  if (disposed) return;
11468
12381
  disposed = true;
12382
+ renderer.off?.("NativeSizeChanged", nativeSizeHook);
11469
12383
  if (currentStyle.placement.basis === "actor" && actor.onTargetVisualChange === visualChangeHook) actor.onTargetVisualChange = originalVisualChange ?? null;
11470
12384
  for (const target of [...drawables].reverse()) renderer.destroyDrawable(target.drawableID, spriteLayer);
11471
12385
  if (bodySkinId !== void 0) {
@@ -11491,10 +12405,20 @@
11491
12405
  const runtime = runtimeInput;
11492
12406
  const renderer = requireRenderer(runtime.renderer);
11493
12407
  const requestedBackend = normalizeRenderBackend(options.bubbleRenderBackend);
11494
- const overlayTextCapability = requestedBackend === "svg-overlay" ? options.svgOverlayTextCapability ?? createDefaultSvgOverlayTextCapability() : void 0;
12408
+ let overlayTextCapability;
12409
+ let overlayTextCapabilityError;
12410
+ if (requestedBackend === "svg-overlay") {
12411
+ if (options.svgOverlayTextCapability !== void 0) overlayTextCapability = options.svgOverlayTextCapability;
12412
+ else if (runtime.ext_kubohiroyasvgtext === void 0) overlayTextCapability = createDefaultSvgOverlayTextCapability();
12413
+ else try {
12414
+ overlayTextCapability = createTurboWarpSvgTextOverlayTextCapability(runtime.ext_kubohiroyasvgtext);
12415
+ } catch (error) {
12416
+ overlayTextCapabilityError = error instanceof Error ? error.message : String(error);
12417
+ }
12418
+ }
11495
12419
  const unsupportedBehavior = normalizeOverlayUnsupportedBehavior(options.svgOverlayUnsupportedBehavior);
11496
12420
  const overlayDocument = requestedBackend === "svg-overlay" ? resolveOverlayDocument(options.document) : void 0;
11497
- const unavailableReason = requestedBackend === "svg-overlay" ? overlayUnavailableReason(renderer, overlayDocument, overlayTextCapability) : void 0;
12421
+ const unavailableReason = requestedBackend === "svg-overlay" ? overlayTextCapabilityError ?? overlayUnavailableReason(renderer, overlayDocument, overlayTextCapability) : void 0;
11498
12422
  if (requestedBackend === "svg-overlay" && unavailableReason !== void 0 && unsupportedBehavior === "error") throw new BubbleRuntimeAdapterError("BUBBLE-RUNTIME-004", `Bubble SVG overlay backend is unavailable because ${unavailableReason}. Use scratch-render or install the required public upstream capability.`);
11499
12423
  const renderBackend = requestedBackend === "svg-overlay" && unavailableReason === void 0 ? "svg-overlay" : "scratch-render";
11500
12424
  const scheduler = options.scheduler ?? {
@@ -11502,6 +12426,11 @@
11502
12426
  clearTimeout: (handle) => globalThis.clearTimeout(handle)
11503
12427
  };
11504
12428
  const getAssetExtension = () => requireAssetManager(runtime.ext_kubohiroyaassetmanager);
12429
+ let assetManagerDOMImages;
12430
+ const getAssetManagerDOMImages = () => {
12431
+ assetManagerDOMImages ?? (assetManagerDOMImages = requireAssetManagerDOMImageCapability(runtime.ext_kubohiroyaassetmanager));
12432
+ return assetManagerDOMImages;
12433
+ };
11505
12434
  let textCapability;
11506
12435
  if (renderBackend === "svg-overlay") try {
11507
12436
  textCapability = createSvgOverlayTextAdapter(overlayTextCapability, renderer);
@@ -11510,18 +12439,27 @@
11510
12439
  }
11511
12440
  else if (options.textCapability !== void 0) textCapability = options.textCapability;
11512
12441
  else try {
11513
- textCapability = createTurboWarpSvgTextCapability(runtime.ext_kubohiroyasvgtext);
11514
- } catch {
11515
- throw new BubbleRuntimeAdapterError("BUBBLE-RUNTIME-003", "Bubble requires a text capability. Load @kubohiroya/turbowarp-svg-text or provide options.textCapability before using Bubble blocks.");
12442
+ textCapability = runtime.ext_kubohiroyasvgtext === void 0 ? createDefaultScratchRenderTextCapability(runtime) : createTurboWarpSvgTextCapability(runtime.ext_kubohiroyasvgtext);
12443
+ } catch (error) {
12444
+ throw new BubbleRuntimeAdapterError("BUBBLE-RUNTIME-003", `Bubble could not initialize the scratch-render text provider: ${error instanceof Error ? error.message : String(error)}`);
11516
12445
  }
11517
12446
  let imageResolver;
11518
- if (renderBackend === "svg-overlay") {
11519
- if (options.svgOverlayImageCapability !== void 0) try {
11520
- imageResolver = createSvgOverlayImageAdapter(options.svgOverlayImageCapability);
11521
- } catch (error) {
11522
- throw new BubbleRuntimeAdapterError("BUBBLE-RUNTIME-004", `Bubble SVG overlay image capability is invalid: ${error instanceof Error ? error.message : String(error)}`);
11523
- }
11524
- } else imageResolver = options.imageResolver ?? {
12447
+ if (renderBackend === "svg-overlay") try {
12448
+ imageResolver = createSvgOverlayImageAdapter(options.svgOverlayImageCapability ?? createAssetManagerSvgOverlayImageCapability(Object.freeze({
12449
+ isRegistered(name) {
12450
+ return getAssetManagerDOMImages().isRegistered(name);
12451
+ },
12452
+ getMimeType(name) {
12453
+ return getAssetManagerDOMImages().getMimeType(name);
12454
+ },
12455
+ resolveDOMImageResource(name) {
12456
+ return getAssetManagerDOMImages().resolveDOMImageResource(name);
12457
+ }
12458
+ })));
12459
+ } catch (error) {
12460
+ throw new BubbleRuntimeAdapterError("BUBBLE-RUNTIME-004", `Bubble SVG overlay image capability is invalid: ${error instanceof Error ? error.message : String(error)}`);
12461
+ }
12462
+ else imageResolver = options.imageResolver ?? {
11525
12463
  isRegistered(name) {
11526
12464
  return getAssetExtension().isLoaded({ NAME: name });
11527
12465
  },
@@ -11556,9 +12494,9 @@
11556
12494
  ...imageResolver === void 0 ? {} : { imageResolver },
11557
12495
  audio,
11558
12496
  textCapability,
11559
- createSurface({ actor, actorKey, style }) {
12497
+ createSurface({ actor, actorKey, kind, style }) {
11560
12498
  if (!isRecord(actor) || typeof actor.id !== "string") throw new BubbleRuntimeAdapterError("BUBBLE-RUNTIME-001", "Bubble actor target is invalid.");
11561
- return renderBackend === "svg-overlay" ? createSvgOverlaySurface(overlayManager, actor, actorKey, style, scheduler) : createSurface(runtime, actor, actorKey, style, scheduler);
12499
+ return renderBackend === "svg-overlay" ? createSvgOverlaySurface(overlayManager, actor, actorKey, kind, style, scheduler) : createSurface(runtime, actor, actorKey, kind, style, scheduler);
11562
12500
  },
11563
12501
  ...options.scheduler === void 0 ? {} : { scheduler: options.scheduler },
11564
12502
  ...options.onAnimationError === void 0 ? {} : { onAnimationError: options.onAnimationError }
@@ -11573,6 +12511,11 @@
11573
12511
  "talking",
11574
12512
  "awaiting-continue"
11575
12513
  ]);
12514
+ var validClosePolicyTriggers = /* @__PURE__ */ new Set([
12515
+ "condition",
12516
+ "timeout",
12517
+ "condition-or-timeout"
12518
+ ]);
11576
12519
  var validRevealUnits = /* @__PURE__ */ new Set([
11577
12520
  "CHARACTER",
11578
12521
  "WORD",
@@ -11604,8 +12547,15 @@
11604
12547
  "easeOut",
11605
12548
  "easeInOut"
11606
12549
  ]);
12550
+ var builtInBubbleStyles = Object.freeze([Object.freeze({
12551
+ name: "say",
12552
+ textStyle: "default"
12553
+ }), Object.freeze({
12554
+ name: "think",
12555
+ textStyle: "default"
12556
+ })]);
11607
12557
  var EXTENSION_DOCS_URI = "https://kubohiroya.github.io/turbowarp-bubble/";
11608
- var EXTENSION_VERSION = "0.8.0";
12558
+ var EXTENSION_VERSION = "0.10.0";
11609
12559
  var BLOCK_ICON_URI = `data:image/svg+xml,${encodeURIComponent("<svg xmlns=\"http://www.w3.org/2000/svg\" viewBox=\"0 0 64 64\"><path fill=\"none\" stroke=\"#fff\" stroke-width=\"5\" stroke-linecap=\"round\" stroke-linejoin=\"round\" d=\"M12 13h40a5 5 0 0 1 5 5v23a5 5 0 0 1-5 5H30L17 55v-9h-5a5 5 0 0 1-5-5V18a5 5 0 0 1 5-5Z\"/><g fill=\"#fff\"><circle cx=\"23\" cy=\"30\" r=\"3\"/><circle cx=\"32\" cy=\"30\" r=\"3\"/><circle cx=\"41\" cy=\"30\" r=\"3\"/></g></svg>")}`;
11610
12560
  function extensionError(message) {
11611
12561
  const error = /* @__PURE__ */ new Error(`[Bubble] ${message}`);
@@ -11616,7 +12566,8 @@
11616
12566
  constructor(runtime = Scratch.vm?.runtime, options = {}) {
11617
12567
  _defineProperty(this, "runtime", void 0);
11618
12568
  _defineProperty(this, "options", void 0);
11619
- _defineProperty(this, "styles", /* @__PURE__ */ new Map());
12569
+ _defineProperty(this, "styles", new Map(builtInBubbleStyles.map((style) => [style.name, style])));
12570
+ _defineProperty(this, "closePolicies", /* @__PURE__ */ new Map());
11620
12571
  _defineProperty(this, "handles", /* @__PURE__ */ new Map());
11621
12572
  _defineProperty(this, "waits", /* @__PURE__ */ new Map());
11622
12573
  _defineProperty(this, "waitScheduler", void 0);
@@ -11644,11 +12595,13 @@
11644
12595
  }
11645
12596
  getInfo() {
11646
12597
  return {
11647
- id: extensionConfig.id,
12598
+ id: extensionConfig$1.id,
11648
12599
  name: Scratch.translate(block_definitions_default$1.extensionName),
11649
12600
  docsURI: EXTENSION_DOCS_URI,
11650
12601
  blockIconURI: BLOCK_ICON_URI,
11651
12602
  color1: "#ff6680",
12603
+ color2: "#e64d6a",
12604
+ color3: "#b83255",
11652
12605
  blocks: blockDefinitions.map((block) => this.toScratchBlock(block)),
11653
12606
  menus: definitionMenus
11654
12607
  };
@@ -11661,6 +12614,23 @@
11661
12614
  });
11662
12615
  this.installStyle(style);
11663
12616
  }
12617
+ defineBubbleClosePolicy(args) {
12618
+ const name = this.requireName(args.POLICY, "close policy");
12619
+ const trigger = this.toString(args.TRIGGER).trim().toLowerCase();
12620
+ if (!validClosePolicyTriggers.has(trigger)) throw extensionError("close policy trigger must be condition, timeout, or condition-or-timeout.");
12621
+ const usesCondition = trigger !== "timeout";
12622
+ const usesTimeout = trigger !== "condition";
12623
+ const condition = usesCondition ? this.toString(args.CONDITION).trim() : void 0;
12624
+ if (usesCondition && !condition) throw extensionError("close policy condition is empty.");
12625
+ const timeoutSeconds = usesTimeout ? Scratch.Cast.toNumber(args.TIMEOUT) : void 0;
12626
+ if (usesTimeout && (!Number.isFinite(timeoutSeconds) || Number(timeoutSeconds) <= 0)) throw extensionError("close policy timeout must be greater than zero when enabled.");
12627
+ this.closePolicies.set(name, Object.freeze({
12628
+ name,
12629
+ trigger,
12630
+ ...condition === void 0 ? {} : { condition },
12631
+ ...timeoutSeconds === void 0 ? {} : { timeoutSeconds: Number(timeoutSeconds) }
12632
+ }));
12633
+ }
11664
12634
  setPortraitBase(args) {
11665
12635
  const style = this.requireStyle(args.STYLE);
11666
12636
  const base = this.toString(args.ASSET).trim();
@@ -11927,6 +12897,22 @@
11927
12897
  durationSeconds: seconds
11928
12898
  });
11929
12899
  }
12900
+ say(args, util) {
12901
+ return this.show("say", Object.freeze({
12902
+ MESSAGE: args.MESSAGE,
12903
+ STYLE: "say"
12904
+ }), util);
12905
+ }
12906
+ think(args, util) {
12907
+ return this.show("think", Object.freeze({
12908
+ MESSAGE: args.MESSAGE,
12909
+ STYLE: "think"
12910
+ }), util);
12911
+ }
12912
+ showWithBubbleStyle(args, util) {
12913
+ const style = this.requireStyle(args.STYLE);
12914
+ return this.show(style.name === "think" ? "think" : "say", args, util);
12915
+ }
11930
12916
  sayWithBubbleStyle(args, util) {
11931
12917
  return this.show("say", args, util);
11932
12918
  }
@@ -11949,43 +12935,33 @@
11949
12935
  if (!condition) throw extensionError("wait condition is empty.");
11950
12936
  const timeoutSeconds = Scratch.Cast.toNumber(args.TIMEOUT);
11951
12937
  if (!Number.isFinite(timeoutSeconds) || timeoutSeconds < 0) throw extensionError("wait timeout must be zero or greater.");
11952
- if (!this.isRecord(this.runtime.ext_kubohiroyaasyncinput)) throw extensionError("Bubble wait requires Async Input. Load @kubohiroya/turbowarp-async-input before using this block.");
11953
- const runtimeExpression = this.runtime.ext_kubohiroyaruntimeexpression;
11954
- if (!this.isRecord(runtimeExpression) || typeof runtimeExpression.runtimeCondition !== "function") throw extensionError("Bubble wait requires Runtime Expression. Load @kubohiroya/turbowarp-runtime-expression before using this block.");
11955
- if (typeof this.runtime.on !== "function" || typeof this.runtime.off !== "function") throw extensionError("TurboWarp runtime events are unavailable.");
11956
- this.cancelWait(target.id, "Bubble wait was replaced.");
11957
- await handle.setAnimationMode("awaiting-continue");
11958
- await new Promise((resolve, reject) => {
11959
- let settled = false;
11960
- let timeoutHandle;
11961
- const cleanup = () => {
11962
- this.runtime.off?.("BEFORE_EXECUTE", checkCondition);
11963
- if (timeoutHandle !== void 0) this.waitScheduler.clearTimeout(timeoutHandle);
11964
- if (this.waits.get(target.id) === pending) this.waits.delete(target.id);
11965
- };
11966
- const finish = (error) => {
11967
- if (settled) return;
11968
- settled = true;
11969
- cleanup();
11970
- if (error) {
11971
- reject(error);
11972
- return;
11973
- }
11974
- handle.setAnimationMode("idle").then(resolve, reject);
11975
- };
11976
- const checkCondition = () => {
11977
- try {
11978
- if (runtimeExpression.runtimeCondition({ EXPRESSION: condition })) finish();
11979
- } catch (error) {
11980
- finish(error instanceof Error ? error : extensionError("wait condition evaluation failed."));
11981
- }
11982
- };
11983
- const pending = Object.freeze({ cancel: finish });
11984
- this.waits.set(target.id, pending);
11985
- this.runtime.on?.("BEFORE_EXECUTE", checkCondition);
11986
- if (timeoutSeconds > 0) timeoutHandle = this.waitScheduler.setTimeout(() => finish(), timeoutSeconds * 1e3);
11987
- checkCondition();
12938
+ await this.waitForBubbleTrigger({
12939
+ targetId: target.id,
12940
+ handle,
12941
+ condition,
12942
+ ...timeoutSeconds === 0 ? {} : { timeoutSeconds },
12943
+ setAwaitingContinue: true,
12944
+ restoreIdle: true,
12945
+ requireAsyncInput: true
12946
+ });
12947
+ }
12948
+ async waitAndCloseBubbleWithPolicy(args, util) {
12949
+ const target = this.requireTarget(util);
12950
+ const handle = this.handles.get(target.id);
12951
+ if (!handle) throw extensionError("this target does not have an active bubble.");
12952
+ const policy = this.requireClosePolicy(args.POLICY);
12953
+ const usesCondition = policy.condition !== void 0;
12954
+ await this.waitForBubbleTrigger({
12955
+ targetId: target.id,
12956
+ handle,
12957
+ ...policy.condition === void 0 ? {} : { condition: policy.condition },
12958
+ ...policy.timeoutSeconds === void 0 ? {} : { timeoutSeconds: policy.timeoutSeconds },
12959
+ setAwaitingContinue: usesCondition,
12960
+ restoreIdle: false,
12961
+ requireAsyncInput: usesCondition
11988
12962
  });
12963
+ if (this.handles.get(target.id) !== handle) throw this.abortError("Bubble was replaced before it could close.");
12964
+ await this.releaseOwnedTarget(target.id);
11989
12965
  }
11990
12966
  async finishBubbleReveal(args, util) {
11991
12967
  const handle = this.requireHandle(util);
@@ -12023,12 +12999,63 @@
12023
12999
  if (this.composition) await this.composition.dispose();
12024
13000
  this.handles.clear();
12025
13001
  this.styles.clear();
13002
+ this.closePolicies.clear();
13003
+ }
13004
+ async waitForBubbleTrigger(input) {
13005
+ let runtimeExpression;
13006
+ if (input.condition !== void 0) {
13007
+ if (input.requireAsyncInput && !this.isRecord(this.runtime.ext_kubohiroyaasyncinput)) throw extensionError("Bubble wait requires Async Input. Load @kubohiroya/turbowarp-async-input before using this block.");
13008
+ const candidate = this.runtime.ext_kubohiroyaruntimeexpression;
13009
+ if (!this.isRecord(candidate) || typeof candidate.runtimeCondition !== "function") throw extensionError("Bubble wait requires Runtime Expression. Load @kubohiroya/turbowarp-runtime-expression before using this block.");
13010
+ if (typeof this.runtime.on !== "function" || typeof this.runtime.off !== "function") throw extensionError("TurboWarp runtime events are unavailable.");
13011
+ runtimeExpression = candidate;
13012
+ }
13013
+ if (input.condition === void 0 && input.timeoutSeconds === void 0) throw extensionError("Bubble wait does not have an enabled trigger.");
13014
+ this.cancelWait(input.targetId, "Bubble wait was replaced.");
13015
+ if (input.setAwaitingContinue) await input.handle.setAnimationMode("awaiting-continue");
13016
+ await new Promise((resolve, reject) => {
13017
+ let settled = false;
13018
+ let timeoutHandle;
13019
+ const checkCondition = () => {
13020
+ if (input.condition === void 0 || runtimeExpression === void 0) return;
13021
+ try {
13022
+ if (runtimeExpression.runtimeCondition({ EXPRESSION: input.condition })) finish();
13023
+ } catch (error) {
13024
+ finish(error instanceof Error ? error : extensionError("wait condition evaluation failed."));
13025
+ }
13026
+ };
13027
+ const cleanup = () => {
13028
+ if (input.condition !== void 0) this.runtime.off?.("BEFORE_EXECUTE", checkCondition);
13029
+ if (timeoutHandle !== void 0) this.waitScheduler.clearTimeout(timeoutHandle);
13030
+ if (this.waits.get(input.targetId) === pending) this.waits.delete(input.targetId);
13031
+ };
13032
+ const finish = (error) => {
13033
+ if (settled) return;
13034
+ settled = true;
13035
+ cleanup();
13036
+ if (error) {
13037
+ reject(error);
13038
+ return;
13039
+ }
13040
+ if (!input.restoreIdle) {
13041
+ resolve();
13042
+ return;
13043
+ }
13044
+ input.handle.setAnimationMode("idle").then(resolve, reject);
13045
+ };
13046
+ const pending = Object.freeze({ cancel: finish });
13047
+ this.waits.set(input.targetId, pending);
13048
+ if (input.condition !== void 0) this.runtime.on?.("BEFORE_EXECUTE", checkCondition);
13049
+ if (input.timeoutSeconds !== void 0) timeoutHandle = this.waitScheduler.setTimeout(() => finish(), input.timeoutSeconds * 1e3);
13050
+ checkCondition();
13051
+ });
12026
13052
  }
12027
13053
  toScratchBlock(block) {
12028
13054
  return {
12029
13055
  opcode: block.opcode,
12030
13056
  blockType: Scratch.BlockType[block.blockType],
12031
13057
  text: Scratch.translate(block.text),
13058
+ ...block.hideFromPalette === true ? { hideFromPalette: true } : {},
12032
13059
  arguments: Object.fromEntries(Object.entries(block.arguments).map(([name, argument]) => [name, {
12033
13060
  type: Scratch.ArgumentType[argument.type],
12034
13061
  defaultValue: argument.defaultValue,
@@ -12064,6 +13091,12 @@
12064
13091
  if (!style) throw extensionError(`bubble style is not defined: ${name}`);
12065
13092
  return style;
12066
13093
  }
13094
+ requireClosePolicy(value) {
13095
+ const name = this.requireName(value, "close policy");
13096
+ const policy = this.closePolicies.get(name);
13097
+ if (!policy) throw extensionError(`bubble close policy is not defined: ${name}`);
13098
+ return policy;
13099
+ }
12067
13100
  normalizeTransformNumber(value, normalize) {
12068
13101
  try {
12069
13102
  return normalize(Scratch.Cast.toNumber(value));
@@ -12153,6 +13186,12 @@
12153
13186
  const placement = normalizeBubblePlacement(style.placement ?? "up-right");
12154
13187
  if (target.isStage && placement.basis === "actor") throw extensionError("actor-relative bubble placement requires a sprite or clone.");
12155
13188
  this.cancelWait(target.id, "Bubble wait was replaced.");
13189
+ const scratchDefault = isScratchDefaultBubbleStyleInput(style);
13190
+ const message = scratchDefault ? formatScratchBubbleArgument(args.MESSAGE) : this.toString(args.MESSAGE);
13191
+ if (scratchDefault && message === "") {
13192
+ await this.releaseOwnedTarget(target.id);
13193
+ return;
13194
+ }
12156
13195
  const composition = this.getComposition();
12157
13196
  let handle;
12158
13197
  try {
@@ -12160,7 +13199,7 @@
12160
13199
  actor: target,
12161
13200
  actorKey: target.id,
12162
13201
  kind,
12163
- text: this.toString(args.MESSAGE),
13202
+ text: message,
12164
13203
  styleName: style.name
12165
13204
  });
12166
13205
  } catch (error) {
@@ -12177,7 +13216,7 @@
12177
13216
  };
12178
13217
  //#endregion
12179
13218
  //#region src/index.ts
12180
- if (extensionConfig.unsandboxed && !Scratch.extensions.unsandboxed) throw new Error(`${extensionConfig.name} must run unsandboxed.`);
13219
+ if (extensionConfig$1.unsandboxed && !Scratch.extensions.unsandboxed) throw new Error(`${extensionConfig$1.name} must run unsandboxed.`);
12181
13220
  Scratch.extensions.register(new BubbleExtension());
12182
13221
  //#endregion
12183
13222