stimulus-library 0.6.2 → 0.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (211) hide show
  1. package/CHANGELOG.md +73 -0
  2. package/dist/controllers/ajax/async_block_controller.d.ts +17 -18
  3. package/dist/controllers/ajax/async_block_controller.d.ts.map +1 -1
  4. package/dist/controllers/ajax/index.d.ts +5 -0
  5. package/dist/controllers/ajax/index.d.ts.map +1 -0
  6. package/dist/controllers/ajax/lazy_block_controller.d.ts +9 -9
  7. package/dist/controllers/ajax/lazy_block_controller.d.ts.map +1 -1
  8. package/dist/controllers/ajax/load_block_controller.d.ts +23 -19
  9. package/dist/controllers/ajax/load_block_controller.d.ts.map +1 -1
  10. package/dist/controllers/ajax/poll_block_controller.d.ts +15 -13
  11. package/dist/controllers/ajax/poll_block_controller.d.ts.map +1 -1
  12. package/dist/controllers/anchor_spy_controller.d.ts +20 -13
  13. package/dist/controllers/anchor_spy_controller.d.ts.map +1 -1
  14. package/dist/controllers/back_link_controller.d.ts +16 -16
  15. package/dist/controllers/clipboard_controller.d.ts +18 -18
  16. package/dist/controllers/confirm_controller.d.ts +12 -12
  17. package/dist/controllers/confirm_navigation_controller.d.ts +14 -15
  18. package/dist/controllers/confirm_navigation_controller.d.ts.map +1 -1
  19. package/dist/controllers/debug_controller.d.ts +6 -6
  20. package/dist/controllers/disable_with_controller.d.ts +19 -23
  21. package/dist/controllers/disable_with_controller.d.ts.map +1 -1
  22. package/dist/controllers/dismissable_controller.d.ts +6 -6
  23. package/dist/controllers/element_save_controller.d.ts +30 -25
  24. package/dist/controllers/element_save_controller.d.ts.map +1 -1
  25. package/dist/controllers/empty_dom_controller.d.ts +21 -29
  26. package/dist/controllers/empty_dom_controller.d.ts.map +1 -1
  27. package/dist/controllers/forms/auto_submit_form_controller.d.ts +22 -21
  28. package/dist/controllers/forms/auto_submit_form_controller.d.ts.map +1 -1
  29. package/dist/controllers/forms/autosize_controller.d.ts +8 -9
  30. package/dist/controllers/forms/autosize_controller.d.ts.map +1 -1
  31. package/dist/controllers/forms/char_count_controller.d.ts +20 -24
  32. package/dist/controllers/forms/char_count_controller.d.ts.map +1 -1
  33. package/dist/controllers/forms/checkbox_disable_inputs_controller.d.ts +16 -16
  34. package/dist/controllers/forms/checkbox_enable_inputs_controller.d.ts +16 -16
  35. package/dist/controllers/forms/checkbox_select_all_controller.d.ts +13 -12
  36. package/dist/controllers/forms/checkbox_select_all_controller.d.ts.map +1 -1
  37. package/dist/controllers/forms/checkbox_xor_controller.d.ts +9 -0
  38. package/dist/controllers/forms/checkbox_xor_controller.d.ts.map +1 -0
  39. package/dist/controllers/forms/detect_dirty_controller.d.ts +14 -14
  40. package/dist/controllers/forms/detect_dirty_controller.d.ts.map +1 -1
  41. package/dist/controllers/forms/detect_dirty_form_controller.d.ts +17 -17
  42. package/dist/controllers/forms/detect_dirty_form_controller.d.ts.map +1 -1
  43. package/dist/controllers/forms/enable_inputs_controller.d.ts +13 -13
  44. package/dist/controllers/forms/focus_steal_controller.d.ts +11 -11
  45. package/dist/controllers/forms/form_rc_controller.d.ts +17 -17
  46. package/dist/controllers/forms/form_save_controller.d.ts +31 -31
  47. package/dist/controllers/forms/index.d.ts +23 -0
  48. package/dist/controllers/forms/index.d.ts.map +1 -0
  49. package/dist/controllers/forms/limited_selection_checkboxes_controller.d.ts +16 -15
  50. package/dist/controllers/forms/limited_selection_checkboxes_controller.d.ts.map +1 -1
  51. package/dist/controllers/forms/navigate_form_errors_controller.d.ts +40 -34
  52. package/dist/controllers/forms/navigate_form_errors_controller.d.ts.map +1 -1
  53. package/dist/controllers/forms/nested_form_controller.d.ts +21 -21
  54. package/dist/controllers/forms/password_confirm_controller.d.ts +11 -15
  55. package/dist/controllers/forms/password_confirm_controller.d.ts.map +1 -1
  56. package/dist/controllers/forms/password_peek_controller.d.ts +8 -8
  57. package/dist/controllers/forms/remote_form_controller.d.ts +13 -13
  58. package/dist/controllers/forms/sync_inputs_controller.d.ts +19 -21
  59. package/dist/controllers/forms/sync_inputs_controller.d.ts.map +1 -1
  60. package/dist/controllers/forms/value_warn_controller.d.ts +30 -37
  61. package/dist/controllers/forms/value_warn_controller.d.ts.map +1 -1
  62. package/dist/controllers/forms/word_count_controller.d.ts +20 -24
  63. package/dist/controllers/forms/word_count_controller.d.ts.map +1 -1
  64. package/dist/controllers/index.d.ts +30 -0
  65. package/dist/controllers/index.d.ts.map +1 -0
  66. package/dist/controllers/media/fallback_image_controller.d.ts +19 -27
  67. package/dist/controllers/media/fallback_image_controller.d.ts.map +1 -1
  68. package/dist/controllers/media/index.d.ts +4 -0
  69. package/dist/controllers/media/index.d.ts.map +1 -0
  70. package/dist/controllers/media/lightbox_image_controller.d.ts +30 -29
  71. package/dist/controllers/media/lightbox_image_controller.d.ts.map +1 -1
  72. package/dist/controllers/media/media_player_controller.d.ts +9 -12
  73. package/dist/controllers/media/media_player_controller.d.ts.map +1 -1
  74. package/dist/controllers/prefetch_controller.d.ts +16 -16
  75. package/dist/controllers/prefetch_controller.d.ts.map +1 -1
  76. package/dist/controllers/print_button_controller.d.ts +7 -11
  77. package/dist/controllers/print_button_controller.d.ts.map +1 -1
  78. package/dist/controllers/responsive_iframe_controller.d.ts +16 -21
  79. package/dist/controllers/responsive_iframe_controller.d.ts.map +1 -1
  80. package/dist/controllers/scroll/index.d.ts +6 -0
  81. package/dist/controllers/scroll/index.d.ts.map +1 -0
  82. package/dist/controllers/scroll/scroll_container_controller.d.ts +21 -21
  83. package/dist/controllers/scroll/scroll_into_focus_controller.d.ts +15 -15
  84. package/dist/controllers/scroll/scroll_to_bottom_controller.d.ts +11 -11
  85. package/dist/controllers/scroll/scroll_to_controller.d.ts +17 -17
  86. package/dist/controllers/scroll/scroll_to_top_controller.d.ts +11 -11
  87. package/dist/controllers/self_destruct_controller.d.ts +8 -8
  88. package/dist/controllers/signal/events.d.ts +4 -0
  89. package/dist/controllers/signal/events.d.ts.map +1 -0
  90. package/dist/controllers/signal/expressions.d.ts +2 -0
  91. package/dist/controllers/signal/expressions.d.ts.map +1 -0
  92. package/dist/controllers/signal/index.d.ts +4 -0
  93. package/dist/controllers/signal/index.d.ts.map +1 -0
  94. package/dist/controllers/signal/signal_action_controller.d.ts +15 -0
  95. package/dist/controllers/signal/signal_action_controller.d.ts.map +1 -0
  96. package/dist/controllers/signal/signal_input_controller.d.ts +20 -0
  97. package/dist/controllers/signal/signal_input_controller.d.ts.map +1 -0
  98. package/dist/controllers/signal/signal_visibility_controller.d.ts +18 -0
  99. package/dist/controllers/signal/signal_visibility_controller.d.ts.map +1 -0
  100. package/dist/controllers/sticky_controller.d.ts +15 -18
  101. package/dist/controllers/sticky_controller.d.ts.map +1 -1
  102. package/dist/controllers/tables/index.d.ts +3 -0
  103. package/dist/controllers/tables/index.d.ts.map +1 -0
  104. package/dist/controllers/tables/table_sort_controller.d.ts +19 -18
  105. package/dist/controllers/tables/table_sort_controller.d.ts.map +1 -1
  106. package/dist/controllers/tables/table_truncate_controller.d.ts +25 -26
  107. package/dist/controllers/tables/table_truncate_controller.d.ts.map +1 -1
  108. package/dist/controllers/teleport_controller.d.ts +15 -15
  109. package/dist/controllers/temporary_state_controller.d.ts +26 -27
  110. package/dist/controllers/temporary_state_controller.d.ts.map +1 -1
  111. package/dist/controllers/toggle_class_controller.d.ts +35 -35
  112. package/dist/controllers/toggle_class_controller.d.ts.map +1 -1
  113. package/dist/controllers/trix_modifier_controller.d.ts +88 -0
  114. package/dist/controllers/trix_modifier_controller.d.ts.map +1 -0
  115. package/dist/controllers/turbo_frame_rc_controller.d.ts +20 -20
  116. package/dist/controllers/turbo_frame_refresh_controller.d.ts +13 -13
  117. package/dist/controllers/utility/alert_controller.d.ts +9 -0
  118. package/dist/controllers/utility/alert_controller.d.ts.map +1 -0
  119. package/dist/controllers/utility/fullscreen_controller.d.ts +8 -0
  120. package/dist/controllers/utility/fullscreen_controller.d.ts.map +1 -0
  121. package/dist/controllers/utility/index.d.ts +9 -0
  122. package/dist/controllers/utility/index.d.ts.map +1 -0
  123. package/dist/controllers/utility/intersection_controller.d.ts +13 -13
  124. package/dist/controllers/utility/intersection_controller.d.ts.map +1 -1
  125. package/dist/controllers/utility/interval_controller.d.ts +10 -10
  126. package/dist/controllers/utility/presence_controller.d.ts +13 -11
  127. package/dist/controllers/utility/presence_controller.d.ts.map +1 -1
  128. package/dist/controllers/utility/print_controller.d.ts +4 -4
  129. package/dist/controllers/utility/timeout_controller.d.ts +9 -9
  130. package/dist/controllers/utility/user_focus_controller.d.ts +8 -8
  131. package/dist/controllers/visual/clock_controller.d.ts +15 -15
  132. package/dist/controllers/visual/countdown_controller.d.ts +45 -53
  133. package/dist/controllers/visual/countdown_controller.d.ts.map +1 -1
  134. package/dist/controllers/visual/duration_controller.d.ts +25 -26
  135. package/dist/controllers/visual/duration_controller.d.ts.map +1 -1
  136. package/dist/controllers/visual/index.d.ts +7 -0
  137. package/dist/controllers/visual/index.d.ts.map +1 -0
  138. package/dist/controllers/visual/tabs_controller.d.ts +29 -35
  139. package/dist/controllers/visual/tabs_controller.d.ts.map +1 -1
  140. package/dist/controllers/visual/time_distance_controller.d.ts +15 -16
  141. package/dist/controllers/visual/time_distance_controller.d.ts.map +1 -1
  142. package/dist/controllers/visual/tree_view_controller.d.ts +25 -29
  143. package/dist/controllers/visual/tree_view_controller.d.ts.map +1 -1
  144. package/dist/index.d.ts +3 -79
  145. package/dist/index.d.ts.map +1 -1
  146. package/dist/mixins/create_mixin.d.ts +3 -0
  147. package/dist/mixins/create_mixin.d.ts.map +1 -0
  148. package/dist/mixins/index.d.ts +9 -0
  149. package/dist/mixins/index.d.ts.map +1 -0
  150. package/dist/mixins/install_class_methods.d.ts +6 -0
  151. package/dist/mixins/install_class_methods.d.ts.map +1 -0
  152. package/dist/mixins/use_click_outside.d.ts +5 -0
  153. package/dist/mixins/use_click_outside.d.ts.map +1 -0
  154. package/dist/mixins/use_event_bus.d.ts +8 -0
  155. package/dist/mixins/use_event_bus.d.ts.map +1 -0
  156. package/dist/mixins/use_event_listener.d.ts +19 -7
  157. package/dist/mixins/use_event_listener.d.ts.map +1 -1
  158. package/dist/mixins/use_fullscreen.d.ts +9 -0
  159. package/dist/mixins/use_fullscreen.d.ts.map +1 -0
  160. package/dist/mixins/use_geolocation.d.ts +19 -0
  161. package/dist/mixins/use_geolocation.d.ts.map +1 -0
  162. package/dist/mixins/use_hover.d.ts +5 -0
  163. package/dist/mixins/use_hover.d.ts.map +1 -0
  164. package/dist/mixins/use_injected_html.d.ts +10 -10
  165. package/dist/mixins/use_injected_html.d.ts.map +1 -1
  166. package/dist/mixins/use_intersection.d.ts +14 -0
  167. package/dist/mixins/use_intersection.d.ts.map +1 -0
  168. package/dist/mixins/use_interval.d.ts +2 -2
  169. package/dist/mixins/use_interval.d.ts.map +1 -1
  170. package/dist/mixins/use_localstorage.d.ts +21 -0
  171. package/dist/mixins/use_localstorage.d.ts.map +1 -0
  172. package/dist/mixins/use_mutation_observer.d.ts +3 -0
  173. package/dist/mixins/use_mutation_observer.d.ts.map +1 -0
  174. package/dist/mixins/use_temporary_content.d.ts +6 -0
  175. package/dist/mixins/use_temporary_content.d.ts.map +1 -0
  176. package/dist/mixins/use_timeout.d.ts +2 -2
  177. package/dist/mixins/use_timeout.d.ts.map +1 -1
  178. package/dist/mixins/use_trix_modifiers.d.ts +11 -0
  179. package/dist/mixins/use_trix_modifiers.d.ts.map +1 -0
  180. package/dist/stimulus-library.cjs.js +1 -1
  181. package/dist/stimulus-library.cjs.js.map +1 -1
  182. package/dist/stimulus-library.es.js +4659 -1
  183. package/dist/stimulus-library.es.js.map +1 -1
  184. package/dist/stimulus-library.umd.js +1 -1
  185. package/dist/stimulus-library.umd.js.map +1 -1
  186. package/dist/utilities/arrays.d.ts +2 -0
  187. package/dist/utilities/arrays.d.ts.map +1 -0
  188. package/dist/utilities/base_controller.d.ts +10 -13
  189. package/dist/utilities/base_controller.d.ts.map +1 -1
  190. package/dist/utilities/elements.d.ts +48 -17
  191. package/dist/utilities/elements.d.ts.map +1 -1
  192. package/dist/utilities/ephemeral_controller.d.ts +5 -5
  193. package/dist/utilities/event_bus.d.ts +3 -3
  194. package/dist/utilities/events.d.ts +3 -0
  195. package/dist/utilities/events.d.ts.map +1 -0
  196. package/dist/utilities/fetchRetry.d.ts +2 -0
  197. package/dist/utilities/fetchRetry.d.ts.map +1 -0
  198. package/dist/utilities/index.d.ts +8 -0
  199. package/dist/utilities/index.d.ts.map +1 -0
  200. package/dist/utilities/logging.d.ts +6 -0
  201. package/dist/utilities/logging.d.ts.map +1 -0
  202. package/dist/utilities/reactive.d.ts +2 -0
  203. package/dist/utilities/reactive.d.ts.map +1 -0
  204. package/dist/utilities/request_submit.d.ts +2 -2
  205. package/dist/utilities/scroll.d.ts +10 -10
  206. package/dist/utilities/stimulus.d.ts +3 -0
  207. package/dist/utilities/stimulus.d.ts.map +1 -0
  208. package/dist/utilities/strings.d.ts +2 -0
  209. package/dist/utilities/strings.d.ts.map +1 -0
  210. package/dist/utilities/turbo.d.ts +1 -1
  211. package/package.json +11 -11
@@ -1,2 +1,4660 @@
1
- var e=Object.defineProperty,t=Object.getOwnPropertySymbols,s=Object.prototype.hasOwnProperty,i=Object.prototype.propertyIsEnumerable,r=(t,s,i)=>s in t?e(t,s,{enumerable:!0,configurable:!0,writable:!0,value:i}):t[s]=i,n=(e,n)=>{for(var o in n||(n={}))s.call(n,o)&&r(e,o,n[o]);if(t)for(var o of t(n))i.call(n,o)&&r(e,o,n[o]);return e},o=(e,t,s)=>(r(e,"symbol"!=typeof t?t+"":t,s),s);import{debounce as a,get as l,set as c,clamp as h,camelCase as u}from"lodash-es";import{isPast as d,intervalToDuration as p,formatDuration as f,toDate as m,formatDistanceToNow as g}from"date-fns";var v=function(){function e(e,t,s){this.eventTarget=e,this.eventName=t,this.eventOptions=s,this.unorderedBindings=new Set}return e.prototype.connect=function(){this.eventTarget.addEventListener(this.eventName,this,this.eventOptions)},e.prototype.disconnect=function(){this.eventTarget.removeEventListener(this.eventName,this,this.eventOptions)},e.prototype.bindingConnected=function(e){this.unorderedBindings.add(e)},e.prototype.bindingDisconnected=function(e){this.unorderedBindings.delete(e)},e.prototype.handleEvent=function(e){for(var t=function(e){if("immediatePropagationStopped"in e)return e;var t=e.stopImmediatePropagation;return Object.assign(e,{immediatePropagationStopped:!1,stopImmediatePropagation:function(){this.immediatePropagationStopped=!0,t.call(this)}})}(e),s=0,i=this.bindings;s<i.length;s++){var r=i[s];if(t.immediatePropagationStopped)break;r.handleEvent(t)}},Object.defineProperty(e.prototype,"bindings",{get:function(){return Array.from(this.unorderedBindings).sort((function(e,t){var s=e.index,i=t.index;return s<i?-1:s>i?1:0}))},enumerable:!1,configurable:!0}),e}();var b=function(){function e(e){this.application=e,this.eventListenerMaps=new Map,this.started=!1}return e.prototype.start=function(){this.started||(this.started=!0,this.eventListeners.forEach((function(e){return e.connect()})))},e.prototype.stop=function(){this.started&&(this.started=!1,this.eventListeners.forEach((function(e){return e.disconnect()})))},Object.defineProperty(e.prototype,"eventListeners",{get:function(){return Array.from(this.eventListenerMaps.values()).reduce((function(e,t){return e.concat(Array.from(t.values()))}),[])},enumerable:!1,configurable:!0}),e.prototype.bindingConnected=function(e){this.fetchEventListenerForBinding(e).bindingConnected(e)},e.prototype.bindingDisconnected=function(e){this.fetchEventListenerForBinding(e).bindingDisconnected(e)},e.prototype.handleError=function(e,t,s){void 0===s&&(s={}),this.application.handleError(e,"Error "+t,s)},e.prototype.fetchEventListenerForBinding=function(e){var t=e.eventTarget,s=e.eventName,i=e.eventOptions;return this.fetchEventListener(t,s,i)},e.prototype.fetchEventListener=function(e,t,s){var i=this.fetchEventListenerMapForEventTarget(e),r=this.cacheKey(t,s),n=i.get(r);return n||(n=this.createEventListener(e,t,s),i.set(r,n)),n},e.prototype.createEventListener=function(e,t,s){var i=new v(e,t,s);return this.started&&i.connect(),i},e.prototype.fetchEventListenerMapForEventTarget=function(e){var t=this.eventListenerMaps.get(e);return t||(t=new Map,this.eventListenerMaps.set(e,t)),t},e.prototype.cacheKey=function(e,t){var s=[e];return Object.keys(t).sort().forEach((function(e){s.push((t[e]?"":"!")+e)})),s.join(":")},e}(),y=/^((.+?)(@(window|document))?->)?(.+?)(#([^:]+?))(:(.+))?$/;function _(e){return"window"==e?window:"document"==e?document:void 0}var w=function(){function e(e,t,s){this.element=e,this.index=t,this.eventTarget=s.eventTarget||e,this.eventName=s.eventName||function(e){var t=e.tagName.toLowerCase();if(t in E)return E[t](e)}(e)||C("missing event name"),this.eventOptions=s.eventOptions||{},this.identifier=s.identifier||C("missing identifier"),this.methodName=s.methodName||C("missing method name")}return e.forToken=function(e){return new this(e.element,e.index,(t=e.content,{eventTarget:_((i=t.trim().match(y)||[])[4]),eventName:i[2],eventOptions:i[9]?(s=i[9],s.split(":").reduce((function(e,t){var s;return Object.assign(e,((s={})[t.replace(/^!/,"")]=!/^!/.test(t),s))}),{})):{},identifier:i[5],methodName:i[7]}));var t,s,i},e.prototype.toString=function(){var e=this.eventTargetName?"@"+this.eventTargetName:"";return""+this.eventName+e+"->"+this.identifier+"#"+this.methodName},Object.defineProperty(e.prototype,"eventTargetName",{get:function(){return(e=this.eventTarget)==window?"window":e==document?"document":void 0;var e},enumerable:!1,configurable:!0}),e}(),E={a:function(e){return"click"},button:function(e){return"click"},form:function(e){return"submit"},input:function(e){return"submit"==e.getAttribute("type")?"click":"input"},select:function(e){return"change"},textarea:function(e){return"input"}};function C(e){throw new Error(e)}var T=function(){function e(e,t){this.context=e,this.action=t}return Object.defineProperty(e.prototype,"index",{get:function(){return this.action.index},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"eventTarget",{get:function(){return this.action.eventTarget},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"eventOptions",{get:function(){return this.action.eventOptions},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"identifier",{get:function(){return this.context.identifier},enumerable:!1,configurable:!0}),e.prototype.handleEvent=function(e){this.willBeInvokedByEvent(e)&&this.invokeWithEvent(e)},Object.defineProperty(e.prototype,"eventName",{get:function(){return this.action.eventName},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"method",{get:function(){var e=this.controller[this.methodName];if("function"==typeof e)return e;throw new Error('Action "'+this.action+'" references undefined method "'+this.methodName+'"')},enumerable:!1,configurable:!0}),e.prototype.invokeWithEvent=function(e){try{this.method.call(this.controller,e)}catch(i){var t=this,s={identifier:t.identifier,controller:t.controller,element:t.element,index:t.index,event:e};this.context.handleError(i,'invoking action "'+this.action+'"',s)}},e.prototype.willBeInvokedByEvent=function(e){var t=e.target;return this.element===t||(t instanceof Element&&this.element.contains(t)?this.scope.containsElement(t):this.scope.containsElement(this.action.element))},Object.defineProperty(e.prototype,"controller",{get:function(){return this.context.controller},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"methodName",{get:function(){return this.action.methodName},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"element",{get:function(){return this.scope.element},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"scope",{get:function(){return this.context.scope},enumerable:!1,configurable:!0}),e}(),k=function(){function e(e,t){var s=this;this.element=e,this.started=!1,this.delegate=t,this.elements=new Set,this.mutationObserver=new MutationObserver((function(e){return s.processMutations(e)}))}return e.prototype.start=function(){this.started||(this.started=!0,this.mutationObserver.observe(this.element,{attributes:!0,childList:!0,subtree:!0}),this.refresh())},e.prototype.stop=function(){this.started&&(this.mutationObserver.takeRecords(),this.mutationObserver.disconnect(),this.started=!1)},e.prototype.refresh=function(){if(this.started){for(var e=new Set(this.matchElementsInTree()),t=0,s=Array.from(this.elements);t<s.length;t++){var i=s[t];e.has(i)||this.removeElement(i)}for(var r=0,n=Array.from(e);r<n.length;r++){i=n[r];this.addElement(i)}}},e.prototype.processMutations=function(e){if(this.started)for(var t=0,s=e;t<s.length;t++){var i=s[t];this.processMutation(i)}},e.prototype.processMutation=function(e){"attributes"==e.type?this.processAttributeChange(e.target,e.attributeName):"childList"==e.type&&(this.processRemovedNodes(e.removedNodes),this.processAddedNodes(e.addedNodes))},e.prototype.processAttributeChange=function(e,t){var s=e;this.elements.has(s)?this.delegate.elementAttributeChanged&&this.matchElement(s)?this.delegate.elementAttributeChanged(s,t):this.removeElement(s):this.matchElement(s)&&this.addElement(s)},e.prototype.processRemovedNodes=function(e){for(var t=0,s=Array.from(e);t<s.length;t++){var i=s[t],r=this.elementFromNode(i);r&&this.processTree(r,this.removeElement)}},e.prototype.processAddedNodes=function(e){for(var t=0,s=Array.from(e);t<s.length;t++){var i=s[t],r=this.elementFromNode(i);r&&this.elementIsActive(r)&&this.processTree(r,this.addElement)}},e.prototype.matchElement=function(e){return this.delegate.matchElement(e)},e.prototype.matchElementsInTree=function(e){return void 0===e&&(e=this.element),this.delegate.matchElementsInTree(e)},e.prototype.processTree=function(e,t){for(var s=0,i=this.matchElementsInTree(e);s<i.length;s++){var r=i[s];t.call(this,r)}},e.prototype.elementFromNode=function(e){if(e.nodeType==Node.ELEMENT_NODE)return e},e.prototype.elementIsActive=function(e){return e.isConnected==this.element.isConnected&&this.element.contains(e)},e.prototype.addElement=function(e){this.elements.has(e)||this.elementIsActive(e)&&(this.elements.add(e),this.delegate.elementMatched&&this.delegate.elementMatched(e))},e.prototype.removeElement=function(e){this.elements.has(e)&&(this.elements.delete(e),this.delegate.elementUnmatched&&this.delegate.elementUnmatched(e))},e}(),V=function(){function e(e,t,s){this.attributeName=t,this.delegate=s,this.elementObserver=new k(e,this)}return Object.defineProperty(e.prototype,"element",{get:function(){return this.elementObserver.element},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"selector",{get:function(){return"["+this.attributeName+"]"},enumerable:!1,configurable:!0}),e.prototype.start=function(){this.elementObserver.start()},e.prototype.stop=function(){this.elementObserver.stop()},e.prototype.refresh=function(){this.elementObserver.refresh()},Object.defineProperty(e.prototype,"started",{get:function(){return this.elementObserver.started},enumerable:!1,configurable:!0}),e.prototype.matchElement=function(e){return e.hasAttribute(this.attributeName)},e.prototype.matchElementsInTree=function(e){var t=this.matchElement(e)?[e]:[],s=Array.from(e.querySelectorAll(this.selector));return t.concat(s)},e.prototype.elementMatched=function(e){this.delegate.elementMatchedAttribute&&this.delegate.elementMatchedAttribute(e,this.attributeName)},e.prototype.elementUnmatched=function(e){this.delegate.elementUnmatchedAttribute&&this.delegate.elementUnmatchedAttribute(e,this.attributeName)},e.prototype.elementAttributeChanged=function(e,t){this.delegate.elementAttributeValueChanged&&this.attributeName==t&&this.delegate.elementAttributeValueChanged(e,t)},e}(),A=function(){function e(e,t){var s=this;this.element=e,this.delegate=t,this.started=!1,this.stringMap=new Map,this.mutationObserver=new MutationObserver((function(e){return s.processMutations(e)}))}return e.prototype.start=function(){this.started||(this.started=!0,this.mutationObserver.observe(this.element,{attributes:!0}),this.refresh())},e.prototype.stop=function(){this.started&&(this.mutationObserver.takeRecords(),this.mutationObserver.disconnect(),this.started=!1)},e.prototype.refresh=function(){if(this.started)for(var e=0,t=this.knownAttributeNames;e<t.length;e++){var s=t[e];this.refreshAttribute(s)}},e.prototype.processMutations=function(e){if(this.started)for(var t=0,s=e;t<s.length;t++){var i=s[t];this.processMutation(i)}},e.prototype.processMutation=function(e){var t=e.attributeName;t&&this.refreshAttribute(t)},e.prototype.refreshAttribute=function(e){var t=this.delegate.getStringMapKeyForAttribute(e);if(null!=t){this.stringMap.has(e)||this.stringMapKeyAdded(t,e);var s=this.element.getAttribute(e);this.stringMap.get(e)!=s&&this.stringMapValueChanged(s,t),null==s?(this.stringMap.delete(e),this.stringMapKeyRemoved(t,e)):this.stringMap.set(e,s)}},e.prototype.stringMapKeyAdded=function(e,t){this.delegate.stringMapKeyAdded&&this.delegate.stringMapKeyAdded(e,t)},e.prototype.stringMapValueChanged=function(e,t){this.delegate.stringMapValueChanged&&this.delegate.stringMapValueChanged(e,t)},e.prototype.stringMapKeyRemoved=function(e,t){this.delegate.stringMapKeyRemoved&&this.delegate.stringMapKeyRemoved(e,t)},Object.defineProperty(e.prototype,"knownAttributeNames",{get:function(){return Array.from(new Set(this.currentAttributeNames.concat(this.recordedAttributeNames)))},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"currentAttributeNames",{get:function(){return Array.from(this.element.attributes).map((function(e){return e.name}))},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"recordedAttributeNames",{get:function(){return Array.from(this.stringMap.keys())},enumerable:!1,configurable:!0}),e}();function S(e,t,s){O(e,t).add(s)}function x(e,t,s){O(e,t).delete(s),function(e,t){var s=e.get(t);null!=s&&0==s.size&&e.delete(t)}(e,t)}function O(e,t){var s=e.get(t);return s||(s=new Set,e.set(t,s)),s}var M,L=function(){function e(){this.valuesByKey=new Map}return Object.defineProperty(e.prototype,"values",{get:function(){return Array.from(this.valuesByKey.values()).reduce((function(e,t){return e.concat(Array.from(t))}),[])},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"size",{get:function(){return Array.from(this.valuesByKey.values()).reduce((function(e,t){return e+t.size}),0)},enumerable:!1,configurable:!0}),e.prototype.add=function(e,t){S(this.valuesByKey,e,t)},e.prototype.delete=function(e,t){x(this.valuesByKey,e,t)},e.prototype.has=function(e,t){var s=this.valuesByKey.get(e);return null!=s&&s.has(t)},e.prototype.hasKey=function(e){return this.valuesByKey.has(e)},e.prototype.hasValue=function(e){return Array.from(this.valuesByKey.values()).some((function(t){return t.has(e)}))},e.prototype.getValuesForKey=function(e){var t=this.valuesByKey.get(e);return t?Array.from(t):[]},e.prototype.getKeysForValue=function(e){return Array.from(this.valuesByKey).filter((function(t){return t[0],t[1].has(e)})).map((function(e){var t=e[0];return e[1],t}))},e}(),N=(M=function(e,t){return(M=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var s in t)t.hasOwnProperty(s)&&(e[s]=t[s])})(e,t)},function(e,t){function s(){this.constructor=e}M(e,t),e.prototype=null===t?Object.create(t):(s.prototype=t.prototype,new s)});!function(e){function t(){var t=e.call(this)||this;return t.keysByValue=new Map,t}N(t,e),Object.defineProperty(t.prototype,"values",{get:function(){return Array.from(this.keysByValue.keys())},enumerable:!1,configurable:!0}),t.prototype.add=function(t,s){e.prototype.add.call(this,t,s),S(this.keysByValue,s,t)},t.prototype.delete=function(t,s){e.prototype.delete.call(this,t,s),x(this.keysByValue,s,t)},t.prototype.hasValue=function(e){return this.keysByValue.has(e)},t.prototype.getKeysForValue=function(e){var t=this.keysByValue.get(e);return t?Array.from(t):[]}}(L);var D=function(){function e(e,t,s){this.attributeObserver=new V(e,t,this),this.delegate=s,this.tokensByElement=new L}return Object.defineProperty(e.prototype,"started",{get:function(){return this.attributeObserver.started},enumerable:!1,configurable:!0}),e.prototype.start=function(){this.attributeObserver.start()},e.prototype.stop=function(){this.attributeObserver.stop()},e.prototype.refresh=function(){this.attributeObserver.refresh()},Object.defineProperty(e.prototype,"element",{get:function(){return this.attributeObserver.element},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"attributeName",{get:function(){return this.attributeObserver.attributeName},enumerable:!1,configurable:!0}),e.prototype.elementMatchedAttribute=function(e){this.tokensMatched(this.readTokensForElement(e))},e.prototype.elementAttributeValueChanged=function(e){var t=this.refreshTokensForElement(e),s=t[0],i=t[1];this.tokensUnmatched(s),this.tokensMatched(i)},e.prototype.elementUnmatchedAttribute=function(e){this.tokensUnmatched(this.tokensByElement.getValuesForKey(e))},e.prototype.tokensMatched=function(e){var t=this;e.forEach((function(e){return t.tokenMatched(e)}))},e.prototype.tokensUnmatched=function(e){var t=this;e.forEach((function(e){return t.tokenUnmatched(e)}))},e.prototype.tokenMatched=function(e){this.delegate.tokenMatched(e),this.tokensByElement.add(e.element,e)},e.prototype.tokenUnmatched=function(e){this.delegate.tokenUnmatched(e),this.tokensByElement.delete(e.element,e)},e.prototype.refreshTokensForElement=function(e){var t,s,i,r=this.tokensByElement.getValuesForKey(e),n=this.readTokensForElement(e),o=(t=r,s=n,i=Math.max(t.length,s.length),Array.from({length:i},(function(e,i){return[t[i],s[i]]}))).findIndex((function(e){return!function(e,t){return e&&t&&e.index==t.index&&e.content==t.content}(e[0],e[1])}));return-1==o?[[],[]]:[r.slice(o),n.slice(o)]},e.prototype.readTokensForElement=function(e){var t=this.attributeName;return function(e,t,s){return e.trim().split(/\s+/).filter((function(e){return e.length})).map((function(e,i){return{element:t,attributeName:s,content:e,index:i}}))}(e.getAttribute(t)||"",e,t)},e}();var I=function(){function e(e,t,s){this.tokenListObserver=new D(e,t,this),this.delegate=s,this.parseResultsByToken=new WeakMap,this.valuesByTokenByElement=new WeakMap}return Object.defineProperty(e.prototype,"started",{get:function(){return this.tokenListObserver.started},enumerable:!1,configurable:!0}),e.prototype.start=function(){this.tokenListObserver.start()},e.prototype.stop=function(){this.tokenListObserver.stop()},e.prototype.refresh=function(){this.tokenListObserver.refresh()},Object.defineProperty(e.prototype,"element",{get:function(){return this.tokenListObserver.element},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"attributeName",{get:function(){return this.tokenListObserver.attributeName},enumerable:!1,configurable:!0}),e.prototype.tokenMatched=function(e){var t=e.element,s=this.fetchParseResultForToken(e).value;s&&(this.fetchValuesByTokenForElement(t).set(e,s),this.delegate.elementMatchedValue(t,s))},e.prototype.tokenUnmatched=function(e){var t=e.element,s=this.fetchParseResultForToken(e).value;s&&(this.fetchValuesByTokenForElement(t).delete(e),this.delegate.elementUnmatchedValue(t,s))},e.prototype.fetchParseResultForToken=function(e){var t=this.parseResultsByToken.get(e);return t||(t=this.parseToken(e),this.parseResultsByToken.set(e,t)),t},e.prototype.fetchValuesByTokenForElement=function(e){var t=this.valuesByTokenByElement.get(e);return t||(t=new Map,this.valuesByTokenByElement.set(e,t)),t},e.prototype.parseToken=function(e){try{return{value:this.delegate.parseValueForToken(e)}}catch(t){return{error:t}}},e}(),P=function(){function e(e,t){this.context=e,this.delegate=t,this.bindingsByAction=new Map}return e.prototype.start=function(){this.valueListObserver||(this.valueListObserver=new I(this.element,this.actionAttribute,this),this.valueListObserver.start())},e.prototype.stop=function(){this.valueListObserver&&(this.valueListObserver.stop(),delete this.valueListObserver,this.disconnectAllActions())},Object.defineProperty(e.prototype,"element",{get:function(){return this.context.element},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"identifier",{get:function(){return this.context.identifier},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"actionAttribute",{get:function(){return this.schema.actionAttribute},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"schema",{get:function(){return this.context.schema},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"bindings",{get:function(){return Array.from(this.bindingsByAction.values())},enumerable:!1,configurable:!0}),e.prototype.connectAction=function(e){var t=new T(this.context,e);this.bindingsByAction.set(e,t),this.delegate.bindingConnected(t)},e.prototype.disconnectAction=function(e){var t=this.bindingsByAction.get(e);t&&(this.bindingsByAction.delete(e),this.delegate.bindingDisconnected(t))},e.prototype.disconnectAllActions=function(){var e=this;this.bindings.forEach((function(t){return e.delegate.bindingDisconnected(t)})),this.bindingsByAction.clear()},e.prototype.parseValueForToken=function(e){var t=w.forToken(e);if(t.identifier==this.identifier)return t},e.prototype.elementMatchedValue=function(e,t){this.connectAction(t)},e.prototype.elementUnmatchedValue=function(e,t){this.disconnectAction(t)},e}(),j=function(){function e(e,t){this.context=e,this.receiver=t,this.stringMapObserver=new A(this.element,this),this.valueDescriptorMap=this.controller.valueDescriptorMap,this.invokeChangedCallbacksForDefaultValues()}return e.prototype.start=function(){this.stringMapObserver.start()},e.prototype.stop=function(){this.stringMapObserver.stop()},Object.defineProperty(e.prototype,"element",{get:function(){return this.context.element},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"controller",{get:function(){return this.context.controller},enumerable:!1,configurable:!0}),e.prototype.getStringMapKeyForAttribute=function(e){if(e in this.valueDescriptorMap)return this.valueDescriptorMap[e].name},e.prototype.stringMapValueChanged=function(e,t){this.invokeChangedCallbackForValue(t)},e.prototype.invokeChangedCallbacksForDefaultValues=function(){for(var e=0,t=this.valueDescriptors;e<t.length;e++){var s=t[e],i=s.key,r=s.name;null==s.defaultValue||this.controller.data.has(i)||this.invokeChangedCallbackForValue(r)}},e.prototype.invokeChangedCallbackForValue=function(e){var t=e+"Changed",s=this.receiver[t];if("function"==typeof s){var i=this.receiver[e];s.call(this.receiver,i)}},Object.defineProperty(e.prototype,"valueDescriptors",{get:function(){var e=this.valueDescriptorMap;return Object.keys(e).map((function(t){return e[t]}))},enumerable:!1,configurable:!0}),e}(),B=function(){function e(e,t){this.module=e,this.scope=t,this.controller=new e.controllerConstructor(this),this.bindingObserver=new P(this,this.dispatcher),this.valueObserver=new j(this,this.controller);try{this.controller.initialize()}catch(s){this.handleError(s,"initializing controller")}}return e.prototype.connect=function(){this.bindingObserver.start(),this.valueObserver.start();try{this.controller.connect()}catch(e){this.handleError(e,"connecting controller")}},e.prototype.disconnect=function(){try{this.controller.disconnect()}catch(e){this.handleError(e,"disconnecting controller")}this.valueObserver.stop(),this.bindingObserver.stop()},Object.defineProperty(e.prototype,"application",{get:function(){return this.module.application},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"identifier",{get:function(){return this.module.identifier},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"schema",{get:function(){return this.application.schema},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"dispatcher",{get:function(){return this.application.dispatcher},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"element",{get:function(){return this.scope.element},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"parentElement",{get:function(){return this.element.parentElement},enumerable:!1,configurable:!0}),e.prototype.handleError=function(e,t,s){void 0===s&&(s={});var i=this,r=i.identifier,n=i.controller,o=i.element;s=Object.assign({identifier:r,controller:n,element:o},s),this.application.handleError(e,"Error "+t,s)},e}();function F(e,t){var s=R(e);return Array.from(s.reduce((function(e,s){return function(e,t){var s=e[t];return Array.isArray(s)?s:[]}(s,t).forEach((function(t){return e.add(t)})),e}),new Set))}function H(e,t){return R(e).reduce((function(e,s){return e.push.apply(e,function(e,t){var s=e[t];return s?Object.keys(s).map((function(e){return[e,s[e]]})):[]}(s,t)),e}),[])}function R(e){for(var t=[];e;)t.push(e),e=Object.getPrototypeOf(e);return t.reverse()}var $=function(){var e=function(t,s){return(e=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var s in t)t.hasOwnProperty(s)&&(e[s]=t[s])})(t,s)};return function(t,s){function i(){this.constructor=t}e(t,s),t.prototype=null===s?Object.create(s):(i.prototype=s.prototype,new i)}}();function q(e){return function(e,t){var s=z(e),i=function(e,t){return U(t).reduce((function(s,i){var r,n=function(e,t,s){var i=Object.getOwnPropertyDescriptor(e,s);if(!i||!("value"in i)){var r=Object.getOwnPropertyDescriptor(t,s).value;return i&&(r.get=i.get||r.get,r.set=i.set||r.set),r}}(e,t,i);return n&&Object.assign(s,((r={})[i]=n,r)),s}),{})}(e.prototype,t);return Object.defineProperties(s.prototype,i),s}(e,function(e){return F(e,"blessings").reduce((function(t,s){var i=s(e);for(var r in i){var n=t[r]||{};t[r]=Object.assign(n,i[r])}return t}),{})}(e))}var U="function"==typeof Object.getOwnPropertySymbols?function(e){return function(){for(var e=0,t=0,s=arguments.length;t<s;t++)e+=arguments[t].length;var i=Array(e),r=0;for(t=0;t<s;t++)for(var n=arguments[t],o=0,a=n.length;o<a;o++,r++)i[r]=n[o];return i}(Object.getOwnPropertyNames(e),Object.getOwnPropertySymbols(e))}:Object.getOwnPropertyNames,z=function(){function e(e){function t(){var s=this&&this instanceof t?this.constructor:void 0;return Reflect.construct(e,arguments,s)}return t.prototype=Object.create(e.prototype,{constructor:{value:t}}),Reflect.setPrototypeOf(t,e),t}try{return(t=e((function(){this.a.call(this)}))).prototype.a=function(){},new t,e}catch(s){return function(e){return function(e){function t(){return null!==e&&e.apply(this,arguments)||this}return $(t,e),t}(e)}}var t}();var K=function(){function e(e,t){this.application=e,this.definition=function(e){return{identifier:e.identifier,controllerConstructor:q(e.controllerConstructor)}}(t),this.contextsByScope=new WeakMap,this.connectedContexts=new Set}return Object.defineProperty(e.prototype,"identifier",{get:function(){return this.definition.identifier},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"controllerConstructor",{get:function(){return this.definition.controllerConstructor},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"contexts",{get:function(){return Array.from(this.connectedContexts)},enumerable:!1,configurable:!0}),e.prototype.connectContextForScope=function(e){var t=this.fetchContextForScope(e);this.connectedContexts.add(t),t.connect()},e.prototype.disconnectContextForScope=function(e){var t=this.contextsByScope.get(e);t&&(this.connectedContexts.delete(t),t.disconnect())},e.prototype.fetchContextForScope=function(e){var t=this.contextsByScope.get(e);return t||(t=new B(this,e),this.contextsByScope.set(e,t)),t},e}(),W=function(){function e(e){this.scope=e}return e.prototype.has=function(e){return this.data.has(this.getDataKey(e))},e.prototype.get=function(e){return this.data.get(this.getDataKey(e))},e.prototype.getAttributeName=function(e){return this.data.getAttributeNameForKey(this.getDataKey(e))},e.prototype.getDataKey=function(e){return e+"-class"},Object.defineProperty(e.prototype,"data",{get:function(){return this.scope.data},enumerable:!1,configurable:!0}),e}();function J(e){return e.replace(/(?:[_-])([a-z0-9])/g,(function(e,t){return t.toUpperCase()}))}function Y(e){return e.charAt(0).toUpperCase()+e.slice(1)}function Z(e){return e.replace(/([A-Z])/g,(function(e,t){return"-"+t.toLowerCase()}))}var X=function(){function e(e){this.scope=e}return Object.defineProperty(e.prototype,"element",{get:function(){return this.scope.element},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"identifier",{get:function(){return this.scope.identifier},enumerable:!1,configurable:!0}),e.prototype.get=function(e){var t=this.getAttributeNameForKey(e);return this.element.getAttribute(t)},e.prototype.set=function(e,t){var s=this.getAttributeNameForKey(e);return this.element.setAttribute(s,t),this.get(e)},e.prototype.has=function(e){var t=this.getAttributeNameForKey(e);return this.element.hasAttribute(t)},e.prototype.delete=function(e){if(this.has(e)){var t=this.getAttributeNameForKey(e);return this.element.removeAttribute(t),!0}return!1},e.prototype.getAttributeNameForKey=function(e){return"data-"+this.identifier+"-"+Z(e)},e}(),G=function(){function e(e){this.warnedKeysByObject=new WeakMap,this.logger=e}return e.prototype.warn=function(e,t,s){var i=this.warnedKeysByObject.get(e);i||(i=new Set,this.warnedKeysByObject.set(e,i)),i.has(t)||(i.add(t),this.logger.warn(s,e))},e}();function Q(e,t){return"["+e+'~="'+t+'"]'}var ee=function(){for(var e=0,t=0,s=arguments.length;t<s;t++)e+=arguments[t].length;var i=Array(e),r=0;for(t=0;t<s;t++)for(var n=arguments[t],o=0,a=n.length;o<a;o++,r++)i[r]=n[o];return i},te=function(){function e(e){this.scope=e}return Object.defineProperty(e.prototype,"element",{get:function(){return this.scope.element},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"identifier",{get:function(){return this.scope.identifier},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"schema",{get:function(){return this.scope.schema},enumerable:!1,configurable:!0}),e.prototype.has=function(e){return null!=this.find(e)},e.prototype.find=function(){for(var e=this,t=[],s=0;s<arguments.length;s++)t[s]=arguments[s];return t.reduce((function(t,s){return t||e.findTarget(s)||e.findLegacyTarget(s)}),void 0)},e.prototype.findAll=function(){for(var e=this,t=[],s=0;s<arguments.length;s++)t[s]=arguments[s];return t.reduce((function(t,s){return ee(t,e.findAllTargets(s),e.findAllLegacyTargets(s))}),[])},e.prototype.findTarget=function(e){var t=this.getSelectorForTargetName(e);return this.scope.findElement(t)},e.prototype.findAllTargets=function(e){var t=this.getSelectorForTargetName(e);return this.scope.findAllElements(t)},e.prototype.getSelectorForTargetName=function(e){return Q("data-"+this.identifier+"-target",e)},e.prototype.findLegacyTarget=function(e){var t=this.getLegacySelectorForTargetName(e);return this.deprecate(this.scope.findElement(t),e)},e.prototype.findAllLegacyTargets=function(e){var t=this,s=this.getLegacySelectorForTargetName(e);return this.scope.findAllElements(s).map((function(s){return t.deprecate(s,e)}))},e.prototype.getLegacySelectorForTargetName=function(e){var t=this.identifier+"."+e;return Q(this.schema.targetAttribute,t)},e.prototype.deprecate=function(e,t){if(e){var s=this.identifier,i=this.schema.targetAttribute;this.guide.warn(e,"target:"+t,"Please replace "+i+'="'+s+"."+t+'" with data-'+s+'-target="'+t+'". The '+i+" attribute is deprecated and will be removed in a future version of Stimulus.")}return e},Object.defineProperty(e.prototype,"guide",{get:function(){return this.scope.guide},enumerable:!1,configurable:!0}),e}(),se=function(){function e(e,t,s,i){var r=this;this.targets=new te(this),this.classes=new W(this),this.data=new X(this),this.containsElement=function(e){return e.closest(r.controllerSelector)===r.element},this.schema=e,this.element=t,this.identifier=s,this.guide=new G(i)}return e.prototype.findElement=function(e){return this.element.matches(e)?this.element:this.queryElements(e).find(this.containsElement)},e.prototype.findAllElements=function(e){return function(){for(var e=0,t=0,s=arguments.length;t<s;t++)e+=arguments[t].length;var i=Array(e),r=0;for(t=0;t<s;t++)for(var n=arguments[t],o=0,a=n.length;o<a;o++,r++)i[r]=n[o];return i}(this.element.matches(e)?[this.element]:[],this.queryElements(e).filter(this.containsElement))},e.prototype.queryElements=function(e){return Array.from(this.element.querySelectorAll(e))},Object.defineProperty(e.prototype,"controllerSelector",{get:function(){return Q(this.schema.controllerAttribute,this.identifier)},enumerable:!1,configurable:!0}),e}(),ie=function(){function e(e,t,s){this.element=e,this.schema=t,this.delegate=s,this.valueListObserver=new I(this.element,this.controllerAttribute,this),this.scopesByIdentifierByElement=new WeakMap,this.scopeReferenceCounts=new WeakMap}return e.prototype.start=function(){this.valueListObserver.start()},e.prototype.stop=function(){this.valueListObserver.stop()},Object.defineProperty(e.prototype,"controllerAttribute",{get:function(){return this.schema.controllerAttribute},enumerable:!1,configurable:!0}),e.prototype.parseValueForToken=function(e){var t=e.element,s=e.content,i=this.fetchScopesByIdentifierForElement(t),r=i.get(s);return r||(r=this.delegate.createScopeForElementAndIdentifier(t,s),i.set(s,r)),r},e.prototype.elementMatchedValue=function(e,t){var s=(this.scopeReferenceCounts.get(t)||0)+1;this.scopeReferenceCounts.set(t,s),1==s&&this.delegate.scopeConnected(t)},e.prototype.elementUnmatchedValue=function(e,t){var s=this.scopeReferenceCounts.get(t);s&&(this.scopeReferenceCounts.set(t,s-1),1==s&&this.delegate.scopeDisconnected(t))},e.prototype.fetchScopesByIdentifierForElement=function(e){var t=this.scopesByIdentifierByElement.get(e);return t||(t=new Map,this.scopesByIdentifierByElement.set(e,t)),t},e}(),re=function(){function e(e){this.application=e,this.scopeObserver=new ie(this.element,this.schema,this),this.scopesByIdentifier=new L,this.modulesByIdentifier=new Map}return Object.defineProperty(e.prototype,"element",{get:function(){return this.application.element},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"schema",{get:function(){return this.application.schema},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"logger",{get:function(){return this.application.logger},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"controllerAttribute",{get:function(){return this.schema.controllerAttribute},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"modules",{get:function(){return Array.from(this.modulesByIdentifier.values())},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"contexts",{get:function(){return this.modules.reduce((function(e,t){return e.concat(t.contexts)}),[])},enumerable:!1,configurable:!0}),e.prototype.start=function(){this.scopeObserver.start()},e.prototype.stop=function(){this.scopeObserver.stop()},e.prototype.loadDefinition=function(e){this.unloadIdentifier(e.identifier);var t=new K(this.application,e);this.connectModule(t)},e.prototype.unloadIdentifier=function(e){var t=this.modulesByIdentifier.get(e);t&&this.disconnectModule(t)},e.prototype.getContextForElementAndIdentifier=function(e,t){var s=this.modulesByIdentifier.get(t);if(s)return s.contexts.find((function(t){return t.element==e}))},e.prototype.handleError=function(e,t,s){this.application.handleError(e,t,s)},e.prototype.createScopeForElementAndIdentifier=function(e,t){return new se(this.schema,e,t,this.logger)},e.prototype.scopeConnected=function(e){this.scopesByIdentifier.add(e.identifier,e);var t=this.modulesByIdentifier.get(e.identifier);t&&t.connectContextForScope(e)},e.prototype.scopeDisconnected=function(e){this.scopesByIdentifier.delete(e.identifier,e);var t=this.modulesByIdentifier.get(e.identifier);t&&t.disconnectContextForScope(e)},e.prototype.connectModule=function(e){this.modulesByIdentifier.set(e.identifier,e),this.scopesByIdentifier.getValuesForKey(e.identifier).forEach((function(t){return e.connectContextForScope(t)}))},e.prototype.disconnectModule=function(e){this.modulesByIdentifier.delete(e.identifier),this.scopesByIdentifier.getValuesForKey(e.identifier).forEach((function(t){return e.disconnectContextForScope(t)}))},e}(),ne={controllerAttribute:"data-controller",actionAttribute:"data-action",targetAttribute:"data-target"},oe=function(e,t,s,i){return new(s||(s=Promise))((function(r,n){function o(e){try{l(i.next(e))}catch(t){n(t)}}function a(e){try{l(i.throw(e))}catch(t){n(t)}}function l(e){var t;e.done?r(e.value):(t=e.value,t instanceof s?t:new s((function(e){e(t)}))).then(o,a)}l((i=i.apply(e,t||[])).next())}))},ae=function(e,t){var s,i,r,n,o={label:0,sent:function(){if(1&r[0])throw r[1];return r[1]},trys:[],ops:[]};return n={next:a(0),throw:a(1),return:a(2)},"function"==typeof Symbol&&(n[Symbol.iterator]=function(){return this}),n;function a(n){return function(a){return function(n){if(s)throw new TypeError("Generator is already executing.");for(;o;)try{if(s=1,i&&(r=2&n[0]?i.return:n[0]?i.throw||((r=i.return)&&r.call(i),0):i.next)&&!(r=r.call(i,n[1])).done)return r;switch(i=0,r&&(n=[2&n[0],r.value]),n[0]){case 0:case 1:r=n;break;case 4:return o.label++,{value:n[1],done:!1};case 5:o.label++,i=n[1],n=[0];continue;case 7:n=o.ops.pop(),o.trys.pop();continue;default:if(!(r=o.trys,(r=r.length>0&&r[r.length-1])||6!==n[0]&&2!==n[0])){o=0;continue}if(3===n[0]&&(!r||n[1]>r[0]&&n[1]<r[3])){o.label=n[1];break}if(6===n[0]&&o.label<r[1]){o.label=r[1],r=n;break}if(r&&o.label<r[2]){o.label=r[2],o.ops.push(n);break}r[2]&&o.ops.pop(),o.trys.pop();continue}n=t.call(e,o)}catch(a){n=[6,a],i=0}finally{s=r=0}if(5&n[0])throw n[1];return{value:n[0]?n[1]:void 0,done:!0}}([n,a])}}},le=function(){for(var e=0,t=0,s=arguments.length;t<s;t++)e+=arguments[t].length;var i=Array(e),r=0;for(t=0;t<s;t++)for(var n=arguments[t],o=0,a=n.length;o<a;o++,r++)i[r]=n[o];return i};function ce(e){return F(e,"classes").reduce((function(e,t){return Object.assign(e,((i={})[r=(s=t)+"Class"]={get:function(){var e=this.classes;if(e.has(s))return e.get(s);var t=e.getAttributeName(s);throw new Error('Missing attribute "'+t+'"')}},i["has"+Y(r)]={get:function(){return this.classes.has(s)}},i));var s,i,r}),{})}function he(e){return F(e,"targets").reduce((function(e,t){return Object.assign(e,((i={})[(s=t)+"Target"]={get:function(){var e=this.targets.find(s);if(e)return e;throw new Error('Missing target element "'+this.identifier+"."+s+'"')}},i[s+"Targets"]={get:function(){return this.targets.findAll(s)}},i["has"+Y(s)+"Target"]={get:function(){return this.targets.has(s)}},i));var s,i}),{})}function ue(e){var t=H(e,"values"),s={valueDescriptorMap:{get:function(){var e=this;return t.reduce((function(t,s){var i,r=de(s),n=e.data.getAttributeNameForKey(r.key);return Object.assign(t,((i={})[n]=r,i))}),{})}}};return t.reduce((function(e,t){return Object.assign(e,function(e){var t,s=de(e),i=s.type,r=s.key,n=s.name,o=fe[i],a=me[i]||me.default;return(t={})[n]={get:function(){var e=this.data.get(r);return null!==e?o(e):s.defaultValue},set:function(e){void 0===e?this.data.delete(r):this.data.set(r,a(e))}},t["has"+Y(n)]={get:function(){return this.data.has(r)}},t}(t))}),s)}function de(e){return function(e,t){var s=Z(e)+"-value";return{type:t,key:s,name:J(s),get defaultValue(){return pe[t]}}}(e[0],function(e){switch(e){case Array:return"array";case Boolean:return"boolean";case Number:return"number";case Object:return"object";case String:return"string"}throw new Error('Unknown value type constant "'+e+'"')}(e[1]))}!function(){function e(e,t){void 0===e&&(e=document.documentElement),void 0===t&&(t=ne),this.logger=console,this.element=e,this.schema=t,this.dispatcher=new b(this),this.router=new re(this)}e.start=function(t,s){var i=new e(t,s);return i.start(),i},e.prototype.start=function(){return oe(this,void 0,void 0,(function(){return ae(this,(function(e){switch(e.label){case 0:return[4,new Promise((function(e){"loading"==document.readyState?document.addEventListener("DOMContentLoaded",e):e()}))];case 1:return e.sent(),this.dispatcher.start(),this.router.start(),[2]}}))}))},e.prototype.stop=function(){this.dispatcher.stop(),this.router.stop()},e.prototype.register=function(e,t){this.load({identifier:e,controllerConstructor:t})},e.prototype.load=function(e){for(var t=this,s=[],i=1;i<arguments.length;i++)s[i-1]=arguments[i];var r=Array.isArray(e)?e:le([e],s);r.forEach((function(e){return t.router.loadDefinition(e)}))},e.prototype.unload=function(e){for(var t=this,s=[],i=1;i<arguments.length;i++)s[i-1]=arguments[i];var r=Array.isArray(e)?e:le([e],s);r.forEach((function(e){return t.router.unloadIdentifier(e)}))},Object.defineProperty(e.prototype,"controllers",{get:function(){return this.router.contexts.map((function(e){return e.controller}))},enumerable:!1,configurable:!0}),e.prototype.getControllerForElementAndIdentifier=function(e,t){var s=this.router.getContextForElementAndIdentifier(e,t);return s?s.controller:null},e.prototype.handleError=function(e,t,s){this.logger.error("%s\n\n%o\n\n%o",t,e,s)}}();var pe={get array(){return[]},boolean:!1,number:0,get object(){return{}},string:""},fe={array:function(e){var t=JSON.parse(e);if(!Array.isArray(t))throw new TypeError("Expected array");return t},boolean:function(e){return!("0"==e||"false"==e)},number:function(e){return parseFloat(e)},object:function(e){var t=JSON.parse(e);if(null===t||"object"!=typeof t||Array.isArray(t))throw new TypeError("Expected object");return t},string:function(e){return e}},me={default:function(e){return""+e},array:ge,object:ge};function ge(e){return JSON.stringify(e)}var ve=function(){function e(e){this.context=e}return Object.defineProperty(e.prototype,"application",{get:function(){return this.context.application},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"scope",{get:function(){return this.context.scope},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"element",{get:function(){return this.scope.element},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"identifier",{get:function(){return this.scope.identifier},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"targets",{get:function(){return this.scope.targets},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"classes",{get:function(){return this.scope.classes},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"data",{get:function(){return this.scope.data},enumerable:!1,configurable:!0}),e.prototype.initialize=function(){},e.prototype.connect=function(){},e.prototype.disconnect=function(){},e.blessings=[ce,he,ue],e.targets=[],e.values={},e}();class be extends ve{constructor(e){return super(e),this.application.debug?new Proxy(this,{get:(e,t)=>{let s=Reflect.get(e,t),i=this;if(function(e){switch(e){case"application":case"el":case"element":case"constructor":case"initialize":case"log":case"logEvent":case"dispatch":case"data":case"valueDescriptorMap":case"mutate":case"identifier":return!1}if(/^_.*?$/.test(e))return!1;if(/^.*?Target(s)?$/.test(e))return!1;if(/^.*?Value$/.test(e))return!1;if(/^.*?ValueChanged$/.test(e))return!1;if(/^.*?Class$/.test(e))return!1;if(/^.*?Classes$/.test(e))return!1;return!0}(t.toString())){if("function"==typeof s)return new Proxy(s,{apply:(e,s,r)=>(i.log(t.toString(),{args:r}),Reflect.apply(e,s,r))});this.log(t.toString())}return s}}):this}get el(){return this.element}get isTurboPreview(){return document.documentElement.hasAttribute("data-turbo-preview")||document.documentElement.hasAttribute("data-turbolinks-preview")}get isTurbolinksPreview(){return this.isTurboPreview}get csrfToken(){return this.metaValue("csrf-token")}metaValue(e){const t=document.head.querySelector(`meta[name="${e}"]`);return(null==t?void 0:t.getAttribute("content"))||null}dispatch(e,t,s={}){let i=Object.assign({},{bubbles:!0,cancelable:!0,detail:{target:e}},s);i.detail.target&&(i.detail.target=e);let r=new CustomEvent(t,i);this.logEvent(t,r,e),e.dispatchEvent(r)}log(e,t={}){if(!this.application.debug)return;let s=console;s.groupCollapsed(`%c${this.identifier} %c#${e}`,"color: #3B82F6","color: unset"),s.log(n({element:this.element,controller:this},t)),s.groupEnd()}warn(e,t={}){if(!this.application.debug)return;let s=console;s.groupCollapsed(`%c${this.identifier} %c#${e}`,"color: F39B1AFF","color: unset"),s.warn(n({element:this.element,controller:this},t)),s.groupEnd()}logEvent(e,t,s){if(!this.application.debug)return;let i=console;i.groupCollapsed(`%c${this.identifier} %c${e}%c`,"color: #3B82F6","color: #0be000","color: unset"),i.log({element:s}),i.groupEnd()}}var ye={exports:{}};const _e=(e,t)=>{if("string"!=typeof e&&!Array.isArray(e))throw new TypeError("Expected the input to be `string | string[]`");if(t=n({pascalCase:!1,preserveConsecutiveUppercase:!1},t),0===(e=Array.isArray(e)?e.map((e=>e.trim())).filter((e=>e.length)).join("-"):e.trim()).length)return"";if(1===e.length)return t.pascalCase?e.toLocaleUpperCase(t.locale):e.toLocaleLowerCase(t.locale);return e!==e.toLocaleLowerCase(t.locale)&&(e=((e,t)=>{let s=!1,i=!1,r=!1;for(let n=0;n<e.length;n++){const o=e[n];s&&/[\p{Lu}]/u.test(o)?(e=e.slice(0,n)+"-"+e.slice(n),s=!1,r=i,i=!0,n++):i&&r&&/[\p{Ll}]/u.test(o)?(e=e.slice(0,n-1)+"-"+e.slice(n-1),r=i,i=!1,s=!0):(s=o.toLocaleLowerCase(t)===o&&o.toLocaleUpperCase(t)!==o,r=i,i=o.toLocaleUpperCase(t)===o&&o.toLocaleLowerCase(t)!==o)}return e})(e,t.locale)),e=e.replace(/^[_.\- ]+/,""),e=t.preserveConsecutiveUppercase?(e=>e.replace(/^[\p{Lu}](?![\p{Lu}])/gu,(e=>e.toLowerCase())))(e):e.toLocaleLowerCase(),t.pascalCase&&(e=e.charAt(0).toLocaleUpperCase(t.locale)+e.slice(1)),((e,t)=>e.replace(/[_.\- ]+([\p{Alpha}\p{N}_]|$)/gu,((e,s)=>s.toLocaleUpperCase(t.locale))).replace(/\d+([\p{Alpha}\p{N}_]|$)/gu,(e=>e.toLocaleUpperCase(t.locale))))(e,t)};ye.exports=_e,ye.exports.default=_e;var we=ye.exports;class Ee extends be{_cleanupSelf(){this.cleanup(this.el)}cleanup(e){var t,s,i;e.dataset.controller=(null==(t=e.dataset.controller)?void 0:t.replaceAll(new RegExp(`(s|^)${this.identifier}(s|$)`,"g"),""))||"",""==e.dataset.controller&&delete e.dataset.controller;let r=new RegExp(`(s|^)${this.identifier}\\..+?(s|$)`,"g");e.dataset.target=(null==(s=e.dataset.target)?void 0:s.replaceAll(r,""))||"",delete e.dataset[we(`${this.identifier}-target`)],""==e.dataset.target&&delete e.dataset.target,e.dataset.action=(null==(i=e.dataset.target)?void 0:i.replaceAll(r,""))||"",delete e.dataset[we(`${this.identifier}-action`)],""==e.dataset.action&&delete e.dataset.action;let n=this.constructor.values;n&&Object.keys(n).forEach((t=>delete e.dataset[we(`${this.identifier}-${t}-value`)]));let o=this.constructor.classes;o&&Object.keys(o).forEach((t=>delete e.dataset[we(`${this.identifier}-${t}-class`)]))}}const Ce="scrollBehavior"in document.documentElement.style;let Te;async function ke(e,{behavior:t="smooth",block:s="start",inline:i="nearest"}={}){"smooth"!=t||Ce||await De(),e.scrollIntoView({behavior:t,block:s,inline:i})}async function Ve(e,{behavior:t="smooth"}={}){"smooth"!=t||Ce||await De(),e.scrollTo({top:0,left:0,behavior:t})}async function Ae(e,{behavior:t="smooth"}={}){"smooth"!=t||Ce||await De(),e==window?e.scrollTo({top:document.body.scrollHeight,left:0,behavior:t}):e.scrollTo({top:e.scrollHeight,left:0,behavior:t})}async function Se(e,{behavior:t="smooth"}={}){"smooth"!=t||Ce||await De(),e.scrollTo({left:0,behavior:t})}async function xe(e,{behavior:t="smooth"}={}){"smooth"!=t||Ce||await De(),e==window?e.scrollTo({left:document.body.scrollWidth,behavior:t}):e.scrollTo({left:e.scrollWidth,behavior:t})}async function Oe(e,t,{behavior:s="smooth"}={}){"smooth"!=s||Ce||await De(),e.scrollBy({top:-t,left:0,behavior:s})}async function Me(e,t,{behavior:s="smooth"}={}){"smooth"!=s||Ce||await De(),e.scrollBy({top:t,left:0,behavior:s})}async function Le(e,t,{behavior:s="smooth"}={}){"smooth"!=s||Ce||await De(),e.scrollBy({top:0,left:-t,behavior:s})}async function Ne(e,t,{behavior:s="smooth"}={}){"smooth"!=s||Ce||await De(),e.scrollBy({top:0,left:t,behavior:s})}async function De(){const{polyfill:e}=await import("smoothscroll-polyfill");Te||(Te=!0,e())}function Ie(e){if(!e)return null;if(e==document.body)return window;const t=getComputedStyle(e).overflowY;return"visible"!==t&&"hidden"!==t&&e.scrollHeight>=e.clientHeight?e:Ie(e.parentElement)||document.body}function Pe(e){return"TURBO-FRAME"==e.nodeName}const je={all:Be=Be||new Map,on:function(e,t){var s=Be.get(e);s?s.push(t):Be.set(e,[t])},off:function(e,t){var s=Be.get(e);s&&(t?s.splice(s.indexOf(t)>>>0,1):Be.set(e,[]))},emit:function(e,t){var s=Be.get(e);s&&s.slice().map((function(e){e(t)})),(s=Be.get("*"))&&s.slice().map((function(s){s(e,t)}))}};var Be;function Fe(e){return"A"==e.nodeName}function He(e){return"FORM"==e.nodeName}function Re(e){return"INPUT"==e.nodeName}function $e(e){return"TEXTAREA"==e.nodeName}function qe(e){return"BUTTON"==e.nodeName}function Ue(e){return"SELECT"==e.nodeName}function ze(e){return Re(e)&&("radio"===e.type||"checkbox"===e.type)}function Ke(e){let t=document.createElement("button");return t.type=e,t.style.display="none",t.dataset.sythentic="true",t}function We(e,t){let s=document.createElement("input");return s.type="hidden",s.name=e,s.value=t,s}function Je(e,t,s){let i=e.insertAdjacentElement(t,s);if(!i)throw new Error(`Failed to insert element ${s.nodeName} into ${e.nodeName}`);return i}function Ye(e,t,s,i){return Je(s,i,We(e,t))}function Ze(e,t,s){return Je(t,s,Ke(e))}function Xe(e){if(e.requestSubmit)e.requestSubmit();else{let t=e.querySelector('button[type="submit"]');t||(t=Ze("submit",e,"beforeend")),t.click()}}function Ge(e){let t=e.querySelector('button[type="reset"]');t||(t=Ze("reset",e,"beforeend")),t.click()}function Qe(e,t,s,i,r){return et(e,t,[s],i,r)}function et(e,t,s,i,r){const n=e.disconnect.bind(e);let o=r;(null==o?void 0:o.debounce)?(i=a(i.bind(e),o.debounce),delete o.debounce):i=i.bind(e);let l=()=>s.forEach((e=>t.addEventListener(e,i,o))),c=()=>s.forEach((e=>t.removeEventListener(e,i)));return l(),Object.assign(e,{disconnect(){c(),n()}}),[l,c]}function tt(e,t,s){const i=e.disconnect.bind(e);t=t.bind(e);let r=null,n=()=>{null!==r&&clearInterval(r)};return r=setInterval(t,s),Object.assign(e,{disconnect(){n(),i()}}),n}function st(e,t,s){const i=e.disconnect.bind(e);t=t.bind(e);let r=null,n=()=>{null!==r&&clearTimeout(r)};return r=setTimeout(t,s),Object.assign(e,{disconnect(){n(),i()}}),n}function it(e,t,s,i,r={}){const n=e.disconnect.bind(e);let o,a=Array.from(i.childNodes);return o=r.cleanup?()=>{console.log("teardown"),a.forEach((e=>e.remove()))}:()=>console.log("void teardown"),(()=>{let e=t.parentElement;if(["beforebegin","afterend"].includes(s)&&null==e)throw new Error("Cannot insert beforebegin into a node with no parent");switch(s){case"beforeend":t.append(i);break;case"afterbegin":t.prepend(i);break;case"beforebegin":case"afterend":e.insertBefore(i,t)}})(),Object.assign(e,{disconnect(){o(),n()}}),[a,o]}function rt(e,t,s,i,r={}){return it(e,t,s,document.createRange().createContextualFragment(i),r)}function nt(e,t,s,i,r={}){const n=new DocumentFragment;n.append(i);let[o,a]=it(e,t,s,n,r);return[o[0],a]}class ot extends be{get _key(){return this.keyValue.replaceAll("#","")}get _anchor(){return window.location.hash.substr(1)}set _anchor(e){window.location.hash=e}connect(){requestAnimationFrame((()=>{this._checkAnchor(),Qe(this,window,"hashchange",this._checkAnchor)}))}write(e){null==e||e.preventDefault(),this._anchor=this._key}_checkAnchor(){this._key===this._anchor?this.dispatch(this.el,"anchor-spy:active"):this.dispatch(this.el,"anchor-spy:inactive")}}o(ot,"values",{key:String});class at extends be{get _errorMessage(){return this.hasErrorMessageValue?this.errorMessageValue:"This content failed to load"}connect(){}async loadContent(e=null){null==e||e.preventDefault();let t=this,s=this.hasReplaceTarget?this.replaceTarget:this.el,i=()=>{s.replaceWith(this._errorMessage),t.dispatch(s,"ajax:error")};try{let e=await fetch(this.endpointValue);e.ok||i();let r=await e.text(),n=document.createElement("div");if(n.innerHTML=r,this.hasSelectorValue){let e=n.querySelectorAll(this.selectorValue);s.replaceWith(...e)}else s.replaceWith(...n.children);t.dispatch(s,"ajax:success")}catch(r){i()}finally{t.dispatch(s,"ajax:complete")}}}o(at,"targets",["replace"]),o(at,"values",{endpoint:String,errorMessage:String,selector:String});class lt extends at{get _errorMessage(){return this.hasErrorMessageValue?this.errorMessageValue:"This content failed to load"}async connect(){await this.loadContent()}}o(lt,"targets",["replace"]),o(lt,"values",{endpoint:String,errorMessage:String,selector:String});class ct extends be{get _eventMode(){if(this.hasEventModeValue){if(!["change","input","debounced"].includes(this.eventModeValue))throw new Error(`The modeValue provided '${this.eventModeValue}' is not one of the recognised configuration options`);return this.eventModeValue}return"change"}get _debounceTimeout(){return this.hasDebounceIntervalValue?this.debounceIntervalValue:1e3}get _mode(){if(this.hasSubmitModeValue){if(!["direct","request"].includes(this.submitModeValue))throw new Error(`The modeValue provided '${this.submitModeValue}' is not one of the recognised configuration options`);return this.submitModeValue}return"request"}get _cssSelector(){return["input","textarea","select"].map((e=>e.concat(":not([data-no-autosubmit])"))).join(",")}get inputElements(){return this.element.querySelectorAll(this._cssSelector)}connect(){this.inputElements.forEach((e=>Qe(this,e,"change"==this._eventMode?"change":"input",this.submit,{debounce:"debounced"==this._eventMode?this._debounceTimeout:void 0})))}submit(){let e=this.el;"request"==this._mode?Xe(e):e.submit()}}o(ct,"values",{submitMode:String,eventMode:String,debounceInterval:Number});const ht=(e,t)=>{const s=e[t];return"function"==typeof s?s:(...e)=>{}},ut=(e,t,s)=>{let i=e;return!0===s?i=`${t.identifier}:${e}`:"string"==typeof s&&(i=`${s}:${e}`),i},dt=(e,t,s)=>{const{bubbles:i,cancelable:r,composed:n}=t||{bubbles:!0,cancelable:!0,composed:!0};t&&Object.assign(s,{originalEvent:t});return new CustomEvent(e,{bubbles:i,cancelable:r,composed:n,detail:s})};const pt={dispatchEvent:!0,eventPrefix:!0},ft=(e,t={})=>{const{dispatchEvent:s,eventPrefix:i}=Object.assign({},pt,t),r=(null==t?void 0:t.element)||e.element,n=t=>{if(e.isVisible=!0,ht(e,"appear").call(e,t),s){const s=ut("appear",e,i),n=dt(s,null,{controller:e,entry:t});r.dispatchEvent(n)}},o=t=>{if(e.isVisible=!1,ht(e,"disappear").call(e,t),s){const s=ut("disappear",e,i),n=dt(s,null,{controller:e,entry:t});r.dispatchEvent(n)}},a=e.disconnect.bind(e),l=new IntersectionObserver((t=>{const[s]=t;s.isIntersecting?n(s):e.isVisible&&o(s)}),t),c=()=>{l.observe(r)},h=()=>{l.unobserve(r)};return Object.assign(e,{isVisible:!1,disconnect(){h(),a()}}),c(),[c,h]},mt={events:["click","touchend"],onlyVisible:!0,dispatchEvent:!0,eventPrefix:!0},gt=(e,t={})=>{const{onlyVisible:s,dispatchEvent:i,events:r,eventPrefix:n}=Object.assign({},mt,t),o=r=>{const o=(null==t?void 0:t.element)||e.element;if(!(o.contains(r.target)||!function(e){const t=e.getBoundingClientRect(),s=window.innerHeight||document.documentElement.clientHeight,i=window.innerWidth||document.documentElement.clientWidth,r=t.top<=s&&t.top+t.height>=0,n=t.left<=i&&t.left+t.width>=0;return r&&n}(o)&&s)&&(e.clickOutside&&e.clickOutside(r),i)){const t=ut("click:outside",e,n),s=dt(t,r,{controller:e});o.dispatchEvent(s)}},a=()=>{null==r||r.forEach((e=>{window.addEventListener(e,o,!1)}))},l=()=>{null==r||r.forEach((e=>{window.removeEventListener(e,o,!1)}))},c=e.disconnect.bind(e);return Object.assign(e,{disconnect(){l(),c()}}),a(),[a,l]},vt={debug:!1,logger:console,dispatchEvent:!0,eventPrefix:!0};class bt{constructor(e,r={}){var o,a,l;this.log=(e,t)=>{this.debug&&(this.logger.groupCollapsed(`%c${this.controller.identifier} %c#${e}`,"color: #3B82F6","color: unset"),this.logger.log(n({controllerId:this.controllerId},t)),this.logger.groupEnd())},this.dispatch=(e,r={})=>{if(this.dispatchEvent){const o=r,{event:a}=o,l=((e,r)=>{var n={};for(var o in e)s.call(e,o)&&r.indexOf(o)<0&&(n[o]=e[o]);if(null!=e&&t)for(var o of t(e))r.indexOf(o)<0&&i.call(e,o)&&(n[o]=e[o]);return n})(o,["event"]),c=this.extendedEvent(e,a||null,l);this.targetElement.dispatchEvent(c),this.log("dispatchEvent",n({eventName:c.type},l))}},this.call=(e,t={})=>{const s=this.controller[e];if("function"==typeof s)return s.call(this.controller,t)},this.extendedEvent=(e,t,s)=>{const{bubbles:i,cancelable:r,composed:n}=t||{bubbles:!0,cancelable:!0,composed:!0};t&&Object.assign(s,{originalEvent:t});return new CustomEvent(this.composeEventName(e),{bubbles:i,cancelable:r,composed:n,detail:s})},this.composeEventName=e=>{let t=e;return!0===this.eventPrefix?t=`${this.controller.identifier}:${e}`:"string"==typeof this.eventPrefix&&(t=`${this.eventPrefix}:${e}`),t},this.debug=null!==(a=null!==(o=null==r?void 0:r.debug)&&void 0!==o?o:e.application.stimulusUseDebug)&&void 0!==a?a:vt.debug,this.logger=null!==(l=null==r?void 0:r.logger)&&void 0!==l?l:vt.logger,this.controller=e,this.controllerId=e.element.id||e.element.dataset.id,this.targetElement=(null==r?void 0:r.element)||e.element;const{dispatchEvent:c,eventPrefix:h}=Object.assign({},vt,r);Object.assign(this,{dispatchEvent:c,eventPrefix:h}),this.controllerInitialize=e.initialize.bind(e),this.controllerConnect=e.connect.bind(e),this.controllerDisconnect=e.disconnect.bind(e)}}class yt extends bt{constructor(e,t={}){super(e,t),this.observe=()=>{this.targetElement.addEventListener("mouseenter",this.onEnter),this.targetElement.addEventListener("mouseleave",this.onLeave)},this.unobserve=()=>{this.targetElement.removeEventListener("mouseenter",this.onEnter),this.targetElement.removeEventListener("mouseleave",this.onLeave)},this.onEnter=e=>{this.call("mouseEnter",e),this.log("mouseEnter",{hover:!0}),this.dispatch("mouseEnter",{hover:!1})},this.onLeave=e=>{this.call("mouseLeave",e),this.log("mouseLeave",{hover:!1}),this.dispatch("mouseLeave",{hover:!1})},this.controller=e,this.enhanceController(),this.observe()}enhanceController(){const e=this.controller.disconnect.bind(this.controller);Object.assign(this.controller,{disconnect:()=>{this.unobserve(),e()}})}}class _t extends bt{constructor(e,t={}){super(e,t),this.observe=()=>{try{this.observer.observe(this.targetElement,this.options)}catch(e){this.controller.application.handleError(e,"At a minimum, one of childList, attributes, and/or characterData must be true",{})}},this.unobserve=()=>{this.observer.disconnect()},this.mutation=e=>{this.call("mutate",e),this.log("mutate",{entries:e}),this.dispatch("mutate",{entries:e})},this.targetElement=(null==t?void 0:t.element)||e.element,this.controller=e,this.options=t,this.observer=new MutationObserver(this.mutation),this.enhanceController(),this.observe()}enhanceController(){const e=this.controller.disconnect.bind(this.controller);Object.assign(this.controller,{disconnect:()=>{this.unobserve(),e()}})}}const wt=(e,t={})=>{const s=new _t(e,t);return[s.observe,s.unobserve]},Et=e=>{const t=t=>{const{innerWidth:s,innerHeight:i}=window,r={height:i||1/0,width:s||1/0,event:t};ht(e,"windowResize").call(e,r)},s=e.disconnect.bind(e),i=()=>{window.addEventListener("resize",t),t()},r=()=>{window.removeEventListener("resize",t)};return Object.assign(e,{disconnect(){r(),s()}}),i(),[i,r]};(class extends ve{}).debounces=[];const Ct=(e,t=200)=>{let s=null;return function(){const i=arguments,r=this,n=()=>e.apply(r,i);s&&clearTimeout(s),s=setTimeout(n,t)}};class Tt extends be{connect(){Et(this);let[,e]=ft(this);if(this.unobserveIntersection=e,!$e(this.el))throw new Error(`Expected controller to be attached to a textarea, but was a '${this.el.tagName}'`);requestAnimationFrame((()=>{this.el.style.resize="none",this.el.style.boxSizing="border-box",this._handler(),et(this,window,["resize"],this._handler),et(this,this.el,["input","focus"],this._handler)}))}appear(e){this.autosize(this.el),this.unobserveIntersection()}_handler(){this.autosize(this.el)}autosize(e){let t=e.offsetHeight-e.clientHeight;e.style.height="auto",e.style.height=e.scrollHeight+t+"px"}}class kt extends be{get _pages(){return this.hasPagesValue?Math.abs(this.pagesValue):1}get _timeout(){return this.hasTimeoutValue?this.timeoutValue:1500}connect(){Qe(this,this.el,"click",this.goBack)}goBack(e){null==e||e.preventDefault(),history.go(-this._pages),this.el.href&&st(this,this.fallback,this._timeout)}fallback(){window.location.href=this.el.href}}o(kt,"values",{timeout:Number,pages:Number});class Vt extends be{get _errorClasses(){return this.errorClass.split(" ")}get _defaultErrorClasses(){return[]}connect(){requestAnimationFrame((()=>{Qe(this,this.inputTarget,"input",this._updateCharCount),this._updateCharCount()}))}_addErrorClasses(e=this.el){this.hasErrorClass?e.classList.add(...this._errorClasses):e.classList.add(...this._defaultErrorClasses)}_removeErrorClasses(e=this.el){this.hasErrorClass?e.classList.remove(...this._errorClasses):e.classList.remove(...this._defaultErrorClasses)}_updateCharCount(){let e=this.inputTarget.value.length;this.outputTarget.innerText=e.toString(),this.hasErrorClass&&(this._isValidCount(e)?this._removeErrorClasses(this.outputTarget):this._addErrorClasses(this.outputTarget))}_isValidCount(e){let t=0,s=99999;return this.hasMinValue&&(t=this.minValue),this.hasMaxValue&&(s=this.maxValue),e>=t&&e<=s}}o(Vt,"targets",["input","output"]),o(Vt,"values",{min:Number,max:Number}),o(Vt,"classes",["error"]);class At extends be{connect(){this.toggle()}toggle(){this.hasDisablerTarget&&this.disablerTarget.checked?this.disable():this.enable()}disable(){let e=this.hasClearValue&&this.clearValue;this.disableTargets.forEach(((t,s)=>{e&&(t.value=""),t.disabled=!0}))}enable(){this.disableTargets.forEach(((e,t)=>{e.disabled=!1}))}}o(At,"targets",["disabler","disable"]),o(At,"values",{clear:Boolean});class St extends be{connect(){this.toggle()}toggle(){this.hasEnablerTarget&&this.enablerTarget.checked?this.enable():this.disable()}disable(){let e=this.hasClearValue&&this.clearValue;this.enableTargets.forEach(((t,s)=>{e&&(t.value=""),t.disabled=!0}))}enable(){this.enableTargets.forEach(((e,t)=>{e.disabled=!1}))}}o(St,"targets",["enabler","enable"]),o(St,"values",{clear:Boolean});class xt extends be{get _checked(){return this.checkboxTargets.filter((e=>e.checked))}get _unchecked(){return this.checkboxTargets.filter((e=>!e.checked))}connect(){requestAnimationFrame((()=>{this.hasSelectAllTarget&&(Qe(this,this.selectAllTarget,"change",this._toggle),this.checkboxTargets.forEach((e=>Qe(this,e,"change",this._refresh))),this._refresh())}))}_toggle(e){e.preventDefault();let t=e.target;this.checkboxTargets.forEach((e=>e.checked=t.checked))}_refresh(){const e=this.checkboxTargets.length,t=this._checked.length;this.selectAllTarget.checked=t>0,this.selectAllTarget.indeterminate=t>0&&t<e}}o(xt,"targets",["selectAll","checkbox"]);class Ot extends be{constructor(){super(...arguments),o(this,"_supported",!1)}connect(){this._supported=document.queryCommandSupported("copy"),this.hasRemoveUnusedValue&&this.removeUnusedValue&&(this._supported&&this.hasFallbackTarget?this.fallbackTarget.remove():this.hasCopyTarget&&this.copyTarget.remove())}select(e){e&&e.preventDefault(),this.sourceTarget.select()}copy(e){e&&e.preventDefault(),this.sourceTarget.select(),this._supported&&document.execCommand("copy")}}o(Ot,"targets",["source","button","copy","fallback"]),o(Ot,"values",{removeUnused:Boolean});class Mt extends be{get _tickInterval(){return this.hasMillisecondsTarget?1:this.hasSecondsTarget?1e3:this.hasMinutesTarget?15e3:3e5}connect(){requestAnimationFrame((()=>{tt(this,this._tick,this._tickInterval)}))}_tick(){let e=new Date;this.hasHoursTarget&&(this.hoursTarget.innerHTML=e.getHours().toString().padStart(2,"0")),this.hasMinutesTarget&&(this.minutesTarget.innerHTML=e.getMinutes().toString().padStart(2,"0")),this.hasSecondsTarget&&(this.secondsTarget.innerHTML=e.getSeconds().toString().padStart(2,"0")),this.hasMillisecondsTarget&&(this.millisecondsTarget.innerHTML=e.getMilliseconds().toString().padStart(3,"0"))}}o(Mt,"targets",["hours","minutes","seconds","milliseconds"]);class Lt extends be{get _message(){return this.hasMessageValue?this.messageValue:"Are you sure?"}get _eventType(){if(He(this.el))return"submit";if(Fe(this.el))return"click";throw new Error("Can't handle confirmation on attached element")}connect(){requestAnimationFrame((()=>{Qe(this,this.el,this._eventType,this.confirm)}))}confirm(e){window.confirm(this._message)||(e.preventDefault(),this.dispatch(this.el,"confirm:cancelled"))}}o(Lt,"values",{message:String});class Nt extends be{get _message(){return this.hasMessageValue?this.messageValue:"Do you want to leave this page? Changes you made may not be saved"}initialize(){this.allowSubmit=this.allowSubmit.bind(this),this.confirmNavigation=this.confirmNavigation.bind(this),this.confirmTurboNavigation=this.confirmTurboNavigation.bind(this)}connect(){window.onbeforeunload=()=>this._message,Qe(this,window,"popstate",this.confirmNavigation),Qe(this,window,"submit",this.allowSubmit),et(this,window,["turbolinks:before-visit","turbo:before-visit"],this.confirmTurboNavigation)}disconnect(){window.onbeforeunload=null}allowSubmit(e){window.removeEventListener("popstate",this.confirmNavigation),window.onbeforeunload=null}confirmNavigation(e){return!1}confirmTurboNavigation(e){confirm(this._message)||e.preventDefault()}}o(Nt,"values",{message:String});class Dt extends be{constructor(){super(...arguments),o(this,"_interval",null)}get _removeUnused(){return!!this.hasRemoveUnusedValue&&this.removeUnusedValue}get _endedClasses(){return this.endedClass.split(" ")}get _defaultEndedClasses(){return[]}get _countingDownClasses(){return this.countingDownClass.split(" ")}get _defaultCountingDownClasses(){return[]}get _deadlineDate(){return new Date(this.deadlineValue)}connect(){this._interval=setInterval(this._tick.bind(this),1e3),this._addCountingDownClasses()}disconnect(){this._clearTick(),this._removeCountingDownClasses(),this._removeEndedClasses()}deadlineValueChanged(){null==this._interval&&(this._interval=setInterval(this._tick.bind(this),1e3))}_tick(){try{const e=new Date;let t={};d(this._deadlineDate)?(t={years:0,months:0,days:0,hours:0,minutes:0,seconds:0},this._clearTick(),this._removeCountingDownClasses(),this._addEndedClasses(),this.dispatch(this.el,"countdown:ended")):t=p({start:this._deadlineDate,end:e}),this.hasYearsTarget&&this._updateTarget(this.yearsTarget,this._years(t)),this.hasMonthsTarget&&this._updateTarget(this.monthsTarget,this._months(t)),this.hasDaysTarget&&this._updateTarget(this.daysTarget,this._days(t)),this.hasHoursTarget&&this._updateTarget(this.hoursTarget,this._hours(t)),this.hasMinutesTarget&&this._updateTarget(this.minutesTarget,this._minutes(t)),this.hasSecondsTarget&&this._updateTarget(this.secondsTarget,this._seconds(t))}catch(e){console.error(e),this._clearTick()}}_clearTick(){this._interval&&(clearInterval(this._interval),this._interval=null)}_updateTarget(e,t){this._removeTargetIfUnused(e,t),e.innerHTML=t.toString()}_removeTargetIfUnused(e,t){this._removeUnused&&(0===t&&e.dataset.unused?Number.parseInt(e.dataset.unused)>Date.now()+1500&&e.remove():e.dataset.unused=0==t?Date.now().toString():void 0)}_years(e){return e.years||0}_months(e){return e.months||0}_days(e){return e.days||0}_hours(e){return e.hours||0}_minutes(e){return e.minutes||0}_seconds(e){return e.seconds||0}_addEndedClasses(e=this.el){this.hasEndedClass?e.classList.add(...this._endedClasses):e.classList.add(...this._defaultEndedClasses)}_removeEndedClasses(e=this.el){this.hasEndedClass?e.classList.remove(...this._endedClasses):e.classList.remove(...this._defaultEndedClasses)}_addCountingDownClasses(e=this.el){this.hasCountingDownClass?e.classList.add(...this._countingDownClasses):e.classList.add(...this._defaultCountingDownClasses)}_removeCountingDownClasses(e=this.el){this.hasCountingDownClass?e.classList.remove(...this._countingDownClasses):e.classList.remove(...this._defaultCountingDownClasses)}}o(Dt,"values",{deadline:String,removeUnused:Boolean}),o(Dt,"targets",["years","months","days","hours","minutes","seconds"]),o(Dt,"classes",["countingDown","ended"]);class It extends be{connect(){console.log("Debug Controller",this,this.testTargets)}}o(It,"targets",["test"]);class Pt extends be{get _cacheAttrName(){return"detect-dirty-load-value"}connect(){let e=this.el;this._cacheLoadValues(),this._checkDirty(),et(this,e,["input","change"],this._checkDirty)}restore(e){null==e||e.preventDefault(),this._restoreElementFromLoadValue()}_getElementValue(){let e=this.el;return ze(e)?e.checked:e.value}_getElementLoadValue(){let e=this.el,t=e.getAttribute(this._cacheAttrName);if(ze(e))return null==t?e.defaultChecked:"true"==t;if(null!==t)return t;if(Ue(e)){Array.from(e.options).forEach((t=>{if(t.defaultSelected)return e.value=t.value,t.value}))}return t}_elementHasCachedLoadValue(){return this.el.hasAttribute(this._cacheAttrName)}_checkDirty(){let e=this.el;this._isElementDirty()?e.setAttribute("data-dirty","true"):e.removeAttribute("data-dirty")}_isElementDirty(){return this._getElementValue()!==this._getElementLoadValue()}_restoreElementFromLoadValue(){let e=this.el,t=e.getAttribute(this._cacheAttrName);if(ze(e))e.setAttribute(this._cacheAttrName,e.checked.toString()),e.checked=null==t?e.defaultChecked:"true"==t;else if(Ue(e))if(null==t){Array.from(e.options).forEach((t=>{t.defaultSelected&&(e.value=t.value)}))}else e.value=t;else e.value=null==t?e.defaultValue:t}_cacheLoadValues(){let e=this.el;!this._elementHasCachedLoadValue()&&ze(e)?e.setAttribute(this._cacheAttrName,e.checked.toString()):e.setAttribute(this._cacheAttrName,e.value.toString())}}function jt(e){return e.hasAttribute("data-dirty")}class Bt extends be{get _formElements(){return Array.from(this.el.querySelectorAll("input, select, textarea"))}get _cacheAttrName(){return"detect-dirty-load-value"}connect(){let e=this.el;this._cacheLoadValues(),this._checkDirty(),et(this,e,["input","change"],this._checkDirty)}restore(e){null==e||e.preventDefault(),this._formElements.forEach((e=>this._restoreElementFromLoadValue(e)))}_getElementValue(e){return ze(e)?e.checked:e.value}_getElementLoadValue(e){let t=e.getAttribute(this._cacheAttrName);if(ze(e))return null==t?e.defaultChecked:"true"==t;if(null!==t)return t;if(Ue(e)){Array.from(e.options).forEach((t=>{if(t.defaultSelected)return e.value=t.value,t.value}))}return t}_elementHasCachedLoadValue(e){return e.hasAttribute(this._cacheAttrName)}_checkElementDirty(e){this._isElementDirty(e)?e.setAttribute("data-dirty","true"):e.removeAttribute("data-dirty")}_isElementDirty(e){return this._getElementValue(e)!==this._getElementLoadValue(e)}_cacheElementLoadValue(e){!this._elementHasCachedLoadValue(e)&&ze(e)?e.setAttribute(this._cacheAttrName,e.checked.toString()):e.setAttribute(this._cacheAttrName,e.value.toString())}_restoreElementFromLoadValue(e){let t=e.getAttribute(this._cacheAttrName);if(ze(e))e.setAttribute(this._cacheAttrName,e.checked.toString()),e.checked=null==t?e.defaultChecked:"true"==t;else if(Ue(e))if(null==t){Array.from(e.options).forEach((t=>{t.defaultSelected&&(e.value=t.value)}))}else e.value=t;else e.value=null==t?e.defaultValue:t}_cacheLoadValues(){this._formElements.forEach((e=>this._cacheElementLoadValue(e)))}_checkDirty(){this._formElements.forEach((e=>this._checkElementDirty(e))),this._formElements.some((e=>Ft(e)))?this.el.setAttribute("data-dirty","true"):this.el.removeAttribute("data-dirty")}}function Ft(e){return e.hasAttribute("data-dirty")}class Ht extends be{constructor(){super(...arguments),o(this,"_cacheText")}get _message(){return this.hasMessageValue?this.messageValue:"Submitting..."}get _timeout(){return this.hasTimeoutValue?this.timeoutValue:1e3}initialize(){}connect(){requestAnimationFrame((()=>{et(this,this.el,["click"],this.disable),et(this,window,["turbo:load","turbolinks:load"],this._enable)}))}disable(e){let t=this.el;this._isDisabled(t)?(null==e||e.preventDefault(),null==e||e.stopImmediatePropagation()):(this._cacheText=this._getElText(t),this._setElText(t,this._message),this._disable(),st(this,this.enable,this._timeout))}enable(e){null==e||e.preventDefault();let t=this.el;this._isDisabled(t)&&(this._setElText(t,this._cacheText),this._enable())}_isDisabled(e){return Re(e)&&"submit"==e.type||qe(e)?e.disabled:"true"==e.dataset.disabled}_getElText(e){return Re(e)&&"submit"==e.type?e.value:e.innerText}_setElText(e,t){Re(e)&&"submit"==e.type?e.value=t:(qe(e)||Fe(e))&&(e.innerText=t)}_disable(){let e=this.el;Re(e)&&"submit"==e.type||qe(e)?e.disabled=!0:e.dataset.disabled="true"}_enable(){let e=this.el;Re(e)&&"submit"==e.type||qe(e)?e.disabled=!1:e.dataset.disabled=void 0}}o(Ht,"values",{message:String,timeout:Number});class Rt extends be{dismiss(){this.el.remove()}}class $t extends Rt{}class qt extends be{constructor(){super(...arguments),o(this,"_intervalHandle",null)}get _format(){return["years","months","weeks","days","hours",...this._minutes?["minutes"]:[],...this._seconds?["seconds"]:[]]}get _output(){let{years:e,months:t,weeks:s,days:i,hours:r,minutes:n,seconds:o}=this._duration;e||(e=0),t||(t=0),s||(s=0),i||(i=0),r||(r=0),n||(n=0),o||(o=0);let a=[e,t,s,i,r];return this._minutes||this._seconds||!a.every((e=>0===e))?f(this._duration,{format:this._format,delimiter:", "}):(n+=o/60,`${(n/60).toFixed(1)} hours`)}get _seconds(){return!this.hasSecondsValue||this.secondsValue}get _minutes(){return!this.hasMinutesValue||this.minutesValue}get _timestamp(){if(this.hasTimestampValue)return m(1e3*this.timestampValue);throw new Error("Expected `timestampValue` to be present")}get _duration(){return p({start:new Date,end:this._timestamp})}get _tickInterval(){return this._seconds?1e3:this._minutes?15e3:12e4}connect(){this._clearInterval=tt(this,this._update,this._tickInterval),this._update()}_update(){try{this.el.innerHTML=this._output}catch{this._intervalHandle&&window.clearInterval(this._intervalHandle)}}}o(qt,"values",{timestamp:Number,minutes:Boolean,seconds:Boolean});class Ut extends be{get _id(){if(this.hasIdValue)return this.idValue;let e=this.el.id;if(""!==e)return e;throw new Error(`No ID value to uniquely identify this element. Please either specify data-${this.identifier}-id-value or give this element an 'id' attribute. `)}get _uniqueIdentifier(){return`${location.href} ${this._id}`}get _restoreOnLoad(){return!this.hasRestoreOnLoadValue||this.restoreOnLoadValue}get _element(){return this.hasElementTarget?this.elementTarget:this.el}connect(){requestAnimationFrame((()=>{this._restoreOnLoad&&this.restore()}))}clear(e){e&&e.preventDefault(),localStorage.removeItem(this._uniqueIdentifier),this.dispatch(this._element,"element-save:cleared")}save(e){e&&e.preventDefault();let t=this._element,s=this.attributesValue.split(" "),i={};s.forEach((e=>i[e]=l(t,e))),localStorage.setItem(this._uniqueIdentifier,JSON.stringify(i)),this.dispatch(t,"element-save:save:success")}restore(e){e&&e.preventDefault();let t=this._element;if(localStorage.getItem(this._uniqueIdentifier)){const e=JSON.parse(localStorage.getItem(this._uniqueIdentifier));Object.keys(e).forEach((s=>{c(t,s,e[s])})),this.dispatch(t,"element-save:restore:success")}else this.dispatch(t,"element-save:restore:empty")}}o(Ut,"targets",["element"]),o(Ut,"values",{id:String,attributes:String,restoreOnLoad:Boolean});class zt extends be{get _container(){return this.hasContainerTarget?this.containerTarget:this.el}get _notEmptyClasses(){return this.notEmptyClass.split(" ")}get _defaultNotEmptyClasses(){return[]}get _emptyClasses(){return this.emptyClass.split(" ")}get _defaultEmptyClasses(){return[]}get _children(){let e=this._container;return this.hasScopeSelectorValue?Array.from(e.querySelectorAll(this.scopeSelectorValue)):Array.from(e.children)}connect(){wt(this,{element:this._container,childList:!0}),this.checkEmpty()}mutate(e){this.checkEmpty()}checkEmpty(){let e=this._container,t=this._children;0===t.length?(this._removeNotEmptyClasses(),this._addEmptyClasses(),this.dispatch(e,"dom:empty")):(this._addNotEmptyClasses(),this._removeEmptyClasses(),this.dispatch(e,"dom:not-empty",{detail:{count:t.length}}))}_addNotEmptyClasses(e=this.el){this.hasNotEmptyClass?e.classList.add(...this._notEmptyClasses):e.classList.add(...this._defaultNotEmptyClasses)}_removeNotEmptyClasses(e=this.el){this.hasNotEmptyClass?e.classList.remove(...this._notEmptyClasses):e.classList.remove(...this._defaultNotEmptyClasses)}_addEmptyClasses(e=this.el){this.hasEmptyClass?e.classList.add(...this._emptyClasses):e.classList.add(...this._defaultEmptyClasses)}_removeEmptyClasses(e=this.el){this.hasEmptyClass?e.classList.remove(...this._emptyClasses):e.classList.remove(...this._defaultEmptyClasses)}}o(zt,"targets",["container"]),o(zt,"classes",["empty","notEmpty"]),o(zt,"values",{scopeSelector:String});class Kt extends be{connect(){}disable(){let e=this.hasClearValue&&this.clearValue;this.inputTargets.forEach(((t,s)=>{e&&(t.value=""),t.disabled=!0}))}enable(){this.inputTargets.forEach(((e,t)=>e.disabled=!1))}}o(Kt,"targets",["input"]),o(Kt,"values",{clear:Boolean});class Wt extends be{get _successClasses(){return this.successClass.split(" ")}get _defaultSuccessClasses(){return[]}get _failClasses(){return this.failClass.split(" ")}get _defaultFailClasses(){return[]}initialize(){this._hasLoadedSuccessfully=this._hasLoadedSuccessfully.bind(this),this._success=this._success.bind(this),this._fail=this._fail.bind(this)}connect(){let e=this.el;e.onerror=this._fail,e.complete&&!this._hasLoadedSuccessfully()?this._fail():this._success()}disconnect(){this._removeSuccessClasses(),this._removeFailClasses()}_success(){this._addSuccessClasses()}_fail(){let e=this.el;this._addFailClasses(),this.hasPlaceholderValue&&e.src!==this.placeholderValue?(this.dispatch(e,"fallback-image:placeholder"),e.src=this.placeholderValue,e.onerror=this._fail):(this.dispatch(e,"fallback-image:fail"),e.style.display="none")}_hasLoadedSuccessfully(){let e=this.el;return e.naturalHeight>0&&e.naturalWidth>0}_addFailClasses(e=this.el){this.hasFailClass?e.classList.add(...this._failClasses):e.classList.add(...this._defaultFailClasses)}_removeFailClasses(e=this.el){this.hasFailClass?e.classList.remove(...this._failClasses):e.classList.remove(...this._defaultFailClasses)}_addSuccessClasses(e=this.el){this.hasSuccessClass?e.classList.add(...this._successClasses):e.classList.add(...this._defaultSuccessClasses)}_removeSuccessClasses(e=this.el){this.hasSuccessClass?e.classList.remove(...this._successClasses):e.classList.remove(...this._defaultSuccessClasses)}}o(Wt,"values",{placeholder:String}),o(Wt,"classes",["success","fail"]);class Jt extends be{get _mode(){const e=["immediate","wait"];if(this.hasModeValue){if(e.includes(this.modeValue))return this.modeValue;throw new Error(`The given modeValue '${this.modeValue}' is not one of the supported modes: "${e.join('", "')}"`)}return e[0]}connect(){"immediate"==this._mode&&this.steal()}steal(){this.el.focus()}}o(Jt,"values",{mode:String});class Yt extends be{get _mode(){if(this.hasSubmitModeValue){if(!["direct","request"].includes(this.submitModeValue))throw new Error(`The modeValue provided '${this.submitModeValue}' is not one of the recognised configuration options`);return this.submitModeValue}return"request"}get form(){let e;if(this.hasFormSelectorValue){if(e=document.querySelector(this.formSelectorValue),!e)throw new Error(`Could not find a form on the page that matches selector '${this.formSelectorValue}'`)}else e=this.formTarget;return e}submit(e){null==e||e.preventDefault();let t=this.el;"request"==this._mode?Xe(t):t.submit()}reset(e){null==e||e.preventDefault(),Ge(this.form)}}o(Yt,"targets",["form"]),o(Yt,"values",{formSelector:String,submitMode:String});class Zt extends be{get _formID(){if(this.hasIdValue)return this.idValue;let e=this.el.id;if(""!==e)return e;throw new Error(`No ID value to uniquely identify this form. Please either specify data-${this.identifier}-id-value or give this form an 'id' attribute. `)}get _formIdentifier(){return`${location.href} ${this._formID}`}get _formElements(){return this.el.elements}get _formData(){let e={[this._formIdentifier]:{}};for(const t of this._formElements){let s=t;s.name.length>0&&(Re(s)&&"checkbox"==s.type?e[this._formIdentifier][s.name]=s.checked:Re(s)&&"radio"==s.type?s.checked&&(e[this._formIdentifier][s.name]=s.value):e[this._formIdentifier][s.name]=s.value)}return e}get _restoreOnLoad(){return!this.hasRestoreOnLoadValue||this.restoreOnLoadValue}get _clearOnSubmit(){return!this.hasClearOnSubmitValue||this.clearOnSubmitValue}connect(){requestAnimationFrame((()=>{if(!He(this.el))throw new Error("Expected controller to be mounted on a form element.");this._restoreOnLoad&&this.restore(),this._clearOnSubmit&&Qe(this,this.el,"submit",this._clear)}))}_clear(){localStorage.removeItem(this._formIdentifier),this.dispatch(this.el,"form-save:cleared")}clear(e){null==e||e.preventDefault(),this._clear()}save(e){e.preventDefault();let t=this._formData;localStorage.setItem(this._formIdentifier,JSON.stringify(t[this._formIdentifier])),this.dispatch(this.el,"form-save:save:success")}restore(e){if(null==e||e.preventDefault(),localStorage.getItem(this._formIdentifier)){const e=JSON.parse(localStorage.getItem(this._formIdentifier));for(const t of this._formElements){let s=t;s.name in e&&(Re(s)&&"checkbox"==s.type?s.checked=e[s.name]:Re(s)&&"radio"==s.type?s.value==e[s.name]&&(s.checked=!0):s.value=e[s.name])}this.dispatch(this.el,"form-save:restore:success")}else this.dispatch(this.el,"form-save:restore:empty")}}o(Zt,"values",{id:String,restoreOnLoad:Boolean,clearOnSubmit:Boolean});class Xt extends be{get _threshold(){return this.hasThresholdValue?this.thresholdValue.split(",").map((e=>Number.parseFloat(e.trim()))).filter((e=>e>=0&&e<=1)):[0,1]}connect(){ft(this,{threshold:this._threshold,element:this.el})}appear(e){this.dispatch(this.el,"intersection:appear",{detail:{element:this.el}})}disappear(e){this.dispatch(this.el,"intersection:disappear",{detail:{element:this.el}})}}o(Xt,"values",{threshold:String});class Gt extends be{connect(){if(!this.hasSecondsValue)throw new Error("Expected `secondsValue` to be present");requestAnimationFrame((()=>{tt(this,this._interval,1e3*this.secondsValue)}))}_interval(){this.dispatch(this.el,"interval:action")}}o(Gt,"values",{seconds:Number});class Qt extends at{async connect(){let e=this.el;"IntersectionObserver"in window?[this.observe,this.unobserve]=ft(this,{element:e,threshold:.3}):await this.loadContent()}async appear(e){e.target===this.el&&e.isIntersecting&&(await this.loadContent(),this.unobserve&&this.unobserve())}}var es=window.CustomEvent;function ts(e,t){var s="on"+t.type.toLowerCase();return"function"==typeof e[s]&&e[s](t),e.dispatchEvent(t)}function ss(e){for(;e;){if("dialog"===e.localName)return e;e=e.parentElement?e.parentElement:e.parentNode?e.parentNode.host:null}return null}function is(e){for(;e&&e.shadowRoot&&e.shadowRoot.activeElement;)e=e.shadowRoot.activeElement;e&&e.blur&&e!==document.body&&e.blur()}function rs(e,t){for(var s=0;s<e.length;++s)if(e[s]===t)return!0;return!1}function ns(e){return!(!e||!e.hasAttribute("method"))&&"dialog"===e.getAttribute("method").toLowerCase()}function os(e){var t=["button","input","keygen","select","textarea"].map((function(e){return e+":not([disabled])"}));t.push('[tabindex]:not([disabled]):not([tabindex=""])');var s=e.querySelector(t.join(", "));if(!s&&"attachShadow"in Element.prototype)for(var i=e.querySelectorAll("*"),r=0;r<i.length&&!(i[r].tagName&&i[r].shadowRoot&&(s=os(i[r].shadowRoot)));r++);return s}function as(e){return e.isConnected||document.body.contains(e)}function ls(e){if(e.submitter)return e.submitter;var t=e.target;if(!(t instanceof HTMLFormElement))return null;var s=us.formSubmitter;if(!s){var i=e.target;s=("getRootNode"in i&&i.getRootNode()||document).activeElement}return s&&s.form===t?s:null}function cs(e){if(!e.defaultPrevented){var t=e.target,s=us.imagemapUseValue,i=ls(e);null===s&&i&&(s=i.value);var r=ss(t);if(r)"dialog"===(i&&i.getAttribute("formmethod")||t.getAttribute("method"))&&(e.preventDefault(),null!=s?r.close(s):r.close())}}function hs(e){if(this.dialog_=e,this.replacedStyleTop_=!1,this.openAsModal_=!1,e.hasAttribute("role")||e.setAttribute("role","dialog"),e.show=this.show.bind(this),e.showModal=this.showModal.bind(this),e.close=this.close.bind(this),e.addEventListener("submit",cs,!1),"returnValue"in e||(e.returnValue=""),"MutationObserver"in window){new MutationObserver(this.maybeHideModal.bind(this)).observe(e,{attributes:!0,attributeFilter:["open"]})}else{var t,s=!1,i=function(){s?this.downgradeModal():this.maybeHideModal(),s=!1}.bind(this),r=function(r){if(r.target===e){var n="DOMNodeRemoved";s|=r.type.substr(0,n.length)===n,window.clearTimeout(t),t=window.setTimeout(i,0)}};["DOMAttrModified","DOMNodeRemoved","DOMNodeRemovedFromDocument"].forEach((function(t){e.addEventListener(t,r)}))}Object.defineProperty(e,"open",{set:this.setOpen.bind(this),get:e.hasAttribute.bind(e,"open")}),this.backdrop_=document.createElement("div"),this.backdrop_.className="backdrop",this.backdrop_.addEventListener("mouseup",this.backdropMouseEvent_.bind(this)),this.backdrop_.addEventListener("mousedown",this.backdropMouseEvent_.bind(this)),this.backdrop_.addEventListener("click",this.backdropMouseEvent_.bind(this))}es&&"object"!=typeof es||((es=function(e,t){t=t||{};var s=document.createEvent("CustomEvent");return s.initCustomEvent(e,!!t.bubbles,!!t.cancelable,t.detail||null),s}).prototype=window.Event.prototype),hs.prototype={get dialog(){return this.dialog_},maybeHideModal:function(){this.dialog_.hasAttribute("open")&&as(this.dialog_)||this.downgradeModal()},downgradeModal:function(){this.openAsModal_&&(this.openAsModal_=!1,this.dialog_.style.zIndex="",this.replacedStyleTop_&&(this.dialog_.style.top="",this.replacedStyleTop_=!1),this.backdrop_.parentNode&&this.backdrop_.parentNode.removeChild(this.backdrop_),us.dm.removeDialog(this))},setOpen:function(e){e?this.dialog_.hasAttribute("open")||this.dialog_.setAttribute("open",""):(this.dialog_.removeAttribute("open"),this.maybeHideModal())},backdropMouseEvent_:function(e){if(this.dialog_.hasAttribute("tabindex"))this.dialog_.focus();else{var t=document.createElement("div");this.dialog_.insertBefore(t,this.dialog_.firstChild),t.tabIndex=-1,t.focus(),this.dialog_.removeChild(t)}var s=document.createEvent("MouseEvents");s.initMouseEvent(e.type,e.bubbles,e.cancelable,window,e.detail,e.screenX,e.screenY,e.clientX,e.clientY,e.ctrlKey,e.altKey,e.shiftKey,e.metaKey,e.button,e.relatedTarget),this.dialog_.dispatchEvent(s),e.stopPropagation()},focus_:function(){var e=this.dialog_.querySelector("[autofocus]:not([disabled])");!e&&this.dialog_.tabIndex>=0&&(e=this.dialog_),e||(e=os(this.dialog_)),is(document.activeElement),e&&e.focus()},updateZIndex:function(e,t){if(e<t)throw new Error("dialogZ should never be < backdropZ");this.dialog_.style.zIndex=e,this.backdrop_.style.zIndex=t},show:function(){this.dialog_.open||(this.setOpen(!0),this.focus_())},showModal:function(){if(this.dialog_.hasAttribute("open"))throw new Error("Failed to execute 'showModal' on dialog: The element is already open, and therefore cannot be opened modally.");if(!as(this.dialog_))throw new Error("Failed to execute 'showModal' on dialog: The element is not in a Document.");if(!us.dm.pushDialog(this))throw new Error("Failed to execute 'showModal' on dialog: There are too many open modal dialogs.");(function(e){for(;e&&e!==document.body;){var t=window.getComputedStyle(e),s=function(e,s){return!(void 0===t[e]||t[e]===s)};if(t.opacity<1||s("zIndex","auto")||s("transform","none")||s("mixBlendMode","normal")||s("filter","none")||s("perspective","none")||"isolate"===t.isolation||"fixed"===t.position||"touch"===t.webkitOverflowScrolling)return!0;e=e.parentElement}return!1})(this.dialog_.parentElement)&&console.warn("A dialog is being shown inside a stacking context. This may cause it to be unusable. For more information, see this link: https://github.com/GoogleChrome/dialog-polyfill/#stacking-context"),this.setOpen(!0),this.openAsModal_=!0,us.needsCentering(this.dialog_)?(us.reposition(this.dialog_),this.replacedStyleTop_=!0):this.replacedStyleTop_=!1,this.dialog_.parentNode.insertBefore(this.backdrop_,this.dialog_.nextSibling),this.focus_()},close:function(e){if(!this.dialog_.hasAttribute("open"))throw new Error("Failed to execute 'close' on dialog: The element does not have an 'open' attribute, and therefore cannot be closed.");this.setOpen(!1),void 0!==e&&(this.dialog_.returnValue=e);var t=new es("close",{bubbles:!1,cancelable:!1});ts(this.dialog_,t)}};var us={reposition:function(e){var t=document.body.scrollTop||document.documentElement.scrollTop,s=t+(window.innerHeight-e.offsetHeight)/2;e.style.top=Math.max(t,s)+"px"},isInlinePositionSetByStylesheet:function(e){for(var t=0;t<document.styleSheets.length;++t){var s=document.styleSheets[t],i=null;try{i=s.cssRules}catch(c){}if(i)for(var r=0;r<i.length;++r){var n=i[r],o=null;try{o=document.querySelectorAll(n.selectorText)}catch(c){}if(o&&rs(o,e)){var a=n.style.getPropertyValue("top"),l=n.style.getPropertyValue("bottom");if(a&&"auto"!==a||l&&"auto"!==l)return!0}}}return!1},needsCentering:function(e){return"absolute"===window.getComputedStyle(e).position&&(!("auto"!==e.style.top&&""!==e.style.top||"auto"!==e.style.bottom&&""!==e.style.bottom)&&!us.isInlinePositionSetByStylesheet(e))},forceRegisterDialog:function(e){if((window.HTMLDialogElement||e.showModal)&&console.warn("This browser already supports <dialog>, the polyfill may not work correctly",e),"dialog"!==e.localName)throw new Error("Failed to register dialog: The element is not a dialog.");new hs(e)},registerDialog:function(e){e.showModal||us.forceRegisterDialog(e)},DialogManager:function(){this.pendingDialogStack=[];var e=this.checkDOM_.bind(this);this.overlay=document.createElement("div"),this.overlay.className="_dialog_overlay",this.overlay.addEventListener("click",function(t){this.forwardTab_=void 0,t.stopPropagation(),e([])}.bind(this)),this.handleKey_=this.handleKey_.bind(this),this.handleFocus_=this.handleFocus_.bind(this),this.zIndexLow_=1e5,this.zIndexHigh_=100150,this.forwardTab_=void 0,"MutationObserver"in window&&(this.mo_=new MutationObserver((function(t){var s=[];t.forEach((function(e){for(var t,i=0;t=e.removedNodes[i];++i)t instanceof Element&&("dialog"===t.localName&&s.push(t),s=s.concat(t.querySelectorAll("dialog")))})),s.length&&e(s)})))}};if(us.DialogManager.prototype.blockDocument=function(){document.documentElement.addEventListener("focus",this.handleFocus_,!0),document.addEventListener("keydown",this.handleKey_),this.mo_&&this.mo_.observe(document,{childList:!0,subtree:!0})},us.DialogManager.prototype.unblockDocument=function(){document.documentElement.removeEventListener("focus",this.handleFocus_,!0),document.removeEventListener("keydown",this.handleKey_),this.mo_&&this.mo_.disconnect()},us.DialogManager.prototype.updateStacking=function(){for(var e,t=this.zIndexHigh_,s=0;e=this.pendingDialogStack[s];++s)e.updateZIndex(--t,--t),0===s&&(this.overlay.style.zIndex=--t);var i=this.pendingDialogStack[0];i?(i.dialog.parentNode||document.body).appendChild(this.overlay):this.overlay.parentNode&&this.overlay.parentNode.removeChild(this.overlay)},us.DialogManager.prototype.containedByTopDialog_=function(e){for(;e=ss(e);){for(var t,s=0;t=this.pendingDialogStack[s];++s)if(t.dialog===e)return 0===s;e=e.parentElement}return!1},us.DialogManager.prototype.handleFocus_=function(e){var t=e.composedPath?e.composedPath()[0]:e.target;if(!this.containedByTopDialog_(t)&&document.activeElement!==document.documentElement&&(e.preventDefault(),e.stopPropagation(),is(t),void 0!==this.forwardTab_)){var s=this.pendingDialogStack[0];return s.dialog.compareDocumentPosition(t)&Node.DOCUMENT_POSITION_PRECEDING&&(this.forwardTab_?s.focus_():t!==document.documentElement&&document.documentElement.focus()),!1}},us.DialogManager.prototype.handleKey_=function(e){if(this.forwardTab_=void 0,27===e.keyCode){e.preventDefault(),e.stopPropagation();var t=new es("cancel",{bubbles:!1,cancelable:!0}),s=this.pendingDialogStack[0];s&&ts(s.dialog,t)&&s.dialog.close()}else 9===e.keyCode&&(this.forwardTab_=!e.shiftKey)},us.DialogManager.prototype.checkDOM_=function(e){this.pendingDialogStack.slice().forEach((function(t){-1!==e.indexOf(t.dialog)?t.downgradeModal():t.maybeHideModal()}))},us.DialogManager.prototype.pushDialog=function(e){var t=(this.zIndexHigh_-this.zIndexLow_)/2-1;return!(this.pendingDialogStack.length>=t)&&(1===this.pendingDialogStack.unshift(e)&&this.blockDocument(),this.updateStacking(),!0)},us.DialogManager.prototype.removeDialog=function(e){var t=this.pendingDialogStack.indexOf(e);-1!==t&&(this.pendingDialogStack.splice(t,1),0===this.pendingDialogStack.length&&this.unblockDocument(),this.updateStacking())},us.dm=new us.DialogManager,us.formSubmitter=null,us.imagemapUseValue=null,void 0===window.HTMLDialogElement){var ds=document.createElement("form");if(ds.setAttribute("method","dialog"),"dialog"!==ds.method){var ps=Object.getOwnPropertyDescriptor(HTMLFormElement.prototype,"method");if(ps){var fs=ps.get;ps.get=function(){return ns(this)?"dialog":fs.call(this)};var ms=ps.set;ps.set=function(e){return"string"==typeof e&&"dialog"===e.toLowerCase()?this.setAttribute("method",e):ms.call(this,e)},Object.defineProperty(HTMLFormElement.prototype,"method",ps)}}document.addEventListener("click",(function(e){if(us.formSubmitter=null,us.imagemapUseValue=null,!e.defaultPrevented){var t=e.target;if("composedPath"in e)t=e.composedPath().shift()||t;if(t&&ns(t.form)){if(!("submit"===t.type&&["button","input"].indexOf(t.localName)>-1)){if("input"!==t.localName||"image"!==t.type)return;us.imagemapUseValue=e.offsetX+","+e.offsetY}ss(t)&&(us.formSubmitter=t)}}}),!1),document.addEventListener("submit",(function(e){var t=e.target;if(!ss(t)){var s=ls(e);"dialog"===(s&&s.getAttribute("formmethod")||t.getAttribute("method"))&&e.preventDefault()}}));var gs=HTMLFormElement.prototype.submit;HTMLFormElement.prototype.submit=function(){if(!ns(this))return gs.call(this);var e=ss(this);e&&e.close()}}class vs extends be{constructor(){super(...arguments),o(this,"_dialog",null)}get _src(){return this.hasSrcValue?this.srcValue:this.el.src}get _srcSet(){return this.hasSrcSetValue?this.srcSetValue:this.el.srcset}get _sizes(){return this.hasSizesValue?this.sizesValue:this.el.sizes}get _modalClassName(){return this.hasModalClass?this.modalClass:"image-lightbox-dialog"}get _imageClassName(){return this.hasImageClass?this.imageClass:"image-lightbox-image"}initialize(){this.open=this.open.bind(this),this.close=this.close.bind(this)}connect(){}open(){let e=this.el;if(this._dialog)return;this._dialog=document.createElement("dialog");let t=document.createElement("img");t.className=this._imageClassName,t.src=this._src,t.srcset=this._srcSet,t.sizes=this._sizes,this._dialog.appendChild(t),e.insertAdjacentElement("afterend",this._dialog),us.registerDialog(this._dialog),this._dialog.className=this._modalClassName,this._dialog.showModal(),ke(this._dialog,{behavior:"smooth",block:"end"}).catch((()=>this._dialog.scrollIntoView(!1))),Qe(this,this._dialog,"click",this.close),Qe(this,this._dialog,"cancel",this.close),Qe(this,this._dialog,"close",this.close)}close(){this._dialog&&(this._dialog.close(),this._dialog.remove(),this._dialog=null,ke(this.el,{behavior:"smooth",block:"end"}).catch((()=>this.el.scrollIntoView(!1))))}}o(vs,"values",{src:String,srcSet:String,sizes:String}),o(vs,"classes",["modal","image"]);class bs extends be{connect(){this.inputTargets.forEach((e=>Qe(this,e,"change",this.handleInputs)))}handleInputs(e){let t=this.inputTargets.reduce(((e,t)=>t.checked?e+1:e),0),s=e.target;t>this.maxValue?(e.preventDefault(),s.checked=!1,this.dispatch(s,"change"),this.dispatch(s,"limited-selection:too-many"),this.hasErrorTarget&&(this.errorTarget.innerHTML=this.messageValue)):(this.dispatch(s,"limited-selection:selection"),this.hasErrorTarget&&(this.errorTarget.innerHTML=""))}}o(bs,"targets",["input","error"]),o(bs,"values",{max:Number,message:String});class ys extends be{initialize(){}connect(){}disconnect(){}async play(e){null==e||e.preventDefault(),await this.mediaTarget.play()}pause(e){null==e||e.preventDefault(),this.mediaTarget.pause()}restart(e){null==e||e.preventDefault(),this.mediaTarget.currentTime=0}seek(e){null==e||e.preventDefault(),this.mediaTarget.currentTime+=5}}o(ys,"targets",["media"]);class _s extends be{constructor(){super(...arguments),o(this,"_errors",[]),o(this,"_firstClick",!1)}get _errorCount(){return this._errors.length}get _previousIndex(){let e=this._index-1;return e<0?0:e}get _nextIndex(){let e=this._index+1;return e>this._errors.length-1?this._errors.length-1:e}get _index(){return h(this.hasIndexValue?this.indexValue:0,0,this._errors.length)}get _selector(){if(this.hasSelectorValue)return this.selectorValue;throw new Error("Expected `selectorValue` to be present")}get _currentError(){return this._errors[this._index]}connect(){requestAnimationFrame((()=>{this._firstClick=!0,this._toggleButtons(),this._toggleVisibility()}))}async current(e){null==e||e.preventDefault(),this._firstClick&&(this._firstClick=!1,this._toggleButtons()),await ke(this._currentError,{behavior:"smooth",block:"center",inline:"center"})}async next(e){null==e||e.preventDefault(),this._firstClick?(this._firstClick=!1,this._toggleButtons()):this.indexValue=this._nextIndex,await ke(this._currentError,{behavior:"smooth",block:"center",inline:"center"})}async previous(e){null==e||e.preventDefault(),this._firstClick?(this._firstClick=!1,this._toggleButtons()):this.indexValue=this._previousIndex,await ke(this._currentError,{behavior:"smooth",block:"center",inline:"center"})}indexValueChanged(){this._toggleButtons()}selectorValueChanged(){this._errors=Array.from(document.querySelectorAll(this._selector)),this.indexValue=0,this._toggleButtons(),this._toggleVisibility()}_toggleVisibility(){0===this._errorCount?this.el.style.display="none":this.el.style.display=""}_toggleButtons(){if(this.hasNextTarget){if(!this.hasCurrentTarget&&this._firstClick&&this.indexValue==this._errorCount-1)return void this.nextTarget.removeAttribute("disabled");this.indexValue>=this._errorCount-1?this.nextTarget.setAttribute("disabled","true"):this.nextTarget.removeAttribute("disabled")}this.hasPreviousTarget&&(this.indexValue<=0?this.previousTarget.setAttribute("disabled","true"):this.previousTarget.removeAttribute("disabled"))}}o(_s,"values",{selector:String,index:Number}),o(_s,"targets",["next","current","previous"]);class ws extends be{get _wrapperClass(){return this.hasWrapperSelectorValue?this.wrapperClassValue:"nested-fields"}get _insertMode(){return this.hasInsertModeValue?this.insertModeValue:"beforeend"}connect(){this._checkStructure()}add(e){null==e||e.preventDefault();const t=this.templateTarget.innerHTML.replace(/NEW_RECORD/g,this._generateID());this.targetTarget.insertAdjacentHTML(this._insertMode,t)}remove(e){e.preventDefault();const t=e.target.closest(`.${this._wrapperClass}`);if(null==t)throw new Error(`#remove was clicked from outside of a child record. Could not find an ancestor with class .${this._wrapperClass}`);if("true"===t.dataset.newRecord)t.remove();else{t.style.display="none";let e=t.querySelector("input[name*='_destroy']");if(null==e)throw new Error("Could not find a hidden input with name '_destroy'. NestedForm cannot remove an already persisted record without it.");e.value="1"}}_generateID(){return(new Date).getTime().toString()+Math.random().toString().slice(2)}_checkStructure(){if(this.templateTarget.innerHTML.indexOf("NEW_RECORD"))throw new Error("Could not find 'NEW_RECORD' in the provided template. Please make sure you've passed `child_index: 'NEW_RECORD'` to `fields_for`")}}o(ws,"targets",["target","template"]),o(ws,"values",{insertMode:String,wrapperClass:String});class Es extends be{get _errorClasses(){return this.errorClass.split(" ")}get _defaultErrorClasses(){return[]}connect(){this.passwordTargets.forEach((e=>Qe(this,e,"change",this._checkPasswordsMatch)))}_addErrorClasses(e=this.el){this.hasErrorClass?e.classList.add(...this._errorClasses):e.classList.add(...this._defaultErrorClasses)}_removeErrorClasses(e=this.el){this.hasErrorClass?e.classList.remove(...this._errorClasses):e.classList.remove(...this._defaultErrorClasses)}_allPasswordsMatch(){let e=new Set(this.passwordTargets.map((e=>e.value)));return e.has("")||1==e.size}_checkPasswordsMatch(){let e=this.el;this._allPasswordsMatch()?(this.dispatch(e,"password-confirm:match"),this.hasErrorClass&&this.passwordTargets.forEach((e=>this._removeErrorClasses(e)))):(this.dispatch(e,"password-confirm:no-match"),this.hasErrorClass&&this.passwordTargets.forEach((e=>this._addErrorClasses(e))))}}o(Es,"targets",["password"]),o(Es,"classes",["error"]);class Cs extends be{peak(e){null==e||e.preventDefault(),this.passwordTarget.type="text"}hide(e){null==e||e.preventDefault(),this.passwordTarget.type="password"}toggle(e){null==e||e.preventDefault(),"password"===this.passwordTarget.type?this.peak():this.hide()}}o(Cs,"targets",["password"]);class Ts extends at{connect(){requestAnimationFrame((()=>{this._timeout(),tt(this,this._timeout,1e3*this.secondsValue)}))}async _timeout(){await this.loadContent()}}o(Ts,"targets",["replace"]),o(Ts,"values",{endpoint:String,errorMessage:String,selector:String,seconds:Number});class ks extends be{get _mode(){return this.hasModeValue?this.modeValue:"mouseover"}get _supportsPrefetch(){var e,t;const s=document.createElement("link");return(null==(e=s.relList)?void 0:e.supports)&&(null==(t=s.relList)?void 0:t.supports("prefetch"))}get _href(){return this.el.href}get _existingPrefetch(){return(document.head.querySelectorAll(`link[rel="prefetch"][href="${this._href}"]`)||[]).length>0}get _connectionSuitable(){const e=navigator.connection;if(!e)return!0;if(e){if(e.saveData)return this.warn("Data Saving is enabled"),!1;if(/2g/.test(e.effectiveType))return this.warn("Network is too slow"),!1}return!0}connect(){if(this._supportsPrefetch)switch(this._mode){case"intersect":this._setupObserver();break;case"mouseover":Qe(this,this.el,"mouseover",this.prefetch,{once:!0});break;default:throw new Error(`'${this._mode}' is not a supported prefetch mode`)}}_setupObserver(){new IntersectionObserver((([e],t)=>{e.isIntersecting&&(this.prefetch(),t.unobserve(e.target))})).observe(this.element)}prefetch(){if(this._existingPrefetch||!this._connectionSuitable)return;const e=document.createElement("link");Object.assign(e,{rel:"prefetch",href:this._href,as:"document"}),document.head.appendChild(e)}}o(ks,"values",{mode:String});class Vs extends be{get name(){return this.hasNameValue?`${this.nameValue}:`:""}connect(){this.dispatch(this.el,`${this.nameValue}presence:added`)}disconnect(){this.dispatch(this.el,`${this.nameValue}presence:removed`)}}o(Vs,"values",{name:String});class As extends be{print(e){null==e||e.preventDefault(),window.print()}}class Ss extends As{get _unsupportedClasses(){return this.unsupportedClass.split(" ")}get _defaultUnsupportedClasses(){return["unsupported"]}connect(){"print"in window||this._addUnsupportedClasses(this.el),Qe(this,this.el,"click",this.print)}_addUnsupportedClasses(e=this.el){this.hasUnsupportedClass?e.classList.add(...this._unsupportedClasses):e.classList.add(...this._defaultUnsupportedClasses)}_removeUnsupportedClasses(e=this.el){this.hasUnsupportedClass?e.classList.remove(...this._unsupportedClasses):e.classList.remove(...this._defaultUnsupportedClasses)}}o(Ss,"classes",["unsupported"]);class xs extends be{get _selector(){return this.hasSelectorValue?this.selectorValue:`[data-controller~="${this.identifier}"]`}replace(e){const[t,s,i]=e.detail;if(t instanceof Node){let e=t.querySelector(this._selector);if(null==e)throw new Error(`expected new form DOM with [data-controller="${this.identifier}"] to be present in returned payload`);let s=this.el.parentNode;if(null==s)throw new Error("expected form to have a DOM parent, could not execute replaceChild");s.replaceChild(e,this.el),this.dispatch(e,"remote-form:replace")}else console.log("Unknown",t)}}o(xs,"targets",[]),o(xs,"values",{selector:String});class Os extends be{connect(){Qe(this,window,"message",this.messageReceived)}messageReceived(e){let t=e.data;t.hasOwnProperty("name")&&"iframe-body"===t.name&&t.hasOwnProperty("height")&&this.resize(t.height)}resize(e){this.el.style.height=`${e}px`}}class Ms extends be{connect(){var e,t,s;window.self!==window.top&&(Et(this),t={},null===(s=(e=this).constructor.debounces)||void 0===s||s.forEach((s=>{if("string"==typeof s&&(e[s]=Ct(e[s],null==t?void 0:t.wait)),"object"==typeof s){const{name:i,wait:r}=s;if(!i)return;e[i]=Ct(e[i],r||(null==t?void 0:t.wait))}})),this.postUpdate())}windowResize(e){this.postUpdate()}postUpdate(){let e={name:"iframe-body",height:this.getHeight()};window.parent.postMessage(e,"*")}getHeight(){const e=document.body,t=document.documentElement;return Math.max(e.scrollHeight,e.offsetHeight,t.clientHeight,t.scrollHeight,t.offsetHeight)}}o(Ms,"debounces",["postUpdate"]);class Ls extends be{get _increment(){return this.hasIncrementValue?this.incrementValue:50}get _behaviour(){if(this.hasBehaviourValue){if(["auto","smooth"].includes(this.behaviourValue))return this.behaviourValue;throw new Error(`'${this.behaviourValue}' is not a recognised scroll behaviour`)}return"auto"}async scrollTop(e){null==e||e.preventDefault(),await Ve(this.el,{behavior:this._behaviour})}async scrollBottom(e){null==e||e.preventDefault(),await Ae(this.el,{behavior:this._behaviour})}async scrollLeft(e){null==e||e.preventDefault(),await Se(this.el,{behavior:this._behaviour})}async scrollRight(e){null==e||e.preventDefault(),await Se(this.el,{behavior:this._behaviour})}async up(e){null==e||e.preventDefault(),await Oe(this.el,this._increment,{behavior:this._behaviour})}async down(e){null==e||e.preventDefault(),await Me(this.el,this._increment,{behavior:this._behaviour})}async left(e){null==e||e.preventDefault(),await Le(this.el,this._increment,{behavior:this._behaviour})}async right(e){null==e||e.preventDefault(),await Ne(this.el,this._increment,{behavior:this._behaviour})}}o(Ls,"values",{behaviour:String,increment:Number});class Ns extends Ee{connect(){requestAnimationFrame((()=>{ke(this.el,{behavior:this.hasBehaviorValue?this.behaviorValue:"smooth",block:this.hasBlockValue?this.blockValue:"center",inline:this.hasInlineValue?this.inlineValue:"center"}).catch((()=>this.el.scrollIntoView())),this._cleanupSelf()}))}}o(Ns,"values",{behavior:String,block:String,inline:String});class Ds extends be{get _mode(){return this.hasModeValue?this.modeValue:"document"}get _scrollTarget(){let e;return e="document"==this._mode?window:Ie(this.el),e}async scroll(e){null==e||e.preventDefault(),this._scrollTarget&&await Ae(this._scrollTarget)}}o(Ds,"values",{mode:String});class Is extends be{scroll(){let e=document.querySelector(this.selectorValue);e?ke(e,{behavior:this.hasBehaviorValue?this.behaviorValue:"smooth",block:this.hasBlockValue?this.blockValue:"center",inline:this.hasInlineValue?this.inlineValue:"center"}).catch((()=>e.scrollIntoView())):console.warn(`Could not find target for '${this.selectorValue}'`)}}o(Is,"values",{selector:String,behavior:String,block:String,inline:String});class Ps extends be{get _mode(){return this.hasModeValue?this.modeValue:"document"}get _scrollTarget(){let e;return e="document"==this._mode?window:Ie(this.el),e}async scroll(e){null==e||e.preventDefault(),this._scrollTarget&&await Ve(this._scrollTarget)}}o(Ps,"values",{mode:String});class js extends be{connect(){requestAnimationFrame((()=>{st(this,(()=>this.el.remove()),1e3*this.secondsValue)}))}}o(js,"values",{seconds:Number});class Bs extends be{constructor(){super(...arguments),o(this,"_magicElement",null)}get _stuckClasses(){return this.stuckClass.split(" ")}get _defaultStuckClasses(){return["stuck"]}get _mode(){if(this.hasModeValue){if(!["top","bottom"].includes(this.modeValue))throw new Error(`The modeValue provided '${this.modeValue}' is not one of the recognised configuration options`);if("top"===this.modeValue)return"beforebegin"}return"afterend"}connect(){this._magicElement=document.createElement("div"),nt(this,this.el,this._mode,this._magicElement);new IntersectionObserver((e=>{e.forEach((e=>{e.target===this._magicElement&&(0===e.intersectionRatio?this._addStuckClasses():1===e.intersectionRatio&&this._removeStuckClasses())}))}),{threshold:[0,1]}).observe(this._magicElement)}_addStuckClasses(e=this.el){this.hasStuckClass?e.classList.add(...this._stuckClasses):e.classList.add(...this._defaultStuckClasses)}_removeStuckClasses(e=this.el){this.hasStuckClass?e.classList.remove(...this._stuckClasses):e.classList.remove(...this._defaultStuckClasses)}}o(Bs,"classes",["stuck"]),o(Bs,"values",{mode:String});class Fs extends be{get _eventName(){return`sync:${this._key}`}get _key(){if(this.hasKeyValue)return this.keyValue;throw new Error("Expected `keyValue` to be present")}get _value(){let e=this.el;return Re(e)&&"checkbox"===e.type?e.checked:Re(e)&&"radio"===e.type?e.checked?e.value:"":e.value}set _value(e){let t=this.el;Re(t)&&"checkbox"===t.type?t.checked="true"===e.toString():Re(t)&&"radio"===t.type?t.checked=t.value===e:Re(t)||$e(t)||Ue(t)?t.value=e.toString():t.innerHTML=e.toString()}initialize(){this._read=this._read.bind(this),this._emit=this._emit.bind(this)}connect(){je.on(this._eventName,this._read),requestAnimationFrame((()=>{var e;(Re(e=this.el)||Ue(e)||$e(e))&&(this._emit(),Qe(this,this.el,"input",this._emit))}))}disconnect(){je.off(this._eventName,this._read)}_emit(){je.emit(this._eventName,{value:this._value,dispatcher:this.el})}_read(e){if(void 0===e)throw new Error("No payload received");let{dispatcher:t,value:s}=e;t!==this.el&&(this._value=s)}}o(Fs,"values",{key:String});class Hs extends be{constructor(){super(...arguments),o(this,"_lastIndex",null),o(this,"_reverse",!1)}get _tableHead(){let e=this.el.tHead;if(null==e)throw new Error("Expected table to have a <thead> element.");return e}get _tableHeaders(){let e=this._tableHead.rows;if(0==e.length)throw new Error("Expected table to have a <thead> element with at least one row.");return Array.from(e[0].cells)}get _tableBody(){return this.el.tBodies[0]}get _tableRows(){return Array.from(this._tableBody.rows)}connect(){requestAnimationFrame((()=>{this._tableHeaders.forEach((e=>Qe(this,e,"click",this.sort))),this.hasStartSortValue&&this._sortByColumn(this.startSortValue)}))}sort(e){e.preventDefault();let t=e.target,s=this._indexOfHeaderCell(t);this._sortByColumn(s)}_indexOfHeaderCell(e){return this._tableHeaders.indexOf(e)}_sortByColumn(e){this._reverse=e===this._lastIndex&&!this._reverse;let t=document.createDocumentFragment();this._tableRows.sort(((t,s)=>{var i,r;let n=Array.from(t.cells),o=Array.from(s.cells),a=(null==(i=n[e])?void 0:i.innerText)||"",l=(null==(r=o[e])?void 0:r.innerText)||"",c=a.localeCompare(l,"en",{sensitivity:"base",numeric:!0,caseFirst:"upper"});return t.dataset.sortTop||s.dataset.sortBottom?t.dataset.sortTop&&s.dataset.sortTop?c:-1:t.dataset.sortBottom||s.dataset.sortTop?t.dataset.sortBottom&&s.dataset.sortBottom?c:1:this._reverse?c>0?-1:1:c})).forEach((e=>t.appendChild(e))),this._tableBody.innerHTML="",this._tableBody.appendChild(t),this._lastIndex=e}}o(Hs,"values",{startSort:Number});class Rs extends be{get _truncated(){return!!this.hasTruncatedValue&&this.truncatedValue}set _truncated(e){this.truncatedValue=e}get _tableBody(){return this.el.tBodies[0]}get _tableRows(){return Array.from(this._tableBody.rows)}get _limit(){return this.hasLimitValue?this.limitValue:20}initialize(){this.truncate=this.truncate.bind(this),this.expand=this.expand.bind(this)}connect(){wt(this,{childList:!0,element:this._tableBody}),requestAnimationFrame((()=>{this.truncate(),Qe(this,this.showMoreTarget,"click",this.expand)}))}truncate(e){null==e||e.preventDefault(),this._truncated=!0,this._tableRows.length>=this._limit?(this._tableRows.slice(this._limit).forEach((e=>{e!==this.showMoreTarget&&this._hideElement(e)})),this._showElement(this.showMoreTarget)):this._hideElement(this.showMoreTarget)}expand(e){this._truncated=!1,null==e||e.preventDefault(),this._tableRows.slice(this._limit).forEach((e=>{e!==this.showMoreTarget&&this._showElement(e)})),this._hideElement(this.showMoreTarget)}mutate(e){this._truncated&&this._reTruncate()}_showElement(e){e.style.display=""}_hideElement(e){e.style.display="none"}_reTruncate(){this._tableRows.slice(0,this._limit).forEach((e=>{e!==this.showMoreTarget&&this._showElement(e)})),this._tableRows.slice(this._limit).forEach((e=>{e!==this.showMoreTarget&&this._hideElement(e)})),this._showElement(this.showMoreTarget)}}o(Rs,"targets",["showMore"]),o(Rs,"values",{limit:Number,truncated:Boolean});class $s extends be{get _hideClasses(){return this.hideClass.split(" ")}get _defaultHideClasses(){return["hide"]}get _activeClasses(){return this.activeClass.split(" ")}get _defaultActiveClasses(){return["is-active"]}get _currentTab(){return this.hasCurrentTabValue?this.currentTabValue:0}get _equalize(){return!!this.hasEqualizeValue&&this.equalizeValue}connect(){this.linkTargets.forEach((e=>Qe(this,e,"click",this.switchTabs))),this._equalize&&this._setMinHeight(),this.currentTabValue=this._currentTab}switchTabs(e){e.preventDefault(),this.currentTabValue=this.linkTargets.indexOf(e.currentTarget)}currentTabValueChanged(){let e=this._currentTab;e=this._clampIndex(e),this._selectTab(e)}_selectTab(e){e=this._clampIndex(e);let t=this.linkTargets,s=this.contentTargets,i=s[e],r=t[e],n=[...s.slice(0,e),...s.slice(e+1)],o=[...t.slice(0,e),...t.slice(e+1)];this._addActiveClasses(r),r.setAttribute("aria-selected","true"),this._addActiveClasses(i),this._removeHideClasses(i),o.forEach((e=>{e.removeAttribute("aria-selected"),this._removeActiveClasses(e)})),n.forEach((e=>{this._removeActiveClasses(e),this._addHideClasses(e)}))}_clampIndex(e){return h(e,0,this.contentTargets.length-1)}_setMinHeight(){let e=0;this.contentTargets.forEach((t=>{let s=t.hasAttribute("tab-hidden");s&&this._removeHideClasses(t);let i=t.offsetHeight;i>e&&(e=i),s&&this._addHideClasses(t)})),this.contentTargets.forEach((t=>t.style.minHeight=e+"px"))}_addHideClasses(e=this.el){e.setAttribute("tab-hidden","true"),this.hasHideClass?e.classList.add(...this._hideClasses):e.classList.add(...this._defaultHideClasses)}_removeHideClasses(e=this.el){e.removeAttribute("tab-hidden"),this.hasHideClass?e.classList.remove(...this._hideClasses):e.classList.remove(...this._defaultHideClasses)}_addActiveClasses(e=this.el){this.hasActiveClass?e.classList.add(...this._activeClasses):e.classList.add(...this._defaultActiveClasses)}_removeActiveClasses(e=this.el){this.hasActiveClass?e.classList.remove(...this._activeClasses):e.classList.remove(...this._defaultActiveClasses)}}o($s,"values",{currentTab:Number,equalize:Boolean}),o($s,"targets",["link","content"]),o($s,"classes",["active","hide"]);class qs extends Ee{connect(){if(!this.hasInsertValue)throw new Error("`insert` value was not specified");requestAnimationFrame((()=>{this.hasImmediateValue&&this.immediateValue&&this.execute()}))}execute(e){null==e||e.preventDefault();let t=this.el,s=document.querySelector(this.targetValue);if(null==s)return void this.dispatch(t,"teleport:error");let i=t.cloneNode(!0);switch(this.cleanup(i),this.insertValue){case"beforebegin":case"beforeend":case"afterend":case"afterbegin":s.insertAdjacentHTML(this.insertValue,i.outerHTML);break;case"replaceOuter":s.outerHTML=i.outerHTML;break;case"replaceInner":s.innerHTML=i.outerHTML;break;case"prepend":s.insertAdjacentHTML("afterbegin",i.outerHTML);break;case"append":s.insertAdjacentHTML("beforeend",i.outerHTML);break;default:throw new Error("`insert` value was not specified")}t.remove()}}o(qs,"values",{target:String,insert:String,immediate:Boolean});class Us extends Ee{constructor(){super(...arguments),o(this,"_previousState",{})}get _value(){if(this.hasValueValue)return this.valueValue;throw new Error("Expected `valueValue` to be present")}get _attribute(){if(this.hasAttributeValue)return this.attributeValue;throw new Error("Expected `attributeValue` to be present")}get _seconds(){if(this.hasSecondsValue)return 1e3*this.secondsValue;throw new Error("Expected `secondsValue` to be present")}initialize(){this.setState=this.setState.bind(this),this.removeState=this.removeState.bind(this)}connect(){this.setState(),st(this,this.removeState,this._seconds)}disconnect(){this.removeState()}setState(){this._previousState[this._attribute]=l(this.el,this._attribute),c(this.el,this._attribute,this.valueValue)}removeState(){c(this.el,this._attribute,this._previousState[this._attribute])}}function zs(e,t,s,i,r="temporary-state"){var n;e.dataset.controller&&(null==(n=e.dataset.controller)?void 0:n.includes(r))||(e.dataset.controller=(e.dataset.controller||` ${r} `).trim().replaceAll(" "," ")),e[u(`${r}-attribute-value`)]=t,e[u(`${r}-seconds-value`)]=i.toString()}function Ks(e,t,s){zs(e,"className",0,s)}o(Us,"values",{attribute:String,seconds:Number,value:String});class Ws extends be{get _duration(){return d(this._timestamp)?p({start:this._timestamp,end:new Date}):p({start:new Date,end:this._timestamp})}get _nextUpdate(){let e=this._duration;return e.years&&e.years>0||e.months&&e.months>0||e.days&&e.days>0?null:e.hours&&e.hours>0?18e5:3e4}timestampValueChanged(){this._timestamp=m(1e3*this.timestampValue)}initialize(){this._update=this._update.bind(this)}connect(){if(!this.hasTimestampValue)throw new Error("Expected `timestampValue` to be present");this._update()}_update(){this.el.innerHTML=g(this._timestamp,{addSuffix:!0,includeSeconds:!0}),this._nextUpdate&&st(this,this._update,this._nextUpdate)}}o(Ws,"values",{timestamp:Number});class Js extends be{connect(){requestAnimationFrame((()=>{st(this,this._timeout,1e3*this.secondsValue)}))}_timeout(){this.dispatch(this.el,"timeout")}}o(Js,"values",{seconds:Number});class Ys extends be{connect(){if(!this.hasClassValue)throw new Error("data-toggle-class-class-value must not be empty");(this.hasMouseEnterValue||this.hasMouseLeaveValue)&&((e,t={})=>{const s=new yt(e,t);s.observe,s.unobserve})(this),this.hasClickAwayValue&&this.clickAwayValue&&gt(this),requestAnimationFrame((()=>{this.hasInitialValue&&("on"===this.initialValue?this.toggleTargets.forEach((e=>this._elementOn(e))):this.toggleTargets.forEach((e=>this._elementOff(e))))}))}clickOutside(){this.toggleTargets.forEach((e=>{this._elementWasToggled(e)&&(this._elementToggleStatus(e),this._elementToggle(e))}))}mouseEnter(){if(this.hasMouseEnterValue)switch(this.mouseEnterValue){case"on":this.on();break;case"off":this.off();break;case"toggle":this.toggle()}return{}}mouseLeave(){if(this.hasMouseLeaveValue)switch(this.mouseLeaveValue){case"on":this.on();break;case"off":this.off();break;case"toggle":this.toggle()}return{}}on(e){this.toggleTargets.forEach((e=>{this._elementToggleStatus(e),this._elementOn(e)}))}off(e){this.toggleTargets.forEach((e=>{this._elementToggleStatus(e),this._elementOff(e)}))}toggle(e){this.toggleTargets.forEach((e=>{this._elementToggleStatus(e),this._elementToggle(e)}))}_elementWasToggled(e){return"true"==e.dataset.toggled}_elementToggleStatus(e){this._elementWasToggled(e)?delete e.dataset.toggled:e.dataset.toggled="true"}_elementToggle(e){this.classValue.split(" ").forEach((t=>e.classList.toggle(t)))}_elementOn(e){this.classValue.split(" ").forEach((t=>e.classList.toggle(t,!0)))}_elementOff(e){this.classValue.split(" ").forEach((t=>e.classList.toggle(t,!1)))}}o(Ys,"targets",["toggle"]),o(Ys,"values",{class:String,mouseEnter:String,mouseLeave:String,clickAway:Boolean,initial:String});class Zs extends be{get _collapsedClasses(){return this.hasCollapsedClass?this.collapsedClass.split(" "):this._defaultCollapsedClasses}get _defaultCollapsedClasses(){return["collapsed"]}get _activeClasses(){return this.hasActiveClass?this.activeClass.split(" "):this._defaultActiveClasses}get _defaultActiveClasses(){return["active"]}initialize(){this._nodeClicked=this._nodeClicked.bind(this)}connect(){this._setup(),wt(this,{subtree:!0,childList:!0})}disconnect(){this._teardown()}_setup(){this._setupNode(this.el)}_setupNode(e){const t=e=>{let t=e.parentElement;t&&(this._nodeActive(t)||this._hideNode(t),t.removeEventListener("click",this._nodeClicked),t.addEventListener("click",this._nodeClicked))};"UL"!==e.tagName&&"OL"!==e.tagName||t(e),e.querySelectorAll("ul, ol").forEach((e=>t(e)))}_teardown(){this.el.querySelectorAll("ul, ol, li").forEach((e=>this._teardownNode(e)))}_teardownNode(e){[e,...Array.from(e.querySelectorAll("ul, ol, li"))].forEach((e=>{e.removeEventListener("click",this._nodeClicked),this._removeActiveClasses(e),this._removeCollapsedClasses(e)}))}_nodeClicked(e){e&&e.stopImmediatePropagation();let t=e.target;t&&this._hasNested(t)&&(this._nodeActive(t)?this._hideNode(t):this._showNode(t))}_nodeActive(e){return this._activeClasses.every((t=>e.classList.contains(t)))}_showNode(e){this._removeCollapsedClasses(e),this._addActiveClasses(e)}_hideNode(e){this._removeActiveClasses(e),this._addCollapsedClasses(e)}_hasNested(e){return e.querySelectorAll("ul, ol").length>0}mutate(e){for(const t of e)"childList"===t.type&&(Array.from(t.addedNodes||[]).forEach((e=>this._setupNode(e))),Array.from(t.removedNodes||[]).forEach((e=>this._teardownNode(e))))}_addCollapsedClasses(e=this.el){this.hasCollapsedClass?e.classList.add(...this._collapsedClasses):e.classList.add(...this._defaultCollapsedClasses)}_removeCollapsedClasses(e=this.el){this.hasCollapsedClass?e.classList.remove(...this._collapsedClasses):e.classList.remove(...this._defaultCollapsedClasses)}_addActiveClasses(e=this.el){this.hasActiveClass?e.classList.add(...this._activeClasses):e.classList.add(...this._defaultActiveClasses)}_removeActiveClasses(e=this.el){this.hasActiveClass?e.classList.remove(...this._activeClasses):e.classList.remove(...this._defaultActiveClasses)}}o(Zs,"classes",["active","collapsed"]);class Xs extends be{toggle(e){null==e||e.preventDefault();let t=this._getFrame().src;null==t||t!==this._getSrc()?this._setSrc():this._clear()}setSrc(e){null==e||e.preventDefault(),this._setSrc()}clear(e){null==e||e.preventDefault(),this._clear()}_setSrc(){let e=this._getFrame();this.hasLoadingMessageValue&&(e.innerHTML=this.loadingMessageValue),e.src=this._getSrc()}_clear(){let e=this._getFrame();e.src="",e.innerHTML=""}_getFrame(){let e=document.getElementById(`${this.frameIdValue}`);if(null==e)throw new Error(`Could not find frame with ID '${this.frameIdValue}'`);if(Pe(e))return e;throw new Error(`Element targeted by ID '${this.frameIdValue}'`)}_getSrc(){let e=this.el;if(this.hasSrcValue)return this.srcValue;if(Fe(e))return e.href;throw new Error("No link given to drive frame to")}}o(Xs,"values",{frameId:String,src:String,loadingMessage:String});class Gs extends be{get _poll(){return!!this.hasPollValue&&this.pollValue}connect(){let e=this.el;if(!Pe(e))throw new Error("Expected controller to be mounted on a <turbo-frame> element.");if(e.src)throw new Error("The provided <turbo-frame> element has no `src` attribute.");this._poll&&requestAnimationFrame((()=>st(this,this.refresh,this.intervalValue)))}refresh(e){null==e||e.preventDefault();let t=this.el;t.src=t.src}}o(Gs,"values",{interval:Number,poll:Boolean});class Qs extends be{connect(){et(this,window,["focus","blur"],this._handleVisibility),Qe(this,document,"visibilitychange",this._handleVisibility),requestAnimationFrame((()=>{this._handleVisibility()}))}appear(){this.dispatch(this.el,"user-focus:active")}away(){this.dispatch(this.el,"user-focus:away")}_handleVisibility(){this._documentIsActive()?this.appear():this.away()}_documentIsActive(){return"visible"==document.visibilityState&&document.hasFocus()}}class ei extends be{get _maxMessage(){return this.hasMaxMessageValue?this.maxMessageValue:`Value must be less than ${this.maxValue}`}get _minMessage(){return this.hasMinMessageValue?this.minMessageValue:`Value must be greater than ${this.minValue}`}get _warningHideClasses(){return this.warningHideClass.split(" ")}get _defaultWarningHideClasses(){return["hide"]}get _inputWarningClasses(){return this.inputWarningClass.split(" ")}get _defaultInputWarningClasses(){return[""]}connect(){this._addWarningHideClasses(this.warningTarget),Qe(this,this.inputTarget,"input",this._check),this._check()}_check(){this.hasMinValue&&Number.parseFloat(this.inputTarget.value)<this.minValue?(this._removeWarningHideClasses(this.warningTarget),this._addInputWarningClasses(this.inputTarget),this.warningTarget.innerText=this._minMessage):this.hasMaxValue&&Number.parseFloat(this.inputTarget.value)>this.maxValue?(this._removeWarningHideClasses(this.warningTarget),this._addInputWarningClasses(this.inputTarget),this.warningTarget.innerText=this._maxMessage):(this._addWarningHideClasses(this.warningTarget),this._removeInputWarningClasses(this.inputTarget),this.warningTarget.innerText="")}_addWarningHideClasses(e=this.el){this.hasWarningHideClass?e.classList.add(...this._warningHideClasses):e.classList.add(...this._defaultWarningHideClasses)}_removeWarningHideClasses(e=this.el){this.hasWarningHideClass?e.classList.remove(...this._warningHideClasses):e.classList.remove(...this._defaultWarningHideClasses)}_addInputWarningClasses(e=this.el){this.hasInputWarningClass?e.classList.add(...this._inputWarningClasses):e.classList.add(...this._defaultInputWarningClasses)}_removeInputWarningClasses(e=this.el){this.hasInputWarningClass?e.classList.remove(...this._inputWarningClasses):e.classList.remove(...this._defaultInputWarningClasses)}}o(ei,"classes",["inputWarning","warningHide"]),o(ei,"targets",["input","warning"]),o(ei,"values",{max:Number,min:Number,minMessage:String,maxMessage:String});class ti extends be{get _errorClasses(){return this.errorClass.split(" ")}get _defaultErrorClasses(){return[]}connect(){this._updateWordCount(),Qe(this,this.inputTarget,"input",this._updateWordCount)}_updateWordCount(){let e=0,t=this.inputTarget.value.match(/\S+/g);e=t&&t.length||0,this.outputTarget.innerText=e.toString(),this.hasErrorClass&&(this._isValidCount(e)?this._removeErrorClasses(this.outputTarget):this._addErrorClasses(this.outputTarget))}_addErrorClasses(e=this.el){this.hasErrorClass?e.classList.add(...this._errorClasses):e.classList.add(...this._defaultErrorClasses)}_removeErrorClasses(e=this.el){this.hasErrorClass?e.classList.remove(...this._errorClasses):e.classList.remove(...this._defaultErrorClasses)}_isValidCount(e){let t=0,s=99999;return this.hasMinValue&&(t=this.minValue),this.hasMaxValue&&(s=this.maxValue),e>=t&&e<=s}}o(ti,"targets",["input","output"]),o(ti,"values",{min:Number,max:Number}),o(ti,"classes",["error"]);export{ot as AnchorSpyController,lt as AsyncBlockController,ct as AutoSubmitFormController,Tt as AutosizeController,kt as BackLinkController,be as BaseController,Vt as CharCountController,At as CheckboxDisableInputsController,St as CheckboxEnableInputsController,xt as CheckboxSelectAllController,Ot as ClipboardController,Mt as ClockController,Lt as ConfirmController,Nt as ConfirmNavigationController,Dt as CountdownController,It as DebugController,Pt as DetectDirtyController,Bt as DetectDirtyFormController,Ht as DisableWithController,Rt as DismissableController,qt as DurationController,Ut as ElementSaveController,zt as EmptyDomController,Kt as EnableInputsController,Ee as EphemeralController,je as EventBus,Wt as FallbackImageController,Jt as FocusStealController,Yt as FormRcController,Zt as FormSaveController,Xt as IntersectionController,Gt as IntervalController,Qt as LazyBlockController,vs as LightboxImageController,bs as LimitedSelectionCheckboxesController,at as LoadBlockController,ys as MediaPlayerController,_s as NavigateFormErrorsController,ws as NestedFormController,Es as PasswordConfirmController,Cs as PasswordPeekController,Ts as PollBlockController,ks as PrefetchController,Vs as PresenceController,Ss as PrintButtonController,As as PrintController,xs as RemoteFormController,$t as RemoveController,Ms as ResponsiveIframeBodyController,Os as ResponsiveIframeWrapperController,Ls as ScrollContainerController,Ns as ScrollIntoFocusController,Ds as ScrollToBottomController,Is as ScrollToController,Ps as ScrollToTopController,js as SelfDestructController,Bs as StickyController,Fs as SyncInputsController,Hs as TableSortController,Rs as TableTruncateController,$s as TabsController,qs as TeleportController,Us as TemporaryStateController,Ws as TimeDistanceController,Js as TimeoutController,Ys as ToggleClassController,Zs as TreeViewController,Xs as TurboFrameRCController,Gs as TurboFrameRefreshController,Qs as UserFocusController,ei as ValueWarnController,ti as WordCountController,Ks as applyTemporaryClass,zs as applyTemporaryState,Ke as createHiddenButton,We as createHiddenInput,Ie as getScrollParent,Je as insertElement,Ze as insertHiddenButton,Ye as insertHiddenInput,jt as isDirty,Ft as isFormDirty,Pe as isTurboFrame,Ge as requestReset,Xe as requestSubmit,Ae as scrollAbsoluteBottom,Se as scrollAbsoluteLeft,xe as scrollAbsoluteRight,Ve as scrollAbsoluteTop,Me as scrollDown,Le as scrollLeft,Ne as scrollRight,ke as scrollToElement,Oe as scrollUp,Qe as useEventListener,et as useEventListeners,nt as useInjectedElement,it as useInjectedFragment,rt as useInjectedHTML,tt as useInterval,st as useTimeout};
1
+ var __defProp = Object.defineProperty;
2
+ var __getOwnPropSymbols = Object.getOwnPropertySymbols;
3
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
4
+ var __propIsEnum = Object.prototype.propertyIsEnumerable;
5
+ var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
6
+ var __spreadValues = (a, b) => {
7
+ for (var prop in b || (b = {}))
8
+ if (__hasOwnProp.call(b, prop))
9
+ __defNormalProp(a, prop, b[prop]);
10
+ if (__getOwnPropSymbols)
11
+ for (var prop of __getOwnPropSymbols(b)) {
12
+ if (__propIsEnum.call(b, prop))
13
+ __defNormalProp(a, prop, b[prop]);
14
+ }
15
+ return a;
16
+ };
17
+ var __publicField = (obj, key, value) => {
18
+ __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
19
+ return value;
20
+ };
21
+ import { Controller } from "stimulus";
22
+ import { camelCase, debounce, upperFirst, clamp, get, set } from "lodash-es";
23
+ import { isPast, intervalToDuration, formatDuration, toDate, formatDistanceToNow } from "date-fns";
24
+ function logProperty(prop) {
25
+ switch (prop) {
26
+ case "application":
27
+ case "el":
28
+ case "element":
29
+ case "constructor":
30
+ case "initialize":
31
+ case "log":
32
+ case "logEvent":
33
+ case "dispatch":
34
+ case "data":
35
+ case "valueDescriptorMap":
36
+ case "mutate":
37
+ case "identifier":
38
+ return false;
39
+ }
40
+ if (/^_.*?$/.test(prop)) {
41
+ return false;
42
+ }
43
+ if (/^.*?Target(s)?$/.test(prop)) {
44
+ return false;
45
+ }
46
+ if (/^.*?Value$/.test(prop)) {
47
+ return false;
48
+ }
49
+ if (/^.*?ValueChanged$/.test(prop)) {
50
+ return false;
51
+ }
52
+ if (/^.*?Class$/.test(prop)) {
53
+ return false;
54
+ }
55
+ if (/^.*?Classes$/.test(prop)) {
56
+ return false;
57
+ }
58
+ if (/^.*?ClassesPresent$/.test(prop)) {
59
+ return false;
60
+ }
61
+ return true;
62
+ }
63
+ function log(controller, functionName, args = {}) {
64
+ if (!controller.application.debug) {
65
+ return;
66
+ }
67
+ let logger = console;
68
+ logger.groupCollapsed(`%c${controller.identifier} %c#${functionName}`, "color: #3B82F6", "color: unset");
69
+ logger.log(__spreadValues({
70
+ element: controller.element,
71
+ controller
72
+ }, args));
73
+ logger.groupEnd();
74
+ }
75
+ function warn(controller, warning, args = {}) {
76
+ if (!controller.application.debug) {
77
+ return;
78
+ }
79
+ let logger = console;
80
+ logger.groupCollapsed(`%c${controller.identifier} %c#${warning}`, "color: F39B1AFF", "color: unset");
81
+ logger.warn(__spreadValues({
82
+ element: controller.element,
83
+ controller
84
+ }, args));
85
+ logger.groupEnd();
86
+ }
87
+ function logEvent(controller, eventName, event, element) {
88
+ if (!controller.application.debug) {
89
+ return;
90
+ }
91
+ let logger = console;
92
+ logger.groupCollapsed(`%c${controller.identifier} %c${eventName}%c`, "color: #3B82F6", "color: #0be000", "color: unset");
93
+ logger.log({ element });
94
+ logger.groupEnd();
95
+ }
96
+ class BaseController extends Controller {
97
+ constructor(context) {
98
+ super(context);
99
+ if (!this.application.debug) {
100
+ return this;
101
+ }
102
+ return new Proxy(this, {
103
+ get: (obj, prop) => {
104
+ let returnVal = Reflect.get(obj, prop);
105
+ let self = this;
106
+ if (logProperty(prop.toString())) {
107
+ if (typeof returnVal == "function") {
108
+ return new Proxy(returnVal, {
109
+ apply(target, thisArg, argArray) {
110
+ log(self, prop.toString(), {
111
+ args: argArray
112
+ });
113
+ return Reflect.apply(target, thisArg, argArray);
114
+ }
115
+ });
116
+ } else {
117
+ log(this, prop.toString());
118
+ }
119
+ }
120
+ return returnVal;
121
+ }
122
+ });
123
+ }
124
+ get el() {
125
+ return this.element;
126
+ }
127
+ get isTurboPreview() {
128
+ return document.documentElement.hasAttribute("data-turbo-preview") || document.documentElement.hasAttribute("data-turbolinks-preview");
129
+ }
130
+ get isTurbolinksPreview() {
131
+ return this.isTurboPreview;
132
+ }
133
+ get csrfToken() {
134
+ return this.metaValue("csrf-token");
135
+ }
136
+ metaValue(name) {
137
+ const element = document.head.querySelector(`meta[name="${name}"]`);
138
+ return (element == null ? void 0 : element.getAttribute("content")) || null;
139
+ }
140
+ dispatchEvent(element, eventName, options = {}) {
141
+ this.dispatchEvent(element, eventName, options);
142
+ }
143
+ }
144
+ class EphemeralController extends BaseController {
145
+ _cleanupSelf() {
146
+ this.cleanup(this.el);
147
+ }
148
+ cleanup(element) {
149
+ var _a, _b, _c;
150
+ element.dataset.controller = ((_a = element.dataset.controller) == null ? void 0 : _a.replaceAll(new RegExp(`(\\s|^)${this.identifier}(\\s|$)`, "g"), "")) || "";
151
+ if (element.dataset.controller == "") {
152
+ delete element.dataset.controller;
153
+ }
154
+ let substringIdentifierValueRegex = new RegExp(`(\\s|^)${this.identifier}\\..+?(\\s|$)`, "g");
155
+ element.dataset.target = ((_b = element.dataset.target) == null ? void 0 : _b.replaceAll(substringIdentifierValueRegex, "")) || "";
156
+ delete element.dataset[camelCase(`${this.identifier}-target`)];
157
+ if (element.dataset.target == "") {
158
+ delete element.dataset.target;
159
+ }
160
+ element.dataset.action = ((_c = element.dataset.target) == null ? void 0 : _c.replaceAll(substringIdentifierValueRegex, "")) || "";
161
+ delete element.dataset[camelCase(`${this.identifier}-action`)];
162
+ if (element.dataset.action == "") {
163
+ delete element.dataset.action;
164
+ }
165
+ let values = this.constructor.values;
166
+ if (values) {
167
+ Object.keys(values).forEach((val) => delete element.dataset[camelCase(`${this.identifier}-${val}-value`)]);
168
+ }
169
+ let classes = this.constructor.classes;
170
+ if (classes) {
171
+ Object.keys(classes).forEach((val) => delete element.dataset[camelCase(`${this.identifier}-${val}-class`)]);
172
+ }
173
+ }
174
+ }
175
+ const smoothSupported = "scrollBehavior" in document.documentElement.style;
176
+ let smoothPolyfilled;
177
+ async function scrollToElement(element, { behavior = "smooth", block = "start", inline = "nearest" } = {}) {
178
+ if (behavior == "smooth" && !smoothSupported) {
179
+ await polyfillSmooth();
180
+ }
181
+ element.scrollIntoView({ behavior, block, inline });
182
+ }
183
+ async function scrollAbsoluteTop(element, { behavior = "smooth" } = {}) {
184
+ if (behavior == "smooth" && !smoothSupported) {
185
+ await polyfillSmooth();
186
+ }
187
+ element.scrollTo({ top: 0, left: 0, behavior });
188
+ }
189
+ async function scrollAbsoluteBottom(element, { behavior = "smooth" } = {}) {
190
+ if (behavior == "smooth" && !smoothSupported) {
191
+ await polyfillSmooth();
192
+ }
193
+ if (element == window) {
194
+ element.scrollTo({ top: document.body.scrollHeight, left: 0, behavior });
195
+ } else {
196
+ element.scrollTo({ top: element.scrollHeight, left: 0, behavior });
197
+ }
198
+ }
199
+ async function scrollAbsoluteLeft(element, { behavior = "smooth" } = {}) {
200
+ if (behavior == "smooth" && !smoothSupported) {
201
+ await polyfillSmooth();
202
+ }
203
+ element.scrollTo({ left: 0, behavior });
204
+ }
205
+ async function scrollAbsoluteRight(element, { behavior = "smooth" } = {}) {
206
+ if (behavior == "smooth" && !smoothSupported) {
207
+ await polyfillSmooth();
208
+ }
209
+ if (element == window) {
210
+ element.scrollTo({ left: document.body.scrollWidth, behavior });
211
+ } else {
212
+ element.scrollTo({ left: element.scrollWidth, behavior });
213
+ }
214
+ }
215
+ async function scrollUp(element, amount, { behavior = "smooth" } = {}) {
216
+ if (behavior == "smooth" && !smoothSupported) {
217
+ await polyfillSmooth();
218
+ }
219
+ element.scrollBy({ top: -amount, left: 0, behavior });
220
+ }
221
+ async function scrollDown(element, amount, { behavior = "smooth" } = {}) {
222
+ if (behavior == "smooth" && !smoothSupported) {
223
+ await polyfillSmooth();
224
+ }
225
+ element.scrollBy({ top: amount, left: 0, behavior });
226
+ }
227
+ async function scrollLeft(element, amount, { behavior = "smooth" } = {}) {
228
+ if (behavior == "smooth" && !smoothSupported) {
229
+ await polyfillSmooth();
230
+ }
231
+ element.scrollBy({ top: 0, left: -amount, behavior });
232
+ }
233
+ async function scrollRight(element, amount, { behavior = "smooth" } = {}) {
234
+ if (behavior == "smooth" && !smoothSupported) {
235
+ await polyfillSmooth();
236
+ }
237
+ element.scrollBy({ top: 0, left: amount, behavior });
238
+ }
239
+ async function polyfillSmooth() {
240
+ const { polyfill } = await import(
241
+ /* webpackChunkName: "smoothscroll-polyfill" */
242
+ "smoothscroll-polyfill"
243
+ );
244
+ if (smoothPolyfilled) {
245
+ return;
246
+ }
247
+ smoothPolyfilled = true;
248
+ polyfill();
249
+ }
250
+ function getScrollParent(node) {
251
+ if (!node) {
252
+ return null;
253
+ }
254
+ if (node == document.body) {
255
+ return window;
256
+ }
257
+ const overflowY = getComputedStyle(node).overflowY;
258
+ const isScrollable = overflowY !== "visible" && overflowY !== "hidden";
259
+ if (isScrollable && node.scrollHeight >= node.clientHeight) {
260
+ return node;
261
+ }
262
+ return getScrollParent(node.parentElement) || document.body;
263
+ }
264
+ function isTurboFrame(element) {
265
+ return element.nodeName == "TURBO-FRAME";
266
+ }
267
+ function mitt(n) {
268
+ return { all: n = n || new Map(), on: function(t, e) {
269
+ var i = n.get(t);
270
+ i ? i.push(e) : n.set(t, [e]);
271
+ }, off: function(t, e) {
272
+ var i = n.get(t);
273
+ i && (e ? i.splice(i.indexOf(e) >>> 0, 1) : n.set(t, []));
274
+ }, emit: function(t, e) {
275
+ var i = n.get(t);
276
+ i && i.slice().map(function(n2) {
277
+ n2(e);
278
+ }), (i = n.get("*")) && i.slice().map(function(n2) {
279
+ n2(t, e);
280
+ });
281
+ } };
282
+ }
283
+ const EventBus = mitt();
284
+ function isHTMLLinkElement(element) {
285
+ return element.nodeName == "LINK";
286
+ }
287
+ function isHTMLAnchorElement(element) {
288
+ return element.nodeName == "A";
289
+ }
290
+ function isHTMLFormElement(element) {
291
+ return element.nodeName == "FORM";
292
+ }
293
+ function isHTMLInputElement(element) {
294
+ return element.nodeName == "INPUT";
295
+ }
296
+ function isHTMLLabelElement(element) {
297
+ return element.nodeName == "LABEL";
298
+ }
299
+ function isHTMLTextAreaElement(element) {
300
+ return element.nodeName == "TEXTAREA";
301
+ }
302
+ function isHTMLButtonElement(element) {
303
+ return element.nodeName == "BUTTON";
304
+ }
305
+ function isHTMLSelectElement(element) {
306
+ return element.nodeName == "SELECT";
307
+ }
308
+ function isHTMLImageElement(element) {
309
+ return element.nodeName == "IMG";
310
+ }
311
+ function isHTMLButtonInputElement(element) {
312
+ return element.nodeName == "INPUT" && element.type == "button";
313
+ }
314
+ function isHTMLSubmitInputElement(element) {
315
+ return element.nodeName == "INPUT" && element.type == "submit";
316
+ }
317
+ function isHTMLResetInputElement(element) {
318
+ return element.nodeName == "INPUT" && element.type == "reset";
319
+ }
320
+ function isHTMLButtonButtonElement(element) {
321
+ return element.nodeName == "BUTTON" && element.type == "button";
322
+ }
323
+ function isHTMLSubmitButtonElement(element) {
324
+ return element.nodeName == "BUTTON" && element.type == "submit";
325
+ }
326
+ function isHTMLResetButtonElement(element) {
327
+ return element.nodeName == "BUTTON" && element.type == "reset";
328
+ }
329
+ function isTypeOfResetButtonElement(element) {
330
+ return isHTMLResetButtonElement(element) || isHTMLResetInputElement(element);
331
+ }
332
+ function isTypeOfSubmitButtonElement(element) {
333
+ return isHTMLSubmitButtonElement(element) || isHTMLSubmitInputElement(element);
334
+ }
335
+ function isTypeOfButtonableElement(element) {
336
+ return isTypeOfResetButtonElement(element) || isTypeOfSubmitButtonElement(element) || isHTMLButtonButtonElement(element);
337
+ }
338
+ function isElementCheckable(element) {
339
+ return isHTMLInputElement(element) && (element.type === "radio" || element.type === "checkbox");
340
+ }
341
+ function isTypeOfFormInputElement(element) {
342
+ return isHTMLInputElement(element) || isHTMLSelectElement(element) || isHTMLTextAreaElement(element);
343
+ }
344
+ function createHiddenButton(type) {
345
+ let button = document.createElement("button");
346
+ button.type = type;
347
+ button.style.display = "none";
348
+ button.dataset.sythentic = "true";
349
+ return button;
350
+ }
351
+ function createHiddenInput(name, value) {
352
+ let input = document.createElement("input");
353
+ input.type = "hidden";
354
+ input.name = name;
355
+ input.value = value;
356
+ return input;
357
+ }
358
+ function insertElement(targetElement, insertPosition, element) {
359
+ let createdElement = targetElement.insertAdjacentElement(insertPosition, element);
360
+ if (!createdElement) {
361
+ throw new Error(`Failed to insert element ${element.nodeName} into ${targetElement.nodeName}`);
362
+ }
363
+ return createdElement;
364
+ }
365
+ function insertHiddenInput(name, value, targetElement, insertPosition) {
366
+ return insertElement(targetElement, insertPosition, createHiddenInput(name, value));
367
+ }
368
+ function insertHiddenButton(type, targetElement, insertPosition) {
369
+ return insertElement(targetElement, insertPosition, createHiddenButton(type));
370
+ }
371
+ function getAllRadiosInGroup(radio) {
372
+ let parent = radio.form || document;
373
+ return Array.from(parent.querySelectorAll(`input[type="radio"][name="${radio.name}"]`));
374
+ }
375
+ function getOtherRadiosInGroup(radio) {
376
+ return getAllRadiosInGroup(radio).filter((r) => r !== radio);
377
+ }
378
+ function isElementInViewport(el) {
379
+ const rect = el.getBoundingClientRect();
380
+ const windowHeight = window.innerHeight || document.documentElement.clientHeight;
381
+ const windowWidth = window.innerWidth || document.documentElement.clientWidth;
382
+ const vertInView = rect.top <= windowHeight && rect.top + rect.height >= 0;
383
+ const horInView = rect.left <= windowWidth && rect.left + rect.width >= 0;
384
+ return vertInView && horInView;
385
+ }
386
+ function requestSubmit(form) {
387
+ if (form.requestSubmit) {
388
+ form.requestSubmit();
389
+ } else {
390
+ let button = form.querySelector('button[type="submit"]');
391
+ if (!button) {
392
+ button = insertHiddenButton("submit", form, "beforeend");
393
+ }
394
+ button.click();
395
+ }
396
+ }
397
+ function requestReset(form) {
398
+ let button = form.querySelector('button[type="reset"]');
399
+ if (!button) {
400
+ button = insertHiddenButton("reset", form, "beforeend");
401
+ }
402
+ button.click();
403
+ }
404
+ function wrapArray(x) {
405
+ return Array.isArray(x) ? x : [x];
406
+ }
407
+ function useMixin(controller, setup, teardown) {
408
+ const controllerDisconnect = controller.disconnect.bind(controller);
409
+ setup();
410
+ Object.assign(controller, {
411
+ disconnect() {
412
+ teardown();
413
+ controllerDisconnect();
414
+ }
415
+ });
416
+ return controllerDisconnect;
417
+ }
418
+ function useEventListener(controller, element, eventNameOrNames, handler, opts) {
419
+ if (opts == null ? void 0 : opts.debounce) {
420
+ handler = debounce(handler.bind(controller), opts.debounce);
421
+ delete opts.debounce;
422
+ } else {
423
+ handler = handler.bind(controller);
424
+ }
425
+ let eventNames = wrapArray(eventNameOrNames);
426
+ let setup = () => eventNames.forEach((eventName) => element.addEventListener(eventName, handler, opts));
427
+ let teardown = () => eventNames.forEach((eventName) => element.removeEventListener(eventName, handler));
428
+ useMixin(controller, setup, teardown);
429
+ return { setup, teardown };
430
+ }
431
+ function useEventListeners(controller, element, eventNameOrNames, handler, opts) {
432
+ return useEventListener(controller, element, eventNameOrNames, handler, opts);
433
+ }
434
+ function useCollectionEventListener(controller, elements, eventNameOrNames, handler, opts) {
435
+ let handlers = [];
436
+ elements.forEach((el) => {
437
+ let { setup, teardown } = useEventListener(controller, el, eventNameOrNames, handler, opts);
438
+ handlers.push({ setup, teardown });
439
+ });
440
+ return [
441
+ () => handlers.forEach((h) => h.setup()),
442
+ () => handlers.forEach((h) => h.teardown())
443
+ ];
444
+ }
445
+ function useCollectionEventListeners(controller, elements, eventNameOrNames, handler, opts) {
446
+ return useCollectionEventListener(controller, elements, eventNameOrNames, handler, opts);
447
+ }
448
+ function useFullscreen(controller, el) {
449
+ let element = el || document.documentElement;
450
+ let fullscreenOpen = document.fullscreenElement !== null;
451
+ const updateFullscreenState = () => fullscreenOpen = document.fullscreenElement !== null;
452
+ const isFullscreen = () => fullscreenOpen;
453
+ const toggle = async () => fullscreenOpen ? await exit() : await enter();
454
+ let setup = () => document.addEventListener("fullscreenchange", updateFullscreenState);
455
+ let teardown = () => document.removeEventListener("fullscreenchange", updateFullscreenState);
456
+ const exit = async () => {
457
+ if (document.exitFullscreen) {
458
+ fullscreenOpen = false;
459
+ await document.exitFullscreen();
460
+ }
461
+ };
462
+ const enter = async () => {
463
+ if (fullscreenOpen) {
464
+ await exit();
465
+ }
466
+ if (element.requestFullscreen) {
467
+ await element.requestFullscreen();
468
+ fullscreenOpen = true;
469
+ }
470
+ };
471
+ useMixin(controller, setup, teardown);
472
+ return {
473
+ isFullscreen,
474
+ enter,
475
+ exit,
476
+ toggle,
477
+ teardown
478
+ };
479
+ }
480
+ function reactive(object) {
481
+ if (object === null || typeof object !== "object") {
482
+ return object;
483
+ }
484
+ for (const property in object) {
485
+ if (Object.getOwnPropertyDescriptor(object, property) == void 0) {
486
+ continue;
487
+ }
488
+ object[property] = reactive(object[property]);
489
+ }
490
+ return new Proxy(object, {
491
+ get(target, property) {
492
+ return target[property];
493
+ },
494
+ set(target, property, value) {
495
+ target[property] = reactive(value);
496
+ return true;
497
+ }
498
+ });
499
+ }
500
+ function useGeolocation(controller, options = {}, update, error) {
501
+ if (update) {
502
+ update = update.bind(controller);
503
+ }
504
+ if (error) {
505
+ error = error.bind(controller);
506
+ }
507
+ const {
508
+ enableHighAccuracy = true,
509
+ maximumAge = 3e4,
510
+ timeout = 27e3
511
+ } = options;
512
+ const isSupported = navigator && "geolocation" in navigator;
513
+ const values = reactive({
514
+ locatedAt: null,
515
+ error: null,
516
+ coords: {
517
+ accuracy: 0,
518
+ latitude: Infinity,
519
+ longitude: Infinity,
520
+ altitude: null,
521
+ altitudeAccuracy: null,
522
+ heading: null,
523
+ speed: null
524
+ },
525
+ teardown: () => {
526
+ if (watcher) {
527
+ navigator.geolocation.clearWatch(watcher);
528
+ watcher = null;
529
+ }
530
+ }
531
+ });
532
+ let setup = () => {
533
+ if (isSupported) {
534
+ watcher = navigator.geolocation.watchPosition((position) => {
535
+ values.locatedAt = position.timestamp;
536
+ values.coords = position.coords;
537
+ values.error = null;
538
+ if (update) {
539
+ update(position);
540
+ }
541
+ }, (err) => {
542
+ values.error = err;
543
+ if (error) {
544
+ error(err);
545
+ }
546
+ }, {
547
+ enableHighAccuracy,
548
+ maximumAge,
549
+ timeout
550
+ });
551
+ }
552
+ };
553
+ let watcher = null;
554
+ useMixin(controller, setup, values.teardown);
555
+ return values;
556
+ }
557
+ function useInjectedFragment(controller, targetElement, insertPosition, fragment, options = {}) {
558
+ let nodes = Array.from(fragment.childNodes);
559
+ let setup = () => {
560
+ let parent = targetElement.parentElement;
561
+ if (["beforebegin", "afterend"].includes(insertPosition) && parent == null) {
562
+ throw new Error("Cannot insert beforebegin into a node with no parent");
563
+ }
564
+ switch (insertPosition) {
565
+ case "beforeend":
566
+ targetElement.append(fragment);
567
+ break;
568
+ case "afterbegin":
569
+ targetElement.prepend(fragment);
570
+ break;
571
+ case "beforebegin":
572
+ parent.insertBefore(fragment, targetElement);
573
+ break;
574
+ case "afterend":
575
+ parent.insertBefore(fragment, targetElement);
576
+ break;
577
+ }
578
+ };
579
+ let teardown = options.cleanup ? () => nodes.forEach((node) => node.remove()) : () => void 0;
580
+ useMixin(controller, setup, teardown);
581
+ return [nodes, teardown];
582
+ }
583
+ function useInjectedHTML(controller, targetElement, insertPosition, html, options = {}) {
584
+ const fragment = document.createRange().createContextualFragment(html);
585
+ return useInjectedFragment(controller, targetElement, insertPosition, fragment, options);
586
+ }
587
+ function useInjectedElement(controller, targetElement, insertPosition, element, options = {}) {
588
+ const fragment = new DocumentFragment();
589
+ fragment.append(element);
590
+ let [nodes, teardown] = useInjectedFragment(controller, targetElement, insertPosition, fragment, options);
591
+ return [nodes[0], teardown];
592
+ }
593
+ function useInterval(controller, handler, interval) {
594
+ handler = handler.bind(controller);
595
+ let intervalHandle = null;
596
+ let setup = () => intervalHandle = setInterval(handler, interval);
597
+ let teardown = () => {
598
+ if (intervalHandle !== null) {
599
+ clearInterval(intervalHandle);
600
+ }
601
+ };
602
+ useMixin(controller, setup, teardown);
603
+ return teardown;
604
+ }
605
+ const StorageSerializers = {
606
+ boolean: {
607
+ deserialize: (v) => v === "true",
608
+ serialize: (v) => String(v),
609
+ isEmpty: (v) => v === "" || v === null
610
+ },
611
+ object: {
612
+ deserialize: (v) => JSON.parse(v),
613
+ serialize: (v) => JSON.stringify(v),
614
+ isEmpty: (v) => {
615
+ const values = Object.values(JSON.parse(v));
616
+ return values.length === 0 || values.every((v2) => v2 === "" || v2 === null);
617
+ }
618
+ },
619
+ number: {
620
+ deserialize: (v) => Number.parseFloat(v),
621
+ serialize: (v) => String(v),
622
+ isEmpty: (v) => v === "" || v === null
623
+ },
624
+ any: {
625
+ deserialize: (v) => v,
626
+ serialize: (v) => String(v),
627
+ isEmpty: (v) => v === "" || v === null
628
+ },
629
+ string: {
630
+ deserialize: (v) => v,
631
+ serialize: (v) => String(v),
632
+ isEmpty: (v) => v === "" || v === null
633
+ },
634
+ map: {
635
+ deserialize: (v) => new Map(JSON.parse(v)),
636
+ serialize: (v) => JSON.stringify(Array.from(v.entries())),
637
+ isEmpty: (v) => {
638
+ const values = Array.from(v.values());
639
+ return values.length === 0 || values.every((v2) => v2 === "" || v2 === null);
640
+ }
641
+ },
642
+ set: {
643
+ deserialize: (v) => new Set(JSON.parse(v)),
644
+ serialize: (v) => JSON.stringify(Array.from(v.entries())),
645
+ isEmpty: (v) => {
646
+ const values = Array.from(v.values());
647
+ return values.length === 0 || values.every((v2) => v2 === "" || v2 === null);
648
+ }
649
+ }
650
+ };
651
+ function useLocalStorage(controller, key, defaultValue, opts = { writeDefaults: true }) {
652
+ let type;
653
+ let { writeDefaults } = opts;
654
+ if (defaultValue == null) {
655
+ type = "any";
656
+ } else if (defaultValue instanceof Set) {
657
+ type = "set";
658
+ } else if (defaultValue instanceof Map) {
659
+ type = "map";
660
+ } else if (typeof defaultValue === "boolean") {
661
+ type = "boolean";
662
+ } else if (typeof defaultValue === "string") {
663
+ type = "string";
664
+ } else if (typeof defaultValue === "object") {
665
+ type = "object";
666
+ } else if (Array.isArray(defaultValue)) {
667
+ type = "object";
668
+ } else if (!Number.isNaN(defaultValue)) {
669
+ type = "number";
670
+ } else {
671
+ type = "any";
672
+ }
673
+ let data = reactive({
674
+ value: defaultValue
675
+ });
676
+ let storage = localStorage;
677
+ const serializer = StorageSerializers[type];
678
+ const read = () => {
679
+ const rawValue = storage.getItem(key);
680
+ if (rawValue == null) {
681
+ data.value = defaultValue;
682
+ if (writeDefaults && defaultValue !== null) {
683
+ storage.setItem(key, serializer.serialize(defaultValue));
684
+ }
685
+ } else {
686
+ data.value = serializer.deserialize(rawValue);
687
+ }
688
+ return data.value;
689
+ };
690
+ const write = (value) => {
691
+ storage.setItem(key, serializer.serialize(value));
692
+ data.value = value;
693
+ };
694
+ const clear = () => {
695
+ storage.removeItem(key);
696
+ data.value = defaultValue;
697
+ return data.value;
698
+ };
699
+ const isEmpty = () => {
700
+ let rawValue = storage.getItem(key);
701
+ return serializer.isEmpty(rawValue);
702
+ };
703
+ read();
704
+ return {
705
+ get value() {
706
+ return read();
707
+ },
708
+ set value(value) {
709
+ write(value);
710
+ },
711
+ read,
712
+ clear,
713
+ write,
714
+ isEmpty
715
+ };
716
+ }
717
+ function useTimeout(controller, handler, timeout) {
718
+ let controllerDisconnect;
719
+ let timeoutHandle = null;
720
+ handler = handler.bind(controller);
721
+ let newHandler = () => {
722
+ handler();
723
+ timeoutHandle = null;
724
+ Object.assign(controller, { disconnect: controllerDisconnect });
725
+ };
726
+ let setup = () => timeoutHandle = setTimeout(newHandler, timeout);
727
+ let teardown = () => {
728
+ if (timeoutHandle !== null) {
729
+ clearTimeout(timeoutHandle);
730
+ timeoutHandle = null;
731
+ }
732
+ };
733
+ controllerDisconnect = useMixin(controller, setup, teardown);
734
+ return teardown;
735
+ }
736
+ function useTemporaryContent(controller, target, content, timeout, teardownCallback) {
737
+ const setContent = (element, text) => {
738
+ if (isHTMLInputElement(element)) {
739
+ element.value = text;
740
+ } else {
741
+ element.textContent = text;
742
+ }
743
+ };
744
+ const getContent = (element) => {
745
+ return isHTMLInputElement(element) ? element.value : element.innerHTML;
746
+ };
747
+ let cleanupTimeout = () => void 0;
748
+ let originalText = getContent(target);
749
+ const teardown = () => {
750
+ setContent(target, originalText);
751
+ cleanupTimeout();
752
+ if (teardownCallback) {
753
+ teardownCallback.call(controller);
754
+ }
755
+ };
756
+ const setup = () => {
757
+ setContent(target, content);
758
+ if (timeout !== void 0) {
759
+ cleanupTimeout = useTimeout(controller, teardown, timeout);
760
+ }
761
+ };
762
+ useMixin(controller, setup, teardown);
763
+ return {
764
+ teardown,
765
+ update(newContent) {
766
+ setContent(target, newContent);
767
+ }
768
+ };
769
+ }
770
+ async function fetchRetry(n, input, init) {
771
+ try {
772
+ return await fetch(input, init);
773
+ } catch (err) {
774
+ if (n === 1) {
775
+ throw err;
776
+ }
777
+ return await fetchRetry(n - 1, input, init);
778
+ }
779
+ }
780
+ class LoadBlockController extends BaseController {
781
+ get _errorMessage() {
782
+ return this.hasErrorMessageValue ? this.errorMessageValue : "This content failed to load";
783
+ }
784
+ get _maxRetries() {
785
+ return this.hasMaxRetriesValue ? this.maxRetriesValue : 1;
786
+ }
787
+ connect() {
788
+ }
789
+ async loadContent(event = null) {
790
+ event == null ? void 0 : event.preventDefault();
791
+ let self = this;
792
+ let el = this.hasReplaceTarget ? this.replaceTarget : this.el;
793
+ let failure = () => {
794
+ el.replaceWith(this._errorMessage);
795
+ self.dispatchEvent(el, "ajax:error");
796
+ };
797
+ try {
798
+ let response = await fetchRetry(this._maxRetries, this.endpointValue);
799
+ if (!response.ok) {
800
+ failure();
801
+ }
802
+ let text = await response.text();
803
+ let newEl = document.createElement("div");
804
+ newEl.innerHTML = text;
805
+ if (this.hasSelectorValue) {
806
+ let selectedContent = newEl.querySelectorAll(this.selectorValue);
807
+ el.replaceWith(...selectedContent);
808
+ } else {
809
+ el.replaceWith(...newEl.children);
810
+ }
811
+ self.dispatchEvent(el, "ajax:success");
812
+ } catch (e) {
813
+ failure();
814
+ } finally {
815
+ self.dispatchEvent(el, "ajax:complete");
816
+ }
817
+ }
818
+ }
819
+ __publicField(LoadBlockController, "targets", ["replace"]);
820
+ __publicField(LoadBlockController, "values", {
821
+ endpoint: String,
822
+ errorMessage: String,
823
+ selector: String,
824
+ maxRetries: Number
825
+ });
826
+ class AsyncBlockController extends LoadBlockController {
827
+ get _errorMessage() {
828
+ return this.hasErrorMessageValue ? this.errorMessageValue : "This content failed to load";
829
+ }
830
+ async connect() {
831
+ await this.loadContent();
832
+ }
833
+ }
834
+ __publicField(AsyncBlockController, "targets", ["replace"]);
835
+ __publicField(AsyncBlockController, "values", {
836
+ endpoint: String,
837
+ errorMessage: String,
838
+ selector: String,
839
+ maxRetries: Number
840
+ });
841
+ function useIntersectionObserver(controller, handler, options) {
842
+ handler = handler.bind(controller);
843
+ let observer = new IntersectionObserver(handler, options);
844
+ let teardown = () => {
845
+ observer == null ? void 0 : observer.disconnect();
846
+ observer = null;
847
+ };
848
+ let observe = (element) => observer == null ? void 0 : observer.observe(element);
849
+ let unobserve = (element) => observer == null ? void 0 : observer.unobserve(element);
850
+ return {
851
+ observer,
852
+ teardown,
853
+ observe,
854
+ unobserve
855
+ };
856
+ }
857
+ function useIntersection(controller, element, appear, disappear, options) {
858
+ if (appear) {
859
+ appear = appear.bind(controller);
860
+ }
861
+ if (disappear) {
862
+ disappear = disappear.bind(controller);
863
+ }
864
+ let opts = options != null ? options : {};
865
+ let processEntries = (entries) => {
866
+ entries.forEach((entry) => {
867
+ if (entry.isIntersecting) {
868
+ appear && appear(entry);
869
+ } else {
870
+ disappear && disappear(entry);
871
+ }
872
+ });
873
+ };
874
+ let { observer, observe, unobserve, teardown } = useIntersectionObserver(controller, processEntries, opts);
875
+ let setup = () => observe(element);
876
+ useMixin(controller, setup, teardown);
877
+ return {
878
+ observer,
879
+ observe: () => observe(element),
880
+ unobserve: () => unobserve(element),
881
+ teardown
882
+ };
883
+ }
884
+ class LazyBlockController extends LoadBlockController {
885
+ async connect() {
886
+ let element = this.el;
887
+ if ("IntersectionObserver" in window) {
888
+ let { observe, unobserve } = useIntersection(this, element, this.appear, null, { threshold: 0.3 });
889
+ this.observe = observe;
890
+ this.unobserve = unobserve;
891
+ } else {
892
+ await this.loadContent();
893
+ }
894
+ }
895
+ async appear(entry) {
896
+ if (entry.target === this.el && entry.isIntersecting) {
897
+ await this.loadContent();
898
+ if (this.unobserve) {
899
+ this.unobserve();
900
+ }
901
+ }
902
+ }
903
+ }
904
+ class PollBlockController extends LoadBlockController {
905
+ connect() {
906
+ if (!this.hasSecondsValue) {
907
+ throw new Error("Required value `seconds` is missing");
908
+ }
909
+ requestAnimationFrame(() => {
910
+ this._timeout();
911
+ useInterval(this, this._timeout, this.secondsValue * 1e3);
912
+ });
913
+ }
914
+ async _timeout() {
915
+ await this.loadContent();
916
+ }
917
+ }
918
+ __publicField(PollBlockController, "targets", ["replace"]);
919
+ __publicField(PollBlockController, "values", {
920
+ endpoint: String,
921
+ errorMessage: String,
922
+ selector: String,
923
+ maxRetries: Number,
924
+ seconds: Number
925
+ });
926
+ class AutoSubmitFormController extends BaseController {
927
+ get _eventModes() {
928
+ if (this.hasEventModeValue) {
929
+ let modes = this.eventModeValue.split(" ").map((mode) => mode.trim());
930
+ if (modes.length === 1 && modes[0] === "debounced") {
931
+ return ["change", "input"];
932
+ }
933
+ if (!modes.every((mode) => ["change", "input"].includes(mode))) {
934
+ throw new Error(`The modeValue provided '${this.eventModeValue}' is not one of the recognised configuration options`);
935
+ }
936
+ return modes;
937
+ } else {
938
+ return ["change"];
939
+ }
940
+ }
941
+ get _debounceTimeout() {
942
+ return this.hasDebounceIntervalValue ? this.debounceIntervalValue : -1;
943
+ }
944
+ get _mode() {
945
+ if (this.hasSubmitModeValue) {
946
+ if (!["direct", "request"].includes(this.submitModeValue)) {
947
+ throw new Error(`The modeValue provided '${this.submitModeValue}' is not one of the recognised configuration options`);
948
+ }
949
+ return this.submitModeValue;
950
+ } else {
951
+ return "request";
952
+ }
953
+ }
954
+ get _cssSelector() {
955
+ let inputTypes = ["input", "textarea", "select"];
956
+ let ignore = ":not([data-no-autosubmit])";
957
+ return inputTypes.map((type) => type.concat(ignore)).join(",");
958
+ }
959
+ get inputElements() {
960
+ let subElements = Array.from(this.element.querySelectorAll(this._cssSelector));
961
+ subElements = subElements.filter((el) => !this._ancestorIsTrix(el));
962
+ return subElements;
963
+ }
964
+ connect() {
965
+ this.inputElements.forEach((el) => {
966
+ return useEventListener(this, el, this._eventModes, this.submit, { debounce: this._debounceTimeout && this._debounceTimeout > 0 ? this._debounceTimeout : void 0 });
967
+ });
968
+ }
969
+ _ancestorIsTrix(element) {
970
+ return element.closest("trix-toolbar") !== null && element.closest("trix-editor") !== null;
971
+ }
972
+ submit() {
973
+ let el = this.el;
974
+ if (this._mode == "request") {
975
+ requestSubmit(el);
976
+ } else {
977
+ el.submit();
978
+ }
979
+ }
980
+ }
981
+ __publicField(AutoSubmitFormController, "values", { submitMode: String, eventMode: String, debounceInterval: Number });
982
+ class AutosizeController extends BaseController {
983
+ connect() {
984
+ let { teardown } = useIntersection(this, this.el, this.appear);
985
+ this._unobserveIntersection = teardown;
986
+ if (!isHTMLTextAreaElement(this.el)) {
987
+ throw new Error(`Expected controller to be attached to a textarea, but was a '${this.el.tagName}'`);
988
+ }
989
+ requestAnimationFrame(() => {
990
+ this.el.style.resize = "none";
991
+ this.el.style.boxSizing = "border-box";
992
+ this._handler();
993
+ useEventListener(this, window, ["resize"], this._handler);
994
+ useEventListener(this, this.el, ["input", "change", "focus"], this._handler, { debounce: 100 });
995
+ });
996
+ }
997
+ appear(_entry) {
998
+ this.autosize(this.el);
999
+ this._unobserveIntersection();
1000
+ }
1001
+ _handler() {
1002
+ this.autosize(this.el);
1003
+ }
1004
+ autosize(element) {
1005
+ let offset = element.offsetHeight - element.clientHeight;
1006
+ element.style.height = "auto";
1007
+ element.style.height = element.scrollHeight + offset + "px";
1008
+ }
1009
+ }
1010
+ function controllerMethod(controller, methodName) {
1011
+ const method = controller[methodName];
1012
+ if (typeof method == "function") {
1013
+ return method;
1014
+ } else if (method != void 0) {
1015
+ return () => method;
1016
+ } else {
1017
+ return () => void 0;
1018
+ }
1019
+ }
1020
+ function pascalCase(str) {
1021
+ return upperFirst(camelCase(str));
1022
+ }
1023
+ function addMethodsForClassDefinition(controller, name) {
1024
+ let defaultElement = controller.element;
1025
+ let hasClass = () => controller[`has${pascalCase(name)}Class`] == true;
1026
+ let classes = () => controller[`${name}Classes`];
1027
+ let defaultClasses = () => controllerMethod(controller, `default${pascalCase(name)}Classes`).call(controller) || [];
1028
+ let classOrDefault = () => hasClass() ? classes() : defaultClasses();
1029
+ if (controller[`${name}Classes`] == void 0) {
1030
+ Object.defineProperty(controller, `${name}Classes`, {
1031
+ get: () => hasClass() ? controller[`${name}Class`].split(" ") : defaultClasses()
1032
+ });
1033
+ }
1034
+ let methods = {
1035
+ [`add${pascalCase(name)}Classes`]: (element = defaultElement) => element.classList.add(...classOrDefault()),
1036
+ [`remove${pascalCase(name)}Classes`]: (element = defaultElement) => element.classList.remove(...classOrDefault()),
1037
+ [`${name}ClassesPresent`]: (element = defaultElement) => classOrDefault().every((klass) => element.classList.contains(klass))
1038
+ };
1039
+ Object.assign(controller, methods);
1040
+ }
1041
+ function installClassMethods(controller) {
1042
+ let classes = controller.constructor.classes || [];
1043
+ classes.forEach((classDefinition) => addMethodsForClassDefinition(controller, classDefinition));
1044
+ }
1045
+ class CharCountController extends BaseController {
1046
+ connect() {
1047
+ installClassMethods(this);
1048
+ requestAnimationFrame(() => {
1049
+ useEventListener(this, this.inputTarget, "input", this._updateCharCount);
1050
+ this._updateCharCount();
1051
+ });
1052
+ }
1053
+ _updateCharCount() {
1054
+ let charCount = this.inputTarget.value.length;
1055
+ this.outputTarget.innerText = charCount.toString();
1056
+ if (this._isValidCount(charCount)) {
1057
+ this.removeErrorClasses(this.outputTarget);
1058
+ } else {
1059
+ this.addErrorClasses(this.outputTarget);
1060
+ }
1061
+ }
1062
+ _isValidCount(count) {
1063
+ let min = 0;
1064
+ let max = 99999;
1065
+ if (this.hasMinValue) {
1066
+ min = this.minValue;
1067
+ }
1068
+ if (this.hasMaxValue) {
1069
+ max = this.maxValue;
1070
+ }
1071
+ return count >= min && count <= max;
1072
+ }
1073
+ }
1074
+ __publicField(CharCountController, "targets", ["input", "output"]);
1075
+ __publicField(CharCountController, "values", { min: Number, max: Number });
1076
+ __publicField(CharCountController, "classes", ["error"]);
1077
+ class CheckboxDisableInputsController extends BaseController {
1078
+ connect() {
1079
+ this.toggle();
1080
+ }
1081
+ toggle() {
1082
+ if (this.hasDisablerTarget && this.disablerTarget.checked) {
1083
+ this.disable();
1084
+ } else {
1085
+ this.enable();
1086
+ }
1087
+ }
1088
+ disable() {
1089
+ let shouldClear = this.hasClearValue && this.clearValue;
1090
+ this.disableTargets.forEach((el, _) => {
1091
+ if (shouldClear) {
1092
+ el.value = "";
1093
+ }
1094
+ el.disabled = true;
1095
+ });
1096
+ }
1097
+ enable() {
1098
+ this.disableTargets.forEach((el, _) => {
1099
+ el.disabled = false;
1100
+ });
1101
+ }
1102
+ }
1103
+ __publicField(CheckboxDisableInputsController, "targets", ["disabler", "disable"]);
1104
+ __publicField(CheckboxDisableInputsController, "values", {
1105
+ clear: Boolean
1106
+ });
1107
+ class CheckboxEnableInputsController extends BaseController {
1108
+ connect() {
1109
+ this.toggle();
1110
+ }
1111
+ toggle() {
1112
+ if (this.hasEnablerTarget && this.enablerTarget.checked) {
1113
+ this.enable();
1114
+ } else {
1115
+ this.disable();
1116
+ }
1117
+ }
1118
+ disable() {
1119
+ let shouldClear = this.hasClearValue && this.clearValue;
1120
+ this.enableTargets.forEach((el, _) => {
1121
+ if (shouldClear) {
1122
+ el.value = "";
1123
+ }
1124
+ el.disabled = true;
1125
+ });
1126
+ }
1127
+ enable() {
1128
+ this.enableTargets.forEach((el, _) => {
1129
+ el.disabled = false;
1130
+ });
1131
+ }
1132
+ }
1133
+ __publicField(CheckboxEnableInputsController, "targets", ["enabler", "enable"]);
1134
+ __publicField(CheckboxEnableInputsController, "values", {
1135
+ clear: Boolean
1136
+ });
1137
+ class CheckboxSelectAllController extends BaseController {
1138
+ get _checked() {
1139
+ return this._enabled.filter((checkbox) => checkbox.checked);
1140
+ }
1141
+ get _enabled() {
1142
+ return this.checkboxTargets.filter((checkbox) => !checkbox.disabled && !checkbox.readOnly);
1143
+ }
1144
+ get _unchecked() {
1145
+ return this._enabled.filter((checkbox) => !checkbox.checked);
1146
+ }
1147
+ connect() {
1148
+ requestAnimationFrame(() => {
1149
+ if (!this.hasSelectAllTarget) {
1150
+ return;
1151
+ }
1152
+ useEventListener(this, this.selectAllTarget, "change", this._toggle);
1153
+ useCollectionEventListener(this, this.checkboxTargets, "change", this._refresh);
1154
+ this._refresh();
1155
+ });
1156
+ }
1157
+ _toggle(event) {
1158
+ event.preventDefault();
1159
+ let target = event.target;
1160
+ this._enabled.forEach((checkbox) => checkbox.checked = checkbox.disabled || checkbox.readOnly ? checkbox.checked : target.checked);
1161
+ }
1162
+ _refresh() {
1163
+ const checkboxesCount = this._enabled.length;
1164
+ const checkboxesCheckedCount = this._checked.length;
1165
+ this.selectAllTarget.checked = checkboxesCheckedCount > 0;
1166
+ this.selectAllTarget.indeterminate = checkboxesCheckedCount > 0 && checkboxesCheckedCount < checkboxesCount;
1167
+ }
1168
+ }
1169
+ __publicField(CheckboxSelectAllController, "targets", ["selectAll", "checkbox"]);
1170
+ class CheckboxXORController extends BaseController {
1171
+ connect() {
1172
+ useCollectionEventListener(this, this.checkboxTargets, "change", this._update);
1173
+ }
1174
+ _otherCheckboxes(el) {
1175
+ return Array.from(this.checkboxTargets).filter((field) => field !== el);
1176
+ }
1177
+ _update(event) {
1178
+ const target = event.target;
1179
+ if (!target) {
1180
+ throw new Error("No target found on event");
1181
+ }
1182
+ let others = this._otherCheckboxes(target);
1183
+ if (target.checked) {
1184
+ others.forEach((checkbox) => {
1185
+ checkbox.checked = false;
1186
+ this.dispatchEvent(this.el, "change");
1187
+ });
1188
+ }
1189
+ }
1190
+ }
1191
+ __publicField(CheckboxXORController, "targets", ["checkbox"]);
1192
+ class DetectDirtyController extends BaseController {
1193
+ get _cacheAttrName() {
1194
+ return "detect-dirty-load-value";
1195
+ }
1196
+ connect() {
1197
+ let element = this.el;
1198
+ this._cacheLoadValues();
1199
+ this._checkDirty();
1200
+ useEventListener(this, element, ["input", "change"], this._checkDirty, { debounce: 10 });
1201
+ }
1202
+ restore(event) {
1203
+ event == null ? void 0 : event.preventDefault();
1204
+ this._restoreElementFromLoadValue();
1205
+ }
1206
+ _getElementValue() {
1207
+ let element = this.el;
1208
+ return isElementCheckable(element) ? element.checked : element.value;
1209
+ }
1210
+ _getElementLoadValue() {
1211
+ let element = this.el;
1212
+ let value = element.getAttribute(this._cacheAttrName);
1213
+ if (isElementCheckable(element)) {
1214
+ return value == null ? element.defaultChecked : value == "true";
1215
+ } else if (isHTMLSelectElement(element)) {
1216
+ let options = Array.from(element.options);
1217
+ options.forEach((option) => {
1218
+ if (option.defaultSelected) {
1219
+ element.value = option.value;
1220
+ return option.value;
1221
+ }
1222
+ });
1223
+ } else if (value !== null) {
1224
+ return value;
1225
+ }
1226
+ return value;
1227
+ }
1228
+ _elementHasCachedLoadValue() {
1229
+ let element = this.el;
1230
+ return element.hasAttribute(this._cacheAttrName);
1231
+ }
1232
+ _checkDirty() {
1233
+ let element = this.el;
1234
+ if (isHTMLInputElement(element) && element.type == "radio") {
1235
+ getOtherRadiosInGroup(element).forEach((radio) => radio.removeAttribute("data-dirty"));
1236
+ }
1237
+ if (this._isElementDirty()) {
1238
+ element.setAttribute("data-dirty", "true");
1239
+ } else {
1240
+ element.removeAttribute("data-dirty");
1241
+ }
1242
+ }
1243
+ _isElementDirty() {
1244
+ return this._getElementValue() !== this._getElementLoadValue();
1245
+ }
1246
+ _restoreElementFromLoadValue() {
1247
+ let element = this.el;
1248
+ let cacheValue = element.getAttribute(this._cacheAttrName);
1249
+ if (isElementCheckable(element)) {
1250
+ element.setAttribute(this._cacheAttrName, element.checked.toString());
1251
+ element.checked = cacheValue == null ? element.defaultChecked : cacheValue == "true";
1252
+ } else if (isHTMLSelectElement(element)) {
1253
+ if (cacheValue == null) {
1254
+ let options = Array.from(element.options);
1255
+ options.forEach((option) => {
1256
+ if (option.defaultSelected) {
1257
+ element.value = option.value;
1258
+ return;
1259
+ }
1260
+ });
1261
+ } else {
1262
+ element.value = cacheValue;
1263
+ }
1264
+ } else {
1265
+ element.value = cacheValue == null ? element.defaultValue : cacheValue;
1266
+ }
1267
+ }
1268
+ _cacheLoadValues() {
1269
+ let element = this.el;
1270
+ if (!this._elementHasCachedLoadValue() && isElementCheckable(element)) {
1271
+ element.setAttribute(this._cacheAttrName, element.checked.toString());
1272
+ } else {
1273
+ element.setAttribute(this._cacheAttrName, element.value.toString());
1274
+ }
1275
+ }
1276
+ }
1277
+ function isDirty(element) {
1278
+ return element.hasAttribute("data-dirty");
1279
+ }
1280
+ class DetectDirtyFormController extends BaseController {
1281
+ get _formElements() {
1282
+ return Array.from(this.el.querySelectorAll("input, select, textarea"));
1283
+ }
1284
+ get _cacheAttrName() {
1285
+ return "detect-dirty-load-value";
1286
+ }
1287
+ connect() {
1288
+ let element = this.el;
1289
+ this._cacheLoadValues();
1290
+ this._checkDirty();
1291
+ useEventListener(this, element, ["input", "change"], this._checkDirty, { debounce: 10 });
1292
+ }
1293
+ restore(event) {
1294
+ event == null ? void 0 : event.preventDefault();
1295
+ this._formElements.forEach((element) => this._restoreElementFromLoadValue(element));
1296
+ }
1297
+ _getElementValue(element) {
1298
+ return isElementCheckable(element) ? element.checked : element.value;
1299
+ }
1300
+ _getElementLoadValue(element) {
1301
+ let value = element.getAttribute(this._cacheAttrName);
1302
+ if (isElementCheckable(element)) {
1303
+ return value == null ? element.defaultChecked : value == "true";
1304
+ } else if (isHTMLSelectElement(element)) {
1305
+ let options = Array.from(element.options);
1306
+ options.forEach((option) => {
1307
+ if (option.defaultSelected) {
1308
+ element.value = option.value;
1309
+ return option.value;
1310
+ }
1311
+ });
1312
+ } else if (value !== null) {
1313
+ return value;
1314
+ }
1315
+ return value;
1316
+ }
1317
+ _elementHasCachedLoadValue(element) {
1318
+ return element.hasAttribute(this._cacheAttrName);
1319
+ }
1320
+ _checkElementDirty(element) {
1321
+ if (isHTMLInputElement(element) && element.type == "radio") {
1322
+ getOtherRadiosInGroup(element).forEach((radio) => radio.removeAttribute("data-dirty"));
1323
+ }
1324
+ if (this._isElementDirty(element)) {
1325
+ element.setAttribute("data-dirty", "true");
1326
+ } else {
1327
+ element.removeAttribute("data-dirty");
1328
+ }
1329
+ }
1330
+ _isElementDirty(element) {
1331
+ return this._getElementValue(element) !== this._getElementLoadValue(element);
1332
+ }
1333
+ _cacheElementLoadValue(element) {
1334
+ if (!this._elementHasCachedLoadValue(element) && isElementCheckable(element)) {
1335
+ element.setAttribute(this._cacheAttrName, element.checked.toString());
1336
+ } else {
1337
+ element.setAttribute(this._cacheAttrName, element.value.toString());
1338
+ }
1339
+ }
1340
+ _restoreElementFromLoadValue(element) {
1341
+ let cacheValue = element.getAttribute(this._cacheAttrName);
1342
+ if (isElementCheckable(element)) {
1343
+ element.setAttribute(this._cacheAttrName, element.checked.toString());
1344
+ element.checked = cacheValue == null ? element.defaultChecked : cacheValue == "true";
1345
+ } else if (isHTMLSelectElement(element)) {
1346
+ if (cacheValue == null) {
1347
+ let options = Array.from(element.options);
1348
+ options.forEach((option) => {
1349
+ if (option.defaultSelected) {
1350
+ element.value = option.value;
1351
+ return;
1352
+ }
1353
+ });
1354
+ } else {
1355
+ element.value = cacheValue;
1356
+ }
1357
+ } else {
1358
+ element.value = cacheValue == null ? element.defaultValue : cacheValue;
1359
+ }
1360
+ }
1361
+ _cacheLoadValues() {
1362
+ this._formElements.forEach((el) => this._cacheElementLoadValue(el));
1363
+ }
1364
+ _checkDirty() {
1365
+ this._formElements.forEach((el) => this._checkElementDirty(el));
1366
+ if (this._formElements.some((el) => isFormDirty(el))) {
1367
+ this.el.setAttribute("data-dirty", "true");
1368
+ } else {
1369
+ this.el.removeAttribute("data-dirty");
1370
+ }
1371
+ }
1372
+ }
1373
+ function isFormDirty(element) {
1374
+ return element.hasAttribute("data-dirty");
1375
+ }
1376
+ class EnableInputsController extends BaseController {
1377
+ connect() {
1378
+ }
1379
+ disable() {
1380
+ let shouldClear = this.hasClearValue && this.clearValue;
1381
+ this.inputTargets.forEach((el, _) => {
1382
+ if (shouldClear) {
1383
+ el.value = "";
1384
+ }
1385
+ el.disabled = true;
1386
+ });
1387
+ }
1388
+ enable() {
1389
+ this.inputTargets.forEach((el, _) => el.disabled = false);
1390
+ }
1391
+ }
1392
+ __publicField(EnableInputsController, "targets", ["input"]);
1393
+ __publicField(EnableInputsController, "values", {
1394
+ clear: Boolean
1395
+ });
1396
+ class FocusStealController extends BaseController {
1397
+ get _mode() {
1398
+ const MODES = ["immediate", "wait"];
1399
+ if (this.hasModeValue) {
1400
+ if (!MODES.includes(this.modeValue)) {
1401
+ throw new Error(`The given modeValue '${this.modeValue}' is not one of the supported modes: "${MODES.join('", "')}"`);
1402
+ } else {
1403
+ return this.modeValue;
1404
+ }
1405
+ } else {
1406
+ return MODES[0];
1407
+ }
1408
+ }
1409
+ connect() {
1410
+ if (this._mode == "immediate") {
1411
+ this.steal();
1412
+ }
1413
+ }
1414
+ steal() {
1415
+ this.el.focus();
1416
+ }
1417
+ }
1418
+ __publicField(FocusStealController, "values", {
1419
+ mode: String
1420
+ });
1421
+ class FormRcController extends BaseController {
1422
+ get _mode() {
1423
+ if (this.hasSubmitModeValue) {
1424
+ if (!["direct", "request"].includes(this.submitModeValue)) {
1425
+ throw new Error(`The modeValue provided '${this.submitModeValue}' is not one of the recognised configuration options`);
1426
+ }
1427
+ return this.submitModeValue;
1428
+ } else {
1429
+ return "request";
1430
+ }
1431
+ }
1432
+ get form() {
1433
+ let form;
1434
+ if (this.hasFormSelectorValue) {
1435
+ form = document.querySelector(this.formSelectorValue);
1436
+ if (!form) {
1437
+ throw new Error(`Could not find a form on the page that matches selector '${this.formSelectorValue}'`);
1438
+ }
1439
+ } else {
1440
+ form = this.formTarget;
1441
+ }
1442
+ return form;
1443
+ }
1444
+ submit(event) {
1445
+ event == null ? void 0 : event.preventDefault();
1446
+ let el = this.formTarget;
1447
+ if (this._mode == "request") {
1448
+ requestSubmit(el);
1449
+ } else {
1450
+ el.submit();
1451
+ }
1452
+ }
1453
+ reset(event) {
1454
+ event == null ? void 0 : event.preventDefault();
1455
+ requestReset(this.form);
1456
+ }
1457
+ }
1458
+ __publicField(FormRcController, "targets", ["form"]);
1459
+ __publicField(FormRcController, "values", {
1460
+ formSelector: String,
1461
+ submitMode: String
1462
+ });
1463
+ class FormSaveController extends BaseController {
1464
+ get _formID() {
1465
+ if (this.hasIdValue) {
1466
+ return this.idValue;
1467
+ }
1468
+ let elementID = this.el.id;
1469
+ if (elementID !== "") {
1470
+ return elementID;
1471
+ } else {
1472
+ throw new Error(`No ID value to uniquely identify this form. Please either specify data-${this.identifier}-id-value or give this form an 'id' attribute. `);
1473
+ }
1474
+ }
1475
+ get _formIdentifier() {
1476
+ const url = location.href;
1477
+ return `${url} ${this._formID}`;
1478
+ }
1479
+ get _formElements() {
1480
+ return this.el.elements;
1481
+ }
1482
+ get _formData() {
1483
+ let data = { [this._formIdentifier]: {} };
1484
+ for (const element of this._formElements) {
1485
+ let el = element;
1486
+ if (el.name.length > 0) {
1487
+ if (isHTMLInputElement(el) && el.type == "checkbox") {
1488
+ data[this._formIdentifier][el.name] = el.checked;
1489
+ } else if (isHTMLInputElement(el) && el.type == "radio") {
1490
+ if (el.checked) {
1491
+ data[this._formIdentifier][el.name] = el.value;
1492
+ }
1493
+ } else {
1494
+ data[this._formIdentifier][el.name] = el.value;
1495
+ }
1496
+ }
1497
+ }
1498
+ return data;
1499
+ }
1500
+ get _restoreOnLoad() {
1501
+ return this.hasRestoreOnLoadValue ? this.restoreOnLoadValue : true;
1502
+ }
1503
+ get _clearOnSubmit() {
1504
+ return this.hasClearOnSubmitValue ? this.clearOnSubmitValue : true;
1505
+ }
1506
+ connect() {
1507
+ requestAnimationFrame(() => {
1508
+ let element = this.el;
1509
+ if (!isHTMLFormElement(element)) {
1510
+ throw new Error("Expected controller to be mounted on a form element.");
1511
+ }
1512
+ if (this._restoreOnLoad) {
1513
+ this.restore();
1514
+ }
1515
+ if (this._clearOnSubmit) {
1516
+ useEventListener(this, this.el, "submit", this._clear);
1517
+ }
1518
+ });
1519
+ }
1520
+ _clear() {
1521
+ localStorage.removeItem(this._formIdentifier);
1522
+ this.dispatchEvent(this.el, `form-save:cleared`);
1523
+ }
1524
+ clear(event) {
1525
+ event == null ? void 0 : event.preventDefault();
1526
+ this._clear();
1527
+ }
1528
+ save(event) {
1529
+ event.preventDefault();
1530
+ let data = this._formData;
1531
+ localStorage.setItem(this._formIdentifier, JSON.stringify(data[this._formIdentifier]));
1532
+ this.dispatchEvent(this.el, `form-save:save:success`);
1533
+ }
1534
+ restore(event) {
1535
+ event == null ? void 0 : event.preventDefault();
1536
+ if (localStorage.getItem(this._formIdentifier)) {
1537
+ const savedData = JSON.parse(localStorage.getItem(this._formIdentifier));
1538
+ for (const element of this._formElements) {
1539
+ let el = element;
1540
+ if (el.name in savedData) {
1541
+ if (isHTMLInputElement(el) && el.type == "checkbox") {
1542
+ el.checked = savedData[el.name];
1543
+ } else if (isHTMLInputElement(el) && el.type == "radio") {
1544
+ if (el.value == savedData[el.name]) {
1545
+ el.checked = true;
1546
+ }
1547
+ } else {
1548
+ el.value = savedData[el.name];
1549
+ }
1550
+ }
1551
+ }
1552
+ this.dispatchEvent(this.el, `form-save:restore:success`);
1553
+ } else {
1554
+ this.dispatchEvent(this.el, `form-save:restore:empty`);
1555
+ }
1556
+ }
1557
+ }
1558
+ __publicField(FormSaveController, "values", {
1559
+ id: String,
1560
+ restoreOnLoad: Boolean,
1561
+ clearOnSubmit: Boolean
1562
+ });
1563
+ class LimitedSelectionCheckboxesController extends BaseController {
1564
+ connect() {
1565
+ useCollectionEventListener(this, this.inputTargets, "change", this._handleInputs);
1566
+ }
1567
+ _handleInputs(event) {
1568
+ let tickedInputs = this.inputTargets.reduce((previousValue, el) => el.checked ? previousValue + 1 : previousValue, 0);
1569
+ let target = event.target;
1570
+ if (tickedInputs > this.maxValue) {
1571
+ event.preventDefault();
1572
+ target.checked = false;
1573
+ this.dispatchEvent(target, "change");
1574
+ this.dispatchEvent(target, "limited-selection:too-many");
1575
+ if (this.hasErrorTarget && this.hasMessageValue) {
1576
+ this.errorTarget.innerHTML = this.messageValue;
1577
+ }
1578
+ } else {
1579
+ this.dispatchEvent(target, "limited-selection:selection");
1580
+ if (this.hasErrorTarget) {
1581
+ this.errorTarget.innerHTML = "";
1582
+ }
1583
+ }
1584
+ }
1585
+ }
1586
+ __publicField(LimitedSelectionCheckboxesController, "targets", ["input", "error"]);
1587
+ __publicField(LimitedSelectionCheckboxesController, "values", { max: Number, message: String });
1588
+ class NavigateFormErrorsController extends BaseController {
1589
+ constructor() {
1590
+ super(...arguments);
1591
+ __publicField(this, "_errors", []);
1592
+ __publicField(this, "_firstClick", false);
1593
+ }
1594
+ get defaultCurrentClasses() {
1595
+ return ["currentError"];
1596
+ }
1597
+ get _errorCount() {
1598
+ return this._errors.length;
1599
+ }
1600
+ get _previousIndex() {
1601
+ let index = this._index - 1;
1602
+ if (index < 0) {
1603
+ return 0;
1604
+ }
1605
+ return index;
1606
+ }
1607
+ get _nextIndex() {
1608
+ let index = this._index + 1;
1609
+ if (index > this._errors.length - 1) {
1610
+ return this._errors.length - 1;
1611
+ }
1612
+ return index;
1613
+ }
1614
+ get _index() {
1615
+ return clamp(this.hasIndexValue ? this.indexValue : 0, 0, this._errors.length);
1616
+ }
1617
+ get _selector() {
1618
+ if (this.hasSelectorValue) {
1619
+ return this.selectorValue;
1620
+ } else {
1621
+ throw new Error("Expected `selectorValue` to be present");
1622
+ }
1623
+ }
1624
+ get _currentError() {
1625
+ return this._errors[this._index];
1626
+ }
1627
+ get _otherErrors() {
1628
+ return this._errors.filter((error, index) => index !== this._index);
1629
+ }
1630
+ connect() {
1631
+ installClassMethods(this);
1632
+ requestAnimationFrame(() => {
1633
+ this._firstClick = true;
1634
+ this._toggleButtons();
1635
+ this._toggleVisibility();
1636
+ });
1637
+ }
1638
+ async current(event) {
1639
+ event == null ? void 0 : event.preventDefault();
1640
+ if (this._firstClick) {
1641
+ this._firstClick = false;
1642
+ this._toggleButtons();
1643
+ }
1644
+ await scrollToElement(this._currentError, { behavior: "smooth", block: "center", inline: "center" });
1645
+ this._updateClasses();
1646
+ }
1647
+ async next(event) {
1648
+ event == null ? void 0 : event.preventDefault();
1649
+ if (this._firstClick) {
1650
+ this._firstClick = false;
1651
+ this._toggleButtons();
1652
+ } else {
1653
+ this.indexValue = this._nextIndex;
1654
+ }
1655
+ await scrollToElement(this._currentError, { behavior: "smooth", block: "center", inline: "center" });
1656
+ this._updateClasses();
1657
+ }
1658
+ async previous(event) {
1659
+ event == null ? void 0 : event.preventDefault();
1660
+ if (this._firstClick) {
1661
+ this._firstClick = false;
1662
+ this._toggleButtons();
1663
+ } else {
1664
+ this.indexValue = this._previousIndex;
1665
+ }
1666
+ await scrollToElement(this._currentError, { behavior: "smooth", block: "center", inline: "center" });
1667
+ this._updateClasses();
1668
+ }
1669
+ indexValueChanged() {
1670
+ this._toggleButtons();
1671
+ }
1672
+ selectorValueChanged() {
1673
+ this._errors = Array.from(document.querySelectorAll(this._selector));
1674
+ this.indexValue = 0;
1675
+ this._toggleButtons();
1676
+ this._toggleVisibility();
1677
+ }
1678
+ _updateClasses() {
1679
+ this.addCurrentClasses(this._currentError);
1680
+ this._otherErrors.forEach((error) => this.removeCurrentClasses(error));
1681
+ }
1682
+ _toggleVisibility() {
1683
+ if (this._errorCount === 0) {
1684
+ this.el.style.display = "none";
1685
+ } else {
1686
+ this.el.style.display = "";
1687
+ }
1688
+ }
1689
+ _toggleButtons() {
1690
+ if (this.hasNextTarget) {
1691
+ if (!this.hasCurrentTarget && this._firstClick && this.indexValue == this._errorCount - 1) {
1692
+ this.nextTarget.removeAttribute("disabled");
1693
+ return;
1694
+ } else if (this.indexValue >= this._errorCount - 1) {
1695
+ this.nextTarget.setAttribute("disabled", "true");
1696
+ } else {
1697
+ this.nextTarget.removeAttribute("disabled");
1698
+ }
1699
+ }
1700
+ if (this.hasPreviousTarget) {
1701
+ if (this.indexValue <= 0) {
1702
+ this.previousTarget.setAttribute("disabled", "true");
1703
+ } else {
1704
+ this.previousTarget.removeAttribute("disabled");
1705
+ }
1706
+ }
1707
+ }
1708
+ }
1709
+ __publicField(NavigateFormErrorsController, "values", {
1710
+ selector: String,
1711
+ index: Number
1712
+ });
1713
+ __publicField(NavigateFormErrorsController, "classes", ["current"]);
1714
+ __publicField(NavigateFormErrorsController, "targets", ["next", "current", "previous"]);
1715
+ class NestedFormController extends BaseController {
1716
+ get _wrapperClass() {
1717
+ return this.hasWrapperSelectorValue ? this.wrapperClassValue : "nested-fields";
1718
+ }
1719
+ get _insertMode() {
1720
+ return this.hasInsertModeValue ? this.insertModeValue : "beforeend";
1721
+ }
1722
+ connect() {
1723
+ this._checkStructure();
1724
+ }
1725
+ add(event) {
1726
+ event == null ? void 0 : event.preventDefault();
1727
+ const content = this.templateTarget.innerHTML.replace(/NEW_RECORD/g, this._generateID());
1728
+ this.targetTarget.insertAdjacentHTML(this._insertMode, content);
1729
+ }
1730
+ remove(event) {
1731
+ event.preventDefault();
1732
+ const wrapper = event.target.closest(`.${this._wrapperClass}`);
1733
+ if (wrapper == null) {
1734
+ throw new Error(`#remove was clicked from outside of a child record. Could not find an ancestor with class .${this._wrapperClass}`);
1735
+ }
1736
+ if (wrapper.dataset.newRecord === "true") {
1737
+ wrapper.remove();
1738
+ } else {
1739
+ wrapper.style.display = "none";
1740
+ let destroyInput = wrapper.querySelector("input[name*='_destroy']");
1741
+ if (destroyInput == null) {
1742
+ throw new Error(`Could not find a hidden input with name '_destroy'. NestedForm cannot remove an already persisted record without it.`);
1743
+ }
1744
+ destroyInput.value = "1";
1745
+ }
1746
+ }
1747
+ _generateID() {
1748
+ return new Date().getTime().toString() + Math.random().toString().slice(2);
1749
+ }
1750
+ _checkStructure() {
1751
+ let template = this.templateTarget.innerHTML;
1752
+ if (template.indexOf("NEW_RECORD")) {
1753
+ throw new Error("Could not find 'NEW_RECORD' in the provided template. Please make sure you've passed `child_index: 'NEW_RECORD'` to `fields_for`");
1754
+ }
1755
+ }
1756
+ }
1757
+ __publicField(NestedFormController, "targets", ["target", "template"]);
1758
+ __publicField(NestedFormController, "values", {
1759
+ insertMode: String,
1760
+ wrapperClass: String
1761
+ });
1762
+ class PasswordConfirmController extends BaseController {
1763
+ connect() {
1764
+ installClassMethods(this);
1765
+ useCollectionEventListener(this, this.passwordTargets, "change", this._checkPasswordsMatch);
1766
+ }
1767
+ _allPasswordsMatch() {
1768
+ let values = new Set(this.passwordTargets.map((el) => el.value));
1769
+ return values.has("") || values.size == 1;
1770
+ }
1771
+ _checkPasswordsMatch() {
1772
+ let element = this.el;
1773
+ if (this._allPasswordsMatch()) {
1774
+ this.dispatchEvent(element, "password-confirm:match");
1775
+ this.passwordTargets.forEach((el) => this.removeErrorClasses(el));
1776
+ } else {
1777
+ this.dispatchEvent(element, "password-confirm:no-match");
1778
+ this.passwordTargets.forEach((el) => this.addErrorClasses(el));
1779
+ }
1780
+ }
1781
+ }
1782
+ __publicField(PasswordConfirmController, "targets", ["password"]);
1783
+ __publicField(PasswordConfirmController, "classes", ["error"]);
1784
+ class PasswordPeekController extends BaseController {
1785
+ peak(event) {
1786
+ event == null ? void 0 : event.preventDefault();
1787
+ this.passwordTarget.type = "text";
1788
+ }
1789
+ hide(event) {
1790
+ event == null ? void 0 : event.preventDefault();
1791
+ this.passwordTarget.type = "password";
1792
+ }
1793
+ toggle(event) {
1794
+ event == null ? void 0 : event.preventDefault();
1795
+ if (this.passwordTarget.type === "password") {
1796
+ this.peak();
1797
+ } else {
1798
+ this.hide();
1799
+ }
1800
+ }
1801
+ }
1802
+ __publicField(PasswordPeekController, "targets", ["password"]);
1803
+ class RemoteFormController extends BaseController {
1804
+ get _selector() {
1805
+ return this.hasSelectorValue ? this.selectorValue : `[data-controller~="${this.identifier}"]`;
1806
+ }
1807
+ replace(event) {
1808
+ const [data, status, xhr] = event.detail;
1809
+ if (data instanceof Node) {
1810
+ let newElement = data.querySelector(this._selector);
1811
+ if (newElement == null) {
1812
+ throw new Error(`expected new form DOM with [data-controller="${this.identifier}"] to be present in returned payload`);
1813
+ }
1814
+ let parentNode = this.el.parentNode;
1815
+ if (parentNode == null) {
1816
+ throw new Error("expected form to have a DOM parent, could not execute replaceChild");
1817
+ }
1818
+ parentNode.replaceChild(newElement, this.el);
1819
+ this.dispatchEvent(newElement, "remote-form:replace");
1820
+ } else {
1821
+ console.log("Unknown", data);
1822
+ }
1823
+ }
1824
+ }
1825
+ __publicField(RemoteFormController, "targets", []);
1826
+ __publicField(RemoteFormController, "values", { selector: String });
1827
+ function useEventBus(controller, eventNameOrNames, handler, opts) {
1828
+ let options = opts;
1829
+ if (options == null ? void 0 : options.debounce) {
1830
+ handler = debounce(handler.bind(controller), options.debounce);
1831
+ delete options.debounce;
1832
+ } else {
1833
+ handler = handler.bind(controller);
1834
+ }
1835
+ let eventNames = wrapArray(eventNameOrNames);
1836
+ let setup = () => eventNames.forEach((eventName) => EventBus.on(eventName, handler));
1837
+ let teardown = () => eventNames.forEach((eventName) => EventBus.off(eventName, handler));
1838
+ useMixin(controller, setup, teardown);
1839
+ return { setup, teardown };
1840
+ }
1841
+ class SyncInputsController extends BaseController {
1842
+ get _eventName() {
1843
+ return `sync:${this._key}`;
1844
+ }
1845
+ get _key() {
1846
+ if (this.hasKeyValue) {
1847
+ return this.keyValue;
1848
+ }
1849
+ throw new Error("Expected `keyValue` to be present");
1850
+ }
1851
+ get _value() {
1852
+ let el = this.el;
1853
+ if (isHTMLInputElement(el) && el.type === "checkbox") {
1854
+ return el.checked;
1855
+ } else if (isHTMLInputElement(el) && el.type === "radio") {
1856
+ return el.checked ? el.value : "";
1857
+ } else {
1858
+ return el.value;
1859
+ }
1860
+ }
1861
+ set _value(val) {
1862
+ let el = this.el;
1863
+ if (isHTMLInputElement(el) && el.type === "checkbox") {
1864
+ el.checked = val.toString() === "true";
1865
+ } else if (isHTMLInputElement(el) && el.type === "radio") {
1866
+ el.checked = el.value === val;
1867
+ } else if (isHTMLInputElement(el) || isHTMLTextAreaElement(el) || isHTMLSelectElement(el)) {
1868
+ el.value = val.toString();
1869
+ } else {
1870
+ el.innerHTML = val.toString();
1871
+ }
1872
+ }
1873
+ connect() {
1874
+ useEventBus(this, this._eventName, this._read);
1875
+ requestAnimationFrame(() => {
1876
+ if (isTypeOfFormInputElement(this.el)) {
1877
+ this._emit();
1878
+ useEventListener(this, this.el, "input", this._emit);
1879
+ }
1880
+ });
1881
+ }
1882
+ _emit() {
1883
+ EventBus.emit(this._eventName, { value: this._value, dispatcher: this.el });
1884
+ }
1885
+ _read(payload) {
1886
+ if (payload === void 0) {
1887
+ throw new Error("No payload received");
1888
+ }
1889
+ let { dispatcher, value } = payload;
1890
+ if (dispatcher !== this.el) {
1891
+ this._value = value;
1892
+ }
1893
+ }
1894
+ }
1895
+ __publicField(SyncInputsController, "values", {
1896
+ key: String
1897
+ });
1898
+ class ValueWarnController extends BaseController {
1899
+ get _maxMessage() {
1900
+ return this.hasMaxMessageValue ? this.maxMessageValue : `Value must be less than ${this.maxValue}`;
1901
+ }
1902
+ get _minMessage() {
1903
+ return this.hasMinMessageValue ? this.minMessageValue : `Value must be greater than ${this.minValue}`;
1904
+ }
1905
+ get defaultWarningHideClasses() {
1906
+ return ["hide"];
1907
+ }
1908
+ connect() {
1909
+ installClassMethods(this);
1910
+ this.addWarningHideClasses(this.warningTarget);
1911
+ useEventListener(this, this.inputTarget, "input", this._check);
1912
+ this._check();
1913
+ }
1914
+ _check() {
1915
+ if (this.hasMinValue && Number.parseFloat(this.inputTarget.value) < this.minValue) {
1916
+ this.removeWarningHideClasses(this.warningTarget);
1917
+ this.addInputWarningClasses(this.inputTarget);
1918
+ this.warningTarget.innerText = this._minMessage;
1919
+ } else if (this.hasMaxValue && Number.parseFloat(this.inputTarget.value) > this.maxValue) {
1920
+ this.removeWarningHideClasses(this.warningTarget);
1921
+ this.addInputWarningClasses(this.inputTarget);
1922
+ this.warningTarget.innerText = this._maxMessage;
1923
+ } else {
1924
+ this.addWarningHideClasses(this.warningTarget);
1925
+ this.removeInputWarningClasses(this.inputTarget);
1926
+ this.warningTarget.innerText = "";
1927
+ }
1928
+ }
1929
+ }
1930
+ __publicField(ValueWarnController, "classes", ["inputWarning", "warningHide"]);
1931
+ __publicField(ValueWarnController, "targets", ["input", "warning"]);
1932
+ __publicField(ValueWarnController, "values", {
1933
+ max: Number,
1934
+ min: Number,
1935
+ minMessage: String,
1936
+ maxMessage: String
1937
+ });
1938
+ class WordCountController extends BaseController {
1939
+ connect() {
1940
+ installClassMethods(this);
1941
+ this._updateWordCount();
1942
+ useEventListener(this, this.inputTarget, "input", this._updateWordCount);
1943
+ }
1944
+ _updateWordCount() {
1945
+ let wordCount = 0;
1946
+ let textAreaValue = this.inputTarget.value;
1947
+ let matches = textAreaValue.match(/\S+/g);
1948
+ wordCount = matches && matches.length || 0;
1949
+ this.outputTarget.innerText = wordCount.toString();
1950
+ if (this._isValidCount(wordCount)) {
1951
+ this.removeErrorClasses(this.outputTarget);
1952
+ } else {
1953
+ this.addErrorClasses(this.outputTarget);
1954
+ }
1955
+ }
1956
+ _isValidCount(count) {
1957
+ let min = 0;
1958
+ let max = 99999;
1959
+ if (this.hasMinValue) {
1960
+ min = this.minValue;
1961
+ }
1962
+ if (this.hasMaxValue) {
1963
+ max = this.maxValue;
1964
+ }
1965
+ return count >= min && count <= max;
1966
+ }
1967
+ }
1968
+ __publicField(WordCountController, "targets", ["input", "output"]);
1969
+ __publicField(WordCountController, "values", { min: Number, max: Number });
1970
+ __publicField(WordCountController, "classes", ["error"]);
1971
+ class FallbackImageController extends BaseController {
1972
+ initialize() {
1973
+ this._hasLoadedSuccessfully = this._hasLoadedSuccessfully.bind(this);
1974
+ this._success = this._success.bind(this);
1975
+ this._fail = this._fail.bind(this);
1976
+ }
1977
+ connect() {
1978
+ let element = this.el;
1979
+ element.onerror = this._fail;
1980
+ if (element.complete && !this._hasLoadedSuccessfully()) {
1981
+ this._fail();
1982
+ } else {
1983
+ this._success();
1984
+ }
1985
+ }
1986
+ disconnect() {
1987
+ this.removeSuccessClasses();
1988
+ this.removeFailClasses();
1989
+ }
1990
+ _success() {
1991
+ this.addSuccessClasses();
1992
+ }
1993
+ _fail() {
1994
+ let element = this.el;
1995
+ this.addFailClasses();
1996
+ if (this.hasPlaceholderValue && element.src !== this.placeholderValue) {
1997
+ this.dispatchEvent(element, "fallback-image:placeholder");
1998
+ element.src = this.placeholderValue;
1999
+ element.onerror = this._fail;
2000
+ } else {
2001
+ this.dispatchEvent(element, "fallback-image:fail");
2002
+ element.style.display = "none";
2003
+ }
2004
+ }
2005
+ _hasLoadedSuccessfully() {
2006
+ let element = this.el;
2007
+ return element.naturalHeight > 0 && element.naturalWidth > 0;
2008
+ }
2009
+ }
2010
+ __publicField(FallbackImageController, "values", { placeholder: String });
2011
+ __publicField(FallbackImageController, "classes", ["success", "fail"]);
2012
+ var supportCustomEvent = window.CustomEvent;
2013
+ if (!supportCustomEvent || typeof supportCustomEvent === "object") {
2014
+ supportCustomEvent = function CustomEvent2(event, x) {
2015
+ x = x || {};
2016
+ var ev = document.createEvent("CustomEvent");
2017
+ ev.initCustomEvent(event, !!x.bubbles, !!x.cancelable, x.detail || null);
2018
+ return ev;
2019
+ };
2020
+ supportCustomEvent.prototype = window.Event.prototype;
2021
+ }
2022
+ function safeDispatchEvent(target, event) {
2023
+ var check = "on" + event.type.toLowerCase();
2024
+ if (typeof target[check] === "function") {
2025
+ target[check](event);
2026
+ }
2027
+ return target.dispatchEvent(event);
2028
+ }
2029
+ function createsStackingContext(el) {
2030
+ while (el && el !== document.body) {
2031
+ var s = window.getComputedStyle(el);
2032
+ var invalid = function(k, ok) {
2033
+ return !(s[k] === void 0 || s[k] === ok);
2034
+ };
2035
+ if (s.opacity < 1 || invalid("zIndex", "auto") || invalid("transform", "none") || invalid("mixBlendMode", "normal") || invalid("filter", "none") || invalid("perspective", "none") || s["isolation"] === "isolate" || s.position === "fixed" || s.webkitOverflowScrolling === "touch") {
2036
+ return true;
2037
+ }
2038
+ el = el.parentElement;
2039
+ }
2040
+ return false;
2041
+ }
2042
+ function findNearestDialog(el) {
2043
+ while (el) {
2044
+ if (el.localName === "dialog") {
2045
+ return el;
2046
+ }
2047
+ if (el.parentElement) {
2048
+ el = el.parentElement;
2049
+ } else if (el.parentNode) {
2050
+ el = el.parentNode.host;
2051
+ } else {
2052
+ el = null;
2053
+ }
2054
+ }
2055
+ return null;
2056
+ }
2057
+ function safeBlur(el) {
2058
+ while (el && el.shadowRoot && el.shadowRoot.activeElement) {
2059
+ el = el.shadowRoot.activeElement;
2060
+ }
2061
+ if (el && el.blur && el !== document.body) {
2062
+ el.blur();
2063
+ }
2064
+ }
2065
+ function inNodeList(nodeList, node) {
2066
+ for (var i = 0; i < nodeList.length; ++i) {
2067
+ if (nodeList[i] === node) {
2068
+ return true;
2069
+ }
2070
+ }
2071
+ return false;
2072
+ }
2073
+ function isFormMethodDialog(el) {
2074
+ if (!el || !el.hasAttribute("method")) {
2075
+ return false;
2076
+ }
2077
+ return el.getAttribute("method").toLowerCase() === "dialog";
2078
+ }
2079
+ function findFocusableElementWithin(hostElement) {
2080
+ var opts = ["button", "input", "keygen", "select", "textarea"];
2081
+ var query = opts.map(function(el) {
2082
+ return el + ":not([disabled])";
2083
+ });
2084
+ query.push('[tabindex]:not([disabled]):not([tabindex=""])');
2085
+ var target = hostElement.querySelector(query.join(", "));
2086
+ if (!target && "attachShadow" in Element.prototype) {
2087
+ var elems = hostElement.querySelectorAll("*");
2088
+ for (var i = 0; i < elems.length; i++) {
2089
+ if (elems[i].tagName && elems[i].shadowRoot) {
2090
+ target = findFocusableElementWithin(elems[i].shadowRoot);
2091
+ if (target) {
2092
+ break;
2093
+ }
2094
+ }
2095
+ }
2096
+ }
2097
+ return target;
2098
+ }
2099
+ function isConnected(element) {
2100
+ return element.isConnected || document.body.contains(element);
2101
+ }
2102
+ function findFormSubmitter(event) {
2103
+ if (event.submitter) {
2104
+ return event.submitter;
2105
+ }
2106
+ var form = event.target;
2107
+ if (!(form instanceof HTMLFormElement)) {
2108
+ return null;
2109
+ }
2110
+ var submitter = dialogPolyfill.formSubmitter;
2111
+ if (!submitter) {
2112
+ var target = event.target;
2113
+ var root = "getRootNode" in target && target.getRootNode() || document;
2114
+ submitter = root.activeElement;
2115
+ }
2116
+ if (!submitter || submitter.form !== form) {
2117
+ return null;
2118
+ }
2119
+ return submitter;
2120
+ }
2121
+ function maybeHandleSubmit(event) {
2122
+ if (event.defaultPrevented) {
2123
+ return;
2124
+ }
2125
+ var form = event.target;
2126
+ var value = dialogPolyfill.imagemapUseValue;
2127
+ var submitter = findFormSubmitter(event);
2128
+ if (value === null && submitter) {
2129
+ value = submitter.value;
2130
+ }
2131
+ var dialog = findNearestDialog(form);
2132
+ if (!dialog) {
2133
+ return;
2134
+ }
2135
+ var formmethod = submitter && submitter.getAttribute("formmethod") || form.getAttribute("method");
2136
+ if (formmethod !== "dialog") {
2137
+ return;
2138
+ }
2139
+ event.preventDefault();
2140
+ if (value != null) {
2141
+ dialog.close(value);
2142
+ } else {
2143
+ dialog.close();
2144
+ }
2145
+ }
2146
+ function dialogPolyfillInfo(dialog) {
2147
+ this.dialog_ = dialog;
2148
+ this.replacedStyleTop_ = false;
2149
+ this.openAsModal_ = false;
2150
+ if (!dialog.hasAttribute("role")) {
2151
+ dialog.setAttribute("role", "dialog");
2152
+ }
2153
+ dialog.show = this.show.bind(this);
2154
+ dialog.showModal = this.showModal.bind(this);
2155
+ dialog.close = this.close.bind(this);
2156
+ dialog.addEventListener("submit", maybeHandleSubmit, false);
2157
+ if (!("returnValue" in dialog)) {
2158
+ dialog.returnValue = "";
2159
+ }
2160
+ if ("MutationObserver" in window) {
2161
+ var mo = new MutationObserver(this.maybeHideModal.bind(this));
2162
+ mo.observe(dialog, { attributes: true, attributeFilter: ["open"] });
2163
+ } else {
2164
+ var removed = false;
2165
+ var cb = function() {
2166
+ removed ? this.downgradeModal() : this.maybeHideModal();
2167
+ removed = false;
2168
+ }.bind(this);
2169
+ var timeout;
2170
+ var delayModel = function(ev) {
2171
+ if (ev.target !== dialog) {
2172
+ return;
2173
+ }
2174
+ var cand = "DOMNodeRemoved";
2175
+ removed |= ev.type.substr(0, cand.length) === cand;
2176
+ window.clearTimeout(timeout);
2177
+ timeout = window.setTimeout(cb, 0);
2178
+ };
2179
+ ["DOMAttrModified", "DOMNodeRemoved", "DOMNodeRemovedFromDocument"].forEach(function(name) {
2180
+ dialog.addEventListener(name, delayModel);
2181
+ });
2182
+ }
2183
+ Object.defineProperty(dialog, "open", {
2184
+ set: this.setOpen.bind(this),
2185
+ get: dialog.hasAttribute.bind(dialog, "open")
2186
+ });
2187
+ this.backdrop_ = document.createElement("div");
2188
+ this.backdrop_.className = "backdrop";
2189
+ this.backdrop_.addEventListener("mouseup", this.backdropMouseEvent_.bind(this));
2190
+ this.backdrop_.addEventListener("mousedown", this.backdropMouseEvent_.bind(this));
2191
+ this.backdrop_.addEventListener("click", this.backdropMouseEvent_.bind(this));
2192
+ }
2193
+ dialogPolyfillInfo.prototype = {
2194
+ get dialog() {
2195
+ return this.dialog_;
2196
+ },
2197
+ maybeHideModal: function() {
2198
+ if (this.dialog_.hasAttribute("open") && isConnected(this.dialog_)) {
2199
+ return;
2200
+ }
2201
+ this.downgradeModal();
2202
+ },
2203
+ downgradeModal: function() {
2204
+ if (!this.openAsModal_) {
2205
+ return;
2206
+ }
2207
+ this.openAsModal_ = false;
2208
+ this.dialog_.style.zIndex = "";
2209
+ if (this.replacedStyleTop_) {
2210
+ this.dialog_.style.top = "";
2211
+ this.replacedStyleTop_ = false;
2212
+ }
2213
+ this.backdrop_.parentNode && this.backdrop_.parentNode.removeChild(this.backdrop_);
2214
+ dialogPolyfill.dm.removeDialog(this);
2215
+ },
2216
+ setOpen: function(value) {
2217
+ if (value) {
2218
+ this.dialog_.hasAttribute("open") || this.dialog_.setAttribute("open", "");
2219
+ } else {
2220
+ this.dialog_.removeAttribute("open");
2221
+ this.maybeHideModal();
2222
+ }
2223
+ },
2224
+ backdropMouseEvent_: function(e) {
2225
+ if (!this.dialog_.hasAttribute("tabindex")) {
2226
+ var fake = document.createElement("div");
2227
+ this.dialog_.insertBefore(fake, this.dialog_.firstChild);
2228
+ fake.tabIndex = -1;
2229
+ fake.focus();
2230
+ this.dialog_.removeChild(fake);
2231
+ } else {
2232
+ this.dialog_.focus();
2233
+ }
2234
+ var redirectedEvent = document.createEvent("MouseEvents");
2235
+ redirectedEvent.initMouseEvent(e.type, e.bubbles, e.cancelable, window, e.detail, e.screenX, e.screenY, e.clientX, e.clientY, e.ctrlKey, e.altKey, e.shiftKey, e.metaKey, e.button, e.relatedTarget);
2236
+ this.dialog_.dispatchEvent(redirectedEvent);
2237
+ e.stopPropagation();
2238
+ },
2239
+ focus_: function() {
2240
+ var target = this.dialog_.querySelector("[autofocus]:not([disabled])");
2241
+ if (!target && this.dialog_.tabIndex >= 0) {
2242
+ target = this.dialog_;
2243
+ }
2244
+ if (!target) {
2245
+ target = findFocusableElementWithin(this.dialog_);
2246
+ }
2247
+ safeBlur(document.activeElement);
2248
+ target && target.focus();
2249
+ },
2250
+ updateZIndex: function(dialogZ, backdropZ) {
2251
+ if (dialogZ < backdropZ) {
2252
+ throw new Error("dialogZ should never be < backdropZ");
2253
+ }
2254
+ this.dialog_.style.zIndex = dialogZ;
2255
+ this.backdrop_.style.zIndex = backdropZ;
2256
+ },
2257
+ show: function() {
2258
+ if (!this.dialog_.open) {
2259
+ this.setOpen(true);
2260
+ this.focus_();
2261
+ }
2262
+ },
2263
+ showModal: function() {
2264
+ if (this.dialog_.hasAttribute("open")) {
2265
+ throw new Error("Failed to execute 'showModal' on dialog: The element is already open, and therefore cannot be opened modally.");
2266
+ }
2267
+ if (!isConnected(this.dialog_)) {
2268
+ throw new Error("Failed to execute 'showModal' on dialog: The element is not in a Document.");
2269
+ }
2270
+ if (!dialogPolyfill.dm.pushDialog(this)) {
2271
+ throw new Error("Failed to execute 'showModal' on dialog: There are too many open modal dialogs.");
2272
+ }
2273
+ if (createsStackingContext(this.dialog_.parentElement)) {
2274
+ console.warn("A dialog is being shown inside a stacking context. This may cause it to be unusable. For more information, see this link: https://github.com/GoogleChrome/dialog-polyfill/#stacking-context");
2275
+ }
2276
+ this.setOpen(true);
2277
+ this.openAsModal_ = true;
2278
+ if (dialogPolyfill.needsCentering(this.dialog_)) {
2279
+ dialogPolyfill.reposition(this.dialog_);
2280
+ this.replacedStyleTop_ = true;
2281
+ } else {
2282
+ this.replacedStyleTop_ = false;
2283
+ }
2284
+ this.dialog_.parentNode.insertBefore(this.backdrop_, this.dialog_.nextSibling);
2285
+ this.focus_();
2286
+ },
2287
+ close: function(opt_returnValue) {
2288
+ if (!this.dialog_.hasAttribute("open")) {
2289
+ throw new Error("Failed to execute 'close' on dialog: The element does not have an 'open' attribute, and therefore cannot be closed.");
2290
+ }
2291
+ this.setOpen(false);
2292
+ if (opt_returnValue !== void 0) {
2293
+ this.dialog_.returnValue = opt_returnValue;
2294
+ }
2295
+ var closeEvent = new supportCustomEvent("close", {
2296
+ bubbles: false,
2297
+ cancelable: false
2298
+ });
2299
+ safeDispatchEvent(this.dialog_, closeEvent);
2300
+ }
2301
+ };
2302
+ var dialogPolyfill = {};
2303
+ dialogPolyfill.reposition = function(element) {
2304
+ var scrollTop = document.body.scrollTop || document.documentElement.scrollTop;
2305
+ var topValue = scrollTop + (window.innerHeight - element.offsetHeight) / 2;
2306
+ element.style.top = Math.max(scrollTop, topValue) + "px";
2307
+ };
2308
+ dialogPolyfill.isInlinePositionSetByStylesheet = function(element) {
2309
+ for (var i = 0; i < document.styleSheets.length; ++i) {
2310
+ var styleSheet = document.styleSheets[i];
2311
+ var cssRules = null;
2312
+ try {
2313
+ cssRules = styleSheet.cssRules;
2314
+ } catch (e) {
2315
+ }
2316
+ if (!cssRules) {
2317
+ continue;
2318
+ }
2319
+ for (var j = 0; j < cssRules.length; ++j) {
2320
+ var rule = cssRules[j];
2321
+ var selectedNodes = null;
2322
+ try {
2323
+ selectedNodes = document.querySelectorAll(rule.selectorText);
2324
+ } catch (e) {
2325
+ }
2326
+ if (!selectedNodes || !inNodeList(selectedNodes, element)) {
2327
+ continue;
2328
+ }
2329
+ var cssTop = rule.style.getPropertyValue("top");
2330
+ var cssBottom = rule.style.getPropertyValue("bottom");
2331
+ if (cssTop && cssTop !== "auto" || cssBottom && cssBottom !== "auto") {
2332
+ return true;
2333
+ }
2334
+ }
2335
+ }
2336
+ return false;
2337
+ };
2338
+ dialogPolyfill.needsCentering = function(dialog) {
2339
+ var computedStyle = window.getComputedStyle(dialog);
2340
+ if (computedStyle.position !== "absolute") {
2341
+ return false;
2342
+ }
2343
+ if (dialog.style.top !== "auto" && dialog.style.top !== "" || dialog.style.bottom !== "auto" && dialog.style.bottom !== "") {
2344
+ return false;
2345
+ }
2346
+ return !dialogPolyfill.isInlinePositionSetByStylesheet(dialog);
2347
+ };
2348
+ dialogPolyfill.forceRegisterDialog = function(element) {
2349
+ if (window.HTMLDialogElement || element.showModal) {
2350
+ console.warn("This browser already supports <dialog>, the polyfill may not work correctly", element);
2351
+ }
2352
+ if (element.localName !== "dialog") {
2353
+ throw new Error("Failed to register dialog: The element is not a dialog.");
2354
+ }
2355
+ new dialogPolyfillInfo(element);
2356
+ };
2357
+ dialogPolyfill.registerDialog = function(element) {
2358
+ if (!element.showModal) {
2359
+ dialogPolyfill.forceRegisterDialog(element);
2360
+ }
2361
+ };
2362
+ dialogPolyfill.DialogManager = function() {
2363
+ this.pendingDialogStack = [];
2364
+ var checkDOM = this.checkDOM_.bind(this);
2365
+ this.overlay = document.createElement("div");
2366
+ this.overlay.className = "_dialog_overlay";
2367
+ this.overlay.addEventListener("click", function(e) {
2368
+ this.forwardTab_ = void 0;
2369
+ e.stopPropagation();
2370
+ checkDOM([]);
2371
+ }.bind(this));
2372
+ this.handleKey_ = this.handleKey_.bind(this);
2373
+ this.handleFocus_ = this.handleFocus_.bind(this);
2374
+ this.zIndexLow_ = 1e5;
2375
+ this.zIndexHigh_ = 1e5 + 150;
2376
+ this.forwardTab_ = void 0;
2377
+ if ("MutationObserver" in window) {
2378
+ this.mo_ = new MutationObserver(function(records) {
2379
+ var removed = [];
2380
+ records.forEach(function(rec) {
2381
+ for (var i = 0, c; c = rec.removedNodes[i]; ++i) {
2382
+ if (!(c instanceof Element)) {
2383
+ continue;
2384
+ } else if (c.localName === "dialog") {
2385
+ removed.push(c);
2386
+ }
2387
+ removed = removed.concat(c.querySelectorAll("dialog"));
2388
+ }
2389
+ });
2390
+ removed.length && checkDOM(removed);
2391
+ });
2392
+ }
2393
+ };
2394
+ dialogPolyfill.DialogManager.prototype.blockDocument = function() {
2395
+ document.documentElement.addEventListener("focus", this.handleFocus_, true);
2396
+ document.addEventListener("keydown", this.handleKey_);
2397
+ this.mo_ && this.mo_.observe(document, { childList: true, subtree: true });
2398
+ };
2399
+ dialogPolyfill.DialogManager.prototype.unblockDocument = function() {
2400
+ document.documentElement.removeEventListener("focus", this.handleFocus_, true);
2401
+ document.removeEventListener("keydown", this.handleKey_);
2402
+ this.mo_ && this.mo_.disconnect();
2403
+ };
2404
+ dialogPolyfill.DialogManager.prototype.updateStacking = function() {
2405
+ var zIndex = this.zIndexHigh_;
2406
+ for (var i = 0, dpi; dpi = this.pendingDialogStack[i]; ++i) {
2407
+ dpi.updateZIndex(--zIndex, --zIndex);
2408
+ if (i === 0) {
2409
+ this.overlay.style.zIndex = --zIndex;
2410
+ }
2411
+ }
2412
+ var last = this.pendingDialogStack[0];
2413
+ if (last) {
2414
+ var p = last.dialog.parentNode || document.body;
2415
+ p.appendChild(this.overlay);
2416
+ } else if (this.overlay.parentNode) {
2417
+ this.overlay.parentNode.removeChild(this.overlay);
2418
+ }
2419
+ };
2420
+ dialogPolyfill.DialogManager.prototype.containedByTopDialog_ = function(candidate) {
2421
+ while (candidate = findNearestDialog(candidate)) {
2422
+ for (var i = 0, dpi; dpi = this.pendingDialogStack[i]; ++i) {
2423
+ if (dpi.dialog === candidate) {
2424
+ return i === 0;
2425
+ }
2426
+ }
2427
+ candidate = candidate.parentElement;
2428
+ }
2429
+ return false;
2430
+ };
2431
+ dialogPolyfill.DialogManager.prototype.handleFocus_ = function(event) {
2432
+ var target = event.composedPath ? event.composedPath()[0] : event.target;
2433
+ if (this.containedByTopDialog_(target)) {
2434
+ return;
2435
+ }
2436
+ if (document.activeElement === document.documentElement) {
2437
+ return;
2438
+ }
2439
+ event.preventDefault();
2440
+ event.stopPropagation();
2441
+ safeBlur(target);
2442
+ if (this.forwardTab_ === void 0) {
2443
+ return;
2444
+ }
2445
+ var dpi = this.pendingDialogStack[0];
2446
+ var dialog = dpi.dialog;
2447
+ var position = dialog.compareDocumentPosition(target);
2448
+ if (position & Node.DOCUMENT_POSITION_PRECEDING) {
2449
+ if (this.forwardTab_) {
2450
+ dpi.focus_();
2451
+ } else if (target !== document.documentElement) {
2452
+ document.documentElement.focus();
2453
+ }
2454
+ }
2455
+ return false;
2456
+ };
2457
+ dialogPolyfill.DialogManager.prototype.handleKey_ = function(event) {
2458
+ this.forwardTab_ = void 0;
2459
+ if (event.keyCode === 27) {
2460
+ event.preventDefault();
2461
+ event.stopPropagation();
2462
+ var cancelEvent = new supportCustomEvent("cancel", {
2463
+ bubbles: false,
2464
+ cancelable: true
2465
+ });
2466
+ var dpi = this.pendingDialogStack[0];
2467
+ if (dpi && safeDispatchEvent(dpi.dialog, cancelEvent)) {
2468
+ dpi.dialog.close();
2469
+ }
2470
+ } else if (event.keyCode === 9) {
2471
+ this.forwardTab_ = !event.shiftKey;
2472
+ }
2473
+ };
2474
+ dialogPolyfill.DialogManager.prototype.checkDOM_ = function(removed) {
2475
+ var clone = this.pendingDialogStack.slice();
2476
+ clone.forEach(function(dpi) {
2477
+ if (removed.indexOf(dpi.dialog) !== -1) {
2478
+ dpi.downgradeModal();
2479
+ } else {
2480
+ dpi.maybeHideModal();
2481
+ }
2482
+ });
2483
+ };
2484
+ dialogPolyfill.DialogManager.prototype.pushDialog = function(dpi) {
2485
+ var allowed = (this.zIndexHigh_ - this.zIndexLow_) / 2 - 1;
2486
+ if (this.pendingDialogStack.length >= allowed) {
2487
+ return false;
2488
+ }
2489
+ if (this.pendingDialogStack.unshift(dpi) === 1) {
2490
+ this.blockDocument();
2491
+ }
2492
+ this.updateStacking();
2493
+ return true;
2494
+ };
2495
+ dialogPolyfill.DialogManager.prototype.removeDialog = function(dpi) {
2496
+ var index = this.pendingDialogStack.indexOf(dpi);
2497
+ if (index === -1) {
2498
+ return;
2499
+ }
2500
+ this.pendingDialogStack.splice(index, 1);
2501
+ if (this.pendingDialogStack.length === 0) {
2502
+ this.unblockDocument();
2503
+ }
2504
+ this.updateStacking();
2505
+ };
2506
+ dialogPolyfill.dm = new dialogPolyfill.DialogManager();
2507
+ dialogPolyfill.formSubmitter = null;
2508
+ dialogPolyfill.imagemapUseValue = null;
2509
+ if (window.HTMLDialogElement === void 0) {
2510
+ var testForm = document.createElement("form");
2511
+ testForm.setAttribute("method", "dialog");
2512
+ if (testForm.method !== "dialog") {
2513
+ var methodDescriptor = Object.getOwnPropertyDescriptor(HTMLFormElement.prototype, "method");
2514
+ if (methodDescriptor) {
2515
+ var realGet = methodDescriptor.get;
2516
+ methodDescriptor.get = function() {
2517
+ if (isFormMethodDialog(this)) {
2518
+ return "dialog";
2519
+ }
2520
+ return realGet.call(this);
2521
+ };
2522
+ var realSet = methodDescriptor.set;
2523
+ methodDescriptor.set = function(v) {
2524
+ if (typeof v === "string" && v.toLowerCase() === "dialog") {
2525
+ return this.setAttribute("method", v);
2526
+ }
2527
+ return realSet.call(this, v);
2528
+ };
2529
+ Object.defineProperty(HTMLFormElement.prototype, "method", methodDescriptor);
2530
+ }
2531
+ }
2532
+ document.addEventListener("click", function(ev) {
2533
+ dialogPolyfill.formSubmitter = null;
2534
+ dialogPolyfill.imagemapUseValue = null;
2535
+ if (ev.defaultPrevented) {
2536
+ return;
2537
+ }
2538
+ var target = ev.target;
2539
+ if ("composedPath" in ev) {
2540
+ var path = ev.composedPath();
2541
+ target = path.shift() || target;
2542
+ }
2543
+ if (!target || !isFormMethodDialog(target.form)) {
2544
+ return;
2545
+ }
2546
+ var valid = target.type === "submit" && ["button", "input"].indexOf(target.localName) > -1;
2547
+ if (!valid) {
2548
+ if (!(target.localName === "input" && target.type === "image")) {
2549
+ return;
2550
+ }
2551
+ dialogPolyfill.imagemapUseValue = ev.offsetX + "," + ev.offsetY;
2552
+ }
2553
+ var dialog = findNearestDialog(target);
2554
+ if (!dialog) {
2555
+ return;
2556
+ }
2557
+ dialogPolyfill.formSubmitter = target;
2558
+ }, false);
2559
+ document.addEventListener("submit", function(ev) {
2560
+ var form = ev.target;
2561
+ var dialog = findNearestDialog(form);
2562
+ if (dialog) {
2563
+ return;
2564
+ }
2565
+ var submitter = findFormSubmitter(ev);
2566
+ var formmethod = submitter && submitter.getAttribute("formmethod") || form.getAttribute("method");
2567
+ if (formmethod === "dialog") {
2568
+ ev.preventDefault();
2569
+ }
2570
+ });
2571
+ var nativeFormSubmit = HTMLFormElement.prototype.submit;
2572
+ var replacementFormSubmit = function() {
2573
+ if (!isFormMethodDialog(this)) {
2574
+ return nativeFormSubmit.call(this);
2575
+ }
2576
+ var dialog = findNearestDialog(this);
2577
+ dialog && dialog.close();
2578
+ };
2579
+ HTMLFormElement.prototype.submit = replacementFormSubmit;
2580
+ }
2581
+ class LightboxImageController extends BaseController {
2582
+ constructor() {
2583
+ super(...arguments);
2584
+ __publicField(this, "_dialog", null);
2585
+ }
2586
+ get _src() {
2587
+ return this.hasSrcValue ? this.srcValue : this.el.src;
2588
+ }
2589
+ get _srcSet() {
2590
+ return this.hasSrcSetValue ? this.srcSetValue : this.el.srcset;
2591
+ }
2592
+ get _sizes() {
2593
+ return this.hasSizesValue ? this.sizesValue : this.el.sizes;
2594
+ }
2595
+ get _modalClassName() {
2596
+ return this.hasModalClass ? this.modalClass : "image-lightbox-dialog";
2597
+ }
2598
+ get _imageClassName() {
2599
+ return this.hasImageClass ? this.imageClass : "image-lightbox-image";
2600
+ }
2601
+ initialize() {
2602
+ this.open = this.open.bind(this);
2603
+ this.close = this.close.bind(this);
2604
+ }
2605
+ connect() {
2606
+ }
2607
+ disconnect() {
2608
+ this.close();
2609
+ }
2610
+ open() {
2611
+ let element = this.el;
2612
+ if (this._dialog) {
2613
+ return;
2614
+ }
2615
+ this._dialog = document.createElement("dialog");
2616
+ let image = document.createElement("img");
2617
+ image.className = this._imageClassName;
2618
+ image.src = this._src;
2619
+ image.srcset = this._srcSet;
2620
+ image.sizes = this._sizes;
2621
+ this._dialog.appendChild(image);
2622
+ element.insertAdjacentElement("afterend", this._dialog);
2623
+ dialogPolyfill.registerDialog(this._dialog);
2624
+ this._dialog.className = this._modalClassName;
2625
+ this._dialog.showModal();
2626
+ scrollToElement(this._dialog, { behavior: "smooth", block: "end" }).catch(() => this._dialog.scrollIntoView(false));
2627
+ useEventListener(this, this._dialog, "click", this.close);
2628
+ useEventListener(this, this._dialog, "cancel", this.close);
2629
+ useEventListener(this, this._dialog, "close", this.close);
2630
+ }
2631
+ close() {
2632
+ if (this._dialog) {
2633
+ this._dialog.close();
2634
+ this._dialog.remove();
2635
+ this._dialog = null;
2636
+ scrollToElement(this.el, { behavior: "smooth", block: "end" }).catch(() => this.el.scrollIntoView(false));
2637
+ }
2638
+ }
2639
+ }
2640
+ __publicField(LightboxImageController, "values", {
2641
+ src: String,
2642
+ srcSet: String,
2643
+ sizes: String
2644
+ });
2645
+ __publicField(LightboxImageController, "classes", ["modal", "image"]);
2646
+ class MediaPlayerController extends BaseController {
2647
+ async play(event) {
2648
+ event == null ? void 0 : event.preventDefault();
2649
+ await this.mediaTarget.play();
2650
+ }
2651
+ pause(event) {
2652
+ event == null ? void 0 : event.preventDefault();
2653
+ this.mediaTarget.pause();
2654
+ }
2655
+ restart(event) {
2656
+ event == null ? void 0 : event.preventDefault();
2657
+ this.mediaTarget.currentTime = 0;
2658
+ }
2659
+ seek(event) {
2660
+ event == null ? void 0 : event.preventDefault();
2661
+ this.mediaTarget.currentTime += 5;
2662
+ }
2663
+ }
2664
+ __publicField(MediaPlayerController, "targets", ["media"]);
2665
+ class ScrollContainerController extends BaseController {
2666
+ get _increment() {
2667
+ return this.hasIncrementValue ? this.incrementValue : 50;
2668
+ }
2669
+ get _behaviour() {
2670
+ if (this.hasBehaviourValue) {
2671
+ if (["auto", "smooth"].includes(this.behaviourValue)) {
2672
+ return this.behaviourValue;
2673
+ } else {
2674
+ throw new Error(`'${this.behaviourValue}' is not a recognised scroll behaviour`);
2675
+ }
2676
+ } else {
2677
+ return "auto";
2678
+ }
2679
+ }
2680
+ async scrollTop(event) {
2681
+ event == null ? void 0 : event.preventDefault();
2682
+ await scrollAbsoluteTop(this.el, { behavior: this._behaviour });
2683
+ }
2684
+ async scrollBottom(event) {
2685
+ event == null ? void 0 : event.preventDefault();
2686
+ await scrollAbsoluteBottom(this.el, { behavior: this._behaviour });
2687
+ }
2688
+ async scrollLeft(event) {
2689
+ event == null ? void 0 : event.preventDefault();
2690
+ await scrollAbsoluteLeft(this.el, { behavior: this._behaviour });
2691
+ }
2692
+ async scrollRight(event) {
2693
+ event == null ? void 0 : event.preventDefault();
2694
+ await scrollAbsoluteLeft(this.el, { behavior: this._behaviour });
2695
+ }
2696
+ async up(event) {
2697
+ event == null ? void 0 : event.preventDefault();
2698
+ await scrollUp(this.el, this._increment, { behavior: this._behaviour });
2699
+ }
2700
+ async down(event) {
2701
+ event == null ? void 0 : event.preventDefault();
2702
+ await scrollDown(this.el, this._increment, { behavior: this._behaviour });
2703
+ }
2704
+ async left(event) {
2705
+ event == null ? void 0 : event.preventDefault();
2706
+ await scrollLeft(this.el, this._increment, { behavior: this._behaviour });
2707
+ }
2708
+ async right(event) {
2709
+ event == null ? void 0 : event.preventDefault();
2710
+ await scrollRight(this.el, this._increment, { behavior: this._behaviour });
2711
+ }
2712
+ }
2713
+ __publicField(ScrollContainerController, "values", {
2714
+ behaviour: String,
2715
+ increment: Number
2716
+ });
2717
+ class ScrollIntoFocusController extends EphemeralController {
2718
+ connect() {
2719
+ requestAnimationFrame(() => {
2720
+ scrollToElement(this.el, {
2721
+ behavior: this.hasBehaviorValue ? this.behaviorValue : "smooth",
2722
+ block: this.hasBlockValue ? this.blockValue : "center",
2723
+ inline: this.hasInlineValue ? this.inlineValue : "center"
2724
+ }).catch(() => this.el.scrollIntoView());
2725
+ this._cleanupSelf();
2726
+ });
2727
+ }
2728
+ }
2729
+ __publicField(ScrollIntoFocusController, "values", {
2730
+ behavior: String,
2731
+ block: String,
2732
+ inline: String
2733
+ });
2734
+ class ScrollToBottomController extends BaseController {
2735
+ get _mode() {
2736
+ return this.hasModeValue ? this.modeValue : "document";
2737
+ }
2738
+ get _scrollTarget() {
2739
+ let target;
2740
+ if (this._mode == "document") {
2741
+ target = window;
2742
+ } else {
2743
+ target = getScrollParent(this.el);
2744
+ }
2745
+ return target;
2746
+ }
2747
+ async scroll(event) {
2748
+ event == null ? void 0 : event.preventDefault();
2749
+ if (this._scrollTarget) {
2750
+ await scrollAbsoluteBottom(this._scrollTarget);
2751
+ }
2752
+ }
2753
+ }
2754
+ __publicField(ScrollToBottomController, "values", {
2755
+ mode: String
2756
+ });
2757
+ class ScrollToController extends BaseController {
2758
+ scroll() {
2759
+ let target = document.querySelector(this.selectorValue);
2760
+ if (!target) {
2761
+ console.warn(`Could not find target for '${this.selectorValue}'`);
2762
+ return;
2763
+ }
2764
+ scrollToElement(target, {
2765
+ behavior: this.hasBehaviorValue ? this.behaviorValue : "smooth",
2766
+ block: this.hasBlockValue ? this.blockValue : "center",
2767
+ inline: this.hasInlineValue ? this.inlineValue : "center"
2768
+ }).catch(() => target.scrollIntoView());
2769
+ }
2770
+ }
2771
+ __publicField(ScrollToController, "values", {
2772
+ selector: String,
2773
+ behavior: String,
2774
+ block: String,
2775
+ inline: String
2776
+ });
2777
+ class ScrollToTopController extends BaseController {
2778
+ get _mode() {
2779
+ return this.hasModeValue ? this.modeValue : "document";
2780
+ }
2781
+ get _scrollTarget() {
2782
+ let target;
2783
+ if (this._mode == "document") {
2784
+ target = window;
2785
+ } else {
2786
+ target = getScrollParent(this.el);
2787
+ }
2788
+ return target;
2789
+ }
2790
+ async scroll(event) {
2791
+ event == null ? void 0 : event.preventDefault();
2792
+ if (this._scrollTarget) {
2793
+ await scrollAbsoluteTop(this._scrollTarget);
2794
+ }
2795
+ }
2796
+ }
2797
+ __publicField(ScrollToTopController, "values", {
2798
+ mode: String
2799
+ });
2800
+ function extractPredicates(expressionString) {
2801
+ expressionString = expressionString.trim();
2802
+ let andExpression = expressionString.includes("&&");
2803
+ let orExpression = expressionString.includes("||");
2804
+ let groupings = expressionString.includes("(") || expressionString.includes(")");
2805
+ if (andExpression && orExpression) {
2806
+ throw new Error("Cannot have both && and || in the same expression.");
2807
+ }
2808
+ if (groupings) {
2809
+ throw new Error("Cannot have logical groupings `(>3 && <= 9) || (>1 && <2)` in the expression. Only supports simple expressions like `>1 && <3`");
2810
+ }
2811
+ let expressions = expressionString.split(andExpression ? "&&" : "||");
2812
+ if (andExpression) {
2813
+ return expressions.map((ex) => _predicateForExpression(ex));
2814
+ } else if (orExpression) {
2815
+ return expressions.map((ex) => _predicateForExpression(ex));
2816
+ } else {
2817
+ return [_predicateForExpression(expressionString)];
2818
+ }
2819
+ }
2820
+ function _predicateForExpression(expression) {
2821
+ let operators = [">=", "<=", "==", "!=", ">", "<"];
2822
+ let operator = operators.find((part) => expression.includes(part));
2823
+ if (!operator) {
2824
+ throw new Error(`Could not find operator in expression: ${expression}`);
2825
+ }
2826
+ let expressionValue = expression.split(operator)[1].trim();
2827
+ let isNumber = /^-?[0-9]\d*(\.\d+)?$/.test(expressionValue);
2828
+ expressionValue = isNumber ? parseFloat(expressionValue) : expressionValue;
2829
+ if (expressionValue == "") {
2830
+ throw new Error(`Could not find a value in expression: ${expression}`);
2831
+ }
2832
+ let notEmpty = (signalValue) => signalValue !== "";
2833
+ switch (operator) {
2834
+ case ">":
2835
+ return (signalValue) => isNumber && notEmpty(signalValue) && signalValue > expressionValue;
2836
+ case "<":
2837
+ return (signalValue) => isNumber && notEmpty(signalValue) && signalValue < expressionValue;
2838
+ case ">=":
2839
+ return (signalValue) => isNumber && notEmpty(signalValue) && signalValue >= expressionValue;
2840
+ case "<=":
2841
+ return (signalValue) => isNumber && notEmpty(signalValue) && signalValue <= expressionValue;
2842
+ case "==":
2843
+ return (signalValue) => notEmpty(signalValue) && signalValue == expressionValue;
2844
+ case "!=":
2845
+ return (signalValue) => notEmpty(signalValue) && signalValue != expressionValue;
2846
+ default:
2847
+ throw new Error(`Unknown operator ${operator}`);
2848
+ }
2849
+ }
2850
+ function signalEventName(name, type) {
2851
+ return `signal:${type}:${name}`;
2852
+ }
2853
+ function signalConnectEvent(name) {
2854
+ return signalEventName(name, "connect");
2855
+ }
2856
+ function signalValueEvent(name) {
2857
+ return signalEventName(name, "value");
2858
+ }
2859
+ class SignalActionController extends BaseController {
2860
+ get _predicates() {
2861
+ return extractPredicates(this.whenValue);
2862
+ }
2863
+ connect() {
2864
+ EventBus.emit(signalConnectEvent(this.nameValue));
2865
+ useEventBus(this, signalValueEvent(this.nameValue), this._onSignal);
2866
+ }
2867
+ _onSignal(payload) {
2868
+ let value = payload.value;
2869
+ if (!this.hasWhenValue) {
2870
+ this.dispatchEvent(this.el, signalEventName(this.nameValue, "match"));
2871
+ return;
2872
+ }
2873
+ if (this._predicates.every((predicate) => predicate(value))) {
2874
+ this.dispatchEvent(this.el, signalEventName(this.nameValue, "match"), { detail: { element: this.el, value } });
2875
+ } else {
2876
+ this.dispatchEvent(this.el, signalEventName(this.nameValue, "no-match"), { detail: { element: this.el, value } });
2877
+ }
2878
+ }
2879
+ }
2880
+ __publicField(SignalActionController, "values", {
2881
+ name: String,
2882
+ when: String
2883
+ });
2884
+ class SignalInputController extends BaseController {
2885
+ get _debounceTimeout() {
2886
+ return this.hasDebounceIntervalValue ? this.debounceIntervalValue : null;
2887
+ }
2888
+ get _name() {
2889
+ return this.hasNameValue ? this.nameValue : this.element.name;
2890
+ }
2891
+ connect() {
2892
+ useEventBus(this, signalConnectEvent(this._name), () => this.emitValue());
2893
+ useEventListener(this, this.el, "input", this.emitValue, { debounce: this._debounceTimeout || void 0 });
2894
+ useEventListener(this, this.el, "change", this.emitValue);
2895
+ requestAnimationFrame(() => this.emitValue());
2896
+ }
2897
+ emitValue() {
2898
+ var _a;
2899
+ let value = this.el.value;
2900
+ if (isHTMLInputElement(this.el) && this.el.type === "checkbox") {
2901
+ value = this.el.checked ? "true" : "false";
2902
+ } else if (isHTMLInputElement(this.el) && this.el.type === "radio") {
2903
+ let selectedValue = (_a = getAllRadiosInGroup(this.el).find((el) => el.checked)) == null ? void 0 : _a.value;
2904
+ value = selectedValue ? selectedValue : "";
2905
+ }
2906
+ EventBus.emit(signalValueEvent(this._name), { element: this.el, value });
2907
+ }
2908
+ }
2909
+ __publicField(SignalInputController, "values", {
2910
+ name: String,
2911
+ debounceInterval: Number
2912
+ });
2913
+ class SignalVisibilityController extends BaseController {
2914
+ get _predicates() {
2915
+ return extractPredicates(this.showValue);
2916
+ }
2917
+ get defaultHideClasses() {
2918
+ return ["hide"];
2919
+ }
2920
+ connect() {
2921
+ installClassMethods(this);
2922
+ EventBus.emit(signalConnectEvent(this.nameValue));
2923
+ useEventBus(this, signalValueEvent(this.nameValue), this._onSignal);
2924
+ }
2925
+ _onSignal(payload) {
2926
+ let value = payload.value;
2927
+ if (this.showValue == "default") {
2928
+ if (value == "") {
2929
+ this.removeHideClasses(this.el);
2930
+ } else {
2931
+ this.addHideClasses(this.el);
2932
+ }
2933
+ return;
2934
+ }
2935
+ if (this._predicates.every((predicate) => predicate(value))) {
2936
+ this.removeHideClasses(this.el);
2937
+ } else {
2938
+ this.addHideClasses(this.el);
2939
+ }
2940
+ }
2941
+ }
2942
+ __publicField(SignalVisibilityController, "values", {
2943
+ name: String,
2944
+ show: String
2945
+ });
2946
+ __publicField(SignalVisibilityController, "classes", ["hide"]);
2947
+ class TableSortController extends BaseController {
2948
+ constructor() {
2949
+ super(...arguments);
2950
+ __publicField(this, "_lastIndex", null);
2951
+ __publicField(this, "_reverse", false);
2952
+ }
2953
+ get _tableHead() {
2954
+ let head = this.el.tHead;
2955
+ if (head == null) {
2956
+ throw new Error("Expected table to have a <thead> element.");
2957
+ }
2958
+ return head;
2959
+ }
2960
+ get _tableHeaders() {
2961
+ let rows = this._tableHead.rows;
2962
+ if (rows.length == 0) {
2963
+ throw new Error("Expected table to have a <thead> element with at least one row.");
2964
+ }
2965
+ return Array.from(rows[0].cells);
2966
+ }
2967
+ get _tableBody() {
2968
+ return this.el.tBodies[0];
2969
+ }
2970
+ get _tableRows() {
2971
+ return Array.from(this._tableBody.rows);
2972
+ }
2973
+ connect() {
2974
+ requestAnimationFrame(() => {
2975
+ useCollectionEventListener(this, this._tableHeaders, "click", this.sort);
2976
+ if (this.hasStartSortValue) {
2977
+ this._sortByColumn(this.startSortValue);
2978
+ }
2979
+ });
2980
+ }
2981
+ sort(event) {
2982
+ event.preventDefault();
2983
+ let headerCell = event.target;
2984
+ let headerCellIndex = this._indexOfHeaderCell(headerCell);
2985
+ if (headerCell.dataset.sortable == "false") {
2986
+ return;
2987
+ }
2988
+ if (headerCell.dataset.sort == "asc") {
2989
+ this._reverse = true;
2990
+ this._otherHeaderCells(headerCell).forEach((cell) => delete cell.dataset.sort);
2991
+ headerCell.dataset.sort = "desc";
2992
+ this._sortByColumn(headerCellIndex);
2993
+ } else {
2994
+ this._reverse = false;
2995
+ this._otherHeaderCells(headerCell).forEach((cell) => delete cell.dataset.sort);
2996
+ headerCell.dataset.sort = "asc";
2997
+ this._sortByColumn(headerCellIndex);
2998
+ }
2999
+ }
3000
+ _indexOfHeaderCell(cell) {
3001
+ return this._tableHeaders.indexOf(cell);
3002
+ }
3003
+ _otherHeaderCells(cell) {
3004
+ return Array.from(this._tableHeaders).filter((otherCell) => otherCell != cell);
3005
+ }
3006
+ _sortByColumn(index) {
3007
+ let frag = document.createDocumentFragment();
3008
+ let rows = this._tableRows;
3009
+ let newRows = rows.sort((row, otherRow) => {
3010
+ var _a, _b;
3011
+ let cells = Array.from(row.cells);
3012
+ let otherCells = Array.from(otherRow.cells);
3013
+ let x = ((_a = cells[index]) == null ? void 0 : _a.innerText) || "";
3014
+ let y = ((_b = otherCells[index]) == null ? void 0 : _b.innerText) || "";
3015
+ let sortVal = x.localeCompare(y, "en", { sensitivity: "base", numeric: true, caseFirst: "upper" });
3016
+ if (row.dataset.sortTop || otherRow.dataset.sortBottom) {
3017
+ if (row.dataset.sortTop && otherRow.dataset.sortTop) {
3018
+ return sortVal;
3019
+ }
3020
+ return -1;
3021
+ }
3022
+ if (row.dataset.sortBottom || otherRow.dataset.sortTop) {
3023
+ if (row.dataset.sortBottom && otherRow.dataset.sortBottom) {
3024
+ return sortVal;
3025
+ }
3026
+ return 1;
3027
+ }
3028
+ if (this._reverse) {
3029
+ return sortVal > 0 ? -1 : 1;
3030
+ }
3031
+ return sortVal;
3032
+ });
3033
+ newRows.forEach((row) => frag.appendChild(row));
3034
+ this._tableBody.innerHTML = "";
3035
+ this._tableBody.appendChild(frag);
3036
+ this._lastIndex = index;
3037
+ }
3038
+ }
3039
+ __publicField(TableSortController, "values", { startSort: Number });
3040
+ function useMutationObserver(controller, element, handler, options) {
3041
+ handler = handler.bind(controller);
3042
+ let observer = new MutationObserver(handler);
3043
+ let setup = () => observer.observe(element, options);
3044
+ let teardown = () => observer.disconnect();
3045
+ useMixin(controller, setup, teardown);
3046
+ return teardown;
3047
+ }
3048
+ class TableTruncateController extends BaseController {
3049
+ get _truncated() {
3050
+ return this.hasTruncatedValue ? this.truncatedValue : false;
3051
+ }
3052
+ set _truncated(value) {
3053
+ this.truncatedValue = value;
3054
+ }
3055
+ get _tableBody() {
3056
+ return this.el.tBodies[0];
3057
+ }
3058
+ get _tableRows() {
3059
+ return Array.from(this._tableBody.rows);
3060
+ }
3061
+ get _limit() {
3062
+ return this.hasLimitValue ? this.limitValue : 20;
3063
+ }
3064
+ connect() {
3065
+ useMutationObserver(this, this._tableBody, this.mutate, { childList: true });
3066
+ requestAnimationFrame(() => {
3067
+ this.truncate();
3068
+ useEventListener(this, this.showMoreTarget, "click", this.expand);
3069
+ });
3070
+ }
3071
+ truncate(event) {
3072
+ event == null ? void 0 : event.preventDefault();
3073
+ this._truncated = true;
3074
+ if (this._tableRows.length >= this._limit) {
3075
+ this._tableRows.slice(this._limit).forEach((el) => {
3076
+ if (el !== this.showMoreTarget) {
3077
+ this._hideElement(el);
3078
+ }
3079
+ });
3080
+ this._showElement(this.showMoreTarget);
3081
+ } else {
3082
+ this._hideElement(this.showMoreTarget);
3083
+ }
3084
+ }
3085
+ expand(event) {
3086
+ this._truncated = false;
3087
+ event == null ? void 0 : event.preventDefault();
3088
+ this._tableRows.slice(this._limit).forEach((el) => {
3089
+ if (el !== this.showMoreTarget) {
3090
+ this._showElement(el);
3091
+ }
3092
+ });
3093
+ this._hideElement(this.showMoreTarget);
3094
+ }
3095
+ mutate(entries) {
3096
+ if (this._truncated) {
3097
+ this._reTruncate();
3098
+ }
3099
+ }
3100
+ _showElement(el) {
3101
+ el.style.display = "";
3102
+ }
3103
+ _hideElement(el) {
3104
+ el.style.display = "none";
3105
+ }
3106
+ _reTruncate() {
3107
+ this._tableRows.slice(0, this._limit).forEach((el) => {
3108
+ if (el !== this.showMoreTarget) {
3109
+ this._showElement(el);
3110
+ }
3111
+ });
3112
+ this._tableRows.slice(this._limit).forEach((el) => {
3113
+ if (el !== this.showMoreTarget) {
3114
+ this._hideElement(el);
3115
+ }
3116
+ });
3117
+ this._showElement(this.showMoreTarget);
3118
+ }
3119
+ }
3120
+ __publicField(TableTruncateController, "targets", ["showMore"]);
3121
+ __publicField(TableTruncateController, "values", {
3122
+ limit: Number,
3123
+ truncated: Boolean
3124
+ });
3125
+ class AlertController extends BaseController {
3126
+ alert() {
3127
+ alert(this.messageValue);
3128
+ }
3129
+ }
3130
+ __publicField(AlertController, "values", { message: String });
3131
+ class FullscreenController extends BaseController {
3132
+ connect() {
3133
+ let { enter, exit, toggle } = useFullscreen(this);
3134
+ this.enter = enter;
3135
+ this.exit = exit;
3136
+ this.toggle = toggle;
3137
+ }
3138
+ }
3139
+ function dispatchEvent(controller, element, eventName, options = {}) {
3140
+ let mergedOptions = Object.assign({}, { bubbles: true, cancelable: true, detail: { target: element } }, options);
3141
+ if (!!mergedOptions.detail.target) {
3142
+ mergedOptions.detail.target = element;
3143
+ }
3144
+ let event = new CustomEvent(eventName, mergedOptions);
3145
+ logEvent(controller, eventName, event, element);
3146
+ element.dispatchEvent(event);
3147
+ }
3148
+ class IntersectionController extends BaseController {
3149
+ get _threshold() {
3150
+ if (this.hasThresholdValue) {
3151
+ return this.thresholdValue.split(",").map((val) => Number.parseFloat(val.trim())).filter((val) => val >= 0 && val <= 1);
3152
+ } else {
3153
+ return [0, 1];
3154
+ }
3155
+ }
3156
+ connect() {
3157
+ useIntersection(this, this.el, this.appear, this.disappear, { threshold: this._threshold });
3158
+ }
3159
+ appear(entry) {
3160
+ dispatchEvent(this, this.el, "intersection:appear");
3161
+ }
3162
+ disappear(entry) {
3163
+ dispatchEvent(this, this.el, "intersection:disappear");
3164
+ }
3165
+ }
3166
+ __publicField(IntersectionController, "values", { threshold: String });
3167
+ class IntervalController extends BaseController {
3168
+ connect() {
3169
+ if (!this.hasSecondsValue) {
3170
+ throw new Error("Expected `secondsValue` to be present");
3171
+ }
3172
+ requestAnimationFrame(() => {
3173
+ useInterval(this, this._interval, this.secondsValue * 1e3);
3174
+ });
3175
+ }
3176
+ _interval() {
3177
+ this.dispatchEvent(this.el, "interval:action");
3178
+ }
3179
+ }
3180
+ __publicField(IntervalController, "values", { seconds: Number });
3181
+ class PresenceController extends BaseController {
3182
+ get name() {
3183
+ return this.hasNameValue ? this.nameValue : ``;
3184
+ }
3185
+ get _addedEventName() {
3186
+ return [this.name, "presence", "added"].filter((el) => !!el).join(":");
3187
+ }
3188
+ get _removedEventName() {
3189
+ return [this.name, "presence", "removed"].filter((el) => !!el).join(":");
3190
+ }
3191
+ connect() {
3192
+ this.dispatchEvent(this.el, this._addedEventName);
3193
+ }
3194
+ disconnect() {
3195
+ this.dispatchEvent(this.el, this._removedEventName);
3196
+ }
3197
+ }
3198
+ __publicField(PresenceController, "values", { name: String });
3199
+ class PrintController extends BaseController {
3200
+ print(event) {
3201
+ event == null ? void 0 : event.preventDefault();
3202
+ window.print();
3203
+ }
3204
+ }
3205
+ class TimeoutController extends BaseController {
3206
+ connect() {
3207
+ requestAnimationFrame(() => {
3208
+ useTimeout(this, this._timeout, this.secondsValue * 1e3);
3209
+ });
3210
+ }
3211
+ _timeout() {
3212
+ this.dispatchEvent(this.el, "timeout");
3213
+ }
3214
+ }
3215
+ __publicField(TimeoutController, "values", { seconds: Number });
3216
+ class UserFocusController extends BaseController {
3217
+ connect() {
3218
+ useEventListener(this, window, ["focus", "blur"], this._handleVisibility);
3219
+ useEventListener(this, document, "visibilitychange", this._handleVisibility);
3220
+ requestAnimationFrame(() => {
3221
+ this._handleVisibility();
3222
+ });
3223
+ }
3224
+ appear() {
3225
+ this.dispatchEvent(this.el, "user-focus:active");
3226
+ }
3227
+ away() {
3228
+ this.dispatchEvent(this.el, "user-focus:away");
3229
+ }
3230
+ _handleVisibility() {
3231
+ this._documentIsActive() ? this.appear() : this.away();
3232
+ }
3233
+ _documentIsActive() {
3234
+ return document.visibilityState == "visible" && document.hasFocus();
3235
+ }
3236
+ }
3237
+ class ClockController extends BaseController {
3238
+ get _tickInterval() {
3239
+ if (this.hasMillisecondsTarget) {
3240
+ return 1;
3241
+ } else if (this.hasSecondsTarget) {
3242
+ return 1e3;
3243
+ } else if (this.hasMinutesTarget) {
3244
+ return 15e3;
3245
+ } else {
3246
+ return 3e5;
3247
+ }
3248
+ }
3249
+ connect() {
3250
+ requestAnimationFrame(() => {
3251
+ useInterval(this, this._tick, this._tickInterval);
3252
+ });
3253
+ }
3254
+ _tick() {
3255
+ let current = new Date();
3256
+ if (this.hasHoursTarget) {
3257
+ this.hoursTarget.innerHTML = current.getHours().toString().padStart(2, "0");
3258
+ }
3259
+ if (this.hasMinutesTarget) {
3260
+ this.minutesTarget.innerHTML = current.getMinutes().toString().padStart(2, "0");
3261
+ }
3262
+ if (this.hasSecondsTarget) {
3263
+ this.secondsTarget.innerHTML = current.getSeconds().toString().padStart(2, "0");
3264
+ }
3265
+ if (this.hasMillisecondsTarget) {
3266
+ this.millisecondsTarget.innerHTML = current.getMilliseconds().toString().padStart(3, "0");
3267
+ }
3268
+ }
3269
+ }
3270
+ __publicField(ClockController, "targets", ["hours", "minutes", "seconds", "milliseconds"]);
3271
+ class CountdownController extends BaseController {
3272
+ constructor() {
3273
+ super(...arguments);
3274
+ __publicField(this, "_interval", null);
3275
+ }
3276
+ get _removeUnused() {
3277
+ return this.hasRemoveUnusedValue ? this.removeUnusedValue : false;
3278
+ }
3279
+ get _deadlineDate() {
3280
+ return new Date(this.deadlineValue);
3281
+ }
3282
+ connect() {
3283
+ this._interval = setInterval(this._tick.bind(this), 1e3);
3284
+ this.addCountingDownClasses();
3285
+ }
3286
+ disconnect() {
3287
+ this._clearTick();
3288
+ this.removeCountingDownClasses();
3289
+ this.removeEndedClasses();
3290
+ }
3291
+ deadlineValueChanged() {
3292
+ if (this._interval == null) {
3293
+ this._interval = setInterval(this._tick.bind(this), 1e3);
3294
+ }
3295
+ }
3296
+ _tick() {
3297
+ try {
3298
+ const now = new Date();
3299
+ let distance = {};
3300
+ if (isPast(this._deadlineDate)) {
3301
+ distance = { years: 0, months: 0, days: 0, hours: 0, minutes: 0, seconds: 0 };
3302
+ this._clearTick();
3303
+ this.removeCountingDownClasses();
3304
+ this.addEndedClasses();
3305
+ this.dispatchEvent(this.el, "countdown:ended");
3306
+ } else {
3307
+ distance = intervalToDuration({ start: this._deadlineDate, end: now });
3308
+ }
3309
+ if (this.hasYearsTarget) {
3310
+ this._updateTarget(this.yearsTarget, this._years(distance));
3311
+ }
3312
+ if (this.hasMonthsTarget) {
3313
+ this._updateTarget(this.monthsTarget, this._months(distance));
3314
+ }
3315
+ if (this.hasDaysTarget) {
3316
+ this._updateTarget(this.daysTarget, this._days(distance));
3317
+ }
3318
+ if (this.hasHoursTarget) {
3319
+ this._updateTarget(this.hoursTarget, this._hours(distance));
3320
+ }
3321
+ if (this.hasMinutesTarget) {
3322
+ this._updateTarget(this.minutesTarget, this._minutes(distance));
3323
+ }
3324
+ if (this.hasSecondsTarget) {
3325
+ this._updateTarget(this.secondsTarget, this._seconds(distance));
3326
+ }
3327
+ } catch (e) {
3328
+ console.error(e);
3329
+ this._clearTick();
3330
+ }
3331
+ }
3332
+ _clearTick() {
3333
+ if (this._interval) {
3334
+ clearInterval(this._interval);
3335
+ this._interval = null;
3336
+ }
3337
+ }
3338
+ _updateTarget(target, value) {
3339
+ this._removeTargetIfUnused(target, value);
3340
+ target.innerHTML = value.toString();
3341
+ }
3342
+ _removeTargetIfUnused(target, value) {
3343
+ if (this._removeUnused) {
3344
+ if (value === 0 && target.dataset.unused) {
3345
+ if (Number.parseInt(target.dataset.unused) > Date.now() + 1500) {
3346
+ target.remove();
3347
+ }
3348
+ } else if (value == 0) {
3349
+ target.dataset.unused = Date.now().toString();
3350
+ } else {
3351
+ target.dataset.unused = void 0;
3352
+ }
3353
+ }
3354
+ }
3355
+ _years(duration) {
3356
+ return duration.years || 0;
3357
+ }
3358
+ _months(duration) {
3359
+ return duration.months || 0;
3360
+ }
3361
+ _days(duration) {
3362
+ return duration.days || 0;
3363
+ }
3364
+ _hours(duration) {
3365
+ return duration.hours || 0;
3366
+ }
3367
+ _minutes(duration) {
3368
+ return duration.minutes || 0;
3369
+ }
3370
+ _seconds(duration) {
3371
+ return duration.seconds || 0;
3372
+ }
3373
+ }
3374
+ __publicField(CountdownController, "values", { deadline: String, removeUnused: Boolean });
3375
+ __publicField(CountdownController, "targets", ["years", "months", "days", "hours", "minutes", "seconds"]);
3376
+ __publicField(CountdownController, "classes", ["countingDown", "ended"]);
3377
+ class DurationController extends BaseController {
3378
+ get _format() {
3379
+ return [
3380
+ "years",
3381
+ "months",
3382
+ "weeks",
3383
+ "days",
3384
+ "hours",
3385
+ ...this._minutes ? ["minutes"] : [],
3386
+ ...this._seconds ? ["seconds"] : []
3387
+ ];
3388
+ }
3389
+ get _output() {
3390
+ let { years, months, weeks, days, hours, minutes, seconds } = this._duration;
3391
+ years || (years = 0);
3392
+ months || (months = 0);
3393
+ weeks || (weeks = 0);
3394
+ days || (days = 0);
3395
+ hours || (hours = 0);
3396
+ minutes || (minutes = 0);
3397
+ seconds || (seconds = 0);
3398
+ let largeDenominators = [years, months, weeks, days, hours];
3399
+ if (!this._minutes && !this._seconds && largeDenominators.every((x) => x === 0)) {
3400
+ minutes = minutes + seconds / 60;
3401
+ return `${(minutes / 60).toFixed(1)} hours`;
3402
+ }
3403
+ return formatDuration(this._duration, { format: this._format, delimiter: ", " });
3404
+ }
3405
+ get _seconds() {
3406
+ return this.hasSecondsValue ? this.secondsValue : true;
3407
+ }
3408
+ get _minutes() {
3409
+ return this.hasMinutesValue ? this.minutesValue : true;
3410
+ }
3411
+ get _timestamp() {
3412
+ if (this.hasTimestampValue) {
3413
+ return toDate(this.timestampValue * 1e3);
3414
+ } else {
3415
+ throw new Error("Expected `timestampValue` to be present");
3416
+ }
3417
+ }
3418
+ get _duration() {
3419
+ return intervalToDuration({ start: new Date(), end: this._timestamp });
3420
+ }
3421
+ get _tickInterval() {
3422
+ if (this._seconds) {
3423
+ return 1e3;
3424
+ } else if (this._minutes) {
3425
+ return 15e3;
3426
+ } else {
3427
+ return 12e4;
3428
+ }
3429
+ }
3430
+ connect() {
3431
+ this._clearInterval = useInterval(this, this._update, this._tickInterval);
3432
+ this._update();
3433
+ }
3434
+ _update() {
3435
+ try {
3436
+ this.el.innerHTML = this._output;
3437
+ } catch {
3438
+ this._clearInterval();
3439
+ }
3440
+ }
3441
+ }
3442
+ __publicField(DurationController, "values", {
3443
+ timestamp: Number,
3444
+ minutes: Boolean,
3445
+ seconds: Boolean
3446
+ });
3447
+ class TabsController extends BaseController {
3448
+ get defaultHideClasses() {
3449
+ return ["hide"];
3450
+ }
3451
+ get defaultActiveClasses() {
3452
+ return ["is-active"];
3453
+ }
3454
+ get _currentTab() {
3455
+ return this.hasCurrentTabValue ? this.currentTabValue : 0;
3456
+ }
3457
+ get _equalize() {
3458
+ return this.hasEqualizeValue ? this.equalizeValue : false;
3459
+ }
3460
+ connect() {
3461
+ useCollectionEventListener(this, this.linkTargets, "click", this.switchTabs);
3462
+ if (this._equalize) {
3463
+ this._setMinHeight();
3464
+ }
3465
+ this.currentTabValue = this._currentTab;
3466
+ }
3467
+ switchTabs(event) {
3468
+ event.preventDefault();
3469
+ this.currentTabValue = this.linkTargets.indexOf(event.currentTarget);
3470
+ }
3471
+ currentTabValueChanged() {
3472
+ let index = this._currentTab;
3473
+ index = this._clampIndex(index);
3474
+ this._selectTab(index);
3475
+ }
3476
+ _selectTab(index) {
3477
+ index = this._clampIndex(index);
3478
+ let links = this.linkTargets;
3479
+ let panels = this.contentTargets;
3480
+ let activePanel = panels[index];
3481
+ let activeLink = links[index];
3482
+ let otherPanels = [...panels.slice(0, index), ...panels.slice(index + 1)];
3483
+ let otherLinks = [...links.slice(0, index), ...links.slice(index + 1)];
3484
+ this.addActiveClasses(activeLink);
3485
+ activeLink.setAttribute("aria-selected", "true");
3486
+ this.addActiveClasses(activePanel);
3487
+ this.removeHideClasses(activePanel);
3488
+ otherLinks.forEach((link) => {
3489
+ link.removeAttribute("aria-selected");
3490
+ this.removeActiveClasses(link);
3491
+ });
3492
+ otherPanels.forEach((panel) => {
3493
+ this.removeActiveClasses(panel);
3494
+ this.addHideClasses(panel);
3495
+ });
3496
+ }
3497
+ _clampIndex(index) {
3498
+ return clamp(index, 0, this.contentTargets.length - 1);
3499
+ }
3500
+ _setMinHeight() {
3501
+ let minHeight = 0;
3502
+ this.contentTargets.forEach((content) => {
3503
+ let hidden = content.hasAttribute("tab-hidden");
3504
+ if (hidden) {
3505
+ this.removeHideClasses(content);
3506
+ }
3507
+ let height = content.offsetHeight;
3508
+ if (height > minHeight) {
3509
+ minHeight = height;
3510
+ }
3511
+ if (hidden) {
3512
+ this.addHideClasses(content);
3513
+ }
3514
+ });
3515
+ this.contentTargets.forEach((content) => content.style.minHeight = minHeight + "px");
3516
+ }
3517
+ }
3518
+ __publicField(TabsController, "values", { currentTab: Number, equalize: Boolean });
3519
+ __publicField(TabsController, "targets", ["link", "content"]);
3520
+ __publicField(TabsController, "classes", ["active", "hide"]);
3521
+ class TimeDistanceController extends BaseController {
3522
+ get _duration() {
3523
+ return isPast(this._timestamp) ? intervalToDuration({ start: this._timestamp, end: new Date() }) : intervalToDuration({ start: new Date(), end: this._timestamp });
3524
+ }
3525
+ get _nextUpdate() {
3526
+ let duration = this._duration;
3527
+ if (duration.years && duration.years > 0) {
3528
+ return null;
3529
+ } else if (duration.months && duration.months > 0) {
3530
+ return null;
3531
+ } else if (duration.days && duration.days > 0) {
3532
+ return null;
3533
+ } else if (duration.hours && duration.hours > 0) {
3534
+ return 18e5;
3535
+ } else {
3536
+ return 3e4;
3537
+ }
3538
+ }
3539
+ timestampValueChanged() {
3540
+ this._timestamp = toDate(this.timestampValue * 1e3);
3541
+ }
3542
+ connect() {
3543
+ if (!this.hasTimestampValue) {
3544
+ throw new Error("Expected `timestampValue` to be present");
3545
+ }
3546
+ this._update();
3547
+ }
3548
+ _update() {
3549
+ this.el.innerHTML = formatDistanceToNow(this._timestamp, {
3550
+ addSuffix: true,
3551
+ includeSeconds: true
3552
+ });
3553
+ if (this._nextUpdate) {
3554
+ useTimeout(this, this._update, this._nextUpdate);
3555
+ }
3556
+ }
3557
+ }
3558
+ __publicField(TimeDistanceController, "values", {
3559
+ timestamp: Number
3560
+ });
3561
+ class TreeViewController extends BaseController {
3562
+ get defaultActiveClasses() {
3563
+ return ["active"];
3564
+ }
3565
+ get defaultCollapsedClasses() {
3566
+ return ["collapsed"];
3567
+ }
3568
+ initialize() {
3569
+ this._nodeClicked = this._nodeClicked.bind(this);
3570
+ }
3571
+ connect() {
3572
+ installClassMethods(this);
3573
+ useMutationObserver(this, this.el, this.mutate, { subtree: true, childList: true });
3574
+ this._setup();
3575
+ }
3576
+ disconnect() {
3577
+ this._teardown();
3578
+ }
3579
+ _setup() {
3580
+ this._setupNode(this.el);
3581
+ }
3582
+ _setupNode(el) {
3583
+ const process = (e) => {
3584
+ let parent = e.parentElement;
3585
+ if (parent) {
3586
+ if (!this._nodeActive(parent)) {
3587
+ this._hideNode(parent);
3588
+ }
3589
+ parent.removeEventListener("click", this._nodeClicked);
3590
+ parent.addEventListener("click", this._nodeClicked);
3591
+ }
3592
+ };
3593
+ if (el.tagName === "UL" || el.tagName === "OL") {
3594
+ process(el);
3595
+ }
3596
+ el.querySelectorAll("ul, ol").forEach((e) => process(e));
3597
+ }
3598
+ _teardown() {
3599
+ this.el.querySelectorAll("ul, ol, li").forEach((el) => this._teardownNode(el));
3600
+ }
3601
+ _teardownNode(el) {
3602
+ [el, ...Array.from(el.querySelectorAll("ul, ol, li"))].forEach((x) => {
3603
+ x.removeEventListener("click", this._nodeClicked);
3604
+ this.removeActiveClasses(x);
3605
+ this.removeCollapsedClasses(x);
3606
+ });
3607
+ }
3608
+ _nodeClicked(event) {
3609
+ if (event) {
3610
+ event.stopImmediatePropagation();
3611
+ }
3612
+ let el = event.target;
3613
+ if (!el || !this._hasNested(el)) {
3614
+ return;
3615
+ }
3616
+ if (this._nodeActive(el)) {
3617
+ this._hideNode(el);
3618
+ } else {
3619
+ this._showNode(el);
3620
+ }
3621
+ }
3622
+ _nodeActive(el) {
3623
+ return this.activeClassesPresent(el);
3624
+ }
3625
+ _showNode(el) {
3626
+ this.removeCollapsedClasses(el);
3627
+ this.addActiveClasses(el);
3628
+ }
3629
+ _hideNode(el) {
3630
+ this.removeActiveClasses(el);
3631
+ this.addCollapsedClasses(el);
3632
+ }
3633
+ _hasNested(el) {
3634
+ return el.querySelectorAll("ul, ol").length > 0;
3635
+ }
3636
+ mutate(entries) {
3637
+ for (const mutation of entries) {
3638
+ if (mutation.type === "childList") {
3639
+ Array.from(mutation.addedNodes || []).forEach((el) => this._setupNode(el));
3640
+ Array.from(mutation.removedNodes || []).forEach((el) => this._teardownNode(el));
3641
+ }
3642
+ }
3643
+ }
3644
+ }
3645
+ __publicField(TreeViewController, "classes", [
3646
+ "active",
3647
+ "collapsed"
3648
+ ]);
3649
+ class AnchorSpyController extends BaseController {
3650
+ get defaultActiveClasses() {
3651
+ return ["active"];
3652
+ }
3653
+ get defaultInactiveClasses() {
3654
+ return ["inactive"];
3655
+ }
3656
+ get _key() {
3657
+ return this.keyValue.replaceAll("#", "");
3658
+ }
3659
+ get _anchor() {
3660
+ return window.location.hash.substr(1);
3661
+ }
3662
+ set _anchor(value) {
3663
+ window.location.hash = value;
3664
+ }
3665
+ connect() {
3666
+ installClassMethods(this);
3667
+ requestAnimationFrame(() => {
3668
+ this._checkAnchor();
3669
+ useEventListener(this, window, "hashchange", this._checkAnchor);
3670
+ });
3671
+ }
3672
+ write(event) {
3673
+ event == null ? void 0 : event.preventDefault();
3674
+ this._anchor = this._key;
3675
+ }
3676
+ _checkAnchor() {
3677
+ if (this._key === this._anchor) {
3678
+ this.dispatchEvent(this.el, "anchor-spy:active");
3679
+ this.addActiveClasses(this.el);
3680
+ this.removeInactiveClasses(this.el);
3681
+ } else {
3682
+ this.dispatchEvent(this.el, "anchor-spy:inactive");
3683
+ this.addInactiveClasses(this.el);
3684
+ this.removeActiveClasses(this.el);
3685
+ }
3686
+ }
3687
+ }
3688
+ __publicField(AnchorSpyController, "values", { key: String });
3689
+ __publicField(AnchorSpyController, "classes", ["active", "inactive"]);
3690
+ class BackLinkController extends BaseController {
3691
+ get _pages() {
3692
+ return this.hasPagesValue ? Math.abs(this.pagesValue) : 1;
3693
+ }
3694
+ get _timeout() {
3695
+ return this.hasTimeoutValue ? this.timeoutValue : 1500;
3696
+ }
3697
+ connect() {
3698
+ useEventListener(this, this.el, "click", this.goBack);
3699
+ }
3700
+ goBack(event) {
3701
+ event == null ? void 0 : event.preventDefault();
3702
+ history.go(-this._pages);
3703
+ if (this.el.href) {
3704
+ useTimeout(this, this.fallback, this._timeout);
3705
+ }
3706
+ }
3707
+ fallback() {
3708
+ window.location.href = this.el.href;
3709
+ }
3710
+ }
3711
+ __publicField(BackLinkController, "values", { timeout: Number, pages: Number });
3712
+ class ClipboardController extends BaseController {
3713
+ constructor() {
3714
+ super(...arguments);
3715
+ __publicField(this, "_supported", false);
3716
+ }
3717
+ connect() {
3718
+ this._supported = document.queryCommandSupported("copy");
3719
+ if (this.hasRemoveUnusedValue && this.removeUnusedValue) {
3720
+ if (this._supported && this.hasFallbackTarget) {
3721
+ this.fallbackTarget.remove();
3722
+ } else if (this.hasCopyTarget) {
3723
+ this.copyTarget.remove();
3724
+ }
3725
+ }
3726
+ }
3727
+ select(event) {
3728
+ if (event) {
3729
+ event.preventDefault();
3730
+ }
3731
+ this.sourceTarget.select();
3732
+ }
3733
+ copy(event) {
3734
+ if (event) {
3735
+ event.preventDefault();
3736
+ }
3737
+ this.sourceTarget.select();
3738
+ if (this._supported) {
3739
+ document.execCommand("copy");
3740
+ }
3741
+ }
3742
+ }
3743
+ __publicField(ClipboardController, "targets", ["source", "button", "copy", "fallback"]);
3744
+ __publicField(ClipboardController, "values", { removeUnused: Boolean });
3745
+ class ConfirmController extends BaseController {
3746
+ get _message() {
3747
+ return this.hasMessageValue ? this.messageValue : "Are you sure?";
3748
+ }
3749
+ get _eventType() {
3750
+ if (isHTMLFormElement(this.el)) {
3751
+ return "submit";
3752
+ } else if (isHTMLAnchorElement(this.el)) {
3753
+ return "click";
3754
+ } else {
3755
+ throw new Error("Can't handle confirmation on attached element");
3756
+ }
3757
+ }
3758
+ connect() {
3759
+ requestAnimationFrame(() => {
3760
+ useEventListener(this, this.el, this._eventType, this.confirm);
3761
+ });
3762
+ }
3763
+ confirm(event) {
3764
+ if (!window.confirm(this._message)) {
3765
+ event.preventDefault();
3766
+ this.dispatchEvent(this.el, "confirm:cancelled");
3767
+ }
3768
+ }
3769
+ }
3770
+ __publicField(ConfirmController, "values", {
3771
+ message: String
3772
+ });
3773
+ class ConfirmNavigationController extends BaseController {
3774
+ get _message() {
3775
+ return this.hasMessageValue ? this.messageValue : "Do you want to leave this page? Changes you made may not be saved";
3776
+ }
3777
+ connect() {
3778
+ window.onbeforeunload = () => this._message;
3779
+ useEventListener(this, window, "popstate", this.confirmNavigation);
3780
+ useEventListener(this, window, "submit", this.allowSubmit);
3781
+ useEventListener(this, window, ["turbolinks:before-visit", "turbo:before-visit"], this.confirmTurboNavigation);
3782
+ }
3783
+ disconnect() {
3784
+ window.onbeforeunload = null;
3785
+ }
3786
+ allowSubmit(_event) {
3787
+ window.removeEventListener("popstate", this.confirmNavigation);
3788
+ window.onbeforeunload = null;
3789
+ }
3790
+ confirmNavigation(_event) {
3791
+ return false;
3792
+ }
3793
+ confirmTurboNavigation(event) {
3794
+ if (!confirm(this._message)) {
3795
+ event.preventDefault();
3796
+ }
3797
+ }
3798
+ }
3799
+ __publicField(ConfirmNavigationController, "values", { message: String });
3800
+ class DebugController extends BaseController {
3801
+ connect() {
3802
+ console.log("Debug Controller", this, this.testTargets);
3803
+ }
3804
+ }
3805
+ __publicField(DebugController, "targets", ["test"]);
3806
+ class DisableWithController extends BaseController {
3807
+ get _message() {
3808
+ return this.hasMessageValue ? this.messageValue : "Submitting...";
3809
+ }
3810
+ get _timeout() {
3811
+ return this.hasTimeoutValue ? this.timeoutValue : 1e3;
3812
+ }
3813
+ connect() {
3814
+ requestAnimationFrame(() => {
3815
+ useEventListener(this, this.el, ["click"], this.disable);
3816
+ useEventListener(this, window, ["turbo:load", "turbolinks:load"], this._enable);
3817
+ });
3818
+ }
3819
+ disable(event) {
3820
+ let element = this.el;
3821
+ if (this._isDisabled(element)) {
3822
+ event == null ? void 0 : event.preventDefault();
3823
+ event == null ? void 0 : event.stopImmediatePropagation();
3824
+ } else {
3825
+ this._disable();
3826
+ useTemporaryContent(this, element, this._message, this._timeout, this._enable);
3827
+ }
3828
+ }
3829
+ enable(event) {
3830
+ event == null ? void 0 : event.preventDefault();
3831
+ let element = this.el;
3832
+ if (this._isDisabled(element)) {
3833
+ this._enable();
3834
+ }
3835
+ }
3836
+ _isDisabled(el) {
3837
+ if (isTypeOfButtonableElement(el)) {
3838
+ return el.disabled;
3839
+ } else {
3840
+ return el.dataset.disabled == "true";
3841
+ }
3842
+ }
3843
+ _disable() {
3844
+ let el = this.el;
3845
+ if (isTypeOfButtonableElement(el)) {
3846
+ el.disabled = true;
3847
+ } else {
3848
+ el.dataset.disabled = "true";
3849
+ }
3850
+ }
3851
+ _enable() {
3852
+ let el = this.el;
3853
+ if (isTypeOfButtonableElement(el)) {
3854
+ el.disabled = false;
3855
+ } else {
3856
+ el.dataset.disabled = void 0;
3857
+ }
3858
+ }
3859
+ }
3860
+ __publicField(DisableWithController, "values", {
3861
+ message: String,
3862
+ timeout: Number
3863
+ });
3864
+ class DismissableController extends BaseController {
3865
+ dismiss() {
3866
+ this.el.remove();
3867
+ }
3868
+ }
3869
+ class RemoveController extends DismissableController {
3870
+ }
3871
+ class ElementSaveController extends BaseController {
3872
+ get _id() {
3873
+ if (this.hasIdValue) {
3874
+ return this.idValue;
3875
+ }
3876
+ let elementID = this.el.id;
3877
+ if (elementID !== "") {
3878
+ return elementID;
3879
+ } else {
3880
+ throw new Error(`No ID value to uniquely identify this element. Please either specify data-${this.identifier}-id-value or give this element an 'id' attribute. `);
3881
+ }
3882
+ }
3883
+ get _uniqueIdentifier() {
3884
+ const url = location.href;
3885
+ return `${url} ${this._id}`;
3886
+ }
3887
+ get _restoreOnLoad() {
3888
+ return this.hasRestoreOnLoadValue ? this.restoreOnLoadValue : true;
3889
+ }
3890
+ get _element() {
3891
+ return this.hasElementTarget ? this.elementTarget : this.el;
3892
+ }
3893
+ initialize() {
3894
+ this.save = debounce(this.save.bind(this), 300);
3895
+ }
3896
+ connect() {
3897
+ this._store = useLocalStorage(this, this._uniqueIdentifier, {});
3898
+ requestAnimationFrame(() => {
3899
+ if (this._restoreOnLoad) {
3900
+ this.restore();
3901
+ }
3902
+ });
3903
+ }
3904
+ clear(event) {
3905
+ if (event) {
3906
+ event.preventDefault();
3907
+ }
3908
+ this._store.clear();
3909
+ this.dispatchEvent(this._element, `element-save:cleared`);
3910
+ }
3911
+ save(event) {
3912
+ if (event) {
3913
+ event.preventDefault();
3914
+ }
3915
+ let element = this._element;
3916
+ let attributes = this.attributesValue.split(" ");
3917
+ let data = {};
3918
+ attributes.forEach((attr) => data[attr] = get(element, attr));
3919
+ this._store.value = data;
3920
+ this.dispatchEvent(element, `element-save:save:success`);
3921
+ }
3922
+ restore(event) {
3923
+ if (event) {
3924
+ event.preventDefault();
3925
+ }
3926
+ let element = this._element;
3927
+ if (!this._store.isEmpty()) {
3928
+ const savedData = this._store.value;
3929
+ Object.keys(savedData).forEach((attr) => set(element, attr, savedData[attr]));
3930
+ this.dispatchEvent(element, `element-save:restore:success`);
3931
+ } else {
3932
+ this.dispatchEvent(element, `element-save:restore:empty`);
3933
+ }
3934
+ }
3935
+ }
3936
+ __publicField(ElementSaveController, "targets", [
3937
+ "element"
3938
+ ]);
3939
+ __publicField(ElementSaveController, "values", {
3940
+ id: String,
3941
+ attributes: String,
3942
+ restoreOnLoad: Boolean
3943
+ });
3944
+ class EmptyDomController extends BaseController {
3945
+ get _container() {
3946
+ return this.hasContainerTarget ? this.containerTarget : this.el;
3947
+ }
3948
+ get _children() {
3949
+ let element = this._container;
3950
+ if (this.hasScopeSelectorValue) {
3951
+ return Array.from(element.querySelectorAll(this.scopeSelectorValue));
3952
+ } else {
3953
+ return Array.from(element.children);
3954
+ }
3955
+ }
3956
+ connect() {
3957
+ installClassMethods(this);
3958
+ useMutationObserver(this, this._container, this.mutate, { childList: true });
3959
+ this.checkEmpty();
3960
+ }
3961
+ mutate(entries) {
3962
+ this.checkEmpty();
3963
+ }
3964
+ checkEmpty() {
3965
+ let element = this._container;
3966
+ let children = this._children;
3967
+ if (children.length === 0) {
3968
+ this.removeNotEmptyClasses();
3969
+ this.addEmptyClasses();
3970
+ this.dispatchEvent(element, "dom:empty");
3971
+ } else {
3972
+ this.addNotEmptyClasses();
3973
+ this.removeEmptyClasses();
3974
+ this.dispatchEvent(element, "dom:not-empty", { detail: { count: children.length } });
3975
+ }
3976
+ }
3977
+ }
3978
+ __publicField(EmptyDomController, "targets", ["container"]);
3979
+ __publicField(EmptyDomController, "classes", ["empty", "notEmpty"]);
3980
+ __publicField(EmptyDomController, "values", { scopeSelector: String });
3981
+ class PrefetchController extends BaseController {
3982
+ get _mode() {
3983
+ return this.hasModeValue ? this.modeValue : "mouseover";
3984
+ }
3985
+ get _supportsPrefetch() {
3986
+ var _a, _b;
3987
+ const link = document.createElement("link");
3988
+ return ((_a = link.relList) == null ? void 0 : _a.supports) && ((_b = link.relList) == null ? void 0 : _b.supports("prefetch"));
3989
+ }
3990
+ get _href() {
3991
+ return this.el.href;
3992
+ }
3993
+ get _existingPrefetch() {
3994
+ return (document.head.querySelectorAll(`link[rel="prefetch"][href="${this._href}"]`) || []).length > 0;
3995
+ }
3996
+ get _connectionSuitable() {
3997
+ const connection = navigator.connection;
3998
+ if (!connection) {
3999
+ return true;
4000
+ }
4001
+ if (connection) {
4002
+ if (connection.saveData) {
4003
+ warn(this, "Data Saving is enabled");
4004
+ return false;
4005
+ }
4006
+ if (/2g/.test(connection.effectiveType)) {
4007
+ warn(this, "Network is too slow");
4008
+ return false;
4009
+ }
4010
+ }
4011
+ return true;
4012
+ }
4013
+ connect() {
4014
+ if (!this._supportsPrefetch) {
4015
+ return;
4016
+ }
4017
+ switch (this._mode) {
4018
+ case "intersect":
4019
+ this._setupObserver();
4020
+ break;
4021
+ case "mouseover":
4022
+ useEventListener(this, this.el, "mouseover", this.prefetch, { once: true });
4023
+ break;
4024
+ default:
4025
+ throw new Error(`'${this._mode}' is not a supported prefetch mode`);
4026
+ }
4027
+ }
4028
+ _setupObserver() {
4029
+ const observer = new IntersectionObserver(([entry], observer2) => {
4030
+ if (entry.isIntersecting) {
4031
+ this.prefetch();
4032
+ observer2.unobserve(entry.target);
4033
+ }
4034
+ });
4035
+ observer.observe(this.element);
4036
+ }
4037
+ prefetch() {
4038
+ if (this._existingPrefetch || !this._connectionSuitable) {
4039
+ return;
4040
+ }
4041
+ const link = document.createElement("link");
4042
+ Object.assign(link, { rel: "prefetch", href: this._href, as: "document" });
4043
+ document.head.appendChild(link);
4044
+ }
4045
+ }
4046
+ __publicField(PrefetchController, "values", { mode: String });
4047
+ class PrintButtonController extends PrintController {
4048
+ get defaultUnsupportedClasses() {
4049
+ return ["unsupported"];
4050
+ }
4051
+ connect() {
4052
+ installClassMethods(this);
4053
+ if (!("print" in window)) {
4054
+ this.addUnsupportedClasses();
4055
+ }
4056
+ useEventListener(this, this.el, "click", this.print);
4057
+ }
4058
+ }
4059
+ __publicField(PrintButtonController, "classes", [
4060
+ "unsupported"
4061
+ ]);
4062
+ class ResponsiveIframeWrapperController extends BaseController {
4063
+ connect() {
4064
+ useEventListener(this, window, "message", this.messageReceived);
4065
+ }
4066
+ messageReceived(message) {
4067
+ let data = message.data;
4068
+ if (data.hasOwnProperty("name") && data.name === "iframe-body" && data.hasOwnProperty("height")) {
4069
+ this.resize(data.height);
4070
+ }
4071
+ }
4072
+ resize(height) {
4073
+ this.el.style.height = `${height}px`;
4074
+ }
4075
+ }
4076
+ class ResponsiveIframeBodyController extends BaseController {
4077
+ connect() {
4078
+ if (window.self !== window.top) {
4079
+ useEventListener(this, window, "resize", this.postUpdate, { debounce: 200 });
4080
+ this.postUpdate();
4081
+ }
4082
+ }
4083
+ postUpdate() {
4084
+ let payload = { name: "iframe-body", height: this.getHeight() };
4085
+ window.parent.postMessage(payload, "*");
4086
+ }
4087
+ getHeight() {
4088
+ const body = document.body;
4089
+ const html = document.documentElement;
4090
+ return Math.max(body.scrollHeight, body.offsetHeight, html.clientHeight, html.scrollHeight, html.offsetHeight);
4091
+ }
4092
+ }
4093
+ class SelfDestructController extends BaseController {
4094
+ connect() {
4095
+ requestAnimationFrame(() => {
4096
+ useTimeout(this, () => this.el.remove(), this.secondsValue * 1e3);
4097
+ });
4098
+ }
4099
+ }
4100
+ __publicField(SelfDestructController, "values", { seconds: Number });
4101
+ class StickyController extends BaseController {
4102
+ constructor() {
4103
+ super(...arguments);
4104
+ __publicField(this, "_magicElement", null);
4105
+ }
4106
+ get defaultStuckClasses() {
4107
+ return ["stuck"];
4108
+ }
4109
+ get _mode() {
4110
+ if (this.hasModeValue) {
4111
+ if (!["top", "bottom"].includes(this.modeValue)) {
4112
+ throw new Error(`The modeValue provided '${this.modeValue}' is not one of the recognised configuration options`);
4113
+ }
4114
+ if (this.modeValue === "top") {
4115
+ return "beforebegin";
4116
+ }
4117
+ }
4118
+ return "afterend";
4119
+ }
4120
+ connect() {
4121
+ this._magicElement = document.createElement("div");
4122
+ useInjectedElement(this, this.el, this._mode, this._magicElement);
4123
+ const observer = new IntersectionObserver((entries) => {
4124
+ entries.forEach((entry) => {
4125
+ if (entry.target !== this._magicElement) {
4126
+ return;
4127
+ }
4128
+ if (entry.intersectionRatio === 0) {
4129
+ this.addStuckClasses();
4130
+ } else if (entry.intersectionRatio === 1) {
4131
+ this.removeStuckClasses();
4132
+ }
4133
+ });
4134
+ }, {
4135
+ threshold: [0, 1]
4136
+ });
4137
+ observer.observe(this._magicElement);
4138
+ }
4139
+ }
4140
+ __publicField(StickyController, "classes", ["stuck"]);
4141
+ __publicField(StickyController, "values", { mode: String });
4142
+ class TeleportController extends EphemeralController {
4143
+ connect() {
4144
+ if (!this.hasInsertValue) {
4145
+ throw new Error("`insert` value was not specified");
4146
+ }
4147
+ requestAnimationFrame(() => {
4148
+ if (this.hasImmediateValue && this.immediateValue) {
4149
+ this.execute();
4150
+ }
4151
+ });
4152
+ }
4153
+ execute(event) {
4154
+ event == null ? void 0 : event.preventDefault();
4155
+ let element = this.el;
4156
+ let destination = document.querySelector(this.targetValue);
4157
+ if (destination == null) {
4158
+ this.dispatchEvent(element, "teleport:error");
4159
+ return;
4160
+ }
4161
+ let copy = element.cloneNode(true);
4162
+ this.cleanup(copy);
4163
+ switch (this.insertValue) {
4164
+ case "beforebegin":
4165
+ case "beforeend":
4166
+ case "afterend":
4167
+ case "afterbegin":
4168
+ destination.insertAdjacentHTML(this.insertValue, copy.outerHTML);
4169
+ break;
4170
+ case "replaceOuter":
4171
+ destination.outerHTML = copy.outerHTML;
4172
+ break;
4173
+ case "replaceInner":
4174
+ destination.innerHTML = copy.outerHTML;
4175
+ break;
4176
+ case "prepend":
4177
+ destination.insertAdjacentHTML("afterbegin", copy.outerHTML);
4178
+ break;
4179
+ case "append":
4180
+ destination.insertAdjacentHTML("beforeend", copy.outerHTML);
4181
+ break;
4182
+ default:
4183
+ throw new Error("`insert` value was not specified");
4184
+ }
4185
+ element.remove();
4186
+ }
4187
+ }
4188
+ __publicField(TeleportController, "values", { target: String, insert: String, immediate: Boolean });
4189
+ class TemporaryStateController extends EphemeralController {
4190
+ constructor() {
4191
+ super(...arguments);
4192
+ __publicField(this, "_previousState", {});
4193
+ }
4194
+ get _value() {
4195
+ if (this.hasValueValue) {
4196
+ return this.valueValue;
4197
+ }
4198
+ throw new Error("Expected `valueValue` to be present");
4199
+ }
4200
+ get _attribute() {
4201
+ if (this.hasAttributeValue) {
4202
+ return this.attributeValue;
4203
+ }
4204
+ throw new Error("Expected `attributeValue` to be present");
4205
+ }
4206
+ get _seconds() {
4207
+ if (this.hasSecondsValue) {
4208
+ return this.secondsValue * 1e3;
4209
+ }
4210
+ throw new Error("Expected `secondsValue` to be present");
4211
+ }
4212
+ connect() {
4213
+ this.setState();
4214
+ useTimeout(this, this.removeState, this._seconds);
4215
+ }
4216
+ disconnect() {
4217
+ this.removeState();
4218
+ }
4219
+ setState() {
4220
+ this._previousState[this._attribute] = get(this.el, this._attribute);
4221
+ set(this.el, this._attribute, this.valueValue);
4222
+ }
4223
+ removeState() {
4224
+ set(this.el, this._attribute, this._previousState[this._attribute]);
4225
+ }
4226
+ }
4227
+ __publicField(TemporaryStateController, "values", {
4228
+ attribute: String,
4229
+ seconds: Number,
4230
+ value: String
4231
+ });
4232
+ function applyTemporaryState(element, propertyString, value, seconds, controllerIdentifier = "temporary-state") {
4233
+ var _a;
4234
+ if (!element.dataset.controller || !((_a = element.dataset.controller) == null ? void 0 : _a.includes(controllerIdentifier))) {
4235
+ element.dataset.controller = (element.dataset.controller || ` ${controllerIdentifier} `).trim().replaceAll(" ", " ");
4236
+ }
4237
+ element[camelCase(`${controllerIdentifier}-attribute-value`)] = propertyString;
4238
+ element[camelCase(`${controllerIdentifier}-seconds-value`)] = seconds.toString();
4239
+ }
4240
+ function applyTemporaryClass(element, value, seconds) {
4241
+ applyTemporaryState(element, "className", value, seconds);
4242
+ }
4243
+ function useClickOutside(controller, element, callback) {
4244
+ callback = callback.bind(controller);
4245
+ const handler = (event) => {
4246
+ if (element.contains(event.target) || !isElementInViewport(element)) {
4247
+ return;
4248
+ }
4249
+ callback(event);
4250
+ };
4251
+ let { teardown } = useEventListener(controller, window, ["click", "touchend"], handler);
4252
+ useMixin(controller, () => void 0, teardown);
4253
+ return {
4254
+ teardown
4255
+ };
4256
+ }
4257
+ function useHover(controller, element, enter, leave) {
4258
+ let teardownEnter = null;
4259
+ let teardownLeave = null;
4260
+ if (enter) {
4261
+ enter = enter.bind(controller);
4262
+ let { teardown: _teardownEnter } = useEventListener(controller, element, "mouseenter", enter);
4263
+ teardownEnter = _teardownEnter;
4264
+ }
4265
+ if (leave) {
4266
+ leave = leave.bind(controller);
4267
+ let { teardown: _teardownLeave } = useEventListener(controller, element, "mouseleave", leave);
4268
+ teardownLeave = _teardownLeave;
4269
+ }
4270
+ let setup = () => void 0;
4271
+ let teardown = () => {
4272
+ if (teardownEnter) {
4273
+ teardownEnter();
4274
+ }
4275
+ if (teardownLeave) {
4276
+ teardownLeave();
4277
+ }
4278
+ };
4279
+ useMixin(controller, setup, teardown);
4280
+ return {
4281
+ teardown
4282
+ };
4283
+ }
4284
+ class ToggleClassController extends BaseController {
4285
+ connect() {
4286
+ if (!this.hasClassValue) {
4287
+ throw new Error("data-toggle-class-class-value must not be empty");
4288
+ }
4289
+ if (this.hasMouseEnterValue || this.hasMouseLeaveValue) {
4290
+ useHover(this, this.el, this.mouseEnter, this.mouseLeave);
4291
+ }
4292
+ if (this.hasClickAwayValue && this.clickAwayValue) {
4293
+ useClickOutside(this, this.el, this.clickOutside);
4294
+ }
4295
+ requestAnimationFrame(() => {
4296
+ if (this.hasInitialValue) {
4297
+ if (this.initialValue === "on") {
4298
+ this.toggleTargets.forEach((target) => this._elementOn(target));
4299
+ } else {
4300
+ this.toggleTargets.forEach((target) => this._elementOff(target));
4301
+ }
4302
+ }
4303
+ });
4304
+ }
4305
+ clickOutside() {
4306
+ this.toggleTargets.forEach((target) => {
4307
+ if (this._elementWasToggled(target)) {
4308
+ this._elementToggleStatus(target);
4309
+ this._elementToggle(target);
4310
+ }
4311
+ });
4312
+ }
4313
+ mouseEnter() {
4314
+ if (this.hasMouseEnterValue) {
4315
+ switch (this.mouseEnterValue) {
4316
+ case "on":
4317
+ this.on();
4318
+ break;
4319
+ case "off":
4320
+ this.off();
4321
+ break;
4322
+ case "toggle":
4323
+ this.toggle();
4324
+ break;
4325
+ }
4326
+ }
4327
+ return {};
4328
+ }
4329
+ mouseLeave() {
4330
+ if (this.hasMouseLeaveValue) {
4331
+ switch (this.mouseLeaveValue) {
4332
+ case "on":
4333
+ this.on();
4334
+ break;
4335
+ case "off":
4336
+ this.off();
4337
+ break;
4338
+ case "toggle":
4339
+ this.toggle();
4340
+ break;
4341
+ }
4342
+ }
4343
+ return {};
4344
+ }
4345
+ on(event) {
4346
+ this.toggleTargets.forEach((target) => {
4347
+ this._elementToggleStatus(target);
4348
+ this._elementOn(target);
4349
+ });
4350
+ }
4351
+ off(event) {
4352
+ this.toggleTargets.forEach((target) => {
4353
+ this._elementToggleStatus(target);
4354
+ this._elementOff(target);
4355
+ });
4356
+ }
4357
+ toggle(event) {
4358
+ this.toggleTargets.forEach((target) => {
4359
+ this._elementToggleStatus(target);
4360
+ this._elementToggle(target);
4361
+ });
4362
+ }
4363
+ _elementWasToggled(el) {
4364
+ return el.dataset.toggled == "true";
4365
+ }
4366
+ _elementToggleStatus(el) {
4367
+ if (this._elementWasToggled(el)) {
4368
+ delete el.dataset.toggled;
4369
+ } else {
4370
+ el.dataset.toggled = "true";
4371
+ }
4372
+ }
4373
+ _elementToggle(el) {
4374
+ let classes = this.classValue.split(" ");
4375
+ classes.forEach((klass) => el.classList.toggle(klass));
4376
+ }
4377
+ _elementOn(el) {
4378
+ let classes = this.classValue.split(" ");
4379
+ classes.forEach((klass) => el.classList.toggle(klass, true));
4380
+ }
4381
+ _elementOff(el) {
4382
+ let classes = this.classValue.split(" ");
4383
+ classes.forEach((klass) => el.classList.toggle(klass, false));
4384
+ }
4385
+ }
4386
+ __publicField(ToggleClassController, "targets", ["toggle"]);
4387
+ __publicField(ToggleClassController, "values", {
4388
+ class: String,
4389
+ mouseEnter: String,
4390
+ mouseLeave: String,
4391
+ clickAway: Boolean,
4392
+ initial: String
4393
+ });
4394
+ function useTrixModifiers(controller) {
4395
+ const controllerDisconnect = controller.disconnect.bind(controller);
4396
+ let observing = false;
4397
+ let observerCallback = (entries, observer2) => {
4398
+ entries.forEach((mutation) => {
4399
+ if (mutation.type === "childList" && Array.from(mutation.addedNodes).some((el) => el.tagName === "TRIX-TOOLBAR")) {
4400
+ attemptSetup();
4401
+ observer2.disconnect();
4402
+ }
4403
+ });
4404
+ };
4405
+ let pasteHandler = (event) => controllerMethod(controller, "pasteEvent").call(controller, event);
4406
+ let observer = new MutationObserver(observerCallback);
4407
+ let attemptSetup = () => {
4408
+ if (controller.element.tagName !== "TRIX-EDITOR") {
4409
+ throw new Error("Expected controller to be mounted on an instance of <trix-editor>");
4410
+ }
4411
+ let editor = controller.element;
4412
+ let editorParent = controller.element.parentElement;
4413
+ if (editorParent == null) {
4414
+ throw new Error("Could not traverse DOM tree from <trix-editor>");
4415
+ }
4416
+ editor.addEventListener("trix-paste", pasteHandler);
4417
+ let toolbar2 = editorParent.querySelector("trix-toolbar");
4418
+ if (!observing && !toolbar2) {
4419
+ observing = true;
4420
+ observer.observe(editorParent, { childList: true });
4421
+ return;
4422
+ } else if (!toolbar2) {
4423
+ throw new Error("Could not find an instance of <trix-toolbar> that is a sibling of this <trix-editor>");
4424
+ } else {
4425
+ observer.disconnect();
4426
+ }
4427
+ controllerMethod(controller, "install").call(controller, { toolbar: toolbar2, editor });
4428
+ };
4429
+ let teardown = () => {
4430
+ if (controller.element.tagName !== "TRIX-EDITOR") {
4431
+ throw new Error("Expected controller to be mounted on an instance of <trix-editor>");
4432
+ }
4433
+ let editor = controller.element;
4434
+ let editorParent = controller.element.parentElement;
4435
+ if (editorParent == null) {
4436
+ throw new Error("Could not traverse DOM tree from <trix-editor>");
4437
+ }
4438
+ editor.removeEventListener("trix-paste", pasteHandler);
4439
+ let toolbar2 = editorParent.querySelector("trix-toolbar");
4440
+ if (!toolbar2) {
4441
+ throw new Error("Could not find <trix-toolbar> that is a sibling of this <trix-editor> element");
4442
+ }
4443
+ controllerMethod(controller, "uninstall").call(controller, { toolbar: toolbar2, editor });
4444
+ };
4445
+ attemptSetup();
4446
+ Object.assign(controller, {
4447
+ disconnect() {
4448
+ observer.disconnect();
4449
+ teardown();
4450
+ controllerMethod(controller, "uninstall").call({ toolbar, editor: controller.element });
4451
+ controllerDisconnect();
4452
+ }
4453
+ });
4454
+ }
4455
+ class TrixModifierController extends BaseController {
4456
+ get enabledBehaviours() {
4457
+ let enabled = (datasetProp) => datasetProp !== void 0 && datasetProp !== "false";
4458
+ let behaviourIfEnabled = (datasetProp, trixInstallable) => enabled(datasetProp) ? [trixInstallable] : [];
4459
+ return [
4460
+ ...behaviourIfEnabled(this.el.dataset.noBold, this.bold),
4461
+ ...behaviourIfEnabled(this.el.dataset.noBulletList, this.bulletList),
4462
+ ...behaviourIfEnabled(this.el.dataset.noCode, this.code),
4463
+ ...behaviourIfEnabled(this.el.dataset.noHeading, this.heading),
4464
+ ...behaviourIfEnabled(this.el.dataset.noItalic, this.italic),
4465
+ ...behaviourIfEnabled(this.el.dataset.noStrikethrough, this.strikethrough),
4466
+ ...behaviourIfEnabled(this.el.dataset.noLink, this.link),
4467
+ ...behaviourIfEnabled(this.el.dataset.noIndents, this.indents),
4468
+ ...behaviourIfEnabled(this.el.dataset.noNumberList, this.numberList),
4469
+ ...behaviourIfEnabled(this.el.dataset.noQuote, this.quote),
4470
+ ...behaviourIfEnabled(this.el.dataset.noFileUploads, this.fileUploads)
4471
+ ];
4472
+ }
4473
+ get bold() {
4474
+ return this.formattingHandlers(".trix-button--icon-bold", "bold");
4475
+ }
4476
+ get bulletList() {
4477
+ return this.formattingHandlers(".trix-button--icon-bullet-list", "bullet-list");
4478
+ }
4479
+ get code() {
4480
+ return this.formattingHandlers(".trix-button--icon-code", "code");
4481
+ }
4482
+ get heading() {
4483
+ return this.formattingHandlers(".trix-button--icon-heading-1", "heading");
4484
+ }
4485
+ get italic() {
4486
+ return this.formattingHandlers(".trix-button--icon-italic", "italic");
4487
+ }
4488
+ get strikethrough() {
4489
+ return this.formattingHandlers(".trix-button--icon-strike", "strike");
4490
+ }
4491
+ get link() {
4492
+ return this.formattingHandlers(".trix-button--icon-link", "href");
4493
+ }
4494
+ get indents() {
4495
+ return this.simpleHideShowHandlers([
4496
+ ".trix-button--icon-decrease-nesting-level, .trix-button--icon-increase-nesting-level",
4497
+ ".trix-button--icon-decrease-nesting-level, .trix-button--icon-increase-nesting-level"
4498
+ ].join(", "));
4499
+ }
4500
+ get numberList() {
4501
+ return this.simpleHideShowHandlers(".trix-button--icon-number-list");
4502
+ }
4503
+ get quote() {
4504
+ return this.simpleHideShowHandlers(".trix-button--icon-quote");
4505
+ }
4506
+ get fileUploads() {
4507
+ let selector = ".trix-button-group.trix-button-group--file-tools";
4508
+ let preventUploads = (e) => e == null ? void 0 : e.preventDefault();
4509
+ let self = this;
4510
+ let element = this.el;
4511
+ return {
4512
+ install(elements) {
4513
+ self.simpleHideShowHandlers(selector).install(elements);
4514
+ self.el.addEventListener("trix-file-accept", preventUploads);
4515
+ },
4516
+ pasteEvent(event) {
4517
+ let { dataTransfer, html } = event.paste;
4518
+ let { editor } = element;
4519
+ if (dataTransfer.files.length > 0 || html.includes("<img")) {
4520
+ alert("The content you pasted contains images and/or files. File uploads are not supported.");
4521
+ editor.undo();
4522
+ }
4523
+ },
4524
+ uninstall(elements) {
4525
+ self.simpleHideShowHandlers(selector).uninstall(elements);
4526
+ self.el.removeEventListener("trix-file-accept", preventUploads);
4527
+ }
4528
+ };
4529
+ }
4530
+ connect() {
4531
+ useTrixModifiers(this);
4532
+ }
4533
+ install(elements) {
4534
+ this.enabledBehaviours.forEach((behaviour) => behaviour.install(elements));
4535
+ }
4536
+ pasteEvent(event) {
4537
+ this.enabledBehaviours.forEach((behaviour) => behaviour.pasteEvent && behaviour.pasteEvent(event));
4538
+ }
4539
+ uninstall(elements) {
4540
+ this.enabledBehaviours.forEach((behaviour) => behaviour.uninstall(elements));
4541
+ }
4542
+ simpleHideShowHandlers(selector) {
4543
+ return {
4544
+ install: ({ toolbar: toolbar2 }) => this.hideToolbarSelector(toolbar2, selector),
4545
+ uninstall: ({ toolbar: toolbar2 }) => this.showToolbarSelector(toolbar2, selector)
4546
+ };
4547
+ }
4548
+ formattingHandlers(selector, trixAttribute) {
4549
+ let element = this.el;
4550
+ let { editor } = element;
4551
+ return {
4552
+ install: (elements) => {
4553
+ this.simpleHideShowHandlers(selector).install(elements);
4554
+ },
4555
+ pasteEvent(pasteEvent) {
4556
+ let { range } = pasteEvent.paste;
4557
+ let prevRange = element.editor.getSelectedRange();
4558
+ editor.setSelectedRange(range);
4559
+ editor.deactivateAttribute(trixAttribute);
4560
+ editor.setSelectedRange(prevRange);
4561
+ },
4562
+ uninstall: (elements) => {
4563
+ this.simpleHideShowHandlers(selector).uninstall(elements);
4564
+ }
4565
+ };
4566
+ }
4567
+ showToolbarSelector(toolbar2, selector) {
4568
+ toolbar2.querySelectorAll(selector).forEach((el) => el.style.display = "");
4569
+ }
4570
+ hideToolbarSelector(toolbar2, selector) {
4571
+ toolbar2.querySelectorAll(selector).forEach((el) => el.style.display = "none");
4572
+ }
4573
+ }
4574
+ class TurboFrameRCController extends BaseController {
4575
+ toggle(event) {
4576
+ event == null ? void 0 : event.preventDefault();
4577
+ let frame = this._getFrame();
4578
+ let frameSrc = frame.src;
4579
+ if (frameSrc == null || frameSrc !== this._getSrc()) {
4580
+ this._setSrc();
4581
+ } else {
4582
+ this._clear();
4583
+ }
4584
+ }
4585
+ setSrc(event) {
4586
+ event == null ? void 0 : event.preventDefault();
4587
+ this._setSrc();
4588
+ }
4589
+ clear(event) {
4590
+ event == null ? void 0 : event.preventDefault();
4591
+ this._clear();
4592
+ }
4593
+ _setSrc() {
4594
+ let frame = this._getFrame();
4595
+ if (this.hasLoadingMessageValue) {
4596
+ frame.innerHTML = this.loadingMessageValue;
4597
+ }
4598
+ frame.src = this._getSrc();
4599
+ }
4600
+ _clear() {
4601
+ let frame = this._getFrame();
4602
+ frame.src = "";
4603
+ frame.innerHTML = "";
4604
+ }
4605
+ _getFrame() {
4606
+ let frame = document.getElementById(`${this.frameIdValue}`);
4607
+ if (frame == null) {
4608
+ throw new Error(`Could not find frame with ID '${this.frameIdValue}'`);
4609
+ }
4610
+ if (!isTurboFrame(frame)) {
4611
+ throw new Error(`Element targeted by ID '${this.frameIdValue}'`);
4612
+ } else {
4613
+ return frame;
4614
+ }
4615
+ }
4616
+ _getSrc() {
4617
+ let element = this.el;
4618
+ if (this.hasSrcValue) {
4619
+ return this.srcValue;
4620
+ } else if (isHTMLAnchorElement(element)) {
4621
+ return element.href;
4622
+ } else {
4623
+ throw new Error("No link given to drive frame to");
4624
+ }
4625
+ }
4626
+ }
4627
+ __publicField(TurboFrameRCController, "values", {
4628
+ frameId: String,
4629
+ src: String,
4630
+ loadingMessage: String
4631
+ });
4632
+ class TurboFrameRefreshController extends BaseController {
4633
+ get _poll() {
4634
+ return this.hasPollValue ? this.pollValue : false;
4635
+ }
4636
+ connect() {
4637
+ let element = this.el;
4638
+ if (isTurboFrame(element)) {
4639
+ if (!!element.src) {
4640
+ throw new Error("The provided <turbo-frame> element has no `src` attribute.");
4641
+ }
4642
+ } else {
4643
+ throw new Error("Expected controller to be mounted on a <turbo-frame> element.");
4644
+ }
4645
+ if (this._poll) {
4646
+ requestAnimationFrame(() => useTimeout(this, this.refresh, this.intervalValue));
4647
+ }
4648
+ }
4649
+ refresh(event) {
4650
+ event == null ? void 0 : event.preventDefault();
4651
+ let element = this.el;
4652
+ element.src = element.src;
4653
+ }
4654
+ }
4655
+ __publicField(TurboFrameRefreshController, "values", {
4656
+ interval: Number,
4657
+ poll: Boolean
4658
+ });
4659
+ export { AlertController, AnchorSpyController, AsyncBlockController, AutoSubmitFormController, AutosizeController, BackLinkController, BaseController, CharCountController, CheckboxDisableInputsController, CheckboxEnableInputsController, CheckboxSelectAllController, CheckboxXORController, ClipboardController, ClockController, ConfirmController, ConfirmNavigationController, CountdownController, DebugController, DetectDirtyController, DetectDirtyFormController, DisableWithController, DismissableController, DurationController, ElementSaveController, EmptyDomController, EnableInputsController, EphemeralController, EventBus, FallbackImageController, FocusStealController, FormRcController, FormSaveController, FullscreenController, IntersectionController, IntervalController, LazyBlockController, LightboxImageController, LimitedSelectionCheckboxesController, LoadBlockController, MediaPlayerController, NavigateFormErrorsController, NestedFormController, PasswordConfirmController, PasswordPeekController, PollBlockController, PrefetchController, PresenceController, PrintButtonController, PrintController, RemoteFormController, RemoveController, ResponsiveIframeBodyController, ResponsiveIframeWrapperController, ScrollContainerController, ScrollIntoFocusController, ScrollToBottomController, ScrollToController, ScrollToTopController, SelfDestructController, SignalActionController, SignalInputController, SignalVisibilityController, StickyController, StorageSerializers, SyncInputsController, TableSortController, TableTruncateController, TabsController, TeleportController, TemporaryStateController, TimeDistanceController, TimeoutController, ToggleClassController, TreeViewController, TrixModifierController, TurboFrameRCController, TurboFrameRefreshController, UserFocusController, ValueWarnController, WordCountController, applyTemporaryClass, applyTemporaryState, createHiddenButton, createHiddenInput, getAllRadiosInGroup, getOtherRadiosInGroup, getScrollParent, insertElement, insertHiddenButton, insertHiddenInput, isDirty, isElementCheckable, isElementInViewport, isFormDirty, isHTMLAnchorElement, isHTMLButtonButtonElement, isHTMLButtonElement, isHTMLButtonInputElement, isHTMLFormElement, isHTMLImageElement, isHTMLInputElement, isHTMLLabelElement, isHTMLLinkElement, isHTMLResetButtonElement, isHTMLResetInputElement, isHTMLSelectElement, isHTMLSubmitButtonElement, isHTMLSubmitInputElement, isHTMLTextAreaElement, isTurboFrame, isTypeOfButtonableElement, isTypeOfFormInputElement, isTypeOfResetButtonElement, isTypeOfSubmitButtonElement, requestReset, requestSubmit, scrollAbsoluteBottom, scrollAbsoluteLeft, scrollAbsoluteRight, scrollAbsoluteTop, scrollDown, scrollLeft, scrollRight, scrollToElement, scrollUp, useCollectionEventListener, useCollectionEventListeners, useEventListener, useEventListeners, useFullscreen, useGeolocation, useInjectedElement, useInjectedFragment, useInjectedHTML, useInterval, useLocalStorage, useTemporaryContent, useTimeout };
2
4660
  //# sourceMappingURL=stimulus-library.es.js.map