Quellcode durchsuchen

Add a DOM API layer for browser JavaScript

Expose interned node wrappers with attribute, mutation and query APIs, classList, dataset and inline style objects, innerHTML fragment parsing, and document/window surfaces (timers, navigator, history, split location and anchor URL components). jQuery 1.11, Bootstrap tooltips and AngularJS 1.3 with ngRoute/ngSanitize now initialize, and Cloudron's local page runs its scripts without errors.
Johannes Zellner vor 1 Woche
Ursprung
Commit
eebd85d84b
7 geänderte Dateien mit 2263 neuen und 41 gelöschten Zeilen
  1. 44 17
      AGENTS.md
  2. 10 3
      browser.c
  3. 969 1
      browser_html.c
  4. 44 0
      browser_html.h
  5. 5 3
      docs/userland.html
  6. 1181 13
      js_browser.c
  7. 10 4
      js_browser.h

+ 44 - 17
AGENTS.md

@@ -752,10 +752,29 @@ it to `0x7E00`.  The kernel region itself only has one wall (`_end` below
   `<script src>` bodies are fetched through the same local/network path as
   pages and CSS (512 KB cap), in document order, through the vendored MuJS
   engine in `third_party/mujs/` (linked only into `browser.elf`);
-  `js_browser.c/h` exposes `console.log`, `alert`,
-  `document.getElementById(...).textContent` and `location.href`.  A state
-  is created after `heap_start()`, shared by the page's scripts and freed
-  before `heap_reset()`.  `js_setlimit()` caps every script at 8M
+  `js_browser.c/h` is the DOM layer on top of the engine: one interned MuJS
+  userdata wrapper per node (so `===` and library expando caches work) with
+  `getAttribute`/`setAttribute`/`hasAttribute`, `appendChild`/
+  `insertBefore`/`removeChild`/`replaceChild`/`cloneNode`/`remove`,
+  `querySelector(All)`/`getElementsByTagName`/`getElementsByClassName`,
+  `classList` (including `toggle`'s force argument), `dataset`, inline
+  `style` (`cssText`, property get/set and `getPropertyValue`/
+  `setProperty`/`removeProperty`), `innerHTML` (fragment parser in
+  `browser_html.c`), `textContent`/`nodeValue`, child/sibling/parent
+  traversal, `matches` and `getBoundingClientRect`.  `<a>` elements expose
+  the DOM URL components (`href`/`protocol`/`host`/`hostname`/`port`/
+  `pathname`/`search`/`hash`/`origin`) resolved against the page URL.
+  `document` exposes `createElement`/`createTextNode`/`createComment`/
+  `createDocumentFragment`/`createAttribute`, `documentElement`/`body`/
+  `head` and `readyState`; `navigator`, `history`, `matchMedia`,
+  `getComputedStyle`, `setTimeout`/`setInterval`/`clearTimeout` and
+  `requestAnimationFrame` exist, and due timers run from
+  `js_browser_tick()` in the browser loop.  `location` carries the split
+  protocol/host/hostname/port/pathname/search/hash/origin fields, so
+  Angular-style URL code works.  jQuery 1.11, Bootstrap 3.2 tooltips and
+  AngularJS 1.3 with ngRoute/ngSanitize initialize on a local test page.
+  A state is created after `heap_start()`, shared by the page's scripts and
+  freed before `heap_reset()`.  `js_setlimit()` caps every script at 8M
   instructions, so a runaway loop reports `script ran too long` instead of
   freezing the browser.  Math, Date and JSON come from the engine plus the
   libc math/time layers.  The parsed page is painted before scripts are
@@ -763,9 +782,10 @@ it to `0x7E00`.  The kernel region itself only has one wall (`_end` below
   `/share/bjs-*` for the current boot.  Classic scripts run sloppy by
   default; the vendored engine also carries small Annex B parser fixes for
   regex literals after control parentheses and identity escapes/braces.
-  There are no timers, event listeners, `innerHTML` or forms yet; flex/grid,
-  basic tables, inline SVG and CSS variables are supported (see known issue
-  22 for the remaining CSS gaps).  `SYS_SPAWN`
+  `addEventListener`/`removeEventListener`/`dispatchEvent` are no-ops (no
+  event dispatch yet), and forms are not supported; flex/grid, basic tables,
+  inline SVG and CSS variables are supported (see known issue 22 for the
+  remaining CSS and DOM gaps).  `SYS_SPAWN`
   loads FAT ELFs through `kmalloc` now (the old 16 KB `fat_load_buf` is gone)
   and wraps the load in `sys_fs_enter/exit`,
   since the floppy needs IRQ 6.
@@ -1312,8 +1332,8 @@ and the WM falls back to polling (`io_keyboard_irq_masked()`).
    compressed pack directly to `0x900000` with INT 15h AH=87h, so the cap is
    `PACK_MAX` 1 MB (not the old ~255 KB low-gap limit).  The browser and
    its ring-3 dependencies are compiled with function sections and linked
-   with `--gc-sections`; the current pack with the UI fonts is ~431 KiB
-   (441580 bytes), leaving ~593 KiB under the cap.  `libdeflate-gzip -12` is
+   with `--gc-sections`; the current pack with the UI fonts is ~444 KiB
+   (455092 bytes), leaving ~580 KiB under the cap.  `libdeflate-gzip -12` is
    still preferred for the extra headroom, though the 1 MB cap leaves room
    for `gzip -9` as a fallback.
 9. SMP is **ACPI/MADT only**: no Intel MP-table fallback, so a Pentium II SMP
@@ -1370,14 +1390,21 @@ and the WM falls back to polling (`io_keyboard_irq_masked()`).
     pack is out of the kernel now, so `_end` keeps ~170 KB of headroom below
     the `0x90000` wall; the remaining limit is kernel code/buffers only.
 
-22. Browser limits: JavaScript is only the first MuJS slice (inline and
-    external classic scripts, `document.getElementById(...).textContent`,
-    `console.log`, `alert`, `location.href`; no timers, event listeners,
-    `innerHTML` or form submission; `type="module"`, `defer` and `async` are
-    ignored).  The DOM bindings remain small: pages that expect
-    `document.createElement`, `querySelector(All)`, `classList`,
-    `addEventListener` or timers (jQuery/Bootstrap/Angular) log errors even
-    though their static HTML renders.  Also no pseudo-classes/elements,
+22. Browser limits: JavaScript runs inline and external classic scripts on
+    MuJS with the DOM surface described above (creation/mutation/selectors/
+    attributes/classList/dataset/style/innerHTML/timers).  Still missing:
+    event dispatch (`addEventListener` is a no-op), form submission,
+    `type="module"`, `defer`/`async`, `MutationObserver`/
+    `IntersectionObserver`, `XMLHttpRequest`/`fetch`, `DOMParser`, canvas/2D
+    contexts and pseudo-class/element selectors.  `getComputedStyle` is a
+    stub (it returns empty values), `outerHTML` returns only the string last
+    assigned to `innerHTML`, and `style`/`dataset` cover inline state rather
+    than computed style.  Libraries that need those APIs (jQuery plugins
+    beyond Bootstrap's tooltip, Angular apps that use `$http`) still log
+    errors even though the static page renders.  CSS also lacks
+    border-radius clipping of descendant content, gradients/box-shadow/
+    transitions (a gradient background falls back to its last solid colour),
+    or CSS `color-mix`.  CSS custom properties (`var()`), flex rows with  Also no pseudo-classes/elements,
     border-radius clipping of descendant content, gradients/box-shadow/
     transitions (a gradient background falls back to its last solid colour),
     or CSS `color-mix`.  CSS custom properties (`var()`), flex rows with

+ 10 - 3
browser.c

@@ -376,8 +376,9 @@ static void js_host_navigate(const char *url)
 
 static void js_host_changed(void)
 {
-	/* textContent only replaces text nodes; computed styles are unchanged.
-	 * A future class/style binding must call br_reset_styles() itself. */
+	/* Class/style/attribute mutations change computed styles, not just the
+	 * text: drop the per-node style cache before the next layout. */
+	br_reset_styles(&doc);
 	layout_valid = 0;
 	ngui_invalidate(&ui);
 }
@@ -417,6 +418,8 @@ static void run_page_scripts(void)
 	host.navigate = js_host_navigate;
 	host.changed = js_host_changed;
 	host.page_url = page_url;
+	host.width = ui.w;
+	host.height = ui.h;
 	if (js_browser_start(&doc, &host) != 0) {
 		js_host_status("JavaScript: out of memory", 1);
 		return;
@@ -470,7 +473,8 @@ static void run_page_scripts(void)
 		if (pending_action)
 			break;
 	}
-	js_browser_stop();
+	/* Keep the state alive for setTimeout/ready callbacks; load_page() and
+	 * load_home() stop it before the next navigation. */
 	if (doc.scripts_truncated && !js_last_error)
 		js_host_status("Page has more than 32 scripts; extra scripts skipped",
 			       1);
@@ -4842,6 +4846,9 @@ void _start(const char *arg)
 			preload_node = 0;
 			preload_active = 1;
 		}
+		js_browser_tick();
+		if (pending_action)
+			continue;
 		now = u_ticks_ms();
 		if (status_until && (int)(now - status_until) >= 0) {
 			status_text[0] = '\0';

Datei-Diff unterdrückt, da er zu groß ist
+ 969 - 1
browser_html.c


+ 44 - 0
browser_html.h

@@ -22,6 +22,8 @@
 /* Node types. */
 #define BR_NODE_TEXT     0
 #define BR_NODE_ELEM     1
+#define BR_NODE_COMMENT  2
+#define BR_NODE_FRAGMENT 3
 
 /* Text-node flag: whitespace was preserved (<pre>). */
 #define BR_NODE_PREFORMAT 1
@@ -29,6 +31,8 @@
 #define BR_NODE_HIDDEN   2
 /* Element flag: width_attr/height_attr hold an SVG viewBox. */
 #define BR_NODE_VIEWBOX  4
+/* Node is not part of the document tree (created or removed at runtime). */
+#define BR_NODE_DETACHED 8
 
 /* Extra attribute presence flags (data-collapse-*, state attributes).
  * Stored separately because struct br_style/selector matching needs them
@@ -140,6 +144,8 @@ struct br_node {
 	unsigned int color_off;
 	unsigned int rel_off;
 	unsigned int name_off;      /* raw tag name for custom elements */
+	unsigned int extra_off;     /* packed name\0value\0 list for getAttribute */
+	unsigned short extra_len;
 	unsigned short width_attr;
 	unsigned short height_attr;
 	unsigned char width_pct;
@@ -238,10 +244,48 @@ unsigned int br_tag_from_name(const char *name);
  * node + 1 (0 means no match); br_text_content concatenates the subtree's
  * text nodes into out and returns the (possibly truncated) length. */
 unsigned int br_find_id(struct br_doc *d, const char *id);
+unsigned int br_find_tag(struct br_doc *d, unsigned int tag);
 unsigned int br_text_content(struct br_doc *d, unsigned int node,
 			     char *out, unsigned int cap);
 int br_set_text_content(struct br_doc *d, unsigned int node,
 			const char *text, unsigned int len);
+int br_set_text_node(struct br_doc *d, unsigned int node,
+		     const char *text, unsigned int len);
+
+/* Runtime DOM construction and mutation (node handles are index + 1). */
+unsigned int br_create_element(struct br_doc *d, const char *name,
+			       unsigned int len);
+unsigned int br_create_text(struct br_doc *d, const char *text,
+			    unsigned int len);
+unsigned int br_create_comment(struct br_doc *d, const char *text,
+			       unsigned int len);
+unsigned int br_create_fragment(struct br_doc *d);
+unsigned int br_clone_node(struct br_doc *d, unsigned int node, int deep);
+int br_append_child(struct br_doc *d, unsigned int parent,
+		    unsigned int child);
+int br_insert_before(struct br_doc *d, unsigned int parent,
+		     unsigned int child, unsigned int before);
+int br_remove_child(struct br_doc *d, unsigned int parent,
+		    unsigned int child);
+unsigned int br_find_child(struct br_doc *d, unsigned int parent,
+			   unsigned int child);
+
+const char *br_find_attr(struct br_doc *d, unsigned int node,
+			 const char *name);
+int br_set_attr(struct br_doc *d, unsigned int node, const char *name,
+		const char *value, unsigned int len);
+int br_remove_attr(struct br_doc *d, unsigned int node, const char *name);
+
+/* Replace a node's children with a parsed HTML fragment. */
+int br_set_inner_html(struct br_doc *d, unsigned int node,
+		      const char *html, unsigned int len);
+
+/* Simple selector subset: #id, .class, tag, [attr], [attr=v],
+ * [attr^=v], [attr$=v], [attr*=v], compounds and descendant chains. */
+unsigned int br_query_all(struct br_doc *d, unsigned int root,
+			  const char *selector, unsigned int *out,
+			  unsigned int max);
+int br_matches(struct br_doc *d, unsigned int node, const char *selector);
 
 const char *br_href(struct br_doc *d, unsigned int node);
 const char *br_src(struct br_doc *d, unsigned int node);

+ 5 - 3
docs/userland.html

@@ -296,7 +296,7 @@
 			</div>
 			<div class="card">
 				<h3>System</h3>
-				<p><code>cpuinfo</code> <code>meminfo</code> <code>storage</code> <code>top</code> <code>mouseinfo</code> <code>sensors</code> <code>powerinfo</code> <code>date</code> <code>spin</code> <code>clock</code> <code>colors</code></p>
+				<p><code>cpuinfo</code> <code>meminfo</code> <code>storage</code> <code>top</code> <code>mouseinfo</code> <code>touchpad</code> <code>sensors</code> <code>powerinfo</code> <code>date</code> <code>spin</code> <code>clock</code> <code>colors</code></p>
 			</div>
 			<div class="card">
 				<h3>Network</h3>
@@ -357,8 +357,10 @@
 		</p>
 		<ul>
 			<li><strong>HTML/CSS subset.</strong> External and inline stylesheets, tag/class/id and descendant/child selectors, colours, backgrounds, real <code>font-size</code> (8–48 px), bold/italic faces, <code>font-family: monospace</code>, margins, padding, borders, alignment, percentage widths, basic floats and <code>@media</code> blocks evaluated at the browser canvas width when the page is parsed. Text is Latin-1; there is no shaping, bidi or <code>@font-face</code> yet.</li>
-			<li><strong>JavaScript.</strong> Inline and external <code>&lt;script src&gt;</code> blocks run on the vendored MuJS engine in document order: <code>console.log</code>, <code>alert</code>, <code>document.getElementById(...).textContent</code> and <code>location.href</code>. External scripts use the same local/network fetch path as pages and CSS (512 KB cap) and are cached under <code>/share/bjs-*</code> for the current boot; the parsed page is painted before scripts run. Classic scripts are sloppy by default, and the engine carries Annex B fixes for regex literals after control parentheses and identity escapes/braces. Math, Date and JSON are the engine's; each page gets one state, and an 8M-instruction limit turns a runaway loop into a <code>script ran too long</code> error instead of freezing the browser. The DOM surface is still small: <code>createElement</code>, <code>querySelector(All)</code>, <code>classList</code>, <code>addEventListener</code>, timers, <code>innerHTML</code>, <code>type="module"</code> and <code>defer</code>/<code>async</code> semantics are not implemented, so jQuery/Bootstrap/Angular pages log errors even though their static HTML renders.</li>
-			<li><strong>Not supported.</strong> Forms, pseudo-classes, border-radius clipping of descendants, gradients/box-shadow/transitions and CSS <code>color-mix</code>. Flex rows, card grids, basic tables, inline SVG and CSS variables are supported.</li>
+			<li><strong>JavaScript.</strong> Inline and external <code>&lt;script src&gt;</code> blocks run on the vendored MuJS engine in document order. External scripts use the same local/network fetch path as pages and CSS (512 KB cap) and are cached under <code>/share/bjs-*</code> for the current boot; the parsed page is painted before scripts run. Classic scripts are sloppy by default, and the engine carries Annex B fixes for regex literals after control parentheses and identity escapes/braces. Math, Date and JSON are the engine's; each page gets one state, and an 8M-instruction limit turns a runaway loop into a <code>script ran too long</code> error instead of freezing the browser.</li>
+			<li><strong>DOM.</strong> Nodes are interned MuJS userdata wrappers, so <code>===</code> and library expando caches behave. Elements support <code>getAttribute</code>/<code>setAttribute</code>/<code>hasAttribute</code>, <code>appendChild</code>/<code>insertBefore</code>/<code>removeChild</code>/<code>replaceChild</code>/<code>cloneNode</code>/<code>remove</code>, <code>querySelector(All)</code>, <code>getElementsByTagName</code>, <code>getElementsByClassName</code>, <code>classList</code>, <code>dataset</code>, inline <code>style</code> (<code>cssText</code>, property get/set, <code>getPropertyValue</code>/<code>setProperty</code>/<code>removeProperty</code>), <code>innerHTML</code> (fragment parser), <code>textContent</code>/<code>nodeValue</code>, traversal and <code>matches</code>. <code>&lt;a&gt;</code> elements expose <code>href</code>/<code>protocol</code>/<code>host</code>/<code>hostname</code>/<code>port</code>/<code>pathname</code>/<code>search</code>/<code>hash</code>/<code>origin</code> resolved against the page URL. <code>document</code> has <code>createElement</code>, <code>createTextNode</code>, <code>createComment</code>, <code>createDocumentFragment</code>, <code>createAttribute</code>, <code>documentElement</code>/<code>body</code>/<code>head</code> and <code>readyState</code>; <code>navigator</code>, <code>history</code>, <code>matchMedia</code>, <code>getComputedStyle</code>, <code>setTimeout</code>/<code>setInterval</code>/<code>clearTimeout</code> and <code>requestAnimationFrame</code> exist, and due timers are pumped from the browser loop. jQuery 1.11, Bootstrap 3.2 tooltips and AngularJS 1.3 (with ngRoute/ngSanitize) initialize on a local test page.</li>
+			<li><strong>Not supported.</strong> Event dispatch (<code>addEventListener</code> is a no-op), forms, <code>type="module"</code>, <code>defer</code>/<code>async</code>, <code>MutationObserver</code>/<code>IntersectionObserver</code>, <code>XMLHttpRequest</code>/<code>fetch</code>, <code>DOMParser</code>, canvas/2D contexts and pseudo-class/element selectors. <code>getComputedStyle</code> is a stub; <code>outerHTML</code> only returns the string last assigned to <code>innerHTML</code>.</li>
+			<li><strong>CSS gaps.</strong> Pseudo-classes, border-radius clipping of descendants, gradients/box-shadow/transitions and <code>color-mix</code>. Flex rows, card grids, basic tables, inline SVG and CSS variables are supported.</li>
 			<li><strong>Caps.</strong> 2 MB page body, 832 KB CSS, 6144 DOM nodes, 4608 rules, 16 images. Each image gets an <code>img_estimate()</code>-sized decode arena that is freed after the scaled bitmap is made; navigation calls <code>heap_reset()</code> and unmaps the page heap.</li>
 			<li><strong>Fetching.</strong> Each network fetch starts a one-shot helper process and a fresh TCP/TLS connection; images load one per loop within the viewport plus 160 px.</li>
 			<li><strong>URL entry.</strong> A dotted name without a scheme that is not a known local file extension is treated as a hostname, so <code>cloudron.io</code> does not hit the local-file stat. Origin-level redirects (the common <code>http://host</code> → <code>https://host</code> → <code>https://www.host</code> chain) are cached per process and in <code>/share/borigins</code>; the first visit still follows them, later visits go straight to the canonical origin. Remote stylesheets are cached under <code>/share/bcss-*</code> for the current boot, so a reload or a fresh browser launch skips the CSS downloads.</li>

Datei-Diff unterdrückt, da er zu groß ist
+ 1181 - 13
js_browser.c


+ 10 - 4
js_browser.h

@@ -1,8 +1,9 @@
-/* Minimal browser bindings for the embedded MuJS interpreter.
+/* Browser bindings for the embedded MuJS interpreter.
  *
- * The host owns the document and the UI; this layer only exposes the small
- * DOM surface the first JavaScript milestone needs: console.log, alert,
- * document.getElementById(...).textContent and location.href. */
+ * The host owns the document and the UI; this layer exposes the DOM surface
+ * (elements, attributes, selectors, classList/dataset/style, innerHTML,
+ * timers) plus document/window/location/navigator globals, and leaves the
+ * node tree operations to browser_html.c. */
 #ifndef JS_BROWSER_H
 #define JS_BROWSER_H
 
@@ -14,6 +15,8 @@ struct js_browser_host {
 	void (*navigate)(const char *url);
 	void (*changed)(void);
 	const char *page_url;   /* location.href for every script on the page */
+	unsigned int width;     /* viewport size for window.inner* */
+	unsigned int height;
 };
 
 /* Create a state for this document.  Returns 0 on success. */
@@ -23,6 +26,9 @@ void js_browser_stop(void);
 /* Run one script.  `url` is used in error messages and by location.href. */
 int js_browser_run(const char *source, const char *url);
 
+/* Run due setTimeout/setInterval callbacks; call once per UI loop. */
+void js_browser_tick(void);
+
 int js_browser_active(void);
 
 #endif

Einige Dateien werden nicht angezeigt, da zu viele Dateien in diesem Diff geändert wurden.