Skip to content
Merged
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
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { VisualSkinConfigSection } from './VisualSkinConfigSection';

const activateMock = vi.hoisted(() => vi.fn());
const deactivateMock = vi.hoisted(() => vi.fn());
const previewMock = vi.hoisted(() => vi.fn());
const cancelPreviewMock = vi.hoisted(() => vi.fn());
const importMock = vi.hoisted(() => vi.fn());
Expand Down Expand Up @@ -43,6 +44,7 @@ vi.mock('@/infrastructure/visual-skin', () => ({
watchProjection: watchProjectionMock,
importPackage: importMock,
activate: activateMock,
deactivate: deactivateMock,
preview: previewMock,
cancelPreview: cancelPreviewMock,
remove: removeMock,
Expand All @@ -62,6 +64,7 @@ describe('VisualSkinConfigSection', () => {
beforeEach(() => {
globalThis.IS_REACT_ACT_ENVIRONMENT = true;
activateMock.mockReset();
deactivateMock.mockReset();
previewMock.mockReset();
cancelPreviewMock.mockReset();
importMock.mockReset();
Expand Down Expand Up @@ -96,6 +99,46 @@ describe('VisualSkinConfigSection', () => {
const html = renderToStaticMarkup(<VisualSkinConfigSection />);
expect(html).toContain('data-testid="visual-skin-empty"');
});

it.each(['active', 'preview'] as const)('offers deactivation while %s without removing imported skins', async state => {
if (state === 'preview') {
skinState.activeSkinId = null;
skinState.previewSkinId = 'sample.skin';
}
await mount();
const button = container.querySelector<HTMLButtonElement>('[data-testid="visual-skin-deactivate"]')!;
expect(button.textContent).toBe('skin.deactivate');
await act(async () => button.click());
expect(deactivateMock).toHaveBeenCalledTimes(1);
expect(removeMock).not.toHaveBeenCalled();
expect(container.querySelector('[data-skin-id="sample.skin"]')).not.toBeNull();
});

it('disables deactivation once no skin or preview is selected', async () => {
skinState.activeSkinId = null;
await mount();
const button = container.querySelector<HTMLButtonElement>('[data-testid="visual-skin-deactivate"]')!;
expect(button.disabled).toBe(true);
await act(async () => button.click());
expect(deactivateMock).not.toHaveBeenCalled();
});

it('prevents duplicate deactivation while persistence is pending and allows retry after failure', async () => {
let reject!: (error: Error) => void;
deactivateMock.mockImplementationOnce(() => new Promise<void>((_, rejectAction) => { reject = rejectAction; }));
await mount();
const button = container.querySelector<HTMLButtonElement>('[data-testid="visual-skin-deactivate"]')!;
await act(async () => button.click());
expect(button.disabled).toBe(true);
await act(async () => button.click());
expect(deactivateMock).toHaveBeenCalledTimes(1);
await act(async () => reject(new Error('Unable to clear selection')));
expect(button.disabled).toBe(false);
expect(container.querySelector('[role="alert"]')?.textContent).toContain('Unable to clear selection');
await act(async () => button.click());
expect(deactivateMock).toHaveBeenCalledTimes(2);
expect(container.querySelector('[role="alert"]')).toBeNull();
});
it('distinguishes the saved skin from a temporary preview and keeps every card action reachable', async () => {
skinState.skins.push({ id: 'other.skin', name: 'Other skin', description: 'A long reference description', version: '2', author: 'Artist' });
skinState.previewSkinId = 'other.skin';
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@ export function VisualSkinConfigSection() {
error: runtimeError,
importPackage,
activate,
deactivate,
preview,
cancelPreview,
previewSkinId,
Expand Down Expand Up @@ -73,6 +74,15 @@ export function VisualSkinConfigSection() {
data-openbitfun-state={disabled ? 'disabled' : undefined}
extra={(
<>
<Button
variant="quiet"
size="sm"
disabled={disabled || (!activeSkinId && !previewSkinId)}
data-testid="visual-skin-deactivate"
onClick={() => void handleAction(deactivate)}
>
{t('skin.deactivate')}
</Button>
<input
ref={fileInputRef}
type="file"
Expand Down
1 change: 1 addition & 0 deletions src/web-ui/src/infrastructure/visual-skin/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ export function useVisualSkin() {
watchProjection: skinRuntime.watchProjection,
skins: snapshot.catalog,
activate: (id: string) => skinRuntime.activate(id),
deactivate: () => skinRuntime.deactivate(),
preview: (id: string) => skinRuntime.preview(id),
cancelPreview: () => skinRuntime.cancelPreview(),
importPackage: (source: ArrayBuffer) => skinRuntime.importPackage(source),
Expand Down
27 changes: 27 additions & 0 deletions src/web-ui/src/infrastructure/visual-skin/runtime.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -101,6 +101,33 @@ describe('VisualSkinRuntime', () => {
expect(document.querySelector('style[data-openbitfun-skin-runtime]')?.textContent).toContain('--openbitfun-color-content-primary:#fefefe');
});

it('deactivates paint and restores the host theme without removing the package', async () => {
const storage = new MemoryVisualSkinStorage();
const runtime = runtimeWith(storage);
document.documentElement.setAttribute('data-color-scheme', 'dark');
const nativeStyle = document.createElement('style');
nativeStyle.textContent = ':root { --openbitfun-color-content-primary: #6789ab; }';
const surface = document.createElement('main');
surface.setAttribute('data-openbitfun-surface', 'shell');
document.head.appendChild(nativeStyle);
document.body.appendChild(surface);
try {
await runtime.importPackage(new TextEncoder().encode(JSON.stringify(projectionPackageSource)).buffer);
expect(surface.hasAttribute('data-openbitfun-skin-artwork')).toBe(true);
await runtime.deactivate();
expect(await storage.getSelection()).toBeNull();
expect(await storage.get('projection-skin')).not.toBeNull();
expect(runtime.getSnapshot()).toMatchObject({ activeSkinId: null, activeSkin: null, previewSkinId: null, projection: null, status: 'ready' });
expect(runtime.getSnapshot().catalog.map(entry => entry.id)).toEqual(['projection-skin']);
expect(document.documentElement.getAttribute('data-color-scheme')).toBe('dark');
expect(getComputedStyle(document.documentElement).getPropertyValue('--openbitfun-color-content-primary')).toBe('#6789ab');
expect(document.querySelector('style[data-openbitfun-skin-runtime]')).toBeNull();
expect(document.querySelector('[data-openbitfun-skin-id], [data-openbitfun-skin-surface], [data-openbitfun-skin-artwork], [data-openbitfun-skin-node], [data-openbitfun-skin-background-source]')).toBeNull();
await runtime.activate('projection-skin');
expect(runtime.getSnapshot().activeSkinId).toBe('projection-skin');
} finally { nativeStyle.remove(); surface.remove(); }
});

it('projects named slots, product components, and surfaces through fixed selectors', async () => {
const runtime = runtimeWith(new MemoryVisualSkinStorage());
const component = document.createElement('div');
Expand Down
22 changes: 12 additions & 10 deletions src/web-ui/src/infrastructure/visual-skin/runtime.ts
Original file line number Diff line number Diff line change
Expand Up @@ -413,6 +413,11 @@ export class VisualSkinRuntime {
await this.applySelection(id);
}

async deactivate(): Promise<void> {
await this.initialize();
await this.applySelection(null);
}

async preview(id: string): Promise<void> {
await this.initialize();
const skin = await this.storage.get(id);
Expand Down Expand Up @@ -458,28 +463,25 @@ export class VisualSkinRuntime {
this.replaceStyle(this.skinCss(skin));
}

private async applySelection(id: string): Promise<void> {
private async applySelection(id: string | null): Promise<void> {
const before = this.snapshot;
const previousSkin = this.appliedSkin;
let committed = false;
try {
const skin = await this.storage.get(id);
if (!skin) throw new Error(`Visual skin is not installed: ${id}`);
this.partImages.ensure(skin);
const skin = id === null ? null : await this.storage.get(id);
if (id !== null && !skin) throw new Error(`Visual skin is not installed: ${id}`);
if (skin) this.partImages.ensure(skin);
// Selection writes are transactional. Do not touch the visible skin
// until IndexedDB confirms that the selection has committed.
this.setSnapshot({ status: 'applying', error: undefined });
await this.storage.setSelection(id);
committed = true;
this.appliedSkin = skin;
document.documentElement.setAttribute(ACTIVE_ID_ATTRIBUTE, id);
this.syncSurfaceMarkers(skin);
this.replaceStyle(this.skinCss(skin));
this.setSnapshot({ initialized: true, activeSkinId: id, activeSkin: skin, previewSkinId: null, projection: createProjectionReport(skin), status: 'ready', error: undefined });
this.restoreDisplay(skin);
this.setSnapshot({ initialized: true, activeSkinId: id, activeSkin: skin, previewSkinId: null, projection: skin ? createProjectionReport(skin) : null, status: 'ready', error: undefined });
this.collectPartImages();
} catch (error) {
const message = error instanceof Error ? error.message : String(error);
log.error('Visual skin activation failed', { skinId: id, error: message });
log.error('Visual skin selection failed', { skinId: id, error: message });
if (committed) {
await this.storage.setSelection(before.activeSkinId);
this.clearAppliedSkin();
Expand Down
50 changes: 50 additions & 0 deletions src/web-ui/src/infrastructure/visual-skin/storage.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -146,6 +146,56 @@ describe('visual skin IndexedDB storage', () => {
expect(write).not.toHaveBeenCalled();
});

it('persists deactivation across runtime restarts while keeping imported skins usable', async () => {
const fixture = createIndexedDbFixture();
vi.stubGlobal('indexedDB', fixture.indexedDB);
const skin = await parsedSkin();
const storage = createVisualSkinStorage();
await storage.put(skin);
const runtime = new VisualSkinRuntime(storage);
const reopened = new VisualSkinRuntime(createVisualSkinStorage());
try {
await runtime.activate(skin.manifest.id);
await runtime.deactivate();
expect(fixture.stores.get('selection')!.has('active')).toBe(false);
runtime.dispose();
await reopened.initialize();
expect(reopened.getSnapshot()).toMatchObject({ activeSkinId: null, previewSkinId: null, status: 'ready' });
expect(reopened.getSnapshot().catalog.map(entry => entry.id)).toEqual([skin.manifest.id]);
expect(document.documentElement.hasAttribute('data-openbitfun-skin-id')).toBe(false);
await reopened.activate(skin.manifest.id);
expect(await storage.getSelection()).toBe(skin.manifest.id);
} finally { runtime.dispose(); reopened.dispose(); }
});

it.each([false, true])('preserves the saved skin and visible preview on failed deactivation (preview: %s)', async preview => {
const fixture = createIndexedDbFixture();
vi.stubGlobal('indexedDB', fixture.indexedDB);
const storage = createVisualSkinStorage();
const skin = await parsedSkin();
const other = { ...skin, manifest: { ...skin.manifest, id: 'other' } };
await storage.put(skin);
await storage.put(other);
const runtime = new VisualSkinRuntime(storage);
try {
await runtime.activate(skin.manifest.id);
if (preview) await runtime.preview(other.manifest.id);
const before = runtime.getSnapshot();
const style = document.querySelector('style[data-openbitfun-skin-runtime]');
fixture.failures.deleteStore = 'selection';
await expect(runtime.deactivate()).rejects.toThrow('Injected selection delete failure');
expect(runtime.getSnapshot()).toEqual({ ...before, error: 'Injected selection delete failure' });
expect(await storage.getSelection()).toBe(skin.manifest.id);
expect(document.querySelector('style[data-openbitfun-skin-runtime]')).toBe(style);
expect(document.documentElement.getAttribute('data-openbitfun-skin-id')).toBe(preview ? other.manifest.id : skin.manifest.id);
fixture.failures.deleteStore = null;
await runtime.deactivate();
expect(runtime.getSnapshot()).toMatchObject({ activeSkinId: null, previewSkinId: null, status: 'ready', error: undefined });
expect(document.querySelector('style[data-openbitfun-skin-runtime]')).toBeNull();
expect(await storage.list()).toEqual({ skins: [skin, other], invalidRecords: [] });
} finally { runtime.dispose(); }
});

it('rejects tampered stored CSS and preserves the invalid record for explicit removal', async () => {
const fixture = createIndexedDbFixture();
vi.stubGlobal('indexedDB', fixture.indexedDB);
Expand Down
1 change: 1 addition & 0 deletions src/web-ui/src/locales/en-US/settings/appearance.json
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,7 @@
"previewing": "Previewing",
"cancelPreview": "Cancel preview",
"activate": "Use skin",
"deactivate": "Disable skin",
"active": "Active",
"remove": "Remove skin",
"error": "Skin operation failed: {{message}}",
Expand Down
1 change: 1 addition & 0 deletions src/web-ui/src/locales/zh-CN/settings/appearance.json
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,7 @@
"previewing": "预览中",
"cancelPreview": "取消预览",
"activate": "使用皮肤",
"deactivate": "不使用皮肤",
"active": "当前使用",
"remove": "移除皮肤",
"error": "皮肤操作失败:{{message}}",
Expand Down
1 change: 1 addition & 0 deletions src/web-ui/src/locales/zh-TW/settings/appearance.json
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,7 @@
"previewing": "預覽中",
"cancelPreview": "取消預覽",
"activate": "使用皮膚",
"deactivate": "不使用皮膚",
"active": "目前使用",
"remove": "移除皮膚",
"error": "皮膚操作失敗:{{message}}",
Expand Down
Loading