2 Commits abbc1fbd1b ... c746da5f08

Autore SHA1 Messaggio Data
  Johannes Zellner c746da5f08 Fix more browser polyfils 1 settimana fa
  Johannes Zellner 40be0da0eb Lay out the Cloudron dashboard: CSS variable scoping, % heights, alignment 1 settimana fa
10 ha cambiato i file con 1002 aggiunte e 60 eliminazioni
  1. 61 9
      AGENTS.md
  2. 299 16
      browser.c
  3. 143 11
      browser_html.c
  4. 3 0
      browser_html.h
  5. 1 1
      docs/graphics.html
  6. 0 0
      docs/userland.html
  7. 241 13
      js_browser.c
  8. 3 0
      js_browser.h
  9. 62 4
      js_mu.c
  10. 189 6
      js_prelude.js

+ 61 - 9
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,8 +1449,20 @@ 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`
-  and `multiple`, and an `<option>` without `value` reports its text.  The
+  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.
+  `offsetWidth`/`clientWidth` of an element without a laid-out box report
+  the viewport width (Vue apps measure on mount and picked a phone layout
+  for 0), and `window` gets a `resize` event after the first layout of a
+  scripted page and whenever the page width changes.  The logged-in
+  dashboard (sidebar with expandable groups, header, app grid, hash-routed
+  views) was verified in QEMU against a local stand-in that proxies the
+  public dashboard assets and mocks `/api/v1` and the OIDC endpoints.  The
   Cloudron dashboard (`my.<domain>`: a Vite/Vue 3 app, 12 modules / 3.5 MB)
   Cloudron dashboard (`my.<domain>`: a Vite/Vue 3 app, 12 modules / 3.5 MB)
   boots, builds its PKCE request, and its OIDC login form renders, submits
   boots, builds its PKCE request, and its OIDC login form renders, submits
   through `fetch()` with the interaction cookie and shows the server's
   through `fetch()` with the interaction cookie and shows the server's
@@ -1510,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,
@@ -2186,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
@@ -2200,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
@@ -2211,7 +2254,16 @@ and the WM falls back to polling (`io_keyboard_irq_masked()`).
     of descendant content, gradients/box-shadow/transitions (a gradient
     of descendant content, gradients/box-shadow/transitions (a gradient
     background falls back to its last solid colour), or CSS `color-mix`.
     background falls back to its last solid colour), or CSS `color-mix`.
     A non-uniform `background-size` uses the width scale for both axes.
     A non-uniform `background-size` uses the width scale for both axes.
-    CSS custom properties (`var()`), flex rows with wrap/grow/gap/justify/
+    CSS custom properties (`var()`: one document-wide table, expanded when
+    a sheet is parsed; definitions on `:root`/`html`/`body`/`*`/`:host`
+    win, a component-level definition applies only while no other rule
+    gives the name a different value, otherwise `var()` uses its fallback
+    -- Font Awesome's competing `--fa-width` values made every icon 100%
+    wide), percentage heights (against the containing block's definite
+    height, `lay.cb_h`, with the viewport for `html`/`body`; used as a
+    minimum since there are no scrollable inner boxes, and auto when the
+    containing height is indefinite -- they used to resolve against the
+    width), flex rows with wrap/grow/gap/justify/
     align, two-track and `repeat(auto-fit, minmax(...))` grids, inline-block
     align, two-track and `repeat(auto-fit, minmax(...))` grids, inline-block
     runs, basic proportional table columns, table rowspan/colspan/percentage
     runs, basic proportional table columns, table rowspan/colspan/percentage
     columns and inline SVG (filled/stroked geometry, `use`/`symbol`,
     columns and inline SVG (filled/stroked geometry, `use`/`symbol`,

+ 299 - 16
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];
 };
 };
 
 
@@ -170,6 +171,9 @@ static unsigned int pending_post_len;
 /* The pending navigation is a POST even when its body is empty (a form
 /* The pending navigation is a POST even when its body is empty (a form
  * without fields, e.g. the OIDC consent auto-submit). */
  * without fields, e.g. the OIDC consent auto-submit). */
 static int pending_post_is;
 static int pending_post_is;
+/* window "resize" bookkeeping: the page width the last event was for. */
+static int resize_sent_w = -1;
+static int resize_pending;
 static unsigned int pending_action;
 static unsigned int pending_action;
 static int cancel_fetch;
 static int cancel_fetch;
 static int quit;
 static int quit;
@@ -182,6 +186,8 @@ static int page_cache_scroll;
 static unsigned int page_cache_nnode;
 static unsigned int page_cache_nnode;
 static int page_cache_x, page_cache_y, page_cache_w, page_cache_h;
 static int page_cache_x, page_cache_y, page_cache_w, page_cache_h;
 static int layout_valid, layout_left, layout_right;
 static int layout_valid, layout_left, layout_right;
+/* Height of the page viewport: what html/body height:100% resolves to. */
+static int layout_view_h;
 static unsigned int layout_nnode;
 static unsigned int layout_nnode;
 static int layout_content_h;
 static int layout_content_h;
 
 
@@ -218,6 +224,8 @@ struct lay {
 	int line_left, line_right;
 	int line_left, line_right;
 	int parent_top;
 	int parent_top;
 	int cb_left, cb_right, cb_top;  /* containing block for absolute boxes */
 	int cb_left, cb_right, cb_top;  /* containing block for absolute boxes */
+	int cb_h;       /* definite content height of the containing block for
+			 * percentage heights; 0 = indefinite (auto) */
 	int run_x;
 	int run_x;
 	int align;
 	int align;
 	int depth;
 	int depth;
@@ -401,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;
@@ -409,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
@@ -1804,6 +1829,8 @@ static void run_page_scripts(void)
 		js_host_status("JavaScript: out of memory", 1);
 		js_host_status("JavaScript: out of memory", 1);
 		return;
 		return;
 	}
 	}
+	resize_sent_w = -1;
+	resize_pending = 0;
 	prefetch_module_preloads();
 	prefetch_module_preloads();
 
 
 	for (i = 0; i < doc.nscripts; i++) {
 	for (i = 0; i < doc.nscripts; i++) {
@@ -2033,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)
 {
 {
@@ -2046,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;
 	}
 	}
@@ -4019,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)
@@ -4033,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
@@ -4069,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);
@@ -4121,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) {
@@ -4141,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;
@@ -4183,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;
 		}
 		}
@@ -4206,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;
@@ -4213,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;
@@ -5482,7 +5537,7 @@ static void flush_line(struct lay *l)
 						   l->ui->theme.border);
 						   l->ui->theme.border);
 					/* A value wider than the field shows its
 					/* A value wider than the field shows its
 					 * tail (where typing happens). */
 					 * tail (where typing happens). */
-					if (editable && w > 12) {
+					if (editable && fs && fs->len && w > 12) {
 						int tw = (int)run_text_width(l->ui,
 						int tw = (int)run_text_width(l->ui,
 							r, txt, tl);
 							r, txt, tl);
 
 
@@ -6950,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)
@@ -7117,6 +7331,7 @@ static void layout_block(struct lay *l, unsigned int node,
 			 unsigned short link)
 			 unsigned short link)
 {
 {
 	int old_left = l->left, old_right = l->right, old_align = l->align;
 	int old_left = l->left, old_right = l->right, old_align = l->align;
+	int parent_cb_h = l->cb_h;
 	int saved_parent_top = l->parent_top;
 	int saved_parent_top = l->parent_top;
 	int saved_cb_left = l->cb_left, saved_cb_right = l->cb_right;
 	int saved_cb_left = l->cb_left, saved_cb_right = l->cb_right;
 	int saved_cb_top = l->cb_top;
 	int saved_cb_top = l->cb_top;
@@ -7192,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;
@@ -7496,6 +7712,21 @@ static void layout_block(struct lay *l, unsigned int node,
 					  st->color);
 					  st->color);
 			}
 			}
 		}
 		}
+		/* This box's definite content height, for its children's
+		 * percentage heights. */
+		if (doc.nodes[node].tag == BR_TAG_HTML ||
+		    doc.nodes[node].tag == BR_TAG_BODY)
+			l->cb_h = layout_view_h;
+		else if (st->height_kind == 1)
+			l->cb_h = (int)st->height -
+				  (st->box_sizing ? deco_h : 0);
+		else if (st->height_kind == 2 && parent_cb_h > 0)
+			l->cb_h = parent_cb_h * (int)st->height / 100 -
+				  (st->box_sizing ? deco_h : 0);
+		else
+			l->cb_h = 0;
+		if (l->cb_h < 0)
+			l->cb_h = 0;
 		if (doc.nodes[node].tag == BR_TAG_TR)
 		if (doc.nodes[node].tag == BR_TAG_TR)
 			layout_table_row(l, node, st, depth + 1, link);
 			layout_table_row(l, node, st, depth + 1, link);
 		else if (doc.nodes[node].tag == BR_TAG_TABLE &&
 		else if (doc.nodes[node].tag == BR_TAG_TABLE &&
@@ -7509,8 +7740,19 @@ static void layout_block(struct lay *l, unsigned int node,
 		else if (st->display == BR_DISPLAY_FLEX && !st->flex_col &&
 		else if (st->display == BR_DISPLAY_FLEX && !st->flex_col &&
 			 flex_wants_row(node, st))
 			 flex_wants_row(node, st))
 			layout_flex_children(l, node, st, depth + 1, link);
 			layout_flex_children(l, node, st, depth + 1, link);
-		else
+		else if (st->display == BR_DISPLAY_FLEX && st->flex_col &&
+			 st->align_items == 1) {
+			/* align-items: center in a column: the items' lines
+			 * (an app card's icon and label) are centred; a child
+			 * with its own text-align keeps it. */
+			struct br_style cst = *st;
+
+			cst.align = BR_ALIGN_CENTER;
+			l->align = BR_ALIGN_CENTER;
+			layout_children(l, node, &cst, depth + 1, link);
+		} else
 			layout_children(l, node, st, depth + 1, link);
 			layout_children(l, node, st, depth + 1, link);
+		l->cb_h = parent_cb_h;
 	}
 	}
 	flush_line(l);
 	flush_line(l);
 	if (clip_pushed)
 	if (clip_pushed)
@@ -7522,6 +7764,21 @@ static void layout_block(struct lay *l, unsigned int node,
 	}
 	}
 	if (doc.nodes[node].tag == BR_TAG_IMG) {
 	if (doc.nodes[node].tag == BR_TAG_IMG) {
 		content_h = img_dh;
 		content_h = img_dh;
+	} else if (st->height_kind == 2 &&
+		   doc.nodes[node].tag != BR_TAG_HTML &&
+		   doc.nodes[node].tag != BR_TAG_BODY) {
+		/* A percentage of the containing block's definite height, or
+		 * auto when it has none (it used to resolve against the
+		 * width).  The result is a minimum: without scrollable inner
+		 * boxes, an app shell's height:100%; overflow:hidden column
+		 * would otherwise clip everything past the first screen. */
+		int auto_h = l->y - (top + bt + pt);
+
+		content_h = parent_cb_h > 0 ?
+			    parent_cb_h * (int)st->height / 100 -
+			    (st->box_sizing ? deco_h : 0) : 0;
+		if (content_h < auto_h)
+			content_h = auto_h;
 	} else if (st->height_kind &&
 	} else if (st->height_kind &&
 	    !((doc.nodes[node].tag == BR_TAG_HTML ||
 	    !((doc.nodes[node].tag == BR_TAG_HTML ||
 	       doc.nodes[node].tag == BR_TAG_BODY) &&
 	       doc.nodes[node].tag == BR_TAG_BODY) &&
@@ -7932,6 +8189,11 @@ static int flex_item_width(struct lay *l, unsigned int n,
 			w = (int)nd->width_attr;
 			w = (int)nd->width_attr;
 		else
 		else
 			w = 64;
 			w = 64;
+	} else if (nd->tag == BR_TAG_INPUT || nd->tag == BR_TAG_SELECT ||
+		   nd->tag == BR_TAG_TEXTAREA) {
+		/* A control has no content to measure: its default size
+		 * (a search field in a filter bar). */
+		w = nd->tag == BR_TAG_TEXTAREA ? 180 : 150;
 	} else {
 	} else {
 		w = intrinsic_width(l->ui, n, cs, 0, avail);
 		w = intrinsic_width(l->ui, n, cs, 0, avail);
 	}
 	}
@@ -7960,6 +8222,10 @@ static unsigned int layout_inline_blocks(struct lay *l, unsigned int first,
 	int row_left = l->left, row_right = l->right;
 	int row_left = l->left, row_right = l->right;
 	int avail = row_right - row_left;
 	int avail = row_right - row_left;
 	int x = row_left, y = l->y, row_h = 0, any = 0;
 	int x = row_left, y = l->y, row_h = 0, any = 0;
+	/* Each box sets l->align from its own style; the text after the row
+	 * must keep the container's (a centred .fa-fw icon centred the menu
+	 * label that followed it). */
+	unsigned char row_align = l->align;
 
 
 	flush_line(l);
 	flush_line(l);
 	y = l->y;
 	y = l->y;
@@ -8026,6 +8292,7 @@ static unsigned int layout_inline_blocks(struct lay *l, unsigned int first,
 		y += row_h;
 		y += row_h;
 	l->left = row_left;
 	l->left = row_left;
 	l->right = row_right;
 	l->right = row_right;
+	l->align = row_align;
 	l->y = y;
 	l->y = y;
 	l->line_x = l->left;
 	l->line_x = l->left;
 	l->run_x = l->left;
 	l->run_x = l->left;
@@ -8052,6 +8319,7 @@ static void layout_flex_children(struct lay *l, unsigned int parent,
 	int row_left = l->left, row_right = l->right;
 	int row_left = l->left, row_right = l->right;
 	int avail = row_right - row_left;
 	int avail = row_right - row_left;
 	int idx, row_top;
 	int idx, row_top;
+	unsigned char row_align = l->align;
 
 
 	if (avail < 160 || depth > 48) {
 	if (avail < 160 || depth > 48) {
 		layout_children(l, parent, pst, depth, link);
 		layout_children(l, parent, pst, depth, link);
@@ -8202,6 +8470,7 @@ static void layout_flex_children(struct lay *l, unsigned int parent,
 	}
 	}
 	l->left = row_left;
 	l->left = row_left;
 	l->right = row_right;
 	l->right = row_right;
+	l->align = row_align;
 	l->y = row_top;
 	l->y = row_top;
 	l->line_x = l->left;
 	l->line_x = l->left;
 	l->run_x = l->left;
 	l->run_x = l->left;
@@ -9334,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 ==
@@ -9420,6 +9690,7 @@ static int measure_page(int left, int right)
 	l->line_y = 0;
 	l->line_y = 0;
 	l->line_h = 0;
 	l->line_h = 0;
 	l->align = BR_ALIGN_LEFT;
 	l->align = BR_ALIGN_LEFT;
+	l->cb_h = layout_view_h;
 	l->float_active = 0;
 	l->float_active = 0;
 	l->parent_top = 0;
 	l->parent_top = 0;
 	l->cb_left = left;
 	l->cb_left = left;
@@ -9477,6 +9748,7 @@ static void render_page(int left, int right, int y0)
 	l->line_y = y0;
 	l->line_y = y0;
 	l->line_h = 0;
 	l->line_h = 0;
 	l->align = BR_ALIGN_LEFT;
 	l->align = BR_ALIGN_LEFT;
+	l->cb_h = layout_view_h;
 	l->float_active = 0;
 	l->float_active = 0;
 	l->parent_top = 0;
 	l->parent_top = 0;
 	l->cb_left = left;
 	l->cb_left = left;
@@ -9698,11 +9970,17 @@ static void draw_page(struct ngui_rect page)
 	right = page.x + page.w - 16;
 	right = page.x + page.w - 16;
 	if (!layout_valid || left != layout_left || right != layout_right ||
 	if (!layout_valid || left != layout_left || right != layout_right ||
 	    layout_nnode != doc.nnode) {
 	    layout_nnode != doc.nnode) {
+		layout_view_h = page.h - 8;
 		layout_content_h = measure_page(left, right);
 		layout_content_h = measure_page(left, right);
 		layout_valid = 1;
 		layout_valid = 1;
 		layout_left = left;
 		layout_left = left;
 		layout_right = right;
 		layout_right = right;
 		layout_nnode = doc.nnode;
 		layout_nnode = doc.nnode;
+		/* Scripts that measured before any layout (offsetWidth on
+		 * mount) get a resize event once real boxes exist, and again
+		 * whenever the page width changes. */
+		if (js_browser_active() && right - left != resize_sent_w)
+			resize_pending = 1;
 	}
 	}
 	ch = layout_content_h;
 	ch = layout_content_h;
 	page_scroll.content_h = ch;
 	page_scroll.content_h = ch;
@@ -10449,6 +10727,11 @@ void _start(const char *arg)
 			preload_active = 1;
 			preload_active = 1;
 		}
 		}
 		js_browser_tick();
 		js_browser_tick();
+		if (resize_pending && !pending_action) {
+			resize_pending = 0;
+			resize_sent_w = layout_right - layout_left;
+			js_browser_window_event("resize");
+		}
 		persist_tick();
 		persist_tick();
 		if (pending_action)
 		if (pending_action)
 			continue;
 			continue;

+ 143 - 11
browser_html.c

@@ -594,18 +594,42 @@ static unsigned int css_var_find(struct br_doc *d, const char *name,
 	}
 	}
 }
 }
 
 
+#define BR_VAR_ROOT     1
+#define BR_VAR_CONFLICT 2
+
+/* Custom properties live in one document-wide table (var() is expanded
+ * when a sheet is parsed, not per element).  Definitions on :root, html,
+ * body or * are the theme and always apply, last one winning.  A definition
+ * on any other selector is a local override: it is used while it is the
+ * only value seen for that name, and a second, different local value marks
+ * the name ambiguous so var() falls back.  Last-wins across components was
+ * wrong: Font Awesome sets --fa-width to 100% on .fa-stack-1x and 1.25em on
+ * .fa-fw, and every icon became 100% wide. */
 static void css_var_set(struct br_doc *d, const char *name,
 static void css_var_set(struct br_doc *d, const char *name,
-			unsigned int nlen, const char *val, unsigned int vlen)
+			unsigned int nlen, const char *val, unsigned int vlen,
+			int root)
 {
 {
 	unsigned int i, noff, voff;
 	unsigned int i, noff, voff;
 
 
 	if (nlen < 3 || name[0] != '-' || name[1] != '-' || !vlen)
 	if (nlen < 3 || name[0] != '-' || name[1] != '-' || !vlen)
 		return;
 		return;
+	i = css_var_find(d, name, nlen);
+	if (i < BR_MAX_VARS && !root) {
+		const char *old = attr_ptr(d, d->var_val[i]);
+		unsigned int k = 0;
+
+		if (d->var_flags[i] & BR_VAR_ROOT)
+			return;
+		while (k < vlen && old[k] == val[k])
+			k++;
+		if (!(k == vlen && old[k] == '\0'))
+			d->var_flags[i] |= BR_VAR_CONFLICT;
+		return;
+	}
 	noff = store_raw(d, name, nlen, 63);
 	noff = store_raw(d, name, nlen, 63);
 	voff = store_raw(d, val, vlen, 199);
 	voff = store_raw(d, val, vlen, 199);
 	if (!noff || !voff)
 	if (!noff || !voff)
 		return;
 		return;
-	i = css_var_find(d, name, nlen);
 	if (i >= BR_MAX_VARS) {
 	if (i >= BR_MAX_VARS) {
 		unsigned int h;
 		unsigned int h;
 
 
@@ -617,8 +641,45 @@ static void css_var_set(struct br_doc *d, const char *name,
 		while (d->var_slot[h])
 		while (d->var_slot[h])
 			h = (h + 1) & (VAR_HASH_SIZE - 1);
 			h = (h + 1) & (VAR_HASH_SIZE - 1);
 		d->var_slot[h] = (unsigned short)(i + 1);
 		d->var_slot[h] = (unsigned short)(i + 1);
+		d->var_flags[i] = 0;
 	}
 	}
 	d->var_val[i] = voff;
 	d->var_val[i] = voff;
+	if (root)
+		d->var_flags[i] = BR_VAR_ROOT;
+}
+
+/* 1 when every selector of the list targets the document root (the theme
+ * scope for custom properties): :root, html, body, * or :host, optionally
+ * with classes/attributes but no combinator. */
+static int css_root_selector(const char *s, unsigned int len)
+{
+	unsigned int i = 0;
+
+	while (i < len) {
+		unsigned int st, en;
+
+		while (i < len && (is_space(s[i]) || s[i] == ','))
+			i++;
+		if (i >= len)
+			break;
+		st = i;
+		while (i < len && s[i] != ',')
+			i++;
+		en = i;
+		while (en > st && is_space(s[en - 1]))
+			en--;
+		if (!((en - st >= 5 && ci_eq_n(s + st, ":root", 5)) ||
+		      (en - st >= 5 && ci_eq_n(s + st, ":host", 5)) ||
+		      (en - st >= 4 && ci_eq_n(s + st, "html", 4)) ||
+		      (en - st >= 4 && ci_eq_n(s + st, "body", 4)) ||
+		      s[st] == '*'))
+			return 0;
+		for (; st < en; st++)
+			if (is_space(s[st]) || s[st] == '>' || s[st] == '+' ||
+			    s[st] == '~')
+				return 0;
+	}
+	return 1;
 }
 }
 
 
 /* Find the end of a declaration value: the next ';' outside quotes and
 /* Find the end of a declaration value: the next ';' outside quotes and
@@ -691,7 +752,7 @@ static int css_dark_selector(const char *s, unsigned int len)
 
 
 /* Collect --custom-property definitions from one declaration block. */
 /* Collect --custom-property definitions from one declaration block. */
 static void css_collect_block(struct br_doc *d, const char *s,
 static void css_collect_block(struct br_doc *d, const char *s,
-			      unsigned int len)
+			      unsigned int len, int root)
 {
 {
 	unsigned int i = 0;
 	unsigned int i = 0;
 
 
@@ -734,7 +795,7 @@ static void css_collect_block(struct br_doc *d, const char *s,
 		if (pend - pstart >= 3 && s[pstart] == '-' &&
 		if (pend - pstart >= 3 && s[pstart] == '-' &&
 		    s[pstart + 1] == '-')
 		    s[pstart + 1] == '-')
 			css_var_set(d, s + pstart, pend - pstart,
 			css_var_set(d, s + pstart, pend - pstart,
-				    s + vstart, vend - vstart);
+				    s + vstart, vend - vstart, root);
 	}
 	}
 }
 }
 
 
@@ -1219,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);
 			}
 			}
@@ -1943,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)
 {
 {
@@ -2003,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';
 		}
 		}
 	}
 	}
@@ -3683,6 +3808,9 @@ static unsigned int css_expand_vars(struct br_doc *d, const char *s,
 		if (nlen >= 3 && s[inner] == '-' && s[inner + 1] == '-') {
 		if (nlen >= 3 && s[inner] == '-' && s[inner + 1] == '-') {
 			unsigned int vi = css_var_find(d, s + inner, nlen);
 			unsigned int vi = css_var_find(d, s + inner, nlen);
 
 
+			if (vi < BR_MAX_VARS &&
+			    (d->var_flags[vi] & BR_VAR_CONFLICT))
+				vi = BR_MAX_VARS;
 			if (vi < BR_MAX_VARS) {
 			if (vi < BR_MAX_VARS) {
 				const char *v = attr_ptr(d, d->var_val[vi]);
 				const char *v = attr_ptr(d, d->var_val[vi]);
 				unsigned int vn = css_expand_vars(d, v, s_len(v),
 				unsigned int vn = css_expand_vars(d, v, s_len(v),
@@ -5047,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;
 
 
@@ -6058,7 +6188,9 @@ static void parse_css(struct br_doc *d, const char *s, unsigned int len)
 		if (sstart == send)
 		if (sstart == send)
 			continue;
 			continue;
 		if (!css_dark_selector(s + sstart, send - sstart))
 		if (!css_dark_selector(s + sstart, send - sstart))
-			css_collect_block(d, s + bstart, bend - bstart);
+			css_collect_block(d, s + bstart, bend - bstart,
+					  css_root_selector(s + sstart,
+							    send - sstart));
 		if (css_collect_only)
 		if (css_collect_only)
 			continue;
 			continue;
 		parse_decls(d, s + bstart, bend - bstart, decls, &nd);
 		parse_decls(d, s + bstart, bend - bstart, decls, &nd);

+ 3 - 0
browser_html.h

@@ -286,6 +286,9 @@ struct br_doc {
 	 * single table: the last definition wins, which matches :root. */
 	 * single table: the last definition wins, which matches :root. */
 	unsigned int var_name[BR_MAX_VARS];
 	unsigned int var_name[BR_MAX_VARS];
 	unsigned int var_val[BR_MAX_VARS];
 	unsigned int var_val[BR_MAX_VARS];
+	/* BR_VAR_ROOT: set by a :root, html, body or * rule; BR_VAR_CONFLICT: two
+	 * component rules disagree, so var() uses its fallback. */
+	unsigned char var_flags[BR_MAX_VARS];
 	unsigned short var_slot[1024];
 	unsigned short var_slot[1024];
 	unsigned int nvars;
 	unsigned int nvars;
 	/* Rule index: rightmost class/id/tag -> linked list of rule indices. */
 	/* Rule index: rightmost class/id/tag -> linked list of rule indices. */

+ 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>

File diff suppressed because it is too large
+ 0 - 0
docs/userland.html


+ 241 - 13
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")) {
@@ -2115,8 +2312,12 @@ static int node_has(js_State *state, void *p, const char *name)
 	    !strcmp(name, "scrollWidth") || !strcmp(name, "scrollHeight")) {
 	    !strcmp(name, "scrollWidth") || !strcmp(name, "scrollHeight")) {
 		int x = 0, y = 0, w = 0, h = 0;
 		int x = 0, y = 0, w = 0, h = 0;
 
 
-		if (host.rect)
-			host.rect(node, &x, &y, &w, &h);
+		/* Before the first layout an element has no box; a block's
+		 * width is then best guessed as the viewport (Vue apps measure
+		 * offsetWidth on mount and pick a phone layout for 0).  A
+		 * resize event after layout lets them measure again. */
+		if (!host.rect || !host.rect(node, &x, &y, &w, &h))
+			w = n->type == BR_NODE_ELEM ? (int)host.width : 0;
 		js_pushnumber(state, (!strcmp(name, "offsetHeight") ||
 		js_pushnumber(state, (!strcmp(name, "offsetHeight") ||
 				      !strcmp(name, "clientHeight") ||
 				      !strcmp(name, "clientHeight") ||
 				      !strcmp(name, "scrollHeight")) ? h : w);
 				      !strcmp(name, "scrollHeight")) ? h : w);
@@ -3061,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);
@@ -3133,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);
@@ -3210,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));
@@ -3277,6 +3483,12 @@ static void report_top(js_State *state)
 	js_pop(state, 1);
 	js_pop(state, 1);
 }
 }
 
 
+void js_browser_window_event(const char *type)
+{
+	if (J && D)
+		js_browser_event(JS_TARGET_WINDOW, type, 0, 0);
+}
+
 void js_browser_hashchange(void)
 void js_browser_hashchange(void)
 {
 {
 	hash_pending = 1;
 	hash_pending = 1;
@@ -3295,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 ||
@@ -3321,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);

+ 3 - 0
js_browser.h

@@ -76,6 +76,9 @@ int js_browser_run_module(const char *source, const char *url);
  * a click on <a href="#/apps">); it fires from the next tick. */
  * a click on <a href="#/apps">); it fires from the next tick. */
 void js_browser_hashchange(void);
 void js_browser_hashchange(void);
 
 
+/* Dispatch a plain event (e.g. "resize") on window now. */
+void js_browser_window_event(const char *type);
+
 /* Run due setTimeout/setInterval callbacks; call once per UI loop. */
 /* Run due setTimeout/setInterval callbacks; call once per UI loop. */
 void js_browser_tick(void);
 void js_browser_tick(void);
 
 

+ 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);

Some files were not shown because too many files changed in this diff