snice 2.5.4 → 3.1.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 (323) hide show
  1. package/README.md +501 -882
  2. package/bin/templates/base/src/components/counter-button.ts +13 -26
  3. package/bin/templates/base/src/controllers/counter-controller.ts +3 -3
  4. package/dist/components/accordion/snice-accordion-item.d.ts +4 -5
  5. package/dist/components/accordion/snice-accordion-item.js +37 -39
  6. package/dist/components/accordion/snice-accordion-item.js.map +1 -1
  7. package/dist/components/accordion/snice-accordion.d.ts +5 -11
  8. package/dist/components/accordion/snice-accordion.js +51 -52
  9. package/dist/components/accordion/snice-accordion.js.map +1 -1
  10. package/dist/components/alert/snice-alert.d.ts +2 -6
  11. package/dist/components/alert/snice-alert.js +41 -56
  12. package/dist/components/alert/snice-alert.js.map +1 -1
  13. package/dist/components/avatar/snice-avatar.d.ts +2 -6
  14. package/dist/components/avatar/snice-avatar.js +64 -71
  15. package/dist/components/avatar/snice-avatar.js.map +1 -1
  16. package/dist/components/badge/snice-badge.d.ts +2 -3
  17. package/dist/components/badge/snice-badge.js +22 -23
  18. package/dist/components/badge/snice-badge.js.map +1 -1
  19. package/dist/components/breadcrumbs/snice-breadcrumbs.d.ts +5 -12
  20. package/dist/components/breadcrumbs/snice-breadcrumbs.js +88 -89
  21. package/dist/components/breadcrumbs/snice-breadcrumbs.js.map +1 -1
  22. package/dist/components/button/snice-button.d.ts +3 -7
  23. package/dist/components/button/snice-button.js +37 -58
  24. package/dist/components/button/snice-button.js.map +1 -1
  25. package/dist/components/card/snice-card.d.ts +5 -8
  26. package/dist/components/card/snice-card.js +71 -56
  27. package/dist/components/card/snice-card.js.map +1 -1
  28. package/dist/components/checkbox/snice-checkbox.d.ts +4 -13
  29. package/dist/components/checkbox/snice-checkbox.js +66 -137
  30. package/dist/components/checkbox/snice-checkbox.js.map +1 -1
  31. package/dist/components/chip/snice-chip.d.ts +5 -11
  32. package/dist/components/chip/snice-chip.js +44 -47
  33. package/dist/components/chip/snice-chip.js.map +1 -1
  34. package/dist/components/date-picker/snice-date-picker.d.ts +11 -11
  35. package/dist/components/date-picker/snice-date-picker.js +134 -133
  36. package/dist/components/date-picker/snice-date-picker.js.map +1 -1
  37. package/dist/components/divider/snice-divider.d.ts +2 -4
  38. package/dist/components/divider/snice-divider.js +14 -22
  39. package/dist/components/divider/snice-divider.js.map +1 -1
  40. package/dist/components/drawer/snice-drawer.d.ts +4 -4
  41. package/dist/components/drawer/snice-drawer.js +25 -19
  42. package/dist/components/drawer/snice-drawer.js.map +1 -1
  43. package/dist/components/input/snice-input.d.ts +8 -6
  44. package/dist/components/input/snice-input.js +122 -105
  45. package/dist/components/input/snice-input.js.map +1 -1
  46. package/dist/components/layout/snice-layout-blog.d.ts +4 -4
  47. package/dist/components/layout/snice-layout-blog.js +21 -19
  48. package/dist/components/layout/snice-layout-blog.js.map +1 -1
  49. package/dist/components/layout/snice-layout-card.d.ts +2 -2
  50. package/dist/components/layout/snice-layout-card.js +16 -9
  51. package/dist/components/layout/snice-layout-card.js.map +1 -1
  52. package/dist/components/layout/snice-layout-centered.d.ts +2 -2
  53. package/dist/components/layout/snice-layout-centered.js +14 -7
  54. package/dist/components/layout/snice-layout-centered.js.map +1 -1
  55. package/dist/components/layout/snice-layout-dashboard.d.ts +5 -5
  56. package/dist/components/layout/snice-layout-dashboard.js +38 -30
  57. package/dist/components/layout/snice-layout-dashboard.js.map +1 -1
  58. package/dist/components/layout/snice-layout-fullscreen.d.ts +2 -2
  59. package/dist/components/layout/snice-layout-fullscreen.js +17 -10
  60. package/dist/components/layout/snice-layout-fullscreen.js.map +1 -1
  61. package/dist/components/layout/snice-layout-landing.d.ts +4 -4
  62. package/dist/components/layout/snice-layout-landing.js +21 -19
  63. package/dist/components/layout/snice-layout-landing.js.map +1 -1
  64. package/dist/components/layout/snice-layout-minimal.d.ts +2 -2
  65. package/dist/components/layout/snice-layout-minimal.js +17 -6
  66. package/dist/components/layout/snice-layout-minimal.js.map +1 -1
  67. package/dist/components/layout/snice-layout-sidebar.d.ts +5 -4
  68. package/dist/components/layout/snice-layout-sidebar.js +42 -20
  69. package/dist/components/layout/snice-layout-sidebar.js.map +1 -1
  70. package/dist/components/layout/snice-layout-split.d.ts +2 -2
  71. package/dist/components/layout/snice-layout-split.js +14 -7
  72. package/dist/components/layout/snice-layout-split.js.map +1 -1
  73. package/dist/components/layout/snice-layout.d.ts +4 -4
  74. package/dist/components/layout/snice-layout.js +16 -10
  75. package/dist/components/layout/snice-layout.js.map +1 -1
  76. package/dist/components/login/snice-login.d.ts +6 -11
  77. package/dist/components/login/snice-login.js +97 -71
  78. package/dist/components/login/snice-login.js.map +1 -1
  79. package/dist/components/modal/snice-modal.d.ts +5 -9
  80. package/dist/components/modal/snice-modal.js +47 -78
  81. package/dist/components/modal/snice-modal.js.map +1 -1
  82. package/dist/components/nav/snice-nav.d.ts +13 -7
  83. package/dist/components/nav/snice-nav.js +191 -100
  84. package/dist/components/nav/snice-nav.js.map +1 -1
  85. package/dist/components/nav/snice-nav.types.d.ts +3 -3
  86. package/dist/components/pagination/snice-pagination.d.ts +6 -7
  87. package/dist/components/pagination/snice-pagination.js +94 -81
  88. package/dist/components/pagination/snice-pagination.js.map +1 -1
  89. package/dist/components/progress/snice-progress.d.ts +2 -7
  90. package/dist/components/progress/snice-progress.js +41 -98
  91. package/dist/components/progress/snice-progress.js.map +1 -1
  92. package/dist/components/radio/snice-radio.d.ts +4 -4
  93. package/dist/components/radio/snice-radio.js +52 -44
  94. package/dist/components/radio/snice-radio.js.map +1 -1
  95. package/dist/components/select/snice-option.d.ts +2 -1
  96. package/dist/components/select/snice-option.js +12 -5
  97. package/dist/components/select/snice-option.js.map +1 -1
  98. package/dist/components/select/snice-select.d.ts +9 -21
  99. package/dist/components/select/snice-select.js +98 -170
  100. package/dist/components/select/snice-select.js.map +1 -1
  101. package/dist/components/skeleton/snice-skeleton.d.ts +2 -6
  102. package/dist/components/skeleton/snice-skeleton.js +18 -49
  103. package/dist/components/skeleton/snice-skeleton.js.map +1 -1
  104. package/dist/components/snice-cell-BLFVdxPp.js +4 -0
  105. package/dist/components/snice-cell-BLFVdxPp.js.map +1 -0
  106. package/dist/components/switch/snice-switch.d.ts +2 -2
  107. package/dist/components/switch/snice-switch.js +38 -26
  108. package/dist/components/switch/snice-switch.js.map +1 -1
  109. package/dist/components/table/snice-cell-actions.d.ts +24 -0
  110. package/dist/components/table/snice-cell-actions.js +149 -0
  111. package/dist/components/table/snice-cell-actions.js.map +1 -0
  112. package/dist/components/table/snice-cell-boolean.d.ts +2 -2
  113. package/dist/components/table/snice-cell-boolean.js +13 -7
  114. package/dist/components/table/snice-cell-boolean.js.map +1 -1
  115. package/dist/components/table/snice-cell-color.d.ts +18 -0
  116. package/dist/components/table/snice-cell-color.js +149 -0
  117. package/dist/components/table/snice-cell-color.js.map +1 -0
  118. package/dist/components/table/snice-cell-currency.d.ts +24 -0
  119. package/dist/components/table/snice-cell-currency.js +235 -0
  120. package/dist/components/table/snice-cell-currency.js.map +1 -0
  121. package/dist/components/table/snice-cell-date.d.ts +2 -2
  122. package/dist/components/table/snice-cell-date.js +14 -8
  123. package/dist/components/table/snice-cell-date.js.map +1 -1
  124. package/dist/components/table/snice-cell-duration.d.ts +2 -2
  125. package/dist/components/table/snice-cell-duration.js +12 -6
  126. package/dist/components/table/snice-cell-duration.js.map +1 -1
  127. package/dist/components/table/snice-cell-email.d.ts +15 -0
  128. package/dist/components/table/snice-cell-email.js +125 -0
  129. package/dist/components/table/snice-cell-email.js.map +1 -0
  130. package/dist/components/table/snice-cell-filesize.d.ts +2 -2
  131. package/dist/components/table/snice-cell-filesize.js +12 -6
  132. package/dist/components/table/snice-cell-filesize.js.map +1 -1
  133. package/dist/components/table/snice-cell-image.d.ts +20 -0
  134. package/dist/components/table/snice-cell-image.js +162 -0
  135. package/dist/components/table/snice-cell-image.js.map +1 -0
  136. package/dist/components/table/snice-cell-json.d.ts +20 -0
  137. package/dist/components/table/snice-cell-json.js +186 -0
  138. package/dist/components/table/snice-cell-json.js.map +1 -0
  139. package/dist/components/table/snice-cell-link.d.ts +17 -0
  140. package/dist/components/table/snice-cell-link.js +142 -0
  141. package/dist/components/table/snice-cell-link.js.map +1 -0
  142. package/dist/components/table/snice-cell-location.d.ts +19 -0
  143. package/dist/components/table/snice-cell-location.js +185 -0
  144. package/dist/components/table/snice-cell-location.js.map +1 -0
  145. package/dist/components/table/snice-cell-number.d.ts +2 -2
  146. package/dist/components/table/snice-cell-number.js +12 -6
  147. package/dist/components/table/snice-cell-number.js.map +1 -1
  148. package/dist/components/table/snice-cell-percentage.d.ts +22 -0
  149. package/dist/components/table/snice-cell-percentage.js +208 -0
  150. package/dist/components/table/snice-cell-percentage.js.map +1 -0
  151. package/dist/components/table/snice-cell-phone.d.ts +18 -0
  152. package/dist/components/table/snice-cell-phone.js +153 -0
  153. package/dist/components/table/snice-cell-phone.js.map +1 -0
  154. package/dist/components/table/snice-cell-progress.d.ts +2 -2
  155. package/dist/components/table/snice-cell-progress.js +12 -6
  156. package/dist/components/table/snice-cell-progress.js.map +1 -1
  157. package/dist/components/table/snice-cell-rating.d.ts +2 -2
  158. package/dist/components/table/snice-cell-rating.js +12 -6
  159. package/dist/components/table/snice-cell-rating.js.map +1 -1
  160. package/dist/components/table/snice-cell-sparkline.d.ts +2 -2
  161. package/dist/components/table/snice-cell-sparkline.js +13 -7
  162. package/dist/components/table/snice-cell-sparkline.js.map +1 -1
  163. package/dist/components/table/snice-cell-status.d.ts +17 -0
  164. package/dist/components/table/snice-cell-status.js +144 -0
  165. package/dist/components/table/snice-cell-status.js.map +1 -0
  166. package/dist/components/table/snice-cell-tag.d.ts +16 -0
  167. package/dist/components/table/snice-cell-tag.js +131 -0
  168. package/dist/components/table/snice-cell-tag.js.map +1 -0
  169. package/dist/components/table/snice-cell-text.d.ts +2 -2
  170. package/dist/components/table/snice-cell-text.js +14 -8
  171. package/dist/components/table/snice-cell-text.js.map +1 -1
  172. package/dist/components/table/snice-cell.d.ts +2 -2
  173. package/dist/components/table/snice-cell.js +12 -6
  174. package/dist/components/table/snice-cell.js.map +1 -1
  175. package/dist/components/table/snice-column.d.ts +1 -1
  176. package/dist/components/table/snice-column.js +6 -3
  177. package/dist/components/table/snice-column.js.map +1 -1
  178. package/dist/components/table/snice-header.d.ts +5 -5
  179. package/dist/components/table/snice-header.js +60 -50
  180. package/dist/components/table/snice-header.js.map +1 -1
  181. package/dist/components/table/snice-progress.d.ts +2 -2
  182. package/dist/components/table/snice-progress.js +18 -11
  183. package/dist/components/table/snice-progress.js.map +1 -1
  184. package/dist/components/table/snice-rating.d.ts +2 -2
  185. package/dist/components/table/snice-rating.js +15 -8
  186. package/dist/components/table/snice-rating.js.map +1 -1
  187. package/dist/components/table/snice-row.d.ts +17 -6
  188. package/dist/components/table/snice-row.js +95 -44
  189. package/dist/components/table/snice-row.js.map +1 -1
  190. package/dist/components/table/snice-table.d.ts +18 -10
  191. package/dist/components/table/snice-table.js +355 -173
  192. package/dist/components/table/snice-table.js.map +1 -1
  193. package/dist/components/table/snice-table.types.d.ts +101 -2
  194. package/dist/components/tabs/snice-tab-panel.d.ts +2 -2
  195. package/dist/components/tabs/snice-tab-panel.js +12 -6
  196. package/dist/components/tabs/snice-tab-panel.js.map +1 -1
  197. package/dist/components/tabs/snice-tab.d.ts +6 -5
  198. package/dist/components/tabs/snice-tab.js +36 -19
  199. package/dist/components/tabs/snice-tab.js.map +1 -1
  200. package/dist/components/tabs/snice-tabs.d.ts +5 -5
  201. package/dist/components/tabs/snice-tabs.js +38 -28
  202. package/dist/components/tabs/snice-tabs.js.map +1 -1
  203. package/dist/components/toast/snice-toast-container.d.ts +7 -7
  204. package/dist/components/toast/snice-toast-container.js +19 -12
  205. package/dist/components/toast/snice-toast-container.js.map +1 -1
  206. package/dist/components/toast/snice-toast.d.ts +3 -15
  207. package/dist/components/toast/snice-toast.js +49 -108
  208. package/dist/components/toast/snice-toast.js.map +1 -1
  209. package/dist/components/tooltip/snice-tooltip.d.ts +2 -2
  210. package/dist/components/tooltip/snice-tooltip.js +14 -7
  211. package/dist/components/tooltip/snice-tooltip.js.map +1 -1
  212. package/dist/context.d.ts +44 -0
  213. package/dist/element-ready.d.ts +40 -0
  214. package/dist/{types/element.d.ts → element.d.ts} +2 -8
  215. package/dist/{types/events.d.ts → events.d.ts} +0 -4
  216. package/dist/index.cjs +2589 -605
  217. package/dist/index.cjs.map +1 -1
  218. package/dist/index.d.ts +21 -0
  219. package/dist/index.esm.js +2568 -604
  220. package/dist/index.esm.js.map +1 -1
  221. package/dist/index.iife.js +2589 -605
  222. package/dist/index.iife.js.map +1 -1
  223. package/dist/method-decorators.d.ts +121 -0
  224. package/dist/on.d.ts +59 -0
  225. package/dist/parts.d.ts +159 -0
  226. package/dist/render-debug.d.ts +27 -0
  227. package/dist/render-tracker.d.ts +14 -0
  228. package/dist/render.d.ts +96 -0
  229. package/dist/symbols.cjs +163 -0
  230. package/dist/symbols.cjs.map +1 -1
  231. package/dist/{types/symbols.d.ts → symbols.d.ts} +22 -0
  232. package/dist/symbols.esm.js +27 -3
  233. package/dist/symbols.esm.js.map +1 -1
  234. package/dist/template.d.ts +100 -0
  235. package/dist/transitions.cjs +219 -0
  236. package/dist/transitions.esm.js +2 -2
  237. package/dist/types/context.d.ts +48 -0
  238. package/dist/types/element-options.d.ts +26 -0
  239. package/dist/types/index.d.ts +25 -9
  240. package/dist/types/nav-context.d.ts +19 -0
  241. package/dist/types/{types/on-options.d.ts → on-options.d.ts} +2 -0
  242. package/dist/types/{types/placard.d.ts → placard.d.ts} +0 -1
  243. package/docs/ai/README.md +17 -0
  244. package/docs/ai/api.md +175 -0
  245. package/docs/ai/architecture.md +160 -0
  246. package/docs/ai/components/accordion.md +174 -0
  247. package/docs/ai/components/alert.md +77 -0
  248. package/docs/ai/components/avatar.md +61 -0
  249. package/docs/ai/components/badge.md +69 -0
  250. package/docs/ai/components/breadcrumbs.md +74 -0
  251. package/docs/ai/components/button.md +75 -0
  252. package/docs/ai/components/card.md +61 -0
  253. package/docs/ai/components/checkbox.md +74 -0
  254. package/docs/ai/components/chip.md +73 -0
  255. package/docs/ai/components/date-picker.md +75 -0
  256. package/docs/ai/components/divider.md +66 -0
  257. package/docs/ai/components/drawer.md +80 -0
  258. package/docs/ai/components/input.md +111 -0
  259. package/docs/ai/components/login.md +109 -0
  260. package/docs/ai/components/modal.md +67 -0
  261. package/docs/ai/components/nav.md +76 -0
  262. package/docs/ai/components/pagination.md +55 -0
  263. package/docs/ai/components/progress.md +72 -0
  264. package/docs/ai/components/radio.md +79 -0
  265. package/docs/ai/components/select.md +92 -0
  266. package/docs/ai/components/skeleton.md +57 -0
  267. package/docs/ai/components/switch.md +53 -0
  268. package/docs/ai/components/table.md +227 -0
  269. package/docs/ai/components/tabs.md +83 -0
  270. package/docs/ai/components/toast.md +140 -0
  271. package/docs/ai/components/tooltip.md +146 -0
  272. package/docs/ai/patterns.md +244 -0
  273. package/docs/components/accordion.md +558 -0
  274. package/docs/components/drawer.md +602 -0
  275. package/docs/components/modal.md +558 -0
  276. package/docs/components/nav.md +239 -0
  277. package/docs/components/pagination.md +289 -0
  278. package/docs/components/select.md +599 -0
  279. package/docs/components/switch.md +354 -0
  280. package/docs/components/tabs.md +546 -0
  281. package/docs/components/toast.md +506 -0
  282. package/docs/components/tooltip.md +523 -0
  283. package/docs/controllers.md +744 -0
  284. package/docs/elements.md +855 -0
  285. package/docs/events.md +807 -0
  286. package/docs/migration-v2-to-v3.md +569 -0
  287. package/docs/observe.md +588 -0
  288. package/docs/placards.md +401 -0
  289. package/docs/request-response.md +852 -0
  290. package/docs/routing.md +1186 -0
  291. package/package.json +10 -11
  292. package/dist/components/snice-cell-C9N6yGxQ.js +0 -4
  293. package/dist/components/snice-cell-C9N6yGxQ.js.map +0 -1
  294. package/dist/types/types/index.d.ts +0 -23
  295. /package/dist/{types/controller.d.ts → controller.d.ts} +0 -0
  296. /package/dist/{types/global.d.ts → global.d.ts} +0 -0
  297. /package/dist/{types/observe.d.ts → observe.d.ts} +0 -0
  298. /package/dist/{types/request-response.d.ts → request-response.d.ts} +0 -0
  299. /package/dist/{types/router.d.ts → router.d.ts} +0 -0
  300. /package/dist/{types/testing.d.ts → testing.d.ts} +0 -0
  301. /package/dist/{types/transitions.d.ts → transitions.d.ts} +0 -0
  302. /package/dist/types/{types/adopted-options.d.ts → adopted-options.d.ts} +0 -0
  303. /package/dist/types/{types/app-context.d.ts → app-context.d.ts} +0 -0
  304. /package/dist/types/{types/dispatch-options.d.ts → dispatch-options.d.ts} +0 -0
  305. /package/dist/types/{types/guard.d.ts → guard.d.ts} +0 -0
  306. /package/dist/types/{types/i-controller.d.ts → i-controller.d.ts} +0 -0
  307. /package/dist/types/{types/moved-options.d.ts → moved-options.d.ts} +0 -0
  308. /package/dist/types/{types/observe-options.d.ts → observe-options.d.ts} +0 -0
  309. /package/dist/types/{types/page-options.d.ts → page-options.d.ts} +0 -0
  310. /package/dist/types/{types/part-options.d.ts → part-options.d.ts} +0 -0
  311. /package/dist/types/{types/property-converter.d.ts → property-converter.d.ts} +0 -0
  312. /package/dist/types/{types/property-options.d.ts → property-options.d.ts} +0 -0
  313. /package/dist/types/{types/query-options.d.ts → query-options.d.ts} +0 -0
  314. /package/dist/types/{types/request-options.d.ts → request-options.d.ts} +0 -0
  315. /package/dist/types/{types/respond-options.d.ts → respond-options.d.ts} +0 -0
  316. /package/dist/types/{types/route-params.d.ts → route-params.d.ts} +0 -0
  317. /package/dist/types/{types/router-instance.d.ts → router-instance.d.ts} +0 -0
  318. /package/dist/types/{types/router-options.d.ts → router-options.d.ts} +0 -0
  319. /package/dist/types/{types/simple-array.d.ts → simple-array.d.ts} +0 -0
  320. /package/dist/types/{types/snice-element.d.ts → snice-element.d.ts} +0 -0
  321. /package/dist/types/{types/snice-global.d.ts → snice-global.d.ts} +0 -0
  322. /package/dist/types/{types/transition.d.ts → transition.d.ts} +0 -0
  323. /package/dist/{types/utils.d.ts → utils.d.ts} +0 -0
package/dist/index.esm.js CHANGED
@@ -1,6 +1,6 @@
1
1
  /*!
2
- * snice v2.5.3
3
- * Imperative TypeScript framework for building vanilla web components with decorators, routing, and controllers. No virtual DOM, no build complexity.
2
+ * snice v3.0.0
3
+ * Imperative TypeScript framework for building vanilla web components with decorators, differential rendering, routing, and controllers. No virtual DOM, no build complexity.
4
4
  * (c) 2024
5
5
  * Released under the MIT License.
6
6
  */
@@ -36,10 +36,12 @@ const CHANNEL_HANDLERS = getSymbol('channel-handlers');
36
36
  // Internal element state symbols
37
37
  const READY_PROMISE = getSymbol('ready-promise');
38
38
  const READY_RESOLVE = getSymbol('ready-resolve');
39
+ getSymbol('rendered-promise');
40
+ getSymbol('rendered-resolve');
39
41
  const CONTROLLER = getSymbol('controller');
40
42
  const INITIALIZED = getSymbol('initialized');
41
43
  // Event handler symbols
42
- const ON_HANDLERS = getSymbol('on-handlers');
44
+ getSymbol('on-handlers');
43
45
  // Controller symbols
44
46
  const CONTROLLER_KEY = getSymbol('controller-key');
45
47
  const CONTROLLER_NAME_KEY = getSymbol('controller-name');
@@ -51,13 +53,14 @@ const CLEANUP = getSymbol('cleanup');
51
53
  // Property symbols
52
54
  const PROPERTIES = getSymbol('properties');
53
55
  const PROPERTY_VALUES = getSymbol('property-values');
56
+ const PRE_INIT_PROPERTY_VALUES = getSymbol('pre-init-property-values');
54
57
  const PROPERTIES_INITIALIZED = getSymbol('properties-initialized');
55
58
  const PROPERTY_WATCHERS = getSymbol('property-watchers');
56
59
  const EXPLICITLY_SET_PROPERTIES = getSymbol('explicitly-set-properties');
57
60
  // Router context symbol
58
61
  const ROUTER_CONTEXT = getSymbol('router-context');
59
62
  getSymbol('current-page-marker');
60
- const CONTEXT_REQUEST_HANDLER = getSymbol('context-request-handler');
63
+ getSymbol('context-request-handler');
61
64
  const PAGE_TRANSITION = getSymbol('page-transition');
62
65
  const CREATED_AT = getSymbol('created-at');
63
66
  // Lifecycle symbols
@@ -68,313 +71,34 @@ const ADOPTED_HANDLERS = getSymbol('adopted-handlers');
68
71
  // Observer symbols
69
72
  const OBSERVERS = getSymbol('observers');
70
73
  // Part symbols
71
- const PARTS = getSymbol('parts');
72
- const PART_TIMERS = getSymbol('part-timers');
74
+ getSymbol('parts');
75
+ getSymbol('part-timers');
73
76
  // Lifecycle callback timers
74
77
  const MOVED_TIMERS = getSymbol('moved-timers');
75
78
  const ADOPTED_TIMERS = getSymbol('adopted-timers');
76
79
  // Dispatch timing symbols
77
80
  const DISPATCH_TIMERS = getSymbol('dispatch-timers');
78
-
79
- function on(eventName, selectorOrOptions, options) {
80
- // Handle overloaded parameters
81
- let selector;
82
- let opts;
83
- if (typeof selectorOrOptions === 'string') {
84
- selector = selectorOrOptions;
85
- opts = options;
86
- }
87
- else {
88
- selector = undefined;
89
- opts = selectorOrOptions;
90
- }
91
- return function (target, context) {
92
- const propertyKey = context.name;
93
- context.addInitializer(function () {
94
- const constructor = this.constructor;
95
- // Store event handler metadata
96
- if (!constructor.prototype[ON_HANDLERS]) {
97
- constructor.prototype[ON_HANDLERS] = [];
98
- }
99
- // Normalize to array and expand at decoration time
100
- const eventNames = Array.isArray(eventName) ? eventName : [eventName];
101
- // Create a handler entry for each event
102
- for (const event of eventNames) {
103
- constructor.prototype[ON_HANDLERS].push({
104
- eventName: event,
105
- selector,
106
- methodName: propertyKey,
107
- method: target,
108
- options: opts
109
- });
110
- }
111
- });
112
- };
113
- }
114
- // Helper to setup event handlers for elements
115
- function setupEventHandlers(instance, element) {
116
- const handlers = instance.constructor.prototype[ON_HANDLERS];
117
- if (!handlers)
118
- return;
119
- // Initialize cleanup object if needed
120
- if (!instance[CLEANUP]) {
121
- instance[CLEANUP] = { events: [], channels: [] };
122
- }
123
- for (const handler of handlers) {
124
- // Get the current method from the instance (preserves decorator stacking)
125
- const currentMethod = instance[handler.method.name];
126
- const originalMethod = currentMethod ? currentMethod.bind(instance) : handler.method.bind(instance);
127
- const handlerOptions = handler.options || {};
128
- // Parse event name for key modifiers
129
- const [baseEventName, keyModifier] = handler.eventName.split(':');
130
- // Create debounced/throttled wrapper if needed
131
- const createTimedWrapper = (method) => {
132
- if (handlerOptions.debounce) {
133
- let timeoutId;
134
- return function (...args) {
135
- clearTimeout(timeoutId);
136
- timeoutId = setTimeout(() => method.apply(this, args), handlerOptions.debounce);
137
- };
138
- }
139
- if (handlerOptions.throttle) {
140
- let lastCall = 0;
141
- let timeoutId;
142
- return function (...args) {
143
- const now = Date.now();
144
- const remaining = handlerOptions.throttle - (now - lastCall);
145
- if (remaining <= 0) {
146
- clearTimeout(timeoutId);
147
- lastCall = now;
148
- method.apply(this, args);
149
- }
150
- else if (!timeoutId) {
151
- timeoutId = setTimeout(() => {
152
- lastCall = Date.now();
153
- timeoutId = null;
154
- method.apply(this, args);
155
- }, remaining);
156
- }
157
- };
158
- }
159
- return method;
160
- };
161
- // Create the event handler with key modifier support
162
- const createEventHandler = (method) => {
163
- if (keyModifier && (baseEventName === 'keydown' || baseEventName === 'keyup' || baseEventName === 'keypress')) {
164
- return (event) => {
165
- const keyEvent = event;
166
- // Helper to normalize key names (e.g., "Space" -> " ")
167
- const normalizeKey = (key) => {
168
- if (key === 'Space')
169
- return ' ';
170
- return key;
171
- };
172
- // Check for "any modifiers" match with ~ prefix
173
- if (keyModifier.startsWith('~')) {
174
- const key = normalizeKey(keyModifier.slice(1)); // Remove the ~ and normalize
175
- // Match if key matches, regardless of modifiers
176
- if (keyEvent.key === key) {
177
- method(event);
178
- }
179
- return;
180
- }
181
- // Check for modifier combinations using +
182
- if (keyModifier.includes('+')) {
183
- const parts = keyModifier.split('+');
184
- const key = normalizeKey(parts[parts.length - 1]); // Last part is the actual key
185
- const modifiers = parts.slice(0, -1); // Everything else is modifiers
186
- // Check the actual key
187
- if (keyEvent.key !== key)
188
- return;
189
- // Create a set of expected modifiers
190
- const expectedModifiers = new Set(modifiers.map((m) => m.toLowerCase()));
191
- const hasCtrl = expectedModifiers.has('ctrl');
192
- const hasShift = expectedModifiers.has('shift');
193
- const hasAlt = expectedModifiers.has('alt');
194
- const hasMeta = expectedModifiers.has('meta') || expectedModifiers.has('cmd');
195
- // Check that expected modifiers are pressed and unexpected ones are not
196
- const modifiersMatch = keyEvent.ctrlKey === hasCtrl &&
197
- keyEvent.shiftKey === hasShift &&
198
- keyEvent.altKey === hasAlt &&
199
- keyEvent.metaKey === hasMeta;
200
- if (modifiersMatch) {
201
- method(event);
202
- }
203
- }
204
- else {
205
- // Default: exact match (no modifiers allowed)
206
- const key = normalizeKey(keyModifier);
207
- // Only match if key matches AND no modifiers are pressed
208
- if (keyEvent.key === key &&
209
- !keyEvent.ctrlKey &&
210
- !keyEvent.shiftKey &&
211
- !keyEvent.altKey &&
212
- !keyEvent.metaKey) {
213
- method(event);
214
- }
215
- }
216
- };
217
- }
218
- return method;
219
- };
220
- // Apply timing wrapper (debounce/throttle)
221
- const timedMethod = createTimedWrapper(originalMethod);
222
- // Wrap boundMethod in try-catch for error isolation
223
- const wrappedMethod = createEventHandler((event) => {
224
- try {
225
- // Apply automatic preventDefault/stopPropagation if configured
226
- if (handlerOptions.preventDefault) {
227
- event.preventDefault();
228
- }
229
- if (handlerOptions.stopPropagation) {
230
- event.stopPropagation();
231
- }
232
- return timedMethod(event);
233
- }
234
- catch (error) {
235
- console.error(`Error in event handler ${handler.methodName}:`, error);
236
- // Don't rethrow - allow other handlers to continue
237
- }
238
- });
239
- if (handler.selector) {
240
- // Delegated event handling - use shadow root if available
241
- const eventRoot = element.shadowRoot || element;
242
- const delegatedHandler = (event) => {
243
- const target = event.target;
244
- let shouldHandle = false;
245
- if (target.matches && target.matches(handler.selector)) {
246
- shouldHandle = true;
247
- }
248
- else if (target.closest) {
249
- const closest = target.closest(handler.selector);
250
- if (closest) {
251
- shouldHandle = true;
252
- }
253
- }
254
- if (shouldHandle) {
255
- // Apply automatic preventDefault/stopPropagation only if we're handling this event
256
- if (handlerOptions.preventDefault) {
257
- event.preventDefault();
258
- }
259
- if (handlerOptions.stopPropagation) {
260
- event.stopPropagation();
261
- event.stopImmediatePropagation(); // Also stop other handlers on same element
262
- }
263
- wrappedMethod(event);
264
- }
265
- };
266
- const listenerOptions = {
267
- capture: handlerOptions.capture || false,
268
- once: handlerOptions.once || false,
269
- passive: handlerOptions.passive || false
270
- };
271
- eventRoot.addEventListener(baseEventName, delegatedHandler, listenerOptions);
272
- instance[CLEANUP].events.push(() => {
273
- eventRoot.removeEventListener(baseEventName, delegatedHandler, listenerOptions);
274
- });
275
- }
276
- else {
277
- // Direct event handling - always on the element itself
278
- const listenerOptions = {
279
- capture: handlerOptions.capture || false,
280
- once: handlerOptions.once || false,
281
- passive: handlerOptions.passive || false
282
- };
283
- element.addEventListener(baseEventName, wrappedMethod, listenerOptions);
284
- instance[CLEANUP].events.push(() => {
285
- element.removeEventListener(baseEventName, wrappedMethod, listenerOptions);
286
- });
287
- }
288
- }
289
- }
290
- // Helper to cleanup event handlers
291
- function cleanupEventHandlers(instance) {
292
- if (instance[CLEANUP]?.events) {
293
- for (const cleanup of instance[CLEANUP].events) {
294
- cleanup();
295
- }
296
- instance[CLEANUP].events = [];
297
- }
298
- }
299
- /**
300
- * Decorator that automatically dispatches a custom event after a method is called.
301
- * The return value of the method becomes the event detail.
302
- *
303
- * @param eventName The name of the event to dispatch
304
- * @param options Optional configuration extending EventInit
305
- */
306
- function dispatch(eventName, options) {
307
- return function (originalMethod, _context) {
308
- return function (...args) {
309
- // Create timing wrappers for dispatch (per-instance)
310
- if (!this[DISPATCH_TIMERS]) {
311
- this[DISPATCH_TIMERS] = new Map();
312
- }
313
- const timerKey = `${eventName}_${_context.name}`;
314
- if (!this[DISPATCH_TIMERS].has(timerKey)) {
315
- this[DISPATCH_TIMERS].set(timerKey, {
316
- debounceTimeout: null,
317
- throttleLastCall: 0,
318
- throttleTimeout: null
319
- });
320
- }
321
- const timers = this[DISPATCH_TIMERS].get(timerKey);
322
- // Call the original method with preserved this context
323
- const result = originalMethod.apply(this, args);
324
- // Helper to dispatch the event
325
- const doDispatch = (detail) => {
326
- // Skip dispatch if result is undefined and dispatchOnUndefined is false
327
- if (detail === undefined && options?.dispatchOnUndefined === false) {
328
- return;
329
- }
330
- // Create event with spread operator for options
331
- const event = new CustomEvent(eventName, {
332
- bubbles: true, // Default to true for component events
333
- composed: true, // Allow crossing shadow DOM boundaries
334
- ...options, // Spread all EventInit options
335
- detail
336
- });
337
- this.dispatchEvent(event);
338
- };
339
- // Helper to handle timed dispatch
340
- const timedDispatch = (detail) => {
341
- if (options?.debounce) {
342
- clearTimeout(timers.debounceTimeout);
343
- timers.debounceTimeout = setTimeout(() => doDispatch(detail), options.debounce);
344
- }
345
- else if (options?.throttle) {
346
- const now = Date.now();
347
- const remaining = options.throttle - (now - timers.throttleLastCall);
348
- if (remaining <= 0) {
349
- clearTimeout(timers.throttleTimeout);
350
- timers.throttleLastCall = now;
351
- doDispatch(detail);
352
- }
353
- else if (!timers.throttleTimeout) {
354
- timers.throttleTimeout = setTimeout(() => {
355
- timers.throttleLastCall = Date.now();
356
- timers.throttleTimeout = null;
357
- doDispatch(detail);
358
- }, remaining);
359
- }
360
- }
361
- else {
362
- doDispatch(detail);
363
- }
364
- };
365
- // Handle async methods
366
- if (result instanceof Promise) {
367
- return result.then((resolvedResult) => {
368
- timedDispatch(resolvedResult);
369
- return resolvedResult;
370
- });
371
- }
372
- // Sync method
373
- timedDispatch(result);
374
- return result;
375
- };
376
- };
377
- }
81
+ // Render symbols (v3.0.0)
82
+ const RENDER_METHOD = getSymbol('render-method');
83
+ const RENDER_OPTIONS = getSymbol('render-options');
84
+ const RENDER_INSTANCE = getSymbol('render-instance');
85
+ const RENDER_SCHEDULED = getSymbol('render-scheduled');
86
+ const RENDER_TIMERS = getSymbol('render-timers');
87
+ const RENDER_CALLBACKS = getSymbol('render-callbacks');
88
+ const STYLES_METHOD = getSymbol('styles-method');
89
+ const STYLES_APPLIED = getSymbol('styles-applied');
90
+ // Navigation context symbols
91
+ const CONTEXT_HANDLER = getSymbol('context-handler');
92
+ getSymbol('context-method-name');
93
+ const NAVIGATION_CONTEXT_INSTANCE = getSymbol('navigation-context-instance');
94
+ const REGISTERED_ELEMENTS = getSymbol('registered-elements');
95
+ const IS_UPDATING = getSymbol('is-updating');
96
+ const CONTEXT_REGISTER = getSymbol('context-register');
97
+ const CONTEXT_UNREGISTER = getSymbol('context-unregister');
98
+ const CONTEXT_NOTIFY_ELEMENT = getSymbol('context-notify-element');
99
+ getSymbol('context-options');
100
+ const CONTEXT_TIMER = getSymbol('context-timer');
101
+ const CONTEXT_CALLED = getSymbol('context-called');
378
102
 
379
103
  // Global cache for MediaQueryList objects
380
104
  const mediaQueryCache = new Map();
@@ -401,21 +125,22 @@ function observe(observeTarget, selectorOrOptions, options) {
401
125
  }
402
126
  return function (target, context) {
403
127
  const propertyKey = context.name;
128
+ const initKey = `__observe_init_${propertyKey}`;
404
129
  context.addInitializer(function () {
405
130
  const constructor = this.constructor;
406
- // Store observer metadata
407
- if (!constructor.prototype[OBSERVERS]) {
408
- constructor.prototype[OBSERVERS] = [];
131
+ if (constructor[initKey])
132
+ return;
133
+ constructor[initKey] = true;
134
+ if (!constructor[OBSERVERS]) {
135
+ constructor[OBSERVERS] = [];
409
136
  }
410
- // Normalize to array
411
137
  const observeTargets = Array.isArray(observeTarget) ? observeTarget : [observeTarget];
412
- // Create an observer entry for each target
413
138
  for (const targetString of observeTargets) {
414
- // Parse the observation type from the observeTarget string
415
139
  const [type, ...modifiers] = targetString.split(':');
416
- constructor.prototype[OBSERVERS].push({
140
+ const targetStr = modifiers.join(':');
141
+ constructor[OBSERVERS].push({
417
142
  type,
418
- target: modifiers.join(':'), // Rejoin for media queries or mutation types
143
+ target: targetStr,
419
144
  selector,
420
145
  methodName: propertyKey,
421
146
  method: target,
@@ -427,8 +152,7 @@ function observe(observeTarget, selectorOrOptions, options) {
427
152
  }
428
153
  // Helper to setup observers for elements
429
154
  function setupObservers(instance, element) {
430
- // Only check the prototype, not the instance itself to avoid property access issues
431
- const observers = instance.constructor.prototype[OBSERVERS];
155
+ const observers = instance.constructor[OBSERVERS];
432
156
  if (!observers || !Array.isArray(observers) || observers.length === 0) {
433
157
  return;
434
158
  }
@@ -856,14 +580,16 @@ function request(requestName, options) {
856
580
  function respond(requestName, options) {
857
581
  return function (target, context) {
858
582
  const propertyKey = context.name;
583
+ const initKey = `__respond_init_${requestName}_${propertyKey}`;
859
584
  context.addInitializer(function () {
860
585
  const constructor = this.constructor;
861
- // Store response metadata on the prototype
862
- // This will be picked up by setupResponseHandlers
863
- if (!constructor.prototype[CHANNEL_HANDLERS]) {
864
- constructor.prototype[CHANNEL_HANDLERS] = [];
586
+ if (constructor[initKey])
587
+ return;
588
+ constructor[initKey] = true;
589
+ if (!constructor[CHANNEL_HANDLERS]) {
590
+ constructor[CHANNEL_HANDLERS] = [];
865
591
  }
866
- constructor.prototype[CHANNEL_HANDLERS].push({
592
+ constructor[CHANNEL_HANDLERS].push({
867
593
  channelName: requestName,
868
594
  methodName: propertyKey,
869
595
  method: target,
@@ -874,7 +600,7 @@ function respond(requestName, options) {
874
600
  }
875
601
  // Helper to setup response handlers for elements and controllers
876
602
  function setupResponseHandlers(instance, element) {
877
- const handlers = instance.constructor.prototype[CHANNEL_HANDLERS];
603
+ const handlers = instance.constructor[CHANNEL_HANDLERS];
878
604
  if (!handlers)
879
605
  return;
880
606
  // Store cleanup functions
@@ -974,71 +700,1296 @@ function cleanupResponseHandlers(instance) {
974
700
  }
975
701
  }
976
702
 
977
- // Controller-scoped cleanup registry
978
- class ControllerScope {
979
- constructor() {
980
- this.cleanupFns = new Map();
981
- this.pendingOperations = new Set();
982
- }
983
- register(key, cleanup) {
984
- this.cleanupFns.set(key, cleanup);
985
- }
986
- unregister(key) {
987
- this.cleanupFns.delete(key);
988
- }
989
- async cleanup() {
990
- // Wait for all pending operations
991
- await Promise.all(this.pendingOperations);
992
- // Run all cleanup functions
993
- for (const cleanup of this.cleanupFns.values()) {
994
- try {
995
- await cleanup();
996
- }
997
- catch (error) {
998
- console.error('Error during cleanup:', error);
999
- }
1000
- }
1001
- this.cleanupFns.clear();
703
+ /**
704
+ * Template system for Snice v3.0.0
705
+ * Inspired by lit-html but custom implementation
706
+ * Provides html`` and css`` tagged template processors with differential rendering
707
+ */
708
+ // Unique symbols for type checking
709
+ const HTML_RESULT = Symbol('html-result');
710
+ const CSS_RESULT = Symbol('css-result');
711
+ /**
712
+ * Tagged template function for creating HTML templates
713
+ *
714
+ * @example
715
+ * ```typescript
716
+ * html`<div class="card">
717
+ * <h1>${this.title}</h1>
718
+ * <button @click=${this.handleClick}>Click me</button>
719
+ * </div>`
720
+ * ```
721
+ */
722
+ function html(strings, ...values) {
723
+ return {
724
+ _$litType$: HTML_RESULT,
725
+ strings,
726
+ values
727
+ };
728
+ }
729
+ /**
730
+ * Tagged template function for creating CSS
731
+ *
732
+ * @example
733
+ * ```typescript
734
+ * css`:host {
735
+ * display: block;
736
+ * padding: 1rem;
737
+ * }`
738
+ * ```
739
+ */
740
+ function css(strings, ...values) {
741
+ // Combine strings and values into final CSS text
742
+ let cssText = strings[0];
743
+ for (let i = 0; i < values.length; i++) {
744
+ cssText += String(values[i]) + strings[i + 1];
1002
745
  }
1003
- async runOperation(operation) {
1004
- const promise = operation();
1005
- const voidPromise = promise.then(() => { }, () => { });
1006
- this.pendingOperations.add(voidPromise);
746
+ const result = {
747
+ _$litType$: CSS_RESULT,
748
+ cssText
749
+ };
750
+ // Try to create constructable stylesheet for better performance
751
+ // This will be cached and reused across instances
752
+ if (typeof CSSStyleSheet !== 'undefined' && 'adoptedStyleSheets' in Document.prototype) {
1007
753
  try {
1008
- const result = await promise;
1009
- this.pendingOperations.delete(voidPromise);
1010
- return result;
754
+ const sheet = new CSSStyleSheet();
755
+ sheet.replaceSync(cssText);
756
+ result.styleSheet = sheet;
1011
757
  }
1012
- catch (error) {
1013
- this.pendingOperations.delete(voidPromise);
1014
- throw error;
758
+ catch (e) {
759
+ // Fall back to regular <style> tag if constructable stylesheets fail
1015
760
  }
1016
761
  }
762
+ return result;
1017
763
  }
1018
764
  /**
1019
- * Decorator to register a controller class with a name
1020
- * @param name The name to register the controller under
765
+ * Check if a value is a TemplateResult
1021
766
  */
1022
- function controller(name) {
1023
- return function (constructor, _context) {
1024
- snice.controllerRegistry.set(name, constructor);
1025
- // Mark as controller class for channel decorator detection
1026
- constructor.prototype[IS_CONTROLLER_CLASS] = true;
1027
- return constructor;
1028
- };
767
+ function isTemplateResult(value) {
768
+ return value && value._$litType$ === HTML_RESULT;
1029
769
  }
1030
770
  /**
1031
- * Attaches a controller to an element
1032
- * @param element The element to attach the controller to
1033
- * @param controllerName The name of the controller to attach
771
+ * Check if a value is a CSSResult
1034
772
  */
1035
- async function attachController(element, controllerName) {
1036
- const existingController = element[CONTROLLER_KEY];
1037
- const existingName = element[CONTROLLER_NAME_KEY];
1038
- // For native elements, check if this is actually the desired controller
1039
- const nativeController = element[NATIVE_CONTROLLER];
1040
- if (nativeController !== undefined && nativeController !== controllerName) {
1041
- // This attachment is outdated, skip it
773
+ function isCSSResult(value) {
774
+ return value && value._$litType$ === CSS_RESULT;
775
+ }
776
+ /**
777
+ * Nothing - represents no value (different from null/undefined)
778
+ * Used to remove content from templates
779
+ */
780
+ const nothing = Symbol('nothing');
781
+ // Unique symbol for unsafe HTML
782
+ const UNSAFE_HTML = Symbol('unsafe-html');
783
+ /**
784
+ * Mark a string as raw HTML that should not be escaped
785
+ * WARNING: Only use with sanitized content - using user input can lead to XSS!
786
+ *
787
+ * @example
788
+ * ```typescript
789
+ * const htmlString = '<span class="bold">Hello</span>';
790
+ * html`<div>${unsafeHTML(htmlString)}</div>`
791
+ * ```
792
+ */
793
+ function unsafeHTML(html) {
794
+ return {
795
+ _$litType$: UNSAFE_HTML,
796
+ html
797
+ };
798
+ }
799
+ /**
800
+ * Check if a value is an UnsafeHTML wrapper
801
+ */
802
+ function isUnsafeHTML(value) {
803
+ return value && value._$litType$ === UNSAFE_HTML;
804
+ }
805
+
806
+ /**
807
+ * Simplified lit-html-style template system
808
+ * Based on lit-html's approach but simplified
809
+ */
810
+ // Unique marker for dynamic parts
811
+ // Using processing instruction syntax like lit-html for better compatibility
812
+ // This parses as a comment node but doesn't get escaped in attributes
813
+ const marker = `snice$${Math.random().toFixed(9).slice(2)}$`;
814
+ const markerMatch = '?' + marker;
815
+ const nodeMarker = `<${markerMatch}>`;
816
+ const markerRegex = new RegExp(marker, 'g');
817
+ // Template cache removed - negligible performance benefit (~0.00004ms per template)
818
+ /**
819
+ * A prepared template ready for rendering
820
+ */
821
+ class Template {
822
+ constructor(result, element, attrNamesForParts) {
823
+ this.parts = [];
824
+ this.element = element;
825
+ const walker = document.createTreeWalker(element.content, NodeFilter.SHOW_ELEMENT | NodeFilter.SHOW_COMMENT | NodeFilter.SHOW_TEXT);
826
+ let partIndex = 0;
827
+ const nodesToRemove = [];
828
+ let node;
829
+ while ((node = walker.nextNode()) !== null) {
830
+ if (node.nodeType === Node.ELEMENT_NODE) {
831
+ const element = node;
832
+ const tagName = element.tagName.toLowerCase();
833
+ // Handle virtual elements: <if>, <case>
834
+ // These elements stay in the DOM but are styled with display:contents
835
+ // to be transparent wrappers that don't affect layout
836
+ if (tagName === 'if') {
837
+ // <if value="${condition}">children</if>
838
+ const valueAttr = element.getAttribute('value');
839
+ if (valueAttr && valueAttr.includes(marker)) {
840
+ // Remove the value attribute
841
+ element.removeAttribute('value');
842
+ this.parts.push({
843
+ type: 'if',
844
+ index: partIndex++,
845
+ element // Keep the <if> element, will show/hide via display property
846
+ });
847
+ // Continue processing children normally
848
+ }
849
+ continue;
850
+ }
851
+ // Handle <case> element
852
+ // Like <if>, <case> stays in DOM styled with display:contents
853
+ if (tagName === 'case') {
854
+ // <case value="${value}">children</case>
855
+ const valueAttr = element.getAttribute('value');
856
+ if (valueAttr && valueAttr.includes(marker)) {
857
+ // Remove the value attribute
858
+ element.removeAttribute('value');
859
+ this.parts.push({
860
+ type: 'case',
861
+ index: partIndex++,
862
+ caseElement: element // Keep the <case> element for when/default processing
863
+ });
864
+ // Continue processing children normally
865
+ }
866
+ continue;
867
+ }
868
+ if (element.hasAttributes()) {
869
+ const attributes = element.attributes;
870
+ const attrsToRemove = [];
871
+ for (let i = 0; i < attributes.length; i++) {
872
+ const attr = attributes[i];
873
+ const value = attr.value;
874
+ // Check for attribute bindings
875
+ if (value.includes(marker)) {
876
+ attrsToRemove.push(attr);
877
+ // Get original attribute name with preserved case
878
+ const originalName = attrNamesForParts[partIndex] || attr.name;
879
+ // Extract static string segments by splitting on marker
880
+ const attrStrings = value.split(marker);
881
+ if (originalName.startsWith('@')) {
882
+ // Event binding
883
+ this.parts.push({
884
+ type: 'event',
885
+ index: partIndex++,
886
+ name: originalName.slice(1),
887
+ element
888
+ });
889
+ }
890
+ else if (originalName.startsWith('.')) {
891
+ // Property binding - preserve original case for JavaScript properties
892
+ this.parts.push({
893
+ type: 'property',
894
+ index: partIndex++,
895
+ name: originalName.slice(1),
896
+ element
897
+ });
898
+ }
899
+ else if (originalName.startsWith('?')) {
900
+ // Boolean attribute
901
+ this.parts.push({
902
+ type: 'boolean-attribute',
903
+ index: partIndex++,
904
+ name: originalName.slice(1),
905
+ element
906
+ });
907
+ }
908
+ else {
909
+ // Regular attribute - use lowercased name from DOM
910
+ // Store static string segments for interpolation
911
+ this.parts.push({
912
+ type: 'attribute',
913
+ index: partIndex++,
914
+ name: attr.name,
915
+ element,
916
+ attrStrings
917
+ });
918
+ }
919
+ }
920
+ }
921
+ // Remove marker attributes
922
+ for (const attr of attrsToRemove) {
923
+ element.removeAttribute(attr.name);
924
+ }
925
+ }
926
+ }
927
+ else if (node.nodeType === Node.COMMENT_NODE) {
928
+ const comment = node;
929
+ // Check for marker match (processing instruction becomes comment)
930
+ if (comment.data === markerMatch) {
931
+ // Node part
932
+ const parent = comment.parentNode;
933
+ const endNode = document.createComment('');
934
+ parent.insertBefore(endNode, comment.nextSibling);
935
+ this.parts.push({
936
+ type: 'node',
937
+ index: partIndex++,
938
+ startNode: comment,
939
+ endNode
940
+ });
941
+ }
942
+ }
943
+ else if (node.nodeType === Node.TEXT_NODE) {
944
+ const text = node;
945
+ const data = text.data;
946
+ if (data.includes(marker)) {
947
+ // Split text node at markers
948
+ const parent = text.parentNode;
949
+ const parts = data.split(markerRegex);
950
+ const lastIndex = parts.length - 1;
951
+ for (let i = 0; i < lastIndex; i++) {
952
+ parent.insertBefore(document.createTextNode(parts[i]), text);
953
+ const comment = document.createComment('');
954
+ const endNode = document.createComment('');
955
+ parent.insertBefore(comment, text);
956
+ parent.insertBefore(endNode, text);
957
+ this.parts.push({
958
+ type: 'node',
959
+ index: partIndex++,
960
+ startNode: comment,
961
+ endNode
962
+ });
963
+ }
964
+ // Last part
965
+ if (parts[lastIndex] !== '') {
966
+ text.data = parts[lastIndex];
967
+ }
968
+ else {
969
+ nodesToRemove.push(text);
970
+ }
971
+ }
972
+ }
973
+ }
974
+ // Remove marker nodes
975
+ for (const node of nodesToRemove) {
976
+ node.parentNode?.removeChild(node);
977
+ }
978
+ }
979
+ }
980
+ /**
981
+ * Prepare a template for rendering
982
+ */
983
+ function prepareTemplate(result) {
984
+ // Build HTML with markers and extract original attribute names
985
+ const { strings } = result;
986
+ let html = '';
987
+ const attrNamesForParts = [];
988
+ for (let i = 0; i < strings.length; i++) {
989
+ const str = strings[i];
990
+ html += str;
991
+ if (i < strings.length - 1) {
992
+ // Check if we're in an attribute context
993
+ // Look backwards for = sign
994
+ const lastEquals = str.lastIndexOf('=');
995
+ const lastCloseTag = str.lastIndexOf('>');
996
+ if (lastEquals > lastCloseTag) {
997
+ // We're in an attribute value - extract and preserve the original attribute name
998
+ let attrStart = lastEquals - 1;
999
+ while (attrStart >= 0 && /\S/.test(str[attrStart])) {
1000
+ attrStart--;
1001
+ }
1002
+ const attrName = str.substring(attrStart + 1, lastEquals).trim();
1003
+ attrNamesForParts.push(attrName);
1004
+ html += marker;
1005
+ }
1006
+ else {
1007
+ // Check if this is a meta element (<if> or <case>) by looking backwards
1008
+ // Match pattern: <if or <case followed by whitespace or >
1009
+ const metaElementMatch = str.match(/<(if|case)\s*$/);
1010
+ if (metaElementMatch) {
1011
+ // This is a meta element - add value attribute
1012
+ attrNamesForParts.push('value');
1013
+ html += `value="${marker}"`;
1014
+ }
1015
+ else {
1016
+ // We're in node content
1017
+ attrNamesForParts.push(''); // Empty string for node parts
1018
+ html += nodeMarker;
1019
+ }
1020
+ }
1021
+ }
1022
+ }
1023
+ const template = document.createElement('template');
1024
+ template.innerHTML = html;
1025
+ return new Template(result, template, attrNamesForParts);
1026
+ }
1027
+ /**
1028
+ * Instance of a rendered template
1029
+ */
1030
+ class TemplateInstance {
1031
+ constructor(result) {
1032
+ this.parts = [];
1033
+ this.fragment = null;
1034
+ this.template = prepareTemplate(result);
1035
+ }
1036
+ renderFragment() {
1037
+ if (!this.fragment) {
1038
+ // First render - clone template and create parts
1039
+ this.fragment = this.template.element.content.cloneNode(true);
1040
+ // Build a map of nodes from template to cloned fragment
1041
+ const walker = document.createTreeWalker(this.template.element.content, NodeFilter.SHOW_ALL);
1042
+ const clonedWalker = document.createTreeWalker(this.fragment, NodeFilter.SHOW_ALL);
1043
+ const nodeMap = new Map();
1044
+ let templateNode = walker.currentNode;
1045
+ let clonedNode = clonedWalker.currentNode;
1046
+ while (templateNode && clonedNode) {
1047
+ nodeMap.set(templateNode, clonedNode);
1048
+ templateNode = walker.nextNode();
1049
+ clonedNode = clonedWalker.nextNode();
1050
+ }
1051
+ for (const partDef of this.template.parts) {
1052
+ let part;
1053
+ switch (partDef.type) {
1054
+ case 'node':
1055
+ const startNode = nodeMap.get(partDef.startNode);
1056
+ const endNode = nodeMap.get(partDef.endNode);
1057
+ part = new NodePart(startNode, endNode);
1058
+ break;
1059
+ case 'attribute':
1060
+ const attrElement = nodeMap.get(partDef.element);
1061
+ part = new AttributePart(attrElement, partDef.name, partDef.attrStrings);
1062
+ break;
1063
+ case 'property':
1064
+ const propElement = nodeMap.get(partDef.element);
1065
+ part = new PropertyPart(propElement, partDef.name);
1066
+ break;
1067
+ case 'boolean-attribute':
1068
+ const boolElement = nodeMap.get(partDef.element);
1069
+ part = new BooleanAttributePart(boolElement, partDef.name);
1070
+ break;
1071
+ case 'event':
1072
+ const eventElement = nodeMap.get(partDef.element);
1073
+ part = new EventPart(eventElement, partDef.name);
1074
+ break;
1075
+ case 'if':
1076
+ const ifElement = nodeMap.get(partDef.element);
1077
+ part = new IfPart(ifElement);
1078
+ break;
1079
+ case 'case':
1080
+ const caseElement = nodeMap.get(partDef.caseElement);
1081
+ part = new CasePart(caseElement);
1082
+ break;
1083
+ default:
1084
+ throw new Error(`Unknown part type: ${partDef.type}`);
1085
+ }
1086
+ this.parts.push(part);
1087
+ }
1088
+ }
1089
+ return this.fragment;
1090
+ }
1091
+ render(values) {
1092
+ const fragment = this.renderFragment();
1093
+ // Commit values to parts
1094
+ this.update(values);
1095
+ return fragment;
1096
+ }
1097
+ update(values) {
1098
+ // Process virtual elements (if/case) first
1099
+ for (let i = 0; i < this.parts.length; i++) {
1100
+ const part = this.parts[i];
1101
+ if (part instanceof IfPart || part instanceof CasePart) {
1102
+ part.commit(values[i]);
1103
+ }
1104
+ }
1105
+ // Then process all other parts
1106
+ for (let i = 0; i < this.parts.length; i++) {
1107
+ const part = this.parts[i];
1108
+ if (!(part instanceof IfPart || part instanceof CasePart)) {
1109
+ part.commit(values[i]);
1110
+ }
1111
+ }
1112
+ }
1113
+ clear() {
1114
+ for (const part of this.parts) {
1115
+ part.clear();
1116
+ }
1117
+ }
1118
+ }
1119
+ /**
1120
+ * Base class for all parts
1121
+ */
1122
+ class Part {
1123
+ }
1124
+ /**
1125
+ * NodePart handles text content and nested templates
1126
+ */
1127
+ class NodePart extends Part {
1128
+ constructor(startNode, endNode) {
1129
+ super();
1130
+ this.value = undefined;
1131
+ this.startNode = startNode;
1132
+ this.endNode = endNode;
1133
+ }
1134
+ commit(value) {
1135
+ if (value === this.value)
1136
+ return;
1137
+ this.value = value;
1138
+ // Handle arrays
1139
+ if (Array.isArray(value)) {
1140
+ this.commitArray(value);
1141
+ return;
1142
+ }
1143
+ // Handle nested templates
1144
+ if (isTemplateResult(value)) {
1145
+ this.commitTemplate(value);
1146
+ return;
1147
+ }
1148
+ // Handle unsafe HTML
1149
+ if (isUnsafeHTML(value)) {
1150
+ this.commitUnsafeHTML(value);
1151
+ return;
1152
+ }
1153
+ // Handle primitives
1154
+ this.commitPrimitive(value);
1155
+ }
1156
+ commitPrimitive(value) {
1157
+ this.clear();
1158
+ const text = value === null || value === undefined ? '' : String(value);
1159
+ const textNode = document.createTextNode(text);
1160
+ this.insertBefore(textNode);
1161
+ }
1162
+ commitTemplate(template) {
1163
+ this.clear();
1164
+ const instance = new TemplateInstance(template);
1165
+ const fragment = instance.render(template.values);
1166
+ this.insertBefore(fragment);
1167
+ }
1168
+ commitArray(values) {
1169
+ this.clear();
1170
+ for (const value of values) {
1171
+ if (isTemplateResult(value)) {
1172
+ const instance = new TemplateInstance(value);
1173
+ const fragment = instance.render(value.values);
1174
+ this.insertBefore(fragment);
1175
+ }
1176
+ else {
1177
+ const text = value === null || value === undefined ? '' : String(value);
1178
+ const textNode = document.createTextNode(text);
1179
+ this.insertBefore(textNode);
1180
+ }
1181
+ }
1182
+ }
1183
+ commitUnsafeHTML(value) {
1184
+ this.clear();
1185
+ // Create a temporary container to parse the HTML
1186
+ const temp = document.createElement('template');
1187
+ temp.innerHTML = value.html;
1188
+ // Insert all parsed nodes
1189
+ const fragment = temp.content;
1190
+ this.insertBefore(fragment);
1191
+ }
1192
+ insertBefore(node) {
1193
+ this.endNode.parentNode?.insertBefore(node, this.endNode);
1194
+ }
1195
+ clear() {
1196
+ const parent = this.startNode.parentNode;
1197
+ if (!parent)
1198
+ return;
1199
+ let node = this.startNode.nextSibling;
1200
+ while (node && node !== this.endNode) {
1201
+ const next = node.nextSibling;
1202
+ parent.removeChild(node);
1203
+ node = next;
1204
+ }
1205
+ }
1206
+ }
1207
+ /**
1208
+ * AttributePart handles regular attribute updates
1209
+ */
1210
+ class AttributePart extends Part {
1211
+ constructor(element, name, attrStrings) {
1212
+ super();
1213
+ this.value = undefined;
1214
+ this.element = element;
1215
+ this.name = name;
1216
+ this.attrStrings = attrStrings;
1217
+ }
1218
+ commit(value) {
1219
+ if (value === this.value)
1220
+ return;
1221
+ this.value = value;
1222
+ if (value === null || value === undefined) {
1223
+ this.element.removeAttribute(this.name);
1224
+ }
1225
+ else {
1226
+ // Data-oriented: compute final value from strings + value
1227
+ const finalValue = computeAttributeValue(this.attrStrings, value);
1228
+ this.element.setAttribute(this.name, finalValue);
1229
+ }
1230
+ }
1231
+ clear() {
1232
+ this.element.removeAttribute(this.name);
1233
+ }
1234
+ }
1235
+ /**
1236
+ * Data-oriented function to compute attribute value from static strings and dynamic value
1237
+ */
1238
+ function computeAttributeValue(attrStrings, value) {
1239
+ if (!attrStrings || attrStrings.length === 0) {
1240
+ // No template strings, just use the value
1241
+ return String(value);
1242
+ }
1243
+ if (attrStrings.length === 1) {
1244
+ // Single string segment, no interpolation (shouldn't happen but handle it)
1245
+ return attrStrings[0];
1246
+ }
1247
+ // Multiple segments: "prefix" + value + "suffix"
1248
+ // For aria-label="Remove ${label}", attrStrings = ["Remove ", ""]
1249
+ return attrStrings[0] + String(value) + attrStrings[1];
1250
+ }
1251
+ /**
1252
+ * PropertyPart handles property bindings
1253
+ */
1254
+ class PropertyPart extends Part {
1255
+ constructor(element, name) {
1256
+ super();
1257
+ this.value = undefined;
1258
+ this.element = element;
1259
+ this.name = name;
1260
+ }
1261
+ commit(value) {
1262
+ if (value === this.value)
1263
+ return;
1264
+ this.value = value;
1265
+ this.element[this.name] = value;
1266
+ }
1267
+ clear() {
1268
+ this.element[this.name] = undefined;
1269
+ }
1270
+ }
1271
+ /**
1272
+ * BooleanAttributePart handles boolean attributes
1273
+ */
1274
+ class BooleanAttributePart extends Part {
1275
+ constructor(element, name) {
1276
+ super();
1277
+ this.value = undefined;
1278
+ this.element = element;
1279
+ this.name = name;
1280
+ }
1281
+ commit(value) {
1282
+ if (value === this.value)
1283
+ return;
1284
+ this.value = value;
1285
+ if (value) {
1286
+ this.element.setAttribute(this.name, '');
1287
+ }
1288
+ else {
1289
+ this.element.removeAttribute(this.name);
1290
+ }
1291
+ }
1292
+ clear() {
1293
+ this.element.removeAttribute(this.name);
1294
+ }
1295
+ }
1296
+ /**
1297
+ * EventPart handles event listener bindings with keyboard shortcut support
1298
+ */
1299
+ class EventPart extends Part {
1300
+ constructor(element, eventName) {
1301
+ super();
1302
+ this.listener = null;
1303
+ this.value = undefined;
1304
+ this.keyFilter = null;
1305
+ this.element = element;
1306
+ // Parse keyboard shortcuts:
1307
+ // Supports both dot notation (@keydown.enter) and colon notation (@keydown:Enter) to match @on decorator
1308
+ const dotIndex = eventName.indexOf('.');
1309
+ const colonIndex = eventName.indexOf(':');
1310
+ // Use whichever delimiter comes first (dot or colon)
1311
+ const delimiterIndex = dotIndex > 0 && colonIndex > 0
1312
+ ? Math.min(dotIndex, colonIndex)
1313
+ : Math.max(dotIndex, colonIndex);
1314
+ if (delimiterIndex > 0) {
1315
+ const baseEvent = eventName.substring(0, delimiterIndex);
1316
+ const keySpec = eventName.substring(delimiterIndex + 1);
1317
+ this.eventName = baseEvent;
1318
+ this.keyFilter = parseKeyboardFilter(keySpec);
1319
+ }
1320
+ else {
1321
+ this.eventName = eventName;
1322
+ }
1323
+ }
1324
+ commit(value) {
1325
+ // Skip if same value (but null/undefined always triggers update)
1326
+ if (value === this.value && value !== null && value !== undefined)
1327
+ return;
1328
+ // Remove old listener
1329
+ if (this.listener) {
1330
+ this.element.removeEventListener(this.eventName, this.listener);
1331
+ this.listener = null;
1332
+ }
1333
+ this.value = value;
1334
+ // Add new listener
1335
+ if (value === null || value === undefined) {
1336
+ return;
1337
+ }
1338
+ if (typeof value === 'function') {
1339
+ // Auto-bind to host element (the custom element with shadow root)
1340
+ // This allows @click=${this.handleClick} to work without manual binding
1341
+ const rootNode = this.element.getRootNode();
1342
+ const host = rootNode.host;
1343
+ // Create a wrapper that calls the handler with the host as context
1344
+ // This ensures consistent function reference for proper cleanup
1345
+ if (host) {
1346
+ this.listener = ((event) => {
1347
+ // If keyboard filter is specified, check if event matches
1348
+ if (this.keyFilter && !matchesKeyboardFilter(event, this.keyFilter)) {
1349
+ return;
1350
+ }
1351
+ value.call(host, event);
1352
+ });
1353
+ }
1354
+ else {
1355
+ this.listener = ((event) => {
1356
+ if (this.keyFilter && !matchesKeyboardFilter(event, this.keyFilter)) {
1357
+ return;
1358
+ }
1359
+ value.call(null, event);
1360
+ });
1361
+ }
1362
+ this.element.addEventListener(this.eventName, this.listener);
1363
+ }
1364
+ }
1365
+ clear() {
1366
+ if (this.listener) {
1367
+ this.element.removeEventListener(this.eventName, this.listener);
1368
+ this.listener = null;
1369
+ }
1370
+ }
1371
+ }
1372
+ /**
1373
+ * Parse keyboard shortcut specification
1374
+ * Examples:
1375
+ * "enter" -> { key: "Enter" }
1376
+ * "ctrl+s" -> { key: "s", ctrl: true }
1377
+ * "ctrl+shift+s" -> { key: "s", ctrl: true, shift: true }
1378
+ * "~enter" -> { key: "Enter", anyModifiers: true }
1379
+ */
1380
+ function parseKeyboardFilter(spec) {
1381
+ // Handle ~ prefix for matching regardless of modifiers
1382
+ const anyModifiers = spec.startsWith('~');
1383
+ if (anyModifiers) {
1384
+ spec = spec.substring(1);
1385
+ }
1386
+ const parts = spec.split('+');
1387
+ const filter = {
1388
+ key: '',
1389
+ anyModifiers
1390
+ };
1391
+ for (const part of parts) {
1392
+ const lower = part.toLowerCase();
1393
+ if (lower === 'ctrl' || lower === 'control') {
1394
+ filter.ctrl = true;
1395
+ }
1396
+ else if (lower === 'alt') {
1397
+ filter.alt = true;
1398
+ }
1399
+ else if (lower === 'shift') {
1400
+ filter.shift = true;
1401
+ }
1402
+ else if (lower === 'meta' || lower === 'cmd' || lower === 'command') {
1403
+ filter.meta = true;
1404
+ }
1405
+ else {
1406
+ // This is the key itself - normalize common keys
1407
+ filter.key = normalizeKey(part);
1408
+ }
1409
+ }
1410
+ return filter;
1411
+ }
1412
+ /**
1413
+ * Normalize key names to match KeyboardEvent.key
1414
+ */
1415
+ function normalizeKey(key) {
1416
+ const keyMap = {
1417
+ 'esc': 'Escape',
1418
+ 'escape': 'Escape',
1419
+ 'enter': 'Enter',
1420
+ 'return': 'Enter',
1421
+ 'space': ' ',
1422
+ 'spacebar': ' ',
1423
+ 'up': 'ArrowUp',
1424
+ 'down': 'ArrowDown',
1425
+ 'left': 'ArrowLeft',
1426
+ 'right': 'ArrowRight',
1427
+ 'arrowup': 'ArrowUp',
1428
+ 'arrowdown': 'ArrowDown',
1429
+ 'arrowleft': 'ArrowLeft',
1430
+ 'arrowright': 'ArrowRight',
1431
+ 'delete': 'Delete',
1432
+ 'del': 'Delete',
1433
+ 'backspace': 'Backspace',
1434
+ 'tab': 'Tab',
1435
+ 'home': 'Home',
1436
+ 'end': 'End',
1437
+ 'pageup': 'PageUp',
1438
+ 'pagedown': 'PageDown'
1439
+ };
1440
+ const lower = key.toLowerCase();
1441
+ return keyMap[lower] || key;
1442
+ }
1443
+ /**
1444
+ * Check if keyboard event matches the filter
1445
+ */
1446
+ function matchesKeyboardFilter(event, filter) {
1447
+ // Check key match
1448
+ if (event.key !== filter.key) {
1449
+ return false;
1450
+ }
1451
+ // If anyModifiers is true, we don't care about modifiers
1452
+ if (filter.anyModifiers) {
1453
+ return true;
1454
+ }
1455
+ // Check modifiers - by default, exact match
1456
+ // If filter specifies ctrl: true, event must have ctrlKey
1457
+ // If filter doesn't specify ctrl, event must NOT have ctrlKey
1458
+ const ctrlMatch = filter.ctrl ? event.ctrlKey : !event.ctrlKey;
1459
+ const altMatch = filter.alt ? event.altKey : !event.altKey;
1460
+ const shiftMatch = filter.shift ? event.shiftKey : !event.shiftKey;
1461
+ const metaMatch = filter.meta ? event.metaKey : !event.metaKey;
1462
+ return ctrlMatch && altMatch && shiftMatch && metaMatch;
1463
+ }
1464
+ /**
1465
+ * IfPart handles <if> conditional rendering
1466
+ * Uses document fragments to actually remove/insert nodes from the DOM
1467
+ * instead of just hiding them with CSS
1468
+ */
1469
+ class IfPart extends Part {
1470
+ constructor(ifElement) {
1471
+ super();
1472
+ this.value = undefined;
1473
+ this.fragment = null;
1474
+ this.childNodes = [];
1475
+ this.ifElement = ifElement;
1476
+ // Set display to contents so the wrapper is transparent
1477
+ // display:contents makes the element invisible but renders its children
1478
+ this.ifElement.style.display = 'contents';
1479
+ // Store initial child nodes
1480
+ this.childNodes = Array.from(this.ifElement.childNodes);
1481
+ }
1482
+ commit(value) {
1483
+ const condition = Boolean(value);
1484
+ // If condition hasn't changed, do nothing
1485
+ if (this.value !== undefined && Boolean(this.value) === condition) {
1486
+ return;
1487
+ }
1488
+ this.value = value;
1489
+ if (condition) {
1490
+ // Show: restore children from fragment if they were removed
1491
+ if (this.fragment && this.fragment.hasChildNodes()) {
1492
+ this.ifElement.appendChild(this.fragment);
1493
+ this.fragment = null;
1494
+ }
1495
+ }
1496
+ else {
1497
+ // Hide: move children to document fragment
1498
+ this.fragment = document.createDocumentFragment();
1499
+ while (this.ifElement.firstChild) {
1500
+ this.fragment.appendChild(this.ifElement.firstChild);
1501
+ }
1502
+ }
1503
+ }
1504
+ clear() {
1505
+ // Move all children to fragment
1506
+ this.fragment = document.createDocumentFragment();
1507
+ while (this.ifElement.firstChild) {
1508
+ this.fragment.appendChild(this.ifElement.firstChild);
1509
+ }
1510
+ }
1511
+ }
1512
+ /**
1513
+ * CasePart handles <case>/<when>/<default> conditional rendering
1514
+ * Uses document fragments to remove/insert <when> and <default> children
1515
+ */
1516
+ class CasePart extends Part {
1517
+ constructor(caseElement) {
1518
+ super();
1519
+ this.value = undefined;
1520
+ this.fragments = new Map(); // Store removed children in fragments
1521
+ this.attachedChildren = new Map(); // Track which children are in DOM
1522
+ this.caseElement = caseElement;
1523
+ // Store children in original order
1524
+ this.childrenList = Array.from(this.caseElement.children);
1525
+ // Initialize all children as attached
1526
+ this.childrenList.forEach(child => {
1527
+ this.attachedChildren.set(child, true);
1528
+ // Create a fragment for each child to hold it when detached
1529
+ this.fragments.set(child, document.createDocumentFragment());
1530
+ });
1531
+ }
1532
+ commit(value) {
1533
+ // If value hasn't changed, do nothing
1534
+ if (this.value === value)
1535
+ return;
1536
+ this.value = value;
1537
+ // Find matching <when> or <default> and remove/insert appropriately
1538
+ let hasMatch = false;
1539
+ // First pass: check if any <when> matches
1540
+ for (const child of this.childrenList) {
1541
+ if (child.tagName.toLowerCase() === 'when') {
1542
+ const whenValue = child.getAttribute('value');
1543
+ if (whenValue === String(value)) {
1544
+ hasMatch = true;
1545
+ break;
1546
+ }
1547
+ }
1548
+ }
1549
+ // Second pass: remove/insert children based on match
1550
+ for (const child of this.childrenList) {
1551
+ const tagName = child.tagName.toLowerCase();
1552
+ const isAttached = this.attachedChildren.get(child) ?? true;
1553
+ let shouldBeAttached = false;
1554
+ if (tagName === 'when') {
1555
+ const whenValue = child.getAttribute('value');
1556
+ shouldBeAttached = (whenValue === String(value));
1557
+ }
1558
+ else if (tagName === 'default') {
1559
+ shouldBeAttached = !hasMatch;
1560
+ }
1561
+ // Update DOM if state changed
1562
+ if (shouldBeAttached && !isAttached) {
1563
+ // Re-insert from fragment in correct position
1564
+ // Find next sibling that is still attached
1565
+ const childIndex = this.childrenList.indexOf(child);
1566
+ let insertBefore = null;
1567
+ for (let i = childIndex + 1; i < this.childrenList.length; i++) {
1568
+ if (this.attachedChildren.get(this.childrenList[i])) {
1569
+ insertBefore = this.childrenList[i];
1570
+ break;
1571
+ }
1572
+ }
1573
+ // Get child from fragment
1574
+ const fragment = this.fragments.get(child);
1575
+ if (fragment && fragment.firstChild) {
1576
+ if (insertBefore) {
1577
+ this.caseElement.insertBefore(fragment.firstChild, insertBefore);
1578
+ }
1579
+ else {
1580
+ this.caseElement.appendChild(fragment.firstChild);
1581
+ }
1582
+ }
1583
+ this.attachedChildren.set(child, true);
1584
+ }
1585
+ else if (!shouldBeAttached && isAttached) {
1586
+ // Move to fragment
1587
+ const fragment = this.fragments.get(child);
1588
+ if (fragment) {
1589
+ fragment.appendChild(child);
1590
+ }
1591
+ this.attachedChildren.set(child, false);
1592
+ }
1593
+ }
1594
+ }
1595
+ clear() {
1596
+ // Move all children to fragments
1597
+ for (const child of this.childrenList) {
1598
+ if (this.attachedChildren.get(child)) {
1599
+ const fragment = this.fragments.get(child);
1600
+ if (fragment) {
1601
+ fragment.appendChild(child);
1602
+ }
1603
+ this.attachedChildren.set(child, false);
1604
+ }
1605
+ }
1606
+ }
1607
+ }
1608
+
1609
+ /**
1610
+ * @on decorator for listening to events
1611
+ * Use in elements or controllers to listen to DOM events or custom events
1612
+ */
1613
+ const ON_HANDLERS = getSymbol('on-handlers');
1614
+ /**
1615
+ * @on decorator for listening to events
1616
+ *
1617
+ * Works in both elements and controllers with full event delegation support.
1618
+ *
1619
+ * @param eventName - Event name(s) to listen for
1620
+ * @param selector - Optional CSS selector for event delegation
1621
+ * @param options - Event listener options including debounce/throttle
1622
+ *
1623
+ * @example
1624
+ * ```typescript
1625
+ * // In elements
1626
+ * @element('my-button')
1627
+ * class MyButton extends HTMLElement {
1628
+ * @on('click', 'button')
1629
+ * handleClick(e: MouseEvent) {
1630
+ * console.log('Button clicked!', e);
1631
+ * }
1632
+ *
1633
+ * @on('input', 'input', { debounce: 300 })
1634
+ * handleInput(e: Event) {
1635
+ * console.log('Input changed:', (e.target as HTMLInputElement).value);
1636
+ * }
1637
+ * }
1638
+ *
1639
+ * // In controllers
1640
+ * @controller('my-controller')
1641
+ * class MyController {
1642
+ * element!: HTMLElement;
1643
+ *
1644
+ * @on('count-changed')
1645
+ * handleCountChanged(e: CustomEvent) {
1646
+ * console.log('Count changed to:', e.detail.count);
1647
+ * }
1648
+ *
1649
+ * @on('click', '.item', { throttle: 100 })
1650
+ * handleItemClick(e: MouseEvent) {
1651
+ * console.log('Item clicked');
1652
+ * }
1653
+ * }
1654
+ * ```
1655
+ */
1656
+ function on(eventName, selectorOrOptions, options) {
1657
+ // Parse arguments to support multiple call signatures
1658
+ let selector = null;
1659
+ let opts = {};
1660
+ if (typeof selectorOrOptions === 'string') {
1661
+ // With selector: (eventName, selector, options)
1662
+ selector = selectorOrOptions;
1663
+ opts = options || {};
1664
+ }
1665
+ else if (selectorOrOptions === null && options) {
1666
+ // With null selector: (eventName, null, options)
1667
+ opts = options;
1668
+ }
1669
+ else if (selectorOrOptions && typeof selectorOrOptions === 'object') {
1670
+ // Without selector: (eventName, options)
1671
+ opts = selectorOrOptions;
1672
+ }
1673
+ return function (originalMethod, context) {
1674
+ const methodName = context.name;
1675
+ const initKey = `__on_init_${methodName}_${selector || ''}_${JSON.stringify(eventName)}`;
1676
+ context.addInitializer(function () {
1677
+ const constructor = this.constructor;
1678
+ // Only initialize once per class, not per instance
1679
+ if (constructor[initKey])
1680
+ return;
1681
+ constructor[initKey] = true;
1682
+ if (!constructor[ON_HANDLERS]) {
1683
+ constructor[ON_HANDLERS] = [];
1684
+ }
1685
+ const eventNames = Array.isArray(eventName) ? eventName : [eventName];
1686
+ for (const event of eventNames) {
1687
+ constructor[ON_HANDLERS].push({
1688
+ eventName: event,
1689
+ selector,
1690
+ methodName,
1691
+ method: originalMethod,
1692
+ options: opts
1693
+ });
1694
+ }
1695
+ });
1696
+ return originalMethod;
1697
+ };
1698
+ }
1699
+ /**
1700
+ * Create a debounced version of a function
1701
+ */
1702
+ function debounce$1(fn, delay) {
1703
+ let timeoutId = null;
1704
+ return function (...args) {
1705
+ if (timeoutId !== null) {
1706
+ clearTimeout(timeoutId);
1707
+ }
1708
+ timeoutId = setTimeout(() => {
1709
+ fn.apply(this, args);
1710
+ timeoutId = null;
1711
+ }, delay);
1712
+ };
1713
+ }
1714
+ /**
1715
+ * Create a throttled version of a function (leading edge only)
1716
+ */
1717
+ function throttle$1(fn, delay) {
1718
+ let lastCall = 0;
1719
+ return function (...args) {
1720
+ const now = Date.now();
1721
+ const timeSinceLastCall = now - lastCall;
1722
+ if (timeSinceLastCall >= delay) {
1723
+ lastCall = now;
1724
+ fn.apply(this, args);
1725
+ }
1726
+ // Events within the throttle window are simply ignored (leading edge only)
1727
+ };
1728
+ }
1729
+ /**
1730
+ * Events that don't bubble - these require capture phase for delegation
1731
+ */
1732
+ const NON_BUBBLING_EVENTS = new Set([
1733
+ 'scroll',
1734
+ 'focus',
1735
+ 'blur',
1736
+ 'load',
1737
+ 'unload',
1738
+ 'error',
1739
+ 'resize',
1740
+ 'abort',
1741
+ 'mouseenter',
1742
+ 'mouseleave',
1743
+ 'pointerenter',
1744
+ 'pointerleave',
1745
+ ]);
1746
+ /**
1747
+ * Setup event listeners for an element or controller instance
1748
+ * Called automatically during element connection or controller attachment
1749
+ */
1750
+ function setupEventHandlers(instance, targetElement) {
1751
+ const handlers = instance.constructor[ON_HANDLERS];
1752
+ if (!handlers || !Array.isArray(handlers) || handlers.length === 0) {
1753
+ return;
1754
+ }
1755
+ // Initialize cleanup object if needed
1756
+ if (!instance[CLEANUP]) {
1757
+ instance[CLEANUP] = { events: [], channels: [], observers: [] };
1758
+ }
1759
+ else if (!instance[CLEANUP].events) {
1760
+ instance[CLEANUP].events = [];
1761
+ }
1762
+ else if (instance[CLEANUP].events.length > 0) {
1763
+ // Events already set up - clean them up first to avoid duplicates
1764
+ cleanupEventHandlers(instance);
1765
+ }
1766
+ for (const handler of handlers) {
1767
+ // Get current method from instance (preserves decorator stacking)
1768
+ const currentMethod = instance[handler.methodName];
1769
+ let boundMethod = currentMethod ? currentMethod.bind(instance) : handler.method.bind(instance);
1770
+ const handlerOptions = handler.options || {};
1771
+ // Parse event name for key modifiers
1772
+ // Supports both dot notation (@keydown.enter) and colon notation (@keydown:Enter)
1773
+ const dotIndex = handler.eventName.indexOf('.');
1774
+ const colonIndex = handler.eventName.indexOf(':');
1775
+ const delimiterIndex = dotIndex > 0 && colonIndex > 0
1776
+ ? Math.min(dotIndex, colonIndex)
1777
+ : Math.max(dotIndex, colonIndex);
1778
+ const baseEventName = delimiterIndex > 0
1779
+ ? handler.eventName.substring(0, delimiterIndex)
1780
+ : handler.eventName;
1781
+ const keyModifier = delimiterIndex > 0
1782
+ ? handler.eventName.substring(delimiterIndex + 1)
1783
+ : null;
1784
+ // Apply debounce if specified
1785
+ if (handlerOptions.debounce && handlerOptions.debounce > 0) {
1786
+ boundMethod = debounce$1(boundMethod, handlerOptions.debounce);
1787
+ }
1788
+ // Apply throttle if specified (debounce takes precedence)
1789
+ else if (handlerOptions.throttle && handlerOptions.throttle > 0) {
1790
+ boundMethod = throttle$1(boundMethod, handlerOptions.throttle);
1791
+ }
1792
+ // Create event handler with key modifier support
1793
+ // Uses shared keyboard filter implementation from parts.ts
1794
+ let keyFilter = null;
1795
+ if (keyModifier && ['keydown', 'keyup', 'keypress'].includes(baseEventName)) {
1796
+ keyFilter = parseKeyboardFilter(keyModifier);
1797
+ }
1798
+ const createKeyModifierHandler = (method) => {
1799
+ if (!keyFilter) {
1800
+ return method;
1801
+ }
1802
+ return (event) => {
1803
+ const keyEvent = event;
1804
+ if (matchesKeyboardFilter(keyEvent, keyFilter)) {
1805
+ method(event);
1806
+ }
1807
+ };
1808
+ };
1809
+ // Apply key modifier wrapper
1810
+ const keyModifierMethod = createKeyModifierHandler(boundMethod);
1811
+ // Main event handler with error handling and event delegation
1812
+ if (handler.selector) {
1813
+ // Delegated event handling - use shadow root if available
1814
+ const eventRoot = targetElement.shadowRoot || targetElement;
1815
+ const delegatedHandler = (event) => {
1816
+ const target = event.target;
1817
+ let matchingElement = null;
1818
+ // Check if target itself matches the selector
1819
+ if (target.matches && target.matches(handler.selector)) {
1820
+ matchingElement = target;
1821
+ }
1822
+ // Check if any parent matches the selector (event delegation)
1823
+ else if (target.closest) {
1824
+ matchingElement = target.closest(handler.selector);
1825
+ }
1826
+ // Only handle if we found a match
1827
+ // Note: No need to check contains() since the event bubbled to eventRoot
1828
+ if (matchingElement) {
1829
+ // Apply automatic preventDefault/stopPropagation
1830
+ if (handlerOptions.preventDefault) {
1831
+ event.preventDefault();
1832
+ }
1833
+ if (handlerOptions.stopPropagation) {
1834
+ event.stopPropagation();
1835
+ event.stopImmediatePropagation();
1836
+ }
1837
+ try {
1838
+ keyModifierMethod(event);
1839
+ }
1840
+ catch (error) {
1841
+ console.error(`Error in event handler ${handler.methodName}:`, error);
1842
+ }
1843
+ }
1844
+ };
1845
+ // Auto-enable capture for non-bubbling events when using delegation
1846
+ const needsCapture = NON_BUBBLING_EVENTS.has(baseEventName);
1847
+ const useCapture = handlerOptions.capture !== undefined
1848
+ ? handlerOptions.capture
1849
+ : needsCapture;
1850
+ const listenerOptions = {
1851
+ capture: useCapture,
1852
+ once: handlerOptions.once || false,
1853
+ passive: handlerOptions.passive || false,
1854
+ };
1855
+ eventRoot.addEventListener(baseEventName, delegatedHandler, listenerOptions);
1856
+ instance[CLEANUP].events.push({
1857
+ target: eventRoot,
1858
+ eventName: baseEventName,
1859
+ handler: delegatedHandler,
1860
+ options: listenerOptions,
1861
+ });
1862
+ }
1863
+ else {
1864
+ // Direct event handling - on the element itself
1865
+ // If element has shadow root, listen on both shadow root AND host element
1866
+ // to catch events from inside shadow DOM (with correct target) and on host itself
1867
+ const shadowRoot = targetElement.shadowRoot;
1868
+ const handledSymbol = Symbol('snice-event-handled');
1869
+ const wrappedMethod = (event) => {
1870
+ // Prevent double-triggering when listening on both shadow root and host
1871
+ if (event[handledSymbol]) {
1872
+ return;
1873
+ }
1874
+ event[handledSymbol] = true;
1875
+ try {
1876
+ // Apply automatic preventDefault/stopPropagation
1877
+ if (handlerOptions.preventDefault) {
1878
+ event.preventDefault();
1879
+ }
1880
+ if (handlerOptions.stopPropagation) {
1881
+ event.stopPropagation();
1882
+ }
1883
+ keyModifierMethod(event);
1884
+ }
1885
+ catch (error) {
1886
+ console.error(`Error in event handler ${handler.methodName}:`, error);
1887
+ }
1888
+ };
1889
+ const listenerOptions = {
1890
+ capture: handlerOptions.capture || false,
1891
+ once: handlerOptions.once || false,
1892
+ passive: handlerOptions.passive || false,
1893
+ };
1894
+ if (shadowRoot) {
1895
+ // Listen on shadow root for events inside shadow DOM
1896
+ shadowRoot.addEventListener(baseEventName, wrappedMethod, listenerOptions);
1897
+ instance[CLEANUP].events.push({
1898
+ target: shadowRoot,
1899
+ eventName: baseEventName,
1900
+ handler: wrappedMethod,
1901
+ options: listenerOptions,
1902
+ });
1903
+ }
1904
+ // Also listen on host element (for clicks on host itself or when no shadow root)
1905
+ targetElement.addEventListener(baseEventName, wrappedMethod, listenerOptions);
1906
+ instance[CLEANUP].events.push({
1907
+ target: targetElement,
1908
+ eventName: baseEventName,
1909
+ handler: wrappedMethod,
1910
+ options: listenerOptions,
1911
+ });
1912
+ }
1913
+ }
1914
+ }
1915
+ /**
1916
+ * Cleanup event listeners for a controller instance
1917
+ * Called automatically by the controller system during detach
1918
+ */
1919
+ function cleanupEventHandlers(instance) {
1920
+ if (!instance[CLEANUP]?.events)
1921
+ return;
1922
+ for (const { target, eventName, handler, options } of instance[CLEANUP].events) {
1923
+ target.removeEventListener(eventName, handler, options);
1924
+ }
1925
+ instance[CLEANUP].events = [];
1926
+ }
1927
+
1928
+ // Controller-scoped cleanup registry
1929
+ class ControllerScope {
1930
+ constructor() {
1931
+ this.cleanupFns = new Map();
1932
+ this.pendingOperations = new Set();
1933
+ }
1934
+ register(key, cleanup) {
1935
+ this.cleanupFns.set(key, cleanup);
1936
+ }
1937
+ unregister(key) {
1938
+ this.cleanupFns.delete(key);
1939
+ }
1940
+ async cleanup() {
1941
+ // Wait for all pending operations
1942
+ await Promise.all(this.pendingOperations);
1943
+ // Run all cleanup functions
1944
+ for (const cleanup of this.cleanupFns.values()) {
1945
+ try {
1946
+ await cleanup();
1947
+ }
1948
+ catch (error) {
1949
+ console.error('Error during cleanup:', error);
1950
+ }
1951
+ }
1952
+ this.cleanupFns.clear();
1953
+ }
1954
+ async runOperation(operation) {
1955
+ const promise = operation();
1956
+ const voidPromise = promise.then(() => { }, () => { });
1957
+ this.pendingOperations.add(voidPromise);
1958
+ try {
1959
+ const result = await promise;
1960
+ this.pendingOperations.delete(voidPromise);
1961
+ return result;
1962
+ }
1963
+ catch (error) {
1964
+ this.pendingOperations.delete(voidPromise);
1965
+ throw error;
1966
+ }
1967
+ }
1968
+ }
1969
+ /**
1970
+ * Decorator to register a controller class with a name
1971
+ * @param name The name to register the controller under
1972
+ */
1973
+ function controller(name) {
1974
+ return function (constructor, _context) {
1975
+ snice.controllerRegistry.set(name, constructor);
1976
+ // Mark as controller class for channel decorator detection
1977
+ constructor.prototype[IS_CONTROLLER_CLASS] = true;
1978
+ return constructor;
1979
+ };
1980
+ }
1981
+ /**
1982
+ * Attaches a controller to an element
1983
+ * @param element The element to attach the controller to
1984
+ * @param controllerName The name of the controller to attach
1985
+ */
1986
+ async function attachController(element, controllerName) {
1987
+ const existingController = element[CONTROLLER_KEY];
1988
+ const existingName = element[CONTROLLER_NAME_KEY];
1989
+ // For native elements, check if this is actually the desired controller
1990
+ const nativeController = element[NATIVE_CONTROLLER];
1991
+ if (nativeController !== undefined && nativeController !== controllerName) {
1992
+ // This attachment is outdated, skip it
1042
1993
  return;
1043
1994
  }
1044
1995
  if (existingName === controllerName && existingController) {
@@ -1077,12 +2028,12 @@ async function attachController(element, controllerName) {
1077
2028
  await scope.runOperation(async () => {
1078
2029
  await controllerInstance.attach(element);
1079
2030
  });
1080
- // Setup @on event handlers for controller
1081
- setupEventHandlers(controllerInstance, element);
1082
2031
  // Setup @observe observers for controller
1083
2032
  setupObservers(controllerInstance, element);
1084
2033
  // Setup @channel handlers for controller
1085
2034
  setupResponseHandlers(controllerInstance, element);
2035
+ // Setup @on event handlers for controller
2036
+ setupEventHandlers(controllerInstance, element);
1086
2037
  element.dispatchEvent(new CustomEvent('@snice/controller-attached', {
1087
2038
  detail: { name: controllerName, controller: controllerInstance }
1088
2039
  }));
@@ -1108,12 +2059,12 @@ async function detachController(element) {
1108
2059
  await controllerInstance.detach(element);
1109
2060
  }
1110
2061
  controllerInstance.element = null;
1111
- // Cleanup @on event handlers for controller
1112
- cleanupEventHandlers(controllerInstance);
1113
2062
  // Cleanup @observe observers for controller
1114
2063
  cleanupObservers(controllerInstance);
1115
2064
  // Cleanup @channel handlers for controller
1116
2065
  cleanupResponseHandlers(controllerInstance);
2066
+ // Cleanup @on event handlers for controller
2067
+ cleanupEventHandlers(controllerInstance);
1117
2068
  // Cleanup the controller scope
1118
2069
  if (scope) {
1119
2070
  await scope.cleanup();
@@ -1196,33 +2147,168 @@ function useNativeElementControllers() {
1196
2147
  });
1197
2148
  }
1198
2149
  }
1199
- });
1200
- // Start observing when DOM is ready
1201
- if (document.readyState === 'loading') {
1202
- document.addEventListener('DOMContentLoaded', () => {
1203
- // Process existing elements (excluding custom elements)
1204
- document.querySelectorAll('[controller]:not([class*="-"])').forEach(processElement);
1205
- // Start observing
1206
- observer.observe(document.body, {
1207
- attributes: true,
1208
- attributeFilter: ['controller'],
1209
- childList: true,
1210
- subtree: true
1211
- });
1212
- });
2150
+ });
2151
+ // Start observing when DOM is ready
2152
+ if (document.readyState === 'loading') {
2153
+ document.addEventListener('DOMContentLoaded', () => {
2154
+ // Process existing elements (excluding custom elements)
2155
+ document.querySelectorAll('[controller]:not([class*="-"])').forEach(processElement);
2156
+ // Start observing
2157
+ observer.observe(document.body, {
2158
+ attributes: true,
2159
+ attributeFilter: ['controller'],
2160
+ childList: true,
2161
+ subtree: true
2162
+ });
2163
+ });
2164
+ }
2165
+ else {
2166
+ // DOM already loaded
2167
+ document.querySelectorAll('[controller]:not([class*="-"])').forEach(processElement);
2168
+ observer.observe(document.body, {
2169
+ attributes: true,
2170
+ attributeFilter: ['controller'],
2171
+ childList: true,
2172
+ subtree: true
2173
+ });
2174
+ }
2175
+ // Store observer reference for cleanup if needed
2176
+ globalThis.sniceNativeControllerObserver = observer;
2177
+ }
2178
+
2179
+ /**
2180
+ * @context decorator for receiving router context updates
2181
+ */
2182
+ const CONTEXT_HANDLERS = getSymbol('context-handlers');
2183
+ /**
2184
+ * @context decorator for receiving router context updates
2185
+ *
2186
+ * @example
2187
+ * ```typescript
2188
+ * @element('my-layout')
2189
+ * class MyLayout extends HTMLElement {
2190
+ * @context
2191
+ * handleContext(ctx: Context) {
2192
+ * this.renderNav(ctx.placards, ctx.currentRoute);
2193
+ * }
2194
+ *
2195
+ * @context({ debounce: 300 })
2196
+ * handleContextDebounced(ctx: Context) {
2197
+ * // Called after 300ms of no updates
2198
+ * }
2199
+ * }
2200
+ * ```
2201
+ */
2202
+ function context$1(options = {}) {
2203
+ return function (originalMethod, context) {
2204
+ const methodName = context.name;
2205
+ const initKey = `__context_init_${methodName}`;
2206
+ context.addInitializer(function () {
2207
+ const constructor = this.constructor;
2208
+ if (constructor[initKey])
2209
+ return;
2210
+ constructor[initKey] = true;
2211
+ if (!constructor[CONTEXT_HANDLERS]) {
2212
+ constructor[CONTEXT_HANDLERS] = [];
2213
+ }
2214
+ constructor[CONTEXT_HANDLERS].push({
2215
+ methodName,
2216
+ method: originalMethod,
2217
+ options,
2218
+ });
2219
+ });
2220
+ return originalMethod;
2221
+ };
2222
+ }
2223
+ /**
2224
+ * Setup context handler for an element instance
2225
+ * Called automatically during element connection
2226
+ */
2227
+ function setupContextHandler(element) {
2228
+ const handlers = element.constructor[CONTEXT_HANDLERS];
2229
+ if (!handlers || !Array.isArray(handlers) || handlers.length === 0) {
2230
+ return;
2231
+ }
2232
+ // Get the Context instance from the router
2233
+ const ctx = element[CONTEXT_HANDLER];
2234
+ if (!ctx) {
2235
+ return;
2236
+ }
2237
+ // Store the Context instance for cleanup
2238
+ element[NAVIGATION_CONTEXT_INSTANCE] = ctx;
2239
+ // Register each handler with the Context
2240
+ for (const handler of handlers) {
2241
+ const { methodName, method, options } = handler;
2242
+ const wrappedMethodName = `__wrapped_${methodName}`;
2243
+ // Create wrapped method with timing controls
2244
+ element[wrappedMethodName] = function (context) {
2245
+ // Skip if already called once
2246
+ if (options.once && element[CONTEXT_CALLED]) {
2247
+ return;
2248
+ }
2249
+ const callMethod = () => {
2250
+ method.call(element, context);
2251
+ // Handle once option
2252
+ if (options.once) {
2253
+ element[CONTEXT_CALLED] = true;
2254
+ // Unregister after first call
2255
+ const ctx = element[NAVIGATION_CONTEXT_INSTANCE];
2256
+ if (ctx && typeof ctx[CONTEXT_UNREGISTER] === 'function') {
2257
+ ctx[CONTEXT_UNREGISTER](element);
2258
+ }
2259
+ }
2260
+ };
2261
+ // Handle debounce
2262
+ if (options.debounce) {
2263
+ clearTimeout(element[CONTEXT_TIMER]);
2264
+ element[CONTEXT_TIMER] = setTimeout(callMethod, options.debounce);
2265
+ }
2266
+ // Handle throttle
2267
+ else if (options.throttle) {
2268
+ const now = Date.now();
2269
+ const lastCall = element[CONTEXT_TIMER] || 0;
2270
+ if (now - lastCall >= options.throttle) {
2271
+ element[CONTEXT_TIMER] = now;
2272
+ callMethod();
2273
+ }
2274
+ }
2275
+ // No timing options - call immediately
2276
+ else {
2277
+ callMethod();
2278
+ }
2279
+ };
2280
+ // Register with the Context using the wrapped method name
2281
+ if (typeof ctx[CONTEXT_REGISTER] === 'function') {
2282
+ ctx[CONTEXT_REGISTER](element, wrappedMethodName);
2283
+ }
2284
+ }
2285
+ }
2286
+ /**
2287
+ * Cleanup context handler for an element instance
2288
+ * Called automatically during element disconnection
2289
+ */
2290
+ function cleanupContextHandler(element) {
2291
+ const handlers = element.constructor[CONTEXT_HANDLERS];
2292
+ if (!handlers || !Array.isArray(handlers) || handlers.length === 0) {
2293
+ return;
2294
+ }
2295
+ // Clear any pending debounce timer
2296
+ for (const handler of handlers) {
2297
+ if (handler.options.debounce && element[CONTEXT_TIMER]) {
2298
+ clearTimeout(element[CONTEXT_TIMER]);
2299
+ delete element[CONTEXT_TIMER];
2300
+ }
2301
+ // Clean up wrapped method
2302
+ const wrappedMethodName = `__wrapped_${handler.methodName}`;
2303
+ delete element[wrappedMethodName];
1213
2304
  }
1214
- else {
1215
- // DOM already loaded
1216
- document.querySelectorAll('[controller]:not([class*="-"])').forEach(processElement);
1217
- observer.observe(document.body, {
1218
- attributes: true,
1219
- attributeFilter: ['controller'],
1220
- childList: true,
1221
- subtree: true
1222
- });
2305
+ // Unregister from Context if available
2306
+ const ctx = element[NAVIGATION_CONTEXT_INSTANCE];
2307
+ if (ctx && typeof ctx[CONTEXT_UNREGISTER] === 'function') {
2308
+ ctx[CONTEXT_UNREGISTER](element);
1223
2309
  }
1224
- // Store observer reference for cleanup if needed
1225
- globalThis.sniceNativeControllerObserver = observer;
2310
+ delete element[NAVIGATION_CONTEXT_INSTANCE];
2311
+ delete element[CONTEXT_CALLED];
1226
2312
  }
1227
2313
 
1228
2314
  /**
@@ -1283,6 +2369,87 @@ class SimpleArray {
1283
2369
  }
1284
2370
  }
1285
2371
 
2372
+ var _a, _b, _c;
2373
+ // Symbol for storing the Set of elements
2374
+ const REGISTERED_ELEMENTS_SET = Symbol('registered-elements-set');
2375
+ // Counter for generating unique context IDs
2376
+ let contextIdCounter = 0;
2377
+ /**
2378
+ * Represents the bundled router state that can notify registered elements of changes
2379
+ */
2380
+ class Context {
2381
+ constructor(context = {}, placards = [], currentRoute = '', routeParams = {}) {
2382
+ this[_a] = new WeakMap();
2383
+ this[_b] = new Set();
2384
+ this[_c] = false;
2385
+ this.id = contextIdCounter++;
2386
+ this.application = context;
2387
+ this.navigation = {
2388
+ placards,
2389
+ route: currentRoute,
2390
+ params: routeParams
2391
+ };
2392
+ }
2393
+ /**
2394
+ * Register an element to receive context updates
2395
+ * @internal Used by @context decorator
2396
+ */
2397
+ [(_a = REGISTERED_ELEMENTS, _b = REGISTERED_ELEMENTS_SET, _c = IS_UPDATING, CONTEXT_REGISTER)](element, methodName) {
2398
+ this[REGISTERED_ELEMENTS].set(element, methodName);
2399
+ this[REGISTERED_ELEMENTS_SET].add(element);
2400
+ }
2401
+ /**
2402
+ * Unregister an element from receiving context updates
2403
+ * @internal Used by @context decorator cleanup
2404
+ */
2405
+ [CONTEXT_UNREGISTER](element) {
2406
+ this[REGISTERED_ELEMENTS].delete(element);
2407
+ this[REGISTERED_ELEMENTS_SET].delete(element);
2408
+ }
2409
+ /**
2410
+ * Update the context and notify all registered elements
2411
+ * Prevents infinite loops by tracking update state
2412
+ */
2413
+ update(context, placards, currentRoute, routeParams) {
2414
+ // Prevent infinite loops
2415
+ if (this[IS_UPDATING]) {
2416
+ return;
2417
+ }
2418
+ this[IS_UPDATING] = true;
2419
+ // Update properties (id remains immutable)
2420
+ this.application = context;
2421
+ this.navigation.placards = placards;
2422
+ this.navigation.route = currentRoute;
2423
+ this.navigation.params = routeParams;
2424
+ // Notify all registered elements by calling their methods directly
2425
+ const elementsSet = this[REGISTERED_ELEMENTS_SET];
2426
+ const elementsMap = this[REGISTERED_ELEMENTS];
2427
+ for (const element of elementsSet) {
2428
+ const methodName = elementsMap.get(element);
2429
+ if (methodName && typeof element[methodName] === 'function') {
2430
+ try {
2431
+ element[methodName](this);
2432
+ }
2433
+ catch (error) {
2434
+ // Log error but continue notifying other elements
2435
+ console.error(`Error calling @context method ${methodName}:`, error);
2436
+ }
2437
+ }
2438
+ }
2439
+ this[IS_UPDATING] = false;
2440
+ }
2441
+ /**
2442
+ * Notify a specific element of the current context state
2443
+ * @internal Used by @context decorator
2444
+ */
2445
+ [CONTEXT_NOTIFY_ELEMENT](element) {
2446
+ const methodName = this[REGISTERED_ELEMENTS].get(element);
2447
+ if (methodName && typeof element[methodName] === 'function') {
2448
+ element[methodName](this);
2449
+ }
2450
+ }
2451
+ }
2452
+
1286
2453
  /**
1287
2454
  * Detects the type constructor from an initial value
1288
2455
  * @param initialValue - The default value assigned to a property field (e.g., `name = "default"` -> "default")
@@ -1411,6 +2578,297 @@ function valueToAttribute(value, propertyOptions, initialValue) {
1411
2578
  }
1412
2579
  }
1413
2580
 
2581
+ /**
2582
+ * @render and @styles decorators for Snice v3.0.0
2583
+ * Provides automatic differential rendering on property changes
2584
+ */
2585
+ /**
2586
+ * Global render scheduler for microtask batching
2587
+ * Batches multiple property changes into a single render
2588
+ */
2589
+ class RenderScheduler {
2590
+ constructor() {
2591
+ this.pending = new Set();
2592
+ this.scheduled = false;
2593
+ }
2594
+ /**
2595
+ * Schedule an element for rendering
2596
+ * Batches renders in a microtask unless sync option is enabled
2597
+ */
2598
+ schedule(element, options) {
2599
+ // Sync rendering - execute immediately
2600
+ if (options.sync) {
2601
+ performRender(element, options);
2602
+ return;
2603
+ }
2604
+ // Async rendering - batch in microtask
2605
+ this.pending.add(element);
2606
+ if (!this.scheduled) {
2607
+ this.scheduled = true;
2608
+ queueMicrotask(() => this.flush());
2609
+ }
2610
+ }
2611
+ /**
2612
+ * Flush all pending renders
2613
+ */
2614
+ flush() {
2615
+ const elements = Array.from(this.pending);
2616
+ this.pending.clear();
2617
+ this.scheduled = false;
2618
+ for (const element of elements) {
2619
+ const options = element[RENDER_OPTIONS] || {};
2620
+ performRender(element, options);
2621
+ }
2622
+ }
2623
+ }
2624
+ const renderScheduler = new RenderScheduler();
2625
+ /**
2626
+ * Perform the actual render of an element
2627
+ */
2628
+ function performRender(element, options, precomputedResult) {
2629
+ const renderMethod = element[RENDER_METHOD];
2630
+ if (!renderMethod)
2631
+ return;
2632
+ // If once is true and we've already rendered, skip
2633
+ if (options.once && element[RENDER_INSTANCE]) {
2634
+ return;
2635
+ }
2636
+ try {
2637
+ // Use precomputed result if provided, otherwise call the render method
2638
+ const result = precomputedResult !== undefined ? precomputedResult : renderMethod.call(element);
2639
+ // Check if differential rendering is disabled (expects string)
2640
+ const differential = options.differential !== false;
2641
+ if (!differential) {
2642
+ // Non-differential expects string
2643
+ if (typeof result !== 'string') {
2644
+ console.warn('Render method with differential: false must return a string');
2645
+ return;
2646
+ }
2647
+ // Simple string rendering
2648
+ if (!element.shadowRoot) {
2649
+ element.attachShadow({ mode: 'open' });
2650
+ }
2651
+ element.shadowRoot.innerHTML = result;
2652
+ // Mark scheduled flag as false
2653
+ element[RENDER_SCHEDULED] = false;
2654
+ // Call all registered render callbacks
2655
+ const callbacks = element[RENDER_CALLBACKS];
2656
+ if (callbacks && callbacks.length > 0) {
2657
+ const cbs = [...callbacks];
2658
+ element[RENDER_CALLBACKS] = [];
2659
+ cbs.forEach(cb => cb());
2660
+ }
2661
+ return;
2662
+ }
2663
+ if (!isTemplateResult(result)) {
2664
+ console.warn('Render method must return html`` template result');
2665
+ return;
2666
+ }
2667
+ // Get or create template instance (differential rendering)
2668
+ let instance = element[RENDER_INSTANCE];
2669
+ if (!instance) {
2670
+ // First render - create shadow root if needed and initial instance
2671
+ if (!element.shadowRoot) {
2672
+ element.attachShadow({ mode: 'open' });
2673
+ }
2674
+ instance = new TemplateInstance(result);
2675
+ element[RENDER_INSTANCE] = instance;
2676
+ // Create the fragment but don't commit values yet
2677
+ const fragment = instance.renderFragment();
2678
+ // Append to shadow root first so getRootNode() works in event handlers
2679
+ element.shadowRoot.appendChild(fragment);
2680
+ // Now commit values (this binds event handlers with correct host)
2681
+ instance.update(result.values);
2682
+ }
2683
+ else {
2684
+ // Subsequent render - just update the parts (differential rendering!)
2685
+ instance.update(result.values);
2686
+ }
2687
+ // Mark scheduled flag as false
2688
+ element[RENDER_SCHEDULED] = false;
2689
+ // Call all registered render callbacks (for testing/debugging)
2690
+ const callbacks = element[RENDER_CALLBACKS];
2691
+ if (callbacks && callbacks.length > 0) {
2692
+ const cbs = [...callbacks];
2693
+ element[RENDER_CALLBACKS] = [];
2694
+ cbs.forEach(cb => cb());
2695
+ }
2696
+ }
2697
+ catch (error) {
2698
+ console.error('Error rendering element:', error);
2699
+ }
2700
+ }
2701
+ /**
2702
+ * Request a render for an element
2703
+ * Respects debounce/throttle/once/sync options
2704
+ * @param immediate - Force immediate render (used for initial render)
2705
+ */
2706
+ function requestRender(element, immediate = false) {
2707
+ const options = element[RENDER_OPTIONS] || {};
2708
+ // Handle once option
2709
+ if (options.once && element[RENDER_INSTANCE]) {
2710
+ return;
2711
+ }
2712
+ // Force immediate render (for initial render)
2713
+ if (immediate) {
2714
+ performRender(element, options);
2715
+ return;
2716
+ }
2717
+ // Handle debounce
2718
+ if (options.debounce !== undefined && options.debounce > 0) {
2719
+ if (!element[RENDER_TIMERS]) {
2720
+ element[RENDER_TIMERS] = {};
2721
+ }
2722
+ clearTimeout(element[RENDER_TIMERS].debounce);
2723
+ element[RENDER_TIMERS].debounce = setTimeout(() => {
2724
+ renderScheduler.schedule(element, options);
2725
+ }, options.debounce);
2726
+ return;
2727
+ }
2728
+ // Handle throttle
2729
+ if (options.throttle !== undefined && options.throttle > 0) {
2730
+ if (!element[RENDER_TIMERS]) {
2731
+ element[RENDER_TIMERS] = { lastThrottle: 0 };
2732
+ }
2733
+ const timers = element[RENDER_TIMERS];
2734
+ const now = Date.now();
2735
+ if (timers.lastThrottle === 0 || now - timers.lastThrottle >= options.throttle) {
2736
+ timers.lastThrottle = now;
2737
+ renderScheduler.schedule(element, options);
2738
+ }
2739
+ else {
2740
+ // Schedule for later if not already scheduled
2741
+ if (!timers.throttleTimer) {
2742
+ const remaining = options.throttle - (now - timers.lastThrottle);
2743
+ timers.throttleTimer = setTimeout(() => {
2744
+ timers.throttleTimer = null;
2745
+ timers.lastThrottle = Date.now();
2746
+ renderScheduler.schedule(element, options);
2747
+ }, remaining);
2748
+ }
2749
+ }
2750
+ return;
2751
+ }
2752
+ // Normal rendering (with microtask batching unless sync)
2753
+ renderScheduler.schedule(element, options);
2754
+ }
2755
+ /**
2756
+ * @render decorator for component rendering
2757
+ *
2758
+ * Marks a method as the render method for the component.
2759
+ * The method should return html`...` template.
2760
+ * Automatically re-renders when properties change (unless once: true).
2761
+ *
2762
+ * @example
2763
+ * ```typescript
2764
+ * @render()
2765
+ * renderContent() {
2766
+ * return html`<div>${this.count}</div>`;
2767
+ * }
2768
+ * ```
2769
+ *
2770
+ * @example
2771
+ * ```typescript
2772
+ * // Debounced rendering
2773
+ * @render({ debounce: 100 })
2774
+ * renderContent() {
2775
+ * return html`<div>${this.searchTerm}</div>`;
2776
+ * }
2777
+ * ```
2778
+ *
2779
+ * @example
2780
+ * ```typescript
2781
+ * // Render only once (manual re-renders only)
2782
+ * @render({ once: true })
2783
+ * renderContent() {
2784
+ * return html`<div>Static content</div>`;
2785
+ * }
2786
+ * ```
2787
+ */
2788
+ function render(options = {}) {
2789
+ return function (originalMethod, context) {
2790
+ context.name;
2791
+ context.addInitializer(function () {
2792
+ // Store the render method and options
2793
+ this[RENDER_METHOD] = originalMethod;
2794
+ this[RENDER_OPTIONS] = options;
2795
+ });
2796
+ // Return wrapped method that triggers re-render when called manually
2797
+ return function (...args) {
2798
+ // Call original method to get the template
2799
+ const result = originalMethod.apply(this, args);
2800
+ // Always render when method is called manually (even if once: true)
2801
+ // Force immediate render to bypass all options, pass precomputed result to avoid calling method twice
2802
+ performRender(this, {}, result);
2803
+ return result;
2804
+ };
2805
+ };
2806
+ }
2807
+ /**
2808
+ * @styles decorator for component styles
2809
+ *
2810
+ * Marks a method as the styles method for the component.
2811
+ * The method should return css`...` template.
2812
+ * Styles are applied once when the component is connected.
2813
+ *
2814
+ * @example
2815
+ * ```typescript
2816
+ * @styles()
2817
+ * styles() {
2818
+ * return css`:host { display: block; }`;
2819
+ * }
2820
+ * ```
2821
+ */
2822
+ function styles() {
2823
+ return function (originalMethod, context) {
2824
+ context.addInitializer(function () {
2825
+ // Store the styles method
2826
+ this[STYLES_METHOD] = originalMethod;
2827
+ });
2828
+ return originalMethod;
2829
+ };
2830
+ }
2831
+ /**
2832
+ * Apply styles to an element
2833
+ * Called during element initialization
2834
+ */
2835
+ function applyStyles(element) {
2836
+ const stylesMethod = element[STYLES_METHOD];
2837
+ if (!stylesMethod)
2838
+ return;
2839
+ // Only apply once
2840
+ if (element[STYLES_APPLIED])
2841
+ return;
2842
+ element[STYLES_APPLIED] = true;
2843
+ try {
2844
+ const result = stylesMethod.call(element);
2845
+ if (!isCSSResult(result)) {
2846
+ console.warn('Styles method must return css`` template result');
2847
+ return;
2848
+ }
2849
+ // Ensure shadow root exists
2850
+ if (!element.shadowRoot) {
2851
+ element.attachShadow({ mode: 'open' });
2852
+ }
2853
+ // Create base styles for meta elements (if, case)
2854
+ const baseStyleSheet = new CSSStyleSheet();
2855
+ baseStyleSheet.replaceSync('if, case { display: contents; }');
2856
+ // Try to use constructable stylesheets for better performance
2857
+ if (element.shadowRoot && result.styleSheet && 'adoptedStyleSheets' in element.shadowRoot) {
2858
+ element.shadowRoot.adoptedStyleSheets = [baseStyleSheet, result.styleSheet];
2859
+ }
2860
+ else if (element.shadowRoot) {
2861
+ // Fallback to <style> tag
2862
+ const style = document.createElement('style');
2863
+ style.textContent = 'if, case { display: contents; }\n' + result.cssText;
2864
+ element.shadowRoot.appendChild(style);
2865
+ }
2866
+ }
2867
+ catch (error) {
2868
+ console.error('Error applying styles:', error);
2869
+ }
2870
+ }
2871
+
1414
2872
  /**
1415
2873
  * Applies core element functionality to a constructor
1416
2874
  * This is shared between @element and @page decorators
@@ -1455,6 +2913,9 @@ function applyElementFunctionality(constructor) {
1455
2913
  enumerable: true,
1456
2914
  configurable: true
1457
2915
  });
2916
+ // Note: rendered promise is stored via symbols RENDERED_PROMISE and RENDERED_RESOLVE
2917
+ // It's not exposed as a public property - only accessible via test utilities
2918
+ // This prevents accidental misuse in production code
1458
2919
  // Add controller property
1459
2920
  Object.defineProperty(constructor.prototype, 'controller', {
1460
2921
  get() {
@@ -1492,6 +2953,7 @@ function applyElementFunctionality(constructor) {
1492
2953
  // Re-establish handlers that get cleaned up on disconnect
1493
2954
  setupEventHandlers(this, this);
1494
2955
  setupResponseHandlers(this, this);
2956
+ setupContextHandler(this);
1495
2957
  // Re-establish observers that get cleaned up on disconnect
1496
2958
  try {
1497
2959
  setupObservers(this, this);
@@ -1506,6 +2968,9 @@ function applyElementFunctionality(constructor) {
1506
2968
  return;
1507
2969
  }
1508
2970
  try {
2971
+ // Mark that properties are being initialized from attributes
2972
+ // This allows property setters to work during initialization
2973
+ this[PROPERTIES_INITIALIZED] = true;
1509
2974
  // Initialize properties from attributes before rendering
1510
2975
  const properties = constructor[PROPERTIES];
1511
2976
  if (properties) {
@@ -1524,82 +2989,69 @@ function applyElementFunctionality(constructor) {
1524
2989
  }
1525
2990
  }
1526
2991
  }
1527
- // Mark that properties have been initialized
1528
- this[PROPERTIES_INITIALIZED] = true;
2992
+ // Apply any properties that were set before element was connected
2993
+ // BUT only if they don't have an HTML attribute (don't override HTML attributes)
2994
+ if (this[PRE_INIT_PROPERTY_VALUES]) {
2995
+ for (const [propName, propValue] of this[PRE_INIT_PROPERTY_VALUES]) {
2996
+ // Remove from map first so getter doesn't return it during setter call
2997
+ this[PRE_INIT_PROPERTY_VALUES].delete(propName);
2998
+ // Only apply pre-init value if NO HTML attribute exists
2999
+ // This prevents field initializers from overwriting HTML attributes
3000
+ const propOptions = properties?.get(propName);
3001
+ const attributeName = typeof propOptions?.attribute === 'string' ? propOptions.attribute : propName.toLowerCase();
3002
+ if (!this.hasAttribute(attributeName)) {
3003
+ this[propName] = propValue;
3004
+ }
3005
+ }
3006
+ // Clear the pre-init values map
3007
+ delete this[PRE_INIT_PROPERTY_VALUES];
3008
+ }
1529
3009
  // Properties are now stateless and read from DOM attributes only
1530
3010
  // Initial values are not automatically reflected
1531
- // Create shadow root if it doesn't exist
1532
- if (!this.shadowRoot) {
1533
- this.attachShadow({ mode: 'open' });
1534
- }
1535
- // Build the shadow DOM content
1536
- let shadowContent = '';
1537
- // Add HTML first (maintaining original order)
1538
- if (this.html) {
1539
- try {
1540
- const htmlResult = this.html();
1541
- // Handle both async and sync html
1542
- const htmlContent = htmlResult instanceof Promise ? await htmlResult : htmlResult;
1543
- if (htmlContent !== undefined) {
1544
- shadowContent += htmlContent;
3011
+ // v3.0.0: Apply @styles decorator if present
3012
+ // This creates the shadow root and applies styles
3013
+ applyStyles(this);
3014
+ // v3.0.0: Perform initial @render if present
3015
+ // This uses differential rendering with template system
3016
+ // Defer initial render to next microtask to allow property bindings
3017
+ // from parent to be set first (avoids infinite loops in nested elements)
3018
+ if (this[RENDER_METHOD]) {
3019
+ queueMicrotask(() => {
3020
+ requestRender(this, true);
3021
+ // Setup observers after first render completes so shadow DOM content exists
3022
+ try {
3023
+ setupObservers(this, this);
1545
3024
  }
1546
- }
1547
- catch (error) {
1548
- console.error(`Error in html() method for ${this.tagName}:`, error);
1549
- }
3025
+ catch (error) {
3026
+ console.error(`Error setting up observers for ${this.tagName}:`, error);
3027
+ }
3028
+ // Mark element as ready after initial render completes
3029
+ if (this[READY_RESOLVE]) {
3030
+ this[READY_RESOLVE]();
3031
+ this[READY_RESOLVE] = null;
3032
+ }
3033
+ });
1550
3034
  }
1551
- // Add CSS after HTML (maintaining original order)
1552
- if (this.css) {
3035
+ else {
3036
+ // No render method, setup observers immediately
1553
3037
  try {
1554
- const cssResult = this.css();
1555
- // Handle both async and sync css
1556
- const cssResolved = cssResult instanceof Promise ? await cssResult : cssResult;
1557
- if (cssResolved) {
1558
- // Handle both string and array of strings
1559
- const cssContent = Array.isArray(cssResolved) ? cssResolved.join('\n') : cssResolved;
1560
- // No need for scoping with Shadow DOM, but add data attribute for compatibility
1561
- shadowContent += `<style data-component-css>${cssContent}</style>`;
1562
- }
3038
+ setupObservers(this, this);
1563
3039
  }
1564
3040
  catch (error) {
1565
- console.error(`Error in css() method for ${this.tagName}:`, error);
3041
+ console.error(`Error setting up observers for ${this.tagName}:`, error);
1566
3042
  }
1567
- }
1568
- // Set shadow DOM content
1569
- if (shadowContent) {
1570
- this.shadowRoot.innerHTML = shadowContent;
1571
- }
1572
- // Render all @part methods into their corresponding elements
1573
- const parts = constructor[PARTS];
1574
- if (parts && this.shadowRoot) {
1575
- for (const [partName, partHandler] of parts) {
1576
- try {
1577
- const partElement = this.shadowRoot.querySelector(`[part="${partName}"]`);
1578
- if (partElement) {
1579
- // For initial render, call original method directly to avoid timing restrictions
1580
- const partResult = partHandler.method.call(this);
1581
- const partContent = partResult instanceof Promise ? await partResult : partResult;
1582
- if (partContent !== undefined) {
1583
- partElement.innerHTML = partContent;
1584
- }
1585
- }
1586
- }
1587
- catch (error) {
1588
- console.error(`Error rendering @part('${partName}') in ${this.tagName}:`, error);
1589
- }
3043
+ // Mark element as ready immediately if no render method
3044
+ if (this[READY_RESOLVE]) {
3045
+ this[READY_RESOLVE]();
3046
+ this[READY_RESOLVE] = null;
1590
3047
  }
1591
3048
  }
1592
- // Setup @on event handlers - use element for host events, shadow root for delegated events
3049
+ // Setup @on event handlers (v2.5.4 compatibility restored!)
1593
3050
  setupEventHandlers(this, this);
1594
3051
  // Setup @respond handlers for elements
1595
3052
  setupResponseHandlers(this, this);
1596
- // Setup @observe observers
1597
- try {
1598
- setupObservers(this, this);
1599
- }
1600
- catch (error) {
1601
- console.error(`Error setting up observers for ${this.tagName}:`, error);
1602
- }
3053
+ // Setup @context handler for elements
3054
+ setupContextHandler(this);
1603
3055
  // Mark as initialized
1604
3056
  this[INITIALIZED] = true;
1605
3057
  // NOW call the original user-defined connectedCallback after shadow DOM is set up
@@ -1608,11 +3060,8 @@ function applyElementFunctionality(constructor) {
1608
3060
  }
1609
3061
  }
1610
3062
  finally {
1611
- // Always mark element as ready, even if there were errors
1612
- if (this[READY_RESOLVE]) {
1613
- this[READY_RESOLVE]();
1614
- this[READY_RESOLVE] = null; // Clear the resolver
1615
- }
3063
+ // Ready is now resolved inside the render microtask (or immediately if no render)
3064
+ // This ensures ready waits for initial render to complete
1616
3065
  }
1617
3066
  // Call @ready handlers after everything is set up and ready promise is resolved
1618
3067
  const readyHandlers = constructor[READY_HANDLERS];
@@ -1649,10 +3098,12 @@ function applyElementFunctionality(constructor) {
1649
3098
  console.error(`Failed to detach controller:`, error);
1650
3099
  });
1651
3100
  }
1652
- // Cleanup @on event handlers
3101
+ // Cleanup @on event handlers (v2.5.4 compatibility restored!)
1653
3102
  cleanupEventHandlers(this);
1654
3103
  // Cleanup @respond handlers
1655
3104
  cleanupResponseHandlers(this);
3105
+ // Cleanup @context handler
3106
+ cleanupContextHandler(this);
1656
3107
  // Cleanup @observe observers
1657
3108
  cleanupObservers(this);
1658
3109
  };
@@ -1715,6 +3166,10 @@ function applyElementFunctionality(constructor) {
1715
3166
  }
1716
3167
  }
1717
3168
  }
3169
+ // Trigger auto-render on attribute change (same as property setter)
3170
+ if (this[RENDER_METHOD] && this[INITIALIZED]) {
3171
+ requestRender(this);
3172
+ }
1718
3173
  }
1719
3174
  }
1720
3175
  break;
@@ -1754,7 +3209,7 @@ function applyElementFunctionality(constructor) {
1754
3209
  }
1755
3210
  };
1756
3211
  }
1757
- function element(tagName) {
3212
+ function element(tagName, options) {
1758
3213
  return function (constructor, context) {
1759
3214
  // Transfer metadata from context to constructor
1760
3215
  if (context.metadata && context.metadata[PROPERTIES]) {
@@ -1765,6 +3220,11 @@ function element(tagName) {
1765
3220
  constructor[PROPERTIES].set(key, value);
1766
3221
  }
1767
3222
  }
3223
+ // Set up form association if requested via options
3224
+ // MUST be done BEFORE applyElementFunctionality and customElements.define
3225
+ if (options?.formAssociated === true) {
3226
+ constructor.formAssociated = true;
3227
+ }
1768
3228
  applyElementFunctionality(constructor);
1769
3229
  customElements.define(tagName, constructor);
1770
3230
  return constructor;
@@ -1820,29 +3280,43 @@ function property(options) {
1820
3280
  if (attrValue !== null) {
1821
3281
  return parseAttributeValue(attrValue, finalOptions || {}, undefined, initialValue);
1822
3282
  }
1823
- // For Boolean properties that have been explicitly set via attribute,
3283
+ // For Boolean properties that have been explicitly set via attribute (and then removed),
1824
3284
  // follow HTML boolean attribute semantics (absence = false)
1825
3285
  const inferredType = finalOptions?.type || detectType(initialValue);
1826
3286
  if (inferredType === Boolean && this[EXPLICITLY_SET_PROPERTIES]?.has(propertyKey)) {
1827
3287
  return false;
1828
3288
  }
1829
- // Otherwise return initial value
3289
+ // Check for pre-init property values (set before element was connected)
3290
+ if (this[PRE_INIT_PROPERTY_VALUES]?.has(propertyKey)) {
3291
+ return this[PRE_INIT_PROPERTY_VALUES].get(propertyKey);
3292
+ }
3293
+ // Otherwise return initial value (respects default values like showRememberMe = true)
1830
3294
  return initialValue;
1831
3295
  },
1832
3296
  set(newValue) {
1833
- // Get old value from stored state for change detection
1834
- if (!this[PROPERTY_VALUES]) {
1835
- this[PROPERTY_VALUES] = {};
1836
- }
1837
- const oldValue = this[PROPERTY_VALUES][propertyKey];
3297
+ // Get old value by calling the getter (which reads from attribute)
3298
+ const oldValue = this[propertyKey];
1838
3299
  // Check if value actually changed
1839
3300
  if (oldValue === newValue)
1840
3301
  return;
1841
- // Update stored value
1842
- this[PROPERTY_VALUES][propertyKey] = newValue;
1843
- // Always reflect to DOM - properties are always backed by attributes
3302
+ // Don't reflect to DOM until connectedCallback has started
3303
+ // This prevents field initializers from overwriting HTML attributes
3304
+ if (!this[PROPERTIES_INITIALIZED]) {
3305
+ // Store value for later application when element is connected
3306
+ if (!this[PRE_INIT_PROPERTY_VALUES]) {
3307
+ this[PRE_INIT_PROPERTY_VALUES] = new Map();
3308
+ }
3309
+ this[PRE_INIT_PROPERTY_VALUES].set(propertyKey, newValue);
3310
+ return;
3311
+ }
3312
+ // Reflect to DOM - properties are backed by attributes
1844
3313
  const attributeName = typeof finalOptions.attribute === 'string' ? finalOptions.attribute : propertyKey.toLowerCase();
1845
3314
  const attributeValue = valueToAttribute(newValue, finalOptions, initialValue);
3315
+ // Mark as explicitly set for boolean handling
3316
+ if (!this[EXPLICITLY_SET_PROPERTIES]) {
3317
+ this[EXPLICITLY_SET_PROPERTIES] = new Set();
3318
+ }
3319
+ this[EXPLICITLY_SET_PROPERTIES].add(propertyKey);
1846
3320
  // Flag to prevent attributeChangedCallback from triggering watchers for this change
1847
3321
  if (!this._settingFromProperty)
1848
3322
  this._settingFromProperty = new Set();
@@ -1884,8 +3358,12 @@ function property(options) {
1884
3358
  }
1885
3359
  }
1886
3360
  }
1887
- if (this.requestUpdate) {
1888
- this.requestUpdate(propertyKey, oldValue);
3361
+ // v3.0.0: Trigger auto-render on property change
3362
+ // This respects @render options (debounce, throttle, once, sync)
3363
+ // Only trigger renders after element is fully initialized to avoid
3364
+ // infinite loops during initial setup
3365
+ if (this[RENDER_METHOD] && this[INITIALIZED]) {
3366
+ requestRender(this);
1889
3367
  }
1890
3368
  },
1891
3369
  configurable: true,
@@ -1980,12 +3458,15 @@ function queryAll(selector, options = {}) {
1980
3458
  function watch(...propertyNames) {
1981
3459
  return function (target, context) {
1982
3460
  const methodName = context.name;
3461
+ const initKey = `__watch_init_${methodName}`;
1983
3462
  context.addInitializer(function () {
1984
3463
  const constructor = this.constructor;
3464
+ if (constructor[initKey])
3465
+ return;
3466
+ constructor[initKey] = true;
1985
3467
  if (!constructor[PROPERTY_WATCHERS]) {
1986
3468
  constructor[PROPERTY_WATCHERS] = new Map();
1987
3469
  }
1988
- // Store the watcher method for each property
1989
3470
  for (const propertyName of propertyNames) {
1990
3471
  if (!constructor[PROPERTY_WATCHERS].has(propertyName)) {
1991
3472
  constructor[PROPERTY_WATCHERS].set(propertyName, []);
@@ -2064,8 +3545,12 @@ function context() {
2064
3545
  function ready() {
2065
3546
  return function (target, context) {
2066
3547
  const methodName = context.name;
3548
+ const initKey = `__ready_init_${methodName}`;
2067
3549
  context.addInitializer(function () {
2068
3550
  const constructor = this.constructor;
3551
+ if (constructor[initKey])
3552
+ return;
3553
+ constructor[initKey] = true;
2069
3554
  if (!constructor[READY_HANDLERS]) {
2070
3555
  constructor[READY_HANDLERS] = [];
2071
3556
  }
@@ -2083,8 +3568,12 @@ function ready() {
2083
3568
  function dispose() {
2084
3569
  return function (target, context) {
2085
3570
  const methodName = context.name;
3571
+ const initKey = `__dispose_init_${methodName}`;
2086
3572
  context.addInitializer(function () {
2087
3573
  const constructor = this.constructor;
3574
+ if (constructor[initKey])
3575
+ return;
3576
+ constructor[initKey] = true;
2088
3577
  if (!constructor[DISPOSE_HANDLERS]) {
2089
3578
  constructor[DISPOSE_HANDLERS] = [];
2090
3579
  }
@@ -2102,8 +3591,12 @@ function dispose() {
2102
3591
  function moved(options = {}) {
2103
3592
  return function (originalMethod, context) {
2104
3593
  const methodName = context.name;
3594
+ const initKey = `__moved_init_${methodName}`;
2105
3595
  context.addInitializer(function () {
2106
3596
  const constructor = this.constructor;
3597
+ if (constructor[initKey])
3598
+ return;
3599
+ constructor[initKey] = true;
2107
3600
  if (!constructor[MOVED_HANDLERS]) {
2108
3601
  constructor[MOVED_HANDLERS] = [];
2109
3602
  }
@@ -2188,102 +3681,20 @@ function adopted(options = {}) {
2188
3681
  return function (...args) {
2189
3682
  // Initialize timers storage if not present
2190
3683
  if (!this[ADOPTED_TIMERS]) {
2191
- this[ADOPTED_TIMERS] = new Map();
2192
- }
2193
- // Get or create timers for this specific method
2194
- if (!this[ADOPTED_TIMERS].has(methodName)) {
2195
- this[ADOPTED_TIMERS].set(methodName, {
2196
- throttleTimer: null,
2197
- debounceTimer: null,
2198
- lastThrottleCall: 0
2199
- });
2200
- }
2201
- const timers = this[ADOPTED_TIMERS].get(methodName);
2202
- // Helper function to execute method
2203
- const executeMethod = (...methodArgs) => {
2204
- return originalMethod.apply(this, methodArgs);
2205
- };
2206
- const hasDebounce = options.debounce !== undefined && options.debounce > 0;
2207
- const hasThrottle = options.throttle !== undefined && options.throttle > 0;
2208
- // Handle timing based on priority: debounce > throttle > immediate
2209
- switch (true) {
2210
- case hasDebounce: {
2211
- clearTimeout(timers.debounceTimer);
2212
- timers.debounceTimer = setTimeout(() => executeMethod(...args), options.debounce);
2213
- return undefined;
2214
- }
2215
- case hasThrottle: {
2216
- const throttleMs = options.throttle;
2217
- const now = Date.now();
2218
- const canExecuteImmediately = timers.lastThrottleCall === 0 || now - timers.lastThrottleCall >= throttleMs;
2219
- if (canExecuteImmediately) {
2220
- timers.lastThrottleCall = now;
2221
- return executeMethod(...args);
2222
- }
2223
- const hasScheduledTimer = !!timers.throttleTimer;
2224
- if (!hasScheduledTimer) {
2225
- const remainingTime = throttleMs - (now - timers.lastThrottleCall);
2226
- timers.throttleTimer = setTimeout(() => {
2227
- timers.throttleTimer = null;
2228
- timers.lastThrottleCall = Date.now();
2229
- executeMethod(...args);
2230
- }, remainingTime);
2231
- }
2232
- return undefined;
2233
- }
2234
- default:
2235
- return executeMethod(...args);
2236
- }
2237
- };
2238
- };
2239
- }
2240
- /**
2241
- * Decorator for methods that render specific parts of the template
2242
- * Parts are identified by the 'part' attribute in the HTML template
2243
- * When the decorated method is called, it automatically re-renders its part
2244
- */
2245
- function part(partName, options = {}) {
2246
- return function (originalMethod, context) {
2247
- const methodName = context.name;
2248
- context.addInitializer(function () {
2249
- const constructor = this.constructor;
2250
- if (!constructor[PARTS]) {
2251
- constructor[PARTS] = new Map();
2252
- }
2253
- constructor[PARTS].set(partName, {
2254
- methodName,
2255
- method: originalMethod
2256
- });
2257
- });
2258
- // Return wrapped method that automatically re-renders the part when called
2259
- return function (...args) {
2260
- // Initialize timers storage if not present
2261
- if (!this[PART_TIMERS]) {
2262
- this[PART_TIMERS] = new Map();
3684
+ this[ADOPTED_TIMERS] = new Map();
2263
3685
  }
2264
- // Get or create timers for this specific part
2265
- if (!this[PART_TIMERS].has(partName)) {
2266
- this[PART_TIMERS].set(partName, {
3686
+ // Get or create timers for this specific method
3687
+ if (!this[ADOPTED_TIMERS].has(methodName)) {
3688
+ this[ADOPTED_TIMERS].set(methodName, {
2267
3689
  throttleTimer: null,
2268
3690
  debounceTimer: null,
2269
3691
  lastThrottleCall: 0
2270
3692
  });
2271
3693
  }
2272
- const timers = this[PART_TIMERS].get(partName);
2273
- // Helper function to execute method and update DOM
2274
- const executeAndUpdate = (...methodArgs) => {
2275
- const result = originalMethod.apply(this, methodArgs);
2276
- const updateDOM = (content) => {
2277
- const hasContent = content !== undefined;
2278
- const hasElement = this.shadowRoot?.querySelector(`[part="${partName}"]`);
2279
- if (hasContent && hasElement) {
2280
- hasElement.innerHTML = content;
2281
- }
2282
- };
2283
- const isPromise = result instanceof Promise;
2284
- return isPromise
2285
- ? result.then(content => { updateDOM(content); return content; })
2286
- : (updateDOM(result), result);
3694
+ const timers = this[ADOPTED_TIMERS].get(methodName);
3695
+ // Helper function to execute method
3696
+ const executeMethod = (...methodArgs) => {
3697
+ return originalMethod.apply(this, methodArgs);
2287
3698
  };
2288
3699
  const hasDebounce = options.debounce !== undefined && options.debounce > 0;
2289
3700
  const hasThrottle = options.throttle !== undefined && options.throttle > 0;
@@ -2291,7 +3702,7 @@ function part(partName, options = {}) {
2291
3702
  switch (true) {
2292
3703
  case hasDebounce: {
2293
3704
  clearTimeout(timers.debounceTimer);
2294
- timers.debounceTimer = setTimeout(() => executeAndUpdate(...args), options.debounce);
3705
+ timers.debounceTimer = setTimeout(() => executeMethod(...args), options.debounce);
2295
3706
  return undefined;
2296
3707
  }
2297
3708
  case hasThrottle: {
@@ -2300,7 +3711,7 @@ function part(partName, options = {}) {
2300
3711
  const canExecuteImmediately = timers.lastThrottleCall === 0 || now - timers.lastThrottleCall >= throttleMs;
2301
3712
  if (canExecuteImmediately) {
2302
3713
  timers.lastThrottleCall = now;
2303
- return executeAndUpdate(...args);
3714
+ return executeMethod(...args);
2304
3715
  }
2305
3716
  const hasScheduledTimer = !!timers.throttleTimer;
2306
3717
  if (!hasScheduledTimer) {
@@ -2308,17 +3719,19 @@ function part(partName, options = {}) {
2308
3719
  timers.throttleTimer = setTimeout(() => {
2309
3720
  timers.throttleTimer = null;
2310
3721
  timers.lastThrottleCall = Date.now();
2311
- executeAndUpdate(...args);
3722
+ executeMethod(...args);
2312
3723
  }, remainingTime);
2313
3724
  }
2314
3725
  return undefined;
2315
3726
  }
2316
3727
  default:
2317
- return executeAndUpdate(...args);
3728
+ return executeMethod(...args);
2318
3729
  }
2319
3730
  };
2320
3731
  };
2321
3732
  }
3733
+ // @part decorator removed in v3.0.0
3734
+ // Use @render with differential rendering instead
2322
3735
 
2323
3736
  /*!
2324
3737
  * pica-route v1.1.2
@@ -3069,6 +4482,8 @@ function Router(options) {
3069
4482
  let currentLayoutName = null; // Track current layout name
3070
4483
  let currentLayoutTimestamp = null; // Track current layout timestamp
3071
4484
  const context = options.context || {}; // Store context for guards
4485
+ // Create Context instance for managing router state
4486
+ const navigationContext = new Context(context, [], '', {});
3072
4487
  function getCurrentLayoutElement(target) {
3073
4488
  const noCurrentLayout = !currentLayoutName || !currentLayoutTimestamp;
3074
4489
  if (noCurrentLayout) {
@@ -3106,33 +4521,19 @@ function Router(options) {
3106
4521
  // Extend the connectedCallback to add router-specific functionality
3107
4522
  const elementConnectedCallback = constructor.prototype.connectedCallback;
3108
4523
  constructor.prototype.connectedCallback = function () {
4524
+ // Store the Context instance for @context decorated methods to access
4525
+ this[CONTEXT_HANDLER] = navigationContext;
3109
4526
  // Call the element's connectedCallback first
3110
4527
  elementConnectedCallback?.call(this);
3111
- // Setup context request handler for nested elements
3112
- const contextRequestHandler = (event) => {
3113
- // Only respond if this element has context
3114
- if (this[ROUTER_CONTEXT] !== undefined) {
3115
- event.detail.context = this[ROUTER_CONTEXT];
3116
- event.stopPropagation(); // Stop bubbling once context is provided
3117
- }
3118
- };
3119
- this.addEventListener('@context/request', contextRequestHandler);
3120
- // Store handler for cleanup
3121
- this[CONTEXT_REQUEST_HANDLER] = contextRequestHandler;
3122
4528
  };
3123
4529
  // Extend the disconnectedCallback to clean up router-specific stuff
3124
4530
  const elementDisconnectedCallback = constructor.prototype.disconnectedCallback;
3125
4531
  constructor.prototype.disconnectedCallback = function () {
3126
4532
  // Call element's disconnectedCallback first
3127
4533
  elementDisconnectedCallback?.call(this);
3128
- // Clean up context request handler
3129
- const handler = this[CONTEXT_REQUEST_HANDLER];
3130
- if (handler) {
3131
- this.removeEventListener('@context/request', handler);
3132
- delete this[CONTEXT_REQUEST_HANDLER];
3133
- }
3134
- // Clean up context reference
4534
+ // Clean up context references
3135
4535
  delete this[ROUTER_CONTEXT];
4536
+ delete this[CONTEXT_HANDLER];
3136
4537
  };
3137
4538
  // Define the custom element
3138
4539
  customElements.define(pageOptions.tag, constructor);
@@ -3191,8 +4592,8 @@ function Router(options) {
3191
4592
  * initialize();
3192
4593
  */
3193
4594
  function initialize() {
3194
- const targetExists = !!document.querySelector(options.target);
3195
- if (!targetExists) {
4595
+ const target = document.querySelector(options.target);
4596
+ if (!target) {
3196
4597
  throw new Error(`Target element not found: ${options.target}`);
3197
4598
  }
3198
4599
  const needsSorting = !is_sorted;
@@ -3216,6 +4617,10 @@ function Router(options) {
3216
4617
  : placard;
3217
4618
  });
3218
4619
  }
4620
+ function emitContextUpdate(target, currentPath, routeParams) {
4621
+ // Update the navigation context and notify all registered elements
4622
+ navigationContext.update(context, placards, currentPath, routeParams);
4623
+ }
3219
4624
  function updateLayout(layoutElement, currentPath, routeParams) {
3220
4625
  // Check if layout implements the update method
3221
4626
  if (typeof layoutElement.update === 'function') {
@@ -3298,6 +4703,7 @@ function Router(options) {
3298
4703
  }
3299
4704
  const newPageElement = document.createElement(route.tag);
3300
4705
  newPageElement[ROUTER_CONTEXT] = context;
4706
+ newPageElement[CONTEXT_HANDLER] = navigationContext;
3301
4707
  const routeParams = params;
3302
4708
  Object.keys(routeParams).forEach(key => newPageElement.setAttribute(key, routeParams[key]));
3303
4709
  return { result: RouteResult.SUCCESS, element: newPageElement, transition: route.transition, layout: route.layout, routeParams };
@@ -3388,7 +4794,7 @@ function Router(options) {
3388
4794
  // Collect fresh placards before navigation
3389
4795
  collectPlacards();
3390
4796
  window.scrollTo(0, 0);
3391
- const isHomePath = (path.trim() === '' || path === '/') && !!home;
4797
+ const isHomePath = (path?.trim() === '' || path === '/') && !!home;
3392
4798
  if (isHomePath) {
3393
4799
  const homeRoute = routes.find(r => r.route.match('/'));
3394
4800
  const guardsAllowed = checkGuards(homeRoute?.guards, {}, target);
@@ -3402,11 +4808,15 @@ function Router(options) {
3402
4808
  const hasLayout = layoutElement !== null || getCurrentLayoutElement(target) !== null;
3403
4809
  if (hasLayout) {
3404
4810
  await renderWithLayout(target, element, finalTransition, layoutElement, needsNewLayout, path, {});
4811
+ emitContextUpdate(target, path, {});
3405
4812
  return;
3406
4813
  }
3407
4814
  await renderDirect(target, element, finalTransition);
4815
+ emitContextUpdate(target, path, {});
3408
4816
  return;
3409
4817
  }
4818
+ if (!path)
4819
+ return;
3410
4820
  const routeResult = resolveRoute(path, target);
3411
4821
  const isGuardsFailed = routeResult.result === RouteResult.GUARDS_FAILED;
3412
4822
  if (isGuardsFailed) {
@@ -3421,9 +4831,11 @@ function Router(options) {
3421
4831
  const hasLayout = layoutElement !== null || getCurrentLayoutElement(target) !== null;
3422
4832
  if (hasLayout) {
3423
4833
  await renderWithLayout(target, element, finalTransition, layoutElement, needsNewLayout, path, routeParams);
4834
+ emitContextUpdate(target, path, routeParams);
3424
4835
  return;
3425
4836
  }
3426
4837
  await renderDirect(target, element, finalTransition);
4838
+ emitContextUpdate(target, path, routeParams);
3427
4839
  return;
3428
4840
  }
3429
4841
  const { element, transition, layout } = create404Element();
@@ -3433,9 +4845,11 @@ function Router(options) {
3433
4845
  const hasLayout = layoutElement !== null || getCurrentLayoutElement(target) !== null;
3434
4846
  if (hasLayout) {
3435
4847
  await renderWithLayout(target, element, finalTransition, layoutElement, needsNewLayout, path, {});
4848
+ emitContextUpdate(target, path, {});
3436
4849
  return;
3437
4850
  }
3438
4851
  await renderDirect(target, element, finalTransition);
4852
+ emitContextUpdate(target, path, {});
3439
4853
  }
3440
4854
  async function performTransition$1(container, oldElement, newElement, transition) {
3441
4855
  return performTransition(container, oldElement, newElement, transition);
@@ -3448,5 +4862,555 @@ function Router(options) {
3448
4862
  };
3449
4863
  }
3450
4864
 
3451
- export { IS_CONTROLLER_INSTANCE, Router, SimpleArray, adopted, applyElementFunctionality, context, controller, dispatch, dispose, element, getSymbol, layout, moved, observe, on, part, property, query, queryAll, ready, request, respond, useNativeElementControllers, watch };
4865
+ // @on decorator removed in v3.0.0 - use template event syntax instead: @click=${handler}
4866
+ /**
4867
+ * Decorator that automatically dispatches a custom event after a method is called.
4868
+ * The return value of the method becomes the event detail.
4869
+ *
4870
+ * @param eventName The name of the event to dispatch
4871
+ * @param options Optional configuration extending EventInit
4872
+ */
4873
+ function dispatch(eventName, options) {
4874
+ return function (originalMethod, _context) {
4875
+ return function (...args) {
4876
+ // Create timing wrappers for dispatch (per-instance)
4877
+ if (!this[DISPATCH_TIMERS]) {
4878
+ this[DISPATCH_TIMERS] = new Map();
4879
+ }
4880
+ const timerKey = `${eventName}_${_context.name}`;
4881
+ if (!this[DISPATCH_TIMERS].has(timerKey)) {
4882
+ this[DISPATCH_TIMERS].set(timerKey, {
4883
+ debounceTimeout: null,
4884
+ throttleLastCall: 0,
4885
+ throttleTimeout: null
4886
+ });
4887
+ }
4888
+ const timers = this[DISPATCH_TIMERS].get(timerKey);
4889
+ // Call the original method with preserved this context
4890
+ const result = originalMethod.apply(this, args);
4891
+ // Helper to dispatch the event
4892
+ const doDispatch = (detail) => {
4893
+ // Skip dispatch if result is undefined and dispatchOnUndefined is false
4894
+ if (detail === undefined && options?.dispatchOnUndefined === false) {
4895
+ return;
4896
+ }
4897
+ // Create event with spread operator for options
4898
+ const event = new CustomEvent(eventName, {
4899
+ bubbles: true, // Default to true for component events
4900
+ composed: true, // Allow crossing shadow DOM boundaries
4901
+ ...options, // Spread all EventInit options
4902
+ detail
4903
+ });
4904
+ this.dispatchEvent(event);
4905
+ };
4906
+ // Helper to handle timed dispatch
4907
+ const timedDispatch = (detail) => {
4908
+ if (options?.debounce) {
4909
+ clearTimeout(timers.debounceTimeout);
4910
+ timers.debounceTimeout = setTimeout(() => doDispatch(detail), options.debounce);
4911
+ }
4912
+ else if (options?.throttle) {
4913
+ const now = Date.now();
4914
+ const remaining = options.throttle - (now - timers.throttleLastCall);
4915
+ if (remaining <= 0) {
4916
+ clearTimeout(timers.throttleTimeout);
4917
+ timers.throttleLastCall = now;
4918
+ doDispatch(detail);
4919
+ }
4920
+ else if (!timers.throttleTimeout) {
4921
+ timers.throttleTimeout = setTimeout(() => {
4922
+ timers.throttleLastCall = Date.now();
4923
+ timers.throttleTimeout = null;
4924
+ doDispatch(detail);
4925
+ }, remaining);
4926
+ }
4927
+ }
4928
+ else {
4929
+ doDispatch(detail);
4930
+ }
4931
+ };
4932
+ // Handle async methods
4933
+ if (result instanceof Promise) {
4934
+ return result.then((resolvedResult) => {
4935
+ timedDispatch(resolvedResult);
4936
+ return resolvedResult;
4937
+ });
4938
+ }
4939
+ // Sync method
4940
+ timedDispatch(result);
4941
+ return result;
4942
+ };
4943
+ };
4944
+ }
4945
+
4946
+ /**
4947
+ * Custom element readiness utilities
4948
+ * Handles waiting for custom elements to be defined with timeout warnings
4949
+ */
4950
+ /**
4951
+ * Global flag to disable custom element readiness timeout warnings
4952
+ * Set this to true in environments where slow element registration is expected
4953
+ */
4954
+ let DISABLE_ELEMENT_READY_WARNINGS = false;
4955
+ /**
4956
+ * Set whether to disable custom element readiness timeout warnings
4957
+ */
4958
+ function setDisableElementReadyWarnings(value) {
4959
+ DISABLE_ELEMENT_READY_WARNINGS = value;
4960
+ }
4961
+ /**
4962
+ * Default timeout for custom element registration warning (500ms)
4963
+ */
4964
+ const DEFAULT_WARNING_TIMEOUT = 500;
4965
+ /**
4966
+ * Wait for a custom element to be defined
4967
+ * Logs a warning if it takes longer than the warning timeout
4968
+ *
4969
+ * @param tagName - The custom element tag name
4970
+ * @param warningTimeout - Time in ms before warning (default 500ms)
4971
+ * @returns Promise that resolves when element is defined
4972
+ */
4973
+ async function waitForElementDefined(tagName, warningTimeout = DEFAULT_WARNING_TIMEOUT) {
4974
+ // If already defined, return immediately
4975
+ if (customElements.get(tagName)) {
4976
+ return;
4977
+ }
4978
+ // Set up warning timer if not disabled
4979
+ let warningTimer = null;
4980
+ if (!DISABLE_ELEMENT_READY_WARNINGS) {
4981
+ warningTimer = setTimeout(() => {
4982
+ console.warn(`Custom element <${tagName}> is taking longer than ${warningTimeout}ms to register. ` +
4983
+ `This may indicate a missing import or circular dependency. ` +
4984
+ `Set DISABLE_ELEMENT_READY_WARNINGS=true to disable this warning.`);
4985
+ }, warningTimeout);
4986
+ }
4987
+ try {
4988
+ // Wait for element to be defined
4989
+ await customElements.whenDefined(tagName);
4990
+ }
4991
+ finally {
4992
+ // Clear warning timer
4993
+ if (warningTimer) {
4994
+ clearTimeout(warningTimer);
4995
+ }
4996
+ }
4997
+ }
4998
+ /**
4999
+ * Wait for a custom element to be defined and ready
5000
+ * First waits for the element to be registered, then waits for its ready promise
5001
+ *
5002
+ * @param element - The custom element instance
5003
+ * @param warningTimeout - Time in ms before warning about registration (default 500ms)
5004
+ * @returns Promise that resolves when element is defined and ready
5005
+ */
5006
+ async function waitForElementReady(element, warningTimeout = DEFAULT_WARNING_TIMEOUT) {
5007
+ const tagName = element.tagName.toLowerCase();
5008
+ // Wait for element to be defined
5009
+ await waitForElementDefined(tagName, warningTimeout);
5010
+ // Wait for element's ready promise if it exists
5011
+ if ('ready' in element && typeof element.ready?.then === 'function') {
5012
+ await element.ready;
5013
+ }
5014
+ }
5015
+ /**
5016
+ * Process all custom elements in a node tree and wait for them to be ready
5017
+ * This is useful after inserting a template with custom elements
5018
+ *
5019
+ * @param node - The root node to scan for custom elements
5020
+ * @param warningTimeout - Time in ms before warning about registration (default 500ms)
5021
+ * @returns Promise that resolves when all custom elements are ready
5022
+ */
5023
+ async function waitForAllCustomElements(node, warningTimeout = DEFAULT_WARNING_TIMEOUT) {
5024
+ const customElements = [];
5025
+ // Find all custom elements (tag names with hyphens)
5026
+ if (node instanceof Element) {
5027
+ if (node.tagName.includes('-')) {
5028
+ customElements.push(node);
5029
+ }
5030
+ // Also check in shadow DOM
5031
+ if (node.shadowRoot) {
5032
+ const shadowCustomElements = node.shadowRoot.querySelectorAll('*');
5033
+ shadowCustomElements.forEach(el => {
5034
+ if (el.tagName.includes('-')) {
5035
+ customElements.push(el);
5036
+ }
5037
+ });
5038
+ }
5039
+ }
5040
+ // If it's a DocumentFragment, check all children
5041
+ if (node instanceof DocumentFragment) {
5042
+ const elements = node.querySelectorAll('*');
5043
+ elements.forEach(el => {
5044
+ if (el.tagName.includes('-')) {
5045
+ customElements.push(el);
5046
+ }
5047
+ });
5048
+ }
5049
+ // Wait for all custom elements to be ready
5050
+ await Promise.all(customElements.map(el => waitForElementReady(el, warningTimeout)));
5051
+ }
5052
+
5053
+ /**
5054
+ * Render debugging utilities for Snice v3.0.0
5055
+ * For testing and debugging only - not recommended for production use
5056
+ */
5057
+ /**
5058
+ * Track renders of an element using an async generator
5059
+ * Each call to tracker.next() waits for the next render to complete
5060
+ *
5061
+ * @example
5062
+ * ```typescript
5063
+ * const tracker = trackRenders(element);
5064
+ *
5065
+ * element.someProp = 'new value';
5066
+ * await tracker.next(); // Waits for render
5067
+ * // DOM is now updated
5068
+ *
5069
+ * element.someProp = 'another value';
5070
+ * await tracker.next(); // Waits for next render
5071
+ * // DOM is updated again
5072
+ * ```
5073
+ *
5074
+ * WARNING: For testing/debugging only!
5075
+ * - Do not use in production code
5076
+ * - The generator yields indefinitely - use it only in controlled test environments
5077
+ * - Each yield waits for the next render event
5078
+ */
5079
+ async function* trackRenders(element) {
5080
+ while (true) {
5081
+ await new Promise(resolve => {
5082
+ if (!element[RENDER_CALLBACKS]) {
5083
+ element[RENDER_CALLBACKS] = [];
5084
+ }
5085
+ element[RENDER_CALLBACKS].push(resolve);
5086
+ });
5087
+ yield;
5088
+ }
5089
+ }
5090
+
5091
+ /**
5092
+ * Method decorators for common patterns
5093
+ * @debounce, @throttle, @once, @memoize
5094
+ */
5095
+ const DEBOUNCE_TIMERS = getSymbol('debounce-timers');
5096
+ const THROTTLE_TIMERS = getSymbol('throttle-timers');
5097
+ const ONCE_CALLED = getSymbol('once-called');
5098
+ const MEMOIZE_CACHE = getSymbol('memoize-cache');
5099
+ /**
5100
+ * @debounce decorator - delays function execution until after wait time has elapsed
5101
+ * since the last invocation
5102
+ *
5103
+ * @param wait - Time to wait in milliseconds (default: 300)
5104
+ * @param options - Debounce options
5105
+ * @param options.leading - Invoke on the leading edge (default: false)
5106
+ * @param options.trailing - Invoke on the trailing edge (default: true)
5107
+ * @param options.maxWait - Maximum time to wait before invoking (default: undefined)
5108
+ *
5109
+ * @example
5110
+ * ```typescript
5111
+ * @element('search-input')
5112
+ * class SearchInput extends HTMLElement {
5113
+ * @debounce(500)
5114
+ * handleSearch(query: string) {
5115
+ * // Only called 500ms after last keystroke
5116
+ * fetch(`/api/search?q=${query}`);
5117
+ * }
5118
+ * }
5119
+ * ```
5120
+ */
5121
+ function debounce(wait = 300, options = {}) {
5122
+ const { leading = false, trailing = true, maxWait } = options;
5123
+ return function (originalMethod, context) {
5124
+ const methodName = context.name;
5125
+ return function (...args) {
5126
+ if (!this[DEBOUNCE_TIMERS]) {
5127
+ this[DEBOUNCE_TIMERS] = {};
5128
+ }
5129
+ const timers = this[DEBOUNCE_TIMERS];
5130
+ const timerKey = methodName;
5131
+ // Clear existing timer
5132
+ if (timers[timerKey]) {
5133
+ clearTimeout(timers[timerKey].timeout);
5134
+ }
5135
+ // Track when debounce started for maxWait
5136
+ const now = Date.now();
5137
+ const isFirstCall = !timers[timerKey];
5138
+ const startTime = isFirstCall ? now : timers[timerKey].startTime;
5139
+ // Check if maxWait exceeded
5140
+ const shouldInvokeFromMaxWait = maxWait !== undefined && now - startTime >= maxWait;
5141
+ // Leading edge invocation
5142
+ if (leading && isFirstCall) {
5143
+ const result = originalMethod.apply(this, args);
5144
+ timers[timerKey] = {
5145
+ timeout: null,
5146
+ startTime,
5147
+ lastArgs: args,
5148
+ };
5149
+ return result;
5150
+ }
5151
+ // Set new timer for trailing edge
5152
+ const timeout = setTimeout(() => {
5153
+ if (trailing || shouldInvokeFromMaxWait) {
5154
+ originalMethod.apply(this, timers[timerKey].lastArgs);
5155
+ }
5156
+ delete timers[timerKey];
5157
+ }, shouldInvokeFromMaxWait ? 0 : wait);
5158
+ timers[timerKey] = {
5159
+ timeout,
5160
+ startTime,
5161
+ lastArgs: args,
5162
+ };
5163
+ };
5164
+ };
5165
+ }
5166
+ /**
5167
+ * @throttle decorator - ensures function is called at most once per specified time period
5168
+ *
5169
+ * @param wait - Time to wait in milliseconds (default: 300)
5170
+ * @param options - Throttle options
5171
+ * @param options.leading - Invoke on the leading edge (default: true)
5172
+ * @param options.trailing - Invoke on the trailing edge (default: true)
5173
+ *
5174
+ * @example
5175
+ * ```typescript
5176
+ * @element('scroll-tracker')
5177
+ * class ScrollTracker extends HTMLElement {
5178
+ * @throttle(100)
5179
+ * handleScroll(e: Event) {
5180
+ * // Called at most once every 100ms
5181
+ * this.updateScrollPosition();
5182
+ * }
5183
+ * }
5184
+ * ```
5185
+ */
5186
+ function throttle(wait = 300, options = {}) {
5187
+ const { leading = true, trailing = true } = options;
5188
+ return function (originalMethod, context) {
5189
+ const methodName = context.name;
5190
+ return function (...args) {
5191
+ if (!this[THROTTLE_TIMERS]) {
5192
+ this[THROTTLE_TIMERS] = {};
5193
+ }
5194
+ const timers = this[THROTTLE_TIMERS];
5195
+ const timerKey = methodName;
5196
+ const now = Date.now();
5197
+ if (!timers[timerKey]) {
5198
+ // First call
5199
+ if (leading) {
5200
+ originalMethod.apply(this, args);
5201
+ }
5202
+ timers[timerKey] = {
5203
+ lastInvoke: now,
5204
+ timeout: null,
5205
+ lastArgs: args,
5206
+ };
5207
+ if (trailing && !leading) {
5208
+ // If no leading edge, set up trailing
5209
+ timers[timerKey].timeout = setTimeout(() => {
5210
+ originalMethod.apply(this, timers[timerKey].lastArgs);
5211
+ delete timers[timerKey];
5212
+ }, wait);
5213
+ }
5214
+ }
5215
+ else {
5216
+ // Subsequent calls
5217
+ const timeSinceLastInvoke = now - timers[timerKey].lastInvoke;
5218
+ // Update last args
5219
+ timers[timerKey].lastArgs = args;
5220
+ // Clear any pending trailing call
5221
+ if (timers[timerKey].timeout) {
5222
+ clearTimeout(timers[timerKey].timeout);
5223
+ }
5224
+ if (timeSinceLastInvoke >= wait) {
5225
+ // Enough time has passed, invoke immediately
5226
+ originalMethod.apply(this, args);
5227
+ timers[timerKey].lastInvoke = now;
5228
+ }
5229
+ else if (trailing) {
5230
+ // Set up trailing call
5231
+ const remaining = wait - timeSinceLastInvoke;
5232
+ timers[timerKey].timeout = setTimeout(() => {
5233
+ originalMethod.apply(this, timers[timerKey].lastArgs);
5234
+ timers[timerKey].lastInvoke = Date.now();
5235
+ timers[timerKey].timeout = null;
5236
+ }, remaining);
5237
+ }
5238
+ }
5239
+ };
5240
+ };
5241
+ }
5242
+ /**
5243
+ * @once decorator - ensures function is only called once
5244
+ * Subsequent calls return the result of the first call
5245
+ *
5246
+ * @param perInstance - If true, function can be called once per instance (default: true)
5247
+ * If false, function can only be called once globally across all instances
5248
+ *
5249
+ * @example
5250
+ * ```typescript
5251
+ * @element('data-loader')
5252
+ * class DataLoader extends HTMLElement {
5253
+ * @once()
5254
+ * async loadData() {
5255
+ * // Only loads data once, even if called multiple times
5256
+ * const data = await fetch('/api/data');
5257
+ * return data.json();
5258
+ * }
5259
+ * }
5260
+ * ```
5261
+ */
5262
+ function once(perInstance = true) {
5263
+ let globalCalled = false;
5264
+ let globalResult;
5265
+ return function (originalMethod, context) {
5266
+ const methodName = context.name;
5267
+ return function (...args) {
5268
+ if (perInstance) {
5269
+ // Per-instance tracking
5270
+ if (!this[ONCE_CALLED]) {
5271
+ this[ONCE_CALLED] = {};
5272
+ }
5273
+ if (!this[ONCE_CALLED][methodName]) {
5274
+ this[ONCE_CALLED][methodName] = {
5275
+ called: true,
5276
+ result: originalMethod.apply(this, args),
5277
+ };
5278
+ }
5279
+ return this[ONCE_CALLED][methodName].result;
5280
+ }
5281
+ else {
5282
+ // Global tracking
5283
+ if (!globalCalled) {
5284
+ globalCalled = true;
5285
+ globalResult = originalMethod.apply(this, args);
5286
+ }
5287
+ return globalResult;
5288
+ }
5289
+ };
5290
+ };
5291
+ }
5292
+ /**
5293
+ * @memoize decorator - caches function results based on arguments
5294
+ * Uses JSON.stringify for argument comparison by default
5295
+ *
5296
+ * @param options - Memoization options
5297
+ * @param options.keyGenerator - Custom function to generate cache key from arguments
5298
+ * @param options.maxSize - Maximum cache size (default: 100)
5299
+ * @param options.ttl - Time to live in milliseconds (default: undefined - no expiration)
5300
+ *
5301
+ * @example
5302
+ * ```typescript
5303
+ * @element('calculator')
5304
+ * class Calculator extends HTMLElement {
5305
+ * @memoize({ maxSize: 50 })
5306
+ * fibonacci(n: number): number {
5307
+ * // Results are cached, subsequent calls with same n are instant
5308
+ * if (n <= 1) return n;
5309
+ * return this.fibonacci(n - 1) + this.fibonacci(n - 2);
5310
+ * }
5311
+ * }
5312
+ * ```
5313
+ */
5314
+ function memoize(options = {}) {
5315
+ const { keyGenerator = (...args) => JSON.stringify(args), maxSize = 100, ttl } = options;
5316
+ return function (originalMethod, context) {
5317
+ const methodName = context.name;
5318
+ return function (...args) {
5319
+ if (!this[MEMOIZE_CACHE]) {
5320
+ this[MEMOIZE_CACHE] = {};
5321
+ }
5322
+ if (!this[MEMOIZE_CACHE][methodName]) {
5323
+ this[MEMOIZE_CACHE][methodName] = new Map();
5324
+ }
5325
+ const cache = this[MEMOIZE_CACHE][methodName];
5326
+ const key = keyGenerator(...args);
5327
+ // Check if cached
5328
+ if (cache.has(key)) {
5329
+ const cached = cache.get(key);
5330
+ // Check TTL
5331
+ if (ttl !== undefined) {
5332
+ const age = Date.now() - cached.timestamp;
5333
+ if (age > ttl) {
5334
+ cache.delete(key);
5335
+ }
5336
+ else {
5337
+ return cached.value;
5338
+ }
5339
+ }
5340
+ else {
5341
+ return cached.value;
5342
+ }
5343
+ }
5344
+ // Compute result
5345
+ const result = originalMethod.apply(this, args);
5346
+ // Store in cache
5347
+ cache.set(key, {
5348
+ value: result,
5349
+ timestamp: Date.now(),
5350
+ });
5351
+ // Enforce max size (LRU - delete oldest)
5352
+ if (cache.size > maxSize) {
5353
+ const firstKey = cache.keys().next().value;
5354
+ cache.delete(firstKey);
5355
+ }
5356
+ return result;
5357
+ };
5358
+ };
5359
+ }
5360
+ /**
5361
+ * Clear all debounce timers for an instance
5362
+ * Useful in cleanup/disconnectedCallback
5363
+ */
5364
+ function clearDebounceTimers(instance) {
5365
+ if (instance[DEBOUNCE_TIMERS]) {
5366
+ for (const timerKey in instance[DEBOUNCE_TIMERS]) {
5367
+ if (instance[DEBOUNCE_TIMERS][timerKey]?.timeout) {
5368
+ clearTimeout(instance[DEBOUNCE_TIMERS][timerKey].timeout);
5369
+ }
5370
+ }
5371
+ instance[DEBOUNCE_TIMERS] = {};
5372
+ }
5373
+ }
5374
+ /**
5375
+ * Clear all throttle timers for an instance
5376
+ * Useful in cleanup/disconnectedCallback
5377
+ */
5378
+ function clearThrottleTimers(instance) {
5379
+ if (instance[THROTTLE_TIMERS]) {
5380
+ for (const timerKey in instance[THROTTLE_TIMERS]) {
5381
+ if (instance[THROTTLE_TIMERS][timerKey]?.timeout) {
5382
+ clearTimeout(instance[THROTTLE_TIMERS][timerKey].timeout);
5383
+ }
5384
+ }
5385
+ instance[THROTTLE_TIMERS] = {};
5386
+ }
5387
+ }
5388
+ /**
5389
+ * Clear memoize cache for an instance
5390
+ */
5391
+ function clearMemoizeCache(instance, methodName) {
5392
+ if (instance[MEMOIZE_CACHE]) {
5393
+ if (methodName) {
5394
+ delete instance[MEMOIZE_CACHE][methodName];
5395
+ }
5396
+ else {
5397
+ instance[MEMOIZE_CACHE] = {};
5398
+ }
5399
+ }
5400
+ }
5401
+ /**
5402
+ * Reset once-called state for an instance
5403
+ */
5404
+ function resetOnce(instance, methodName) {
5405
+ if (instance[ONCE_CALLED]) {
5406
+ if (methodName) {
5407
+ delete instance[ONCE_CALLED][methodName];
5408
+ }
5409
+ else {
5410
+ instance[ONCE_CALLED] = {};
5411
+ }
5412
+ }
5413
+ }
5414
+
5415
+ export { Context, IS_CONTROLLER_INSTANCE, Router, SimpleArray, adopted, applyElementFunctionality, clearDebounceTimers, clearMemoizeCache, clearThrottleTimers, context$1 as context, context as contextProperty, controller, css, debounce, dispatch, dispose, element, getSymbol, html, layout, memoize, moved, nothing, observe, on, once, property, query, queryAll, ready, render, request, resetOnce, respond, setDisableElementReadyWarnings, styles, throttle, trackRenders, unsafeHTML, useNativeElementControllers, waitForAllCustomElements, waitForElementDefined, waitForElementReady, watch };
3452
5416
  //# sourceMappingURL=index.esm.js.map