js_browser.c 93 KB

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