Browse Source

browser: fix flex layout and DOMPurify for the Cloudron login page

Layout:
- A single-line flex row takes its container's definite height and
  stretches align-items: stretch items to the line (flex_stretch_h[]);
  align-items/align-self parse flex-start/start/baseline separately
  from stretch.
- flex-direction: column gets its own layout (layout_flex_column):
  justify-content shares out the free height, start/center/end items
  shrink to their content width.
- Absolute/fixed children of a flex container are out of flow
  (layout_out_of_flow, shared with block layout), not flex items.
- justify-content: space-* makes a row of two plain inline items.
- A box placed by `bottom` without a height uses its measured height
  (also in the deferred fixed-box clip), and a fixed box without
  left/right keeps its static x.
- No browser gutter of its own: body has the UA 8 px margin, so
  `body { margin: 0 }` starts at the canvas edge.
- Reset line_left with line_x in every new box context; the stale value
  made flush_line() emit an empty line and pushed later flex items, grid
  columns and table cells down 2 px.

Scripting (js_prelude.js):
- NodeFilter and document.createNodeIterator.
- Real accessors/methods on the shared node prototype for the members
  DOMPurify reads via getOwnPropertyDescriptor(Node.prototype, ...).
- The page document's lookups called on an inert document answer for
  it: DOMPurify got the page's real <body> and emptied the page.
- DOMParser splits a whole document at <head>/<body>.
Johannes Zellner 2 ngày trước cách đây
mục cha
commit
e528274751

+ 34 - 4
AGENTS.md

@@ -1581,7 +1581,26 @@ it to `0x7E00`.  The kernel region itself only has one wall (`_end` below
   sets `--ifm-col-width`, `.col[class*=col--]` uses it).  The flex shorthand
   and `flex-basis` map a definite basis onto the item width, and flex items
   are clamped by `min-width`/`max-width` (a capped growing item leaves its
-  space to the others).
+  space to the others).  A single-line flex row takes its container's
+  definite height (`lay.cb_h`), and `align-items: stretch` items without a
+  height grow to the line (`flex_stretch_h[]`, set by the measure pass:
+  before the item is laid out when the height is definite, else once the
+  line is known); `align-items` parses `flex-start`/`start`/`baseline` as 3,
+  separate from stretch (0).  `flex-direction: column` is
+  `layout_flex_column()`: items stack with the gap, `justify-content`
+  shares out the free height of the container's measured box in the draw
+  pass, and `start`/`center`/`end` items shrink to their content width (a
+  login form's button, a centred logo).  Absolute/fixed children of a flex
+  container are out of flow (`layout_out_of_flow()`, shared with block
+  layout), not items.  `justify-content: space-*` makes a row of even two
+  plain inline items.  A box placed by `bottom` without a height uses its
+  measured height, and a fixed box without `left`/`right` keeps its static
+  x.  The page has no gutter of its own: layout spans
+  `[page.x, page.x + page.w - 12)` (the 12 px are the scrollbar) from
+  `page.y`, and `body` has the UA 8 px margin, so `body { margin: 0 }`
+  starts at the canvas edge.  Every new box context resets `line_left` with
+  `line_x`; a stale one made `flush_line()` emit an empty line and pushed
+  later flex items, grid columns and table cells down 2 px.
   `@font-face` loads one regular TTF per family from a local path or HTTP URL
   (the browser fetches remote faces before layout).  The compatibility
   ladder is `testdata/browser/compat/`
@@ -1794,7 +1813,14 @@ it to `0x7E00`.  The kernel region itself only has one wall (`_end` below
   (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
+  native one), `NodeFilter` and `document.createNodeIterator` (a document-
+  order snapshot that skips nodes removed meanwhile; DOMPurify), real
+  accessors on the shared node prototype for `nodeName`/`nodeType`/
+  `parentNode`/`nextSibling`/`childNodes`/`attributes` and the
+  `cloneNode`/`remove`/`removeAttributeNode` methods (DOMPurify reads them
+  with `getOwnPropertyDescriptor(Node.prototype, ...)`; a wrapper's own
+  lookup still reaches the C hook first), 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
@@ -2768,8 +2794,12 @@ and the WM falls back to polling (`io_keyboard_irq_masked()`).
     small RX ring and stall TLS handshakes into a 10 s timeout; use e1000.
     `DOMParser` and `document.implementation.createHTMLDocument` return an
     inert detached document (its nodes live in the page arena; markup goes
-    through the innerHTML fragment parser, head elements included), which is
-    enough for jQuery's probe and parseHTML but not a separate XML parser.
+    through the innerHTML fragment parser, split at `<head>`/`<body>`),
+    which is enough for jQuery's probe, parseHTML and DOMPurify but not a
+    separate XML parser.  The page document's `getElementsByTagName`/
+    `querySelector(All)`/`getElementsByClassName`/`getElementById` called on
+    an inert document (`.call(parsed, "body")`) answer for that document:
+    DOMPurify used to get the page's real `<body>` and empty it.
     Also missing: `defer`/`async` ordering,
     `document.implementation.createDocument`, canvas/2D contexts, user-state
     pseudo-classes (`:hover`, `:focus`, ...), `:nth-child(... of S)` and

Những thai đổi đã bị hủy bỏ vì nó quá lớn
+ 0 - 0
docs/userland.html


+ 376 - 105
user/apps/browser/browser.c

@@ -149,7 +149,7 @@ static unsigned int img_repaint_ms;
 static int img_repaint_pending;
 
 /* Painted border boxes, in page/screen coordinates (layout starts at
- * page_rect.y + 4 - scroll).  getBoundingClientRect() subtracts page_rect. */
+ * page_rect.y - scroll).  getBoundingClientRect() subtracts page_rect. */
 struct br_layout_box {
 	int x, y;
 	int w, h;
@@ -525,6 +525,10 @@ static struct hit hits[HIT_MAX];
 static int nhits;
 
 static unsigned short block_h[BR_MAX_NODES];
+/* Border-box height a flex container stretches an item to (align-items:
+ * stretch in a row with a taller line or a definite height), 0 = none.
+ * Written by the measure pass, read by both. */
+static unsigned short flex_stretch_h[BR_MAX_NODES];
 /* Measure-pass top of each block, in the same document coordinates as
  * img_top[] (layout_boxes[] is rewritten in screen coordinates by every
  * paint, so it cannot drive the lazy background loader). */
@@ -7888,9 +7892,19 @@ static void layout_table(struct lay *l, unsigned int table,
  * heading/icon pair.  Our flex row positions such items without emitting
  * their inline text in some deep page contexts; normal inline flow renders
  * the same content correctly. */
+static int layout_out_of_flow(struct lay *l, unsigned int n,
+			      const struct br_style *cs, int depth,
+			      unsigned short lk);
+static void layout_flex_column(struct lay *l, unsigned int parent,
+			       const struct br_style *pst, int depth,
+			       unsigned short link);
+static void emit_pseudo(struct lay *l, unsigned int node,
+			const struct br_style *st, int pe, unsigned short link);
+
 static int flex_wants_row(unsigned int parent, const struct br_style *pst)
 {
 	unsigned int c;
+	int items = 0;
 
 	for (c = doc.nodes[parent].first; c; c = doc.nodes[c].next) {
 		struct br_node *nd = &doc.nodes[c];
@@ -7901,6 +7915,11 @@ static int flex_wants_row(unsigned int parent, const struct br_style *pst)
 		br_style_for(&doc, c, pst, &cs);
 		if (cs.display == BR_DISPLAY_NONE)
 			continue;
+		/* `justify-content: space-between` spreads even two plain
+		 * inline items (a "Password ... Reset password" label row)
+		 * across the line; inline flow would set them side by side. */
+		if (++items >= 2 && pst->justify >= 3)
+			return 1;
 		if (cs.display != BR_DISPLAY_INLINE || cs.flex_grow ||
 		    cs.width_kind || cs.has_bg ||
 		    cs.border_w[0] || cs.border_w[1] ||
@@ -8959,15 +8978,27 @@ static void layout_block(struct lay *l, unsigned int node,
 			if (st->right_set && def_w >= 0)
 				l->left = page_rect.x + avail_w - st->right -
 					  def_w;
+			else if (!st->left_set && !st->right_set)
+				l->left = flow_left;    /* static position */
 			else
 				l->left = page_rect.x +
 					  (st->left_set ? st->left : 0);
 			l->right = def_w >= 0 ? l->left + def_w :
-						page_rect.x + avail_w;
+				   st->width_kind == 2 ?
+				   l->left + avail_w * (int)st->width / 100 :
+				   page_rect.x + avail_w;
+			/* Placed by `bottom` (a page footer): an auto
+			 * height is the measured one. */
 			if (st->bottom_set && st->height_kind)
 				l->y = page_rect.y + page_rect.h -
 				      st->bottom -
 				      style_height_px(st, page_rect.w);
+			else if (st->bottom_set && !st->top_set &&
+				 block_h[node])
+				l->y = page_rect.y + page_rect.h -
+				      st->bottom - (int)block_h[node] -
+				      mp_px(st, 0, avail_w) -
+				      mp_px(st, 2, avail_w);
 			else
 				l->y = page_rect.y +
 				      (st->top_set ? st->top : 0);
@@ -8986,6 +9017,13 @@ static void layout_block(struct lay *l, unsigned int node,
 			    parent < BR_MAX_NODES && block_h[parent] > 0)
 				l->y = flow_y + block_h[parent] - st->bottom -
 				      style_height_px(st, old_right - old_left);
+			else if (st->bottom_set && !st->top_set &&
+				 parent < BR_MAX_NODES && block_h[parent] > 0 &&
+				 block_h[node] > 0)
+				l->y = flow_y + block_h[parent] - st->bottom -
+				      (int)block_h[node] -
+				      mp_px(st, 0, old_right - old_left) -
+				      mp_px(st, 2, old_right - old_left);
 		}
 		/* `left: 100%` parks a box (Docusaurus' "Skip to main
 		 * content" link) past the containing block's right edge
@@ -9136,7 +9174,7 @@ static void layout_block(struct lay *l, unsigned int node,
 	normal_top = top;
 	if (sticky) {
 		if (st->top_set) {
-			int stick = page_rect.y + 4 + st->top;
+			int stick = page_rect.y + st->top;
 
 			if (normal_top < stick)
 				rel_dy += stick - normal_top;
@@ -9335,6 +9373,9 @@ static void layout_block(struct lay *l, unsigned int node,
 		else if (!st->height_kind && st->aspect_w && st->aspect_h)
 			l->cb_h = content_w * (int)st->aspect_h /
 				  (int)st->aspect_w;
+		else if (!st->height_kind && node < BR_MAX_NODES &&
+			 flex_stretch_h[node] > deco_h)
+			l->cb_h = flex_stretch_h[node] - deco_h;
 		else
 			l->cb_h = 0;
 		if (l->cb_h < 0)
@@ -9352,17 +9393,9 @@ static void layout_block(struct lay *l, unsigned int node,
 		else if (st->display == BR_DISPLAY_FLEX && !st->flex_col &&
 			 flex_wants_row(node, st))
 			layout_flex_children(l, node, st, depth + 1, link);
-		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
+		else if (st->display == BR_DISPLAY_FLEX && st->flex_col)
+			layout_flex_column(l, node, st, depth + 1, link);
+		else
 			layout_children(l, node, st, depth + 1, link);
 		l->cb_h = parent_cb_h;
 	}
@@ -9417,6 +9450,9 @@ static void layout_block(struct lay *l, unsigned int node,
 	}
 	if (content_h < 0)
 		content_h = 0;
+	if (!st->height_kind && node < BR_MAX_NODES &&
+	    content_h + deco_h < flex_stretch_h[node])
+		content_h = flex_stretch_h[node] - deco_h;
 	if (st->max_height_kind) {
 		int mh = st->max_height_kind == 3 ?
 			 cbw * st->max_height_calc_pct / 100 +
@@ -9793,7 +9829,7 @@ static unsigned int layout_float_group(struct lay *l, unsigned int first,
 		if (l->right < l->left + 8)
 			l->right = l->left + 8;
 		l->y = row_top;
-		l->line_x = l->left;
+		l->line_left = l->line_x = l->left;
 		l->run_x = l->left;
 		l->line_y = l->y;
 		l->line_h = 0;
@@ -10045,7 +10081,7 @@ static unsigned int layout_inline_blocks(struct lay *l, unsigned int first,
 		if (l->right < l->left + 8)
 			l->right = l->left + 8;
 		l->y = y;
-		l->line_x = l->left;
+		l->line_left = l->line_x = l->left;
 		l->run_x = l->left;
 		l->line_y = l->y;
 		l->line_h = 0;
@@ -10066,7 +10102,7 @@ static unsigned int layout_inline_blocks(struct lay *l, unsigned int first,
 	l->right = row_right;
 	l->align = row_align;
 	l->y = y;
-	l->line_x = l->left;
+	l->line_left = l->line_x = l->left;
 	l->run_x = l->left;
 	l->line_y = l->y;
 	l->line_h = 0;
@@ -10118,6 +10154,35 @@ static int flex_clamp_w(const struct br_style *cs, int w, int avail)
 	return w;
 }
 
+/* Does a flex row stretch this item to the line height?  Only items with
+ * no height of their own and align-self/align-items stretch; replaced
+ * content (images, icons) keeps its aspect ratio. */
+static int flex_item_stretches(unsigned int node, const struct br_style *cs,
+			       const struct br_style *pst)
+{
+	int ai = cs->align_self ? cs->align_self - 1 : pst->align_items;
+	unsigned char tag = doc.nodes[node].tag;
+
+	return ai == 0 && !cs->height_kind && !cs->max_height_kind &&
+	       tag != BR_TAG_IMG && tag != BR_TAG_SVG && tag != BR_TAG_INPUT &&
+	       tag != BR_TAG_SELECT && tag != BR_TAG_TEXTAREA &&
+	       tag != BR_TAG_BUTTON;
+}
+
+static void flex_set_stretch(unsigned int node, const struct br_style *cs,
+			     int line_h, int cbw)
+{
+	int h = line_h - mp_px(cs, 0, cbw) - mp_px(cs, 2, cbw);
+
+	if (node >= BR_MAX_NODES || h <= 0)
+		return;
+	if (h > 65535)
+		h = 65535;
+	flex_stretch_h[node] = (unsigned short)h;
+	if (block_h[node] < h)
+		block_h[node] = (unsigned short)h;
+}
+
 static void layout_flex_children(struct lay *l, unsigned int parent,
 				 const struct br_style *pst, int depth,
 				 unsigned short link)
@@ -10132,6 +10197,7 @@ static void layout_flex_children(struct lay *l, unsigned int parent,
 	unsigned char row_align = l->align;
 	int box_left = l->left, box_right = l->right, row_top0 = l->y;
 	int bw = 0, aw = 0, first_h = -1;
+	int cont_h = l->cb_h;   /* the container's definite content height */
 	struct br_style bps, aps;
 
 	if (avail < 8 || depth > 48) {
@@ -10175,6 +10241,11 @@ static void layout_flex_children(struct lay *l, unsigned int parent,
 		br_style_for(&doc, c, pst, &cs);
 		if (cs.display == BR_DISPLAY_NONE)
 			continue;
+		if ((cs.pos == 1 || cs.pos == 2) &&
+		    layout_out_of_flow(l, c, &cs, depth,
+				       (nd->tag == BR_TAG_A && nd->href_off) ?
+				       (unsigned short)c : link))
+			continue;       /* absolutely positioned: not an item */
 		it[nitem].node = c;
 		it[nitem].link = (nd->tag == BR_TAG_A && nd->href_off) ?
 				 (unsigned short)c : link;
@@ -10300,12 +10371,12 @@ static void layout_flex_children(struct lay *l, unsigned int parent,
 			if (h > row_h)
 				row_h = h;
 		}
-		if (pst->height_kind) {
-			int hh = style_height_px(pst, avail);
-
-			if (hh > row_h)
-				row_h = hh;
-		}
+		/* A single line fills a definite container height (an app
+		 * shell's `height: 100%` sidebar + content row). */
+		if (pst->flex_wrap != 1 && cont_h > row_h)
+			row_h = cont_h;
+		else if (pst->height_kind == 1 && (int)pst->height > row_h)
+			row_h = pst->height;
 		for (k = 0; k < count; k++) {
 			struct br_style cs;
 			int node = (int)it[start + k].node;
@@ -10314,6 +10385,13 @@ static void layout_flex_children(struct lay *l, unsigned int parent,
 			br_style_for(&doc, node, pst, &cs);
 			cs.width_kind = 0;
 			cs.max_width_kind = 0;
+			/* align-items: stretch.  With a definite line height
+			 * the item is laid out at it, so its own children see
+			 * a definite height; otherwise the measure pass
+			 * stretches it once the line is known (below). */
+			if (!l->draw && row_h > 0 && flex_item_stretches(node,
+							&cs, pst))
+				flex_set_stretch(node, &cs, row_h, avail);
 			{
 				int ai = cs.align_self ? cs.align_self - 1 :
 					 pst->align_items;
@@ -10331,15 +10409,22 @@ static void layout_flex_children(struct lay *l, unsigned int parent,
 			if (l->right < l->left + 8)
 				l->right = l->left + 8;
 			l->y = row_top + yoff;
-			l->line_x = l->left;
-			l->run_x = l->left;
+			/* line_left too: a stale one from the previous item
+			 * made flush_line() see a non-empty line and push
+			 * every later item down by an empty line's height. */
+			l->line_left = l->line_x = l->run_x = l->left;
+			l->line_right = l->right;
 			l->line_y = l->y;
 			l->line_h = 0;
 			l->nruns = 0;
 			l->space_pending = 0;
 			l->align = cs.align;
 			layout_block(l, node, &cs, depth + 1, it[start + k].link);
-			if (!l->draw) {
+			{
+				/* Both passes: a form control item has no
+				 * block_h of its own, so the draw pass would
+				 * otherwise end a row of only an <input> at
+				 * height 0 and pull the content below up. */
 				int h = l->y - row_top;
 
 				if (h > row_h)
@@ -10349,6 +10434,26 @@ static void layout_flex_children(struct lay *l, unsigned int parent,
 			if (k + 1 < count)
 				x += gap + extra;
 		}
+		if (!l->draw) {
+			for (k = 0; k < count; k++) {
+				struct br_style cs;
+				int node = (int)it[start + k].node;
+
+				br_style_for(&doc, node, pst, &cs);
+				if (!flex_item_stretches(node, &cs, pst))
+					continue;
+				/* To the line's bottom edge from where the
+				 * item really starts (its top margin, or a
+				 * line box above it). */
+				if (layout_boxes[node].valid)
+					flex_set_stretch(node, &cs,
+						 row_top + row_h -
+						 layout_boxes[node].y +
+						 mp_px(&cs, 0, avail), avail);
+				else
+					flex_set_stretch(node, &cs, row_h, avail);
+			}
+		}
 		if (first_h < 0)
 			first_h = row_h;
 		row_top += row_h;
@@ -10386,12 +10491,140 @@ static void layout_flex_children(struct lay *l, unsigned int parent,
 	l->right = box_right;
 	l->align = row_align;
 	l->y = row_top;
-	l->line_x = l->left;
-	l->run_x = l->left;
+	l->line_left = l->line_x = l->run_x = l->left;
+	l->line_right = l->right;
+	l->line_y = l->y;
+	l->line_h = 0;
+	l->nruns = 0;
+	l->space_pending = 0;
+}
+
+/* flex-direction: column.  Items stack in order with the gap and never
+ * collapse margins.  In the draw pass justify-content shares out the free
+ * height of the container's measured box (a definite or min-height, or a
+ * row stretch), and align-items places each item: stretch (the default)
+ * fills the line, start/center/end shrink an item to its content width
+ * (a login form's "Log in" button, a centred logo and name). */
+static void layout_flex_column(struct lay *l, unsigned int parent,
+			       const struct br_style *pst, int depth,
+			       unsigned short link)
+{
+	unsigned int c;
+	int box_left = l->left, box_right = l->right;
+	int avail = box_right - box_left;
+	int gap = pst->grid_gap, y0 = l->y;
+	int n = 0, k = 0, total = 0, lead = 0, extra = 0;
+	unsigned char row_align = l->align;
+
+	for (c = doc.nodes[parent].first; c; c = doc.nodes[c].next) {
+		struct br_node *nd = &doc.nodes[c];
+
+		if (nd->type == BR_NODE_TEXT && !text_node_blank(nd))
+			break;
+	}
+	if (c || avail < 8 || depth > 48) {
+		/* Loose text: block flow, with centred lines standing in
+		 * for align-items: center. */
+		struct br_style cst = *pst;
+
+		if (pst->align_items == 1) {
+			cst.align = BR_ALIGN_CENTER;
+			l->align = BR_ALIGN_CENTER;
+		}
+		layout_children(l, parent, &cst, depth, link);
+		return;
+	}
+	emit_pseudo(l, parent, pst, 1, link);
+	flush_line(l);
+	y0 = l->y;
+	if (l->draw && parent < BR_MAX_NODES && block_h[parent]) {
+		int inner = (int)block_h[parent] - pst->border_w[0] -
+			    pst->border_w[2] - mp_px(pst, 4, avail) -
+			    mp_px(pst, 6, avail) - (y0 - l->parent_top -
+			    pst->border_w[0] - mp_px(pst, 4, avail));
+		int free_h;
+
+		for (c = doc.nodes[parent].first; c; c = doc.nodes[c].next) {
+			struct br_style cs;
+
+			if (doc.nodes[c].type != BR_NODE_ELEM)
+				continue;
+			br_style_for(&doc, c, pst, &cs);
+			if (cs.display == BR_DISPLAY_NONE || cs.pos == 1 ||
+			    cs.pos == 2)
+				continue;
+			total += block_h[c] + mp_px(&cs, 0, avail) +
+				 mp_px(&cs, 2, avail);
+			n++;
+		}
+		if (n > 1)
+			total += gap * (n - 1);
+		free_h = inner - total;
+		if (n && free_h > 0) {
+			if (pst->justify == 1) {
+				lead = free_h / 2;
+			} else if (pst->justify == 2) {
+				lead = free_h;
+			} else if (pst->justify == 3) {
+				extra = n > 1 ? free_h / (n - 1) : 0;
+			} else if (pst->justify == 4) {
+				extra = free_h / n;
+				lead = extra / 2;
+			} else if (pst->justify == 5) {
+				extra = free_h / (n + 1);
+				lead = extra;
+			}
+		}
+	}
+	l->y = y0 + lead;
+	for (c = doc.nodes[parent].first; c; c = doc.nodes[c].next) {
+		struct br_node *nd = &doc.nodes[c];
+		unsigned short lk = (nd->tag == BR_TAG_A && nd->href_off) ?
+				    (unsigned short)c : link;
+		struct br_style cs;
+		int ai, left = box_left, right = box_right;
+
+		if (nd->type != BR_NODE_ELEM)
+			continue;
+		br_style_for(&doc, c, pst, &cs);
+		if (cs.display == BR_DISPLAY_NONE)
+			continue;
+		if ((cs.pos == 1 || cs.pos == 2) &&
+		    layout_out_of_flow(l, c, &cs, depth, lk))
+			continue;
+		if (k++)
+			l->y += gap + extra;
+		ai = cs.align_self ? cs.align_self - 1 : pst->align_items;
+		if (ai) {
+			int w = flex_clamp_w(&cs, flex_item_width(l, c, &cs,
+								  avail),
+					     avail);
+
+			if (ai == 1)
+				left += (avail - w) / 2;
+			else if (ai == 2)
+				left += avail - w;
+			right = left + w;
+			cs.width_kind = 0;
+			cs.max_width_kind = 0;
+		}
+		l->left = l->line_left = l->line_x = l->run_x = left;
+		l->right = l->line_right = right;
+		l->line_y = l->y;
+		l->line_h = 0;
+		l->nruns = 0;
+		l->space_pending = 0;
+		l->align = cs.align;
+		layout_block(l, c, &cs, depth + 1, lk);
+	}
+	l->left = l->line_left = l->line_x = l->run_x = box_left;
+	l->right = l->line_right = box_right;
+	l->align = row_align;
 	l->line_y = l->y;
 	l->line_h = 0;
 	l->nruns = 0;
 	l->space_pending = 0;
+	emit_pseudo(l, parent, pst, 2, link);
 }
 
 /* Two-column CSS grid: track sizes from grid-template-columns (px, %, fr)
@@ -10526,7 +10759,7 @@ static void layout_grid_children(struct lay *l, unsigned int parent,
 		if (l->right < l->left + 8)
 			l->right = l->left + 8;
 		l->y = row_y;
-		l->line_x = l->left;
+		l->line_left = l->line_x = l->left;
 		l->run_x = l->left;
 		l->line_y = l->y;
 		l->line_h = 0;
@@ -10541,7 +10774,7 @@ static void layout_grid_children(struct lay *l, unsigned int parent,
 	l->left = row_left;
 	l->right = row_right;
 	l->y = row_bottom;
-	l->line_x = l->left;
+	l->line_left = l->line_x = l->left;
 	l->run_x = l->left;
 	l->line_y = l->y;
 	l->line_h = 0;
@@ -10617,7 +10850,7 @@ static void layout_grid_auto(struct lay *l, unsigned int parent,
 		if (l->right < l->left + 8)
 			l->right = l->left + 8;
 		l->y = y;
-		l->line_x = l->left;
+		l->line_left = l->line_x = l->left;
 		l->run_x = l->left;
 		l->line_y = l->y;
 		l->line_h = 0;
@@ -10646,7 +10879,7 @@ static void layout_grid_auto(struct lay *l, unsigned int parent,
 	l->left = row_left;
 	l->right = row_right;
 	l->y = y;
-	l->line_x = l->left;
+	l->line_left = l->line_x = l->left;
 	l->run_x = l->left;
 	l->line_y = l->y;
 	l->line_h = 0;
@@ -10935,7 +11168,7 @@ static void layout_table_row(struct lay *l, unsigned int row,
 		l->left = prefix[start];
 		l->right = l->left + w;
 		l->y = y;
-		l->line_x = l->left;
+		l->line_left = l->line_x = l->left;
 		l->run_x = l->left;
 		l->line_y = l->y;
 		l->line_h = 0;
@@ -10949,7 +11182,7 @@ static void layout_table_row(struct lay *l, unsigned int row,
 	l->left = row_left;
 	l->right = row_right;
 	l->y = bottom;
-	l->line_x = l->left;
+	l->line_left = l->line_x = l->left;
 	l->run_x = l->left;
 	l->line_y = l->y;
 	l->line_h = 0;
@@ -11218,7 +11451,7 @@ static void layout_table(struct lay *l, unsigned int table,
 		l->left = prefix[col];
 		l->right = l->left + w;
 		l->y = 0;
-		l->line_x = l->left;
+		l->line_left = l->line_x = l->left;
 		l->run_x = l->left;
 		l->line_y = 0;
 		l->line_h = 0;
@@ -11309,7 +11542,7 @@ static void layout_table(struct lay *l, unsigned int table,
 		l->left = prefix[col];
 		l->right = l->left + w;
 		l->y = rowy[row];
-		l->line_x = l->left;
+		l->line_left = l->line_x = l->left;
 		l->run_x = l->left;
 		l->line_y = l->y;
 		l->line_h = 0;
@@ -11523,6 +11756,82 @@ static void emit_pseudo(struct lay *l, unsigned int node,
 		flush_line(l);
 }
 
+/* An out-of-flow child (absolute/fixed, or a relative/sticky box with a
+ * z-index): measured in place, painted from the deferred stacked pass
+ * against its containing block.  Shared by block and flex layout, so an
+ * absolute icon inside a flex row (a password field's reveal button) is
+ * not laid out as one of the row's items.  Returns 1 when it handled n. */
+static int layout_out_of_flow(struct lay *l, unsigned int n,
+			      const struct br_style *cs, int depth,
+			      unsigned short lk)
+{
+	if (!(cs->pos == 1 || cs->pos == 2 ||
+	      ((cs->pos == 3 || cs->pos == 4) && cs->z_set)))
+		return 0;
+	if ((cs->pos == 3 || cs->pos == 4) && l->draw &&
+	    ndeferred < BR_MAX_DEFERRED) {
+		/* Relative or sticky z-index (a sticky site
+		 * header): measure and advance the flow without
+		 * painting, then paint it in the deferred
+		 * (stacked) pass, above the content after it. */
+		int fy = l->y, fl = l->left, fr = l->right;
+		int save_draw = l->draw;
+
+		l->draw = 0;
+		layout_block(l, n, cs, depth + 1, lk);
+		l->draw = save_draw;
+		deferred[ndeferred].node = n;
+		deferred[ndeferred].parent_top = l->parent_top;
+		deferred[ndeferred].flow_y = fy;
+		deferred[ndeferred].flow_left = fl;
+		deferred[ndeferred].flow_right = fr;
+		deferred[ndeferred].link = lk;
+		deferred[ndeferred].z_index = cs->z_index;
+		deferred[ndeferred].z_set = cs->z_set;
+		deferred[ndeferred].order = (unsigned int)ndeferred;
+		ndeferred++;
+	} else if (l->draw && ndeferred < BR_MAX_DEFERRED) {
+		deferred[ndeferred].node = n;
+		deferred[ndeferred].parent_top = l->parent_top;
+		deferred[ndeferred].flow_y =
+			cs->pos == 1 ? l->cb_top : l->y;
+		deferred[ndeferred].flow_left =
+			cs->pos == 1 ? l->cb_left : l->left;
+		deferred[ndeferred].flow_right =
+			cs->pos == 1 ? l->cb_right : l->right;
+		deferred[ndeferred].link = lk;
+		deferred[ndeferred].z_index = cs->z_index;
+		deferred[ndeferred].z_set = cs->z_set;
+		deferred[ndeferred].order = (unsigned int)ndeferred;
+		ndeferred++;
+	} else if (l->draw && cs->pos == 1) {
+		/* Deferred list full: paint in place, but still
+		 * against the containing block, not the flow. */
+		int fy = l->y, fl = l->left, fr = l->right;
+
+		l->y = l->cb_top;
+		l->left = l->cb_left;
+		l->right = l->cb_right;
+		layout_block(l, n, cs, depth + 1, lk);
+		l->y = fy;
+		l->left = fl;
+		l->right = fr;
+	} else {
+		layout_block(l, n, cs, depth + 1, lk);
+	}
+	if (cs->pos == 1 && block_h[n] &&
+	    doc.nodes[n].class_off) {
+		const char *cl = doc.attrs +
+			doc.nodes[n].class_off;
+
+		if ((contains_ci(cl, "poster-wrapper") ||
+		     contains_ci(cl, "ts-picture")) &&
+		    !has_skeleton_sibling(n))
+			l->y += block_h[n];
+	}
+	return 1;
+}
+
 static void layout_children(struct lay *l, unsigned int parent,
 			    const struct br_style *pst, int depth,
 			    unsigned short link)
@@ -11565,69 +11874,7 @@ static void layout_children(struct lay *l, unsigned int parent,
 		}
 		if (nd->tag == BR_TAG_A && nd->href_off)
 			lk = (unsigned short)n;
-		if (cs.pos == 1 || cs.pos == 2 ||
-		    ((cs.pos == 3 || cs.pos == 4) && cs.z_set)) {
-			if ((cs.pos == 3 || cs.pos == 4) && l->draw &&
-			    ndeferred < BR_MAX_DEFERRED) {
-				/* Relative or sticky z-index (a sticky site
-				 * header): measure and advance the flow without
-				 * painting, then paint it in the deferred
-				 * (stacked) pass, above the content after it. */
-				int fy = l->y, fl = l->left, fr = l->right;
-				int save_draw = l->draw;
-
-				l->draw = 0;
-				layout_block(l, n, &cs, depth + 1, lk);
-				l->draw = save_draw;
-				deferred[ndeferred].node = n;
-				deferred[ndeferred].parent_top = l->parent_top;
-				deferred[ndeferred].flow_y = fy;
-				deferred[ndeferred].flow_left = fl;
-				deferred[ndeferred].flow_right = fr;
-				deferred[ndeferred].link = lk;
-				deferred[ndeferred].z_index = cs.z_index;
-				deferred[ndeferred].z_set = cs.z_set;
-				deferred[ndeferred].order = (unsigned int)ndeferred;
-				ndeferred++;
-			} else if (l->draw && ndeferred < BR_MAX_DEFERRED) {
-				deferred[ndeferred].node = n;
-				deferred[ndeferred].parent_top = l->parent_top;
-				deferred[ndeferred].flow_y =
-					cs.pos == 1 ? l->cb_top : l->y;
-				deferred[ndeferred].flow_left =
-					cs.pos == 1 ? l->cb_left : l->left;
-				deferred[ndeferred].flow_right =
-					cs.pos == 1 ? l->cb_right : l->right;
-				deferred[ndeferred].link = lk;
-				deferred[ndeferred].z_index = cs.z_index;
-				deferred[ndeferred].z_set = cs.z_set;
-				deferred[ndeferred].order = (unsigned int)ndeferred;
-				ndeferred++;
-			} else if (l->draw && cs.pos == 1) {
-				/* Deferred list full: paint in place, but still
-				 * against the containing block, not the flow. */
-				int fy = l->y, fl = l->left, fr = l->right;
-
-				l->y = l->cb_top;
-				l->left = l->cb_left;
-				l->right = l->cb_right;
-				layout_block(l, n, &cs, depth + 1, lk);
-				l->y = fy;
-				l->left = fl;
-				l->right = fr;
-			} else {
-				layout_block(l, n, &cs, depth + 1, lk);
-			}
-			if (cs.pos == 1 && block_h[n] &&
-			    doc.nodes[n].class_off) {
-				const char *cl = doc.attrs +
-					doc.nodes[n].class_off;
-
-				if ((contains_ci(cl, "poster-wrapper") ||
-				     contains_ci(cl, "ts-picture")) &&
-				    !has_skeleton_sibling(n))
-					l->y += block_h[n];
-			}
+		if (layout_out_of_flow(l, n, &cs, depth, lk)) {
 			n = nd->next;
 			continue;
 		}
@@ -11729,6 +11976,7 @@ static int measure_page(int left, int right)
 
 	for (i = 0; i < BR_MAX_NODES; i++) {
 		block_h[i] = 0;
+		flex_stretch_h[i] = 0;
 		img_top[i] = 0;
 		block_top[i] = 0;
 		img_h[i] = 0;
@@ -11834,7 +12082,7 @@ static void render_page(int left, int right, int y0)
 			l->right = deferred[i].flow_right;
 			l->y = deferred[i].flow_y;
 			l->parent_top = deferred[i].parent_top;
-			l->line_x = l->left;
+			l->line_left = l->line_x = l->left;
 			l->run_x = l->left;
 			l->line_y = l->y;
 			l->line_h = 0;
@@ -11846,6 +12094,18 @@ static void render_page(int left, int right, int y0)
 				int ch = block_h[deferred[i].node] + 24;
 				int pr = page_rect.x + page_rect.w - 12;
 				int x0 = page_rect.x, x1 = pr;
+				int y0 = page_rect.y;
+
+				/* A box placed by `bottom` (a page footer) is
+				 * clipped and filled where layout_block puts
+				 * it, against the bottom edge. */
+				if (st.bottom_set && !st.top_set) {
+					ch = block_h[deferred[i].node] +
+					     mp_px(&st, 0, pr - page_rect.x) +
+					     mp_px(&st, 2, pr - page_rect.x);
+					y0 = page_rect.y + page_rect.h -
+					     st.bottom - ch;
+				}
 
 				/* The background pre-fill spans the box's own
 				 * columns, not the whole page: Docusaurus parks
@@ -11854,6 +12114,8 @@ static void render_page(int left, int right, int y0)
 				 * and a full-width fill painted over the bar. */
 				if (st.left_set)
 					x0 = page_rect.x + st.left;
+				else if (!st.right_set)
+					x0 = deferred[i].flow_left;
 				if (st.width_kind == 1) {
 					if (st.right_set && !st.left_set)
 						x0 = pr - st.right - st.width;
@@ -11867,11 +12129,17 @@ static void render_page(int left, int right, int y0)
 					x0 = page_rect.x;
 				if (x1 > pr)
 					x1 = pr;
+				if (y0 < page_rect.y) {
+					ch -= page_rect.y - y0;
+					y0 = page_rect.y;
+				}
 				clip.x = x0;
-				clip.y = page_rect.y;
+				clip.y = y0;
 				clip.w = x1 - x0;
 				if (ch > page_rect.h)
 					ch = page_rect.h;
+				if (ch <= 0)
+					continue;
 				clip.h = ch;
 				ngui_push_clip(&ui, clip);
 				if (st.has_bg)
@@ -12411,13 +12679,16 @@ static void draw_page(struct ngui_rect page)
 		ngui_fill_rect(&ui, page, page_bg);
 	}
 
-	left = page.x + 8;
-	right = page.x + page.w - 16;
+	/* No gutter of our own: the body's UA margin provides it.  The
+	 * right 12 px stay clear for the scrollbar, like every viewport
+	 * width below (page_rect.w - 12). */
+	left = page.x;
+	right = page.x + page.w - 12;
 	if (!layout_valid || left != layout_left || right != layout_right ||
 	    layout_nnode != doc.nnode) {
 		unsigned int tm = u_ticks_ms();
 
-		layout_view_h = page.h - 8;
+		layout_view_h = page.h;
 		layout_content_h = measure_page(left, right);
 		if (img_stat_n)
 			img_stat_reflow += u_ticks_ms() - tm;
@@ -12437,7 +12708,7 @@ static void draw_page(struct ngui_rect page)
 	t0 = u_ticks_ms();
 	ngui_scroll_begin(&ui, page, &page_scroll);
 	ngui_scroll_wheel(&ui, page, &page_scroll);
-	render_page(left, right, page.y + 4 - page_scroll.offset);
+	render_page(left, right, page.y - page_scroll.offset);
 	old_panel = ui.theme.panel_alt;
 	old_dim = ui.theme.text_dim;
 	ui.theme.panel_alt = 0xC618;

+ 13 - 1
user/apps/browser/browser_html.c

@@ -5767,6 +5767,11 @@ static void parse_decls(struct br_doc *d, const char *s,
 				 contains_ci_len(s + vstart, vend - vstart,
 						 "end"))
 				a = 3;
+			else if (contains_ci_len(s + vstart, vend - vstart,
+						 "start") ||
+				 contains_ci_len(s + vstart, vend - vstart,
+						 "baseline"))
+				a = 4;
 			decl_add(out, nout, PROP_ALIGN_SELF, a, important);
 		} else if (str_eq(prop, "align-items")) {
 			int a = 0;
@@ -5778,6 +5783,11 @@ static void parse_decls(struct br_doc *d, const char *s,
 				 contains_ci_len(s + vstart, vend - vstart,
 						 "end"))
 				a = 2;
+			else if (contains_ci_len(s + vstart, vend - vstart,
+						 "start") ||
+				 contains_ci_len(s + vstart, vend - vstart,
+						 "baseline"))
+				a = 3;          /* not stretched */
 			decl_add(out, nout, PROP_ALIGN_ITEMS, a, important);
 		} else if (str_eq(prop, "position")) {
 			int p = 0;
@@ -9071,7 +9081,9 @@ void br_style_for(struct br_doc *d, unsigned int node,
 		out->display = BR_DISPLAY_NONE;
 		break;
 	case BR_TAG_BODY:
-		out->mt = out->mb = out->ml = out->mr = 4;
+		/* The UA default: the page itself has no gutter, so a site's
+		 * `body { margin: 0 }` really starts at the canvas edge. */
+		out->mt = out->mb = out->ml = out->mr = 8;
 		break;
 	case BR_TAG_P:
 		out->mt = out->mb = 8;

+ 1 - 1
user/apps/browser/browser_html.h

@@ -150,7 +150,7 @@ struct br_style {
 	unsigned char flex_col;     /* flex-direction: column */
 	unsigned char flex_wrap;    /* flex-wrap: wrap */
 	unsigned char justify;      /* 0 start, 1 center, 2 end, 3 between, 4 around */
-	unsigned char align_items;  /* 0 start/stretch, 1 center, 2 end */
+	unsigned char align_items;  /* 0 stretch, 1 center, 2 end, 3 start */
 	unsigned char align_self;   /* 0 auto, else align_items + 1 */
 	unsigned char grid_ncols;   /* 1 or 2 supported */
 	unsigned char grid_gap;     /* px */

+ 130 - 4
user/apps/browser/js_prelude.js

@@ -972,6 +972,54 @@ function domClass(name, test) {
 	return C;
 }
 function tag(t) { return function (o) { return o.nodeType === 1 && o.tagName === t; }; }
+
+/* Real accessors and methods on the shared prototype for the members the
+ * C hook answers.  A wrapper's own lookup reaches the hook first, so these
+ * only serve code that takes them from the prototype, like DOMPurify's
+ * clobbering-safe `getOwnPropertyDescriptor(Node.prototype, "nodeName")
+ * .get.call(node)`; without them it read every node as null and treated
+ * the whole tree as detached.  `busy` stops the recursion when the hook
+ * does not know the name (or `this` is not a wrapper). */
+(function () {
+	var busy = false;
+
+	function own(name) {
+		return Object.getOwnPropertyDescriptor(nodeproto, name);
+	}
+	["nodeName", "nodeType", "parentNode", "nextSibling", "childNodes",
+	 "attributes"].forEach(function (name) {
+		if (own(name)) return;
+		Object.defineProperty(nodeproto, name, {
+			configurable: true, enumerable: false,
+			get: function () {
+				if (busy) return undefined;
+				busy = true;
+				try { return this[name]; } finally { busy = false; }
+			},
+			set: function (v) {
+				if (busy) return;
+				busy = true;
+				try { this[name] = v; } finally { busy = false; }
+			}
+		});
+	});
+	["cloneNode", "remove", "removeAttributeNode"].forEach(function (name) {
+		if (own(name)) return;
+		Object.defineProperty(nodeproto, name, {
+			configurable: true, enumerable: false, writable: true,
+			value: function () {
+				var f;
+
+				if (busy) return undefined;
+				busy = true;
+				try { f = this[name]; } finally { busy = false; }
+				if (typeof f !== "function" || f === nodeproto[name])
+					return undefined;
+				return f.apply(this, arguments);
+			}
+		});
+	});
+})();
 domClass("EventTarget", function (o) { return true; });
 domClass("Node", function (o) { return true; });
 domClass("Element", function (o) { return o.nodeType === 1; });
@@ -1284,6 +1332,59 @@ doc.createRange = function () {
 	};
 };
 doc.createTreeWalker = undefined;
+
+/* NodeIterator over a snapshot of the subtree in document order.  A node
+ * removed from the root meanwhile is skipped, and the children a sanitizer
+ * hoists out of a removed element are still visited, which is what
+ * DOMPurify (the Cloudron dashboard's markdown) relies on. */
+def("NodeFilter", {
+	FILTER_ACCEPT: 1, FILTER_REJECT: 2, FILTER_SKIP: 3,
+	SHOW_ALL: 0xFFFFFFFF, SHOW_ELEMENT: 0x1, SHOW_ATTRIBUTE: 0x2,
+	SHOW_TEXT: 0x4, SHOW_CDATA_SECTION: 0x8,
+	SHOW_PROCESSING_INSTRUCTION: 0x40, SHOW_COMMENT: 0x80,
+	SHOW_DOCUMENT: 0x100, SHOW_DOCUMENT_TYPE: 0x200,
+	SHOW_DOCUMENT_FRAGMENT: 0x400
+});
+doc.createNodeIterator = function (root, what, filter) {
+	var list = [], stack = [root], i = -1, n, c, kids;
+
+	what = what === undefined ? 0xFFFFFFFF : what >>> 0;
+	while (stack.length) {
+		n = stack.pop();
+		list.push(n);
+		kids = [];
+		for (c = n.firstChild; c; c = c.nextSibling) kids.push(c);
+		while (kids.length) stack.push(kids.pop());
+	}
+	function shown(x) {
+		var t = x.nodeType || 1, r;
+
+		if (t > 32 || !(what & (1 << (t - 1)))) return false;
+		if (!filter) return true;
+		r = typeof filter === "function" ? filter(x) : filter.acceptNode(x);
+		return r === 1;
+	}
+	function inside(x) { return x === root || root.contains(x); }
+	return {
+		root: root, whatToShow: what, filter: filter || null,
+		referenceNode: root, pointerBeforeReferenceNode: true,
+		nextNode: function () {
+			while (++i < list.length)
+				if (inside(list[i]) && shown(list[i]))
+					return (this.referenceNode = list[i]);
+			i = list.length;
+			return null;
+		},
+		previousNode: function () {
+			while (--i >= 0)
+				if (inside(list[i]) && shown(list[i]))
+					return (this.referenceNode = list[i]);
+			i = -1;
+			return null;
+		},
+		detach: function () {}
+	};
+};
 doc.hasFocus = function () { return true; };
 doc.getElementsByName = function (n) {
 	return doc.querySelectorAll("[name=\"" + String(n).replace(/"/g, "\\\"") + "\"]");
@@ -1315,6 +1416,7 @@ function nbInertDocument(title) {
 		head.appendChild(t);
 	}
 	d = {
+		__nbInert: true,
 		nodeType: 9, nodeName: "#document", documentElement: html,
 		head: head, body: body, readyState: "complete",
 		compatMode: "CSS1Compat", characterSet: "UTF-8",
@@ -1349,19 +1451,43 @@ function nbInertDocument(title) {
 		} });
 	return d;
 }
+/* The page document's lookups called on an inert document
+ * (`document.getElementsByTagName.call(parsed, "body")`, as DOMPurify does)
+ * answer for that document: searching the page instead handed DOMPurify the
+ * real <body> to sanitize, and it emptied the page. */
+["getElementsByTagName", "getElementsByClassName", "querySelector",
+ "querySelectorAll", "getElementById"].forEach(function (m) {
+	var f = doc[m];
+
+	if (typeof f !== "function") return;
+	doc[m] = function () {
+		if (this && this !== doc && this.__nbInert)
+			return this[m].apply(this, arguments);
+		return f.apply(doc, arguments);
+	};
+});
 doc.implementation = {
 	hasFeature: function () { return true; },
 	createHTMLDocument: function (title) { return nbInertDocument(title); }
 };
 /* DOMParser on the same inert document: the markup goes through the
- * innerHTML fragment parser into the detached body (head elements included,
- * as an approximation). */
+ * innerHTML fragment parser.  A whole document is split at its <head> and
+ * <body>, so the parsed body holds the body's children and not a nested
+ * copy of the <html>/<head>/<body> elements. */
 if (!g.DOMParser) {
 	g.DOMParser = function DOMParser() {};
 	g.DOMParser.prototype.parseFromString = function (str) {
-		var d = nbInertDocument();
+		var d = nbInertDocument(), s = String(str), m;
 
-		d.body.innerHTML = String(str);
+		s = s.replace(/<!doctype[^>]*>/i, "");
+		m = /<head(\s[^>]*)?>([\s\S]*?)<\/head>/i.exec(s);
+		if (m) {
+			d.head.innerHTML = m[2];
+			s = s.slice(0, m.index) + s.slice(m.index + m[0].length);
+		}
+		m = /<body(\s[^>]*)?>([\s\S]*?)(<\/body>|$)/i.exec(s);
+		s = m ? m[2] : s.replace(/<\/?html(\s[^>]*)?>/gi, "");
+		d.body.innerHTML = s;
 		return d;
 	};
 }

Một số tệp đã không được hiển thị bởi vì quá nhiều tập tin thay đổi trong này khác