diff --git a/README.md b/README.md
index 00c56af..b9c10db 100644
--- a/README.md
+++ b/README.md
@@ -70,6 +70,12 @@ pnpm --dir packages/live2d dev
## 自定义配置
> 此部分内容建议初步尝试过 Live2d 的用户观看。
+### 移动端显示
+
+在 `插件设置 -> 基本设置 -> 在移动端显示` 中,可以控制手机和平板是否显示看板娘。此项默认开启,升级后保持原有显示行为。关闭后,移动端不会初始化看板娘或加载渲染模块、模型资源,桌面端仍正常显示;保存设置后刷新前台页面生效。
+
+移动端按浏览器设备信息识别,不按窗口宽度判断,因此桌面浏览器缩窄窗口不会触发此开关。
+
### 自定义 Live2d 接口
若主题内置接口不满足用户使用,可以参考 [live2d_api](https://github.com/fghrsh/live2d_api) 自行开发接口。
diff --git a/packages/live2d/src/__tests__/halo.test.ts b/packages/live2d/src/__tests__/halo.test.ts
new file mode 100644
index 0000000..ad25492
--- /dev/null
+++ b/packages/live2d/src/__tests__/halo.test.ts
@@ -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();
+ }
+ },
+ );
+});
diff --git a/packages/live2d/src/components/Live2dCanvas.tsx b/packages/live2d/src/components/Live2dCanvas.tsx
index 7e79dab..dec7b62 100644
--- a/packages/live2d/src/components/Live2dCanvas.tsx
+++ b/packages/live2d/src/components/Live2dCanvas.tsx
@@ -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 })
@@ -31,21 +32,34 @@ export class Live2dCanvas extends UnoLitElement {
private _modelInitialized = false;
+ @state()
+ private _canvasGeneration = 0;
+
render(): TemplateResult {
return html`
-
+ ${keyed(
+ this._canvasGeneration,
+ html``,
+ )}
`;
}
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;
}
@@ -70,25 +84,39 @@ export class Live2dCanvas extends UnoLitElement {
}
private async initializeModel(): Promise {
- 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;
}
diff --git a/packages/live2d/src/components/__tests__/Live2dCanvas.test.ts b/packages/live2d/src/components/__tests__/Live2dCanvas.test.ts
new file mode 100644
index 0000000..3c498a6
--- /dev/null
+++ b/packages/live2d/src/components/__tests__/Live2dCanvas.test.ts
@@ -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 = () => {
+ let resolve!: (value: T) => void;
+ const promise = new Promise((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();
+ 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();
+ 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();
+ 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();
+ 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();
+ const resizing = deferred();
+ 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();
+ const resizing = deferred();
+ 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();
+ });
+});
diff --git a/packages/live2d/src/config/default-config.ts b/packages/live2d/src/config/default-config.ts
index c16abf4..f7c05ce 100644
--- a/packages/live2d/src/config/default-config.ts
+++ b/packages/live2d/src/config/default-config.ts
@@ -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,
diff --git a/packages/live2d/src/config/normalize-config.ts b/packages/live2d/src/config/normalize-config.ts
index 09e5e2b..83badc1 100644
--- a/packages/live2d/src/config/normalize-config.ts
+++ b/packages/live2d/src/config/normalize-config.ts
@@ -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(
diff --git a/packages/live2d/src/context/config-context.ts b/packages/live2d/src/context/config-context.ts
index abfcb5c..398d34a 100644
--- a/packages/live2d/src/context/config-context.ts
+++ b/packages/live2d/src/context/config-context.ts
@@ -100,6 +100,8 @@ export interface Live2dToolsConfig {
}
export interface Live2dConfig extends Live2dToolsConfig {
+ // 是否在移动端显示,默认开启
+ showOnMobile?: boolean;
// Live2d API 路径
apiPath: string;
// Live2d 定位
diff --git a/packages/live2d/src/halo.ts b/packages/live2d/src/halo.ts
index 430e9bb..e66c953 100644
--- a/packages/live2d/src/halo.ts
+++ b/packages/live2d/src/halo.ts
@@ -2,6 +2,7 @@ import {
HALO_LIVE2D_CONFIG_ELEMENT_ID,
readHaloLive2dConfig,
} from "./halo-config";
+import { shouldShowLive2d } from "./utils/mobile-visibility";
let bootstrapPromise: Promise | undefined;
@@ -12,6 +13,9 @@ export const bootstrapFromHalo = async (): Promise => {
bootstrapPromise = (async () => {
const config = readHaloLive2dConfig();
+ if (!shouldShowLive2d(config)) {
+ return;
+ }
if (import.meta.env.DEV) {
await import("@vitejs/plugin-react/preamble");
}
diff --git a/packages/live2d/src/live2d/__tests__/runtime.test.ts b/packages/live2d/src/live2d/__tests__/runtime.test.ts
new file mode 100644
index 0000000..354802b
--- /dev/null
+++ b/packages/live2d/src/live2d/__tests__/runtime.test.ts
@@ -0,0 +1,79 @@
+import { LIVE2D_DISPLAY_STORAGE_KEY } from "@/live2d/helpers/widgetVisibility";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import { createLive2d } from "../runtime";
+
+vi.mock("@/live2d/components/Live2dContext", () => ({}));
+
+describe("runtime mobile visibility", () => {
+ beforeEach(() => {
+ document.body.replaceChildren();
+ vi.spyOn(navigator, "userAgent", "get").mockReturnValue("iPhone");
+ localStorage.setItem(LIVE2D_DISPLAY_STORAGE_KEY, "12345");
+ });
+
+ afterEach(() => {
+ document.body.replaceChildren();
+ localStorage.clear();
+ vi.restoreAllMocks();
+ });
+
+ it("does not mount a disabled mobile widget or change user preferences", () => {
+ createLive2d().init("/assets/", { showOnMobile: false });
+ expect(document.getElementById("plugin-live2d-root")).toBeNull();
+ expect(localStorage.getItem(LIVE2D_DISPLAY_STORAGE_KEY)).toBe("12345");
+ });
+
+ it("removes an existing root when reinitialized with mobile display disabled", () => {
+ const runtime = createLive2d();
+ runtime.init("/assets/", { showOnMobile: true });
+ expect(document.getElementById("plugin-live2d-root")).not.toBeNull();
+ runtime.init("/assets/", { showOnMobile: false });
+ expect(document.getElementById("plugin-live2d-root")).toBeNull();
+ runtime.init("/assets/", { showOnMobile: true });
+ expect(document.querySelectorAll("#plugin-live2d-root")).toHaveLength(1);
+ });
+
+ it("removes a root mounted by another runtime and reuses one root after enabling", () => {
+ const firstRuntime = createLive2d();
+ const secondRuntime = createLive2d();
+ firstRuntime.init("/assets/", { showOnMobile: true });
+
+ secondRuntime.init("/assets/", { showOnMobile: false });
+ expect(document.getElementById("plugin-live2d-root")).toBeNull();
+ expect(localStorage.getItem(LIVE2D_DISPLAY_STORAGE_KEY)).toBe("12345");
+
+ secondRuntime.init("/assets/", { showOnMobile: true });
+ const enabledRoot = document.getElementById("plugin-live2d-root");
+ firstRuntime.init("/assets/", { showOnMobile: true });
+ expect(document.getElementById("plugin-live2d-root")).toBe(enabledRoot);
+ expect(document.querySelectorAll("#plugin-live2d-root")).toHaveLength(1);
+ expect(localStorage.getItem(LIVE2D_DISPLAY_STORAGE_KEY)).toBe("12345");
+ });
+
+ it("removes the connected root when its cached root has been detached", () => {
+ const runtime = createLive2d();
+ runtime.init("/assets/", { showOnMobile: true });
+ const cachedRoot = document.getElementById("plugin-live2d-root");
+ cachedRoot?.remove();
+ createLive2d().init("/assets/", { showOnMobile: true });
+ expect(document.getElementById("plugin-live2d-root")).not.toBe(cachedRoot);
+
+ runtime.init("/assets/", { showOnMobile: false });
+ expect(document.getElementById("plugin-live2d-root")).toBeNull();
+ expect(localStorage.getItem(LIVE2D_DISPLAY_STORAGE_KEY)).toBe("12345");
+
+ runtime.init("/assets/", { showOnMobile: true });
+ expect(document.querySelectorAll("#plugin-live2d-root")).toHaveLength(1);
+ });
+
+ it("mounts a desktop widget regardless of the mobile setting", () => {
+ vi.spyOn(navigator, "userAgent", "get").mockReturnValue("Windows NT 10.0");
+ createLive2d().init("/assets/", { showOnMobile: false });
+ const desktopRoot = document.getElementById("plugin-live2d-root");
+ expect(desktopRoot).not.toBeNull();
+ createLive2d().init("/assets/", { showOnMobile: false });
+ expect(document.getElementById("plugin-live2d-root")).toBe(desktopRoot);
+ expect(document.querySelectorAll("#plugin-live2d-root")).toHaveLength(1);
+ expect(localStorage.getItem(LIVE2D_DISPLAY_STORAGE_KEY)).toBe("12345");
+ });
+});
diff --git a/packages/live2d/src/live2d/runtime.ts b/packages/live2d/src/live2d/runtime.ts
index 5d5f56b..d200d84 100644
--- a/packages/live2d/src/live2d/runtime.ts
+++ b/packages/live2d/src/live2d/runtime.ts
@@ -3,6 +3,7 @@ import {
type LegacyLive2dConfigInput,
normalizeLive2dConfig,
} from "@/live2d/config/normalize-config";
+import { shouldShowLive2d } from "@/live2d/utils/mobile-visibility";
import "@/live2d/components/Live2dContext";
const LIVE2D_CONTEXT_ID = "plugin-live2d-root";
@@ -17,6 +18,12 @@ export class Live2dRuntime {
private rootElement?: Live2dContext;
init(path: string, config: LegacyLive2dConfigInput = {}): void {
+ if (!shouldShowLive2d(config)) {
+ this.rootElement?.remove();
+ document.getElementById(LIVE2D_CONTEXT_ID)?.remove();
+ this.rootElement = undefined;
+ return;
+ }
const rootElement = this.getOrCreateRoot();
rootElement.config = normalizeLive2dConfig(path, config);
}
diff --git a/packages/live2d/src/utils/__tests__/mobile-visibility.test.ts b/packages/live2d/src/utils/__tests__/mobile-visibility.test.ts
new file mode 100644
index 0000000..3c3f40b
--- /dev/null
+++ b/packages/live2d/src/utils/__tests__/mobile-visibility.test.ts
@@ -0,0 +1,55 @@
+import { normalizeLive2dConfig } from "@/live2d/config/normalize-config";
+import type { Live2dConfig } from "@/live2d/context/config-context";
+import { describe, expect, it } from "vitest";
+import { isMobileDevice, shouldShowLive2d } from "../mobile-visibility";
+
+const desktop = {
+ userAgent: "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7)",
+ platform: "MacIntel",
+ maxTouchPoints: 0,
+};
+
+describe("mobile visibility", () => {
+ it.each(["iPhone", "iPad", "iPod", "Android", "Windows Phone Mobile"])(
+ "recognizes %s devices",
+ (userAgent) => {
+ const device = { ...desktop, userAgent };
+ expect(isMobileDevice(device)).toBe(true);
+ expect(shouldShowLive2d({ showOnMobile: false }, device)).toBe(false);
+ expect(shouldShowLive2d({ showOnMobile: true }, device)).toBe(true);
+ },
+ );
+
+ it("recognizes iPadOS with a desktop user agent", () => {
+ expect(isMobileDevice({ ...desktop, maxTouchPoints: 5 })).toBe(true);
+ });
+
+ it("does not disable desktop devices, including touch screen PCs", () => {
+ expect(shouldShowLive2d({ showOnMobile: false }, desktop)).toBe(true);
+ expect(
+ shouldShowLive2d(
+ { showOnMobile: false },
+ { ...desktop, platform: "Win32", maxTouchPoints: 10 },
+ ),
+ ).toBe(true);
+ });
+
+ it.each([undefined, null, "false", 0])(
+ "keeps the default for missing or invalid configuration: %s",
+ (showOnMobile) => {
+ const config = normalizeLive2dConfig("/assets/", {
+ showOnMobile: showOnMobile as Live2dConfig["showOnMobile"],
+ });
+ expect(config.showOnMobile).toBe(true);
+ expect(
+ shouldShowLive2d({ showOnMobile }, { ...desktop, userAgent: "iPhone" }),
+ ).toBe(true);
+ },
+ );
+
+ it("preserves an explicit false while normalizing configuration", () => {
+ expect(
+ normalizeLive2dConfig("/assets/", { showOnMobile: false }).showOnMobile,
+ ).toBe(false);
+ });
+});
diff --git a/packages/live2d/src/utils/mobile-visibility.ts b/packages/live2d/src/utils/mobile-visibility.ts
new file mode 100644
index 0000000..e0002dd
--- /dev/null
+++ b/packages/live2d/src/utils/mobile-visibility.ts
@@ -0,0 +1,17 @@
+interface DeviceEnvironment {
+ userAgent: string;
+ platform: string;
+ maxTouchPoints: number;
+}
+
+export const isMobileDevice = (
+ device: DeviceEnvironment = navigator,
+): boolean =>
+ /Android|iPhone|iPad|iPod|Mobile/i.test(device.userAgent) ||
+ // iPadOS can use a desktop user agent.
+ (device.platform === "MacIntel" && device.maxTouchPoints > 1);
+
+export const shouldShowLive2d = (
+ config: { showOnMobile?: unknown },
+ device: DeviceEnvironment = navigator,
+): boolean => config.showOnMobile !== false || !isMobileDevice(device);
diff --git a/src/main/java/run/halo/live2d/Live2dSettingProcess.java b/src/main/java/run/halo/live2d/Live2dSettingProcess.java
index 0d1b0e3..3e26a7c 100644
--- a/src/main/java/run/halo/live2d/Live2dSettingProcess.java
+++ b/src/main/java/run/halo/live2d/Live2dSettingProcess.java
@@ -26,7 +26,7 @@
@RequiredArgsConstructor
public class Live2dSettingProcess implements Live2dSetting {
private static final List BASE_FIELDS = List.of(
- "modelId", "modelTexturesId", "isForceUseDefaultConfig", "isTools", "tools");
+ "showOnMobile", "modelId", "modelTexturesId", "isForceUseDefaultConfig", "isTools", "tools");
private static final List API_FIELDS = List.of("apiPath", "hitokotoApi");
private static final List TIPS_FIELDS = List.of(
"firstOpenSite", "backSite", "backSiteTip", "copyContent", "copyContentTip",
diff --git a/src/main/resources/extensions/settings.yaml b/src/main/resources/extensions/settings.yaml
index b5d4f42..7ca34e1 100644
--- a/src/main/resources/extensions/settings.yaml
+++ b/src/main/resources/extensions/settings.yaml
@@ -7,6 +7,11 @@ spec:
- group: base
label: 基本设置
formSchema:
+ - $formkit: switch
+ name: showOnMobile
+ label: 在移动端显示
+ help: 关闭后,手机和平板访问时不会加载看板娘模型,减少屏幕占用和性能开销;桌面端不受影响。保存后刷新前台页面生效。
+ value: true
- $formkit: text
label: 默认模型编号
help: 默认模型编号为访客首次浏览网站时所展示的模型
diff --git a/src/test/java/run/halo/live2d/Live2dSettingProcessTest.java b/src/test/java/run/halo/live2d/Live2dSettingProcessTest.java
new file mode 100644
index 0000000..9b6a997
--- /dev/null
+++ b/src/test/java/run/halo/live2d/Live2dSettingProcessTest.java
@@ -0,0 +1,63 @@
+package run.halo.live2d;
+
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.when;
+
+import com.fasterxml.jackson.databind.JsonNode;
+import com.fasterxml.jackson.databind.node.BooleanNode;
+import com.fasterxml.jackson.databind.node.JsonNodeFactory;
+import com.fasterxml.jackson.databind.node.ObjectNode;
+import java.util.Map;
+import org.junit.jupiter.api.Test;
+import reactor.core.publisher.Mono;
+import run.halo.app.plugin.ReactiveSettingFetcher;
+import run.halo.live2d.agent.AgentToolNormalizer;
+import run.halo.live2d.ai.HaloAiFoundationAvailability;
+
+class Live2dSettingProcessTest {
+
+ private final ReactiveSettingFetcher settingFetcher = mock(ReactiveSettingFetcher.class);
+ private final HaloAiFoundationAvailability aiFoundationAvailability =
+ mock(HaloAiFoundationAvailability.class);
+
+ @Test
+ void shouldIncludeShowOnMobileWhenDisabled() {
+ var base = JsonNodeFactory.instance.objectNode();
+ base.put("showOnMobile", false);
+
+ var config = publicConfig(base);
+
+ assertThat(config.get("showOnMobile")).isEqualTo(BooleanNode.FALSE);
+ }
+
+ @Test
+ void shouldIncludeShowOnMobileWhenEnabled() {
+ var base = JsonNodeFactory.instance.objectNode();
+ base.put("showOnMobile", true);
+
+ var config = publicConfig(base);
+
+ assertThat(config.get("showOnMobile")).isEqualTo(BooleanNode.TRUE);
+ }
+
+ @Test
+ void shouldKeepOlderConfigurationWithoutShowOnMobileCompatible() {
+ var base = JsonNodeFactory.instance.objectNode();
+ base.put("modelId", 3);
+
+ var config = publicConfig(base);
+
+ assertThat(config.has("showOnMobile")).isFalse();
+ assertThat(config.get("modelId").intValue()).isEqualTo(3);
+ }
+
+ private JsonNode publicConfig(ObjectNode base) {
+ when(settingFetcher.getValues()).thenReturn(Mono.just(Map.of("base", base)));
+ when(aiFoundationAvailability.isEnabled()).thenReturn(Mono.just(false));
+ var settingProcess = new Live2dSettingProcess(settingFetcher,
+ mock(AgentToolNormalizer.class), aiFoundationAvailability);
+
+ return settingProcess.getPublicConfig(null).block();
+ }
+}