@kubohiroya/turbowarp-bubble 0.6.0 → 0.8.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.
@@ -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 and references a named SVG Text layout style.",
51
51
  "arguments": {
52
52
  "STYLE": {
53
53
  "type": "STRING",
@@ -92,6 +92,39 @@
92
92
  }
93
93
  }
94
94
  },
95
+ {
96
+ "opcode": "setPortraitLayout",
97
+ "blockType": "COMMAND",
98
+ "text": "set portrait [PLACEMENT] offset x [X] y [Y] zoom [ZOOM] % corner radius [RADIUS] px for bubble style [STYLE]",
99
+ "description": "Places the portrait at a bubble edge or corner with a local offset, zoom, and rounded corners. NONE removes the portrait.",
100
+ "arguments": {
101
+ "PLACEMENT": {
102
+ "type": "STRING",
103
+ "defaultValue": "left",
104
+ "menu": "portraitPlacement"
105
+ },
106
+ "X": {
107
+ "type": "NUMBER",
108
+ "defaultValue": 0
109
+ },
110
+ "Y": {
111
+ "type": "NUMBER",
112
+ "defaultValue": 0
113
+ },
114
+ "ZOOM": {
115
+ "type": "NUMBER",
116
+ "defaultValue": 100
117
+ },
118
+ "RADIUS": {
119
+ "type": "NUMBER",
120
+ "defaultValue": 0
121
+ },
122
+ "STYLE": {
123
+ "type": "STRING",
124
+ "defaultValue": "dialogue"
125
+ }
126
+ }
127
+ },
95
128
  {
96
129
  "opcode": "setBubbleDistance",
97
130
  "blockType": "COMMAND",
@@ -504,7 +537,7 @@
504
537
  "opcode": "closeBubble",
505
538
  "blockType": "COMMAND",
506
539
  "text": "close this bubble",
507
- "description": "Closes this sprite's bubble and releases its timers, SVG text skin, and drawables.",
540
+ "description": "Closes this sprite's bubble and releases its timers and rendering resources.",
508
541
  "arguments": {}
509
542
  },
510
543
  {
@@ -516,6 +549,18 @@
516
549
  }
517
550
  ],
518
551
  menus: {
552
+ "portraitPlacement": {
553
+ "acceptReporters": true,
554
+ "items": [
555
+ "none",
556
+ "left",
557
+ "right",
558
+ "top-left",
559
+ "top-right",
560
+ "bottom-left",
561
+ "bottom-right"
562
+ ]
563
+ },
519
564
  "visualStyle": {
520
565
  "acceptReporters": true,
521
566
  "items": [
@@ -8397,6 +8442,45 @@
8397
8442
  return chunks.slice(0, Math.max(0, Math.min(count, chunks.length))).join("");
8398
8443
  }
8399
8444
  //#endregion
8445
+ //#region src/portrait-layout.ts
8446
+ var bubblePortraitPlacements = Object.freeze([
8447
+ "left",
8448
+ "right",
8449
+ "top-left",
8450
+ "top-right",
8451
+ "bottom-left",
8452
+ "bottom-right"
8453
+ ]);
8454
+ var defaultBubblePortraitOffset = Object.freeze({
8455
+ x: 0,
8456
+ y: 0,
8457
+ zoomPercent: 100
8458
+ });
8459
+ function normalizeBubblePortraitPlacement(value) {
8460
+ if (typeof value !== "string") throw new TypeError("Bubble portrait placement must be a string.");
8461
+ const normalized = value.trim().toLowerCase().replaceAll("_", "-");
8462
+ if (!bubblePortraitPlacements.includes(normalized)) throw new TypeError(`Unsupported Bubble portrait placement: ${value}`);
8463
+ return normalized;
8464
+ }
8465
+ function normalizeBubblePortraitOffset(value) {
8466
+ if (!Array.isArray(value) || value.length !== 2 && value.length !== 3) throw new TypeError("Bubble portrait offset must be [x, y] or [x, y, zoom].");
8467
+ const [x, y, zoomPercent = 100] = value;
8468
+ if (![
8469
+ x,
8470
+ y,
8471
+ zoomPercent
8472
+ ].every(Number.isFinite) || zoomPercent <= 0) throw new TypeError("Bubble portrait offset values must be finite and zoom positive.");
8473
+ return Object.freeze({
8474
+ x,
8475
+ y,
8476
+ zoomPercent
8477
+ });
8478
+ }
8479
+ function normalizeBubblePortraitCornerRadius(value) {
8480
+ if (typeof value !== "number" || !Number.isFinite(value) || value < 0) throw new TypeError("Bubble portrait corner radius must be zero or greater.");
8481
+ return value;
8482
+ }
8483
+ //#endregion
8400
8484
  //#region src/composition.ts
8401
8485
  var BubbleCompositionError = class extends Error {
8402
8486
  constructor(code, message) {
@@ -8431,16 +8515,16 @@
8431
8515
  "easeOut",
8432
8516
  "easeInOut"
8433
8517
  ]);
8434
- function isRecord$2(value) {
8518
+ function isRecord$4(value) {
8435
8519
  return typeof value === "object" && value !== null && !Array.isArray(value);
8436
8520
  }
8437
- function requireExactKeys(value, required, optional, label) {
8521
+ function requireExactKeys$1(value, required, optional, label) {
8438
8522
  const allowed = /* @__PURE__ */ new Set([...required, ...optional]);
8439
8523
  const missing = required.filter((key) => !Object.prototype.hasOwnProperty.call(value, key));
8440
8524
  const unknown = Object.keys(value).filter((key) => !allowed.has(key));
8441
8525
  if (missing.length > 0 || unknown.length > 0) throw new BubbleCompositionError("BUBBLE-COMPOSITION-001", `${label} has missing or unknown properties.`);
8442
8526
  }
8443
- function requireName(value, label) {
8527
+ function requireName$1(value, label) {
8444
8528
  if (typeof value !== "string" || value.trim().length === 0) throw new BubbleCompositionError("BUBBLE-COMPOSITION-001", `${label} must be a non-empty string.`);
8445
8529
  return value.trim();
8446
8530
  }
@@ -8449,8 +8533,8 @@
8449
8533
  return value;
8450
8534
  }
8451
8535
  function normalizeAnimation(value, label, minimumFrames) {
8452
- if (!isRecord$2(value)) throw new BubbleCompositionError("BUBBLE-COMPOSITION-001", `${label} must be an object.`);
8453
- requireExactKeys(value, ["frames", "frameIntervalSeconds"], [], label);
8536
+ if (!isRecord$4(value)) throw new BubbleCompositionError("BUBBLE-COMPOSITION-001", `${label} must be an object.`);
8537
+ requireExactKeys$1(value, ["frames", "frameIntervalSeconds"], [], label);
8454
8538
  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"}.`);
8455
8539
  const frames = Object.freeze(value.frames.map((frame, index) => requireAssetName(frame, `${label}.frames[${index}]`)));
8456
8540
  const interval = value.frameIntervalSeconds;
@@ -8461,19 +8545,38 @@
8461
8545
  });
8462
8546
  }
8463
8547
  function normalizePortrait(value) {
8464
- if (!isRecord$2(value)) throw new BubbleCompositionError("BUBBLE-COMPOSITION-001", "Bubble portrait must be an object.");
8465
- requireExactKeys(value, ["base"], ["blink", "lipSync"], "Bubble portrait");
8548
+ if (!isRecord$4(value)) throw new BubbleCompositionError("BUBBLE-COMPOSITION-001", "Bubble portrait must be an object.");
8549
+ requireExactKeys$1(value, ["base"], [
8550
+ "blink",
8551
+ "lipSync",
8552
+ "placement",
8553
+ "offset",
8554
+ "cornerRadius"
8555
+ ], "Bubble portrait");
8466
8556
  const blink = value.blink === void 0 ? void 0 : normalizeAnimation(value.blink, "Bubble portrait blink", 1);
8467
8557
  const lipSync = value.lipSync === void 0 ? void 0 : normalizeAnimation(value.lipSync, "Bubble portrait lip-sync", 1);
8558
+ let placement;
8559
+ let offset;
8560
+ let cornerRadius;
8561
+ try {
8562
+ placement = normalizeBubblePortraitPlacement(value.placement ?? "left");
8563
+ offset = value.offset === void 0 ? defaultBubblePortraitOffset : normalizeBubblePortraitOffset(value.offset);
8564
+ cornerRadius = normalizeBubblePortraitCornerRadius(value.cornerRadius ?? 0);
8565
+ } catch (error) {
8566
+ throw new BubbleCompositionError("BUBBLE-COMPOSITION-001", error instanceof Error ? error.message : "Bubble portrait layout is invalid.");
8567
+ }
8468
8568
  return Object.freeze({
8469
8569
  base: requireAssetName(value.base, "Bubble portrait base"),
8470
8570
  ...blink === void 0 ? {} : { blink },
8471
- ...lipSync === void 0 ? {} : { lipSync }
8571
+ ...lipSync === void 0 ? {} : { lipSync },
8572
+ placement,
8573
+ offset,
8574
+ cornerRadius
8472
8575
  });
8473
8576
  }
8474
8577
  function normalizeMotion(value, label) {
8475
- if (!isRecord$2(value)) throw new BubbleCompositionError("BUBBLE-COMPOSITION-001", `${label} must be an object.`);
8476
- requireExactKeys(value, ["name"], [
8578
+ if (!isRecord$4(value)) throw new BubbleCompositionError("BUBBLE-COMPOSITION-001", `${label} must be an object.`);
8579
+ requireExactKeys$1(value, ["name"], [
8477
8580
  "durationSeconds",
8478
8581
  "ease",
8479
8582
  "direction",
@@ -8512,8 +8615,8 @@
8512
8615
  }
8513
8616
  function normalizeAudio(value) {
8514
8617
  if (value === void 0) return void 0;
8515
- if (!isRecord$2(value)) throw new BubbleCompositionError("BUBBLE-COMPOSITION-001", "Bubble audio must be an object.");
8516
- requireExactKeys(value, [], [
8618
+ if (!isRecord$4(value)) throw new BubbleCompositionError("BUBBLE-COMPOSITION-001", "Bubble audio must be an object.");
8619
+ requireExactKeys$1(value, [], [
8517
8620
  "voice",
8518
8621
  "reveal",
8519
8622
  "finish"
@@ -8530,8 +8633,8 @@
8530
8633
  return Object.freeze(result);
8531
8634
  }
8532
8635
  function normalizeStyle(value) {
8533
- if (!isRecord$2(value)) throw new BubbleCompositionError("BUBBLE-COMPOSITION-001", "Bubble style must be an object.");
8534
- requireExactKeys(value, ["name", "textStyle"], [
8636
+ if (!isRecord$4(value)) throw new BubbleCompositionError("BUBBLE-COMPOSITION-001", "Bubble style must be an object.");
8637
+ requireExactKeys$1(value, ["name", "textStyle"], [
8535
8638
  "placement",
8536
8639
  "maxWidth",
8537
8640
  "textLocale",
@@ -8580,10 +8683,10 @@
8580
8683
  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.");
8581
8684
  maxWidth = value.maxWidth;
8582
8685
  }
8583
- const textLocale = value.textLocale === void 0 ? void 0 : requireName(value.textLocale, "Bubble style text locale");
8686
+ const textLocale = value.textLocale === void 0 ? void 0 : requireName$1(value.textLocale, "Bubble style text locale");
8584
8687
  return Object.freeze({
8585
- name: requireName(value.name, "Bubble style name"),
8586
- textStyle: requireName(value.textStyle, "Bubble text style name"),
8688
+ name: requireName$1(value.name, "Bubble style name"),
8689
+ textStyle: requireName$1(value.textStyle, "Bubble text style name"),
8587
8690
  ...maxWidth === void 0 ? {} : { maxWidth },
8588
8691
  ...textLocale === void 0 ? {} : { textLocale },
8589
8692
  placement,
@@ -8601,12 +8704,12 @@
8601
8704
  }
8602
8705
  function validateImageResolver(value) {
8603
8706
  if (value === void 0) return void 0;
8604
- 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.");
8707
+ if (!isRecord$4(value) || typeof value.applyToTarget !== "function" || typeof value.getMimeType !== "function" || typeof value.isRegistered !== "function") throw new TypeError("Bubble image capability must provide applyToTarget, getMimeType, and isRegistered.");
8605
8708
  return value;
8606
8709
  }
8607
8710
  function validateAudioCapability(value) {
8608
8711
  if (value === void 0) return void 0;
8609
- if (!isRecord$2(value) || typeof value.playSound !== "function") throw new TypeError("Bubble audio capability must provide playSound.");
8712
+ if (!isRecord$4(value) || typeof value.playSound !== "function") throw new TypeError("Bubble audio capability must provide playSound.");
8610
8713
  if (value.isRegistered !== void 0 && typeof value.isRegistered !== "function") throw new TypeError("Bubble audio capability isRegistered must be a function.");
8611
8714
  if (value.getMimeType !== void 0 && typeof value.getMimeType !== "function") throw new TypeError("Bubble audio capability getMimeType must be a function.");
8612
8715
  return value;
@@ -8616,7 +8719,7 @@
8616
8719
  return value;
8617
8720
  }
8618
8721
  function validateTextCapability(value) {
8619
- if (!isRecord$2(value) || typeof value.setText !== "function" || typeof value.releaseTarget !== "function") throw new TypeError("Bubble text capability must provide setText and releaseTarget.");
8722
+ if (!isRecord$4(value) || typeof value.setText !== "function" || typeof value.releaseTarget !== "function") throw new TypeError("Bubble text capability must provide setText and releaseTarget.");
8620
8723
  return value;
8621
8724
  }
8622
8725
  function defaultScheduler() {
@@ -8626,11 +8729,11 @@
8626
8729
  });
8627
8730
  }
8628
8731
  function validateScheduler(value) {
8629
- if (!isRecord$2(value) || typeof value.setTimeout !== "function" || typeof value.clearTimeout !== "function") throw new TypeError("Bubble scheduler must provide setTimeout and clearTimeout.");
8732
+ if (!isRecord$4(value) || typeof value.setTimeout !== "function" || typeof value.clearTimeout !== "function") throw new TypeError("Bubble scheduler must provide setTimeout and clearTimeout.");
8630
8733
  return value;
8631
8734
  }
8632
8735
  function validateAssetTarget(value, label) {
8633
- 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.`);
8736
+ if (!isRecord$4(value) || typeof value.id !== "string" || value.id.length === 0 || typeof value.isStage !== "boolean") throw new BubbleCompositionError("BUBBLE-COMPOSITION-004", `${label} must provide id and isStage.`);
8634
8737
  return value;
8635
8738
  }
8636
8739
  function validateTextTarget(value) {
@@ -8638,7 +8741,7 @@
8638
8741
  return value;
8639
8742
  }
8640
8743
  function validateSurface(value, style) {
8641
- 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.");
8744
+ if (!isRecord$4(value) || !isRecord$4(value.targets) || typeof value.setLayerVisible !== "function" || typeof value.updateStyle !== "function" || typeof value.show !== "function" || typeof value.hide !== "function" || typeof value.dispose !== "function") throw new BubbleCompositionError("BUBBLE-COMPOSITION-004", "Bubble surface is invalid.");
8642
8745
  const targets = value.targets;
8643
8746
  validateTextTarget(targets.text);
8644
8747
  const assetTargetIds = /* @__PURE__ */ new Set();
@@ -8749,8 +8852,8 @@
8749
8852
  });
8750
8853
  }
8751
8854
  function normalizeShowInput(value) {
8752
- if (!isRecord$2(value)) throw new BubbleCompositionError("BUBBLE-COMPOSITION-001", "Show bubble input must be an object.");
8753
- requireExactKeys(value, [
8855
+ if (!isRecord$4(value)) throw new BubbleCompositionError("BUBBLE-COMPOSITION-001", "Show bubble input must be an object.");
8856
+ requireExactKeys$1(value, [
8754
8857
  "actor",
8755
8858
  "actorKey",
8756
8859
  "kind",
@@ -8769,16 +8872,16 @@
8769
8872
  }
8770
8873
  return {
8771
8874
  actor: value.actor,
8772
- actorKey: requireName(value.actorKey, "Bubble actor key"),
8875
+ actorKey: requireName$1(value.actorKey, "Bubble actor key"),
8773
8876
  kind: value.kind,
8774
8877
  text: value.text,
8775
- styleName: requireName(value.styleName, "Bubble style name"),
8878
+ styleName: requireName$1(value.styleName, "Bubble style name"),
8776
8879
  animationMode,
8777
8880
  ...reveal === void 0 ? {} : { reveal }
8778
8881
  };
8779
8882
  }
8780
8883
  function createBubbleComposition(options) {
8781
- if (!isRecord$2(options)) throw new TypeError("Bubble composition options must be an object.");
8884
+ if (!isRecord$4(options)) throw new TypeError("Bubble composition options must be an object.");
8782
8885
  const imageResolver = validateImageResolver(options.imageResolver);
8783
8886
  const audio = validateAudioCapability(options.audio);
8784
8887
  const textCapability = validateTextCapability(options.textCapability);
@@ -9256,7 +9359,7 @@
9256
9359
  styles.set(style.name, style);
9257
9360
  },
9258
9361
  hasActiveBubble(actorKey) {
9259
- return active.has(requireName(actorKey, "Bubble actor key"));
9362
+ return active.has(requireName$1(actorKey, "Bubble actor key"));
9260
9363
  },
9261
9364
  async show(input) {
9262
9365
  ensureActive();
@@ -9265,7 +9368,7 @@
9265
9368
  },
9266
9369
  releaseTarget(actorKey) {
9267
9370
  ensureActive();
9268
- const normalized = requireName(actorKey, "Bubble actor key");
9371
+ const normalized = requireName$1(actorKey, "Bubble actor key");
9269
9372
  return enqueueActor(normalized, async () => {
9270
9373
  await active.get(normalized)?.close();
9271
9374
  });
@@ -9286,14 +9389,580 @@
9286
9389
  });
9287
9390
  }
9288
9391
  //#endregion
9392
+ //#region node_modules/.pnpm/@kubohiroya+turbowarp-svg-text@0.8.0/node_modules/@kubohiroya/turbowarp-svg-text/dist/composition.js
9393
+ var block_definitions_default = {
9394
+ extensionName: "SVG Text",
9395
+ blocks: [{
9396
+ "opcode": "defineStyle",
9397
+ "blockType": "COMMAND",
9398
+ "text": "define text style [STYLE] background [BACKGROUND] text [TEXT_COLOR] font [FONT] size [SIZE] align [ALIGN]",
9399
+ "description": "Defines or replaces a named text style for SVG text actors. Bubble shape and placement are owned by the host Bubble layer.",
9400
+ "arguments": {
9401
+ "STYLE": {
9402
+ "type": "STRING",
9403
+ "defaultValue": "default"
9404
+ },
9405
+ "BACKGROUND": {
9406
+ "type": "COLOR",
9407
+ "defaultValue": "#ffffff"
9408
+ },
9409
+ "TEXT_COLOR": {
9410
+ "type": "COLOR",
9411
+ "defaultValue": "#575e75"
9412
+ },
9413
+ "FONT": {
9414
+ "type": "STRING",
9415
+ "defaultValue": "Helvetica"
9416
+ },
9417
+ "SIZE": {
9418
+ "type": "NUMBER",
9419
+ "defaultValue": 100
9420
+ },
9421
+ "ALIGN": {
9422
+ "type": "STRING",
9423
+ "defaultValue": "left",
9424
+ "menu": "alignment"
9425
+ }
9426
+ }
9427
+ }, {
9428
+ "opcode": "setText",
9429
+ "blockType": "COMMAND",
9430
+ "text": "set this sprite text [TEXT] with style [STYLE]",
9431
+ "description": "Replaces this sprite's skin with responsive styled SVG text.",
9432
+ "arguments": {
9433
+ "TEXT": {
9434
+ "type": "STRING",
9435
+ "defaultValue": "Title\\nSubtitle"
9436
+ },
9437
+ "STYLE": {
9438
+ "type": "STRING",
9439
+ "defaultValue": "default"
9440
+ }
9441
+ }
9442
+ }],
9443
+ menus: { "alignment": {
9444
+ "acceptReporters": true,
9445
+ "items": [
9446
+ "left",
9447
+ "center",
9448
+ "right"
9449
+ ]
9450
+ } }
9451
+ };
9452
+ var baseStageWidth = 480;
9453
+ var baseStageHeight = 360;
9454
+ var defaultFontPercent$1 = 100;
9455
+ var defaultRubyFontPercent$1 = 50;
9456
+ var defaultRubyGap$1 = 1;
9457
+ var maximumFontNameLength = 128;
9458
+ var textStyle = {
9459
+ fontSize: 14,
9460
+ lineHeight: 16,
9461
+ padding: 12,
9462
+ cornerRadius: 8
9463
+ };
9464
+ var DEFAULT_SVG_TEXT_STYLE = Object.freeze({
9465
+ alignment: "left",
9466
+ backgroundColor: "#ffffff",
9467
+ font: "Helvetica",
9468
+ fontPercent: defaultFontPercent$1,
9469
+ textColor: "#575e75"
9470
+ });
9471
+ var DEFAULT_SVG_TEXT_RICH_STYLE = Object.freeze({
9472
+ ...DEFAULT_SVG_TEXT_STYLE,
9473
+ rubyFontPercent: defaultRubyFontPercent$1,
9474
+ rubyGap: defaultRubyGap$1
9475
+ });
9476
+ function createSvgTextLayout(text, definition, nativeSize) {
9477
+ const metrics = createTextMetrics(definition, nativeSize);
9478
+ const lineMeasurements = text.split("\n").map((line) => ({
9479
+ text: line,
9480
+ width: measureTextWidth(line, metrics.fontSize)
9481
+ }));
9482
+ const contentWidth = Math.max(1, ...lineMeasurements.map((line) => line.width));
9483
+ const width = Math.max(1, Math.ceil(contentWidth + metrics.padding * 2));
9484
+ const height = Math.max(1, Math.ceil(metrics.lineHeight * lineMeasurements.length + metrics.padding * 2));
9485
+ const x = definition.alignment === "center" ? width / 2 : definition.alignment === "right" ? width - metrics.padding : metrics.padding;
9486
+ const lines = Object.freeze(lineMeasurements.map((line, index) => Object.freeze({
9487
+ baseline: metrics.padding + metrics.fontSize + metrics.lineHeight * index,
9488
+ text: line.text,
9489
+ width: line.width,
9490
+ x
9491
+ })));
9492
+ const style = createLayoutStyle(definition, metrics);
9493
+ return Object.freeze({
9494
+ height,
9495
+ lines,
9496
+ preserveWhitespace: true,
9497
+ style,
9498
+ width
9499
+ });
9500
+ }
9501
+ function createSvgTextRichLayout(runs, definition, nativeSize, maxWidth) {
9502
+ const metrics = createTextMetrics(definition, nativeSize);
9503
+ const rubyFontSize = metrics.fontSize * (definition.rubyFontPercent / defaultFontPercent$1);
9504
+ const rubyGap = definition.rubyGap * metrics.fontScale;
9505
+ const style = Object.freeze({
9506
+ ...createLayoutStyle(definition, metrics),
9507
+ rubyFontPercent: definition.rubyFontPercent,
9508
+ rubyFontSize,
9509
+ rubyGap
9510
+ });
9511
+ const plainText = runs.map((run) => run.type === "ruby" ? run.base : run.text).join("");
9512
+ const readingText = runs.map((run) => run.type === "ruby" ? run.reading : run.text).join("");
9513
+ const revealUnits = [];
9514
+ const items = [];
9515
+ for (const [runIndex, run] of runs.entries()) {
9516
+ if (run.type === "ruby") {
9517
+ const reveal = Object.freeze({
9518
+ end: run.base.length,
9519
+ index: revealUnits.length,
9520
+ runIndex,
9521
+ start: 0,
9522
+ type: "ruby"
9523
+ });
9524
+ revealUnits.push(reveal);
9525
+ const baseWidth = measureTextWidth(run.base, metrics.fontSize);
9526
+ const readingWidth = measureTextWidth(run.reading, rubyFontSize);
9527
+ items.push({
9528
+ base: run.base,
9529
+ baseWidth,
9530
+ reading: run.reading,
9531
+ readingWidth,
9532
+ reveal,
9533
+ type: "ruby",
9534
+ width: Math.max(baseWidth, readingWidth)
9535
+ });
9536
+ continue;
9537
+ }
9538
+ for (const grapheme of segmentGraphemes(run.text)) {
9539
+ if (grapheme.segment === "\n") {
9540
+ items.push("break");
9541
+ continue;
9542
+ }
9543
+ const reveal = Object.freeze({
9544
+ end: grapheme.end,
9545
+ index: revealUnits.length,
9546
+ runIndex,
9547
+ start: grapheme.start,
9548
+ type: "text"
9549
+ });
9550
+ revealUnits.push(reveal);
9551
+ items.push({
9552
+ reveal,
9553
+ text: grapheme.segment,
9554
+ type: "text",
9555
+ width: measureTextWidth(grapheme.segment, metrics.fontSize)
9556
+ });
9557
+ }
9558
+ }
9559
+ const contentLimit = maxWidth === void 0 ? void 0 : Math.max(1, maxWidth - metrics.padding * 2);
9560
+ const pendingLines = [];
9561
+ let pendingLine = {
9562
+ units: [],
9563
+ width: 0
9564
+ };
9565
+ const finishLine = () => {
9566
+ pendingLines.push(pendingLine);
9567
+ pendingLine = {
9568
+ units: [],
9569
+ width: 0
9570
+ };
9571
+ };
9572
+ for (const item of items) {
9573
+ if (item === "break") {
9574
+ finishLine();
9575
+ continue;
9576
+ }
9577
+ if (contentLimit !== void 0 && pendingLine.units.length > 0 && pendingLine.width + item.width > contentLimit) finishLine();
9578
+ pendingLine.units.push(item);
9579
+ pendingLine.width += item.width;
9580
+ }
9581
+ finishLine();
9582
+ const naturalWidth = Math.max(1, ...pendingLines.map((line) => line.width)) + metrics.padding * 2;
9583
+ const width = Math.max(1, Math.ceil(maxWidth === void 0 ? naturalWidth : Math.max(maxWidth, naturalWidth)));
9584
+ const baseDescent = Math.max(0, metrics.lineHeight - metrics.fontSize);
9585
+ let lineTop = metrics.padding;
9586
+ const lines = Object.freeze(pendingLines.map((pending) => {
9587
+ const hasRuby = pending.units.some((unit) => unit.type === "ruby");
9588
+ const ascent = metrics.fontSize + (hasRuby ? rubyFontSize + rubyGap : 0);
9589
+ const descent = baseDescent;
9590
+ const height = ascent + descent;
9591
+ const baseline = lineTop + ascent;
9592
+ const x = definition.alignment === "center" ? (width - pending.width) / 2 : definition.alignment === "right" ? width - metrics.padding - pending.width : metrics.padding;
9593
+ let fragmentX = x;
9594
+ const fragments = Object.freeze(pending.units.map((unit) => {
9595
+ if (unit.type === "text") {
9596
+ const fragment = Object.freeze({
9597
+ baseline,
9598
+ revealIndex: unit.reveal.index,
9599
+ text: unit.text,
9600
+ type: "text",
9601
+ width: unit.width,
9602
+ x: fragmentX
9603
+ });
9604
+ fragmentX += unit.width;
9605
+ return fragment;
9606
+ }
9607
+ const groupX = fragmentX;
9608
+ const base = Object.freeze({
9609
+ baseline,
9610
+ fontSize: metrics.fontSize,
9611
+ text: unit.base,
9612
+ width: unit.baseWidth,
9613
+ x: groupX + (unit.width - unit.baseWidth) / 2
9614
+ });
9615
+ const reading = Object.freeze({
9616
+ baseline: baseline - metrics.fontSize - rubyGap,
9617
+ fontSize: rubyFontSize,
9618
+ text: unit.reading,
9619
+ width: unit.readingWidth,
9620
+ x: groupX + (unit.width - unit.readingWidth) / 2
9621
+ });
9622
+ const fragment = Object.freeze({
9623
+ base,
9624
+ reading,
9625
+ revealIndex: unit.reveal.index,
9626
+ type: "ruby",
9627
+ width: unit.width,
9628
+ x: groupX
9629
+ });
9630
+ fragmentX += unit.width;
9631
+ return fragment;
9632
+ }));
9633
+ const line = Object.freeze({
9634
+ ascent,
9635
+ baseline,
9636
+ descent,
9637
+ fragments,
9638
+ height,
9639
+ overflow: contentLimit !== void 0 && pending.width > contentLimit,
9640
+ width: pending.width,
9641
+ x
9642
+ });
9643
+ lineTop += height;
9644
+ return line;
9645
+ }));
9646
+ const height = Math.max(1, Math.ceil(lineTop + metrics.padding));
9647
+ const overflow = lines.some((line) => line.overflow);
9648
+ return Object.freeze({
9649
+ height,
9650
+ lines,
9651
+ overflow,
9652
+ plainText,
9653
+ preserveWhitespace: true,
9654
+ readingText,
9655
+ revealUnits: Object.freeze(revealUnits),
9656
+ style,
9657
+ width
9658
+ });
9659
+ }
9660
+ function normalizeSvgTextColor(value, fallback) {
9661
+ const color = value.trim();
9662
+ if (color === "") return fallback;
9663
+ if (color.toLowerCase() === "transparent") return color;
9664
+ if (/^#(?:[\da-f]{3}|[\da-f]{4}|[\da-f]{6}|[\da-f]{8})$/iu.test(color)) return color;
9665
+ if (globalThis.CSS?.supports?.("color", color)) return color;
9666
+ return fallback;
9667
+ }
9668
+ function normalizeSvgTextFont(value) {
9669
+ const font = value.trim();
9670
+ const hasUnsafeCharacter = [...font].some((character) => {
9671
+ const codePoint = character.codePointAt(0) ?? 0;
9672
+ return codePoint <= 31 || codePoint === 127 || ",;{}".includes(character);
9673
+ });
9674
+ if (font === "" || font.length > maximumFontNameLength || hasUnsafeCharacter) return DEFAULT_SVG_TEXT_STYLE.font;
9675
+ return font;
9676
+ }
9677
+ function createTextMetrics(definition, nativeSize) {
9678
+ const stageScale = Math.min(nativeSize[0] / baseStageWidth, nativeSize[1] / baseStageHeight);
9679
+ const fontScale = stageScale * (definition.fontPercent / defaultFontPercent$1);
9680
+ return {
9681
+ cornerRadius: textStyle.cornerRadius * stageScale,
9682
+ fontScale,
9683
+ fontSize: textStyle.fontSize * fontScale,
9684
+ lineHeight: textStyle.lineHeight * fontScale,
9685
+ padding: textStyle.padding * stageScale
9686
+ };
9687
+ }
9688
+ function createLayoutStyle(definition, metrics) {
9689
+ return Object.freeze({
9690
+ alignment: definition.alignment,
9691
+ backgroundColor: definition.backgroundColor,
9692
+ cornerRadius: metrics.cornerRadius,
9693
+ font: definition.font,
9694
+ fontPercent: definition.fontPercent,
9695
+ fontSize: metrics.fontSize,
9696
+ lineHeight: metrics.lineHeight,
9697
+ padding: metrics.padding,
9698
+ textColor: definition.textColor
9699
+ });
9700
+ }
9701
+ function segmentGraphemes(value) {
9702
+ const segments = [];
9703
+ let current = "";
9704
+ let currentStart = 0;
9705
+ let joinNext = false;
9706
+ let offset = 0;
9707
+ for (const character of value) {
9708
+ if (!(current !== "" && (joinNext || character === "‍" || isGraphemeExtender(character))) && current !== "") {
9709
+ segments.push({
9710
+ end: offset,
9711
+ segment: current,
9712
+ start: currentStart
9713
+ });
9714
+ current = "";
9715
+ }
9716
+ if (current === "") currentStart = offset;
9717
+ current += character;
9718
+ joinNext = character === "‍";
9719
+ offset += character.length;
9720
+ }
9721
+ if (current !== "") segments.push({
9722
+ end: offset,
9723
+ segment: current,
9724
+ start: currentStart
9725
+ });
9726
+ return segments;
9727
+ }
9728
+ function isGraphemeExtender(character) {
9729
+ if (/\p{Mark}/u.test(character)) return true;
9730
+ const codePoint = character.codePointAt(0) ?? 0;
9731
+ return codePoint >= 65024 && codePoint <= 65039 || codePoint >= 917760 && codePoint <= 917999 || codePoint >= 127995 && codePoint <= 127999;
9732
+ }
9733
+ function measureTextWidth(text, fontSize) {
9734
+ let units = 0;
9735
+ for (const character of text) {
9736
+ if (/\p{Mark}/u.test(character)) continue;
9737
+ if (/\s/u.test(character)) {
9738
+ units += .35;
9739
+ continue;
9740
+ }
9741
+ const codePoint = character.codePointAt(0) ?? 0;
9742
+ units += codePoint <= 127 ? .62 : 1;
9743
+ }
9744
+ return units * fontSize;
9745
+ }
9746
+ block_definitions_default.blocks;
9747
+ block_definitions_default.menus;
9748
+ `${encodeURIComponent("<svg xmlns=\"http://www.w3.org/2000/svg\" viewBox=\"0 0 64 64\"><g fill=\"none\" stroke=\"#fff\" stroke-width=\"5\" stroke-linecap=\"round\" stroke-linejoin=\"round\"><path d=\"M13 23V12h11M40 12h11v11M13 41v11h11M40 52h11V41M22 23h20M32 23v23\"/></g></svg>")}`;
9749
+ var defaultStyleName = "default";
9750
+ var maximumContentCharacters = 1e5;
9751
+ var maximumContentLines = 1e3;
9752
+ var maximumContentRuns = 1024;
9753
+ var maximumLayoutFragments = 1e4;
9754
+ var maximumLayoutWidth = 1e5;
9755
+ var maximumRubyBaseCharacters = 256;
9756
+ var maximumRubyReadingCharacters = 512;
9757
+ function isRecord$3(value) {
9758
+ return typeof value === "object" && value !== null && !Array.isArray(value);
9759
+ }
9760
+ function compositionError(code, message) {
9761
+ const error = new Error(message);
9762
+ Object.defineProperty(error, "code", { value: code });
9763
+ return error;
9764
+ }
9765
+ function requireExactKeys(value, required, optional, label) {
9766
+ const allowed = /* @__PURE__ */ new Set([...required, ...optional]);
9767
+ 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.`);
9768
+ }
9769
+ function requireName(value, label) {
9770
+ if (typeof value !== "string" || value.trim().length === 0) throw compositionError("SVG-TEXT-COMPOSITION-001", `${label} must be a non-empty string.`);
9771
+ return value.trim();
9772
+ }
9773
+ function validateOptionalString(value, label) {
9774
+ if (value !== void 0 && (typeof value !== "string" || value.length === 0)) throw compositionError("SVG-TEXT-COMPOSITION-001", `${label} must be a non-empty string when provided.`);
9775
+ }
9776
+ function validateStyle(value) {
9777
+ if (!isRecord$3(value)) throw compositionError("SVG-TEXT-COMPOSITION-001", "SVG Text style must be an object.");
9778
+ requireExactKeys(value, ["name"], [
9779
+ "alignment",
9780
+ "backgroundColor",
9781
+ "font",
9782
+ "fontPercent",
9783
+ "rubyFontPercent",
9784
+ "rubyGap",
9785
+ "textColor"
9786
+ ], "SVG Text style");
9787
+ const name = requireName(value.name, "SVG Text style name");
9788
+ 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.");
9789
+ validateOptionalString(value.backgroundColor, "SVG Text backgroundColor");
9790
+ validateOptionalString(value.font, "SVG Text font");
9791
+ validateOptionalString(value.textColor, "SVG Text textColor");
9792
+ 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.");
9793
+ 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.");
9794
+ 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.");
9795
+ return {
9796
+ ...value,
9797
+ name
9798
+ };
9799
+ }
9800
+ function createStyleDefinition(style) {
9801
+ return Object.freeze({
9802
+ alignment: style.alignment ?? DEFAULT_SVG_TEXT_STYLE.alignment,
9803
+ backgroundColor: normalizeSvgTextColor(style.backgroundColor ?? "", DEFAULT_SVG_TEXT_STYLE.backgroundColor),
9804
+ font: normalizeSvgTextFont(style.font ?? ""),
9805
+ fontPercent: style.fontPercent ?? DEFAULT_SVG_TEXT_STYLE.fontPercent,
9806
+ rubyFontPercent: style.rubyFontPercent ?? DEFAULT_SVG_TEXT_RICH_STYLE.rubyFontPercent,
9807
+ rubyGap: style.rubyGap ?? DEFAULT_SVG_TEXT_RICH_STYLE.rubyGap,
9808
+ textColor: normalizeSvgTextColor(style.textColor ?? "", DEFAULT_SVG_TEXT_STYLE.textColor)
9809
+ });
9810
+ }
9811
+ function validateNativeSize(value) {
9812
+ if (!Array.isArray(value) || value.length !== 2 || value.some((dimension) => typeof dimension !== "number" || !Number.isFinite(dimension) || dimension <= 0)) throw compositionError("SVG-TEXT-COMPOSITION-001", "SVG Text nativeSize must be [width, height] with two positive finite numbers.");
9813
+ return value;
9814
+ }
9815
+ function normalizeText(value) {
9816
+ return value.replace(/\\r\\n|\\n|\\r/gu, "\n");
9817
+ }
9818
+ function normalizeRichText(value) {
9819
+ return normalizeText(value.replace(/\r\n?|\n/gu, "\n"));
9820
+ }
9821
+ function contentLimitError(message) {
9822
+ return compositionError("SVG-TEXT-COMPOSITION-007", message);
9823
+ }
9824
+ function validateContentRuns(value) {
9825
+ if (!Array.isArray(value)) throw compositionError("SVG-TEXT-COMPOSITION-001", "SVG Text rich content runs must be an array.");
9826
+ if (value.length > maximumContentRuns) throw contentLimitError(`SVG Text rich content exceeds ${maximumContentRuns} runs.`);
9827
+ let characterCount = 0;
9828
+ let fragmentCount = 0;
9829
+ let lineCount = 1;
9830
+ const runs = value.map((candidate, runIndex) => {
9831
+ if (!isRecord$3(candidate)) throw compositionError("SVG-TEXT-COMPOSITION-001", `SVG Text rich content run ${runIndex} must be an object.`);
9832
+ if (candidate.type === "text") {
9833
+ requireExactKeys(candidate, ["type", "text"], [], `SVG Text rich content run ${runIndex}`);
9834
+ if (typeof candidate.text !== "string") throw compositionError("SVG-TEXT-COMPOSITION-001", `SVG Text rich content run ${runIndex} text must be a string.`);
9835
+ const text = normalizeRichText(candidate.text);
9836
+ characterCount += text.length;
9837
+ lineCount += text.split("\n").length - 1;
9838
+ fragmentCount += [...text.replace(/\n/gu, "")].length;
9839
+ return Object.freeze({
9840
+ text,
9841
+ type: "text"
9842
+ });
9843
+ }
9844
+ if (candidate.type === "ruby") {
9845
+ requireExactKeys(candidate, [
9846
+ "type",
9847
+ "base",
9848
+ "reading"
9849
+ ], [], `SVG Text rich content run ${runIndex}`);
9850
+ 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.`);
9851
+ const base = normalizeRichText(candidate.base);
9852
+ const reading = normalizeRichText(candidate.reading);
9853
+ 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.`);
9854
+ if (base.length > maximumRubyBaseCharacters) throw contentLimitError(`SVG Text ruby base exceeds ${maximumRubyBaseCharacters} characters.`);
9855
+ if (reading.length > maximumRubyReadingCharacters) throw contentLimitError(`SVG Text ruby reading exceeds ${maximumRubyReadingCharacters} characters.`);
9856
+ characterCount += base.length + reading.length;
9857
+ fragmentCount += 1;
9858
+ return Object.freeze({
9859
+ base,
9860
+ reading,
9861
+ type: "ruby"
9862
+ });
9863
+ }
9864
+ throw compositionError("SVG-TEXT-COMPOSITION-001", `SVG Text rich content run ${runIndex} type is invalid.`);
9865
+ });
9866
+ if (characterCount > maximumContentCharacters) throw contentLimitError(`SVG Text rich content exceeds ${maximumContentCharacters} characters.`);
9867
+ if (lineCount > maximumContentLines) throw contentLimitError(`SVG Text rich content exceeds ${maximumContentLines} lines.`);
9868
+ if (fragmentCount > maximumLayoutFragments) throw contentLimitError(`SVG Text rich content exceeds ${maximumLayoutFragments} layout fragments.`);
9869
+ return Object.freeze(runs);
9870
+ }
9871
+ function validateMaxWidth(value) {
9872
+ if (value === void 0) return void 0;
9873
+ 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}.`);
9874
+ return value;
9875
+ }
9876
+ function layoutTextFromStyles(styles, input) {
9877
+ if (!isRecord$3(input)) throw compositionError("SVG-TEXT-COMPOSITION-001", "SVG Text layout input is invalid.");
9878
+ requireExactKeys(input, [
9879
+ "styleName",
9880
+ "text",
9881
+ "nativeSize"
9882
+ ], [], "SVG Text layout input");
9883
+ const styleName = requireName(input.styleName, "SVG Text styleName");
9884
+ const definition = styles.get(styleName);
9885
+ if (!definition) throw compositionError("SVG-TEXT-COMPOSITION-003", `SVG Text style is not defined: ${styleName}`);
9886
+ if (typeof input.text !== "string") throw compositionError("SVG-TEXT-COMPOSITION-001", "SVG Text text must be a string.");
9887
+ return createSvgTextLayout(normalizeText(input.text), definition, validateNativeSize(input.nativeSize));
9888
+ }
9889
+ function layoutRichTextFromStyles(styles, input) {
9890
+ if (!isRecord$3(input)) throw compositionError("SVG-TEXT-COMPOSITION-001", "SVG Text rich layout input is invalid.");
9891
+ requireExactKeys(input, [
9892
+ "styleName",
9893
+ "runs",
9894
+ "nativeSize"
9895
+ ], ["maxWidth"], "SVG Text rich layout input");
9896
+ const styleName = requireName(input.styleName, "SVG Text styleName");
9897
+ const definition = styles.get(styleName);
9898
+ if (!definition) throw compositionError("SVG-TEXT-COMPOSITION-003", `SVG Text style is not defined: ${styleName}`);
9899
+ const runs = validateContentRuns(input.runs);
9900
+ const nativeSize = validateNativeSize(input.nativeSize);
9901
+ const maxWidth = validateMaxWidth(input.maxWidth);
9902
+ return maxWidth === void 0 ? createSvgTextRichLayout(runs, definition, nativeSize) : createSvgTextRichLayout(runs, definition, nativeSize, maxWidth);
9903
+ }
9904
+ function createSvgTextLayoutComposition() {
9905
+ const styles = /* @__PURE__ */ new Map([[defaultStyleName, DEFAULT_SVG_TEXT_RICH_STYLE]]);
9906
+ return Object.freeze({
9907
+ defineStyle(input) {
9908
+ const style = validateStyle(input);
9909
+ styles.set(style.name, createStyleDefinition(style));
9910
+ },
9911
+ layoutRichText(input) {
9912
+ return layoutRichTextFromStyles(styles, input);
9913
+ },
9914
+ layoutText(input) {
9915
+ return layoutTextFromStyles(styles, input);
9916
+ }
9917
+ });
9918
+ }
9919
+ //#endregion
9289
9920
  //#region src/turbowarp-svg-text-adapter.ts
9290
- function isRecord$1(value) {
9921
+ function isRecord$2(value) {
9291
9922
  return typeof value === "object" && value !== null && !Array.isArray(value);
9292
9923
  }
9293
9924
  function validateExtension(value) {
9294
- if (!isRecord$1(value) || typeof value.setText !== "function" || typeof value.releaseTextActor !== "function") throw new TypeError("TurboWarp SVG Text adapter requires setText and releaseTextActor.");
9925
+ if (!isRecord$2(value) || typeof value.setText !== "function" || typeof value.releaseTextActor !== "function") throw new TypeError("TurboWarp SVG Text adapter requires setText and releaseTextActor.");
9926
+ return value;
9927
+ }
9928
+ function validateLayoutComposition(value) {
9929
+ if (!isRecord$2(value) || typeof value.layoutText !== "function") throw new TypeError("SVG Text overlay adapter requires the layoutText composition API.");
9295
9930
  return value;
9296
9931
  }
9932
+ function requireFiniteNumber(value, label) {
9933
+ const result = Number(value);
9934
+ if (!Number.isFinite(result)) throw new TypeError(`${label} must be a finite number.`);
9935
+ return result;
9936
+ }
9937
+ function adaptSvgTextLayout(value) {
9938
+ if (!isRecord$2(value) || !isRecord$2(value.style) || !Array.isArray(value.lines)) throw new TypeError("SVG Text layout result is invalid.");
9939
+ const style = value.style;
9940
+ const alignment = style.alignment;
9941
+ if (alignment !== "left" && alignment !== "center" && alignment !== "right") throw new TypeError("SVG Text layout alignment is invalid.");
9942
+ const width = requireFiniteNumber(value.width, "SVG Text layout width");
9943
+ const height = requireFiniteNumber(value.height, "SVG Text layout height");
9944
+ const lines = Object.freeze(value.lines.map((line) => {
9945
+ if (!isRecord$2(line) || typeof line.text !== "string") throw new TypeError("SVG Text layout line is invalid.");
9946
+ return Object.freeze({
9947
+ baseline: requireFiniteNumber(line.baseline, "SVG Text line baseline") - height / 2,
9948
+ text: line.text,
9949
+ x: requireFiniteNumber(line.x, "SVG Text line x") - width / 2
9950
+ });
9951
+ }));
9952
+ return Object.freeze({
9953
+ alignment,
9954
+ backgroundColor: String(style.backgroundColor),
9955
+ backgroundCornerRadius: requireFiniteNumber(style.cornerRadius, "SVG Text corner radius"),
9956
+ fill: String(style.textColor),
9957
+ fontFamily: String(style.font),
9958
+ fontSize: requireFiniteNumber(style.fontSize, "SVG Text font size"),
9959
+ height,
9960
+ lineHeight: requireFiniteNumber(style.lineHeight, "SVG Text line height"),
9961
+ lines,
9962
+ preserveWhitespace: value.preserveWhitespace !== false,
9963
+ width
9964
+ });
9965
+ }
9297
9966
  /**
9298
9967
  * Adapt the TurboWarp SVG Text extension to Bubble's host-neutral text
9299
9968
  * capability contract.
@@ -9316,81 +9985,37 @@
9316
9985
  }
9317
9986
  });
9318
9987
  }
9319
- //#endregion
9320
- //#region src/turbowarp-adapter.ts
9321
- var spriteLayer = "sprite";
9322
- var portraitBoxSize = 96;
9323
- var indicatorBoxSize = 18;
9324
- var contentGap = 8;
9325
- var stageSafeMargin = 16;
9326
- var surfaceSequence = 0;
9327
- var BubbleRuntimeAdapterError = class extends Error {
9328
- constructor(code, message) {
9329
- super(message);
9330
- _defineProperty(this, "code", void 0);
9331
- this.name = "BubbleRuntimeAdapterError";
9332
- this.code = code;
9333
- }
9334
- };
9335
- function isRecord(value) {
9336
- return typeof value === "object" && value !== null && !Array.isArray(value);
9337
- }
9338
- function requireRenderer(value) {
9339
- if (!isRecord(value)) throw new BubbleRuntimeAdapterError("BUBBLE-RUNTIME-001", "Bubble requires the TurboWarp renderer.");
9340
- const methods = [
9341
- "createSVGSkin",
9342
- "createDrawable",
9343
- "destroyDrawable",
9344
- "destroySkin",
9345
- "getCurrentSkinSize",
9346
- "getNativeSize",
9347
- "updateDrawablePosition",
9348
- "updateDrawableScale",
9349
- "updateDrawableSkinId",
9350
- "updateDrawableVisible"
9351
- ];
9352
- if (methods.some((method) => typeof value[method] !== "function")) throw new BubbleRuntimeAdapterError("BUBBLE-RUNTIME-001", `Bubble renderer must provide ${methods.join(", ")}.`);
9353
- return value;
9354
- }
9355
- function requireAssetManager(value) {
9356
- 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.");
9357
- return value;
9358
- }
9359
- function targetBounds(target) {
9360
- try {
9361
- const bounds = target.getBoundsForBubble?.();
9362
- if (bounds && [
9363
- bounds.bottom,
9364
- bounds.left,
9365
- bounds.right,
9366
- bounds.top
9367
- ].every((value) => Number.isFinite(value))) return bounds;
9368
- } catch {}
9369
- const x = Number.isFinite(target.x) ? Number(target.x) : 0;
9370
- const y = Number.isFinite(target.y) ? Number(target.y) : 0;
9371
- return {
9372
- bottom: y,
9373
- left: x,
9374
- right: x,
9375
- top: y
9376
- };
9377
- }
9378
- function readSize(renderer, target, fallback) {
9379
- const raw = renderer.getCurrentSkinSize(target.drawableID);
9380
- if (!Array.isArray(raw) || raw.length < 2) return fallback;
9381
- const width = Number(raw[0]);
9382
- const height = Number(raw[1]);
9383
- if (!(width > 0) || !(height > 0)) return fallback;
9384
- return {
9385
- width,
9386
- height
9387
- };
9988
+ /**
9989
+ * Adapt SVG Text's host-neutral layout composition to Bubble's SVG overlay.
9990
+ * The adapter preserves SVG Text's line coordinates without creating skins.
9991
+ */
9992
+ function createSvgTextOverlayTextCapability(compositionInput) {
9993
+ const composition = validateLayoutComposition(compositionInput);
9994
+ return Object.freeze({
9995
+ layoutText({ nativeSize, styleName, text }) {
9996
+ return adaptSvgTextLayout(composition.layoutText({
9997
+ nativeSize: [nativeSize.width, nativeSize.height],
9998
+ styleName,
9999
+ text
10000
+ }));
10001
+ },
10002
+ measureText({ nativeSize, styleName, text }) {
10003
+ const layout = composition.layoutText({
10004
+ nativeSize: [nativeSize.width, nativeSize.height],
10005
+ styleName,
10006
+ text
10007
+ });
10008
+ return Math.max(1, ...layout.lines.map((line) => requireFiniteNumber(line.width, "SVG Text line width")));
10009
+ }
10010
+ });
9388
10011
  }
9389
- function clamp01(value) {
10012
+ //#endregion
10013
+ //#region src/surface-motion.ts
10014
+ function clampMotionProgress(value) {
9390
10015
  return Math.max(0, Math.min(1, value));
9391
10016
  }
9392
- function easeProgress(value, ease) {
9393
- const progress = clamp01(value);
10017
+ function easeMotionProgress(value, ease) {
10018
+ const progress = clampMotionProgress(value);
9394
10019
  switch (ease) {
9395
10020
  case "linear": return progress;
9396
10021
  case "easeIn": return progress * progress;
@@ -9400,9 +10025,8 @@
9400
10025
  }
9401
10026
  }
9402
10027
  /**
9403
- * Drives a motion with the same scheduler used by frame loops and reveal.
9404
- * The adapter intentionally does not depend on requestAnimationFrame so a
9405
- * host can provide deterministic time in tests and non-browser runtimes.
10028
+ * Drive a motion with Bubble's scheduler so tests and non-browser hosts can
10029
+ * provide deterministic time without requestAnimationFrame.
9406
10030
  */
9407
10031
  function runMotionTimeline(scheduler, durationSeconds, onFrame) {
9408
10032
  const durationMilliseconds = Math.max(0, durationSeconds * 1e3);
@@ -9417,7 +10041,7 @@
9417
10041
  const step = Math.min(16, durationMilliseconds - elapsed);
9418
10042
  elapsed += step;
9419
10043
  try {
9420
- onFrame(clamp01(elapsed / durationMilliseconds));
10044
+ onFrame(clampMotionProgress(elapsed / durationMilliseconds));
9421
10045
  } catch (error) {
9422
10046
  if (timer !== void 0) scheduler.clearTimeout(timer);
9423
10047
  reject(error);
@@ -9432,8 +10056,948 @@
9432
10056
  timer = scheduler.setTimeout(tick, Math.min(16, durationMilliseconds));
9433
10057
  });
9434
10058
  }
9435
- function fitDrawable(renderer, target, boxSize, scaleMultiplier = 1) {
9436
- const native = readSize(renderer, target, {
10059
+ //#endregion
10060
+ //#region src/svg-overlay-surface.ts
10061
+ var svgNamespace = "http://www.w3.org/2000/svg";
10062
+ var xmlNamespace = "http://www.w3.org/XML/1998/namespace";
10063
+ var portraitBoxSize$1 = 96;
10064
+ var indicatorBoxSize$1 = 18;
10065
+ var contentGap$1 = 8;
10066
+ var stageSafeMargin$1 = 16;
10067
+ var overlayTextTargetMarker = Symbol("BubbleSvgOverlayTextTarget");
10068
+ var overlayImageTargetMarker = Symbol("BubbleSvgOverlayImageTarget");
10069
+ var overlaySurfaceSequence = 0;
10070
+ Object.freeze(["scratch-render", "svg-overlay"]);
10071
+ function isRecord$1(value) {
10072
+ return typeof value === "object" && value !== null && !Array.isArray(value);
10073
+ }
10074
+ function readNativeSize(renderer) {
10075
+ const raw = renderer.getNativeSize();
10076
+ const width = Array.isArray(raw) ? Number(raw[0]) : NaN;
10077
+ const height = Array.isArray(raw) ? Number(raw[1]) : NaN;
10078
+ return Object.freeze({
10079
+ width: width > 0 ? width : 480,
10080
+ height: height > 0 ? height : 360
10081
+ });
10082
+ }
10083
+ function requireFiniteDimension(value, label) {
10084
+ const result = Number(value);
10085
+ if (!Number.isFinite(result) || result <= 0) throw new TypeError(`${label} must be a positive finite number.`);
10086
+ return result;
10087
+ }
10088
+ function requireSafeColor(value, label) {
10089
+ if (typeof value !== "string" || value.length === 0 || value.length > 128) throw new TypeError(`${label} must be a non-empty color string.`);
10090
+ if (/url\s*\(|[<>;]/iu.test(value)) throw new TypeError(`${label} contains a disallowed SVG value.`);
10091
+ return value;
10092
+ }
10093
+ function requireSafeFontFamily(value) {
10094
+ if (typeof value !== "string" || value.length === 0 || value.length > 256 || /url\s*\(|[<>{};]/iu.test(value)) throw new TypeError("SVG overlay fontFamily is invalid.");
10095
+ return value;
10096
+ }
10097
+ function normalizeTextLayout(value) {
10098
+ if (!isRecord$1(value) || !Array.isArray(value.lines)) throw new TypeError("SVG overlay text layout is invalid.");
10099
+ const alignment = value.alignment;
10100
+ if (alignment !== "left" && alignment !== "center" && alignment !== "right") throw new TypeError("SVG overlay text alignment is invalid.");
10101
+ const fontStyle = value.fontStyle;
10102
+ if (fontStyle !== void 0 && fontStyle !== "normal" && fontStyle !== "italic") throw new TypeError("SVG overlay fontStyle is invalid.");
10103
+ const fontWeight = value.fontWeight;
10104
+ 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.");
10105
+ const lines = Object.freeze(value.lines.map((line) => {
10106
+ if (typeof line === "string") return line;
10107
+ if (!isRecord$1(line) || typeof line.text !== "string") throw new TypeError("SVG overlay text lines must be strings or positioned line records.");
10108
+ const hasX = line.x !== void 0;
10109
+ if (hasX !== (line.baseline !== void 0)) throw new TypeError("SVG overlay positioned text lines require both x and baseline.");
10110
+ if (hasX && (!Number.isFinite(line.x) || !Number.isFinite(line.baseline))) throw new TypeError("SVG overlay text line coordinates must be finite numbers.");
10111
+ return Object.freeze({
10112
+ text: line.text,
10113
+ ...hasX ? {
10114
+ x: Number(line.x),
10115
+ baseline: Number(line.baseline)
10116
+ } : {}
10117
+ });
10118
+ }));
10119
+ const backgroundColor = value.backgroundColor === void 0 ? void 0 : requireSafeColor(value.backgroundColor, "SVG overlay backgroundColor");
10120
+ const backgroundCornerRadius = value.backgroundCornerRadius === void 0 ? void 0 : Number(value.backgroundCornerRadius);
10121
+ if (backgroundCornerRadius !== void 0 && (!Number.isFinite(backgroundCornerRadius) || backgroundCornerRadius < 0)) throw new TypeError("SVG overlay backgroundCornerRadius must be a non-negative finite number.");
10122
+ const preserveWhitespace = value.preserveWhitespace;
10123
+ if (preserveWhitespace !== void 0 && typeof preserveWhitespace !== "boolean") throw new TypeError("SVG overlay preserveWhitespace must be a boolean.");
10124
+ return Object.freeze({
10125
+ alignment,
10126
+ fill: requireSafeColor(value.fill, "SVG overlay text fill"),
10127
+ fontFamily: requireSafeFontFamily(value.fontFamily),
10128
+ fontSize: requireFiniteDimension(value.fontSize, "SVG overlay fontSize"),
10129
+ height: requireFiniteDimension(value.height, "SVG overlay text height"),
10130
+ lineHeight: requireFiniteDimension(value.lineHeight, "SVG overlay lineHeight"),
10131
+ lines,
10132
+ width: requireFiniteDimension(value.width, "SVG overlay text width"),
10133
+ ...backgroundColor === void 0 ? {} : { backgroundColor },
10134
+ ...backgroundCornerRadius === void 0 ? {} : { backgroundCornerRadius },
10135
+ ...fontStyle === void 0 ? {} : { fontStyle },
10136
+ ...fontWeight === void 0 ? {} : { fontWeight },
10137
+ ...preserveWhitespace === void 0 ? {} : { preserveWhitespace }
10138
+ });
10139
+ }
10140
+ function createTextTarget(document, group) {
10141
+ let size = {
10142
+ width: 180,
10143
+ height: 48
10144
+ };
10145
+ let layoutProvider;
10146
+ let capturedLayoutProvider;
10147
+ let capturedSize;
10148
+ const applyLayout = (layoutInput) => {
10149
+ const layout = normalizeTextLayout(layoutInput);
10150
+ const children = [];
10151
+ if (layout.backgroundColor !== void 0 && layout.backgroundColor !== "transparent") {
10152
+ const background = document.createElementNS(svgNamespace, "rect");
10153
+ background.setAttribute("x", String(-layout.width / 2));
10154
+ background.setAttribute("y", String(-layout.height / 2));
10155
+ background.setAttribute("width", String(layout.width));
10156
+ background.setAttribute("height", String(layout.height));
10157
+ background.setAttribute("fill", layout.backgroundColor);
10158
+ if (layout.backgroundCornerRadius !== void 0) background.setAttribute("rx", String(layout.backgroundCornerRadius));
10159
+ children.push(background);
10160
+ }
10161
+ const text = document.createElementNS(svgNamespace, "text");
10162
+ const anchor = layout.alignment === "left" ? "start" : layout.alignment === "right" ? "end" : "middle";
10163
+ const x = layout.alignment === "left" ? -layout.width / 2 : layout.alignment === "right" ? layout.width / 2 : 0;
10164
+ text.setAttribute("text-anchor", anchor);
10165
+ text.setAttribute("fill", layout.fill);
10166
+ text.setAttribute("font-family", layout.fontFamily);
10167
+ text.setAttribute("font-size", String(layout.fontSize));
10168
+ if (layout.preserveWhitespace !== false) text.setAttributeNS(xmlNamespace, "xml:space", "preserve");
10169
+ if (layout.fontStyle !== void 0) text.setAttribute("font-style", layout.fontStyle);
10170
+ if (layout.fontWeight !== void 0) text.setAttribute("font-weight", String(layout.fontWeight));
10171
+ const firstBaseline = -Math.max(layout.fontSize, (layout.lines.length - 1) * layout.lineHeight + layout.fontSize) / 2 + layout.fontSize;
10172
+ layout.lines.forEach((line, index) => {
10173
+ const tspan = document.createElementNS(svgNamespace, "tspan");
10174
+ const positionedLine = typeof line === "string" ? void 0 : line;
10175
+ tspan.setAttribute("x", String(positionedLine?.x ?? x));
10176
+ tspan.setAttribute("y", String(positionedLine?.baseline ?? firstBaseline + index * layout.lineHeight));
10177
+ tspan.textContent = typeof line === "string" ? line : line.text;
10178
+ text.appendChild(tspan);
10179
+ });
10180
+ children.push(text);
10181
+ group.replaceChildren(...children);
10182
+ size = {
10183
+ width: layout.width,
10184
+ height: layout.height
10185
+ };
10186
+ };
10187
+ return Object.freeze({
10188
+ [overlayTextTargetMarker]: true,
10189
+ group,
10190
+ captureLayout() {
10191
+ capturedLayoutProvider = layoutProvider;
10192
+ capturedSize = { ...size };
10193
+ },
10194
+ clear() {
10195
+ group.replaceChildren();
10196
+ size = {
10197
+ width: 180,
10198
+ height: 48
10199
+ };
10200
+ layoutProvider = void 0;
10201
+ capturedLayoutProvider = void 0;
10202
+ capturedSize = void 0;
10203
+ },
10204
+ clearCapturedLayout() {
10205
+ capturedLayoutProvider = void 0;
10206
+ capturedSize = void 0;
10207
+ },
10208
+ getCapturedSize() {
10209
+ return capturedSize;
10210
+ },
10211
+ getSize() {
10212
+ return size;
10213
+ },
10214
+ refresh() {
10215
+ if (capturedLayoutProvider !== void 0) {
10216
+ const capturedLayout = normalizeTextLayout(capturedLayoutProvider());
10217
+ capturedSize = {
10218
+ width: capturedLayout.width,
10219
+ height: capturedLayout.height
10220
+ };
10221
+ }
10222
+ if (layoutProvider !== void 0) applyLayout(layoutProvider());
10223
+ },
10224
+ render(layout, nextLayoutProvider) {
10225
+ layoutProvider = nextLayoutProvider;
10226
+ applyLayout(layout);
10227
+ }
10228
+ });
10229
+ }
10230
+ function requireTextTarget(value) {
10231
+ const candidate = value;
10232
+ if (candidate?.[overlayTextTargetMarker] !== true) throw new TypeError("SVG overlay text target is invalid.");
10233
+ return candidate;
10234
+ }
10235
+ function createSvgOverlayTextAdapter(capabilityInput, renderer) {
10236
+ if (!isRecord$1(capabilityInput) || typeof capabilityInput.layoutText !== "function") throw new TypeError("SVG overlay backend requires a text layout capability.");
10237
+ const capability = capabilityInput;
10238
+ return Object.freeze({
10239
+ setText({ styleName, target, text }) {
10240
+ const overlayTarget = requireTextTarget(target);
10241
+ const layoutProvider = () => capability.layoutText({
10242
+ nativeSize: readNativeSize(renderer),
10243
+ styleName,
10244
+ text
10245
+ });
10246
+ overlayTarget.render(layoutProvider(), layoutProvider);
10247
+ },
10248
+ releaseTarget(target) {
10249
+ requireTextTarget(target).clear();
10250
+ },
10251
+ measureText({ styleName, text }) {
10252
+ const nativeSize = readNativeSize(renderer);
10253
+ return requireFiniteDimension(capability.measureText?.({
10254
+ nativeSize,
10255
+ styleName,
10256
+ text
10257
+ }) ?? capability.layoutText({
10258
+ nativeSize,
10259
+ styleName,
10260
+ text
10261
+ }).width, "SVG overlay measured text width");
10262
+ }
10263
+ });
10264
+ }
10265
+ function isSafeImageSource(resource) {
10266
+ if (!(/* @__PURE__ */ new Set([
10267
+ "image/avif",
10268
+ "image/gif",
10269
+ "image/jpeg",
10270
+ "image/png",
10271
+ "image/svg+xml",
10272
+ "image/webp"
10273
+ ])).has(resource.mimeType.toLowerCase())) return false;
10274
+ if (resource.mimeType.toLowerCase() === "image/svg+xml" && resource.svgSecurity !== "sanitized") return false;
10275
+ if (resource.src.startsWith("blob:")) return typeof resource.release === "function";
10276
+ return /^data:image\/(?:avif|gif|jpeg|png|webp);base64,/iu.test(resource.src);
10277
+ }
10278
+ async function releaseImageResource(resource) {
10279
+ await resource?.release?.();
10280
+ }
10281
+ function createImageTarget(document, id, group) {
10282
+ const image = document.createElementNS(svgNamespace, "image");
10283
+ image.setAttribute("preserveAspectRatio", "xMidYMid meet");
10284
+ group.appendChild(image);
10285
+ let resource;
10286
+ let displaySize = {
10287
+ width: 1,
10288
+ height: 1
10289
+ };
10290
+ let resourceGeneration = 0;
10291
+ const applyDisplaySize = () => {
10292
+ image.setAttribute("x", String(-displaySize.width / 2));
10293
+ image.setAttribute("y", String(-displaySize.height / 2));
10294
+ image.setAttribute("width", String(displaySize.width));
10295
+ image.setAttribute("height", String(displaySize.height));
10296
+ };
10297
+ applyDisplaySize();
10298
+ return Object.freeze({
10299
+ id,
10300
+ isStage: false,
10301
+ [overlayImageTargetMarker]: true,
10302
+ group,
10303
+ async applyResource(nextResource) {
10304
+ const generation = resourceGeneration + 1;
10305
+ resourceGeneration = generation;
10306
+ try {
10307
+ requireFiniteDimension(nextResource.width, "SVG overlay image width");
10308
+ requireFiniteDimension(nextResource.height, "SVG overlay image height");
10309
+ 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.");
10310
+ } catch (error) {
10311
+ await releaseImageResource(nextResource);
10312
+ throw error;
10313
+ }
10314
+ if (generation !== resourceGeneration) {
10315
+ await releaseImageResource(nextResource);
10316
+ return;
10317
+ }
10318
+ const previous = resource;
10319
+ resource = nextResource;
10320
+ image.setAttribute("href", nextResource.src);
10321
+ await releaseImageResource(previous);
10322
+ },
10323
+ getSize() {
10324
+ return resource ? {
10325
+ width: resource.width,
10326
+ height: resource.height
10327
+ } : {
10328
+ width: 1,
10329
+ height: 1
10330
+ };
10331
+ },
10332
+ async release() {
10333
+ resourceGeneration += 1;
10334
+ const previous = resource;
10335
+ resource = void 0;
10336
+ image.removeAttribute("href");
10337
+ await releaseImageResource(previous);
10338
+ },
10339
+ setDisplaySize(nextSize) {
10340
+ displaySize = nextSize;
10341
+ applyDisplaySize();
10342
+ },
10343
+ setVisible(visible) {
10344
+ group.setAttribute("visibility", visible ? "visible" : "hidden");
10345
+ }
10346
+ });
10347
+ }
10348
+ function requireImageTarget(value) {
10349
+ const candidate = value;
10350
+ if (candidate?.[overlayImageTargetMarker] !== true) throw new TypeError("SVG overlay image target is invalid.");
10351
+ return candidate;
10352
+ }
10353
+ function createSvgOverlayImageAdapter(capabilityInput) {
10354
+ 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.");
10355
+ const capability = capabilityInput;
10356
+ return Object.freeze({
10357
+ isRegistered(name) {
10358
+ return capability.isRegistered(name);
10359
+ },
10360
+ getMimeType(name) {
10361
+ return capability.getMimeType(name);
10362
+ },
10363
+ async applyToTarget(name, target) {
10364
+ await requireImageTarget(target).applyResource(await capability.resolveImage(name));
10365
+ }
10366
+ });
10367
+ }
10368
+ function createSvgOverlaySurfaceManager(renderer, documentInput) {
10369
+ const root = documentInput.createElementNS(svgNamespace, "svg");
10370
+ root.setAttribute("xmlns", svgNamespace);
10371
+ root.setAttribute("aria-hidden", "true");
10372
+ root.setAttribute("focusable", "false");
10373
+ root.setAttribute("data-bubble-render-backend", "svg-overlay");
10374
+ root.style.display = "block";
10375
+ root.style.overflow = "hidden";
10376
+ root.style.pointerEvents = "none";
10377
+ const groups = /* @__PURE__ */ new Set();
10378
+ let attached = false;
10379
+ const updateNativeSize = () => {
10380
+ const size = readNativeSize(renderer);
10381
+ root.setAttribute("width", String(size.width));
10382
+ root.setAttribute("height", String(size.height));
10383
+ root.setAttribute("viewBox", `0 0 ${size.width} ${size.height}`);
10384
+ return size;
10385
+ };
10386
+ return Object.freeze({
10387
+ document: documentInput,
10388
+ renderer,
10389
+ acquire(group) {
10390
+ if (groups.has(group)) return;
10391
+ updateNativeSize();
10392
+ if (!attached) try {
10393
+ renderer.addOverlay(root, "scale");
10394
+ attached = true;
10395
+ } catch (error) {
10396
+ renderer.removeOverlay(root);
10397
+ throw error;
10398
+ }
10399
+ root.appendChild(group);
10400
+ groups.add(group);
10401
+ },
10402
+ release(group) {
10403
+ if (!groups.delete(group)) return;
10404
+ group.remove();
10405
+ if (groups.size === 0 && attached) {
10406
+ renderer.removeOverlay(root);
10407
+ attached = false;
10408
+ }
10409
+ },
10410
+ updateNativeSize
10411
+ });
10412
+ }
10413
+ function targetBounds$1(target) {
10414
+ try {
10415
+ const bounds = target.getBoundsForBubble?.();
10416
+ if (bounds && [
10417
+ bounds.bottom,
10418
+ bounds.left,
10419
+ bounds.right,
10420
+ bounds.top
10421
+ ].every((value) => Number.isFinite(value))) return bounds;
10422
+ } catch {}
10423
+ const x = Number.isFinite(target.x) ? Number(target.x) : 0;
10424
+ const y = Number.isFinite(target.y) ? Number(target.y) : 0;
10425
+ return {
10426
+ bottom: y,
10427
+ left: x,
10428
+ right: x,
10429
+ top: y
10430
+ };
10431
+ }
10432
+ function clamp$1(value, minimum, maximum) {
10433
+ if (maximum < minimum) return (minimum + maximum) / 2;
10434
+ return Math.min(maximum, Math.max(minimum, value));
10435
+ }
10436
+ function tailDirectionForPlacement$1(direction) {
10437
+ const vector = bubbleDirectionVector(direction);
10438
+ return (Math.atan2(-vector.x, -vector.y) * 180 / Math.PI % 360 + 360) % 360;
10439
+ }
10440
+ var allowedBodyElements = /* @__PURE__ */ new Set([
10441
+ "circle",
10442
+ "g",
10443
+ "path",
10444
+ "rect",
10445
+ "title"
10446
+ ]);
10447
+ var allowedBodyAttributes = /* @__PURE__ */ new Set([
10448
+ "cx",
10449
+ "cy",
10450
+ "d",
10451
+ "data-boolean-operation",
10452
+ "data-tail-base-on-border",
10453
+ "fill",
10454
+ "fill-rule",
10455
+ "height",
10456
+ "opacity",
10457
+ "r",
10458
+ "rx",
10459
+ "stroke",
10460
+ "stroke-dasharray",
10461
+ "stroke-linejoin",
10462
+ "stroke-width",
10463
+ "transform",
10464
+ "width",
10465
+ "x",
10466
+ "y"
10467
+ ]);
10468
+ function copyAllowedBodyNode(source, document) {
10469
+ const name = source.localName;
10470
+ if (!allowedBodyElements.has(name)) throw new TypeError(`Bubble body SVG element is not allowed: ${name}`);
10471
+ const result = document.createElementNS(svgNamespace, name);
10472
+ for (const attribute of source.getAttributeNames()) {
10473
+ if (!allowedBodyAttributes.has(attribute)) throw new TypeError(`Bubble body SVG attribute is not allowed: ${attribute}`);
10474
+ const value = source.getAttribute(attribute) ?? "";
10475
+ if (/javascript:|url\s*\(/iu.test(value)) throw new TypeError("Bubble body SVG contains an unsafe attribute value.");
10476
+ result.setAttribute(attribute, value);
10477
+ }
10478
+ if (name === "title") result.textContent = source.textContent ?? "";
10479
+ for (const child of Array.from(source.children)) result.appendChild(copyAllowedBodyNode(child, document));
10480
+ return result;
10481
+ }
10482
+ function replaceBodyFromCanonicalSvg(group, svg, document) {
10483
+ const Parser = document.defaultView?.DOMParser;
10484
+ if (!Parser) throw new TypeError("SVG overlay backend requires DOMParser.");
10485
+ const parsed = new Parser().parseFromString(svg, "image/svg+xml");
10486
+ if (parsed.querySelector("parsererror")) throw new TypeError("Canonical Bubble body SVG could not be parsed.");
10487
+ const children = Array.from(parsed.documentElement.children).map((child) => copyAllowedBodyNode(child, document));
10488
+ group.replaceChildren(...children);
10489
+ }
10490
+ function fitImage(target, boxSize, scaleMultiplier = 1) {
10491
+ const native = target.getSize();
10492
+ const scale = Math.min(boxSize / native.width, boxSize / native.height);
10493
+ const size = {
10494
+ width: native.width * scale * scaleMultiplier,
10495
+ height: native.height * scale * scaleMultiplier
10496
+ };
10497
+ target.setDisplaySize(size);
10498
+ return size;
10499
+ }
10500
+ function createSvgOverlaySurface(manager, actor, actorKey, style, scheduler) {
10501
+ const { document, renderer } = manager;
10502
+ const sequence = overlaySurfaceSequence;
10503
+ overlaySurfaceSequence += 1;
10504
+ const surfaceGroup = document.createElementNS(svgNamespace, "g");
10505
+ surfaceGroup.setAttribute("data-bubble-surface", `${actorKey}:${sequence}`);
10506
+ const bodyGroup = document.createElementNS(svgNamespace, "g");
10507
+ bodyGroup.setAttribute("data-bubble-layer", "body");
10508
+ surfaceGroup.appendChild(bodyGroup);
10509
+ const createLayerGroup = (layer) => {
10510
+ const group = document.createElementNS(svgNamespace, "g");
10511
+ group.setAttribute("data-bubble-layer", layer);
10512
+ group.setAttribute("visibility", "hidden");
10513
+ surfaceGroup.appendChild(group);
10514
+ return group;
10515
+ };
10516
+ const portraitBase = createImageTarget(document, `bubble:${actorKey}:${sequence}:portrait-base`, createLayerGroup("portrait-base"));
10517
+ const portraitBlink = createImageTarget(document, `bubble:${actorKey}:${sequence}:portrait-blink`, createLayerGroup("portrait-blink"));
10518
+ const portraitLipSync = createImageTarget(document, `bubble:${actorKey}:${sequence}:portrait-lip-sync`, createLayerGroup("portrait-lip-sync"));
10519
+ const textGroup = createLayerGroup("text");
10520
+ const text = createTextTarget(document, textGroup);
10521
+ const continueIndicator = createImageTarget(document, `bubble:${actorKey}:${sequence}:continue-indicator`, createLayerGroup("continue-indicator"));
10522
+ const targets = Object.freeze({
10523
+ text,
10524
+ portraitBase,
10525
+ portraitBlink,
10526
+ portraitLipSync,
10527
+ continueIndicator
10528
+ });
10529
+ const layerTargets = /* @__PURE__ */ new Map([
10530
+ ["portraitBase", portraitBase],
10531
+ ["portraitBlink", portraitBlink],
10532
+ ["portraitLipSync", portraitLipSync],
10533
+ ["continueIndicator", continueIndicator]
10534
+ ]);
10535
+ const layerVisibility = /* @__PURE__ */ new Map();
10536
+ const clipId = `bubble-portrait-clip-${sequence}`;
10537
+ const definitions = document.createElementNS(svgNamespace, "defs");
10538
+ const clipPath = document.createElementNS(svgNamespace, "clipPath");
10539
+ const clipRect = document.createElementNS(svgNamespace, "rect");
10540
+ clipPath.setAttribute("id", clipId);
10541
+ clipPath.appendChild(clipRect);
10542
+ definitions.appendChild(clipPath);
10543
+ surfaceGroup.insertBefore(definitions, bodyGroup);
10544
+ let currentStyle = style;
10545
+ let disposed = false;
10546
+ let surfaceVisible = false;
10547
+ let bodySignature = "";
10548
+ let motionTranslation = [0, 0];
10549
+ let motionScaleMultiplier = 1;
10550
+ let motionOpacity = 1;
10551
+ let center = [0, 0];
10552
+ let shapeTransition;
10553
+ const applyMotionTransform = (native = manager.updateNativeSize()) => {
10554
+ const centerX = native.width / 2 + center[0];
10555
+ const centerY = native.height / 2 - center[1];
10556
+ const translatedX = centerX + motionTranslation[0];
10557
+ const translatedY = centerY - motionTranslation[1];
10558
+ surfaceGroup.setAttribute("transform", `translate(${translatedX} ${translatedY}) scale(${motionScaleMultiplier}) translate(${-centerX} ${-centerY})`);
10559
+ surfaceGroup.setAttribute("opacity", String(motionOpacity));
10560
+ };
10561
+ const layerAllowedByStyle = (layer) => {
10562
+ if (layer === "continueIndicator") return currentStyle.continueIndicator !== void 0;
10563
+ if (layer === "portraitBase") return currentStyle.portrait !== void 0;
10564
+ if (layer === "portraitBlink") return currentStyle.portrait?.blink !== void 0;
10565
+ return currentStyle.portrait?.lipSync !== void 0;
10566
+ };
10567
+ const updateVisibility = (nativeSize) => {
10568
+ const actorVisible = currentStyle.placement.basis === "background" || actor.visible !== false;
10569
+ const visible = surfaceVisible && actorVisible && motionOpacity > 0;
10570
+ surfaceGroup.setAttribute("visibility", visible ? "visible" : "hidden");
10571
+ bodyGroup.setAttribute("visibility", visible && currentStyle.visualStyle !== "NO_BUBBLE" ? "visible" : "hidden");
10572
+ textGroup.setAttribute("visibility", visible ? "visible" : "hidden");
10573
+ for (const [layer, target] of layerTargets) target.setVisible(visible && layerAllowedByStyle(layer) && (layerVisibility.get(layer) ?? false));
10574
+ applyMotionTransform(nativeSize);
10575
+ };
10576
+ const position = () => {
10577
+ if (disposed) return;
10578
+ const native = manager.updateNativeSize();
10579
+ const scaleMultiplier = currentStyle.placement.basis === "actor" ? currentStyle.offset.scalePercent / 100 : 1;
10580
+ const nativeTextSize = text.getCapturedSize() ?? text.getSize();
10581
+ const textSize = {
10582
+ width: nativeTextSize.width * scaleMultiplier,
10583
+ height: nativeTextSize.height * scaleMultiplier
10584
+ };
10585
+ const portraitZoomMultiplier = (currentStyle.portrait?.offset.zoomPercent ?? 100) / 100;
10586
+ const hasPortrait = currentStyle.portrait !== void 0;
10587
+ const portraitSize = hasPortrait ? fitImage(portraitBase, portraitBoxSize$1 * portraitZoomMultiplier, scaleMultiplier) : {
10588
+ width: 0,
10589
+ height: 0
10590
+ };
10591
+ for (const target of [portraitBlink, portraitLipSync]) if (hasPortrait) fitImage(target, portraitBoxSize$1 * portraitZoomMultiplier, scaleMultiplier);
10592
+ const indicatorSize = fitImage(continueIndicator, indicatorBoxSize$1, scaleMultiplier);
10593
+ const totalWidth = portraitSize.width + (hasPortrait ? contentGap$1 * scaleMultiplier : 0) + textSize.width;
10594
+ const contentHeight = Math.max(portraitSize.height, textSize.height);
10595
+ const baseBubbleWidth = totalWidth / scaleMultiplier + 48;
10596
+ const baseBubbleHeight = contentHeight / scaleMultiplier + 48;
10597
+ const stageLeft = -native.width / 2;
10598
+ const stageRight = native.width / 2;
10599
+ const stageTop = native.height / 2;
10600
+ const stageBottom = -native.height / 2;
10601
+ let centerX;
10602
+ let centerY;
10603
+ if (currentStyle.placement.basis === "background") {
10604
+ centerX = 0;
10605
+ if (currentStyle.placement.region === "HEADER_LIKE") centerY = stageTop - stageSafeMargin$1 - contentHeight / 2;
10606
+ else if (currentStyle.placement.region === "FOOTER_LIKE") centerY = stageBottom + stageSafeMargin$1 + contentHeight / 2;
10607
+ else centerY = 0;
10608
+ } else {
10609
+ const nextCenter = actorRelativeBubbleCenter({
10610
+ bounds: targetBounds$1(actor),
10611
+ bubbleWidth: totalWidth,
10612
+ bubbleHeight: contentHeight,
10613
+ direction: currentStyle.placement.direction,
10614
+ distance: currentStyle.distance,
10615
+ tailLength: currentStyle.tailLength,
10616
+ offset: currentStyle.offset
10617
+ });
10618
+ centerX = nextCenter.x;
10619
+ centerY = nextCenter.y;
10620
+ }
10621
+ centerX = clamp$1(centerX, stageLeft + totalWidth / 2, stageRight - totalWidth / 2);
10622
+ centerY = clamp$1(centerY, stageBottom + contentHeight / 2, stageTop - contentHeight / 2);
10623
+ center = [centerX, centerY];
10624
+ const tailDirection = currentStyle.placement.basis === "actor" ? tailDirectionForPlacement$1(currentStyle.placement.direction) : null;
10625
+ const bodyOffset = currentStyle.placement.basis === "actor" ? [
10626
+ currentStyle.offset.x,
10627
+ currentStyle.offset.y,
10628
+ currentStyle.offset.scalePercent
10629
+ ] : [
10630
+ 0,
10631
+ 0,
10632
+ 100
10633
+ ];
10634
+ const bodyCenterOffset = tailDirection === null ? {
10635
+ x: 0,
10636
+ y: 0
10637
+ } : bubbleBodyCenterOffset({
10638
+ style: currentStyle.visualStyle,
10639
+ width: baseBubbleWidth,
10640
+ height: baseBubbleHeight,
10641
+ tailDirection,
10642
+ tailLength: currentStyle.tailLength,
10643
+ offset: bodyOffset
10644
+ });
10645
+ const nextBodySignature = JSON.stringify({
10646
+ baseBubbleHeight,
10647
+ baseBubbleWidth,
10648
+ bodyOffset,
10649
+ shapeTransition,
10650
+ tailDirection,
10651
+ tailLength: currentStyle.tailLength,
10652
+ visualStyle: currentStyle.visualStyle
10653
+ });
10654
+ if (nextBodySignature !== bodySignature) {
10655
+ replaceBodyFromCanonicalSvg(bodyGroup, renderBubbleSvg({
10656
+ style: currentStyle.visualStyle,
10657
+ lines: [],
10658
+ width: baseBubbleWidth,
10659
+ height: baseBubbleHeight,
10660
+ tailDirection,
10661
+ tailLength: currentStyle.tailLength,
10662
+ offset: bodyOffset,
10663
+ title: `${currentStyle.name} Bubble body`,
10664
+ ...shapeTransition === void 0 ? {} : { shapeTransition }
10665
+ }), document);
10666
+ bodySignature = nextBodySignature;
10667
+ }
10668
+ bodyGroup.setAttribute("data-bubble-style", currentStyle.visualStyle);
10669
+ if (shapeTransition === void 0) {
10670
+ bodyGroup.removeAttribute("data-bubble-shape-transition-from");
10671
+ bodyGroup.removeAttribute("data-bubble-shape-transition-to");
10672
+ bodyGroup.removeAttribute("data-bubble-shape-transition-progress");
10673
+ } else {
10674
+ bodyGroup.setAttribute("data-bubble-shape-transition-from", shapeTransition.from);
10675
+ bodyGroup.setAttribute("data-bubble-shape-transition-to", shapeTransition.to);
10676
+ bodyGroup.setAttribute("data-bubble-shape-transition-progress", String(shapeTransition.progress));
10677
+ }
10678
+ const bodyDrawableX = centerX - bodyCenterOffset.x;
10679
+ const bodyDrawableY = centerY + bodyCenterOffset.y;
10680
+ bodyGroup.setAttribute("transform", `translate(${native.width / 2 + bodyDrawableX - baseBubbleWidth / 2} ${native.height / 2 - bodyDrawableY - baseBubbleHeight / 2})`);
10681
+ const left = centerX - totalWidth / 2;
10682
+ const portraitPlacement = currentStyle.portrait?.placement ?? "left";
10683
+ const portraitOnRight = portraitPlacement.endsWith("right");
10684
+ const portraitOffsetX = (currentStyle.portrait?.offset.x ?? 0) * scaleMultiplier;
10685
+ const portraitOffsetY = (currentStyle.portrait?.offset.y ?? 0) * scaleMultiplier;
10686
+ const portraitX = (portraitOnRight ? left + textSize.width + contentGap$1 * scaleMultiplier : left) + portraitSize.width / 2 + portraitOffsetX;
10687
+ let portraitY = centerY;
10688
+ if (portraitPlacement.startsWith("top-")) portraitY = centerY + contentHeight / 2 - portraitSize.height / 2;
10689
+ else if (portraitPlacement.startsWith("bottom-")) portraitY = centerY - contentHeight / 2 + portraitSize.height / 2;
10690
+ portraitY += portraitOffsetY;
10691
+ const textX = (portraitOnRight || !hasPortrait ? left : left + portraitSize.width + contentGap$1 * scaleMultiplier) + textSize.width / 2;
10692
+ const toDomTransform = (x, y) => `translate(${native.width / 2 + x} ${native.height / 2 - y})`;
10693
+ for (const target of [
10694
+ portraitBase,
10695
+ portraitBlink,
10696
+ portraitLipSync
10697
+ ]) target.group.setAttribute("transform", toDomTransform(portraitX, portraitY));
10698
+ textGroup.setAttribute("transform", `${toDomTransform(textX, centerY)} scale(${scaleMultiplier})`);
10699
+ const indicatorX = textX + textSize.width / 2 - indicatorSize.width / 2 - contentGap$1 * scaleMultiplier;
10700
+ const indicatorY = centerY - textSize.height / 2 + indicatorSize.height / 2 + contentGap$1 * scaleMultiplier;
10701
+ continueIndicator.group.setAttribute("transform", toDomTransform(indicatorX, indicatorY));
10702
+ const radius = Math.min(currentStyle.portrait?.cornerRadius ?? 0, portraitSize.width / 2, portraitSize.height / 2);
10703
+ clipRect.setAttribute("x", String(-portraitSize.width / 2));
10704
+ clipRect.setAttribute("y", String(-portraitSize.height / 2));
10705
+ clipRect.setAttribute("width", String(portraitSize.width));
10706
+ clipRect.setAttribute("height", String(portraitSize.height));
10707
+ clipRect.setAttribute("rx", String(radius));
10708
+ for (const target of [
10709
+ portraitBase,
10710
+ portraitBlink,
10711
+ portraitLipSync
10712
+ ]) if (radius > 0) target.group.setAttribute("clip-path", `url(#${clipId})`);
10713
+ else target.group.removeAttribute("clip-path");
10714
+ updateVisibility(native);
10715
+ };
10716
+ const originalVisualChange = actor.onTargetVisualChange;
10717
+ const visualChangeHook = (changedTarget) => {
10718
+ originalVisualChange?.(changedTarget);
10719
+ position();
10720
+ };
10721
+ const nativeSizeHook = () => {
10722
+ text.refresh();
10723
+ position();
10724
+ };
10725
+ manager.acquire(surfaceGroup);
10726
+ if (currentStyle.placement.basis === "actor") actor.onTargetVisualChange = visualChangeHook;
10727
+ renderer.on?.("NativeSizeChanged", nativeSizeHook);
10728
+ return Object.freeze({
10729
+ targets,
10730
+ setLayerVisible(layer, visible) {
10731
+ if (disposed) return;
10732
+ layerVisibility.set(layer, visible);
10733
+ updateVisibility();
10734
+ },
10735
+ updateStyle(nextStyle) {
10736
+ if (disposed) return;
10737
+ const wasActorRelative = currentStyle.placement.basis === "actor";
10738
+ currentStyle = nextStyle;
10739
+ motionTranslation = [0, 0];
10740
+ motionScaleMultiplier = 1;
10741
+ motionOpacity = 1;
10742
+ shapeTransition = void 0;
10743
+ bodySignature = "";
10744
+ if (nextStyle.reveal?.layout !== "RESERVED") text.clearCapturedLayout();
10745
+ const isActorRelative = currentStyle.placement.basis === "actor";
10746
+ if (wasActorRelative && !isActorRelative) {
10747
+ if (actor.onTargetVisualChange === visualChangeHook) actor.onTargetVisualChange = originalVisualChange ?? null;
10748
+ } else if (!wasActorRelative && isActorRelative) actor.onTargetVisualChange = visualChangeHook;
10749
+ position();
10750
+ },
10751
+ captureTextLayout() {
10752
+ if (disposed) return;
10753
+ text.captureLayout();
10754
+ position();
10755
+ },
10756
+ clearTextLayout() {
10757
+ text.clearCapturedLayout();
10758
+ position();
10759
+ },
10760
+ async animate(motion) {
10761
+ if (disposed) return;
10762
+ const durationSeconds = Math.max(0, motion.durationSeconds ?? 0);
10763
+ const setFrame = () => {
10764
+ if (disposed) return;
10765
+ updateVisibility();
10766
+ };
10767
+ const eased = (progress) => easeMotionProgress(progress, motion.ease ?? "easeInOut");
10768
+ if (motion.name === "fadeIn" || motion.name === "floatIn" || motion.name === "zoomIn" || motion.name === "riseUp") {
10769
+ surfaceVisible = true;
10770
+ const startingTranslation = motion.name === "floatIn" || motion.name === "riseUp" ? [0, 16] : [0, 0];
10771
+ const startingScale = motion.name === "zoomIn" ? .01 : 1;
10772
+ motionTranslation = startingTranslation;
10773
+ motionScaleMultiplier = startingScale;
10774
+ motionOpacity = motion.name === "fadeIn" ? 0 : 1;
10775
+ setFrame();
10776
+ await runMotionTimeline(scheduler, durationSeconds, (progress) => {
10777
+ const easedProgress = eased(progress);
10778
+ motionTranslation = [startingTranslation[0] * (1 - easedProgress), startingTranslation[1] * (1 - easedProgress)];
10779
+ motionScaleMultiplier = startingScale + (1 - startingScale) * easedProgress;
10780
+ motionOpacity = motion.name === "fadeIn" ? easedProgress : 1;
10781
+ setFrame();
10782
+ });
10783
+ motionTranslation = [0, 0];
10784
+ motionScaleMultiplier = 1;
10785
+ motionOpacity = 1;
10786
+ position();
10787
+ return;
10788
+ }
10789
+ if (motion.name === "fadeOut" || motion.name === "floatOut" || motion.name === "zoomOut" || motion.name === "sink") {
10790
+ const endingTranslation = motion.name === "floatOut" || motion.name === "sink" ? [0, -16] : [0, 0];
10791
+ const endingScale = motion.name === "zoomOut" ? .01 : 1;
10792
+ await runMotionTimeline(scheduler, durationSeconds, (progress) => {
10793
+ const easedProgress = eased(progress);
10794
+ motionTranslation = [endingTranslation[0] * easedProgress, endingTranslation[1] * easedProgress];
10795
+ motionScaleMultiplier = 1 + (endingScale - 1) * easedProgress;
10796
+ motionOpacity = motion.name === "fadeOut" ? 1 - easedProgress : 1;
10797
+ setFrame();
10798
+ });
10799
+ surfaceVisible = false;
10800
+ updateVisibility();
10801
+ motionTranslation = [0, 0];
10802
+ motionScaleMultiplier = 1;
10803
+ motionOpacity = 1;
10804
+ return;
10805
+ }
10806
+ if (motion.name === "shake") {
10807
+ const count = Math.max(1, Math.floor(motion.count ?? 1));
10808
+ const animationDuration = durationSeconds > 0 ? durationSeconds : count * .08;
10809
+ const vector = bubbleDirectionVector(typeof motion.direction === "number" ? motion.direction : motion.direction ?? "right");
10810
+ await runMotionTimeline(scheduler, animationDuration, (progress) => {
10811
+ const displacement = Math.sin(eased(progress) * count * Math.PI * 2) * 5;
10812
+ motionTranslation = [vector.x * displacement, vector.y * displacement];
10813
+ setFrame();
10814
+ });
10815
+ motionTranslation = [0, 0];
10816
+ position();
10817
+ return;
10818
+ }
10819
+ if (motion.name === "explode") {
10820
+ const count = Math.max(1, Math.floor(motion.count ?? 1));
10821
+ const animationDuration = durationSeconds > 0 ? durationSeconds : count * .12;
10822
+ const factor = motion.relativeScale ?? 1.15;
10823
+ await runMotionTimeline(scheduler, animationDuration, (progress) => {
10824
+ const wave = Math.abs(Math.sin(eased(progress) * count * Math.PI));
10825
+ motionScaleMultiplier = 1 + (factor - 1) * wave;
10826
+ setFrame();
10827
+ });
10828
+ motionScaleMultiplier = 1;
10829
+ position();
10830
+ return;
10831
+ }
10832
+ if (motion.name === "animateBubbleShape") {
10833
+ const targetStyle = motion.visualStyle ?? currentStyle.visualStyle;
10834
+ const fromStyle = currentStyle.visualStyle;
10835
+ const speed = motion.speed === void 0 ? 1 : Math.max(0, motion.speed);
10836
+ shapeTransition = {
10837
+ from: fromStyle,
10838
+ to: targetStyle,
10839
+ progress: 0
10840
+ };
10841
+ position();
10842
+ await runMotionTimeline(scheduler, durationSeconds, (progress) => {
10843
+ const speedProgress = durationSeconds === 0 ? 1 : clampMotionProgress(progress * Math.max(speed, 1));
10844
+ shapeTransition = {
10845
+ from: fromStyle,
10846
+ to: targetStyle,
10847
+ progress: easeMotionProgress(speedProgress, motion.ease ?? "easeInOut")
10848
+ };
10849
+ bodySignature = "";
10850
+ position();
10851
+ });
10852
+ shapeTransition = void 0;
10853
+ bodySignature = "";
10854
+ position();
10855
+ }
10856
+ },
10857
+ show() {
10858
+ if (disposed) return;
10859
+ surfaceVisible = true;
10860
+ position();
10861
+ },
10862
+ hide() {
10863
+ if (disposed) return;
10864
+ surfaceVisible = false;
10865
+ updateVisibility();
10866
+ },
10867
+ async dispose() {
10868
+ if (disposed) return;
10869
+ disposed = true;
10870
+ const cleanupErrors = [];
10871
+ const runCleanup = (operation) => {
10872
+ try {
10873
+ operation();
10874
+ } catch (error) {
10875
+ cleanupErrors.push(error);
10876
+ }
10877
+ };
10878
+ runCleanup(() => {
10879
+ if (actor.onTargetVisualChange === visualChangeHook) actor.onTargetVisualChange = originalVisualChange ?? null;
10880
+ });
10881
+ runCleanup(() => renderer.off?.("NativeSizeChanged", nativeSizeHook));
10882
+ runCleanup(() => manager.release(surfaceGroup));
10883
+ runCleanup(() => text.clear());
10884
+ const releaseResults = await Promise.allSettled([...layerTargets.values()].map((target) => target.release()));
10885
+ cleanupErrors.push(...releaseResults.flatMap((result) => result.status === "rejected" ? [result.reason] : []));
10886
+ if (cleanupErrors.length === 1) throw cleanupErrors[0];
10887
+ if (cleanupErrors.length > 1) throw new AggregateError(cleanupErrors, "Failed to dispose SVG overlay Bubble surface.");
10888
+ }
10889
+ });
10890
+ }
10891
+ //#endregion
10892
+ //#region src/turbowarp-adapter.ts
10893
+ var spriteLayer = "sprite";
10894
+ var portraitBoxSize = 96;
10895
+ var indicatorBoxSize = 18;
10896
+ var contentGap = 8;
10897
+ var stageSafeMargin = 16;
10898
+ var surfaceSequence = 0;
10899
+ var BubbleRuntimeAdapterError = class extends Error {
10900
+ constructor(code, message) {
10901
+ super(message);
10902
+ _defineProperty(this, "code", void 0);
10903
+ this.name = "BubbleRuntimeAdapterError";
10904
+ this.code = code;
10905
+ }
10906
+ };
10907
+ function isRecord(value) {
10908
+ return typeof value === "object" && value !== null && !Array.isArray(value);
10909
+ }
10910
+ function requireRenderer(value) {
10911
+ if (!isRecord(value)) throw new BubbleRuntimeAdapterError("BUBBLE-RUNTIME-001", "Bubble requires the TurboWarp renderer.");
10912
+ const methods = [
10913
+ "createSVGSkin",
10914
+ "createDrawable",
10915
+ "destroyDrawable",
10916
+ "destroySkin",
10917
+ "getCurrentSkinSize",
10918
+ "getNativeSize",
10919
+ "updateDrawablePosition",
10920
+ "updateDrawableScale",
10921
+ "updateDrawableSkinId",
10922
+ "updateDrawableVisible"
10923
+ ];
10924
+ if (methods.some((method) => typeof value[method] !== "function")) throw new BubbleRuntimeAdapterError("BUBBLE-RUNTIME-001", `Bubble renderer must provide ${methods.join(", ")}.`);
10925
+ return value;
10926
+ }
10927
+ function normalizeRenderBackend(value) {
10928
+ const backend = value ?? "svg-overlay";
10929
+ if (backend !== "scratch-render" && backend !== "svg-overlay") throw new BubbleRuntimeAdapterError("BUBBLE-RUNTIME-004", "Bubble bubbleRenderBackend must be scratch-render or svg-overlay.");
10930
+ return backend;
10931
+ }
10932
+ function normalizeOverlayUnsupportedBehavior(value) {
10933
+ const behavior = value ?? "error";
10934
+ if (behavior !== "error" && behavior !== "fallback") throw new BubbleRuntimeAdapterError("BUBBLE-RUNTIME-004", "Bubble svgOverlayUnsupportedBehavior must be error or fallback.");
10935
+ return behavior;
10936
+ }
10937
+ function resolveOverlayDocument(value) {
10938
+ const documentValue = value ?? (typeof globalThis.document === "undefined" ? void 0 : globalThis.document);
10939
+ if (documentValue === void 0) return void 0;
10940
+ if (!isRecord(documentValue) || typeof documentValue.createElementNS !== "function") throw new BubbleRuntimeAdapterError("BUBBLE-RUNTIME-004", "Bubble SVG overlay document must provide createElementNS().");
10941
+ return documentValue;
10942
+ }
10943
+ function overlayUnavailableReason(renderer, documentValue, textCapability) {
10944
+ if (typeof renderer.addOverlay !== "function" || typeof renderer.removeOverlay !== "function") return "the renderer does not provide addOverlay() and removeOverlay()";
10945
+ if (documentValue === void 0) return "the host does not provide a DOM document";
10946
+ if (typeof documentValue.defaultView?.DOMParser !== "function") return "the host document does not provide DOMParser";
10947
+ if (!isRecord(textCapability) || typeof textCapability.layoutText !== "function") return "a host-neutral svgOverlayTextCapability is not available";
10948
+ }
10949
+ function createDefaultSvgOverlayTextCapability() {
10950
+ const composition = createSvgTextLayoutComposition();
10951
+ const definedStyles = /* @__PURE__ */ new Set();
10952
+ const defineStyle = (name) => {
10953
+ composition.defineStyle({
10954
+ name,
10955
+ backgroundColor: "transparent"
10956
+ });
10957
+ definedStyles.add(name);
10958
+ };
10959
+ defineStyle("default");
10960
+ return createSvgTextOverlayTextCapability(Object.freeze({ layoutText(input) {
10961
+ if (!definedStyles.has(input.styleName)) defineStyle(input.styleName);
10962
+ return composition.layoutText(input);
10963
+ } }));
10964
+ }
10965
+ function requireAssetManager(value) {
10966
+ if (!isRecord(value) || typeof value.isLoaded !== "function" || typeof value.getAssetMimeType !== "function" || typeof value.resolveSkin !== "function") throw new BubbleRuntimeAdapterError("BUBBLE-RUNTIME-002", "Bubble image assets require an imageResolver capability. Load @kubohiroya/turbowarp-asset-manager or provide options.imageResolver before using image features.");
10967
+ return value;
10968
+ }
10969
+ function targetBounds(target) {
10970
+ try {
10971
+ const bounds = target.getBoundsForBubble?.();
10972
+ if (bounds && [
10973
+ bounds.bottom,
10974
+ bounds.left,
10975
+ bounds.right,
10976
+ bounds.top
10977
+ ].every((value) => Number.isFinite(value))) return bounds;
10978
+ } catch {}
10979
+ const x = Number.isFinite(target.x) ? Number(target.x) : 0;
10980
+ const y = Number.isFinite(target.y) ? Number(target.y) : 0;
10981
+ return {
10982
+ bottom: y,
10983
+ left: x,
10984
+ right: x,
10985
+ top: y
10986
+ };
10987
+ }
10988
+ function readSize(renderer, target, fallback) {
10989
+ const raw = renderer.getCurrentSkinSize(target.drawableID);
10990
+ if (!Array.isArray(raw) || raw.length < 2) return fallback;
10991
+ const width = Number(raw[0]);
10992
+ const height = Number(raw[1]);
10993
+ if (!(width > 0) || !(height > 0)) return fallback;
10994
+ return {
10995
+ width,
10996
+ height
10997
+ };
10998
+ }
10999
+ function fitDrawable(renderer, target, boxSize, scaleMultiplier = 1) {
11000
+ const native = readSize(renderer, target, {
9437
11001
  width: boxSize,
9438
11002
  height: boxSize
9439
11003
  });
@@ -9441,9 +11005,18 @@
9441
11005
  renderer.updateDrawableScale(target.drawableID, [effectiveScale * 100, effectiveScale * 100]);
9442
11006
  return {
9443
11007
  width: native.width * effectiveScale,
9444
- height: native.height * effectiveScale
11008
+ height: native.height * effectiveScale,
11009
+ scalePercent: effectiveScale * 100
9445
11010
  };
9446
11011
  }
11012
+ function renderPortraitCornerMaskSvg(width, height, radius) {
11013
+ const roundedRadius = Math.min(radius, width / 2, height / 2);
11014
+ const right = width - roundedRadius;
11015
+ const bottom = height - roundedRadius;
11016
+ return `<svg xmlns="http://www.w3.org/2000/svg" width="${width}" height="${height}" viewBox="0 0 ${width} ${height}">
11017
+ <path d="M0 0H${width}V${height}H0Z M${roundedRadius} 0H${right}A${roundedRadius} ${roundedRadius} 0 0 1 ${width} ${roundedRadius}V${bottom}A${roundedRadius} ${roundedRadius} 0 0 1 ${right} ${height}H${roundedRadius}A${roundedRadius} ${roundedRadius} 0 0 1 0 ${bottom}V${roundedRadius}A${roundedRadius} ${roundedRadius} 0 0 1 ${roundedRadius} 0Z" fill="#fff4cc" fill-rule="evenodd" data-bubble-portrait-corner-radius="${roundedRadius}"/>
11018
+ </svg>`;
11019
+ }
9447
11020
  function clamp(value, minimum, maximum) {
9448
11021
  if (maximum < minimum) return (minimum + maximum) / 2;
9449
11022
  return Math.min(maximum, Math.max(minimum, value));
@@ -9463,6 +11036,7 @@
9463
11036
  surfaceSequence += 1;
9464
11037
  const drawables = [];
9465
11038
  let bodySkinId;
11039
+ let portraitMaskSkinId;
9466
11040
  const createTarget = (layer) => {
9467
11041
  const drawableID = renderer.createDrawable(spriteLayer);
9468
11042
  if (!Number.isInteger(drawableID) || drawableID < 0) throw new BubbleRuntimeAdapterError("BUBBLE-RUNTIME-001", `TurboWarp did not create the Bubble ${layer} drawable.`);
@@ -9481,6 +11055,7 @@
9481
11055
  const portraitBase = style.portrait ? createTarget("portrait-base") : void 0;
9482
11056
  const portraitBlink = style.portrait?.blink ? createTarget("portrait-blink") : void 0;
9483
11057
  const portraitLipSync = style.portrait?.lipSync ? createTarget("portrait-lip-sync") : void 0;
11058
+ const portraitMask = style.portrait ? createTarget("portrait-corner-mask") : void 0;
9484
11059
  const text = createTarget("text");
9485
11060
  const continueIndicator = style.continueIndicator ? createTarget("continue-indicator") : void 0;
9486
11061
  const targets = Object.freeze({
@@ -9499,6 +11074,7 @@
9499
11074
  let surfaceVisible = false;
9500
11075
  let disposed = false;
9501
11076
  let cachedBodySkinSignature = "";
11077
+ let cachedPortraitMaskSignature = "";
9502
11078
  let currentStyle = style;
9503
11079
  let reservedTextSize;
9504
11080
  const layoutPositions = /* @__PURE__ */ new Map();
@@ -9521,6 +11097,7 @@
9521
11097
  renderer.updateDrawableVisible(body.drawableID, surfaceVisible && actorVisible && currentStyle.visualStyle !== "NO_BUBBLE" && (renderer.updateDrawableEffect !== void 0 || motionOpacity > 0));
9522
11098
  renderer.updateDrawableVisible(text.drawableID, surfaceVisible && actorVisible && (renderer.updateDrawableEffect !== void 0 || motionOpacity > 0));
9523
11099
  for (const [layer, target] of layerTargets) renderer.updateDrawableVisible(target.drawableID, surfaceVisible && actorVisible && (layerVisibility.get(layer) ?? false) && (renderer.updateDrawableEffect !== void 0 || motionOpacity > 0));
11100
+ 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));
9524
11101
  applyMotionTransforms();
9525
11102
  runtime.requestRedraw?.();
9526
11103
  };
@@ -9536,16 +11113,25 @@
9536
11113
  width: nativeTextSize.width * scaleMultiplier,
9537
11114
  height: nativeTextSize.height * scaleMultiplier
9538
11115
  };
9539
- const portraitSize = portraitBase ? fitDrawable(renderer, portraitBase, portraitBoxSize, scaleMultiplier) : {
11116
+ const portraitFitBoxSize = portraitBoxSize * ((currentStyle.portrait?.offset.zoomPercent ?? 100) / 100);
11117
+ const hasPortrait = portraitBase !== void 0 && currentStyle.portrait !== void 0;
11118
+ const portraitSize = hasPortrait ? fitDrawable(renderer, portraitBase, portraitFitBoxSize, scaleMultiplier) : {
9540
11119
  width: 0,
9541
- height: 0
11120
+ height: 0,
11121
+ scalePercent: 0
9542
11122
  };
9543
- for (const target of [portraitBlink, portraitLipSync]) if (target) fitDrawable(renderer, target, portraitBoxSize, scaleMultiplier);
11123
+ const portraitLayerScales = /* @__PURE__ */ new Map();
11124
+ if (hasPortrait) portraitLayerScales.set(portraitBase.drawableID, portraitSize.scalePercent);
11125
+ for (const target of [portraitBlink, portraitLipSync]) if (target && hasPortrait) {
11126
+ const fitted = fitDrawable(renderer, target, portraitFitBoxSize, scaleMultiplier);
11127
+ portraitLayerScales.set(target.drawableID, fitted.scalePercent);
11128
+ }
9544
11129
  const indicatorSize = continueIndicator ? fitDrawable(renderer, continueIndicator, indicatorBoxSize, scaleMultiplier) : {
9545
11130
  width: 0,
9546
- height: 0
11131
+ height: 0,
11132
+ scalePercent: 0
9547
11133
  };
9548
- const totalWidth = portraitSize.width + (portraitBase ? contentGap * scaleMultiplier : 0) + textSize.width;
11134
+ const totalWidth = portraitSize.width + (hasPortrait ? contentGap * scaleMultiplier : 0) + textSize.width;
9549
11135
  const contentHeight = Math.max(portraitSize.height, textSize.height);
9550
11136
  const baseBubbleWidth = totalWidth / scaleMultiplier + 48;
9551
11137
  const baseBubbleHeight = contentHeight / scaleMultiplier + 48;
@@ -9646,13 +11232,49 @@
9646
11232
  renderer.updateDrawableScale(body.drawableID, [100, 100]);
9647
11233
  renderer.updateDrawablePosition(body.drawableID, [centerX - bodyCenterOffset.x, centerY + bodyCenterOffset.y]);
9648
11234
  const left = centerX - totalWidth / 2;
9649
- const portraitX = left + portraitSize.width / 2;
9650
- const textX = left + portraitSize.width + (portraitBase ? contentGap * scaleMultiplier : 0) + textSize.width / 2;
11235
+ const portraitPlacement = currentStyle.portrait?.placement ?? "left";
11236
+ const portraitOnRight = portraitPlacement.endsWith("right");
11237
+ const portraitOffsetX = (currentStyle.portrait?.offset.x ?? 0) * scaleMultiplier;
11238
+ const portraitOffsetY = (currentStyle.portrait?.offset.y ?? 0) * scaleMultiplier;
11239
+ const portraitX = (portraitOnRight ? left + textSize.width + contentGap * scaleMultiplier : left) + portraitSize.width / 2 + portraitOffsetX;
11240
+ let portraitY = centerY;
11241
+ if (portraitPlacement.startsWith("top-")) portraitY = centerY + contentHeight / 2 - portraitSize.height / 2;
11242
+ else if (portraitPlacement.startsWith("bottom-")) portraitY = centerY - contentHeight / 2 + portraitSize.height / 2;
11243
+ portraitY += portraitOffsetY;
11244
+ const textX = (portraitOnRight || !hasPortrait ? left : left + portraitSize.width + contentGap * scaleMultiplier) + textSize.width / 2;
9651
11245
  for (const target of [
9652
11246
  portraitBase,
9653
11247
  portraitBlink,
9654
11248
  portraitLipSync
9655
- ]) if (target) renderer.updateDrawablePosition(target.drawableID, [portraitX, centerY]);
11249
+ ]) if (target) renderer.updateDrawablePosition(target.drawableID, [portraitX, portraitY]);
11250
+ if (portraitMask) {
11251
+ const maskWidth = portraitSize.width / scaleMultiplier;
11252
+ const maskHeight = portraitSize.height / scaleMultiplier;
11253
+ const radius = Math.min(currentStyle.portrait?.cornerRadius ?? 0, maskWidth / 2, maskHeight / 2);
11254
+ const nextPortraitMaskSignature = radius > 0 ? JSON.stringify({
11255
+ maskHeight,
11256
+ maskWidth,
11257
+ radius
11258
+ }) : "";
11259
+ if (nextPortraitMaskSignature !== cachedPortraitMaskSignature) {
11260
+ const previousPortraitMaskSkinId = portraitMaskSkinId;
11261
+ portraitMaskSkinId = void 0;
11262
+ cachedPortraitMaskSignature = nextPortraitMaskSignature;
11263
+ if (radius > 0) {
11264
+ const nextSkinId = renderer.createSVGSkin(renderPortraitCornerMaskSvg(maskWidth, maskHeight, radius));
11265
+ if (!Number.isInteger(nextSkinId) || nextSkinId < 0) throw new BubbleRuntimeAdapterError("BUBBLE-RUNTIME-001", "TurboWarp did not create the Bubble portrait corner mask SVG skin.");
11266
+ try {
11267
+ renderer.updateDrawableSkinId(portraitMask.drawableID, nextSkinId);
11268
+ portraitMaskSkinId = nextSkinId;
11269
+ } catch (error) {
11270
+ renderer.destroySkin(nextSkinId);
11271
+ throw error;
11272
+ }
11273
+ }
11274
+ if (previousPortraitMaskSkinId !== void 0) renderer.destroySkin(previousPortraitMaskSkinId);
11275
+ }
11276
+ renderer.updateDrawablePosition(portraitMask.drawableID, [portraitX, portraitY]);
11277
+ }
9656
11278
  renderer.updateDrawablePosition(text.drawableID, [textX, centerY]);
9657
11279
  if (continueIndicator) renderer.updateDrawablePosition(continueIndicator.drawableID, [textX + textSize.width / 2 - indicatorSize.width / 2 - contentGap * scaleMultiplier, centerY - textSize.height / 2 + indicatorSize.height / 2 + contentGap * scaleMultiplier]);
9658
11280
  const remember = (target, positionValue) => {
@@ -9661,15 +11283,23 @@
9661
11283
  };
9662
11284
  remember(body, [centerX - bodyCenterOffset.x, centerY + bodyCenterOffset.y]);
9663
11285
  remember(text, [textX, centerY]);
9664
- remember(portraitBase, [portraitX, centerY]);
9665
- remember(portraitBlink, [portraitX, centerY]);
9666
- remember(portraitLipSync, [portraitX, centerY]);
11286
+ remember(portraitBase, [portraitX, portraitY]);
11287
+ remember(portraitBlink, [portraitX, portraitY]);
11288
+ remember(portraitLipSync, [portraitX, portraitY]);
11289
+ remember(portraitMask, [portraitX, portraitY]);
9667
11290
  layoutScales.set(body.drawableID, [100, 100]);
9668
11291
  layoutScales.set(text.drawableID, [scaleMultiplier * 100, scaleMultiplier * 100]);
9669
- if (portraitBase) layoutScales.set(portraitBase.drawableID, [scaleMultiplier * 100, scaleMultiplier * 100]);
9670
- if (portraitBlink) layoutScales.set(portraitBlink.drawableID, [scaleMultiplier * 100, scaleMultiplier * 100]);
9671
- if (portraitLipSync) layoutScales.set(portraitLipSync.drawableID, [scaleMultiplier * 100, scaleMultiplier * 100]);
9672
- if (continueIndicator) layoutScales.set(continueIndicator.drawableID, [scaleMultiplier * 100, scaleMultiplier * 100]);
11292
+ for (const target of [
11293
+ portraitBase,
11294
+ portraitBlink,
11295
+ portraitLipSync
11296
+ ]) {
11297
+ if (!target) continue;
11298
+ const portraitScale = portraitLayerScales.get(target.drawableID) ?? 0;
11299
+ layoutScales.set(target.drawableID, [portraitScale, portraitScale]);
11300
+ }
11301
+ if (portraitMask) layoutScales.set(portraitMask.drawableID, [scaleMultiplier * 100, scaleMultiplier * 100]);
11302
+ if (continueIndicator) layoutScales.set(continueIndicator.drawableID, [indicatorSize.scalePercent, indicatorSize.scalePercent]);
9673
11303
  if (continueIndicator) remember(continueIndicator, [textX + textSize.width / 2 - indicatorSize.width / 2 - contentGap * scaleMultiplier, centerY - textSize.height / 2 + indicatorSize.height / 2 + contentGap * scaleMultiplier]);
9674
11304
  applyMotionTransforms();
9675
11305
  updateVisibility();
@@ -9722,7 +11352,7 @@
9722
11352
  applyMotionTransforms();
9723
11353
  updateVisibility();
9724
11354
  };
9725
- const eased = (progress) => easeProgress(progress, motion.ease ?? "easeInOut");
11355
+ const eased = (progress) => easeMotionProgress(progress, motion.ease ?? "easeInOut");
9726
11356
  if (motion.name === "fadeIn" || motion.name === "floatIn" || motion.name === "zoomIn" || motion.name === "riseUp") {
9727
11357
  surfaceVisible = true;
9728
11358
  const startingTranslation = motion.name === "floatIn" || motion.name === "riseUp" ? [0, 16] : [0, 0];
@@ -9810,11 +11440,11 @@
9810
11440
  };
9811
11441
  position();
9812
11442
  await runMotionTimeline(scheduler, durationSeconds, (progress) => {
9813
- const speedProgress = durationSeconds === 0 ? 1 : clamp01(progress * Math.max(speed, 1) / 1);
11443
+ const speedProgress = durationSeconds === 0 ? 1 : clampMotionProgress(progress * Math.max(speed, 1) / 1);
9814
11444
  shapeTransition = {
9815
11445
  from: fromStyle,
9816
11446
  to: targetStyle,
9817
- progress: easeProgress(speedProgress, motion.ease ?? "easeInOut")
11447
+ progress: easeMotionProgress(speedProgress, motion.ease ?? "easeInOut")
9818
11448
  };
9819
11449
  position();
9820
11450
  });
@@ -9842,12 +11472,17 @@
9842
11472
  renderer.destroySkin(bodySkinId);
9843
11473
  bodySkinId = void 0;
9844
11474
  }
11475
+ if (portraitMaskSkinId !== void 0) {
11476
+ renderer.destroySkin(portraitMaskSkinId);
11477
+ portraitMaskSkinId = void 0;
11478
+ }
9845
11479
  runtime.requestRedraw?.();
9846
11480
  }
9847
11481
  });
9848
11482
  } catch (error) {
9849
11483
  for (const target of [...drawables].reverse()) renderer.destroyDrawable(target.drawableID, spriteLayer);
9850
11484
  if (bodySkinId !== void 0) renderer.destroySkin(bodySkinId);
11485
+ if (portraitMaskSkinId !== void 0) renderer.destroySkin(portraitMaskSkinId);
9851
11486
  throw error;
9852
11487
  }
9853
11488
  }
@@ -9855,52 +11490,75 @@
9855
11490
  if (!isRecord(runtimeInput)) throw new BubbleRuntimeAdapterError("BUBBLE-RUNTIME-001", "Bubble requires the TurboWarp runtime.");
9856
11491
  const runtime = runtimeInput;
9857
11492
  const renderer = requireRenderer(runtime.renderer);
11493
+ const requestedBackend = normalizeRenderBackend(options.bubbleRenderBackend);
11494
+ const overlayTextCapability = requestedBackend === "svg-overlay" ? options.svgOverlayTextCapability ?? createDefaultSvgOverlayTextCapability() : void 0;
11495
+ const unsupportedBehavior = normalizeOverlayUnsupportedBehavior(options.svgOverlayUnsupportedBehavior);
11496
+ const overlayDocument = requestedBackend === "svg-overlay" ? resolveOverlayDocument(options.document) : void 0;
11497
+ const unavailableReason = requestedBackend === "svg-overlay" ? overlayUnavailableReason(renderer, overlayDocument, overlayTextCapability) : void 0;
11498
+ if (requestedBackend === "svg-overlay" && unavailableReason !== void 0 && unsupportedBehavior === "error") throw new BubbleRuntimeAdapterError("BUBBLE-RUNTIME-004", `Bubble SVG overlay backend is unavailable because ${unavailableReason}. Use scratch-render or install the required public upstream capability.`);
11499
+ const renderBackend = requestedBackend === "svg-overlay" && unavailableReason === void 0 ? "svg-overlay" : "scratch-render";
11500
+ const scheduler = options.scheduler ?? {
11501
+ setTimeout: (callback, milliseconds) => globalThis.setTimeout(callback, milliseconds),
11502
+ clearTimeout: (handle) => globalThis.clearTimeout(handle)
11503
+ };
9858
11504
  const getAssetExtension = () => requireAssetManager(runtime.ext_kubohiroyaassetmanager);
9859
11505
  let textCapability;
9860
- if (options.textCapability !== void 0) textCapability = options.textCapability;
11506
+ if (renderBackend === "svg-overlay") try {
11507
+ textCapability = createSvgOverlayTextAdapter(overlayTextCapability, renderer);
11508
+ } catch (error) {
11509
+ throw new BubbleRuntimeAdapterError("BUBBLE-RUNTIME-004", `Bubble SVG overlay text capability is invalid: ${error instanceof Error ? error.message : String(error)}`);
11510
+ }
11511
+ else if (options.textCapability !== void 0) textCapability = options.textCapability;
9861
11512
  else try {
9862
11513
  textCapability = createTurboWarpSvgTextCapability(runtime.ext_kubohiroyasvgtext);
9863
11514
  } catch {
9864
11515
  throw new BubbleRuntimeAdapterError("BUBBLE-RUNTIME-003", "Bubble requires a text capability. Load @kubohiroya/turbowarp-svg-text or provide options.textCapability before using Bubble blocks.");
9865
11516
  }
9866
- return createBubbleComposition({
9867
- imageResolver: options.imageResolver ?? {
9868
- isRegistered(name) {
9869
- return getAssetExtension().isLoaded({ NAME: name });
9870
- },
9871
- getMimeType(name) {
9872
- return getAssetExtension().getAssetMimeType({ NAME: name });
9873
- },
9874
- async applyToTarget(name, target) {
9875
- const drawableID = target.drawableID;
9876
- if (!Number.isInteger(drawableID) || drawableID < 0) throw new BubbleRuntimeAdapterError("BUBBLE-RUNTIME-001", "Bubble image target drawable is invalid.");
9877
- const skin = await getAssetExtension().resolveSkin(name);
9878
- 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)}`);
9879
- renderer.updateDrawableSkinId(drawableID, skin.skinId);
9880
- runtime.requestRedraw?.();
9881
- }
11517
+ let imageResolver;
11518
+ if (renderBackend === "svg-overlay") {
11519
+ if (options.svgOverlayImageCapability !== void 0) try {
11520
+ imageResolver = createSvgOverlayImageAdapter(options.svgOverlayImageCapability);
11521
+ } catch (error) {
11522
+ throw new BubbleRuntimeAdapterError("BUBBLE-RUNTIME-004", `Bubble SVG overlay image capability is invalid: ${error instanceof Error ? error.message : String(error)}`);
11523
+ }
11524
+ } else imageResolver = options.imageResolver ?? {
11525
+ isRegistered(name) {
11526
+ return getAssetExtension().isLoaded({ NAME: name });
9882
11527
  },
9883
- audio: options.audio ?? {
9884
- isRegistered(name) {
9885
- return getAssetExtension().isLoaded({ NAME: name });
9886
- },
9887
- getMimeType(name) {
9888
- return getAssetExtension().getAssetMimeType({ NAME: name });
9889
- },
9890
- async playSound(name, playOptions = {}) {
9891
- const extension = getAssetExtension();
9892
- const method = playOptions.untilDone ? extension?.playSoundUntilDone : extension?.playSound;
9893
- if (typeof method !== "function") throw new BubbleRuntimeAdapterError("BUBBLE-RUNTIME-002", "TurboWarp Asset Manager does not provide audio playback.");
9894
- await method.call(extension, { NAME: name });
9895
- }
11528
+ getMimeType(name) {
11529
+ return getAssetExtension().getAssetMimeType({ NAME: name });
11530
+ },
11531
+ async applyToTarget(name, target) {
11532
+ const drawableID = target.drawableID;
11533
+ if (!Number.isInteger(drawableID) || drawableID < 0) throw new BubbleRuntimeAdapterError("BUBBLE-RUNTIME-001", "Bubble image target drawable is invalid.");
11534
+ const skin = await getAssetExtension().resolveSkin(name);
11535
+ 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)}`);
11536
+ renderer.updateDrawableSkinId(drawableID, skin.skinId);
11537
+ runtime.requestRedraw?.();
11538
+ }
11539
+ };
11540
+ const audio = options.audio ?? {
11541
+ isRegistered(name) {
11542
+ return getAssetExtension().isLoaded({ NAME: name });
9896
11543
  },
11544
+ getMimeType(name) {
11545
+ return getAssetExtension().getAssetMimeType({ NAME: name });
11546
+ },
11547
+ async playSound(name, playOptions = {}) {
11548
+ const extension = getAssetExtension();
11549
+ const method = playOptions.untilDone ? extension?.playSoundUntilDone : extension?.playSound;
11550
+ if (typeof method !== "function") throw new BubbleRuntimeAdapterError("BUBBLE-RUNTIME-002", "TurboWarp Asset Manager does not provide audio playback.");
11551
+ await method.call(extension, { NAME: name });
11552
+ }
11553
+ };
11554
+ const overlayManager = renderBackend === "svg-overlay" ? createSvgOverlaySurfaceManager(renderer, overlayDocument) : void 0;
11555
+ return createBubbleComposition({
11556
+ ...imageResolver === void 0 ? {} : { imageResolver },
11557
+ audio,
9897
11558
  textCapability,
9898
11559
  createSurface({ actor, actorKey, style }) {
9899
11560
  if (!isRecord(actor) || typeof actor.id !== "string") throw new BubbleRuntimeAdapterError("BUBBLE-RUNTIME-001", "Bubble actor target is invalid.");
9900
- return createSurface(runtime, actor, actorKey, style, options.scheduler ?? {
9901
- setTimeout: (callback, milliseconds) => globalThis.setTimeout(callback, milliseconds),
9902
- clearTimeout: (handle) => globalThis.clearTimeout(handle)
9903
- });
11561
+ return renderBackend === "svg-overlay" ? createSvgOverlaySurface(overlayManager, actor, actorKey, style, scheduler) : createSurface(runtime, actor, actorKey, style, scheduler);
9904
11562
  },
9905
11563
  ...options.scheduler === void 0 ? {} : { scheduler: options.scheduler },
9906
11564
  ...options.onAnimationError === void 0 ? {} : { onAnimationError: options.onAnimationError }
@@ -9908,8 +11566,8 @@
9908
11566
  }
9909
11567
  //#endregion
9910
11568
  //#region src/extension.ts
9911
- var blockDefinitions = block_definitions_default.blocks;
9912
- var definitionMenus = block_definitions_default.menus;
11569
+ var blockDefinitions = block_definitions_default$1.blocks;
11570
+ var definitionMenus = block_definitions_default$1.menus;
9913
11571
  var validAnimationModes = /* @__PURE__ */ new Set([
9914
11572
  "idle",
9915
11573
  "talking",
@@ -9947,7 +11605,7 @@
9947
11605
  "easeInOut"
9948
11606
  ]);
9949
11607
  var EXTENSION_DOCS_URI = "https://kubohiroya.github.io/turbowarp-bubble/";
9950
- var EXTENSION_VERSION = "0.6.0";
11608
+ var EXTENSION_VERSION = "0.8.0";
9951
11609
  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>")}`;
9952
11610
  function extensionError(message) {
9953
11611
  const error = /* @__PURE__ */ new Error(`[Bubble] ${message}`);
@@ -9987,7 +11645,7 @@
9987
11645
  getInfo() {
9988
11646
  return {
9989
11647
  id: extensionConfig.id,
9990
- name: Scratch.translate(block_definitions_default.extensionName),
11648
+ name: Scratch.translate(block_definitions_default$1.extensionName),
9991
11649
  docsURI: EXTENSION_DOCS_URI,
9992
11650
  blockIconURI: BLOCK_ICON_URI,
9993
11651
  color1: "#ff6680",
@@ -10018,6 +11676,42 @@
10018
11676
  })();
10019
11677
  this.installStyle(nextStyle);
10020
11678
  }
11679
+ setPortraitLayout(args) {
11680
+ const style = this.requireStyle(args.STYLE);
11681
+ if (this.toString(args.PLACEMENT).trim().toLowerCase() === "none") {
11682
+ const { portrait, ...withoutPortrait } = style;
11683
+ this.installStyle(Object.freeze(withoutPortrait));
11684
+ return;
11685
+ }
11686
+ if (!style.portrait?.base) throw extensionError("set the portrait base before portrait layout.");
11687
+ let placement;
11688
+ let offset;
11689
+ let cornerRadius;
11690
+ try {
11691
+ placement = normalizeBubblePortraitPlacement(args.PLACEMENT);
11692
+ offset = normalizeBubblePortraitOffset([
11693
+ Scratch.Cast.toNumber(args.X),
11694
+ Scratch.Cast.toNumber(args.Y),
11695
+ Scratch.Cast.toNumber(args.ZOOM)
11696
+ ]);
11697
+ cornerRadius = normalizeBubblePortraitCornerRadius(Scratch.Cast.toNumber(args.RADIUS));
11698
+ } catch (error) {
11699
+ throw extensionError(error instanceof Error ? error.message : "Bubble portrait layout is invalid.");
11700
+ }
11701
+ this.installStyle(Object.freeze({
11702
+ ...style,
11703
+ portrait: Object.freeze({
11704
+ ...style.portrait,
11705
+ placement,
11706
+ offset: Object.freeze([
11707
+ offset.x,
11708
+ offset.y,
11709
+ offset.zoomPercent
11710
+ ]),
11711
+ cornerRadius
11712
+ })
11713
+ }));
11714
+ }
10021
11715
  setBubblePlacement(args) {
10022
11716
  const style = this.requireStyle(args.STYLE);
10023
11717
  let placement;
@@ -10412,13 +12106,14 @@
10412
12106
  if (!portrait?.base) throw extensionError("set the portrait base before portrait animation frames.");
10413
12107
  const frames = this.parseFrames(args.ASSETS);
10414
12108
  const animation = frames.length === 0 ? void 0 : this.animationInput(frames, args.SECONDS, field);
12109
+ const { blink, lipSync, ...portraitLayout } = portrait;
10415
12110
  const nextPortrait = Object.freeze({
10416
- base: portrait.base,
12111
+ ...portraitLayout,
10417
12112
  ...field === "blink" ? {
10418
12113
  ...animation ? { blink: animation } : {},
10419
- ...portrait.lipSync ? { lipSync: portrait.lipSync } : {}
12114
+ ...lipSync ? { lipSync } : {}
10420
12115
  } : {
10421
- ...portrait.blink ? { blink: portrait.blink } : {},
12116
+ ...blink ? { blink } : {},
10422
12117
  ...animation ? { lipSync: animation } : {}
10423
12118
  }
10424
12119
  });