js_browser.c 96 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752
  1. /* Browser bindings for the page JavaScript engine (QuickJS, driven through
  2. * the MuJS-style stack API in js_mu.c): the DOM layer (interned node wrappers,
  3. * attributes, query selectors, classList/dataset/style, innerHTML, timers)
  4. * plus document/window/location/navigator globals. */
  5. #include <setjmp.h>
  6. #include <stdint.h>
  7. #include <stdio.h>
  8. #include <stdlib.h>
  9. #include <string.h>
  10. #include "ucmd_lib.h"
  11. #include "browser_html.h"
  12. #include "js_browser.h"
  13. #include "js_mu.h"
  14. /* Wall-clock budget per script/handler/timer entry, in milliseconds. It is
  15. * reset before every entry; a runaway loop becomes a catchable
  16. * "interrupted" exception instead of a frozen browser. A framework
  17. * bootstrap (AngularJS rendering ~300 cards) needs several seconds on a
  18. * slow CPU, so the budget is generous. */
  19. #define JS_RUN_LIMIT 20000
  20. /* Component frameworks schedule a zero-delay timer per element (heise's
  21. * base component awaits setTimeout(0) in every connectedCallback): a full
  22. * table silently drops timers and those components never start. */
  23. #define JS_TIMERS 1024
  24. #define JS_TIMERS_PER_TICK 32
  25. struct js_timer {
  26. int used;
  27. int repeat;
  28. unsigned int deadline;
  29. unsigned int interval;
  30. char ref[32];
  31. };
  32. static struct js_timer timers[JS_TIMERS];
  33. static js_State *J;
  34. static struct br_doc *D;
  35. static struct js_browser_host host;
  36. static const char *current_url;
  37. static jmp_buf panic_env;
  38. static int panic_armed;
  39. static void report_top(js_State *state);
  40. static void report_cb(js_State *state, const char *message)
  41. {
  42. (void)state;
  43. if (host.report)
  44. host.report(message);
  45. }
  46. static void panic_cb(js_State *state)
  47. {
  48. if (panic_armed)
  49. longjmp(panic_env, 1);
  50. if (js_isobject(state, -1))
  51. report_top(state);
  52. else if (host.report)
  53. host.report(js_trystring(state, -1,
  54. "uncaught JavaScript exception"));
  55. if (host.report)
  56. host.report("uncaught JavaScript exception");
  57. }
  58. static unsigned int node_of(void *p)
  59. {
  60. return (unsigned int)(uintptr_t)p - 1;
  61. }
  62. static int node_has(js_State *state, void *p, const char *name);
  63. static int node_put(js_State *state, void *p, const char *name);
  64. static int node_delete(js_State *state, void *p, const char *name);
  65. static void push_element_url(js_State *state, unsigned int node,
  66. const char *name);
  67. static void rellist_supports(js_State *state);
  68. static void push_query_array(js_State *state, unsigned int root,
  69. const char *selector);
  70. static void node_push_text(js_State *state, unsigned int node);
  71. static void url_resolve(const char *base, const char *rel,
  72. char *out, unsigned int cap);
  73. static int hash_pending;
  74. /* Set by every DOM mutation (host.changed is wrapped): the tick then lets
  75. * the prelude upgrade/connect new Custom Elements. */
  76. static int dom_dirty;
  77. static void (*host_changed_orig)(void);
  78. static void dom_changed(void)
  79. {
  80. dom_dirty = 1;
  81. if (host_changed_orig)
  82. host_changed_orig();
  83. }
  84. static int node_parent_idx(unsigned int node);
  85. /* One wrapper per DOM node: the same element must have the same object
  86. * identity on every access, or library caches (jQuery expando data, Sizzle)
  87. * silently split into disconnected copies. */
  88. static void push_node(js_State *state, unsigned int handle)
  89. {
  90. char key[24];
  91. if (!handle) {
  92. js_pushnull(state);
  93. return;
  94. }
  95. snprintf(key, sizeof(key), "jsonnode_%u", handle);
  96. js_getregistry(state, key);
  97. if (!js_isundefined(state, -1))
  98. return;
  99. js_pop(state, 1);
  100. /* js_newuserdatax() pops a prototype from the top. Wrappers inherit
  101. * from Object.prototype like real DOM nodes (toString/hasOwnProperty;
  102. * Angular calls node.toString() to sniff SVG). */
  103. js_getregistry(state, "nodeproto");
  104. js_newuserdatax(state, "node", (void *)(uintptr_t)handle,
  105. node_has, node_put, node_delete, 0);
  106. js_copy(state, -1);
  107. js_setregistry(state, key);
  108. }
  109. static unsigned int arg_node(js_State *state, int idx)
  110. {
  111. if (!js_isuserdata(state, idx, "node"))
  112. js_typeerror(state, "not a DOM node");
  113. return (unsigned int)(uintptr_t)js_touserdata(state, idx, "node");
  114. }
  115. static void def_func_data(js_State *state, const char *name,
  116. js_CFunction fn, int length, unsigned int handle)
  117. {
  118. js_newcfunctionx(state, fn, name, length,
  119. (void *)(uintptr_t)handle, 0);
  120. js_setproperty(state, -2, name);
  121. }
  122. static void def_func(js_State *state, const char *name,
  123. js_CFunction fn, int length)
  124. {
  125. js_newcfunction(state, fn, name, length);
  126. js_setproperty(state, -2, name);
  127. }
  128. static void def_global_func(js_State *state, const char *name,
  129. js_CFunction fn, int length)
  130. {
  131. js_newcfunction(state, fn, name, length);
  132. js_defglobal(state, name, JS_DONTENUM);
  133. }
  134. static void push_func_data(js_State *state, const char *name,
  135. js_CFunction fn, int length, unsigned int handle)
  136. {
  137. js_newcfunctionx(state, fn, name, length,
  138. (void *)(uintptr_t)handle, 0);
  139. }
  140. static const char *node_attr(unsigned int node, const char *name)
  141. {
  142. return br_find_attr(D, node, name);
  143. }
  144. static void push_attr(js_State *state, unsigned int node, const char *name,
  145. int null_if_missing)
  146. {
  147. const char *s = node_attr(node, name);
  148. if (s)
  149. js_pushstring(state, s);
  150. else if (null_if_missing)
  151. js_pushnull(state);
  152. else
  153. js_pushstring(state, "");
  154. }
  155. static unsigned int node_name(unsigned int node, char *buf, unsigned int cap)
  156. {
  157. struct br_node *n;
  158. const char *s;
  159. unsigned int i = 0;
  160. if (!D || node >= D->nnode || cap == 0)
  161. return 0;
  162. n = &D->nodes[node];
  163. if (n->type == BR_NODE_TEXT)
  164. s = "#text";
  165. else if (n->type == BR_NODE_COMMENT)
  166. s = "#comment";
  167. else if (n->type == BR_NODE_FRAGMENT)
  168. s = "#document-fragment";
  169. else if (n->tag == BR_TAG_UNKNOWN && n->name_off)
  170. s = D->attrs + n->name_off;
  171. else
  172. s = br_tag_name(n->tag);
  173. while (s && *s && i + 1 < cap) {
  174. char c = *s++;
  175. if (c >= 'a' && c <= 'z')
  176. c = (char)(c - 'a' + 'A');
  177. buf[i++] = c;
  178. }
  179. buf[i] = '\0';
  180. return i;
  181. }
  182. /* ---- DOM events ------------------------------------------------------- *
  183. *
  184. * Listeners live in a fixed table, one entry per (target, type, callback)
  185. * registration, and callbacks are retained through the engine registry. The
  186. * dispatcher walks the parent chain for bubbling and runs one listener at a
  187. * time so a handler can safely mutate the tree. `preventDefault` is tracked
  188. * per dispatch in a small event-state table and mirrored onto the event
  189. * object, so a submit handler can cancel the browser's default action. */
  190. #define JS_LISTENERS 256
  191. #define JS_EVENT_SLOTS 8
  192. #define JS_EVENT_TEMPLATES 16
  193. #define JS_TARGET_WINDOW 0xFFFFFFF0u
  194. #define JS_TARGET_DOCUMENT 0xFFFFFFF1u
  195. struct js_listener {
  196. unsigned char used;
  197. unsigned char capture;
  198. unsigned int target;
  199. char type[24];
  200. char ref[32];
  201. };
  202. struct js_event_state {
  203. int used;
  204. int prevented;
  205. int stopped;
  206. int immediate;
  207. char objref[32];
  208. };
  209. struct js_template {
  210. int used;
  211. char ref[32];
  212. };
  213. static struct js_listener listeners[JS_LISTENERS];
  214. static struct js_event_state events[JS_EVENT_SLOTS];
  215. static struct js_template event_templates[JS_EVENT_TEMPLATES];
  216. static void push_event_target(js_State *state, unsigned int target)
  217. {
  218. if (target == JS_TARGET_WINDOW)
  219. js_pushglobal(state);
  220. else if (target == JS_TARGET_DOCUMENT)
  221. js_getglobal(state, "document");
  222. else
  223. push_node(state, target + 1);
  224. }
  225. static void obj_set(js_State *state, int idx, const char *name)
  226. {
  227. /* The value was just pushed, so a negative object index moved down. */
  228. if (idx < 0)
  229. idx--;
  230. js_setproperty(state, idx, name);
  231. }
  232. static void obj_set_string(js_State *state, int idx, const char *name,
  233. const char *value)
  234. {
  235. js_pushstring(state, value ? value : "");
  236. obj_set(state, idx, name);
  237. }
  238. static void obj_set_bool(js_State *state, int idx, const char *name, int value)
  239. {
  240. js_pushboolean(state, value != 0);
  241. obj_set(state, idx, name);
  242. }
  243. static int event_slot(js_State *state)
  244. {
  245. int slot = (int)(uintptr_t)js_currentfunctiondata(state);
  246. if (slot < 0 || slot >= JS_EVENT_SLOTS)
  247. return -1;
  248. return slot;
  249. }
  250. static void event_preventdefault(js_State *state)
  251. {
  252. int slot = event_slot(state);
  253. if (slot >= 0) {
  254. struct js_event_state *ev = &events[slot];
  255. ev->prevented = 1;
  256. if (ev->objref[0]) {
  257. js_getregistry(state, ev->objref);
  258. if (js_isobject(state, -1)) {
  259. js_pushboolean(state, 1);
  260. js_setproperty(state, -2, "defaultPrevented");
  261. }
  262. js_pop(state, 1);
  263. }
  264. }
  265. js_pushundefined(state);
  266. }
  267. static void event_stoppropagation(js_State *state)
  268. {
  269. int slot = event_slot(state);
  270. if (slot >= 0)
  271. events[slot].stopped = 1;
  272. js_pushundefined(state);
  273. }
  274. static void event_stopimmediate(js_State *state)
  275. {
  276. int slot = event_slot(state);
  277. if (slot >= 0) {
  278. events[slot].stopped = 1;
  279. events[slot].immediate = 1;
  280. }
  281. js_pushundefined(state);
  282. }
  283. /* Event-object field helpers. Every dispatch owns a registry key for its
  284. * event object so preventDefault can update the object without access to
  285. * `this` (the stack API has no this accessor). */
  286. static void ev_set_string(js_State *state, int slot, const char *name,
  287. const char *value)
  288. {
  289. js_getregistry(state, events[slot].objref);
  290. js_pushstring(state, value ? value : "");
  291. js_setproperty(state, -2, name);
  292. js_pop(state, 1);
  293. }
  294. static void ev_set_bool(js_State *state, int slot, const char *name, int value)
  295. {
  296. js_getregistry(state, events[slot].objref);
  297. js_pushboolean(state, value != 0);
  298. js_setproperty(state, -2, name);
  299. js_pop(state, 1);
  300. }
  301. static void ev_set_number(js_State *state, int slot, const char *name,
  302. double value)
  303. {
  304. js_getregistry(state, events[slot].objref);
  305. js_pushnumber(state, value);
  306. js_setproperty(state, -2, name);
  307. js_pop(state, 1);
  308. }
  309. static void ev_set_target(js_State *state, int slot, const char *name,
  310. unsigned int target)
  311. {
  312. js_getregistry(state, events[slot].objref);
  313. push_event_target(state, target);
  314. js_setproperty(state, -2, name);
  315. js_pop(state, 1);
  316. }
  317. static int ev_get_bool(js_State *state, int slot, const char *name, int def)
  318. {
  319. int rv = def;
  320. js_getregistry(state, events[slot].objref);
  321. js_getproperty(state, -1, name);
  322. if (js_isboolean(state, -1))
  323. rv = js_toboolean(state, -1);
  324. js_pop(state, 2);
  325. return rv;
  326. }
  327. static void ev_get_string(js_State *state, int slot, const char *name,
  328. char *out, int cap, const char *def)
  329. {
  330. const char *s = def ? def : "";
  331. int n = 0;
  332. js_getregistry(state, events[slot].objref);
  333. js_getproperty(state, -1, name);
  334. if (js_isstring(state, -1))
  335. s = js_tostring(state, -1);
  336. while (s[n] && n + 1 < cap) {
  337. out[n] = s[n];
  338. n++;
  339. }
  340. out[n] = '\0';
  341. js_pop(state, 2);
  342. }
  343. static void event_bind_methods(js_State *state, int slot)
  344. {
  345. js_getregistry(state, events[slot].objref);
  346. def_func_data(state, "preventDefault", event_preventdefault, 0,
  347. (unsigned int)slot);
  348. def_func_data(state, "stopPropagation", event_stoppropagation, 0,
  349. (unsigned int)slot);
  350. def_func_data(state, "stopImmediatePropagation", event_stopimmediate, 0,
  351. (unsigned int)slot);
  352. js_pop(state, 1);
  353. }
  354. /* The event object is on top of the stack; move it into the registry and
  355. * fill in the standard fields. */
  356. static int event_prepare(js_State *state, unsigned int target)
  357. {
  358. int slot;
  359. for (slot = 0; slot < JS_EVENT_SLOTS; slot++)
  360. if (!events[slot].used)
  361. break;
  362. if (slot == JS_EVENT_SLOTS)
  363. return -1;
  364. events[slot].used = 1;
  365. events[slot].prevented = 0;
  366. events[slot].stopped = 0;
  367. events[slot].immediate = 0;
  368. snprintf(events[slot].objref, sizeof(events[slot].objref),
  369. "jseventobj_%d", slot);
  370. js_setregistry(state, events[slot].objref);
  371. ev_set_bool(state, slot, "defaultPrevented", 0);
  372. ev_set_bool(state, slot, "isTrusted", 0);
  373. ev_set_number(state, slot, "timeStamp", (double)u_ticks_ms());
  374. ev_set_target(state, slot, "target", target);
  375. ev_set_target(state, slot, "currentTarget", target);
  376. ev_set_number(state, slot, "eventPhase", 2);
  377. event_bind_methods(state, slot);
  378. return slot;
  379. }
  380. static int listener_call(js_State *state, const struct js_listener *l,
  381. int slot, unsigned int current_target)
  382. {
  383. js_getregistry(state, l->ref);
  384. if (!js_iscallable(state, -1)) {
  385. js_pop(state, 1);
  386. return 0;
  387. }
  388. push_event_target(state, current_target);
  389. js_getregistry(state, events[slot].objref);
  390. if (js_pcall(state, 1)) {
  391. report_top(state);
  392. return 0;
  393. }
  394. js_pop(state, 1);
  395. return 1;
  396. }
  397. static void listener_phase(js_State *state, unsigned int target,
  398. const char *type, int phase, int slot)
  399. {
  400. int i;
  401. for (i = 0; i < JS_LISTENERS; i++) {
  402. struct js_listener *l = &listeners[i];
  403. if (!l->used || l->target != target ||
  404. strcmp(l->type, type) != 0)
  405. continue;
  406. if (phase == 1 && !l->capture)
  407. continue;
  408. if (phase == 2 && l->capture)
  409. continue;
  410. ev_set_target(state, slot, "currentTarget", target);
  411. listener_call(state, l, slot, target);
  412. if (events[slot].immediate)
  413. return;
  414. }
  415. }
  416. /* supplied_idx: 0 creates a fresh object, otherwise it is the argument
  417. * index of an Event supplied by JavaScript. Leaves a boolean result. */
  418. static void inline_attr_decode(const char *s, char *d, unsigned int cap)
  419. {
  420. unsigned int i = 0, n = 0;
  421. while (s && s[i] && n + 1 < cap) {
  422. if (s[i] == '&') {
  423. if (!strncmp(s + i, "&quot;", 6)) {
  424. d[n++] = '"'; i += 6; continue;
  425. }
  426. if (!strncmp(s + i, "&#39;", 5)) {
  427. d[n++] = '\''; i += 5; continue;
  428. }
  429. if (!strncmp(s + i, "&amp;", 5)) {
  430. d[n++] = '&'; i += 5; continue;
  431. }
  432. if (!strncmp(s + i, "&lt;", 4)) {
  433. d[n++] = '<'; i += 4; continue;
  434. }
  435. if (!strncmp(s + i, "&gt;", 4)) {
  436. d[n++] = '>'; i += 4; continue;
  437. }
  438. }
  439. d[n++] = s[i++];
  440. }
  441. d[n] = '\0';
  442. }
  443. /* Inline on<event> attributes run at the target and while bubbling, after
  444. * the registered listeners for that node. The handler gets the event and
  445. * the element as `this`; a false return prevents the default action. */
  446. static void run_inline_handler(js_State *state, unsigned int node,
  447. const char *type, int slot, int *prevented)
  448. {
  449. char name[40], body[512], src[640];
  450. const char *attr;
  451. int truthy;
  452. if (!D || node >= D->nnode || !events[slot].objref[0])
  453. return;
  454. snprintf(name, sizeof(name), "on%s", type);
  455. attr = br_find_attr(D, node, name);
  456. if (!attr || !attr[0])
  457. return;
  458. inline_attr_decode(attr, body, sizeof(body));
  459. snprintf(src, sizeof(src), "(function(event){ %s\n})", body);
  460. if (js_try(state)) {
  461. /* The throw already unwound this try frame. */
  462. js_pop(state, 1);
  463. return;
  464. }
  465. js_loadstring(state, "[inline]", src);
  466. /* The script evaluates the function expression; run it first, then
  467. * call the resulting function with the element as `this`. */
  468. js_pushundefined(state);
  469. if (js_pcall(state, 0) || !js_iscallable(state, -1)) {
  470. js_pop(state, 1);
  471. js_endtry(state);
  472. return;
  473. }
  474. push_node(state, node + 1);
  475. js_getregistry(state, events[slot].objref);
  476. if (js_pcall(state, 1)) {
  477. js_pop(state, 1);
  478. js_endtry(state);
  479. return;
  480. }
  481. truthy = js_toboolean(state, -1);
  482. js_pop(state, 1);
  483. js_endtry(state);
  484. if (!truthy && prevented)
  485. *prevented = 1;
  486. }
  487. static int dispatch_object(js_State *state, unsigned int target,
  488. int supplied_idx, const char *fallback,
  489. int def_bubbles, int def_cancelable)
  490. {
  491. unsigned int path[64];
  492. char type[32];
  493. int np = 0, slot, i, prevented;
  494. if (supplied_idx)
  495. js_copy(state, supplied_idx);
  496. else
  497. js_newobject(state);
  498. slot = event_prepare(state, target);
  499. if (slot < 0) {
  500. js_pushboolean(state, 1);
  501. return 1;
  502. }
  503. ev_get_string(state, slot, "type", type, sizeof(type), fallback);
  504. if (!type[0]) {
  505. js_unref(state, events[slot].objref);
  506. events[slot].objref[0] = '\0';
  507. events[slot].used = 0;
  508. js_pushboolean(state, 1);
  509. return 1;
  510. }
  511. ev_set_string(state, slot, "type", type);
  512. ev_set_bool(state, slot, "bubbles",
  513. ev_get_bool(state, slot, "bubbles", def_bubbles));
  514. ev_set_bool(state, slot, "cancelable",
  515. ev_get_bool(state, slot, "cancelable", def_cancelable));
  516. path[np++] = target;
  517. if (target != JS_TARGET_WINDOW && target != JS_TARGET_DOCUMENT &&
  518. D && target < D->nnode) {
  519. unsigned int cur = target;
  520. int p;
  521. while ((p = node_parent_idx(cur)) >= 0 &&
  522. np < (int)(sizeof(path) / sizeof(path[0]))) {
  523. path[np++] = (unsigned int)p;
  524. cur = (unsigned int)p;
  525. }
  526. }
  527. if (target != JS_TARGET_WINDOW)
  528. path[np++] = JS_TARGET_DOCUMENT;
  529. if (target != JS_TARGET_WINDOW &&
  530. np < (int)(sizeof(path) / sizeof(path[0])))
  531. path[np++] = JS_TARGET_WINDOW;
  532. /* Capture from the outermost ancestor down to the parent. */
  533. for (i = np - 1; i > 0; i--) {
  534. if (events[slot].stopped)
  535. break;
  536. listener_phase(state, path[i], type, 1, slot);
  537. }
  538. /* Target phase: capture and bubble listeners in registration order. */
  539. if (!events[slot].stopped) {
  540. listener_phase(state, path[0], type, 0, slot);
  541. if (!events[slot].stopped)
  542. run_inline_handler(state, path[0], type, slot,
  543. &events[slot].prevented);
  544. }
  545. /* Bubble only for events that ask for it; stopPropagation stops the
  546. * remaining ancestors. */
  547. if (ev_get_bool(state, slot, "bubbles", def_bubbles)) {
  548. for (i = 1; i < np && !events[slot].stopped; i++) {
  549. listener_phase(state, path[i], type, 2, slot);
  550. if (!events[slot].stopped &&
  551. path[i] != JS_TARGET_WINDOW &&
  552. path[i] != JS_TARGET_DOCUMENT)
  553. run_inline_handler(state, path[i], type, slot,
  554. &events[slot].prevented);
  555. }
  556. }
  557. prevented = events[slot].prevented;
  558. js_unref(state, events[slot].objref);
  559. events[slot].objref[0] = '\0';
  560. events[slot].used = 0;
  561. js_pushboolean(state, prevented ? 0 : 1);
  562. return prevented ? 0 : 1;
  563. }
  564. static void add_listener(js_State *state, unsigned int target, int remove)
  565. {
  566. const char *type;
  567. int i;
  568. if (!js_iscallable(state, 2))
  569. return;
  570. type = js_tostring(state, 1);
  571. if (!type[0])
  572. return;
  573. if (!remove) {
  574. for (i = 0; i < JS_LISTENERS; i++)
  575. if (!listeners[i].used)
  576. break;
  577. if (i == JS_LISTENERS)
  578. return;
  579. listeners[i].used = 1;
  580. listeners[i].capture = js_isboolean(state, 3) &&
  581. js_toboolean(state, 3);
  582. listeners[i].target = target;
  583. snprintf(listeners[i].type, sizeof(listeners[i].type), "%s",
  584. type);
  585. js_copy(state, 2);
  586. snprintf(listeners[i].ref, sizeof(listeners[i].ref), "%s",
  587. js_ref(state));
  588. return;
  589. }
  590. for (i = 0; i < JS_LISTENERS; i++) {
  591. struct js_listener *l = &listeners[i];
  592. int eq;
  593. if (!l->used || l->target != target ||
  594. strcmp(l->type, type) != 0)
  595. continue;
  596. js_getregistry(state, l->ref);
  597. js_copy(state, 2);
  598. eq = js_equal(state);
  599. js_pop(state, 2);
  600. if (!eq)
  601. continue;
  602. js_unref(state, l->ref);
  603. l->used = 0;
  604. return;
  605. }
  606. }
  607. static void node_addlistener(js_State *state)
  608. {
  609. unsigned int node = (unsigned int)(uintptr_t)
  610. js_currentfunctiondata(state) - 1;
  611. add_listener(state, node, 0);
  612. }
  613. static void node_removelistener(js_State *state)
  614. {
  615. unsigned int node = (unsigned int)(uintptr_t)
  616. js_currentfunctiondata(state) - 1;
  617. add_listener(state, node, 1);
  618. }
  619. /* document.dispatchEvent / window.dispatchEvent (WebComponentsReady, custom
  620. * app events): the same dispatcher, targeting document or window. */
  621. static void target_dispatchevent(js_State *state, unsigned int target)
  622. {
  623. if (!D || !js_isobject(state, 1)) {
  624. js_pushboolean(state, 1);
  625. return;
  626. }
  627. dispatch_object(state, target, 1, "event", 1, 0);
  628. }
  629. static void doc_dispatchevent(js_State *state)
  630. {
  631. target_dispatchevent(state, JS_TARGET_DOCUMENT);
  632. }
  633. static void win_dispatchevent(js_State *state)
  634. {
  635. target_dispatchevent(state, JS_TARGET_WINDOW);
  636. }
  637. static void node_dispatchevent(js_State *state)
  638. {
  639. unsigned int node = (unsigned int)(uintptr_t)
  640. js_currentfunctiondata(state) - 1;
  641. if (!D || !node) {
  642. js_pushboolean(state, 1);
  643. return;
  644. }
  645. if (js_isobject(state, 1)) {
  646. dispatch_object(state, node, 1, "event", 1, 0);
  647. } else {
  648. char type[32];
  649. const char *s = js_tostring(state, 1);
  650. unsigned int i = 0;
  651. while (s[i] && i + 1 < sizeof(type)) {
  652. type[i] = s[i];
  653. i++;
  654. }
  655. type[i] = '\0';
  656. dispatch_object(state, node, 0, type, 1, 0);
  657. }
  658. }
  659. static void win_addlistener(js_State *state)
  660. {
  661. add_listener(state, JS_TARGET_WINDOW, 0);
  662. }
  663. static void win_removelistener(js_State *state)
  664. {
  665. add_listener(state, JS_TARGET_WINDOW, 1);
  666. }
  667. static void doc_addlistener(js_State *state)
  668. {
  669. add_listener(state, JS_TARGET_DOCUMENT, 0);
  670. }
  671. static void doc_removelistener(js_State *state)
  672. {
  673. add_listener(state, JS_TARGET_DOCUMENT, 1);
  674. }
  675. static void event_init(js_State *state)
  676. {
  677. int slot = (int)(uintptr_t)js_currentfunctiondata(state);
  678. const char *type;
  679. if (slot < 0 || slot >= JS_EVENT_TEMPLATES ||
  680. !event_templates[slot].used)
  681. return;
  682. type = js_tostring(state, 1);
  683. js_getregistry(state, event_templates[slot].ref);
  684. if (!js_isobject(state, -1)) {
  685. js_pop(state, 1);
  686. return;
  687. }
  688. obj_set_string(state, -1, "type", type);
  689. obj_set_bool(state, -1, "bubbles", js_toboolean(state, 2));
  690. obj_set_bool(state, -1, "cancelable", js_toboolean(state, 3));
  691. js_pop(state, 1);
  692. }
  693. static void event_build_object(js_State *state, const char *type,
  694. int bubbles, int cancelable, int with_init)
  695. {
  696. js_newobject(state);
  697. js_pushstring(state, type ? type : "");
  698. js_setproperty(state, -2, "type");
  699. js_pushboolean(state, bubbles != 0);
  700. js_setproperty(state, -2, "bubbles");
  701. js_pushboolean(state, cancelable != 0);
  702. js_setproperty(state, -2, "cancelable");
  703. js_pushboolean(state, 0);
  704. js_setproperty(state, -2, "defaultPrevented");
  705. if (with_init) {
  706. int i;
  707. for (i = 0; i < JS_EVENT_TEMPLATES; i++)
  708. if (!event_templates[i].used)
  709. break;
  710. if (i < JS_EVENT_TEMPLATES) {
  711. event_templates[i].used = 1;
  712. snprintf(event_templates[i].ref,
  713. sizeof(event_templates[i].ref),
  714. "jseventtmpl_%d", i);
  715. js_copy(state, -1);
  716. js_setregistry(state, event_templates[i].ref);
  717. def_func_data(state, "initEvent", event_init, 3,
  718. (unsigned int)i);
  719. }
  720. }
  721. }
  722. static void event_call(js_State *state)
  723. {
  724. const char *type = js_isdefined(state, 1) ? js_tostring(state, 1) : "";
  725. int bubbles = 0, cancelable = 0;
  726. if (js_isobject(state, 2)) {
  727. js_getproperty(state, 2, "bubbles");
  728. bubbles = js_toboolean(state, -1);
  729. js_pop(state, 1);
  730. js_getproperty(state, 2, "cancelable");
  731. cancelable = js_toboolean(state, -1);
  732. js_pop(state, 1);
  733. }
  734. event_build_object(state, type, bubbles, cancelable, 1);
  735. }
  736. static void doc_createevent(js_State *state)
  737. {
  738. const char *type = js_tostring(state, 1);
  739. event_build_object(state, type, 0, 0, 1);
  740. }
  741. static void custom_event_call(js_State *state)
  742. {
  743. event_call(state);
  744. if (js_isobject(state, 2))
  745. js_getproperty(state, 2, "detail");
  746. else
  747. js_pushnull(state);
  748. js_setproperty(state, -2, "detail");
  749. }
  750. static void mouse_event_call(js_State *state)
  751. {
  752. static const struct {
  753. const char *name;
  754. int is_number;
  755. } props[] = {
  756. { "clientX", 1 }, { "clientY", 1 }, { "screenX", 1 },
  757. { "screenY", 1 }, { "button", 1 }, { "buttons", 1 },
  758. { "ctrlKey", 0 }, { "shiftKey", 0 }, { "altKey", 0 },
  759. { "metaKey", 0 }
  760. };
  761. unsigned int i;
  762. event_call(state);
  763. if (!js_isobject(state, 2))
  764. return;
  765. for (i = 0; i < sizeof(props) / sizeof(props[0]); i++) {
  766. js_getproperty(state, 2, props[i].name);
  767. if (props[i].is_number) {
  768. double v = js_isnumber(state, -1) ?
  769. js_tonumber(state, -1) : 0;
  770. js_pop(state, 1);
  771. js_pushnumber(state, v);
  772. } else {
  773. int v = js_toboolean(state, -1);
  774. js_pop(state, 1);
  775. js_pushboolean(state, v);
  776. }
  777. js_setproperty(state, -2, props[i].name);
  778. }
  779. }
  780. int js_browser_event(unsigned int node, const char *type, int bubbles,
  781. int cancelable)
  782. {
  783. int slot, rv;
  784. if (!J || !D)
  785. return 1;
  786. for (slot = 0; slot < JS_EVENT_SLOTS; slot++)
  787. if (!events[slot].used)
  788. break;
  789. if (slot == JS_EVENT_SLOTS)
  790. return 1;
  791. js_setlimit(J, JS_RUN_LIMIT, 0);
  792. rv = dispatch_object(J, node, 0, type, bubbles, cancelable);
  793. js_pop(J, 1);
  794. js_runjobs(J);
  795. return rv;
  796. }
  797. int js_browser_mouse_event(unsigned int node, const char *type,
  798. int bubbles, int related, int x, int y)
  799. {
  800. int slot, rv;
  801. if (!J || !D)
  802. return 1;
  803. for (slot = 0; slot < JS_EVENT_SLOTS; slot++)
  804. if (!events[slot].used)
  805. break;
  806. if (slot == JS_EVENT_SLOTS)
  807. return 1;
  808. js_setlimit(J, JS_RUN_LIMIT, 0);
  809. js_newobject(J);
  810. js_pushnumber(J, x); js_setproperty(J, -2, "clientX");
  811. js_pushnumber(J, y); js_setproperty(J, -2, "clientY");
  812. js_pushnumber(J, x); js_setproperty(J, -2, "pageX");
  813. js_pushnumber(J, y); js_setproperty(J, -2, "pageY");
  814. js_pushnumber(J, x); js_setproperty(J, -2, "screenX");
  815. js_pushnumber(J, y); js_setproperty(J, -2, "screenY");
  816. js_pushnumber(J, 0); js_setproperty(J, -2, "button");
  817. js_pushnumber(J, 0); js_setproperty(J, -2, "buttons");
  818. js_pushnumber(J, 0); js_setproperty(J, -2, "which");
  819. if (related >= 0)
  820. push_node(J, (unsigned int)related + 1);
  821. else
  822. js_pushnull(J);
  823. js_setproperty(J, -2, "relatedTarget");
  824. /* -1: the object on top (index 0 would mean "none supplied"). */
  825. rv = dispatch_object(J, node, -1, type, bubbles, 1);
  826. js_pop(J, 2);
  827. js_runjobs(J);
  828. return rv;
  829. }
  830. static unsigned int node_type_value(unsigned int node)
  831. {
  832. struct br_node *n;
  833. if (!D || node >= D->nnode)
  834. return 0;
  835. n = &D->nodes[node];
  836. if (n->type == BR_NODE_TEXT)
  837. return 3;
  838. if (n->type == BR_NODE_COMMENT)
  839. return 8;
  840. if (n->type == BR_NODE_FRAGMENT)
  841. return 11;
  842. return 1;
  843. }
  844. static void push_child_list(js_State *state, unsigned int node, int elements)
  845. {
  846. struct br_node *n;
  847. unsigned int c, i = 0;
  848. js_newarray(state);
  849. if (!D || node >= D->nnode)
  850. return;
  851. n = &D->nodes[node];
  852. for (c = n->first; c; c = D->nodes[c].next) {
  853. if (elements && D->nodes[c].type != BR_NODE_ELEM)
  854. continue;
  855. push_node(state, c + 1);
  856. js_setindex(state, -2, (int)i++);
  857. }
  858. }
  859. /* The parent element index of an attached node, or -1 when it has none
  860. * (a detached subtree root, or a child of the document). A parent field of
  861. * 0 is ambiguous: node 0 is the tree root, which is the <html> element itself
  862. * when the page starts with one, and detached roots also keep parent 0. */
  863. static int node_parent_idx(unsigned int node)
  864. {
  865. const struct br_node *n;
  866. if (!D || node >= D->nnode)
  867. return -1;
  868. n = &D->nodes[node];
  869. if (n->parent)
  870. return n->parent;
  871. if (node == 0 || (n->flags & BR_NODE_DETACHED))
  872. return -1;
  873. return D->nodes[0].type == BR_NODE_ELEM &&
  874. D->nodes[0].tag == BR_TAG_HTML ? 0 : -1;
  875. }
  876. static unsigned int node_prev_sibling(unsigned int node)
  877. {
  878. unsigned int p, c, prev = 0;
  879. if (!D || node >= D->nnode)
  880. return 0;
  881. p = D->nodes[node].parent;
  882. for (c = D->nodes[p].first; c && c != node; c = D->nodes[c].next)
  883. prev = c;
  884. return prev;
  885. }
  886. /* ---- inline style and dataset objects ---- */
  887. static int ci_eq_n(const char *a, const char *b, unsigned int n)
  888. {
  889. unsigned int i;
  890. for (i = 0; i < n; i++) {
  891. char ca = a[i], cb = b[i];
  892. if (ca >= 'A' && ca <= 'Z')
  893. ca = (char)(ca - 'A' + 'a');
  894. if (cb >= 'A' && cb <= 'Z')
  895. cb = (char)(cb - 'A' + 'a');
  896. if (ca != cb)
  897. return 0;
  898. }
  899. return 1;
  900. }
  901. /* camelCase JS property -> CSS property ("marginTop" -> "margin-top"). */
  902. static void css_name(const char *name, char *out, unsigned int cap)
  903. {
  904. unsigned int n = 0, i;
  905. if (!strcmp(name, "cssFloat")) {
  906. if (cap > 6)
  907. memcpy(out, "float", 6);
  908. else if (cap)
  909. out[0] = '\0';
  910. return;
  911. }
  912. for (i = 0; name[i] && n + 2 < cap; i++) {
  913. char c = name[i];
  914. if (c >= 'A' && c <= 'Z') {
  915. if (n == 0 || out[n - 1] != '-')
  916. out[n++] = '-';
  917. out[n++] = (char)(c - 'A' + 'a');
  918. } else {
  919. out[n++] = c;
  920. }
  921. }
  922. if (cap)
  923. out[n] = '\0';
  924. }
  925. /* camelCase dataset property -> attribute name ("fooBar" -> "data-foo-bar"). */
  926. static void data_name(const char *name, char *out, unsigned int cap)
  927. {
  928. unsigned int n = 0, i;
  929. for (i = 0; i < 5 && n + 1 < cap; i++)
  930. out[n++] = "data-"[i];
  931. for (i = 0; name[i] && n + 2 < cap; i++) {
  932. char c = name[i];
  933. if (c >= 'A' && c <= 'Z') {
  934. out[n++] = '-';
  935. c = (char)(c - 'A' + 'a');
  936. }
  937. out[n++] = c;
  938. }
  939. if (cap)
  940. out[n] = '\0';
  941. }
  942. static int style_lookup(const char *style, const char *prop, char *out,
  943. unsigned int cap)
  944. {
  945. unsigned int i = 0, nl = (unsigned int)strlen(prop);
  946. while (style && style[i]) {
  947. unsigned int ns, ne, vs, ve, a, b, k;
  948. while (style[i] == ' ' || style[i] == ';' || style[i] == '\t')
  949. i++;
  950. if (!style[i])
  951. break;
  952. ns = i;
  953. while (style[i] && style[i] != ':' && style[i] != ';')
  954. i++;
  955. ne = i;
  956. if (style[i] != ':') {
  957. if (style[i] == ';')
  958. i++;
  959. continue;
  960. }
  961. i++;
  962. while (style[i] == ' ' || style[i] == '\t')
  963. i++;
  964. vs = i;
  965. while (style[i] && style[i] != ';')
  966. i++;
  967. ve = i;
  968. a = ns;
  969. b = ne;
  970. while (a < b && (style[a] == ' ' || style[a] == '\t'))
  971. a++;
  972. while (b > a && (style[b - 1] == ' ' || style[b - 1] == '\t'))
  973. b--;
  974. while (ve > vs && (style[ve - 1] == ' ' || style[ve - 1] == '\t'))
  975. ve--;
  976. if (b - a == nl && ci_eq_n(style + a, prop, nl)) {
  977. for (k = 0; k < ve - vs && k + 1 < cap; k++)
  978. out[k] = style[vs + k];
  979. out[k < cap ? k : cap - 1] = '\0';
  980. return 1;
  981. }
  982. }
  983. return 0;
  984. }
  985. static unsigned int style_count(const char *style)
  986. {
  987. unsigned int i = 0, n = 0;
  988. while (style && style[i]) {
  989. while (style[i] == ' ' || style[i] == ';' || style[i] == '\t')
  990. i++;
  991. if (!style[i])
  992. break;
  993. while (style[i] && style[i] != ';')
  994. i++;
  995. n++;
  996. }
  997. return n;
  998. }
  999. static unsigned int style_span(const char *style, unsigned int i)
  1000. {
  1001. while (style[i] == ' ' || style[i] == ';' || style[i] == '\t')
  1002. i++;
  1003. return i;
  1004. }
  1005. static void style_update(unsigned int node, const char *prop,
  1006. const char *value, int remove)
  1007. {
  1008. const char *old = br_find_attr(D, node, "style");
  1009. char arr[512];
  1010. unsigned int n = 0, i = 0, nl = (unsigned int)strlen(prop);
  1011. int replaced = 0;
  1012. if (remove && !old)
  1013. return;
  1014. while (old && old[i] && n + 2 < sizeof(arr)) {
  1015. unsigned int start = style_span(old, i);
  1016. unsigned int ns, ne, ve, a, b, k;
  1017. i = start;
  1018. if (!old[i])
  1019. break;
  1020. ns = i;
  1021. while (old[i] && old[i] != ':' && old[i] != ';')
  1022. i++;
  1023. ne = i;
  1024. if (old[i] == ':') {
  1025. i++;
  1026. while (old[i] == ' ' || old[i] == '\t')
  1027. i++;
  1028. while (old[i] && old[i] != ';')
  1029. i++;
  1030. }
  1031. ve = i;
  1032. a = ns;
  1033. b = ne;
  1034. while (a < b && (old[a] == ' ' || old[a] == '\t'))
  1035. a++;
  1036. while (b > a && (old[b - 1] == ' ' || old[b - 1] == '\t'))
  1037. b--;
  1038. if (b - a == nl && ci_eq_n(old + a, prop, nl)) {
  1039. replaced = 1;
  1040. if (remove || !value || !value[0])
  1041. continue;
  1042. }
  1043. for (k = ns; k < ve && n + 1 < sizeof(arr); k++)
  1044. arr[n++] = old[k];
  1045. if (n + 1 < sizeof(arr))
  1046. arr[n++] = ';';
  1047. }
  1048. if (replaced && (remove || !value || !value[0])) {
  1049. arr[n] = '\0';
  1050. br_set_attr(D, node, "style", arr, n);
  1051. if (host.changed)
  1052. host.changed();
  1053. return;
  1054. }
  1055. if (value && value[0] && n + nl + strlen(value) + 3 < sizeof(arr)) {
  1056. for (i = 0; i < nl; i++)
  1057. arr[n++] = prop[i];
  1058. arr[n++] = ':';
  1059. for (i = 0; value[i]; i++)
  1060. arr[n++] = value[i];
  1061. arr[n++] = ';';
  1062. }
  1063. arr[n] = '\0';
  1064. br_set_attr(D, node, "style", arr, n);
  1065. if (host.changed)
  1066. host.changed();
  1067. }
  1068. static void style_getproperty(js_State *state)
  1069. {
  1070. unsigned int node = node_of(js_currentfunctiondata(state));
  1071. char val[256];
  1072. if (style_lookup(br_find_attr(D, node, "style"),
  1073. js_tostring(state, 1), val, sizeof(val)))
  1074. js_pushstring(state, val);
  1075. else
  1076. js_pushstring(state, "");
  1077. }
  1078. static void style_setproperty(js_State *state)
  1079. {
  1080. unsigned int node = node_of(js_currentfunctiondata(state));
  1081. style_update(node, js_tostring(state, 1),
  1082. js_tostring(state, 2), 0);
  1083. }
  1084. static void style_removeproperty(js_State *state)
  1085. {
  1086. unsigned int node = node_of(js_currentfunctiondata(state));
  1087. const char *prop = js_tostring(state, 1);
  1088. char old[256];
  1089. int had = style_lookup(br_find_attr(D, node, "style"), prop,
  1090. old, sizeof(old));
  1091. style_update(node, prop, "", 1);
  1092. if (had)
  1093. js_pushstring(state, old);
  1094. else
  1095. js_pushstring(state, "");
  1096. }
  1097. static int style_has(js_State *state, void *p, const char *name)
  1098. {
  1099. unsigned int node = node_of(p);
  1100. const char *style;
  1101. char prop[64], val[256];
  1102. if (!D || node >= D->nnode)
  1103. return 0;
  1104. style = br_find_attr(D, node, "style");
  1105. if (!strcmp(name, "cssText")) {
  1106. js_pushstring(state, style ? style : "");
  1107. return 1;
  1108. }
  1109. if (!strcmp(name, "length")) {
  1110. js_pushnumber(state, style_count(style));
  1111. return 1;
  1112. }
  1113. if (!strcmp(name, "getPropertyValue")) {
  1114. push_func_data(state, name, style_getproperty, 1, node + 1);
  1115. return 1;
  1116. }
  1117. if (!strcmp(name, "setProperty")) {
  1118. push_func_data(state, name, style_setproperty, 2, node + 1);
  1119. return 1;
  1120. }
  1121. if (!strcmp(name, "removeProperty")) {
  1122. push_func_data(state, name, style_removeproperty, 1, node + 1);
  1123. return 1;
  1124. }
  1125. css_name(name, prop, sizeof(prop));
  1126. if (style_lookup(style, prop, val, sizeof(val)))
  1127. js_pushstring(state, val);
  1128. else
  1129. js_pushstring(state, "");
  1130. return 1;
  1131. }
  1132. static int style_put(js_State *state, void *p, const char *name)
  1133. {
  1134. unsigned int node = node_of(p);
  1135. const char *value;
  1136. char prop[64];
  1137. if (!D || node >= D->nnode)
  1138. return 0;
  1139. value = js_tostring(state, -1);
  1140. if (!strcmp(name, "cssText")) {
  1141. br_set_attr(D, node, "style", value, (unsigned int)strlen(value));
  1142. if (host.changed)
  1143. host.changed();
  1144. return 1;
  1145. }
  1146. css_name(name, prop, sizeof(prop));
  1147. style_update(node, prop, value, 0);
  1148. return 1;
  1149. }
  1150. static void push_style_object(js_State *state, unsigned int node)
  1151. {
  1152. char key[32];
  1153. snprintf(key, sizeof(key), "sty_%u", node + 1);
  1154. js_getregistry(state, key);
  1155. if (!js_isundefined(state, -1))
  1156. return;
  1157. js_pop(state, 1);
  1158. js_getregistry(state, "wrapproto");
  1159. js_newuserdatax(state, "style", (void *)(uintptr_t)(node + 1),
  1160. style_has, style_put, 0, 0);
  1161. js_copy(state, -1);
  1162. js_setregistry(state, key);
  1163. }
  1164. static int dataset_has(js_State *state, void *p, const char *name)
  1165. {
  1166. unsigned int node = node_of(p);
  1167. char attr[64];
  1168. const char *value;
  1169. if (!D || node >= D->nnode)
  1170. return 0;
  1171. data_name(name, attr, sizeof(attr));
  1172. value = br_find_attr(D, node, attr);
  1173. /* A missing data-* attribute is not a property: answering with
  1174. * undefined made `"x" in el.dataset` true for every name, and
  1175. * google.com's click handler, which looks for the nearest element
  1176. * with `"cthref" in dataset`, navigated every click to "null". */
  1177. if (!value)
  1178. return 0;
  1179. js_pushstring(state, value);
  1180. return 1;
  1181. }
  1182. static int dataset_put(js_State *state, void *p, const char *name)
  1183. {
  1184. unsigned int node = node_of(p);
  1185. char attr[64];
  1186. const char *value = js_tostring(state, -1);
  1187. if (!D || node >= D->nnode)
  1188. return 0;
  1189. data_name(name, attr, sizeof(attr));
  1190. br_set_attr(D, node, attr, value, (unsigned int)strlen(value));
  1191. if (host.changed)
  1192. host.changed();
  1193. return 1;
  1194. }
  1195. static int dataset_delete(js_State *state, void *p, const char *name)
  1196. {
  1197. unsigned int node = node_of(p);
  1198. char attr[64];
  1199. (void)state;
  1200. if (!D || node >= D->nnode)
  1201. return 0;
  1202. data_name(name, attr, sizeof(attr));
  1203. br_remove_attr(D, node, attr);
  1204. if (host.changed)
  1205. host.changed();
  1206. return 1;
  1207. }
  1208. static void push_dataset(js_State *state, unsigned int node)
  1209. {
  1210. char key[32];
  1211. snprintf(key, sizeof(key), "ds_%u", node + 1);
  1212. js_getregistry(state, key);
  1213. if (!js_isundefined(state, -1))
  1214. return;
  1215. js_pop(state, 1);
  1216. js_getregistry(state, "wrapproto");
  1217. js_newuserdatax(state, "dataset", (void *)(uintptr_t)(node + 1),
  1218. dataset_has, dataset_put, dataset_delete, 0);
  1219. js_copy(state, -1);
  1220. js_setregistry(state, key);
  1221. }
  1222. static void node_class_set(unsigned int node, const char *classes)
  1223. {
  1224. br_set_attr(D, node, "class", classes,
  1225. (unsigned int)strlen(classes));
  1226. if (host.changed)
  1227. host.changed();
  1228. }
  1229. static int class_has(const char *classes, const char *name)
  1230. {
  1231. unsigned int i = 0;
  1232. if (!classes)
  1233. return 0;
  1234. while (classes[i]) {
  1235. unsigned int start;
  1236. while (classes[i] == ' ' || classes[i] == '\t')
  1237. i++;
  1238. start = i;
  1239. while (classes[i] && classes[i] != ' ' && classes[i] != '\t')
  1240. i++;
  1241. if (i - start == strlen(name) &&
  1242. !strncmp(classes + start, name, i - start))
  1243. return 1;
  1244. }
  1245. return 0;
  1246. }
  1247. static void class_add(unsigned int node, const char *name, int add)
  1248. {
  1249. const char *old = node_attr(node, "class");
  1250. char buf[2048]; /* BR_CLASS_MAX: Tailwind class lists */
  1251. unsigned int n = 0, i = 0;
  1252. if (add) {
  1253. if (class_has(old, name))
  1254. return;
  1255. if (old && old[0]) {
  1256. while (old[i] && n + 1 < sizeof(buf))
  1257. buf[n++] = old[i++];
  1258. if (n + 1 < sizeof(buf))
  1259. buf[n++] = ' ';
  1260. }
  1261. i = 0;
  1262. while (name[i] && n + 1 < sizeof(buf))
  1263. buf[n++] = name[i++];
  1264. } else {
  1265. if (!old)
  1266. return;
  1267. while (old[i]) {
  1268. unsigned int start;
  1269. while (old[i] == ' ' || old[i] == '\t')
  1270. i++;
  1271. start = i;
  1272. while (old[i] && old[i] != ' ' && old[i] != '\t')
  1273. i++;
  1274. if (i - start == strlen(name) &&
  1275. !strncmp(old + start, name, i - start))
  1276. continue;
  1277. if (n && n + 1 < sizeof(buf))
  1278. buf[n++] = ' ';
  1279. {
  1280. unsigned int k;
  1281. for (k = start; k < i && n + 1 < sizeof(buf);
  1282. k++)
  1283. buf[n++] = old[k];
  1284. }
  1285. }
  1286. }
  1287. buf[n] = '\0';
  1288. node_class_set(node, buf);
  1289. }
  1290. static void node_classlist_add(js_State *state)
  1291. {
  1292. class_add(node_of(js_currentfunctiondata(state)),
  1293. js_tostring(state, 1), 1);
  1294. }
  1295. static void node_classlist_remove(js_State *state)
  1296. {
  1297. class_add(node_of(js_currentfunctiondata(state)),
  1298. js_tostring(state, 1), 0);
  1299. }
  1300. static void node_classlist_toggle(js_State *state)
  1301. {
  1302. unsigned int node = node_of(js_currentfunctiondata(state));
  1303. const char *name = js_tostring(state, 1);
  1304. int has = class_has(node_attr(node, "class"), name);
  1305. int want = !has;
  1306. if (js_isdefined(state, 2))
  1307. want = js_toboolean(state, 2);
  1308. if (want != has)
  1309. class_add(node, name, want);
  1310. js_pushboolean(state, want);
  1311. }
  1312. static void node_classlist_contains(js_State *state)
  1313. {
  1314. unsigned int node = node_of(js_currentfunctiondata(state));
  1315. js_pushboolean(state, class_has(node_attr(node, "class"),
  1316. js_tostring(state, 1)));
  1317. }
  1318. static unsigned int class_count(const char *classes)
  1319. {
  1320. unsigned int i = 0, n = 0;
  1321. if (!classes)
  1322. return 0;
  1323. while (classes[i]) {
  1324. while (classes[i] == ' ' || classes[i] == '\t')
  1325. i++;
  1326. if (!classes[i])
  1327. break;
  1328. n++;
  1329. while (classes[i] && classes[i] != ' ' && classes[i] != '\t')
  1330. i++;
  1331. }
  1332. return n;
  1333. }
  1334. /* ---- innerHTML / outerHTML serialization ---- */
  1335. #define JS_SERIALIZE_MAX (2u * 1024u * 1024u)
  1336. struct sbuf {
  1337. char *p;
  1338. unsigned int n, cap;
  1339. int full;
  1340. };
  1341. static void sb_put(struct sbuf *b, const char *s, unsigned int len)
  1342. {
  1343. if (b->full)
  1344. return;
  1345. if (b->n + len + 1 > b->cap) {
  1346. unsigned int nc = b->cap ? b->cap : 1024;
  1347. char *np;
  1348. while (nc < b->n + len + 1)
  1349. nc *= 2;
  1350. if (nc > JS_SERIALIZE_MAX) {
  1351. b->full = 1;
  1352. return;
  1353. }
  1354. np = (char *)realloc(b->p, nc);
  1355. if (!np) {
  1356. b->full = 1;
  1357. return;
  1358. }
  1359. b->p = np;
  1360. b->cap = nc;
  1361. }
  1362. memcpy(b->p + b->n, s, len);
  1363. b->n += len;
  1364. b->p[b->n] = '\0';
  1365. }
  1366. static void sb_str(struct sbuf *b, const char *s)
  1367. {
  1368. sb_put(b, s, (unsigned int)strlen(s));
  1369. }
  1370. static void sb_escaped(struct sbuf *b, const char *s, unsigned int len,
  1371. int attr)
  1372. {
  1373. unsigned int i, start = 0;
  1374. for (i = 0; i < len; i++) {
  1375. const char *rep = 0;
  1376. if (s[i] == '&')
  1377. rep = "&amp;";
  1378. else if (s[i] == '<' && !attr)
  1379. rep = "&lt;";
  1380. else if (s[i] == '>' && !attr)
  1381. rep = "&gt;";
  1382. else if (s[i] == '"' && attr)
  1383. rep = "&quot;";
  1384. else if ((unsigned char)s[i] == 0xA0)
  1385. rep = "&nbsp;";
  1386. if (!rep)
  1387. continue;
  1388. sb_put(b, s + start, i - start);
  1389. sb_str(b, rep);
  1390. start = i + 1;
  1391. }
  1392. sb_put(b, s + start, len - start);
  1393. }
  1394. static void serialize_node(struct sbuf *b, unsigned int node, int depth);
  1395. static void serialize_children(struct sbuf *b, unsigned int node, int depth)
  1396. {
  1397. unsigned int c;
  1398. for (c = D->nodes[node].first; c && !b->full; c = D->nodes[c].next)
  1399. serialize_node(b, c, depth + 1);
  1400. }
  1401. /* HTML serialization of the parsed tree (lower-case names, quoted
  1402. * attributes, raw text inside script/style, no end tag for void
  1403. * elements). heise reads its JSON config through innerHTML; DOMPurify
  1404. * returns its result the same way. */
  1405. static void serialize_node(struct sbuf *b, unsigned int node, int depth)
  1406. {
  1407. struct br_node *n;
  1408. char name[64];
  1409. unsigned int i;
  1410. const char *p, *end;
  1411. if (!D || node >= D->nnode || depth > 200 || b->full)
  1412. return;
  1413. n = &D->nodes[node];
  1414. if (n->type == BR_NODE_TEXT) {
  1415. unsigned int par = n->parent;
  1416. int raw = par < D->nnode &&
  1417. D->nodes[par].type == BR_NODE_ELEM &&
  1418. (D->nodes[par].tag == BR_TAG_SCRIPT ||
  1419. D->nodes[par].tag == BR_TAG_STYLE ||
  1420. D->nodes[par].tag == BR_TAG_NOSCRIPT);
  1421. if (raw)
  1422. sb_put(b, D->text + n->text_off, n->text_len);
  1423. else
  1424. sb_escaped(b, D->text + n->text_off, n->text_len, 0);
  1425. return;
  1426. }
  1427. if (n->type == BR_NODE_COMMENT) {
  1428. sb_str(b, "<!--");
  1429. sb_put(b, D->text + n->text_off, n->text_len);
  1430. sb_str(b, "-->");
  1431. return;
  1432. }
  1433. if (n->type == BR_NODE_FRAGMENT) {
  1434. serialize_children(b, node, depth);
  1435. return;
  1436. }
  1437. node_name(node, name, sizeof(name));
  1438. for (i = 0; name[i]; i++)
  1439. if (name[i] >= 'A' && name[i] <= 'Z')
  1440. name[i] = (char)(name[i] - 'A' + 'a');
  1441. sb_str(b, "<");
  1442. sb_str(b, name);
  1443. p = D->attrs + n->extra_off;
  1444. end = p + n->extra_len;
  1445. while (n->extra_len && p + 1 < end) {
  1446. const char *an = p, *av;
  1447. p += strlen(p) + 1;
  1448. if (p >= end)
  1449. break;
  1450. av = p;
  1451. p += strlen(p) + 1;
  1452. sb_str(b, " ");
  1453. sb_str(b, an);
  1454. sb_str(b, "=\"");
  1455. sb_escaped(b, av, (unsigned int)strlen(av), 1);
  1456. sb_str(b, "\"");
  1457. }
  1458. sb_str(b, ">");
  1459. if (br_tag_is_void(n->tag) && !n->first)
  1460. return;
  1461. serialize_children(b, node, depth);
  1462. sb_str(b, "</");
  1463. sb_str(b, name);
  1464. sb_str(b, ">");
  1465. }
  1466. static void push_serialized(js_State *state, unsigned int node, int outer)
  1467. {
  1468. struct sbuf b;
  1469. memset(&b, 0, sizeof(b));
  1470. if (outer)
  1471. serialize_node(&b, node, 0);
  1472. else
  1473. serialize_children(&b, node, 0);
  1474. js_pushlstring(state, b.p ? b.p : "", (int)b.n);
  1475. free(b.p);
  1476. }
  1477. static void push_attributes(js_State *state, unsigned int node)
  1478. {
  1479. struct br_node *n;
  1480. const char *p, *end;
  1481. unsigned int count = 0;
  1482. js_newobject(state);
  1483. if (!D || node >= D->nnode)
  1484. return;
  1485. n = &D->nodes[node];
  1486. p = D->attrs + n->extra_off;
  1487. end = p + n->extra_len;
  1488. while (p + 1 < end) {
  1489. const char *an = p;
  1490. const char *av;
  1491. p += strlen(p) + 1;
  1492. if (p >= end)
  1493. break;
  1494. av = p;
  1495. p += strlen(p) + 1;
  1496. js_newobject(state);
  1497. js_pushstring(state, an);
  1498. js_setproperty(state, -2, "name");
  1499. js_pushstring(state, av);
  1500. js_setproperty(state, -2, "value");
  1501. js_pushboolean(state, 1);
  1502. js_setproperty(state, -2, "specified");
  1503. /* Array-like: attributes[i] and attributes[name] both work. */
  1504. js_copy(state, -1);
  1505. js_setproperty(state, -3, an);
  1506. js_setindex(state, -2, (int)count);
  1507. count++;
  1508. }
  1509. js_pushnumber(state, count);
  1510. js_setproperty(state, -2, "length");
  1511. }
  1512. static void push_classlist(js_State *state, unsigned int node)
  1513. {
  1514. js_newobject(state);
  1515. def_func_data(state, "add", node_classlist_add, 1, node + 1);
  1516. def_func_data(state, "remove", node_classlist_remove, 1, node + 1);
  1517. def_func_data(state, "toggle", node_classlist_toggle, 1, node + 1);
  1518. def_func_data(state, "contains", node_classlist_contains, 1, node + 1);
  1519. js_pushnumber(state, class_count(node_attr(node, "class")));
  1520. js_setproperty(state, -2, "length");
  1521. }
  1522. static void node_getattr(js_State *state)
  1523. {
  1524. unsigned int node = node_of(js_currentfunctiondata(state));
  1525. push_attr(state, node, js_tostring(state, 1), 1);
  1526. }
  1527. static void node_setattr(js_State *state)
  1528. {
  1529. unsigned int node = node_of(js_currentfunctiondata(state));
  1530. const char *name = js_tostring(state, 1);
  1531. const char *value = js_tostring(state, 2);
  1532. char lower[64];
  1533. unsigned int i;
  1534. for (i = 0; name[i] && i + 1 < sizeof(lower); i++) {
  1535. char c = name[i];
  1536. if (c >= 'A' && c <= 'Z')
  1537. c = (char)(c - 'A' + 'a');
  1538. lower[i] = c;
  1539. }
  1540. lower[i] = '\0';
  1541. br_set_attr(D, node, lower, value, (unsigned int)strlen(value));
  1542. if (host.changed)
  1543. host.changed();
  1544. }
  1545. static void node_removeattr(js_State *state)
  1546. {
  1547. unsigned int node = node_of(js_currentfunctiondata(state));
  1548. const char *name = js_tostring(state, 1);
  1549. char lower[64];
  1550. unsigned int i;
  1551. for (i = 0; name[i] && i + 1 < sizeof(lower); i++) {
  1552. char c = name[i];
  1553. if (c >= 'A' && c <= 'Z')
  1554. c = (char)(c - 'A' + 'a');
  1555. lower[i] = c;
  1556. }
  1557. lower[i] = '\0';
  1558. br_remove_attr(D, node, lower);
  1559. if (host.changed)
  1560. host.changed();
  1561. }
  1562. static void node_hasattr(js_State *state)
  1563. {
  1564. unsigned int node = node_of(js_currentfunctiondata(state));
  1565. js_pushboolean(state, node_attr(node, js_tostring(state, 1)) != 0);
  1566. }
  1567. static void node_appendchild(js_State *state)
  1568. {
  1569. unsigned int node = node_of(js_currentfunctiondata(state));
  1570. unsigned int child = arg_node(state, 1);
  1571. if (br_append_child(D, node, child) != 0) {
  1572. js_pushnull(state);
  1573. return;
  1574. }
  1575. if (host.changed)
  1576. host.changed();
  1577. push_node(state, child);
  1578. }
  1579. static void node_insertbefore(js_State *state)
  1580. {
  1581. unsigned int node = node_of(js_currentfunctiondata(state));
  1582. unsigned int child = arg_node(state, 1);
  1583. unsigned int before = 0;
  1584. if (!js_isnull(state, 2) && !js_isundefined(state, 2))
  1585. before = arg_node(state, 2);
  1586. if (br_insert_before(D, node, child, before) != 0) {
  1587. js_pushnull(state);
  1588. return;
  1589. }
  1590. if (host.changed)
  1591. host.changed();
  1592. push_node(state, child);
  1593. }
  1594. static void node_removechild(js_State *state)
  1595. {
  1596. unsigned int node = node_of(js_currentfunctiondata(state));
  1597. unsigned int child = arg_node(state, 1);
  1598. if (br_remove_child(D, node, child) != 0) {
  1599. js_pushnull(state);
  1600. return;
  1601. }
  1602. if (host.changed)
  1603. host.changed();
  1604. push_node(state, child);
  1605. }
  1606. static void node_replacechild(js_State *state)
  1607. {
  1608. unsigned int node = node_of(js_currentfunctiondata(state));
  1609. unsigned int child = arg_node(state, 1);
  1610. unsigned int old = arg_node(state, 2);
  1611. br_insert_before(D, node, child, old);
  1612. br_remove_child(D, node, old);
  1613. if (host.changed)
  1614. host.changed();
  1615. push_node(state, old);
  1616. }
  1617. static void node_clone(js_State *state)
  1618. {
  1619. unsigned int node = node_of(js_currentfunctiondata(state));
  1620. unsigned int h = br_clone_node(D, node + 1,
  1621. js_toboolean(state, 1));
  1622. push_node(state, h);
  1623. }
  1624. static void node_contains(js_State *state)
  1625. {
  1626. unsigned int node = node_of(js_currentfunctiondata(state));
  1627. unsigned int other = arg_node(state, 1);
  1628. unsigned int p = other;
  1629. while (1) {
  1630. if (p == node) {
  1631. js_pushboolean(state, 1);
  1632. return;
  1633. }
  1634. if (p == 0)
  1635. break;
  1636. p = D->nodes[p].parent;
  1637. }
  1638. js_pushboolean(state, 0);
  1639. }
  1640. static void node_haschildren(js_State *state)
  1641. {
  1642. unsigned int node = node_of(js_currentfunctiondata(state));
  1643. js_pushboolean(state, node < D->nnode && D->nodes[node].first != 0);
  1644. }
  1645. static void node_remove(js_State *state)
  1646. {
  1647. unsigned int node = node_of(js_currentfunctiondata(state));
  1648. unsigned int parent = node < D->nnode ? D->nodes[node].parent : 0;
  1649. (void)state;
  1650. if (parent)
  1651. br_remove_child(D, parent, node + 1);
  1652. if (host.changed)
  1653. host.changed();
  1654. }
  1655. static void node_matches(js_State *state)
  1656. {
  1657. unsigned int node = node_of(js_currentfunctiondata(state));
  1658. js_pushboolean(state, br_matches(D, node + 1,
  1659. js_tostring(state, 1)));
  1660. }
  1661. static void node_click(js_State *state)
  1662. {
  1663. unsigned int node = node_of(js_currentfunctiondata(state));
  1664. if (host.click)
  1665. host.click(node);
  1666. js_pushundefined(state);
  1667. }
  1668. static void node_getelementsbytagname(js_State *state)
  1669. {
  1670. unsigned int node = node_of(js_currentfunctiondata(state));
  1671. const char *name = js_tostring(state, 1);
  1672. unsigned int out[256];
  1673. unsigned int n = br_query_all(D, node + 1, name, out, 256);
  1674. js_newarray(state);
  1675. for (unsigned int i = 0; i < n; i++) {
  1676. push_node(state, out[i]);
  1677. js_setindex(state, -2, (int)i);
  1678. }
  1679. }
  1680. static void node_getelementsbyclassname(js_State *state)
  1681. {
  1682. unsigned int node = node_of(js_currentfunctiondata(state));
  1683. const char *name = js_tostring(state, 1);
  1684. char sel[256];
  1685. unsigned int n = 0, i = 0;
  1686. unsigned int out[256], count;
  1687. while (name[i] && n + 2 < sizeof(sel)) {
  1688. while (name[i] == ' ')
  1689. i++;
  1690. if (!name[i])
  1691. break;
  1692. sel[n++] = '.';
  1693. while (name[i] && name[i] != ' ' && n + 1 < sizeof(sel))
  1694. sel[n++] = name[i++];
  1695. }
  1696. sel[n] = '\0';
  1697. count = br_query_all(D, node + 1, sel, out, 256);
  1698. js_newarray(state);
  1699. for (i = 0; i < count; i++) {
  1700. push_node(state, out[i]);
  1701. js_setindex(state, -2, (int)i);
  1702. }
  1703. }
  1704. static void node_queryselector(js_State *state)
  1705. {
  1706. unsigned int node = node_of(js_currentfunctiondata(state));
  1707. unsigned int out[1];
  1708. unsigned int n = br_query_all(D, node + 1, js_tostring(state, 1),
  1709. out, 1);
  1710. if (n)
  1711. push_node(state, out[0]);
  1712. else
  1713. js_pushnull(state);
  1714. }
  1715. static void node_queryselectorall(js_State *state)
  1716. {
  1717. unsigned int node = node_of(js_currentfunctiondata(state));
  1718. unsigned int out[256];
  1719. unsigned int n = br_query_all(D, node + 1, js_tostring(state, 1),
  1720. out, 256);
  1721. js_newarray(state);
  1722. for (unsigned int i = 0; i < n; i++) {
  1723. push_node(state, out[i]);
  1724. js_setindex(state, -2, (int)i);
  1725. }
  1726. }
  1727. static void node_getrect(js_State *state)
  1728. {
  1729. unsigned int node = node_of(js_currentfunctiondata(state));
  1730. int x = 0, y = 0, w = 0, h = 0;
  1731. if (host.rect)
  1732. host.rect(node, &x, &y, &w, &h);
  1733. js_newobject(state);
  1734. js_pushnumber(state, y); js_setproperty(state, -2, "top");
  1735. js_pushnumber(state, x); js_setproperty(state, -2, "left");
  1736. js_pushnumber(state, x + w); js_setproperty(state, -2, "right");
  1737. js_pushnumber(state, y + h); js_setproperty(state, -2, "bottom");
  1738. js_pushnumber(state, w); js_setproperty(state, -2, "width");
  1739. js_pushnumber(state, h); js_setproperty(state, -2, "height");
  1740. }
  1741. static void node_noop(js_State *state)
  1742. {
  1743. (void)state;
  1744. }
  1745. static void node_push_text(js_State *state, unsigned int node)
  1746. {
  1747. unsigned int cap = D->text_used + 1;
  1748. char *buf;
  1749. unsigned int len;
  1750. if (cap < 32)
  1751. cap = 32;
  1752. buf = (char *)malloc(cap);
  1753. if (!buf) {
  1754. js_pushstring(state, "");
  1755. return;
  1756. }
  1757. len = br_text_content(D, node, buf, cap);
  1758. js_pushlstring(state, buf, (int)len);
  1759. free(buf);
  1760. }
  1761. static unsigned int node_form_ancestor(unsigned int node)
  1762. {
  1763. while (node && node < D->nnode) {
  1764. if (D->nodes[node].type == BR_NODE_ELEM &&
  1765. D->nodes[node].tag == BR_TAG_FORM)
  1766. return node;
  1767. node = D->nodes[node].parent;
  1768. }
  1769. return 0;
  1770. }
  1771. static void push_form_elements(js_State *state, unsigned int form)
  1772. {
  1773. unsigned int out[128];
  1774. int n = 0, i;
  1775. if (host.form_elements)
  1776. n = host.form_elements(form, out, (int)(sizeof(out) /
  1777. sizeof(out[0])));
  1778. js_newarray(state);
  1779. for (i = 0; i < n; i++) {
  1780. const char *name;
  1781. push_node(state, out[i] + 1);
  1782. js_setindex(state, -2, i);
  1783. name = br_find_attr(D, out[i], "name");
  1784. if (name && name[0]) {
  1785. push_node(state, out[i] + 1);
  1786. js_setproperty(state, -2, name);
  1787. }
  1788. }
  1789. }
  1790. static void form_submit_js(js_State *state)
  1791. {
  1792. unsigned int node = node_of(js_currentfunctiondata(state));
  1793. if (host.form_submit)
  1794. host.form_submit(node);
  1795. }
  1796. static void form_reset_js(js_State *state)
  1797. {
  1798. unsigned int node = node_of(js_currentfunctiondata(state));
  1799. if (host.form_reset)
  1800. host.form_reset(node);
  1801. }
  1802. /* Userdata property hooks: every element wrapper carries node + 1. */
  1803. static int node_has(js_State *state, void *p, const char *name)
  1804. {
  1805. unsigned int node = node_of(p);
  1806. struct br_node *n;
  1807. char buf[64];
  1808. if (!D || node >= D->nnode)
  1809. return 0;
  1810. n = &D->nodes[node];
  1811. if (n->type == BR_NODE_ELEM && n->tag == BR_TAG_FORM) {
  1812. if (!strcmp(name, "elements")) {
  1813. push_form_elements(state, node);
  1814. return 1;
  1815. }
  1816. if (!strcmp(name, "length")) {
  1817. unsigned int out[128];
  1818. int count = 0;
  1819. if (host.form_elements)
  1820. count = host.form_elements(node, out,
  1821. (int)(sizeof(out) / sizeof(out[0])));
  1822. js_pushnumber(state, count);
  1823. return 1;
  1824. }
  1825. if (!strcmp(name, "submit")) {
  1826. push_func_data(state, "submit", form_submit_js, 0,
  1827. node + 1);
  1828. return 1;
  1829. }
  1830. if (!strcmp(name, "reset")) {
  1831. push_func_data(state, "reset", form_reset_js, 0,
  1832. node + 1);
  1833. return 1;
  1834. }
  1835. }
  1836. if (!strcmp(name, "form")) {
  1837. unsigned int f;
  1838. if (n->type == BR_NODE_ELEM && n->tag == BR_TAG_FORM)
  1839. f = 0;
  1840. else
  1841. f = node_form_ancestor(node);
  1842. if (f)
  1843. push_node(state, f + 1);
  1844. else
  1845. js_pushnull(state);
  1846. return 1;
  1847. }
  1848. if (!strcmp(name, "textContent") || !strcmp(name, "innerText")) {
  1849. node_push_text(state, node);
  1850. return 1;
  1851. }
  1852. if (!strcmp(name, "nodeValue")) {
  1853. if (n->type == BR_NODE_TEXT || n->type == BR_NODE_COMMENT)
  1854. js_pushlstring(state, D->text + n->text_off,
  1855. (int)n->text_len);
  1856. else
  1857. js_pushnull(state);
  1858. return 1;
  1859. }
  1860. if (!strcmp(name, "nodeType")) {
  1861. js_pushnumber(state, node_type_value(node));
  1862. return 1;
  1863. }
  1864. if (!strcmp(name, "nodeName") || !strcmp(name, "tagName")) {
  1865. node_name(node, buf, sizeof(buf));
  1866. js_pushstring(state, buf);
  1867. return 1;
  1868. }
  1869. if (!strcmp(name, "parentNode") || !strcmp(name, "parentElement")) {
  1870. int p = node_parent_idx(node);
  1871. if (p >= 0)
  1872. push_node(state, (unsigned int)p + 1);
  1873. else if (name[6] == 'N' && !(n->flags & BR_NODE_DETACHED) &&
  1874. n->type == BR_NODE_ELEM && n->tag == BR_TAG_HTML)
  1875. js_getglobal(state, "document"); /* <html>'s parent */
  1876. else
  1877. js_pushnull(state);
  1878. return 1;
  1879. }
  1880. if (!strcmp(name, "childNodes")) {
  1881. push_child_list(state, node, 0);
  1882. return 1;
  1883. }
  1884. if (!strcmp(name, "children")) {
  1885. push_child_list(state, node, 1);
  1886. return 1;
  1887. }
  1888. if (!strcmp(name, "firstChild")) {
  1889. push_node(state, n->first ? n->first + 1 : 0);
  1890. return 1;
  1891. }
  1892. if (!strcmp(name, "lastChild")) {
  1893. push_node(state, n->last ? n->last + 1 : 0);
  1894. return 1;
  1895. }
  1896. if (!strcmp(name, "firstElementChild") ||
  1897. !strcmp(name, "lastElementChild")) {
  1898. unsigned int c = n->first;
  1899. unsigned int found = 0;
  1900. if (!strcmp(name, "lastElementChild")) {
  1901. for (c = n->first; c; c = D->nodes[c].next)
  1902. if (D->nodes[c].type == BR_NODE_ELEM)
  1903. found = c;
  1904. } else {
  1905. while (c && D->nodes[c].type != BR_NODE_ELEM)
  1906. c = D->nodes[c].next;
  1907. found = c;
  1908. }
  1909. push_node(state, found ? found + 1 : 0);
  1910. return 1;
  1911. }
  1912. if (!strcmp(name, "nextSibling") || !strcmp(name, "nextElementSibling")) {
  1913. unsigned int c = n->next;
  1914. if (!strcmp(name, "nextElementSibling"))
  1915. while (c && D->nodes[c].type != BR_NODE_ELEM)
  1916. c = D->nodes[c].next;
  1917. push_node(state, c ? c + 1 : 0);
  1918. return 1;
  1919. }
  1920. if (!strcmp(name, "previousSibling") ||
  1921. !strcmp(name, "previousElementSibling")) {
  1922. unsigned int c = node_prev_sibling(node);
  1923. if (!strcmp(name, "previousElementSibling"))
  1924. while (c && D->nodes[c].type != BR_NODE_ELEM)
  1925. c = node_prev_sibling(c);
  1926. push_node(state, c ? c + 1 : 0);
  1927. return 1;
  1928. }
  1929. if (!strcmp(name, "childElementCount")) {
  1930. unsigned int c, count = 0;
  1931. for (c = n->first; c; c = D->nodes[c].next)
  1932. if (D->nodes[c].type == BR_NODE_ELEM)
  1933. count++;
  1934. js_pushnumber(state, count);
  1935. return 1;
  1936. }
  1937. if (n->tag == BR_TAG_A || n->tag == BR_TAG_AREA) {
  1938. if (!strcmp(name, "href") || !strcmp(name, "protocol") ||
  1939. !strcmp(name, "host") || !strcmp(name, "hostname") ||
  1940. !strcmp(name, "port") || !strcmp(name, "pathname") ||
  1941. !strcmp(name, "search") || !strcmp(name, "hash") ||
  1942. !strcmp(name, "origin")) {
  1943. push_element_url(state, node, name);
  1944. return 1;
  1945. }
  1946. }
  1947. if (!strcmp(name, "id")) { push_attr(state, node, "id", 0); return 1; }
  1948. if (!strcmp(name, "className")) {
  1949. push_attr(state, node, "class", 0);
  1950. return 1;
  1951. }
  1952. if (!strcmp(name, "href")) { push_attr(state, node, "href", 0); return 1; }
  1953. if (!strcmp(name, "src")) { push_attr(state, node, "src", 0); return 1; }
  1954. if (n->type == BR_NODE_ELEM && n->tag == BR_TAG_SELECT) {
  1955. if (!strcmp(name, "options")) {
  1956. push_query_array(state, node, "option");
  1957. return 1;
  1958. }
  1959. if (!strcmp(name, "multiple")) {
  1960. js_pushboolean(state, node_attr(node, "multiple") != 0);
  1961. return 1;
  1962. }
  1963. }
  1964. /* <canvas>: getContext() and friends from the prelude
  1965. * (__nb_canvas); there is no drawing backend. */
  1966. if (n->type == BR_NODE_ELEM && n->tag == BR_TAG_CANVAS &&
  1967. (!strcmp(name, "getContext") || !strcmp(name, "toDataURL") ||
  1968. !strcmp(name, "toBlob") ||
  1969. !strcmp(name, "transferControlToOffscreen"))) {
  1970. js_getglobal(state, "__nb_canvas");
  1971. js_getproperty(state, -1, name);
  1972. return 1;
  1973. }
  1974. /* <video>/<audio> are placeholder boxes: give them the
  1975. * HTMLMediaElement methods from the prelude (__nb_media) and report a
  1976. * paused, never-loaded element. The global object stays below the
  1977. * method on the stack; the hook result is the top value. */
  1978. if (n->type == BR_NODE_ELEM &&
  1979. (n->tag == BR_TAG_VIDEO || n->tag == BR_TAG_AUDIO)) {
  1980. if (!strcmp(name, "play") || !strcmp(name, "pause") ||
  1981. !strcmp(name, "load") || !strcmp(name, "canPlayType")) {
  1982. js_getglobal(state, "__nb_media");
  1983. js_getproperty(state, -1, name);
  1984. return 1;
  1985. }
  1986. if (!strcmp(name, "paused")) {
  1987. js_pushboolean(state, 1);
  1988. return 1;
  1989. }
  1990. if (!strcmp(name, "readyState")) {
  1991. js_pushnumber(state, 0);
  1992. return 1;
  1993. }
  1994. }
  1995. /* An <option> without a value attribute has its text as value. */
  1996. if (n->type == BR_NODE_ELEM && n->tag == BR_TAG_OPTION &&
  1997. !strcmp(name, "value") && !node_attr(node, "value")) {
  1998. node_push_text(state, node);
  1999. return 1;
  2000. }
  2001. if (!strcmp(name, "value")) {
  2002. char buf[128];
  2003. if (host.form_value && host.form_value(node, buf, sizeof(buf)))
  2004. js_pushstring(state, buf);
  2005. else
  2006. push_attr(state, node, "value", 0);
  2007. return 1;
  2008. }
  2009. if (!strcmp(name, "type")) { push_attr(state, node, "type", 0); return 1; }
  2010. if (!strcmp(name, "name")) { push_attr(state, node, "name", 0); return 1; }
  2011. if (!strcmp(name, "alt")) { push_attr(state, node, "alt", 0); return 1; }
  2012. if (!strcmp(name, "title")) { push_attr(state, node, "title", 0); return 1; }
  2013. if (!strcmp(name, "checked")) {
  2014. int c = host.form_checked ? host.form_checked(node) : -1;
  2015. js_pushboolean(state, c >= 0 ? c : node_attr(node, name) != 0);
  2016. return 1;
  2017. }
  2018. if (!strcmp(name, "selectedIndex")) {
  2019. int c = host.form_selected ? host.form_selected(node) : -1;
  2020. js_pushnumber(state, c >= 0 ? c : 0);
  2021. return 1;
  2022. }
  2023. if (!strcmp(name, "selected")) {
  2024. int c = host.form_selected ? host.form_selected(node) : -1;
  2025. if (c >= 0)
  2026. js_pushboolean(state, c != 0);
  2027. else
  2028. js_pushboolean(state, node_attr(node, name) != 0);
  2029. return 1;
  2030. }
  2031. if (!strcmp(name, "disabled")) {
  2032. js_pushboolean(state, node_attr(node, name) != 0);
  2033. return 1;
  2034. }
  2035. if (!strcmp(name, "style")) {
  2036. push_style_object(state, node);
  2037. return 1;
  2038. }
  2039. if (!strcmp(name, "dataset") || !strcmp(name, "domStringMap")) {
  2040. push_dataset(state, node);
  2041. return 1;
  2042. }
  2043. if (!strcmp(name, "classList")) {
  2044. push_classlist(state, node);
  2045. return 1;
  2046. }
  2047. if (!strcmp(name, "attributes")) {
  2048. push_attributes(state, node);
  2049. return 1;
  2050. }
  2051. if (!strcmp(name, "innerHTML") || !strcmp(name, "outerHTML")) {
  2052. push_serialized(state, node, name[0] == 'o');
  2053. return 1;
  2054. }
  2055. if (!strcmp(name, "ownerDocument")) {
  2056. js_getglobal(state, "document");
  2057. return 1;
  2058. }
  2059. if (!strcmp(name, "localName")) {
  2060. unsigned int i;
  2061. if (n->type != BR_NODE_ELEM) {
  2062. js_pushnull(state);
  2063. return 1;
  2064. }
  2065. node_name(node, buf, sizeof(buf));
  2066. for (i = 0; buf[i]; i++)
  2067. if (buf[i] >= 'A' && buf[i] <= 'Z')
  2068. buf[i] = (char)(buf[i] - 'A' + 'a');
  2069. js_pushstring(state, buf);
  2070. return 1;
  2071. }
  2072. if (!strcmp(name, "namespaceURI")) {
  2073. unsigned int a;
  2074. if (n->type != BR_NODE_ELEM) {
  2075. js_pushnull(state);
  2076. return 1;
  2077. }
  2078. for (a = node; a && a < D->nnode; a = D->nodes[a].parent)
  2079. if (D->nodes[a].type == BR_NODE_ELEM &&
  2080. D->nodes[a].tag == BR_TAG_SVG)
  2081. break;
  2082. js_pushstring(state, a && a < D->nnode ?
  2083. "http://www.w3.org/2000/svg" :
  2084. "http://www.w3.org/1999/xhtml");
  2085. return 1;
  2086. }
  2087. if (!strcmp(name, "isConnected")) {
  2088. /* Connected when the top ancestor hangs off the document root
  2089. * (index 0); script-created subtrees also have parent 0 but
  2090. * are not among the root's children. */
  2091. unsigned int a = node, c;
  2092. int conn = node == 0;
  2093. while (a && a < D->nnode && D->nodes[a].parent)
  2094. a = D->nodes[a].parent;
  2095. for (c = D->nodes[0].first; c && !conn; c = D->nodes[c].next)
  2096. if (c == a)
  2097. conn = 1;
  2098. js_pushboolean(state, conn);
  2099. return 1;
  2100. }
  2101. if (!strcmp(name, "relList")) {
  2102. /* Only supports(): Vite's modulepreload polyfill asks it and
  2103. * otherwise refetches every preloaded module through fetch(). */
  2104. js_newobject(state);
  2105. def_func(state, "supports", rellist_supports, 1);
  2106. return 1;
  2107. }
  2108. if (!strcmp(name, "getAttribute"))
  2109. { push_func_data(state, "getAttribute", node_getattr, 1, node + 1); return 1; }
  2110. if (!strcmp(name, "setAttribute"))
  2111. { push_func_data(state, "setAttribute", node_setattr, 2, node + 1); return 1; }
  2112. if (!strcmp(name, "removeAttribute"))
  2113. { push_func_data(state, "removeAttribute", node_removeattr, 1, node + 1); return 1; }
  2114. if (!strcmp(name, "hasAttribute"))
  2115. { push_func_data(state, "hasAttribute", node_hasattr, 1, node + 1); return 1; }
  2116. if (!strcmp(name, "appendChild"))
  2117. { push_func_data(state, "appendChild", node_appendchild, 1, node + 1); return 1; }
  2118. if (!strcmp(name, "insertBefore"))
  2119. { push_func_data(state, "insertBefore", node_insertbefore, 2, node + 1); return 1; }
  2120. if (!strcmp(name, "removeChild"))
  2121. { push_func_data(state, "removeChild", node_removechild, 1, node + 1); return 1; }
  2122. if (!strcmp(name, "replaceChild"))
  2123. { push_func_data(state, "replaceChild", node_replacechild, 2, node + 1); return 1; }
  2124. if (!strcmp(name, "cloneNode"))
  2125. { push_func_data(state, "cloneNode", node_clone, 1, node + 1); return 1; }
  2126. if (!strcmp(name, "contains"))
  2127. { push_func_data(state, "contains", node_contains, 1, node + 1); return 1; }
  2128. if (!strcmp(name, "hasChildNodes"))
  2129. { push_func_data(state, "hasChildNodes", node_haschildren, 0, node + 1); return 1; }
  2130. if (!strcmp(name, "remove"))
  2131. { push_func_data(state, "remove", node_remove, 0, node + 1); return 1; }
  2132. if (!strcmp(name, "matches") || !strcmp(name, "webkitMatchesSelector") ||
  2133. !strcmp(name, "mozMatchesSelector") ||
  2134. !strcmp(name, "msMatchesSelector"))
  2135. { push_func_data(state, name, node_matches, 1, node + 1); return 1; }
  2136. if (!strcmp(name, "getElementsByTagName"))
  2137. { push_func_data(state, "getElementsByTagName", node_getelementsbytagname, 1, node + 1); return 1; }
  2138. if (!strcmp(name, "getElementsByClassName"))
  2139. { push_func_data(state, "getElementsByClassName", node_getelementsbyclassname, 1, node + 1); return 1; }
  2140. if (!strcmp(name, "querySelector"))
  2141. { push_func_data(state, "querySelector", node_queryselector, 1, node + 1); return 1; }
  2142. if (!strcmp(name, "querySelectorAll"))
  2143. { push_func_data(state, "querySelectorAll", node_queryselectorall, 1, node + 1); return 1; }
  2144. if (!strcmp(name, "addEventListener"))
  2145. { push_func_data(state, "addEventListener", node_addlistener, 2, node + 1); return 1; }
  2146. if (!strcmp(name, "removeEventListener"))
  2147. { push_func_data(state, "removeEventListener", node_removelistener, 2, node + 1); return 1; }
  2148. if (!strcmp(name, "dispatchEvent"))
  2149. { push_func_data(state, "dispatchEvent", node_dispatchevent, 1, node + 1); return 1; }
  2150. if (!strcmp(name, "getBoundingClientRect"))
  2151. { push_func_data(state, "getBoundingClientRect", node_getrect, 0, node + 1); return 1; }
  2152. if (!strcmp(name, "getClientRects")) {
  2153. js_newarray(state);
  2154. return 1;
  2155. }
  2156. if (!strcmp(name, "offsetWidth") || !strcmp(name, "offsetHeight") ||
  2157. !strcmp(name, "clientWidth") || !strcmp(name, "clientHeight") ||
  2158. !strcmp(name, "scrollWidth") || !strcmp(name, "scrollHeight")) {
  2159. int x = 0, y = 0, w = 0, h = 0;
  2160. /* The root element's client size is the viewport: jQuery's
  2161. * $(window).height() reads documentElement.clientHeight, and
  2162. * Bootstrap's tooltip clamps itself to that (0 pushed every
  2163. * tooltip above the page). */
  2164. if (n->type == BR_NODE_ELEM && n->tag == BR_TAG_HTML &&
  2165. (!strcmp(name, "clientWidth") ||
  2166. !strcmp(name, "clientHeight"))) {
  2167. js_pushnumber(state, !strcmp(name, "clientWidth") ?
  2168. (host.width ? (int)host.width : 1024) :
  2169. (host.height ? (int)host.height : 768));
  2170. return 1;
  2171. }
  2172. /* Before the first layout an element has no box; a block's
  2173. * width is then best guessed as the viewport (Vue apps measure
  2174. * offsetWidth on mount and pick a phone layout for 0). A
  2175. * resize event after layout lets them measure again. */
  2176. if (!host.rect || !host.rect(node, &x, &y, &w, &h))
  2177. w = n->type == BR_NODE_ELEM ? (int)host.width : 0;
  2178. js_pushnumber(state, (!strcmp(name, "offsetHeight") ||
  2179. !strcmp(name, "clientHeight") ||
  2180. !strcmp(name, "scrollHeight")) ? h : w);
  2181. return 1;
  2182. }
  2183. if (!strcmp(name, "scrollTop") || !strcmp(name, "scrollLeft")) {
  2184. js_pushnumber(state, 0);
  2185. return 1;
  2186. }
  2187. if (!strcmp(name, "click")) {
  2188. push_func_data(state, "click", node_click, 0, node + 1);
  2189. return 1;
  2190. }
  2191. if (!strcmp(name, "focus") || !strcmp(name, "blur")) {
  2192. push_func_data(state, name, node_noop, 0, node + 1);
  2193. return 1;
  2194. }
  2195. return 0;
  2196. }
  2197. static void node_set_string(unsigned int node, const char *name,
  2198. const char *value)
  2199. {
  2200. br_set_attr(D, node, name, value, (unsigned int)strlen(value));
  2201. if (host.changed)
  2202. host.changed();
  2203. }
  2204. static int node_put(js_State *state, void *p, const char *name)
  2205. {
  2206. unsigned int node = node_of(p);
  2207. if (!D || node >= D->nnode)
  2208. return 0;
  2209. if (!strcmp(name, "textContent") || !strcmp(name, "innerText")) {
  2210. const char *text = js_tostring(state, -1);
  2211. unsigned int len = (unsigned int)strlen(text);
  2212. if (br_set_text_content(D, node, text, len) != 0) {
  2213. if (host.status)
  2214. host.status("Page text arena is full", 1);
  2215. } else if (host.changed) {
  2216. host.changed();
  2217. }
  2218. return 1;
  2219. }
  2220. if (!strcmp(name, "nodeValue")) {
  2221. const char *text = js_tostring(state, -1);
  2222. if (br_set_text_node(D, node, text,
  2223. (unsigned int)strlen(text)) == 0 &&
  2224. host.changed)
  2225. host.changed();
  2226. return 1;
  2227. }
  2228. if (!strcmp(name, "id") || !strcmp(name, "className") ||
  2229. !strcmp(name, "href") || !strcmp(name, "src") ||
  2230. !strcmp(name, "value") || !strcmp(name, "type") ||
  2231. !strcmp(name, "name") || !strcmp(name, "alt") ||
  2232. !strcmp(name, "title")) {
  2233. const char *value = js_tostring(state, -1);
  2234. if (!strcmp(name, "value") && host.form_set_value &&
  2235. host.form_set_value(node, value))
  2236. return 1;
  2237. if (!strcmp(name, "className"))
  2238. node_set_string(node, "class", value);
  2239. else
  2240. node_set_string(node, name, value);
  2241. return 1;
  2242. }
  2243. if (!strcmp(name, "selectedIndex")) {
  2244. if (host.form_set_selected)
  2245. host.form_set_selected(node, js_tointeger(state, -1));
  2246. return 1;
  2247. }
  2248. if (!strcmp(name, "checked") || !strcmp(name, "disabled") ||
  2249. !strcmp(name, "selected")) {
  2250. int b = js_toboolean(state, -1);
  2251. if (!strcmp(name, "checked") && host.form_set_checked &&
  2252. host.form_set_checked(node, b))
  2253. return 1;
  2254. if (!strcmp(name, "selected") && host.form_set_selected &&
  2255. host.form_set_selected(node, b ? 1 : 0))
  2256. return 1;
  2257. if (b)
  2258. br_set_attr(D, node, name, "", 0);
  2259. else
  2260. br_remove_attr(D, node, name);
  2261. if (host.changed)
  2262. host.changed();
  2263. return 1;
  2264. }
  2265. if (!strcmp(name, "innerHTML")) {
  2266. const char *html = js_tostring(state, -1);
  2267. char key[32];
  2268. br_set_inner_html(D, node, html, (unsigned int)strlen(html));
  2269. snprintf(key, sizeof(key), "html_%u", node + 1);
  2270. js_pushstring(state, html);
  2271. js_setregistry(state, key);
  2272. if (host.changed)
  2273. host.changed();
  2274. return 1;
  2275. }
  2276. if (!strcmp(name, "outerHTML")) {
  2277. char key[32];
  2278. snprintf(key, sizeof(key), "html_%u", node + 1);
  2279. js_pushstring(state, js_tostring(state, -1));
  2280. js_setregistry(state, key);
  2281. return 1;
  2282. }
  2283. /* There are no scrollable inner boxes, so an element's scroll offset
  2284. * stays 0; accept the write (jQuery's scrollTop(0) in Bootstrap's
  2285. * modal show) instead of letting the getter make it read-only. */
  2286. if (!strcmp(name, "scrollTop") || !strcmp(name, "scrollLeft"))
  2287. return 1;
  2288. if (!strcmp(name, "style")) {
  2289. if (js_isstring(state, -1))
  2290. node_set_string(node, "style",
  2291. js_tostring(state, -1));
  2292. return 1;
  2293. }
  2294. return 0;
  2295. }
  2296. static int node_delete(js_State *state, void *p, const char *name)
  2297. {
  2298. (void)state;
  2299. (void)p;
  2300. (void)name;
  2301. return 0;
  2302. }
  2303. static void doc_getelementbyid(js_State *state)
  2304. {
  2305. const char *id = js_tostring(state, 1);
  2306. push_node(state, br_find_id(D, id));
  2307. }
  2308. static void console_log(js_State *state)
  2309. {
  2310. int i;
  2311. int n = js_gettop(state);
  2312. for (i = 1; i < n; i++) {
  2313. if (i > 1)
  2314. u_putc(' ');
  2315. u_puts(js_tostring(state, i));
  2316. }
  2317. u_putc('\n');
  2318. }
  2319. static void js_alert(js_State *state)
  2320. {
  2321. char msg[160];
  2322. unsigned int used = 0;
  2323. int i;
  2324. int n = js_gettop(state);
  2325. for (i = 1; i < n; i++) {
  2326. const char *s = js_tostring(state, i);
  2327. unsigned int k;
  2328. if (i > 1 && used + 1 < sizeof(msg))
  2329. msg[used++] = ' ';
  2330. for (k = 0; s[k] && used + 1 < sizeof(msg); k++)
  2331. msg[used++] = s[k];
  2332. }
  2333. msg[used] = '\0';
  2334. if (host.status)
  2335. host.status(msg, 0);
  2336. }
  2337. static void push_query_array(js_State *state, unsigned int root,
  2338. const char *selector)
  2339. {
  2340. unsigned int out[256];
  2341. unsigned int n = br_query_all(D, root, selector, out, 256);
  2342. unsigned int i;
  2343. js_newarray(state);
  2344. for (i = 0; i < n; i++) {
  2345. push_node(state, out[i]);
  2346. js_setindex(state, -2, (int)i);
  2347. }
  2348. }
  2349. static void doc_create_element(js_State *state)
  2350. {
  2351. const char *name = js_tostring(state, 1);
  2352. char lower[32];
  2353. unsigned int i;
  2354. for (i = 0; name[i] && i + 1 < sizeof(lower); i++) {
  2355. char c = name[i];
  2356. if (c >= 'A' && c <= 'Z')
  2357. c = (char)(c - 'A' + 'a');
  2358. lower[i] = c;
  2359. }
  2360. lower[i] = '\0';
  2361. push_node(state, br_create_element(D, lower, i));
  2362. }
  2363. static void doc_create_text(js_State *state)
  2364. {
  2365. const char *text = js_tostring(state, 1);
  2366. push_node(state, br_create_text(D, text, (unsigned int)strlen(text)));
  2367. }
  2368. static void doc_create_comment(js_State *state)
  2369. {
  2370. const char *text = js_tostring(state, 1);
  2371. push_node(state, br_create_comment(D, text, (unsigned int)strlen(text)));
  2372. }
  2373. static void doc_create_fragment(js_State *state)
  2374. {
  2375. push_node(state, br_create_fragment(D));
  2376. }
  2377. static void doc_create_attribute(js_State *state)
  2378. {
  2379. const char *name = js_tostring(state, 1);
  2380. js_newobject(state);
  2381. js_pushstring(state, name);
  2382. js_setproperty(state, -2, "name");
  2383. js_pushstring(state, "");
  2384. js_setproperty(state, -2, "value");
  2385. js_pushboolean(state, 1);
  2386. js_setproperty(state, -2, "specified");
  2387. }
  2388. static void doc_getelementsbytagname(js_State *state)
  2389. {
  2390. push_query_array(state, 0, js_tostring(state, 1));
  2391. }
  2392. static void doc_getelementsbyclassname(js_State *state)
  2393. {
  2394. const char *name = js_tostring(state, 1);
  2395. char sel[256];
  2396. unsigned int n = 0, i = 0;
  2397. while (name[i] && n + 2 < sizeof(sel)) {
  2398. while (name[i] == ' ')
  2399. i++;
  2400. if (!name[i])
  2401. break;
  2402. sel[n++] = '.';
  2403. while (name[i] && name[i] != ' ' && n + 1 < sizeof(sel))
  2404. sel[n++] = name[i++];
  2405. }
  2406. sel[n] = '\0';
  2407. push_query_array(state, 0, sel);
  2408. }
  2409. static void doc_queryselector(js_State *state)
  2410. {
  2411. unsigned int out[1];
  2412. unsigned int n = br_query_all(D, 0, js_tostring(state, 1), out, 1);
  2413. if (n)
  2414. push_node(state, out[0]);
  2415. else
  2416. js_pushnull(state);
  2417. }
  2418. static void doc_queryselectorall(js_State *state)
  2419. {
  2420. push_query_array(state, 0, js_tostring(state, 1));
  2421. }
  2422. static void location_get(js_State *state)
  2423. {
  2424. js_pushstring(state, current_url ? current_url : "");
  2425. }
  2426. /* Length of a URL without its #fragment. */
  2427. static unsigned int url_doc_len(const char *u)
  2428. {
  2429. unsigned int n = 0;
  2430. while (u[n] && u[n] != '#')
  2431. n++;
  2432. return n;
  2433. }
  2434. /* Navigate, or, when only the #fragment changes, stay on the page: the
  2435. * host updates the URL (location.href follows it) and a hashchange event is
  2436. * queued. Hash-routed apps (the Cloudron dashboard) navigate this way; a
  2437. * reload would restart the whole app. */
  2438. static void location_go(const char *url)
  2439. {
  2440. char abs[1024];
  2441. unsigned int n;
  2442. if (!current_url || !url) {
  2443. if (host.navigate && url)
  2444. host.navigate(url);
  2445. return;
  2446. }
  2447. url_resolve(current_url, url, abs, sizeof(abs));
  2448. n = url_doc_len(abs);
  2449. if (host.set_hash && abs[n] == '#' && n == url_doc_len(current_url) &&
  2450. !strncmp(abs, current_url, n)) {
  2451. if (strcmp(abs, current_url) && host.set_hash(abs) == 0)
  2452. hash_pending = 1;
  2453. return;
  2454. }
  2455. if (host.navigate)
  2456. host.navigate(url);
  2457. }
  2458. static void location_set(js_State *state)
  2459. {
  2460. location_go(js_tostring(state, 1));
  2461. }
  2462. /* assign()/replace(): navigate (the history entry is not replaced yet). */
  2463. static void location_assign(js_State *state)
  2464. {
  2465. location_go(js_tostring(state, 1));
  2466. js_pushundefined(state);
  2467. }
  2468. static void location_hash_get(js_State *state)
  2469. {
  2470. const char *h = current_url ? strchr(current_url, '#') : 0;
  2471. js_pushstring(state, h && h[1] ? h : "");
  2472. }
  2473. static void location_hash_set(js_State *state)
  2474. {
  2475. const char *v = js_tostring(state, 1);
  2476. char url[1024];
  2477. unsigned int n;
  2478. if (!current_url)
  2479. return;
  2480. n = url_doc_len(current_url);
  2481. if (n + 2 >= sizeof(url))
  2482. return;
  2483. memcpy(url, current_url, n);
  2484. url[n] = '#';
  2485. snprintf(url + n + 1, sizeof(url) - n - 1, "%s", v[0] == '#' ? v + 1 : v);
  2486. location_go(url);
  2487. }
  2488. static void location_reload(js_State *state)
  2489. {
  2490. if (host.navigate && current_url)
  2491. host.navigate(current_url);
  2492. js_pushundefined(state);
  2493. }
  2494. static void location_tostring(js_State *state)
  2495. {
  2496. js_pushstring(state, current_url ? current_url : "");
  2497. }
  2498. static void win_noop(js_State *state);
  2499. struct loc_parts {
  2500. const char *protocol, *host, *hostname, *port, *path, *search, *hash;
  2501. const char *origin;
  2502. unsigned int protocol_len, host_len, hostname_len, port_len;
  2503. unsigned int path_len, search_len, hash_len, origin_len;
  2504. };
  2505. static void loc_split(const char *u, struct loc_parts *p)
  2506. {
  2507. unsigned int n = (unsigned int)strlen(u), i;
  2508. const char *rest;
  2509. memset(p, 0, sizeof(*p));
  2510. p->path = u;
  2511. p->path_len = n;
  2512. p->origin = "null";
  2513. p->origin_len = 4;
  2514. for (i = 0; i < n; i++)
  2515. if (u[i] == ':')
  2516. break;
  2517. if (i + 2 < n && u[i] == ':' && u[i + 1] == '/' && u[i + 2] == '/') {
  2518. const char *hosts = u + i + 3, *hoste = hosts;
  2519. while (*hoste && *hoste != '/' && *hoste != '?' && *hoste != '#')
  2520. hoste++;
  2521. p->protocol = u;
  2522. p->protocol_len = i + 1;
  2523. p->host = hosts;
  2524. p->host_len = (unsigned int)(hoste - hosts);
  2525. p->hostname = hosts;
  2526. p->hostname_len = p->host_len;
  2527. for (i = 0; i < p->hostname_len; i++)
  2528. if (hosts[i] == ':') {
  2529. p->port = hosts + i + 1;
  2530. p->port_len = p->hostname_len - i - 1;
  2531. p->hostname_len = i;
  2532. break;
  2533. }
  2534. p->origin = u;
  2535. p->origin_len = (unsigned int)(hoste - u);
  2536. rest = hoste;
  2537. } else {
  2538. p->protocol = "file:";
  2539. p->protocol_len = 5;
  2540. rest = u;
  2541. }
  2542. {
  2543. const char *q = rest;
  2544. while (*q && *q != '?' && *q != '#')
  2545. q++;
  2546. p->path = rest;
  2547. p->path_len = (unsigned int)(q - rest);
  2548. if (*q == '?') {
  2549. const char *s = q;
  2550. while (*q && *q != '#')
  2551. q++;
  2552. p->search = s;
  2553. p->search_len = (unsigned int)(q - s);
  2554. }
  2555. if (*q == '#') {
  2556. p->hash = q;
  2557. p->hash_len = (unsigned int)strlen(q);
  2558. }
  2559. }
  2560. }
  2561. static void push_location(js_State *state)
  2562. {
  2563. struct loc_parts p;
  2564. loc_split(current_url ? current_url : "", &p);
  2565. js_newobject(state);
  2566. js_newcfunction(state, location_get, "get href", 0);
  2567. js_newcfunction(state, location_set, "set href", 1);
  2568. js_defaccessor(state, -3, "href", 0);
  2569. #define LOC_FIELD(field) \
  2570. do { \
  2571. js_pushlstring(state, p.field ? p.field : "", \
  2572. p.field ? (int)p.field##_len : 0); \
  2573. js_setproperty(state, -2, #field); \
  2574. } while (0)
  2575. LOC_FIELD(protocol);
  2576. LOC_FIELD(host);
  2577. LOC_FIELD(hostname);
  2578. LOC_FIELD(port);
  2579. js_pushlstring(state, p.path ? p.path : "",
  2580. p.path ? (int)p.path_len : 0);
  2581. js_setproperty(state, -2, "pathname");
  2582. LOC_FIELD(search);
  2583. LOC_FIELD(origin);
  2584. #undef LOC_FIELD
  2585. js_newcfunction(state, location_hash_get, "get hash", 0);
  2586. js_newcfunction(state, location_hash_set, "set hash", 1);
  2587. js_defaccessor(state, -3, "hash", 0);
  2588. js_newcfunction(state, location_reload, "reload", 0);
  2589. js_setproperty(state, -2, "reload");
  2590. js_newcfunction(state, location_assign, "assign", 1);
  2591. js_setproperty(state, -2, "assign");
  2592. js_newcfunction(state, location_assign, "replace", 1);
  2593. js_setproperty(state, -2, "replace");
  2594. js_newcfunction(state, location_tostring, "toString", 0);
  2595. js_setproperty(state, -2, "toString");
  2596. }
  2597. /* ---- URL resolution for <a>/<area> URL properties ---- */
  2598. static int url_has_scheme(const char *s)
  2599. {
  2600. unsigned int i = 1;
  2601. if (!((s[0] >= 'a' && s[0] <= 'z') ||
  2602. (s[0] >= 'A' && s[0] <= 'Z')))
  2603. return 0;
  2604. while (s[i]) {
  2605. char c = s[i];
  2606. if (c == ':')
  2607. return 1;
  2608. if (!((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') ||
  2609. (c >= '0' && c <= '9') || c == '+' || c == '-' ||
  2610. c == '.'))
  2611. return 0;
  2612. i++;
  2613. }
  2614. return 0;
  2615. }
  2616. static void url_put(char *out, unsigned int cap, unsigned int *n,
  2617. const char *s, unsigned int len)
  2618. {
  2619. unsigned int i;
  2620. for (i = 0; i < len && *n + 1 < cap; i++)
  2621. out[(*n)++] = s[i];
  2622. }
  2623. /* Collapse //, /./ and /../ inside the path part of an absolute URL. */
  2624. static void url_normalize(char *url)
  2625. {
  2626. char tmp[1024];
  2627. char *path;
  2628. unsigned int n = 0, i = 0;
  2629. path = strstr(url, "://");
  2630. if (path) {
  2631. path += 3;
  2632. while (*path && *path != '/')
  2633. path++;
  2634. } else {
  2635. path = url;
  2636. }
  2637. if (path[0] != '/')
  2638. return;
  2639. /* The path only: ?query and #fragment are copied verbatim below. */
  2640. while (path[i] && path[i] != '?' && path[i] != '#') {
  2641. unsigned int start;
  2642. while (path[i] == '/')
  2643. i++;
  2644. start = i;
  2645. while (path[i] && path[i] != '/' && path[i] != '?' &&
  2646. path[i] != '#')
  2647. i++;
  2648. if (i == start)
  2649. continue;
  2650. if (i - start == 1 && path[start] == '.')
  2651. continue;
  2652. if (i - start == 2 && path[start] == '.' &&
  2653. path[start + 1] == '.') {
  2654. while (n > 0 && tmp[n - 1] != '/')
  2655. n--;
  2656. if (n > 0)
  2657. n--;
  2658. continue;
  2659. }
  2660. if (n + 1 < sizeof(tmp))
  2661. tmp[n++] = '/';
  2662. while (start < i && n + 1 < sizeof(tmp))
  2663. tmp[n++] = path[start++];
  2664. }
  2665. if (n == 0)
  2666. tmp[n++] = '/';
  2667. else if (i > 0 && path[i - 1] == '/' && n + 1 < sizeof(tmp))
  2668. tmp[n++] = '/'; /* keep "dir/" a directory */
  2669. while (path[i] && n + 1 < sizeof(tmp))
  2670. tmp[n++] = path[i++];
  2671. tmp[n] = '\0';
  2672. memcpy(path, tmp, n + 1);
  2673. }
  2674. static void url_resolve(const char *base, const char *rel,
  2675. char *out, unsigned int cap)
  2676. {
  2677. struct loc_parts bp;
  2678. unsigned int n = 0, i;
  2679. if (cap == 0)
  2680. return;
  2681. if (!rel[0]) {
  2682. url_put(out, cap, &n, base, (unsigned int)strlen(base));
  2683. out[n] = '\0';
  2684. return;
  2685. }
  2686. if (url_has_scheme(rel)) {
  2687. url_put(out, cap, &n, rel, (unsigned int)strlen(rel));
  2688. out[n] = '\0';
  2689. url_normalize(out);
  2690. return;
  2691. }
  2692. loc_split(base, &bp);
  2693. if (rel[0] == '/' && rel[1] == '/') {
  2694. url_put(out, cap, &n, bp.protocol, bp.protocol_len);
  2695. url_put(out, cap, &n, rel, (unsigned int)strlen(rel));
  2696. } else if (rel[0] == '/') {
  2697. url_put(out, cap, &n, bp.protocol, bp.protocol_len);
  2698. url_put(out, cap, &n, "//", 2);
  2699. url_put(out, cap, &n, bp.host, bp.host_len);
  2700. url_put(out, cap, &n, rel, (unsigned int)strlen(rel));
  2701. } else if (rel[0] == '#' || rel[0] == '?') {
  2702. url_put(out, cap, &n, bp.protocol, bp.protocol_len);
  2703. if (bp.host_len || (bp.protocol_len == 5 &&
  2704. bp.protocol[0] == 'f')) {
  2705. url_put(out, cap, &n, "//", 2);
  2706. url_put(out, cap, &n, bp.host, bp.host_len);
  2707. }
  2708. url_put(out, cap, &n, bp.path, bp.path_len);
  2709. if (rel[0] == '#')
  2710. url_put(out, cap, &n, bp.search, bp.search_len);
  2711. url_put(out, cap, &n, rel, (unsigned int)strlen(rel));
  2712. } else {
  2713. const char *dir_end = bp.path;
  2714. for (i = 0; i < bp.path_len; i++)
  2715. if (bp.path[i] == '/')
  2716. dir_end = bp.path + i + 1;
  2717. if (dir_end == bp.path)
  2718. dir_end = bp.path + bp.path_len;
  2719. url_put(out, cap, &n, bp.protocol, bp.protocol_len);
  2720. if (bp.host_len || (bp.protocol_len == 5 &&
  2721. bp.protocol[0] == 'f')) {
  2722. url_put(out, cap, &n, "//", 2);
  2723. url_put(out, cap, &n, bp.host, bp.host_len);
  2724. }
  2725. url_put(out, cap, &n, bp.path,
  2726. (unsigned int)(dir_end - bp.path));
  2727. url_put(out, cap, &n, rel, (unsigned int)strlen(rel));
  2728. }
  2729. out[n] = '\0';
  2730. url_normalize(out);
  2731. }
  2732. /* <a> URL properties are resolved against the page URL, like the DOM. */
  2733. static void push_element_url(js_State *state, unsigned int node,
  2734. const char *name)
  2735. {
  2736. char abs_url[512];
  2737. const char *href = br_find_attr(D, node, "href");
  2738. struct loc_parts p;
  2739. if (!href || !href[0]) {
  2740. js_pushstring(state, "");
  2741. return;
  2742. }
  2743. url_resolve(current_url ? current_url : "/", href,
  2744. abs_url, sizeof(abs_url));
  2745. loc_split(abs_url, &p);
  2746. if (!strcmp(name, "href"))
  2747. js_pushstring(state, abs_url);
  2748. else if (!strcmp(name, "protocol"))
  2749. js_pushlstring(state, p.protocol, (int)p.protocol_len);
  2750. else if (!strcmp(name, "origin"))
  2751. js_pushlstring(state, p.origin ? p.origin : "",
  2752. (int)p.origin_len);
  2753. else if (!strcmp(name, "host"))
  2754. js_pushlstring(state, p.host ? p.host : "", (int)p.host_len);
  2755. else if (!strcmp(name, "hostname"))
  2756. js_pushlstring(state, p.hostname ? p.hostname : "",
  2757. (int)p.hostname_len);
  2758. else if (!strcmp(name, "port"))
  2759. js_pushlstring(state, p.port ? p.port : "", (int)p.port_len);
  2760. else if (!strcmp(name, "pathname"))
  2761. js_pushlstring(state, p.path ? p.path : "", (int)p.path_len);
  2762. else if (!strcmp(name, "search"))
  2763. js_pushlstring(state, p.search ? p.search : "",
  2764. (int)p.search_len);
  2765. else
  2766. js_pushlstring(state, p.hash ? p.hash : "", (int)p.hash_len);
  2767. }
  2768. static void win_noop(js_State *state)
  2769. {
  2770. (void)state;
  2771. }
  2772. static void timer_add(js_State *state, int repeat)
  2773. {
  2774. int i;
  2775. unsigned int ms;
  2776. if (!js_iscallable(state, 1)) {
  2777. js_pushnumber(state, 0);
  2778. return;
  2779. }
  2780. ms = js_isdefined(state, 2) ?
  2781. (unsigned int)js_tointeger(state, 2) : 0;
  2782. if (repeat && ms == 0)
  2783. ms = 1;
  2784. for (i = 0; i < JS_TIMERS; i++)
  2785. if (!timers[i].used)
  2786. break;
  2787. if (i == JS_TIMERS) {
  2788. js_pushnumber(state, 0);
  2789. return;
  2790. }
  2791. js_copy(state, 1);
  2792. snprintf(timers[i].ref, sizeof(timers[i].ref), "%s",
  2793. js_ref(state));
  2794. timers[i].used = 1;
  2795. timers[i].repeat = repeat;
  2796. timers[i].interval = ms;
  2797. timers[i].deadline = u_ticks_ms() + ms;
  2798. js_pushnumber(state, i + 1);
  2799. }
  2800. static void win_settimeout(js_State *state)
  2801. {
  2802. timer_add(state, 0);
  2803. }
  2804. static void win_setinterval(js_State *state)
  2805. {
  2806. timer_add(state, 1);
  2807. }
  2808. static void timer_clear(js_State *state)
  2809. {
  2810. int id = js_tointeger(state, 1);
  2811. if (id >= 1 && id <= JS_TIMERS && timers[id - 1].used) {
  2812. js_unref(state, timers[id - 1].ref);
  2813. timers[id - 1].used = 0;
  2814. }
  2815. }
  2816. static void win_requestanimationframe(js_State *state)
  2817. {
  2818. timer_add(state, 0);
  2819. }
  2820. static void win_performance_now(js_State *state)
  2821. {
  2822. js_pushnumber(state, (double)u_ticks_ms());
  2823. }
  2824. struct computed_prop {
  2825. const char *js;
  2826. const char *css;
  2827. };
  2828. static const struct computed_prop computed_props[] = {
  2829. { "display", "display" }, { "position", "position" },
  2830. { "width", "width" }, { "height", "height" },
  2831. { "color", "color" }, { "backgroundColor", "background-color" },
  2832. { "fill", "fill" }, { "stroke", "stroke" },
  2833. { "fontSize", "font-size" }, { "fontWeight", "font-weight" },
  2834. { "fontStyle", "font-style" }, { "fontFamily", "font-family" },
  2835. { "textAlign", "text-align" }, { "float", "float" },
  2836. { "cssFloat", "float" }, { "clear", "clear" },
  2837. { "opacity", "opacity" }, { "visibility", "visibility" },
  2838. { "overflow", "overflow" }, { "whiteSpace", "white-space" },
  2839. { "textTransform", "text-transform" }, { "boxSizing", "box-sizing" },
  2840. { "lineHeight", "line-height" }, { "zIndex", "z-index" },
  2841. { "top", "top" }, { "left", "left" }, { "right", "right" },
  2842. { "bottom", "bottom" },
  2843. { "marginTop", "margin-top" }, { "marginRight", "margin-right" },
  2844. { "marginBottom", "margin-bottom" }, { "marginLeft", "margin-left" },
  2845. { "paddingTop", "padding-top" }, { "paddingRight", "padding-right" },
  2846. { "paddingBottom", "padding-bottom" },
  2847. { "paddingLeft", "padding-left" },
  2848. { "borderTopWidth", "border-top-width" },
  2849. { "borderRightWidth", "border-right-width" },
  2850. { "borderBottomWidth", "border-bottom-width" },
  2851. { "borderLeftWidth", "border-left-width" },
  2852. { "borderTopColor", "border-top-color" },
  2853. { "borderRightColor", "border-right-color" },
  2854. { "borderBottomColor", "border-bottom-color" },
  2855. { "borderLeftColor", "border-left-color" },
  2856. { "backgroundImage", "background-image" },
  2857. { "backgroundRepeat", "background-repeat" },
  2858. { "backgroundPosition", "background-position" },
  2859. { "backgroundSize", "background-size" },
  2860. { "transform", "transform" },
  2861. { 0, 0 }
  2862. };
  2863. static void computed_get(js_State *state)
  2864. {
  2865. unsigned int node = node_of(js_currentfunctiondata(state));
  2866. const char *prop = js_tostring(state, 1);
  2867. char buf[192];
  2868. if (host.computed && host.computed(node, prop, buf, sizeof(buf)))
  2869. js_pushstring(state, buf);
  2870. else
  2871. js_pushstring(state, "");
  2872. }
  2873. static void win_getcomputedstyle(js_State *state)
  2874. {
  2875. unsigned int node = 0;
  2876. char buf[192];
  2877. int i;
  2878. if (js_isuserdata(state, 1, "node"))
  2879. node = node_of(js_touserdata(state, 1, "node"));
  2880. js_newobject(state);
  2881. def_func_data(state, "getPropertyValue", computed_get, 1, node + 1);
  2882. for (i = 0; computed_props[i].js; i++) {
  2883. if (!host.computed ||
  2884. !host.computed(node, computed_props[i].css, buf,
  2885. sizeof(buf)))
  2886. continue;
  2887. js_pushstring(state, buf);
  2888. js_setproperty(state, -2, computed_props[i].js);
  2889. }
  2890. js_pushstring(state, "");
  2891. js_setproperty(state, -2, "cssText");
  2892. }
  2893. static void win_matchmedia(js_State *state)
  2894. {
  2895. const char *query = js_tostring(state, 1);
  2896. js_newobject(state);
  2897. js_pushboolean(state, br_media_matches(query));
  2898. js_setproperty(state, -2, "matches");
  2899. js_pushstring(state, query);
  2900. js_setproperty(state, -2, "media");
  2901. def_func(state, "addListener", win_noop, 1);
  2902. def_func(state, "removeListener", win_noop, 1);
  2903. def_func(state, "addEventListener", win_noop, 2);
  2904. def_func(state, "removeEventListener", win_noop, 2);
  2905. }
  2906. static void rellist_supports(js_State *state)
  2907. {
  2908. const char *t = js_tostring(state, 1);
  2909. js_pushboolean(state, !strcmp(t, "modulepreload") ||
  2910. !strcmp(t, "preload") || !strcmp(t, "stylesheet"));
  2911. }
  2912. /* ---- primitives for js_prelude.js ---- */
  2913. /* __nb_http(method, url, contentType, body) -> [status, ctype, url, text].
  2914. * Synchronous: the host fetches through its helpers while the script
  2915. * waits. A network failure throws (fetch() turns it into a TypeError). */
  2916. static void nb_http(js_State *state)
  2917. {
  2918. struct js_http_resp r;
  2919. const char *method = js_tostring(state, 1);
  2920. const char *url = js_tostring(state, 2);
  2921. const char *ctype = js_tostring(state, 3);
  2922. const char *body = js_tostring(state, 4);
  2923. char err[96];
  2924. int rv;
  2925. memset(&r, 0, sizeof(r));
  2926. err[0] = '\0';
  2927. rv = host.http ? host.http(method, url, ctype, body,
  2928. (unsigned int)strlen(body), &r, err,
  2929. (int)sizeof(err)) : -1;
  2930. /* The budget covers running JavaScript, not the network wait. */
  2931. js_setlimit(state, JS_RUN_LIMIT, 0);
  2932. if (rv != 0) {
  2933. free(r.body);
  2934. js_typeerror(state, "network error: %s",
  2935. err[0] ? err : "fetch failed");
  2936. }
  2937. js_newarray(state);
  2938. js_pushnumber(state, r.status);
  2939. js_setindex(state, -2, 0);
  2940. js_pushstring(state, r.ctype);
  2941. js_setindex(state, -2, 1);
  2942. js_pushstring(state, r.url);
  2943. js_setindex(state, -2, 2);
  2944. js_pushlstring(state, r.body ? r.body : "", (int)r.len);
  2945. js_setindex(state, -2, 3);
  2946. free(r.body);
  2947. }
  2948. #define JS_STORAGE_MAX (32u * 1024u)
  2949. /* __nb_storage(kind) -> text, __nb_storage(kind, text) stores it. */
  2950. static void nb_storage(js_State *state)
  2951. {
  2952. int kind = js_tointeger(state, 1);
  2953. char *buf;
  2954. int n;
  2955. if (js_isstring(state, 2)) {
  2956. if (host.storage)
  2957. host.storage(kind, js_tostring(state, 2), 0, 0);
  2958. js_pushundefined(state);
  2959. return;
  2960. }
  2961. buf = (char *)malloc(JS_STORAGE_MAX);
  2962. n = buf && host.storage ?
  2963. host.storage(kind, 0, buf, (int)JS_STORAGE_MAX) : -1;
  2964. if (n > 0)
  2965. js_pushlstring(state, buf, n);
  2966. else
  2967. js_pushstring(state, "");
  2968. free(buf);
  2969. }
  2970. static void url_resolve(const char *base, const char *rel,
  2971. char *out, unsigned int cap);
  2972. static void nb_resolve(js_State *state)
  2973. {
  2974. char out[512];
  2975. url_resolve(js_tostring(state, 1), js_tostring(state, 2), out,
  2976. sizeof(out));
  2977. js_pushstring(state, out);
  2978. }
  2979. extern const char js_prelude_source[];
  2980. static void install_prelude(js_State *state)
  2981. {
  2982. js_newcfunction(state, nb_http, "__nb_http", 4);
  2983. js_defglobal(state, "__nb_http", 0);
  2984. js_newcfunction(state, nb_storage, "__nb_storage", 2);
  2985. js_defglobal(state, "__nb_storage", 0);
  2986. js_newcfunction(state, nb_resolve, "__nb_resolve", 2);
  2987. js_defglobal(state, "__nb_resolve", 0);
  2988. js_getregistry(state, "nodeproto");
  2989. js_defglobal(state, "__nb_nodeproto", 0);
  2990. if (js_ploadstring(state, "[prelude]", js_prelude_source)) {
  2991. report_top(state);
  2992. return;
  2993. }
  2994. js_pushundefined(state);
  2995. if (js_pcall(state, 0))
  2996. report_top(state);
  2997. else
  2998. js_pop(state, 1);
  2999. }
  3000. static void install_globals(js_State *state)
  3001. {
  3002. unsigned int h;
  3003. /* Shared prototype of the node/style/dataset wrappers. */
  3004. js_newobject(state);
  3005. js_setregistry(state, "wrapproto");
  3006. /* DOM node wrappers: their own prototype, so the prelude can add the
  3007. * Element methods there without touching style/dataset objects. */
  3008. js_newobject(state);
  3009. js_setregistry(state, "nodeproto");
  3010. js_newobject(state);
  3011. def_func(state, "getElementById", doc_getelementbyid, 1);
  3012. def_func(state, "createElement", doc_create_element, 1);
  3013. def_func(state, "createTextNode", doc_create_text, 1);
  3014. def_func(state, "createComment", doc_create_comment, 1);
  3015. def_func(state, "createDocumentFragment", doc_create_fragment, 0);
  3016. def_func(state, "createAttribute", doc_create_attribute, 1);
  3017. def_func(state, "getElementsByTagName", doc_getelementsbytagname, 1);
  3018. def_func(state, "getElementsByClassName", doc_getelementsbyclassname, 1);
  3019. def_func(state, "querySelector", doc_queryselector, 1);
  3020. def_func(state, "querySelectorAll", doc_queryselectorall, 1);
  3021. def_func(state, "addEventListener", doc_addlistener, 2);
  3022. def_func(state, "removeEventListener", doc_removelistener, 2);
  3023. def_func(state, "dispatchEvent", doc_dispatchevent, 1);
  3024. def_func(state, "createEvent", doc_createevent, 1);
  3025. h = br_find_tag(D, BR_TAG_HTML);
  3026. if (!h && D->nnode > 1)
  3027. h = D->nodes[0].first ? D->nodes[0].first + 1 : 0;
  3028. push_node(state, h);
  3029. js_setproperty(state, -2, "documentElement");
  3030. h = br_find_tag(D, BR_TAG_BODY);
  3031. push_node(state, h);
  3032. js_setproperty(state, -2, "body");
  3033. h = br_find_tag(D, BR_TAG_HEAD);
  3034. push_node(state, h);
  3035. js_setproperty(state, -2, "head");
  3036. js_pushnumber(state, 9);
  3037. js_setproperty(state, -2, "nodeType");
  3038. js_pushstring(state, "#document");
  3039. js_setproperty(state, -2, "nodeName");
  3040. js_pushnull(state);
  3041. js_setproperty(state, -2, "ownerDocument");
  3042. js_pushstring(state, "CSS1Compat");
  3043. js_setproperty(state, -2, "compatMode");
  3044. js_pushstring(state, D->title);
  3045. js_setproperty(state, -2, "title");
  3046. js_pushstring(state, "complete");
  3047. js_setproperty(state, -2, "readyState");
  3048. js_pushnull(state);
  3049. js_setproperty(state, -2, "currentScript");
  3050. js_pushstring(state, "");
  3051. js_setproperty(state, -2, "cookie");
  3052. js_pushstring(state, current_url ? current_url : "");
  3053. js_setproperty(state, -2, "URL");
  3054. js_defglobal(state, "document", JS_DONTENUM);
  3055. js_newobject(state);
  3056. js_newcfunction(state, console_log, "log", 0);
  3057. js_setproperty(state, -2, "log");
  3058. js_defglobal(state, "console", JS_DONTENUM);
  3059. js_newcfunction(state, js_alert, "alert", 1);
  3060. js_defglobal(state, "alert", JS_DONTENUM);
  3061. js_newcfunction(state, event_call, "Event", 1);
  3062. js_defglobal(state, "Event", JS_DONTENUM);
  3063. js_newcfunction(state, custom_event_call, "CustomEvent", 1);
  3064. js_defglobal(state, "CustomEvent", JS_DONTENUM);
  3065. js_newcfunction(state, mouse_event_call, "MouseEvent", 1);
  3066. js_defglobal(state, "MouseEvent", JS_DONTENUM);
  3067. push_location(state);
  3068. js_defglobal(state, "location", JS_DONTENUM);
  3069. js_newobject(state);
  3070. js_pushstring(state, "Mozilla/5.0 (X11; Linux i686) NebOS/0.2");
  3071. js_setproperty(state, -2, "userAgent");
  3072. js_pushstring(state, "NebOS");
  3073. js_setproperty(state, -2, "platform");
  3074. js_pushstring(state, "en-US");
  3075. js_setproperty(state, -2, "language");
  3076. js_defglobal(state, "navigator", JS_DONTENUM);
  3077. js_newobject(state);
  3078. js_pushnumber(state, 1);
  3079. js_setproperty(state, -2, "length");
  3080. def_func(state, "pushState", win_noop, 3);
  3081. def_func(state, "replaceState", win_noop, 3);
  3082. def_func(state, "back", win_noop, 0);
  3083. def_func(state, "forward", win_noop, 0);
  3084. def_func(state, "go", win_noop, 1);
  3085. js_defglobal(state, "history", JS_DONTENUM);
  3086. def_global_func(state, "matchMedia", win_matchmedia, 1);
  3087. def_global_func(state, "getComputedStyle", win_getcomputedstyle, 1);
  3088. def_global_func(state, "addEventListener", win_addlistener, 2);
  3089. def_global_func(state, "removeEventListener", win_removelistener, 2);
  3090. def_global_func(state, "dispatchEvent", win_dispatchevent, 1);
  3091. def_global_func(state, "scrollTo", win_noop, 2);
  3092. def_global_func(state, "scrollBy", win_noop, 2);
  3093. def_global_func(state, "setTimeout", win_settimeout, 1);
  3094. def_global_func(state, "setInterval", win_setinterval, 1);
  3095. def_global_func(state, "clearTimeout", timer_clear, 1);
  3096. def_global_func(state, "clearInterval", timer_clear, 1);
  3097. def_global_func(state, "requestAnimationFrame", win_requestanimationframe, 1);
  3098. def_global_func(state, "cancelAnimationFrame", timer_clear, 1);
  3099. js_newobject(state);
  3100. def_func(state, "now", win_performance_now, 0);
  3101. js_newobject(state);
  3102. js_setproperty(state, -2, "timing");
  3103. js_defglobal(state, "performance", JS_DONTENUM);
  3104. js_pushnumber(state, host.width ? (int)host.width : 1024);
  3105. js_defglobal(state, "innerWidth", JS_DONTENUM);
  3106. js_pushnumber(state, host.height ? (int)host.height : 768);
  3107. js_defglobal(state, "innerHeight", JS_DONTENUM);
  3108. js_pushnumber(state, 0);
  3109. js_defglobal(state, "pageXOffset", JS_DONTENUM);
  3110. js_pushnumber(state, 0);
  3111. js_defglobal(state, "pageYOffset", JS_DONTENUM);
  3112. js_pushnumber(state, 0);
  3113. js_defglobal(state, "scrollX", JS_DONTENUM);
  3114. js_pushnumber(state, 0);
  3115. js_defglobal(state, "scrollY", JS_DONTENUM);
  3116. js_pushnumber(state, 1);
  3117. js_defglobal(state, "devicePixelRatio", JS_DONTENUM);
  3118. js_pushglobal(state);
  3119. js_defglobal(state, "window", JS_DONTENUM);
  3120. js_pushglobal(state);
  3121. js_defglobal(state, "globalThis", JS_DONTENUM);
  3122. js_getglobal(state, "document");
  3123. js_getglobal(state, "location");
  3124. js_setproperty(state, -2, "location");
  3125. js_pop(state, 1);
  3126. js_getglobal(state, "document");
  3127. js_pushglobal(state);
  3128. js_setproperty(state, -2, "defaultView");
  3129. js_pop(state, 1);
  3130. }
  3131. static int module_resolve(const char *base, const char *name, char *out,
  3132. unsigned int cap)
  3133. {
  3134. url_resolve(base && base[0] ? base :
  3135. (current_url ? current_url : ""), name, out, cap);
  3136. return 0;
  3137. }
  3138. static char *module_load(const char *url, unsigned int *len)
  3139. {
  3140. char *src;
  3141. if (!host.load_script)
  3142. return 0;
  3143. src = host.load_script(url, len);
  3144. if (J)
  3145. js_setlimit(J, JS_RUN_LIMIT, 0);
  3146. if (!src && host.report) {
  3147. char msg[600];
  3148. snprintf(msg, sizeof(msg), "Cannot load module %s", url);
  3149. host.report(msg);
  3150. }
  3151. return src;
  3152. }
  3153. int js_browser_start(struct br_doc *doc, const struct js_browser_host *h)
  3154. {
  3155. if (!doc || !h)
  3156. return -1;
  3157. D = doc;
  3158. host = *h;
  3159. host_changed_orig = host.changed;
  3160. host.changed = dom_changed;
  3161. dom_dirty = 0;
  3162. current_url = h->page_url;
  3163. panic_armed = 0;
  3164. memset(timers, 0, sizeof(timers));
  3165. memset(listeners, 0, sizeof(listeners));
  3166. memset(events, 0, sizeof(events));
  3167. memset(event_templates, 0, sizeof(event_templates));
  3168. /* Classic scripts are sloppy by default in browsers; strict mode is
  3169. * opt-in via a "use strict" directive. */
  3170. J = js_newstate(0, 0, 0);
  3171. if (!J)
  3172. return -1;
  3173. js_setreport(J, report_cb);
  3174. js_atpanic(J, panic_cb);
  3175. js_setmodulehost(J, module_resolve, module_load);
  3176. install_globals(J);
  3177. js_setlimit(J, JS_RUN_LIMIT, 0);
  3178. install_prelude(J);
  3179. return 0;
  3180. }
  3181. void js_browser_stop(void)
  3182. {
  3183. if (J)
  3184. js_freestate(J);
  3185. J = 0;
  3186. D = 0;
  3187. current_url = 0;
  3188. panic_armed = 0;
  3189. memset(timers, 0, sizeof(timers));
  3190. }
  3191. int js_browser_active(void)
  3192. {
  3193. return J != 0;
  3194. }
  3195. static void report_top(js_State *state)
  3196. {
  3197. const char *msg;
  3198. /* An "interrupted" error leaves the deadline expired: formatting the
  3199. * error runs JavaScript (toString), which would be interrupted too. */
  3200. js_setlimit(state, 0, 0);
  3201. js_getproperty(state, -1, "stack");
  3202. if (js_isstring(state, -1)) {
  3203. /* QuickJS's stack is only the frames: lead with
  3204. * "Name: message" like the MuJS reports did. */
  3205. char buf[768];
  3206. const char *head = js_trystring(state, -2, "JavaScript error");
  3207. snprintf(buf, sizeof(buf), "%s\n%s", head,
  3208. js_tostring(state, -1));
  3209. msg = buf;
  3210. if (host.report)
  3211. host.report(msg);
  3212. js_pop(state, 1);
  3213. } else {
  3214. js_pop(state, 1);
  3215. msg = js_trystring(state, -1, "JavaScript error");
  3216. if (host.report)
  3217. host.report(msg);
  3218. }
  3219. js_pop(state, 1);
  3220. }
  3221. void js_browser_window_event(const char *type)
  3222. {
  3223. if (J && D)
  3224. js_browser_event(JS_TARGET_WINDOW, type, 0, 0);
  3225. }
  3226. void js_browser_hashchange(void)
  3227. {
  3228. hash_pending = 1;
  3229. }
  3230. void js_browser_tick(void)
  3231. {
  3232. unsigned int now;
  3233. int i, ran = 0;
  3234. if (!J)
  3235. return;
  3236. if (hash_pending) {
  3237. hash_pending = 0;
  3238. js_browser_event(JS_TARGET_WINDOW, "hashchange", 0, 0);
  3239. if (!J)
  3240. return;
  3241. }
  3242. if (dom_dirty) {
  3243. dom_dirty = 0;
  3244. js_setlimit(J, JS_RUN_LIMIT, 0);
  3245. js_getglobal(J, "__nb_ce_scan");
  3246. if (js_iscallable(J, -1)) {
  3247. js_pushundefined(J);
  3248. if (js_pcall(J, 0))
  3249. report_top(J);
  3250. else
  3251. js_pop(J, 1);
  3252. } else {
  3253. js_pop(J, 1);
  3254. }
  3255. if (!J)
  3256. return;
  3257. }
  3258. now = u_ticks_ms();
  3259. for (i = 0; i < JS_TIMERS; i++) {
  3260. if (!timers[i].used ||
  3261. (int)(now - timers[i].deadline) < 0)
  3262. continue;
  3263. js_setlimit(J, JS_RUN_LIMIT, 0);
  3264. js_getregistry(J, timers[i].ref);
  3265. if (!js_iscallable(J, -1)) {
  3266. js_pop(J, 1);
  3267. js_unref(J, timers[i].ref);
  3268. timers[i].used = 0;
  3269. continue;
  3270. }
  3271. js_pushundefined(J);
  3272. if (js_pcall(J, 0))
  3273. report_top(J);
  3274. else
  3275. js_pop(J, 1);
  3276. if (timers[i].used) {
  3277. if (timers[i].repeat)
  3278. timers[i].deadline = now + timers[i].interval;
  3279. else {
  3280. js_unref(J, timers[i].ref);
  3281. timers[i].used = 0;
  3282. }
  3283. }
  3284. if (++ran >= JS_TIMERS_PER_TICK)
  3285. break;
  3286. }
  3287. js_runjobs(J);
  3288. }
  3289. void js_browser_set_current_script(unsigned int node)
  3290. {
  3291. if (!J || !D)
  3292. return;
  3293. js_getglobal(J, "document");
  3294. if (node && node < D->nnode)
  3295. push_node(J, node);
  3296. else
  3297. js_pushnull(J);
  3298. js_setproperty(J, -2, "currentScript");
  3299. js_pop(J, 1);
  3300. }
  3301. int js_browser_run(const char *source, const char *url)
  3302. {
  3303. int r;
  3304. if (!J || !D)
  3305. return -1;
  3306. js_setlimit(J, JS_RUN_LIMIT, 0);
  3307. panic_armed = 1;
  3308. if (setjmp(panic_env)) {
  3309. panic_armed = 0;
  3310. if (host.report)
  3311. host.report("uncaught JavaScript exception");
  3312. /* The try/exception stack is unusable after a panic. Leak the
  3313. * state; the page heap reset on navigation reclaims it. */
  3314. J = 0;
  3315. D = 0;
  3316. return -1;
  3317. }
  3318. if (js_ploadstring(J, url ? url : "[inline]", source)) {
  3319. report_top(J);
  3320. panic_armed = 0;
  3321. return -1;
  3322. }
  3323. js_pushundefined(J);
  3324. r = js_pcall(J, 0);
  3325. if (r) {
  3326. report_top(J);
  3327. panic_armed = 0;
  3328. return -1;
  3329. }
  3330. js_pop(J, 1);
  3331. js_runjobs(J);
  3332. panic_armed = 0;
  3333. return 0;
  3334. }
  3335. /* Run a <script type="module">: imports are resolved against `url` and
  3336. * loaded through host.load_script. */
  3337. int js_browser_run_module(const char *source, const char *url)
  3338. {
  3339. if (!J || !D)
  3340. return -1;
  3341. js_setlimit(J, JS_RUN_LIMIT, 0);
  3342. panic_armed = 1;
  3343. if (setjmp(panic_env)) {
  3344. panic_armed = 0;
  3345. if (host.report)
  3346. host.report("uncaught JavaScript exception");
  3347. J = 0;
  3348. D = 0;
  3349. return -1;
  3350. }
  3351. if (js_ploadmodule(J, url ? url : "[module]", source)) {
  3352. report_top(J);
  3353. panic_armed = 0;
  3354. return -1;
  3355. }
  3356. js_pop(J, 1);
  3357. panic_armed = 0;
  3358. return 0;
  3359. }