| 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403 |
- /* 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 <setjmp.h>
- #include <stdint.h>
- #include <stdio.h>
- #include <stdlib.h>
- #include <string.h>
- #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
- #define JS_TIMERS 64
- 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;
- /* 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<event> 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;
- 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 (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);
- }
- 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;
- }
- 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++);
- }
- }
- 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);
- if (value)
- js_pushstring(state, value);
- else
- js_pushundefined(state);
- 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[256];
- 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;
- }
- 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")) {
- unsigned int p = n->parent;
- push_node(state, p ? p + 1 : 0);
- 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;
- }
- }
- /* An <option> without a value attribute has its text as value. */
- if (n->type == BR_NODE_ELEM && n->tag == BR_TAG_OPTION &&
- !strcmp(name, "value") && !node_attr(node, "value")) {
- node_push_text(state, node);
- return 1;
- }
- if (!strcmp(name, "value")) {
- char buf[128];
- if (host.form_value && host.form_value(node, buf, sizeof(buf)))
- js_pushstring(state, buf);
- else
- push_attr(state, node, "value", 0);
- return 1;
- }
- if (!strcmp(name, "type")) { push_attr(state, node, "type", 0); return 1; }
- if (!strcmp(name, "name")) { push_attr(state, node, "name", 0); return 1; }
- if (!strcmp(name, "alt")) { push_attr(state, node, "alt", 0); return 1; }
- if (!strcmp(name, "title")) { push_attr(state, node, "title", 0); return 1; }
- if (!strcmp(name, "checked")) {
- int c = host.form_checked ? host.form_checked(node) : -1;
- js_pushboolean(state, c >= 0 ? c : node_attr(node, name) != 0);
- return 1;
- }
- if (!strcmp(name, "selectedIndex")) {
- int c = host.form_selected ? host.form_selected(node) : -1;
- js_pushnumber(state, c >= 0 ? c : 0);
- return 1;
- }
- if (!strcmp(name, "selected")) {
- int c = host.form_selected ? host.form_selected(node) : -1;
- if (c >= 0)
- js_pushboolean(state, c != 0);
- else
- js_pushboolean(state, node_attr(node, name) != 0);
- return 1;
- }
- if (!strcmp(name, "disabled")) {
- js_pushboolean(state, node_attr(node, name) != 0);
- return 1;
- }
- if (!strcmp(name, "style")) {
- push_style_object(state, node);
- return 1;
- }
- if (!strcmp(name, "dataset") || !strcmp(name, "domStringMap")) {
- push_dataset(state, node);
- return 1;
- }
- if (!strcmp(name, "classList")) {
- push_classlist(state, node);
- return 1;
- }
- if (!strcmp(name, "attributes")) {
- push_attributes(state, node);
- return 1;
- }
- if (!strcmp(name, "innerHTML") || !strcmp(name, "outerHTML")) {
- char key[32];
- snprintf(key, sizeof(key), "html_%u", node + 1);
- js_getregistry(state, key);
- if (js_isundefined(state, -1)) {
- js_pop(state, 1);
- js_pushstring(state, "");
- }
- return 1;
- }
- if (!strcmp(name, "ownerDocument")) {
- js_getglobal(state, "document");
- return 1;
- }
- if (!strcmp(name, "localName")) {
- unsigned int i;
- if (n->type != BR_NODE_ELEM) {
- js_pushnull(state);
- return 1;
- }
- node_name(node, buf, sizeof(buf));
- for (i = 0; buf[i]; i++)
- if (buf[i] >= 'A' && buf[i] <= 'Z')
- buf[i] = (char)(buf[i] - 'A' + 'a');
- js_pushstring(state, buf);
- return 1;
- }
- if (!strcmp(name, "namespaceURI")) {
- unsigned int a;
- if (n->type != BR_NODE_ELEM) {
- js_pushnull(state);
- return 1;
- }
- for (a = node; a && a < D->nnode; a = D->nodes[a].parent)
- if (D->nodes[a].type == BR_NODE_ELEM &&
- D->nodes[a].tag == BR_TAG_SVG)
- break;
- js_pushstring(state, a && a < D->nnode ?
- "http://www.w3.org/2000/svg" :
- "http://www.w3.org/1999/xhtml");
- return 1;
- }
- if (!strcmp(name, "isConnected")) {
- unsigned int a = node;
- while (a && a < D->nnode && D->nodes[a].parent)
- a = D->nodes[a].parent;
- js_pushboolean(state, a == 0 || a == D->root);
- return 1;
- }
- if (!strcmp(name, "relList")) {
- /* Only supports(): Vite's modulepreload polyfill asks it and
- * otherwise refetches every preloaded module through fetch(). */
- js_newobject(state);
- def_func(state, "supports", rellist_supports, 1);
- return 1;
- }
- if (!strcmp(name, "getAttribute"))
- { push_func_data(state, "getAttribute", node_getattr, 1, node + 1); return 1; }
- if (!strcmp(name, "setAttribute"))
- { push_func_data(state, "setAttribute", node_setattr, 2, node + 1); return 1; }
- if (!strcmp(name, "removeAttribute"))
- { push_func_data(state, "removeAttribute", node_removeattr, 1, node + 1); return 1; }
- if (!strcmp(name, "hasAttribute"))
- { push_func_data(state, "hasAttribute", node_hasattr, 1, node + 1); return 1; }
- if (!strcmp(name, "appendChild"))
- { push_func_data(state, "appendChild", node_appendchild, 1, node + 1); return 1; }
- if (!strcmp(name, "insertBefore"))
- { push_func_data(state, "insertBefore", node_insertbefore, 2, node + 1); return 1; }
- if (!strcmp(name, "removeChild"))
- { push_func_data(state, "removeChild", node_removechild, 1, node + 1); return 1; }
- if (!strcmp(name, "replaceChild"))
- { push_func_data(state, "replaceChild", node_replacechild, 2, node + 1); return 1; }
- if (!strcmp(name, "cloneNode"))
- { push_func_data(state, "cloneNode", node_clone, 1, node + 1); return 1; }
- if (!strcmp(name, "contains"))
- { push_func_data(state, "contains", node_contains, 1, node + 1); return 1; }
- if (!strcmp(name, "hasChildNodes"))
- { push_func_data(state, "hasChildNodes", node_haschildren, 0, node + 1); return 1; }
- if (!strcmp(name, "remove"))
- { push_func_data(state, "remove", node_remove, 0, node + 1); return 1; }
- if (!strcmp(name, "matches") || !strcmp(name, "webkitMatchesSelector") ||
- !strcmp(name, "mozMatchesSelector") ||
- !strcmp(name, "msMatchesSelector"))
- { push_func_data(state, name, node_matches, 1, node + 1); return 1; }
- if (!strcmp(name, "getElementsByTagName"))
- { push_func_data(state, "getElementsByTagName", node_getelementsbytagname, 1, node + 1); return 1; }
- if (!strcmp(name, "getElementsByClassName"))
- { push_func_data(state, "getElementsByClassName", node_getelementsbyclassname, 1, node + 1); return 1; }
- if (!strcmp(name, "querySelector"))
- { push_func_data(state, "querySelector", node_queryselector, 1, node + 1); return 1; }
- 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_addlistener, 2, node + 1); return 1; }
- if (!strcmp(name, "removeEventListener"))
- { push_func_data(state, "removeEventListener", node_removelistener, 2, node + 1); return 1; }
- if (!strcmp(name, "dispatchEvent"))
- { 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")) {
- js_newarray(state);
- return 1;
- }
- if (!strcmp(name, "offsetWidth") || !strcmp(name, "offsetHeight") ||
- !strcmp(name, "clientWidth") || !strcmp(name, "clientHeight") ||
- !strcmp(name, "scrollWidth") || !strcmp(name, "scrollHeight")) {
- int x = 0, y = 0, w = 0, h = 0;
- /* Before the first layout an element has no box; a block's
- * width is then best guessed as the viewport (Vue apps measure
- * offsetWidth on mount and pick a phone layout for 0). A
- * resize event after layout lets them measure again. */
- if (!host.rect || !host.rect(node, &x, &y, &w, &h))
- w = n->type == BR_NODE_ELEM ? (int)host.width : 0;
- js_pushnumber(state, (!strcmp(name, "offsetHeight") ||
- !strcmp(name, "clientHeight") ||
- !strcmp(name, "scrollHeight")) ? h : w);
- return 1;
- }
- if (!strcmp(name, "scrollTop") || !strcmp(name, "scrollLeft")) {
- js_pushnumber(state, 0);
- return 1;
- }
- 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;
- }
- return 0;
- }
- static void node_set_string(unsigned int node, const char *name,
- const char *value)
- {
- br_set_attr(D, node, name, value, (unsigned int)strlen(value));
- if (host.changed)
- host.changed();
- }
- static int node_put(js_State *state, void *p, const char *name)
- {
- unsigned int node = node_of(p);
- if (!D || node >= D->nnode)
- return 0;
- if (!strcmp(name, "textContent") || !strcmp(name, "innerText")) {
- const char *text = js_tostring(state, -1);
- unsigned int len = (unsigned int)strlen(text);
- if (br_set_text_content(D, node, text, len) != 0) {
- if (host.status)
- host.status("Page text arena is full", 1);
- } else if (host.changed) {
- host.changed();
- }
- return 1;
- }
- if (!strcmp(name, "nodeValue")) {
- const char *text = js_tostring(state, -1);
- if (br_set_text_node(D, node, text,
- (unsigned int)strlen(text)) == 0 &&
- host.changed)
- host.changed();
- return 1;
- }
- if (!strcmp(name, "id") || !strcmp(name, "className") ||
- !strcmp(name, "href") || !strcmp(name, "src") ||
- !strcmp(name, "value") || !strcmp(name, "type") ||
- !strcmp(name, "name") || !strcmp(name, "alt") ||
- !strcmp(name, "title")) {
- const char *value = js_tostring(state, -1);
- if (!strcmp(name, "value") && host.form_set_value &&
- host.form_set_value(node, value))
- return 1;
- if (!strcmp(name, "className"))
- node_set_string(node, "class", value);
- else
- node_set_string(node, name, value);
- return 1;
- }
- if (!strcmp(name, "selectedIndex")) {
- if (host.form_set_selected)
- host.form_set_selected(node, js_tointeger(state, -1));
- return 1;
- }
- if (!strcmp(name, "checked") || !strcmp(name, "disabled") ||
- !strcmp(name, "selected")) {
- int b = js_toboolean(state, -1);
- if (!strcmp(name, "checked") && host.form_set_checked &&
- host.form_set_checked(node, b))
- return 1;
- if (!strcmp(name, "selected") && host.form_set_selected &&
- host.form_set_selected(node, b ? 1 : 0))
- return 1;
- if (b)
- br_set_attr(D, node, name, "", 0);
- else
- br_remove_attr(D, node, name);
- if (host.changed)
- host.changed();
- return 1;
- }
- if (!strcmp(name, "innerHTML")) {
- const char *html = js_tostring(state, -1);
- char key[32];
- br_set_inner_html(D, node, html, (unsigned int)strlen(html));
- snprintf(key, sizeof(key), "html_%u", node + 1);
- js_pushstring(state, html);
- js_setregistry(state, key);
- if (host.changed)
- host.changed();
- return 1;
- }
- if (!strcmp(name, "outerHTML")) {
- char key[32];
- snprintf(key, sizeof(key), "html_%u", node + 1);
- js_pushstring(state, js_tostring(state, -1));
- js_setregistry(state, key);
- return 1;
- }
- if (!strcmp(name, "style")) {
- if (js_isstring(state, -1))
- node_set_string(node, "style",
- js_tostring(state, -1));
- return 1;
- }
- return 0;
- }
- static int node_delete(js_State *state, void *p, const char *name)
- {
- (void)state;
- (void)p;
- (void)name;
- return 0;
- }
- static void doc_getelementbyid(js_State *state)
- {
- const char *id = js_tostring(state, 1);
- push_node(state, br_find_id(D, id));
- }
- static void console_log(js_State *state)
- {
- int i;
- int n = js_gettop(state);
- for (i = 1; i < n; i++) {
- if (i > 1)
- u_putc(' ');
- u_puts(js_tostring(state, i));
- }
- u_putc('\n');
- }
- static void js_alert(js_State *state)
- {
- char msg[160];
- unsigned int used = 0;
- int i;
- int n = js_gettop(state);
- for (i = 1; i < n; i++) {
- const char *s = js_tostring(state, i);
- unsigned int k;
- if (i > 1 && used + 1 < sizeof(msg))
- msg[used++] = ' ';
- for (k = 0; s[k] && used + 1 < sizeof(msg); k++)
- msg[used++] = s[k];
- }
- msg[used] = '\0';
- if (host.status)
- host.status(msg, 0);
- }
- static void push_query_array(js_State *state, unsigned int root,
- const char *selector)
- {
- unsigned int out[256];
- unsigned int n = br_query_all(D, root, selector, out, 256);
- unsigned int i;
- js_newarray(state);
- for (i = 0; i < n; i++) {
- push_node(state, out[i]);
- js_setindex(state, -2, (int)i);
- }
- }
- static void doc_create_element(js_State *state)
- {
- const char *name = js_tostring(state, 1);
- char lower[32];
- 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';
- push_node(state, br_create_element(D, lower, i));
- }
- static void doc_create_text(js_State *state)
- {
- const char *text = js_tostring(state, 1);
- push_node(state, br_create_text(D, text, (unsigned int)strlen(text)));
- }
- static void doc_create_comment(js_State *state)
- {
- const char *text = js_tostring(state, 1);
- push_node(state, br_create_comment(D, text, (unsigned int)strlen(text)));
- }
- static void doc_create_fragment(js_State *state)
- {
- push_node(state, br_create_fragment(D));
- }
- static void doc_create_attribute(js_State *state)
- {
- const char *name = js_tostring(state, 1);
- js_newobject(state);
- js_pushstring(state, name);
- js_setproperty(state, -2, "name");
- js_pushstring(state, "");
- js_setproperty(state, -2, "value");
- js_pushboolean(state, 1);
- js_setproperty(state, -2, "specified");
- }
- static void doc_getelementsbytagname(js_State *state)
- {
- push_query_array(state, 0, js_tostring(state, 1));
- }
- static void doc_getelementsbyclassname(js_State *state)
- {
- const char *name = js_tostring(state, 1);
- char sel[256];
- unsigned int n = 0, i = 0;
- 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';
- push_query_array(state, 0, sel);
- }
- static void doc_queryselector(js_State *state)
- {
- unsigned int out[1];
- unsigned int n = br_query_all(D, 0, js_tostring(state, 1), out, 1);
- if (n)
- push_node(state, out[0]);
- else
- js_pushnull(state);
- }
- static void doc_queryselectorall(js_State *state)
- {
- push_query_array(state, 0, js_tostring(state, 1));
- }
- static void location_get(js_State *state)
- {
- js_pushstring(state, current_url ? current_url : "");
- }
- /* Length of a URL without its #fragment. */
- static unsigned int url_doc_len(const char *u)
- {
- unsigned int n = 0;
- while (u[n] && u[n] != '#')
- n++;
- return n;
- }
- /* Navigate, or, when only the #fragment changes, stay on the page: the
- * host updates the URL (location.href follows it) and a hashchange event is
- * queued. Hash-routed apps (the Cloudron dashboard) navigate this way; a
- * reload would restart the whole app. */
- static void location_go(const char *url)
- {
- char abs[1024];
- unsigned int n;
- if (!current_url || !url) {
- if (host.navigate && url)
- host.navigate(url);
- return;
- }
- url_resolve(current_url, url, abs, sizeof(abs));
- n = url_doc_len(abs);
- if (host.set_hash && abs[n] == '#' && n == url_doc_len(current_url) &&
- !strncmp(abs, current_url, n)) {
- if (strcmp(abs, current_url) && host.set_hash(abs) == 0)
- hash_pending = 1;
- return;
- }
- if (host.navigate)
- host.navigate(url);
- }
- static void location_set(js_State *state)
- {
- location_go(js_tostring(state, 1));
- }
- /* assign()/replace(): navigate (the history entry is not replaced yet). */
- static void location_assign(js_State *state)
- {
- location_go(js_tostring(state, 1));
- js_pushundefined(state);
- }
- static void location_hash_get(js_State *state)
- {
- const char *h = current_url ? strchr(current_url, '#') : 0;
- js_pushstring(state, h && h[1] ? h : "");
- }
- static void location_hash_set(js_State *state)
- {
- const char *v = js_tostring(state, 1);
- char url[1024];
- unsigned int n;
- if (!current_url)
- return;
- n = url_doc_len(current_url);
- if (n + 2 >= sizeof(url))
- return;
- memcpy(url, current_url, n);
- url[n] = '#';
- snprintf(url + n + 1, sizeof(url) - n - 1, "%s", v[0] == '#' ? v + 1 : v);
- location_go(url);
- }
- static void location_reload(js_State *state)
- {
- if (host.navigate && current_url)
- host.navigate(current_url);
- js_pushundefined(state);
- }
- static void location_tostring(js_State *state)
- {
- js_pushstring(state, current_url ? current_url : "");
- }
- static void win_noop(js_State *state);
- struct loc_parts {
- const char *protocol, *host, *hostname, *port, *path, *search, *hash;
- const char *origin;
- unsigned int protocol_len, host_len, hostname_len, port_len;
- unsigned int path_len, search_len, hash_len, origin_len;
- };
- static void loc_split(const char *u, struct loc_parts *p)
- {
- unsigned int n = (unsigned int)strlen(u), i;
- const char *rest;
- memset(p, 0, sizeof(*p));
- p->path = u;
- p->path_len = n;
- p->origin = "null";
- p->origin_len = 4;
- for (i = 0; i < n; i++)
- if (u[i] == ':')
- break;
- if (i + 2 < n && u[i] == ':' && u[i + 1] == '/' && u[i + 2] == '/') {
- const char *hosts = u + i + 3, *hoste = hosts;
- while (*hoste && *hoste != '/' && *hoste != '?' && *hoste != '#')
- hoste++;
- p->protocol = u;
- p->protocol_len = i + 1;
- p->host = hosts;
- p->host_len = (unsigned int)(hoste - hosts);
- p->hostname = hosts;
- p->hostname_len = p->host_len;
- for (i = 0; i < p->hostname_len; i++)
- if (hosts[i] == ':') {
- p->port = hosts + i + 1;
- p->port_len = p->hostname_len - i - 1;
- p->hostname_len = i;
- break;
- }
- p->origin = u;
- p->origin_len = (unsigned int)(hoste - u);
- rest = hoste;
- } else {
- p->protocol = "file:";
- p->protocol_len = 5;
- rest = u;
- }
- {
- const char *q = rest;
- while (*q && *q != '?' && *q != '#')
- q++;
- p->path = rest;
- p->path_len = (unsigned int)(q - rest);
- if (*q == '?') {
- const char *s = q;
- while (*q && *q != '#')
- q++;
- p->search = s;
- p->search_len = (unsigned int)(q - s);
- }
- if (*q == '#') {
- p->hash = q;
- p->hash_len = (unsigned int)strlen(q);
- }
- }
- }
- static void push_location(js_State *state)
- {
- struct loc_parts p;
- loc_split(current_url ? current_url : "", &p);
- js_newobject(state);
- js_newcfunction(state, location_get, "get href", 0);
- js_newcfunction(state, location_set, "set href", 1);
- js_defaccessor(state, -3, "href", 0);
- #define LOC_FIELD(field) \
- do { \
- js_pushlstring(state, p.field ? p.field : "", \
- p.field ? (int)p.field##_len : 0); \
- js_setproperty(state, -2, #field); \
- } while (0)
- LOC_FIELD(protocol);
- LOC_FIELD(host);
- LOC_FIELD(hostname);
- LOC_FIELD(port);
- js_pushlstring(state, p.path ? p.path : "",
- p.path ? (int)p.path_len : 0);
- js_setproperty(state, -2, "pathname");
- LOC_FIELD(search);
- LOC_FIELD(origin);
- #undef LOC_FIELD
- js_newcfunction(state, location_hash_get, "get hash", 0);
- js_newcfunction(state, location_hash_set, "set hash", 1);
- js_defaccessor(state, -3, "hash", 0);
- js_newcfunction(state, location_reload, "reload", 0);
- js_setproperty(state, -2, "reload");
- js_newcfunction(state, location_assign, "assign", 1);
- js_setproperty(state, -2, "assign");
- js_newcfunction(state, location_assign, "replace", 1);
- js_setproperty(state, -2, "replace");
- js_newcfunction(state, location_tostring, "toString", 0);
- js_setproperty(state, -2, "toString");
- }
- /* ---- URL resolution for <a>/<area> URL properties ---- */
- static int url_has_scheme(const char *s)
- {
- unsigned int i = 1;
- if (!((s[0] >= 'a' && s[0] <= 'z') ||
- (s[0] >= 'A' && s[0] <= 'Z')))
- return 0;
- while (s[i]) {
- char c = s[i];
- if (c == ':')
- return 1;
- if (!((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') ||
- (c >= '0' && c <= '9') || c == '+' || c == '-' ||
- c == '.'))
- return 0;
- i++;
- }
- return 0;
- }
- static void url_put(char *out, unsigned int cap, unsigned int *n,
- const char *s, unsigned int len)
- {
- unsigned int i;
- for (i = 0; i < len && *n + 1 < cap; i++)
- out[(*n)++] = s[i];
- }
- /* Collapse //, /./ and /../ inside the path part of an absolute URL. */
- static void url_normalize(char *url)
- {
- char tmp[1024];
- char *path;
- unsigned int n = 0, i = 0;
- path = strstr(url, "://");
- if (path) {
- path += 3;
- while (*path && *path != '/')
- path++;
- } else {
- path = url;
- }
- if (path[0] != '/')
- return;
- /* The path only: ?query and #fragment are copied verbatim below. */
- while (path[i] && path[i] != '?' && path[i] != '#') {
- unsigned int start;
- while (path[i] == '/')
- i++;
- start = i;
- while (path[i] && path[i] != '/' && path[i] != '?' &&
- path[i] != '#')
- i++;
- if (i == start)
- continue;
- if (i - start == 1 && path[start] == '.')
- continue;
- if (i - start == 2 && path[start] == '.' &&
- path[start + 1] == '.') {
- while (n > 0 && tmp[n - 1] != '/')
- n--;
- if (n > 0)
- n--;
- continue;
- }
- if (n + 1 < sizeof(tmp))
- tmp[n++] = '/';
- while (start < i && n + 1 < sizeof(tmp))
- tmp[n++] = path[start++];
- }
- if (n == 0)
- tmp[n++] = '/';
- else if (i > 0 && path[i - 1] == '/' && n + 1 < sizeof(tmp))
- tmp[n++] = '/'; /* keep "dir/" a directory */
- while (path[i] && n + 1 < sizeof(tmp))
- tmp[n++] = path[i++];
- tmp[n] = '\0';
- memcpy(path, tmp, n + 1);
- }
- static void url_resolve(const char *base, const char *rel,
- char *out, unsigned int cap)
- {
- struct loc_parts bp;
- unsigned int n = 0, i;
- if (cap == 0)
- return;
- if (!rel[0]) {
- url_put(out, cap, &n, base, (unsigned int)strlen(base));
- out[n] = '\0';
- return;
- }
- if (url_has_scheme(rel)) {
- url_put(out, cap, &n, rel, (unsigned int)strlen(rel));
- out[n] = '\0';
- url_normalize(out);
- return;
- }
- loc_split(base, &bp);
- if (rel[0] == '/' && rel[1] == '/') {
- url_put(out, cap, &n, bp.protocol, bp.protocol_len);
- url_put(out, cap, &n, rel, (unsigned int)strlen(rel));
- } else if (rel[0] == '/') {
- url_put(out, cap, &n, bp.protocol, bp.protocol_len);
- url_put(out, cap, &n, "//", 2);
- url_put(out, cap, &n, bp.host, bp.host_len);
- url_put(out, cap, &n, rel, (unsigned int)strlen(rel));
- } else if (rel[0] == '#' || rel[0] == '?') {
- url_put(out, cap, &n, bp.protocol, bp.protocol_len);
- if (bp.host_len || (bp.protocol_len == 5 &&
- bp.protocol[0] == 'f')) {
- url_put(out, cap, &n, "//", 2);
- url_put(out, cap, &n, bp.host, bp.host_len);
- }
- url_put(out, cap, &n, bp.path, bp.path_len);
- if (rel[0] == '#')
- url_put(out, cap, &n, bp.search, bp.search_len);
- url_put(out, cap, &n, rel, (unsigned int)strlen(rel));
- } else {
- const char *dir_end = bp.path;
- for (i = 0; i < bp.path_len; i++)
- if (bp.path[i] == '/')
- dir_end = bp.path + i + 1;
- if (dir_end == bp.path)
- dir_end = bp.path + bp.path_len;
- url_put(out, cap, &n, bp.protocol, bp.protocol_len);
- if (bp.host_len || (bp.protocol_len == 5 &&
- bp.protocol[0] == 'f')) {
- url_put(out, cap, &n, "//", 2);
- url_put(out, cap, &n, bp.host, bp.host_len);
- }
- url_put(out, cap, &n, bp.path,
- (unsigned int)(dir_end - bp.path));
- url_put(out, cap, &n, rel, (unsigned int)strlen(rel));
- }
- out[n] = '\0';
- url_normalize(out);
- }
- /* <a> URL properties are resolved against the page URL, like the DOM. */
- static void push_element_url(js_State *state, unsigned int node,
- const char *name)
- {
- char abs_url[512];
- const char *href = br_find_attr(D, node, "href");
- struct loc_parts p;
- if (!href || !href[0]) {
- js_pushstring(state, "");
- return;
- }
- url_resolve(current_url ? current_url : "/", href,
- abs_url, sizeof(abs_url));
- loc_split(abs_url, &p);
- if (!strcmp(name, "href"))
- js_pushstring(state, abs_url);
- else if (!strcmp(name, "protocol"))
- js_pushlstring(state, p.protocol, (int)p.protocol_len);
- else if (!strcmp(name, "origin"))
- js_pushlstring(state, p.origin ? p.origin : "",
- (int)p.origin_len);
- else if (!strcmp(name, "host"))
- js_pushlstring(state, p.host ? p.host : "", (int)p.host_len);
- else if (!strcmp(name, "hostname"))
- js_pushlstring(state, p.hostname ? p.hostname : "",
- (int)p.hostname_len);
- else if (!strcmp(name, "port"))
- js_pushlstring(state, p.port ? p.port : "", (int)p.port_len);
- else if (!strcmp(name, "pathname"))
- js_pushlstring(state, p.path ? p.path : "", (int)p.path_len);
- else if (!strcmp(name, "search"))
- js_pushlstring(state, p.search ? p.search : "",
- (int)p.search_len);
- else
- js_pushlstring(state, p.hash ? p.hash : "", (int)p.hash_len);
- }
- static void win_noop(js_State *state)
- {
- (void)state;
- }
- static void timer_add(js_State *state, int repeat)
- {
- int i;
- unsigned int ms;
- if (!js_iscallable(state, 1)) {
- js_pushnumber(state, 0);
- return;
- }
- ms = js_isdefined(state, 2) ?
- (unsigned int)js_tointeger(state, 2) : 0;
- if (repeat && ms == 0)
- ms = 1;
- for (i = 0; i < JS_TIMERS; i++)
- if (!timers[i].used)
- break;
- if (i == JS_TIMERS) {
- js_pushnumber(state, 0);
- return;
- }
- js_copy(state, 1);
- snprintf(timers[i].ref, sizeof(timers[i].ref), "%s",
- js_ref(state));
- timers[i].used = 1;
- timers[i].repeat = repeat;
- timers[i].interval = ms;
- timers[i].deadline = u_ticks_ms() + ms;
- js_pushnumber(state, i + 1);
- }
- static void win_settimeout(js_State *state)
- {
- timer_add(state, 0);
- }
- static void win_setinterval(js_State *state)
- {
- timer_add(state, 1);
- }
- static void timer_clear(js_State *state)
- {
- int id = js_tointeger(state, 1);
- if (id >= 1 && id <= JS_TIMERS && timers[id - 1].used) {
- js_unref(state, timers[id - 1].ref);
- timers[id - 1].used = 0;
- }
- }
- static void win_requestanimationframe(js_State *state)
- {
- timer_add(state, 0);
- }
- static void win_performance_now(js_State *state)
- {
- js_pushnumber(state, (double)u_ticks_ms());
- }
- struct computed_prop {
- const char *js;
- const char *css;
- };
- static const struct computed_prop computed_props[] = {
- { "display", "display" }, { "position", "position" },
- { "width", "width" }, { "height", "height" },
- { "color", "color" }, { "backgroundColor", "background-color" },
- { "fill", "fill" }, { "stroke", "stroke" },
- { "fontSize", "font-size" }, { "fontWeight", "font-weight" },
- { "fontStyle", "font-style" }, { "fontFamily", "font-family" },
- { "textAlign", "text-align" }, { "float", "float" },
- { "cssFloat", "float" }, { "clear", "clear" },
- { "opacity", "opacity" }, { "visibility", "visibility" },
- { "overflow", "overflow" }, { "whiteSpace", "white-space" },
- { "textTransform", "text-transform" }, { "boxSizing", "box-sizing" },
- { "lineHeight", "line-height" }, { "zIndex", "z-index" },
- { "top", "top" }, { "left", "left" }, { "right", "right" },
- { "bottom", "bottom" },
- { "marginTop", "margin-top" }, { "marginRight", "margin-right" },
- { "marginBottom", "margin-bottom" }, { "marginLeft", "margin-left" },
- { "paddingTop", "padding-top" }, { "paddingRight", "padding-right" },
- { "paddingBottom", "padding-bottom" },
- { "paddingLeft", "padding-left" },
- { "borderTopWidth", "border-top-width" },
- { "borderRightWidth", "border-right-width" },
- { "borderBottomWidth", "border-bottom-width" },
- { "borderLeftWidth", "border-left-width" },
- { "borderTopColor", "border-top-color" },
- { "borderRightColor", "border-right-color" },
- { "borderBottomColor", "border-bottom-color" },
- { "borderLeftColor", "border-left-color" },
- { "backgroundImage", "background-image" },
- { "backgroundRepeat", "background-repeat" },
- { "backgroundPosition", "background-position" },
- { "backgroundSize", "background-size" },
- { "transform", "transform" },
- { 0, 0 }
- };
- static void computed_get(js_State *state)
- {
- unsigned int node = node_of(js_currentfunctiondata(state));
- const char *prop = js_tostring(state, 1);
- char buf[192];
- if (host.computed && host.computed(node, prop, buf, sizeof(buf)))
- js_pushstring(state, buf);
- else
- js_pushstring(state, "");
- }
- static void win_getcomputedstyle(js_State *state)
- {
- unsigned int node = 0;
- char buf[192];
- int i;
- if (js_isuserdata(state, 1, "node"))
- node = node_of(js_touserdata(state, 1, "node"));
- js_newobject(state);
- def_func_data(state, "getPropertyValue", computed_get, 1, node + 1);
- for (i = 0; computed_props[i].js; i++) {
- if (!host.computed ||
- !host.computed(node, computed_props[i].css, buf,
- sizeof(buf)))
- continue;
- js_pushstring(state, buf);
- js_setproperty(state, -2, computed_props[i].js);
- }
- js_pushstring(state, "");
- js_setproperty(state, -2, "cssText");
- }
- static void win_matchmedia(js_State *state)
- {
- const char *query = js_tostring(state, 1);
- js_newobject(state);
- js_pushboolean(state, 0);
- js_setproperty(state, -2, "matches");
- js_pushstring(state, query);
- js_setproperty(state, -2, "media");
- def_func(state, "addListener", win_noop, 1);
- def_func(state, "removeListener", win_noop, 1);
- def_func(state, "addEventListener", win_noop, 2);
- def_func(state, "removeEventListener", win_noop, 2);
- }
- static void rellist_supports(js_State *state)
- {
- const char *t = js_tostring(state, 1);
- js_pushboolean(state, !strcmp(t, "modulepreload") ||
- !strcmp(t, "preload") || !strcmp(t, "stylesheet"));
- }
- /* ---- primitives for js_prelude.js ---- */
- /* __nb_http(method, url, contentType, body) -> [status, ctype, url, text].
- * Synchronous: the host fetches through its helpers while the script
- * waits. A network failure throws (fetch() turns it into a TypeError). */
- static void nb_http(js_State *state)
- {
- struct js_http_resp r;
- const char *method = js_tostring(state, 1);
- const char *url = js_tostring(state, 2);
- const char *ctype = js_tostring(state, 3);
- const char *body = js_tostring(state, 4);
- char err[96];
- int rv;
- memset(&r, 0, sizeof(r));
- err[0] = '\0';
- rv = host.http ? host.http(method, url, ctype, body,
- (unsigned int)strlen(body), &r, err,
- (int)sizeof(err)) : -1;
- /* The budget covers running JavaScript, not the network wait. */
- js_setlimit(state, JS_RUN_LIMIT, 0);
- if (rv != 0) {
- free(r.body);
- js_typeerror(state, "network error: %s",
- err[0] ? err : "fetch failed");
- }
- js_newarray(state);
- js_pushnumber(state, r.status);
- js_setindex(state, -2, 0);
- js_pushstring(state, r.ctype);
- js_setindex(state, -2, 1);
- js_pushstring(state, r.url);
- js_setindex(state, -2, 2);
- js_pushlstring(state, r.body ? r.body : "", (int)r.len);
- js_setindex(state, -2, 3);
- free(r.body);
- }
- #define JS_STORAGE_MAX (32u * 1024u)
- /* __nb_storage(kind) -> text, __nb_storage(kind, text) stores it. */
- static void nb_storage(js_State *state)
- {
- int kind = js_tointeger(state, 1);
- char *buf;
- int n;
- if (js_isstring(state, 2)) {
- if (host.storage)
- host.storage(kind, js_tostring(state, 2), 0, 0);
- js_pushundefined(state);
- return;
- }
- buf = (char *)malloc(JS_STORAGE_MAX);
- n = buf && host.storage ?
- host.storage(kind, 0, buf, (int)JS_STORAGE_MAX) : -1;
- if (n > 0)
- js_pushlstring(state, buf, n);
- else
- js_pushstring(state, "");
- free(buf);
- }
- static void url_resolve(const char *base, const char *rel,
- char *out, unsigned int cap);
- static void nb_resolve(js_State *state)
- {
- char out[512];
- url_resolve(js_tostring(state, 1), js_tostring(state, 2), out,
- sizeof(out));
- js_pushstring(state, out);
- }
- extern const char js_prelude_source[];
- static void install_prelude(js_State *state)
- {
- js_newcfunction(state, nb_http, "__nb_http", 4);
- js_defglobal(state, "__nb_http", 0);
- js_newcfunction(state, nb_storage, "__nb_storage", 2);
- js_defglobal(state, "__nb_storage", 0);
- js_newcfunction(state, nb_resolve, "__nb_resolve", 2);
- js_defglobal(state, "__nb_resolve", 0);
- js_getregistry(state, "nodeproto");
- js_defglobal(state, "__nb_nodeproto", 0);
- if (js_ploadstring(state, "[prelude]", js_prelude_source)) {
- report_top(state);
- return;
- }
- js_pushundefined(state);
- if (js_pcall(state, 0))
- report_top(state);
- else
- js_pop(state, 1);
- }
- static void install_globals(js_State *state)
- {
- unsigned int h;
- /* Shared prototype of the node/style/dataset wrappers. */
- js_newobject(state);
- js_setregistry(state, "wrapproto");
- /* DOM node wrappers: their own prototype, so the prelude can add the
- * Element methods there without touching style/dataset objects. */
- js_newobject(state);
- js_setregistry(state, "nodeproto");
- js_newobject(state);
- def_func(state, "getElementById", doc_getelementbyid, 1);
- def_func(state, "createElement", doc_create_element, 1);
- def_func(state, "createTextNode", doc_create_text, 1);
- def_func(state, "createComment", doc_create_comment, 1);
- def_func(state, "createDocumentFragment", doc_create_fragment, 0);
- def_func(state, "createAttribute", doc_create_attribute, 1);
- def_func(state, "getElementsByTagName", doc_getelementsbytagname, 1);
- 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_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)
- h = D->nodes[0].first ? D->nodes[0].first + 1 : 0;
- push_node(state, h);
- js_setproperty(state, -2, "documentElement");
- h = br_find_tag(D, BR_TAG_BODY);
- push_node(state, h);
- js_setproperty(state, -2, "body");
- h = br_find_tag(D, BR_TAG_HEAD);
- push_node(state, h);
- js_setproperty(state, -2, "head");
- js_pushnumber(state, 9);
- js_setproperty(state, -2, "nodeType");
- js_pushstring(state, "#document");
- js_setproperty(state, -2, "nodeName");
- js_pushnull(state);
- js_setproperty(state, -2, "ownerDocument");
- js_pushstring(state, "CSS1Compat");
- js_setproperty(state, -2, "compatMode");
- js_pushstring(state, D->title);
- js_setproperty(state, -2, "title");
- js_pushstring(state, "complete");
- js_setproperty(state, -2, "readyState");
- js_pushstring(state, "");
- js_setproperty(state, -2, "cookie");
- js_pushstring(state, current_url ? current_url : "");
- js_setproperty(state, -2, "URL");
- js_defglobal(state, "document", JS_DONTENUM);
- js_newobject(state);
- js_newcfunction(state, console_log, "log", 0);
- js_setproperty(state, -2, "log");
- js_defglobal(state, "console", JS_DONTENUM);
- 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);
- js_newcfunction(state, custom_event_call, "CustomEvent", 1);
- js_defglobal(state, "CustomEvent", JS_DONTENUM);
- js_newcfunction(state, mouse_event_call, "MouseEvent", 1);
- js_defglobal(state, "MouseEvent", JS_DONTENUM);
- push_location(state);
- js_defglobal(state, "location", JS_DONTENUM);
- js_newobject(state);
- js_pushstring(state, "Mozilla/5.0 (X11; Linux i686) NebOS/0.2");
- js_setproperty(state, -2, "userAgent");
- js_pushstring(state, "NebOS");
- js_setproperty(state, -2, "platform");
- js_pushstring(state, "en-US");
- js_setproperty(state, -2, "language");
- js_defglobal(state, "navigator", JS_DONTENUM);
- js_newobject(state);
- js_pushnumber(state, 1);
- js_setproperty(state, -2, "length");
- def_func(state, "pushState", win_noop, 3);
- def_func(state, "replaceState", win_noop, 3);
- def_func(state, "back", win_noop, 0);
- def_func(state, "forward", win_noop, 0);
- def_func(state, "go", win_noop, 1);
- js_defglobal(state, "history", JS_DONTENUM);
- def_global_func(state, "matchMedia", win_matchmedia, 1);
- def_global_func(state, "getComputedStyle", win_getcomputedstyle, 1);
- 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);
- def_global_func(state, "setInterval", win_setinterval, 1);
- def_global_func(state, "clearTimeout", timer_clear, 1);
- def_global_func(state, "clearInterval", timer_clear, 1);
- def_global_func(state, "requestAnimationFrame", win_requestanimationframe, 1);
- def_global_func(state, "cancelAnimationFrame", timer_clear, 1);
- js_newobject(state);
- def_func(state, "now", win_performance_now, 0);
- js_newobject(state);
- js_setproperty(state, -2, "timing");
- js_defglobal(state, "performance", JS_DONTENUM);
- js_pushnumber(state, host.width ? (int)host.width : 1024);
- js_defglobal(state, "innerWidth", JS_DONTENUM);
- js_pushnumber(state, host.height ? (int)host.height : 768);
- js_defglobal(state, "innerHeight", JS_DONTENUM);
- js_pushnumber(state, 0);
- js_defglobal(state, "pageXOffset", JS_DONTENUM);
- js_pushnumber(state, 0);
- js_defglobal(state, "pageYOffset", JS_DONTENUM);
- js_pushnumber(state, 0);
- js_defglobal(state, "scrollX", JS_DONTENUM);
- js_pushnumber(state, 0);
- js_defglobal(state, "scrollY", JS_DONTENUM);
- js_pushnumber(state, 1);
- js_defglobal(state, "devicePixelRatio", JS_DONTENUM);
- js_pushglobal(state);
- js_defglobal(state, "window", JS_DONTENUM);
- js_pushglobal(state);
- js_defglobal(state, "globalThis", JS_DONTENUM);
- js_getglobal(state, "document");
- js_getglobal(state, "location");
- js_setproperty(state, -2, "location");
- js_pop(state, 1);
- js_getglobal(state, "document");
- js_pushglobal(state);
- js_setproperty(state, -2, "defaultView");
- js_pop(state, 1);
- }
- static int module_resolve(const char *base, const char *name, char *out,
- unsigned int cap)
- {
- url_resolve(base && base[0] ? base :
- (current_url ? current_url : ""), name, out, cap);
- return 0;
- }
- static char *module_load(const char *url, unsigned int *len)
- {
- char *src;
- if (!host.load_script)
- return 0;
- src = host.load_script(url, len);
- if (J)
- js_setlimit(J, JS_RUN_LIMIT, 0);
- if (!src && host.report) {
- char msg[600];
- snprintf(msg, sizeof(msg), "Cannot load module %s", url);
- host.report(msg);
- }
- return src;
- }
- int js_browser_start(struct br_doc *doc, const struct js_browser_host *h)
- {
- if (!doc || !h)
- return -1;
- D = doc;
- 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. */
- J = js_newstate(0, 0, 0);
- if (!J)
- return -1;
- js_setreport(J, report_cb);
- js_atpanic(J, panic_cb);
- js_setmodulehost(J, module_resolve, module_load);
- install_globals(J);
- js_setlimit(J, JS_RUN_LIMIT, 0);
- install_prelude(J);
- return 0;
- }
- void js_browser_stop(void)
- {
- if (J)
- js_freestate(J);
- J = 0;
- D = 0;
- current_url = 0;
- panic_armed = 0;
- memset(timers, 0, sizeof(timers));
- }
- int js_browser_active(void)
- {
- return J != 0;
- }
- static void report_top(js_State *state)
- {
- const char *msg;
- /* An "interrupted" error leaves the deadline expired: formatting the
- * error runs JavaScript (toString), which would be interrupted too. */
- js_setlimit(state, 0, 0);
- js_getproperty(state, -1, "stack");
- if (js_isstring(state, -1)) {
- /* QuickJS's stack is only the frames: lead with
- * "Name: message" like the MuJS reports did. */
- char buf[768];
- const char *head = js_trystring(state, -2, "JavaScript error");
- snprintf(buf, sizeof(buf), "%s\n%s", head,
- js_tostring(state, -1));
- msg = buf;
- if (host.report)
- host.report(msg);
- js_pop(state, 1);
- } else {
- js_pop(state, 1);
- msg = js_trystring(state, -1, "JavaScript error");
- if (host.report)
- host.report(msg);
- }
- js_pop(state, 1);
- }
- void js_browser_window_event(const char *type)
- {
- if (J && D)
- js_browser_event(JS_TARGET_WINDOW, type, 0, 0);
- }
- void js_browser_hashchange(void)
- {
- hash_pending = 1;
- }
- void js_browser_tick(void)
- {
- unsigned int now;
- int i, ran = 0;
- if (!J)
- return;
- if (hash_pending) {
- hash_pending = 0;
- js_browser_event(JS_TARGET_WINDOW, "hashchange", 0, 0);
- if (!J)
- return;
- }
- now = u_ticks_ms();
- for (i = 0; i < JS_TIMERS; i++) {
- if (!timers[i].used ||
- (int)(now - timers[i].deadline) < 0)
- continue;
- js_setlimit(J, JS_RUN_LIMIT, 0);
- js_getregistry(J, timers[i].ref);
- if (!js_iscallable(J, -1)) {
- js_pop(J, 1);
- js_unref(J, timers[i].ref);
- timers[i].used = 0;
- continue;
- }
- js_pushundefined(J);
- if (js_pcall(J, 0))
- report_top(J);
- else
- js_pop(J, 1);
- if (timers[i].used) {
- if (timers[i].repeat)
- timers[i].deadline = now + timers[i].interval;
- else {
- js_unref(J, timers[i].ref);
- timers[i].used = 0;
- }
- }
- if (++ran >= 4)
- break;
- }
- js_runjobs(J);
- }
- int js_browser_run(const char *source, const char *url)
- {
- int r;
- if (!J || !D)
- return -1;
- js_setlimit(J, JS_RUN_LIMIT, 0);
- panic_armed = 1;
- if (setjmp(panic_env)) {
- panic_armed = 0;
- if (host.report)
- host.report("uncaught JavaScript exception");
- /* The try/exception stack is unusable after a panic. Leak the
- * state; the page heap reset on navigation reclaims it. */
- J = 0;
- D = 0;
- return -1;
- }
- if (js_ploadstring(J, url ? url : "[inline]", source)) {
- report_top(J);
- panic_armed = 0;
- return -1;
- }
- js_pushundefined(J);
- r = js_pcall(J, 0);
- if (r) {
- report_top(J);
- panic_armed = 0;
- return -1;
- }
- js_pop(J, 1);
- js_runjobs(J);
- panic_armed = 0;
- return 0;
- }
- /* Run a <script type="module">: imports are resolved against `url` and
- * loaded through host.load_script. */
- int js_browser_run_module(const char *source, const char *url)
- {
- if (!J || !D)
- return -1;
- js_setlimit(J, JS_RUN_LIMIT, 0);
- panic_armed = 1;
- if (setjmp(panic_env)) {
- panic_armed = 0;
- if (host.report)
- host.report("uncaught JavaScript exception");
- J = 0;
- D = 0;
- return -1;
- }
- if (js_ploadmodule(J, url ? url : "[module]", source)) {
- report_top(J);
- panic_armed = 0;
- return -1;
- }
- js_pop(J, 1);
- panic_armed = 0;
- return 0;
- }
|