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