Skip to content

armgit / raea

Public Imported from GitHub
0

Render Anything Engine: tell your AI what to make. Videos, motion graphics, 3D and games as React and TypeScript, rendered on your own GPU. Rust + Bevy, macOS, Linux and Windows.

A loaded new Image() has the picture's size (#253) (#255)

shanee70d9c79c165
diff --git a/docs/manual/guides/web-components.md b/docs/manual/guides/web-components.md
index f393d481..3d57cea1 100644
--- a/docs/manual/guides/web-components.md
+++ b/docs/manual/guides/web-components.md
@@ -66,7 +66,9 @@ else throws a SyntaxError, as Chrome's does.
that doesn't load rejects, and the text falls back.
- `window` has `innerWidth`, `innerHeight` and `devicePixelRatio` for the composition's size, and `getComputedStyle`.
- `requestAnimationFrame` calls back once per frame drawn, given that frame's time, so a frame drawn again gets the
- same calls. `new Image()` fires `load` when its `src` is set, with no pixel size.
+ same calls. `new Image()` fires `load` when its `src` is set (a `staticFile` path, a data: URL or an http URL), and
+ by then `naturalWidth` and `naturalHeight` are the picture's size; `width` and `height` are the ones you gave, else
+ the same. A file that isn't there fires `error` instead.
- `ResizeObserver` calls back once when it starts observing, then after any layout that changed an observed element's
size, with `contentRect`, `borderBoxSize` and `contentBoxSize`.
@@ -75,7 +77,6 @@ else throws a SyntaxError, as Chrome's does.
- `MutationObserver` and `IntersectionObserver` exist, so a component that makes one doesn't throw, but they never
call back.
- An `<img>`'s `onError` never fires: an image that doesn't load fails the render, naming its src.
-- `new Image()` has no `naturalWidth` or `naturalHeight` (they stay 0).
- An element has no `innerHTML` or `outerHTML`: read `textContent`, or walk `children` and `childNodes`.
- A Range across wrapped lines is one rect, not one per line, and an inline element's `getClientRects()` is one rect
too.
diff --git a/sdk/raea/conformance/frame-globals.test.ts b/sdk/raea/conformance/frame-globals.test.ts
index d6d3fc3a..88dbf4c6 100644
--- a/sdk/raea/conformance/frame-globals.test.ts
+++ b/sdk/raea/conformance/frame-globals.test.ts
@@ -41,3 +41,59 @@ test("an Image's load fires once its src is set", async () => {
await Promise.resolve();
expect([seen, img.complete, img.src]).toEqual([["onload", "listener"], true, "/media/x.png"]);
});
+
+// #253: a loaded Image has the picture's size (a canvas sized from it was 0 high, and its CanvasTexture refused)
+const host = globalThis as { __raea_call?: (n: string, j: string) => string | undefined };
+const loaded = (img: any) => new Promise<string>((ok) => {
+ img.onload = () => ok("load");
+ img.onerror = () => ok("error");
+});
+
+test("a loaded Image's width, height and natural size are the picture's, from the host (asset.load)", async () => {
+ const calls: string[] = [];
+ host.__raea_call = (name, json) => {
+ calls.push(`${name} ${json}`);
+ return name === "asset.load" ? JSON.stringify({ path: "/edit/public/site.png", bytes: 999, width: 400, height: 300 }) : undefined;
+ };
+ try {
+ const img = new ours.Image();
+ const done = loaded(img);
+ img.src = "/media/site.png";
+ expect([img.naturalWidth, img.width]).toEqual([0, 0]);
+ expect(await done).toBe("load");
+ expect([img.width, img.height, img.naturalWidth, img.naturalHeight]).toEqual([400, 300, 400, 300]);
+ expect(calls).toEqual([`asset.load {"path":"/media/site.png"}`]);
+ // width and height given (the constructor's, or set) stay as given; the natural size is still the picture's
+ const sized = new ours.Image(50, 20);
+ const both = loaded(sized);
+ sized.src = "/media/site.png";
+ await both;
+ expect([sized.width, sized.height, sized.naturalWidth, sized.naturalHeight]).toEqual([50, 20, 400, 300]);
+ sized.height = 10;
+ expect([sized.width, sized.height]).toEqual([50, 10]);
+ } finally {
+ delete host.__raea_call;
+ }
+});
+
+test("a data: URL Image's size comes from its header; a file the host can't find fires error", async () => {
+ // a 3 x 2 PNG
+ const png = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAMAAAACCAYAAACddGYaAAAAEklEQVR4nGP4z8DwH4YZYBwAaG8H+VKwN2UAAAAASUVORK5CYII=";
+ const img = new ours.Image();
+ const done = loaded(img);
+ img.src = png;
+ expect(await done).toBe("load");
+ expect([img.width, img.height, img.naturalWidth, img.naturalHeight]).toEqual([3, 2, 3, 2]);
+ host.__raea_call = () => {
+ throw new Error("asset.load: asset /media/gone.png: No such file or directory");
+ };
+ try {
+ const gone = new ours.Image();
+ const failed = loaded(gone);
+ gone.src = "/media/gone.png";
+ expect(await failed).toBe("error");
+ expect([gone.complete, gone.naturalWidth, gone.width]).toEqual([true, 0, 0]);
+ } finally {
+ delete host.__raea_call;
+ }
+});
diff --git a/sdk/raea/src/frame-globals.ts b/sdk/raea/src/frame-globals.ts
index fd49d85d..c1d01129 100644
--- a/sdk/raea/src/frame-globals.ts
+++ b/sdk/raea/src/frame-globals.ts
@@ -2,8 +2,13 @@
// for a web page call them. requestAnimationFrame's callbacks run once per frame the composition draws, given that frame's
// time (f * 1000 / fps ms), so a frame drawn again (a resumed render, `--at`) gets the same calls; one asked for while a
// frame draws runs at the next frame. `new Image()` loads: setting its src fires load (and onload) on the next microtask,
-// so a preload resolves. It has no pixel size (naturalWidth and the rest stay 0): nothing reads a file's size
-// synchronously here, and `<img>` draws the file itself.
+// so a preload resolves, and by then naturalWidth and naturalHeight are the picture's size (#253): a data: URL's from its
+// header, a file's or URL's from the host (native asset.load, which finds staticFile's /media/ paths as <Img> does).
+// width and height are the ones given (the constructor's, or set) else the natural size, as a browser has them. A file
+// the host can't find fires error (and onerror) instead. Under plain bun, with no host, a file's size stays 0.
+
+import { hasNative, native } from "@raea/app/native";
+import { sniffSize } from "@raea/ui/canvas";
type FrameCallback = (time: number) => void;
@@ -54,13 +59,20 @@ export function frameCallbacks(f: number, fps: number): void {
type Listener = (e: { type: string; target: unknown; currentTarget: unknown }) => void;
-/** A preloadable image: its src set, load fires. */
+/** A picture's size: a data: URL's from its header, anything else from the host (asset.load); null when it has none
+ * (no host, or a format the header doesn't say). Throws the host's error for a file that isn't there. */
+function pictureSize(src: string): [number, number] | null {
+ if (src.startsWith("data:")) return sniffSize(src);
+ if (src.startsWith("blob:") || !hasNative()) return null;
+ const got = native("asset.load", { path: src });
+ return got && typeof got.width === "number" && typeof got.height === "number" ? [got.width, got.height] : null;
+}
+
+/** A preloadable image: its src set, load fires, with the picture's size. */
class FrameImage {
onload: Listener | null = null;
onerror: Listener | null = null;
complete = true;
- width = 0;
- height = 0;
naturalWidth = 0;
naturalHeight = 0;
alt = "";
@@ -68,11 +80,30 @@ class FrameImage {
decoding = "auto";
loading = "eager";
#src = "";
+ #width: number | null;
+ #height: number | null;
+ #loads = 0;
#listeners = new Map<string, Set<Listener>>();
constructor(width?: number, height?: number) {
- this.width = width ?? 0;
- this.height = height ?? 0;
+ this.#width = width ?? null;
+ this.#height = height ?? null;
+ }
+
+ get width(): number {
+ return this.#width ?? this.naturalWidth;
+ }
+
+ set width(v: number) {
+ this.#width = Number(v) || 0;
+ }
+
+ get height(): number {
+ return this.#height ?? this.naturalHeight;
+ }
+
+ set height(v: number) {
+ this.#height = Number(v) || 0;
}
get src(): string {
@@ -80,13 +111,27 @@ class FrameImage {
}
set src(v: string) {
- this.#src = String(v);
+ const src = String(v);
+ this.#src = src;
this.complete = false;
+ this.naturalWidth = 0;
+ this.naturalHeight = 0;
+ const load = ++this.#loads;
queueMicrotask(() => {
+ // a src set again before this one loaded: only the last one's load fires, as in a browser
+ if (load !== this.#loads) return;
+ let type = "load";
+ try {
+ const size = pictureSize(src);
+ if (size) [this.naturalWidth, this.naturalHeight] = size;
+ } catch (err) {
+ type = "error";
+ console.warn(`new Image(): ${src} didn't load: ${err instanceof Error ? err.message : String(err)}`);
+ }
this.complete = true;
- const e = { type: "load", target: this, currentTarget: this };
- this.onload?.call(this, e);
- for (const l of this.#listeners.get("load") ?? []) l.call(this, e);
+ const e = { type, target: this, currentTarget: this };
+ (type === "load" ? this.onload : this.onerror)?.call(this, e);
+ for (const l of this.#listeners.get(type) ?? []) l.call(this, e);
});
}