js_browser.c 94 KB

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