js_browser.c 93 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665
  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. static unsigned int node_type_value(unsigned int node)
  798. {
  799. struct br_node *n;
  800. if (!D || node >= D->nnode)
  801. return 0;
  802. n = &D->nodes[node];
  803. if (n->type == BR_NODE_TEXT)
  804. return 3;
  805. if (n->type == BR_NODE_COMMENT)
  806. return 8;
  807. if (n->type == BR_NODE_FRAGMENT)
  808. return 11;
  809. return 1;
  810. }
  811. static void push_child_list(js_State *state, unsigned int node, int elements)
  812. {
  813. struct br_node *n;
  814. unsigned int c, i = 0;
  815. js_newarray(state);
  816. if (!D || node >= D->nnode)
  817. return;
  818. n = &D->nodes[node];
  819. for (c = n->first; c; c = D->nodes[c].next) {
  820. if (elements && D->nodes[c].type != BR_NODE_ELEM)
  821. continue;
  822. push_node(state, c + 1);
  823. js_setindex(state, -2, (int)i++);
  824. }
  825. }
  826. /* The parent element index of an attached node, or -1 when it has none
  827. * (a detached subtree root, or a child of the document). A parent field of
  828. * 0 is ambiguous: node 0 is the tree root, which is the <html> element itself
  829. * when the page starts with one, and detached roots also keep parent 0. */
  830. static int node_parent_idx(unsigned int node)
  831. {
  832. const struct br_node *n;
  833. if (!D || node >= D->nnode)
  834. return -1;
  835. n = &D->nodes[node];
  836. if (n->parent)
  837. return n->parent;
  838. if (node == 0 || (n->flags & BR_NODE_DETACHED))
  839. return -1;
  840. return D->nodes[0].type == BR_NODE_ELEM &&
  841. D->nodes[0].tag == BR_TAG_HTML ? 0 : -1;
  842. }
  843. static unsigned int node_prev_sibling(unsigned int node)
  844. {
  845. unsigned int p, c, prev = 0;
  846. if (!D || node >= D->nnode)
  847. return 0;
  848. p = D->nodes[node].parent;
  849. for (c = D->nodes[p].first; c && c != node; c = D->nodes[c].next)
  850. prev = c;
  851. return prev;
  852. }
  853. /* ---- inline style and dataset objects ---- */
  854. static int ci_eq_n(const char *a, const char *b, unsigned int n)
  855. {
  856. unsigned int i;
  857. for (i = 0; i < n; i++) {
  858. char ca = a[i], cb = b[i];
  859. if (ca >= 'A' && ca <= 'Z')
  860. ca = (char)(ca - 'A' + 'a');
  861. if (cb >= 'A' && cb <= 'Z')
  862. cb = (char)(cb - 'A' + 'a');
  863. if (ca != cb)
  864. return 0;
  865. }
  866. return 1;
  867. }
  868. /* camelCase JS property -> CSS property ("marginTop" -> "margin-top"). */
  869. static void css_name(const char *name, char *out, unsigned int cap)
  870. {
  871. unsigned int n = 0, i;
  872. if (!strcmp(name, "cssFloat")) {
  873. if (cap > 6)
  874. memcpy(out, "float", 6);
  875. else if (cap)
  876. out[0] = '\0';
  877. return;
  878. }
  879. for (i = 0; name[i] && n + 2 < cap; i++) {
  880. char c = name[i];
  881. if (c >= 'A' && c <= 'Z') {
  882. if (n == 0 || out[n - 1] != '-')
  883. out[n++] = '-';
  884. out[n++] = (char)(c - 'A' + 'a');
  885. } else {
  886. out[n++] = c;
  887. }
  888. }
  889. if (cap)
  890. out[n] = '\0';
  891. }
  892. /* camelCase dataset property -> attribute name ("fooBar" -> "data-foo-bar"). */
  893. static void data_name(const char *name, char *out, unsigned int cap)
  894. {
  895. unsigned int n = 0, i;
  896. for (i = 0; i < 5 && n + 1 < cap; i++)
  897. out[n++] = "data-"[i];
  898. for (i = 0; name[i] && n + 2 < cap; i++) {
  899. char c = name[i];
  900. if (c >= 'A' && c <= 'Z') {
  901. out[n++] = '-';
  902. c = (char)(c - 'A' + 'a');
  903. }
  904. out[n++] = c;
  905. }
  906. if (cap)
  907. out[n] = '\0';
  908. }
  909. static int style_lookup(const char *style, const char *prop, char *out,
  910. unsigned int cap)
  911. {
  912. unsigned int i = 0, nl = (unsigned int)strlen(prop);
  913. while (style && style[i]) {
  914. unsigned int ns, ne, vs, ve, a, b, k;
  915. while (style[i] == ' ' || style[i] == ';' || style[i] == '\t')
  916. i++;
  917. if (!style[i])
  918. break;
  919. ns = i;
  920. while (style[i] && style[i] != ':' && style[i] != ';')
  921. i++;
  922. ne = i;
  923. if (style[i] != ':') {
  924. if (style[i] == ';')
  925. i++;
  926. continue;
  927. }
  928. i++;
  929. while (style[i] == ' ' || style[i] == '\t')
  930. i++;
  931. vs = i;
  932. while (style[i] && style[i] != ';')
  933. i++;
  934. ve = i;
  935. a = ns;
  936. b = ne;
  937. while (a < b && (style[a] == ' ' || style[a] == '\t'))
  938. a++;
  939. while (b > a && (style[b - 1] == ' ' || style[b - 1] == '\t'))
  940. b--;
  941. while (ve > vs && (style[ve - 1] == ' ' || style[ve - 1] == '\t'))
  942. ve--;
  943. if (b - a == nl && ci_eq_n(style + a, prop, nl)) {
  944. for (k = 0; k < ve - vs && k + 1 < cap; k++)
  945. out[k] = style[vs + k];
  946. out[k < cap ? k : cap - 1] = '\0';
  947. return 1;
  948. }
  949. }
  950. return 0;
  951. }
  952. static unsigned int style_count(const char *style)
  953. {
  954. unsigned int i = 0, n = 0;
  955. while (style && style[i]) {
  956. while (style[i] == ' ' || style[i] == ';' || style[i] == '\t')
  957. i++;
  958. if (!style[i])
  959. break;
  960. while (style[i] && style[i] != ';')
  961. i++;
  962. n++;
  963. }
  964. return n;
  965. }
  966. static unsigned int style_span(const char *style, unsigned int i)
  967. {
  968. while (style[i] == ' ' || style[i] == ';' || style[i] == '\t')
  969. i++;
  970. return i;
  971. }
  972. static void style_update(unsigned int node, const char *prop,
  973. const char *value, int remove)
  974. {
  975. const char *old = br_find_attr(D, node, "style");
  976. char arr[512];
  977. unsigned int n = 0, i = 0, nl = (unsigned int)strlen(prop);
  978. int replaced = 0;
  979. if (remove && !old)
  980. return;
  981. while (old && old[i] && n + 2 < sizeof(arr)) {
  982. unsigned int start = style_span(old, i);
  983. unsigned int ns, ne, ve, a, b, k;
  984. i = start;
  985. if (!old[i])
  986. break;
  987. ns = i;
  988. while (old[i] && old[i] != ':' && old[i] != ';')
  989. i++;
  990. ne = i;
  991. if (old[i] == ':') {
  992. i++;
  993. while (old[i] == ' ' || old[i] == '\t')
  994. i++;
  995. while (old[i] && old[i] != ';')
  996. i++;
  997. }
  998. ve = i;
  999. a = ns;
  1000. b = ne;
  1001. while (a < b && (old[a] == ' ' || old[a] == '\t'))
  1002. a++;
  1003. while (b > a && (old[b - 1] == ' ' || old[b - 1] == '\t'))
  1004. b--;
  1005. if (b - a == nl && ci_eq_n(old + a, prop, nl)) {
  1006. replaced = 1;
  1007. if (remove || !value || !value[0])
  1008. continue;
  1009. }
  1010. for (k = ns; k < ve && n + 1 < sizeof(arr); k++)
  1011. arr[n++] = old[k];
  1012. if (n + 1 < sizeof(arr))
  1013. arr[n++] = ';';
  1014. }
  1015. if (replaced && (remove || !value || !value[0])) {
  1016. arr[n] = '\0';
  1017. br_set_attr(D, node, "style", arr, n);
  1018. if (host.changed)
  1019. host.changed();
  1020. return;
  1021. }
  1022. if (value && value[0] && n + nl + strlen(value) + 3 < sizeof(arr)) {
  1023. for (i = 0; i < nl; i++)
  1024. arr[n++] = prop[i];
  1025. arr[n++] = ':';
  1026. for (i = 0; value[i]; i++)
  1027. arr[n++] = value[i];
  1028. arr[n++] = ';';
  1029. }
  1030. arr[n] = '\0';
  1031. br_set_attr(D, node, "style", arr, n);
  1032. if (host.changed)
  1033. host.changed();
  1034. }
  1035. static void style_getproperty(js_State *state)
  1036. {
  1037. unsigned int node = node_of(js_currentfunctiondata(state));
  1038. char val[256];
  1039. if (style_lookup(br_find_attr(D, node, "style"),
  1040. js_tostring(state, 1), val, sizeof(val)))
  1041. js_pushstring(state, val);
  1042. else
  1043. js_pushstring(state, "");
  1044. }
  1045. static void style_setproperty(js_State *state)
  1046. {
  1047. unsigned int node = node_of(js_currentfunctiondata(state));
  1048. style_update(node, js_tostring(state, 1),
  1049. js_tostring(state, 2), 0);
  1050. }
  1051. static void style_removeproperty(js_State *state)
  1052. {
  1053. unsigned int node = node_of(js_currentfunctiondata(state));
  1054. const char *prop = js_tostring(state, 1);
  1055. char old[256];
  1056. int had = style_lookup(br_find_attr(D, node, "style"), prop,
  1057. old, sizeof(old));
  1058. style_update(node, prop, "", 1);
  1059. if (had)
  1060. js_pushstring(state, old);
  1061. else
  1062. js_pushstring(state, "");
  1063. }
  1064. static int style_has(js_State *state, void *p, const char *name)
  1065. {
  1066. unsigned int node = node_of(p);
  1067. const char *style;
  1068. char prop[64], val[256];
  1069. if (!D || node >= D->nnode)
  1070. return 0;
  1071. style = br_find_attr(D, node, "style");
  1072. if (!strcmp(name, "cssText")) {
  1073. js_pushstring(state, style ? style : "");
  1074. return 1;
  1075. }
  1076. if (!strcmp(name, "length")) {
  1077. js_pushnumber(state, style_count(style));
  1078. return 1;
  1079. }
  1080. if (!strcmp(name, "getPropertyValue")) {
  1081. push_func_data(state, name, style_getproperty, 1, node + 1);
  1082. return 1;
  1083. }
  1084. if (!strcmp(name, "setProperty")) {
  1085. push_func_data(state, name, style_setproperty, 2, node + 1);
  1086. return 1;
  1087. }
  1088. if (!strcmp(name, "removeProperty")) {
  1089. push_func_data(state, name, style_removeproperty, 1, node + 1);
  1090. return 1;
  1091. }
  1092. css_name(name, prop, sizeof(prop));
  1093. if (style_lookup(style, prop, val, sizeof(val)))
  1094. js_pushstring(state, val);
  1095. else
  1096. js_pushstring(state, "");
  1097. return 1;
  1098. }
  1099. static int style_put(js_State *state, void *p, const char *name)
  1100. {
  1101. unsigned int node = node_of(p);
  1102. const char *value;
  1103. char prop[64];
  1104. if (!D || node >= D->nnode)
  1105. return 0;
  1106. value = js_tostring(state, -1);
  1107. if (!strcmp(name, "cssText")) {
  1108. br_set_attr(D, node, "style", value, (unsigned int)strlen(value));
  1109. if (host.changed)
  1110. host.changed();
  1111. return 1;
  1112. }
  1113. css_name(name, prop, sizeof(prop));
  1114. style_update(node, prop, value, 0);
  1115. return 1;
  1116. }
  1117. static void push_style_object(js_State *state, unsigned int node)
  1118. {
  1119. char key[32];
  1120. snprintf(key, sizeof(key), "sty_%u", node + 1);
  1121. js_getregistry(state, key);
  1122. if (!js_isundefined(state, -1))
  1123. return;
  1124. js_pop(state, 1);
  1125. js_getregistry(state, "wrapproto");
  1126. js_newuserdatax(state, "style", (void *)(uintptr_t)(node + 1),
  1127. style_has, style_put, 0, 0);
  1128. js_copy(state, -1);
  1129. js_setregistry(state, key);
  1130. }
  1131. static int dataset_has(js_State *state, void *p, const char *name)
  1132. {
  1133. unsigned int node = node_of(p);
  1134. char attr[64];
  1135. const char *value;
  1136. if (!D || node >= D->nnode)
  1137. return 0;
  1138. data_name(name, attr, sizeof(attr));
  1139. value = br_find_attr(D, node, attr);
  1140. if (value)
  1141. js_pushstring(state, value);
  1142. else
  1143. js_pushundefined(state);
  1144. return 1;
  1145. }
  1146. static int dataset_put(js_State *state, void *p, const char *name)
  1147. {
  1148. unsigned int node = node_of(p);
  1149. char attr[64];
  1150. const char *value = js_tostring(state, -1);
  1151. if (!D || node >= D->nnode)
  1152. return 0;
  1153. data_name(name, attr, sizeof(attr));
  1154. br_set_attr(D, node, attr, value, (unsigned int)strlen(value));
  1155. if (host.changed)
  1156. host.changed();
  1157. return 1;
  1158. }
  1159. static int dataset_delete(js_State *state, void *p, const char *name)
  1160. {
  1161. unsigned int node = node_of(p);
  1162. char attr[64];
  1163. (void)state;
  1164. if (!D || node >= D->nnode)
  1165. return 0;
  1166. data_name(name, attr, sizeof(attr));
  1167. br_remove_attr(D, node, attr);
  1168. if (host.changed)
  1169. host.changed();
  1170. return 1;
  1171. }
  1172. static void push_dataset(js_State *state, unsigned int node)
  1173. {
  1174. char key[32];
  1175. snprintf(key, sizeof(key), "ds_%u", node + 1);
  1176. js_getregistry(state, key);
  1177. if (!js_isundefined(state, -1))
  1178. return;
  1179. js_pop(state, 1);
  1180. js_getregistry(state, "wrapproto");
  1181. js_newuserdatax(state, "dataset", (void *)(uintptr_t)(node + 1),
  1182. dataset_has, dataset_put, dataset_delete, 0);
  1183. js_copy(state, -1);
  1184. js_setregistry(state, key);
  1185. }
  1186. static void node_class_set(unsigned int node, const char *classes)
  1187. {
  1188. br_set_attr(D, node, "class", classes,
  1189. (unsigned int)strlen(classes));
  1190. if (host.changed)
  1191. host.changed();
  1192. }
  1193. static int class_has(const char *classes, const char *name)
  1194. {
  1195. unsigned int i = 0;
  1196. if (!classes)
  1197. return 0;
  1198. while (classes[i]) {
  1199. unsigned int start;
  1200. while (classes[i] == ' ' || classes[i] == '\t')
  1201. i++;
  1202. start = i;
  1203. while (classes[i] && classes[i] != ' ' && classes[i] != '\t')
  1204. i++;
  1205. if (i - start == strlen(name) &&
  1206. !strncmp(classes + start, name, i - start))
  1207. return 1;
  1208. }
  1209. return 0;
  1210. }
  1211. static void class_add(unsigned int node, const char *name, int add)
  1212. {
  1213. const char *old = node_attr(node, "class");
  1214. char buf[2048]; /* BR_CLASS_MAX: Tailwind class lists */
  1215. unsigned int n = 0, i = 0;
  1216. if (add) {
  1217. if (class_has(old, name))
  1218. return;
  1219. if (old && old[0]) {
  1220. while (old[i] && n + 1 < sizeof(buf))
  1221. buf[n++] = old[i++];
  1222. if (n + 1 < sizeof(buf))
  1223. buf[n++] = ' ';
  1224. }
  1225. i = 0;
  1226. while (name[i] && n + 1 < sizeof(buf))
  1227. buf[n++] = name[i++];
  1228. } else {
  1229. if (!old)
  1230. return;
  1231. while (old[i]) {
  1232. unsigned int start;
  1233. while (old[i] == ' ' || old[i] == '\t')
  1234. i++;
  1235. start = i;
  1236. while (old[i] && old[i] != ' ' && old[i] != '\t')
  1237. i++;
  1238. if (i - start == strlen(name) &&
  1239. !strncmp(old + start, name, i - start))
  1240. continue;
  1241. if (n && n + 1 < sizeof(buf))
  1242. buf[n++] = ' ';
  1243. {
  1244. unsigned int k;
  1245. for (k = start; k < i && n + 1 < sizeof(buf);
  1246. k++)
  1247. buf[n++] = old[k];
  1248. }
  1249. }
  1250. }
  1251. buf[n] = '\0';
  1252. node_class_set(node, buf);
  1253. }
  1254. static void node_classlist_add(js_State *state)
  1255. {
  1256. class_add(node_of(js_currentfunctiondata(state)),
  1257. js_tostring(state, 1), 1);
  1258. }
  1259. static void node_classlist_remove(js_State *state)
  1260. {
  1261. class_add(node_of(js_currentfunctiondata(state)),
  1262. js_tostring(state, 1), 0);
  1263. }
  1264. static void node_classlist_toggle(js_State *state)
  1265. {
  1266. unsigned int node = node_of(js_currentfunctiondata(state));
  1267. const char *name = js_tostring(state, 1);
  1268. int has = class_has(node_attr(node, "class"), name);
  1269. int want = !has;
  1270. if (js_isdefined(state, 2))
  1271. want = js_toboolean(state, 2);
  1272. if (want != has)
  1273. class_add(node, name, want);
  1274. js_pushboolean(state, want);
  1275. }
  1276. static void node_classlist_contains(js_State *state)
  1277. {
  1278. unsigned int node = node_of(js_currentfunctiondata(state));
  1279. js_pushboolean(state, class_has(node_attr(node, "class"),
  1280. js_tostring(state, 1)));
  1281. }
  1282. static unsigned int class_count(const char *classes)
  1283. {
  1284. unsigned int i = 0, n = 0;
  1285. if (!classes)
  1286. return 0;
  1287. while (classes[i]) {
  1288. while (classes[i] == ' ' || classes[i] == '\t')
  1289. i++;
  1290. if (!classes[i])
  1291. break;
  1292. n++;
  1293. while (classes[i] && classes[i] != ' ' && classes[i] != '\t')
  1294. i++;
  1295. }
  1296. return n;
  1297. }
  1298. /* ---- innerHTML / outerHTML serialization ---- */
  1299. #define JS_SERIALIZE_MAX (2u * 1024u * 1024u)
  1300. struct sbuf {
  1301. char *p;
  1302. unsigned int n, cap;
  1303. int full;
  1304. };
  1305. static void sb_put(struct sbuf *b, const char *s, unsigned int len)
  1306. {
  1307. if (b->full)
  1308. return;
  1309. if (b->n + len + 1 > b->cap) {
  1310. unsigned int nc = b->cap ? b->cap : 1024;
  1311. char *np;
  1312. while (nc < b->n + len + 1)
  1313. nc *= 2;
  1314. if (nc > JS_SERIALIZE_MAX) {
  1315. b->full = 1;
  1316. return;
  1317. }
  1318. np = (char *)realloc(b->p, nc);
  1319. if (!np) {
  1320. b->full = 1;
  1321. return;
  1322. }
  1323. b->p = np;
  1324. b->cap = nc;
  1325. }
  1326. memcpy(b->p + b->n, s, len);
  1327. b->n += len;
  1328. b->p[b->n] = '\0';
  1329. }
  1330. static void sb_str(struct sbuf *b, const char *s)
  1331. {
  1332. sb_put(b, s, (unsigned int)strlen(s));
  1333. }
  1334. static void sb_escaped(struct sbuf *b, const char *s, unsigned int len,
  1335. int attr)
  1336. {
  1337. unsigned int i, start = 0;
  1338. for (i = 0; i < len; i++) {
  1339. const char *rep = 0;
  1340. if (s[i] == '&')
  1341. rep = "&amp;";
  1342. else if (s[i] == '<' && !attr)
  1343. rep = "&lt;";
  1344. else if (s[i] == '>' && !attr)
  1345. rep = "&gt;";
  1346. else if (s[i] == '"' && attr)
  1347. rep = "&quot;";
  1348. else if ((unsigned char)s[i] == 0xA0)
  1349. rep = "&nbsp;";
  1350. if (!rep)
  1351. continue;
  1352. sb_put(b, s + start, i - start);
  1353. sb_str(b, rep);
  1354. start = i + 1;
  1355. }
  1356. sb_put(b, s + start, len - start);
  1357. }
  1358. static void serialize_node(struct sbuf *b, unsigned int node, int depth);
  1359. static void serialize_children(struct sbuf *b, unsigned int node, int depth)
  1360. {
  1361. unsigned int c;
  1362. for (c = D->nodes[node].first; c && !b->full; c = D->nodes[c].next)
  1363. serialize_node(b, c, depth + 1);
  1364. }
  1365. /* HTML serialization of the parsed tree (lower-case names, quoted
  1366. * attributes, raw text inside script/style, no end tag for void
  1367. * elements). heise reads its JSON config through innerHTML; DOMPurify
  1368. * returns its result the same way. */
  1369. static void serialize_node(struct sbuf *b, unsigned int node, int depth)
  1370. {
  1371. struct br_node *n;
  1372. char name[64];
  1373. unsigned int i;
  1374. const char *p, *end;
  1375. if (!D || node >= D->nnode || depth > 200 || b->full)
  1376. return;
  1377. n = &D->nodes[node];
  1378. if (n->type == BR_NODE_TEXT) {
  1379. unsigned int par = n->parent;
  1380. int raw = par < D->nnode &&
  1381. D->nodes[par].type == BR_NODE_ELEM &&
  1382. (D->nodes[par].tag == BR_TAG_SCRIPT ||
  1383. D->nodes[par].tag == BR_TAG_STYLE);
  1384. if (raw)
  1385. sb_put(b, D->text + n->text_off, n->text_len);
  1386. else
  1387. sb_escaped(b, D->text + n->text_off, n->text_len, 0);
  1388. return;
  1389. }
  1390. if (n->type == BR_NODE_COMMENT) {
  1391. sb_str(b, "<!--");
  1392. sb_put(b, D->text + n->text_off, n->text_len);
  1393. sb_str(b, "-->");
  1394. return;
  1395. }
  1396. if (n->type == BR_NODE_FRAGMENT) {
  1397. serialize_children(b, node, depth);
  1398. return;
  1399. }
  1400. node_name(node, name, sizeof(name));
  1401. for (i = 0; name[i]; i++)
  1402. if (name[i] >= 'A' && name[i] <= 'Z')
  1403. name[i] = (char)(name[i] - 'A' + 'a');
  1404. sb_str(b, "<");
  1405. sb_str(b, name);
  1406. p = D->attrs + n->extra_off;
  1407. end = p + n->extra_len;
  1408. while (n->extra_len && p + 1 < end) {
  1409. const char *an = p, *av;
  1410. p += strlen(p) + 1;
  1411. if (p >= end)
  1412. break;
  1413. av = p;
  1414. p += strlen(p) + 1;
  1415. sb_str(b, " ");
  1416. sb_str(b, an);
  1417. sb_str(b, "=\"");
  1418. sb_escaped(b, av, (unsigned int)strlen(av), 1);
  1419. sb_str(b, "\"");
  1420. }
  1421. sb_str(b, ">");
  1422. if (br_tag_is_void(n->tag) && !n->first)
  1423. return;
  1424. serialize_children(b, node, depth);
  1425. sb_str(b, "</");
  1426. sb_str(b, name);
  1427. sb_str(b, ">");
  1428. }
  1429. static void push_serialized(js_State *state, unsigned int node, int outer)
  1430. {
  1431. struct sbuf b;
  1432. memset(&b, 0, sizeof(b));
  1433. if (outer)
  1434. serialize_node(&b, node, 0);
  1435. else
  1436. serialize_children(&b, node, 0);
  1437. js_pushlstring(state, b.p ? b.p : "", (int)b.n);
  1438. free(b.p);
  1439. }
  1440. static void push_attributes(js_State *state, unsigned int node)
  1441. {
  1442. struct br_node *n;
  1443. const char *p, *end;
  1444. unsigned int count = 0;
  1445. js_newobject(state);
  1446. if (!D || node >= D->nnode)
  1447. return;
  1448. n = &D->nodes[node];
  1449. p = D->attrs + n->extra_off;
  1450. end = p + n->extra_len;
  1451. while (p + 1 < end) {
  1452. const char *an = p;
  1453. const char *av;
  1454. p += strlen(p) + 1;
  1455. if (p >= end)
  1456. break;
  1457. av = p;
  1458. p += strlen(p) + 1;
  1459. js_newobject(state);
  1460. js_pushstring(state, an);
  1461. js_setproperty(state, -2, "name");
  1462. js_pushstring(state, av);
  1463. js_setproperty(state, -2, "value");
  1464. js_pushboolean(state, 1);
  1465. js_setproperty(state, -2, "specified");
  1466. /* Array-like: attributes[i] and attributes[name] both work. */
  1467. js_copy(state, -1);
  1468. js_setproperty(state, -3, an);
  1469. js_setindex(state, -2, (int)count);
  1470. count++;
  1471. }
  1472. js_pushnumber(state, count);
  1473. js_setproperty(state, -2, "length");
  1474. }
  1475. static void push_classlist(js_State *state, unsigned int node)
  1476. {
  1477. js_newobject(state);
  1478. def_func_data(state, "add", node_classlist_add, 1, node + 1);
  1479. def_func_data(state, "remove", node_classlist_remove, 1, node + 1);
  1480. def_func_data(state, "toggle", node_classlist_toggle, 1, node + 1);
  1481. def_func_data(state, "contains", node_classlist_contains, 1, node + 1);
  1482. js_pushnumber(state, class_count(node_attr(node, "class")));
  1483. js_setproperty(state, -2, "length");
  1484. }
  1485. static void node_getattr(js_State *state)
  1486. {
  1487. unsigned int node = node_of(js_currentfunctiondata(state));
  1488. push_attr(state, node, js_tostring(state, 1), 1);
  1489. }
  1490. static void node_setattr(js_State *state)
  1491. {
  1492. unsigned int node = node_of(js_currentfunctiondata(state));
  1493. const char *name = js_tostring(state, 1);
  1494. const char *value = js_tostring(state, 2);
  1495. char lower[64];
  1496. unsigned int i;
  1497. for (i = 0; name[i] && i + 1 < sizeof(lower); i++) {
  1498. char c = name[i];
  1499. if (c >= 'A' && c <= 'Z')
  1500. c = (char)(c - 'A' + 'a');
  1501. lower[i] = c;
  1502. }
  1503. lower[i] = '\0';
  1504. br_set_attr(D, node, lower, value, (unsigned int)strlen(value));
  1505. if (host.changed)
  1506. host.changed();
  1507. }
  1508. static void node_removeattr(js_State *state)
  1509. {
  1510. unsigned int node = node_of(js_currentfunctiondata(state));
  1511. const char *name = js_tostring(state, 1);
  1512. char lower[64];
  1513. unsigned int i;
  1514. for (i = 0; name[i] && i + 1 < sizeof(lower); i++) {
  1515. char c = name[i];
  1516. if (c >= 'A' && c <= 'Z')
  1517. c = (char)(c - 'A' + 'a');
  1518. lower[i] = c;
  1519. }
  1520. lower[i] = '\0';
  1521. br_remove_attr(D, node, lower);
  1522. if (host.changed)
  1523. host.changed();
  1524. }
  1525. static void node_hasattr(js_State *state)
  1526. {
  1527. unsigned int node = node_of(js_currentfunctiondata(state));
  1528. js_pushboolean(state, node_attr(node, js_tostring(state, 1)) != 0);
  1529. }
  1530. static void node_appendchild(js_State *state)
  1531. {
  1532. unsigned int node = node_of(js_currentfunctiondata(state));
  1533. unsigned int child = arg_node(state, 1);
  1534. if (br_append_child(D, node, child) != 0) {
  1535. js_pushnull(state);
  1536. return;
  1537. }
  1538. if (host.changed)
  1539. host.changed();
  1540. push_node(state, child);
  1541. }
  1542. static void node_insertbefore(js_State *state)
  1543. {
  1544. unsigned int node = node_of(js_currentfunctiondata(state));
  1545. unsigned int child = arg_node(state, 1);
  1546. unsigned int before = 0;
  1547. if (!js_isnull(state, 2) && !js_isundefined(state, 2))
  1548. before = arg_node(state, 2);
  1549. if (br_insert_before(D, node, child, before) != 0) {
  1550. js_pushnull(state);
  1551. return;
  1552. }
  1553. if (host.changed)
  1554. host.changed();
  1555. push_node(state, child);
  1556. }
  1557. static void node_removechild(js_State *state)
  1558. {
  1559. unsigned int node = node_of(js_currentfunctiondata(state));
  1560. unsigned int child = arg_node(state, 1);
  1561. if (br_remove_child(D, node, child) != 0) {
  1562. js_pushnull(state);
  1563. return;
  1564. }
  1565. if (host.changed)
  1566. host.changed();
  1567. push_node(state, child);
  1568. }
  1569. static void node_replacechild(js_State *state)
  1570. {
  1571. unsigned int node = node_of(js_currentfunctiondata(state));
  1572. unsigned int child = arg_node(state, 1);
  1573. unsigned int old = arg_node(state, 2);
  1574. br_insert_before(D, node, child, old);
  1575. br_remove_child(D, node, old);
  1576. if (host.changed)
  1577. host.changed();
  1578. push_node(state, old);
  1579. }
  1580. static void node_clone(js_State *state)
  1581. {
  1582. unsigned int node = node_of(js_currentfunctiondata(state));
  1583. unsigned int h = br_clone_node(D, node + 1,
  1584. js_toboolean(state, 1));
  1585. push_node(state, h);
  1586. }
  1587. static void node_contains(js_State *state)
  1588. {
  1589. unsigned int node = node_of(js_currentfunctiondata(state));
  1590. unsigned int other = arg_node(state, 1);
  1591. unsigned int p = other;
  1592. while (1) {
  1593. if (p == node) {
  1594. js_pushboolean(state, 1);
  1595. return;
  1596. }
  1597. if (p == 0)
  1598. break;
  1599. p = D->nodes[p].parent;
  1600. }
  1601. js_pushboolean(state, 0);
  1602. }
  1603. static void node_haschildren(js_State *state)
  1604. {
  1605. unsigned int node = node_of(js_currentfunctiondata(state));
  1606. js_pushboolean(state, node < D->nnode && D->nodes[node].first != 0);
  1607. }
  1608. static void node_remove(js_State *state)
  1609. {
  1610. unsigned int node = node_of(js_currentfunctiondata(state));
  1611. unsigned int parent = node < D->nnode ? D->nodes[node].parent : 0;
  1612. (void)state;
  1613. if (parent)
  1614. br_remove_child(D, parent, node + 1);
  1615. if (host.changed)
  1616. host.changed();
  1617. }
  1618. static void node_matches(js_State *state)
  1619. {
  1620. unsigned int node = node_of(js_currentfunctiondata(state));
  1621. js_pushboolean(state, br_matches(D, node + 1,
  1622. js_tostring(state, 1)));
  1623. }
  1624. static void node_click(js_State *state)
  1625. {
  1626. unsigned int node = node_of(js_currentfunctiondata(state));
  1627. if (host.click)
  1628. host.click(node);
  1629. js_pushundefined(state);
  1630. }
  1631. static void node_getelementsbytagname(js_State *state)
  1632. {
  1633. unsigned int node = node_of(js_currentfunctiondata(state));
  1634. const char *name = js_tostring(state, 1);
  1635. unsigned int out[256];
  1636. unsigned int n = br_query_all(D, node + 1, name, out, 256);
  1637. js_newarray(state);
  1638. for (unsigned int i = 0; i < n; i++) {
  1639. push_node(state, out[i]);
  1640. js_setindex(state, -2, (int)i);
  1641. }
  1642. }
  1643. static void node_getelementsbyclassname(js_State *state)
  1644. {
  1645. unsigned int node = node_of(js_currentfunctiondata(state));
  1646. const char *name = js_tostring(state, 1);
  1647. char sel[256];
  1648. unsigned int n = 0, i = 0;
  1649. unsigned int out[256], count;
  1650. while (name[i] && n + 2 < sizeof(sel)) {
  1651. while (name[i] == ' ')
  1652. i++;
  1653. if (!name[i])
  1654. break;
  1655. sel[n++] = '.';
  1656. while (name[i] && name[i] != ' ' && n + 1 < sizeof(sel))
  1657. sel[n++] = name[i++];
  1658. }
  1659. sel[n] = '\0';
  1660. count = br_query_all(D, node + 1, sel, out, 256);
  1661. js_newarray(state);
  1662. for (i = 0; i < count; i++) {
  1663. push_node(state, out[i]);
  1664. js_setindex(state, -2, (int)i);
  1665. }
  1666. }
  1667. static void node_queryselector(js_State *state)
  1668. {
  1669. unsigned int node = node_of(js_currentfunctiondata(state));
  1670. unsigned int out[1];
  1671. unsigned int n = br_query_all(D, node + 1, js_tostring(state, 1),
  1672. out, 1);
  1673. if (n)
  1674. push_node(state, out[0]);
  1675. else
  1676. js_pushnull(state);
  1677. }
  1678. static void node_queryselectorall(js_State *state)
  1679. {
  1680. unsigned int node = node_of(js_currentfunctiondata(state));
  1681. unsigned int out[256];
  1682. unsigned int n = br_query_all(D, node + 1, js_tostring(state, 1),
  1683. out, 256);
  1684. js_newarray(state);
  1685. for (unsigned int i = 0; i < n; i++) {
  1686. push_node(state, out[i]);
  1687. js_setindex(state, -2, (int)i);
  1688. }
  1689. }
  1690. static void node_getrect(js_State *state)
  1691. {
  1692. unsigned int node = node_of(js_currentfunctiondata(state));
  1693. int x = 0, y = 0, w = 0, h = 0;
  1694. if (host.rect)
  1695. host.rect(node, &x, &y, &w, &h);
  1696. js_newobject(state);
  1697. js_pushnumber(state, y); js_setproperty(state, -2, "top");
  1698. js_pushnumber(state, x); js_setproperty(state, -2, "left");
  1699. js_pushnumber(state, x + w); js_setproperty(state, -2, "right");
  1700. js_pushnumber(state, y + h); js_setproperty(state, -2, "bottom");
  1701. js_pushnumber(state, w); js_setproperty(state, -2, "width");
  1702. js_pushnumber(state, h); js_setproperty(state, -2, "height");
  1703. }
  1704. static void node_noop(js_State *state)
  1705. {
  1706. (void)state;
  1707. }
  1708. static void node_push_text(js_State *state, unsigned int node)
  1709. {
  1710. unsigned int cap = D->text_used + 1;
  1711. char *buf;
  1712. unsigned int len;
  1713. if (cap < 32)
  1714. cap = 32;
  1715. buf = (char *)malloc(cap);
  1716. if (!buf) {
  1717. js_pushstring(state, "");
  1718. return;
  1719. }
  1720. len = br_text_content(D, node, buf, cap);
  1721. js_pushlstring(state, buf, (int)len);
  1722. free(buf);
  1723. }
  1724. static unsigned int node_form_ancestor(unsigned int node)
  1725. {
  1726. while (node && node < D->nnode) {
  1727. if (D->nodes[node].type == BR_NODE_ELEM &&
  1728. D->nodes[node].tag == BR_TAG_FORM)
  1729. return node;
  1730. node = D->nodes[node].parent;
  1731. }
  1732. return 0;
  1733. }
  1734. static void push_form_elements(js_State *state, unsigned int form)
  1735. {
  1736. unsigned int out[128];
  1737. int n = 0, i;
  1738. if (host.form_elements)
  1739. n = host.form_elements(form, out, (int)(sizeof(out) /
  1740. sizeof(out[0])));
  1741. js_newarray(state);
  1742. for (i = 0; i < n; i++) {
  1743. const char *name;
  1744. push_node(state, out[i] + 1);
  1745. js_setindex(state, -2, i);
  1746. name = br_find_attr(D, out[i], "name");
  1747. if (name && name[0]) {
  1748. push_node(state, out[i] + 1);
  1749. js_setproperty(state, -2, name);
  1750. }
  1751. }
  1752. }
  1753. static void form_submit_js(js_State *state)
  1754. {
  1755. unsigned int node = node_of(js_currentfunctiondata(state));
  1756. if (host.form_submit)
  1757. host.form_submit(node);
  1758. }
  1759. static void form_reset_js(js_State *state)
  1760. {
  1761. unsigned int node = node_of(js_currentfunctiondata(state));
  1762. if (host.form_reset)
  1763. host.form_reset(node);
  1764. }
  1765. /* Userdata property hooks: every element wrapper carries node + 1. */
  1766. static int node_has(js_State *state, void *p, const char *name)
  1767. {
  1768. unsigned int node = node_of(p);
  1769. struct br_node *n;
  1770. char buf[64];
  1771. if (!D || node >= D->nnode)
  1772. return 0;
  1773. n = &D->nodes[node];
  1774. if (n->type == BR_NODE_ELEM && n->tag == BR_TAG_FORM) {
  1775. if (!strcmp(name, "elements")) {
  1776. push_form_elements(state, node);
  1777. return 1;
  1778. }
  1779. if (!strcmp(name, "length")) {
  1780. unsigned int out[128];
  1781. int count = 0;
  1782. if (host.form_elements)
  1783. count = host.form_elements(node, out,
  1784. (int)(sizeof(out) / sizeof(out[0])));
  1785. js_pushnumber(state, count);
  1786. return 1;
  1787. }
  1788. if (!strcmp(name, "submit")) {
  1789. push_func_data(state, "submit", form_submit_js, 0,
  1790. node + 1);
  1791. return 1;
  1792. }
  1793. if (!strcmp(name, "reset")) {
  1794. push_func_data(state, "reset", form_reset_js, 0,
  1795. node + 1);
  1796. return 1;
  1797. }
  1798. }
  1799. if (!strcmp(name, "form")) {
  1800. unsigned int f;
  1801. if (n->type == BR_NODE_ELEM && n->tag == BR_TAG_FORM)
  1802. f = 0;
  1803. else
  1804. f = node_form_ancestor(node);
  1805. if (f)
  1806. push_node(state, f + 1);
  1807. else
  1808. js_pushnull(state);
  1809. return 1;
  1810. }
  1811. if (!strcmp(name, "textContent") || !strcmp(name, "innerText")) {
  1812. node_push_text(state, node);
  1813. return 1;
  1814. }
  1815. if (!strcmp(name, "nodeValue")) {
  1816. if (n->type == BR_NODE_TEXT || n->type == BR_NODE_COMMENT)
  1817. js_pushlstring(state, D->text + n->text_off,
  1818. (int)n->text_len);
  1819. else
  1820. js_pushnull(state);
  1821. return 1;
  1822. }
  1823. if (!strcmp(name, "nodeType")) {
  1824. js_pushnumber(state, node_type_value(node));
  1825. return 1;
  1826. }
  1827. if (!strcmp(name, "nodeName") || !strcmp(name, "tagName")) {
  1828. node_name(node, buf, sizeof(buf));
  1829. js_pushstring(state, buf);
  1830. return 1;
  1831. }
  1832. if (!strcmp(name, "parentNode") || !strcmp(name, "parentElement")) {
  1833. int p = node_parent_idx(node);
  1834. if (p >= 0)
  1835. push_node(state, (unsigned int)p + 1);
  1836. else if (name[6] == 'N' && !(n->flags & BR_NODE_DETACHED) &&
  1837. n->type == BR_NODE_ELEM && n->tag == BR_TAG_HTML)
  1838. js_getglobal(state, "document"); /* <html>'s parent */
  1839. else
  1840. js_pushnull(state);
  1841. return 1;
  1842. }
  1843. if (!strcmp(name, "childNodes")) {
  1844. push_child_list(state, node, 0);
  1845. return 1;
  1846. }
  1847. if (!strcmp(name, "children")) {
  1848. push_child_list(state, node, 1);
  1849. return 1;
  1850. }
  1851. if (!strcmp(name, "firstChild")) {
  1852. push_node(state, n->first ? n->first + 1 : 0);
  1853. return 1;
  1854. }
  1855. if (!strcmp(name, "lastChild")) {
  1856. push_node(state, n->last ? n->last + 1 : 0);
  1857. return 1;
  1858. }
  1859. if (!strcmp(name, "firstElementChild") ||
  1860. !strcmp(name, "lastElementChild")) {
  1861. unsigned int c = n->first;
  1862. unsigned int found = 0;
  1863. if (!strcmp(name, "lastElementChild")) {
  1864. for (c = n->first; c; c = D->nodes[c].next)
  1865. if (D->nodes[c].type == BR_NODE_ELEM)
  1866. found = c;
  1867. } else {
  1868. while (c && D->nodes[c].type != BR_NODE_ELEM)
  1869. c = D->nodes[c].next;
  1870. found = c;
  1871. }
  1872. push_node(state, found ? found + 1 : 0);
  1873. return 1;
  1874. }
  1875. if (!strcmp(name, "nextSibling") || !strcmp(name, "nextElementSibling")) {
  1876. unsigned int c = n->next;
  1877. if (!strcmp(name, "nextElementSibling"))
  1878. while (c && D->nodes[c].type != BR_NODE_ELEM)
  1879. c = D->nodes[c].next;
  1880. push_node(state, c ? c + 1 : 0);
  1881. return 1;
  1882. }
  1883. if (!strcmp(name, "previousSibling") ||
  1884. !strcmp(name, "previousElementSibling")) {
  1885. unsigned int c = node_prev_sibling(node);
  1886. if (!strcmp(name, "previousElementSibling"))
  1887. while (c && D->nodes[c].type != BR_NODE_ELEM)
  1888. c = node_prev_sibling(c);
  1889. push_node(state, c ? c + 1 : 0);
  1890. return 1;
  1891. }
  1892. if (!strcmp(name, "childElementCount")) {
  1893. unsigned int c, count = 0;
  1894. for (c = n->first; c; c = D->nodes[c].next)
  1895. if (D->nodes[c].type == BR_NODE_ELEM)
  1896. count++;
  1897. js_pushnumber(state, count);
  1898. return 1;
  1899. }
  1900. if (n->tag == BR_TAG_A || n->tag == BR_TAG_AREA) {
  1901. if (!strcmp(name, "href") || !strcmp(name, "protocol") ||
  1902. !strcmp(name, "host") || !strcmp(name, "hostname") ||
  1903. !strcmp(name, "port") || !strcmp(name, "pathname") ||
  1904. !strcmp(name, "search") || !strcmp(name, "hash") ||
  1905. !strcmp(name, "origin")) {
  1906. push_element_url(state, node, name);
  1907. return 1;
  1908. }
  1909. }
  1910. if (!strcmp(name, "id")) { push_attr(state, node, "id", 0); return 1; }
  1911. if (!strcmp(name, "className")) {
  1912. push_attr(state, node, "class", 0);
  1913. return 1;
  1914. }
  1915. if (!strcmp(name, "href")) { push_attr(state, node, "href", 0); return 1; }
  1916. if (!strcmp(name, "src")) { push_attr(state, node, "src", 0); return 1; }
  1917. if (n->type == BR_NODE_ELEM && n->tag == BR_TAG_SELECT) {
  1918. if (!strcmp(name, "options")) {
  1919. push_query_array(state, node, "option");
  1920. return 1;
  1921. }
  1922. if (!strcmp(name, "multiple")) {
  1923. js_pushboolean(state, node_attr(node, "multiple") != 0);
  1924. return 1;
  1925. }
  1926. }
  1927. /* An <option> without a value attribute has its text as value. */
  1928. if (n->type == BR_NODE_ELEM && n->tag == BR_TAG_OPTION &&
  1929. !strcmp(name, "value") && !node_attr(node, "value")) {
  1930. node_push_text(state, node);
  1931. return 1;
  1932. }
  1933. if (!strcmp(name, "value")) {
  1934. char buf[128];
  1935. if (host.form_value && host.form_value(node, buf, sizeof(buf)))
  1936. js_pushstring(state, buf);
  1937. else
  1938. push_attr(state, node, "value", 0);
  1939. return 1;
  1940. }
  1941. if (!strcmp(name, "type")) { push_attr(state, node, "type", 0); return 1; }
  1942. if (!strcmp(name, "name")) { push_attr(state, node, "name", 0); return 1; }
  1943. if (!strcmp(name, "alt")) { push_attr(state, node, "alt", 0); return 1; }
  1944. if (!strcmp(name, "title")) { push_attr(state, node, "title", 0); return 1; }
  1945. if (!strcmp(name, "checked")) {
  1946. int c = host.form_checked ? host.form_checked(node) : -1;
  1947. js_pushboolean(state, c >= 0 ? c : node_attr(node, name) != 0);
  1948. return 1;
  1949. }
  1950. if (!strcmp(name, "selectedIndex")) {
  1951. int c = host.form_selected ? host.form_selected(node) : -1;
  1952. js_pushnumber(state, c >= 0 ? c : 0);
  1953. return 1;
  1954. }
  1955. if (!strcmp(name, "selected")) {
  1956. int c = host.form_selected ? host.form_selected(node) : -1;
  1957. if (c >= 0)
  1958. js_pushboolean(state, c != 0);
  1959. else
  1960. js_pushboolean(state, node_attr(node, name) != 0);
  1961. return 1;
  1962. }
  1963. if (!strcmp(name, "disabled")) {
  1964. js_pushboolean(state, node_attr(node, name) != 0);
  1965. return 1;
  1966. }
  1967. if (!strcmp(name, "style")) {
  1968. push_style_object(state, node);
  1969. return 1;
  1970. }
  1971. if (!strcmp(name, "dataset") || !strcmp(name, "domStringMap")) {
  1972. push_dataset(state, node);
  1973. return 1;
  1974. }
  1975. if (!strcmp(name, "classList")) {
  1976. push_classlist(state, node);
  1977. return 1;
  1978. }
  1979. if (!strcmp(name, "attributes")) {
  1980. push_attributes(state, node);
  1981. return 1;
  1982. }
  1983. if (!strcmp(name, "innerHTML") || !strcmp(name, "outerHTML")) {
  1984. push_serialized(state, node, name[0] == 'o');
  1985. return 1;
  1986. }
  1987. if (!strcmp(name, "ownerDocument")) {
  1988. js_getglobal(state, "document");
  1989. return 1;
  1990. }
  1991. if (!strcmp(name, "localName")) {
  1992. unsigned int i;
  1993. if (n->type != BR_NODE_ELEM) {
  1994. js_pushnull(state);
  1995. return 1;
  1996. }
  1997. node_name(node, buf, sizeof(buf));
  1998. for (i = 0; buf[i]; i++)
  1999. if (buf[i] >= 'A' && buf[i] <= 'Z')
  2000. buf[i] = (char)(buf[i] - 'A' + 'a');
  2001. js_pushstring(state, buf);
  2002. return 1;
  2003. }
  2004. if (!strcmp(name, "namespaceURI")) {
  2005. unsigned int a;
  2006. if (n->type != BR_NODE_ELEM) {
  2007. js_pushnull(state);
  2008. return 1;
  2009. }
  2010. for (a = node; a && a < D->nnode; a = D->nodes[a].parent)
  2011. if (D->nodes[a].type == BR_NODE_ELEM &&
  2012. D->nodes[a].tag == BR_TAG_SVG)
  2013. break;
  2014. js_pushstring(state, a && a < D->nnode ?
  2015. "http://www.w3.org/2000/svg" :
  2016. "http://www.w3.org/1999/xhtml");
  2017. return 1;
  2018. }
  2019. if (!strcmp(name, "isConnected")) {
  2020. /* Connected when the top ancestor hangs off the document root
  2021. * (index 0); script-created subtrees also have parent 0 but
  2022. * are not among the root's children. */
  2023. unsigned int a = node, c;
  2024. int conn = node == 0;
  2025. while (a && a < D->nnode && D->nodes[a].parent)
  2026. a = D->nodes[a].parent;
  2027. for (c = D->nodes[0].first; c && !conn; c = D->nodes[c].next)
  2028. if (c == a)
  2029. conn = 1;
  2030. js_pushboolean(state, conn);
  2031. return 1;
  2032. }
  2033. if (!strcmp(name, "relList")) {
  2034. /* Only supports(): Vite's modulepreload polyfill asks it and
  2035. * otherwise refetches every preloaded module through fetch(). */
  2036. js_newobject(state);
  2037. def_func(state, "supports", rellist_supports, 1);
  2038. return 1;
  2039. }
  2040. if (!strcmp(name, "getAttribute"))
  2041. { push_func_data(state, "getAttribute", node_getattr, 1, node + 1); return 1; }
  2042. if (!strcmp(name, "setAttribute"))
  2043. { push_func_data(state, "setAttribute", node_setattr, 2, node + 1); return 1; }
  2044. if (!strcmp(name, "removeAttribute"))
  2045. { push_func_data(state, "removeAttribute", node_removeattr, 1, node + 1); return 1; }
  2046. if (!strcmp(name, "hasAttribute"))
  2047. { push_func_data(state, "hasAttribute", node_hasattr, 1, node + 1); return 1; }
  2048. if (!strcmp(name, "appendChild"))
  2049. { push_func_data(state, "appendChild", node_appendchild, 1, node + 1); return 1; }
  2050. if (!strcmp(name, "insertBefore"))
  2051. { push_func_data(state, "insertBefore", node_insertbefore, 2, node + 1); return 1; }
  2052. if (!strcmp(name, "removeChild"))
  2053. { push_func_data(state, "removeChild", node_removechild, 1, node + 1); return 1; }
  2054. if (!strcmp(name, "replaceChild"))
  2055. { push_func_data(state, "replaceChild", node_replacechild, 2, node + 1); return 1; }
  2056. if (!strcmp(name, "cloneNode"))
  2057. { push_func_data(state, "cloneNode", node_clone, 1, node + 1); return 1; }
  2058. if (!strcmp(name, "contains"))
  2059. { push_func_data(state, "contains", node_contains, 1, node + 1); return 1; }
  2060. if (!strcmp(name, "hasChildNodes"))
  2061. { push_func_data(state, "hasChildNodes", node_haschildren, 0, node + 1); return 1; }
  2062. if (!strcmp(name, "remove"))
  2063. { push_func_data(state, "remove", node_remove, 0, node + 1); return 1; }
  2064. if (!strcmp(name, "matches") || !strcmp(name, "webkitMatchesSelector") ||
  2065. !strcmp(name, "mozMatchesSelector") ||
  2066. !strcmp(name, "msMatchesSelector"))
  2067. { push_func_data(state, name, node_matches, 1, node + 1); return 1; }
  2068. if (!strcmp(name, "getElementsByTagName"))
  2069. { push_func_data(state, "getElementsByTagName", node_getelementsbytagname, 1, node + 1); return 1; }
  2070. if (!strcmp(name, "getElementsByClassName"))
  2071. { push_func_data(state, "getElementsByClassName", node_getelementsbyclassname, 1, node + 1); return 1; }
  2072. if (!strcmp(name, "querySelector"))
  2073. { push_func_data(state, "querySelector", node_queryselector, 1, node + 1); return 1; }
  2074. if (!strcmp(name, "querySelectorAll"))
  2075. { push_func_data(state, "querySelectorAll", node_queryselectorall, 1, node + 1); return 1; }
  2076. if (!strcmp(name, "addEventListener"))
  2077. { push_func_data(state, "addEventListener", node_addlistener, 2, node + 1); return 1; }
  2078. if (!strcmp(name, "removeEventListener"))
  2079. { push_func_data(state, "removeEventListener", node_removelistener, 2, node + 1); return 1; }
  2080. if (!strcmp(name, "dispatchEvent"))
  2081. { push_func_data(state, "dispatchEvent", node_dispatchevent, 1, node + 1); return 1; }
  2082. if (!strcmp(name, "getBoundingClientRect"))
  2083. { push_func_data(state, "getBoundingClientRect", node_getrect, 0, node + 1); return 1; }
  2084. if (!strcmp(name, "getClientRects")) {
  2085. js_newarray(state);
  2086. return 1;
  2087. }
  2088. if (!strcmp(name, "offsetWidth") || !strcmp(name, "offsetHeight") ||
  2089. !strcmp(name, "clientWidth") || !strcmp(name, "clientHeight") ||
  2090. !strcmp(name, "scrollWidth") || !strcmp(name, "scrollHeight")) {
  2091. int x = 0, y = 0, w = 0, h = 0;
  2092. /* Before the first layout an element has no box; a block's
  2093. * width is then best guessed as the viewport (Vue apps measure
  2094. * offsetWidth on mount and pick a phone layout for 0). A
  2095. * resize event after layout lets them measure again. */
  2096. if (!host.rect || !host.rect(node, &x, &y, &w, &h))
  2097. w = n->type == BR_NODE_ELEM ? (int)host.width : 0;
  2098. js_pushnumber(state, (!strcmp(name, "offsetHeight") ||
  2099. !strcmp(name, "clientHeight") ||
  2100. !strcmp(name, "scrollHeight")) ? h : w);
  2101. return 1;
  2102. }
  2103. if (!strcmp(name, "scrollTop") || !strcmp(name, "scrollLeft")) {
  2104. js_pushnumber(state, 0);
  2105. return 1;
  2106. }
  2107. if (!strcmp(name, "click")) {
  2108. push_func_data(state, "click", node_click, 0, node + 1);
  2109. return 1;
  2110. }
  2111. if (!strcmp(name, "focus") || !strcmp(name, "blur")) {
  2112. push_func_data(state, name, node_noop, 0, node + 1);
  2113. return 1;
  2114. }
  2115. return 0;
  2116. }
  2117. static void node_set_string(unsigned int node, const char *name,
  2118. const char *value)
  2119. {
  2120. br_set_attr(D, node, name, value, (unsigned int)strlen(value));
  2121. if (host.changed)
  2122. host.changed();
  2123. }
  2124. static int node_put(js_State *state, void *p, const char *name)
  2125. {
  2126. unsigned int node = node_of(p);
  2127. if (!D || node >= D->nnode)
  2128. return 0;
  2129. if (!strcmp(name, "textContent") || !strcmp(name, "innerText")) {
  2130. const char *text = js_tostring(state, -1);
  2131. unsigned int len = (unsigned int)strlen(text);
  2132. if (br_set_text_content(D, node, text, len) != 0) {
  2133. if (host.status)
  2134. host.status("Page text arena is full", 1);
  2135. } else if (host.changed) {
  2136. host.changed();
  2137. }
  2138. return 1;
  2139. }
  2140. if (!strcmp(name, "nodeValue")) {
  2141. const char *text = js_tostring(state, -1);
  2142. if (br_set_text_node(D, node, text,
  2143. (unsigned int)strlen(text)) == 0 &&
  2144. host.changed)
  2145. host.changed();
  2146. return 1;
  2147. }
  2148. if (!strcmp(name, "id") || !strcmp(name, "className") ||
  2149. !strcmp(name, "href") || !strcmp(name, "src") ||
  2150. !strcmp(name, "value") || !strcmp(name, "type") ||
  2151. !strcmp(name, "name") || !strcmp(name, "alt") ||
  2152. !strcmp(name, "title")) {
  2153. const char *value = js_tostring(state, -1);
  2154. if (!strcmp(name, "value") && host.form_set_value &&
  2155. host.form_set_value(node, value))
  2156. return 1;
  2157. if (!strcmp(name, "className"))
  2158. node_set_string(node, "class", value);
  2159. else
  2160. node_set_string(node, name, value);
  2161. return 1;
  2162. }
  2163. if (!strcmp(name, "selectedIndex")) {
  2164. if (host.form_set_selected)
  2165. host.form_set_selected(node, js_tointeger(state, -1));
  2166. return 1;
  2167. }
  2168. if (!strcmp(name, "checked") || !strcmp(name, "disabled") ||
  2169. !strcmp(name, "selected")) {
  2170. int b = js_toboolean(state, -1);
  2171. if (!strcmp(name, "checked") && host.form_set_checked &&
  2172. host.form_set_checked(node, b))
  2173. return 1;
  2174. if (!strcmp(name, "selected") && host.form_set_selected &&
  2175. host.form_set_selected(node, b ? 1 : 0))
  2176. return 1;
  2177. if (b)
  2178. br_set_attr(D, node, name, "", 0);
  2179. else
  2180. br_remove_attr(D, node, name);
  2181. if (host.changed)
  2182. host.changed();
  2183. return 1;
  2184. }
  2185. if (!strcmp(name, "innerHTML")) {
  2186. const char *html = js_tostring(state, -1);
  2187. char key[32];
  2188. br_set_inner_html(D, node, html, (unsigned int)strlen(html));
  2189. snprintf(key, sizeof(key), "html_%u", node + 1);
  2190. js_pushstring(state, html);
  2191. js_setregistry(state, key);
  2192. if (host.changed)
  2193. host.changed();
  2194. return 1;
  2195. }
  2196. if (!strcmp(name, "outerHTML")) {
  2197. char key[32];
  2198. snprintf(key, sizeof(key), "html_%u", node + 1);
  2199. js_pushstring(state, js_tostring(state, -1));
  2200. js_setregistry(state, key);
  2201. return 1;
  2202. }
  2203. if (!strcmp(name, "style")) {
  2204. if (js_isstring(state, -1))
  2205. node_set_string(node, "style",
  2206. js_tostring(state, -1));
  2207. return 1;
  2208. }
  2209. return 0;
  2210. }
  2211. static int node_delete(js_State *state, void *p, const char *name)
  2212. {
  2213. (void)state;
  2214. (void)p;
  2215. (void)name;
  2216. return 0;
  2217. }
  2218. static void doc_getelementbyid(js_State *state)
  2219. {
  2220. const char *id = js_tostring(state, 1);
  2221. push_node(state, br_find_id(D, id));
  2222. }
  2223. static void console_log(js_State *state)
  2224. {
  2225. int i;
  2226. int n = js_gettop(state);
  2227. for (i = 1; i < n; i++) {
  2228. if (i > 1)
  2229. u_putc(' ');
  2230. u_puts(js_tostring(state, i));
  2231. }
  2232. u_putc('\n');
  2233. }
  2234. static void js_alert(js_State *state)
  2235. {
  2236. char msg[160];
  2237. unsigned int used = 0;
  2238. int i;
  2239. int n = js_gettop(state);
  2240. for (i = 1; i < n; i++) {
  2241. const char *s = js_tostring(state, i);
  2242. unsigned int k;
  2243. if (i > 1 && used + 1 < sizeof(msg))
  2244. msg[used++] = ' ';
  2245. for (k = 0; s[k] && used + 1 < sizeof(msg); k++)
  2246. msg[used++] = s[k];
  2247. }
  2248. msg[used] = '\0';
  2249. if (host.status)
  2250. host.status(msg, 0);
  2251. }
  2252. static void push_query_array(js_State *state, unsigned int root,
  2253. const char *selector)
  2254. {
  2255. unsigned int out[256];
  2256. unsigned int n = br_query_all(D, root, selector, out, 256);
  2257. unsigned int i;
  2258. js_newarray(state);
  2259. for (i = 0; i < n; i++) {
  2260. push_node(state, out[i]);
  2261. js_setindex(state, -2, (int)i);
  2262. }
  2263. }
  2264. static void doc_create_element(js_State *state)
  2265. {
  2266. const char *name = js_tostring(state, 1);
  2267. char lower[32];
  2268. unsigned int i;
  2269. for (i = 0; name[i] && i + 1 < sizeof(lower); i++) {
  2270. char c = name[i];
  2271. if (c >= 'A' && c <= 'Z')
  2272. c = (char)(c - 'A' + 'a');
  2273. lower[i] = c;
  2274. }
  2275. lower[i] = '\0';
  2276. push_node(state, br_create_element(D, lower, i));
  2277. }
  2278. static void doc_create_text(js_State *state)
  2279. {
  2280. const char *text = js_tostring(state, 1);
  2281. push_node(state, br_create_text(D, text, (unsigned int)strlen(text)));
  2282. }
  2283. static void doc_create_comment(js_State *state)
  2284. {
  2285. const char *text = js_tostring(state, 1);
  2286. push_node(state, br_create_comment(D, text, (unsigned int)strlen(text)));
  2287. }
  2288. static void doc_create_fragment(js_State *state)
  2289. {
  2290. push_node(state, br_create_fragment(D));
  2291. }
  2292. static void doc_create_attribute(js_State *state)
  2293. {
  2294. const char *name = js_tostring(state, 1);
  2295. js_newobject(state);
  2296. js_pushstring(state, name);
  2297. js_setproperty(state, -2, "name");
  2298. js_pushstring(state, "");
  2299. js_setproperty(state, -2, "value");
  2300. js_pushboolean(state, 1);
  2301. js_setproperty(state, -2, "specified");
  2302. }
  2303. static void doc_getelementsbytagname(js_State *state)
  2304. {
  2305. push_query_array(state, 0, js_tostring(state, 1));
  2306. }
  2307. static void doc_getelementsbyclassname(js_State *state)
  2308. {
  2309. const char *name = js_tostring(state, 1);
  2310. char sel[256];
  2311. unsigned int n = 0, i = 0;
  2312. while (name[i] && n + 2 < sizeof(sel)) {
  2313. while (name[i] == ' ')
  2314. i++;
  2315. if (!name[i])
  2316. break;
  2317. sel[n++] = '.';
  2318. while (name[i] && name[i] != ' ' && n + 1 < sizeof(sel))
  2319. sel[n++] = name[i++];
  2320. }
  2321. sel[n] = '\0';
  2322. push_query_array(state, 0, sel);
  2323. }
  2324. static void doc_queryselector(js_State *state)
  2325. {
  2326. unsigned int out[1];
  2327. unsigned int n = br_query_all(D, 0, js_tostring(state, 1), out, 1);
  2328. if (n)
  2329. push_node(state, out[0]);
  2330. else
  2331. js_pushnull(state);
  2332. }
  2333. static void doc_queryselectorall(js_State *state)
  2334. {
  2335. push_query_array(state, 0, js_tostring(state, 1));
  2336. }
  2337. static void location_get(js_State *state)
  2338. {
  2339. js_pushstring(state, current_url ? current_url : "");
  2340. }
  2341. /* Length of a URL without its #fragment. */
  2342. static unsigned int url_doc_len(const char *u)
  2343. {
  2344. unsigned int n = 0;
  2345. while (u[n] && u[n] != '#')
  2346. n++;
  2347. return n;
  2348. }
  2349. /* Navigate, or, when only the #fragment changes, stay on the page: the
  2350. * host updates the URL (location.href follows it) and a hashchange event is
  2351. * queued. Hash-routed apps (the Cloudron dashboard) navigate this way; a
  2352. * reload would restart the whole app. */
  2353. static void location_go(const char *url)
  2354. {
  2355. char abs[1024];
  2356. unsigned int n;
  2357. if (!current_url || !url) {
  2358. if (host.navigate && url)
  2359. host.navigate(url);
  2360. return;
  2361. }
  2362. url_resolve(current_url, url, abs, sizeof(abs));
  2363. n = url_doc_len(abs);
  2364. if (host.set_hash && abs[n] == '#' && n == url_doc_len(current_url) &&
  2365. !strncmp(abs, current_url, n)) {
  2366. if (strcmp(abs, current_url) && host.set_hash(abs) == 0)
  2367. hash_pending = 1;
  2368. return;
  2369. }
  2370. if (host.navigate)
  2371. host.navigate(url);
  2372. }
  2373. static void location_set(js_State *state)
  2374. {
  2375. location_go(js_tostring(state, 1));
  2376. }
  2377. /* assign()/replace(): navigate (the history entry is not replaced yet). */
  2378. static void location_assign(js_State *state)
  2379. {
  2380. location_go(js_tostring(state, 1));
  2381. js_pushundefined(state);
  2382. }
  2383. static void location_hash_get(js_State *state)
  2384. {
  2385. const char *h = current_url ? strchr(current_url, '#') : 0;
  2386. js_pushstring(state, h && h[1] ? h : "");
  2387. }
  2388. static void location_hash_set(js_State *state)
  2389. {
  2390. const char *v = js_tostring(state, 1);
  2391. char url[1024];
  2392. unsigned int n;
  2393. if (!current_url)
  2394. return;
  2395. n = url_doc_len(current_url);
  2396. if (n + 2 >= sizeof(url))
  2397. return;
  2398. memcpy(url, current_url, n);
  2399. url[n] = '#';
  2400. snprintf(url + n + 1, sizeof(url) - n - 1, "%s", v[0] == '#' ? v + 1 : v);
  2401. location_go(url);
  2402. }
  2403. static void location_reload(js_State *state)
  2404. {
  2405. if (host.navigate && current_url)
  2406. host.navigate(current_url);
  2407. js_pushundefined(state);
  2408. }
  2409. static void location_tostring(js_State *state)
  2410. {
  2411. js_pushstring(state, current_url ? current_url : "");
  2412. }
  2413. static void win_noop(js_State *state);
  2414. struct loc_parts {
  2415. const char *protocol, *host, *hostname, *port, *path, *search, *hash;
  2416. const char *origin;
  2417. unsigned int protocol_len, host_len, hostname_len, port_len;
  2418. unsigned int path_len, search_len, hash_len, origin_len;
  2419. };
  2420. static void loc_split(const char *u, struct loc_parts *p)
  2421. {
  2422. unsigned int n = (unsigned int)strlen(u), i;
  2423. const char *rest;
  2424. memset(p, 0, sizeof(*p));
  2425. p->path = u;
  2426. p->path_len = n;
  2427. p->origin = "null";
  2428. p->origin_len = 4;
  2429. for (i = 0; i < n; i++)
  2430. if (u[i] == ':')
  2431. break;
  2432. if (i + 2 < n && u[i] == ':' && u[i + 1] == '/' && u[i + 2] == '/') {
  2433. const char *hosts = u + i + 3, *hoste = hosts;
  2434. while (*hoste && *hoste != '/' && *hoste != '?' && *hoste != '#')
  2435. hoste++;
  2436. p->protocol = u;
  2437. p->protocol_len = i + 1;
  2438. p->host = hosts;
  2439. p->host_len = (unsigned int)(hoste - hosts);
  2440. p->hostname = hosts;
  2441. p->hostname_len = p->host_len;
  2442. for (i = 0; i < p->hostname_len; i++)
  2443. if (hosts[i] == ':') {
  2444. p->port = hosts + i + 1;
  2445. p->port_len = p->hostname_len - i - 1;
  2446. p->hostname_len = i;
  2447. break;
  2448. }
  2449. p->origin = u;
  2450. p->origin_len = (unsigned int)(hoste - u);
  2451. rest = hoste;
  2452. } else {
  2453. p->protocol = "file:";
  2454. p->protocol_len = 5;
  2455. rest = u;
  2456. }
  2457. {
  2458. const char *q = rest;
  2459. while (*q && *q != '?' && *q != '#')
  2460. q++;
  2461. p->path = rest;
  2462. p->path_len = (unsigned int)(q - rest);
  2463. if (*q == '?') {
  2464. const char *s = q;
  2465. while (*q && *q != '#')
  2466. q++;
  2467. p->search = s;
  2468. p->search_len = (unsigned int)(q - s);
  2469. }
  2470. if (*q == '#') {
  2471. p->hash = q;
  2472. p->hash_len = (unsigned int)strlen(q);
  2473. }
  2474. }
  2475. }
  2476. static void push_location(js_State *state)
  2477. {
  2478. struct loc_parts p;
  2479. loc_split(current_url ? current_url : "", &p);
  2480. js_newobject(state);
  2481. js_newcfunction(state, location_get, "get href", 0);
  2482. js_newcfunction(state, location_set, "set href", 1);
  2483. js_defaccessor(state, -3, "href", 0);
  2484. #define LOC_FIELD(field) \
  2485. do { \
  2486. js_pushlstring(state, p.field ? p.field : "", \
  2487. p.field ? (int)p.field##_len : 0); \
  2488. js_setproperty(state, -2, #field); \
  2489. } while (0)
  2490. LOC_FIELD(protocol);
  2491. LOC_FIELD(host);
  2492. LOC_FIELD(hostname);
  2493. LOC_FIELD(port);
  2494. js_pushlstring(state, p.path ? p.path : "",
  2495. p.path ? (int)p.path_len : 0);
  2496. js_setproperty(state, -2, "pathname");
  2497. LOC_FIELD(search);
  2498. LOC_FIELD(origin);
  2499. #undef LOC_FIELD
  2500. js_newcfunction(state, location_hash_get, "get hash", 0);
  2501. js_newcfunction(state, location_hash_set, "set hash", 1);
  2502. js_defaccessor(state, -3, "hash", 0);
  2503. js_newcfunction(state, location_reload, "reload", 0);
  2504. js_setproperty(state, -2, "reload");
  2505. js_newcfunction(state, location_assign, "assign", 1);
  2506. js_setproperty(state, -2, "assign");
  2507. js_newcfunction(state, location_assign, "replace", 1);
  2508. js_setproperty(state, -2, "replace");
  2509. js_newcfunction(state, location_tostring, "toString", 0);
  2510. js_setproperty(state, -2, "toString");
  2511. }
  2512. /* ---- URL resolution for <a>/<area> URL properties ---- */
  2513. static int url_has_scheme(const char *s)
  2514. {
  2515. unsigned int i = 1;
  2516. if (!((s[0] >= 'a' && s[0] <= 'z') ||
  2517. (s[0] >= 'A' && s[0] <= 'Z')))
  2518. return 0;
  2519. while (s[i]) {
  2520. char c = s[i];
  2521. if (c == ':')
  2522. return 1;
  2523. if (!((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') ||
  2524. (c >= '0' && c <= '9') || c == '+' || c == '-' ||
  2525. c == '.'))
  2526. return 0;
  2527. i++;
  2528. }
  2529. return 0;
  2530. }
  2531. static void url_put(char *out, unsigned int cap, unsigned int *n,
  2532. const char *s, unsigned int len)
  2533. {
  2534. unsigned int i;
  2535. for (i = 0; i < len && *n + 1 < cap; i++)
  2536. out[(*n)++] = s[i];
  2537. }
  2538. /* Collapse //, /./ and /../ inside the path part of an absolute URL. */
  2539. static void url_normalize(char *url)
  2540. {
  2541. char tmp[1024];
  2542. char *path;
  2543. unsigned int n = 0, i = 0;
  2544. path = strstr(url, "://");
  2545. if (path) {
  2546. path += 3;
  2547. while (*path && *path != '/')
  2548. path++;
  2549. } else {
  2550. path = url;
  2551. }
  2552. if (path[0] != '/')
  2553. return;
  2554. /* The path only: ?query and #fragment are copied verbatim below. */
  2555. while (path[i] && path[i] != '?' && path[i] != '#') {
  2556. unsigned int start;
  2557. while (path[i] == '/')
  2558. i++;
  2559. start = i;
  2560. while (path[i] && path[i] != '/' && path[i] != '?' &&
  2561. path[i] != '#')
  2562. i++;
  2563. if (i == start)
  2564. continue;
  2565. if (i - start == 1 && path[start] == '.')
  2566. continue;
  2567. if (i - start == 2 && path[start] == '.' &&
  2568. path[start + 1] == '.') {
  2569. while (n > 0 && tmp[n - 1] != '/')
  2570. n--;
  2571. if (n > 0)
  2572. n--;
  2573. continue;
  2574. }
  2575. if (n + 1 < sizeof(tmp))
  2576. tmp[n++] = '/';
  2577. while (start < i && n + 1 < sizeof(tmp))
  2578. tmp[n++] = path[start++];
  2579. }
  2580. if (n == 0)
  2581. tmp[n++] = '/';
  2582. else if (i > 0 && path[i - 1] == '/' && n + 1 < sizeof(tmp))
  2583. tmp[n++] = '/'; /* keep "dir/" a directory */
  2584. while (path[i] && n + 1 < sizeof(tmp))
  2585. tmp[n++] = path[i++];
  2586. tmp[n] = '\0';
  2587. memcpy(path, tmp, n + 1);
  2588. }
  2589. static void url_resolve(const char *base, const char *rel,
  2590. char *out, unsigned int cap)
  2591. {
  2592. struct loc_parts bp;
  2593. unsigned int n = 0, i;
  2594. if (cap == 0)
  2595. return;
  2596. if (!rel[0]) {
  2597. url_put(out, cap, &n, base, (unsigned int)strlen(base));
  2598. out[n] = '\0';
  2599. return;
  2600. }
  2601. if (url_has_scheme(rel)) {
  2602. url_put(out, cap, &n, rel, (unsigned int)strlen(rel));
  2603. out[n] = '\0';
  2604. url_normalize(out);
  2605. return;
  2606. }
  2607. loc_split(base, &bp);
  2608. if (rel[0] == '/' && rel[1] == '/') {
  2609. url_put(out, cap, &n, bp.protocol, bp.protocol_len);
  2610. url_put(out, cap, &n, rel, (unsigned int)strlen(rel));
  2611. } else if (rel[0] == '/') {
  2612. url_put(out, cap, &n, bp.protocol, bp.protocol_len);
  2613. url_put(out, cap, &n, "//", 2);
  2614. url_put(out, cap, &n, bp.host, bp.host_len);
  2615. url_put(out, cap, &n, rel, (unsigned int)strlen(rel));
  2616. } else if (rel[0] == '#' || rel[0] == '?') {
  2617. url_put(out, cap, &n, bp.protocol, bp.protocol_len);
  2618. if (bp.host_len || (bp.protocol_len == 5 &&
  2619. bp.protocol[0] == 'f')) {
  2620. url_put(out, cap, &n, "//", 2);
  2621. url_put(out, cap, &n, bp.host, bp.host_len);
  2622. }
  2623. url_put(out, cap, &n, bp.path, bp.path_len);
  2624. if (rel[0] == '#')
  2625. url_put(out, cap, &n, bp.search, bp.search_len);
  2626. url_put(out, cap, &n, rel, (unsigned int)strlen(rel));
  2627. } else {
  2628. const char *dir_end = bp.path;
  2629. for (i = 0; i < bp.path_len; i++)
  2630. if (bp.path[i] == '/')
  2631. dir_end = bp.path + i + 1;
  2632. if (dir_end == bp.path)
  2633. dir_end = bp.path + bp.path_len;
  2634. url_put(out, cap, &n, bp.protocol, bp.protocol_len);
  2635. if (bp.host_len || (bp.protocol_len == 5 &&
  2636. bp.protocol[0] == 'f')) {
  2637. url_put(out, cap, &n, "//", 2);
  2638. url_put(out, cap, &n, bp.host, bp.host_len);
  2639. }
  2640. url_put(out, cap, &n, bp.path,
  2641. (unsigned int)(dir_end - bp.path));
  2642. url_put(out, cap, &n, rel, (unsigned int)strlen(rel));
  2643. }
  2644. out[n] = '\0';
  2645. url_normalize(out);
  2646. }
  2647. /* <a> URL properties are resolved against the page URL, like the DOM. */
  2648. static void push_element_url(js_State *state, unsigned int node,
  2649. const char *name)
  2650. {
  2651. char abs_url[512];
  2652. const char *href = br_find_attr(D, node, "href");
  2653. struct loc_parts p;
  2654. if (!href || !href[0]) {
  2655. js_pushstring(state, "");
  2656. return;
  2657. }
  2658. url_resolve(current_url ? current_url : "/", href,
  2659. abs_url, sizeof(abs_url));
  2660. loc_split(abs_url, &p);
  2661. if (!strcmp(name, "href"))
  2662. js_pushstring(state, abs_url);
  2663. else if (!strcmp(name, "protocol"))
  2664. js_pushlstring(state, p.protocol, (int)p.protocol_len);
  2665. else if (!strcmp(name, "origin"))
  2666. js_pushlstring(state, p.origin ? p.origin : "",
  2667. (int)p.origin_len);
  2668. else if (!strcmp(name, "host"))
  2669. js_pushlstring(state, p.host ? p.host : "", (int)p.host_len);
  2670. else if (!strcmp(name, "hostname"))
  2671. js_pushlstring(state, p.hostname ? p.hostname : "",
  2672. (int)p.hostname_len);
  2673. else if (!strcmp(name, "port"))
  2674. js_pushlstring(state, p.port ? p.port : "", (int)p.port_len);
  2675. else if (!strcmp(name, "pathname"))
  2676. js_pushlstring(state, p.path ? p.path : "", (int)p.path_len);
  2677. else if (!strcmp(name, "search"))
  2678. js_pushlstring(state, p.search ? p.search : "",
  2679. (int)p.search_len);
  2680. else
  2681. js_pushlstring(state, p.hash ? p.hash : "", (int)p.hash_len);
  2682. }
  2683. static void win_noop(js_State *state)
  2684. {
  2685. (void)state;
  2686. }
  2687. static void timer_add(js_State *state, int repeat)
  2688. {
  2689. int i;
  2690. unsigned int ms;
  2691. if (!js_iscallable(state, 1)) {
  2692. js_pushnumber(state, 0);
  2693. return;
  2694. }
  2695. ms = js_isdefined(state, 2) ?
  2696. (unsigned int)js_tointeger(state, 2) : 0;
  2697. if (repeat && ms == 0)
  2698. ms = 1;
  2699. for (i = 0; i < JS_TIMERS; i++)
  2700. if (!timers[i].used)
  2701. break;
  2702. if (i == JS_TIMERS) {
  2703. js_pushnumber(state, 0);
  2704. return;
  2705. }
  2706. js_copy(state, 1);
  2707. snprintf(timers[i].ref, sizeof(timers[i].ref), "%s",
  2708. js_ref(state));
  2709. timers[i].used = 1;
  2710. timers[i].repeat = repeat;
  2711. timers[i].interval = ms;
  2712. timers[i].deadline = u_ticks_ms() + ms;
  2713. js_pushnumber(state, i + 1);
  2714. }
  2715. static void win_settimeout(js_State *state)
  2716. {
  2717. timer_add(state, 0);
  2718. }
  2719. static void win_setinterval(js_State *state)
  2720. {
  2721. timer_add(state, 1);
  2722. }
  2723. static void timer_clear(js_State *state)
  2724. {
  2725. int id = js_tointeger(state, 1);
  2726. if (id >= 1 && id <= JS_TIMERS && timers[id - 1].used) {
  2727. js_unref(state, timers[id - 1].ref);
  2728. timers[id - 1].used = 0;
  2729. }
  2730. }
  2731. static void win_requestanimationframe(js_State *state)
  2732. {
  2733. timer_add(state, 0);
  2734. }
  2735. static void win_performance_now(js_State *state)
  2736. {
  2737. js_pushnumber(state, (double)u_ticks_ms());
  2738. }
  2739. struct computed_prop {
  2740. const char *js;
  2741. const char *css;
  2742. };
  2743. static const struct computed_prop computed_props[] = {
  2744. { "display", "display" }, { "position", "position" },
  2745. { "width", "width" }, { "height", "height" },
  2746. { "color", "color" }, { "backgroundColor", "background-color" },
  2747. { "fill", "fill" }, { "stroke", "stroke" },
  2748. { "fontSize", "font-size" }, { "fontWeight", "font-weight" },
  2749. { "fontStyle", "font-style" }, { "fontFamily", "font-family" },
  2750. { "textAlign", "text-align" }, { "float", "float" },
  2751. { "cssFloat", "float" }, { "clear", "clear" },
  2752. { "opacity", "opacity" }, { "visibility", "visibility" },
  2753. { "overflow", "overflow" }, { "whiteSpace", "white-space" },
  2754. { "textTransform", "text-transform" }, { "boxSizing", "box-sizing" },
  2755. { "lineHeight", "line-height" }, { "zIndex", "z-index" },
  2756. { "top", "top" }, { "left", "left" }, { "right", "right" },
  2757. { "bottom", "bottom" },
  2758. { "marginTop", "margin-top" }, { "marginRight", "margin-right" },
  2759. { "marginBottom", "margin-bottom" }, { "marginLeft", "margin-left" },
  2760. { "paddingTop", "padding-top" }, { "paddingRight", "padding-right" },
  2761. { "paddingBottom", "padding-bottom" },
  2762. { "paddingLeft", "padding-left" },
  2763. { "borderTopWidth", "border-top-width" },
  2764. { "borderRightWidth", "border-right-width" },
  2765. { "borderBottomWidth", "border-bottom-width" },
  2766. { "borderLeftWidth", "border-left-width" },
  2767. { "borderTopColor", "border-top-color" },
  2768. { "borderRightColor", "border-right-color" },
  2769. { "borderBottomColor", "border-bottom-color" },
  2770. { "borderLeftColor", "border-left-color" },
  2771. { "backgroundImage", "background-image" },
  2772. { "backgroundRepeat", "background-repeat" },
  2773. { "backgroundPosition", "background-position" },
  2774. { "backgroundSize", "background-size" },
  2775. { "transform", "transform" },
  2776. { 0, 0 }
  2777. };
  2778. static void computed_get(js_State *state)
  2779. {
  2780. unsigned int node = node_of(js_currentfunctiondata(state));
  2781. const char *prop = js_tostring(state, 1);
  2782. char buf[192];
  2783. if (host.computed && host.computed(node, prop, buf, sizeof(buf)))
  2784. js_pushstring(state, buf);
  2785. else
  2786. js_pushstring(state, "");
  2787. }
  2788. static void win_getcomputedstyle(js_State *state)
  2789. {
  2790. unsigned int node = 0;
  2791. char buf[192];
  2792. int i;
  2793. if (js_isuserdata(state, 1, "node"))
  2794. node = node_of(js_touserdata(state, 1, "node"));
  2795. js_newobject(state);
  2796. def_func_data(state, "getPropertyValue", computed_get, 1, node + 1);
  2797. for (i = 0; computed_props[i].js; i++) {
  2798. if (!host.computed ||
  2799. !host.computed(node, computed_props[i].css, buf,
  2800. sizeof(buf)))
  2801. continue;
  2802. js_pushstring(state, buf);
  2803. js_setproperty(state, -2, computed_props[i].js);
  2804. }
  2805. js_pushstring(state, "");
  2806. js_setproperty(state, -2, "cssText");
  2807. }
  2808. static void win_matchmedia(js_State *state)
  2809. {
  2810. const char *query = js_tostring(state, 1);
  2811. js_newobject(state);
  2812. js_pushboolean(state, 0);
  2813. js_setproperty(state, -2, "matches");
  2814. js_pushstring(state, query);
  2815. js_setproperty(state, -2, "media");
  2816. def_func(state, "addListener", win_noop, 1);
  2817. def_func(state, "removeListener", win_noop, 1);
  2818. def_func(state, "addEventListener", win_noop, 2);
  2819. def_func(state, "removeEventListener", win_noop, 2);
  2820. }
  2821. static void rellist_supports(js_State *state)
  2822. {
  2823. const char *t = js_tostring(state, 1);
  2824. js_pushboolean(state, !strcmp(t, "modulepreload") ||
  2825. !strcmp(t, "preload") || !strcmp(t, "stylesheet"));
  2826. }
  2827. /* ---- primitives for js_prelude.js ---- */
  2828. /* __nb_http(method, url, contentType, body) -> [status, ctype, url, text].
  2829. * Synchronous: the host fetches through its helpers while the script
  2830. * waits. A network failure throws (fetch() turns it into a TypeError). */
  2831. static void nb_http(js_State *state)
  2832. {
  2833. struct js_http_resp r;
  2834. const char *method = js_tostring(state, 1);
  2835. const char *url = js_tostring(state, 2);
  2836. const char *ctype = js_tostring(state, 3);
  2837. const char *body = js_tostring(state, 4);
  2838. char err[96];
  2839. int rv;
  2840. memset(&r, 0, sizeof(r));
  2841. err[0] = '\0';
  2842. rv = host.http ? host.http(method, url, ctype, body,
  2843. (unsigned int)strlen(body), &r, err,
  2844. (int)sizeof(err)) : -1;
  2845. /* The budget covers running JavaScript, not the network wait. */
  2846. js_setlimit(state, JS_RUN_LIMIT, 0);
  2847. if (rv != 0) {
  2848. free(r.body);
  2849. js_typeerror(state, "network error: %s",
  2850. err[0] ? err : "fetch failed");
  2851. }
  2852. js_newarray(state);
  2853. js_pushnumber(state, r.status);
  2854. js_setindex(state, -2, 0);
  2855. js_pushstring(state, r.ctype);
  2856. js_setindex(state, -2, 1);
  2857. js_pushstring(state, r.url);
  2858. js_setindex(state, -2, 2);
  2859. js_pushlstring(state, r.body ? r.body : "", (int)r.len);
  2860. js_setindex(state, -2, 3);
  2861. free(r.body);
  2862. }
  2863. #define JS_STORAGE_MAX (32u * 1024u)
  2864. /* __nb_storage(kind) -> text, __nb_storage(kind, text) stores it. */
  2865. static void nb_storage(js_State *state)
  2866. {
  2867. int kind = js_tointeger(state, 1);
  2868. char *buf;
  2869. int n;
  2870. if (js_isstring(state, 2)) {
  2871. if (host.storage)
  2872. host.storage(kind, js_tostring(state, 2), 0, 0);
  2873. js_pushundefined(state);
  2874. return;
  2875. }
  2876. buf = (char *)malloc(JS_STORAGE_MAX);
  2877. n = buf && host.storage ?
  2878. host.storage(kind, 0, buf, (int)JS_STORAGE_MAX) : -1;
  2879. if (n > 0)
  2880. js_pushlstring(state, buf, n);
  2881. else
  2882. js_pushstring(state, "");
  2883. free(buf);
  2884. }
  2885. static void url_resolve(const char *base, const char *rel,
  2886. char *out, unsigned int cap);
  2887. static void nb_resolve(js_State *state)
  2888. {
  2889. char out[512];
  2890. url_resolve(js_tostring(state, 1), js_tostring(state, 2), out,
  2891. sizeof(out));
  2892. js_pushstring(state, out);
  2893. }
  2894. extern const char js_prelude_source[];
  2895. static void install_prelude(js_State *state)
  2896. {
  2897. js_newcfunction(state, nb_http, "__nb_http", 4);
  2898. js_defglobal(state, "__nb_http", 0);
  2899. js_newcfunction(state, nb_storage, "__nb_storage", 2);
  2900. js_defglobal(state, "__nb_storage", 0);
  2901. js_newcfunction(state, nb_resolve, "__nb_resolve", 2);
  2902. js_defglobal(state, "__nb_resolve", 0);
  2903. js_getregistry(state, "nodeproto");
  2904. js_defglobal(state, "__nb_nodeproto", 0);
  2905. if (js_ploadstring(state, "[prelude]", js_prelude_source)) {
  2906. report_top(state);
  2907. return;
  2908. }
  2909. js_pushundefined(state);
  2910. if (js_pcall(state, 0))
  2911. report_top(state);
  2912. else
  2913. js_pop(state, 1);
  2914. }
  2915. static void install_globals(js_State *state)
  2916. {
  2917. unsigned int h;
  2918. /* Shared prototype of the node/style/dataset wrappers. */
  2919. js_newobject(state);
  2920. js_setregistry(state, "wrapproto");
  2921. /* DOM node wrappers: their own prototype, so the prelude can add the
  2922. * Element methods there without touching style/dataset objects. */
  2923. js_newobject(state);
  2924. js_setregistry(state, "nodeproto");
  2925. js_newobject(state);
  2926. def_func(state, "getElementById", doc_getelementbyid, 1);
  2927. def_func(state, "createElement", doc_create_element, 1);
  2928. def_func(state, "createTextNode", doc_create_text, 1);
  2929. def_func(state, "createComment", doc_create_comment, 1);
  2930. def_func(state, "createDocumentFragment", doc_create_fragment, 0);
  2931. def_func(state, "createAttribute", doc_create_attribute, 1);
  2932. def_func(state, "getElementsByTagName", doc_getelementsbytagname, 1);
  2933. def_func(state, "getElementsByClassName", doc_getelementsbyclassname, 1);
  2934. def_func(state, "querySelector", doc_queryselector, 1);
  2935. def_func(state, "querySelectorAll", doc_queryselectorall, 1);
  2936. def_func(state, "addEventListener", doc_addlistener, 2);
  2937. def_func(state, "removeEventListener", doc_removelistener, 2);
  2938. def_func(state, "dispatchEvent", doc_dispatchevent, 1);
  2939. def_func(state, "createEvent", doc_createevent, 1);
  2940. h = br_find_tag(D, BR_TAG_HTML);
  2941. if (!h && D->nnode > 1)
  2942. h = D->nodes[0].first ? D->nodes[0].first + 1 : 0;
  2943. push_node(state, h);
  2944. js_setproperty(state, -2, "documentElement");
  2945. h = br_find_tag(D, BR_TAG_BODY);
  2946. push_node(state, h);
  2947. js_setproperty(state, -2, "body");
  2948. h = br_find_tag(D, BR_TAG_HEAD);
  2949. push_node(state, h);
  2950. js_setproperty(state, -2, "head");
  2951. js_pushnumber(state, 9);
  2952. js_setproperty(state, -2, "nodeType");
  2953. js_pushstring(state, "#document");
  2954. js_setproperty(state, -2, "nodeName");
  2955. js_pushnull(state);
  2956. js_setproperty(state, -2, "ownerDocument");
  2957. js_pushstring(state, "CSS1Compat");
  2958. js_setproperty(state, -2, "compatMode");
  2959. js_pushstring(state, D->title);
  2960. js_setproperty(state, -2, "title");
  2961. js_pushstring(state, "complete");
  2962. js_setproperty(state, -2, "readyState");
  2963. js_pushnull(state);
  2964. js_setproperty(state, -2, "currentScript");
  2965. js_pushstring(state, "");
  2966. js_setproperty(state, -2, "cookie");
  2967. js_pushstring(state, current_url ? current_url : "");
  2968. js_setproperty(state, -2, "URL");
  2969. js_defglobal(state, "document", JS_DONTENUM);
  2970. js_newobject(state);
  2971. js_newcfunction(state, console_log, "log", 0);
  2972. js_setproperty(state, -2, "log");
  2973. js_defglobal(state, "console", JS_DONTENUM);
  2974. js_newcfunction(state, js_alert, "alert", 1);
  2975. js_defglobal(state, "alert", JS_DONTENUM);
  2976. js_newcfunction(state, event_call, "Event", 1);
  2977. js_defglobal(state, "Event", JS_DONTENUM);
  2978. js_newcfunction(state, custom_event_call, "CustomEvent", 1);
  2979. js_defglobal(state, "CustomEvent", JS_DONTENUM);
  2980. js_newcfunction(state, mouse_event_call, "MouseEvent", 1);
  2981. js_defglobal(state, "MouseEvent", JS_DONTENUM);
  2982. push_location(state);
  2983. js_defglobal(state, "location", JS_DONTENUM);
  2984. js_newobject(state);
  2985. js_pushstring(state, "Mozilla/5.0 (X11; Linux i686) NebOS/0.2");
  2986. js_setproperty(state, -2, "userAgent");
  2987. js_pushstring(state, "NebOS");
  2988. js_setproperty(state, -2, "platform");
  2989. js_pushstring(state, "en-US");
  2990. js_setproperty(state, -2, "language");
  2991. js_defglobal(state, "navigator", JS_DONTENUM);
  2992. js_newobject(state);
  2993. js_pushnumber(state, 1);
  2994. js_setproperty(state, -2, "length");
  2995. def_func(state, "pushState", win_noop, 3);
  2996. def_func(state, "replaceState", win_noop, 3);
  2997. def_func(state, "back", win_noop, 0);
  2998. def_func(state, "forward", win_noop, 0);
  2999. def_func(state, "go", win_noop, 1);
  3000. js_defglobal(state, "history", JS_DONTENUM);
  3001. def_global_func(state, "matchMedia", win_matchmedia, 1);
  3002. def_global_func(state, "getComputedStyle", win_getcomputedstyle, 1);
  3003. def_global_func(state, "addEventListener", win_addlistener, 2);
  3004. def_global_func(state, "removeEventListener", win_removelistener, 2);
  3005. def_global_func(state, "dispatchEvent", win_dispatchevent, 1);
  3006. def_global_func(state, "scrollTo", win_noop, 2);
  3007. def_global_func(state, "scrollBy", win_noop, 2);
  3008. def_global_func(state, "setTimeout", win_settimeout, 1);
  3009. def_global_func(state, "setInterval", win_setinterval, 1);
  3010. def_global_func(state, "clearTimeout", timer_clear, 1);
  3011. def_global_func(state, "clearInterval", timer_clear, 1);
  3012. def_global_func(state, "requestAnimationFrame", win_requestanimationframe, 1);
  3013. def_global_func(state, "cancelAnimationFrame", timer_clear, 1);
  3014. js_newobject(state);
  3015. def_func(state, "now", win_performance_now, 0);
  3016. js_newobject(state);
  3017. js_setproperty(state, -2, "timing");
  3018. js_defglobal(state, "performance", JS_DONTENUM);
  3019. js_pushnumber(state, host.width ? (int)host.width : 1024);
  3020. js_defglobal(state, "innerWidth", JS_DONTENUM);
  3021. js_pushnumber(state, host.height ? (int)host.height : 768);
  3022. js_defglobal(state, "innerHeight", JS_DONTENUM);
  3023. js_pushnumber(state, 0);
  3024. js_defglobal(state, "pageXOffset", JS_DONTENUM);
  3025. js_pushnumber(state, 0);
  3026. js_defglobal(state, "pageYOffset", JS_DONTENUM);
  3027. js_pushnumber(state, 0);
  3028. js_defglobal(state, "scrollX", JS_DONTENUM);
  3029. js_pushnumber(state, 0);
  3030. js_defglobal(state, "scrollY", JS_DONTENUM);
  3031. js_pushnumber(state, 1);
  3032. js_defglobal(state, "devicePixelRatio", JS_DONTENUM);
  3033. js_pushglobal(state);
  3034. js_defglobal(state, "window", JS_DONTENUM);
  3035. js_pushglobal(state);
  3036. js_defglobal(state, "globalThis", JS_DONTENUM);
  3037. js_getglobal(state, "document");
  3038. js_getglobal(state, "location");
  3039. js_setproperty(state, -2, "location");
  3040. js_pop(state, 1);
  3041. js_getglobal(state, "document");
  3042. js_pushglobal(state);
  3043. js_setproperty(state, -2, "defaultView");
  3044. js_pop(state, 1);
  3045. }
  3046. static int module_resolve(const char *base, const char *name, char *out,
  3047. unsigned int cap)
  3048. {
  3049. url_resolve(base && base[0] ? base :
  3050. (current_url ? current_url : ""), name, out, cap);
  3051. return 0;
  3052. }
  3053. static char *module_load(const char *url, unsigned int *len)
  3054. {
  3055. char *src;
  3056. if (!host.load_script)
  3057. return 0;
  3058. src = host.load_script(url, len);
  3059. if (J)
  3060. js_setlimit(J, JS_RUN_LIMIT, 0);
  3061. if (!src && host.report) {
  3062. char msg[600];
  3063. snprintf(msg, sizeof(msg), "Cannot load module %s", url);
  3064. host.report(msg);
  3065. }
  3066. return src;
  3067. }
  3068. int js_browser_start(struct br_doc *doc, const struct js_browser_host *h)
  3069. {
  3070. if (!doc || !h)
  3071. return -1;
  3072. D = doc;
  3073. host = *h;
  3074. host_changed_orig = host.changed;
  3075. host.changed = dom_changed;
  3076. dom_dirty = 0;
  3077. current_url = h->page_url;
  3078. panic_armed = 0;
  3079. memset(timers, 0, sizeof(timers));
  3080. memset(listeners, 0, sizeof(listeners));
  3081. memset(events, 0, sizeof(events));
  3082. memset(event_templates, 0, sizeof(event_templates));
  3083. /* Classic scripts are sloppy by default in browsers; strict mode is
  3084. * opt-in via a "use strict" directive. */
  3085. J = js_newstate(0, 0, 0);
  3086. if (!J)
  3087. return -1;
  3088. js_setreport(J, report_cb);
  3089. js_atpanic(J, panic_cb);
  3090. js_setmodulehost(J, module_resolve, module_load);
  3091. install_globals(J);
  3092. js_setlimit(J, JS_RUN_LIMIT, 0);
  3093. install_prelude(J);
  3094. return 0;
  3095. }
  3096. void js_browser_stop(void)
  3097. {
  3098. if (J)
  3099. js_freestate(J);
  3100. J = 0;
  3101. D = 0;
  3102. current_url = 0;
  3103. panic_armed = 0;
  3104. memset(timers, 0, sizeof(timers));
  3105. }
  3106. int js_browser_active(void)
  3107. {
  3108. return J != 0;
  3109. }
  3110. static void report_top(js_State *state)
  3111. {
  3112. const char *msg;
  3113. /* An "interrupted" error leaves the deadline expired: formatting the
  3114. * error runs JavaScript (toString), which would be interrupted too. */
  3115. js_setlimit(state, 0, 0);
  3116. js_getproperty(state, -1, "stack");
  3117. if (js_isstring(state, -1)) {
  3118. /* QuickJS's stack is only the frames: lead with
  3119. * "Name: message" like the MuJS reports did. */
  3120. char buf[768];
  3121. const char *head = js_trystring(state, -2, "JavaScript error");
  3122. snprintf(buf, sizeof(buf), "%s\n%s", head,
  3123. js_tostring(state, -1));
  3124. msg = buf;
  3125. if (host.report)
  3126. host.report(msg);
  3127. js_pop(state, 1);
  3128. } else {
  3129. js_pop(state, 1);
  3130. msg = js_trystring(state, -1, "JavaScript error");
  3131. if (host.report)
  3132. host.report(msg);
  3133. }
  3134. js_pop(state, 1);
  3135. }
  3136. void js_browser_window_event(const char *type)
  3137. {
  3138. if (J && D)
  3139. js_browser_event(JS_TARGET_WINDOW, type, 0, 0);
  3140. }
  3141. void js_browser_hashchange(void)
  3142. {
  3143. hash_pending = 1;
  3144. }
  3145. void js_browser_tick(void)
  3146. {
  3147. unsigned int now;
  3148. int i, ran = 0;
  3149. if (!J)
  3150. return;
  3151. if (hash_pending) {
  3152. hash_pending = 0;
  3153. js_browser_event(JS_TARGET_WINDOW, "hashchange", 0, 0);
  3154. if (!J)
  3155. return;
  3156. }
  3157. if (dom_dirty) {
  3158. dom_dirty = 0;
  3159. js_setlimit(J, JS_RUN_LIMIT, 0);
  3160. js_getglobal(J, "__nb_ce_scan");
  3161. if (js_iscallable(J, -1)) {
  3162. js_pushundefined(J);
  3163. if (js_pcall(J, 0))
  3164. report_top(J);
  3165. else
  3166. js_pop(J, 1);
  3167. } else {
  3168. js_pop(J, 1);
  3169. }
  3170. if (!J)
  3171. return;
  3172. }
  3173. now = u_ticks_ms();
  3174. for (i = 0; i < JS_TIMERS; i++) {
  3175. if (!timers[i].used ||
  3176. (int)(now - timers[i].deadline) < 0)
  3177. continue;
  3178. js_setlimit(J, JS_RUN_LIMIT, 0);
  3179. js_getregistry(J, timers[i].ref);
  3180. if (!js_iscallable(J, -1)) {
  3181. js_pop(J, 1);
  3182. js_unref(J, timers[i].ref);
  3183. timers[i].used = 0;
  3184. continue;
  3185. }
  3186. js_pushundefined(J);
  3187. if (js_pcall(J, 0))
  3188. report_top(J);
  3189. else
  3190. js_pop(J, 1);
  3191. if (timers[i].used) {
  3192. if (timers[i].repeat)
  3193. timers[i].deadline = now + timers[i].interval;
  3194. else {
  3195. js_unref(J, timers[i].ref);
  3196. timers[i].used = 0;
  3197. }
  3198. }
  3199. if (++ran >= JS_TIMERS_PER_TICK)
  3200. break;
  3201. }
  3202. js_runjobs(J);
  3203. }
  3204. void js_browser_set_current_script(unsigned int node)
  3205. {
  3206. if (!J || !D)
  3207. return;
  3208. js_getglobal(J, "document");
  3209. if (node && node < D->nnode)
  3210. push_node(J, node);
  3211. else
  3212. js_pushnull(J);
  3213. js_setproperty(J, -2, "currentScript");
  3214. js_pop(J, 1);
  3215. }
  3216. int js_browser_run(const char *source, const char *url)
  3217. {
  3218. int r;
  3219. if (!J || !D)
  3220. return -1;
  3221. js_setlimit(J, JS_RUN_LIMIT, 0);
  3222. panic_armed = 1;
  3223. if (setjmp(panic_env)) {
  3224. panic_armed = 0;
  3225. if (host.report)
  3226. host.report("uncaught JavaScript exception");
  3227. /* The try/exception stack is unusable after a panic. Leak the
  3228. * state; the page heap reset on navigation reclaims it. */
  3229. J = 0;
  3230. D = 0;
  3231. return -1;
  3232. }
  3233. if (js_ploadstring(J, url ? url : "[inline]", source)) {
  3234. report_top(J);
  3235. panic_armed = 0;
  3236. return -1;
  3237. }
  3238. js_pushundefined(J);
  3239. r = js_pcall(J, 0);
  3240. if (r) {
  3241. report_top(J);
  3242. panic_armed = 0;
  3243. return -1;
  3244. }
  3245. js_pop(J, 1);
  3246. js_runjobs(J);
  3247. panic_armed = 0;
  3248. return 0;
  3249. }
  3250. /* Run a <script type="module">: imports are resolved against `url` and
  3251. * loaded through host.load_script. */
  3252. int js_browser_run_module(const char *source, const char *url)
  3253. {
  3254. if (!J || !D)
  3255. return -1;
  3256. js_setlimit(J, JS_RUN_LIMIT, 0);
  3257. panic_armed = 1;
  3258. if (setjmp(panic_env)) {
  3259. panic_armed = 0;
  3260. if (host.report)
  3261. host.report("uncaught JavaScript exception");
  3262. J = 0;
  3263. D = 0;
  3264. return -1;
  3265. }
  3266. if (js_ploadmodule(J, url ? url : "[module]", source)) {
  3267. report_top(J);
  3268. panic_armed = 0;
  3269. return -1;
  3270. }
  3271. js_pop(J, 1);
  3272. panic_armed = 0;
  3273. return 0;
  3274. }