ソースを参照

Fix more browser polyfils

Johannes Zellner 1 週間 前
親
コミット
c746da5f08
8 ファイル変更、817 行追加、49 行削除
  1. 43 7
      AGENTS.md
  2. 221 14
      browser.c
  3. 72 6
      browser_html.c
  4. 1 1
      docs/graphics.html
  5. 0 0
      docs/userland.html
  6. 229 11
      js_browser.c
  7. 62 4
      js_mu.c
  8. 189 6
      js_prelude.js

+ 43 - 7
AGENTS.md

@@ -1388,11 +1388,38 @@ it to `0x7E00`.  The kernel region itself only has one wall (`_end` below
   `File`/`FormData` (urlencoded only), `AbortController`,
   `File`/`FormData` (urlencoded only), `AbortController`,
   `localStorage`/`sessionStorage` (a Proxy, so `localStorage.token = x`
   `localStorage`/`sessionStorage` (a Proxy, so `localStorage.token = x`
   works), `crypto.getRandomValues`/`randomUUID`/`subtle.digest("SHA-256")`
   works), `crypto.getRandomValues`/`randomUUID`/`subtle.digest("SHA-256")`
-  (PKCE), inert `MutationObserver`/`ResizeObserver`/`IntersectionObserver`,
+  (PKCE; `queueMicrotask` uses the engine's Promise captured at startup,
+  because core-js swaps in a Promise polyfill that schedules through
+  `queueMicrotask`, and `PromiseRejectionEvent` exists so it keeps the
+  native one), inert `MutationObserver`/`ResizeObserver`, an
+  `IntersectionObserver` that reports every observed target visible once
+  (batched into one timer, capped at 400 per page; `IntersectionObserverEntry`
+  exists so the common polyfill keeps it), Custom Elements
+  (`customElements.define/get/whenDefined/upgrade`: `HTMLElement` as a base
+  constructor returns the element being upgraded with its prototype
+  switched to the subclass, as the polyfills do; upgrades run on
+  `createElement` and from a scan after any DOM change (`__nb_ce_scan`,
+  called from the tick when `host.changed` fired), `connectedCallback` runs
+  once the element is connected, `attributeChangedCallback` only for the
+  observed attributes present at upgrade), script-created `<img>` elements
+  that fire `load` once they have a `src` (preload-then-swap code),
+  `DocumentType`/`Attr` classes, `document.dispatchEvent` and
+  `window.dispatchEvent`,
   `instanceof`-able DOM classes (`HTMLElement`, `Node`, ...), and Element
   `instanceof`-able DOM classes (`HTMLElement`, `Node`, ...), and Element
   methods (`closest`, `append`/`prepend`/`before`/`after`, `replaceWith`,
   methods (`closest`, `append`/`prepend`/`before`/`after`, `replaceWith`,
   `insertAdjacentHTML`, `toggleAttribute`, `*AttributeNS`) on the node
   `insertAdjacentHTML`, `toggleAttribute`, `*AttributeNS`) on the node
-  wrappers' own prototype.  fetch()/XHR are synchronous inside a Promise:
+  wrappers' own prototype.  A node wrapper resolves names through the C
+  hook, then its own expandos (the backing object), then its real
+  prototype chain with the wrapper as receiver (`js_mu.c`), so prototype
+  getters/setters see the element and a Custom Element upgrade's prototype
+  takes effect.  `innerHTML`/`outerHTML` serialize the live tree (escaped
+  text, raw `script`/`style` text, quoted attributes, no end tag for void
+  elements; 2 MB cap).  Attribute values in the getAttribute list are
+  entity-decoded (`&amp; &lt; &gt; &quot; &#39; &apos;` and ASCII numeric
+  references), and text set through `innerHTML` is decoded like the page
+  parser's.  `isConnected` is true when the top ancestor is a child of the
+  document root.  The timer table holds 1024 timers and a tick runs up to
+  32 due ones (heise's components each await `setTimeout(0)`).  fetch()/XHR are synchronous inside a Promise:
   `js_host_http` submits `X <method> <len> <ctype> <url>` to a helper and
   `js_host_http` submits `X <method> <len> <ctype> <url>` to a helper and
   returns the status and body whatever the HTTP status (2 MB response, 16 KB
   returns the status and body whatever the HTTP status (2 MB response, 16 KB
   request body).  Web Storage is stored in `/share/bls<origin-hash>`
   request body).  Web Storage is stored in `/share/bls<origin-hash>`
@@ -1422,7 +1449,12 @@ it to `0x7E00`.  The kernel region itself only has one wall (`_end` below
   between fragments of the same page do the same (hash-routed apps such as
   between fragments of the same page do the same (hash-routed apps such as
   the Cloudron dashboard would otherwise reload on every menu click).
   the Cloudron dashboard would otherwise reload on every menu click).
   Clicks on plain elements with listeners (`div role="button"`) reach the
   Clicks on plain elements with listeners (`div role="button"`) reach the
-  innermost laid-out box under the pointer.  `<select>` exposes `options`
+  innermost laid-out box under the pointer; a `<button>` with element
+  content (an icon `<svg>`) is laid out like a normal element instead of a
+  "Submit" control.  An `<img>` reuses an already decoded bitmap with the
+  same URL (`br_image.url_hash`), and `.svg` sources are no longer skipped.
+  CSS `gap`/`column-gap` are parsed from the value (they used to be read
+  from the block start and were ignored).  `<select>` exposes `options`
   and `multiple`, and an `<option>` without `value` reports its text.
   and `multiple`, and an `<option>` without `value` reports its text.
   `offsetWidth`/`clientWidth` of an element without a laid-out box report
   `offsetWidth`/`clientWidth` of an element without a laid-out box report
   the viewport width (Vue apps measure on mount and picked a phone layout
   the viewport width (Vue apps measure on mount and picked a phone layout
@@ -1517,7 +1549,11 @@ it to `0x7E00`.  The kernel region itself only has one wall (`_end` below
   cheap header probe; `img_decode()` returns `struct img_image`; `img_draw()`
   cheap header probe; `img_decode()` returns `struct img_image`; `img_draw()`
   is a clipped, scaled (box-filter down, bilinear up) RGB565 blit with alpha
   is a clipped, scaled (box-filter down, bilinear up) RGB565 blit with alpha
   over a checkerboard or over the destination (for the browser and chat).  Progressive
   over a checkerboard or over the destination (for the browser and chat).  Progressive
-  JPEG (successive approximation), EXIF orientation, ICO/CUR, PAM and
+  JPEG (successive approximation), EXIF orientation, ICO/CUR, PAM, SVG
+  files in the browser (an SVG body is parsed into a detached subtree of
+  the page and drawn by the inline-SVG renderer into an RGB565 + alpha
+  bitmap: intrinsic size from width/height/viewBox, drawn at up to 4x for
+  small icons, `currentColor` black, no `<text>`) and
   animated GIF frames are supported as well; arithmetic JPEG/CMYK are not.
   animated GIF frames are supported as well; arithmetic JPEG/CMYK are not.
   The viewer, `ucmd_view.c`, owns a canvas window and reads its file through
   The viewer, `ucmd_view.c`, owns a canvas window and reads its file through
   `SYS_READ_FILE`; it uses fit/1:1/zoom/pan, shows format/dimensions/size,
   `SYS_READ_FILE`; it uses fit/1:1/zoom/pan, shows format/dimensions/size,
@@ -2193,7 +2229,8 @@ and the WM falls back to polling (`io_keyboard_irq_masked()`).
     urlencoded (no multipart/files), only `Content-Type` is forwarded from
     urlencoded (no multipart/files), only `Content-Type` is forwarded from
     request headers, response headers other than `Content-Type` are not
     request headers, response headers other than `Content-Type` are not
     exposed, bodies are text (Latin-1/UTF-8, no binary `arrayBuffer`),
     exposed, bodies are text (Latin-1/UTF-8, no binary `arrayBuffer`),
-    CORS is not enforced, and the observers never fire.  Module loading is
+    CORS is not enforced, Mutation/ResizeObservers never fire and the
+    IntersectionObserver always reports "visible".  Module loading is
     sequential apart from the modulepreload pass.  `crypto` entropy is the
     sequential apart from the modulepreload pass.  `crypto` entropy is the
     weak Math.random/clock mix (fine for PKCE nonces, like the TLS DRBG).
     weak Math.random/clock mix (fine for PKCE nonces, like the TLS DRBG).
     On QEMU's NE2000 the four parallel module downloads can overrun its
     On QEMU's NE2000 the four parallel module downloads can overrun its
@@ -2207,8 +2244,7 @@ and the WM falls back to polling (`io_keyboard_irq_masked()`).
     pseudo-elements inside flex/grid containers are not emitted).
     pseudo-elements inside flex/grid containers are not emitted).
     `getComputedStyle` returns the engine's
     `getComputedStyle` returns the engine's
     known properties (display, box metrics, colours, fonts, borders,
     known properties (display, box metrics, colours, fonts, borders,
-    background and transform state), `outerHTML` returns only the string last
-    assigned to `innerHTML`, and `style`/`dataset` cover inline state rather
+    background and transform state), and `style`/`dataset` cover inline state rather
     than computed style.  Libraries that need those APIs (jQuery plugins
     than computed style.  Libraries that need those APIs (jQuery plugins
     beyond Bootstrap's tooltip, Angular apps that use `$http`) still log
     beyond Bootstrap's tooltip, Angular apps that use `$http`) still log
     errors even though the static page renders.  CSS also lacks multiple
     errors even though the static page renders.  CSS also lacks multiple

+ 221 - 14
browser.c

@@ -95,6 +95,7 @@ struct br_image {
 	int state;                  /* 0 empty, 1 ready */
 	int state;                  /* 0 empty, 1 ready */
 	struct img_image img;       /* scaled bitmap at <= BR_IMG_LAYOUT_W */
 	struct img_image img;       /* scaled bitmap at <= BR_IMG_LAYOUT_W */
 	int native_w, native_h;
 	int native_w, native_h;
+	unsigned int url_hash;      /* <img> source, 0 = not shareable */
 	char err[32];
 	char err[32];
 };
 };
 
 
@@ -408,6 +409,22 @@ static void form_reset_state(void)
 	form_focus = 0;
 	form_focus = 0;
 }
 }
 
 
+/* A <button> with element content (an icon <svg>/<img>, a <span> label)
+ * is laid out like a normal element so that content shows; only a text or
+ * empty button is drawn as a native control.  Clicks still reach it
+ * through the box hit test. */
+static int button_has_elements(unsigned int node)
+{
+	unsigned int c;
+
+	if (node >= doc.nnode || doc.nodes[node].tag != BR_TAG_BUTTON)
+		return 0;
+	for (c = doc.nodes[node].first; c; c = doc.nodes[c].next)
+		if (doc.nodes[c].type == BR_NODE_ELEM)
+			return 1;
+	return 0;
+}
+
 static int form_is_control(unsigned int node)
 static int form_is_control(unsigned int node)
 {
 {
 	unsigned int tag;
 	unsigned int tag;
@@ -416,7 +433,8 @@ static int form_is_control(unsigned int node)
 		return 0;
 		return 0;
 	tag = doc.nodes[node].tag;
 	tag = doc.nodes[node].tag;
 	return tag == BR_TAG_INPUT || tag == BR_TAG_TEXTAREA ||
 	return tag == BR_TAG_INPUT || tag == BR_TAG_TEXTAREA ||
-	       tag == BR_TAG_SELECT || tag == BR_TAG_BUTTON;
+	       tag == BR_TAG_SELECT ||
+	       (tag == BR_TAG_BUTTON && !button_has_elements(node));
 }
 }
 
 
 #define HIT_MAX 96
 #define HIT_MAX 96
@@ -2042,6 +2060,10 @@ static void decode_arena_put(void)
 /* box_w/box_h: the laid-out box a background image paints, or 0.  The
 /* box_w/box_h: the laid-out box a background image paints, or 0.  The
  * bitmap then only needs to cover that box (an app-store icon is 48 px), not
  * bitmap then only needs to cover that box (an app-store icon is 48 px), not
  * BR_IMG_LAYOUT_W, which keeps hundreds of small images inside the budget. */
  * BR_IMG_LAYOUT_W, which keeps hundreds of small images inside the budget. */
+static int svg_text_sniff(const unsigned char *d, unsigned int len);
+static int svg_decode_image(const unsigned char *data, unsigned int len,
+			    struct br_image *bi, int box_w, int box_h);
+
 static int decode_image_data(const unsigned char *data, unsigned int len,
 static int decode_image_data(const unsigned char *data, unsigned int len,
 			     struct br_image *bi, int box_w, int box_h)
 			     struct br_image *bi, int box_w, int box_h)
 {
 {
@@ -2055,7 +2077,10 @@ static int decode_image_data(const unsigned char *data, unsigned int len,
 	unsigned char *alpha = 0;
 	unsigned char *alpha = 0;
 	int dw, dh, r;
 	int dw, dh, r;
 
 
+	bi->url_hash = 0;
 	if (img_sniff(data, len, &info) != 0) {
 	if (img_sniff(data, len, &info) != 0) {
+		if (svg_text_sniff(data, len))
+			return svg_decode_image(data, len, bi, box_w, box_h);
 		s_copy(bi->err, "unknown image format", sizeof(bi->err));
 		s_copy(bi->err, "unknown image format", sizeof(bi->err));
 		return -1;
 		return -1;
 	}
 	}
@@ -4028,7 +4053,8 @@ static void preload_job_error(struct fetch_worker *w)
 }
 }
 
 
 static void preload_decode(unsigned int node, int bg,
 static void preload_decode(unsigned int node, int bg,
-			   const unsigned char *data, unsigned int len)
+			   const unsigned char *data, unsigned int len,
+			   const char *url)
 {
 {
 	if (image_count >= BR_MAX_IMAGES) {
 	if (image_count >= BR_MAX_IMAGES) {
 		if (bg)
 		if (bg)
@@ -4042,6 +4068,12 @@ static void preload_decode(unsigned int node, int bg,
 			      layout_boxes[node].valid ? layout_boxes[node].w : 0,
 			      layout_boxes[node].valid ? layout_boxes[node].w : 0,
 			      bg && node < BR_MAX_NODES &&
 			      bg && node < BR_MAX_NODES &&
 			      layout_boxes[node].valid ? layout_boxes[node].h : 0) == 0) {
 			      layout_boxes[node].valid ? layout_boxes[node].h : 0) == 0) {
+		/* An <img> bitmap only depends on its URL, so the next
+		 * <img> with the same source reuses it (heise repeats one
+		 * comment icon 85 times).  Backgrounds are scaled to their
+		 * box and are not shared. */
+		images[image_count].url_hash =
+			!bg && url ? script_cache_hash(url) | 1u : 0;
 		if (bg)
 		if (bg)
 			doc.nodes[node].bg_img_index = (short)image_count;
 			doc.nodes[node].bg_img_index = (short)image_count;
 		else
 		else
@@ -4078,7 +4110,7 @@ static int preload_finish_worker(struct fetch_worker *w)
 				    &tr, err, sizeof(err));
 				    &tr, err, sizeof(err));
 	if (rv >= 0)
 	if (rv >= 0)
 		preload_decode(w->node, w->bg, image_file_buf,
 		preload_decode(w->node, w->bg, image_file_buf,
-			       (unsigned int)rv);
+			       (unsigned int)rv, w->url);
 	else
 	else
 		preload_job_error(w);
 		preload_job_error(w);
 	fetch_worker_release(w);
 	fetch_worker_release(w);
@@ -4130,7 +4162,6 @@ static int preload_fill_jobs(void)
 						continue;
 						continue;
 					}
 					}
 					if (bsrc[0] &&
 					if (bsrc[0] &&
-					    !contains_ci(bsrc, ".svg") &&
 					    !starts_with(bsrc, "data:") &&
 					    !starts_with(bsrc, "data:") &&
 					    resolve_link(page_url, bsrc, url,
 					    resolve_link(page_url, bsrc, url,
 							 sizeof(url)) == 0) {
 							 sizeof(url)) == 0) {
@@ -4150,7 +4181,7 @@ static int preload_fill_jobs(void)
 									&data, &len,
 									&data, &len,
 									err,
 									err,
 									sizeof(err)) == 0)
 									sizeof(err)) == 0)
-								preload_decode(i, 1, data, len);
+								preload_decode(i, 1, data, len, 0);
 							else
 							else
 								nd->bg_img_index = -2;
 								nd->bg_img_index = -2;
 							continue;
 							continue;
@@ -4192,8 +4223,7 @@ static int preload_fill_jobs(void)
 			continue;
 			continue;
 		}
 		}
 		src = br_src(&doc, i);
 		src = br_src(&doc, i);
-		if (!src[0] || contains_ci(src, ".svg") ||
-		    starts_with(src, "data:")) {
+		if (!src[0] || starts_with(src, "data:")) {
 			preload_node++;
 			preload_node++;
 			continue;
 			continue;
 		}
 		}
@@ -4215,6 +4245,22 @@ static int preload_fill_jobs(void)
 			continue;
 			continue;
 		}
 		}
 
 
+		{
+			unsigned int uh = script_cache_hash(url) | 1u;
+			int k;
+
+			for (k = 0; k < image_count; k++)
+				if (images[k].state == 1 &&
+				    images[k].url_hash == uh)
+					break;
+			if (k < image_count) {
+				nd->img_index = (short)k;
+				layout_valid = 0;
+				preload_node = i + 1;
+				ngui_invalidate(&ui);
+				continue;
+			}
+		}
 		if (url[0] == '/') {
 		if (url[0] == '/') {
 			unsigned char *data = 0;
 			unsigned char *data = 0;
 			unsigned int len = 0;
 			unsigned int len = 0;
@@ -4222,7 +4268,7 @@ static int preload_fill_jobs(void)
 			preload_node = i + 1;
 			preload_node = i + 1;
 			if (fetch_image(url, BR_IMG_FILE_MAX, &data, &len,
 			if (fetch_image(url, BR_IMG_FILE_MAX, &data, &len,
 					err, sizeof(err)) == 0)
 					err, sizeof(err)) == 0)
-				preload_decode(i, 0, data, len);
+				preload_decode(i, 0, data, len, url);
 			else
 			else
 				nd->img_index = -2;
 				nd->img_index = -2;
 			continue;
 			continue;
@@ -6959,6 +7005,165 @@ static struct svg_cache_ent *svg_layer(unsigned int node, int w, int h,
 	return e;
 	return e;
 }
 }
 
 
+/* ---- SVG files as images (<img src="logo.svg">, CSS backgrounds) ----
+ *
+ * The markup is parsed into a detached subtree of the page document and
+ * drawn with the inline-SVG renderer above into a fresh RGB565 + alpha
+ * bitmap, which then behaves like any decoded image.  currentColor is
+ * black (an image has no inherited text colour); <text> is not drawn. */
+static int svg_text_sniff(const unsigned char *d, unsigned int len)
+{
+	unsigned int i = 0;
+
+	if (len >= 3 && d[0] == 0xEF && d[1] == 0xBB && d[2] == 0xBF)
+		i = 3;
+	while (i < len) {
+		while (i < len && (d[i] == ' ' || d[i] == '\t' ||
+				   d[i] == '\r' || d[i] == '\n'))
+			i++;
+		if (i + 4 <= len && !memcmp(d + i, "<svg", 4))
+			return 1;
+		if (i + 4 <= len && !memcmp(d + i, "<!--", 4)) {
+			i += 4;
+			while (i + 3 <= len && memcmp(d + i, "-->", 3))
+				i++;
+			i += 3;
+			continue;
+		}
+		if (i + 1 < len && d[i] == '<' && (d[i + 1] == '?' || d[i + 1] == '!')) {
+			while (i < len && d[i] != '>')
+				i++;
+			i++;
+			continue;
+		}
+		return 0;
+	}
+	return 0;
+}
+
+static int svg_len_attr(unsigned int node, const char *name)
+{
+	const char *v = br_find_attr(&doc, node, name);
+	int n = 0, any = 0;
+
+	if (!v)
+		return 0;
+	while (*v == ' ')
+		v++;
+	while (*v >= '0' && *v <= '9') {
+		n = n * 10 + (*v++ - '0');
+		any = 1;
+	}
+	if (*v == '.')
+		while (*++v >= '0' && *v <= '9')
+			;
+	if (!any || *v == '%')
+		return 0;
+	return n;
+}
+
+static int svg_decode_image(const unsigned char *data, unsigned int len,
+			    struct br_image *bi, int box_w, int box_h)
+{
+	unsigned int holder, svg = 0, c, need, i;
+	struct br_style base = base_style(), st;
+	struct svgr_layer L;
+	double vb[4], m[6];
+	int w, h, have_vb, nat_w, nat_h;
+
+	holder = br_create_element(&doc, "div", 3);
+	if (!holder) {
+		s_copy(bi->err, "page is full", sizeof(bi->err));
+		return -1;
+	}
+	holder--;
+	br_set_inner_html(&doc, holder, (const char *)data, len);
+	for (c = doc.nodes[holder].first; c; c = doc.nodes[c].next)
+		if (doc.nodes[c].type == BR_NODE_ELEM &&
+		    doc.nodes[c].tag == BR_TAG_SVG) {
+			svg = c;
+			break;
+		}
+	if (!svg) {
+		s_copy(bi->err, "bad SVG", sizeof(bi->err));
+		return -1;
+	}
+	have_vb = svg_viewbox4(svg, vb) && vb[2] > 0 && vb[3] > 0;
+	w = svg_len_attr(svg, "width");
+	h = svg_len_attr(svg, "height");
+	if (box_w > 0 && box_h > 0) {
+		w = box_w;
+		h = box_h;
+	} else if (!w && !h) {
+		w = have_vb ? (int)(vb[2] + 0.5) : 150;
+		h = have_vb ? (int)(vb[3] + 0.5) : 150;
+	} else if (!w) {
+		w = have_vb ? (int)(h * vb[2] / vb[3] + 0.5) : h;
+	} else if (!h) {
+		h = have_vb ? (int)(w * vb[3] / vb[2] + 0.5) : w;
+	}
+	/* Layout uses the intrinsic size; small icons are drawn at up to 4x
+	 * so CSS scaling stays crisp. */
+	nat_w = w;
+	nat_h = h;
+	while (w < 96 && h < 96 && w * h > 0 && w * 2 <= 384) {
+		w *= 2;
+		h *= 2;
+	}
+	if (w > BR_IMG_LAYOUT_W) {
+		h = (int)((long)h * BR_IMG_LAYOUT_W / w);
+		w = BR_IMG_LAYOUT_W;
+	}
+	if (h > 2048)
+		h = 2048;
+	if (w < 1)
+		w = 1;
+	if (h < 1)
+		h = 1;
+	need = (unsigned int)w * (unsigned int)h;
+	if (image_pixels + need > BR_IMG_PIXEL_BUDGET) {
+		s_copy(bi->err, "image budget exhausted", sizeof(bi->err));
+		return -1;
+	}
+	if (!svg_geom_buf) {
+		svg_geom_buf = malloc(SVG_MAX_POINTS * (2 * sizeof(float) + 1));
+		if (!svg_geom_buf) {
+			s_copy(bi->err, "out of memory", sizeof(bi->err));
+			return -1;
+		}
+	}
+	svgr_init(&svg_geom, svg_geom_buf, SVG_MAX_POINTS);
+	L.px = (unsigned short *)malloc(need * sizeof(unsigned short));
+	L.a = (unsigned char *)calloc(need, 1);
+	if (!L.px || !L.a) {
+		free(L.px);
+		free(L.a);
+		s_copy(bi->err, "out of memory", sizeof(bi->err));
+		return -1;
+	}
+	for (i = 0; i < need; i++)
+		L.px[i] = 0xFFFF;
+	L.w = w;
+	L.h = h;
+	base.color = 0x0000;
+	br_style_for(&doc, svg, &base, &st);
+	svg_root_matrix(svg, w, h, m);
+	svg_vp_w = have_vb ? vb[2] : w;
+	svg_vp_h = have_vb ? vb[3] : h;
+	svg_draw_children(&L, svg, m, &st, 255, 0);
+	bi->native_w = nat_w;
+	bi->native_h = nat_h;
+	bi->img.format = 0;
+	bi->img.w = (unsigned int)w;
+	bi->img.h = (unsigned int)h;
+	bi->img.px = L.px;
+	bi->img.alpha = L.a;
+	bi->img.flags = 0;
+	bi->state = 1;
+	image_pixels += need;
+	return 0;
+}
+
 /* Intrinsic size of an inline <svg> in a w-wide containing box. */
 /* Intrinsic size of an inline <svg> in a w-wide containing box. */
 static void svg_size(unsigned int node, const struct br_style *st, int cw,
 static void svg_size(unsigned int node, const struct br_style *st, int cw,
 		     int *out_w, int *out_h)
 		     int *out_w, int *out_h)
@@ -7202,10 +7407,11 @@ static void layout_block(struct lay *l, unsigned int node,
 		rel_dx += st->tx;
 		rel_dx += st->tx;
 		rel_dy += st->ty;
 		rel_dy += st->ty;
 	}
 	}
-	if (doc.nodes[node].tag == BR_TAG_INPUT ||
-	    doc.nodes[node].tag == BR_TAG_TEXTAREA ||
-	    doc.nodes[node].tag == BR_TAG_SELECT ||
-	    doc.nodes[node].tag == BR_TAG_BUTTON) {
+	if ((doc.nodes[node].tag == BR_TAG_INPUT ||
+	     doc.nodes[node].tag == BR_TAG_TEXTAREA ||
+	     doc.nodes[node].tag == BR_TAG_SELECT ||
+	     doc.nodes[node].tag == BR_TAG_BUTTON) &&
+	    !button_has_elements(node)) {
 		if (doc.nodes[node].tag == BR_TAG_INPUT &&
 		if (doc.nodes[node].tag == BR_TAG_INPUT &&
 		    s_eq(br_type(&doc, node), "hidden"))
 		    s_eq(br_type(&doc, node), "hidden"))
 			return;
 			return;
@@ -9397,8 +9603,9 @@ static void layout_children(struct lay *l, unsigned int parent,
 			n = nd->next;
 			n = nd->next;
 			continue;
 			continue;
 		}
 		}
-		if (nd->tag == BR_TAG_INPUT || nd->tag == BR_TAG_TEXTAREA ||
-		    nd->tag == BR_TAG_SELECT || nd->tag == BR_TAG_BUTTON) {
+		if ((nd->tag == BR_TAG_INPUT || nd->tag == BR_TAG_TEXTAREA ||
+		     nd->tag == BR_TAG_SELECT || nd->tag == BR_TAG_BUTTON) &&
+		    !button_has_elements(n)) {
 			if (!(nd->tag == BR_TAG_INPUT &&
 			if (!(nd->tag == BR_TAG_INPUT &&
 			      s_eq(br_type(&doc, n), "hidden"))) {
 			      s_eq(br_type(&doc, n), "hidden"))) {
 				form_fill_line = pst->display ==
 				form_fill_line = pst->display ==

+ 72 - 6
browser_html.c

@@ -1280,9 +1280,17 @@ int br_set_inner_html(struct br_doc *d, unsigned int node,
 				i++;
 				i++;
 			end = i;
 			end = i;
 			if (end > start) {
 			if (end > start) {
-				unsigned int h = br_create_text(d, html + start,
-								end - start);
-
+				/* Entities decoded like the page parser does
+				 * (createTextNode stays literal). */
+				char *tb = (char *)malloc(end - start + 1);
+				unsigned int tl = 0, h = 0;
+
+				if (tb) {
+					tl = decode_text(html + start, end - start,
+							 tb, end - start + 1, 1);
+					h = br_create_text(d, tb, tl);
+					free(tb);
+				}
 				if (h)
 				if (h)
 					br_append_child(d, stack[sp - 1], h);
 					br_append_child(d, stack[sp - 1], h);
 			}
 			}
@@ -2004,6 +2012,62 @@ static void note_attr_flag(struct br_node *n, const char *name)
 /* Store a packed name/value list for getAttribute()/selectors.  This is a
 /* Store a packed name/value list for getAttribute()/selectors.  This is a
  * second pass so the block stays contiguous even though the known attributes
  * second pass so the block stays contiguous even though the known attributes
  * above also use the shared attr arena. */
  * above also use the shared attr arena. */
+/* Attribute value copy with the markup entities decoded (&amp; &lt; &gt;
+ * &quot; &#39; &apos; and ASCII numeric references); other bytes are kept
+ * as they are, so URLs and JSON in attributes survive.  Returns the bytes
+ * written. */
+static unsigned int attr_unescape(const char *s, unsigned int len, char *out)
+{
+	static const struct { const char *e; char c; } ents[] = {
+		{ "&amp;", '&' }, { "&lt;", '<' }, { "&gt;", '>' },
+		{ "&quot;", '"' }, { "&apos;", '\'' }, { "&#39;", '\'' },
+		{ 0, 0 }
+	};
+	unsigned int i = 0, n = 0;
+
+	while (i < len) {
+		int k, done = 0;
+
+		if (s[i] == '&') {
+			for (k = 0; ents[k].e; k++) {
+				unsigned int el = (unsigned int)strlen(ents[k].e);
+
+				if (i + el <= len && !memcmp(s + i, ents[k].e, el)) {
+					out[n++] = ents[k].c;
+					i += el;
+					done = 1;
+					break;
+				}
+			}
+			if (!done && i + 3 < len && s[i + 1] == '#') {
+				unsigned int j = i + 2, v = 0;
+				int hex = s[j] == 'x' || s[j] == 'X';
+
+				if (hex)
+					j++;
+				while (j < len && j < i + 10 &&
+				       ((s[j] >= '0' && s[j] <= '9') ||
+					(hex && ((s[j] >= 'a' && s[j] <= 'f') ||
+						 (s[j] >= 'A' && s[j] <= 'F'))))) {
+					char c = s[j++];
+
+					v = v * (hex ? 16 : 10) +
+					    (unsigned int)(c <= '9' ? c - '0' :
+					     (c | 0x20) - 'a' + 10);
+				}
+				if (j < len && s[j] == ';' && v > 0 && v < 128) {
+					out[n++] = (char)v;
+					i = j + 1;
+					done = 1;
+				}
+			}
+		}
+		if (!done)
+			out[n++] = s[i++];
+	}
+	return n;
+}
+
 static void parse_attrs_generic(struct br_doc *d, struct br_node *n,
 static void parse_attrs_generic(struct br_doc *d, struct br_node *n,
 				const char *s, unsigned int len)
 				const char *s, unsigned int len)
 {
 {
@@ -2064,8 +2128,8 @@ static void parse_attrs_generic(struct br_doc *d, struct br_node *n,
 			for (k = 0; k < nl; k++)
 			for (k = 0; k < nl; k++)
 				d->attrs[d->attrs_used++] = name[k];
 				d->attrs[d->attrs_used++] = name[k];
 			d->attrs[d->attrs_used++] = '\0';
 			d->attrs[d->attrs_used++] = '\0';
-			for (k = 0; k < vlen; k++)
-				d->attrs[d->attrs_used++] = s[vstart + k];
+			d->attrs_used += attr_unescape(s + vstart, vlen,
+						d->attrs + d->attrs_used);
 			d->attrs[d->attrs_used++] = '\0';
 			d->attrs[d->attrs_used++] = '\0';
 		}
 		}
 	}
 	}
@@ -5111,7 +5175,9 @@ static void parse_decls(struct br_doc *d, const char *s,
 				}
 				}
 			}
 			}
 		} else if (str_eq(prop, "gap") || str_eq(prop, "column-gap")) {
 		} else if (str_eq(prop, "gap") || str_eq(prop, "column-gap")) {
-			unsigned int gp = 0;
+			/* From the value, not the block start: gap was
+			 * ignored on nearly every site. */
+			unsigned int gp = vstart;
 			unsigned short gv = 0;
 			unsigned short gv = 0;
 			unsigned char gk = 1;
 			unsigned char gk = 1;
 
 

+ 1 - 1
docs/graphics.html

@@ -420,7 +420,7 @@
 			bodies in memory.
 			bodies in memory.
 		</p>
 		</p>
 		<ul>
 		<ul>
-			<li><strong>Formats.</strong> PNG, baseline and progressive JPEG, animated GIF, BMP, TGA, PNM, ICO/CUR and PAM.</li>
+			<li><strong>Formats.</strong> PNG, baseline and progressive JPEG, animated GIF, BMP, TGA, PNM, ICO/CUR and PAM. The browser also takes SVG files (<code>&lt;img src="logo.svg"&gt;</code>, CSS backgrounds): the markup is parsed into a detached subtree and drawn by its inline-SVG renderer into an RGB565 + alpha bitmap.</li>
 			<li><strong>Drawing.</strong> <code>img_draw()</code> is a clipped, scaled RGB565 blit: box-filter downscale, bilinear upscale, alpha over a checkerboard or over the destination.</li>
 			<li><strong>Drawing.</strong> <code>img_draw()</code> is a clipped, scaled RGB565 blit: box-filter downscale, bilinear upscale, alpha over a checkerboard or over the destination.</li>
 			<li><strong>Orientation.</strong> EXIF orientation is applied; arithmetic JPEG and CMYK are rejected.</li>
 			<li><strong>Orientation.</strong> EXIF orientation is applied; arithmetic JPEG and CMYK are rejected.</li>
 			<li><strong>Cost.</strong> Downscaling runs on the CPU. The viewer caches one image; the browser keeps a display bitmap but still rescales on repaint; the chat client caches up to 480x320 message images and 32x32 circular avatars.</li>
 			<li><strong>Cost.</strong> Downscaling runs on the CPU. The viewer caches one image; the browser keeps a display bitmap but still rescales on repaint; the chat client caches up to 480x320 message images and 32x32 circular avatars.</li>

ファイルの差分が大きいため隠しています
+ 0 - 0
docs/userland.html


+ 229 - 11
js_browser.c

@@ -20,7 +20,11 @@
  * bootstrap (AngularJS rendering ~300 cards) needs several seconds on a
  * bootstrap (AngularJS rendering ~300 cards) needs several seconds on a
  * slow CPU, so the budget is generous. */
  * slow CPU, so the budget is generous. */
 #define JS_RUN_LIMIT 20000
 #define JS_RUN_LIMIT 20000
-#define JS_TIMERS 64
+/* Component frameworks schedule a zero-delay timer per element (heise's
+ * base component awaits setTimeout(0) in every connectedCallback): a full
+ * table silently drops timers and those components never start. */
+#define JS_TIMERS 1024
+#define JS_TIMERS_PER_TICK 32
 
 
 struct js_timer {
 struct js_timer {
 	int used;
 	int used;
@@ -78,6 +82,17 @@ static void node_push_text(js_State *state, unsigned int node);
 static void url_resolve(const char *base, const char *rel,
 static void url_resolve(const char *base, const char *rel,
 			char *out, unsigned int cap);
 			char *out, unsigned int cap);
 static int hash_pending;
 static int hash_pending;
+/* Set by every DOM mutation (host.changed is wrapped): the tick then lets
+ * the prelude upgrade/connect new Custom Elements. */
+static int dom_dirty;
+static void (*host_changed_orig)(void);
+
+static void dom_changed(void)
+{
+	dom_dirty = 1;
+	if (host_changed_orig)
+		host_changed_orig();
+}
 
 
 /* One wrapper per DOM node: the same element must have the same object
 /* One wrapper per DOM node: the same element must have the same object
  * identity on every access, or library caches (jQuery expando data, Sizzle)
  * identity on every access, or library caches (jQuery expando data, Sizzle)
@@ -677,6 +692,27 @@ static void node_removelistener(js_State *state)
 	add_listener(state, node, 1);
 	add_listener(state, node, 1);
 }
 }
 
 
+/* document.dispatchEvent / window.dispatchEvent (WebComponentsReady, custom
+ * app events): the same dispatcher, targeting document or window. */
+static void target_dispatchevent(js_State *state, unsigned int target)
+{
+	if (!D || !js_isobject(state, 1)) {
+		js_pushboolean(state, 1);
+		return;
+	}
+	dispatch_object(state, target, 1, "event", 1, 0);
+}
+
+static void doc_dispatchevent(js_State *state)
+{
+	target_dispatchevent(state, JS_TARGET_DOCUMENT);
+}
+
+static void win_dispatchevent(js_State *state)
+{
+	target_dispatchevent(state, JS_TARGET_WINDOW);
+}
+
 static void node_dispatchevent(js_State *state)
 static void node_dispatchevent(js_State *state)
 {
 {
 	unsigned int node = (unsigned int)(uintptr_t)
 	unsigned int node = (unsigned int)(uintptr_t)
@@ -1404,6 +1440,166 @@ static unsigned int class_count(const char *classes)
 	return n;
 	return n;
 }
 }
 
 
+/* ---- innerHTML / outerHTML serialization ---- */
+
+#define JS_SERIALIZE_MAX (2u * 1024u * 1024u)
+
+struct sbuf {
+	char *p;
+	unsigned int n, cap;
+	int full;
+};
+
+static void sb_put(struct sbuf *b, const char *s, unsigned int len)
+{
+	if (b->full)
+		return;
+	if (b->n + len + 1 > b->cap) {
+		unsigned int nc = b->cap ? b->cap : 1024;
+		char *np;
+
+		while (nc < b->n + len + 1)
+			nc *= 2;
+		if (nc > JS_SERIALIZE_MAX) {
+			b->full = 1;
+			return;
+		}
+		np = (char *)realloc(b->p, nc);
+		if (!np) {
+			b->full = 1;
+			return;
+		}
+		b->p = np;
+		b->cap = nc;
+	}
+	memcpy(b->p + b->n, s, len);
+	b->n += len;
+	b->p[b->n] = '\0';
+}
+
+static void sb_str(struct sbuf *b, const char *s)
+{
+	sb_put(b, s, (unsigned int)strlen(s));
+}
+
+static void sb_escaped(struct sbuf *b, const char *s, unsigned int len,
+		       int attr)
+{
+	unsigned int i, start = 0;
+
+	for (i = 0; i < len; i++) {
+		const char *rep = 0;
+
+		if (s[i] == '&')
+			rep = "&amp;";
+		else if (s[i] == '<' && !attr)
+			rep = "&lt;";
+		else if (s[i] == '>' && !attr)
+			rep = "&gt;";
+		else if (s[i] == '"' && attr)
+			rep = "&quot;";
+		else if ((unsigned char)s[i] == 0xA0)
+			rep = "&nbsp;";
+		if (!rep)
+			continue;
+		sb_put(b, s + start, i - start);
+		sb_str(b, rep);
+		start = i + 1;
+	}
+	sb_put(b, s + start, len - start);
+}
+
+static void serialize_node(struct sbuf *b, unsigned int node, int depth);
+
+static void serialize_children(struct sbuf *b, unsigned int node, int depth)
+{
+	unsigned int c;
+
+	for (c = D->nodes[node].first; c && !b->full; c = D->nodes[c].next)
+		serialize_node(b, c, depth + 1);
+}
+
+/* HTML serialization of the parsed tree (lower-case names, quoted
+ * attributes, raw text inside script/style, no end tag for void
+ * elements).  heise reads its JSON config through innerHTML; DOMPurify
+ * returns its result the same way. */
+static void serialize_node(struct sbuf *b, unsigned int node, int depth)
+{
+	struct br_node *n;
+	char name[64];
+	unsigned int i;
+	const char *p, *end;
+
+	if (!D || node >= D->nnode || depth > 200 || b->full)
+		return;
+	n = &D->nodes[node];
+	if (n->type == BR_NODE_TEXT) {
+		unsigned int par = n->parent;
+		int raw = par < D->nnode &&
+			  D->nodes[par].type == BR_NODE_ELEM &&
+			  (D->nodes[par].tag == BR_TAG_SCRIPT ||
+			   D->nodes[par].tag == BR_TAG_STYLE);
+
+		if (raw)
+			sb_put(b, D->text + n->text_off, n->text_len);
+		else
+			sb_escaped(b, D->text + n->text_off, n->text_len, 0);
+		return;
+	}
+	if (n->type == BR_NODE_COMMENT) {
+		sb_str(b, "<!--");
+		sb_put(b, D->text + n->text_off, n->text_len);
+		sb_str(b, "-->");
+		return;
+	}
+	if (n->type == BR_NODE_FRAGMENT) {
+		serialize_children(b, node, depth);
+		return;
+	}
+	node_name(node, name, sizeof(name));
+	for (i = 0; name[i]; i++)
+		if (name[i] >= 'A' && name[i] <= 'Z')
+			name[i] = (char)(name[i] - 'A' + 'a');
+	sb_str(b, "<");
+	sb_str(b, name);
+	p = D->attrs + n->extra_off;
+	end = p + n->extra_len;
+	while (n->extra_len && p + 1 < end) {
+		const char *an = p, *av;
+
+		p += strlen(p) + 1;
+		if (p >= end)
+			break;
+		av = p;
+		p += strlen(p) + 1;
+		sb_str(b, " ");
+		sb_str(b, an);
+		sb_str(b, "=\"");
+		sb_escaped(b, av, (unsigned int)strlen(av), 1);
+		sb_str(b, "\"");
+	}
+	sb_str(b, ">");
+	if (br_tag_is_void(n->tag) && !n->first)
+		return;
+	serialize_children(b, node, depth);
+	sb_str(b, "</");
+	sb_str(b, name);
+	sb_str(b, ">");
+}
+
+static void push_serialized(js_State *state, unsigned int node, int outer)
+{
+	struct sbuf b;
+
+	memset(&b, 0, sizeof(b));
+	if (outer)
+		serialize_node(&b, node, 0);
+	else
+		serialize_children(&b, node, 0);
+	js_pushlstring(state, b.p ? b.p : "", (int)b.n);
+	free(b.p);
+}
+
 static void push_attributes(js_State *state, unsigned int node)
 static void push_attributes(js_State *state, unsigned int node)
 {
 {
 	struct br_node *n;
 	struct br_node *n;
@@ -2004,13 +2200,7 @@ static int node_has(js_State *state, void *p, const char *name)
 		return 1;
 		return 1;
 	}
 	}
 	if (!strcmp(name, "innerHTML") || !strcmp(name, "outerHTML")) {
 	if (!strcmp(name, "innerHTML") || !strcmp(name, "outerHTML")) {
-		char key[32];
-		snprintf(key, sizeof(key), "html_%u", node + 1);
-		js_getregistry(state, key);
-		if (js_isundefined(state, -1)) {
-			js_pop(state, 1);
-			js_pushstring(state, "");
-		}
+		push_serialized(state, node, name[0] == 'o');
 		return 1;
 		return 1;
 	}
 	}
 	if (!strcmp(name, "ownerDocument")) {
 	if (!strcmp(name, "ownerDocument")) {
@@ -2048,11 +2238,18 @@ static int node_has(js_State *state, void *p, const char *name)
 		return 1;
 		return 1;
 	}
 	}
 	if (!strcmp(name, "isConnected")) {
 	if (!strcmp(name, "isConnected")) {
-		unsigned int a = node;
+		/* Connected when the top ancestor hangs off the document root
+		 * (index 0); script-created subtrees also have parent 0 but
+		 * are not among the root's children. */
+		unsigned int a = node, c;
+		int conn = node == 0;
 
 
 		while (a && a < D->nnode && D->nodes[a].parent)
 		while (a && a < D->nnode && D->nodes[a].parent)
 			a = D->nodes[a].parent;
 			a = D->nodes[a].parent;
-		js_pushboolean(state, a == 0 || a == D->root);
+		for (c = D->nodes[0].first; c && !conn; c = D->nodes[c].next)
+			if (c == a)
+				conn = 1;
+		js_pushboolean(state, conn);
 		return 1;
 		return 1;
 	}
 	}
 	if (!strcmp(name, "relList")) {
 	if (!strcmp(name, "relList")) {
@@ -3065,6 +3262,7 @@ static void install_globals(js_State *state)
 	def_func(state, "querySelectorAll", doc_queryselectorall, 1);
 	def_func(state, "querySelectorAll", doc_queryselectorall, 1);
 	def_func(state, "addEventListener", doc_addlistener, 2);
 	def_func(state, "addEventListener", doc_addlistener, 2);
 	def_func(state, "removeEventListener", doc_removelistener, 2);
 	def_func(state, "removeEventListener", doc_removelistener, 2);
+	def_func(state, "dispatchEvent", doc_dispatchevent, 1);
 	def_func(state, "createEvent", doc_createevent, 1);
 	def_func(state, "createEvent", doc_createevent, 1);
 
 
 	h = br_find_tag(D, BR_TAG_HTML);
 	h = br_find_tag(D, BR_TAG_HTML);
@@ -3137,6 +3335,7 @@ static void install_globals(js_State *state)
 	def_global_func(state, "getComputedStyle", win_getcomputedstyle, 1);
 	def_global_func(state, "getComputedStyle", win_getcomputedstyle, 1);
 	def_global_func(state, "addEventListener", win_addlistener, 2);
 	def_global_func(state, "addEventListener", win_addlistener, 2);
 	def_global_func(state, "removeEventListener", win_removelistener, 2);
 	def_global_func(state, "removeEventListener", win_removelistener, 2);
+	def_global_func(state, "dispatchEvent", win_dispatchevent, 1);
 	def_global_func(state, "scrollTo", win_noop, 2);
 	def_global_func(state, "scrollTo", win_noop, 2);
 	def_global_func(state, "scrollBy", win_noop, 2);
 	def_global_func(state, "scrollBy", win_noop, 2);
 	def_global_func(state, "setTimeout", win_settimeout, 1);
 	def_global_func(state, "setTimeout", win_settimeout, 1);
@@ -3214,6 +3413,9 @@ int js_browser_start(struct br_doc *doc, const struct js_browser_host *h)
 		return -1;
 		return -1;
 	D = doc;
 	D = doc;
 	host = *h;
 	host = *h;
+	host_changed_orig = host.changed;
+	host.changed = dom_changed;
+	dom_dirty = 0;
 	current_url = h->page_url;
 	current_url = h->page_url;
 	panic_armed = 0;
 	panic_armed = 0;
 	memset(timers, 0, sizeof(timers));
 	memset(timers, 0, sizeof(timers));
@@ -3305,6 +3507,22 @@ void js_browser_tick(void)
 		if (!J)
 		if (!J)
 			return;
 			return;
 	}
 	}
+	if (dom_dirty) {
+		dom_dirty = 0;
+		js_setlimit(J, JS_RUN_LIMIT, 0);
+		js_getglobal(J, "__nb_ce_scan");
+		if (js_iscallable(J, -1)) {
+			js_pushundefined(J);
+			if (js_pcall(J, 0))
+				report_top(J);
+			else
+				js_pop(J, 1);
+		} else {
+			js_pop(J, 1);
+		}
+		if (!J)
+			return;
+	}
 	now = u_ticks_ms();
 	now = u_ticks_ms();
 	for (i = 0; i < JS_TIMERS; i++) {
 	for (i = 0; i < JS_TIMERS; i++) {
 		if (!timers[i].used ||
 		if (!timers[i].used ||
@@ -3331,7 +3549,7 @@ void js_browser_tick(void)
 				timers[i].used = 0;
 				timers[i].used = 0;
 			}
 			}
 		}
 		}
-		if (++ran >= 4)
+		if (++ran >= JS_TIMERS_PER_TICK)
 			break;
 			break;
 	}
 	}
 	js_runjobs(J);
 	js_runjobs(J);

+ 62 - 4
js_mu.c

@@ -400,6 +400,34 @@ static struct mu_ud *mu_ud_of(JSValueConst obj)
 	return (struct mu_ud *)JS_GetOpaque(obj, mu_ud_class);
 	return (struct mu_ud *)JS_GetOpaque(obj, mu_ud_class);
 }
 }
 
 
+/* Expandos live on the backing object; everything else comes from the
+ * wrapper's own prototype chain with the wrapper as receiver, so a getter
+ * or setter defined on a prototype sees the element as `this`, and a
+ * changed prototype (a Custom Element upgrade) takes effect. */
+static JSValue mu_ud_inherited_get(JSContext *ctx, struct mu_ud *u,
+				   JSValueConst obj, JSAtom atom,
+				   JSValueConst receiver)
+{
+	JSValue proto, v;
+	int own = JS_GetOwnProperty(ctx, 0, u->backing, atom);
+
+	if (own < 0)
+		return JS_EXCEPTION;
+	if (own)
+		return JS_GetProperty(ctx, u->backing, atom);
+	proto = JS_GetPrototype(ctx, obj);
+	if (JS_IsException(proto))
+		return proto;
+	if (!JS_IsObject(proto)) {
+		JS_FreeValue(ctx, proto);
+		return JS_UNDEFINED;
+	}
+	v = JS_GetPropertyInternal(ctx, proto, atom,
+				   JS_IsObject(receiver) ? receiver : obj, 0);
+	JS_FreeValue(ctx, proto);
+	return v;
+}
+
 static JSValue mu_ud_get(JSContext *ctx, JSValueConst obj, JSAtom atom,
 static JSValue mu_ud_get(JSContext *ctx, JSValueConst obj, JSAtom atom,
 			 JSValueConst receiver)
 			 JSValueConst receiver)
 {
 {
@@ -407,7 +435,6 @@ static JSValue mu_ud_get(JSContext *ctx, JSValueConst obj, JSAtom atom,
 	JSValue v;
 	JSValue v;
 	int r;
 	int r;
 
 
-	(void)receiver;
 	if (!u)
 	if (!u)
 		return JS_UNDEFINED;
 		return JS_UNDEFINED;
 	r = mu_ud_lookup(ctx, u, atom, &v);
 	r = mu_ud_lookup(ctx, u, atom, &v);
@@ -415,7 +442,7 @@ static JSValue mu_ud_get(JSContext *ctx, JSValueConst obj, JSAtom atom,
 		return JS_EXCEPTION;
 		return JS_EXCEPTION;
 	if (r > 0)
 	if (r > 0)
 		return v;
 		return v;
-	return JS_GetProperty(ctx, u->backing, atom);
+	return mu_ud_inherited_get(ctx, u, obj, atom, receiver);
 }
 }
 
 
 static int mu_ud_has(JSContext *ctx, JSValueConst obj, JSAtom atom)
 static int mu_ud_has(JSContext *ctx, JSValueConst obj, JSAtom atom)
@@ -433,7 +460,18 @@ static int mu_ud_has(JSContext *ctx, JSValueConst obj, JSAtom atom)
 		JS_FreeValue(ctx, v);
 		JS_FreeValue(ctx, v);
 		return 1;
 		return 1;
 	}
 	}
-	return JS_HasProperty(ctx, u->backing, atom);
+	r = JS_GetOwnProperty(ctx, 0, u->backing, atom);
+	if (r != 0)
+		return r;
+	{
+		JSValue proto = JS_GetPrototype(ctx, obj);
+
+		if (JS_IsException(proto))
+			return -1;
+		r = JS_IsObject(proto) ? JS_HasProperty(ctx, proto, atom) : 0;
+		JS_FreeValue(ctx, proto);
+	}
+	return r;
 }
 }
 
 
 static int mu_ud_set(JSContext *ctx, JSValueConst obj, JSAtom atom,
 static int mu_ud_set(JSContext *ctx, JSValueConst obj, JSAtom atom,
@@ -444,7 +482,6 @@ static int mu_ud_set(JSContext *ctx, JSValueConst obj, JSAtom atom,
 	int savetop = J->top, r;
 	int savetop = J->top, r;
 
 
 	(void)receiver;
 	(void)receiver;
-	(void)flags;
 	if (!u)
 	if (!u)
 		return 0;
 		return 0;
 	if (u->put) {
 	if (u->put) {
@@ -456,6 +493,26 @@ static int mu_ud_set(JSContext *ctx, JSValueConst obj, JSAtom atom,
 		if (r > 0)
 		if (r > 0)
 			return 1;
 			return 1;
 	}
 	}
+	r = JS_GetOwnProperty(ctx, 0, u->backing, atom);
+	if (r < 0)
+		return -1;
+	if (!r) {
+		/* A setter on the prototype chain runs with the element as
+		 * `this`; a plain new property lands on the backing object
+		 * through mu_ud_define(). */
+		JSValue proto = JS_GetPrototype(ctx, obj);
+
+		if (JS_IsException(proto))
+			return -1;
+		if (JS_IsObject(proto)) {
+			r = JS_SetPropertyInternal(ctx, proto, atom,
+						   JS_DupValue(ctx, value),
+						   obj, flags);
+			JS_FreeValue(ctx, proto);
+			return r;
+		}
+		JS_FreeValue(ctx, proto);
+	}
 	return JS_SetProperty(ctx, u->backing, atom, JS_DupValue(ctx, value));
 	return JS_SetProperty(ctx, u->backing, atom, JS_DupValue(ctx, value));
 }
 }
 
 
@@ -1301,3 +1358,4 @@ int js_equal(js_State *J)
 	JS_FreeCString(J->ctx, b);
 	JS_FreeCString(J->ctx, b);
 	return eq;
 	return eq;
 }
 }
+

+ 189 - 6
js_prelude.js

@@ -55,7 +55,22 @@ con.assert = function (c) {
 def("self", g); def("top", g); def("parent", g); def("frames", g);
 def("self", g); def("top", g); def("parent", g); def("frames", g);
 def("isSecureContext", true);
 def("isSecureContext", true);
 def("origin", g.location.origin);
 def("origin", g.location.origin);
-def("queueMicrotask", function (f) { Promise.resolve().then(f); });
+/* The engine's own Promise, captured before any page script runs: core-js
+ * (heise's consent script) installs a Promise polyfill that schedules its
+ * reactions through queueMicrotask, and a queueMicrotask built on the
+ * replaced global Promise would call back into the polyfill forever. */
+var NativePromise = Promise;
+def("queueMicrotask", function (f) { NativePromise.resolve().then(f); });
+/* Present so core-js keeps the native Promise (it polyfills browsers that
+ * lack unhandled-rejection events). */
+class PromiseRejectionEvent {
+	constructor(type, init) {
+		this.type = type;
+		this.promise = init && init.promise;
+		this.reason = init && init.reason;
+	}
+}
+def("PromiseRejectionEvent", PromiseRejectionEvent);
 def("requestIdleCallback", function (f) {
 def("requestIdleCallback", function (f) {
 	return setTimeout(function () {
 	return setTimeout(function () {
 		f({ didTimeout: false, timeRemaining: function () { return 10; } });
 		f({ didTimeout: false, timeRemaining: function () { return 10; } });
@@ -884,16 +899,63 @@ class ResizeObserver {
 	unobserve() {}
 	unobserve() {}
 	disconnect() {}
 	disconnect() {}
 }
 }
+/* Without scroll geometry every observed target is reported visible, once
+ * per observe(): lazy loaders and "becomes visible" components (heise's
+ * a-img) then load their content.  Capped per page against infinite-scroll
+ * sentinels that re-observe forever. */
+var ioBudget = 400;
+/* One timer drains every deferred callback: a page with hundreds of lazy
+ * images would otherwise overflow the browser's timer table. */
+var laterQ = [], laterArmed = false;
+function later(f) {
+	laterQ.push(f);
+	if (laterArmed) return;
+	laterArmed = true;
+	setTimeout(function () {
+		var q = laterQ, i;
+		laterQ = [];
+		laterArmed = false;
+		for (i = 0; i < q.length; i++)
+			try { q[i](); } catch (e) { con.error(e); }
+	}, 0);
+}
 class IntersectionObserver {
 class IntersectionObserver {
-	constructor(cb, opts) { this._cb = cb; this.root = null; this.thresholds = [0]; }
-	observe() {}
-	unobserve() {}
-	disconnect() {}
+	constructor(cb, opts) {
+		this._cb = cb;
+		this._t = [];
+		this.root = (opts && opts.root) || null;
+		this.rootMargin = (opts && opts.rootMargin) || "0px";
+		this.thresholds = [0];
+	}
+	observe(t) {
+		var self = this;
+		if (!t || this._t.indexOf(t) >= 0 || ioBudget <= 0) return;
+		ioBudget--;
+		this._t.push(t);
+		later(function () {
+			if (self._t.indexOf(t) < 0) return;
+			var r = t.getBoundingClientRect();
+			self._cb([{ target: t, isIntersecting: true,
+				intersectionRatio: 1, boundingClientRect: r,
+				intersectionRect: r, rootBounds: null,
+				time: g.performance.now() }], self);
+		});
+	}
+	unobserve(t) { this._t = this._t.filter(function (x) { return x !== t; }); }
+	disconnect() { this._t = []; }
 	takeRecords() { return []; }
 	takeRecords() { return []; }
 }
 }
 def("MutationObserver", MutationObserver);
 def("MutationObserver", MutationObserver);
 def("ResizeObserver", ResizeObserver);
 def("ResizeObserver", ResizeObserver);
 def("IntersectionObserver", IntersectionObserver);
 def("IntersectionObserver", IntersectionObserver);
+/* Present with isIntersecting/intersectionRatio on the prototype so the
+ * common IntersectionObserver polyfill (bundled by heise) keeps ours. */
+class IntersectionObserverEntry {
+	constructor(init) { Object.assign(this, init); }
+	get isIntersecting() { return !!this._i; }
+	get intersectionRatio() { return this._r || 0; }
+}
+def("IntersectionObserverEntry", IntersectionObserverEntry);
 
 
 /* ---- DOM classes: instanceof works on the node wrappers ---- */
 /* ---- DOM classes: instanceof works on the node wrappers ---- */
 function domClass(name, test) {
 function domClass(name, test) {
@@ -920,6 +982,8 @@ domClass("Text", function (o) { return o.nodeType === 3; });
 domClass("Comment", function (o) { return o.nodeType === 8; });
 domClass("Comment", function (o) { return o.nodeType === 8; });
 domClass("DocumentFragment", function (o) { return o.nodeType === 11; });
 domClass("DocumentFragment", function (o) { return o.nodeType === 11; });
 domClass("Document", function (o) { return o.nodeType === 9; });
 domClass("Document", function (o) { return o.nodeType === 9; });
+domClass("DocumentType", function (o) { return o.nodeType === 10; });
+domClass("Attr", function (o) { return o.nodeType === 2; });
 domClass("HTMLDocument", function (o) { return o.nodeType === 9; });
 domClass("HTMLDocument", function (o) { return o.nodeType === 9; });
 domClass("HTMLInputElement", tag("INPUT"));
 domClass("HTMLInputElement", tag("INPUT"));
 domClass("HTMLTextAreaElement", tag("TEXTAREA"));
 domClass("HTMLTextAreaElement", tag("TEXTAREA"));
@@ -936,6 +1000,125 @@ domClass("HTMLScriptElement", tag("SCRIPT"));
 domClass("HTMLStyleElement", tag("STYLE"));
 domClass("HTMLStyleElement", tag("STYLE"));
 domClass("HTMLCanvasElement", tag("CANVAS"));
 domClass("HTMLCanvasElement", tag("CANVAS"));
 def("Window", function Window() {});
 def("Window", function Window() {});
+
+/* ---- Custom Elements ----
+ * A registered class adopts an existing element: HTMLElement, used as the
+ * base constructor, returns the element being upgraded (or a fresh one for
+ * `new MyElement()`) with its prototype switched to the subclass, the way
+ * the custom-elements polyfills do it.  New elements are upgraded when
+ * created by script and by a scan after DOM changes (js_browser.c calls
+ * __nb_ce_scan from its tick); connectedCallback runs once the element is
+ * in the document.  attributeChangedCallback fires for the observed
+ * attributes present at upgrade, not for later changes. */
+var ceRegistry = new Map(), ceNames = new Map(), ceWaiters = new Map();
+var cePending = [];
+var createEl = g.document.createElement;
+function HTMLElementCtor() {
+	var el = cePending.length ? cePending[cePending.length - 1] : null;
+	if (!el) {
+		var name = ceNames.get(new.target);
+		if (!name) throw new TypeError("Illegal constructor");
+		el = createEl.call(g.document, name);
+	}
+	Object.setPrototypeOf(el, new.target.prototype);
+	return el;
+}
+HTMLElementCtor.prototype = nodeproto;
+Object.defineProperty(HTMLElementCtor, "name", { value: "HTMLElement" });
+Object.defineProperty(HTMLElementCtor, Symbol.hasInstance, {
+	value: function (o) {
+		if (this !== HTMLElementCtor)
+			return Function.prototype[Symbol.hasInstance].call(this, o);
+		return o != null && typeof o === "object" && o.nodeType === 1;
+	}
+});
+def("HTMLElement", HTMLElementCtor);
+function ceUpgrade(el) {
+	var C, obs, i;
+	if (!el || el.nodeType !== 1 || el.__nbce) return;
+	C = ceRegistry.get(el.localName);
+	if (!C) return;
+	el.__nbce = 1;
+	cePending.push(el);
+	try { new C(); } catch (e) { con.error(e); }
+	cePending.pop();
+	obs = C.observedAttributes;
+	if (obs && typeof el.attributeChangedCallback === "function")
+		for (i = 0; i < obs.length; i++)
+			if (el.hasAttribute(obs[i]))
+				try { el.attributeChangedCallback(obs[i], null, el.getAttribute(obs[i])); }
+				catch (e) { con.error(e); }
+	ceConnect(el);
+}
+function ceConnect(el) {
+	if (el.__nbceConn || !el.isConnected) return;
+	el.__nbceConn = 1;
+	if (typeof el.connectedCallback === "function") {
+		try {
+			var r = el.connectedCallback();
+			if (r && typeof r.then === "function")
+				r.then(null, function (e) { con.error(e); });
+		} catch (e) { con.error(e); }
+	}
+}
+function ceScan() {
+	ceRegistry.forEach(function (C, name) {
+		var list = g.document.querySelectorAll(name), i;
+		for (i = 0; i < list.length; i++) {
+			if (!list[i].__nbce) ceUpgrade(list[i]);
+			else ceConnect(list[i]);
+		}
+	});
+}
+def("__nb_ce_scan", function () { if (ceRegistry.size) ceScan(); });
+def("customElements", {
+	define: function (name, C) {
+		name = String(name).toLowerCase();
+		if (ceRegistry.has(name))
+			throw new DOMException("'" + name + "' is already defined", "NotSupportedError");
+		ceRegistry.set(name, C);
+		ceNames.set(C, name);
+		ceScan();
+		var w = ceWaiters.get(name);
+		if (w) { w.forEach(function (f) { f(C); }); ceWaiters.delete(name); }
+	},
+	get: function (name) { return ceRegistry.get(String(name).toLowerCase()); },
+	getName: function (C) { return ceNames.get(C) || null; },
+	whenDefined: function (name) {
+		name = String(name).toLowerCase();
+		if (ceRegistry.has(name)) return Promise.resolve(ceRegistry.get(name));
+		return new Promise(function (res) {
+			if (!ceWaiters.has(name)) ceWaiters.set(name, []);
+			ceWaiters.get(name).push(res);
+		});
+	},
+	upgrade: function (root) {
+		ceUpgrade(root);
+		if (root && root.querySelectorAll) ceScan();
+	}
+});
+g.document.createElement = function (name, opts) {
+	var el = createEl.call(g.document, name);
+	var n = String(name).toLowerCase();
+	if (ceRegistry.has(n)) ceUpgrade(el);
+	if (n === "img") imgLoadShim(el);
+	return el;
+};
+/* Script-created images never really load in the page's DOM; fire "load"
+ * once a src is set so preload-then-swap code (load a detached <img>, then
+ * copy its URL) proceeds.  The visible <img> is loaded by the browser. */
+function imgLoadShim(el) {
+	later(function () {
+		if (el.getAttribute("src"))
+			el.dispatchEvent(new Event("load"));
+	});
+}
+def("Image", function Image(w, h) {
+	var el = g.document.createElement("img");
+	if (w !== undefined) el.setAttribute("width", String(w));
+	if (h !== undefined) el.setAttribute("height", String(h));
+	return el;
+});
 def("ShadowRoot", function ShadowRoot() {});
 def("ShadowRoot", function ShadowRoot() {});
 
 
 var NodeConst = g.Node;
 var NodeConst = g.Node;
@@ -1128,5 +1311,5 @@ g.print = function () {};
 g.postMessage = function () {};
 g.postMessage = function () {};
 g.confirm = function () { return true; };
 g.confirm = function () { return true; };
 g.prompt = function () { return null; };
 g.prompt = function () { return null; };
-g.dispatchEvent = g.dispatchEvent || function () { return true; };
+
 })(globalThis);
 })(globalThis);

この差分においてかなりの量のファイルが変更されているため、一部のファイルを表示していません