js_browser.c 91 KB

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