diff --git a/CONTEXT.md b/CONTEXT.md index 128652b25..8f6a6445a 100644 --- a/CONTEXT.md +++ b/CONTEXT.md @@ -173,3 +173,17 @@ Right-click on the sprite — character switching, settings, quit. **Summon**: The deliberate act that opens the Functional Layer. _Avoid_: Invoke, activate, wake + +### Expression + +**Speech bubble**: +A bubble above the sprite showing Frame.dialogue, held for reading time (900ms ++ 55ms per character, clamped to 2–8 s). A new line replaces the old one. +Implemented in #119. +_Avoid_: Chat bubble, message, tooltip + +**Thinking ellipsis**: +Three animated dots in a bubble above the sprite, shown while a reactive +Director turn is in flight (Poke, Summon, Throw). Appears after 250ms grace, +held ≥600ms once shown. Ambient wakes stay invisible. #119. +_Avoid_: Loading, spinner, progress diff --git a/crates/core/src/director.rs b/crates/core/src/director.rs index f566bdeb7..d38c09290 100644 --- a/crates/core/src/director.rs +++ b/crates/core/src/director.rs @@ -158,8 +158,8 @@ impl ModelDirector { } } -/// A reply that is not a declared Behavior. Empty name: the Engine speaks -/// and starts nothing. #17 will show this in a bubble. +/// A reply that is not a declared Behavior. Empty name: the Engine plays +/// `talk` and speaks. #119 shows this in a bubble. fn as_speech(reply: &str) -> Option { let text = reply.trim(); let text = text diff --git a/crates/core/src/dispatch.rs b/crates/core/src/dispatch.rs index 42a842898..e9394a531 100644 --- a/crates/core/src/dispatch.rs +++ b/crates/core/src/dispatch.rs @@ -257,6 +257,7 @@ mod tests { fn window(owner: &str, x: f64, y: f64, width: f64, height: f64) -> WindowRect { WindowRect { + id: 0, bounds: Rect { x, y, diff --git a/crates/core/src/engine.rs b/crates/core/src/engine.rs index 8d8eac136..90aef427d 100644 --- a/crates/core/src/engine.rs +++ b/crates/core/src/engine.rs @@ -446,6 +446,9 @@ impl Engine { // // #84: Do Not Disturb refuses proposals before they reach the State // gate, so the Character stops starting things while staying visible. + // + // #119: dialogue with an empty behavior plays `talk`. Duration is + // PRIMITIVE_MS, independent of bubble reading time. let mut behavior = None; if let Some(proposal) = &snapshot.proposal { if !self.do_not_disturb { @@ -454,6 +457,11 @@ impl Engine { started = true; behavior = Some(proposal.behavior.clone()); } + } else if proposal.behavior.is_empty() + && proposal.dialogue.is_some() + && self.play(&[Primitive::Talk]) + { + started = true; } } } @@ -3918,4 +3926,75 @@ mod tests { "the sprite settles to sleep without Director proposals waking it" ); } + + /// #119: dialogue with an empty behavior plays `talk` for PRIMITIVE_MS, + /// independent of bubble duration. + #[test] + fn dialogue_with_empty_behavior_plays_talk() { + let mut engine = a_resting_sprite(); + + let spoken = engine.tick(&WorldSnapshot { + proposal: Some(BehaviorProposal { + behavior: String::new(), + dialogue: Some("hello there".to_string()), + }), + ..snapshot(100) + }); + + assert_eq!( + spoken.animation, "talk", + "dialogue with no Behavior plays talk" + ); + assert_eq!(spoken.dialogue.as_deref(), Some("hello there")); + + let playing: Vec<&'static str> = (0..10) + .map(|_| engine.tick(&snapshot(100)).animation) + .collect(); + + let talk_ticks = playing.iter().filter(|&&anim| anim == "talk").count(); + assert!( + talk_ticks == 5, + "talk holds for PRIMITIVE_MS (600ms = 5 more ticks after the first): {playing:?}" + ); + } + + /// #119: dialogue with a playable Behavior plays both — the Behavior and + /// its dialogue are independent. + #[test] + fn dialogue_with_a_playable_behavior_plays_the_behavior_not_talk() { + let mut engine = a_resting_sprite(); + + let spoken = engine.tick(&WorldSnapshot { + proposal: Some(BehaviorProposal { + behavior: "greet".to_string(), + dialogue: Some("hi".to_string()), + }), + ..snapshot(100) + }); + + assert_eq!( + spoken.animation, "react", + "greet plays its own animation, not talk" + ); + assert_eq!(spoken.dialogue.as_deref(), Some("hi")); + assert_eq!(spoken.behavior, Some("greet".to_string())); + } + + /// #119: a Behavior with no dialogue does not play talk. + #[test] + fn a_behavior_without_dialogue_does_not_play_talk() { + let mut engine = a_resting_sprite(); + + let silent = engine.tick(&WorldSnapshot { + proposal: Some(BehaviorProposal { + behavior: "greet".to_string(), + dialogue: None, + }), + ..snapshot(100) + }); + + assert_eq!(silent.animation, "react", "greet plays its own animation"); + assert_eq!(silent.dialogue, None); + assert_eq!(silent.behavior, Some("greet".to_string())); + } } diff --git a/docs/SPEC.md b/docs/SPEC.md index 398951eb2..5e008d8b3 100644 --- a/docs/SPEC.md +++ b/docs/SPEC.md @@ -381,8 +381,8 @@ Two implementations ship: Director is disabled, and as the fallback on any session error or timeout. The Shell may wake it often: the path is free. - **Session** — an attached Harness, the same conversation as chat. Proposes a Behavior - identifier plus optional dialogue. A reply that is not a declared Behavior is - spoken (`say:`) and starts nothing; #17 will put that in a bubble. Until a + identifier plus optional dialogue. A reply that is not a declared Behavior plays + `talk` and is spoken (`say:`); #119 put that in a bubble. Until a Harness exists, an HTTP Completer stands in behind the same trait ([ADR-0008](./adr/0008-one-harness-session.md)). diff --git a/src-tauri/src/main.rs b/src-tauri/src/main.rs index 5d48e86a6..a4f076a98 100644 --- a/src-tauri/src/main.rs +++ b/src-tauri/src/main.rs @@ -99,7 +99,7 @@ struct Drawn { /// /// Pushed every tick rather than fetched, so the webview holds no authoritative /// state — it draws what it was last told and remembers nothing. -#[derive(Clone, Copy, Serialize)] +#[derive(Clone, Serialize)] struct Placement<'a> { x: i32, y: i32, @@ -123,6 +123,13 @@ struct Placement<'a> { fade_ms: u32, /// -1 to mirror the art (heading left), 1 to draw it as authored. facing: i8, + /// A line to speak on this tick only. Dialogue is an event, not a state. + /// #119: the webview latches it and owns display duration. + dialogue: Option, + /// Whether to show the thinking ellipsis. Derived from InFlight state and + /// addressed. #119: grace and min-hold are in the webview so the Engine + /// stays tick-pure. + thinking: bool, } /// Every Animation's frames as `data:` URLs, in play order, keyed by the @@ -638,41 +645,55 @@ fn run_frame_loop( } // After the tick so a Throw is already Falling, not still Dragged. - if let (Some(model), Some(activity)) = (&model, last_activity.as_ref()) { - if director::session_due( - addressed, - since_ambient, - &pace, - activity.displays_asleep, - engine.do_not_disturb(), - ) && pending.ready() - && !applied - { - let context = Context { - activity: activity.clone(), - recent: recent.clone(), - personality: character.personality.clone(), - state: frame.state, - happened, - standing: assembler.standing_on(frame.position), - }; - if addressed { - pace.after_reactive(); + let reactive_wake = + if let (Some(model), Some(activity)) = (&model, last_activity.as_ref()) { + if director::session_due( + addressed, + since_ambient, + &pace, + activity.displays_asleep, + engine.do_not_disturb(), + ) && pending.ready() + && !applied + { + let context = Context { + activity: activity.clone(), + recent: recent.clone(), + personality: character.personality.clone(), + state: frame.state, + happened, + standing: assembler.standing_on(frame.position), + }; + let was_addressed = addressed; + if addressed { + pace.after_reactive(); + } else { + pace.after_ambient(); + } + addressed = false; + happened = Happened::Ambient; + since_ambient = Duration::ZERO; + let payload = model.prompt(&context); + if let Ok(mut inspect) = inspect.lock() { + inspect.last_payload = Some(payload); + inspect.wake_secs = pace.wait().as_secs(); + } + pending.start(Arc::clone(model), context.clone()); + in_flight = Some(context); + was_addressed } else { - pace.after_ambient(); + false } - addressed = false; - happened = Happened::Ambient; - since_ambient = Duration::ZERO; - let payload = model.prompt(&context); - if let Ok(mut inspect) = inspect.lock() { - inspect.last_payload = Some(payload); - inspect.wake_secs = pace.wait().as_secs(); - } - pending.start(Arc::clone(model), context.clone()); - in_flight = Some(context); - } - } + } else { + false + }; + + let thinking = !pending.ready() + && (reactive_wake + || in_flight + .as_ref() + .is_some_and(|ctx| ctx.happened != Happened::Ambient)) + && !engine.do_not_disturb(); // What the user has seen is what the Engine played, not what the // Director asked for: a proposal the State refuses never reaches @@ -832,6 +853,8 @@ fn run_frame_loop( visible: presence.visible, fade_ms: presence.fade_ms, facing: frame.facing as i8, + dialogue: frame.dialogue.clone(), + thinking, }, ); diff --git a/src/bubble.js b/src/bubble.js new file mode 100644 index 000000000..67f9289ee --- /dev/null +++ b/src/bubble.js @@ -0,0 +1,74 @@ +// Bubble rendering logic for speech and thinking indicators. + +export const CEILING_CLEARANCE = 128; + +const MIN_DURATION_MS = 2000; +const MAX_DURATION_MS = 8000; +const BASE_DURATION_MS = 900; +const MS_PER_CHAR = 55; +const MAX_LINES = 6; + +export function bubbleDuration(text) { + const duration = BASE_DURATION_MS + text.length * MS_PER_CHAR; + return Math.max(MIN_DURATION_MS, Math.min(MAX_DURATION_MS, duration)); +} + +export function wrapText(text, maxWidth, measureFn) { + const lines = []; + const paragraphs = text.split("\n"); + + for (const paragraph of paragraphs) { + if (lines.length >= MAX_LINES) break; + + const words = paragraph.split(" "); + let currentLine = ""; + + for (const word of words) { + if (lines.length >= MAX_LINES) break; + + const testLine = currentLine ? `${currentLine} ${word}` : word; + const metrics = measureFn(testLine); + + if (metrics.width > maxWidth && currentLine) { + lines.push(currentLine); + currentLine = word; + } else { + currentLine = testLine; + } + } + + if (currentLine && lines.length < MAX_LINES) { + lines.push(currentLine); + } + } + + if (lines.length === MAX_LINES && (lines.length < paragraphs.length || + paragraphs[paragraphs.length - 1].split(" ").length > lines[lines.length - 1].split(" ").length)) { + lines[MAX_LINES - 1] = lines[MAX_LINES - 1].trimEnd() + "…"; + } + + return lines.slice(0, MAX_LINES); +} + +export function placeBubble(spriteRect, bubbleSize, displayBounds, ceilingClearance) { + const spriteHeadY = spriteRect.y; + const spriteBottomY = spriteRect.y + spriteRect.height; + const spriteCenterX = spriteRect.x + spriteRect.width / 2; + + let x = spriteCenterX - bubbleSize.width / 2; + let y = spriteHeadY - bubbleSize.height - 10; + let flipped = false; + + if (spriteHeadY < ceilingClearance) { + y = spriteBottomY + 10; + flipped = true; + } + + const unclamped = x; + x = Math.max(displayBounds.x, Math.min(x, displayBounds.x + displayBounds.width - bubbleSize.width)); + y = Math.max(displayBounds.y, Math.min(y, displayBounds.y + displayBounds.height - bubbleSize.height)); + + const tailOffset = spriteCenterX - (x + bubbleSize.width / 2); + + return { x, y, flipped, tailOffset }; +} diff --git a/src/index.html b/src/index.html index 20b584fab..02dc1f642 100644 --- a/src/index.html +++ b/src/index.html @@ -6,6 +6,16 @@ + + diff --git a/src/main.css b/src/main.css index e3fe3d3a8..509a24f3a 100644 --- a/src/main.css +++ b/src/main.css @@ -16,6 +16,91 @@ body { user-select: none; } +.bubble { + position: absolute; + max-width: 260px; + padding: 12px 16px; + background: white; + border: 2px solid #333; + border-radius: 12px; + box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15); + font-family: system-ui, -apple-system, sans-serif; + font-size: 14px; + line-height: 1.4; + color: #333; + pointer-events: none; + opacity: 0; + transition: opacity 300ms ease; + word-wrap: break-word; + z-index: 1; +} + +.bubble::after { + content: ""; + position: absolute; + bottom: -10px; + left: 50%; + transform: translateX(calc(-50% + var(--tail-offset, 0px))); + width: 0; + height: 0; + border-left: 10px solid transparent; + border-right: 10px solid transparent; + border-top: 10px solid #333; +} + +.bubble.flipped::after { + bottom: auto; + top: -10px; + border-top: none; + border-bottom: 10px solid #333; +} + +.bubble.visible { + opacity: 1; +} + +.bubble.hidden { + opacity: 0; + visibility: hidden; +} + +.bubble-content { + white-space: pre-wrap; +} + +.thinking-bubble .thinking-dots { + display: flex; + gap: 6px; + justify-content: center; + align-items: center; + padding: 4px 0; +} + +.thinking-bubble .thinking-dots span { + width: 8px; + height: 8px; + background: #333; + border-radius: 50%; + animation: thinking-bounce 1.4s infinite ease-in-out both; +} + +.thinking-bubble .thinking-dots span:nth-child(1) { + animation-delay: -0.32s; +} + +.thinking-bubble .thinking-dots span:nth-child(2) { + animation-delay: -0.16s; +} + +@keyframes thinking-bounce { + 0%, 80%, 100% { + transform: scale(0); + } + 40% { + transform: scale(1); + } +} + #sprite { position: absolute; /* Positioned by transform rather than by left/top: the renderer moves the diff --git a/src/main.js b/src/main.js index e864fb846..181004d21 100644 --- a/src/main.js +++ b/src/main.js @@ -4,8 +4,12 @@ // interpolated across. import { interpolate } from "./interpolate.js"; +import { bubbleDuration, wrapText, placeBubble, CEILING_CLEARANCE } from "./bubble.js"; const sprite = document.getElementById("sprite"); +const bubble = document.getElementById("bubble"); +const thinkingBubble = document.getElementById("thinking-bubble"); +const bubbleContent = bubble.querySelector(".bubble-content"); // Every Animation's frames as data: URLs, fetched once. Art, not state. let art = {}; @@ -36,6 +40,16 @@ let latest = null; // ask the loader for art it already has. let drawn = null; +// Bubble state: latched dialogue and timers for grace/min-hold. +let speechTimeout = null; +let thinkingGraceTimeout = null; +let thinkingMinHoldTimeout = null; +let thinkingShown = false; +let lastLatchedDialogue = null; +let lastLatchedThinking = false; +const THINKING_GRACE_MS = 250; +const THINKING_MIN_HOLD_MS = 600; + function draw(now) { requestAnimationFrame(draw); if (!latest) { @@ -43,11 +57,14 @@ function draw(now) { } const at = previous ? interpolate(previous, latest, now) : latest; + const spriteX = Math.round(at.x); + const spriteY = Math.round(at.y); + // Whole pixels, so a sprite drawn at an integer scale is not resampled back // onto a fractional grid by the compositor. ADR-0006. The art is authored // heading right; `scaleX(-1)` mirrors it in place when the Engine says the // sprite faces left. main.css sets the center origin that makes it in-place. - sprite.style.transform = `translate(${Math.round(at.x)}px, ${Math.round(at.y)}px) scaleX(${latest.facing})`; + sprite.style.transform = `translate(${spriteX}px, ${spriteY}px) scaleX(${latest.facing})`; // The hide rules, carried on every frame rather than announced when they // change: a change announced while this file was still fetching its art is a @@ -57,6 +74,46 @@ function draw(now) { sprite.style.transition = `opacity ${latest.fade_ms}ms linear`; sprite.style.opacity = latest.visible ? "1" : "0"; + // Bubble visibility follows sprite visibility with same fade + bubble.style.transition = `opacity ${latest.fade_ms}ms linear`; + thinkingBubble.style.transition = `opacity ${latest.fade_ms}ms linear`; + if (!latest.visible) { + bubble.style.opacity = "0"; + thinkingBubble.style.opacity = "0"; + if (latest.fade_ms === 0) { + bubble.classList.add("hidden"); + thinkingBubble.classList.add("hidden"); + clearThinkingBubble(); + } + } else { + bubble.style.opacity = ""; + thinkingBubble.style.opacity = ""; + + // Reposition visible bubbles to follow walking sprite + const spriteRect = { + x: spriteX, + y: spriteY, + width: latest.width, + height: latest.height, + }; + const displayBounds = { + x: 0, + y: 0, + width: window.innerWidth, + height: window.innerHeight, + }; + + if (bubble.classList.contains("visible")) { + positionBubble(bubble, spriteRect, displayBounds); + } + + if (thinkingBubble.classList.contains("visible")) { + positionBubble(thinkingBubble, spriteRect, displayBounds); + } + } + + latchBubbles(); + const placement = `${latest.animation}#${latest.frame_index} ${latest.width}x${latest.height}`; if (placement === drawn) { return; @@ -74,6 +131,118 @@ function draw(now) { sprite.style.visibility = "visible"; } +function positionBubble(element, spriteRect, displayBounds) { + const bubbleSize = { + width: element.offsetWidth, + height: element.offsetHeight, + }; + const pos = placeBubble(spriteRect, bubbleSize, displayBounds, CEILING_CLEARANCE); + element.style.left = `${pos.x}px`; + element.style.top = `${pos.y}px`; + element.classList.toggle("flipped", pos.flipped); + element.style.setProperty("--tail-offset", `${pos.tailOffset}px`); +} + +function latchBubbles() { + if (!latest) return; + + const dialogueChanged = latest.dialogue !== lastLatchedDialogue; + const thinkingChanged = latest.thinking !== lastLatchedThinking; + + if (!dialogueChanged && !thinkingChanged) { + return; + } + + lastLatchedDialogue = latest.dialogue; + lastLatchedThinking = latest.thinking; + + const spriteRect = { + x: latest.x, + y: latest.y, + width: latest.width, + height: latest.height, + }; + + const displayBounds = { + x: 0, + y: 0, + width: window.innerWidth, + height: window.innerHeight, + }; + + if (latest.dialogue && latest.visible) { + if (speechTimeout) clearTimeout(speechTimeout); + + const canvas = document.createElement("canvas"); + const ctx = canvas.getContext("2d"); + ctx.font = "14px system-ui, sans-serif"; + const lines = wrapText(latest.dialogue, 260, ctx.measureText.bind(ctx)); + bubbleContent.textContent = lines.join("\n"); + + bubble.classList.remove("hidden"); + bubble.classList.add("visible"); + + positionBubble(bubble, spriteRect, displayBounds); + + const duration = bubbleDuration(latest.dialogue); + const fadeMs = latest.fade_ms || 0; + speechTimeout = setTimeout(() => { + bubble.classList.remove("visible"); + setTimeout(() => bubble.classList.add("hidden"), fadeMs); + }, duration); + + clearThinkingBubble(); + } + + if (latest.thinking && latest.visible) { + if (!thinkingShown && !thinkingGraceTimeout) { + thinkingGraceTimeout = setTimeout(() => { + thinkingGraceTimeout = null; + if (latest?.thinking && latest?.visible) { + showThinkingBubble(spriteRect, displayBounds); + } + }, THINKING_GRACE_MS); + } + } else if (thinkingShown || thinkingGraceTimeout) { + if (thinkingGraceTimeout) { + clearTimeout(thinkingGraceTimeout); + thinkingGraceTimeout = null; + } else if (thinkingShown && !thinkingMinHoldTimeout) { + clearThinkingBubble(); + } + } +} + +function showThinkingBubble(spriteRect, displayBounds) { + thinkingBubble.classList.remove("hidden"); + thinkingBubble.classList.add("visible"); + thinkingShown = true; + + positionBubble(thinkingBubble, spriteRect, displayBounds); + + thinkingMinHoldTimeout = setTimeout(() => { + thinkingMinHoldTimeout = null; + if (!latest?.thinking) { + clearThinkingBubble(); + } + }, THINKING_MIN_HOLD_MS); +} + +function clearThinkingBubble() { + if (thinkingGraceTimeout) { + clearTimeout(thinkingGraceTimeout); + thinkingGraceTimeout = null; + } + if (thinkingMinHoldTimeout) { + clearTimeout(thinkingMinHoldTimeout); + thinkingMinHoldTimeout = null; + } + thinkingBubble.classList.remove("visible"); + const fadeMs = latest?.fade_ms || 0; + setTimeout(() => thinkingBubble.classList.add("hidden"), fadeMs); + thinkingShown = false; +} + async function start() { const character = await window.__TAURI__.core.invoke("character"); art = character.art; diff --git a/tests/bubble.test.js b/tests/bubble.test.js new file mode 100644 index 000000000..dac5d4e75 --- /dev/null +++ b/tests/bubble.test.js @@ -0,0 +1,96 @@ +// Run with `node --test tests/`. + +import assert from "node:assert/strict"; +import { test } from "node:test"; + +import { bubbleDuration, wrapText, placeBubble, CEILING_CLEARANCE } from "../src/bubble.js"; + +const testMeasureFn = (text) => ({ width: text.length * 8 }); + +test("bubble duration is 900ms + 55ms per character, clamped to 2-8s", () => { + assert.equal(bubbleDuration("hi"), 2000, "min clamp"); + assert.equal(bubbleDuration("hello"), 2000, "still at min"); + // "hello there" = 11 chars = 900 + 605 = 1505ms, clamped to 2000ms min + assert.equal(bubbleDuration("hello there"), 2000, "short text clamped to min"); + // Longer text that exceeds min + const medium = "a".repeat(30); + assert.equal(bubbleDuration(medium), 900 + 55 * 30, "base + per-char, no clamp"); + + const long = "a".repeat(200); + assert.equal(bubbleDuration(long), 8000, "max clamp"); +}); + +test("wrap text at max width", () => { + const short = "hi"; + const wrapped = wrapText(short, 260, testMeasureFn); + assert.equal(wrapped.length, 1); + assert.equal(wrapped[0], "hi"); +}); + +test("long text wraps at word boundaries", () => { + const text = "The quick brown fox jumps over the lazy dog"; + const wrapped = wrapText(text, 100, testMeasureFn); + assert.ok(wrapped.length > 1, "text should wrap"); + assert.ok(wrapped.every(line => line.length > 0), "no empty lines"); +}); + +test("text truncates with ellipsis past 6 lines", () => { + const manyLines = "line1\nline2\nline3\nline4\nline5\nline6\nline7\nline8"; + const wrapped = wrapText(manyLines, 260, testMeasureFn); + assert.ok(wrapped.length <= 6, "truncated to 6 lines"); + if (wrapped.length === 6) { + assert.ok(wrapped[5].endsWith("…"), "last line has ellipsis"); + } +}); + +test("bubble placement stays above sprite by default", () => { + const spriteRect = { x: 100, y: 400, width: 64, height: 64 }; + const bubbleSize = { width: 200, height: 100 }; + const displayBounds = { x: 0, y: 0, width: 1000, height: 800 }; + + const pos = placeBubble(spriteRect, bubbleSize, displayBounds, CEILING_CLEARANCE); + + assert.ok(pos.y < spriteRect.y, "bubble is above sprite"); + assert.ok(pos.x >= displayBounds.x, "bubble is within display left"); + assert.ok(pos.x + bubbleSize.width <= displayBounds.x + displayBounds.width, "bubble is within display right"); + assert.equal(pos.flipped, false, "not flipped when above"); + assert.equal(pos.tailOffset, 0, "tail centered when bubble not clamped"); +}); + +test("bubble flips below sprite when near ceiling", () => { + const spriteRect = { x: 100, y: 50, width: 64, height: 64 }; + const bubbleSize = { width: 200, height: 100 }; + const displayBounds = { x: 0, y: 0, width: 1000, height: 800 }; + + const pos = placeBubble(spriteRect, bubbleSize, displayBounds, CEILING_CLEARANCE); + + assert.ok(pos.y > spriteRect.y + spriteRect.height, "bubble flips below when near ceiling"); + assert.equal(pos.flipped, true, "flipped flag is true"); +}); + +test("bubble slides horizontally at display edges", () => { + const spriteNearLeftEdge = { x: 10, y: 400, width: 64, height: 64 }; + const bubbleSize = { width: 200, height: 100 }; + const displayBounds = { x: 0, y: 0, width: 1000, height: 800 }; + + const pos = placeBubble(spriteNearLeftEdge, bubbleSize, displayBounds, CEILING_CLEARANCE); + + assert.ok(pos.x >= displayBounds.x, "bubble clamped to left edge"); + assert.ok(pos.x + bubbleSize.width <= displayBounds.x + displayBounds.width, "bubble within right bound"); + assert.equal(typeof pos.flipped, "boolean", "flipped flag is present"); + const spriteCenterX = spriteNearLeftEdge.x + spriteNearLeftEdge.width / 2; + const bubbleCenterX = pos.x + bubbleSize.width / 2; + assert.equal(pos.tailOffset, spriteCenterX - bubbleCenterX, "tail offset points to sprite"); +}); + +test("bubble stays whole across display seam", () => { + const spriteAtSeam = { x: 995, y: 400, width: 64, height: 64 }; + const bubbleSize = { width: 200, height: 100 }; + const displayBounds = { x: 0, y: 0, width: 1000, height: 800 }; + + const pos = placeBubble(spriteAtSeam, bubbleSize, displayBounds, CEILING_CLEARANCE); + + assert.ok(pos.x >= displayBounds.x, "bubble not past left edge"); + assert.ok(pos.x + bubbleSize.width <= displayBounds.x + displayBounds.width, "bubble not past right edge"); + assert.equal(typeof pos.flipped, "boolean", "flipped flag is present"); +});