event-dispatch.mjs 59 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544
  1. /**
  2. * @license Angular v19.2.4
  3. * (c) 2010-2025 Google LLC. https://angular.io/
  4. * License: MIT
  5. */
  6. const Attribute = {
  7. /**
  8. * The jsaction attribute defines a mapping of a DOM event to a
  9. * generic event (aka jsaction), to which the actual event handlers
  10. * that implement the behavior of the application are bound. The
  11. * value is a semicolon separated list of colon separated pairs of
  12. * an optional DOM event name and a jsaction name. If the optional
  13. * DOM event name is omitted, 'click' is assumed. The jsaction names
  14. * are dot separated pairs of a namespace and a simple jsaction
  15. * name.
  16. *
  17. * See grammar in README.md for expected syntax in the attribute value.
  18. */
  19. JSACTION: 'jsaction',
  20. };
  21. /** All properties that are used by jsaction. */
  22. const Property = {
  23. /**
  24. * The parsed value of the jsaction attribute is stored in this
  25. * property on the DOM node. The parsed value is an Object. The
  26. * property names of the object are the events; the values are the
  27. * names of the actions. This property is attached even on nodes
  28. * that don't have a jsaction attribute as an optimization, because
  29. * property lookup is faster than attribute access.
  30. */
  31. JSACTION: '__jsaction',
  32. /**
  33. * The owner property references an a logical owner for a DOM node. JSAction
  34. * will follow this reference instead of parentNode when traversing the DOM
  35. * to find jsaction attributes. This allows overlaying a logical structure
  36. * over a document where the DOM structure can't reflect that structure.
  37. */
  38. OWNER: '__owner',
  39. };
  40. /**
  41. * Map from jsaction annotation to a parsed map from event name to action name.
  42. */
  43. const parseCache = {};
  44. /**
  45. * Reads the jsaction parser cache from the given DOM Element.
  46. */
  47. function get(element) {
  48. return element[Property.JSACTION];
  49. }
  50. /**
  51. * Reads the jsaction parser cache for the given DOM element. If no cache is yet present,
  52. * creates an empty one.
  53. */
  54. function getDefaulted(element) {
  55. const cache = get(element) ?? {};
  56. set(element, cache);
  57. return cache;
  58. }
  59. /**
  60. * Writes the jsaction parser cache to the given DOM Element.
  61. */
  62. function set(element, actionMap) {
  63. element[Property.JSACTION] = actionMap;
  64. }
  65. /**
  66. * Looks up the parsed action map from the source jsaction attribute value.
  67. *
  68. * @param text Unparsed jsaction attribute value.
  69. * @return Parsed jsaction attribute value, if already present in the cache.
  70. */
  71. function getParsed(text) {
  72. return parseCache[text];
  73. }
  74. /**
  75. * Inserts the parse result for the given source jsaction value into the cache.
  76. *
  77. * @param text Unparsed jsaction attribute value.
  78. * @param parsed Attribute value parsed into the action map.
  79. */
  80. function setParsed(text, parsed) {
  81. parseCache[text] = parsed;
  82. }
  83. /*
  84. * Names of events that are special to jsaction. These are not all
  85. * event types that are legal to use in either HTML or the addEvent()
  86. * API, but these are the ones that are treated specially. All other
  87. * DOM events can be used in either addEvent() or in the value of the
  88. * jsaction attribute. Beware of browser specific events or events
  89. * that don't bubble though: If they are not mentioned here, then
  90. * event contract doesn't work around their peculiarities.
  91. */
  92. const EventType = {
  93. /**
  94. * The click event. In addEvent() refers to all click events, in the
  95. * jsaction attribute it refers to the unmodified click and Enter/Space
  96. * keypress events. In the latter case, a jsaction click will be triggered,
  97. * for accessibility reasons. See clickmod and clickonly, below.
  98. */
  99. CLICK: 'click',
  100. /**
  101. * Specifies the jsaction for a modified click event (i.e. a mouse
  102. * click with the modifier key Cmd/Ctrl pressed). This event isn't
  103. * separately enabled in addEvent(), because in the DOM, it's just a
  104. * click event.
  105. */
  106. CLICKMOD: 'clickmod',
  107. /**
  108. * The dblclick event.
  109. */
  110. DBLCLICK: 'dblclick',
  111. /**
  112. * Focus doesn't bubble, but you can use it in addEvent() and
  113. * jsaction anyway. EventContract does the right thing under the
  114. * hood.
  115. */
  116. FOCUS: 'focus',
  117. /**
  118. * This event only exists in IE. For addEvent() and jsaction, use
  119. * focus instead; EventContract does the right thing even though
  120. * focus doesn't bubble.
  121. */
  122. FOCUSIN: 'focusin',
  123. /**
  124. * Analog to focus.
  125. */
  126. BLUR: 'blur',
  127. /**
  128. * Analog to focusin.
  129. */
  130. FOCUSOUT: 'focusout',
  131. /**
  132. * Submit doesn't bubble, so it cannot be used with event
  133. * contract. However, the browser helpfully fires a click event on
  134. * the submit button of a form (even if the form is not submitted by
  135. * a click on the submit button). So you should handle click on the
  136. * submit button instead.
  137. */
  138. SUBMIT: 'submit',
  139. /**
  140. * The keydown event. In addEvent() and non-click jsaction it represents the
  141. * regular DOM keydown event. It represents click actions in non-Gecko
  142. * browsers.
  143. */
  144. KEYDOWN: 'keydown',
  145. /**
  146. * The keypress event. In addEvent() and non-click jsaction it represents the
  147. * regular DOM keypress event. It represents click actions in Gecko browsers.
  148. */
  149. KEYPRESS: 'keypress',
  150. /**
  151. * The keyup event. In addEvent() and non-click jsaction it represents the
  152. * regular DOM keyup event. It represents click actions in non-Gecko
  153. * browsers.
  154. */
  155. KEYUP: 'keyup',
  156. /**
  157. * The mouseover event. Can either be used directly or used implicitly to
  158. * capture mouseenter events. In addEvent(), it represents a regular DOM
  159. * mouseover event.
  160. */
  161. MOUSEOVER: 'mouseover',
  162. /**
  163. * The mouseout event. Can either be used directly or used implicitly to
  164. * capture mouseover events. In addEvent(), it represents a regular DOM
  165. * mouseout event.
  166. */
  167. MOUSEOUT: 'mouseout',
  168. /**
  169. * The mouseenter event. Does not bubble and fires individually on each
  170. * element being entered within a DOM tree.
  171. */
  172. MOUSEENTER: 'mouseenter',
  173. /**
  174. * The mouseleave event. Does not bubble and fires individually on each
  175. * element being entered within a DOM tree.
  176. */
  177. MOUSELEAVE: 'mouseleave',
  178. /**
  179. * The pointerover event. Can either be used directly or used implicitly to
  180. * capture pointerenter events. In addEvent(), it represents a regular DOM
  181. * pointerover event.
  182. */
  183. POINTEROVER: 'pointerover',
  184. /**
  185. * The pointerout event. Can either be used directly or used implicitly to
  186. * capture pointerover events. In addEvent(), it represents a regular DOM
  187. * pointerout event.
  188. */
  189. POINTEROUT: 'pointerout',
  190. /**
  191. * The pointerenter event. Does not bubble and fires individually on each
  192. * element being entered within a DOM tree.
  193. */
  194. POINTERENTER: 'pointerenter',
  195. /**
  196. * The pointerleave event. Does not bubble and fires individually on each
  197. * element being entered within a DOM tree.
  198. */
  199. POINTERLEAVE: 'pointerleave',
  200. /**
  201. * The error event. The error event doesn't bubble, but you can use it in
  202. * addEvent() and jsaction anyway. EventContract does the right thing under
  203. * the hood (except in IE8 which does not use error events).
  204. */
  205. ERROR: 'error',
  206. /**
  207. * The load event. The load event doesn't bubble, but you can use it in
  208. * addEvent() and jsaction anyway. EventContract does the right thing
  209. * under the hood.
  210. */
  211. LOAD: 'load',
  212. /**
  213. * The touchstart event. Bubbles, will only ever fire in browsers with
  214. * touch support.
  215. */
  216. TOUCHSTART: 'touchstart',
  217. /**
  218. * The touchend event. Bubbles, will only ever fire in browsers with
  219. * touch support.
  220. */
  221. TOUCHEND: 'touchend',
  222. /**
  223. * The touchmove event. Bubbles, will only ever fire in browsers with
  224. * touch support.
  225. */
  226. TOUCHMOVE: 'touchmove',
  227. /**
  228. * The toggle event. The toggle event doesn't bubble, but you can use it in
  229. * addEvent() and jsaction anyway. EventContract does the right thing
  230. * under the hood.
  231. */
  232. TOGGLE: 'toggle'};
  233. /** All event types that do not bubble or capture and need a polyfill. */
  234. const MOUSE_SPECIAL_EVENT_TYPES = [
  235. EventType.MOUSEENTER,
  236. EventType.MOUSELEAVE,
  237. 'pointerenter',
  238. 'pointerleave',
  239. ];
  240. /** All event types that are registered in the bubble phase. */
  241. const BUBBLE_EVENT_TYPES = [
  242. EventType.CLICK,
  243. EventType.DBLCLICK,
  244. EventType.FOCUSIN,
  245. EventType.FOCUSOUT,
  246. EventType.KEYDOWN,
  247. EventType.KEYUP,
  248. EventType.KEYPRESS,
  249. EventType.MOUSEOVER,
  250. EventType.MOUSEOUT,
  251. EventType.SUBMIT,
  252. EventType.TOUCHSTART,
  253. EventType.TOUCHEND,
  254. EventType.TOUCHMOVE,
  255. 'touchcancel',
  256. 'auxclick',
  257. 'change',
  258. 'compositionstart',
  259. 'compositionupdate',
  260. 'compositionend',
  261. 'beforeinput',
  262. 'input',
  263. 'select',
  264. 'copy',
  265. 'cut',
  266. 'paste',
  267. 'mousedown',
  268. 'mouseup',
  269. 'wheel',
  270. 'contextmenu',
  271. 'dragover',
  272. 'dragenter',
  273. 'dragleave',
  274. 'drop',
  275. 'dragstart',
  276. 'dragend',
  277. 'pointerdown',
  278. 'pointermove',
  279. 'pointerup',
  280. 'pointercancel',
  281. 'pointerover',
  282. 'pointerout',
  283. 'gotpointercapture',
  284. 'lostpointercapture',
  285. // Video events.
  286. 'ended',
  287. 'loadedmetadata',
  288. // Page visibility events.
  289. 'pagehide',
  290. 'pageshow',
  291. 'visibilitychange',
  292. // Content visibility events.
  293. 'beforematch',
  294. ];
  295. /** All event types that are registered in the capture phase. */
  296. const CAPTURE_EVENT_TYPES = [
  297. EventType.FOCUS,
  298. EventType.BLUR,
  299. EventType.ERROR,
  300. EventType.LOAD,
  301. EventType.TOGGLE,
  302. ];
  303. /**
  304. * Whether or not an event type should be registered in the capture phase.
  305. * @param eventType
  306. * @returns bool
  307. */
  308. const isCaptureEventType = (eventType) => CAPTURE_EVENT_TYPES.indexOf(eventType) >= 0;
  309. /** All event types that are registered early. */
  310. const EARLY_EVENT_TYPES = BUBBLE_EVENT_TYPES.concat(CAPTURE_EVENT_TYPES);
  311. /**
  312. * Whether or not an event type is registered in the early contract.
  313. */
  314. const isEarlyEventType = (eventType) => EARLY_EVENT_TYPES.indexOf(eventType) >= 0;
  315. /**
  316. * Gets a browser event type, if it would differ from the JSAction event type.
  317. */
  318. function getBrowserEventType(eventType) {
  319. // Mouseenter and mouseleave events are not handled directly because they
  320. // are not available everywhere. In browsers where they are available, they
  321. // don't bubble and aren't visible at the container boundary. Instead, we
  322. // synthesize the mouseenter and mouseleave events from mouseover and
  323. // mouseout events, respectively. Cf. eventcontract.js.
  324. if (eventType === EventType.MOUSEENTER) {
  325. return EventType.MOUSEOVER;
  326. }
  327. else if (eventType === EventType.MOUSELEAVE) {
  328. return EventType.MOUSEOUT;
  329. }
  330. else if (eventType === EventType.POINTERENTER) {
  331. return EventType.POINTEROVER;
  332. }
  333. else if (eventType === EventType.POINTERLEAVE) {
  334. return EventType.POINTEROUT;
  335. }
  336. return eventType;
  337. }
  338. /**
  339. * Registers the event handler function with the given DOM element for
  340. * the given event type.
  341. *
  342. * @param element The element.
  343. * @param eventType The event type.
  344. * @param handler The handler function to install.
  345. * @param passive A boolean value that, if `true`, indicates that the function
  346. * specified by `handler` will never call `preventDefault()`.
  347. * @return Information needed to uninstall the event handler eventually.
  348. */
  349. function addEventListener(element, eventType, handler, passive) {
  350. // All event handlers are registered in the bubbling
  351. // phase.
  352. //
  353. // All browsers support focus and blur, but these events only are propagated
  354. // in the capture phase. Very legacy browsers do not support focusin or
  355. // focusout.
  356. //
  357. // It would be a bad idea to register all event handlers in the
  358. // capture phase because then regular onclick handlers would not be
  359. // executed at all on events that trigger a jsaction. That's not
  360. // entirely what we want, at least for now.
  361. //
  362. // Error and load events (i.e. on images) do not bubble so they are also
  363. // handled in the capture phase.
  364. let capture = false;
  365. if (isCaptureEventType(eventType)) {
  366. capture = true;
  367. }
  368. const options = typeof passive === 'boolean' ? { capture, passive } : capture;
  369. element.addEventListener(eventType, handler, options);
  370. return { eventType, handler, capture, passive };
  371. }
  372. /**
  373. * Removes the event handler for the given event from the element.
  374. * the given event type.
  375. *
  376. * @param element The element.
  377. * @param info The information needed to deregister the handler, as returned by
  378. * addEventListener(), above.
  379. */
  380. function removeEventListener(element, info) {
  381. if (element.removeEventListener) {
  382. // It's worth noting that some browser releases have been inconsistent on this, and unless
  383. // you have specific reasons otherwise, it's probably wise to use the same values used for
  384. // the call to addEventListener() when calling removeEventListener().
  385. const options = typeof info.passive === 'boolean' ? { capture: info.capture } : info.capture;
  386. element.removeEventListener(info.eventType, info.handler, options);
  387. // `detachEvent` is an old DOM API.
  388. }
  389. else if (element.detachEvent) {
  390. // `detachEvent` is an old DOM API.
  391. element.detachEvent(`on${info.eventType}`, info.handler);
  392. }
  393. }
  394. /**
  395. * Prevents the default action of an event.
  396. * @param e The event to prevent the default action for.
  397. */
  398. function preventDefault(e) {
  399. e.preventDefault ? e.preventDefault() : (e.returnValue = false);
  400. }
  401. /**
  402. * Whether we are on a Mac. Not pulling in useragent just for this.
  403. */
  404. let isMac = typeof navigator !== 'undefined' && /Macintosh/.test(navigator.userAgent);
  405. /**
  406. * Determines and returns whether the given event (which is assumed to be a
  407. * click event) is a middle click.
  408. * NOTE: There is not a consistent way to identify middle click
  409. * http://www.unixpapa.com/js/mouse.html
  410. */
  411. function isMiddleClick(e) {
  412. return (
  413. // `which` is an old DOM API.
  414. e.which === 2 ||
  415. // `which` is an old DOM API.
  416. (e.which == null &&
  417. // `button` is an old DOM API.
  418. e.button === 4) // middle click for IE
  419. );
  420. }
  421. /**
  422. * Determines and returns whether the given event (which is assumed
  423. * to be a click event) is modified. A middle click is considered a modified
  424. * click to retain the default browser action, which opens a link in a new tab.
  425. * @param e The event.
  426. * @return Whether the given event is modified.
  427. */
  428. function isModifiedClickEvent(e) {
  429. return (
  430. // `metaKey` is an old DOM API.
  431. (isMac && e.metaKey) ||
  432. // `ctrlKey` is an old DOM API.
  433. (!isMac && e.ctrlKey) ||
  434. isMiddleClick(e) ||
  435. // `shiftKey` is an old DOM API.
  436. e.shiftKey);
  437. }
  438. /**
  439. * Determines whether the event corresponds to a non-bubbling mouse
  440. * event type (mouseenter, mouseleave, pointerenter, and pointerleave).
  441. *
  442. * During mouseover (mouseenter) and pointerover (pointerenter), the
  443. * relatedTarget is the element being entered from. During mouseout (mouseleave)
  444. * and pointerout (pointerleave), the relatedTarget is the element being exited
  445. * to.
  446. *
  447. * In both cases, if relatedTarget is outside target, then the corresponding
  448. * special event has occurred, otherwise it hasn't.
  449. *
  450. * @param e The mouseover/mouseout event.
  451. * @param type The type of the mouse special event.
  452. * @param element The element on which the jsaction for the
  453. * mouseenter/mouseleave event is defined.
  454. * @return True if the event is a mouseenter/mouseleave event.
  455. */
  456. function isMouseSpecialEvent(e, type, element) {
  457. // `relatedTarget` is an old DOM API.
  458. const related = e.relatedTarget;
  459. return (((e.type === EventType.MOUSEOVER && type === EventType.MOUSEENTER) ||
  460. (e.type === EventType.MOUSEOUT && type === EventType.MOUSELEAVE) ||
  461. (e.type === EventType.POINTEROVER && type === EventType.POINTERENTER) ||
  462. (e.type === EventType.POINTEROUT && type === EventType.POINTERLEAVE)) &&
  463. (!related || (related !== element && !element.contains(related))));
  464. }
  465. /**
  466. * Creates a new EventLike object for a mouseenter/mouseleave event that's
  467. * derived from the original corresponding mouseover/mouseout event.
  468. * @param e The event.
  469. * @param target The element on which the jsaction for the mouseenter/mouseleave
  470. * event is defined.
  471. * @return A modified event-like object copied from the event object passed into
  472. * this function.
  473. */
  474. function createMouseSpecialEvent(e, target) {
  475. // We have to create a copy of the event object because we need to mutate
  476. // its fields. We do this for the special mouse events because the event
  477. // target needs to be retargeted to the action element rather than the real
  478. // element (since we are simulating the special mouse events with mouseover/
  479. // mouseout).
  480. //
  481. // Since we're making a copy anyways, we might as well attempt to convert
  482. // this event into a pseudo-real mouseenter/mouseleave event by adjusting
  483. // its type.
  484. //
  485. const copy = {};
  486. for (const property in e) {
  487. if (property === 'srcElement' || property === 'target') {
  488. continue;
  489. }
  490. const key = property;
  491. // Making a copy requires iterating through all properties of `Event`.
  492. const value = e[key];
  493. if (typeof value === 'function') {
  494. continue;
  495. }
  496. // Value should be the expected type, but the value of `key` is not known
  497. // statically.
  498. copy[key] = value;
  499. }
  500. if (e.type === EventType.MOUSEOVER) {
  501. copy['type'] = EventType.MOUSEENTER;
  502. }
  503. else if (e.type === EventType.MOUSEOUT) {
  504. copy['type'] = EventType.MOUSELEAVE;
  505. }
  506. else if (e.type === EventType.POINTEROVER) {
  507. copy['type'] = EventType.POINTERENTER;
  508. }
  509. else {
  510. copy['type'] = EventType.POINTERLEAVE;
  511. }
  512. copy['target'] = copy['srcElement'] = target;
  513. copy['bubbles'] = false;
  514. copy['_originalEvent'] = e;
  515. return copy;
  516. }
  517. /**
  518. * Whether the user agent is running on iOS.
  519. */
  520. const isIos = typeof navigator !== 'undefined' && /iPhone|iPad|iPod/.test(navigator.userAgent);
  521. /**
  522. * A class representing a container node and all the event handlers
  523. * installed on it. Used so that handlers can be cleaned up if the
  524. * container is removed from the contract.
  525. */
  526. class EventContractContainer {
  527. element;
  528. /**
  529. * Array of event handlers and their corresponding event types that are
  530. * installed on this container.
  531. *
  532. */
  533. handlerInfos = [];
  534. /**
  535. * @param element The container Element.
  536. */
  537. constructor(element) {
  538. this.element = element;
  539. }
  540. /**
  541. * Installs the provided installer on the element owned by this container,
  542. * and maintains a reference to resulting handler in order to remove it
  543. * later if desired.
  544. */
  545. addEventListener(eventType, getHandler, passive) {
  546. // In iOS, event bubbling doesn't happen automatically in any DOM element,
  547. // unless it has an onclick attribute or DOM event handler attached to it.
  548. // This breaks JsAction in some cases. See "Making Elements Clickable"
  549. // section at http://goo.gl/2VoGnB.
  550. //
  551. // A workaround for this issue is to change the CSS cursor style to 'pointer'
  552. // for the container element, which magically turns on event bubbling. This
  553. // solution is described in the comments section at http://goo.gl/6pEO1z.
  554. //
  555. // We use a navigator.userAgent check here as this problem is present both
  556. // on Mobile Safari and thin WebKit wrappers, such as Chrome for iOS.
  557. if (isIos) {
  558. this.element.style.cursor = 'pointer';
  559. }
  560. this.handlerInfos.push(addEventListener(this.element, eventType, getHandler(this.element), passive));
  561. }
  562. /**
  563. * Removes all the handlers installed on this container.
  564. */
  565. cleanUp() {
  566. for (let i = 0; i < this.handlerInfos.length; i++) {
  567. removeEventListener(this.element, this.handlerInfos[i]);
  568. }
  569. this.handlerInfos = [];
  570. }
  571. }
  572. const Char = {
  573. /**
  574. * The separator between the event name and action in the jsaction
  575. * attribute value.
  576. */
  577. EVENT_ACTION_SEPARATOR: ':',
  578. };
  579. /** Added for readability when accessing stable property names. */
  580. function getEventType(eventInfo) {
  581. return eventInfo.eventType;
  582. }
  583. /** Added for readability when accessing stable property names. */
  584. function setEventType(eventInfo, eventType) {
  585. eventInfo.eventType = eventType;
  586. }
  587. /** Added for readability when accessing stable property names. */
  588. function getEvent(eventInfo) {
  589. return eventInfo.event;
  590. }
  591. /** Added for readability when accessing stable property names. */
  592. function setEvent(eventInfo, event) {
  593. eventInfo.event = event;
  594. }
  595. /** Added for readability when accessing stable property names. */
  596. function getTargetElement(eventInfo) {
  597. return eventInfo.targetElement;
  598. }
  599. /** Added for readability when accessing stable property names. */
  600. function setTargetElement(eventInfo, targetElement) {
  601. eventInfo.targetElement = targetElement;
  602. }
  603. /** Added for readability when accessing stable property names. */
  604. function getContainer(eventInfo) {
  605. return eventInfo.eic;
  606. }
  607. /** Added for readability when accessing stable property names. */
  608. function setContainer(eventInfo, container) {
  609. eventInfo.eic = container;
  610. }
  611. /** Added for readability when accessing stable property names. */
  612. function getTimestamp(eventInfo) {
  613. return eventInfo.timeStamp;
  614. }
  615. /** Added for readability when accessing stable property names. */
  616. function setTimestamp(eventInfo, timestamp) {
  617. eventInfo.timeStamp = timestamp;
  618. }
  619. /** Added for readability when accessing stable property names. */
  620. function getAction(eventInfo) {
  621. return eventInfo.eia;
  622. }
  623. /** Added for readability when accessing stable property names. */
  624. function setAction(eventInfo, actionName, actionElement) {
  625. eventInfo.eia = [actionName, actionElement];
  626. }
  627. /** Added for readability when accessing stable property names. */
  628. function unsetAction(eventInfo) {
  629. eventInfo.eia = undefined;
  630. }
  631. /** Added for readability when accessing stable property names. */
  632. function getActionElement(actionInfo) {
  633. return actionInfo[1];
  634. }
  635. /** Added for readability when accessing stable property names. */
  636. function getIsReplay(eventInfo) {
  637. return eventInfo.eirp;
  638. }
  639. /** Added for readability when accessing stable property names. */
  640. function setIsReplay(eventInfo, replay) {
  641. eventInfo.eirp = replay;
  642. }
  643. /** Added for readability when accessing stable property names. */
  644. function getResolved(eventInfo) {
  645. return eventInfo.eir;
  646. }
  647. /** Added for readability when accessing stable property names. */
  648. function setResolved(eventInfo, resolved) {
  649. eventInfo.eir = resolved;
  650. }
  651. /** Clones an `EventInfo` */
  652. function cloneEventInfo(eventInfo) {
  653. return {
  654. eventType: eventInfo.eventType,
  655. event: eventInfo.event,
  656. targetElement: eventInfo.targetElement,
  657. eic: eventInfo.eic,
  658. eia: eventInfo.eia,
  659. timeStamp: eventInfo.timeStamp,
  660. eirp: eventInfo.eirp,
  661. eiack: eventInfo.eiack,
  662. eir: eventInfo.eir,
  663. };
  664. }
  665. /**
  666. * Utility function for creating an `EventInfo`.
  667. *
  668. * This can be used from code-size sensitive compilation units, as taking
  669. * parameters vs. an `Object` literal reduces code size.
  670. */
  671. function createEventInfoFromParameters(eventType, event, targetElement, container, timestamp, action, isReplay, a11yClickKey) {
  672. return {
  673. eventType,
  674. event,
  675. targetElement,
  676. eic: container,
  677. timeStamp: timestamp,
  678. eia: action,
  679. eirp: isReplay,
  680. eiack: a11yClickKey,
  681. };
  682. }
  683. /**
  684. * Utility class around an `EventInfo`.
  685. *
  686. * This should be used in compilation units that are less sensitive to code
  687. * size.
  688. */
  689. class EventInfoWrapper {
  690. eventInfo;
  691. constructor(eventInfo) {
  692. this.eventInfo = eventInfo;
  693. }
  694. getEventType() {
  695. return getEventType(this.eventInfo);
  696. }
  697. setEventType(eventType) {
  698. setEventType(this.eventInfo, eventType);
  699. }
  700. getEvent() {
  701. return getEvent(this.eventInfo);
  702. }
  703. setEvent(event) {
  704. setEvent(this.eventInfo, event);
  705. }
  706. getTargetElement() {
  707. return getTargetElement(this.eventInfo);
  708. }
  709. setTargetElement(targetElement) {
  710. setTargetElement(this.eventInfo, targetElement);
  711. }
  712. getContainer() {
  713. return getContainer(this.eventInfo);
  714. }
  715. setContainer(container) {
  716. setContainer(this.eventInfo, container);
  717. }
  718. getTimestamp() {
  719. return getTimestamp(this.eventInfo);
  720. }
  721. setTimestamp(timestamp) {
  722. setTimestamp(this.eventInfo, timestamp);
  723. }
  724. getAction() {
  725. const action = getAction(this.eventInfo);
  726. if (!action)
  727. return undefined;
  728. return {
  729. name: action[0],
  730. element: action[1],
  731. };
  732. }
  733. setAction(action) {
  734. if (!action) {
  735. unsetAction(this.eventInfo);
  736. return;
  737. }
  738. setAction(this.eventInfo, action.name, action.element);
  739. }
  740. getIsReplay() {
  741. return getIsReplay(this.eventInfo);
  742. }
  743. setIsReplay(replay) {
  744. setIsReplay(this.eventInfo, replay);
  745. }
  746. getResolved() {
  747. return getResolved(this.eventInfo);
  748. }
  749. setResolved(resolved) {
  750. setResolved(this.eventInfo, resolved);
  751. }
  752. clone() {
  753. return new EventInfoWrapper(cloneEventInfo(this.eventInfo));
  754. }
  755. }
  756. /**
  757. * Since maps from event to action are immutable we can use a single map
  758. * to represent the empty map.
  759. */
  760. const EMPTY_ACTION_MAP = {};
  761. /**
  762. * This regular expression matches a semicolon.
  763. */
  764. const REGEXP_SEMICOLON = /\s*;\s*/;
  765. /** If no event type is defined, defaults to `click`. */
  766. const DEFAULT_EVENT_TYPE = EventType.CLICK;
  767. /** Resolves actions for Events. */
  768. class ActionResolver {
  769. a11yClickSupport = false;
  770. clickModSupport = true;
  771. syntheticMouseEventSupport;
  772. updateEventInfoForA11yClick = undefined;
  773. preventDefaultForA11yClick = undefined;
  774. populateClickOnlyAction = undefined;
  775. constructor({ syntheticMouseEventSupport = false, clickModSupport = true, } = {}) {
  776. this.syntheticMouseEventSupport = syntheticMouseEventSupport;
  777. this.clickModSupport = clickModSupport;
  778. }
  779. resolveEventType(eventInfo) {
  780. // We distinguish modified and plain clicks in order to support the
  781. // default browser behavior of modified clicks on links; usually to
  782. // open the URL of the link in new tab or new window on ctrl/cmd
  783. // click. A DOM 'click' event is mapped to the jsaction 'click'
  784. // event iff there is no modifier present on the event. If there is
  785. // a modifier, it's mapped to 'clickmod' instead.
  786. //
  787. // It's allowed to omit the event in the jsaction attribute. In that
  788. // case, 'click' is assumed. Thus the following two are equivalent:
  789. //
  790. // <a href="someurl" jsaction="gna.fu">
  791. // <a href="someurl" jsaction="click:gna.fu">
  792. //
  793. // For unmodified clicks, EventContract invokes the jsaction
  794. // 'gna.fu'. For modified clicks, EventContract won't find a
  795. // suitable action and leave the event to be handled by the
  796. // browser.
  797. //
  798. // In order to also invoke a jsaction handler for a modifier click,
  799. // 'clickmod' needs to be used:
  800. //
  801. // <a href="someurl" jsaction="clickmod:gna.fu">
  802. //
  803. // EventContract invokes the jsaction 'gna.fu' for modified
  804. // clicks. Unmodified clicks are left to the browser.
  805. //
  806. // In order to set up the event contract to handle both clickonly and
  807. // clickmod, only addEvent(EventType.CLICK) is necessary.
  808. //
  809. // In order to set up the event contract to handle click,
  810. // addEvent() is necessary for CLICK, KEYDOWN, and KEYPRESS event types. If
  811. // a11y click support is enabled, addEvent() will set up the appropriate key
  812. // event handler automatically.
  813. if (this.clickModSupport &&
  814. getEventType(eventInfo) === EventType.CLICK &&
  815. isModifiedClickEvent(getEvent(eventInfo))) {
  816. setEventType(eventInfo, EventType.CLICKMOD);
  817. }
  818. else if (this.a11yClickSupport) {
  819. this.updateEventInfoForA11yClick(eventInfo);
  820. }
  821. }
  822. resolveAction(eventInfo) {
  823. if (getResolved(eventInfo)) {
  824. return;
  825. }
  826. this.populateAction(eventInfo, getTargetElement(eventInfo));
  827. setResolved(eventInfo, true);
  828. }
  829. resolveParentAction(eventInfo) {
  830. const action = getAction(eventInfo);
  831. const actionElement = action && getActionElement(action);
  832. unsetAction(eventInfo);
  833. const parentNode = actionElement && this.getParentNode(actionElement);
  834. if (!parentNode) {
  835. return;
  836. }
  837. this.populateAction(eventInfo, parentNode);
  838. }
  839. /**
  840. * Searches for a jsaction that the DOM event maps to and creates an
  841. * object containing event information used for dispatching by
  842. * jsaction.Dispatcher. This method populates the `action` and `actionElement`
  843. * fields of the EventInfo object passed in by finding the first
  844. * jsaction attribute above the target Node of the event, and below
  845. * the container Node, that specifies a jsaction for the event
  846. * type. If no such jsaction is found, then action is undefined.
  847. *
  848. * @param eventInfo `EventInfo` to set `action` and `actionElement` if an
  849. * action is found on any `Element` in the path of the `Event`.
  850. */
  851. populateAction(eventInfo, currentTarget) {
  852. let actionElement = currentTarget;
  853. while (actionElement && actionElement !== getContainer(eventInfo)) {
  854. if (actionElement.nodeType === Node.ELEMENT_NODE) {
  855. this.populateActionOnElement(actionElement, eventInfo);
  856. }
  857. if (getAction(eventInfo)) {
  858. // An event is handled by at most one jsaction. Thus we stop at the
  859. // first matching jsaction specified in a jsaction attribute up the
  860. // ancestor chain of the event target node.
  861. break;
  862. }
  863. actionElement = this.getParentNode(actionElement);
  864. }
  865. const action = getAction(eventInfo);
  866. if (!action) {
  867. // No action found.
  868. return;
  869. }
  870. if (this.a11yClickSupport) {
  871. this.preventDefaultForA11yClick(eventInfo);
  872. }
  873. // We attempt to handle the mouseenter/mouseleave events here by
  874. // detecting whether the mouseover/mouseout events correspond to
  875. // entering/leaving an element.
  876. if (this.syntheticMouseEventSupport) {
  877. if (getEventType(eventInfo) === EventType.MOUSEENTER ||
  878. getEventType(eventInfo) === EventType.MOUSELEAVE ||
  879. getEventType(eventInfo) === EventType.POINTERENTER ||
  880. getEventType(eventInfo) === EventType.POINTERLEAVE) {
  881. // We attempt to handle the mouseenter/mouseleave events here by
  882. // detecting whether the mouseover/mouseout events correspond to
  883. // entering/leaving an element.
  884. if (isMouseSpecialEvent(getEvent(eventInfo), getEventType(eventInfo), getActionElement(action))) {
  885. // If both mouseover/mouseout and mouseenter/mouseleave events are
  886. // enabled, two separate handlers for mouseover/mouseout are
  887. // registered. Both handlers will see the same event instance
  888. // so we create a copy to avoid interfering with the dispatching of
  889. // the mouseover/mouseout event.
  890. const copiedEvent = createMouseSpecialEvent(getEvent(eventInfo), getActionElement(action));
  891. setEvent(eventInfo, copiedEvent);
  892. // Since the mouseenter/mouseleave events do not bubble, the target
  893. // of the event is technically the `actionElement` (the node with the
  894. // `jsaction` attribute)
  895. setTargetElement(eventInfo, getActionElement(action));
  896. }
  897. else {
  898. unsetAction(eventInfo);
  899. }
  900. }
  901. }
  902. }
  903. /**
  904. * Walk to the parent node, unless the node has a different owner in
  905. * which case we walk to the owner. Attempt to walk to host of a
  906. * shadow root if needed.
  907. */
  908. getParentNode(element) {
  909. const owner = element[Property.OWNER];
  910. if (owner) {
  911. return owner;
  912. }
  913. const parentNode = element.parentNode;
  914. if (parentNode?.nodeName === '#document-fragment') {
  915. return parentNode?.host ?? null;
  916. }
  917. return parentNode;
  918. }
  919. /**
  920. * Accesses the jsaction map on a node and retrieves the name of the
  921. * action the given event is mapped to, if any. It parses the
  922. * attribute value and stores it in a property on the node for
  923. * subsequent retrieval without re-parsing and re-accessing the
  924. * attribute.
  925. *
  926. * @param actionElement The DOM node to retrieve the jsaction map from.
  927. * @param eventInfo `EventInfo` to set `action` and `actionElement` if an
  928. * action is found on the `actionElement`.
  929. */
  930. populateActionOnElement(actionElement, eventInfo) {
  931. const actionMap = this.parseActions(actionElement);
  932. const actionName = actionMap[getEventType(eventInfo)];
  933. if (actionName !== undefined) {
  934. setAction(eventInfo, actionName, actionElement);
  935. }
  936. if (this.a11yClickSupport) {
  937. this.populateClickOnlyAction(actionElement, eventInfo, actionMap);
  938. }
  939. }
  940. /**
  941. * Parses and caches an element's jsaction element into a map.
  942. *
  943. * This is primarily for internal use.
  944. *
  945. * @param actionElement The DOM node to retrieve the jsaction map from.
  946. * @return Map from event to qualified name of the jsaction bound to it.
  947. */
  948. parseActions(actionElement) {
  949. let actionMap = get(actionElement);
  950. if (!actionMap) {
  951. const jsactionAttribute = actionElement.getAttribute(Attribute.JSACTION);
  952. if (!jsactionAttribute) {
  953. actionMap = EMPTY_ACTION_MAP;
  954. set(actionElement, actionMap);
  955. }
  956. else {
  957. actionMap = getParsed(jsactionAttribute);
  958. if (!actionMap) {
  959. actionMap = {};
  960. const values = jsactionAttribute.split(REGEXP_SEMICOLON);
  961. for (let idx = 0; idx < values.length; idx++) {
  962. const value = values[idx];
  963. if (!value) {
  964. continue;
  965. }
  966. const colon = value.indexOf(Char.EVENT_ACTION_SEPARATOR);
  967. const hasColon = colon !== -1;
  968. const type = hasColon ? value.substr(0, colon).trim() : DEFAULT_EVENT_TYPE;
  969. const action = hasColon ? value.substr(colon + 1).trim() : value;
  970. actionMap[type] = action;
  971. }
  972. setParsed(jsactionAttribute, actionMap);
  973. }
  974. set(actionElement, actionMap);
  975. }
  976. }
  977. return actionMap;
  978. }
  979. addA11yClickSupport(updateEventInfoForA11yClick, preventDefaultForA11yClick, populateClickOnlyAction) {
  980. this.a11yClickSupport = true;
  981. this.updateEventInfoForA11yClick = updateEventInfoForA11yClick;
  982. this.preventDefaultForA11yClick = preventDefaultForA11yClick;
  983. this.populateClickOnlyAction = populateClickOnlyAction;
  984. }
  985. }
  986. /**
  987. * @fileoverview An enum to control who can call certain jsaction APIs.
  988. */
  989. var Restriction;
  990. (function (Restriction) {
  991. Restriction[Restriction["I_AM_THE_JSACTION_FRAMEWORK"] = 0] = "I_AM_THE_JSACTION_FRAMEWORK";
  992. })(Restriction || (Restriction = {}));
  993. /**
  994. * Receives a DOM event, determines the jsaction associated with the source
  995. * element of the DOM event, and invokes the handler associated with the
  996. * jsaction.
  997. */
  998. class Dispatcher {
  999. dispatchDelegate;
  1000. // The ActionResolver to use to resolve actions.
  1001. actionResolver;
  1002. /** The replayer function to be called when there are queued events. */
  1003. eventReplayer;
  1004. /** Whether the event replay is scheduled. */
  1005. eventReplayScheduled = false;
  1006. /** The queue of events. */
  1007. replayEventInfoWrappers = [];
  1008. /**
  1009. * Options are:
  1010. * - `eventReplayer`: When the event contract dispatches replay events
  1011. * to the Dispatcher, the Dispatcher collects them and in the next tick
  1012. * dispatches them to the `eventReplayer`. Defaults to dispatching to `dispatchDelegate`.
  1013. * @param dispatchDelegate A function that should handle dispatching an `EventInfoWrapper` to handlers.
  1014. */
  1015. constructor(dispatchDelegate, { actionResolver, eventReplayer, } = {}) {
  1016. this.dispatchDelegate = dispatchDelegate;
  1017. this.actionResolver = actionResolver;
  1018. this.eventReplayer = eventReplayer;
  1019. }
  1020. /**
  1021. * Receives an event or the event queue from the EventContract. The event
  1022. * queue is copied and it attempts to replay.
  1023. * If event info is passed in it looks for an action handler that can handle
  1024. * the given event. If there is no handler registered queues the event and
  1025. * checks if a loader is registered for the given namespace. If so, calls it.
  1026. *
  1027. * Alternatively, if in global dispatch mode, calls all registered global
  1028. * handlers for the appropriate event type.
  1029. *
  1030. * The three functionalities of this call are deliberately not split into
  1031. * three methods (and then declared as an abstract interface), because the
  1032. * interface is used by EventContract, which lives in a different jsbinary.
  1033. * Therefore the interface between the three is defined entirely in terms that
  1034. * are invariant under jscompiler processing (Function and Array, as opposed
  1035. * to a custom type with method names).
  1036. *
  1037. * @param eventInfo The info for the event that triggered this call or the
  1038. * queue of events from EventContract.
  1039. */
  1040. dispatch(eventInfo) {
  1041. const eventInfoWrapper = new EventInfoWrapper(eventInfo);
  1042. this.actionResolver?.resolveEventType(eventInfo);
  1043. this.actionResolver?.resolveAction(eventInfo);
  1044. const action = eventInfoWrapper.getAction();
  1045. if (action && shouldPreventDefaultBeforeDispatching(action.element, eventInfoWrapper)) {
  1046. preventDefault(eventInfoWrapper.getEvent());
  1047. }
  1048. if (this.eventReplayer && eventInfoWrapper.getIsReplay()) {
  1049. this.scheduleEventInfoWrapperReplay(eventInfoWrapper);
  1050. return;
  1051. }
  1052. this.dispatchDelegate(eventInfoWrapper);
  1053. }
  1054. /**
  1055. * Schedules an `EventInfoWrapper` for replay. The replaying will happen in its own
  1056. * stack once the current flow cedes control. This is done to mimic
  1057. * browser event handling.
  1058. */
  1059. scheduleEventInfoWrapperReplay(eventInfoWrapper) {
  1060. this.replayEventInfoWrappers.push(eventInfoWrapper);
  1061. if (this.eventReplayScheduled) {
  1062. return;
  1063. }
  1064. this.eventReplayScheduled = true;
  1065. Promise.resolve().then(() => {
  1066. this.eventReplayScheduled = false;
  1067. this.eventReplayer(this.replayEventInfoWrappers);
  1068. });
  1069. }
  1070. }
  1071. /**
  1072. * Returns true if the default action of this event should be prevented before
  1073. * this event is dispatched.
  1074. */
  1075. function shouldPreventDefaultBeforeDispatching(actionElement, eventInfoWrapper) {
  1076. // Prevent browser from following <a> node links if a jsaction is present
  1077. // and we are dispatching the action now. Note that the targetElement may be
  1078. // a child of an anchor that has a jsaction attached. For that reason, we
  1079. // need to check the actionElement rather than the targetElement.
  1080. return (actionElement.tagName === 'A' &&
  1081. (eventInfoWrapper.getEventType() === EventType.CLICK ||
  1082. eventInfoWrapper.getEventType() === EventType.CLICKMOD));
  1083. }
  1084. /** An internal symbol used to indicate whether propagation should be stopped or not. */
  1085. const PROPAGATION_STOPPED_SYMBOL = Symbol.for('propagationStopped');
  1086. /** Extra event phases beyond what the browser provides. */
  1087. const EventPhase = {
  1088. REPLAY: 101,
  1089. };
  1090. const PREVENT_DEFAULT_ERROR_MESSAGE_DETAILS = ' Because event replay occurs after browser dispatch, `preventDefault` would have no ' +
  1091. 'effect. You can check whether an event is being replayed by accessing the event phase: ' +
  1092. '`event.eventPhase === EventPhase.REPLAY`.';
  1093. const PREVENT_DEFAULT_ERROR_MESSAGE = `\`preventDefault\` called during event replay.`;
  1094. const COMPOSED_PATH_ERROR_MESSAGE_DETAILS = ' Because event replay occurs after browser ' +
  1095. 'dispatch, `composedPath()` will be empty. Iterate parent nodes from `event.target` or ' +
  1096. '`event.currentTarget` if you need to check elements in the event path.';
  1097. const COMPOSED_PATH_ERROR_MESSAGE = `\`composedPath\` called during event replay.`;
  1098. /**
  1099. * A dispatcher that uses browser-based `Event` semantics, for example bubbling, `stopPropagation`,
  1100. * `currentTarget`, etc.
  1101. */
  1102. class EventDispatcher {
  1103. dispatchDelegate;
  1104. clickModSupport;
  1105. actionResolver;
  1106. dispatcher;
  1107. constructor(dispatchDelegate, clickModSupport = true) {
  1108. this.dispatchDelegate = dispatchDelegate;
  1109. this.clickModSupport = clickModSupport;
  1110. this.actionResolver = new ActionResolver({ clickModSupport });
  1111. this.dispatcher = new Dispatcher((eventInfoWrapper) => {
  1112. this.dispatchToDelegate(eventInfoWrapper);
  1113. }, {
  1114. actionResolver: this.actionResolver,
  1115. });
  1116. }
  1117. /**
  1118. * The entrypoint for the `EventContract` dispatch.
  1119. */
  1120. dispatch(eventInfo) {
  1121. this.dispatcher.dispatch(eventInfo);
  1122. }
  1123. /** Internal method that does basic disaptching. */
  1124. dispatchToDelegate(eventInfoWrapper) {
  1125. if (eventInfoWrapper.getIsReplay()) {
  1126. prepareEventForReplay(eventInfoWrapper);
  1127. }
  1128. prepareEventForBubbling(eventInfoWrapper);
  1129. while (eventInfoWrapper.getAction()) {
  1130. prepareEventForDispatch(eventInfoWrapper);
  1131. // If this is a capture event, ONLY dispatch if the action element is the target.
  1132. if (isCaptureEventType(eventInfoWrapper.getEventType()) &&
  1133. eventInfoWrapper.getAction().element !== eventInfoWrapper.getTargetElement()) {
  1134. return;
  1135. }
  1136. this.dispatchDelegate(eventInfoWrapper.getEvent(), eventInfoWrapper.getAction().name);
  1137. if (propagationStopped(eventInfoWrapper)) {
  1138. return;
  1139. }
  1140. this.actionResolver.resolveParentAction(eventInfoWrapper.eventInfo);
  1141. }
  1142. }
  1143. }
  1144. function prepareEventForBubbling(eventInfoWrapper) {
  1145. const event = eventInfoWrapper.getEvent();
  1146. const originalStopPropagation = eventInfoWrapper.getEvent().stopPropagation.bind(event);
  1147. const stopPropagation = () => {
  1148. event[PROPAGATION_STOPPED_SYMBOL] = true;
  1149. originalStopPropagation();
  1150. };
  1151. patchEventInstance(event, 'stopPropagation', stopPropagation);
  1152. patchEventInstance(event, 'stopImmediatePropagation', stopPropagation);
  1153. }
  1154. function propagationStopped(eventInfoWrapper) {
  1155. const event = eventInfoWrapper.getEvent();
  1156. return !!event[PROPAGATION_STOPPED_SYMBOL];
  1157. }
  1158. function prepareEventForReplay(eventInfoWrapper) {
  1159. const event = eventInfoWrapper.getEvent();
  1160. const target = eventInfoWrapper.getTargetElement();
  1161. const originalPreventDefault = event.preventDefault.bind(event);
  1162. patchEventInstance(event, 'target', target);
  1163. patchEventInstance(event, 'eventPhase', EventPhase.REPLAY);
  1164. patchEventInstance(event, 'preventDefault', () => {
  1165. originalPreventDefault();
  1166. throw new Error(PREVENT_DEFAULT_ERROR_MESSAGE + (ngDevMode ? PREVENT_DEFAULT_ERROR_MESSAGE_DETAILS : ''));
  1167. });
  1168. patchEventInstance(event, 'composedPath', () => {
  1169. throw new Error(COMPOSED_PATH_ERROR_MESSAGE + (ngDevMode ? COMPOSED_PATH_ERROR_MESSAGE_DETAILS : ''));
  1170. });
  1171. }
  1172. function prepareEventForDispatch(eventInfoWrapper) {
  1173. const event = eventInfoWrapper.getEvent();
  1174. const currentTarget = eventInfoWrapper.getAction()?.element;
  1175. if (currentTarget) {
  1176. patchEventInstance(event, 'currentTarget', currentTarget, {
  1177. // `currentTarget` is going to get reassigned every dispatch.
  1178. configurable: true,
  1179. });
  1180. }
  1181. }
  1182. /**
  1183. * Patch `Event` instance during non-standard `Event` dispatch. This patches just the `Event`
  1184. * instance that the browser created, it does not patch global properties or methods.
  1185. *
  1186. * This is necessary because dispatching an `Event` outside of browser dispatch results in
  1187. * incorrect properties and methods that need to be polyfilled or do not work.
  1188. *
  1189. * JSAction dispatch adds two extra "phases" to event dispatch:
  1190. * 1. Event delegation - the event is being dispatched by a delegating event handler on a container
  1191. * (typically `window.document.documentElement`), to a delegated event handler on some child
  1192. * element. Certain `Event` properties will be unintuitive, such as `currentTarget`, which would
  1193. * be the container rather than the child element. Bubbling would also not work. In order to
  1194. * emulate the browser, these properties and methods on the `Event` are patched.
  1195. * 2. Event replay - the event is being dispatched by the framework once the handlers have been
  1196. * loaded (during hydration, or late-loaded). Certain `Event` properties can be unset by the
  1197. * browser because the `Event` is no longer actively being dispatched, such as `target`. Other
  1198. * methods have no effect because the `Event` has already been dispatched, such as
  1199. * `preventDefault`. Bubbling would also not work. These properties and methods are patched,
  1200. * either to fill in information that the browser may have removed, or to throw errors in methods
  1201. * that no longer behave as expected.
  1202. */
  1203. function patchEventInstance(event, property, value, { configurable = false } = {}) {
  1204. Object.defineProperty(event, property, { value, configurable });
  1205. }
  1206. /**
  1207. * Registers deferred functionality for an EventContract and a Jsaction
  1208. * Dispatcher.
  1209. */
  1210. function registerDispatcher$1(eventContract, dispatcher) {
  1211. eventContract.ecrd((eventInfo) => {
  1212. dispatcher.dispatch(eventInfo);
  1213. }, Restriction.I_AM_THE_JSACTION_FRAMEWORK);
  1214. }
  1215. /** Creates an `EarlyJsactionData` object. */
  1216. function createEarlyJsactionData(container) {
  1217. const q = [];
  1218. const d = (eventInfo) => {
  1219. q.push(eventInfo);
  1220. };
  1221. const h = (event) => {
  1222. d(createEventInfoFromParameters(event.type, event, event.target, container, Date.now()));
  1223. };
  1224. return {
  1225. c: container,
  1226. q,
  1227. et: [],
  1228. etc: [],
  1229. d,
  1230. h,
  1231. };
  1232. }
  1233. /** Add all the events to the container stored in the `EarlyJsactionData`. */
  1234. function addEvents(earlyJsactionData, types, capture) {
  1235. for (let i = 0; i < types.length; i++) {
  1236. const eventType = types[i];
  1237. const eventTypes = capture ? earlyJsactionData.etc : earlyJsactionData.et;
  1238. eventTypes.push(eventType);
  1239. earlyJsactionData.c.addEventListener(eventType, earlyJsactionData.h, capture);
  1240. }
  1241. }
  1242. /** Get the queued `EventInfo` objects that were dispatched before a dispatcher was registered. */
  1243. function getQueuedEventInfos(earlyJsactionData) {
  1244. return earlyJsactionData?.q ?? [];
  1245. }
  1246. /** Register a different dispatcher function on the `EarlyJsactionData`. */
  1247. function registerDispatcher(earlyJsactionData, dispatcher) {
  1248. if (!earlyJsactionData) {
  1249. return;
  1250. }
  1251. earlyJsactionData.d = dispatcher;
  1252. }
  1253. /** Removes all event listener handlers. */
  1254. function removeAllEventListeners(earlyJsactionData) {
  1255. if (!earlyJsactionData) {
  1256. return;
  1257. }
  1258. removeEventListeners(earlyJsactionData.c, earlyJsactionData.et, earlyJsactionData.h);
  1259. removeEventListeners(earlyJsactionData.c, earlyJsactionData.etc, earlyJsactionData.h, true);
  1260. }
  1261. function removeEventListeners(container, eventTypes, earlyEventHandler, capture) {
  1262. for (let i = 0; i < eventTypes.length; i++) {
  1263. container.removeEventListener(eventTypes[i], earlyEventHandler, /* useCapture */ capture);
  1264. }
  1265. }
  1266. /**
  1267. * @define Support for the non-bubbling mouseenter and mouseleave events. This
  1268. * flag can be overridden in a build rule.
  1269. */
  1270. const MOUSE_SPECIAL_SUPPORT = false;
  1271. /**
  1272. * @fileoverview Implements the local event handling contract. This
  1273. * allows DOM objects in a container that enters into this contract to
  1274. * define event handlers which are executed in a local context.
  1275. *
  1276. * One EventContract instance can manage the contract for multiple
  1277. * containers, which are added using the addContainer() method.
  1278. *
  1279. * Events can be registered using the addEvent() method.
  1280. *
  1281. * A Dispatcher is added using the registerDispatcher() method. Until there is
  1282. * a dispatcher, events are queued. The idea is that the EventContract
  1283. * class is inlined in the HTML of the top level page and instantiated
  1284. * right after the start of <body>. The Dispatcher class is contained
  1285. * in the external deferred js, and instantiated and registered with
  1286. * EventContract when the external javascript in the page loads. The
  1287. * external javascript will also register the jsaction handlers, which
  1288. * then pick up the queued events at the time of registration.
  1289. *
  1290. * Since this class is meant to be inlined in the main page HTML, the
  1291. * size of the binary compiled from this file MUST be kept as small as
  1292. * possible and thus its dependencies to a minimum.
  1293. */
  1294. /**
  1295. * EventContract intercepts events in the bubbling phase at the
  1296. * boundary of a container element, and maps them to generic actions
  1297. * which are specified using the custom jsaction attribute in
  1298. * HTML. Behavior of the application is then specified in terms of
  1299. * handler for such actions, cf. jsaction.Dispatcher in dispatcher.js.
  1300. *
  1301. * This has several benefits: (1) No DOM event handlers need to be
  1302. * registered on the specific elements in the UI. (2) The set of
  1303. * events that the application has to handle can be specified in terms
  1304. * of the semantics of the application, rather than in terms of DOM
  1305. * events. (3) Invocation of handlers can be delayed and handlers can
  1306. * be delay loaded in a generic way.
  1307. */
  1308. class EventContract {
  1309. static MOUSE_SPECIAL_SUPPORT = MOUSE_SPECIAL_SUPPORT;
  1310. containerManager;
  1311. /**
  1312. * The DOM events which this contract covers. Used to prevent double
  1313. * registration of event types. The value of the map is the
  1314. * internally created DOM event handler function that handles the
  1315. * DOM events. See addEvent().
  1316. *
  1317. */
  1318. eventHandlers = {};
  1319. browserEventTypeToExtraEventTypes = {};
  1320. /**
  1321. * The dispatcher function. Events are passed to this function for
  1322. * handling once it was set using the registerDispatcher() method. This is
  1323. * done because the function is passed from another jsbinary, so passing the
  1324. * instance and invoking the method here would require to leave the method
  1325. * unobfuscated.
  1326. */
  1327. dispatcher = null;
  1328. /**
  1329. * The list of suspended `EventInfo` that will be dispatched
  1330. * as soon as the `Dispatcher` is registered.
  1331. */
  1332. queuedEventInfos = [];
  1333. constructor(containerManager) {
  1334. this.containerManager = containerManager;
  1335. }
  1336. handleEvent(eventType, event, container) {
  1337. const eventInfo = createEventInfoFromParameters(
  1338. /* eventType= */ eventType,
  1339. /* event= */ event,
  1340. /* targetElement= */ event.target,
  1341. /* container= */ container,
  1342. /* timestamp= */ Date.now());
  1343. this.handleEventInfo(eventInfo);
  1344. }
  1345. /**
  1346. * Handle an `EventInfo`.
  1347. */
  1348. handleEventInfo(eventInfo) {
  1349. if (!this.dispatcher) {
  1350. // All events are queued when the dispatcher isn't yet loaded.
  1351. setIsReplay(eventInfo, true);
  1352. this.queuedEventInfos?.push(eventInfo);
  1353. return;
  1354. }
  1355. this.dispatcher(eventInfo);
  1356. }
  1357. /**
  1358. * Enables jsaction handlers to be called for the event type given by
  1359. * name.
  1360. *
  1361. * If the event is already registered, this does nothing.
  1362. *
  1363. * @param prefixedEventType If supplied, this event is used in
  1364. * the actual browser event registration instead of the name that is
  1365. * exposed to jsaction. Use this if you e.g. want users to be able
  1366. * to subscribe to jsaction="transitionEnd:foo" while the underlying
  1367. * event is webkitTransitionEnd in one browser and mozTransitionEnd
  1368. * in another.
  1369. *
  1370. * @param passive A boolean value that, if `true`, indicates that the event
  1371. * handler will never call `preventDefault()`.
  1372. */
  1373. addEvent(eventType, prefixedEventType, passive) {
  1374. if (eventType in this.eventHandlers || !this.containerManager) {
  1375. return;
  1376. }
  1377. if (!EventContract.MOUSE_SPECIAL_SUPPORT && MOUSE_SPECIAL_EVENT_TYPES.indexOf(eventType) >= 0) {
  1378. return;
  1379. }
  1380. const eventHandler = (eventType, event, container) => {
  1381. this.handleEvent(eventType, event, container);
  1382. };
  1383. // Store the callback to allow us to replay events.
  1384. this.eventHandlers[eventType] = eventHandler;
  1385. const browserEventType = getBrowserEventType(prefixedEventType || eventType);
  1386. if (browserEventType !== eventType) {
  1387. const eventTypes = this.browserEventTypeToExtraEventTypes[browserEventType] || [];
  1388. eventTypes.push(eventType);
  1389. this.browserEventTypeToExtraEventTypes[browserEventType] = eventTypes;
  1390. }
  1391. this.containerManager.addEventListener(browserEventType, (element) => {
  1392. return (event) => {
  1393. eventHandler(eventType, event, element);
  1394. };
  1395. }, passive);
  1396. }
  1397. /**
  1398. * Gets the queued early events and replay them using the appropriate handler
  1399. * in the provided event contract. Once all the events are replayed, it cleans
  1400. * up the early contract.
  1401. */
  1402. replayEarlyEvents(earlyJsactionData = window._ejsa) {
  1403. // Check if the early contract is present and prevent calling this function
  1404. // more than once.
  1405. if (!earlyJsactionData) {
  1406. return;
  1407. }
  1408. // Replay the early contract events.
  1409. this.replayEarlyEventInfos(earlyJsactionData.q);
  1410. // Clean up the early contract.
  1411. removeAllEventListeners(earlyJsactionData);
  1412. delete window._ejsa;
  1413. }
  1414. /**
  1415. * Replays all the early `EventInfo` objects, dispatching them through the normal
  1416. * `EventContract` flow.
  1417. */
  1418. replayEarlyEventInfos(earlyEventInfos) {
  1419. for (let i = 0; i < earlyEventInfos.length; i++) {
  1420. const earlyEventInfo = earlyEventInfos[i];
  1421. const eventTypes = this.getEventTypesForBrowserEventType(earlyEventInfo.eventType);
  1422. for (let j = 0; j < eventTypes.length; j++) {
  1423. const eventInfo = cloneEventInfo(earlyEventInfo);
  1424. // EventInfo eventType maps to JSAction's internal event type,
  1425. // rather than the browser event type.
  1426. setEventType(eventInfo, eventTypes[j]);
  1427. this.handleEventInfo(eventInfo);
  1428. }
  1429. }
  1430. }
  1431. /**
  1432. * Returns all JSAction event types that have been registered for a given
  1433. * browser event type.
  1434. */
  1435. getEventTypesForBrowserEventType(browserEventType) {
  1436. const eventTypes = [];
  1437. if (this.eventHandlers[browserEventType]) {
  1438. eventTypes.push(browserEventType);
  1439. }
  1440. if (this.browserEventTypeToExtraEventTypes[browserEventType]) {
  1441. eventTypes.push(...this.browserEventTypeToExtraEventTypes[browserEventType]);
  1442. }
  1443. return eventTypes;
  1444. }
  1445. /**
  1446. * Returns the event handler function for a given event type.
  1447. */
  1448. handler(eventType) {
  1449. return this.eventHandlers[eventType];
  1450. }
  1451. /**
  1452. * Cleans up the event contract. This resets all of the `EventContract`'s
  1453. * internal state. Users are responsible for not using this `EventContract`
  1454. * after it has been cleaned up.
  1455. */
  1456. cleanUp() {
  1457. this.containerManager?.cleanUp();
  1458. this.containerManager = null;
  1459. this.eventHandlers = {};
  1460. this.browserEventTypeToExtraEventTypes = {};
  1461. this.dispatcher = null;
  1462. this.queuedEventInfos = [];
  1463. }
  1464. /**
  1465. * Register a dispatcher function. Event info of each event mapped to
  1466. * a jsaction is passed for handling to this callback. The queued
  1467. * events are passed as well to the dispatcher for later replaying
  1468. * once the dispatcher is registered. Clears the event queue to null.
  1469. *
  1470. * @param dispatcher The dispatcher function.
  1471. * @param restriction
  1472. */
  1473. registerDispatcher(dispatcher, restriction) {
  1474. this.ecrd(dispatcher, restriction);
  1475. }
  1476. /**
  1477. * Unrenamed alias for registerDispatcher. Necessary for any codebases that
  1478. * split the `EventContract` and `Dispatcher` code into different compilation
  1479. * units.
  1480. */
  1481. ecrd(dispatcher, restriction) {
  1482. this.dispatcher = dispatcher;
  1483. if (this.queuedEventInfos?.length) {
  1484. for (let i = 0; i < this.queuedEventInfos.length; i++) {
  1485. this.handleEventInfo(this.queuedEventInfos[i]);
  1486. }
  1487. this.queuedEventInfos = null;
  1488. }
  1489. }
  1490. }
  1491. /**
  1492. * Creates an `EarlyJsactionData`, adds events to it, and populates it on a nested object on
  1493. * the window.
  1494. */
  1495. function bootstrapAppScopedEarlyEventContract(container, appId, bubbleEventTypes, captureEventTypes, dataContainer = window) {
  1496. const earlyJsactionData = createEarlyJsactionData(container);
  1497. if (!dataContainer._ejsas) {
  1498. dataContainer._ejsas = {};
  1499. }
  1500. dataContainer._ejsas[appId] = earlyJsactionData;
  1501. addEvents(earlyJsactionData, bubbleEventTypes);
  1502. addEvents(earlyJsactionData, captureEventTypes, /* capture= */ true);
  1503. }
  1504. /** Get the queued `EventInfo` objects that were dispatched before a dispatcher was registered. */
  1505. function getAppScopedQueuedEventInfos(appId, dataContainer = window) {
  1506. return getQueuedEventInfos(dataContainer._ejsas?.[appId]);
  1507. }
  1508. /**
  1509. * Registers a dispatcher function on the `EarlyJsactionData` present on the nested object on the
  1510. * window.
  1511. */
  1512. function registerAppScopedDispatcher(restriction, appId, dispatcher, dataContainer = window) {
  1513. registerDispatcher(dataContainer._ejsas?.[appId], dispatcher);
  1514. }
  1515. /** Removes all event listener handlers. */
  1516. function removeAllAppScopedEventListeners(appId, dataContainer = window) {
  1517. removeAllEventListeners(dataContainer._ejsas?.[appId]);
  1518. }
  1519. /** Clear the early event contract. */
  1520. function clearAppScopedEarlyEventContract(appId, dataContainer = window) {
  1521. if (!dataContainer._ejsas) {
  1522. return;
  1523. }
  1524. dataContainer._ejsas[appId] = undefined;
  1525. }
  1526. export { Attribute, EventContract, EventContractContainer, EventDispatcher, EventInfoWrapper, EventPhase, bootstrapAppScopedEarlyEventContract, clearAppScopedEarlyEventContract, getDefaulted as getActionCache, getAppScopedQueuedEventInfos, isCaptureEventType, isEarlyEventType, registerAppScopedDispatcher, registerDispatcher$1 as registerDispatcher, removeAllAppScopedEventListeners };
  1527. //# sourceMappingURL=event-dispatch.mjs.map