@kubohiroya/turbowarp-bubble 0.7.0 → 0.9.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",
@@ -40,14 +40,14 @@
40
40
  license: "MPL-2.0",
41
41
  unsandboxed: true
42
42
  };
43
- var block_definitions_default = {
43
+ var block_definitions_default$1 = {
44
44
  extensionName: "Bubble",
45
45
  blocks: [
46
46
  {
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 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",
@@ -145,7 +145,7 @@
145
145
  "opcode": "setBubbleVisualStyle",
146
146
  "blockType": "COMMAND",
147
147
  "text": "set bubble visual style [VISUAL_STYLE] for bubble style [STYLE]",
148
- "description": "Sets the SVG body shape used by this bubble style.",
148
+ "description": "Sets the inseparable SVG body and tail or trail shape pair used by this bubble style.",
149
149
  "arguments": {
150
150
  "VISUAL_STYLE": {
151
151
  "type": "STRING",
@@ -474,11 +474,48 @@
474
474
  }
475
475
  }
476
476
  },
477
+ {
478
+ "opcode": "say",
479
+ "blockType": "COMMAND",
480
+ "text": "say [MESSAGE]",
481
+ "description": "Shows or replaces this sprite's Scratch-compatible default say bubble. An empty message closes it.",
482
+ "arguments": { "MESSAGE": {
483
+ "type": "STRING",
484
+ "defaultValue": "Hello!"
485
+ } }
486
+ },
487
+ {
488
+ "opcode": "think",
489
+ "blockType": "COMMAND",
490
+ "text": "think [MESSAGE]",
491
+ "description": "Shows or replaces this sprite's Scratch-compatible default think bubble. An empty message closes it.",
492
+ "arguments": { "MESSAGE": {
493
+ "type": "STRING",
494
+ "defaultValue": "Hmm..."
495
+ } }
496
+ },
497
+ {
498
+ "opcode": "showWithBubbleStyle",
499
+ "blockType": "COMMAND",
500
+ "text": "show [MESSAGE] with bubble style [STYLE]",
501
+ "description": "Shows or replaces this sprite's Bubble. The selected style determines the complete body and tail or trail shape.",
502
+ "arguments": {
503
+ "MESSAGE": {
504
+ "type": "STRING",
505
+ "defaultValue": "Hello!"
506
+ },
507
+ "STYLE": {
508
+ "type": "STRING",
509
+ "defaultValue": "say"
510
+ }
511
+ }
512
+ },
477
513
  {
478
514
  "opcode": "sayWithBubbleStyle",
479
515
  "blockType": "COMMAND",
480
516
  "text": "say [MESSAGE] with bubble style [STYLE]",
481
- "description": "Shows or replaces this sprite's layered say bubble in talking animation mode.",
517
+ "description": "Shows or replaces this sprite's say bubble in talking animation mode. An empty message closes the basic profile.",
518
+ "hideFromPalette": true,
482
519
  "arguments": {
483
520
  "MESSAGE": {
484
521
  "type": "STRING",
@@ -494,7 +531,8 @@
494
531
  "opcode": "thinkWithBubbleStyle",
495
532
  "blockType": "COMMAND",
496
533
  "text": "think [MESSAGE] with bubble style [STYLE]",
497
- "description": "Shows or replaces this sprite's layered think bubble in talking animation mode.",
534
+ "description": "Shows or replaces this sprite's think bubble in talking animation mode. An empty message closes the basic profile.",
535
+ "hideFromPalette": true,
498
536
  "arguments": {
499
537
  "MESSAGE": {
500
538
  "type": "STRING",
@@ -537,7 +575,7 @@
537
575
  "opcode": "closeBubble",
538
576
  "blockType": "COMMAND",
539
577
  "text": "close this bubble",
540
- "description": "Closes this sprite's bubble and releases its timers, SVG text skin, and drawables.",
578
+ "description": "Closes this sprite's bubble and releases its timers and rendering resources.",
541
579
  "arguments": {}
542
580
  },
543
581
  {
@@ -6005,7 +6043,18 @@
6005
6043
  "NARRATION",
6006
6044
  "NO_BUBBLE"
6007
6045
  ]);
6008
- function escapeXml(value) {
6046
+ var cloudBodyMinimumSize = Object.freeze({
6047
+ height: 96,
6048
+ width: 176
6049
+ });
6050
+ var emptyBodyMinimumSize = Object.freeze({
6051
+ height: 0,
6052
+ width: 0
6053
+ });
6054
+ function bubbleBodyMinimumSize(...styles) {
6055
+ return styles.some((style) => style === "THINKING" || style === "DREAMING") ? cloudBodyMinimumSize : emptyBodyMinimumSize;
6056
+ }
6057
+ function escapeXml$2(value) {
6009
6058
  return value.replaceAll("&", "&amp;").replaceAll("<", "&lt;").replaceAll(">", "&gt;").replaceAll("\"", "&quot;").replaceAll("'", "&apos;");
6010
6059
  }
6011
6060
  function requireDimension(value, fallback) {
@@ -6196,22 +6245,56 @@
6196
6245
  if (!outer) throw new Error("JSClipper returned an empty Bubble outline.");
6197
6246
  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
6247
  }
6248
+ function smoothClosedPath(points) {
6249
+ const first = points[0];
6250
+ if (!first || points.length < 3) throw new TypeError("Smooth Bubble path requires at least three points.");
6251
+ const format = (value) => value.toFixed(4);
6252
+ const segments = points.map((current, index) => {
6253
+ const previous = points[(index - 1 + points.length) % points.length];
6254
+ const next = points[(index + 1) % points.length];
6255
+ const afterNext = points[(index + 2) % points.length];
6256
+ if (!previous || !next || !afterNext) throw new Error("Smooth Bubble path is invalid.");
6257
+ const firstControl = {
6258
+ x: current.x + (next.x - previous.x) / 6,
6259
+ y: current.y + (next.y - previous.y) / 6
6260
+ };
6261
+ const secondControl = {
6262
+ x: next.x - (afterNext.x - current.x) / 6,
6263
+ y: next.y - (afterNext.y - current.y) / 6
6264
+ };
6265
+ return `C ${format(firstControl.x)} ${format(firstControl.y)} ${format(secondControl.x)} ${format(secondControl.y)} ${format(next.x)} ${format(next.y)}`;
6266
+ });
6267
+ return `M ${format(first.x)} ${format(first.y)} ${segments.join(" ")} Z`;
6268
+ }
6199
6269
  function cloudBody(width, height, fill, border) {
6270
+ const x = 24;
6200
6271
  const y = 24;
6201
6272
  const right = width - 24;
6202
6273
  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"/>`;
6274
+ const bodyWidth = right - x;
6275
+ const bodyHeight = bottom - y;
6276
+ const point = (xRatio, yRatio) => ({
6277
+ x: x + bodyWidth * xRatio,
6278
+ y: y + bodyHeight * yRatio
6279
+ });
6280
+ return `<path d="${smoothClosedPath([
6281
+ point(0, .5),
6282
+ point(.03, .3),
6283
+ point(.18, .2),
6284
+ point(.28, .04),
6285
+ point(.5, .16),
6286
+ point(.68, .03),
6287
+ point(.84, .18),
6288
+ point(.98, .3),
6289
+ point(1, .52),
6290
+ point(.95, .7),
6291
+ point(.82, .82),
6292
+ point(.68, .97),
6293
+ point(.5, .84),
6294
+ point(.32, .97),
6295
+ point(.18, .82),
6296
+ point(.03, .7)
6297
+ ])}" fill="${fill}" stroke="${border}" stroke-width="3" stroke-linejoin="round"/>`;
6215
6298
  }
6216
6299
  function thoughtTrail(body, bodyCenter, tip, fill, border, dreaming) {
6217
6300
  const tipVector = subtract(tip, bodyCenter);
@@ -6306,8 +6389,9 @@
6306
6389
  return roundedRectanglePoints(width, height);
6307
6390
  }
6308
6391
  function bubbleBodyCenterOffset(input) {
6309
- const width = requireDimension(input.width, 220);
6310
- const height = requireDimension(input.height, 112);
6392
+ const minimumSize = bubbleBodyMinimumSize(input.style);
6393
+ const width = Math.max(requireDimension(input.width, 220), minimumSize.width);
6394
+ const height = Math.max(requireDimension(input.height, 112), minimumSize.height);
6311
6395
  const direction = normalizeDirection(input.tailDirection);
6312
6396
  if (direction === null) throw new TypeError("Bubble body center offset requires a tail direction.");
6313
6397
  const tailLength = normalizeSvgTailLength(input.tailLength ?? svgDefaultTailLength);
@@ -6364,8 +6448,8 @@
6364
6448
  function renderBubbleSvg(input) {
6365
6449
  if (!bubbleVisualStyles.includes(input.style)) throw new TypeError(`Unsupported Bubble visual style: ${String(input.style)}`);
6366
6450
  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);
6451
+ const requestedWidth = requireDimension(input.width, 220);
6452
+ const requestedHeight = requireDimension(input.height, 112);
6369
6453
  const fontSize = requireDimension(input.fontSize, 15);
6370
6454
  const direction = normalizeDirection(input.tailDirection);
6371
6455
  const tailLength = normalizeSvgTailLength(input.tailLength ?? svgDefaultTailLength);
@@ -6374,6 +6458,9 @@
6374
6458
  if (shapeTransition !== void 0) {
6375
6459
  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
6460
  }
6461
+ const minimumSize = bubbleBodyMinimumSize(input.style, ...shapeTransition === void 0 ? [] : [shapeTransition.from, shapeTransition.to]);
6462
+ const width = Math.max(requestedWidth, minimumSize.width);
6463
+ const height = Math.max(requestedHeight, minimumSize.height);
6377
6464
  const fill = input.fillColor ?? "#fff4cc";
6378
6465
  const border = input.borderColor ?? "#6f5b45";
6379
6466
  const textColor = input.textColor ?? "#25283a";
@@ -6385,11 +6472,11 @@
6385
6472
  x: width / 2,
6386
6473
  y: height / 2
6387
6474
  } : 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("");
6475
+ 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
6476
  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`);
6477
+ const title = escapeXml$2(input.title ?? `${input.style} bubble`);
6391
6478
  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>`;
6479
+ 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
6480
  }
6394
6481
  //#endregion
6395
6482
  //#region node_modules/.pnpm/@cto.af+unicode-trie-runtime@3.2.9/node_modules/@cto.af/unicode-trie-runtime/constants.js
@@ -8480,6 +8567,144 @@
8480
8567
  if (typeof value !== "number" || !Number.isFinite(value) || value < 0) throw new TypeError("Bubble portrait corner radius must be zero or greater.");
8481
8568
  return value;
8482
8569
  }
8570
+ var scratchDefaultOptionalStyleKeys = Object.freeze([
8571
+ "placement",
8572
+ "maxWidth",
8573
+ "textLocale",
8574
+ "distance",
8575
+ "tailLength",
8576
+ "offset",
8577
+ "visualStyle",
8578
+ "portrait",
8579
+ "continueIndicator",
8580
+ "reveal",
8581
+ "audio",
8582
+ "showAnimation",
8583
+ "hideAnimation"
8584
+ ]);
8585
+ function isRecord$6(value) {
8586
+ return typeof value === "object" && value !== null && !Array.isArray(value);
8587
+ }
8588
+ /**
8589
+ * The block-level basic style is intentionally narrow. Any explicit layout,
8590
+ * body, media, reveal, or motion option selects the existing custom renderer.
8591
+ */
8592
+ function bubbleLayoutProfileForStyleInput(value) {
8593
+ if (!isRecord$6(value)) return "custom";
8594
+ if (typeof value.textStyle !== "string" || value.textStyle.trim() !== "default") return "custom";
8595
+ return scratchDefaultOptionalStyleKeys.every((key) => value[key] === void 0) ? "scratch-default" : "custom";
8596
+ }
8597
+ function isScratchDefaultBubbleStyleInput(value) {
8598
+ return bubbleLayoutProfileForStyleInput(value) === "scratch-default";
8599
+ }
8600
+ /** Matches the numeric presentation and length limit used by say/think. */
8601
+ function formatScratchBubbleArgument(value) {
8602
+ let formatted = value;
8603
+ if (typeof value === "number" && Math.abs(value) >= .01 && value % 1 !== 0) formatted = value.toFixed(2);
8604
+ return String(formatted).slice(0, 330);
8605
+ }
8606
+ function estimatedHelveticaWidth(text) {
8607
+ let units = 0;
8608
+ for (const character of text) {
8609
+ if (/\p{Mark}/u.test(character)) continue;
8610
+ if (/\s/u.test(character)) {
8611
+ units += .35;
8612
+ continue;
8613
+ }
8614
+ units += (character.codePointAt(0) ?? 0) <= 127 ? .62 : 1;
8615
+ }
8616
+ return units * 14;
8617
+ }
8618
+ function layoutScratchBubbleText(value, measureText = estimatedHelveticaWidth) {
8619
+ const text = value.slice(0, 330);
8620
+ const measured = (candidate) => {
8621
+ let width;
8622
+ try {
8623
+ width = measureText(candidate);
8624
+ } catch {
8625
+ return estimatedHelveticaWidth(candidate);
8626
+ }
8627
+ return Number.isFinite(width) && width >= 0 ? width : estimatedHelveticaWidth(candidate);
8628
+ };
8629
+ const wrapped = wrapText({
8630
+ text,
8631
+ maxWidth: 170,
8632
+ measureText: measured
8633
+ });
8634
+ const lines = Object.freeze(wrapped.lines.map((line) => Object.freeze({
8635
+ text: line.text,
8636
+ width: line.width
8637
+ })));
8638
+ return Object.freeze({
8639
+ lines,
8640
+ maxLineWidth: Math.max(0, ...lines.map((line) => line.width)),
8641
+ text: lines.map((line) => line.text).join("\n")
8642
+ });
8643
+ }
8644
+ function scratchBubbleMetrics(layout) {
8645
+ const lineCount = Math.max(1, layout.lines.length);
8646
+ const paddedWidth = Math.max(layout.maxLineWidth, 50) + 20;
8647
+ const paddedHeight = 16 * lineCount + 20;
8648
+ return Object.freeze({
8649
+ bodyHeight: paddedHeight + 4,
8650
+ bodyWidth: paddedWidth + 4,
8651
+ height: paddedHeight + 4 + 12,
8652
+ paddedHeight,
8653
+ paddedWidth,
8654
+ width: paddedWidth + 4
8655
+ });
8656
+ }
8657
+ function positionScratchBubble(input) {
8658
+ const stageLeft = -input.stageWidth / 2;
8659
+ const stageRight = input.stageWidth / 2;
8660
+ const stageTop = input.stageHeight / 2;
8661
+ let pointsLeft = input.pointsLeft;
8662
+ if (!pointsLeft && input.width + input.bounds.right > stageRight && input.bounds.left - input.width > stageLeft) pointsLeft = true;
8663
+ else if (pointsLeft && input.bounds.left - input.width < stageLeft && input.width + input.bounds.right < stageRight) pointsLeft = false;
8664
+ 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));
8665
+ const top = Math.min(stageTop, input.bounds.bottom + input.height);
8666
+ return Object.freeze({
8667
+ centerX: left + input.width / 2,
8668
+ centerY: top - input.height / 2,
8669
+ left,
8670
+ pointsLeft,
8671
+ top
8672
+ });
8673
+ }
8674
+ function escapeXml$1(value) {
8675
+ return value.replaceAll("&", "&amp;").replaceAll("<", "&lt;").replaceAll(">", "&gt;").replaceAll("\"", "&quot;").replaceAll("'", "&apos;");
8676
+ }
8677
+ function scratchBodyPath(metrics) {
8678
+ const { paddedHeight: height, paddedWidth: width } = metrics;
8679
+ const radius = Math.min(16, width / 2, height / 2);
8680
+ return [
8681
+ `M ${radius} ${height}`,
8682
+ `Q 0 ${height} 0 ${height - radius}`,
8683
+ `L 0 ${radius}`,
8684
+ `Q 0 0 ${radius} 0`,
8685
+ `L ${width - radius} 0`,
8686
+ `Q ${width} 0 ${width} ${radius}`,
8687
+ `L ${width} ${height - radius}`,
8688
+ `Q ${width} ${height} ${width - radius} ${height}`
8689
+ ].join(" ");
8690
+ }
8691
+ function scratchSayBody(metrics) {
8692
+ const { paddedHeight: height, paddedWidth: width } = metrics;
8693
+ 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"/>`;
8694
+ }
8695
+ function scratchThinkBody(metrics) {
8696
+ const { paddedHeight: height, paddedWidth: width } = metrics;
8697
+ 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"/>`;
8698
+ }
8699
+ function renderScratchBubbleSvg(input) {
8700
+ const metrics = scratchBubbleMetrics(input.layout);
8701
+ const body = input.kind === "say" ? scratchSayBody(metrics) : scratchThinkBody(metrics);
8702
+ const bodyTransform = input.pointsLeft ? `translate(2 2)` : `translate(${metrics.width} 0) scale(-1 1) translate(2 2)`;
8703
+ const firstBaseline = 24.6;
8704
+ 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("");
8705
+ const title = escapeXml$1(input.title ?? `${input.kind} bubble`);
8706
+ 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>`;
8707
+ }
8483
8708
  //#endregion
8484
8709
  //#region src/composition.ts
8485
8710
  var BubbleCompositionError = class extends Error {
@@ -8515,16 +8740,16 @@
8515
8740
  "easeOut",
8516
8741
  "easeInOut"
8517
8742
  ]);
8518
- function isRecord$2(value) {
8743
+ function isRecord$5(value) {
8519
8744
  return typeof value === "object" && value !== null && !Array.isArray(value);
8520
8745
  }
8521
- function requireExactKeys(value, required, optional, label) {
8746
+ function requireExactKeys$1(value, required, optional, label) {
8522
8747
  const allowed = /* @__PURE__ */ new Set([...required, ...optional]);
8523
8748
  const missing = required.filter((key) => !Object.prototype.hasOwnProperty.call(value, key));
8524
8749
  const unknown = Object.keys(value).filter((key) => !allowed.has(key));
8525
8750
  if (missing.length > 0 || unknown.length > 0) throw new BubbleCompositionError("BUBBLE-COMPOSITION-001", `${label} has missing or unknown properties.`);
8526
8751
  }
8527
- function requireName(value, label) {
8752
+ function requireName$1(value, label) {
8528
8753
  if (typeof value !== "string" || value.trim().length === 0) throw new BubbleCompositionError("BUBBLE-COMPOSITION-001", `${label} must be a non-empty string.`);
8529
8754
  return value.trim();
8530
8755
  }
@@ -8533,8 +8758,8 @@
8533
8758
  return value;
8534
8759
  }
8535
8760
  function normalizeAnimation(value, label, minimumFrames) {
8536
- if (!isRecord$2(value)) throw new BubbleCompositionError("BUBBLE-COMPOSITION-001", `${label} must be an object.`);
8537
- requireExactKeys(value, ["frames", "frameIntervalSeconds"], [], label);
8761
+ if (!isRecord$5(value)) throw new BubbleCompositionError("BUBBLE-COMPOSITION-001", `${label} must be an object.`);
8762
+ requireExactKeys$1(value, ["frames", "frameIntervalSeconds"], [], label);
8538
8763
  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
8764
  const frames = Object.freeze(value.frames.map((frame, index) => requireAssetName(frame, `${label}.frames[${index}]`)));
8540
8765
  const interval = value.frameIntervalSeconds;
@@ -8545,8 +8770,8 @@
8545
8770
  });
8546
8771
  }
8547
8772
  function normalizePortrait(value) {
8548
- if (!isRecord$2(value)) throw new BubbleCompositionError("BUBBLE-COMPOSITION-001", "Bubble portrait must be an object.");
8549
- requireExactKeys(value, ["base"], [
8773
+ if (!isRecord$5(value)) throw new BubbleCompositionError("BUBBLE-COMPOSITION-001", "Bubble portrait must be an object.");
8774
+ requireExactKeys$1(value, ["base"], [
8550
8775
  "blink",
8551
8776
  "lipSync",
8552
8777
  "placement",
@@ -8575,8 +8800,8 @@
8575
8800
  });
8576
8801
  }
8577
8802
  function normalizeMotion(value, label) {
8578
- if (!isRecord$2(value)) throw new BubbleCompositionError("BUBBLE-COMPOSITION-001", `${label} must be an object.`);
8579
- requireExactKeys(value, ["name"], [
8803
+ if (!isRecord$5(value)) throw new BubbleCompositionError("BUBBLE-COMPOSITION-001", `${label} must be an object.`);
8804
+ requireExactKeys$1(value, ["name"], [
8580
8805
  "durationSeconds",
8581
8806
  "ease",
8582
8807
  "direction",
@@ -8615,8 +8840,8 @@
8615
8840
  }
8616
8841
  function normalizeAudio(value) {
8617
8842
  if (value === void 0) return void 0;
8618
- if (!isRecord$2(value)) throw new BubbleCompositionError("BUBBLE-COMPOSITION-001", "Bubble audio must be an object.");
8619
- requireExactKeys(value, [], [
8843
+ if (!isRecord$5(value)) throw new BubbleCompositionError("BUBBLE-COMPOSITION-001", "Bubble audio must be an object.");
8844
+ requireExactKeys$1(value, [], [
8620
8845
  "voice",
8621
8846
  "reveal",
8622
8847
  "finish"
@@ -8633,8 +8858,8 @@
8633
8858
  return Object.freeze(result);
8634
8859
  }
8635
8860
  function normalizeStyle(value) {
8636
- if (!isRecord$2(value)) throw new BubbleCompositionError("BUBBLE-COMPOSITION-001", "Bubble style must be an object.");
8637
- requireExactKeys(value, ["name", "textStyle"], [
8861
+ if (!isRecord$5(value)) throw new BubbleCompositionError("BUBBLE-COMPOSITION-001", "Bubble style must be an object.");
8862
+ requireExactKeys$1(value, ["name", "textStyle"], [
8638
8863
  "placement",
8639
8864
  "maxWidth",
8640
8865
  "textLocale",
@@ -8683,10 +8908,12 @@
8683
8908
  if (typeof value.maxWidth !== "number" || !Number.isFinite(value.maxWidth) || value.maxWidth <= 0) throw new BubbleCompositionError("BUBBLE-COMPOSITION-001", "Bubble style maxWidth must be a positive finite number.");
8684
8909
  maxWidth = value.maxWidth;
8685
8910
  }
8686
- const textLocale = value.textLocale === void 0 ? void 0 : requireName(value.textLocale, "Bubble style text locale");
8911
+ const textLocale = value.textLocale === void 0 ? void 0 : requireName$1(value.textLocale, "Bubble style text locale");
8912
+ const layoutProfile = bubbleLayoutProfileForStyleInput(value);
8687
8913
  return Object.freeze({
8688
- name: requireName(value.name, "Bubble style name"),
8689
- textStyle: requireName(value.textStyle, "Bubble text style name"),
8914
+ name: requireName$1(value.name, "Bubble style name"),
8915
+ textStyle: requireName$1(value.textStyle, "Bubble text style name"),
8916
+ layoutProfile,
8690
8917
  ...maxWidth === void 0 ? {} : { maxWidth },
8691
8918
  ...textLocale === void 0 ? {} : { textLocale },
8692
8919
  placement,
@@ -8704,12 +8931,12 @@
8704
8931
  }
8705
8932
  function validateImageResolver(value) {
8706
8933
  if (value === void 0) return void 0;
8707
- if (!isRecord$2(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.");
8934
+ 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
8935
  return value;
8709
8936
  }
8710
8937
  function validateAudioCapability(value) {
8711
8938
  if (value === void 0) return void 0;
8712
- if (!isRecord$2(value) || typeof value.playSound !== "function") throw new TypeError("Bubble audio capability must provide playSound.");
8939
+ if (!isRecord$5(value) || typeof value.playSound !== "function") throw new TypeError("Bubble audio capability must provide playSound.");
8713
8940
  if (value.isRegistered !== void 0 && typeof value.isRegistered !== "function") throw new TypeError("Bubble audio capability isRegistered must be a function.");
8714
8941
  if (value.getMimeType !== void 0 && typeof value.getMimeType !== "function") throw new TypeError("Bubble audio capability getMimeType must be a function.");
8715
8942
  return value;
@@ -8719,7 +8946,7 @@
8719
8946
  return value;
8720
8947
  }
8721
8948
  function validateTextCapability(value) {
8722
- if (!isRecord$2(value) || typeof value.setText !== "function" || typeof value.releaseTarget !== "function") throw new TypeError("Bubble text capability must provide setText and releaseTarget.");
8949
+ if (!isRecord$5(value) || typeof value.setText !== "function" || typeof value.releaseTarget !== "function") throw new TypeError("Bubble text capability must provide setText and releaseTarget.");
8723
8950
  return value;
8724
8951
  }
8725
8952
  function defaultScheduler() {
@@ -8729,11 +8956,11 @@
8729
8956
  });
8730
8957
  }
8731
8958
  function validateScheduler(value) {
8732
- if (!isRecord$2(value) || typeof value.setTimeout !== "function" || typeof value.clearTimeout !== "function") throw new TypeError("Bubble scheduler must provide setTimeout and clearTimeout.");
8959
+ if (!isRecord$5(value) || typeof value.setTimeout !== "function" || typeof value.clearTimeout !== "function") throw new TypeError("Bubble scheduler must provide setTimeout and clearTimeout.");
8733
8960
  return value;
8734
8961
  }
8735
8962
  function validateAssetTarget(value, label) {
8736
- if (!isRecord$2(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.`);
8963
+ 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
8964
  return value;
8738
8965
  }
8739
8966
  function validateTextTarget(value) {
@@ -8741,7 +8968,7 @@
8741
8968
  return value;
8742
8969
  }
8743
8970
  function validateSurface(value, style) {
8744
- if (!isRecord$2(value) || !isRecord$2(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.");
8971
+ 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
8972
  const targets = value.targets;
8746
8973
  validateTextTarget(targets.text);
8747
8974
  const assetTargetIds = /* @__PURE__ */ new Set();
@@ -8777,6 +9004,10 @@
8777
9004
  ], ...style.continueIndicator?.frames ?? []];
8778
9005
  }
8779
9006
  function formatBubbleText(text, style, textCapability) {
9007
+ if (style.layoutProfile === "scratch-default") return layoutScratchBubbleText(text, (candidate) => typeof textCapability.measureText === "function" ? textCapability.measureText({
9008
+ styleName: style.textStyle,
9009
+ text: candidate
9010
+ }) : NaN).text;
8780
9011
  if (style.maxWidth === void 0) return text;
8781
9012
  if (typeof textCapability.measureText !== "function") throw new BubbleCompositionError("BUBBLE-COMPOSITION-007", "Bubble style maxWidth requires the text capability measureText method.");
8782
9013
  return wrapText({
@@ -8852,8 +9083,8 @@
8852
9083
  });
8853
9084
  }
8854
9085
  function normalizeShowInput(value) {
8855
- if (!isRecord$2(value)) throw new BubbleCompositionError("BUBBLE-COMPOSITION-001", "Show bubble input must be an object.");
8856
- requireExactKeys(value, [
9086
+ if (!isRecord$5(value)) throw new BubbleCompositionError("BUBBLE-COMPOSITION-001", "Show bubble input must be an object.");
9087
+ requireExactKeys$1(value, [
8857
9088
  "actor",
8858
9089
  "actorKey",
8859
9090
  "kind",
@@ -8872,16 +9103,16 @@
8872
9103
  }
8873
9104
  return {
8874
9105
  actor: value.actor,
8875
- actorKey: requireName(value.actorKey, "Bubble actor key"),
9106
+ actorKey: requireName$1(value.actorKey, "Bubble actor key"),
8876
9107
  kind: value.kind,
8877
9108
  text: value.text,
8878
- styleName: requireName(value.styleName, "Bubble style name"),
9109
+ styleName: requireName$1(value.styleName, "Bubble style name"),
8879
9110
  animationMode,
8880
9111
  ...reveal === void 0 ? {} : { reveal }
8881
9112
  };
8882
9113
  }
8883
9114
  function createBubbleComposition(options) {
8884
- if (!isRecord$2(options)) throw new TypeError("Bubble composition options must be an object.");
9115
+ if (!isRecord$5(options)) throw new TypeError("Bubble composition options must be an object.");
8885
9116
  const imageResolver = validateImageResolver(options.imageResolver);
8886
9117
  const audio = validateAudioCapability(options.audio);
8887
9118
  const textCapability = validateTextCapability(options.textCapability);
@@ -8911,6 +9142,7 @@
8911
9142
  let activeStyle = style;
8912
9143
  if (input.reveal !== void 0) activeStyle = Object.freeze({
8913
9144
  ...style,
9145
+ layoutProfile: "custom",
8914
9146
  reveal: input.reveal
8915
9147
  });
8916
9148
  let currentText = input.text;
@@ -8998,21 +9230,34 @@
8998
9230
  kind: input.kind,
8999
9231
  style: activeStyle
9000
9232
  })), activeStyle);
9001
- const fullText = formatBubbleText(input.text, activeStyle, textCapability);
9233
+ const applySurfaceText = async (rawText, nextStyle = activeStyle) => {
9234
+ if (nextStyle.layoutProfile === "scratch-default" && surface?.renderScratchText) {
9235
+ const layout = layoutScratchBubbleText(rawText, (candidate) => typeof textCapability.measureText === "function" ? textCapability.measureText({
9236
+ styleName: nextStyle.textStyle,
9237
+ text: candidate
9238
+ }) : NaN);
9239
+ await surface.renderScratchText(layout);
9240
+ return;
9241
+ }
9242
+ if (!surface) return;
9243
+ textCapability.setText({
9244
+ styleName: nextStyle.textStyle,
9245
+ target: surface.targets.text,
9246
+ text: formatBubbleText(rawText, nextStyle, textCapability)
9247
+ });
9248
+ textOwned = true;
9249
+ };
9002
9250
  if (reveal?.layout === "RESERVED") {
9251
+ const fullText = formatBubbleText(input.text, activeStyle, textCapability);
9003
9252
  textCapability.setText({
9004
9253
  styleName: activeStyle.textStyle,
9005
9254
  target: surface.targets.text,
9006
9255
  text: fullText
9007
9256
  });
9257
+ textOwned = true;
9008
9258
  surface.captureTextLayout?.();
9009
9259
  }
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;
9260
+ await applySurfaceText(reveal ? revealedBubbleText(revealChunks, revealedCount) : input.text);
9016
9261
  await primeStyleImages(activeStyle, styleImageResolver, surface);
9017
9262
  createStyleLoops(activeStyle, styleImageResolver, surface);
9018
9263
  let currentAnimationMode = "idle";
@@ -9021,11 +9266,7 @@
9021
9266
  const renderVisibleText = async () => {
9022
9267
  if (!surface) return;
9023
9268
  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
- });
9269
+ await applySurfaceText(visible);
9029
9270
  await surface.show();
9030
9271
  };
9031
9272
  const stopRevealTimer = () => {
@@ -9102,6 +9343,7 @@
9102
9343
  target: surface.targets.text,
9103
9344
  text: formatBubbleText(text, activeStyle, textCapability)
9104
9345
  });
9346
+ textOwned = true;
9105
9347
  surface.captureTextLayout?.();
9106
9348
  }
9107
9349
  await renderVisibleText();
@@ -9146,13 +9388,10 @@
9146
9388
  target: surface.targets.text,
9147
9389
  text: formatBubbleText(currentText, nextStyle, textCapability)
9148
9390
  });
9391
+ textOwned = true;
9149
9392
  surface.captureTextLayout?.();
9150
9393
  }
9151
- textCapability.setText({
9152
- styleName: nextStyle.textStyle,
9153
- target: surface.targets.text,
9154
- text: formatBubbleText(currentText, nextStyle, textCapability)
9155
- });
9394
+ await applySurfaceText(currentText, nextStyle);
9156
9395
  createStyleLoops(nextStyle, nextImageResolver, surface);
9157
9396
  await Promise.all([
9158
9397
  surface.setLayerVisible("portraitBase", nextStyle.portrait !== void 0),
@@ -9214,6 +9453,7 @@
9214
9453
  target: surface.targets.text,
9215
9454
  text: formatBubbleText(currentText, activeStyle, textCapability)
9216
9455
  });
9456
+ textOwned = true;
9217
9457
  surface.captureTextLayout?.();
9218
9458
  }
9219
9459
  }
@@ -9276,10 +9516,19 @@
9276
9516
  }
9277
9517
  transitionTail = transitionTail.then(async () => {
9278
9518
  if (normalized.name === "animateBubbleShape" && normalized.visualStyle) {
9279
- const nextStyle = Object.freeze({
9519
+ const transitionStyle = Object.freeze({
9280
9520
  ...activeStyle,
9521
+ layoutProfile: "custom"
9522
+ });
9523
+ const nextStyle = Object.freeze({
9524
+ ...transitionStyle,
9281
9525
  visualStyle: normalized.visualStyle
9282
9526
  });
9527
+ if (activeStyle.layoutProfile === "scratch-default") {
9528
+ await surface?.updateStyle(transitionStyle);
9529
+ await applySurfaceText(currentText, transitionStyle);
9530
+ await surface?.show();
9531
+ }
9283
9532
  await surface?.animate?.(normalized);
9284
9533
  activeStyle = nextStyle;
9285
9534
  await surface?.updateStyle(activeStyle);
@@ -9359,7 +9608,7 @@
9359
9608
  styles.set(style.name, style);
9360
9609
  },
9361
9610
  hasActiveBubble(actorKey) {
9362
- return active.has(requireName(actorKey, "Bubble actor key"));
9611
+ return active.has(requireName$1(actorKey, "Bubble actor key"));
9363
9612
  },
9364
9613
  async show(input) {
9365
9614
  ensureActive();
@@ -9368,7 +9617,7 @@
9368
9617
  },
9369
9618
  releaseTarget(actorKey) {
9370
9619
  ensureActive();
9371
- const normalized = requireName(actorKey, "Bubble actor key");
9620
+ const normalized = requireName$1(actorKey, "Bubble actor key");
9372
9621
  return enqueueActor(normalized, async () => {
9373
9622
  await active.get(normalized)?.close();
9374
9623
  });
@@ -9389,111 +9638,1101 @@
9389
9638
  });
9390
9639
  }
9391
9640
  //#endregion
9392
- //#region src/turbowarp-svg-text-adapter.ts
9393
- function isRecord$1(value) {
9394
- return typeof value === "object" && value !== null && !Array.isArray(value);
9641
+ //#region node_modules/.pnpm/@kubohiroya+turbowarp-svg-text@0.8.1/node_modules/@kubohiroya/turbowarp-svg-text/dist/composition.js
9642
+ var block_definitions_default = {
9643
+ extensionName: "SVG Text",
9644
+ blocks: [{
9645
+ "opcode": "defineStyle",
9646
+ "blockType": "COMMAND",
9647
+ "text": "define text style [STYLE] background [BACKGROUND] text [TEXT_COLOR] font [FONT] size [SIZE] align [ALIGN]",
9648
+ "description": "Defines or replaces a named text style for SVG text actors. Bubble shape and placement are owned by the host Bubble layer.",
9649
+ "arguments": {
9650
+ "STYLE": {
9651
+ "type": "STRING",
9652
+ "defaultValue": "default"
9653
+ },
9654
+ "BACKGROUND": {
9655
+ "type": "COLOR",
9656
+ "defaultValue": "#ffffff"
9657
+ },
9658
+ "TEXT_COLOR": {
9659
+ "type": "COLOR",
9660
+ "defaultValue": "#575e75"
9661
+ },
9662
+ "FONT": {
9663
+ "type": "STRING",
9664
+ "defaultValue": "Helvetica"
9665
+ },
9666
+ "SIZE": {
9667
+ "type": "NUMBER",
9668
+ "defaultValue": 100
9669
+ },
9670
+ "ALIGN": {
9671
+ "type": "STRING",
9672
+ "defaultValue": "left",
9673
+ "menu": "alignment"
9674
+ }
9675
+ }
9676
+ }, {
9677
+ "opcode": "setText",
9678
+ "blockType": "COMMAND",
9679
+ "text": "set this sprite text [TEXT] with style [STYLE]",
9680
+ "description": "Replaces this sprite's skin with responsive styled SVG text.",
9681
+ "arguments": {
9682
+ "TEXT": {
9683
+ "type": "STRING",
9684
+ "defaultValue": "Title\\nSubtitle"
9685
+ },
9686
+ "STYLE": {
9687
+ "type": "STRING",
9688
+ "defaultValue": "default"
9689
+ }
9690
+ }
9691
+ }],
9692
+ menus: { "alignment": {
9693
+ "acceptReporters": true,
9694
+ "items": [
9695
+ "left",
9696
+ "center",
9697
+ "right"
9698
+ ]
9699
+ } }
9700
+ };
9701
+ var extensionConfig = {
9702
+ id: "kubohiroyasvgtext",
9703
+ slug: "svg-text",
9704
+ name: "SVG Text",
9705
+ description: "Responsive named-style SVG text actors for TurboWarp.",
9706
+ author: "Hiroya Kubo",
9707
+ license: "MPL-2.0",
9708
+ unsandboxed: true
9709
+ };
9710
+ var baseStageWidth = 480;
9711
+ var baseStageHeight = 360;
9712
+ var defaultFontPercent$1 = 100;
9713
+ var defaultRubyFontPercent$1 = 50;
9714
+ var defaultRubyGap$1 = 1;
9715
+ var maximumFontNameLength = 128;
9716
+ var textStyle = {
9717
+ fontSize: 14,
9718
+ lineHeight: 16,
9719
+ padding: 12,
9720
+ cornerRadius: 8
9721
+ };
9722
+ var DEFAULT_SVG_TEXT_STYLE = Object.freeze({
9723
+ alignment: "left",
9724
+ backgroundColor: "#ffffff",
9725
+ font: "Helvetica",
9726
+ fontPercent: defaultFontPercent$1,
9727
+ textColor: "#575e75"
9728
+ });
9729
+ var DEFAULT_SVG_TEXT_RICH_STYLE = Object.freeze({
9730
+ ...DEFAULT_SVG_TEXT_STYLE,
9731
+ rubyFontPercent: defaultRubyFontPercent$1,
9732
+ rubyGap: defaultRubyGap$1
9733
+ });
9734
+ function createSvgTextLayout(text, definition, nativeSize) {
9735
+ const metrics = createTextMetrics(definition, nativeSize);
9736
+ const lineMeasurements = text.split("\n").map((line) => ({
9737
+ text: line,
9738
+ width: measureTextWidth(line, metrics.fontSize)
9739
+ }));
9740
+ const contentWidth = Math.max(1, ...lineMeasurements.map((line) => line.width));
9741
+ const width = Math.max(1, Math.ceil(contentWidth + metrics.padding * 2));
9742
+ const height = Math.max(1, Math.ceil(metrics.lineHeight * lineMeasurements.length + metrics.padding * 2));
9743
+ const x = definition.alignment === "center" ? width / 2 : definition.alignment === "right" ? width - metrics.padding : metrics.padding;
9744
+ const lines = Object.freeze(lineMeasurements.map((line, index) => Object.freeze({
9745
+ baseline: metrics.padding + metrics.fontSize + metrics.lineHeight * index,
9746
+ text: line.text,
9747
+ width: line.width,
9748
+ x
9749
+ })));
9750
+ const style = createLayoutStyle(definition, metrics);
9751
+ return Object.freeze({
9752
+ height,
9753
+ lines,
9754
+ preserveWhitespace: true,
9755
+ style,
9756
+ width
9757
+ });
9395
9758
  }
9396
- function validateExtension(value) {
9397
- if (!isRecord$1(value) || typeof value.setText !== "function" || typeof value.releaseTextActor !== "function") throw new TypeError("TurboWarp SVG Text adapter requires setText and releaseTextActor.");
9398
- return value;
9759
+ function createSvgTextRichLayout(runs, definition, nativeSize, maxWidth) {
9760
+ const metrics = createTextMetrics(definition, nativeSize);
9761
+ const rubyFontSize = metrics.fontSize * (definition.rubyFontPercent / defaultFontPercent$1);
9762
+ const rubyGap = definition.rubyGap * metrics.fontScale;
9763
+ const style = Object.freeze({
9764
+ ...createLayoutStyle(definition, metrics),
9765
+ rubyFontPercent: definition.rubyFontPercent,
9766
+ rubyFontSize,
9767
+ rubyGap
9768
+ });
9769
+ const plainText = runs.map((run) => run.type === "ruby" ? run.base : run.text).join("");
9770
+ const readingText = runs.map((run) => run.type === "ruby" ? run.reading : run.text).join("");
9771
+ const revealUnits = [];
9772
+ const items = [];
9773
+ for (const [runIndex, run] of runs.entries()) {
9774
+ if (run.type === "ruby") {
9775
+ const reveal = Object.freeze({
9776
+ end: run.base.length,
9777
+ index: revealUnits.length,
9778
+ runIndex,
9779
+ start: 0,
9780
+ type: "ruby"
9781
+ });
9782
+ revealUnits.push(reveal);
9783
+ const baseWidth = measureTextWidth(run.base, metrics.fontSize);
9784
+ const readingWidth = measureTextWidth(run.reading, rubyFontSize);
9785
+ items.push({
9786
+ base: run.base,
9787
+ baseWidth,
9788
+ reading: run.reading,
9789
+ readingWidth,
9790
+ reveal,
9791
+ type: "ruby",
9792
+ width: Math.max(baseWidth, readingWidth)
9793
+ });
9794
+ continue;
9795
+ }
9796
+ for (const grapheme of segmentGraphemes(run.text)) {
9797
+ if (grapheme.segment === "\n") {
9798
+ items.push("break");
9799
+ continue;
9800
+ }
9801
+ const reveal = Object.freeze({
9802
+ end: grapheme.end,
9803
+ index: revealUnits.length,
9804
+ runIndex,
9805
+ start: grapheme.start,
9806
+ type: "text"
9807
+ });
9808
+ revealUnits.push(reveal);
9809
+ items.push({
9810
+ reveal,
9811
+ text: grapheme.segment,
9812
+ type: "text",
9813
+ width: measureTextWidth(grapheme.segment, metrics.fontSize)
9814
+ });
9815
+ }
9816
+ }
9817
+ const contentLimit = maxWidth === void 0 ? void 0 : Math.max(1, maxWidth - metrics.padding * 2);
9818
+ const pendingLines = [];
9819
+ let pendingLine = {
9820
+ units: [],
9821
+ width: 0
9822
+ };
9823
+ const finishLine = () => {
9824
+ pendingLines.push(pendingLine);
9825
+ pendingLine = {
9826
+ units: [],
9827
+ width: 0
9828
+ };
9829
+ };
9830
+ for (const item of items) {
9831
+ if (item === "break") {
9832
+ finishLine();
9833
+ continue;
9834
+ }
9835
+ if (contentLimit !== void 0 && pendingLine.units.length > 0 && pendingLine.width + item.width > contentLimit) finishLine();
9836
+ pendingLine.units.push(item);
9837
+ pendingLine.width += item.width;
9838
+ }
9839
+ finishLine();
9840
+ const naturalWidth = Math.max(1, ...pendingLines.map((line) => line.width)) + metrics.padding * 2;
9841
+ const width = Math.max(1, Math.ceil(maxWidth === void 0 ? naturalWidth : Math.max(maxWidth, naturalWidth)));
9842
+ const baseDescent = Math.max(0, metrics.lineHeight - metrics.fontSize);
9843
+ let lineTop = metrics.padding;
9844
+ const lines = Object.freeze(pendingLines.map((pending) => {
9845
+ const hasRuby = pending.units.some((unit) => unit.type === "ruby");
9846
+ const ascent = metrics.fontSize + (hasRuby ? rubyFontSize + rubyGap : 0);
9847
+ const descent = baseDescent;
9848
+ const height = ascent + descent;
9849
+ const baseline = lineTop + ascent;
9850
+ const x = definition.alignment === "center" ? (width - pending.width) / 2 : definition.alignment === "right" ? width - metrics.padding - pending.width : metrics.padding;
9851
+ let fragmentX = x;
9852
+ const fragments = Object.freeze(pending.units.map((unit) => {
9853
+ if (unit.type === "text") {
9854
+ const fragment = Object.freeze({
9855
+ baseline,
9856
+ revealIndex: unit.reveal.index,
9857
+ text: unit.text,
9858
+ type: "text",
9859
+ width: unit.width,
9860
+ x: fragmentX
9861
+ });
9862
+ fragmentX += unit.width;
9863
+ return fragment;
9864
+ }
9865
+ const groupX = fragmentX;
9866
+ const base = Object.freeze({
9867
+ baseline,
9868
+ fontSize: metrics.fontSize,
9869
+ text: unit.base,
9870
+ width: unit.baseWidth,
9871
+ x: groupX + (unit.width - unit.baseWidth) / 2
9872
+ });
9873
+ const reading = Object.freeze({
9874
+ baseline: baseline - metrics.fontSize - rubyGap,
9875
+ fontSize: rubyFontSize,
9876
+ text: unit.reading,
9877
+ width: unit.readingWidth,
9878
+ x: groupX + (unit.width - unit.readingWidth) / 2
9879
+ });
9880
+ const fragment = Object.freeze({
9881
+ base,
9882
+ reading,
9883
+ revealIndex: unit.reveal.index,
9884
+ type: "ruby",
9885
+ width: unit.width,
9886
+ x: groupX
9887
+ });
9888
+ fragmentX += unit.width;
9889
+ return fragment;
9890
+ }));
9891
+ const line = Object.freeze({
9892
+ ascent,
9893
+ baseline,
9894
+ descent,
9895
+ fragments,
9896
+ height,
9897
+ overflow: contentLimit !== void 0 && pending.width > contentLimit,
9898
+ width: pending.width,
9899
+ x
9900
+ });
9901
+ lineTop += height;
9902
+ return line;
9903
+ }));
9904
+ const height = Math.max(1, Math.ceil(lineTop + metrics.padding));
9905
+ const overflow = lines.some((line) => line.overflow);
9906
+ return Object.freeze({
9907
+ height,
9908
+ lines,
9909
+ overflow,
9910
+ plainText,
9911
+ preserveWhitespace: true,
9912
+ readingText,
9913
+ revealUnits: Object.freeze(revealUnits),
9914
+ style,
9915
+ width
9916
+ });
9399
9917
  }
9400
- /**
9401
- * Adapt the TurboWarp SVG Text extension to Bubble's host-neutral text
9402
- * capability contract.
9403
- */
9404
- function createTurboWarpSvgTextCapability(extensionInput) {
9405
- const extension = validateExtension(extensionInput);
9918
+ function renderSvgTextLayout(layout) {
9919
+ const textAnchor = layout.style.alignment === "center" ? "middle" : layout.style.alignment === "right" ? "end" : "start";
9920
+ const text = layout.lines.map((line) => line.text).join("\n");
9921
+ const tspans = layout.lines.map((line) => `<tspan x="${formatSvgNumber(line.x)}" y="${formatSvgNumber(line.baseline)}">${escapeXml(line.text)}</tspan>`).join("");
9922
+ const whitespaceAttribute = layout.preserveWhitespace ? " xml:space=\"preserve\"" : "";
9923
+ 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>`;
9924
+ }
9925
+ function renderSvgTextRichLayout(layout) {
9926
+ const tspans = layout.lines.flatMap((line) => line.fragments.flatMap((fragment) => {
9927
+ if (fragment.type === "text") return [`<tspan x="${formatSvgNumber(fragment.x)}" y="${formatSvgNumber(fragment.baseline)}" font-size="${formatSvgNumber(layout.style.fontSize)}">${escapeXml(fragment.text)}</tspan>`];
9928
+ 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>`];
9929
+ })).join("");
9930
+ const whitespaceAttribute = layout.preserveWhitespace ? " xml:space=\"preserve\"" : "";
9931
+ 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>`;
9932
+ }
9933
+ function normalizeSvgTextColor(value, fallback) {
9934
+ const color = value.trim();
9935
+ if (color === "") return fallback;
9936
+ if (color.toLowerCase() === "transparent") return color;
9937
+ if (/^#(?:[\da-f]{3}|[\da-f]{4}|[\da-f]{6}|[\da-f]{8})$/iu.test(color)) return color;
9938
+ if (globalThis.CSS?.supports?.("color", color)) return color;
9939
+ return fallback;
9940
+ }
9941
+ function normalizeSvgTextFont(value) {
9942
+ const font = value.trim();
9943
+ const hasUnsafeCharacter = [...font].some((character) => {
9944
+ const codePoint = character.codePointAt(0) ?? 0;
9945
+ return codePoint <= 31 || codePoint === 127 || ",;{}".includes(character);
9946
+ });
9947
+ if (font === "" || font.length > maximumFontNameLength || hasUnsafeCharacter) return DEFAULT_SVG_TEXT_STYLE.font;
9948
+ return font;
9949
+ }
9950
+ function createTextMetrics(definition, nativeSize) {
9951
+ const stageScale = Math.min(nativeSize[0] / baseStageWidth, nativeSize[1] / baseStageHeight);
9952
+ const fontScale = stageScale * (definition.fontPercent / defaultFontPercent$1);
9953
+ return {
9954
+ cornerRadius: textStyle.cornerRadius * stageScale,
9955
+ fontScale,
9956
+ fontSize: textStyle.fontSize * fontScale,
9957
+ lineHeight: textStyle.lineHeight * fontScale,
9958
+ padding: textStyle.padding * stageScale
9959
+ };
9960
+ }
9961
+ function createLayoutStyle(definition, metrics) {
9406
9962
  return Object.freeze({
9407
- setText({ styleName, target, text }) {
9408
- extension.setText({
9409
- STYLE: styleName,
9410
- TEXT: text
9411
- }, { target });
9412
- },
9413
- releaseTarget(target) {
9414
- extension.releaseTextActor(target);
9415
- },
9416
- measureText({ styleName, text }) {
9417
- if (typeof extension.measureText !== "function") throw new Error("TurboWarp SVG Text does not provide text measurement.");
9418
- return extension.measureText(styleName, text);
9963
+ alignment: definition.alignment,
9964
+ backgroundColor: definition.backgroundColor,
9965
+ cornerRadius: metrics.cornerRadius,
9966
+ font: definition.font,
9967
+ fontPercent: definition.fontPercent,
9968
+ fontSize: metrics.fontSize,
9969
+ lineHeight: metrics.lineHeight,
9970
+ padding: metrics.padding,
9971
+ textColor: definition.textColor
9972
+ });
9973
+ }
9974
+ function segmentGraphemes(value) {
9975
+ const segments = [];
9976
+ let current = "";
9977
+ let currentStart = 0;
9978
+ let joinNext = false;
9979
+ let offset = 0;
9980
+ for (const character of value) {
9981
+ if (!(current !== "" && (joinNext || character === "‍" || isGraphemeExtender(character))) && current !== "") {
9982
+ segments.push({
9983
+ end: offset,
9984
+ segment: current,
9985
+ start: currentStart
9986
+ });
9987
+ current = "";
9419
9988
  }
9989
+ if (current === "") currentStart = offset;
9990
+ current += character;
9991
+ joinNext = character === "‍";
9992
+ offset += character.length;
9993
+ }
9994
+ if (current !== "") segments.push({
9995
+ end: offset,
9996
+ segment: current,
9997
+ start: currentStart
9420
9998
  });
9999
+ return segments;
9421
10000
  }
9422
- //#endregion
9423
- //#region src/turbowarp-adapter.ts
9424
- var spriteLayer = "sprite";
9425
- var portraitBoxSize = 96;
9426
- var indicatorBoxSize = 18;
9427
- var contentGap = 8;
9428
- var stageSafeMargin = 16;
9429
- var surfaceSequence = 0;
9430
- var BubbleRuntimeAdapterError = class extends Error {
9431
- constructor(code, message) {
9432
- super(message);
9433
- _defineProperty(this, "code", void 0);
9434
- this.name = "BubbleRuntimeAdapterError";
9435
- this.code = code;
10001
+ function isGraphemeExtender(character) {
10002
+ if (/\p{Mark}/u.test(character)) return true;
10003
+ const codePoint = character.codePointAt(0) ?? 0;
10004
+ return codePoint >= 65024 && codePoint <= 65039 || codePoint >= 917760 && codePoint <= 917999 || codePoint >= 127995 && codePoint <= 127999;
10005
+ }
10006
+ function measureTextWidth(text, fontSize) {
10007
+ let units = 0;
10008
+ for (const character of text) {
10009
+ if (/\p{Mark}/u.test(character)) continue;
10010
+ if (/\s/u.test(character)) {
10011
+ units += .35;
10012
+ continue;
10013
+ }
10014
+ const codePoint = character.codePointAt(0) ?? 0;
10015
+ units += codePoint <= 127 ? .62 : 1;
10016
+ }
10017
+ return units * fontSize;
10018
+ }
10019
+ function escapeXml(value) {
10020
+ return value.replace(/[&<>"']/gu, (character) => {
10021
+ switch (character) {
10022
+ case "&": return "&amp;";
10023
+ case "<": return "&lt;";
10024
+ case ">": return "&gt;";
10025
+ case "\"": return "&quot;";
10026
+ default: return "&apos;";
10027
+ }
10028
+ });
10029
+ }
10030
+ function formatSvgNumber(value) {
10031
+ return String(Math.round(value * 1e3) / 1e3);
10032
+ }
10033
+ var blockDefinitions$1 = block_definitions_default.blocks;
10034
+ var definitionMenus$1 = block_definitions_default.menus;
10035
+ var EXTENSION_DOCS_URI$1 = "https://kubohiroya.github.io/turbowarp-svg-text/";
10036
+ var defaultStyleName$1 = "default";
10037
+ var defaultFontPercent = 100;
10038
+ var defaultRubyFontPercent = 50;
10039
+ var defaultRubyGap = 1;
10040
+ var minimumFontPercent = 1;
10041
+ var maximumFontPercent = 1e3;
10042
+ var minimumRubyFontPercent = 10;
10043
+ var maximumRubyFontPercent = 100;
10044
+ var minimumRubyGap = 0;
10045
+ var maximumRubyGap = 100;
10046
+ 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>")}`;
10047
+ var SvgTextExtension = class {
10048
+ constructor(runtime = Scratch.vm?.runtime, options = {}) {
10049
+ this.styles = /* @__PURE__ */ new Map([[defaultStyleName$1, DEFAULT_SVG_TEXT_RICH_STYLE]]);
10050
+ this.textActors = /* @__PURE__ */ new Map();
10051
+ if (!runtime) throw new Error("SVG Text requires the TurboWarp VM.");
10052
+ this.runtime = runtime;
10053
+ this.castToString = options.castToString ?? Scratch.Cast.toString;
10054
+ if (options.listenForRuntimeEvents ?? true) this.runtime.on("STAGE_SIZE_CHANGED", () => {
10055
+ this.restyleTextActors();
10056
+ });
10057
+ }
10058
+ getInfo() {
10059
+ return {
10060
+ id: extensionConfig.id,
10061
+ name: Scratch.translate(block_definitions_default.extensionName),
10062
+ docsURI: EXTENSION_DOCS_URI$1,
10063
+ blockIconURI: BLOCK_ICON_URI$1,
10064
+ color1: "#9966ff",
10065
+ blocks: blockDefinitions$1.map((block) => this.toScratchBlock(block)),
10066
+ menus: definitionMenus$1
10067
+ };
10068
+ }
10069
+ defineStyle(args) {
10070
+ const styleName = this.normalizeStyleName(args.STYLE);
10071
+ this.styles.set(styleName, {
10072
+ alignment: this.normalizeAlignment(args.ALIGN),
10073
+ backgroundColor: this.normalizeColor(args.BACKGROUND, DEFAULT_SVG_TEXT_STYLE.backgroundColor),
10074
+ font: this.normalizeFont(args.FONT),
10075
+ fontPercent: this.normalizeFontPercent(args.SIZE),
10076
+ rubyFontPercent: this.normalizeRubyFontPercent(args.RUBY_SIZE),
10077
+ rubyGap: this.normalizeRubyGap(args.RUBY_GAP),
10078
+ textColor: this.normalizeColor(args.TEXT_COLOR, DEFAULT_SVG_TEXT_STYLE.textColor)
10079
+ });
10080
+ this.restyleTextActors(styleName);
10081
+ }
10082
+ setText(args, util) {
10083
+ this.applyTextActor(util.target, {
10084
+ kind: "plain",
10085
+ text: this.normalizeMessage(args.TEXT)
10086
+ }, this.resolveStyle(args.STYLE));
10087
+ }
10088
+ measureText(styleName, text) {
10089
+ const selection = this.resolveStyle(styleName);
10090
+ const layout = createSvgTextLayout(this.normalizeMessage(text), selection.definition, this.getNativeSize());
10091
+ return Math.max(0, ...layout.lines.map((line) => line.width));
10092
+ }
10093
+ /**
10094
+ * Exposes the stock named-style registry through a skin-free layout contract.
10095
+ * Consumers receive current layout data without access to the mutable registry.
10096
+ */
10097
+ getLayoutCapability() {
10098
+ this.layoutCapabilityValue ?? (this.layoutCapabilityValue = Object.freeze({ layoutText: (input) => {
10099
+ if (typeof input !== "object" || input === null || typeof input.styleName !== "string" || typeof input.text !== "string") throw new TypeError("SVG Text layout capability input is invalid.");
10100
+ const nativeSize = this.requireLayoutNativeSize(input.nativeSize);
10101
+ const selection = this.resolveStyle(input.styleName);
10102
+ return createSvgTextLayout(this.normalizeMessage(input.text), selection.definition, nativeSize);
10103
+ } }));
10104
+ return this.layoutCapabilityValue;
10105
+ }
10106
+ setCompositionText(styleName, render, target) {
10107
+ const content = Object.freeze({
10108
+ kind: "composition",
10109
+ render
10110
+ });
10111
+ this.applyTextActor(target, content, this.resolveStyle(styleName));
10112
+ }
10113
+ releaseTextActor(target) {
10114
+ const state = this.textActors.get(target);
10115
+ if (!state) return false;
10116
+ this.textActors.delete(target);
10117
+ this.runtime.renderer?.destroySkin?.(state.skinId);
10118
+ this.runtime.requestRedraw?.();
10119
+ return true;
10120
+ }
10121
+ toScratchBlock(block) {
10122
+ return {
10123
+ opcode: block.opcode,
10124
+ blockType: Scratch.BlockType[block.blockType],
10125
+ text: Scratch.translate(block.text),
10126
+ hideFromPalette: block.hideFromPalette ?? false,
10127
+ arguments: Object.fromEntries(Object.entries(block.arguments).map(([name, argument]) => [name, {
10128
+ type: Scratch.ArgumentType[argument.type],
10129
+ defaultValue: argument.defaultValue,
10130
+ ...argument.menu === void 0 ? {} : { menu: argument.menu }
10131
+ }]))
10132
+ };
10133
+ }
10134
+ normalizeStyleName(value) {
10135
+ return this.castToString(value).trim() || defaultStyleName$1;
10136
+ }
10137
+ normalizeFontPercent(value) {
10138
+ if (typeof value === "string" && value.trim() === "") return defaultFontPercent;
10139
+ const numericValue = Number(value);
10140
+ if (!Number.isFinite(numericValue)) return defaultFontPercent;
10141
+ return Math.min(maximumFontPercent, Math.max(minimumFontPercent, numericValue));
10142
+ }
10143
+ normalizeRubyFontPercent(value) {
10144
+ if (typeof value === "string" && value.trim() === "") return defaultRubyFontPercent;
10145
+ const numericValue = Number(value);
10146
+ if (!Number.isFinite(numericValue)) return defaultRubyFontPercent;
10147
+ return Math.min(maximumRubyFontPercent, Math.max(minimumRubyFontPercent, numericValue));
10148
+ }
10149
+ normalizeRubyGap(value) {
10150
+ if (typeof value === "string" && value.trim() === "") return defaultRubyGap;
10151
+ const numericValue = Number(value);
10152
+ if (!Number.isFinite(numericValue)) return defaultRubyGap;
10153
+ return Math.min(maximumRubyGap, Math.max(minimumRubyGap, numericValue));
10154
+ }
10155
+ normalizeMessage(value) {
10156
+ return this.castToString(value).replace(/\\r\\n|\\n|\\r/gu, "\n");
10157
+ }
10158
+ normalizeAlignment(value) {
10159
+ const alignment = this.castToString(value).trim().toLowerCase();
10160
+ if (alignment === "center" || alignment === "right") return alignment;
10161
+ return "left";
10162
+ }
10163
+ normalizeColor(value, fallback) {
10164
+ return normalizeSvgTextColor(this.castToString(value), fallback);
10165
+ }
10166
+ normalizeFont(value) {
10167
+ return normalizeSvgTextFont(this.castToString(value));
10168
+ }
10169
+ getNativeSize() {
10170
+ const nativeSize = this.runtime.renderer?.getNativeSize?.();
10171
+ if (!Array.isArray(nativeSize) || nativeSize.length < 2) return [480, 360];
10172
+ const width = Number(nativeSize[0]);
10173
+ const height = Number(nativeSize[1]);
10174
+ if (!Number.isFinite(width) || !Number.isFinite(height) || width <= 0 || height <= 0) return [480, 360];
10175
+ return [width, height];
10176
+ }
10177
+ requireLayoutNativeSize(value) {
10178
+ 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.");
10179
+ return value;
10180
+ }
10181
+ createTextActorSvg(content, definition) {
10182
+ if (content.kind === "composition") return content.render(definition, this.getNativeSize());
10183
+ return renderSvgTextLayout(createSvgTextLayout(content.text, definition, this.getNativeSize()));
10184
+ }
10185
+ applyTextActor(target, content, selection) {
10186
+ const renderer = this.runtime.renderer;
10187
+ if (typeof target.drawableID !== "number" || typeof renderer?.createSVGSkin !== "function" || typeof renderer.updateDrawableSkinId !== "function") throw new Error("SVG Text requires SVG skin APIs from TurboWarp.");
10188
+ const skinId = renderer.createSVGSkin(this.createTextActorSvg(content, selection.definition));
10189
+ if (!Number.isInteger(skinId) || skinId < 0) throw new Error("TurboWarp did not create an SVG text skin.");
10190
+ try {
10191
+ renderer.updateDrawableSkinId(target.drawableID, skinId);
10192
+ } catch (error) {
10193
+ renderer.destroySkin?.(skinId);
10194
+ throw error;
10195
+ }
10196
+ const previous = this.textActors.get(target);
10197
+ this.textActors.set(target, {
10198
+ content,
10199
+ skinId,
10200
+ styleName: selection.styleName
10201
+ });
10202
+ if (previous && previous.skinId !== skinId) renderer.destroySkin?.(previous.skinId);
10203
+ this.runtime.requestRedraw?.();
10204
+ }
10205
+ resolveStyle(value) {
10206
+ const requestedName = this.normalizeStyleName(value);
10207
+ const definition = this.styles.get(requestedName);
10208
+ if (definition) return {
10209
+ definition,
10210
+ styleName: requestedName
10211
+ };
10212
+ return {
10213
+ definition: this.styles.get(defaultStyleName$1) ?? DEFAULT_SVG_TEXT_RICH_STYLE,
10214
+ styleName: defaultStyleName$1
10215
+ };
10216
+ }
10217
+ restyleTextActors(styleName) {
10218
+ for (const [target, state] of [...this.textActors]) {
10219
+ if (styleName !== void 0 && state.styleName !== styleName) continue;
10220
+ this.applyTextActor(target, state.content, this.resolveStyle(state.styleName));
10221
+ }
9436
10222
  }
9437
10223
  };
9438
- function isRecord(value) {
10224
+ var defaultStyleName = "default";
10225
+ var maximumContentCharacters = 1e5;
10226
+ var maximumContentLines = 1e3;
10227
+ var maximumContentRuns = 1024;
10228
+ var maximumLayoutFragments = 1e4;
10229
+ var maximumLayoutWidth = 1e5;
10230
+ var maximumRubyBaseCharacters = 256;
10231
+ var maximumRubyReadingCharacters = 512;
10232
+ function isRecord$4(value) {
9439
10233
  return typeof value === "object" && value !== null && !Array.isArray(value);
9440
10234
  }
9441
- function requireRenderer(value) {
9442
- if (!isRecord(value)) throw new BubbleRuntimeAdapterError("BUBBLE-RUNTIME-001", "Bubble requires the TurboWarp renderer.");
10235
+ function compositionError(code, message) {
10236
+ const error = new Error(message);
10237
+ Object.defineProperty(error, "code", { value: code });
10238
+ return error;
10239
+ }
10240
+ function requireExactKeys(value, required, optional, label) {
10241
+ const allowed = /* @__PURE__ */ new Set([...required, ...optional]);
10242
+ if (required.some((key) => !Object.prototype.hasOwnProperty.call(value, key)) || Object.keys(value).some((key) => !allowed.has(key))) throw compositionError("SVG-TEXT-COMPOSITION-001", `${label} has missing or unknown properties.`);
10243
+ }
10244
+ function requireName(value, label) {
10245
+ if (typeof value !== "string" || value.trim().length === 0) throw compositionError("SVG-TEXT-COMPOSITION-001", `${label} must be a non-empty string.`);
10246
+ return value.trim();
10247
+ }
10248
+ function validateRuntime(value) {
10249
+ if (!isRecord$4(value) || !isRecord$4(value.renderer)) throw new TypeError("SVG Text composition runtime must provide a renderer.");
10250
+ const renderer = value.renderer;
9443
10251
  const methods = [
9444
10252
  "createSVGSkin",
9445
- "createDrawable",
9446
- "destroyDrawable",
9447
10253
  "destroySkin",
9448
- "getCurrentSkinSize",
9449
- "getNativeSize",
9450
- "updateDrawablePosition",
9451
- "updateDrawableScale",
9452
- "updateDrawableSkinId",
9453
- "updateDrawableVisible"
10254
+ "updateDrawableSkinId"
9454
10255
  ];
9455
- if (methods.some((method) => typeof value[method] !== "function")) throw new BubbleRuntimeAdapterError("BUBBLE-RUNTIME-001", `Bubble renderer must provide ${methods.join(", ")}.`);
10256
+ if (methods.some((method) => typeof renderer[method] !== "function")) throw new TypeError(`SVG Text composition renderer must provide ${methods.join(", ")}.`);
10257
+ if (value.requestRedraw !== void 0 && typeof value.requestRedraw !== "function") throw new TypeError("SVG Text composition requestRedraw must be a function.");
9456
10258
  return value;
9457
10259
  }
9458
- function requireAssetManager(value) {
9459
- 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.");
10260
+ function validateTarget(value) {
10261
+ 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.");
9460
10262
  return value;
9461
10263
  }
9462
- function targetBounds(target) {
9463
- try {
9464
- const bounds = target.getBoundsForBubble?.();
9465
- if (bounds && [
9466
- bounds.bottom,
9467
- bounds.left,
9468
- bounds.right,
9469
- bounds.top
9470
- ].every((value) => Number.isFinite(value))) return bounds;
9471
- } catch {}
9472
- const x = Number.isFinite(target.x) ? Number(target.x) : 0;
9473
- const y = Number.isFinite(target.y) ? Number(target.y) : 0;
10264
+ function validateOptionalString(value, label) {
10265
+ 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.`);
10266
+ }
10267
+ function validateStyle(value) {
10268
+ if (!isRecord$4(value)) throw compositionError("SVG-TEXT-COMPOSITION-001", "SVG Text style must be an object.");
10269
+ requireExactKeys(value, ["name"], [
10270
+ "alignment",
10271
+ "backgroundColor",
10272
+ "font",
10273
+ "fontPercent",
10274
+ "rubyFontPercent",
10275
+ "rubyGap",
10276
+ "textColor"
10277
+ ], "SVG Text style");
10278
+ const name = requireName(value.name, "SVG Text style name");
10279
+ if (value.alignment !== void 0 && value.alignment !== "left" && value.alignment !== "center" && value.alignment !== "right") throw compositionError("SVG-TEXT-COMPOSITION-001", "SVG Text alignment is invalid.");
10280
+ validateOptionalString(value.backgroundColor, "SVG Text backgroundColor");
10281
+ validateOptionalString(value.font, "SVG Text font");
10282
+ validateOptionalString(value.textColor, "SVG Text textColor");
10283
+ if (value.fontPercent !== void 0 && (typeof value.fontPercent !== "number" || !Number.isFinite(value.fontPercent) || value.fontPercent < 1 || value.fontPercent > 1e3)) throw compositionError("SVG-TEXT-COMPOSITION-001", "SVG Text fontPercent must be a finite number from 1 to 1000.");
10284
+ if (value.rubyFontPercent !== void 0 && (typeof value.rubyFontPercent !== "number" || !Number.isFinite(value.rubyFontPercent) || value.rubyFontPercent < 10 || value.rubyFontPercent > 100)) throw compositionError("SVG-TEXT-COMPOSITION-001", "SVG Text rubyFontPercent must be a finite number from 10 to 100.");
10285
+ if (value.rubyGap !== void 0 && (typeof value.rubyGap !== "number" || !Number.isFinite(value.rubyGap) || value.rubyGap < 0 || value.rubyGap > 100)) throw compositionError("SVG-TEXT-COMPOSITION-001", "SVG Text rubyGap must be a finite number from 0 to 100.");
9474
10286
  return {
9475
- bottom: y,
9476
- left: x,
9477
- right: x,
9478
- top: y
10287
+ ...value,
10288
+ name
9479
10289
  };
9480
10290
  }
9481
- function readSize(renderer, target, fallback) {
9482
- const raw = renderer.getCurrentSkinSize(target.drawableID);
9483
- if (!Array.isArray(raw) || raw.length < 2) return fallback;
9484
- const width = Number(raw[0]);
9485
- const height = Number(raw[1]);
9486
- if (!(width > 0) || !(height > 0)) return fallback;
9487
- return {
9488
- width,
9489
- height
10291
+ function createStyleDefinition(style) {
10292
+ return Object.freeze({
10293
+ alignment: style.alignment ?? DEFAULT_SVG_TEXT_STYLE.alignment,
10294
+ backgroundColor: normalizeSvgTextColor(style.backgroundColor ?? "", DEFAULT_SVG_TEXT_STYLE.backgroundColor),
10295
+ font: normalizeSvgTextFont(style.font ?? ""),
10296
+ fontPercent: style.fontPercent ?? DEFAULT_SVG_TEXT_STYLE.fontPercent,
10297
+ rubyFontPercent: style.rubyFontPercent ?? DEFAULT_SVG_TEXT_RICH_STYLE.rubyFontPercent,
10298
+ rubyGap: style.rubyGap ?? DEFAULT_SVG_TEXT_RICH_STYLE.rubyGap,
10299
+ textColor: normalizeSvgTextColor(style.textColor ?? "", DEFAULT_SVG_TEXT_STYLE.textColor)
10300
+ });
10301
+ }
10302
+ function validateNativeSize(value) {
10303
+ 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.");
10304
+ return value;
10305
+ }
10306
+ function getRuntimeNativeSize(renderer) {
10307
+ const value = renderer.getNativeSize?.();
10308
+ if (!Array.isArray(value) || value.length < 2) return [480, 360];
10309
+ const width = Number(value[0]);
10310
+ const height = Number(value[1]);
10311
+ if (!Number.isFinite(width) || !Number.isFinite(height) || width <= 0 || height <= 0) return [480, 360];
10312
+ return [width, height];
10313
+ }
10314
+ function normalizeText(value) {
10315
+ return value.replace(/\\r\\n|\\n|\\r/gu, "\n");
10316
+ }
10317
+ function normalizeRichText(value) {
10318
+ return normalizeText(value.replace(/\r\n?|\n/gu, "\n"));
10319
+ }
10320
+ function contentLimitError(message) {
10321
+ return compositionError("SVG-TEXT-COMPOSITION-007", message);
10322
+ }
10323
+ function validateContentRuns(value) {
10324
+ if (!Array.isArray(value)) throw compositionError("SVG-TEXT-COMPOSITION-001", "SVG Text rich content runs must be an array.");
10325
+ if (value.length > maximumContentRuns) throw contentLimitError(`SVG Text rich content exceeds ${maximumContentRuns} runs.`);
10326
+ let characterCount = 0;
10327
+ let fragmentCount = 0;
10328
+ let lineCount = 1;
10329
+ const runs = value.map((candidate, runIndex) => {
10330
+ if (!isRecord$4(candidate)) throw compositionError("SVG-TEXT-COMPOSITION-001", `SVG Text rich content run ${runIndex} must be an object.`);
10331
+ if (candidate.type === "text") {
10332
+ requireExactKeys(candidate, ["type", "text"], [], `SVG Text rich content run ${runIndex}`);
10333
+ if (typeof candidate.text !== "string") throw compositionError("SVG-TEXT-COMPOSITION-001", `SVG Text rich content run ${runIndex} text must be a string.`);
10334
+ const text = normalizeRichText(candidate.text);
10335
+ characterCount += text.length;
10336
+ lineCount += text.split("\n").length - 1;
10337
+ fragmentCount += [...text.replace(/\n/gu, "")].length;
10338
+ return Object.freeze({
10339
+ text,
10340
+ type: "text"
10341
+ });
10342
+ }
10343
+ if (candidate.type === "ruby") {
10344
+ requireExactKeys(candidate, [
10345
+ "type",
10346
+ "base",
10347
+ "reading"
10348
+ ], [], `SVG Text rich content run ${runIndex}`);
10349
+ if (typeof candidate.base !== "string" || typeof candidate.reading !== "string") throw compositionError("SVG-TEXT-COMPOSITION-001", `SVG Text rich content run ${runIndex} ruby base and reading must be strings.`);
10350
+ const base = normalizeRichText(candidate.base);
10351
+ const reading = normalizeRichText(candidate.reading);
10352
+ if (base.length === 0 || reading.length === 0 || base.includes("\n") || reading.includes("\n")) throw compositionError("SVG-TEXT-COMPOSITION-001", `SVG Text rich content run ${runIndex} ruby base and reading must be non-empty single-line strings.`);
10353
+ if (base.length > maximumRubyBaseCharacters) throw contentLimitError(`SVG Text ruby base exceeds ${maximumRubyBaseCharacters} characters.`);
10354
+ if (reading.length > maximumRubyReadingCharacters) throw contentLimitError(`SVG Text ruby reading exceeds ${maximumRubyReadingCharacters} characters.`);
10355
+ characterCount += base.length + reading.length;
10356
+ fragmentCount += 1;
10357
+ return Object.freeze({
10358
+ base,
10359
+ reading,
10360
+ type: "ruby"
10361
+ });
10362
+ }
10363
+ throw compositionError("SVG-TEXT-COMPOSITION-001", `SVG Text rich content run ${runIndex} type is invalid.`);
10364
+ });
10365
+ if (characterCount > maximumContentCharacters) throw contentLimitError(`SVG Text rich content exceeds ${maximumContentCharacters} characters.`);
10366
+ if (lineCount > maximumContentLines) throw contentLimitError(`SVG Text rich content exceeds ${maximumContentLines} lines.`);
10367
+ if (fragmentCount > maximumLayoutFragments) throw contentLimitError(`SVG Text rich content exceeds ${maximumLayoutFragments} layout fragments.`);
10368
+ return Object.freeze(runs);
10369
+ }
10370
+ function validateMaxWidth(value) {
10371
+ if (value === void 0) return void 0;
10372
+ if (typeof value !== "number" || !Number.isFinite(value) || value <= 0 || value > maximumLayoutWidth) throw compositionError("SVG-TEXT-COMPOSITION-001", `SVG Text maxWidth must be a finite number greater than 0 and no greater than ${maximumLayoutWidth}.`);
10373
+ return value;
10374
+ }
10375
+ function layoutTextFromStyles(styles, input) {
10376
+ if (!isRecord$4(input)) throw compositionError("SVG-TEXT-COMPOSITION-001", "SVG Text layout input is invalid.");
10377
+ requireExactKeys(input, [
10378
+ "styleName",
10379
+ "text",
10380
+ "nativeSize"
10381
+ ], [], "SVG Text layout input");
10382
+ const styleName = requireName(input.styleName, "SVG Text styleName");
10383
+ const definition = styles.get(styleName);
10384
+ if (!definition) throw compositionError("SVG-TEXT-COMPOSITION-003", `SVG Text style is not defined: ${styleName}`);
10385
+ if (typeof input.text !== "string") throw compositionError("SVG-TEXT-COMPOSITION-001", "SVG Text text must be a string.");
10386
+ return createSvgTextLayout(normalizeText(input.text), definition, validateNativeSize(input.nativeSize));
10387
+ }
10388
+ function layoutRichTextFromStyles(styles, input) {
10389
+ if (!isRecord$4(input)) throw compositionError("SVG-TEXT-COMPOSITION-001", "SVG Text rich layout input is invalid.");
10390
+ requireExactKeys(input, [
10391
+ "styleName",
10392
+ "runs",
10393
+ "nativeSize"
10394
+ ], ["maxWidth"], "SVG Text rich layout input");
10395
+ const styleName = requireName(input.styleName, "SVG Text styleName");
10396
+ const definition = styles.get(styleName);
10397
+ if (!definition) throw compositionError("SVG-TEXT-COMPOSITION-003", `SVG Text style is not defined: ${styleName}`);
10398
+ const runs = validateContentRuns(input.runs);
10399
+ const nativeSize = validateNativeSize(input.nativeSize);
10400
+ const maxWidth = validateMaxWidth(input.maxWidth);
10401
+ return maxWidth === void 0 ? createSvgTextRichLayout(runs, definition, nativeSize) : createSvgTextRichLayout(runs, definition, nativeSize, maxWidth);
10402
+ }
10403
+ function createSvgTextLayoutComposition() {
10404
+ const styles = /* @__PURE__ */ new Map([[defaultStyleName, DEFAULT_SVG_TEXT_RICH_STYLE]]);
10405
+ return Object.freeze({
10406
+ defineStyle(input) {
10407
+ const style = validateStyle(input);
10408
+ styles.set(style.name, createStyleDefinition(style));
10409
+ },
10410
+ layoutRichText(input) {
10411
+ return layoutRichTextFromStyles(styles, input);
10412
+ },
10413
+ layoutText(input) {
10414
+ return layoutTextFromStyles(styles, input);
10415
+ }
10416
+ });
10417
+ }
10418
+ function createSvgTextComposition(options) {
10419
+ if (!isRecord$4(options)) throw new TypeError("SVG Text composition options must be an object.");
10420
+ const runtime = validateRuntime(options.runtime);
10421
+ const extension = new SvgTextExtension(runtime, {
10422
+ castToString: (value) => String(value),
10423
+ listenForRuntimeEvents: false
10424
+ });
10425
+ const styles = /* @__PURE__ */ new Map([[defaultStyleName, DEFAULT_SVG_TEXT_RICH_STYLE]]);
10426
+ const targets = /* @__PURE__ */ new Set();
10427
+ let disposed = false;
10428
+ function ensureActive() {
10429
+ if (disposed) throw compositionError("SVG-TEXT-COMPOSITION-004", "SVG Text composition has been released.");
10430
+ }
10431
+ return Object.freeze({
10432
+ defineStyle(input) {
10433
+ ensureActive();
10434
+ const style = validateStyle(input);
10435
+ extension.defineStyle({
10436
+ ALIGN: style.alignment ?? "",
10437
+ BACKGROUND: style.backgroundColor ?? "",
10438
+ FONT: style.font ?? "",
10439
+ RUBY_GAP: style.rubyGap ?? "",
10440
+ RUBY_SIZE: style.rubyFontPercent ?? "",
10441
+ SIZE: style.fontPercent ?? "",
10442
+ STYLE: style.name,
10443
+ TEXT_COLOR: style.textColor ?? ""
10444
+ });
10445
+ styles.set(style.name, createStyleDefinition(style));
10446
+ },
10447
+ layoutRichText(input) {
10448
+ ensureActive();
10449
+ return layoutRichTextFromStyles(styles, input);
10450
+ },
10451
+ layoutText(input) {
10452
+ ensureActive();
10453
+ return layoutTextFromStyles(styles, input);
10454
+ },
10455
+ measureText(input) {
10456
+ ensureActive();
10457
+ if (!isRecord$4(input)) throw compositionError("SVG-TEXT-COMPOSITION-001", "SVG Text measure input is invalid.");
10458
+ requireExactKeys(input, ["styleName", "text"], [], "SVG Text measure input");
10459
+ const styleName = requireName(input.styleName, "SVG Text styleName");
10460
+ if (!styles.has(styleName)) throw compositionError("SVG-TEXT-COMPOSITION-003", `SVG Text style is not defined: ${styleName}`);
10461
+ if (typeof input.text !== "string") throw compositionError("SVG-TEXT-COMPOSITION-001", "SVG Text text must be a string.");
10462
+ return extension.measureText(styleName, input.text);
10463
+ },
10464
+ measureRichText(input) {
10465
+ ensureActive();
10466
+ if (!isRecord$4(input)) throw compositionError("SVG-TEXT-COMPOSITION-001", "SVG Text rich measure input is invalid.");
10467
+ requireExactKeys(input, ["styleName", "runs"], ["maxWidth"], "SVG Text rich measure input");
10468
+ const styleName = requireName(input.styleName, "SVG Text styleName");
10469
+ const definition = styles.get(styleName);
10470
+ if (!definition) throw compositionError("SVG-TEXT-COMPOSITION-003", `SVG Text style is not defined: ${styleName}`);
10471
+ const runs = validateContentRuns(input.runs);
10472
+ const maxWidth = validateMaxWidth(input.maxWidth);
10473
+ const nativeSize = getRuntimeNativeSize(runtime.renderer);
10474
+ const layout = maxWidth === void 0 ? createSvgTextRichLayout(runs, definition, nativeSize) : createSvgTextRichLayout(runs, definition, nativeSize, maxWidth);
10475
+ return Math.max(0, ...layout.lines.map((line) => line.width));
10476
+ },
10477
+ setRichText(input) {
10478
+ ensureActive();
10479
+ if (!isRecord$4(input)) throw compositionError("SVG-TEXT-COMPOSITION-001", "SVG Text rich actor input is invalid.");
10480
+ requireExactKeys(input, [
10481
+ "styleName",
10482
+ "target",
10483
+ "runs"
10484
+ ], ["maxWidth"], "SVG Text rich actor input");
10485
+ const target = validateTarget(input.target);
10486
+ const styleName = requireName(input.styleName, "SVG Text styleName");
10487
+ if (!styles.has(styleName)) throw compositionError("SVG-TEXT-COMPOSITION-003", `SVG Text style is not defined: ${styleName}`);
10488
+ const runs = validateContentRuns(input.runs);
10489
+ const maxWidth = validateMaxWidth(input.maxWidth);
10490
+ extension.setCompositionText(styleName, (definition, nativeSize) => {
10491
+ return renderSvgTextRichLayout(maxWidth === void 0 ? createSvgTextRichLayout(runs, definition, nativeSize) : createSvgTextRichLayout(runs, definition, nativeSize, maxWidth));
10492
+ }, target);
10493
+ targets.add(target);
10494
+ },
10495
+ setText(input) {
10496
+ ensureActive();
10497
+ if (!isRecord$4(input)) throw compositionError("SVG-TEXT-COMPOSITION-001", "SVG Text actor input is invalid.");
10498
+ requireExactKeys(input, [
10499
+ "styleName",
10500
+ "target",
10501
+ "text"
10502
+ ], [], "SVG Text actor input");
10503
+ const target = validateTarget(input.target);
10504
+ const styleName = requireName(input.styleName, "SVG Text styleName");
10505
+ if (!styles.has(styleName)) throw compositionError("SVG-TEXT-COMPOSITION-003", `SVG Text style is not defined: ${styleName}`);
10506
+ if (typeof input.text !== "string") throw compositionError("SVG-TEXT-COMPOSITION-001", "SVG Text text must be a string.");
10507
+ extension.setText({
10508
+ STYLE: styleName,
10509
+ TEXT: input.text
10510
+ }, { target });
10511
+ targets.add(target);
10512
+ },
10513
+ releaseTarget(value) {
10514
+ ensureActive();
10515
+ const target = validateTarget(value);
10516
+ if (!targets.delete(target)) throw compositionError("SVG-TEXT-COMPOSITION-005", "SVG Text target is not owned by this composition.");
10517
+ if (!extension.releaseTextActor(target)) throw compositionError("SVG-TEXT-COMPOSITION-005", "SVG Text target ownership is inconsistent.");
10518
+ },
10519
+ releaseAll() {
10520
+ if (disposed) return;
10521
+ disposed = true;
10522
+ const errors = [];
10523
+ for (const target of targets) try {
10524
+ extension.releaseTextActor(target);
10525
+ } catch (error) {
10526
+ errors.push(error);
10527
+ }
10528
+ targets.clear();
10529
+ styles.clear();
10530
+ if (errors.length > 0) {
10531
+ const error = compositionError("SVG-TEXT-COMPOSITION-006", "SVG Text composition failed to release one or more skins.");
10532
+ Object.defineProperty(error, "errors", { value: Object.freeze([...errors]) });
10533
+ throw error;
10534
+ }
10535
+ }
10536
+ });
10537
+ }
10538
+ //#endregion
10539
+ //#region src/turbowarp-svg-text-adapter.ts
10540
+ function isRecord$3(value) {
10541
+ return typeof value === "object" && value !== null && !Array.isArray(value);
10542
+ }
10543
+ function validateExtension(value) {
10544
+ if (!isRecord$3(value) || typeof value.setText !== "function" || typeof value.releaseTextActor !== "function") throw new TypeError("TurboWarp SVG Text adapter requires setText and releaseTextActor.");
10545
+ return value;
10546
+ }
10547
+ function validateComposition(value) {
10548
+ if (!isRecord$3(value) || typeof value.setText !== "function" || typeof value.releaseTarget !== "function") throw new TypeError("SVG Text composition adapter requires setText and releaseTarget.");
10549
+ return value;
10550
+ }
10551
+ function validateLayoutComposition(value) {
10552
+ if (!isRecord$3(value) || typeof value.layoutText !== "function") throw new TypeError("SVG Text overlay adapter requires the layoutText composition API.");
10553
+ return value;
10554
+ }
10555
+ function requireFiniteNumber(value, label) {
10556
+ const result = Number(value);
10557
+ if (!Number.isFinite(result)) throw new TypeError(`${label} must be a finite number.`);
10558
+ return result;
10559
+ }
10560
+ function adaptSvgTextLayout(value) {
10561
+ if (!isRecord$3(value) || !isRecord$3(value.style) || !Array.isArray(value.lines)) throw new TypeError("SVG Text layout result is invalid.");
10562
+ const style = value.style;
10563
+ const alignment = style.alignment;
10564
+ if (alignment !== "left" && alignment !== "center" && alignment !== "right") throw new TypeError("SVG Text layout alignment is invalid.");
10565
+ const width = requireFiniteNumber(value.width, "SVG Text layout width");
10566
+ const height = requireFiniteNumber(value.height, "SVG Text layout height");
10567
+ const lines = Object.freeze(value.lines.map((line) => {
10568
+ if (!isRecord$3(line) || typeof line.text !== "string") throw new TypeError("SVG Text layout line is invalid.");
10569
+ return Object.freeze({
10570
+ baseline: requireFiniteNumber(line.baseline, "SVG Text line baseline") - height / 2,
10571
+ text: line.text,
10572
+ x: requireFiniteNumber(line.x, "SVG Text line x") - width / 2
10573
+ });
10574
+ }));
10575
+ return Object.freeze({
10576
+ alignment,
10577
+ backgroundColor: String(style.backgroundColor),
10578
+ backgroundCornerRadius: requireFiniteNumber(style.cornerRadius, "SVG Text corner radius"),
10579
+ fill: String(style.textColor),
10580
+ fontFamily: String(style.font),
10581
+ fontSize: requireFiniteNumber(style.fontSize, "SVG Text font size"),
10582
+ height,
10583
+ lineHeight: requireFiniteNumber(style.lineHeight, "SVG Text line height"),
10584
+ lines,
10585
+ preserveWhitespace: value.preserveWhitespace !== false,
10586
+ width
10587
+ });
10588
+ }
10589
+ /**
10590
+ * Adapt the TurboWarp SVG Text extension to Bubble's host-neutral text
10591
+ * capability contract.
10592
+ */
10593
+ function createTurboWarpSvgTextCapability(extensionInput) {
10594
+ const extension = validateExtension(extensionInput);
10595
+ return Object.freeze({
10596
+ setText({ styleName, target, text }) {
10597
+ extension.setText({
10598
+ STYLE: styleName,
10599
+ TEXT: text
10600
+ }, { target });
10601
+ },
10602
+ releaseTarget(target) {
10603
+ extension.releaseTextActor(target);
10604
+ },
10605
+ measureText({ styleName, text }) {
10606
+ if (typeof extension.measureText !== "function") throw new Error("TurboWarp SVG Text does not provide text measurement.");
10607
+ return extension.measureText(styleName, text);
10608
+ }
10609
+ });
10610
+ }
10611
+ /**
10612
+ * Adapt the SVG Text package's composition API to Bubble's text capability.
10613
+ * This helper keeps the core package independent from SVG Text's target type.
10614
+ */
10615
+ function createSvgTextCompositionCapability(compositionInput) {
10616
+ const composition = validateComposition(compositionInput);
10617
+ const capability = {
10618
+ setText({ styleName, target, text }) {
10619
+ composition.setText({
10620
+ styleName,
10621
+ target,
10622
+ text
10623
+ });
10624
+ },
10625
+ releaseTarget(target) {
10626
+ composition.releaseTarget(target);
10627
+ }
9490
10628
  };
10629
+ if (typeof composition.measureText === "function") capability.measureText = ({ styleName, text }) => composition.measureText?.({
10630
+ styleName,
10631
+ text
10632
+ }) ?? 0;
10633
+ return Object.freeze(capability);
10634
+ }
10635
+ /**
10636
+ * Adapt SVG Text's host-neutral layout composition to Bubble's SVG overlay.
10637
+ * The adapter preserves SVG Text's line coordinates without creating skins.
10638
+ */
10639
+ function createSvgTextOverlayTextCapability(compositionInput) {
10640
+ const composition = validateLayoutComposition(compositionInput);
10641
+ return Object.freeze({
10642
+ layoutText({ nativeSize, styleName, text }) {
10643
+ return adaptSvgTextLayout(composition.layoutText({
10644
+ nativeSize: [nativeSize.width, nativeSize.height],
10645
+ styleName,
10646
+ text
10647
+ }));
10648
+ },
10649
+ measureText({ nativeSize, styleName, text }) {
10650
+ const layout = composition.layoutText({
10651
+ nativeSize: [nativeSize.width, nativeSize.height],
10652
+ styleName,
10653
+ text
10654
+ });
10655
+ return Math.max(1, ...layout.lines.map((line) => requireFiniteNumber(line.width, "SVG Text line width")));
10656
+ }
10657
+ });
10658
+ }
10659
+ /**
10660
+ * Adapts the stock SVG Text extension's shared named-style layout registry.
10661
+ */
10662
+ function createTurboWarpSvgTextOverlayTextCapability(extensionInput) {
10663
+ if (!isRecord$3(extensionInput) || typeof extensionInput.getLayoutCapability !== "function") throw new TypeError("TurboWarp SVG Text overlay adapter requires SVG Text 0.8.1 getLayoutCapability().");
10664
+ return createSvgTextOverlayTextCapability(extensionInput.getLayoutCapability());
10665
+ }
10666
+ //#endregion
10667
+ //#region src/asset-manager-image-adapter.ts
10668
+ var supportedMimeTypes = /* @__PURE__ */ new Set([
10669
+ "image/avif",
10670
+ "image/gif",
10671
+ "image/jpeg",
10672
+ "image/png",
10673
+ "image/svg+xml",
10674
+ "image/webp"
10675
+ ]);
10676
+ function isRecord$2(value) {
10677
+ return typeof value === "object" && value !== null && !Array.isArray(value);
10678
+ }
10679
+ function normalizeMimeType(value) {
10680
+ const mimeType = value.split(";", 1)[0]?.trim().toLowerCase() ?? "";
10681
+ if (mimeType === "image/jpg" || mimeType === "image/pjpeg") return "image/jpeg";
10682
+ if (mimeType === "image/x-png") return "image/png";
10683
+ return mimeType;
10684
+ }
10685
+ function isSupportedMimeType(value) {
10686
+ return supportedMimeTypes.has(normalizeMimeType(value));
10687
+ }
10688
+ function requireAssetManagerResource(value) {
10689
+ 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().");
10690
+ return value;
10691
+ }
10692
+ /**
10693
+ * Adapts Asset Manager's host-neutral DOM resource API to Bubble's SVG overlay contract.
10694
+ * Asset Manager owns byte validation and SVG sanitization; Bubble owns its capability shape.
10695
+ */
10696
+ function createAssetManagerSvgOverlayImageCapability(capabilityInput) {
10697
+ 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.");
10698
+ const capability = capabilityInput;
10699
+ return Object.freeze({
10700
+ isRegistered(name) {
10701
+ return capability.isRegistered(name) && isSupportedMimeType(capability.getMimeType(name));
10702
+ },
10703
+ getMimeType(name) {
10704
+ return normalizeMimeType(capability.getMimeType(name));
10705
+ },
10706
+ async resolveImage(name) {
10707
+ const declaredMimeType = normalizeMimeType(capability.getMimeType(name));
10708
+ if (!capability.isRegistered(name) || !isSupportedMimeType(declaredMimeType)) throw new TypeError("Asset Manager image is not registered with a Bubble-compatible MIME type.");
10709
+ const resource = await capability.resolveDOMImageResource(name);
10710
+ try {
10711
+ requireAssetManagerResource(resource);
10712
+ const mimeType = normalizeMimeType(resource.mimeType);
10713
+ if (mimeType !== declaredMimeType) throw new TypeError("Asset Manager DOM image resource MIME type changed during resolution.");
10714
+ return Object.freeze({
10715
+ height: resource.height,
10716
+ mimeType,
10717
+ src: resource.url,
10718
+ width: resource.width,
10719
+ release: () => resource.release(),
10720
+ ...mimeType === "image/svg+xml" ? { svgSecurity: "sanitized" } : {}
10721
+ });
10722
+ } catch (error) {
10723
+ resource?.release?.();
10724
+ throw error;
10725
+ }
10726
+ }
10727
+ });
9491
10728
  }
9492
- function clamp01(value) {
10729
+ //#endregion
10730
+ //#region src/surface-motion.ts
10731
+ function clampMotionProgress(value) {
9493
10732
  return Math.max(0, Math.min(1, value));
9494
10733
  }
9495
- function easeProgress(value, ease) {
9496
- const progress = clamp01(value);
10734
+ function easeMotionProgress(value, ease) {
10735
+ const progress = clampMotionProgress(value);
9497
10736
  switch (ease) {
9498
10737
  case "linear": return progress;
9499
10738
  case "easeIn": return progress * progress;
@@ -9503,9 +10742,8 @@
9503
10742
  }
9504
10743
  }
9505
10744
  /**
9506
- * Drives a motion with the same scheduler used by frame loops and reveal.
9507
- * The adapter intentionally does not depend on requestAnimationFrame so a
9508
- * host can provide deterministic time in tests and non-browser runtimes.
10745
+ * Drive a motion with Bubble's scheduler so tests and non-browser hosts can
10746
+ * provide deterministic time without requestAnimationFrame.
9509
10747
  */
9510
10748
  function runMotionTimeline(scheduler, durationSeconds, onFrame) {
9511
10749
  const durationMilliseconds = Math.max(0, durationSeconds * 1e3);
@@ -9520,7 +10758,7 @@
9520
10758
  const step = Math.min(16, durationMilliseconds - elapsed);
9521
10759
  elapsed += step;
9522
10760
  try {
9523
- onFrame(clamp01(elapsed / durationMilliseconds));
10761
+ onFrame(clampMotionProgress(elapsed / durationMilliseconds));
9524
10762
  } catch (error) {
9525
10763
  if (timer !== void 0) scheduler.clearTimeout(timer);
9526
10764
  reject(error);
@@ -9535,6 +10773,1042 @@
9535
10773
  timer = scheduler.setTimeout(tick, Math.min(16, durationMilliseconds));
9536
10774
  });
9537
10775
  }
10776
+ //#endregion
10777
+ //#region src/svg-overlay-surface.ts
10778
+ var svgNamespace = "http://www.w3.org/2000/svg";
10779
+ var xmlNamespace = "http://www.w3.org/XML/1998/namespace";
10780
+ var portraitBoxSize$1 = 96;
10781
+ var indicatorBoxSize$1 = 18;
10782
+ var contentGap$1 = 8;
10783
+ var stageSafeMargin$1 = 16;
10784
+ var overlayTextTargetMarker = Symbol("BubbleSvgOverlayTextTarget");
10785
+ var overlayImageTargetMarker = Symbol("BubbleSvgOverlayImageTarget");
10786
+ var overlaySurfaceSequence = 0;
10787
+ Object.freeze(["scratch-render", "svg-overlay"]);
10788
+ function isRecord$1(value) {
10789
+ return typeof value === "object" && value !== null && !Array.isArray(value);
10790
+ }
10791
+ function readNativeSize(renderer) {
10792
+ const raw = renderer.getNativeSize();
10793
+ const width = Array.isArray(raw) ? Number(raw[0]) : NaN;
10794
+ const height = Array.isArray(raw) ? Number(raw[1]) : NaN;
10795
+ return Object.freeze({
10796
+ width: width > 0 ? width : 480,
10797
+ height: height > 0 ? height : 360
10798
+ });
10799
+ }
10800
+ function requireFiniteDimension(value, label) {
10801
+ const result = Number(value);
10802
+ if (!Number.isFinite(result) || result <= 0) throw new TypeError(`${label} must be a positive finite number.`);
10803
+ return result;
10804
+ }
10805
+ function requireSafeColor(value, label) {
10806
+ if (typeof value !== "string" || value.length === 0 || value.length > 128) throw new TypeError(`${label} must be a non-empty color string.`);
10807
+ if (/url\s*\(|[<>;]/iu.test(value)) throw new TypeError(`${label} contains a disallowed SVG value.`);
10808
+ return value;
10809
+ }
10810
+ function requireSafeFontFamily(value) {
10811
+ if (typeof value !== "string" || value.length === 0 || value.length > 256 || /url\s*\(|[<>{};]/iu.test(value)) throw new TypeError("SVG overlay fontFamily is invalid.");
10812
+ return value;
10813
+ }
10814
+ function normalizeTextLayout(value) {
10815
+ if (!isRecord$1(value) || !Array.isArray(value.lines)) throw new TypeError("SVG overlay text layout is invalid.");
10816
+ const alignment = value.alignment;
10817
+ if (alignment !== "left" && alignment !== "center" && alignment !== "right") throw new TypeError("SVG overlay text alignment is invalid.");
10818
+ const fontStyle = value.fontStyle;
10819
+ if (fontStyle !== void 0 && fontStyle !== "normal" && fontStyle !== "italic") throw new TypeError("SVG overlay fontStyle is invalid.");
10820
+ const fontWeight = value.fontWeight;
10821
+ if (fontWeight !== void 0 && fontWeight !== "normal" && fontWeight !== "bold" && (!Number.isFinite(fontWeight) || Number(fontWeight) < 1 || Number(fontWeight) > 1e3)) throw new TypeError("SVG overlay fontWeight is invalid.");
10822
+ const lines = Object.freeze(value.lines.map((line) => {
10823
+ if (typeof line === "string") return line;
10824
+ if (!isRecord$1(line) || typeof line.text !== "string") throw new TypeError("SVG overlay text lines must be strings or positioned line records.");
10825
+ const hasX = line.x !== void 0;
10826
+ if (hasX !== (line.baseline !== void 0)) throw new TypeError("SVG overlay positioned text lines require both x and baseline.");
10827
+ if (hasX && (!Number.isFinite(line.x) || !Number.isFinite(line.baseline))) throw new TypeError("SVG overlay text line coordinates must be finite numbers.");
10828
+ return Object.freeze({
10829
+ text: line.text,
10830
+ ...hasX ? {
10831
+ x: Number(line.x),
10832
+ baseline: Number(line.baseline)
10833
+ } : {}
10834
+ });
10835
+ }));
10836
+ const backgroundColor = value.backgroundColor === void 0 ? void 0 : requireSafeColor(value.backgroundColor, "SVG overlay backgroundColor");
10837
+ const backgroundCornerRadius = value.backgroundCornerRadius === void 0 ? void 0 : Number(value.backgroundCornerRadius);
10838
+ if (backgroundCornerRadius !== void 0 && (!Number.isFinite(backgroundCornerRadius) || backgroundCornerRadius < 0)) throw new TypeError("SVG overlay backgroundCornerRadius must be a non-negative finite number.");
10839
+ const preserveWhitespace = value.preserveWhitespace;
10840
+ if (preserveWhitespace !== void 0 && typeof preserveWhitespace !== "boolean") throw new TypeError("SVG overlay preserveWhitespace must be a boolean.");
10841
+ return Object.freeze({
10842
+ alignment,
10843
+ fill: requireSafeColor(value.fill, "SVG overlay text fill"),
10844
+ fontFamily: requireSafeFontFamily(value.fontFamily),
10845
+ fontSize: requireFiniteDimension(value.fontSize, "SVG overlay fontSize"),
10846
+ height: requireFiniteDimension(value.height, "SVG overlay text height"),
10847
+ lineHeight: requireFiniteDimension(value.lineHeight, "SVG overlay lineHeight"),
10848
+ lines,
10849
+ width: requireFiniteDimension(value.width, "SVG overlay text width"),
10850
+ ...backgroundColor === void 0 ? {} : { backgroundColor },
10851
+ ...backgroundCornerRadius === void 0 ? {} : { backgroundCornerRadius },
10852
+ ...fontStyle === void 0 ? {} : { fontStyle },
10853
+ ...fontWeight === void 0 ? {} : { fontWeight },
10854
+ ...preserveWhitespace === void 0 ? {} : { preserveWhitespace }
10855
+ });
10856
+ }
10857
+ function createTextTarget(document, group) {
10858
+ let size = {
10859
+ width: 180,
10860
+ height: 48
10861
+ };
10862
+ let layoutProvider;
10863
+ let capturedLayoutProvider;
10864
+ let capturedSize;
10865
+ const applyLayout = (layoutInput) => {
10866
+ const layout = normalizeTextLayout(layoutInput);
10867
+ const children = [];
10868
+ if (layout.backgroundColor !== void 0 && layout.backgroundColor !== "transparent") {
10869
+ const background = document.createElementNS(svgNamespace, "rect");
10870
+ background.setAttribute("x", String(-layout.width / 2));
10871
+ background.setAttribute("y", String(-layout.height / 2));
10872
+ background.setAttribute("width", String(layout.width));
10873
+ background.setAttribute("height", String(layout.height));
10874
+ background.setAttribute("fill", layout.backgroundColor);
10875
+ if (layout.backgroundCornerRadius !== void 0) background.setAttribute("rx", String(layout.backgroundCornerRadius));
10876
+ children.push(background);
10877
+ }
10878
+ const text = document.createElementNS(svgNamespace, "text");
10879
+ const anchor = layout.alignment === "left" ? "start" : layout.alignment === "right" ? "end" : "middle";
10880
+ const x = layout.alignment === "left" ? -layout.width / 2 : layout.alignment === "right" ? layout.width / 2 : 0;
10881
+ text.setAttribute("text-anchor", anchor);
10882
+ text.setAttribute("fill", layout.fill);
10883
+ text.setAttribute("font-family", layout.fontFamily);
10884
+ text.setAttribute("font-size", String(layout.fontSize));
10885
+ if (layout.preserveWhitespace !== false) text.setAttributeNS(xmlNamespace, "xml:space", "preserve");
10886
+ if (layout.fontStyle !== void 0) text.setAttribute("font-style", layout.fontStyle);
10887
+ if (layout.fontWeight !== void 0) text.setAttribute("font-weight", String(layout.fontWeight));
10888
+ const firstBaseline = -Math.max(layout.fontSize, (layout.lines.length - 1) * layout.lineHeight + layout.fontSize) / 2 + layout.fontSize;
10889
+ layout.lines.forEach((line, index) => {
10890
+ const tspan = document.createElementNS(svgNamespace, "tspan");
10891
+ const positionedLine = typeof line === "string" ? void 0 : line;
10892
+ tspan.setAttribute("x", String(positionedLine?.x ?? x));
10893
+ tspan.setAttribute("y", String(positionedLine?.baseline ?? firstBaseline + index * layout.lineHeight));
10894
+ tspan.textContent = typeof line === "string" ? line : line.text;
10895
+ text.appendChild(tspan);
10896
+ });
10897
+ children.push(text);
10898
+ group.replaceChildren(...children);
10899
+ size = {
10900
+ width: layout.width,
10901
+ height: layout.height
10902
+ };
10903
+ };
10904
+ return Object.freeze({
10905
+ [overlayTextTargetMarker]: true,
10906
+ group,
10907
+ captureLayout() {
10908
+ capturedLayoutProvider = layoutProvider;
10909
+ capturedSize = { ...size };
10910
+ },
10911
+ clear() {
10912
+ group.replaceChildren();
10913
+ size = {
10914
+ width: 180,
10915
+ height: 48
10916
+ };
10917
+ layoutProvider = void 0;
10918
+ capturedLayoutProvider = void 0;
10919
+ capturedSize = void 0;
10920
+ },
10921
+ clearCapturedLayout() {
10922
+ capturedLayoutProvider = void 0;
10923
+ capturedSize = void 0;
10924
+ },
10925
+ getCapturedSize() {
10926
+ return capturedSize;
10927
+ },
10928
+ getSize() {
10929
+ return size;
10930
+ },
10931
+ refresh() {
10932
+ if (capturedLayoutProvider !== void 0) {
10933
+ const capturedLayout = normalizeTextLayout(capturedLayoutProvider());
10934
+ capturedSize = {
10935
+ width: capturedLayout.width,
10936
+ height: capturedLayout.height
10937
+ };
10938
+ }
10939
+ if (layoutProvider !== void 0) applyLayout(layoutProvider());
10940
+ },
10941
+ render(layout, nextLayoutProvider) {
10942
+ layoutProvider = nextLayoutProvider;
10943
+ applyLayout(layout);
10944
+ }
10945
+ });
10946
+ }
10947
+ function requireTextTarget(value) {
10948
+ const candidate = value;
10949
+ if (candidate?.[overlayTextTargetMarker] !== true) throw new TypeError("SVG overlay text target is invalid.");
10950
+ return candidate;
10951
+ }
10952
+ function createSvgOverlayTextAdapter(capabilityInput, renderer) {
10953
+ if (!isRecord$1(capabilityInput) || typeof capabilityInput.layoutText !== "function") throw new TypeError("SVG overlay backend requires a text layout capability.");
10954
+ const capability = capabilityInput;
10955
+ return Object.freeze({
10956
+ setText({ styleName, target, text }) {
10957
+ const overlayTarget = requireTextTarget(target);
10958
+ const layoutProvider = () => capability.layoutText({
10959
+ nativeSize: readNativeSize(renderer),
10960
+ styleName,
10961
+ text
10962
+ });
10963
+ overlayTarget.render(layoutProvider(), layoutProvider);
10964
+ },
10965
+ releaseTarget(target) {
10966
+ requireTextTarget(target).clear();
10967
+ },
10968
+ measureText({ styleName, text }) {
10969
+ const nativeSize = readNativeSize(renderer);
10970
+ return requireFiniteDimension(capability.measureText?.({
10971
+ nativeSize,
10972
+ styleName,
10973
+ text
10974
+ }) ?? capability.layoutText({
10975
+ nativeSize,
10976
+ styleName,
10977
+ text
10978
+ }).width, "SVG overlay measured text width");
10979
+ }
10980
+ });
10981
+ }
10982
+ function isSafeImageSource(resource) {
10983
+ if (!(/* @__PURE__ */ new Set([
10984
+ "image/avif",
10985
+ "image/gif",
10986
+ "image/jpeg",
10987
+ "image/png",
10988
+ "image/svg+xml",
10989
+ "image/webp"
10990
+ ])).has(resource.mimeType.toLowerCase())) return false;
10991
+ if (resource.mimeType.toLowerCase() === "image/svg+xml" && resource.svgSecurity !== "sanitized") return false;
10992
+ if (resource.src.startsWith("blob:")) return typeof resource.release === "function";
10993
+ return /^data:image\/(?:avif|gif|jpeg|png|webp);base64,/iu.test(resource.src);
10994
+ }
10995
+ async function releaseImageResource(resource) {
10996
+ await resource?.release?.();
10997
+ }
10998
+ function createImageTarget(document, id, group) {
10999
+ const image = document.createElementNS(svgNamespace, "image");
11000
+ image.setAttribute("preserveAspectRatio", "xMidYMid meet");
11001
+ group.appendChild(image);
11002
+ let resource;
11003
+ let displaySize = {
11004
+ width: 1,
11005
+ height: 1
11006
+ };
11007
+ let resourceGeneration = 0;
11008
+ const applyDisplaySize = () => {
11009
+ image.setAttribute("x", String(-displaySize.width / 2));
11010
+ image.setAttribute("y", String(-displaySize.height / 2));
11011
+ image.setAttribute("width", String(displaySize.width));
11012
+ image.setAttribute("height", String(displaySize.height));
11013
+ };
11014
+ applyDisplaySize();
11015
+ return Object.freeze({
11016
+ id,
11017
+ isStage: false,
11018
+ [overlayImageTargetMarker]: true,
11019
+ group,
11020
+ async applyResource(nextResource) {
11021
+ const generation = resourceGeneration + 1;
11022
+ resourceGeneration = generation;
11023
+ try {
11024
+ requireFiniteDimension(nextResource.width, "SVG overlay image width");
11025
+ requireFiniteDimension(nextResource.height, "SVG overlay image height");
11026
+ if (typeof nextResource.mimeType !== "string" || !nextResource.mimeType.startsWith("image/") || typeof nextResource.src !== "string" || !isSafeImageSource(nextResource)) throw new TypeError("SVG overlay image resources must use a supported MIME type, a releasable blob URL or approved raster data URL, and sanitized SVG metadata when applicable.");
11027
+ } catch (error) {
11028
+ await releaseImageResource(nextResource);
11029
+ throw error;
11030
+ }
11031
+ if (generation !== resourceGeneration) {
11032
+ await releaseImageResource(nextResource);
11033
+ return;
11034
+ }
11035
+ const previous = resource;
11036
+ resource = nextResource;
11037
+ image.setAttribute("href", nextResource.src);
11038
+ await releaseImageResource(previous);
11039
+ },
11040
+ getSize() {
11041
+ return resource ? {
11042
+ width: resource.width,
11043
+ height: resource.height
11044
+ } : {
11045
+ width: 1,
11046
+ height: 1
11047
+ };
11048
+ },
11049
+ async release() {
11050
+ resourceGeneration += 1;
11051
+ const previous = resource;
11052
+ resource = void 0;
11053
+ image.removeAttribute("href");
11054
+ await releaseImageResource(previous);
11055
+ },
11056
+ setDisplaySize(nextSize) {
11057
+ displaySize = nextSize;
11058
+ applyDisplaySize();
11059
+ },
11060
+ setVisible(visible) {
11061
+ group.setAttribute("visibility", visible ? "visible" : "hidden");
11062
+ }
11063
+ });
11064
+ }
11065
+ function requireImageTarget(value) {
11066
+ const candidate = value;
11067
+ if (candidate?.[overlayImageTargetMarker] !== true) throw new TypeError("SVG overlay image target is invalid.");
11068
+ return candidate;
11069
+ }
11070
+ function createSvgOverlayImageAdapter(capabilityInput) {
11071
+ if (!isRecord$1(capabilityInput) || typeof capabilityInput.isRegistered !== "function" || typeof capabilityInput.getMimeType !== "function" || typeof capabilityInput.resolveImage !== "function") throw new TypeError("SVG overlay image capability is invalid.");
11072
+ const capability = capabilityInput;
11073
+ return Object.freeze({
11074
+ isRegistered(name) {
11075
+ return capability.isRegistered(name);
11076
+ },
11077
+ getMimeType(name) {
11078
+ return capability.getMimeType(name);
11079
+ },
11080
+ async applyToTarget(name, target) {
11081
+ await requireImageTarget(target).applyResource(await capability.resolveImage(name));
11082
+ }
11083
+ });
11084
+ }
11085
+ function createSvgOverlaySurfaceManager(renderer, documentInput) {
11086
+ const root = documentInput.createElementNS(svgNamespace, "svg");
11087
+ root.setAttribute("xmlns", svgNamespace);
11088
+ root.setAttribute("aria-hidden", "true");
11089
+ root.setAttribute("focusable", "false");
11090
+ root.setAttribute("data-bubble-render-backend", "svg-overlay");
11091
+ root.style.display = "block";
11092
+ root.style.overflow = "hidden";
11093
+ root.style.pointerEvents = "none";
11094
+ const groups = /* @__PURE__ */ new Set();
11095
+ let attached = false;
11096
+ const updateNativeSize = () => {
11097
+ const size = readNativeSize(renderer);
11098
+ root.setAttribute("width", String(size.width));
11099
+ root.setAttribute("height", String(size.height));
11100
+ root.setAttribute("viewBox", `0 0 ${size.width} ${size.height}`);
11101
+ return size;
11102
+ };
11103
+ return Object.freeze({
11104
+ document: documentInput,
11105
+ renderer,
11106
+ acquire(group) {
11107
+ if (groups.has(group)) return;
11108
+ updateNativeSize();
11109
+ if (!attached) try {
11110
+ renderer.addOverlay(root, "scale");
11111
+ attached = true;
11112
+ } catch (error) {
11113
+ renderer.removeOverlay(root);
11114
+ throw error;
11115
+ }
11116
+ root.appendChild(group);
11117
+ groups.add(group);
11118
+ },
11119
+ release(group) {
11120
+ if (!groups.delete(group)) return;
11121
+ group.remove();
11122
+ if (groups.size === 0 && attached) {
11123
+ renderer.removeOverlay(root);
11124
+ attached = false;
11125
+ }
11126
+ },
11127
+ updateNativeSize
11128
+ });
11129
+ }
11130
+ function targetBounds$1(target) {
11131
+ try {
11132
+ const bounds = target.getBoundsForBubble?.();
11133
+ if (bounds && [
11134
+ bounds.bottom,
11135
+ bounds.left,
11136
+ bounds.right,
11137
+ bounds.top
11138
+ ].every((value) => Number.isFinite(value))) return bounds;
11139
+ } catch {}
11140
+ const x = Number.isFinite(target.x) ? Number(target.x) : 0;
11141
+ const y = Number.isFinite(target.y) ? Number(target.y) : 0;
11142
+ return {
11143
+ bottom: y,
11144
+ left: x,
11145
+ right: x,
11146
+ top: y
11147
+ };
11148
+ }
11149
+ function clamp$1(value, minimum, maximum) {
11150
+ if (maximum < minimum) return (minimum + maximum) / 2;
11151
+ return Math.min(maximum, Math.max(minimum, value));
11152
+ }
11153
+ function tailDirectionForPlacement$1(direction) {
11154
+ const vector = bubbleDirectionVector(direction);
11155
+ return (Math.atan2(-vector.x, -vector.y) * 180 / Math.PI % 360 + 360) % 360;
11156
+ }
11157
+ var allowedBodyElements = /* @__PURE__ */ new Set([
11158
+ "circle",
11159
+ "g",
11160
+ "path",
11161
+ "rect",
11162
+ "text",
11163
+ "title"
11164
+ ]);
11165
+ var allowedBodyAttributes = /* @__PURE__ */ new Set([
11166
+ "cx",
11167
+ "cy",
11168
+ "d",
11169
+ "data-boolean-operation",
11170
+ "data-tail-base-on-border",
11171
+ "fill",
11172
+ "fill-rule",
11173
+ "font-family",
11174
+ "font-size",
11175
+ "height",
11176
+ "opacity",
11177
+ "paint-order",
11178
+ "r",
11179
+ "rx",
11180
+ "stroke",
11181
+ "stroke-dasharray",
11182
+ "stroke-linejoin",
11183
+ "stroke-width",
11184
+ "transform",
11185
+ "width",
11186
+ "xml:space",
11187
+ "x",
11188
+ "y"
11189
+ ]);
11190
+ function copyAllowedBodyNode(source, document) {
11191
+ const name = source.localName;
11192
+ if (!allowedBodyElements.has(name)) throw new TypeError(`Bubble body SVG element is not allowed: ${name}`);
11193
+ const result = document.createElementNS(svgNamespace, name);
11194
+ for (const attribute of source.getAttributeNames()) {
11195
+ if (!allowedBodyAttributes.has(attribute)) throw new TypeError(`Bubble body SVG attribute is not allowed: ${attribute}`);
11196
+ const value = source.getAttribute(attribute) ?? "";
11197
+ if (/javascript:|url\s*\(/iu.test(value)) throw new TypeError("Bubble body SVG contains an unsafe attribute value.");
11198
+ result.setAttribute(attribute, value);
11199
+ }
11200
+ if (name === "title" || name === "text") result.textContent = source.textContent ?? "";
11201
+ for (const child of Array.from(source.children)) result.appendChild(copyAllowedBodyNode(child, document));
11202
+ return result;
11203
+ }
11204
+ function replaceBodyFromCanonicalSvg(group, svg, document) {
11205
+ const Parser = document.defaultView?.DOMParser;
11206
+ if (!Parser) throw new TypeError("SVG overlay backend requires DOMParser.");
11207
+ const parsed = new Parser().parseFromString(svg, "image/svg+xml");
11208
+ if (parsed.querySelector("parsererror")) throw new TypeError("Canonical Bubble body SVG could not be parsed.");
11209
+ const children = Array.from(parsed.documentElement.children).map((child) => copyAllowedBodyNode(child, document));
11210
+ group.replaceChildren(...children);
11211
+ }
11212
+ function fitImage(target, boxSize, scaleMultiplier = 1) {
11213
+ const native = target.getSize();
11214
+ const scale = Math.min(boxSize / native.width, boxSize / native.height);
11215
+ const size = {
11216
+ width: native.width * scale * scaleMultiplier,
11217
+ height: native.height * scale * scaleMultiplier
11218
+ };
11219
+ target.setDisplaySize(size);
11220
+ return size;
11221
+ }
11222
+ function createSvgOverlaySurface(manager, actor, actorKey, kind, style, scheduler) {
11223
+ const { document, renderer } = manager;
11224
+ const sequence = overlaySurfaceSequence;
11225
+ overlaySurfaceSequence += 1;
11226
+ const surfaceGroup = document.createElementNS(svgNamespace, "g");
11227
+ surfaceGroup.setAttribute("data-bubble-surface", `${actorKey}:${sequence}`);
11228
+ const bodyGroup = document.createElementNS(svgNamespace, "g");
11229
+ bodyGroup.setAttribute("data-bubble-layer", "body");
11230
+ surfaceGroup.appendChild(bodyGroup);
11231
+ const createLayerGroup = (layer) => {
11232
+ const group = document.createElementNS(svgNamespace, "g");
11233
+ group.setAttribute("data-bubble-layer", layer);
11234
+ group.setAttribute("visibility", "hidden");
11235
+ surfaceGroup.appendChild(group);
11236
+ return group;
11237
+ };
11238
+ const portraitBase = createImageTarget(document, `bubble:${actorKey}:${sequence}:portrait-base`, createLayerGroup("portrait-base"));
11239
+ const portraitBlink = createImageTarget(document, `bubble:${actorKey}:${sequence}:portrait-blink`, createLayerGroup("portrait-blink"));
11240
+ const portraitLipSync = createImageTarget(document, `bubble:${actorKey}:${sequence}:portrait-lip-sync`, createLayerGroup("portrait-lip-sync"));
11241
+ const textGroup = createLayerGroup("text");
11242
+ const text = createTextTarget(document, textGroup);
11243
+ const continueIndicator = createImageTarget(document, `bubble:${actorKey}:${sequence}:continue-indicator`, createLayerGroup("continue-indicator"));
11244
+ const targets = Object.freeze({
11245
+ text,
11246
+ portraitBase,
11247
+ portraitBlink,
11248
+ portraitLipSync,
11249
+ continueIndicator
11250
+ });
11251
+ const layerTargets = /* @__PURE__ */ new Map([
11252
+ ["portraitBase", portraitBase],
11253
+ ["portraitBlink", portraitBlink],
11254
+ ["portraitLipSync", portraitLipSync],
11255
+ ["continueIndicator", continueIndicator]
11256
+ ]);
11257
+ const layerVisibility = /* @__PURE__ */ new Map();
11258
+ const clipId = `bubble-portrait-clip-${sequence}`;
11259
+ const definitions = document.createElementNS(svgNamespace, "defs");
11260
+ const clipPath = document.createElementNS(svgNamespace, "clipPath");
11261
+ const clipRect = document.createElementNS(svgNamespace, "rect");
11262
+ clipPath.setAttribute("id", clipId);
11263
+ clipPath.appendChild(clipRect);
11264
+ definitions.appendChild(clipPath);
11265
+ surfaceGroup.insertBefore(definitions, bodyGroup);
11266
+ let currentStyle = style;
11267
+ let disposed = false;
11268
+ let surfaceVisible = false;
11269
+ let bodySignature = "";
11270
+ let motionTranslation = [0, 0];
11271
+ let motionScaleMultiplier = 1;
11272
+ let motionOpacity = 1;
11273
+ let center = [0, 0];
11274
+ let shapeTransition;
11275
+ let scratchTextLayout;
11276
+ let scratchPointsLeft = false;
11277
+ const applyMotionTransform = (native = manager.updateNativeSize()) => {
11278
+ const centerX = native.width / 2 + center[0];
11279
+ const centerY = native.height / 2 - center[1];
11280
+ const translatedX = centerX + motionTranslation[0];
11281
+ const translatedY = centerY - motionTranslation[1];
11282
+ surfaceGroup.setAttribute("transform", `translate(${translatedX} ${translatedY}) scale(${motionScaleMultiplier}) translate(${-centerX} ${-centerY})`);
11283
+ surfaceGroup.setAttribute("opacity", String(motionOpacity));
11284
+ };
11285
+ const layerAllowedByStyle = (layer) => {
11286
+ if (layer === "continueIndicator") return currentStyle.continueIndicator !== void 0;
11287
+ if (layer === "portraitBase") return currentStyle.portrait !== void 0;
11288
+ if (layer === "portraitBlink") return currentStyle.portrait?.blink !== void 0;
11289
+ return currentStyle.portrait?.lipSync !== void 0;
11290
+ };
11291
+ const updateVisibility = (nativeSize) => {
11292
+ const actorVisible = currentStyle.placement.basis === "background" || actor.visible !== false;
11293
+ const visible = surfaceVisible && actorVisible && motionOpacity > 0;
11294
+ const scratchDefaultRendered = currentStyle.layoutProfile === "scratch-default" && scratchTextLayout !== void 0;
11295
+ surfaceGroup.setAttribute("visibility", visible ? "visible" : "hidden");
11296
+ bodyGroup.setAttribute("visibility", visible && (scratchDefaultRendered || currentStyle.visualStyle !== "NO_BUBBLE") ? "visible" : "hidden");
11297
+ textGroup.setAttribute("visibility", visible && !scratchDefaultRendered ? "visible" : "hidden");
11298
+ for (const [layer, target] of layerTargets) target.setVisible(visible && layerAllowedByStyle(layer) && (layerVisibility.get(layer) ?? false));
11299
+ applyMotionTransform(nativeSize);
11300
+ };
11301
+ const position = () => {
11302
+ if (disposed) return;
11303
+ const native = manager.updateNativeSize();
11304
+ if (currentStyle.layoutProfile === "scratch-default" && scratchTextLayout !== void 0) {
11305
+ const metrics = scratchBubbleMetrics(scratchTextLayout);
11306
+ const nextPosition = positionScratchBubble({
11307
+ bounds: targetBounds$1(actor),
11308
+ height: metrics.height,
11309
+ pointsLeft: scratchPointsLeft,
11310
+ stageHeight: native.height,
11311
+ stageWidth: native.width,
11312
+ width: metrics.width
11313
+ });
11314
+ scratchPointsLeft = nextPosition.pointsLeft;
11315
+ center = [nextPosition.centerX, nextPosition.centerY];
11316
+ const nextBodySignature = JSON.stringify({
11317
+ kind,
11318
+ layout: scratchTextLayout,
11319
+ pointsLeft: scratchPointsLeft
11320
+ });
11321
+ if (nextBodySignature !== bodySignature) {
11322
+ replaceBodyFromCanonicalSvg(bodyGroup, renderScratchBubbleSvg({
11323
+ kind,
11324
+ layout: scratchTextLayout,
11325
+ pointsLeft: scratchPointsLeft,
11326
+ title: `${currentStyle.name} ${kind} Bubble`
11327
+ }), document);
11328
+ bodySignature = nextBodySignature;
11329
+ }
11330
+ bodyGroup.setAttribute("data-bubble-style", "SCRATCH_DEFAULT");
11331
+ bodyGroup.setAttribute("data-bubble-profile", "scratch-default");
11332
+ bodyGroup.setAttribute("data-bubble-kind", kind);
11333
+ bodyGroup.setAttribute("data-bubble-body-width", String(metrics.width));
11334
+ bodyGroup.setAttribute("data-bubble-body-height", String(metrics.height));
11335
+ bodyGroup.setAttribute("transform", `translate(${native.width / 2 + nextPosition.left} ${native.height / 2 - nextPosition.top})`);
11336
+ updateVisibility(native);
11337
+ return;
11338
+ }
11339
+ bodyGroup.removeAttribute("data-bubble-profile");
11340
+ bodyGroup.removeAttribute("data-bubble-kind");
11341
+ const scaleMultiplier = currentStyle.placement.basis === "actor" ? currentStyle.offset.scalePercent / 100 : 1;
11342
+ const nativeTextSize = text.getCapturedSize() ?? text.getSize();
11343
+ const textSize = {
11344
+ width: nativeTextSize.width * scaleMultiplier,
11345
+ height: nativeTextSize.height * scaleMultiplier
11346
+ };
11347
+ const portraitZoomMultiplier = (currentStyle.portrait?.offset.zoomPercent ?? 100) / 100;
11348
+ const hasPortrait = currentStyle.portrait !== void 0;
11349
+ const portraitSize = hasPortrait ? fitImage(portraitBase, portraitBoxSize$1 * portraitZoomMultiplier, scaleMultiplier) : {
11350
+ width: 0,
11351
+ height: 0
11352
+ };
11353
+ for (const target of [portraitBlink, portraitLipSync]) if (hasPortrait) fitImage(target, portraitBoxSize$1 * portraitZoomMultiplier, scaleMultiplier);
11354
+ const indicatorSize = fitImage(continueIndicator, indicatorBoxSize$1, scaleMultiplier);
11355
+ const totalWidth = portraitSize.width + (hasPortrait ? contentGap$1 * scaleMultiplier : 0) + textSize.width;
11356
+ const contentHeight = Math.max(portraitSize.height, textSize.height);
11357
+ const minimumBodySize = bubbleBodyMinimumSize(currentStyle.visualStyle, ...shapeTransition === void 0 ? [] : [shapeTransition.from, shapeTransition.to]);
11358
+ const baseBubbleWidth = Math.max(totalWidth / scaleMultiplier + 48, minimumBodySize.width);
11359
+ const baseBubbleHeight = Math.max(contentHeight / scaleMultiplier + 48, minimumBodySize.height);
11360
+ const bubbleWidth = Math.max(totalWidth, (baseBubbleWidth - 48) * scaleMultiplier);
11361
+ const bubbleHeight = Math.max(contentHeight, (baseBubbleHeight - 48) * scaleMultiplier);
11362
+ const stageLeft = -native.width / 2;
11363
+ const stageRight = native.width / 2;
11364
+ const stageTop = native.height / 2;
11365
+ const stageBottom = -native.height / 2;
11366
+ let centerX;
11367
+ let centerY;
11368
+ if (currentStyle.placement.basis === "background") {
11369
+ centerX = 0;
11370
+ if (currentStyle.placement.region === "HEADER_LIKE") centerY = stageTop - stageSafeMargin$1 - bubbleHeight / 2;
11371
+ else if (currentStyle.placement.region === "FOOTER_LIKE") centerY = stageBottom + stageSafeMargin$1 + bubbleHeight / 2;
11372
+ else centerY = 0;
11373
+ } else {
11374
+ const nextCenter = actorRelativeBubbleCenter({
11375
+ bounds: targetBounds$1(actor),
11376
+ bubbleWidth,
11377
+ bubbleHeight,
11378
+ direction: currentStyle.placement.direction,
11379
+ distance: currentStyle.distance,
11380
+ tailLength: currentStyle.tailLength,
11381
+ offset: currentStyle.offset
11382
+ });
11383
+ centerX = nextCenter.x;
11384
+ centerY = nextCenter.y;
11385
+ }
11386
+ centerX = clamp$1(centerX, stageLeft + bubbleWidth / 2, stageRight - bubbleWidth / 2);
11387
+ centerY = clamp$1(centerY, stageBottom + bubbleHeight / 2, stageTop - bubbleHeight / 2);
11388
+ center = [centerX, centerY];
11389
+ const tailDirection = currentStyle.placement.basis === "actor" ? tailDirectionForPlacement$1(currentStyle.placement.direction) : null;
11390
+ const bodyOffset = currentStyle.placement.basis === "actor" ? [
11391
+ currentStyle.offset.x,
11392
+ currentStyle.offset.y,
11393
+ currentStyle.offset.scalePercent
11394
+ ] : [
11395
+ 0,
11396
+ 0,
11397
+ 100
11398
+ ];
11399
+ const bodyCenterOffset = tailDirection === null ? {
11400
+ x: 0,
11401
+ y: 0
11402
+ } : bubbleBodyCenterOffset({
11403
+ style: currentStyle.visualStyle,
11404
+ width: baseBubbleWidth,
11405
+ height: baseBubbleHeight,
11406
+ tailDirection,
11407
+ tailLength: currentStyle.tailLength,
11408
+ offset: bodyOffset
11409
+ });
11410
+ const nextBodySignature = JSON.stringify({
11411
+ baseBubbleHeight,
11412
+ baseBubbleWidth,
11413
+ bodyOffset,
11414
+ shapeTransition,
11415
+ tailDirection,
11416
+ tailLength: currentStyle.tailLength,
11417
+ visualStyle: currentStyle.visualStyle
11418
+ });
11419
+ if (nextBodySignature !== bodySignature) {
11420
+ replaceBodyFromCanonicalSvg(bodyGroup, renderBubbleSvg({
11421
+ style: currentStyle.visualStyle,
11422
+ lines: [],
11423
+ width: baseBubbleWidth,
11424
+ height: baseBubbleHeight,
11425
+ tailDirection,
11426
+ tailLength: currentStyle.tailLength,
11427
+ offset: bodyOffset,
11428
+ title: `${currentStyle.name} Bubble body`,
11429
+ ...shapeTransition === void 0 ? {} : { shapeTransition }
11430
+ }), document);
11431
+ bodySignature = nextBodySignature;
11432
+ }
11433
+ bodyGroup.setAttribute("data-bubble-style", currentStyle.visualStyle);
11434
+ bodyGroup.setAttribute("data-bubble-body-width", String(baseBubbleWidth));
11435
+ bodyGroup.setAttribute("data-bubble-body-height", String(baseBubbleHeight));
11436
+ if (shapeTransition === void 0) {
11437
+ bodyGroup.removeAttribute("data-bubble-shape-transition-from");
11438
+ bodyGroup.removeAttribute("data-bubble-shape-transition-to");
11439
+ bodyGroup.removeAttribute("data-bubble-shape-transition-progress");
11440
+ } else {
11441
+ bodyGroup.setAttribute("data-bubble-shape-transition-from", shapeTransition.from);
11442
+ bodyGroup.setAttribute("data-bubble-shape-transition-to", shapeTransition.to);
11443
+ bodyGroup.setAttribute("data-bubble-shape-transition-progress", String(shapeTransition.progress));
11444
+ }
11445
+ const bodyDrawableX = centerX - bodyCenterOffset.x;
11446
+ const bodyDrawableY = centerY + bodyCenterOffset.y;
11447
+ bodyGroup.setAttribute("transform", `translate(${native.width / 2 + bodyDrawableX - baseBubbleWidth / 2} ${native.height / 2 - bodyDrawableY - baseBubbleHeight / 2})`);
11448
+ const left = centerX - totalWidth / 2;
11449
+ const portraitPlacement = currentStyle.portrait?.placement ?? "left";
11450
+ const portraitOnRight = portraitPlacement.endsWith("right");
11451
+ const portraitOffsetX = (currentStyle.portrait?.offset.x ?? 0) * scaleMultiplier;
11452
+ const portraitOffsetY = (currentStyle.portrait?.offset.y ?? 0) * scaleMultiplier;
11453
+ const portraitX = (portraitOnRight ? left + textSize.width + contentGap$1 * scaleMultiplier : left) + portraitSize.width / 2 + portraitOffsetX;
11454
+ let portraitY = centerY;
11455
+ if (portraitPlacement.startsWith("top-")) portraitY = centerY + contentHeight / 2 - portraitSize.height / 2;
11456
+ else if (portraitPlacement.startsWith("bottom-")) portraitY = centerY - contentHeight / 2 + portraitSize.height / 2;
11457
+ portraitY += portraitOffsetY;
11458
+ const textX = (portraitOnRight || !hasPortrait ? left : left + portraitSize.width + contentGap$1 * scaleMultiplier) + textSize.width / 2;
11459
+ const toDomTransform = (x, y) => `translate(${native.width / 2 + x} ${native.height / 2 - y})`;
11460
+ for (const target of [
11461
+ portraitBase,
11462
+ portraitBlink,
11463
+ portraitLipSync
11464
+ ]) target.group.setAttribute("transform", toDomTransform(portraitX, portraitY));
11465
+ textGroup.setAttribute("transform", `${toDomTransform(textX, centerY)} scale(${scaleMultiplier})`);
11466
+ const indicatorX = textX + textSize.width / 2 - indicatorSize.width / 2 - contentGap$1 * scaleMultiplier;
11467
+ const indicatorY = centerY - textSize.height / 2 + indicatorSize.height / 2 + contentGap$1 * scaleMultiplier;
11468
+ continueIndicator.group.setAttribute("transform", toDomTransform(indicatorX, indicatorY));
11469
+ const radius = Math.min(currentStyle.portrait?.cornerRadius ?? 0, portraitSize.width / 2, portraitSize.height / 2);
11470
+ clipRect.setAttribute("x", String(-portraitSize.width / 2));
11471
+ clipRect.setAttribute("y", String(-portraitSize.height / 2));
11472
+ clipRect.setAttribute("width", String(portraitSize.width));
11473
+ clipRect.setAttribute("height", String(portraitSize.height));
11474
+ clipRect.setAttribute("rx", String(radius));
11475
+ for (const target of [
11476
+ portraitBase,
11477
+ portraitBlink,
11478
+ portraitLipSync
11479
+ ]) if (radius > 0) target.group.setAttribute("clip-path", `url(#${clipId})`);
11480
+ else target.group.removeAttribute("clip-path");
11481
+ updateVisibility(native);
11482
+ };
11483
+ const originalVisualChange = actor.onTargetVisualChange;
11484
+ const visualChangeHook = (changedTarget) => {
11485
+ originalVisualChange?.(changedTarget);
11486
+ position();
11487
+ };
11488
+ const nativeSizeHook = () => {
11489
+ text.refresh();
11490
+ position();
11491
+ };
11492
+ manager.acquire(surfaceGroup);
11493
+ if (currentStyle.placement.basis === "actor") actor.onTargetVisualChange = visualChangeHook;
11494
+ renderer.on?.("NativeSizeChanged", nativeSizeHook);
11495
+ return Object.freeze({
11496
+ targets,
11497
+ setLayerVisible(layer, visible) {
11498
+ if (disposed) return;
11499
+ layerVisibility.set(layer, visible);
11500
+ updateVisibility();
11501
+ },
11502
+ async updateStyle(nextStyle) {
11503
+ if (disposed) return;
11504
+ const removedTargets = [...nextStyle.portrait === void 0 ? [
11505
+ portraitBase,
11506
+ portraitBlink,
11507
+ portraitLipSync
11508
+ ] : [...nextStyle.portrait.blink === void 0 ? [portraitBlink] : [], ...nextStyle.portrait.lipSync === void 0 ? [portraitLipSync] : []], ...nextStyle.continueIndicator === void 0 ? [continueIndicator] : []];
11509
+ await Promise.all(removedTargets.map((target) => target.release()));
11510
+ const wasActorRelative = currentStyle.placement.basis === "actor";
11511
+ currentStyle = nextStyle;
11512
+ motionTranslation = [0, 0];
11513
+ motionScaleMultiplier = 1;
11514
+ motionOpacity = 1;
11515
+ shapeTransition = void 0;
11516
+ bodySignature = "";
11517
+ if (nextStyle.reveal?.layout !== "RESERVED") text.clearCapturedLayout();
11518
+ const isActorRelative = currentStyle.placement.basis === "actor";
11519
+ if (wasActorRelative && !isActorRelative) {
11520
+ if (actor.onTargetVisualChange === visualChangeHook) actor.onTargetVisualChange = originalVisualChange ?? null;
11521
+ } else if (!wasActorRelative && isActorRelative) actor.onTargetVisualChange = visualChangeHook;
11522
+ position();
11523
+ },
11524
+ captureTextLayout() {
11525
+ if (disposed) return;
11526
+ text.captureLayout();
11527
+ position();
11528
+ },
11529
+ clearTextLayout() {
11530
+ text.clearCapturedLayout();
11531
+ position();
11532
+ },
11533
+ renderScratchText(layout) {
11534
+ if (disposed) return;
11535
+ scratchTextLayout = layout;
11536
+ bodySignature = "";
11537
+ position();
11538
+ },
11539
+ async animate(motion) {
11540
+ if (disposed) return;
11541
+ const durationSeconds = Math.max(0, motion.durationSeconds ?? 0);
11542
+ const setFrame = () => {
11543
+ if (disposed) return;
11544
+ updateVisibility();
11545
+ };
11546
+ const eased = (progress) => easeMotionProgress(progress, motion.ease ?? "easeInOut");
11547
+ if (motion.name === "fadeIn" || motion.name === "floatIn" || motion.name === "zoomIn" || motion.name === "riseUp") {
11548
+ surfaceVisible = true;
11549
+ const startingTranslation = motion.name === "floatIn" || motion.name === "riseUp" ? [0, 16] : [0, 0];
11550
+ const startingScale = motion.name === "zoomIn" ? .01 : 1;
11551
+ motionTranslation = startingTranslation;
11552
+ motionScaleMultiplier = startingScale;
11553
+ motionOpacity = motion.name === "fadeIn" ? 0 : 1;
11554
+ setFrame();
11555
+ await runMotionTimeline(scheduler, durationSeconds, (progress) => {
11556
+ const easedProgress = eased(progress);
11557
+ motionTranslation = [startingTranslation[0] * (1 - easedProgress), startingTranslation[1] * (1 - easedProgress)];
11558
+ motionScaleMultiplier = startingScale + (1 - startingScale) * easedProgress;
11559
+ motionOpacity = motion.name === "fadeIn" ? easedProgress : 1;
11560
+ setFrame();
11561
+ });
11562
+ motionTranslation = [0, 0];
11563
+ motionScaleMultiplier = 1;
11564
+ motionOpacity = 1;
11565
+ position();
11566
+ return;
11567
+ }
11568
+ if (motion.name === "fadeOut" || motion.name === "floatOut" || motion.name === "zoomOut" || motion.name === "sink") {
11569
+ const endingTranslation = motion.name === "floatOut" || motion.name === "sink" ? [0, -16] : [0, 0];
11570
+ const endingScale = motion.name === "zoomOut" ? .01 : 1;
11571
+ await runMotionTimeline(scheduler, durationSeconds, (progress) => {
11572
+ const easedProgress = eased(progress);
11573
+ motionTranslation = [endingTranslation[0] * easedProgress, endingTranslation[1] * easedProgress];
11574
+ motionScaleMultiplier = 1 + (endingScale - 1) * easedProgress;
11575
+ motionOpacity = motion.name === "fadeOut" ? 1 - easedProgress : 1;
11576
+ setFrame();
11577
+ });
11578
+ surfaceVisible = false;
11579
+ updateVisibility();
11580
+ motionTranslation = [0, 0];
11581
+ motionScaleMultiplier = 1;
11582
+ motionOpacity = 1;
11583
+ return;
11584
+ }
11585
+ if (motion.name === "shake") {
11586
+ const count = Math.max(1, Math.floor(motion.count ?? 1));
11587
+ const animationDuration = durationSeconds > 0 ? durationSeconds : count * .08;
11588
+ const vector = bubbleDirectionVector(typeof motion.direction === "number" ? motion.direction : motion.direction ?? "right");
11589
+ await runMotionTimeline(scheduler, animationDuration, (progress) => {
11590
+ const displacement = Math.sin(eased(progress) * count * Math.PI * 2) * 5;
11591
+ motionTranslation = [vector.x * displacement, vector.y * displacement];
11592
+ setFrame();
11593
+ });
11594
+ motionTranslation = [0, 0];
11595
+ position();
11596
+ return;
11597
+ }
11598
+ if (motion.name === "explode") {
11599
+ const count = Math.max(1, Math.floor(motion.count ?? 1));
11600
+ const animationDuration = durationSeconds > 0 ? durationSeconds : count * .12;
11601
+ const factor = motion.relativeScale ?? 1.15;
11602
+ await runMotionTimeline(scheduler, animationDuration, (progress) => {
11603
+ const wave = Math.abs(Math.sin(eased(progress) * count * Math.PI));
11604
+ motionScaleMultiplier = 1 + (factor - 1) * wave;
11605
+ setFrame();
11606
+ });
11607
+ motionScaleMultiplier = 1;
11608
+ position();
11609
+ return;
11610
+ }
11611
+ if (motion.name === "animateBubbleShape") {
11612
+ const targetStyle = motion.visualStyle ?? currentStyle.visualStyle;
11613
+ const fromStyle = currentStyle.visualStyle;
11614
+ const speed = motion.speed === void 0 ? 1 : Math.max(0, motion.speed);
11615
+ shapeTransition = {
11616
+ from: fromStyle,
11617
+ to: targetStyle,
11618
+ progress: 0
11619
+ };
11620
+ position();
11621
+ await runMotionTimeline(scheduler, durationSeconds, (progress) => {
11622
+ const speedProgress = durationSeconds === 0 ? 1 : clampMotionProgress(progress * Math.max(speed, 1));
11623
+ shapeTransition = {
11624
+ from: fromStyle,
11625
+ to: targetStyle,
11626
+ progress: easeMotionProgress(speedProgress, motion.ease ?? "easeInOut")
11627
+ };
11628
+ bodySignature = "";
11629
+ position();
11630
+ });
11631
+ shapeTransition = void 0;
11632
+ bodySignature = "";
11633
+ position();
11634
+ }
11635
+ },
11636
+ show() {
11637
+ if (disposed) return;
11638
+ surfaceVisible = true;
11639
+ position();
11640
+ },
11641
+ hide() {
11642
+ if (disposed) return;
11643
+ surfaceVisible = false;
11644
+ updateVisibility();
11645
+ },
11646
+ async dispose() {
11647
+ if (disposed) return;
11648
+ disposed = true;
11649
+ const cleanupErrors = [];
11650
+ const runCleanup = (operation) => {
11651
+ try {
11652
+ operation();
11653
+ } catch (error) {
11654
+ cleanupErrors.push(error);
11655
+ }
11656
+ };
11657
+ runCleanup(() => {
11658
+ if (actor.onTargetVisualChange === visualChangeHook) actor.onTargetVisualChange = originalVisualChange ?? null;
11659
+ });
11660
+ runCleanup(() => renderer.off?.("NativeSizeChanged", nativeSizeHook));
11661
+ runCleanup(() => manager.release(surfaceGroup));
11662
+ runCleanup(() => text.clear());
11663
+ const releaseResults = await Promise.allSettled([...layerTargets.values()].map((target) => target.release()));
11664
+ cleanupErrors.push(...releaseResults.flatMap((result) => result.status === "rejected" ? [result.reason] : []));
11665
+ if (cleanupErrors.length === 1) throw cleanupErrors[0];
11666
+ if (cleanupErrors.length > 1) throw new AggregateError(cleanupErrors, "Failed to dispose SVG overlay Bubble surface.");
11667
+ }
11668
+ });
11669
+ }
11670
+ //#endregion
11671
+ //#region src/turbowarp-adapter.ts
11672
+ var spriteLayer = "sprite";
11673
+ var portraitBoxSize = 96;
11674
+ var indicatorBoxSize = 18;
11675
+ var contentGap = 8;
11676
+ var stageSafeMargin = 16;
11677
+ var surfaceSequence = 0;
11678
+ var BubbleRuntimeAdapterError = class extends Error {
11679
+ constructor(code, message) {
11680
+ super(message);
11681
+ _defineProperty(this, "code", void 0);
11682
+ this.name = "BubbleRuntimeAdapterError";
11683
+ this.code = code;
11684
+ }
11685
+ };
11686
+ function isRecord(value) {
11687
+ return typeof value === "object" && value !== null && !Array.isArray(value);
11688
+ }
11689
+ function requireRenderer(value) {
11690
+ if (!isRecord(value)) throw new BubbleRuntimeAdapterError("BUBBLE-RUNTIME-001", "Bubble requires the TurboWarp renderer.");
11691
+ const methods = [
11692
+ "createSVGSkin",
11693
+ "createDrawable",
11694
+ "destroyDrawable",
11695
+ "destroySkin",
11696
+ "getCurrentSkinSize",
11697
+ "getNativeSize",
11698
+ "updateDrawablePosition",
11699
+ "updateDrawableScale",
11700
+ "updateDrawableSkinId",
11701
+ "updateDrawableVisible"
11702
+ ];
11703
+ if (methods.some((method) => typeof value[method] !== "function")) throw new BubbleRuntimeAdapterError("BUBBLE-RUNTIME-001", `Bubble renderer must provide ${methods.join(", ")}.`);
11704
+ return value;
11705
+ }
11706
+ function normalizeRenderBackend(value) {
11707
+ const backend = value ?? "svg-overlay";
11708
+ if (backend !== "scratch-render" && backend !== "svg-overlay") throw new BubbleRuntimeAdapterError("BUBBLE-RUNTIME-004", "Bubble bubbleRenderBackend must be scratch-render or svg-overlay.");
11709
+ return backend;
11710
+ }
11711
+ function normalizeOverlayUnsupportedBehavior(value) {
11712
+ const behavior = value ?? "error";
11713
+ if (behavior !== "error" && behavior !== "fallback") throw new BubbleRuntimeAdapterError("BUBBLE-RUNTIME-004", "Bubble svgOverlayUnsupportedBehavior must be error or fallback.");
11714
+ return behavior;
11715
+ }
11716
+ function resolveOverlayDocument(value) {
11717
+ const documentValue = value ?? (typeof globalThis.document === "undefined" ? void 0 : globalThis.document);
11718
+ if (documentValue === void 0) return void 0;
11719
+ if (!isRecord(documentValue) || typeof documentValue.createElementNS !== "function") throw new BubbleRuntimeAdapterError("BUBBLE-RUNTIME-004", "Bubble SVG overlay document must provide createElementNS().");
11720
+ return documentValue;
11721
+ }
11722
+ function overlayUnavailableReason(renderer, documentValue, textCapability) {
11723
+ if (typeof renderer.addOverlay !== "function" || typeof renderer.removeOverlay !== "function") return "the renderer does not provide addOverlay() and removeOverlay()";
11724
+ if (documentValue === void 0) return "the host does not provide a DOM document";
11725
+ if (typeof documentValue.defaultView?.DOMParser !== "function") return "the host document does not provide DOMParser";
11726
+ if (!isRecord(textCapability) || typeof textCapability.layoutText !== "function") return "a host-neutral svgOverlayTextCapability is not available";
11727
+ }
11728
+ function createDefaultSvgOverlayTextCapability() {
11729
+ const composition = createSvgTextLayoutComposition();
11730
+ const definedStyles = /* @__PURE__ */ new Set();
11731
+ const defineStyle = (name) => {
11732
+ composition.defineStyle({
11733
+ name,
11734
+ backgroundColor: "transparent"
11735
+ });
11736
+ definedStyles.add(name);
11737
+ };
11738
+ defineStyle("default");
11739
+ return createSvgTextOverlayTextCapability(Object.freeze({ layoutText(input) {
11740
+ if (!definedStyles.has(input.styleName)) defineStyle(input.styleName);
11741
+ return composition.layoutText(input);
11742
+ } }));
11743
+ }
11744
+ function createDefaultScratchRenderTextCapability(runtime) {
11745
+ const composition = createSvgTextComposition({ runtime });
11746
+ const definedStyles = /* @__PURE__ */ new Set();
11747
+ const defineStyle = (name) => {
11748
+ composition.defineStyle({
11749
+ name,
11750
+ backgroundColor: "transparent"
11751
+ });
11752
+ definedStyles.add(name);
11753
+ };
11754
+ const ensureStyle = (name) => {
11755
+ if (!definedStyles.has(name)) defineStyle(name);
11756
+ };
11757
+ defineStyle("default");
11758
+ return createSvgTextCompositionCapability(Object.freeze({
11759
+ setText(input) {
11760
+ ensureStyle(input.styleName);
11761
+ composition.setText(input);
11762
+ },
11763
+ releaseTarget(target) {
11764
+ composition.releaseTarget(target);
11765
+ },
11766
+ measureText(input) {
11767
+ ensureStyle(input.styleName);
11768
+ return composition.measureText(input);
11769
+ }
11770
+ }));
11771
+ }
11772
+ function requireAssetManager(value) {
11773
+ 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.");
11774
+ return value;
11775
+ }
11776
+ function requireAssetManagerDOMImageCapability(value) {
11777
+ 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.");
11778
+ const capability = value.getDOMImageCapability();
11779
+ 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.");
11780
+ return capability;
11781
+ }
11782
+ function targetBounds(target) {
11783
+ try {
11784
+ const bounds = target.getBoundsForBubble?.();
11785
+ if (bounds && [
11786
+ bounds.bottom,
11787
+ bounds.left,
11788
+ bounds.right,
11789
+ bounds.top
11790
+ ].every((value) => Number.isFinite(value))) return bounds;
11791
+ } catch {}
11792
+ const x = Number.isFinite(target.x) ? Number(target.x) : 0;
11793
+ const y = Number.isFinite(target.y) ? Number(target.y) : 0;
11794
+ return {
11795
+ bottom: y,
11796
+ left: x,
11797
+ right: x,
11798
+ top: y
11799
+ };
11800
+ }
11801
+ function readSize(renderer, target, fallback) {
11802
+ const raw = renderer.getCurrentSkinSize(target.drawableID);
11803
+ if (!Array.isArray(raw) || raw.length < 2) return fallback;
11804
+ const width = Number(raw[0]);
11805
+ const height = Number(raw[1]);
11806
+ if (!(width > 0) || !(height > 0)) return fallback;
11807
+ return {
11808
+ width,
11809
+ height
11810
+ };
11811
+ }
9538
11812
  function fitDrawable(renderer, target, boxSize, scaleMultiplier = 1) {
9539
11813
  const native = readSize(renderer, target, {
9540
11814
  width: boxSize,
@@ -9569,7 +11843,7 @@
9569
11843
  const vector = bubbleDirectionVector(direction);
9570
11844
  return (Math.atan2(-vector.x, -vector.y) * 180 / Math.PI % 360 + 360) % 360;
9571
11845
  }
9572
- function createSurface(runtime, actor, actorKey, style, scheduler) {
11846
+ function createSurface(runtime, actor, actorKey, kind, style, scheduler) {
9573
11847
  const renderer = runtime.renderer;
9574
11848
  const sequence = surfaceSequence;
9575
11849
  surfaceSequence += 1;
@@ -9622,6 +11896,8 @@
9622
11896
  let motionScaleMultiplier = 1;
9623
11897
  let motionOpacity = 1;
9624
11898
  let shapeTransition;
11899
+ let scratchTextLayout;
11900
+ let scratchPointsLeft = false;
9625
11901
  const applyMotionTransforms = () => {
9626
11902
  for (const target of drawables) {
9627
11903
  const basePosition = layoutPositions.get(target.drawableID);
@@ -9633,8 +11909,9 @@
9633
11909
  };
9634
11910
  const updateVisibility = () => {
9635
11911
  const actorVisible = currentStyle.placement.basis === "background" || actor.visible !== false;
9636
- renderer.updateDrawableVisible(body.drawableID, surfaceVisible && actorVisible && currentStyle.visualStyle !== "NO_BUBBLE" && (renderer.updateDrawableEffect !== void 0 || motionOpacity > 0));
9637
- renderer.updateDrawableVisible(text.drawableID, surfaceVisible && actorVisible && (renderer.updateDrawableEffect !== void 0 || motionOpacity > 0));
11912
+ const scratchDefaultRendered = currentStyle.layoutProfile === "scratch-default" && scratchTextLayout !== void 0;
11913
+ renderer.updateDrawableVisible(body.drawableID, surfaceVisible && actorVisible && (scratchDefaultRendered || currentStyle.visualStyle !== "NO_BUBBLE") && (renderer.updateDrawableEffect !== void 0 || motionOpacity > 0));
11914
+ renderer.updateDrawableVisible(text.drawableID, surfaceVisible && actorVisible && !scratchDefaultRendered && (renderer.updateDrawableEffect !== void 0 || motionOpacity > 0));
9638
11915
  for (const [layer, target] of layerTargets) renderer.updateDrawableVisible(target.drawableID, surfaceVisible && actorVisible && (layerVisibility.get(layer) ?? false) && (renderer.updateDrawableEffect !== void 0 || motionOpacity > 0));
9639
11916
  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));
9640
11917
  applyMotionTransforms();
@@ -9642,6 +11919,51 @@
9642
11919
  };
9643
11920
  const position = () => {
9644
11921
  if (disposed) return;
11922
+ if (currentStyle.layoutProfile === "scratch-default" && scratchTextLayout !== void 0) {
11923
+ const nativeSize = renderer.getNativeSize();
11924
+ const stageWidth = Array.isArray(nativeSize) && Number(nativeSize[0]) > 0 ? Number(nativeSize[0]) : 480;
11925
+ const stageHeight = Array.isArray(nativeSize) && Number(nativeSize[1]) > 0 ? Number(nativeSize[1]) : 360;
11926
+ const metrics = scratchBubbleMetrics(scratchTextLayout);
11927
+ const nextPosition = positionScratchBubble({
11928
+ bounds: targetBounds(actor),
11929
+ height: metrics.height,
11930
+ pointsLeft: scratchPointsLeft,
11931
+ stageHeight,
11932
+ stageWidth,
11933
+ width: metrics.width
11934
+ });
11935
+ scratchPointsLeft = nextPosition.pointsLeft;
11936
+ const nextBodySkinSignature = JSON.stringify({
11937
+ kind,
11938
+ layout: scratchTextLayout,
11939
+ pointsLeft: scratchPointsLeft
11940
+ });
11941
+ if (nextBodySkinSignature !== cachedBodySkinSignature) {
11942
+ const nextSkinId = renderer.createSVGSkin(renderScratchBubbleSvg({
11943
+ kind,
11944
+ layout: scratchTextLayout,
11945
+ pointsLeft: scratchPointsLeft,
11946
+ title: `${currentStyle.name} ${kind} Bubble`
11947
+ }));
11948
+ if (!Number.isInteger(nextSkinId) || nextSkinId < 0) throw new BubbleRuntimeAdapterError("BUBBLE-RUNTIME-001", "TurboWarp did not create the Scratch-compatible Bubble SVG skin.");
11949
+ try {
11950
+ renderer.updateDrawableSkinId(body.drawableID, nextSkinId);
11951
+ } catch (error) {
11952
+ renderer.destroySkin(nextSkinId);
11953
+ throw error;
11954
+ }
11955
+ const previousBodySkinId = bodySkinId;
11956
+ bodySkinId = nextSkinId;
11957
+ cachedBodySkinSignature = nextBodySkinSignature;
11958
+ if (previousBodySkinId !== void 0) renderer.destroySkin(previousBodySkinId);
11959
+ }
11960
+ renderer.updateDrawableScale(body.drawableID, [100, 100]);
11961
+ renderer.updateDrawablePosition(body.drawableID, [nextPosition.centerX, nextPosition.centerY]);
11962
+ layoutPositions.set(body.drawableID, [nextPosition.centerX, nextPosition.centerY]);
11963
+ layoutScales.set(body.drawableID, [100, 100]);
11964
+ updateVisibility();
11965
+ return;
11966
+ }
9645
11967
  const scaleMultiplier = currentStyle.placement.basis === "actor" ? currentStyle.offset.scalePercent / 100 : 1;
9646
11968
  const nativeTextSize = reservedTextSize ?? readSize(renderer, text, {
9647
11969
  width: 180,
@@ -9672,10 +11994,11 @@
9672
11994
  };
9673
11995
  const totalWidth = portraitSize.width + (hasPortrait ? contentGap * scaleMultiplier : 0) + textSize.width;
9674
11996
  const contentHeight = Math.max(portraitSize.height, textSize.height);
9675
- const baseBubbleWidth = totalWidth / scaleMultiplier + 48;
9676
- const baseBubbleHeight = contentHeight / scaleMultiplier + 48;
9677
- const bubbleWidth = totalWidth;
9678
- const bubbleHeight = contentHeight;
11997
+ const minimumBodySize = bubbleBodyMinimumSize(currentStyle.visualStyle, ...shapeTransition === void 0 ? [] : [shapeTransition.from, shapeTransition.to]);
11998
+ const baseBubbleWidth = Math.max(totalWidth / scaleMultiplier + 48, minimumBodySize.width);
11999
+ const baseBubbleHeight = Math.max(contentHeight / scaleMultiplier + 48, minimumBodySize.height);
12000
+ const bubbleWidth = Math.max(totalWidth, (baseBubbleWidth - 48) * scaleMultiplier);
12001
+ const bubbleHeight = Math.max(contentHeight, (baseBubbleHeight - 48) * scaleMultiplier);
9679
12002
  const nativeSize = renderer.getNativeSize();
9680
12003
  const stageWidth = Array.isArray(nativeSize) && Number(nativeSize[0]) > 0 ? Number(nativeSize[0]) : 480;
9681
12004
  const stageHeight = Array.isArray(nativeSize) && Number(nativeSize[1]) > 0 ? Number(nativeSize[1]) : 360;
@@ -9848,7 +12171,9 @@
9848
12171
  originalVisualChange?.(changedTarget);
9849
12172
  position();
9850
12173
  };
12174
+ const nativeSizeHook = () => position();
9851
12175
  if (currentStyle.placement.basis === "actor") actor.onTargetVisualChange = visualChangeHook;
12176
+ renderer.on?.("NativeSizeChanged", nativeSizeHook);
9852
12177
  return Object.freeze({
9853
12178
  targets,
9854
12179
  setLayerVisible(layer, visible) {
@@ -9883,6 +12208,12 @@
9883
12208
  reservedTextSize = void 0;
9884
12209
  position();
9885
12210
  },
12211
+ renderScratchText(layout) {
12212
+ if (disposed) return;
12213
+ scratchTextLayout = layout;
12214
+ cachedBodySkinSignature = "";
12215
+ position();
12216
+ },
9886
12217
  async animate(motion) {
9887
12218
  if (disposed) return;
9888
12219
  const durationSeconds = Math.max(0, motion.durationSeconds ?? 0);
@@ -9891,7 +12222,7 @@
9891
12222
  applyMotionTransforms();
9892
12223
  updateVisibility();
9893
12224
  };
9894
- const eased = (progress) => easeProgress(progress, motion.ease ?? "easeInOut");
12225
+ const eased = (progress) => easeMotionProgress(progress, motion.ease ?? "easeInOut");
9895
12226
  if (motion.name === "fadeIn" || motion.name === "floatIn" || motion.name === "zoomIn" || motion.name === "riseUp") {
9896
12227
  surfaceVisible = true;
9897
12228
  const startingTranslation = motion.name === "floatIn" || motion.name === "riseUp" ? [0, 16] : [0, 0];
@@ -9979,11 +12310,11 @@
9979
12310
  };
9980
12311
  position();
9981
12312
  await runMotionTimeline(scheduler, durationSeconds, (progress) => {
9982
- const speedProgress = durationSeconds === 0 ? 1 : clamp01(progress * Math.max(speed, 1) / 1);
12313
+ const speedProgress = durationSeconds === 0 ? 1 : clampMotionProgress(progress * Math.max(speed, 1) / 1);
9983
12314
  shapeTransition = {
9984
12315
  from: fromStyle,
9985
12316
  to: targetStyle,
9986
- progress: easeProgress(speedProgress, motion.ease ?? "easeInOut")
12317
+ progress: easeMotionProgress(speedProgress, motion.ease ?? "easeInOut")
9987
12318
  };
9988
12319
  position();
9989
12320
  });
@@ -10005,6 +12336,7 @@
10005
12336
  dispose() {
10006
12337
  if (disposed) return;
10007
12338
  disposed = true;
12339
+ renderer.off?.("NativeSizeChanged", nativeSizeHook);
10008
12340
  if (currentStyle.placement.basis === "actor" && actor.onTargetVisualChange === visualChangeHook) actor.onTargetVisualChange = originalVisualChange ?? null;
10009
12341
  for (const target of [...drawables].reverse()) renderer.destroyDrawable(target.drawableID, spriteLayer);
10010
12342
  if (bodySkinId !== void 0) {
@@ -10029,52 +12361,99 @@
10029
12361
  if (!isRecord(runtimeInput)) throw new BubbleRuntimeAdapterError("BUBBLE-RUNTIME-001", "Bubble requires the TurboWarp runtime.");
10030
12362
  const runtime = runtimeInput;
10031
12363
  const renderer = requireRenderer(runtime.renderer);
12364
+ const requestedBackend = normalizeRenderBackend(options.bubbleRenderBackend);
12365
+ let overlayTextCapability;
12366
+ let overlayTextCapabilityError;
12367
+ if (requestedBackend === "svg-overlay") {
12368
+ if (options.svgOverlayTextCapability !== void 0) overlayTextCapability = options.svgOverlayTextCapability;
12369
+ else if (runtime.ext_kubohiroyasvgtext === void 0) overlayTextCapability = createDefaultSvgOverlayTextCapability();
12370
+ else try {
12371
+ overlayTextCapability = createTurboWarpSvgTextOverlayTextCapability(runtime.ext_kubohiroyasvgtext);
12372
+ } catch (error) {
12373
+ overlayTextCapabilityError = error instanceof Error ? error.message : String(error);
12374
+ }
12375
+ }
12376
+ const unsupportedBehavior = normalizeOverlayUnsupportedBehavior(options.svgOverlayUnsupportedBehavior);
12377
+ const overlayDocument = requestedBackend === "svg-overlay" ? resolveOverlayDocument(options.document) : void 0;
12378
+ const unavailableReason = requestedBackend === "svg-overlay" ? overlayTextCapabilityError ?? overlayUnavailableReason(renderer, overlayDocument, overlayTextCapability) : void 0;
12379
+ 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.`);
12380
+ const renderBackend = requestedBackend === "svg-overlay" && unavailableReason === void 0 ? "svg-overlay" : "scratch-render";
12381
+ const scheduler = options.scheduler ?? {
12382
+ setTimeout: (callback, milliseconds) => globalThis.setTimeout(callback, milliseconds),
12383
+ clearTimeout: (handle) => globalThis.clearTimeout(handle)
12384
+ };
10032
12385
  const getAssetExtension = () => requireAssetManager(runtime.ext_kubohiroyaassetmanager);
12386
+ let assetManagerDOMImages;
12387
+ const getAssetManagerDOMImages = () => {
12388
+ assetManagerDOMImages ?? (assetManagerDOMImages = requireAssetManagerDOMImageCapability(runtime.ext_kubohiroyaassetmanager));
12389
+ return assetManagerDOMImages;
12390
+ };
10033
12391
  let textCapability;
10034
- if (options.textCapability !== void 0) textCapability = options.textCapability;
12392
+ if (renderBackend === "svg-overlay") try {
12393
+ textCapability = createSvgOverlayTextAdapter(overlayTextCapability, renderer);
12394
+ } catch (error) {
12395
+ throw new BubbleRuntimeAdapterError("BUBBLE-RUNTIME-004", `Bubble SVG overlay text capability is invalid: ${error instanceof Error ? error.message : String(error)}`);
12396
+ }
12397
+ else if (options.textCapability !== void 0) textCapability = options.textCapability;
10035
12398
  else try {
10036
- textCapability = createTurboWarpSvgTextCapability(runtime.ext_kubohiroyasvgtext);
10037
- } catch {
10038
- throw new BubbleRuntimeAdapterError("BUBBLE-RUNTIME-003", "Bubble requires a text capability. Load @kubohiroya/turbowarp-svg-text or provide options.textCapability before using Bubble blocks.");
12399
+ textCapability = runtime.ext_kubohiroyasvgtext === void 0 ? createDefaultScratchRenderTextCapability(runtime) : createTurboWarpSvgTextCapability(runtime.ext_kubohiroyasvgtext);
12400
+ } catch (error) {
12401
+ throw new BubbleRuntimeAdapterError("BUBBLE-RUNTIME-003", `Bubble could not initialize the scratch-render text provider: ${error instanceof Error ? error.message : String(error)}`);
10039
12402
  }
10040
- return createBubbleComposition({
10041
- imageResolver: options.imageResolver ?? {
12403
+ let imageResolver;
12404
+ if (renderBackend === "svg-overlay") try {
12405
+ imageResolver = createSvgOverlayImageAdapter(options.svgOverlayImageCapability ?? createAssetManagerSvgOverlayImageCapability(Object.freeze({
10042
12406
  isRegistered(name) {
10043
- return getAssetExtension().isLoaded({ NAME: name });
12407
+ return getAssetManagerDOMImages().isRegistered(name);
10044
12408
  },
10045
12409
  getMimeType(name) {
10046
- return getAssetExtension().getAssetMimeType({ NAME: name });
12410
+ return getAssetManagerDOMImages().getMimeType(name);
10047
12411
  },
10048
- async applyToTarget(name, target) {
10049
- const drawableID = target.drawableID;
10050
- if (!Number.isInteger(drawableID) || drawableID < 0) throw new BubbleRuntimeAdapterError("BUBBLE-RUNTIME-001", "Bubble image target drawable is invalid.");
10051
- const skin = await getAssetExtension().resolveSkin(name);
10052
- if (!isRecord(skin) || !Number.isInteger(skin.skinId) || skin.skinId < 0) throw new BubbleRuntimeAdapterError("BUBBLE-RUNTIME-002", `Asset Manager did not resolve an image skin: ${String(name)}`);
10053
- renderer.updateDrawableSkinId(drawableID, skin.skinId);
10054
- runtime.requestRedraw?.();
12412
+ resolveDOMImageResource(name) {
12413
+ return getAssetManagerDOMImages().resolveDOMImageResource(name);
10055
12414
  }
12415
+ })));
12416
+ } catch (error) {
12417
+ throw new BubbleRuntimeAdapterError("BUBBLE-RUNTIME-004", `Bubble SVG overlay image capability is invalid: ${error instanceof Error ? error.message : String(error)}`);
12418
+ }
12419
+ else imageResolver = options.imageResolver ?? {
12420
+ isRegistered(name) {
12421
+ return getAssetExtension().isLoaded({ NAME: name });
10056
12422
  },
10057
- audio: options.audio ?? {
10058
- isRegistered(name) {
10059
- return getAssetExtension().isLoaded({ NAME: name });
10060
- },
10061
- getMimeType(name) {
10062
- return getAssetExtension().getAssetMimeType({ NAME: name });
10063
- },
10064
- async playSound(name, playOptions = {}) {
10065
- const extension = getAssetExtension();
10066
- const method = playOptions.untilDone ? extension?.playSoundUntilDone : extension?.playSound;
10067
- if (typeof method !== "function") throw new BubbleRuntimeAdapterError("BUBBLE-RUNTIME-002", "TurboWarp Asset Manager does not provide audio playback.");
10068
- await method.call(extension, { NAME: name });
10069
- }
12423
+ getMimeType(name) {
12424
+ return getAssetExtension().getAssetMimeType({ NAME: name });
10070
12425
  },
12426
+ async applyToTarget(name, target) {
12427
+ const drawableID = target.drawableID;
12428
+ if (!Number.isInteger(drawableID) || drawableID < 0) throw new BubbleRuntimeAdapterError("BUBBLE-RUNTIME-001", "Bubble image target drawable is invalid.");
12429
+ const skin = await getAssetExtension().resolveSkin(name);
12430
+ if (!isRecord(skin) || !Number.isInteger(skin.skinId) || skin.skinId < 0) throw new BubbleRuntimeAdapterError("BUBBLE-RUNTIME-002", `Asset Manager did not resolve an image skin: ${String(name)}`);
12431
+ renderer.updateDrawableSkinId(drawableID, skin.skinId);
12432
+ runtime.requestRedraw?.();
12433
+ }
12434
+ };
12435
+ const audio = options.audio ?? {
12436
+ isRegistered(name) {
12437
+ return getAssetExtension().isLoaded({ NAME: name });
12438
+ },
12439
+ getMimeType(name) {
12440
+ return getAssetExtension().getAssetMimeType({ NAME: name });
12441
+ },
12442
+ async playSound(name, playOptions = {}) {
12443
+ const extension = getAssetExtension();
12444
+ const method = playOptions.untilDone ? extension?.playSoundUntilDone : extension?.playSound;
12445
+ if (typeof method !== "function") throw new BubbleRuntimeAdapterError("BUBBLE-RUNTIME-002", "TurboWarp Asset Manager does not provide audio playback.");
12446
+ await method.call(extension, { NAME: name });
12447
+ }
12448
+ };
12449
+ const overlayManager = renderBackend === "svg-overlay" ? createSvgOverlaySurfaceManager(renderer, overlayDocument) : void 0;
12450
+ return createBubbleComposition({
12451
+ ...imageResolver === void 0 ? {} : { imageResolver },
12452
+ audio,
10071
12453
  textCapability,
10072
- createSurface({ actor, actorKey, style }) {
12454
+ createSurface({ actor, actorKey, kind, style }) {
10073
12455
  if (!isRecord(actor) || typeof actor.id !== "string") throw new BubbleRuntimeAdapterError("BUBBLE-RUNTIME-001", "Bubble actor target is invalid.");
10074
- return createSurface(runtime, actor, actorKey, style, options.scheduler ?? {
10075
- setTimeout: (callback, milliseconds) => globalThis.setTimeout(callback, milliseconds),
10076
- clearTimeout: (handle) => globalThis.clearTimeout(handle)
10077
- });
12456
+ return renderBackend === "svg-overlay" ? createSvgOverlaySurface(overlayManager, actor, actorKey, kind, style, scheduler) : createSurface(runtime, actor, actorKey, kind, style, scheduler);
10078
12457
  },
10079
12458
  ...options.scheduler === void 0 ? {} : { scheduler: options.scheduler },
10080
12459
  ...options.onAnimationError === void 0 ? {} : { onAnimationError: options.onAnimationError }
@@ -10082,8 +12461,8 @@
10082
12461
  }
10083
12462
  //#endregion
10084
12463
  //#region src/extension.ts
10085
- var blockDefinitions = block_definitions_default.blocks;
10086
- var definitionMenus = block_definitions_default.menus;
12464
+ var blockDefinitions = block_definitions_default$1.blocks;
12465
+ var definitionMenus = block_definitions_default$1.menus;
10087
12466
  var validAnimationModes = /* @__PURE__ */ new Set([
10088
12467
  "idle",
10089
12468
  "talking",
@@ -10120,8 +12499,15 @@
10120
12499
  "easeOut",
10121
12500
  "easeInOut"
10122
12501
  ]);
12502
+ var builtInBubbleStyles = Object.freeze([Object.freeze({
12503
+ name: "say",
12504
+ textStyle: "default"
12505
+ }), Object.freeze({
12506
+ name: "think",
12507
+ textStyle: "default"
12508
+ })]);
10123
12509
  var EXTENSION_DOCS_URI = "https://kubohiroya.github.io/turbowarp-bubble/";
10124
- var EXTENSION_VERSION = "0.7.0";
12510
+ var EXTENSION_VERSION = "0.9.0";
10125
12511
  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>")}`;
10126
12512
  function extensionError(message) {
10127
12513
  const error = /* @__PURE__ */ new Error(`[Bubble] ${message}`);
@@ -10132,7 +12518,7 @@
10132
12518
  constructor(runtime = Scratch.vm?.runtime, options = {}) {
10133
12519
  _defineProperty(this, "runtime", void 0);
10134
12520
  _defineProperty(this, "options", void 0);
10135
- _defineProperty(this, "styles", /* @__PURE__ */ new Map());
12521
+ _defineProperty(this, "styles", new Map(builtInBubbleStyles.map((style) => [style.name, style])));
10136
12522
  _defineProperty(this, "handles", /* @__PURE__ */ new Map());
10137
12523
  _defineProperty(this, "waits", /* @__PURE__ */ new Map());
10138
12524
  _defineProperty(this, "waitScheduler", void 0);
@@ -10160,11 +12546,13 @@
10160
12546
  }
10161
12547
  getInfo() {
10162
12548
  return {
10163
- id: extensionConfig.id,
10164
- name: Scratch.translate(block_definitions_default.extensionName),
12549
+ id: extensionConfig$1.id,
12550
+ name: Scratch.translate(block_definitions_default$1.extensionName),
10165
12551
  docsURI: EXTENSION_DOCS_URI,
10166
12552
  blockIconURI: BLOCK_ICON_URI,
10167
12553
  color1: "#ff6680",
12554
+ color2: "#e64d6a",
12555
+ color3: "#b83255",
10168
12556
  blocks: blockDefinitions.map((block) => this.toScratchBlock(block)),
10169
12557
  menus: definitionMenus
10170
12558
  };
@@ -10443,6 +12831,22 @@
10443
12831
  durationSeconds: seconds
10444
12832
  });
10445
12833
  }
12834
+ say(args, util) {
12835
+ return this.show("say", Object.freeze({
12836
+ MESSAGE: args.MESSAGE,
12837
+ STYLE: "say"
12838
+ }), util);
12839
+ }
12840
+ think(args, util) {
12841
+ return this.show("think", Object.freeze({
12842
+ MESSAGE: args.MESSAGE,
12843
+ STYLE: "think"
12844
+ }), util);
12845
+ }
12846
+ showWithBubbleStyle(args, util) {
12847
+ const style = this.requireStyle(args.STYLE);
12848
+ return this.show(style.name === "think" ? "think" : "say", args, util);
12849
+ }
10446
12850
  sayWithBubbleStyle(args, util) {
10447
12851
  return this.show("say", args, util);
10448
12852
  }
@@ -10545,6 +12949,7 @@
10545
12949
  opcode: block.opcode,
10546
12950
  blockType: Scratch.BlockType[block.blockType],
10547
12951
  text: Scratch.translate(block.text),
12952
+ ...block.hideFromPalette === true ? { hideFromPalette: true } : {},
10548
12953
  arguments: Object.fromEntries(Object.entries(block.arguments).map(([name, argument]) => [name, {
10549
12954
  type: Scratch.ArgumentType[argument.type],
10550
12955
  defaultValue: argument.defaultValue,
@@ -10669,6 +13074,12 @@
10669
13074
  const placement = normalizeBubblePlacement(style.placement ?? "up-right");
10670
13075
  if (target.isStage && placement.basis === "actor") throw extensionError("actor-relative bubble placement requires a sprite or clone.");
10671
13076
  this.cancelWait(target.id, "Bubble wait was replaced.");
13077
+ const scratchDefault = isScratchDefaultBubbleStyleInput(style);
13078
+ const message = scratchDefault ? formatScratchBubbleArgument(args.MESSAGE) : this.toString(args.MESSAGE);
13079
+ if (scratchDefault && message === "") {
13080
+ await this.releaseOwnedTarget(target.id);
13081
+ return;
13082
+ }
10672
13083
  const composition = this.getComposition();
10673
13084
  let handle;
10674
13085
  try {
@@ -10676,7 +13087,7 @@
10676
13087
  actor: target,
10677
13088
  actorKey: target.id,
10678
13089
  kind,
10679
- text: this.toString(args.MESSAGE),
13090
+ text: message,
10680
13091
  styleName: style.name
10681
13092
  });
10682
13093
  } catch (error) {
@@ -10693,7 +13104,7 @@
10693
13104
  };
10694
13105
  //#endregion
10695
13106
  //#region src/index.ts
10696
- if (extensionConfig.unsandboxed && !Scratch.extensions.unsandboxed) throw new Error(`${extensionConfig.name} must run unsandboxed.`);
13107
+ if (extensionConfig$1.unsandboxed && !Scratch.extensions.unsandboxed) throw new Error(`${extensionConfig$1.name} must run unsandboxed.`);
10697
13108
  Scratch.extensions.register(new BubbleExtension());
10698
13109
  //#endregion
10699
13110