/* Browser bindings for the page JavaScript engine (QuickJS, driven through * the MuJS-style stack API in js_mu.c): the DOM layer (interned node wrappers, * attributes, query selectors, classList/dataset/style, innerHTML, timers) * plus document/window/location/navigator globals. */ #include #include #include #include #include #include "ucmd_lib.h" #include "browser_html.h" #include "js_browser.h" #include "js_mu.h" /* Wall-clock budget per script/handler/timer entry, in milliseconds. It is * reset before every entry; a runaway loop becomes a catchable * "interrupted" exception instead of a frozen browser. A framework * bootstrap (AngularJS rendering ~300 cards) needs several seconds on a * slow CPU, so the budget is generous. */ #define JS_RUN_LIMIT 20000 /* Component frameworks schedule a zero-delay timer per element (heise's * base component awaits setTimeout(0) in every connectedCallback): a full * table silently drops timers and those components never start. */ #define JS_TIMERS 1024 #define JS_TIMERS_PER_TICK 32 struct js_timer { int used; int repeat; unsigned int deadline; unsigned int interval; char ref[32]; }; static struct js_timer timers[JS_TIMERS]; static js_State *J; static struct br_doc *D; static struct js_browser_host host; 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; if (host.report) host.report(message); } static void panic_cb(js_State *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"); } static unsigned int node_of(void *p) { return (unsigned int)(uintptr_t)p - 1; } static int node_has(js_State *state, void *p, const char *name); static int node_put(js_State *state, void *p, const char *name); static int node_delete(js_State *state, void *p, const char *name); static void push_element_url(js_State *state, unsigned int node, const char *name); static void rellist_supports(js_State *state); static void push_query_array(js_State *state, unsigned int root, const char *selector); static void node_push_text(js_State *state, unsigned int node); static void url_resolve(const char *base, const char *rel, char *out, unsigned int cap); static int hash_pending; /* Set by every DOM mutation (host.changed is wrapped): the tick then lets * the prelude upgrade/connect new Custom Elements. */ static int dom_dirty; static void (*host_changed_orig)(void); static void dom_changed(void) { dom_dirty = 1; if (host_changed_orig) host_changed_orig(); } static int node_parent_idx(unsigned int node); /* One wrapper per DOM node: the same element must have the same object * identity on every access, or library caches (jQuery expando data, Sizzle) * silently split into disconnected copies. */ static void push_node(js_State *state, unsigned int handle) { char key[24]; if (!handle) { js_pushnull(state); return; } snprintf(key, sizeof(key), "jsonnode_%u", handle); js_getregistry(state, key); if (!js_isundefined(state, -1)) return; js_pop(state, 1); /* js_newuserdatax() pops a prototype from the top. Wrappers inherit * from Object.prototype like real DOM nodes (toString/hasOwnProperty; * Angular calls node.toString() to sniff SVG). */ js_getregistry(state, "nodeproto"); js_newuserdatax(state, "node", (void *)(uintptr_t)handle, node_has, node_put, node_delete, 0); js_copy(state, -1); js_setregistry(state, key); } static unsigned int arg_node(js_State *state, int idx) { if (!js_isuserdata(state, idx, "node")) js_typeerror(state, "not a DOM node"); return (unsigned int)(uintptr_t)js_touserdata(state, idx, "node"); } static void def_func_data(js_State *state, const char *name, js_CFunction fn, int length, unsigned int handle) { js_newcfunctionx(state, fn, name, length, (void *)(uintptr_t)handle, 0); js_setproperty(state, -2, name); } static void def_func(js_State *state, const char *name, js_CFunction fn, int length) { js_newcfunction(state, fn, name, length); js_setproperty(state, -2, name); } static void def_global_func(js_State *state, const char *name, js_CFunction fn, int length) { js_newcfunction(state, fn, name, length); js_defglobal(state, name, JS_DONTENUM); } static void push_func_data(js_State *state, const char *name, js_CFunction fn, int length, unsigned int handle) { js_newcfunctionx(state, fn, name, length, (void *)(uintptr_t)handle, 0); } static const char *node_attr(unsigned int node, const char *name) { return br_find_attr(D, node, name); } static void push_attr(js_State *state, unsigned int node, const char *name, int null_if_missing) { const char *s = node_attr(node, name); if (s) js_pushstring(state, s); else if (null_if_missing) js_pushnull(state); else js_pushstring(state, ""); } static unsigned int node_name(unsigned int node, char *buf, unsigned int cap) { struct br_node *n; const char *s; unsigned int i = 0; if (!D || node >= D->nnode || cap == 0) return 0; n = &D->nodes[node]; if (n->type == BR_NODE_TEXT) s = "#text"; else if (n->type == BR_NODE_COMMENT) s = "#comment"; else if (n->type == BR_NODE_FRAGMENT) s = "#document-fragment"; else if (n->tag == BR_TAG_UNKNOWN && n->name_off) s = D->attrs + n->name_off; else s = br_tag_name(n->tag); while (s && *s && i + 1 < cap) { char c = *s++; if (c >= 'a' && c <= 'z') c = (char)(c - 'a' + 'A'); buf[i++] = c; } buf[i] = '\0'; return i; } /* ---- DOM events ------------------------------------------------------- * * * Listeners live in a fixed table, one entry per (target, type, callback) * registration, and callbacks are retained through the engine 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 256 #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` (the stack API 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 void inline_attr_decode(const char *s, char *d, unsigned int cap) { unsigned int i = 0, n = 0; while (s && s[i] && n + 1 < cap) { if (s[i] == '&') { if (!strncmp(s + i, """, 6)) { d[n++] = '"'; i += 6; continue; } if (!strncmp(s + i, "'", 5)) { d[n++] = '\''; i += 5; continue; } if (!strncmp(s + i, "&", 5)) { d[n++] = '&'; i += 5; continue; } if (!strncmp(s + i, "<", 4)) { d[n++] = '<'; i += 4; continue; } if (!strncmp(s + i, ">", 4)) { d[n++] = '>'; i += 4; continue; } } d[n++] = s[i++]; } d[n] = '\0'; } /* Inline on attributes run at the target and while bubbling, after * the registered listeners for that node. The handler gets the event and * the element as `this`; a false return prevents the default action. */ static void run_inline_handler(js_State *state, unsigned int node, const char *type, int slot, int *prevented) { char name[40], body[512], src[640]; const char *attr; int truthy; if (!D || node >= D->nnode || !events[slot].objref[0]) return; snprintf(name, sizeof(name), "on%s", type); attr = br_find_attr(D, node, name); if (!attr || !attr[0]) return; inline_attr_decode(attr, body, sizeof(body)); snprintf(src, sizeof(src), "(function(event){ %s\n})", body); if (js_try(state)) { /* The throw already unwound this try frame. */ js_pop(state, 1); return; } js_loadstring(state, "[inline]", src); /* The script evaluates the function expression; run it first, then * call the resulting function with the element as `this`. */ js_pushundefined(state); if (js_pcall(state, 0) || !js_iscallable(state, -1)) { js_pop(state, 1); js_endtry(state); return; } push_node(state, node + 1); js_getregistry(state, events[slot].objref); if (js_pcall(state, 1)) { js_pop(state, 1); js_endtry(state); return; } truthy = js_toboolean(state, -1); js_pop(state, 1); js_endtry(state); if (!truthy && prevented) *prevented = 1; } 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; 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) { unsigned int cur = target; int p; while ((p = node_parent_idx(cur)) >= 0 && np < (int)(sizeof(path) / sizeof(path[0]))) { path[np++] = (unsigned int)p; cur = (unsigned int)p; } } if (target != JS_TARGET_WINDOW) path[np++] = JS_TARGET_DOCUMENT; if (target != JS_TARGET_WINDOW && 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); if (!events[slot].stopped) run_inline_handler(state, path[0], type, slot, &events[slot].prevented); } /* 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); if (!events[slot].stopped && path[i] != JS_TARGET_WINDOW && path[i] != JS_TARGET_DOCUMENT) run_inline_handler(state, path[i], type, slot, &events[slot].prevented); } } 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); } /* document.dispatchEvent / window.dispatchEvent (WebComponentsReady, custom * app events): the same dispatcher, targeting document or window. */ static void target_dispatchevent(js_State *state, unsigned int target) { if (!D || !js_isobject(state, 1)) { js_pushboolean(state, 1); return; } dispatch_object(state, target, 1, "event", 1, 0); } static void doc_dispatchevent(js_State *state) { target_dispatchevent(state, JS_TARGET_DOCUMENT); } static void win_dispatchevent(js_State *state) { target_dispatchevent(state, JS_TARGET_WINDOW); } static void node_dispatchevent(js_State *state) { 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); } static void custom_event_call(js_State *state) { event_call(state); if (js_isobject(state, 2)) js_getproperty(state, 2, "detail"); else js_pushnull(state); js_setproperty(state, -2, "detail"); } static void mouse_event_call(js_State *state) { static const struct { const char *name; int is_number; } props[] = { { "clientX", 1 }, { "clientY", 1 }, { "screenX", 1 }, { "screenY", 1 }, { "button", 1 }, { "buttons", 1 }, { "ctrlKey", 0 }, { "shiftKey", 0 }, { "altKey", 0 }, { "metaKey", 0 } }; unsigned int i; event_call(state); if (!js_isobject(state, 2)) return; for (i = 0; i < sizeof(props) / sizeof(props[0]); i++) { js_getproperty(state, 2, props[i].name); if (props[i].is_number) { double v = js_isnumber(state, -1) ? js_tonumber(state, -1) : 0; js_pop(state, 1); js_pushnumber(state, v); } else { int v = js_toboolean(state, -1); js_pop(state, 1); js_pushboolean(state, v); } js_setproperty(state, -2, props[i].name); } } 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); js_runjobs(J); return rv; } int js_browser_mouse_event(unsigned int node, const char *type, int bubbles, int related, int x, int y) { 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); js_newobject(J); js_pushnumber(J, x); js_setproperty(J, -2, "clientX"); js_pushnumber(J, y); js_setproperty(J, -2, "clientY"); js_pushnumber(J, x); js_setproperty(J, -2, "pageX"); js_pushnumber(J, y); js_setproperty(J, -2, "pageY"); js_pushnumber(J, x); js_setproperty(J, -2, "screenX"); js_pushnumber(J, y); js_setproperty(J, -2, "screenY"); js_pushnumber(J, 0); js_setproperty(J, -2, "button"); js_pushnumber(J, 0); js_setproperty(J, -2, "buttons"); js_pushnumber(J, 0); js_setproperty(J, -2, "which"); if (related >= 0) push_node(J, (unsigned int)related + 1); else js_pushnull(J); js_setproperty(J, -2, "relatedTarget"); /* -1: the object on top (index 0 would mean "none supplied"). */ rv = dispatch_object(J, node, -1, type, bubbles, 1); js_pop(J, 2); js_runjobs(J); return rv; } static unsigned int node_type_value(unsigned int node) { struct br_node *n; if (!D || node >= D->nnode) return 0; n = &D->nodes[node]; if (n->type == BR_NODE_TEXT) return 3; if (n->type == BR_NODE_COMMENT) return 8; if (n->type == BR_NODE_FRAGMENT) return 11; return 1; } static void push_child_list(js_State *state, unsigned int node, int elements) { struct br_node *n; unsigned int c, i = 0; js_newarray(state); if (!D || node >= D->nnode) return; n = &D->nodes[node]; for (c = n->first; c; c = D->nodes[c].next) { if (elements && D->nodes[c].type != BR_NODE_ELEM) continue; push_node(state, c + 1); js_setindex(state, -2, (int)i++); } } /* The parent element index of an attached node, or -1 when it has none * (a detached subtree root, or a child of the document). A parent field of * 0 is ambiguous: node 0 is the tree root, which is the element itself * when the page starts with one, and detached roots also keep parent 0. */ static int node_parent_idx(unsigned int node) { const struct br_node *n; if (!D || node >= D->nnode) return -1; n = &D->nodes[node]; if (n->parent) return n->parent; if (node == 0 || (n->flags & BR_NODE_DETACHED)) return -1; return D->nodes[0].type == BR_NODE_ELEM && D->nodes[0].tag == BR_TAG_HTML ? 0 : -1; } static unsigned int node_prev_sibling(unsigned int node) { unsigned int p, c, prev = 0; if (!D || node >= D->nnode) return 0; p = D->nodes[node].parent; for (c = D->nodes[p].first; c && c != node; c = D->nodes[c].next) prev = c; return prev; } /* ---- inline style and dataset objects ---- */ static int ci_eq_n(const char *a, const char *b, unsigned int n) { unsigned int i; for (i = 0; i < n; i++) { char ca = a[i], cb = b[i]; if (ca >= 'A' && ca <= 'Z') ca = (char)(ca - 'A' + 'a'); if (cb >= 'A' && cb <= 'Z') cb = (char)(cb - 'A' + 'a'); if (ca != cb) return 0; } return 1; } /* camelCase JS property -> CSS property ("marginTop" -> "margin-top"). */ static void css_name(const char *name, char *out, unsigned int cap) { unsigned int n = 0, i; if (!strcmp(name, "cssFloat")) { if (cap > 6) memcpy(out, "float", 6); else if (cap) out[0] = '\0'; return; } for (i = 0; name[i] && n + 2 < cap; i++) { char c = name[i]; if (c >= 'A' && c <= 'Z') { if (n == 0 || out[n - 1] != '-') out[n++] = '-'; out[n++] = (char)(c - 'A' + 'a'); } else { out[n++] = c; } } if (cap) out[n] = '\0'; } /* camelCase dataset property -> attribute name ("fooBar" -> "data-foo-bar"). */ static void data_name(const char *name, char *out, unsigned int cap) { unsigned int n = 0, i; for (i = 0; i < 5 && n + 1 < cap; i++) out[n++] = "data-"[i]; for (i = 0; name[i] && n + 2 < cap; i++) { char c = name[i]; if (c >= 'A' && c <= 'Z') { out[n++] = '-'; c = (char)(c - 'A' + 'a'); } out[n++] = c; } if (cap) out[n] = '\0'; } static int style_lookup(const char *style, const char *prop, char *out, unsigned int cap) { unsigned int i = 0, nl = (unsigned int)strlen(prop); while (style && style[i]) { unsigned int ns, ne, vs, ve, a, b, k; while (style[i] == ' ' || style[i] == ';' || style[i] == '\t') i++; if (!style[i]) break; ns = i; while (style[i] && style[i] != ':' && style[i] != ';') i++; ne = i; if (style[i] != ':') { if (style[i] == ';') i++; continue; } i++; while (style[i] == ' ' || style[i] == '\t') i++; vs = i; while (style[i] && style[i] != ';') i++; ve = i; a = ns; b = ne; while (a < b && (style[a] == ' ' || style[a] == '\t')) a++; while (b > a && (style[b - 1] == ' ' || style[b - 1] == '\t')) b--; while (ve > vs && (style[ve - 1] == ' ' || style[ve - 1] == '\t')) ve--; if (b - a == nl && ci_eq_n(style + a, prop, nl)) { for (k = 0; k < ve - vs && k + 1 < cap; k++) out[k] = style[vs + k]; out[k < cap ? k : cap - 1] = '\0'; return 1; } } return 0; } static unsigned int style_count(const char *style) { unsigned int i = 0, n = 0; while (style && style[i]) { while (style[i] == ' ' || style[i] == ';' || style[i] == '\t') i++; if (!style[i]) break; while (style[i] && style[i] != ';') i++; n++; } return n; } static unsigned int style_span(const char *style, unsigned int i) { while (style[i] == ' ' || style[i] == ';' || style[i] == '\t') i++; return i; } static void style_update(unsigned int node, const char *prop, const char *value, int remove) { const char *old = br_find_attr(D, node, "style"); char arr[512]; unsigned int n = 0, i = 0, nl = (unsigned int)strlen(prop); int replaced = 0; if (remove && !old) return; while (old && old[i] && n + 2 < sizeof(arr)) { unsigned int start = style_span(old, i); unsigned int ns, ne, ve, a, b, k; i = start; if (!old[i]) break; ns = i; while (old[i] && old[i] != ':' && old[i] != ';') i++; ne = i; if (old[i] == ':') { i++; while (old[i] == ' ' || old[i] == '\t') i++; while (old[i] && old[i] != ';') i++; } ve = i; a = ns; b = ne; while (a < b && (old[a] == ' ' || old[a] == '\t')) a++; while (b > a && (old[b - 1] == ' ' || old[b - 1] == '\t')) b--; if (b - a == nl && ci_eq_n(old + a, prop, nl)) { replaced = 1; if (remove || !value || !value[0]) continue; } for (k = ns; k < ve && n + 1 < sizeof(arr); k++) arr[n++] = old[k]; if (n + 1 < sizeof(arr)) arr[n++] = ';'; } if (replaced && (remove || !value || !value[0])) { arr[n] = '\0'; br_set_attr(D, node, "style", arr, n); if (host.changed) host.changed(); return; } if (value && value[0] && n + nl + strlen(value) + 3 < sizeof(arr)) { for (i = 0; i < nl; i++) arr[n++] = prop[i]; arr[n++] = ':'; for (i = 0; value[i]; i++) arr[n++] = value[i]; arr[n++] = ';'; } arr[n] = '\0'; br_set_attr(D, node, "style", arr, n); if (host.changed) host.changed(); } static void style_getproperty(js_State *state) { unsigned int node = node_of(js_currentfunctiondata(state)); char val[256]; if (style_lookup(br_find_attr(D, node, "style"), js_tostring(state, 1), val, sizeof(val))) js_pushstring(state, val); else js_pushstring(state, ""); } static void style_setproperty(js_State *state) { unsigned int node = node_of(js_currentfunctiondata(state)); style_update(node, js_tostring(state, 1), js_tostring(state, 2), 0); } static void style_removeproperty(js_State *state) { unsigned int node = node_of(js_currentfunctiondata(state)); const char *prop = js_tostring(state, 1); char old[256]; int had = style_lookup(br_find_attr(D, node, "style"), prop, old, sizeof(old)); style_update(node, prop, "", 1); if (had) js_pushstring(state, old); else js_pushstring(state, ""); } static int style_has(js_State *state, void *p, const char *name) { unsigned int node = node_of(p); const char *style; char prop[64], val[256]; if (!D || node >= D->nnode) return 0; style = br_find_attr(D, node, "style"); if (!strcmp(name, "cssText")) { js_pushstring(state, style ? style : ""); return 1; } if (!strcmp(name, "length")) { js_pushnumber(state, style_count(style)); return 1; } if (!strcmp(name, "getPropertyValue")) { push_func_data(state, name, style_getproperty, 1, node + 1); return 1; } if (!strcmp(name, "setProperty")) { push_func_data(state, name, style_setproperty, 2, node + 1); return 1; } if (!strcmp(name, "removeProperty")) { push_func_data(state, name, style_removeproperty, 1, node + 1); return 1; } css_name(name, prop, sizeof(prop)); if (style_lookup(style, prop, val, sizeof(val))) js_pushstring(state, val); else js_pushstring(state, ""); return 1; } static int style_put(js_State *state, void *p, const char *name) { unsigned int node = node_of(p); const char *value; char prop[64]; if (!D || node >= D->nnode) return 0; value = js_tostring(state, -1); if (!strcmp(name, "cssText")) { br_set_attr(D, node, "style", value, (unsigned int)strlen(value)); if (host.changed) host.changed(); return 1; } css_name(name, prop, sizeof(prop)); style_update(node, prop, value, 0); return 1; } static void push_style_object(js_State *state, unsigned int node) { char key[32]; snprintf(key, sizeof(key), "sty_%u", node + 1); js_getregistry(state, key); if (!js_isundefined(state, -1)) return; js_pop(state, 1); js_getregistry(state, "wrapproto"); js_newuserdatax(state, "style", (void *)(uintptr_t)(node + 1), style_has, style_put, 0, 0); js_copy(state, -1); js_setregistry(state, key); } static int dataset_has(js_State *state, void *p, const char *name) { unsigned int node = node_of(p); char attr[64]; const char *value; if (!D || node >= D->nnode) return 0; data_name(name, attr, sizeof(attr)); value = br_find_attr(D, node, attr); /* A missing data-* attribute is not a property: answering with * undefined made `"x" in el.dataset` true for every name, and * google.com's click handler, which looks for the nearest element * with `"cthref" in dataset`, navigated every click to "null". */ if (!value) return 0; js_pushstring(state, value); return 1; } static int dataset_put(js_State *state, void *p, const char *name) { unsigned int node = node_of(p); char attr[64]; const char *value = js_tostring(state, -1); if (!D || node >= D->nnode) return 0; data_name(name, attr, sizeof(attr)); br_set_attr(D, node, attr, value, (unsigned int)strlen(value)); if (host.changed) host.changed(); return 1; } static int dataset_delete(js_State *state, void *p, const char *name) { unsigned int node = node_of(p); char attr[64]; (void)state; if (!D || node >= D->nnode) return 0; data_name(name, attr, sizeof(attr)); br_remove_attr(D, node, attr); if (host.changed) host.changed(); return 1; } static void push_dataset(js_State *state, unsigned int node) { char key[32]; snprintf(key, sizeof(key), "ds_%u", node + 1); js_getregistry(state, key); if (!js_isundefined(state, -1)) return; js_pop(state, 1); js_getregistry(state, "wrapproto"); js_newuserdatax(state, "dataset", (void *)(uintptr_t)(node + 1), dataset_has, dataset_put, dataset_delete, 0); js_copy(state, -1); js_setregistry(state, key); } static void node_class_set(unsigned int node, const char *classes) { br_set_attr(D, node, "class", classes, (unsigned int)strlen(classes)); if (host.changed) host.changed(); } static int class_has(const char *classes, const char *name) { unsigned int i = 0; if (!classes) return 0; while (classes[i]) { unsigned int start; while (classes[i] == ' ' || classes[i] == '\t') i++; start = i; while (classes[i] && classes[i] != ' ' && classes[i] != '\t') i++; if (i - start == strlen(name) && !strncmp(classes + start, name, i - start)) return 1; } return 0; } static void class_add(unsigned int node, const char *name, int add) { const char *old = node_attr(node, "class"); char buf[2048]; /* BR_CLASS_MAX: Tailwind class lists */ unsigned int n = 0, i = 0; if (add) { if (class_has(old, name)) return; if (old && old[0]) { while (old[i] && n + 1 < sizeof(buf)) buf[n++] = old[i++]; if (n + 1 < sizeof(buf)) buf[n++] = ' '; } i = 0; while (name[i] && n + 1 < sizeof(buf)) buf[n++] = name[i++]; } else { if (!old) return; while (old[i]) { unsigned int start; while (old[i] == ' ' || old[i] == '\t') i++; start = i; while (old[i] && old[i] != ' ' && old[i] != '\t') i++; if (i - start == strlen(name) && !strncmp(old + start, name, i - start)) continue; if (n && n + 1 < sizeof(buf)) buf[n++] = ' '; { unsigned int k; for (k = start; k < i && n + 1 < sizeof(buf); k++) buf[n++] = old[k]; } } } buf[n] = '\0'; node_class_set(node, buf); } static void node_classlist_add(js_State *state) { class_add(node_of(js_currentfunctiondata(state)), js_tostring(state, 1), 1); } static void node_classlist_remove(js_State *state) { class_add(node_of(js_currentfunctiondata(state)), js_tostring(state, 1), 0); } static void node_classlist_toggle(js_State *state) { unsigned int node = node_of(js_currentfunctiondata(state)); const char *name = js_tostring(state, 1); int has = class_has(node_attr(node, "class"), name); int want = !has; if (js_isdefined(state, 2)) want = js_toboolean(state, 2); if (want != has) class_add(node, name, want); js_pushboolean(state, want); } static void node_classlist_contains(js_State *state) { unsigned int node = node_of(js_currentfunctiondata(state)); js_pushboolean(state, class_has(node_attr(node, "class"), js_tostring(state, 1))); } static unsigned int class_count(const char *classes) { unsigned int i = 0, n = 0; if (!classes) return 0; while (classes[i]) { while (classes[i] == ' ' || classes[i] == '\t') i++; if (!classes[i]) break; n++; while (classes[i] && classes[i] != ' ' && classes[i] != '\t') i++; } return n; } /* ---- innerHTML / outerHTML serialization ---- */ #define JS_SERIALIZE_MAX (2u * 1024u * 1024u) struct sbuf { char *p; unsigned int n, cap; int full; }; static void sb_put(struct sbuf *b, const char *s, unsigned int len) { if (b->full) return; if (b->n + len + 1 > b->cap) { unsigned int nc = b->cap ? b->cap : 1024; char *np; while (nc < b->n + len + 1) nc *= 2; if (nc > JS_SERIALIZE_MAX) { b->full = 1; return; } np = (char *)realloc(b->p, nc); if (!np) { b->full = 1; return; } b->p = np; b->cap = nc; } memcpy(b->p + b->n, s, len); b->n += len; b->p[b->n] = '\0'; } static void sb_str(struct sbuf *b, const char *s) { sb_put(b, s, (unsigned int)strlen(s)); } static void sb_escaped(struct sbuf *b, const char *s, unsigned int len, int attr) { unsigned int i, start = 0; for (i = 0; i < len; i++) { const char *rep = 0; if (s[i] == '&') rep = "&"; else if (s[i] == '<' && !attr) rep = "<"; else if (s[i] == '>' && !attr) rep = ">"; else if (s[i] == '"' && attr) rep = """; else if ((unsigned char)s[i] == 0xA0) rep = " "; if (!rep) continue; sb_put(b, s + start, i - start); sb_str(b, rep); start = i + 1; } sb_put(b, s + start, len - start); } static void serialize_node(struct sbuf *b, unsigned int node, int depth); static void serialize_children(struct sbuf *b, unsigned int node, int depth) { unsigned int c; for (c = D->nodes[node].first; c && !b->full; c = D->nodes[c].next) serialize_node(b, c, depth + 1); } /* HTML serialization of the parsed tree (lower-case names, quoted * attributes, raw text inside script/style, no end tag for void * elements). heise reads its JSON config through innerHTML; DOMPurify * returns its result the same way. */ static void serialize_node(struct sbuf *b, unsigned int node, int depth) { struct br_node *n; char name[64]; unsigned int i; const char *p, *end; if (!D || node >= D->nnode || depth > 200 || b->full) return; n = &D->nodes[node]; if (n->type == BR_NODE_TEXT) { unsigned int par = n->parent; int raw = par < D->nnode && D->nodes[par].type == BR_NODE_ELEM && (D->nodes[par].tag == BR_TAG_SCRIPT || D->nodes[par].tag == BR_TAG_STYLE || D->nodes[par].tag == BR_TAG_NOSCRIPT); if (raw) sb_put(b, D->text + n->text_off, n->text_len); else sb_escaped(b, D->text + n->text_off, n->text_len, 0); return; } if (n->type == BR_NODE_COMMENT) { sb_str(b, ""); return; } if (n->type == BR_NODE_FRAGMENT) { serialize_children(b, node, depth); return; } node_name(node, name, sizeof(name)); for (i = 0; name[i]; i++) if (name[i] >= 'A' && name[i] <= 'Z') name[i] = (char)(name[i] - 'A' + 'a'); sb_str(b, "<"); sb_str(b, name); p = D->attrs + n->extra_off; end = p + n->extra_len; while (n->extra_len && p + 1 < end) { const char *an = p, *av; p += strlen(p) + 1; if (p >= end) break; av = p; p += strlen(p) + 1; sb_str(b, " "); sb_str(b, an); sb_str(b, "=\""); sb_escaped(b, av, (unsigned int)strlen(av), 1); sb_str(b, "\""); } sb_str(b, ">"); if (br_tag_is_void(n->tag) && !n->first) return; serialize_children(b, node, depth); sb_str(b, ""); } static void push_serialized(js_State *state, unsigned int node, int outer) { struct sbuf b; memset(&b, 0, sizeof(b)); if (outer) serialize_node(&b, node, 0); else serialize_children(&b, node, 0); js_pushlstring(state, b.p ? b.p : "", (int)b.n); free(b.p); } static void push_attributes(js_State *state, unsigned int node) { struct br_node *n; const char *p, *end; unsigned int count = 0; js_newobject(state); if (!D || node >= D->nnode) return; n = &D->nodes[node]; p = D->attrs + n->extra_off; end = p + n->extra_len; while (p + 1 < end) { const char *an = p; const char *av; p += strlen(p) + 1; if (p >= end) break; av = p; p += strlen(p) + 1; js_newobject(state); js_pushstring(state, an); js_setproperty(state, -2, "name"); js_pushstring(state, av); js_setproperty(state, -2, "value"); js_pushboolean(state, 1); js_setproperty(state, -2, "specified"); /* Array-like: attributes[i] and attributes[name] both work. */ js_copy(state, -1); js_setproperty(state, -3, an); js_setindex(state, -2, (int)count); count++; } js_pushnumber(state, count); js_setproperty(state, -2, "length"); } static void push_classlist(js_State *state, unsigned int node) { js_newobject(state); def_func_data(state, "add", node_classlist_add, 1, node + 1); def_func_data(state, "remove", node_classlist_remove, 1, node + 1); def_func_data(state, "toggle", node_classlist_toggle, 1, node + 1); def_func_data(state, "contains", node_classlist_contains, 1, node + 1); js_pushnumber(state, class_count(node_attr(node, "class"))); js_setproperty(state, -2, "length"); } static void node_getattr(js_State *state) { unsigned int node = node_of(js_currentfunctiondata(state)); push_attr(state, node, js_tostring(state, 1), 1); } static void node_setattr(js_State *state) { unsigned int node = node_of(js_currentfunctiondata(state)); const char *name = js_tostring(state, 1); const char *value = js_tostring(state, 2); char lower[64]; unsigned int i; for (i = 0; name[i] && i + 1 < sizeof(lower); i++) { char c = name[i]; if (c >= 'A' && c <= 'Z') c = (char)(c - 'A' + 'a'); lower[i] = c; } lower[i] = '\0'; br_set_attr(D, node, lower, value, (unsigned int)strlen(value)); if (host.changed) host.changed(); } static void node_removeattr(js_State *state) { unsigned int node = node_of(js_currentfunctiondata(state)); const char *name = js_tostring(state, 1); char lower[64]; unsigned int i; for (i = 0; name[i] && i + 1 < sizeof(lower); i++) { char c = name[i]; if (c >= 'A' && c <= 'Z') c = (char)(c - 'A' + 'a'); lower[i] = c; } lower[i] = '\0'; br_remove_attr(D, node, lower); if (host.changed) host.changed(); } static void node_hasattr(js_State *state) { unsigned int node = node_of(js_currentfunctiondata(state)); js_pushboolean(state, node_attr(node, js_tostring(state, 1)) != 0); } static void node_appendchild(js_State *state) { unsigned int node = node_of(js_currentfunctiondata(state)); unsigned int child = arg_node(state, 1); if (br_append_child(D, node, child) != 0) { js_pushnull(state); return; } if (host.changed) host.changed(); push_node(state, child); } static void node_insertbefore(js_State *state) { unsigned int node = node_of(js_currentfunctiondata(state)); unsigned int child = arg_node(state, 1); unsigned int before = 0; if (!js_isnull(state, 2) && !js_isundefined(state, 2)) before = arg_node(state, 2); if (br_insert_before(D, node, child, before) != 0) { js_pushnull(state); return; } if (host.changed) host.changed(); push_node(state, child); } static void node_removechild(js_State *state) { unsigned int node = node_of(js_currentfunctiondata(state)); unsigned int child = arg_node(state, 1); if (br_remove_child(D, node, child) != 0) { js_pushnull(state); return; } if (host.changed) host.changed(); push_node(state, child); } static void node_replacechild(js_State *state) { unsigned int node = node_of(js_currentfunctiondata(state)); unsigned int child = arg_node(state, 1); unsigned int old = arg_node(state, 2); br_insert_before(D, node, child, old); br_remove_child(D, node, old); if (host.changed) host.changed(); push_node(state, old); } static void node_clone(js_State *state) { unsigned int node = node_of(js_currentfunctiondata(state)); unsigned int h = br_clone_node(D, node + 1, js_toboolean(state, 1)); push_node(state, h); } static void node_contains(js_State *state) { unsigned int node = node_of(js_currentfunctiondata(state)); unsigned int other = arg_node(state, 1); unsigned int p = other; while (1) { if (p == node) { js_pushboolean(state, 1); return; } if (p == 0) break; p = D->nodes[p].parent; } js_pushboolean(state, 0); } static void node_haschildren(js_State *state) { unsigned int node = node_of(js_currentfunctiondata(state)); js_pushboolean(state, node < D->nnode && D->nodes[node].first != 0); } static void node_remove(js_State *state) { unsigned int node = node_of(js_currentfunctiondata(state)); unsigned int parent = node < D->nnode ? D->nodes[node].parent : 0; (void)state; if (parent) br_remove_child(D, parent, node + 1); if (host.changed) host.changed(); } static void node_matches(js_State *state) { unsigned int node = node_of(js_currentfunctiondata(state)); js_pushboolean(state, br_matches(D, node + 1, 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)); const char *name = js_tostring(state, 1); unsigned int out[256]; unsigned int n = br_query_all(D, node + 1, name, out, 256); js_newarray(state); for (unsigned int i = 0; i < n; i++) { push_node(state, out[i]); js_setindex(state, -2, (int)i); } } static void node_getelementsbyclassname(js_State *state) { unsigned int node = node_of(js_currentfunctiondata(state)); const char *name = js_tostring(state, 1); char sel[256]; unsigned int n = 0, i = 0; unsigned int out[256], count; while (name[i] && n + 2 < sizeof(sel)) { while (name[i] == ' ') i++; if (!name[i]) break; sel[n++] = '.'; while (name[i] && name[i] != ' ' && n + 1 < sizeof(sel)) sel[n++] = name[i++]; } sel[n] = '\0'; count = br_query_all(D, node + 1, sel, out, 256); js_newarray(state); for (i = 0; i < count; i++) { push_node(state, out[i]); js_setindex(state, -2, (int)i); } } static void node_queryselector(js_State *state) { unsigned int node = node_of(js_currentfunctiondata(state)); unsigned int out[1]; unsigned int n = br_query_all(D, node + 1, js_tostring(state, 1), out, 1); if (n) push_node(state, out[0]); else js_pushnull(state); } static void node_queryselectorall(js_State *state) { unsigned int node = node_of(js_currentfunctiondata(state)); unsigned int out[256]; unsigned int n = br_query_all(D, node + 1, js_tostring(state, 1), out, 256); js_newarray(state); for (unsigned int i = 0; i < n; i++) { push_node(state, out[i]); js_setindex(state, -2, (int)i); } } static void node_getrect(js_State *state) { unsigned int node = node_of(js_currentfunctiondata(state)); int x = 0, y = 0, w = 0, h = 0; if (host.rect) host.rect(node, &x, &y, &w, &h); js_newobject(state); js_pushnumber(state, y); js_setproperty(state, -2, "top"); js_pushnumber(state, x); js_setproperty(state, -2, "left"); js_pushnumber(state, x + w); js_setproperty(state, -2, "right"); js_pushnumber(state, y + h); js_setproperty(state, -2, "bottom"); js_pushnumber(state, w); js_setproperty(state, -2, "width"); js_pushnumber(state, h); js_setproperty(state, -2, "height"); } static void node_noop(js_State *state) { (void)state; } static void node_push_text(js_State *state, unsigned int node) { unsigned int cap = D->text_used + 1; char *buf; unsigned int len; if (cap < 32) cap = 32; buf = (char *)malloc(cap); if (!buf) { js_pushstring(state, ""); return; } len = br_text_content(D, node, buf, cap); js_pushlstring(state, buf, (int)len); 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) { unsigned int node = node_of(p); struct br_node *n; char buf[64]; if (!D || node >= D->nnode) 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; } if (!strcmp(name, "nodeValue")) { if (n->type == BR_NODE_TEXT || n->type == BR_NODE_COMMENT) js_pushlstring(state, D->text + n->text_off, (int)n->text_len); else js_pushnull(state); return 1; } if (!strcmp(name, "nodeType")) { js_pushnumber(state, node_type_value(node)); return 1; } if (!strcmp(name, "nodeName") || !strcmp(name, "tagName")) { node_name(node, buf, sizeof(buf)); js_pushstring(state, buf); return 1; } if (!strcmp(name, "parentNode") || !strcmp(name, "parentElement")) { int p = node_parent_idx(node); if (p >= 0) push_node(state, (unsigned int)p + 1); else if (name[6] == 'N' && !(n->flags & BR_NODE_DETACHED) && n->type == BR_NODE_ELEM && n->tag == BR_TAG_HTML) js_getglobal(state, "document"); /* 's parent */ else js_pushnull(state); return 1; } if (!strcmp(name, "childNodes")) { push_child_list(state, node, 0); return 1; } if (!strcmp(name, "children")) { push_child_list(state, node, 1); return 1; } if (!strcmp(name, "firstChild")) { push_node(state, n->first ? n->first + 1 : 0); return 1; } if (!strcmp(name, "lastChild")) { push_node(state, n->last ? n->last + 1 : 0); return 1; } if (!strcmp(name, "firstElementChild") || !strcmp(name, "lastElementChild")) { unsigned int c = n->first; unsigned int found = 0; if (!strcmp(name, "lastElementChild")) { for (c = n->first; c; c = D->nodes[c].next) if (D->nodes[c].type == BR_NODE_ELEM) found = c; } else { while (c && D->nodes[c].type != BR_NODE_ELEM) c = D->nodes[c].next; found = c; } push_node(state, found ? found + 1 : 0); return 1; } if (!strcmp(name, "nextSibling") || !strcmp(name, "nextElementSibling")) { unsigned int c = n->next; if (!strcmp(name, "nextElementSibling")) while (c && D->nodes[c].type != BR_NODE_ELEM) c = D->nodes[c].next; push_node(state, c ? c + 1 : 0); return 1; } if (!strcmp(name, "previousSibling") || !strcmp(name, "previousElementSibling")) { unsigned int c = node_prev_sibling(node); if (!strcmp(name, "previousElementSibling")) while (c && D->nodes[c].type != BR_NODE_ELEM) c = node_prev_sibling(c); push_node(state, c ? c + 1 : 0); return 1; } if (!strcmp(name, "childElementCount")) { unsigned int c, count = 0; for (c = n->first; c; c = D->nodes[c].next) if (D->nodes[c].type == BR_NODE_ELEM) count++; js_pushnumber(state, count); return 1; } if (n->tag == BR_TAG_A || n->tag == BR_TAG_AREA) { if (!strcmp(name, "href") || !strcmp(name, "protocol") || !strcmp(name, "host") || !strcmp(name, "hostname") || !strcmp(name, "port") || !strcmp(name, "pathname") || !strcmp(name, "search") || !strcmp(name, "hash") || !strcmp(name, "origin")) { push_element_url(state, node, name); return 1; } } if (!strcmp(name, "id")) { push_attr(state, node, "id", 0); return 1; } if (!strcmp(name, "className")) { push_attr(state, node, "class", 0); return 1; } if (!strcmp(name, "href")) { push_attr(state, node, "href", 0); return 1; } if (!strcmp(name, "src")) { push_attr(state, node, "src", 0); return 1; } if (n->type == BR_NODE_ELEM && n->tag == BR_TAG_SELECT) { if (!strcmp(name, "options")) { push_query_array(state, node, "option"); return 1; } if (!strcmp(name, "multiple")) { js_pushboolean(state, node_attr(node, "multiple") != 0); return 1; } } /*