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
63 changes: 55 additions & 8 deletions src/core/dom-renderer/domRenderer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -327,6 +327,44 @@ function applyLegacyObjectFit(
);
}

/**
* The URL an <img> loads for an image source: a string as is; a Blob through
* an object URL the node makes once and reuses while that Blob stays its
* source; anything else (ImageData) null, as the DOM can't load it.
*/
function imageUrlOf(node: DOMNode, source: unknown): string | null {
if (typeof Blob === 'undefined' || !(source instanceof Blob)) {
node.blobSrc = null;
node.blobUrl = null;
return typeof source === 'string' ? source : null;
}
// A destroyed node can still be written to (an animation or effect that
// outlives it): a URL made now would never be revoked.
if (node.destroyed) return null;
if (node.blobSrc !== source) {
const url = URL.createObjectURL(source);
node.blobSrc = source;
node.blobUrl = url;
(node.blobUrls ??= new Set()).add(url);
}
return node.blobUrl;
}

/**
* Revokes the object URLs `node` made that are no longer in use: all of them
* once it is destroyed, else all but its current one and the one its <img>
* still shows (out of bounds, the <img> moves to a new src only on re-entry).
*/
function releaseBlobUrls(node: DOMNode, all: boolean) {
const urls = node.blobUrls!;
const shown = node.imgEl?.dataset.rawSrc;
for (const url of urls) {
if (!all && (url === node.blobUrl || url === shown)) continue;
URL.revokeObjectURL(url);
urls.delete(url);
}
}

function updateNodeStyles(node: DOMNode | DOMText) {
const { props } = node;

Expand Down Expand Up @@ -483,7 +521,7 @@ function updateNodeStyles(node: DOMNode | DOMText) {
let srcImg: string | null = null;
let srcPos: null | InstanceType<lng.TextureMap['SubTexture']>['props'] =
null;
let rawImgSrc: string | null = null;
let imgSource: unknown = props.src;

if (
props.texture != null &&
Expand All @@ -493,13 +531,11 @@ function updateNodeStyles(node: DOMNode | DOMText) {
lng.TextureMap['SubTexture']
>;
srcPos = texture.props;
rawImgSrc = (texture.props.texture as any).props.src;
} else if (typeof props.src === 'string') {
// Renderer 1.8 widened `src` to `string | Blob | ImageData`; the DOM
// renderer only paints string URLs.
rawImgSrc = props.src;
imgSource = (texture.props.texture as any).props.src;
}

const rawImgSrc = imageUrlOf(node, imgSource);

if (rawImgSrc) {
srcImg = `url(${rawImgSrc})`;
}
Expand Down Expand Up @@ -1053,6 +1089,8 @@ function updateNodeStyles(node: DOMNode | DOMText) {
style += bgStyle;
}

if (node.blobUrls !== null) releaseBlobUrls(node, false);

const needsSeparateBorderLayer = needsBackgroundLayer && maskStyle !== '';

if (needsSeparateBorderLayer) {
Expand Down Expand Up @@ -1395,6 +1433,11 @@ export class DOMNode extends EventEmitter implements IRendererNode {
lazyImageSubTextureProps:
| InstanceType<lng.TextureMap['SubTexture']>['props']
| null = null;
/** The Blob image source shown through `blobUrl`, if the source is one. */
blobSrc: Blob | null = null;
blobUrl: string | null = null;
/** Object URLs this node made and has not revoked yet. */
blobUrls: Set<string> | null = null;
boundsDirty = true;
children = new Set<DOMNode>();
/** Cached result of the last updateNodeStyles call — avoids redundant setAttribute writes. */
Expand Down Expand Up @@ -1442,6 +1485,7 @@ export class DOMNode extends EventEmitter implements IRendererNode {
// Like CoreNode, destroying a node marks its whole subtree destroyed.
private markDestroyed() {
this.destroyed = true;
if (this.blobUrls !== null) releaseBlobUrls(this, true);
for (const child of this.children) {
child.markDestroyed();
}
Expand Down Expand Up @@ -1593,15 +1637,18 @@ export class DOMNode extends EventEmitter implements IRendererNode {
this.imgEl.style.display = '';
this.imgEl.dataset.pendingSrc = pendingSrc;
// crossOrigin + data: URI fails to load on old WebKit engines (e.g. PS4 WebMAF) —
// only request CORS for real network sources, never for inlined base64 images.
if (pendingSrc.startsWith('data:')) {
// only request CORS for real network sources, never for inlined base64
// images or same-origin object URLs.
if (pendingSrc.startsWith('data:') || pendingSrc.startsWith('blob:')) {
this.imgEl.removeAttribute('crossorigin');
} else {
this.imgEl.crossOrigin = 'anonymous';
}
this.imgEl.src = pendingSrc;
this.imgEl.dataset.rawSrc = pendingSrc;
this.imgEl.dataset.pendingSrc = '';
// The <img> has moved off the object URL it showed out of bounds.
if (this.blobUrls !== null) releaseBlobUrls(this, false);
}

get x() {
Expand Down
17 changes: 10 additions & 7 deletions src/core/elementNode.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2051,8 +2051,13 @@ export class ElementNode {
}

set src(src) {
if (typeof src === 'string') {
this.lng.src = src;
if (
typeof src === 'string' ||
(typeof Blob !== 'undefined' && src instanceof Blob)
) {
// The renderer types `Node.src` as a string, but loads a Blob src as
// ImageTexture does; the DOM renderer shows it through an object URL.
this.lng.src = src as string;
if (!this.color && this.rendered) {
this.color = 0xffffffff;
}
Expand All @@ -2061,11 +2066,9 @@ export class ElementNode {
}
}

get src(): string | null | undefined {
// Renderer 1.8 widened `src` to `string | Blob | ImageData`. The solid
// `src` prop only ever assigns strings (see the setter above), so the
// non-string arms are unreachable through this path.
return this.lng.src as string | null | undefined;
/** An image URL, or a Blob holding the image (e.g. a fetch() response's). */
get src(): string | Blob | null | undefined {
return this.lng.src as string | Blob | null | undefined;
}

getChildById(id: string) {
Expand Down
185 changes: 185 additions & 0 deletions tests/blobSrc.test.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,185 @@
// A Blob `src` on the DOM renderer: shown through an object URL the node owns,
// revoked once its <img> no longer uses it.
import * as v from 'vitest';
import * as s from 'solid-js';
import * as lng from '@solidtv/solid';
import { renderer } from './setup.js';

/** Lets the post-mutation pass (which destroys removed nodes) run. */
const settle = () => new Promise<void>((r) => setTimeout(r, 0));

/** The renderer node behind an element, as the DOM renderer makes it. */
const dom = (el: lng.ElementNode) => el.lng as unknown as lng.DOMNode;

const blob = () => new Blob(['x'], { type: 'image/png' });

// jsdom has no object URLs: stand in for them, tracking which are live.
let live: Set<string>;
let made: number;
const original = {
create: URL.createObjectURL,
revoke: URL.revokeObjectURL,
};

v.beforeEach(() => {
live = new Set();
made = 0;
URL.createObjectURL = () => {
const url = `blob:test/${++made}`;
live.add(url);
return url;
};
URL.revokeObjectURL = (url: string) => {
v.expect(live.has(url), `revoked ${url} twice or never made`).toBe(true);
live.delete(url);
};
});

v.afterEach(() => {
URL.createObjectURL = original.create;
URL.revokeObjectURL = original.revoke;
});

/**
* Renders an image view showing `view`'s props inside a parent, so
* `remove()` takes it out of the tree and the renderer node is destroyed.
*/
async function renderImage(
view: (ref: (el: lng.ElementNode) => void) => s.JSX.Element,
) {
const [show, setShow] = s.createSignal(true);
let el!: lng.ElementNode;
const dispose = renderer.render(() => (
<view width={1920} height={1080}>
<s.Show when={show()}>{view((e) => (el = e))}</s.Show>
</view>
));
await settle();
return {
el,
node: dom(el),
async remove() {
setShow(false);
await settle();
dispose();
},
};
}

/** The URL the <img> loads. */
const shown = (node: lng.DOMNode) => node.imgEl?.getAttribute('src');

v.describe('Blob src on the DOM renderer', () => {
v.test('<view src={blob}> shows the blob through an object URL', async () => {
const b = blob();
const { el, node, remove } = await renderImage((ref) => (
<view ref={ref} width={10} height={10} src={b} />
));

v.expect(el.src).toBe(b);
v.expect(shown(node)).toBe('blob:test/1');
// A same-origin inline source: no CORS request (old WebKit fails it).
v.expect(node.imgEl!.hasAttribute('crossorigin')).toBe(false);

// Restyling the same Blob reuses its URL.
node.alpha = 0.5;
node.w = 20;
v.expect(made).toBe(1);
v.expect(shown(node)).toBe('blob:test/1');

await remove();
v.expect(node.destroyed).toBe(true);
v.expect(live.size).toBe(0);
});

v.test(
'a new src revokes the old URL once the <img> has moved off it',
async () => {
const [src, setSrc] = s.createSignal<string | Blob>('poster.png');
const { node, remove } = await renderImage((ref) => (
<view ref={ref} width={10} height={10} src={src()} />
));

const b = blob();
setSrc(b);
v.expect(shown(node)).toBe('blob:test/1');
// Set after render, a Blob turns an uncolored view white, as a URL does.
v.expect(node.color).toBe(0xffffffff);

setSrc(blob());
v.expect(shown(node)).toBe('blob:test/2');
v.expect(live).toEqual(new Set(['blob:test/2']));

setSrc('poster.png');
v.expect(shown(node)).toBe('poster.png');
v.expect(live.size).toBe(0);

// The same Blob again gets a fresh URL: its old one is revoked.
setSrc(b);
v.expect(shown(node)).toBe('blob:test/3');

await remove();
v.expect(live.size).toBe(0);
},
);

v.test(
'out of bounds, the URL the <img> still shows lives until it moves off',
async () => {
const [src, setSrc] = s.createSignal<Blob>(blob());
const [x, setX] = s.createSignal(0);
const { node, remove } = await renderImage((ref) => (
<view ref={ref} x={x()} width={10} height={10} src={src()} />
));
v.expect(shown(node)).toBe('blob:test/1');

setX(100_000);
await settle();
setSrc(blob());
setSrc(blob());
// The <img> still shows #1; #2 was never shown, so it is revoked.
v.expect(shown(node)).toBe('blob:test/1');
v.expect(live).toEqual(new Set(['blob:test/1', 'blob:test/3']));

setX(0);
await settle();
v.expect(shown(node)).toBe('blob:test/3');
v.expect(live).toEqual(new Set(['blob:test/3']));

await remove();
v.expect(live.size).toBe(0);
},
);

v.test('a destroyed node makes no new URL when restyled', async () => {
const { node, remove } = await renderImage((ref) => (
<view ref={ref} width={10} height={10} src={blob()} />
));
await remove();
v.expect(node.destroyed).toBe(true);

// An animation or effect that outlives the node keeps writing to it.
node.alpha = 0.5;
node.src = blob() as unknown as string;
v.expect(made).toBe(1);
v.expect(live.size).toBe(0);
});

v.test('a SubTexture of a Blob ImageTexture shows the Blob', async () => {
const image = lng.renderer.createTexture('ImageTexture', { src: blob() });
const sub = lng.renderer.createTexture('SubTexture', {
texture: image,
x: 2,
y: 3,
w: 4,
h: 5,
});
const { node, remove } = await renderImage((ref) => (
<view ref={ref} width={4} height={5} texture={sub} />
));

v.expect(shown(node)).toBe('blob:test/1');
await remove();
v.expect(live.size).toBe(0);
});
});
47 changes: 47 additions & 0 deletions tests/webgl/blobSrc.test.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
/**
* A Blob `src` on the real renderer: `<view src={blob}>` reaches the renderer
* node and loads, as a URL src does. The DOM renderer half is
* tests/blobSrc.test.tsx.
*
* pnpm test:webgl
*/
import * as v from 'vitest';
import type { ElementNode } from '@solidtv/solid';
import atlasUrl from './fonts/Lato-Regular.msdf.png?url';
import { render, settle } from './setup.js';

v.test('<view src={blob}> loads the Blob', async () => {
const blob = await (await fetch(atlasUrl)).blob();
let el!: ElementNode;
let dimensions: unknown;
const failed = v.vi.fn();

const dispose = render(() => (
<view
ref={el}
width={100}
height={100}
src={blob}
onEvent={{
loaded: (_el: ElementNode, payload: { dimensions: unknown }) => {
dimensions = payload.dimensions;
},
failed,
}}
/>
));

await v.vi.waitFor(() => v.expect(dimensions).toBeDefined(), {
timeout: 5000,
});
await settle();

v.expect(el.src).toBe(blob);
v.expect(el.lng.src).toBe(blob);
v.expect(failed).not.toHaveBeenCalled();
v.expect(dimensions).toMatchObject({
w: v.expect.any(Number),
h: v.expect.any(Number),
});
dispose();
});
1 change: 1 addition & 0 deletions vitest.browser.config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@ export default defineConfig(() => ({
// (vitest.config.ts defines SOLIDTV_DOM_RENDERING; here Solid renders
// through WebGL, so they fail), and publicApi (node:fs). The other
// contract files pass here.
'tests/blobSrc.test.tsx',
'tests/contract-lazy.test.tsx',
'tests/contract-nodes.test.tsx',
'tests/contract-row-column.test.tsx',
Expand Down
Loading