Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -70,6 +70,12 @@ pnpm --dir packages/live2d dev
## 自定义配置
> 此部分内容建议初步尝试过 Live2d 的用户观看。

### 移动端显示

在 `插件设置 -> 基本设置 -> 在移动端显示` 中,可以控制手机和平板是否显示看板娘。此项默认开启,升级后保持原有显示行为。关闭后,移动端不会初始化看板娘或加载渲染模块、模型资源,桌面端仍正常显示;保存设置后刷新前台页面生效。

移动端按浏览器设备信息识别,不按窗口宽度判断,因此桌面浏览器缩窄窗口不会触发此开关。

### 自定义 Live2d 接口
若主题内置接口不满足用户使用,可以参考 [live2d_api](https://github.com/fghrsh/live2d_api) 自行开发接口。

Expand Down
71 changes: 71 additions & 0 deletions packages/live2d/src/__tests__/halo.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,71 @@
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";

const { loadRuntime, createLive2d, init } = vi.hoisted(() => {
const init = vi.fn();
return {
init,
loadRuntime: vi.fn(),
createLive2d: vi.fn(() => ({ init })),
};
});

vi.mock("@vitejs/plugin-react/preamble", () => ({}));

describe("Halo mobile visibility bootstrap", () => {
beforeEach(() => {
vi.resetModules();
vi.clearAllMocks();
vi.doMock("../live2d/runtime", () => {
loadRuntime();
return { createLive2d };
});
document.body.replaceChildren();
window.live2d = undefined;
});

afterEach(() => {
document.body.replaceChildren();
window.live2d = undefined;
vi.restoreAllMocks();
});

it.each([
["iPhone", false, false],
["Android", true, true],
["iPhone", undefined, true],
["iPhone", "false", true],
["Mozilla/5.0 (Windows NT 10.0; Win64; x64)", false, true],
])(
"bootstraps %s with showOnMobile=%s: %s",
async (userAgent, showOnMobile, expected) => {
vi.spyOn(navigator, "userAgent", "get").mockReturnValue(userAgent);
const config = {
assetPath: "/plugins/PluginLive2d/assets/static/",
showOnMobile,
};
const configElement = document.createElement("script");
configElement.id = "plugin-live2d-config";
configElement.type = "application/json";
configElement.textContent = JSON.stringify(config);
document.body.append(configElement);

const { bootstrapFromHalo } = await import("../halo");
await bootstrapFromHalo();
// Repeat callers must not load or initialize a second runtime.
await bootstrapFromHalo();

expect(loadRuntime).toHaveBeenCalledTimes(expected ? 1 : 0);
expect(createLive2d).toHaveBeenCalledTimes(expected ? 1 : 0);
expect(init).toHaveBeenCalledTimes(expected ? 1 : 0);
if (expected) {
expect(init).toHaveBeenCalledWith(
config.assetPath,
JSON.parse(JSON.stringify(config)),
);
} else {
expect(window.live2d).toBeUndefined();
expect(document.getElementById("plugin-live2d-root")).toBeNull();
}
},
);
});
56 changes: 42 additions & 14 deletions packages/live2d/src/components/Live2dCanvas.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ import { DESKTOP_LIVE2D_CANVAS_SIZE } from "@/live2d/utils/responsive";
import { consume } from "@lit/context";
import { type PropertyValues, type TemplateResult, html } from "lit";
import { property, query, state } from "lit/decorators.js";
import { keyed } from "lit/directives/keyed.js";

export class Live2dCanvas extends UnoLitElement {
@consume({ context: configContext })
Expand All @@ -31,21 +32,34 @@ export class Live2dCanvas extends UnoLitElement {

private _modelInitialized = false;

@state()
private _canvasGeneration = 0;

render(): TemplateResult {
return html`
<canvas id="live2d" class="block h-full w-full cursor-grab"></canvas>
${keyed(
this._canvasGeneration,
html`<canvas id="live2d" class="block h-full w-full cursor-grab"></canvas>`,
)}
`;
}

connectedCallback(): void {
super.connectedCallback();
window.dispatchEvent(new BeforeInitEvent({ config: this.config }));
if (this.hasUpdated) {
void this.updateComplete.then(() => this.initializeModel());
}
}

disconnectedCallback(): void {
super.disconnectedCallback();
clearCurrentLive2dModel(this.model);
this.model?.destroy();
// Reconnecting must not reuse a canvas still owned by an old renderer.
this._canvasGeneration++;
if (this.model) {
clearCurrentLive2dModel(this.model);
this.model.destroy();
}
this.model = null;
this._modelInitialized = false;
}
Expand All @@ -70,25 +84,39 @@ export class Live2dCanvas extends UnoLitElement {
}

private async initializeModel(): Promise<void> {
if (!this.config || !this._live2d || this._modelInitialized) {
if (
!this.isConnected ||
!this.config ||
!this._live2d ||
this._modelInitialized
) {
return;
}

this._modelInitialized = true;
const canvasGeneration = this._canvasGeneration;
let model: Model | undefined;

try {
const initialCanvasSize = this.canvasSize;
this.model = await Model.create(
this._live2d,
this.config,
initialCanvasSize,
);
if (initialCanvasSize !== this.canvasSize) {
await this.model.resize(this.canvasSize);
let canvasSize = this.canvasSize;
model = await Model.create(this._live2d, this.config, canvasSize);
while (true) {
if (!this.isConnected || canvasGeneration !== this._canvasGeneration) {
model.destroy();
return;
}
if (canvasSize === this.canvasSize) break;
canvasSize = this.canvasSize;
await model.resize(canvasSize);
}
setCurrentLive2dModel(this.model);
window.dispatchEvent(new ModelReadyEvent({ model: this.model }));
this.model = model;
setCurrentLive2dModel(model);
window.dispatchEvent(new ModelReadyEvent({ model }));
} catch (error) {
model?.destroy();
if (canvasGeneration !== this._canvasGeneration) {
return;
}
this._modelInitialized = false;
throw error;
}
Expand Down
193 changes: 193 additions & 0 deletions packages/live2d/src/components/__tests__/Live2dCanvas.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,193 @@
import type { Live2dCanvas } from "@/live2d/components/Live2dCanvas";
import { createDefaultLive2dConfig } from "@/live2d/config/default-config";
import { MODEL_READY_EVENT_NAME } from "@/live2d/events/model-ready";
import Model from "@/live2d/live2d/model";
import {
clearCurrentLive2dModel,
getCurrentLive2dModel,
} from "@/live2d/live2d/model-store";
import { createLive2d } from "@/live2d/live2d/runtime";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import "../Live2dCanvas";

vi.mock("@/live2d/live2d/model", () => ({
default: { create: vi.fn() },
}));
vi.mock("@/live2d/components/Live2dContext", () => ({}));

const deferred = <T>() => {
let resolve!: (value: T) => void;
const promise = new Promise<T>((resolvePromise) => {
resolve = resolvePromise;
});
return { promise, resolve };
};

const createModel = () =>
({
destroy: vi.fn(),
resize: vi.fn().mockResolvedValue(undefined),
}) as unknown as Model;

const mountCanvas = async (parent: HTMLElement = document.body) => {
const canvas = document.createElement("live2d-canvas") as Live2dCanvas;
canvas.config = createDefaultLive2dConfig();
parent.append(canvas);
await canvas.updateComplete;
return canvas;
};

describe("Live2dCanvas model lifecycle", () => {
const onReady = vi.fn();

beforeEach(() => {
clearCurrentLive2dModel();
vi.mocked(Model.create).mockReset();
onReady.mockClear();
window.addEventListener(MODEL_READY_EVENT_NAME, onReady);
});

afterEach(() => {
document.body.replaceChildren();
window.removeEventListener(MODEL_READY_EVENT_NAME, onReady);
clearCurrentLive2dModel();
vi.restoreAllMocks();
});

it("publishes a loaded model and destroys it when disconnected", async () => {
const model = createModel();
vi.mocked(Model.create).mockResolvedValue(model);
const canvas = await mountCanvas();
await vi.waitFor(() => expect(canvas.getModel()).toBe(model));

expect(getCurrentLive2dModel()).toBe(model);
expect(onReady).toHaveBeenCalledOnce();
canvas.remove();
expect(model.destroy).toHaveBeenCalledOnce();
expect(canvas.getModel()).toBeNull();
expect(getCurrentLive2dModel()).toBeNull();
});

it("disposes a model that finishes loading after mobile display is disabled", async () => {
vi.spyOn(navigator, "userAgent", "get").mockReturnValue("iPhone");
const pending = deferred<Model>();
const model = createModel();
vi.mocked(Model.create).mockReturnValue(pending.promise);
const runtime = createLive2d();
runtime.init("/assets/", { showOnMobile: true });
const root = document.getElementById("plugin-live2d-root");
expect(root).not.toBeNull();
if (!root) throw new Error("Expected the runtime to mount a root");
const canvas = await mountCanvas(root);
expect(Model.create).toHaveBeenCalledOnce();

runtime.init("/assets/", { showOnMobile: false });
expect(canvas.isConnected).toBe(false);
pending.resolve(model);
await vi.waitFor(() => expect(model.destroy).toHaveBeenCalledOnce());

expect(canvas.getModel()).toBeNull();
expect(getCurrentLive2dModel()).toBeNull();
expect(onReady).not.toHaveBeenCalled();
});

it("preserves another canvas's active model when an unloaded canvas disconnects", async () => {
const pending = deferred<Model>();
const activeModel = createModel();
const lateModel = createModel();
vi.mocked(Model.create)
.mockResolvedValueOnce(activeModel)
.mockReturnValueOnce(pending.promise);
const activeCanvas = await mountCanvas();
await vi.waitFor(() => expect(activeCanvas.getModel()).toBe(activeModel));
const loadingCanvas = await mountCanvas();

loadingCanvas.remove();
expect(getCurrentLive2dModel()).toBe(activeModel);
pending.resolve(lateModel);
await vi.waitFor(() => expect(lateModel.destroy).toHaveBeenCalledOnce());
expect(getCurrentLive2dModel()).toBe(activeModel);
expect(activeModel.destroy).not.toHaveBeenCalled();
expect(onReady).toHaveBeenCalledOnce();
});

it("reconnects with a fresh canvas and discards the earlier pending model", async () => {
const pending = deferred<Model>();
const lateModel = createModel();
const currentModel = createModel();
vi.mocked(Model.create)
.mockReturnValueOnce(pending.promise)
.mockResolvedValueOnce(currentModel);
const canvas = await mountCanvas();
canvas.remove();
document.body.append(canvas);
await vi.waitFor(() => expect(canvas.getModel()).toBe(currentModel));
expect(vi.mocked(Model.create).mock.calls[0][0]).not.toBe(
vi.mocked(Model.create).mock.calls[1][0],
);
pending.resolve(lateModel);
await vi.waitFor(() => expect(lateModel.destroy).toHaveBeenCalledOnce());
expect(canvas.getModel()).toBe(currentModel);
expect(getCurrentLive2dModel()).toBe(currentModel);
expect(currentModel.destroy).not.toHaveBeenCalled();
expect(onReady).toHaveBeenCalledOnce();
});

it("resizes a loading model to the latest canvas size before publishing it", async () => {
const pending = deferred<Model>();
const model = createModel();
vi.mocked(Model.create).mockReturnValue(pending.promise);
const canvas = await mountCanvas();
canvas.canvasSize = 240;
await canvas.updateComplete;
pending.resolve(model);

await vi.waitFor(() => expect(canvas.getModel()).toBe(model));
expect(model.resize).toHaveBeenCalledWith(240);
expect(getCurrentLive2dModel()).toBe(model);
canvas.canvasSize = 300;
await canvas.updateComplete;
expect(model.resize).toHaveBeenLastCalledWith(300);
});

it("disposes a model disconnected while its initial resize is pending", async () => {
const pending = deferred<Model>();
const resizing = deferred<void>();
const model = createModel();
vi.mocked(model.resize).mockReturnValue(resizing.promise);
vi.mocked(Model.create).mockReturnValue(pending.promise);
const canvas = await mountCanvas();
canvas.canvasSize = 240;
await canvas.updateComplete;
pending.resolve(model);
await vi.waitFor(() => expect(model.resize).toHaveBeenCalledOnce());

canvas.remove();
resizing.resolve();
await vi.waitFor(() => expect(model.destroy).toHaveBeenCalledOnce());
expect(canvas.getModel()).toBeNull();
expect(getCurrentLive2dModel()).toBeNull();
expect(onReady).not.toHaveBeenCalled();
});

it("applies further size changes while the initial resize is pending", async () => {
const pending = deferred<Model>();
const resizing = deferred<void>();
const model = createModel();
vi.mocked(model.resize).mockReturnValueOnce(resizing.promise);
vi.mocked(Model.create).mockReturnValue(pending.promise);
const canvas = await mountCanvas();
canvas.canvasSize = 240;
await canvas.updateComplete;
pending.resolve(model);
await vi.waitFor(() => expect(model.resize).toHaveBeenCalledWith(240));

canvas.canvasSize = 300;
await canvas.updateComplete;
resizing.resolve();
await vi.waitFor(() => expect(canvas.getModel()).toBe(model));
expect(model.resize).toHaveBeenLastCalledWith(300);
expect(getCurrentLive2dModel()).toBe(model);
expect(onReady).toHaveBeenCalledOnce();
});
});
1 change: 1 addition & 0 deletions packages/live2d/src/config/default-config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ export const DEFAULT_TOOL_NAMES = [
] as const;

export const createDefaultLive2dConfig = (): Live2dConfig => ({
showOnMobile: true,
apiPath: "https://live2d.fghrsh.net/api/",
live2dLocation: "left",
consoleShowStatus: import.meta.env.DEV ?? false,
Expand Down
1 change: 1 addition & 0 deletions packages/live2d/src/config/normalize-config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -92,6 +92,7 @@ export const normalizeLive2dConfig = (
return {
...defaults,
...input,
showOnMobile: pickBoolean(input.showOnMobile, defaults.showOnMobile),
apiPath: ensureTrailingSlash(normalizedApiPath),
live2dLocation: input.live2dLocation === "right" ? "right" : "left",
consoleShowStatus: pickBoolean(
Expand Down
Loading
Loading