js_browser.c 93 KB

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