Parcourir la source

Add browser form events and POST submission

Johannes Zellner il y a 1 semaine
Parent
commit
fe2677f050

+ 24 - 12
AGENTS.md

@@ -824,7 +824,8 @@ it to `0x7E00`.  The kernel region itself only has one wall (`_end` below
   `@media (min-width/max-width)` blocks are evaluated against the browser
   canvas width when the page is parsed; `@font-face`/`@import`/`@keyframes` are
   skipped.  The compatibility ladder is `testdata/browser/compat/`
-  (`make compat-serve`); pages 010–035 and 030a pass.  Inline
+  (`make compat-serve`); pages 010–036 and 030a pass (036a needs the
+  POST echo server).  Inline
   `<svg>` subtrees and closed `<details>` are skipped (not renderable), and
   `<video>` gets a placeholder box.  The default page canvas follows
   `ngui_theme_dark` (dark page, light text, `theme.panel` for `<pre>`);
@@ -888,14 +889,19 @@ 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.
-  `addEventListener`/`removeEventListener`/`dispatchEvent` are no-ops (no
-  event dispatch yet).  Form controls render, focus, edit, toggle and select
+  `addEventListener`/`removeEventListener`/`dispatchEvent` dispatch real DOM
+  events (capture/bubble, `preventDefault`, `stopPropagation`, `Event` and
+  `document.createEvent`), and element `.click()` runs the default click
+  action.  Form controls render, focus, edit, toggle and select
   (text/password/textarea, checkbox/radio, buttons, select); GET submission
-  builds a query from successful controls, native reset works, and the DOM
+  builds a query from successful controls and POST sends the same encoded
+  body through the fetch helper, native reset works, and the DOM
   `value`/`checked`/`selectedIndex` properties read/write the live control
-  state.  POST and JS `input`/`change`/`submit` events are not implemented.
-  Flex/grid, basic tables, inline SVG and CSS variables are supported (see
-  known issue 22 for the remaining CSS and DOM gaps).  `SYS_SPAWN`
+  state.  Forms expose `elements`/`length`/`submit()`/`reset()`; typing and
+  checkbox/select changes fire `input` and `change`, and submit/reset fire
+  their cancellable events.  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.
@@ -1519,11 +1525,17 @@ and the WM falls back to polling (`io_keyboard_irq_masked()`).
 
 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), POST forms and JS form
-    events, `type="module"`, `defer`/`async`, `MutationObserver`/
-    `IntersectionObserver`, `XMLHttpRequest`/`fetch`, `DOMParser`, canvas/2D
-    contexts and pseudo-class/element selectors.  `getComputedStyle` is a
+    attributes/classList/dataset/style/innerHTML/timers/events).  Event
+    listeners support capture/bubble, `preventDefault`, `stopPropagation`,
+    `Event` and `document.createEvent`; still missing: inline event
+    attributes (`onclick=`), `MouseEvent`/`CustomEvent` and
+    `once`/`passive` options.  POST uses
+    `application/x-www-form-urlencoded`; a redirected POST follows as GET,
+    and `enctype=multipart/form-data` plus file inputs are unsupported.
+    Also missing: `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

+ 214 - 52
browser.c

@@ -143,6 +143,9 @@ static int hist_len, hist_pos;
 
 static char click_url[BR_URL_MAX];
 static char pending_url[BR_URL_MAX];
+#define BR_POST_MAX 4096
+static char pending_post[BR_POST_MAX];
+static unsigned int pending_post_len;
 static unsigned int pending_action;
 static int cancel_fetch;
 static int quit;
@@ -212,10 +215,16 @@ struct form_state {
 };
 static struct form_state form_states[FORM_MAX];
 static unsigned int form_focus;
+static unsigned int form_dirty;
+
+static int form_descendant(unsigned int node, unsigned int form);
+static int form_submit_form(unsigned int node, int fire_event);
+static void form_reset_event(unsigned int form);
 
 static unsigned int s_len(const char *s);
 static int s_eq(const char *a, const char *b);
 static void form_key(int k);
+static void form_click(unsigned int node);
 
 static int form_disabled(unsigned int node)
 {
@@ -721,6 +730,62 @@ static int js_host_form_set_selected(unsigned int node, int index)
 	return 1;
 }
 
+static int js_host_form_elements(unsigned int form, unsigned int *out, int cap)
+{
+	unsigned int i;
+	int n = 0;
+
+	if (!form || form >= doc.nnode || doc.nodes[form].type != BR_NODE_ELEM ||
+	    doc.nodes[form].tag != BR_TAG_FORM)
+		return 0;
+	for (i = 0; i < doc.nnode && n < cap; i++) {
+		struct br_node *nd = &doc.nodes[i];
+
+		if (i == form || nd->type != BR_NODE_ELEM)
+			continue;
+		if (nd->tag != BR_TAG_INPUT && nd->tag != BR_TAG_SELECT &&
+		    nd->tag != BR_TAG_TEXTAREA && nd->tag != BR_TAG_BUTTON)
+			continue;
+		if (!form_descendant(i, form))
+			continue;
+		out[n++] = i;
+	}
+	return n;
+}
+
+static int js_host_form_submit(unsigned int form)
+{
+	form_submit_form(form, 0);
+	return 1;
+}
+
+static int js_host_form_reset(unsigned int form)
+{
+	form_reset_event(form);
+	return 1;
+}
+
+static int js_host_click(unsigned int node)
+{
+	char url[BR_URL_MAX];
+	const char *href;
+
+	if (node >= doc.nnode)
+		return 0;
+	if (form_is_control(node)) {
+		form_click(node);
+		return 1;
+	}
+	href = br_href(&doc, node);
+	if (resolve_link(page_url, href, url, sizeof(url)) != 0)
+		return 0;
+	s_copy(pending_url, url, sizeof(pending_url));
+	pending_action |= ACT_NAV;
+	cancel_fetch = 1;
+	ngui_invalidate(&ui);
+	return 1;
+}
+
 static int fetch_script_text(const char *url, unsigned char **out,
 			     unsigned int *outlen, char *err,
 			     unsigned int errcap);
@@ -762,6 +827,10 @@ static void run_page_scripts(void)
 	host.form_set_value = js_host_form_set_value;
 	host.form_set_checked = js_host_form_set_checked;
 	host.form_set_selected = js_host_form_set_selected;
+	host.form_elements = js_host_form_elements;
+	host.form_submit = js_host_form_submit;
+	host.form_reset = js_host_form_reset;
+	host.click = js_host_click;
 	host.page_url = page_url;
 	host.width = ui.w;
 	host.height = ui.h;
@@ -1399,6 +1468,7 @@ static int inflate_trunc(const unsigned char *src, unsigned int len,
 #define FETCH_BODY "/share/bfbody"
 #define FETCH_META "/share/bfmeta"
 #define FETCH_DONE "/share/bfdone"
+#define FETCH_POST "/share/bfpost"
 
 struct fetch_meta {
 	int status;
@@ -1507,6 +1577,7 @@ static int fetch_helper_start(char *err, unsigned int errcap)
 }
 
 static int worker_fetch(const char *url, unsigned int cap,
+			const char *post, unsigned int post_len,
 			struct fetch_meta *m, char *err, unsigned int errcap)
 {
 	static char req[768], meta[1024], done[24];
@@ -1529,8 +1600,18 @@ static int worker_fetch(const char *url, unsigned int cap,
 	s_append(req, &n, " ", sizeof(req));
 	s_append_dec(req, &n, cap, sizeof(req));
 	s_append(req, &n, " ", sizeof(req));
+	if (post_len) {
+		s_append(req, &n, "POST ", sizeof(req));
+		s_append_dec(req, &n, post_len, sizeof(req));
+		s_append(req, &n, " ", sizeof(req));
+	}
 	s_append(req, &n, url, sizeof(req));
 	s_append(req, &n, "\n", sizeof(req));
+	if (post_len && u_syscall3(SYS_WRITE_FILE, (int)FETCH_POST,
+				   (int)post, (int)post_len) < 0) {
+		s_copy(err, "cannot queue form body", errcap);
+		return -1;
+	}
 	u_syscall1(SYS_UNLINK, (int)FETCH_DONE);
 	u_syscall1(SYS_UNLINK, (int)FETCH_META);
 	if (u_syscall3(SYS_WRITE_FILE, (int)FETCH_REQ, (int)req, (int)n) < 0) {
@@ -1601,6 +1682,7 @@ static int worker_fetch(const char *url, unsigned int cap,
 }
 
 static int fetch_remote(const char *url, unsigned int cap,
+			const char *post, unsigned int post_len,
 			unsigned char *plain, unsigned int plaincap,
 			unsigned char *comp, unsigned int compcap,
 			struct fetch_meta *m, int *truncated,
@@ -1608,7 +1690,7 @@ static int fetch_remote(const char *url, unsigned int cap,
 {
 	int rv, zr, was_trunc;
 
-	rv = worker_fetch(url, cap, m, err, errcap);
+	rv = worker_fetch(url, cap, post, post_len, m, err, errcap);
 	if (rv == FETCH_ABORT)
 		return FETCH_ABORT;
 	if (rv != 0)
@@ -1657,7 +1739,8 @@ static int fetch_remote(const char *url, unsigned int cap,
 static int read_url(const char *url, unsigned int cap, unsigned char **out,
 		    unsigned int *outlen, int *is_local, char *ctype,
 		    unsigned int ctcap, char *final, unsigned int finalcap,
-		    char *err, unsigned int errcap, int *truncated)
+		    char *err, unsigned int errcap, int *truncated,
+		    const char *post, unsigned int post_len)
 {
 	unsigned char *buf;
 	unsigned int len;
@@ -1713,8 +1796,8 @@ static int read_url(const char *url, unsigned int cap, unsigned char **out,
 		s_copy(err, "out of memory", errcap);
 		return -1;
 	}
-	rv = fetch_remote(url, cap, buf, cap, image_io_buf, BR_PAGE_COMP_MAX,
-			  &fetch_meta, &tr, err, errcap);
+	rv = fetch_remote(url, cap, post, post_len, buf, cap, image_io_buf,
+			  BR_PAGE_COMP_MAX, &fetch_meta, &tr, err, errcap);
 	if (rv == FETCH_ABORT) {
 		free(buf);
 		return FETCH_ABORT;
@@ -1863,7 +1946,7 @@ static int fetch_script_text(const char *url, unsigned char **out,
 		return 0;
 	rv = read_url(url, BR_SCRIPT_MAX, &buf, &len, &local, ctype,
 		      sizeof(ctype), final, sizeof(final), err, errcap,
-		      &truncated);
+		      &truncated, 0, 0);
 	if (rv != 0)
 		return rv;
 	if (truncated || len >= BR_SCRIPT_MAX) {
@@ -1904,7 +1987,7 @@ static int fetch_image(const char *url, unsigned int cap,
 		*outlen = (unsigned int)rv;
 		return 0;
 	}
-	rv = fetch_remote(url, cap, image_file_buf, cap, image_comp_buf,
+	rv = fetch_remote(url, cap, 0, 0, image_file_buf, cap, image_comp_buf,
 			  BR_IMG_FILE_MAX, &fetch_meta, &tr, err, errcap);
 	if (rv == FETCH_ABORT)
 		return FETCH_ABORT;
@@ -2044,7 +2127,7 @@ static int fetch_css(const char *url, unsigned char **out, unsigned int *outlen,
 	}
 	if (css_cache_get(url, out, outlen))
 		return 0;
-	rv = fetch_remote(url, BR_CSS_MAX, image_io_buf, BR_CSS_MAX,
+	rv = fetch_remote(url, BR_CSS_MAX, 0, 0, image_io_buf, BR_CSS_MAX,
 			  image_io_buf + BR_CSS_MAX, BR_CSS_COMP_MAX,
 			  &fetch_meta, &tr, err, errcap);
 	if (rv == FETCH_ABORT)
@@ -2420,9 +2503,12 @@ static void load_page(const char *url, int local, int push)
 	char final[BR_URL_MAX];
 	char err[80];
 	const char *detail = 0;
+	const char *post = pending_post_len ? pending_post : 0;
+	unsigned int post_len = pending_post_len;
 	int rv;
 
 	final[0] = '\0';
+	pending_post_len = 0;
 	cancel_fetch = 0;
 	preload_active = 0;
 	preload_pending = 0;
@@ -2463,7 +2549,7 @@ static void load_page(const char *url, int local, int push)
 	browser_rules_alloc();
 	rv = read_url(url, BR_PAGE_MAX, &body, &len, &local, ctype,
 		     sizeof(ctype), final, sizeof(final), err, sizeof(err),
-		     &truncated);
+		     &truncated, post, post_len);
 	if (rv == FETCH_ABORT)
 		return;
 	if (rv != 0) {
@@ -2550,6 +2636,7 @@ static void load_page(const char *url, int local, int push)
 
 static void load_home(int push)
 {
+	pending_post_len = 0;
 	cancel_fetch = 0;
 	preload_active = 0;
 	preload_pending = 0;
@@ -6445,26 +6532,25 @@ static void form_add_param(char *dst, unsigned int *n, unsigned int cap,
 	dst[*n] = '\0';
 }
 
-static void form_submit(unsigned int node)
+static int form_submit_form(unsigned int node, int fire_event)
 {
 	unsigned int form = form_ancestor(node);
 	char action[BR_URL_MAX], query[2048];
 	unsigned int qn = 0, i;
-	int first = 1;
+	int first = 1, is_post = 0;
 	const char *a, *method;
 
 	if (!form)
-		return;
+		return 0;
+	if (fire_event && !js_browser_event(form, "submit", 1, 1))
+		return 0;
 	method = br_find_attr(&doc, form, "method");
-	if (method && (s_eq(method, "post") || s_eq(method, "POST"))) {
-		set_status("POST forms are not supported", 1, 4000);
-		ngui_invalidate(&ui);
-		return;
-	}
+	if (method && (s_eq(method, "post") || s_eq(method, "POST")))
+		is_post = 1;
 	a = br_find_attr(&doc, form, "action");
 	if (a && a[0]) {
 		if (resolve_link(page_url, a, action, sizeof(action)) != 0)
-			return;
+			return 0;
 	} else {
 		s_copy(action, page_url, sizeof(action));
 	}
@@ -6536,40 +6622,88 @@ static void form_submit(unsigned int node)
 		}
 		form_add_param(query, &qn, sizeof(query), name, value, &first);
 	}
-	if (qn) {
-		unsigned int an = s_len(action);
-
-		if (an + qn + 2 < sizeof(action)) {
-			action[an++] = strchr(action, '?') ? '&' : '?';
-			action[an] = '\0';
-			s_copy(action + an, query, sizeof(action) - an);
+	if (is_post) {
+		if (action[0] == '/') {
+			set_status("POST forms need an HTTP action URL", 1, 4000);
+			ngui_invalidate(&ui);
+			return 0;
+		}
+		if (qn >= sizeof(pending_post))
+			qn = sizeof(pending_post) - 1;
+		if (qn)
+			memcpy(pending_post, query, qn);
+		pending_post[qn] = '\0';
+		pending_post_len = qn;
+	} else {
+		pending_post_len = 0;
+		if (qn) {
+			unsigned int an = s_len(action);
+
+			if (an + qn + 2 < sizeof(action)) {
+				action[an++] = strchr(action, '?') ? '&' : '?';
+				action[an] = '\0';
+				s_copy(action + an, query,
+				       sizeof(action) - an);
+			}
 		}
 	}
 	s_copy(pending_url, action, sizeof(pending_url));
 	pending_action |= ACT_NAV;
 	cancel_fetch = 1;
 	ngui_invalidate(&ui);
+	return 1;
+}
+
+static void form_reset_event(unsigned int form)
+{
+	if (form && !js_browser_event(form, "reset", 1, 1))
+		return;
+	if (form)
+		form_reset_form(form);
+	else
+		form_reset_state();
+	form_dirty = 0;
+	layout_valid = 0;
+	ngui_invalidate(&ui);
+}
+
+static void form_blur(void)
+{
+	unsigned int node = form_focus;
+
+	form_focus = 0;
+	if (node && form_dirty) {
+		form_dirty = 0;
+		js_browser_event(node, "change", 1, 0);
+	}
 }
 
 static void form_click(unsigned int node)
 {
 	struct form_state *fs;
-	int kind;
+	int kind, changed = 0;
 
 	if (!form_is_control(node) || form_disabled(node))
 		return;
+	if (form_focus != node)
+		form_blur();
+	if (!js_browser_event(node, "click", 1, 1))
+		return;
 	fs = form_get(node, 1);
 	if (!fs)
 		return;
 	kind = form_kind_of(node);
 	form_focus = node;
+	form_dirty = 0;
 	if (kind == FORM_CHECKBOX) {
 		fs->checked = !fs->checked;
+		changed = 1;
 	} else if (kind == FORM_RADIO) {
 		const char *name = br_find_attr(&doc, node, "name");
 		unsigned int i;
 
 		fs->checked = 1;
+		changed = 1;
 		if (name) {
 			for (i = 0; i < FORM_MAX; i++) {
 				struct form_state *o = &form_states[i];
@@ -6588,24 +6722,25 @@ static void form_click(unsigned int node)
 	} else if (kind == FORM_SELECT) {
 		unsigned int n = form_option_count(node);
 
-		if (n)
-			fs->selected = (unsigned char)((fs->selected + 1) % n);
+		if (n) {
+			fs->selected = (unsigned char)
+				((fs->selected + 1) % n);
+			changed = 1;
+		}
 	} else if (kind == FORM_SUBMIT) {
-		form_submit(node);
+		form_submit_form(node, 1);
+		return;
 	} else if (kind == FORM_RESET) {
-		unsigned int f = form_ancestor(node);
-
-		if (f)
-			form_reset_form(f);
-		else
-			form_reset_state();
-		layout_valid = 0;
-		ngui_invalidate(&ui);
+		form_reset_event(form_ancestor(node));
 		return;
 	} else if (kind == FORM_TEXT || kind == FORM_PASSWORD ||
 		   kind == FORM_TEXTAREA) {
 		fs->caret = fs->len;
 	}
+	if (changed) {
+		js_browser_event(node, "input", 1, 0);
+		js_browser_event(node, "change", 1, 0);
+	}
 	layout_valid = 0;
 	ngui_invalidate(&ui);
 }
@@ -6615,6 +6750,7 @@ static void form_focus_next(void)
 	unsigned int start = form_focus ? form_focus + 1 : 0;
 	unsigned int i;
 
+	form_blur();
 	for (i = start; i < doc.nnode; i++) {
 		if (form_is_control(i) && !form_disabled(i) &&
 		    !s_eq(br_type(&doc, i), "hidden")) {
@@ -6644,48 +6780,66 @@ static void form_key(int k)
 	kind = form_kind_of(form_focus);
 	if (kind == FORM_SELECT) {
 		unsigned int n = form_option_count(form_focus);
+		int changed = 0;
 
-		if (k == NGUI_KEY_UP && n)
+		if (k == NGUI_KEY_UP && n) {
 			fs->selected = (unsigned char)
 				((fs->selected + n - 1) % n);
-		else if (k == NGUI_KEY_DOWN && n)
+			changed = 1;
+		} else if (k == NGUI_KEY_DOWN && n) {
 			fs->selected = (unsigned char)
 				((fs->selected + 1) % n);
-		else if (k == NGUI_KEY_ESC || k == '\r' || k == '\n')
-			form_focus = 0;
-		else
+			changed = 1;
+		} else if (k == NGUI_KEY_ESC || k == '\r' || k == '\n') {
+			form_blur();
+			layout_valid = 0;
+			ngui_invalidate(&ui);
 			return;
+		} else {
+			return;
+		}
+		if (changed) {
+			js_browser_event(form_focus, "input", 1, 0);
+			js_browser_event(form_focus, "change", 1, 0);
+		}
 	} else if (kind == FORM_CHECKBOX || kind == FORM_RADIO) {
 		if (k == ' ') {
 			form_click(form_focus);
 			return;
 		}
 		if (k == NGUI_KEY_ESC || k == '\r' || k == '\n') {
-			form_focus = 0;
+			form_blur();
 			layout_valid = 0;
 			ngui_invalidate(&ui);
 		}
 		return;
 	} else if (kind == FORM_BUTTON || kind == FORM_SUBMIT ||
 		   kind == FORM_RESET) {
-		if (k == NGUI_KEY_ESC || k == '\r' || k == '\n') {
-			form_focus = 0;
+		if (k == NGUI_KEY_ESC) {
+			form_blur();
 			layout_valid = 0;
 			ngui_invalidate(&ui);
+		} else if (k == '\r' || k == '\n' || k == ' ') {
+			form_click(form_focus);
 		}
 		return;
 	} else if (k == NGUI_KEY_TAB) {
 		form_focus_next();
 		return;
 	} else if (k == NGUI_KEY_ESC) {
-		form_focus = 0;
+		form_blur();
+		layout_valid = 0;
+		ngui_invalidate(&ui);
+		return;
 	} else if (k == '\r' || k == '\n') {
-		if (form_ancestor(form_focus)) {
-			form_submit(form_focus);
-			form_focus = 0;
-		} else {
-			form_focus = 0;
-		}
+		unsigned int node = form_focus;
+
+		form_blur();
+		if (form_ancestor(node))
+			form_submit_form(node, 1);
+		layout_valid = 0;
+		ngui_invalidate(&ui);
+		return;
 	} else if (k == NGUI_KEY_BACKSPACE) {
 		if (fs->caret) {
 			unsigned int i = --fs->caret;
@@ -6694,6 +6848,8 @@ static void form_key(int k)
 				fs->value[i] = fs->value[i + 1];
 			if (fs->len)
 				fs->len--;
+			form_dirty = 1;
+			js_browser_event(form_focus, "input", 1, 0);
 		}
 	} else if (k == NGUI_KEY_DELETE) {
 		if (fs->caret < fs->len) {
@@ -6702,6 +6858,8 @@ static void form_key(int k)
 			for (i = fs->caret; i < fs->len; i++)
 				fs->value[i] = fs->value[i + 1];
 			fs->len--;
+			form_dirty = 1;
+			js_browser_event(form_focus, "input", 1, 0);
 		}
 	} else if (k == NGUI_KEY_LEFT) {
 		if (fs->caret)
@@ -6721,6 +6879,8 @@ static void form_key(int k)
 				fs->value[i] = fs->value[i - 1];
 			fs->value[fs->caret++] = (char)k;
 			fs->len++;
+			form_dirty = 1;
+			js_browser_event(form_focus, "input", 1, 0);
 		}
 	} else {
 		return;
@@ -6749,7 +6909,9 @@ static void handle_page_click(unsigned int *action)
 		form_click((unsigned int)node);
 		return;
 	}
-	form_focus = 0;
+	form_blur();
+	if (!js_browser_event((unsigned int)node, "click", 1, 1))
+		return;
 	if (resolve_link(page_url, br_href(&doc, (unsigned int)node), url,
 			 sizeof(url)) != 0)
 		return;

Fichier diff supprimé car celui-ci est trop grand
+ 0 - 2
docs/userland.html


+ 665 - 15
js_browser.c

@@ -36,6 +36,8 @@ static const char *current_url;
 static jmp_buf panic_env;
 static int panic_armed;
 
+static void report_top(js_State *state);
+
 static void report_cb(js_State *state, const char *message)
 {
 	(void)state;
@@ -45,9 +47,13 @@ static void report_cb(js_State *state, const char *message)
 
 static void panic_cb(js_State *state)
 {
-	(void)state;
 	if (panic_armed)
 		longjmp(panic_env, 1);
+	if (js_isobject(state, -1))
+		report_top(state);
+	else if (host.report)
+		host.report(js_trystring(state, -1,
+			"uncaught JavaScript exception"));
 	if (host.report)
 		host.report("uncaught JavaScript exception");
 }
@@ -170,6 +176,548 @@ static unsigned int node_name(unsigned int node, char *buf, unsigned int cap)
 	return i;
 }
 
+/* ---- DOM events ------------------------------------------------------- *
+ *
+ * Listeners live in a fixed table, one entry per (target, type, callback)
+ * registration, and callbacks are retained through the MuJS registry.  The
+ * dispatcher walks the parent chain for bubbling and runs one listener at a
+ * time so a handler can safely mutate the tree.  `preventDefault` is tracked
+ * per dispatch in a small event-state table and mirrored onto the event
+ * object, so a submit handler can cancel the browser's default action. */
+
+#define JS_LISTENERS        64
+#define JS_EVENT_SLOTS       8
+#define JS_EVENT_TEMPLATES  16
+
+#define JS_TARGET_WINDOW   0xFFFFFFF0u
+#define JS_TARGET_DOCUMENT 0xFFFFFFF1u
+
+struct js_listener {
+	unsigned char used;
+	unsigned char capture;
+	unsigned int target;
+	char type[24];
+	char ref[32];
+};
+
+struct js_event_state {
+	int used;
+	int prevented;
+	int stopped;
+	int immediate;
+	char objref[32];
+};
+
+struct js_template {
+	int used;
+	char ref[32];
+};
+
+static struct js_listener listeners[JS_LISTENERS];
+static struct js_event_state events[JS_EVENT_SLOTS];
+static struct js_template event_templates[JS_EVENT_TEMPLATES];
+
+static void push_event_target(js_State *state, unsigned int target)
+{
+	if (target == JS_TARGET_WINDOW)
+		js_pushglobal(state);
+	else if (target == JS_TARGET_DOCUMENT)
+		js_getglobal(state, "document");
+	else
+		push_node(state, target + 1);
+}
+
+static void obj_set(js_State *state, int idx, const char *name)
+{
+	/* The value was just pushed, so a negative object index moved down. */
+	if (idx < 0)
+		idx--;
+	js_setproperty(state, idx, name);
+}
+
+static void obj_set_string(js_State *state, int idx, const char *name,
+			   const char *value)
+{
+	js_pushstring(state, value ? value : "");
+	obj_set(state, idx, name);
+}
+
+static void obj_set_bool(js_State *state, int idx, const char *name, int value)
+{
+	js_pushboolean(state, value != 0);
+	obj_set(state, idx, name);
+}
+
+static int event_slot(js_State *state)
+{
+	int slot = (int)(uintptr_t)js_currentfunctiondata(state);
+
+	if (slot < 0 || slot >= JS_EVENT_SLOTS)
+		return -1;
+	return slot;
+}
+
+static void event_preventdefault(js_State *state)
+{
+	int slot = event_slot(state);
+
+	if (slot >= 0) {
+		struct js_event_state *ev = &events[slot];
+
+		ev->prevented = 1;
+		if (ev->objref[0]) {
+			js_getregistry(state, ev->objref);
+			if (js_isobject(state, -1)) {
+				js_pushboolean(state, 1);
+				js_setproperty(state, -2, "defaultPrevented");
+			}
+			js_pop(state, 1);
+		}
+	}
+	js_pushundefined(state);
+}
+
+static void event_stoppropagation(js_State *state)
+{
+	int slot = event_slot(state);
+
+	if (slot >= 0)
+		events[slot].stopped = 1;
+	js_pushundefined(state);
+}
+
+static void event_stopimmediate(js_State *state)
+{
+	int slot = event_slot(state);
+
+	if (slot >= 0) {
+		events[slot].stopped = 1;
+		events[slot].immediate = 1;
+	}
+	js_pushundefined(state);
+}
+
+/* Event-object field helpers.  Every dispatch owns a registry key for its
+ * event object so preventDefault can update the object without access to
+ * `this` (this MuJS has no this accessor). */
+static void ev_set_string(js_State *state, int slot, const char *name,
+			  const char *value)
+{
+	js_getregistry(state, events[slot].objref);
+	js_pushstring(state, value ? value : "");
+	js_setproperty(state, -2, name);
+	js_pop(state, 1);
+}
+
+static void ev_set_bool(js_State *state, int slot, const char *name, int value)
+{
+	js_getregistry(state, events[slot].objref);
+	js_pushboolean(state, value != 0);
+	js_setproperty(state, -2, name);
+	js_pop(state, 1);
+}
+
+static void ev_set_number(js_State *state, int slot, const char *name,
+			  double value)
+{
+	js_getregistry(state, events[slot].objref);
+	js_pushnumber(state, value);
+	js_setproperty(state, -2, name);
+	js_pop(state, 1);
+}
+
+static void ev_set_target(js_State *state, int slot, const char *name,
+			  unsigned int target)
+{
+	js_getregistry(state, events[slot].objref);
+	push_event_target(state, target);
+	js_setproperty(state, -2, name);
+	js_pop(state, 1);
+}
+
+static int ev_get_bool(js_State *state, int slot, const char *name, int def)
+{
+	int rv = def;
+
+	js_getregistry(state, events[slot].objref);
+	js_getproperty(state, -1, name);
+	if (js_isboolean(state, -1))
+		rv = js_toboolean(state, -1);
+	js_pop(state, 2);
+	return rv;
+}
+
+static void ev_get_string(js_State *state, int slot, const char *name,
+			  char *out, int cap, const char *def)
+{
+	const char *s = def ? def : "";
+	int n = 0;
+
+	js_getregistry(state, events[slot].objref);
+	js_getproperty(state, -1, name);
+	if (js_isstring(state, -1))
+		s = js_tostring(state, -1);
+	while (s[n] && n + 1 < cap) {
+		out[n] = s[n];
+		n++;
+	}
+	out[n] = '\0';
+	js_pop(state, 2);
+}
+
+static void event_bind_methods(js_State *state, int slot)
+{
+	js_getregistry(state, events[slot].objref);
+	def_func_data(state, "preventDefault", event_preventdefault, 0,
+		      (unsigned int)slot);
+	def_func_data(state, "stopPropagation", event_stoppropagation, 0,
+		      (unsigned int)slot);
+	def_func_data(state, "stopImmediatePropagation", event_stopimmediate, 0,
+		      (unsigned int)slot);
+	js_pop(state, 1);
+}
+
+/* The event object is on top of the stack; move it into the registry and
+ * fill in the standard fields. */
+static int event_prepare(js_State *state, unsigned int target)
+{
+	int slot;
+
+	for (slot = 0; slot < JS_EVENT_SLOTS; slot++)
+		if (!events[slot].used)
+			break;
+	if (slot == JS_EVENT_SLOTS)
+		return -1;
+	events[slot].used = 1;
+	events[slot].prevented = 0;
+	events[slot].stopped = 0;
+	events[slot].immediate = 0;
+	snprintf(events[slot].objref, sizeof(events[slot].objref),
+		 "jseventobj_%d", slot);
+	js_setregistry(state, events[slot].objref);
+
+	ev_set_bool(state, slot, "defaultPrevented", 0);
+	ev_set_bool(state, slot, "isTrusted", 0);
+	ev_set_number(state, slot, "timeStamp", (double)u_ticks_ms());
+	ev_set_target(state, slot, "target", target);
+	ev_set_target(state, slot, "currentTarget", target);
+	ev_set_number(state, slot, "eventPhase", 2);
+	event_bind_methods(state, slot);
+	return slot;
+}
+
+static int listener_call(js_State *state, const struct js_listener *l,
+			 int slot, unsigned int current_target)
+{
+	js_getregistry(state, l->ref);
+	if (!js_iscallable(state, -1)) {
+		js_pop(state, 1);
+		return 0;
+	}
+	push_event_target(state, current_target);
+	js_getregistry(state, events[slot].objref);
+	if (js_pcall(state, 1)) {
+		report_top(state);
+		return 0;
+	}
+	js_pop(state, 1);
+	return 1;
+}
+
+static void listener_phase(js_State *state, unsigned int target,
+			   const char *type, int phase, int slot)
+{
+	int i;
+
+	for (i = 0; i < JS_LISTENERS; i++) {
+		struct js_listener *l = &listeners[i];
+
+		if (!l->used || l->target != target ||
+		    strcmp(l->type, type) != 0)
+			continue;
+		if (phase == 1 && !l->capture)
+			continue;
+		if (phase == 2 && l->capture)
+			continue;
+		ev_set_target(state, slot, "currentTarget", target);
+		listener_call(state, l, slot, target);
+		if (events[slot].immediate)
+			return;
+	}
+}
+
+/* supplied_idx: 0 creates a fresh object, otherwise it is the argument
+ * index of an Event supplied by JavaScript.  Leaves a boolean result. */
+static int dispatch_object(js_State *state, unsigned int target,
+			   int supplied_idx, const char *fallback,
+			   int def_bubbles, int def_cancelable)
+{
+	unsigned int path[64];
+	char type[32];
+	int np = 0, slot, i, prevented;
+	struct br_node *nd;
+
+	if (supplied_idx)
+		js_copy(state, supplied_idx);
+	else
+		js_newobject(state);
+	slot = event_prepare(state, target);
+	if (slot < 0) {
+		js_pushboolean(state, 1);
+		return 1;
+	}
+	ev_get_string(state, slot, "type", type, sizeof(type), fallback);
+	if (!type[0]) {
+		js_unref(state, events[slot].objref);
+		events[slot].objref[0] = '\0';
+		events[slot].used = 0;
+		js_pushboolean(state, 1);
+		return 1;
+	}
+	ev_set_string(state, slot, "type", type);
+	ev_set_bool(state, slot, "bubbles",
+		    ev_get_bool(state, slot, "bubbles", def_bubbles));
+	ev_set_bool(state, slot, "cancelable",
+		    ev_get_bool(state, slot, "cancelable", def_cancelable));
+
+	path[np++] = target;
+	if (target != JS_TARGET_WINDOW && target != JS_TARGET_DOCUMENT &&
+	    D && target < D->nnode) {
+		nd = &D->nodes[target];
+		while (nd->parent && nd->parent < D->nnode &&
+		       np < (int)(sizeof(path) / sizeof(path[0]))) {
+			path[np++] = nd->parent;
+			nd = &D->nodes[nd->parent];
+		}
+	}
+	if (target != JS_TARGET_WINDOW)
+		path[np++] = JS_TARGET_DOCUMENT;
+	if (np < (int)(sizeof(path) / sizeof(path[0])))
+		path[np++] = JS_TARGET_WINDOW;
+
+	/* Capture from the outermost ancestor down to the parent. */
+	for (i = np - 1; i > 0; i--) {
+		if (events[slot].stopped)
+			break;
+		listener_phase(state, path[i], type, 1, slot);
+	}
+	/* Target phase: capture and bubble listeners in registration order. */
+	if (!events[slot].stopped)
+		listener_phase(state, path[0], type, 0, slot);
+	/* Bubble only for events that ask for it; stopPropagation stops the
+	 * remaining ancestors. */
+	if (ev_get_bool(state, slot, "bubbles", def_bubbles)) {
+		for (i = 1; i < np && !events[slot].stopped; i++)
+			listener_phase(state, path[i], type, 2, slot);
+	}
+
+	prevented = events[slot].prevented;
+	js_unref(state, events[slot].objref);
+	events[slot].objref[0] = '\0';
+	events[slot].used = 0;
+	js_pushboolean(state, prevented ? 0 : 1);
+	return prevented ? 0 : 1;
+}
+
+static void add_listener(js_State *state, unsigned int target, int remove)
+{
+	const char *type;
+	int i;
+
+	if (!js_iscallable(state, 2))
+		return;
+	type = js_tostring(state, 1);
+	if (!type[0])
+		return;
+	if (!remove) {
+		for (i = 0; i < JS_LISTENERS; i++)
+			if (!listeners[i].used)
+				break;
+		if (i == JS_LISTENERS)
+			return;
+		listeners[i].used = 1;
+		listeners[i].capture = js_isboolean(state, 3) &&
+				       js_toboolean(state, 3);
+		listeners[i].target = target;
+		snprintf(listeners[i].type, sizeof(listeners[i].type), "%s",
+			 type);
+		js_copy(state, 2);
+		snprintf(listeners[i].ref, sizeof(listeners[i].ref), "%s",
+			 js_ref(state));
+		return;
+	}
+	for (i = 0; i < JS_LISTENERS; i++) {
+		struct js_listener *l = &listeners[i];
+		int eq;
+
+		if (!l->used || l->target != target ||
+		    strcmp(l->type, type) != 0)
+			continue;
+		js_getregistry(state, l->ref);
+		js_copy(state, 2);
+		eq = js_equal(state);
+		js_pop(state, 2);
+		if (!eq)
+			continue;
+		js_unref(state, l->ref);
+		l->used = 0;
+		return;
+	}
+}
+
+static void node_addlistener(js_State *state)
+{
+	unsigned int node = (unsigned int)(uintptr_t)
+				js_currentfunctiondata(state) - 1;
+
+	add_listener(state, node, 0);
+}
+
+static void node_removelistener(js_State *state)
+{
+	unsigned int node = (unsigned int)(uintptr_t)
+				js_currentfunctiondata(state) - 1;
+
+	add_listener(state, node, 1);
+}
+
+static void node_dispatchevent(js_State *state)
+{
+	unsigned int node = (unsigned int)(uintptr_t)
+				js_currentfunctiondata(state) - 1;
+
+	if (!D || !node) {
+		js_pushboolean(state, 1);
+		return;
+	}
+	if (js_isobject(state, 1)) {
+		dispatch_object(state, node, 1, "event", 1, 0);
+	} else {
+		char type[32];
+		const char *s = js_tostring(state, 1);
+		unsigned int i = 0;
+
+		while (s[i] && i + 1 < sizeof(type)) {
+			type[i] = s[i];
+			i++;
+		}
+		type[i] = '\0';
+		dispatch_object(state, node, 0, type, 1, 0);
+	}
+}
+
+static void win_addlistener(js_State *state)
+{
+	add_listener(state, JS_TARGET_WINDOW, 0);
+}
+
+static void win_removelistener(js_State *state)
+{
+	add_listener(state, JS_TARGET_WINDOW, 1);
+}
+
+static void doc_addlistener(js_State *state)
+{
+	add_listener(state, JS_TARGET_DOCUMENT, 0);
+}
+
+static void doc_removelistener(js_State *state)
+{
+	add_listener(state, JS_TARGET_DOCUMENT, 1);
+}
+
+static void event_init(js_State *state)
+{
+	int slot = (int)(uintptr_t)js_currentfunctiondata(state);
+	const char *type;
+
+	if (slot < 0 || slot >= JS_EVENT_TEMPLATES ||
+	    !event_templates[slot].used)
+		return;
+	type = js_tostring(state, 1);
+	js_getregistry(state, event_templates[slot].ref);
+	if (!js_isobject(state, -1)) {
+		js_pop(state, 1);
+		return;
+	}
+	obj_set_string(state, -1, "type", type);
+	obj_set_bool(state, -1, "bubbles", js_toboolean(state, 2));
+	obj_set_bool(state, -1, "cancelable", js_toboolean(state, 3));
+	js_pop(state, 1);
+}
+
+static void event_build_object(js_State *state, const char *type,
+			       int bubbles, int cancelable, int with_init)
+{
+	js_newobject(state);
+	js_pushstring(state, type ? type : "");
+	js_setproperty(state, -2, "type");
+	js_pushboolean(state, bubbles != 0);
+	js_setproperty(state, -2, "bubbles");
+	js_pushboolean(state, cancelable != 0);
+	js_setproperty(state, -2, "cancelable");
+	js_pushboolean(state, 0);
+	js_setproperty(state, -2, "defaultPrevented");
+	if (with_init) {
+		int i;
+
+		for (i = 0; i < JS_EVENT_TEMPLATES; i++)
+			if (!event_templates[i].used)
+				break;
+		if (i < JS_EVENT_TEMPLATES) {
+			event_templates[i].used = 1;
+			snprintf(event_templates[i].ref,
+				 sizeof(event_templates[i].ref),
+				 "jseventtmpl_%d", i);
+			js_copy(state, -1);
+			js_setregistry(state, event_templates[i].ref);
+			def_func_data(state, "initEvent", event_init, 3,
+				      (unsigned int)i);
+		}
+	}
+}
+
+static void event_call(js_State *state)
+{
+	const char *type = js_isdefined(state, 1) ? js_tostring(state, 1) : "";
+	int bubbles = 0, cancelable = 0;
+
+	if (js_isobject(state, 2)) {
+		js_getproperty(state, 2, "bubbles");
+		bubbles = js_toboolean(state, -1);
+		js_pop(state, 1);
+		js_getproperty(state, 2, "cancelable");
+		cancelable = js_toboolean(state, -1);
+		js_pop(state, 1);
+	}
+	event_build_object(state, type, bubbles, cancelable, 1);
+}
+
+static void doc_createevent(js_State *state)
+{
+	const char *type = js_tostring(state, 1);
+
+	event_build_object(state, type, 0, 0, 1);
+}
+
+int js_browser_event(unsigned int node, const char *type, int bubbles,
+		     int cancelable)
+{
+	int slot, rv;
+
+	if (!J || !D)
+		return 1;
+	for (slot = 0; slot < JS_EVENT_SLOTS; slot++)
+		if (!events[slot].used)
+			break;
+	if (slot == JS_EVENT_SLOTS)
+		return 1;
+	js_setlimit(J, JS_RUN_LIMIT, 0);
+	rv = dispatch_object(J, node, 0, type, bubbles, cancelable);
+	js_pop(J, 1);
+	return rv;
+}
+
 static unsigned int node_type_value(unsigned int node)
 {
 	struct br_node *n;
@@ -929,6 +1477,15 @@ static void node_matches(js_State *state)
 					 js_tostring(state, 1)));
 }
 
+static void node_click(js_State *state)
+{
+	unsigned int node = node_of(js_currentfunctiondata(state));
+
+	if (host.click)
+		host.click(node);
+	js_pushundefined(state);
+}
+
 static void node_getelementsbytagname(js_State *state)
 {
 	unsigned int node = node_of(js_currentfunctiondata(state));
@@ -1035,6 +1592,55 @@ static void node_push_text(js_State *state, unsigned int node)
 	free(buf);
 }
 
+static unsigned int node_form_ancestor(unsigned int node)
+{
+	while (node && node < D->nnode) {
+		if (D->nodes[node].type == BR_NODE_ELEM &&
+		    D->nodes[node].tag == BR_TAG_FORM)
+			return node;
+		node = D->nodes[node].parent;
+	}
+	return 0;
+}
+
+static void push_form_elements(js_State *state, unsigned int form)
+{
+	unsigned int out[128];
+	int n = 0, i;
+
+	if (host.form_elements)
+		n = host.form_elements(form, out, (int)(sizeof(out) /
+						       sizeof(out[0])));
+	js_newarray(state);
+	for (i = 0; i < n; i++) {
+		const char *name;
+
+		push_node(state, out[i] + 1);
+		js_setindex(state, -2, i);
+		name = br_find_attr(D, out[i], "name");
+		if (name && name[0]) {
+			push_node(state, out[i] + 1);
+			js_setproperty(state, -2, name);
+		}
+	}
+}
+
+static void form_submit_js(js_State *state)
+{
+	unsigned int node = node_of(js_currentfunctiondata(state));
+
+	if (host.form_submit)
+		host.form_submit(node);
+}
+
+static void form_reset_js(js_State *state)
+{
+	unsigned int node = node_of(js_currentfunctiondata(state));
+
+	if (host.form_reset)
+		host.form_reset(node);
+}
+
 /* Userdata property hooks: every element wrapper carries node + 1. */
 static int node_has(js_State *state, void *p, const char *name)
 {
@@ -1046,6 +1652,45 @@ static int node_has(js_State *state, void *p, const char *name)
 		return 0;
 	n = &D->nodes[node];
 
+	if (n->type == BR_NODE_ELEM && n->tag == BR_TAG_FORM) {
+		if (!strcmp(name, "elements")) {
+			push_form_elements(state, node);
+			return 1;
+		}
+		if (!strcmp(name, "length")) {
+			unsigned int out[128];
+			int count = 0;
+
+			if (host.form_elements)
+				count = host.form_elements(node, out,
+					(int)(sizeof(out) / sizeof(out[0])));
+			js_pushnumber(state, count);
+			return 1;
+		}
+		if (!strcmp(name, "submit")) {
+			push_func_data(state, "submit", form_submit_js, 0,
+				       node + 1);
+			return 1;
+		}
+		if (!strcmp(name, "reset")) {
+			push_func_data(state, "reset", form_reset_js, 0,
+				       node + 1);
+			return 1;
+		}
+	}
+	if (!strcmp(name, "form")) {
+		unsigned int f;
+
+		if (n->type == BR_NODE_ELEM && n->tag == BR_TAG_FORM)
+			f = 0;
+		else
+			f = node_form_ancestor(node);
+		if (f)
+			push_node(state, f + 1);
+		else
+			js_pushnull(state);
+		return 1;
+	}
 	if (!strcmp(name, "textContent") || !strcmp(name, "innerText")) {
 		node_push_text(state, node);
 		return 1;
@@ -1252,11 +1897,11 @@ static int node_has(js_State *state, void *p, const char *name)
 	if (!strcmp(name, "querySelectorAll"))
 		{ push_func_data(state, "querySelectorAll", node_queryselectorall, 1, node + 1); return 1; }
 	if (!strcmp(name, "addEventListener"))
-		{ push_func_data(state, "addEventListener", node_noop, 2, node + 1); return 1; }
+		{ push_func_data(state, "addEventListener", node_addlistener, 2, node + 1); return 1; }
 	if (!strcmp(name, "removeEventListener"))
-		{ push_func_data(state, "removeEventListener", node_noop, 2, node + 1); return 1; }
+		{ push_func_data(state, "removeEventListener", node_removelistener, 2, node + 1); return 1; }
 	if (!strcmp(name, "dispatchEvent"))
-		{ push_func_data(state, "dispatchEvent", node_noop, 1, node + 1); return 1; }
+		{ push_func_data(state, "dispatchEvent", node_dispatchevent, 1, node + 1); return 1; }
 	if (!strcmp(name, "getBoundingClientRect"))
 		{ push_func_data(state, "getBoundingClientRect", node_getrect, 0, node + 1); return 1; }
 	if (!strcmp(name, "getClientRects")) {
@@ -1279,8 +1924,11 @@ static int node_has(js_State *state, void *p, const char *name)
 		js_pushnumber(state, 0);
 		return 1;
 	}
-	if (!strcmp(name, "click") || !strcmp(name, "focus") ||
-	    !strcmp(name, "blur")) {
+	if (!strcmp(name, "click")) {
+		push_func_data(state, "click", node_click, 0, node + 1);
+		return 1;
+	}
+	if (!strcmp(name, "focus") || !strcmp(name, "blur")) {
 		push_func_data(state, name, node_noop, 0, node + 1);
 		return 1;
 	}
@@ -1537,11 +2185,6 @@ static void doc_queryselectorall(js_State *state)
 	push_query_array(state, 0, js_tostring(state, 1));
 }
 
-static void doc_noop(js_State *state)
-{
-	(void)state;
-}
-
 static void location_get(js_State *state)
 {
 	js_pushstring(state, current_url ? current_url : "");
@@ -1956,8 +2599,9 @@ static void install_globals(js_State *state)
 	def_func(state, "getElementsByClassName", doc_getelementsbyclassname, 1);
 	def_func(state, "querySelector", doc_queryselector, 1);
 	def_func(state, "querySelectorAll", doc_queryselectorall, 1);
-	def_func(state, "addEventListener", doc_noop, 2);
-	def_func(state, "removeEventListener", doc_noop, 2);
+	def_func(state, "addEventListener", doc_addlistener, 2);
+	def_func(state, "removeEventListener", doc_removelistener, 2);
+	def_func(state, "createEvent", doc_createevent, 1);
 
 	h = br_find_tag(D, BR_TAG_HTML);
 	if (!h && D->nnode > 1)
@@ -1996,6 +2640,9 @@ static void install_globals(js_State *state)
 	js_newcfunction(state, js_alert, "alert", 1);
 	js_defglobal(state, "alert", JS_DONTENUM);
 
+	js_newcfunction(state, event_call, "Event", 1);
+	js_defglobal(state, "Event", JS_DONTENUM);
+
 	push_location(state);
 	js_defglobal(state, "location", JS_DONTENUM);
 
@@ -2020,8 +2667,8 @@ static void install_globals(js_State *state)
 
 	def_global_func(state, "matchMedia", win_matchmedia, 1);
 	def_global_func(state, "getComputedStyle", win_getcomputedstyle, 1);
-	def_global_func(state, "addEventListener", win_noop, 2);
-	def_global_func(state, "removeEventListener", win_noop, 2);
+	def_global_func(state, "addEventListener", win_addlistener, 2);
+	def_global_func(state, "removeEventListener", win_removelistener, 2);
 	def_global_func(state, "scrollTo", win_noop, 2);
 	def_global_func(state, "scrollBy", win_noop, 2);
 	def_global_func(state, "setTimeout", win_settimeout, 1);
@@ -2076,6 +2723,9 @@ int js_browser_start(struct br_doc *doc, const struct js_browser_host *h)
 	current_url = h->page_url;
 	panic_armed = 0;
 	memset(timers, 0, sizeof(timers));
+	memset(listeners, 0, sizeof(listeners));
+	memset(events, 0, sizeof(events));
+	memset(event_templates, 0, sizeof(event_templates));
 
 	/* Classic scripts are sloppy by default in browsers; strict mode is
 	 * opt-in via a "use strict" directive. */

+ 10 - 0
js_browser.h

@@ -24,6 +24,11 @@ struct js_browser_host {
 	int (*form_set_value)(unsigned int node, const char *value);
 	int (*form_set_checked)(unsigned int node, int checked);
 	int (*form_set_selected)(unsigned int node, int index);
+	/* Collect a form's listed controls (input/select/textarea/button). */
+	int (*form_elements)(unsigned int form, unsigned int *out, int cap);
+	int (*form_submit)(unsigned int form);  /* JS submit(), no event */
+	int (*form_reset)(unsigned int form);   /* JS reset(), fires reset */
+	int (*click)(unsigned int node);        /* element.click() */
 	const char *page_url;   /* location.href for every script on the page */
 	unsigned int width;     /* viewport size for window.inner* */
 	unsigned int height;
@@ -39,6 +44,11 @@ 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);
 
+/* Dispatch a DOM event at a node.  Returns 0 when a handler called
+ * preventDefault().  Bubbles to ancestors, document and window. */
+int js_browser_event(unsigned int node, const char *type, int bubbles,
+		     int cancelable);
+
 int js_browser_active(void);
 
 #endif

+ 95 - 0
testdata/browser/compat/036-form-events.html

@@ -0,0 +1,95 @@
+<!doctype html>
+<html>
+<head>
+<meta charset="utf-8">
+<title>036 form events</title>
+<style>
+html, body { margin: 0; padding: 0; background: #ffffff; color: #202020; }
+body { font-family: sans-serif; font-size: 13px; padding: 10px; }
+h1 { font-size: 20px; margin: 0 0 6px 0; }
+p { margin: 0 0 10px 0; }
+.row { margin: 6px 0; }
+label { margin-right: 8px; }
+input, select, textarea, button { font-family: sans-serif; font-size: 13px; }
+#result { margin-top: 10px; padding: 8px; background: #eeeeee; color: #000000; font-family: monospace; font-weight: bold; }
+</style>
+</head>
+<body>
+<h1>036 &middot; form events and elements</h1>
+<p>Listeners must bubble to document, <code>form.elements</code> must list the controls, and a cancelled click/submit must block the default action.</p>
+<form id="f" action="/nowhere.html">
+  <div class="row">
+    <label for="alpha">Alpha</label><input id="alpha" name="alpha" value="one">
+    <label><input id="beta" name="beta" type="checkbox"> Beta</label>
+  </div>
+  <div class="row">
+    <button id="go" type="submit" name="send" value="yes">Go</button>
+  </div>
+</form>
+<div id="result">checking...</div>
+<script>
+setTimeout(function () {
+  var f = document.getElementById('f');
+  var a = document.getElementById('alpha');
+  var b = document.getElementById('beta');
+  var go = document.getElementById('go');
+  var out = document.getElementById('result');
+  var inputs = 0, clicks = 0, docClicks = 0, submits = 0, changes = 0;
+  var details = [];
+
+  a.addEventListener('click', function (e) { clicks++; e.preventDefault(); });
+  a.addEventListener('input', function (e) {
+    inputs += (e.target === a) ? 1 : 0;
+  });
+  a.addEventListener('change', function () { changes++; });
+  f.addEventListener('submit', function (e) { submits++; e.preventDefault(); });
+  document.addEventListener('click', function (e) {
+    if (e.target === a) docClicks++;
+  });
+
+  a.dispatchEvent(new Event('input', { bubbles: true }));
+  a.value = 'two';
+  a.click();
+  go.click();
+
+  var ok = true;
+  var elems = f.elements;
+  if (elems.length !== 3) { ok = false; details.push('length=' + elems.length); }
+  if (elems.alpha !== a) { ok = false; details.push('named element mismatch'); }
+  if (elems[0] !== a) { ok = false; details.push('indexed element mismatch'); }
+  if (inputs !== 1) { ok = false; details.push('input=' + inputs); }
+  if (clicks !== 1) { ok = false; details.push('click=' + clicks); }
+  if (docClicks !== 1) { ok = false; details.push('document click=' + docClicks); }
+  if (submits !== 1) { ok = false; details.push('submit=' + submits); }
+  if (a.value !== 'two') { ok = false; details.push('value=' + a.value); }
+
+  b.checked = true;
+  f.reset();
+  if (a.value !== 'one' || b.checked !== false) {
+    ok = false;
+    details.push('reset value=' + a.value + ' checked=' + b.checked);
+  }
+
+  var removed = 0;
+  function once() { removed++; }
+  a.addEventListener('change', once);
+  a.removeEventListener('change', once);
+  a.dispatchEvent(new Event('change', { bubbles: true }));
+  if (removed !== 0) { ok = false; details.push('removed listener ran=' + removed); }
+  if (changes !== 1) { ok = false; details.push('change=' + changes); }
+
+  var ceTarget = false;
+  a.addEventListener('change', function (e) { ceTarget = (e.target === a); });
+  var ce = document.createEvent('Event');
+  ce.initEvent('change', true, false);
+  a.dispatchEvent(ce);
+  if (!ceTarget) { ok = false; details.push('createEvent target'); }
+  if (changes !== 2) { ok = false; details.push('createEvent change=' + changes); }
+
+  out.textContent = ok ? 'PASS: form events and elements' :
+    ('FAIL: ' + details.join(', '));
+  out.style.background = ok ? '#ccffcc' : '#ffcccc';
+}, 600);
+</script>
+</body>
+</html>

+ 33 - 0
testdata/browser/compat/036a-post.html

@@ -0,0 +1,33 @@
+<!doctype html>
+<html>
+<head>
+<meta charset="utf-8">
+<title>036a post</title>
+<style>
+html, body { margin: 0; padding: 0; background: #ffffff; color: #202020; }
+body { font-family: sans-serif; font-size: 13px; padding: 10px; }
+h1 { font-size: 20px; margin: 0 0 6px 0; }
+p { margin: 0 0 10px 0; }
+label { margin-right: 8px; }
+input, button { font-family: sans-serif; font-size: 13px; }
+</style>
+</head>
+<body>
+<h1>036a &middot; POST form submission</h1>
+<p>This local page cannot POST; it redirects the form to the test server.</p>
+<form id="f" method="post" action="http://10.0.2.2:8765/echo">
+  <label>Alpha <input id="alpha" name="alpha" value="one"></label>
+  <label><input id="beta" name="beta" type="checkbox"> Beta</label>
+  <button id="go" type="submit" name="send" value="yes">Send</button>
+</form>
+<p>The script sets the fields and submits via <code>form.submit()</code>.</p>
+<script>
+setTimeout(function () {
+  var f = document.getElementById('f');
+  document.getElementById('alpha').value = 'two';
+  document.getElementById('beta').checked = true;
+  f.submit();
+}, 700);
+</script>
+</body>
+</html>

+ 12 - 4
testdata/browser/compat/README

@@ -17,13 +17,21 @@ Serve this directory from the host and open it on the board:
   browser http://<host>:8000/            # board
   browser http://10.0.2.2:8000/         # QEMU with -netdev user
 
-Status: 010-035 and 030a pass.  Still missing from the ladder: POST forms
-and JS form events, @font-face, background repeat/position/size, the rest
-of transform, sticky bottom/container clamping, and calc() beyond widths.
+Status: 010-036 and 030a pass.  036a needs the POST echo server:
+
+  python3 testdata/browser/compat/post_server.py
+  browser /floppy1/036a.htm      # action is http://10.0.2.2:8765/echo
+
+Still missing from the ladder: @font-face, background repeat/position/size,
+the rest of transform, sticky bottom/container clamping, and calc() beyond
+widths.
 
 Rules for new pages:
   - one behaviour per page;
-  - no JavaScript and no network assets outside this directory;
+  - no network assets outside this directory (036a is the one explicit
+    POST test and documents its server);
+  - pages up to 034 are static; 035/036 use JavaScript and assert their own
+    PASS/FAIL line;
   - explicit white background and dark text;
   - page chrome uses only primitives introduced earlier in the ladder;
   - keep the two panes at fixed offsets: floats with explicit px widths.

+ 3 - 1
testdata/browser/compat/index.html

@@ -40,7 +40,7 @@ a { color: #0645ad; }
 <tr><td>017</td><td><a href="017-z-index.html">z-index</a></td><td>stacking of positioned boxes</td><td class="pass">PASS</td></tr>
 <tr><td>018</td><td><a href="018-relative.html">relative</a></td><td>position: relative offsets</td><td class="pass">PASS</td></tr>
 <tr><td>019</td><td><a href="019-right-bottom.html">right/bottom</a></td><td>absolute right and bottom</td><td class="pass">PASS</td></tr>
-<tr><td>020</td><td><a href="020-table-span.html">table colspan</a></td><td>colspan (rowspan still open)</td><td class="pass">PASS</td></tr>
+<tr><td>020</td><td><a href="020-table-span.html">table colspan</a></td><td>colspan (see 030 for rowspan)</td><td class="pass">PASS</td></tr>
 <tr><td>021</td><td><a href="021-table-percent.html">table percent</a></td><td>table width and percentage columns</td><td class="pass">PASS</td></tr>
 <tr><td>022</td><td><a href="022-flex-align.html">flex align</a></td><td>justify-content and align-items</td><td class="pass">PASS</td></tr>
 <tr><td>023</td><td><a href="023-calc.html">calc</a></td><td>calc(percent +/- px)</td><td class="pass">PASS</td></tr>
@@ -57,6 +57,8 @@ a { color: #0645ad; }
 <tr><td>033</td><td><a href="033-forms.html">form controls</a></td><td>text, password, checkbox, radio, select, textarea, buttons</td><td class="pass">PASS</td></tr>
 <tr><td>034</td><td><a href="034-form-submit.html">form submit</a></td><td>GET submission and reset</td><td class="pass">PASS</td></tr>
 <tr><td>035</td><td><a href="035-form-js.html">form JS state</a></td><td>live value / checked / selectedIndex</td><td class="pass">PASS</td></tr>
+<tr><td>036</td><td><a href="036-form-events.html">form events</a></td><td>addEventListener, bubbling, preventDefault, form.elements</td><td class="pass">PASS</td></tr>
+<tr><td>036a</td><td><a href="036a-post.html">POST form</a></td><td>POST submission to <code>/echo</code> (needs <code>post_server.py</code>)</td><td class="pass">PASS</td></tr>
 </table>
 </body>
 </html>

+ 53 - 0
testdata/browser/compat/post_server.py

@@ -0,0 +1,53 @@
+#!/usr/bin/env python3
+"""POST echo endpoint for the compatibility ladder's 036a page.
+
+Run this on the host, then start QEMU with a user-mode NIC:
+
+    python3 testdata/browser/compat/post_server.py
+    qemu-system-i386 ... -netdev user,id=n0 -device ne2k_pci,netdev=n0
+
+036a posts `alpha=two&beta=on` to http://10.0.2.2:8765/echo and expects the
+response page to say PASS.  The guest uses QEMU's slirp host address, so the
+same script works for `make run-net` (use the host's LAN address instead).
+"""
+
+from http.server import BaseHTTPRequestHandler, HTTPServer
+
+PORT = 8765
+
+
+class Handler(BaseHTTPRequestHandler):
+    def do_POST(self):
+        length = int(self.headers.get('Content-Length', '0') or 0)
+        data = self.rfile.read(length).decode('latin-1')
+        ok = (self.path == '/echo' and data == 'alpha=two&beta=on')
+        verdict = 'PASS: server received POST' if ok else 'FAIL: body=' + data
+        body = (
+            '<!doctype html><html><head><meta charset="utf-8">'
+            '<title>post result</title>'
+            '<style>body{font-family:sans-serif;padding:10px}'
+            'pre{background:#eeeeee;padding:6px}</style></head><body>'
+            '<h1>POST result</h1><p id="verdict">' + verdict + '</p>'
+            '<pre>' + data.replace('&', '&amp;').replace('<', '&lt;') +
+            '</pre></body></html>'
+        ).encode('latin-1')
+        self.send_response(200)
+        self.send_header('Content-Type', 'text/html')
+        self.send_header('Content-Length', str(len(body)))
+        self.end_headers()
+        self.wfile.write(body)
+
+    def do_GET(self):
+        body = b'POST test endpoint'
+        self.send_response(200)
+        self.send_header('Content-Type', 'text/plain')
+        self.send_header('Content-Length', str(len(body)))
+        self.end_headers()
+        self.wfile.write(body)
+
+    def log_message(self, fmt, *args):
+        pass
+
+
+if __name__ == '__main__':
+    HTTPServer(('0.0.0.0', PORT), Handler).serve_forever()

+ 48 - 6
ucmd_curl.c

@@ -9,6 +9,7 @@
  * only keeps the CLI, the helper mode and the verbose output hooks. */
 
 #include <stdlib.h>
+#include <string.h>
 
 #include "ucmd_lib.h"
 #include "uhttp.h"
@@ -63,6 +64,8 @@ static const struct uhttp_hooks hooks = {
 #define FETCH_BODY  "/share/bfbody"
 #define FETCH_META  "/share/bfmeta"
 #define FETCH_DONE  "/share/bfdone"
+#define FETCH_POST  "/share/bfpost"
+#define FETCH_POST_MAX 4096u
 #define FETCH_MAX   (2u * 1024u * 1024u)
 
 static unsigned int c_len(const char *s)
@@ -138,6 +141,7 @@ static void write_meta(unsigned int seq, int with_seq, struct uhttp *h,
 
 /* Fetch one URL through a possibly reused keep-alive connection. */
 static void helper_fetch(struct uhttp *h, const char *url, unsigned int cap,
+			 const char *post, unsigned int post_len,
 			 unsigned char *buf, unsigned int *outlen,
 			 unsigned int *outtrunc, int *outerr)
 {
@@ -147,6 +151,8 @@ static void helper_fetch(struct uhttp *h, const char *url, unsigned int cap,
 	*outlen = 0;
 	*outtrunc = 0;
 	*outerr = 0;
+	uhttp_set_method(h, post_len ? "POST" : 0, post, post_len,
+			 "application/x-www-form-urlencoded");
 	rv = uhttp_open(h, url, UHTTP_GZIP, 0);
 	if (rv == UHTTP_ERR_BUSY) {
 		int tries;
@@ -219,7 +225,7 @@ static void fetch_once(void)
 
 	uhttp_init(&h);
 	h.user_agent = "Mozilla/5.0 (X11; Linux i686) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0 Safari/537.36";
-	helper_fetch(&h, req + i, cap, buf, &body_len, &body_trunc, &err);
+	helper_fetch(&h, req + i, cap, 0, 0, buf, &body_len, &body_trunc, &err);
 	if (body_len)
 		u_syscall3(SYS_WRITE_FILE, (int)FETCH_BODY, (int)buf,
 			   (int)body_len);
@@ -237,11 +243,12 @@ static void fetch_serve(void)
 {
 	static struct uhttp h;
 	char req[768];
-	unsigned char *buf;
+	unsigned char *buf, *post;
 	unsigned int last_seq = 0, idle = 0;
 
 	buf = (unsigned char *)malloc(FETCH_MAX);
-	if (!buf)
+	post = (unsigned char *)malloc(FETCH_POST_MAX);
+	if (!buf || !post)
 		u_exit(1);
 	uhttp_init(&h);
 	h.user_agent = "Mozilla/5.0 (X11; Linux i686) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0 Safari/537.36";
@@ -249,6 +256,8 @@ static void fetch_serve(void)
 
 	for (;;) {
 		unsigned int seq = 0, cap = 0, body_len = 0, body_trunc = 0;
+		unsigned int post_len = 0;
+		int is_post = 0;
 		char done[16];
 		unsigned int dn = 0;
 		unsigned int i = 0;
@@ -273,6 +282,17 @@ static void fetch_serve(void)
 			}
 			while (req[i] == ' ')
 				i++;
+			if (!strncmp(req + i, "POST ", 5)) {
+				is_post = 1;
+				i += 5;
+				while (req[i] >= '0' && req[i] <= '9') {
+					post_len = post_len * 10 +
+						(unsigned int)(req[i] - '0');
+					i++;
+				}
+				while (req[i] == ' ')
+					i++;
+			}
 			while (rn > 0 && (req[rn - 1] == '\n' ||
 					  req[rn - 1] == '\r'))
 				req[--rn] = '\0';
@@ -289,8 +309,23 @@ static void fetch_serve(void)
 		last_seq = seq;
 		if (cap == 0 || cap > FETCH_MAX)
 			cap = FETCH_MAX;
+		if (is_post) {
+			int pn;
+
+			if (post_len > FETCH_POST_MAX)
+				post_len = FETCH_POST_MAX;
+			pn = u_syscall3(SYS_READ_FILE, (int)FETCH_POST,
+					(int)post, (int)FETCH_POST_MAX);
+			if (pn < 0)
+				pn = 0;
+			if ((unsigned int)pn < post_len)
+				post_len = (unsigned int)pn;
+		} else {
+			post_len = 0;
+		}
 
-		helper_fetch(&h, url, cap, buf, &body_len, &body_trunc, &err);
+		helper_fetch(&h, url, cap, is_post ? (char *)post : 0, post_len,
+			     buf, &body_len, &body_trunc, &err);
 		if (body_len)
 			u_syscall3(SYS_WRITE_FILE, (int)FETCH_BODY, (int)buf,
 				   (int)body_len);
@@ -298,15 +333,22 @@ static void fetch_serve(void)
 		app_dec(done, &dn, seq, sizeof(done));
 		u_syscall3(SYS_WRITE_FILE, (int)FETCH_DONE, (int)done, (int)dn);
 
-		if (err || body_trunc || h.peer_close) {
+		if (err || body_trunc || h.peer_close || is_post) {
 			h.keepalive = 0;
 			uhttp_close(&h);
-			h.keepalive = 1;
+			if (is_post) {
+				uhttp_init(&h);
+				h.user_agent = "Mozilla/5.0 (X11; Linux i686) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0 Safari/537.36";
+				h.keepalive = 1;
+			} else {
+				h.keepalive = 1;
+			}
 		}
 	}
 	h.keepalive = 0;
 	uhttp_close(&h);
 	free(buf);
+	free(post);
 	u_exit(0);
 }
 

+ 32 - 1
uhttp.c

@@ -589,7 +589,8 @@ static int send_request(struct uhttp *h, unsigned int flags)
 	unsigned int n = 0;
 	int rv;
 
-	n = req_app(req, 0, sizeof(req), "GET ");
+	n = req_app(req, 0, sizeof(req), h->method ? h->method : "GET");
+	n = req_app(req, n, sizeof(req), " ");
 	n = req_app(req, n, sizeof(req), h->url.path);
 	n = req_app(req, n, sizeof(req), " HTTP/1.1\r\nHost: ");
 	n = req_app(req, n, sizeof(req), h->url.host);
@@ -602,6 +603,14 @@ static int send_request(struct uhttp *h, unsigned int flags)
 	n = req_app(req, n, sizeof(req), "\r\nAccept: */*\r\n");
 	if (flags & UHTTP_GZIP)
 		n = req_app(req, n, sizeof(req), "Accept-Encoding: gzip\r\n");
+	if (h->body_len) {
+		n = req_app(req, n, sizeof(req), "Content-Type: ");
+		n = req_app(req, n, sizeof(req), h->content_type ?
+			    h->content_type : "application/octet-stream");
+		n = req_app(req, n, sizeof(req), "\r\nContent-Length: ");
+		n = req_app_dec(req, n, sizeof(req), h->body_len);
+		n = req_app(req, n, sizeof(req), "\r\n");
+	}
 	n = req_app(req, n, sizeof(req),
 		      (h->keepalive && !h->peer_close) ?
 		      "Connection: keep-alive\r\n\r\n" :
@@ -612,6 +621,11 @@ static int send_request(struct uhttp *h, unsigned int flags)
 	rv = xport_send(h, req, n);
 	if (rv != 0)
 		return UHTTP_ERR_SEND;
+	if (h->body_len) {
+		rv = xport_send(h, h->body, h->body_len);
+		if (rv != 0)
+			return UHTTP_ERR_SEND;
+	}
 	return 0;
 }
 
@@ -624,6 +638,15 @@ void uhttp_init(struct uhttp *h)
 	h->user_agent = "Mozilla/5.0 (X11; Linux i686) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0 Safari/537.36";
 }
 
+void uhttp_set_method(struct uhttp *h, const char *method, const char *body,
+		      unsigned int body_len, const char *content_type)
+{
+	h->method = method;
+	h->body = body;
+	h->body_len = body_len;
+	h->content_type = content_type;
+}
+
 static int host_same(const char *a, const char *b)
 {
 	while (*a && *b && *a == *b) {
@@ -724,6 +747,14 @@ int uhttp_open(struct uhttp *h, const char *url, unsigned int flags,
 				rv = UHTTP_ERR_REDIRECT;
 				goto fail;
 			}
+			/* A redirected POST becomes a GET unless the
+			 * server explicitly asks to repeat the request. */
+			if (h->resp.status != 307 && h->resp.status != 308) {
+				h->method = 0;
+				h->body = 0;
+				h->body_len = 0;
+				h->content_type = 0;
+			}
 			url_build(&h->url, h->resp.final_url,
 				  sizeof(h->resp.final_url));
 			hops++;

+ 8 - 0
uhttp.h

@@ -75,6 +75,10 @@ struct uhttp {
 	struct uhttp_response resp;
 	const struct uhttp_hooks *hooks;
 	const char *user_agent;
+	const char *method;        /* NULL means GET */
+	const char *body;          /* request body for POST */
+	unsigned int body_len;
+	const char *content_type;
 
 	unsigned char buf[UHTTP_READER_MAX];
 	unsigned int len, pos;
@@ -93,6 +97,10 @@ struct uhttp {
 };
 
 void uhttp_init(struct uhttp *h);
+/* Select the request method and body.  Call after uhttp_init() and before
+ * uhttp_open(); NULL method restores GET. */
+void uhttp_set_method(struct uhttp *h, const char *method, const char *body,
+		      unsigned int body_len, const char *content_type);
 int  uhttp_parse_url(const char *s, struct uhttp_url *u);
 int  uhttp_open(struct uhttp *h, const char *url, unsigned int flags,
 		const struct uhttp_hooks *hooks);

Certains fichiers n'ont pas été affichés car il y a eu trop de fichiers modifiés dans ce diff