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
24 changes: 16 additions & 8 deletions docs/features/visual-skin-packs.md
Original file line number Diff line number Diff line change
Expand Up @@ -69,7 +69,7 @@ The importer accepts two package forms:
- **Canonical JSON** uses `manifest`, `modes`, `assets`, `components`, and
`surfaces`. JSON assets must be embedded as base64 data URLs.
- **ZIP** may contain a canonical `skin.json` with declared package-relative
image assets. The importer also accepts the multi-file entrypoint format
image or MP4 video assets. The importer also accepts the multi-file entrypoint format
(`format: openbitfun-visual-skin`), resolving its token/asset/slot/recipe files
into canonical fields. New Skill output uses the canonical format directly
to avoid authoring fields that the conversion does not project.
Expand All @@ -78,16 +78,24 @@ The runtime accepts the public token contract from
`@openbitfun/theme-openbitfun` and `@openbitfun/design-tokens`, named visual
slots, component recipes, interaction states, and surface profiles. It validates
identifiers, exact public token names (without aliases), asset MIME types, data URLs, package-relative paths,
archive size, and undeclared files before persisting a package. ZIP directory
metadata is checked before extraction (96 entries including directories,
16 MiB per entry, 416 MiB total); manifest/entrypoint reads additionally have a
512 KiB limit. Extraction uses a bounded streaming sink, cancellation, and CRC
validation. Actual output is bounded as well as declared sizes, and each asset
is extracted once. Packages cannot
and undeclared files before persisting a package. The only size limit is
**128 MiB per file** (including `skin.json`); entry count, package size and
total expanded size are not limited. ZIP directory metadata is checked before
extraction. Extraction uses a bounded streaming sink, cancellation, and CRC
validation. Actual output is bounded by the per-file limit as well as the
declared size, and each asset is extracted once. Assets are kept in memory as
base64 data URLs, so very large assets cost far more memory than their file size.

Assets may be PNG, JPEG, WebP, SVG or `video/mp4`. An MP4 is valid only as a
surface `backgroundAssetId` (or the preview): the runtime mounts it as a muted,
looping `<video>` in the surface's paint plane, mapping `fit` to `object-fit`
and `backgroundPosition` to `object-position`; the surface scrim still tints it.
CSS cannot paint video, so an MP4 cannot be used as a component or state slot
`assetId`, and the validator rejects it there. Packages cannot
provide CSS, selectors, JavaScript, network URLs, markup, product copy,
permissions, or business logic.

The importer consumes image assets, semantic/theme colors, component color
The importer consumes image and MP4 video assets, semantic/theme colors, component color
aliases and public color/shadow system tokens. Radius, spacing, typography
metrics, layout, control dimensions and motion tokens are rejected. A package
cannot ship executable font or stylesheet code.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -93,7 +93,7 @@ Start from the supplied pixels when the brief is reference-driven. Record source
and delivered resolution, animation frames/duration, target CSS size and DPR.
Do not silently downscale, retime, shorten loops, or upscale and call it sharper.
If an asset exceeds the current limits, report the limit and proposed tradeoff.
The current package supports images, not video backgrounds.
The package also supports an MP4 surface backdrop (muted, looping, no audio).

Use an available image generator for matching raster fragments when useful.
Example requests include a sparse vertical edge, shallow toolbar ornament or
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ The optional [authoring template](authoring-template.md) does not override it.
| Theme/material | Exported paint tokens: semantic/component colors and public color/shadow tokens | No font metrics/families, spacing, radius, dimensions, layout or motion overrides |
| Existing surfaces | Base material, one backdrop, one scrim, supported image fit/position/alpha, local tokens and supported states | No new surfaces, arbitrary layer stacks, clipping or content geometry |
| Existing components and owned parts | Supported background assets/material, foreground, existing border color, box/glyph shadows and emitted states | No arbitrary selectors, DOM changes, icon/text replacement, hiding, repositioning or new behaviors |
| Assets | Local PNG/JPEG/WebP/SVG, including supported animated image content | No external URLs, scripts, video backgrounds or font installation |
| Assets | Local PNG/JPEG/WebP/SVG, including supported animated image content, and MP4 video as a surface backdrop | No external URLs, scripts, video in component slots or font installation |
| Modes | Any nonempty subset of the four supported modes, with documented fallback/merging | A fallback is not a separately authored mode; requested coverage is a user requirement |

Assets, component recipes and explicit surface profiles are optional. A valid
Expand Down Expand Up @@ -60,7 +60,7 @@ The ZIP root contains `skin.json`:

`schemaVersion` is the parser's format identifier. Do not invent alternate
generations of the skin system. Optional manifest keys are `author`,
`description`, and `previewAssetId` (a declared image id). Ids use lower-case
`description`, and `previewAssetId` (a declared asset id). Ids use lower-case
letters/digits with `.`, `_`, or `-` separators; manifest id is at most 96 chars.
`name` and `version` are non-empty strings of at most 160 chars.

Expand Down Expand Up @@ -103,20 +103,26 @@ or prove browser consumption of a syntactically safe string.
}
```

Supported MIME types are `image/png`, `image/jpeg`, `image/webp`, and
`image/svg+xml`. A ZIP may use path assets or embedded data assets. Standalone
Supported MIME types are `image/png`, `image/jpeg`, `image/webp`,
`image/svg+xml`, and `video/mp4`. An MP4 is only valid as a surface
`backgroundAssetId` (or `previewAssetId`); the runtime plays it muted and looping
in the surface's paint plane, with `fit` mapped to `object-fit` and
`backgroundPosition` to `object-position`. It cannot be used as a component or
state slot `assetId`, which paint CSS backgrounds. Use H.264 for the widest
decoder support. A ZIP may use path assets or embedded data assets. Standalone
JSON requires `source: { "kind": "data", "data": "data:image/webp;base64,..." }`.
Paths are relative POSIX paths inside the skin directory; no traversal, absolute
paths, remote URLs, or escaping symlinks. Every file must exist and every asset
reference must resolve. Keep SVGs self-contained; do not embed scripts, HTML,
external resources, or font files. Provenance, licensing, dimensions, and safe
areas belong in the accompanying analysis, not invented manifest keys.

Current importer limits: 32 MiB input, 96 ZIP entries including directory entries,
16 MiB per expanded entry, 48 MiB expanded total, and 512 KiB for `skin.json`.
The packer emits no directory entries. JSON-only imports also have the 512 KiB
manifest limit. The production parser checks bounded extraction and CRC; it
does not certify asset licensing, raster identity, or aesthetic suitability.
Current importer limit: one file may be at most 128 MiB once expanded (this
includes `skin.json`). There is no limit on package size, entry count, or total
expanded size. The production parser checks bounded per-file extraction and CRC;
it does not certify asset licensing, raster identity, or aesthetic suitability.
Large assets are held in memory as base64 data URLs, so the resident cost is
well above the file size.

## Surfaces

Expand Down Expand Up @@ -294,7 +300,7 @@ not padding, geometry, or a new `calendar-body` slot. See

A canonical ZIP has `skin.json` at its root and declared relative assets, with no
enclosing skin directory. Standalone canonical JSON can be imported when every
asset is embedded and its bytes fit the manifest limit. Worksheets, provenance,
asset is embedded as a data URL within the per-file limit. Worksheets, provenance,
analysis and visual reports are not importer fields or required archive files.

```text
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -169,22 +169,19 @@ async function readBounded(path, limit) {

export async function buildDirectory(directory, product) {
const root = await realpath(resolve(directory));
const manifestBytes = await readBounded(join(root, 'skin.json'), product.MAX_SKIN_MANIFEST_BYTES);
const manifestBytes = await readBounded(join(root, 'skin.json'), product.MAX_SKIN_ASSET_BYTES);
const skin = JSON.parse(manifestBytes.toString('utf8'));
lintAuthoring(skin, product);
const paths = Object.values(skin.assets ?? {}).flatMap(asset => asset.source.kind === 'path' ? [asset.source.path] : []);
unique(['skin.json', ...paths], 'archive paths');
const files = new Map([['skin.json', manifestBytes]]);
let total = manifestBytes.length;
for (const path of paths.sort()) {
const target = await realpath(resolve(root, path));
const inside = relative(root, target);
if (!inside || inside === '..' || inside.startsWith(`..${process.platform === 'win32' ? '\\' : '/'}`) || isAbsolute(inside)) {
throw new Error(`Asset resolves outside the skin directory: ${path}`);
}
const bytes = await readBounded(target, product.MAX_SKIN_ASSET_BYTES);
total += bytes.length;
if (total > product.MAX_SKIN_EXPANDED_BYTES) throw new Error('Skin exceeds the total expanded size limit');
files.set(path, bytes);
}
const zip = new product.JSZip();
Expand All @@ -198,14 +195,14 @@ export async function buildDirectory(directory, product) {

export async function validateInput(input, product) {
if ((await stat(input)).isDirectory()) return buildDirectory(input, product);
// The parser performs the same archive and expansion checks used on import.
const bytes = await readBounded(input, 32 * 1024 * 1024);
// The only product limit is per file (MAX_SKIN_ASSET_BYTES); the package itself is unbounded.
const bytes = await readBounded(input, Number.POSITIVE_INFINITY);
const parser = new product.VisualSkinPackageParser();
const skin = await parser.parse(bufferSource(bytes));
let raw;
if (bytes[0] === 0x50 && bytes[1] === 0x4b) {
const archive = await product.SkinArchive.open(bufferSource(bytes));
try { raw = JSON.parse(new TextDecoder().decode(await archive.read('skin.json', product.MAX_SKIN_MANIFEST_BYTES))); }
try { raw = JSON.parse(new TextDecoder().decode(await archive.read('skin.json'))); }
finally { await archive.close(); }
} else raw = JSON.parse(bytes.toString('utf8'));
lintAuthoring(raw, product);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -291,3 +291,25 @@ test('packs exposed text contrast using the product contract', async () => {
assert.equal(skin.components[0].slots.root.textShadowToken, 'shadow.base');
assert.equal(product.validateVisualSkinPackage({ ...skin, components: [{ component: 'markdown', slots: { root: { textShadowToken: 'color.surface.panel' } } }] }).valid, false);
});

test('packs MP4 surface backdrops while rejecting non-MP4 files and component video slots', async () => {
const mp4 = Buffer.from([0, 0, 0, 16, 0x66, 0x74, 0x79, 0x70, 0x69, 0x73, 0x6f, 0x6d, 0, 0, 2, 0]);
const { directory } = await fixture(skin => {
skin.assets.film = { mimeType: 'video/mp4', source: { kind: 'path', path: 'assets/film.mp4' } };
skin.manifest.previewAssetId = 'film';
skin.surfaces = [{ surface: 'shell', backgroundAssetId: 'film', fit: 'cover' }];
});
await writeFile(join(directory, 'assets/film.mp4'), mp4);
const packed = await buildDirectory(directory, product);
assert.match(packed.skin.assets.film.dataUrl, /^data:video\/mp4;base64,/);

await writeFile(join(directory, 'assets/film.mp4'), Buffer.alloc(16));
await assert.rejects(buildDirectory(directory, product), /not a valid MP4/);

const badSlot = await fixture(skin => {
skin.assets.film = { mimeType: 'video/mp4', source: { kind: 'path', path: 'assets/film.mp4' } };
skin.components = [{ component: 'button', slots: { root: { assetId: 'film' } } }];
});
await writeFile(join(badSlot.directory, 'assets/film.mp4'), mp4);
await assert.rejects(buildDirectory(badSlot.directory, product), /only supported as a surface backgroundAssetId/);
});
Original file line number Diff line number Diff line change
Expand Up @@ -160,6 +160,7 @@
}

&__preview {
position: relative;
grid-row: span 2;
display: grid;
place-items: center;
Expand All @@ -171,6 +172,16 @@
background-position: center;
background-size: cover;
color: var(--openbitfun-color-content-muted);

> video {
position: absolute;
inset: 0;
width: 100%;
height: 100%;
object-fit: cover;
border-radius: inherit;
pointer-events: none;
}
}

&__copy {
Expand Down
16 changes: 16 additions & 0 deletions src/web-ui/src/app/styles/visual-skin.scss
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,8 @@
--openbitfun-skin-surface-background-position: center;
--openbitfun-skin-surface-background-size: cover;
--openbitfun-skin-surface-background-opacity: 0;
--openbitfun-skin-surface-video-fit: cover;
--openbitfun-skin-surface-video-position: center;
--openbitfun-skin-surface-scrim-color: transparent;
--openbitfun-skin-surface-scrim-opacity: 0;

Expand Down Expand Up @@ -59,6 +61,20 @@
opacity: var(--openbitfun-skin-surface-background-opacity);
}

// MP4 backdrop. Appended after ::before and before ::after, so the
// scrim still tints it. It never receives input.
> video[data-openbitfun-skin-video] {
position: absolute;
inset: 0;
width: 100%;
height: 100%;
border-radius: inherit;
object-fit: var(--openbitfun-skin-surface-video-fit);
object-position: var(--openbitfun-skin-surface-video-position);
opacity: var(--openbitfun-skin-surface-background-opacity);
pointer-events: none;
}

&::after {
background: var(--openbitfun-skin-surface-scrim-color);
opacity: var(--openbitfun-skin-surface-scrim-opacity);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -204,4 +204,36 @@ describe('VisualSkinConfigSection', () => {
expect(watchProjectionMock).not.toHaveBeenCalled();
});

it('renders an MP4 preview as a muted looping blob video and revokes it on unmount', async () => {
const createObjectURL = vi.spyOn(URL, 'createObjectURL').mockReturnValue('blob:skin-preview');
const revokeObjectURL = vi.spyOn(URL, 'revokeObjectURL').mockImplementation(() => undefined);
try {
const mp4 = Buffer.from([0, 0, 0, 16, 0x66, 0x74, 0x79, 0x70, 0x69, 0x73, 0x6f, 0x6d, 0, 0, 2, 0]).toString('base64');
skinState.skins = [{
id: 'video.skin',
name: 'Video Skin',
description: 'Looping MP4 backdrop',
version: '1.0.0',
author: 'AI',
previewAsset: `data:video/mp4;base64,${mp4}`,
} as (typeof skinState.skins)[number]];
await mount();
const preview = container.querySelector<HTMLDivElement>('.visual-skin-config__preview')!;
const video = preview.querySelector<HTMLVideoElement>('video')!;
expect(preview.style.backgroundImage).toBe('');
expect(video).not.toBeNull();
expect(video.getAttribute('src')).toBe('blob:skin-preview');
expect(video.muted && video.loop && video.autoplay).toBe(true);
expect(video.hasAttribute('disablepictureinpicture')).toBe(true);
expect(video.tabIndex).toBe(-1);
await act(async () => root!.unmount());
root = null;
container.remove();
expect(revokeObjectURL).toHaveBeenCalledWith('blob:skin-preview');
} finally {
createObjectURL.mockRestore();
revokeObjectURL.mockRestore();
}
});

});
Original file line number Diff line number Diff line change
@@ -1,9 +1,10 @@
import { Button, IconButton } from '@openbitfun/ui';
import { Check, Image, Palette, Trash2, Upload } from 'lucide-react';
import { useRef, useState } from 'react';
import { useEffect, useRef, useState } from 'react';
import { useTranslation } from 'react-i18next';

import { useVisualSkin, type VisualSkinCatalogEntry } from '@/infrastructure/visual-skin';
import { decodeSkinDataUrl } from '@/infrastructure/visual-skin/archive';
import { ConfigPageSection, formatStandaloneUiText } from './common';

function previewSource(entry: VisualSkinCatalogEntry): string | undefined {
Expand All @@ -12,6 +13,48 @@ function previewSource(entry: VisualSkinCatalogEntry): string | undefined {
: undefined;
}

function isVideoPreview(source: string | undefined): boolean {
return Boolean(source?.startsWith('data:video/'));
}

function VideoPreview({ source }: { source: string }) {
const [blobUrl, setBlobUrl] = useState<string | null>(null);

useEffect(() => {
if (typeof URL.createObjectURL !== 'function') return undefined;
try {
const mimeMatch = /^data:([^;,]+);base64,/i.exec(source);
const mimeType = mimeMatch?.[1] || 'video/mp4';
const bytes = decodeSkinDataUrl(source);
const buffer = bytes.buffer instanceof ArrayBuffer
? bytes.buffer.slice(bytes.byteOffset, bytes.byteOffset + bytes.byteLength)
: new Uint8Array(bytes).buffer;
const url = URL.createObjectURL(new Blob([buffer], { type: mimeType }));
setBlobUrl(url);
return () => {
URL.revokeObjectURL(url);
};
} catch {
setBlobUrl(null);
return undefined;
}
}, [source]);

return (
<video
src={blobUrl ?? (typeof URL.createObjectURL === 'function' ? undefined : source)}
muted
loop
autoPlay
playsInline
disablePictureInPicture
preload="metadata"
tabIndex={-1}
aria-hidden="true"
/>
);
}

/**
* Import and activate declarative visual skin packs generated from a reference
* image. The runtime owns validation and persistence; this component only
Expand Down Expand Up @@ -131,6 +174,7 @@ export function VisualSkinConfigSection() {
const active = entry.id === activeSkinId;
const previewing = previewSkinId === entry.id;
const previewAsset = previewSource(entry);
const videoPreview = isVideoPreview(previewAsset);
return (
<article
key={entry.id}
Expand All @@ -145,10 +189,11 @@ export function VisualSkinConfigSection() {
>
<div
className="visual-skin-config__preview"
style={previewAsset ? { backgroundImage: `url(${previewAsset})` } : undefined}
style={previewAsset && !videoPreview ? { backgroundImage: `url(${previewAsset})` } : undefined}
role={previewAsset ? 'img' : undefined}
aria-label={previewAsset ? t('skin.previewAlt', { name: entry.name }) : undefined}
>
{videoPreview && previewAsset && <VideoPreview source={previewAsset} />}
{!previewAsset && <Image size={22} aria-hidden="true" />}
</div>
<div className="visual-skin-config__copy">
Expand Down
Loading
Loading