From 9af31424809e436418911377c88c7ce5aa222efe Mon Sep 17 00:00:00 2001 From: LIlGG <1103069291@qq.com> Date: Thu, 22 Oct 2026 17:18:20 +0800 Subject: [PATCH] fix: keep long Live2D messages within the viewport --- packages/live2d/src/components/Live2dTips.tsx | 125 ++++++++- .../__tests__/Live2dTipsViewport.test.ts | 246 ++++++++++++++++++ packages/live2d/src/mixins/draggable.ts | 1 + packages/live2d/src/styles/unocss.global.css | 20 ++ 4 files changed, 388 insertions(+), 4 deletions(-) create mode 100644 packages/live2d/src/components/__tests__/Live2dTipsViewport.test.ts diff --git a/packages/live2d/src/components/Live2dTips.tsx b/packages/live2d/src/components/Live2dTips.tsx index 6a4f8c3..2e54f50 100644 --- a/packages/live2d/src/components/Live2dTips.tsx +++ b/packages/live2d/src/components/Live2dTips.tsx @@ -17,7 +17,7 @@ import { import { isNotEmpty } from "@/live2d/utils/isNotEmpty"; import { randomSelection } from "@/live2d/utils/randomSelection"; import { consume } from "@lit/context"; -import { type TemplateResult, html } from "lit"; +import { type PropertyValues, type TemplateResult, html } from "lit"; import { property, state } from "lit/decorators.js"; import { classMap } from "lit/directives/class-map.js"; import { unsafeHTML } from "lit/directives/unsafe-html.js"; @@ -26,6 +26,7 @@ export class Live2dTips extends UnoLitElement { private static readonly DEFAULT_BOTTOM_OFFSET = 250; private static readonly MODEL_OVERLAP_OFFSET = 20; private static readonly OPACITY_TRANSITION_MS = 1000; + private static readonly VIEWPORT_MARGIN = 12; @consume({ context: configContext }) @property({ attribute: false }) @@ -44,6 +45,10 @@ export class Live2dTips extends UnoLitElement { private messageTimer: number | null = null; private streamModeResetTimer: number | null = null; private streamInactivityTimeout = 60_000; + private followStream = false; + private positionFrame?: number; + private resizeObserver?: ResizeObserver; + private positionObserver?: MutationObserver; // 流式消息模式标志 @state() private isStreamMode = false; @@ -87,16 +92,16 @@ export class Live2dTips extends UnoLitElement { "rounded-xl": true, "shadow-tips": true, "text-size-sm": true, - "overflow-hidden": true, + "live2d-tips-content": true, "px-2.5": true, "py-1.5": true, - "text-ellipsis": true, "transition-opacity-1000": true, "break-all": true, "live2d-tips-markdown": isMarkdownBlock, "opacity-100": this._isShow, "opacity-0": !this._isShow, - "select-none": true, + "pointer-events-auto": this._isShow, + "pointer-events-none": !this._isShow, }; const width = this.compact ? "min(220px, calc(100vw - 1rem))" @@ -106,6 +111,12 @@ export class Live2dTips extends UnoLitElement { id="live2d-tips" class=${classMap(classes)} style="width: ${width};" + role="region" + aria-label="看板娘消息" + aria-hidden=${!this._isShow} + tabindex=${this._isShow ? 0 : -1} + ?inert=${!this._isShow} + @scroll=${this.handleContentScroll} > ${unsafeHTML(renderedMessage)} @@ -114,12 +125,32 @@ export class Live2dTips extends UnoLitElement { connectedCallback(): void { super.connectedCallback(); + this.style.zIndex = "2"; this.applyHostPosition(); window.addEventListener("live2d:send-message", this.onMessage); window.addEventListener("live2d:stream-message-start", this.onStreamStart); window.addEventListener("live2d:stream-message", this.onStreamMessage); window.addEventListener("live2d:stream-message-stop", this.onStreamStop); window.addEventListener("live2d:model-layout", this.onModelLayout); + window.addEventListener("resize", this.schedulePosition); + window.visualViewport?.addEventListener("resize", this.schedulePosition); + window.visualViewport?.addEventListener("scroll", this.schedulePosition); + this.shadowRoot?.addEventListener("load", this.handleContentLoad, true); + if (typeof ResizeObserver !== "undefined") { + this.resizeObserver = new ResizeObserver(this.schedulePosition); + this.resizeObserver.observe(this); + } + const root = this.getRootNode(); + const widget = + root instanceof ShadowRoot ? root.getElementById("live2d-plugin") : null; + if (widget) { + this.resizeObserver?.observe(widget); + this.positionObserver = new MutationObserver(this.schedulePosition); + this.positionObserver.observe(widget, { + attributes: true, + attributeFilter: ["style", "class"], + }); + } } disconnectedCallback(): void { @@ -134,6 +165,33 @@ export class Live2dTips extends UnoLitElement { window.removeEventListener("live2d:model-layout", this.onModelLayout); this.clearMessageTimer(); this.clearStreamModeResetTimer(); + window.removeEventListener("resize", this.schedulePosition); + window.visualViewport?.removeEventListener("resize", this.schedulePosition); + window.visualViewport?.removeEventListener("scroll", this.schedulePosition); + this.shadowRoot?.removeEventListener("load", this.handleContentLoad, true); + this.resizeObserver?.disconnect(); + this.positionObserver?.disconnect(); + if (this.positionFrame !== undefined) { + window.cancelAnimationFrame(this.positionFrame); + this.positionFrame = undefined; + } + } + + protected updated(changed: PropertyValues): void { + super.updated(changed); + const content = this.shadowRoot?.getElementById("live2d-tips"); + if (content && changed.has("_message") && this.followStream) { + content.scrollTop = content.scrollHeight; + } + const focused = this.shadowRoot?.activeElement; + if ( + !this._isShow && + focused instanceof HTMLElement && + content?.contains(focused) + ) { + focused.blur(); + } + this.schedulePosition(); } handleMessage(e: SendMessageEvent): void { @@ -155,6 +213,9 @@ export class Live2dTips extends UnoLitElement { return; } this.priority = priority; + this.followStream = false; + const content = this.shadowRoot?.getElementById("live2d-tips"); + if (content) content.scrollTop = 0; this.isStreamMode = false; this._message = message; this._isShow = true; @@ -173,6 +234,7 @@ export class Live2dTips extends UnoLitElement { this.clearStreamModeResetTimer(); this.priority = STREAM_PRIORITY; this.isStreamMode = true; + this.followStream = true; this.streamInactivityTimeout = timeout; // 清空消息并显示 @@ -190,6 +252,7 @@ export class Live2dTips extends UnoLitElement { return; } const { text } = e.detail; + if (e.detail.mode === "replace") this.followStream = true; this.scheduleStreamInactivityTimeout(this.streamInactivityTimeout); if (e.detail.mode === "replace") { this._message = text; @@ -227,6 +290,60 @@ export class Live2dTips extends UnoLitElement { private applyHostPosition(): void { this.style.bottom = `${this._bottomOffset}px`; + this.schedulePosition(); + } + + private readonly handleContentScroll = (event: Event): void => { + const content = event.currentTarget as HTMLElement; + this.followStream = + content.scrollHeight - content.scrollTop - content.clientHeight <= 24; + }; + + private readonly handleContentLoad = (): void => { + const content = this.shadowRoot?.getElementById("live2d-tips"); + if (content && this._isShow && this.isStreamMode && this.followStream) { + content.scrollTop = content.scrollHeight; + } + this.schedulePosition(); + }; + + private readonly schedulePosition = (): void => { + if (!this.isConnected || !this._isShow || this.positionFrame !== undefined) + return; + this.positionFrame = window.requestAnimationFrame(() => { + this.positionFrame = undefined; + this.keepInViewport(); + }); + }; + + private keepInViewport(): void { + const content = this.shadowRoot?.getElementById("live2d-tips"); + if (!content || !this.isConnected || !this._isShow) return; + const viewport = window.visualViewport; + const width = viewport?.width ?? window.innerWidth; + const height = viewport?.height ?? window.innerHeight; + const left = (viewport?.offsetLeft ?? 0) + Live2dTips.VIEWPORT_MARGIN; + const top = (viewport?.offsetTop ?? 0) + Live2dTips.VIEWPORT_MARGIN; + content.style.maxWidth = `${Math.max(0, width - 2 * Live2dTips.VIEWPORT_MARGIN)}px`; + content.style.maxHeight = `min(20rem, ${Math.max(0, height - 2 * Live2dTips.VIEWPORT_MARGIN)}px)`; + // Measure the model's original anchor again so dragging back restores it. + this.style.translate = "0px 0px"; + const rect = this.getBoundingClientRect(); + const x = Math.max( + left, + Math.min( + rect.left, + left + width - 2 * Live2dTips.VIEWPORT_MARGIN - rect.width, + ), + ); + const y = Math.max( + top, + Math.min( + rect.top, + top + height - 2 * Live2dTips.VIEWPORT_MARGIN - rect.height, + ), + ); + this.style.translate = `${x - rect.left}px ${y - rect.top}px`; } private clearMessageTimer(): void { diff --git a/packages/live2d/src/components/__tests__/Live2dTipsViewport.test.ts b/packages/live2d/src/components/__tests__/Live2dTipsViewport.test.ts new file mode 100644 index 0000000..5dbdef2 --- /dev/null +++ b/packages/live2d/src/components/__tests__/Live2dTipsViewport.test.ts @@ -0,0 +1,246 @@ +import { SendMessageEvent } from "@/live2d/events/send-message"; +import { + StreamMessageEvent, + StreamMessageStartEvent, + StreamMessageStopEvent, +} from "@/live2d/events/stream-message"; +import { DraggableMixin } from "@/live2d/mixins/draggable"; +import { LitElement, html } from "lit"; +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; +import type { Live2dTips } from "../Live2dTips"; +import "../Live2dTips"; + +class DraggableTipsFixture extends DraggableMixin(LitElement, { + storageKey: "tips-test", + targetSelector: "#widget", +}) { + render() { + return html`
Model
`; + } +} +customElements.define("draggable-tips-fixture", DraggableTipsFixture); + +let frames: Map; +let nextFrame: number; + +beforeEach(() => { + vi.useFakeTimers(); + frames = new Map(); + nextFrame = 0; + vi.stubGlobal( + "requestAnimationFrame", + vi.fn((callback: FrameRequestCallback) => { + frames.set(++nextFrame, callback); + return nextFrame; + }), + ); + vi.stubGlobal( + "cancelAnimationFrame", + vi.fn((id: number) => frames.delete(id)), + ); + vi.stubGlobal("innerWidth", 390); + vi.stubGlobal("innerHeight", 844); +}); + +afterEach(() => { + document.body.replaceChildren(); + vi.useRealTimers(); + vi.restoreAllMocks(); + vi.unstubAllGlobals(); +}); + +async function createTips() { + const tips = document.createElement("live2d-tips") as Live2dTips; + document.body.append(tips); + await tips.updateComplete; + const content = tips.shadowRoot?.getElementById("live2d-tips"); + if (!content) throw new Error("Missing message content"); + return { tips, content }; +} + +function message(text: string, timeout = 10_000) { + window.dispatchEvent(new SendMessageEvent({ text, timeout, priority: 10 })); +} + +function startStream() { + window.dispatchEvent(new StreamMessageStartEvent({ timeout: 60_000 })); +} + +function flushFrames() { + const pending = [...frames.values()]; + frames.clear(); + for (const callback of pending) callback(0); +} + +describe("Live2dTips long messages", () => { + it("keeps the complete message in a keyboard-accessible region while visible", async () => { + const { tips, content } = await createTips(); + const text = "长回复内容。".repeat(160); + message(text); + await tips.updateComplete; + expect(content.textContent?.trim()).toBe(text); + expect(content.getAttribute("role")).toBe("region"); + expect(content.tabIndex).toBe(0); + expect(content.classList.contains("pointer-events-auto")).toBe(true); + expect(content.getAttribute("aria-hidden")).toBe("false"); + }); + + it("disables interaction and releases focus when the message expires", async () => { + const { tips, content } = await createTips(); + message("消息", 50); + await tips.updateComplete; + content.focus(); + expect(tips.shadowRoot?.activeElement).toBe(content); + await vi.advanceTimersByTimeAsync(50); + await tips.updateComplete; + expect(content.tabIndex).toBe(-1); + expect(content.classList.contains("pointer-events-none")).toBe(true); + expect(content.getAttribute("aria-hidden")).toBe("true"); + expect(tips.shadowRoot?.activeElement).not.toBe(content); + }); + + it("follows appended output only while the reader remains at the end", async () => { + const { tips, content } = await createTips(); + startStream(); + await tips.updateComplete; + Object.defineProperty(content, "scrollHeight", { + value: 1000, + configurable: true, + }); + Object.defineProperty(content, "clientHeight", { value: 200 }); + content.scrollTop = 800; + window.dispatchEvent(new StreamMessageEvent({ text: "第一段" })); + await tips.updateComplete; + expect(content.scrollTop).toBe(1000); + + content.scrollTop = 100; + content.dispatchEvent(new Event("scroll")); + window.dispatchEvent(new StreamMessageEvent({ text: "第二段" })); + await tips.updateComplete; + expect(content.scrollTop).toBe(100); + expect(content.textContent).toContain("第一段第二段"); + + window.dispatchEvent( + new StreamMessageEvent({ text: "新回复", mode: "replace" }), + ); + await tips.updateComplete; + expect(content.scrollTop).toBe(1000); + }); + + it("follows asynchronously loaded Markdown images unless the reader scrolls up", async () => { + const { tips, content } = await createTips(); + startStream(); + window.dispatchEvent( + new StreamMessageEvent({ text: "![图片](/sample.png)" }), + ); + await tips.updateComplete; + const image = content.querySelector("img"); + Object.defineProperty(content, "scrollHeight", { + value: 1000, + configurable: true, + }); + Object.defineProperty(content, "clientHeight", { value: 200 }); + image?.dispatchEvent(new Event("load")); + expect(content.scrollTop).toBe(1000); + content.scrollTop = 100; + content.dispatchEvent(new Event("scroll")); + Object.defineProperty(content, "scrollHeight", { value: 2000 }); + image?.dispatchEvent(new Event("load")); + expect(content.scrollTop).toBe(100); + }); + + it("makes hidden Markdown links inert and releases their focus", async () => { + const { tips, content } = await createTips(); + startStream(); + window.dispatchEvent( + new StreamMessageEvent({ text: "[链接](https://example.com)" }), + ); + await tips.updateComplete; + const link = content.querySelector("a"); + link?.focus(); + expect(tips.shadowRoot?.activeElement).toBe(link); + window.dispatchEvent(new StreamMessageStopEvent({ showTimeout: 50 })); + await vi.advanceTimersByTimeAsync(50); + await tips.updateComplete; + expect(content.hasAttribute("inert")).toBe(true); + expect(tips.shadowRoot?.activeElement).not.toBe(link); + }); + + it("resets scrolling for a new ordinary message", async () => { + const { tips, content } = await createTips(); + content.scrollTop = 200; + message("新消息"); + await tips.updateComplete; + expect(content.scrollTop).toBe(0); + }); + + it("keeps a displaced bubble inside the viewport and restores its model anchor", async () => { + const { tips, content } = await createTips(); + const bounds = vi + .spyOn(tips, "getBoundingClientRect") + .mockReturnValue(new DOMRect(-30, -200, 220, 320)); + message("长回复"); + await tips.updateComplete; + flushFrames(); + expect(tips.style.translate).toBe("42px 212px"); + expect(content.style.maxWidth).toBe("366px"); + + bounds.mockReturnValue(new DOMRect(20, 400, 220, 320)); + window.dispatchEvent(new Event("resize")); + flushFrames(); + expect(tips.style.translate).toBe("0px 0px"); + + window.innerHeight = 500; + window.dispatchEvent(new Event("resize")); + flushFrames(); + expect(tips.style.translate).toBe("0px -232px"); + }); + + it("cancels pending layout and removes viewport listeners on disconnect", async () => { + const { tips } = await createTips(); + message("消息"); + await tips.updateComplete; + expect(frames.size).toBe(1); + tips.remove(); + expect(frames.size).toBe(0); + window.dispatchEvent(new Event("resize")); + expect(frames.size).toBe(0); + }); + + it("allows reading gestures inside the bubble without dragging the widget", async () => { + const fixture = document.createElement( + "draggable-tips-fixture", + ) as DraggableTipsFixture; + document.body.append(fixture); + await fixture.updateComplete; + const tips = fixture.shadowRoot?.querySelector("live2d-tips") as Live2dTips; + await tips.updateComplete; + const content = tips.shadowRoot?.getElementById("live2d-tips"); + const down = new MouseEvent("mousedown", { + bubbles: true, + composed: true, + cancelable: true, + button: 0, + }); + content?.dispatchEvent(down); + document.dispatchEvent( + new MouseEvent("mousemove", { clientX: 40, clientY: 40 }), + ); + expect(down.defaultPrevented).toBe(false); + expect(document.getElementById("live2d-drag-overlay")).toBeNull(); + + const modelDown = new MouseEvent("mousedown", { + bubbles: true, + composed: true, + cancelable: true, + button: 0, + }); + fixture.shadowRoot?.getElementById("model")?.dispatchEvent(modelDown); + document.dispatchEvent( + new MouseEvent("mousemove", { clientX: 40, clientY: 40 }), + ); + expect(modelDown.defaultPrevented).toBe(true); + expect(document.getElementById("live2d-drag-overlay")).not.toBeNull(); + document.dispatchEvent(new MouseEvent("mouseup")); + }); +}); diff --git a/packages/live2d/src/mixins/draggable.ts b/packages/live2d/src/mixins/draggable.ts index d7c4c25..a28601e 100644 --- a/packages/live2d/src/mixins/draggable.ts +++ b/packages/live2d/src/mixins/draggable.ts @@ -295,6 +295,7 @@ export const DraggableMixin = ( // 检查是否在工具栏内部 if ( el.closest("#live2d-tools") || + el.closest("#live2d-tips") || el.closest("#live2d-chat-input") || el.closest("#live2d-chat-send") ) { diff --git a/packages/live2d/src/styles/unocss.global.css b/packages/live2d/src/styles/unocss.global.css index 1f7aefc..a6506e7 100644 --- a/packages/live2d/src/styles/unocss.global.css +++ b/packages/live2d/src/styles/unocss.global.css @@ -1,5 +1,25 @@ @unocss; +.live2d-tips-content { + max-height: min(20rem, calc(100dvh - 1.5rem)); + overflow-x: hidden; + overflow-y: auto; + overscroll-behavior: contain; +} + +.live2d-tips-markdown :is(img, table) { + max-width: 100%; +} + +.live2d-tips-markdown table { + display: block; + overflow-x: auto; +} + +.live2d-tips-markdown img { + height: auto; +} + .live2d-tips-markdown { text-align: left; line-height: 1.55;