@aceshooting/lyra-ui 14.0.0 → 14.1.1

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 (475) hide show
  1. package/CHANGELOG.md +155 -19
  2. package/custom-elements.json +1 -1
  3. package/dist/components/agent-tools/commit-card/commit-card.class.d.ts +3 -1
  4. package/dist/components/agent-tools/commit-card/commit-card.class.js +2 -2
  5. package/dist/components/agent-tools/compare-panel/compare-panel.class.d.ts +2 -1
  6. package/dist/components/agent-tools/compare-panel/compare-panel.styles.js +1 -1
  7. package/dist/components/agent-tools/prompt-studio/prompt-studio.class.d.ts +6 -2
  8. package/dist/components/agent-tools/prompt-studio/prompt-studio.class.js +4 -4
  9. package/dist/components/agent-tools/result-card/result-card.class.d.ts +1 -1
  10. package/dist/components/agent-tools/result-card/result-card.class.js +1 -1
  11. package/dist/components/agent-tools/result-card/result-field.class.d.ts +1 -1
  12. package/dist/components/agent-tools/result-card/result-field.class.js +1 -1
  13. package/dist/components/agent-tools/stack-trace/stack-trace.class.d.ts +1 -1
  14. package/dist/components/agent-tools/stack-trace/stack-trace.class.js +1 -1
  15. package/dist/components/agent-tools/terminal/terminal.class.d.ts +1 -1
  16. package/dist/components/agent-tools/terminal/terminal.class.js +2 -2
  17. package/dist/components/agent-tools/tool-call-chip/tool-call-chip.class.d.ts +2 -2
  18. package/dist/components/agent-tools/tool-call-chip/tool-call-chip.class.js +1 -1
  19. package/dist/components/agent-tools/tool-param-form/tool-param-form.class.js +1 -1
  20. package/dist/components/agent-tools/tool-result-dialog/tool-result-dialog.class.js +2 -2
  21. package/dist/components/agent-tools/tool-select-dialog/tool-select-dialog.class.js +4 -4
  22. package/dist/components/agent-tools/trace-tree/span.d.ts +3 -1
  23. package/dist/components/agent-tools/trace-tree/span.js +1 -1
  24. package/dist/components/charts/chart/box-plot.class.d.ts +2 -0
  25. package/dist/components/charts/chart/box-plot.class.js +1 -1
  26. package/dist/components/charts/chart/chart.class.d.ts +6 -1
  27. package/dist/components/charts/chart/chart.class.js +1 -1
  28. package/dist/components/charts/chart/lite-chart.class.d.ts +20 -11
  29. package/dist/components/charts/chart/lite-chart.class.js +10 -8
  30. package/dist/components/conversation/chat-message/chat-message.class.d.ts +4 -3
  31. package/dist/components/conversation/code-block/code-block-core.class.d.ts +4 -3
  32. package/dist/components/conversation/code-block/code-block-core.class.js +1 -1
  33. package/dist/components/conversation/code-block/code-block-shared.d.ts +3 -3
  34. package/dist/components/conversation/code-block/code-block-shared.js +2 -2
  35. package/dist/components/conversation/code-block/code-block.class.d.ts +4 -3
  36. package/dist/components/conversation/code-block/code-block.class.js +1 -1
  37. package/dist/components/conversation/code-block/shiki-types.d.ts +2 -0
  38. package/dist/components/conversation/code-block/shiki-types.js +1 -1
  39. package/dist/components/conversation/conversation-item/conversation-item.class.js +1 -1
  40. package/dist/components/conversation/markdown/markdown-base.class.js +1 -1
  41. package/dist/components/conversation/markdown/markdown-core.class.d.ts +1 -1
  42. package/dist/components/conversation/markdown/markdown.class.d.ts +1 -1
  43. package/dist/components/conversation/message-actions/message-actions.class.d.ts +2 -0
  44. package/dist/components/conversation/message-actions/message-actions.class.js +1 -1
  45. package/dist/components/conversation/message-feedback/message-feedback.class.d.ts +3 -1
  46. package/dist/components/conversation/message-feedback/message-feedback.class.js +2 -2
  47. package/dist/components/conversation/message-parts/message-parts.class.d.ts +3 -0
  48. package/dist/components/conversation/model-select/model-select.class.js +3 -3
  49. package/dist/components/conversation/thread-list/thread-list.class.js +1 -1
  50. package/dist/components/conversation/transcript-feed/transcript-feed.class.d.ts +2 -0
  51. package/dist/components/conversation/transcript-feed/transcript-feed.class.js +1 -1
  52. package/dist/components/conversation/typing-indicator/typing-indicator.class.d.ts +2 -1
  53. package/dist/components/conversation/typing-indicator/typing-indicator.class.js +1 -1
  54. package/dist/components/conversation/usage-badge/usage-badge-overlay-runtime.d.ts +3 -0
  55. package/dist/components/conversation/usage-badge/usage-badge-overlay-runtime.js +1 -0
  56. package/dist/components/conversation/usage-badge/usage-badge.class.d.ts +4 -2
  57. package/dist/components/conversation/usage-badge/usage-badge.class.js +1 -1
  58. package/dist/components/conversation/voice-picker/voice-picker.class.js +3 -3
  59. package/dist/components/conversation/widget-renderer/resolve.d.ts +4 -6
  60. package/dist/components/conversation/widget-renderer/resolve.js +1 -1
  61. package/dist/components/data/calendar/calendar.class.d.ts +6 -3
  62. package/dist/components/data/calendar/calendar.class.js +1 -1
  63. package/dist/components/data/calendar/calendar.styles.js +1 -1
  64. package/dist/components/data/condition-builder/condition-builder.class.d.ts +3 -1
  65. package/dist/components/data/condition-builder/condition-builder.class.js +15 -1
  66. package/dist/components/data/context-meter/context-meter.class.js +2 -2
  67. package/dist/components/data/data-grid/data-grid.class.d.ts +6 -2
  68. package/dist/components/data/data-grid/data-grid.class.js +1 -1
  69. package/dist/components/data/document-library/document-library.class.d.ts +5 -2
  70. package/dist/components/data/document-library/document-library.class.js +1 -1
  71. package/dist/components/data/file-tree/file-tree.class.d.ts +2 -1
  72. package/dist/components/data/file-tree/file-tree.class.js +1 -1
  73. package/dist/components/data/flow-canvas/flow-canvas.class.d.ts +5 -2
  74. package/dist/components/data/flow-canvas/flow-canvas.styles.js +1 -1
  75. package/dist/components/data/flow-canvas/flow-model.js +1 -1
  76. package/dist/components/data/flow-canvas/flow-types.d.ts +2 -1
  77. package/dist/components/data/funnel/funnel.class.d.ts +1 -0
  78. package/dist/components/data/funnel/funnel.class.js +1 -1
  79. package/dist/components/data/gauge/gauge.class.d.ts +4 -1
  80. package/dist/components/data/gauge/gauge.class.js +6 -6
  81. package/dist/components/data/graph-query-builder/graph-query-builder.class.d.ts +5 -2
  82. package/dist/components/data/graph-query-builder/graph-query-builder.class.js +15 -1
  83. package/dist/components/data/heatmap/heatmap.class.d.ts +7 -4
  84. package/dist/components/data/heatmap/heatmap.class.js +1 -1
  85. package/dist/components/data/sparkline/sparkline.class.d.ts +2 -1
  86. package/dist/components/data/sparkline/sparkline.class.js +1 -1
  87. package/dist/components/data/stat/stat.class.d.ts +6 -2
  88. package/dist/components/data/stat/stat.class.js +1 -1
  89. package/dist/components/data/table/table.class.d.ts +5 -2
  90. package/dist/components/data/table/table.class.js +2 -2
  91. package/dist/components/data/timeline/timeline.class.d.ts +7 -2
  92. package/dist/components/data/timeline/timeline.class.js +1 -1
  93. package/dist/components/data/timeline/timeline.styles.js +1 -1
  94. package/dist/components/data/tree/tree-item.class.d.ts +3 -1
  95. package/dist/components/data/tree/tree-item.class.js +1 -1
  96. package/dist/components/data/tree/tree.class.d.ts +4 -1
  97. package/dist/components/data/tree/tree.class.js +1 -1
  98. package/dist/components/data/word-cloud/word-cloud-layout.d.ts +2 -1
  99. package/dist/components/data/word-cloud/word-cloud-layout.js +1 -1
  100. package/dist/components/data/word-cloud/word-cloud.class.d.ts +2 -1
  101. package/dist/components/forms/button/button.class.d.ts +5 -3
  102. package/dist/components/forms/button/button.class.js +1 -1
  103. package/dist/components/forms/checkbox/checkbox.class.d.ts +3 -0
  104. package/dist/components/forms/checkbox/checkbox.class.js +1 -1
  105. package/dist/components/forms/code-editor/code-editor.class.d.ts +11 -3
  106. package/dist/components/forms/code-editor/code-editor.class.js +6 -7
  107. package/dist/components/forms/code-editor/code-editor.styles.js +1 -1
  108. package/dist/components/forms/color-picker/color-picker.class.d.ts +5 -1
  109. package/dist/components/forms/color-picker/color-picker.class.js +4 -4
  110. package/dist/components/forms/combobox/combobox.class.d.ts +19 -8
  111. package/dist/components/forms/combobox/combobox.class.js +3 -3
  112. package/dist/components/forms/combobox/option.class.d.ts +4 -0
  113. package/dist/components/forms/combobox/option.class.js +2 -2
  114. package/dist/components/forms/date-picker/calendar-core.d.ts +1 -1
  115. package/dist/components/forms/date-picker/calendar-core.js +1 -1
  116. package/dist/components/forms/date-picker/date-input.class.d.ts +20 -10
  117. package/dist/components/forms/date-picker/date-input.class.js +4 -4
  118. package/dist/components/forms/date-picker/date-picker.class.d.ts +24 -13
  119. package/dist/components/forms/date-picker/date-picker.class.js +7 -7
  120. package/dist/components/forms/date-picker/date-picker.styles.js +1 -1
  121. package/dist/components/forms/emoji-picker/emoji-picker.class.d.ts +11 -3
  122. package/dist/components/forms/emoji-picker/emoji-picker.class.js +3 -3
  123. package/dist/components/forms/emoji-picker/emoji-types.d.ts +2 -2
  124. package/dist/components/forms/icon-button/icon-button.class.d.ts +4 -2
  125. package/dist/components/forms/icon-button/icon-button.class.js +1 -1
  126. package/dist/components/forms/input/input.class.d.ts +5 -1
  127. package/dist/components/forms/input/input.class.js +1 -1
  128. package/dist/components/forms/input/native-time-input.class.d.ts +3 -0
  129. package/dist/components/forms/input/number-input.class.d.ts +3 -0
  130. package/dist/components/forms/input/time-input.class.d.ts +3 -0
  131. package/dist/components/forms/input/time-input.class.js +1 -1
  132. package/dist/components/forms/locale-picker/locale-picker.class.d.ts +5 -1
  133. package/dist/components/forms/locale-picker/locale-picker.class.js +2 -2
  134. package/dist/components/forms/otp-input/otp-input.class.d.ts +5 -1
  135. package/dist/components/forms/otp-input/otp-input.class.js +1 -1
  136. package/dist/components/forms/phone-input/phone-input.class.d.ts +21 -8
  137. package/dist/components/forms/phone-input/phone-input.class.js +1 -1
  138. package/dist/components/forms/radio/radio-button.class.d.ts +4 -0
  139. package/dist/components/forms/radio/radio-group.class.d.ts +4 -1
  140. package/dist/components/forms/radio/radio-group.class.js +1 -1
  141. package/dist/components/forms/radio/radio.class.d.ts +6 -2
  142. package/dist/components/forms/radio/radio.class.js +1 -1
  143. package/dist/components/forms/rubric-form/rubric-form.class.d.ts +7 -1
  144. package/dist/components/forms/rubric-form/rubric-form.class.js +3 -3
  145. package/dist/components/forms/select/select.class.d.ts +8 -2
  146. package/dist/components/forms/select/select.class.js +2 -2
  147. package/dist/components/forms/slider/slider.class.d.ts +12 -6
  148. package/dist/components/forms/slider/slider.class.js +2 -2
  149. package/dist/components/forms/swatch-picker/swatch-picker.class.d.ts +4 -0
  150. package/dist/components/forms/swatch-picker/swatch-picker.class.js +1 -1
  151. package/dist/components/forms/switch/switch.class.d.ts +5 -1
  152. package/dist/components/forms/switch/switch.class.js +1 -1
  153. package/dist/components/forms/textarea/textarea.class.d.ts +3 -0
  154. package/dist/components/forms/textarea/textarea.class.js +1 -1
  155. package/dist/components/forms/time-range/time-range.class.d.ts +3 -0
  156. package/dist/components/forms/time-range/time-range.class.js +1 -1
  157. package/dist/components/forms/token-input/token-input.class.d.ts +8 -2
  158. package/dist/components/forms/token-input/token-input.class.js +2 -2
  159. package/dist/components/forms/token-input/token-input.styles.js +1 -1
  160. package/dist/components/layout/app-rail/app-rail.class.d.ts +3 -1
  161. package/dist/components/layout/app-rail/app-rail.class.js +1 -1
  162. package/dist/components/layout/carousel/carousel.class.d.ts +3 -2
  163. package/dist/components/layout/carousel/carousel.class.js +1 -1
  164. package/dist/components/layout/command-palette/command-palette.class.js +1 -1
  165. package/dist/components/layout/dashboard-grid/dashboard-grid.class.d.ts +2 -0
  166. package/dist/components/layout/dashboard-grid/dashboard-grid.class.js +1 -1
  167. package/dist/components/layout/details/details.class.d.ts +3 -3
  168. package/dist/components/layout/filter-bar/filter-bar.class.d.ts +3 -1
  169. package/dist/components/layout/filter-bar/filter-bar.class.js +1 -1
  170. package/dist/components/layout/menu/menu-label.class.d.ts +3 -3
  171. package/dist/components/layout/menu/menu.class.d.ts +4 -1
  172. package/dist/components/layout/menu/menu.class.js +1 -1
  173. package/dist/components/layout/multi-split/multi-split.class.d.ts +9 -3
  174. package/dist/components/layout/multi-split/multi-split.class.js +1 -1
  175. package/dist/components/layout/multi-split/multi-split.styles.js +1 -1
  176. package/dist/components/layout/reorder-list/reorder-item.class.d.ts +2 -1
  177. package/dist/components/layout/reorder-list/reorder-item.class.js +1 -1
  178. package/dist/components/layout/reorder-list/reorder-list.class.js +1 -1
  179. package/dist/components/layout/reorder-list/reorder-owner.js +1 -1
  180. package/dist/components/layout/split-panel/split-panel.class.d.ts +2 -1
  181. package/dist/components/layout/split-panel/split-panel.class.js +1 -1
  182. package/dist/components/layout/tab-group/tab-group.class.d.ts +3 -1
  183. package/dist/components/layout/tab-group/tab-group.class.js +1 -1
  184. package/dist/components/layout/widget/widget.class.d.ts +6 -2
  185. package/dist/components/layout/widget/widget.class.js +1 -1
  186. package/dist/components/media/animation/animation.class.d.ts +3 -2
  187. package/dist/components/media/animation/animation.class.js +1 -1
  188. package/dist/components/media/attachment-chip/attachment-chip.class.d.ts +4 -3
  189. package/dist/components/media/attachment-chip/attachment-chip.class.js +1 -1
  190. package/dist/components/media/av-player/av-metadata.d.ts +3 -2
  191. package/dist/components/media/av-player/av-player.class.d.ts +4 -3
  192. package/dist/components/media/av-player/av-player.class.js +3 -3
  193. package/dist/components/media/av-player/av-player.styles.js +1 -1
  194. package/dist/components/media/avatar/avatar.class.d.ts +2 -1
  195. package/dist/components/media/avatar/avatar.class.js +1 -1
  196. package/dist/components/media/file-input/file-input.class.d.ts +4 -2
  197. package/dist/components/media/file-input/file-input.class.js +1 -1
  198. package/dist/components/media/file-input/file-input.styles.js +1 -1
  199. package/dist/components/media/image-viewer/image-viewer.class.d.ts +2 -1
  200. package/dist/components/media/image-viewer/image-viewer.class.js +1 -1
  201. package/dist/components/media/image-viewer/image-viewer.styles.js +1 -1
  202. package/dist/components/media/map/map.class.d.ts +5 -3
  203. package/dist/components/media/map/map.class.js +1 -1
  204. package/dist/components/media/map/map.styles.js +1 -1
  205. package/dist/components/media/media-card/media-card.class.d.ts +1 -1
  206. package/dist/components/media/media-card/media-card.class.js +1 -1
  207. package/dist/components/media/pan-zoom/pan-zoom.class.js +1 -1
  208. package/dist/components/media/sequence-playback/sequence-playback.class.d.ts +1 -1
  209. package/dist/components/media/sequence-playback/sequence-playback.styles.js +1 -1
  210. package/dist/components/media/video/video.class.d.ts +2 -1
  211. package/dist/components/media/video/video.styles.js +1 -1
  212. package/dist/components/media/zoomable-frame/zoomable-frame.class.d.ts +3 -2
  213. package/dist/components/media/zoomable-frame/zoomable-frame.class.js +2 -2
  214. package/dist/components/overlays/chip/chip-group.class.d.ts +2 -0
  215. package/dist/components/overlays/chip/chip-group.class.js +1 -1
  216. package/dist/components/overlays/dialog/dialog.class.d.ts +2 -0
  217. package/dist/components/overlays/dialog/dialog.class.js +1 -1
  218. package/dist/components/overlays/empty/empty.class.d.ts +2 -0
  219. package/dist/components/overlays/empty/empty.class.js +1 -1
  220. package/dist/components/overlays/kbd/kbd.class.d.ts +2 -0
  221. package/dist/components/overlays/kbd/kbd.class.js +1 -1
  222. package/dist/components/overlays/overlay/popover.class.d.ts +3 -1
  223. package/dist/components/overlays/overlay/popover.class.js +1 -1
  224. package/dist/components/overlays/overlay/tooltip.class.d.ts +3 -1
  225. package/dist/components/overlays/overlay/tooltip.class.js +1 -1
  226. package/dist/components/overlays/rating/rating.class.d.ts +2 -0
  227. package/dist/components/overlays/rating/rating.class.js +1 -1
  228. package/dist/components/retrieval/embedding-explorer/embedding-explorer.class.js +2 -2
  229. package/dist/components/retrieval/entity-card/entity-card.class.d.ts +5 -2
  230. package/dist/components/retrieval/entity-card/entity-card.class.js +1 -1
  231. package/dist/components/retrieval/entity-chip/entity-chip.class.d.ts +4 -2
  232. package/dist/components/retrieval/entity-chip/entity-chip.class.js +1 -1
  233. package/dist/components/retrieval/graph/graph-canvas.js +1 -1
  234. package/dist/components/retrieval/graph/graph.class.d.ts +9 -7
  235. package/dist/components/retrieval/graph/graph.class.js +1 -1
  236. package/dist/components/retrieval/grounding-summary/grounding-summary.class.d.ts +1 -3
  237. package/dist/components/retrieval/ingestion-queue/ingestion-queue.class.d.ts +2 -0
  238. package/dist/components/retrieval/ingestion-queue/ingestion-queue.class.js +1 -1
  239. package/dist/components/retrieval/knowledge-graph-explorer/knowledge-graph-explorer.class.d.ts +3 -2
  240. package/dist/components/retrieval/knowledge-graph-explorer/knowledge-graph-explorer.class.js +7 -3
  241. package/dist/components/retrieval/provenance-panel/provenance-panel.class.d.ts +2 -1
  242. package/dist/components/retrieval/provenance-panel/provenance-panel.class.js +1 -1
  243. package/dist/components/retrieval/source-picker/source-picker.class.d.ts +2 -1
  244. package/dist/components/retrieval/source-picker/source-picker.class.js +1 -1
  245. package/dist/components/utility/format/format-number.class.d.ts +3 -1
  246. package/dist/components/utility/format/format-options.js +1 -1
  247. package/dist/components/utility/json-viewer/json-viewer.class.d.ts +3 -2
  248. package/dist/components/utility/json-viewer/json-viewer.class.js +2 -2
  249. package/dist/components/utility/known-date/known-date.class.d.ts +9 -5
  250. package/dist/components/utility/known-date/known-date.class.js +2 -2
  251. package/dist/components/utility/known-date/known-date.styles.js +1 -1
  252. package/dist/components/utility/mention-popover/mention-popover.class.d.ts +3 -1
  253. package/dist/components/utility/mention-popover/mention-popover.class.js +1 -1
  254. package/dist/components/utility/poll-status/poll-status.class.d.ts +3 -0
  255. package/dist/components/utility/poll-status/poll-status.styles.js +1 -1
  256. package/dist/components/viewers/calendar-viewer/calendar-viewer.class.d.ts +1 -0
  257. package/dist/components/viewers/calendar-viewer/calendar-viewer.class.js +1 -1
  258. package/dist/components/viewers/dataset-viewer/dataset-viewer.class.d.ts +2 -1
  259. package/dist/components/viewers/dataset-viewer/dataset-viewer.styles.js +1 -1
  260. package/dist/components/viewers/document-preview/document-preview.class.d.ts +4 -2
  261. package/dist/components/viewers/document-preview/document-preview.class.js +1 -1
  262. package/dist/components/viewers/document-preview/document-preview.styles.js +1 -1
  263. package/dist/components/viewers/document-viewer/document-viewer.class.d.ts +3 -2
  264. package/dist/components/viewers/document-viewer/document-viewer.class.js +2 -2
  265. package/dist/components/viewers/document-viewer/registry-ownership.d.ts +1 -0
  266. package/dist/components/viewers/document-viewer/registry-ownership.js +1 -0
  267. package/dist/components/viewers/document-viewer/registry.js +1 -1
  268. package/dist/components/viewers/ebook-viewer/ebook-viewer.class.d.ts +7 -1
  269. package/dist/components/viewers/ebook-viewer/ebook-viewer.class.js +1 -1
  270. package/dist/components/viewers/email-viewer/email-viewer.class.d.ts +2 -1
  271. package/dist/components/viewers/email-viewer/email-viewer.class.js +2 -2
  272. package/dist/components/viewers/include/include-resource.js +1 -1
  273. package/dist/components/viewers/include/include.class.d.ts +3 -1
  274. package/dist/components/viewers/notebook-viewer/notebook-viewer.class.d.ts +4 -2
  275. package/dist/components/viewers/notebook-viewer/notebook-viewer.class.js +4 -4
  276. package/dist/components/viewers/notebook-viewer/notebook-viewer.styles.js +1 -1
  277. package/dist/components/viewers/passive-markup.js +1 -1
  278. package/dist/components/viewers/svg-viewer/svg-viewer.class.d.ts +2 -1
  279. package/dist/components/viewers/svg-viewer/svg-viewer.styles.js +1 -1
  280. package/dist/components/viewers/xml-viewer/xml-viewer.class.d.ts +2 -1
  281. package/dist/components/viewers/xml-viewer/xml-viewer.class.js +1 -1
  282. package/dist/components/viewers/xml-viewer/xml-viewer.js +1 -1
  283. package/dist/custom-elements-jsx.d.ts +1 -1
  284. package/dist/internal/aria-reflection.js +1 -1
  285. package/dist/internal/catalog-picker.js +1 -1
  286. package/dist/internal/default-strings.generated.d.ts +1 -1
  287. package/dist/internal/default-strings.generated.js +1 -1
  288. package/dist/internal/dev-mode-attribute-warning.d.ts +3 -0
  289. package/dist/internal/dev-mode-attribute-warning.js +1 -1
  290. package/dist/internal/form-associated.js +1 -1
  291. package/dist/internal/localization-types.d.ts +1 -1
  292. package/dist/internal/localization.js +1 -1
  293. package/dist/internal/lyra-element.js +1 -1
  294. package/dist/internal/native-control-description.d.ts +7 -0
  295. package/dist/internal/native-control-description.js +1 -0
  296. package/dist/internal/option-selection.js +1 -1
  297. package/dist/internal/overlay-order.d.ts +6 -0
  298. package/dist/internal/overlay-order.js +1 -0
  299. package/dist/internal/overlay-stack.d.ts +1 -1
  300. package/dist/internal/overlay-stack.js +1 -1
  301. package/dist/internal/package-metadata.d.ts +1 -1
  302. package/dist/internal/package-metadata.js +1 -1
  303. package/dist/internal/positioner.d.ts +5 -4
  304. package/dist/internal/reactive-property-writes.d.ts +1 -0
  305. package/dist/internal/reactive-property-writes.js +1 -0
  306. package/dist/internal/svg-title.d.ts +3 -0
  307. package/dist/internal/svg-title.js +1 -0
  308. package/dist/svelte.d.ts +1 -1
  309. package/dist/translations/ar.js +1 -1
  310. package/dist/translations/de.js +1 -1
  311. package/dist/translations/es.js +1 -1
  312. package/dist/translations/fa.js +1 -1
  313. package/dist/translations/fr.js +1 -1
  314. package/dist/translations/he.js +1 -1
  315. package/dist/translations/ja.js +1 -1
  316. package/dist/translations/pt-BR.js +1 -1
  317. package/dist/translations/ru.js +1 -1
  318. package/dist/translations/zh-CN.js +1 -1
  319. package/dist/vue.d.ts +1 -1
  320. package/llms/components/lr-accordion-item.md +4 -0
  321. package/llms/components/lr-accordion.md +4 -0
  322. package/llms/components/lr-agent-trace.md +3 -0
  323. package/llms/components/lr-animation.md +4 -0
  324. package/llms/components/lr-app-rail-item.md +4 -2
  325. package/llms/components/lr-app-rail.md +4 -2
  326. package/llms/components/lr-attachment-chip.md +6 -0
  327. package/llms/components/lr-av-player.md +14 -0
  328. package/llms/components/lr-avatar.md +4 -0
  329. package/llms/components/lr-box-plot.md +6 -0
  330. package/llms/components/lr-button.md +11 -3
  331. package/llms/components/lr-calendar-viewer.md +4 -0
  332. package/llms/components/lr-calendar.md +5 -0
  333. package/llms/components/lr-carousel.md +5 -0
  334. package/llms/components/lr-chart.md +13 -4
  335. package/llms/components/lr-chat-message.md +4 -0
  336. package/llms/components/lr-checkbox.md +3 -0
  337. package/llms/components/lr-chip-group.md +3 -0
  338. package/llms/components/lr-chip.md +3 -0
  339. package/llms/components/lr-code-block-core.md +16 -4
  340. package/llms/components/lr-code-block.md +7 -0
  341. package/llms/components/lr-code-editor.md +18 -5
  342. package/llms/components/lr-color-picker.md +9 -0
  343. package/llms/components/lr-combobox.md +35 -4
  344. package/llms/components/lr-command-palette.md +4 -0
  345. package/llms/components/lr-commit-card.md +3 -0
  346. package/llms/components/lr-compare-panel.md +7 -0
  347. package/llms/components/lr-condition-builder.md +5 -0
  348. package/llms/components/lr-conversation-item.md +3 -0
  349. package/llms/components/lr-copy-button.md +6 -0
  350. package/llms/components/lr-dashboard-grid.md +5 -0
  351. package/llms/components/lr-data-grid.md +11 -1
  352. package/llms/components/lr-dataset-viewer.md +3 -2
  353. package/llms/components/lr-date-input.md +46 -6
  354. package/llms/components/lr-date-picker.md +46 -6
  355. package/llms/components/lr-details.md +4 -0
  356. package/llms/components/lr-dialog.md +4 -0
  357. package/llms/components/lr-document-library.md +4 -0
  358. package/llms/components/lr-document-preview.md +7 -1
  359. package/llms/components/lr-document-viewer.md +9 -3
  360. package/llms/components/lr-dropdown-item.md +4 -0
  361. package/llms/components/lr-dropdown.md +3 -0
  362. package/llms/components/lr-ebook-viewer.md +4 -0
  363. package/llms/components/lr-email-viewer.md +5 -0
  364. package/llms/components/lr-emoji-picker.md +17 -3
  365. package/llms/components/lr-empty.md +3 -0
  366. package/llms/components/lr-entity-card.md +3 -0
  367. package/llms/components/lr-entity-chip.md +4 -0
  368. package/llms/components/lr-file-input.md +7 -0
  369. package/llms/components/lr-file-tree.md +5 -1
  370. package/llms/components/lr-filter-bar.md +5 -0
  371. package/llms/components/lr-flow-canvas.md +8 -1
  372. package/llms/components/lr-flow-node.md +2 -1
  373. package/llms/components/lr-flow-run-status.md +1 -1
  374. package/llms/components/lr-format-number.md +4 -0
  375. package/llms/components/lr-funnel.md +4 -0
  376. package/llms/components/lr-gauge.md +4 -0
  377. package/llms/components/lr-generation-metrics.md +5 -0
  378. package/llms/components/lr-graph-query-builder.md +6 -0
  379. package/llms/components/lr-graph.md +8 -2
  380. package/llms/components/lr-heatmap.md +13 -0
  381. package/llms/components/lr-icon-button.md +7 -0
  382. package/llms/components/lr-image-viewer.md +9 -0
  383. package/llms/components/lr-include.md +5 -0
  384. package/llms/components/lr-ingestion-queue.md +4 -0
  385. package/llms/components/lr-input.md +22 -8
  386. package/llms/components/lr-json-viewer.md +4 -0
  387. package/llms/components/lr-kbd.md +3 -0
  388. package/llms/components/lr-knowledge-graph-explorer.md +7 -0
  389. package/llms/components/lr-known-date.md +7 -0
  390. package/llms/components/lr-lite-chart.md +21 -4
  391. package/llms/components/lr-live-region.md +3 -0
  392. package/llms/components/lr-locale-picker.md +6 -0
  393. package/llms/components/lr-map.md +8 -0
  394. package/llms/components/lr-markdown-core.md +4 -0
  395. package/llms/components/lr-markdown.md +8 -4
  396. package/llms/components/lr-media-card.md +5 -2
  397. package/llms/components/lr-mention-popover.md +5 -0
  398. package/llms/components/lr-menu-item.md +4 -0
  399. package/llms/components/lr-menu-label.md +4 -3
  400. package/llms/components/lr-menu.md +4 -0
  401. package/llms/components/lr-message-actions.md +3 -0
  402. package/llms/components/lr-message-feedback.md +4 -0
  403. package/llms/components/lr-message-parts.md +3 -2
  404. package/llms/components/lr-model-select.md +8 -0
  405. package/llms/components/lr-multi-split.md +15 -6
  406. package/llms/components/lr-native-time-input.md +10 -0
  407. package/llms/components/lr-node-palette.md +3 -0
  408. package/llms/components/lr-notebook-viewer.md +4 -1
  409. package/llms/components/lr-number-input.md +12 -1
  410. package/llms/components/lr-option.md +35 -4
  411. package/llms/components/lr-otp-input.md +10 -0
  412. package/llms/components/lr-pan-zoom.md +1 -2
  413. package/llms/components/lr-phone-input.md +20 -5
  414. package/llms/components/lr-poll-status.md +4 -0
  415. package/llms/components/lr-popover.md +3 -0
  416. package/llms/components/lr-popup.md +3 -2
  417. package/llms/components/lr-prompt-studio.md +7 -0
  418. package/llms/components/lr-provenance-panel.md +3 -0
  419. package/llms/components/lr-push-to-talk.md +3 -0
  420. package/llms/components/lr-radio-button.md +13 -4
  421. package/llms/components/lr-radio-group.md +5 -0
  422. package/llms/components/lr-radio.md +9 -0
  423. package/llms/components/lr-rating.md +3 -0
  424. package/llms/components/lr-reorder-item.md +6 -0
  425. package/llms/components/lr-reorder-list.md +6 -0
  426. package/llms/components/lr-result-card.md +3 -0
  427. package/llms/components/lr-result-field.md +3 -0
  428. package/llms/components/lr-rubric-form.md +12 -0
  429. package/llms/components/lr-select.md +9 -0
  430. package/llms/components/lr-sequence-playback.md +4 -0
  431. package/llms/components/lr-slider.md +16 -4
  432. package/llms/components/lr-source-picker.md +4 -0
  433. package/llms/components/lr-span-waterfall.md +3 -0
  434. package/llms/components/lr-sparkline.md +4 -0
  435. package/llms/components/lr-split-panel.md +4 -0
  436. package/llms/components/lr-stack-trace.md +3 -0
  437. package/llms/components/lr-stat.md +10 -0
  438. package/llms/components/lr-subagent-panel.md +3 -2
  439. package/llms/components/lr-svg-viewer.md +3 -0
  440. package/llms/components/lr-swatch-picker.md +4 -0
  441. package/llms/components/lr-switch.md +6 -0
  442. package/llms/components/lr-tab-group.md +4 -0
  443. package/llms/components/lr-table.md +10 -2
  444. package/llms/components/lr-terminal.md +3 -0
  445. package/llms/components/lr-textarea.md +9 -0
  446. package/llms/components/lr-thread-list.md +6 -3
  447. package/llms/components/lr-time-input.md +3 -0
  448. package/llms/components/lr-time-range.md +5 -0
  449. package/llms/components/lr-timeline-item.md +6 -0
  450. package/llms/components/lr-timeline.md +6 -0
  451. package/llms/components/lr-token-input.md +14 -0
  452. package/llms/components/lr-tool-call-chip.md +5 -3
  453. package/llms/components/lr-tool-param-form.md +4 -0
  454. package/llms/components/lr-tool-result-dialog.md +4 -0
  455. package/llms/components/lr-tool-select-dialog.md +4 -0
  456. package/llms/components/lr-tooltip.md +6 -0
  457. package/llms/components/lr-trace-tree.md +3 -0
  458. package/llms/components/lr-transcript-feed.md +3 -0
  459. package/llms/components/lr-tree-item.md +12 -5
  460. package/llms/components/lr-tree.md +12 -5
  461. package/llms/components/lr-typing-indicator.md +3 -0
  462. package/llms/components/lr-usage-badge.md +4 -0
  463. package/llms/components/lr-video.md +8 -2
  464. package/llms/components/lr-virtual-list.md +5 -3
  465. package/llms/components/lr-voice-picker.md +8 -0
  466. package/llms/components/lr-widget-renderer.md +9 -0
  467. package/llms/components/lr-widget.md +4 -2
  468. package/llms/components/lr-word-cloud.md +4 -0
  469. package/llms/components/lr-xml-viewer.md +9 -2
  470. package/llms/components/lr-zoomable-frame.md +6 -3
  471. package/llms-full.txt +4080 -2711
  472. package/package.json +4 -4
  473. package/vscode-css-data.json +1 -1
  474. package/vscode-html-data.json +1 -1
  475. package/web-types.json +1 -1
@@ -1,4 +1,4 @@
1
- var __decorate=function(decorators,target,key,desc){var c=arguments.length,r=c<3?target:desc===null?desc=Object.getOwnPropertyDescriptor(target,key):desc,d;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")r=Reflect.decorate(decorators,target,key,desc);else for(var i=decorators.length-1;i>=0;i--)(d=decorators[i])&&(r=(c<3?d(r):c>3?d(target,key,r):d(target,key))||r);return c>3&&r&&Object.defineProperty(target,key,r),r};import{html,nothing}from"lit";import{property,query,state}from"lit/decorators.js";import{styleMap}from"lit/directives/style-map.js";import{LyraElement}from"../../../internal/lyra-element.js";import{srOnly}from"../../../internal/a11y.js";import{finiteInteger,finiteNumber,finiteRange}from"../../../internal/numbers.js";import{getScratchCtx}from"../../../internal/canvas.js";import{resolveCssLength}from"../../../internal/css-length.js";import{ThemeWatcher}from"../../../internal/theme-watcher.js";import{activeElementIn}from"../../../internal/active-element.js";import{linearAlpha,linearBucket,midpointAlpha,midpointBucket,minMax,sqrtStep}from"./heatmap-scale.js";import{styles}from"./heatmap.styles.js";import{buildCalendarGrid,parseIsoDate,quartileBucket}from"./calendar-grid.js";import{getDateTimeFormat,getNumberFormat}from"../../../internal/intl-cache.js";import{sanitizeCssColor}from"../../../internal/safe-css.js";import{literalSetConverter}from"../../../internal/converters.js";import{devWarnOnce}from"../../../internal/dev-mode-attribute-warning.js";import{acquireAnnouncementSink}from"../../../internal/announcer.js";import{LYRA_DEFAULT_heatmapCalendarCellLabel,LYRA_DEFAULT_heatmapCalendarLabel,LYRA_DEFAULT_heatmapDecorationLimit,LYRA_DEFAULT_heatmapDefaultColLabel,LYRA_DEFAULT_heatmapDefaultRowLabel,LYRA_DEFAULT_heatmapMatrixCellLabel,LYRA_DEFAULT_heatmapMatrixLabel,LYRA_DEFAULT_heatmapNoDataValue,LYRA_DEFAULT_heatmapProjectionLimit,LYRA_DEFAULT_heatmapSelectedCellLabel,LYRA_DEFAULT_heatmapValueLabel}from"../../../internal/default-strings.generated.js";const PAD_LEFT=60,PAD_TOP=20,ROW_LABEL_INSET=4,MAX_ROW_LABEL_FRACTION=.4,MAX_COL_LABEL_HEIGHT=240,COL_LABEL_INSET=6,labelExtentConverter={fromAttribute:value=>{if(value===null)return;const trimmed=value.trim();if(trimmed.toLowerCase()==="auto")return"auto";const parsed=Number.parseFloat(trimmed);return Number.isFinite(parsed)&&parsed>=0?parsed:void 0},toAttribute:value=>value===void 0?null:String(value)},STICKY_LABELS=literalSetConverter(["none","rows","cols","both"],"none"),FALLBACK_NO_DATA_FILL="rgba(128,128,128,0.25)",FALLBACK_STICKY_LABEL_BG="#ffffff",RAMP_STEPS=7,FALLBACK_SCALE_LO="#cde2fb",FALLBACK_SCALE_HI="#0969da",FALLBACK_LABEL_FONT="10px system-ui, sans-serif",CAL_PAD_LEFT=28,CAL_WEEKDAY_LABEL_INSET=2,CAL_LABEL_H=16,CAL_CELL=11,CAL_GAP=2,DEFAULT_MATRIX_CELL_SIZE=22,DEFAULT_ACCESSIBLE_TARGET_SIZE_PX=40,DEFAULT_BUCKET_COUNT=5,FIT_MIN_CELL=4,MAX_BUCKET_COUNT=256,MAX_HEATMAP_CELLS=1e4,MAX_HEATMAP_DECORATIONS=256,MAX_ACCESSIBLE_HEATMAP_CELLS=400,RING_LINE_WIDTH=2,FALLBACK_FOCUS_RING_COLOR="#0969da",FALLBACK_ANNOTATION_COLOR="#cf222e",FALLBACK_SELECTED_COLOR="#1a7f37",ARROW_KEYS=new Set(["ArrowUp","ArrowDown","ArrowLeft","ArrowRight"]),MS_PER_DAY=864e5;function isoDateAtOffset(firstWeekStart,dayOffset){return new Date(firstWeekStart.getTime()+dayOffset*MS_PER_DAY).toISOString().slice(0,10)}function legendStopsChanged(value,previous){if(Object.is(value,previous))return!1;if(!Array.isArray(value)||!Array.isArray(previous)||value.length!==previous.length)return!0;for(let index=0;index<value.length;index+=1){if(Object.hasOwn(value,index)!==Object.hasOwn(previous,index))return!0;const next=value[index],before=previous[index];if(!next||!before){if(!Object.is(next,before))return!0;continue}if(!Object.is(next.value,before.value)||!Object.is(next.color,before.color)||!Object.is(next.label,before.label)||!Object.is(next.partOfRamp,before.partOfRamp))return!0}return!1}const HEX_RE=/^([0-9a-f]{3,4}|[0-9a-f]{6}|[0-9a-f]{8})$/i,RGB_RE=/^rgba?\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)(?:\s*,\s*([\d.]+))?\s*\)/i;function hexToRgb(hex){const clean=hex.trim().replace("#","");if(!HEX_RE.test(clean))return null;const hasAlpha=clean.length===4||clean.length===8,full=clean.length<=4?clean.split("").map(c=>c+c).join(""):clean,num=Number.parseInt(full,16);return hasAlpha?[num>>>24&255,num>>>16&255,num>>>8&255,(num&255)/255]:[num>>16&255,num>>8&255,num&255,1]}function parseRgbString(value){const match=RGB_RE.exec(value);if(!match)return null;const a=match[4]===void 0?1:Number(match[4]);return[Number(match[1]),Number(match[2]),Number(match[3]),a]}function resolveViaPixelReadback(ctx){try{ctx.clearRect(0,0,1,1),ctx.fillRect(0,0,1,1);const[r=0,g=0,b=0,a=0]=ctx.getImageData(0,0,1,1).data;return[r,g,b,a/255]}catch{return null}}function formatRgb([r,g,b,a]){const alpha=Math.min(1,Math.max(0,a));return alpha>=1?`rgb(${r}, ${g}, ${b})`:`rgba(${r}, ${g}, ${b}, ${Math.round(alpha*1e3)/1e3})`}const warnedInvalidColors=new Set;function warnInvalidColor(color){warnedInvalidColors.has(color)||(warnedInvalidColors.add(color),console.warn(`<lr-heatmap> could not parse "${color}" (set via --lr-heatmap-scale-lo/-hi) as a CSS color; falling back to the default ramp endpoint.`))}let warnedNoCanvasContext=!1;function warnNoCanvasContext(){warnedNoCanvasContext||(warnedNoCanvasContext=!0,console.warn("<lr-heatmap>: no 2D canvas context is available in this environment; color resolution for non-hex/non-rgb values (e.g. oklch(), color(srgb ...), named colors) will fall back to the given default instead of resolving the requested color."))}function normalizeBucketCount(bucketCount){return finiteInteger(bucketCount,DEFAULT_BUCKET_COUNT,2,MAX_BUCKET_COUNT)}const optionalCellSizeConverter={fromAttribute(value){if(value===null||value.trim()==="")return;const parsed=Number(value);return Number.isFinite(parsed)?parsed:void 0}},DEFAULT_MATRIX_DATA=Object.freeze({kind:"matrix",rowLabels:Object.freeze([]),colLabels:Object.freeze([]),values:Object.freeze([])});function normalizeCellSizeClamp(value){if(!(value==null||!Number.isFinite(value)))return finiteRange(value,FIT_MIN_CELL,FIT_MIN_CELL)}const bucketCountConverter={fromAttribute(value){return value===null?DEFAULT_BUCKET_COUNT:normalizeBucketCount(Number(value))}};function resolveRgb(color,fallbackHex,ownerDocument){const fallback=hexToRgb(fallbackHex)??[0,0,0,1],direct=hexToRgb(color);if(direct)return direct;const ctx=getScratchCtx(ownerDocument);if(!ctx)return warnNoCanvasContext(),fallback;const sentinel="rgb(1, 2, 3)";ctx.fillStyle=sentinel;const sentinelNormalized=ctx.fillStyle;if(ctx.fillStyle=color,ctx.fillStyle===sentinelNormalized&&color.trim()!==sentinel)return warnInvalidColor(color),fallback;const normalized=ctx.fillStyle;return hexToRgb(normalized)??parseRgbString(normalized)??resolveViaPixelReadback(ctx)??fallback}function mixRgb(from,to,t){const clamped=Math.min(1,Math.max(0,t)),r=Math.round(from[0]+(to[0]-from[0])*clamped),g=Math.round(from[1]+(to[1]-from[1])*clamped),b=Math.round(from[2]+(to[2]-from[2])*clamped),a=from[3]+(to[3]-from[3])*clamped;return formatRgb([r,g,b,a])}class LyraHeatmap extends LyraElement{static{this.defaultStrings={...super.defaultStrings,heatmapCalendarCellLabel:LYRA_DEFAULT_heatmapCalendarCellLabel,heatmapCalendarLabel:LYRA_DEFAULT_heatmapCalendarLabel,heatmapDecorationLimit:LYRA_DEFAULT_heatmapDecorationLimit,heatmapDefaultColLabel:LYRA_DEFAULT_heatmapDefaultColLabel,heatmapDefaultRowLabel:LYRA_DEFAULT_heatmapDefaultRowLabel,heatmapMatrixCellLabel:LYRA_DEFAULT_heatmapMatrixCellLabel,heatmapMatrixLabel:LYRA_DEFAULT_heatmapMatrixLabel,heatmapNoDataValue:LYRA_DEFAULT_heatmapNoDataValue,heatmapProjectionLimit:LYRA_DEFAULT_heatmapProjectionLimit,heatmapSelectedCellLabel:LYRA_DEFAULT_heatmapSelectedCellLabel,heatmapValueLabel:LYRA_DEFAULT_heatmapValueLabel}}static{this.ownedCollectionProperties=Object.freeze(["data","annotations","legendStops","colorSteps"])}static{this.identityCollectionObjectProperties=Object.freeze(["data"])}static{this.styles=[LyraElement.styles,styles,srOnly]}static get observedAttributes(){return[...new Set([...super.observedAttributes,"role"])]}get effectiveMode(){return this.data.kind}get stickyLabels(){return this._stickyLabels}set stickyLabels(next){const normalized=STICKY_LABELS.normalizeReflected(this,"sticky-labels",next),old=this._stickyLabels;old!==normalized&&(this._stickyLabels=normalized,this.requestUpdate("stickyLabels",old))}get effectiveStickyLabels(){return this.effectiveMode==="matrix"?this._stickyLabels:"none"}get freezesRowLabels(){const sticky=this.effectiveStickyLabels;return sticky==="rows"||sticky==="both"}get freezesColLabels(){const sticky=this.effectiveStickyLabels;return sticky==="cols"||sticky==="both"}get effectiveColLabelRotation(){if(typeof this.colLabelRotation!="number")return 0;const degrees=finiteNumber(this.colLabelRotation,0);return Math.min(90,Math.max(0,degrees))}get matrixPadLeft(){if(this.rowLabelWidth==="auto")return this.resolvedRowLabelWidth;if(typeof this.rowLabelWidth!="number")return PAD_LEFT;const resolved=finiteNumber(this.rowLabelWidth,PAD_LEFT);return resolved>=0?resolved:PAD_LEFT}get matrixGeometry(){if(this.effectiveMode==="matrix")return this.lastPaintedMatrixGeometry}get matrixPadTop(){if(this.colLabelHeight==="auto")return this.resolvedColLabelHeight;if(typeof this.colLabelHeight!="number")return PAD_TOP;const resolved=finiteNumber(this.colLabelHeight,PAD_TOP);return resolved>=0?resolved:PAD_TOP}measureColLabelHeight(cs){const labels=this.matrixColLabels;if(labels.length===0)return PAD_TOP;const ctx=getScratchCtx(this.ownerDocument);if(!ctx)return PAD_TOP;ctx.font=this.labelFont(cs);let widest=0;for(const label of labels)widest=Math.max(widest,ctx.measureText(label).width);const radians=this.effectiveColLabelRotation*Math.PI/180,projected=widest*Math.sin(radians);return Math.max(PAD_TOP,Math.min(Math.ceil(projected)+COL_LABEL_INSET,MAX_COL_LABEL_HEIGHT))}measureRowLabelWidth(cs){const labels=this.matrixRowLabels;if(labels.length===0)return PAD_LEFT;const ctx=getScratchCtx(this.ownerDocument);if(!ctx)return PAD_LEFT;ctx.font=this.labelFont(cs);let widest=0;for(const label of labels)widest=Math.max(widest,ctx.measureText(label).width);const hostWidth=this.clientWidth||0,cap=hostWidth>0?hostWidth*MAX_ROW_LABEL_FRACTION:Number.POSITIVE_INFINITY;return Math.min(Math.max(PAD_LEFT,Math.ceil(widest)+ROW_LABEL_INSET*2),cap)}ellipsize(ctx,label,maxWidth){if(maxWidth<=0)return"";if(ctx.measureText(label).width<=maxWidth)return label;const characters=[...label];let kept=characters.length-1;for(;kept>0;){const candidate=`${characters.slice(0,kept).join("")}…`;if(ctx.measureText(candidate).width<=maxWidth)return candidate;kept-=1}return ctx.measureText("…").width<=maxWidth?"…":""}get calendarPadLeft(){const requested=this.calendarWeekdayLabelWidth;return requested==="auto"?this.resolvedCalendarWeekdayLabelWidth:requested??CAL_PAD_LEFT}measureCalendarWeekdayLabelWidth(cs,firstWeekStart){const ctx=getScratchCtx(this.ownerDocument);if(!ctx)return CAL_PAD_LEFT;ctx.font=this.labelFont(cs);let widest=0;for(const label of this.weekdayLabels(firstWeekStart))label&&(widest=Math.max(widest,ctx.measureText(label).width));const hostWidth=this.clientWidth||0,cap=hostWidth>0?Math.max(CAL_PAD_LEFT,hostWidth*MAX_ROW_LABEL_FRACTION):Number.POSITIVE_INFINITY;return Math.min(Math.max(CAL_PAD_LEFT,Math.ceil(widest)+CAL_WEEKDAY_LABEL_INSET*2),cap)}get matrixRowLabels(){return this.cachedMatrixData.rowLabels}get matrixColLabels(){return this.cachedMatrixData.colLabels}get matrixValues(){return this.cachedMatrixData.values}get calendarDays(){return this.data.kind==="calendar"?this.data.days:[]}get calendarData(){return this.data.kind==="calendar"?this.data:void 0}get cellSize(){return this._cellSize??(this.effectiveMode==="calendar"?CAL_CELL:DEFAULT_MATRIX_CELL_SIZE)}set cellSize(value){const oldValue=this._cellSize;this._cellSize=value==null?void 0:finiteRange(value,this.effectiveMode==="calendar"?CAL_CELL:DEFAULT_MATRIX_CELL_SIZE,1),this.requestUpdate("cellSize",oldValue)}get signedDomain(){return this.domain!==void 0||this.midpoint!==void 0}rampAlpha(value,lo,hi){const anchor=this.midpoint;return anchor===void 0?linearAlpha(value,lo,hi):midpointAlpha(value,lo,hi,anchor)}rampBucket(value,lo,hi,steps){const anchor=this.midpoint;return anchor===void 0?linearBucket(value,lo,hi,steps):midpointBucket(value,lo,hi,anchor,steps)}isNoData(value){return Number.isFinite(value)?value<0&&!this.signedDomain:!0}get maxCellSize(){return this._maxCellSize}set maxCellSize(value){const oldValue=this._maxCellSize;this._maxCellSize=normalizeCellSizeClamp(value),this.requestUpdate("maxCellSize",oldValue)}get minCellSize(){return this._minCellSize}set minCellSize(value){const oldValue=this._minCellSize;this._minCellSize=normalizeCellSizeClamp(value),this.requestUpdate("minCellSize",oldValue)}get normalizedFirstDayOfWeek(){return(finiteInteger(this.calendarData?.firstDayOfWeek??0,0)%7+7)%7}get bucketCount(){return this._bucketCount}set bucketCount(value){const oldValue=this._bucketCount;this._bucketCount=normalizeBucketCount(value),this.requestUpdate("bucketCount",oldValue)}get calendarWeekdayLabelText(){return this.calendarData?.weekdayLabelText}get calendarWeekdayLabelWidth(){const value=this.calendarData?.weekdayLabelWidth;if(value==="auto")return value;if(typeof value!="number")return;const resolved=finiteNumber(value,CAL_PAD_LEFT);return resolved>=0?resolved:void 0}get calendarMonthLabelText(){return this.calendarData?.monthLabelText}get calendarColumnX(){return this.calendarData?.columnX}get calendarRowY(){return this.calendarData?.rowY}constructor(){super(),this.data=DEFAULT_MATRIX_DATA,this._stickyLabels="none",this.resolvedColLabelHeight=PAD_TOP,this.resolvedRowLabelWidth=PAD_LEFT,this.resolvedCalendarWeekdayLabelWidth=CAL_PAD_LEFT,this.scale="linear",this.fitToWidth=!1,this._bucketCount=DEFAULT_BUCKET_COUNT,this.annotations=[],this.selectedCell=null,this.accessibleCells=!1,this.cachedValueRange=null,this.cachedMatrixData={rowLabels:[],colLabels:[],values:[],truncated:!1},this.cachedCalendarGrid=buildCalendarGrid(this.calendarDays),this.cachedCalendarSortedValues=[],this.cachedCalendarCellsByPos=new Map,this.cachedCalendarCellsByDate=new Map,this.cachedAnnotations=[],this.cachedLegendStops=[],this.cachedColorSteps=[],this.cachedCalendarAnnotationDates=new Set,this.cachedMatrixAnnotationPositions=new Set,this.decorationProjectionTruncated=!1,this.cachedCalendarDateByPos=[],this.cachedAccessiblePositions=[],this.cachedAccessiblePositionsByKey=new Map,this.cachedAccessiblePositionIndexByKey=new Map,this.cachedRamp=null,this.canvasHasContent=!1,this.canvasVisible=!0,this.drawDirty=!1,this.hoverCell=null,this.focusedCell=null,this.liveText="",this.accessibleTargetSizePx=DEFAULT_ACCESSIBLE_TARGET_SIZE_PX,this.restoringAccessibleFocus=!1,this.accessibleFocusGeneration=0,this.authorRole=null,this.authorAriaLabel=null,this.generatedAriaLabel="",this.syncingGeneratedSemantics=!1,this.onDprChange=()=>{this.watchDpr(),this.requestDraw()},this.scheduleDraw=()=>{if(this.drawFrameRequest)return;const owner=this.ownerDocument.defaultView;if(!owner||!this.isConnected)return;const request={owner,handle:0};request.handle=owner.requestAnimationFrame(()=>{this.drawFrameRequest===request&&(this.drawFrameRequest=void 0,this.isConnected&&this.ownerDocument.defaultView===owner&&this.requestDraw())}),this.drawFrameRequest=request},this.tooltipSize={inline:0,block:0},this.onPointerMove=e=>{const next=this.hitTest(e.offsetX,e.offsetY);this.samePos(this.hoverCell,next)||(this.hoverCell=next)},this.onPointerLeave=()=>{this.hoverCell=null},this.onCanvasClick=e=>{const pos=this.hitTest(e.offsetX,e.offsetY);pos&&(this.focusedCell=pos,this.announce(pos),this.emitCellClick(pos))},this.onKeyDown=e=>{this.effectiveMode==="calendar"?this.onCalendarKeyDown(e):this.onMatrixKeyDown(e)},this.canvasColorCache=new Map,this.onAccessibleCellFocus=e=>{if(this.restoringAccessibleFocus)return;const key=e.currentTarget.dataset.cellKey,pos=key?this.accessibleCellAtKey(key):null;pos&&(this.focusedCell=pos,this.announce(pos))},this.onAccessibleCellClick=e=>{const key=e.currentTarget.dataset.cellKey,pos=key?this.accessibleCellAtKey(key):null;pos&&(this.focusedCell=pos,this.announce(pos),this.emitCellClick(pos))},this.onAccessibleCellKeyDown=e=>{if(!ARROW_KEYS.has(e.key))return;const key=e.currentTarget.dataset.cellKey,pos=key?this.accessibleCellAtKey(key):null;pos&&(e.preventDefault(),this.focusedCell=pos,this.onKeyDown(e),this.focusAccessibleCell(this.focusedCell))},new ThemeWatcher(this,()=>this.refreshTheme())}warnOnLegendRampMismatch(){const rampColors=this.cachedColorSteps.map(color=>sanitizeCssColor(color)??color);if(rampColors.length===0)return;const legendColors=this.cachedLegendStops.filter(stop=>!!stop.color&&stop.partOfRamp!==!1).map(stop=>sanitizeCssColor(stop.color??"")??stop.color??"");legendColors.length===0||legendColors.length===rampColors.length&&legendColors.every((color,index)=>color===rampColors[index])||devWarnOnce("lyra-heatmap-legend-ramp-mismatch",`<${this.localName}>: legendStops describes ${legendColors.length} colour(s) that do not match the ${rampColors.length} colorSteps the cells are painted from, so the legend may misdescribe the ramp. Supply legendStops built from the same array as colorSteps, or omit it to keep the built-in gradient key.`)}attributeChangedCallback(name,oldValue,value){super.attributeChangedCallback(name,oldValue,value),!(oldValue===value||this.syncingGeneratedSemantics)&&(name==="role"&&(this.authorRole=value),name==="aria-label"&&(this.authorAriaLabel=value))}connectedCallback(){super.connectedCallback(),this.syncAnnouncementSink(),this.refreshAccessibleTargetSize();const owner=this.ownerDocument.defaultView,ResizeObserverCtor=owner?.ResizeObserver;if(owner&&ResizeObserverCtor){let observer;observer=new ResizeObserverCtor(()=>{!this.isConnected||this.ownerDocument.defaultView!==owner||this.resizeObserver!==observer||this.scheduleDraw()}),this.resizeObserver=observer,observer.observe(this)}const IntersectionObserverCtor=owner?.IntersectionObserver;if(this.canvasVisible=!0,owner&&IntersectionObserverCtor){let observer;observer=new IntersectionObserverCtor(entries=>{if(!this.isConnected||this.ownerDocument.defaultView!==owner||this.intersectionObserver!==observer)return;const entry=entries.find(candidate=>candidate.target===this);!entry||entry.isIntersecting===this.canvasVisible||(this.canvasVisible=entry.isIntersecting,this.canvasVisible&&this.drawDirty&&this.scheduleDraw())}),this.intersectionObserver=observer,observer.observe(this)}this.cachedRamp=null,this.canvasColorCache.clear(),this.watchDpr()}disconnectedCallback(){super.disconnectedCallback(),this.accessibleFocusGeneration++,this.pendingAccessibleFocus=void 0,this.pendingAccessibleFocusOrigin=void 0,this.restoringAccessibleFocus=!1,this.releaseAnnouncementSink(),this.hoverCell=null,this.focusedCell=null,this.liveText="",this.canvasHasContent=!1,this.drawDirty=!0,this.resizeObserver?.disconnect(),this.resizeObserver=void 0,this.intersectionObserver?.disconnect(),this.intersectionObserver=void 0,this.canvasVisible=!0,this.clearDprWatcher(),this.cancelDrawFrame()}releaseAnnouncementSink(){this.announcementSink?.release(),this.announcementSink=void 0}syncAnnouncementSink(){if(!this.isConnected){this.releaseAnnouncementSink();return}this.announcementSink?.element.ownerDocument!==this.ownerDocument&&(this.releaseAnnouncementSink(),this.announcementSink=acquireAnnouncementSink("polite",{document:this.ownerDocument,source:this}))}watchDpr(){this.clearDprWatcher();const owner=this.ownerDocument.defaultView;if(!owner||typeof owner.matchMedia!="function")return;const query2=owner.matchMedia(`(resolution: ${owner.devicePixelRatio}dppx)`),listener=()=>{!this.isConnected||this.ownerDocument.defaultView!==owner||this.dprQuery!==query2||this.onDprChange()};this.dprQuery=query2,this.dprChangeListener=listener,query2.addEventListener("change",listener)}clearDprWatcher(){this.dprQuery&&this.dprChangeListener&&this.dprQuery.removeEventListener("change",this.dprChangeListener),this.dprQuery=void 0,this.dprChangeListener=void 0}willUpdate(changed){super.willUpdate(changed),(changed.has("data")||!this.hasUpdated)&&this.rebuildCanonicalMatrixData(),(changed.has("annotations")||changed.has("legendStops")||changed.has("colorSteps")||!this.hasUpdated)&&this.rebuildBoundedDecorations();const accessibleModeChanged=changed.has("accessibleCells")&&this.hasUpdated,collectionChanged=changed.has("data")||changed.has("cellInteractive"),activeRenderedControl=collectionChanged||accessibleModeChanged?activeElementIn(this.shadowRoot):null,activeAccessibleCell=activeRenderedControl?.matches('[part="cell"]')?activeRenderedControl:null,renderedAccessibleCells=activeAccessibleCell?.matches('[part="cell"]')?[...this.shadowRoot?.querySelectorAll('[part="cell"]')??[]]:[],accessibleFocusSnapshot=activeAccessibleCell?.matches('[part="cell"]')?{identity:activeAccessibleCell.dataset.cellIdentity,index:renderedAccessibleCells.indexOf(activeAccessibleCell)}:void 0;if(collectionChanged&&(this.focusedCell=null,this.hoverCell=null,this.liveText=""),changed.has("data")||changed.has("locale")||!this.hasUpdated){this.cachedCalendarGrid=buildCalendarGrid(this.calendarDays,this.normalizedFirstDayOfWeek,this.calendarMonthLabelText,this.effectiveLocale),this.cachedCalendarSortedValues=this.cachedCalendarGrid.cells.map(cell=>cell.value).filter(value=>!this.isNoData(value)).sort((a,b)=>a-b),this.cachedCalendarCellsByPos=new Map(this.cachedCalendarGrid.cells.map(cell=>[`${cell.week}:${cell.weekday}`,cell])),this.cachedCalendarCellsByDate=new Map(this.cachedCalendarGrid.cells.map(cell=>[cell.date,cell]));const{firstWeekStart,weekCount}=this.cachedCalendarGrid;this.cachedCalendarDateByPos=Array.from({length:weekCount*7},(_,index)=>isoDateAtOffset(firstWeekStart,index))}if(changed.has("colorSteps")||!this.hasUpdated){const colorSteps=this.cachedColorSteps.map(sanitizeCssColor);colorSteps.length>=2&&colorSteps.every(color=>color!==void 0)?this.style.setProperty("--lr-heatmap-color-steps-gradient",`linear-gradient(to right, ${colorSteps.join(", ")})`):this.style.removeProperty("--lr-heatmap-color-steps-gradient")}if((changed.has("data")||changed.has("domain")||changed.has("midpoint")||!this.hasUpdated)&&(this.cachedValueRange=this.computeValueRange()),(collectionChanged||!this.hasUpdated)&&this.rebuildAccessiblePositions(),accessibleFocusSnapshot){const positions=this.accessibleCellPositions(),target=(accessibleFocusSnapshot.identity==null?void 0:positions.find(pos=>this.accessibleCellIdentity(pos)===accessibleFocusSnapshot.identity))??positions[Math.min(Math.max(accessibleFocusSnapshot.index,0),positions.length-1)]??null;this.focusedCell=target,this.liveText=target?this.resolveCellText(target):"",this.pendingAccessibleFocus=target??"base",this.pendingAccessibleFocusOrigin=activeAccessibleCell??void 0,this.restoringAccessibleFocus=!0,this.accessibleFocusGeneration++}if(accessibleModeChanged){const previouslyAccessible=changed.get("accessibleCells")===!0;if(previouslyAccessible&&!this.accessibleCells&&activeAccessibleCell){const key=activeAccessibleCell.dataset.cellKey,target=key?this.accessibleCellAtKey(key):null;target&&(this.focusedCell=target,this.liveText=this.resolveCellText(target)),this.pendingAccessibleFocus="canvas",this.pendingAccessibleFocusOrigin=activeAccessibleCell,this.restoringAccessibleFocus=!0,this.accessibleFocusGeneration++}else if(!previouslyAccessible&&this.accessibleCells&&activeRenderedControl?.matches('[part="canvas"]')){const positions=this.accessibleCellPositions(),target=this.focusedCell?positions.find(pos=>this.samePos(pos,this.focusedCell))??positions[0]??null:positions[0]??null;this.focusedCell=target,this.liveText=target?this.resolveCellText(target):"",this.pendingAccessibleFocus=target??"base",this.pendingAccessibleFocusOrigin=activeRenderedControl,this.restoringAccessibleFocus=!0,this.accessibleFocusGeneration++}}const bounds=this.cachedValueRange,range=bounds?`${this.formatNumericValue(bounds[0])}–${this.formatNumericValue(bounds[1])}`:this.localize("heatmapNoDataValue"),valueLabel=this.localizedValueLabel();let label;if(this.effectiveMode==="calendar")label=this.localize("heatmapCalendarLabel",void 0,{days:this.formatCount(this.cachedCalendarGrid.cells.length),label:valueLabel,range});else{const rows=this.matrixRowLabels.length,cols=this.matrixColLabels.length;label=this.localize("heatmapMatrixLabel",void 0,{rows:this.formatCount(rows),cols:this.formatCount(cols),label:valueLabel,range})}const selectedText=this.selectedCellDescription(),generatedAriaLabel=[label,selectedText,this.projectionDescription()].filter(Boolean).join(" ");this.generatedAriaLabel=generatedAriaLabel,this.syncingGeneratedSemantics=!0;try{this.authorRole===null&&this.setAttribute("role","group"),this.authorAriaLabel===null&&this.setAttribute("aria-label",generatedAriaLabel)}finally{this.syncingGeneratedSemantics=!1}}rebuildBoundedDecorations(){this.cachedAnnotations=this.annotations.slice(0,MAX_HEATMAP_DECORATIONS).map(entry=>({...entry})),this.cachedLegendStops=(this.legendStops??[]).slice(0,MAX_HEATMAP_DECORATIONS).map(entry=>({...entry})),this.cachedColorSteps=(this.colorSteps??[]).slice(0,MAX_HEATMAP_DECORATIONS),this.warnOnLegendRampMismatch(),this.cachedCalendarAnnotationDates=new Set(this.cachedAnnotations.flatMap(annotation=>annotation.date==null?[]:[annotation.date])),this.cachedMatrixAnnotationPositions=new Set(this.cachedAnnotations.flatMap(annotation=>annotation.row==null||annotation.col==null?[]:[`${annotation.row}:${annotation.col}`])),this.decorationProjectionTruncated=this.annotations.length>MAX_HEATMAP_DECORATIONS||(this.legendStops?.length??0)>MAX_HEATMAP_DECORATIONS||(this.colorSteps?.length??0)>MAX_HEATMAP_DECORATIONS}get projectionTruncated(){return this.decorationProjectionTruncated||(this.effectiveMode==="calendar"?this.cachedCalendarGrid.truncated:this.cachedMatrixData.truncated)}get cellProjectionTruncated(){return this.effectiveMode==="calendar"?this.cachedCalendarGrid.truncated:this.cachedMatrixData.truncated}projectedCellCount(){return this.effectiveMode==="calendar"?this.cachedCalendarGrid.weekCount*7:this.matrixRowLabels.length*this.matrixColLabels.length}projectionDescription(){const messages=[];return this.cellProjectionTruncated&&messages.push(this.localize("heatmapProjectionLimit",void 0,{count:this.formatCount(this.projectedCellCount())})),this.decorationProjectionTruncated&&messages.push(this.localize("heatmapDecorationLimit",void 0,{count:this.formatCount(MAX_HEATMAP_DECORATIONS)})),messages.join(" ")}rebuildCanonicalMatrixData(){if(this.data.kind!=="matrix"){this.cachedMatrixData={rowLabels:[],colLabels:[],values:[],truncated:!1};return}const colCount=Math.min(this.data.colLabels.length,MAX_HEATMAP_CELLS),rowLimit=colCount===0?Math.min(this.data.rowLabels.length,MAX_HEATMAP_CELLS):Math.floor(MAX_HEATMAP_CELLS/colCount),rowCount=Math.min(this.data.rowLabels.length,rowLimit),rowLabels=this.data.rowLabels.slice(0,rowCount).map(String),colLabels=this.data.colLabels.slice(0,colCount).map(String),source=this.data,values=Array.from({length:rowCount},(_,row)=>Array.from({length:colCount},(_2,col)=>source.values[row]?.[col]??(this.signedDomain?Number.NaN:-1)));this.cachedMatrixData={rowLabels,colLabels,values,truncated:rowCount!==this.data.rowLabels.length||colCount!==this.data.colLabels.length||this.data.values.some((row,index)=>index>=rowCount||row.length>colCount)}}selectedCellDescription(){if(!this.selectedCell)return"";if(this.effectiveMode==="calendar"){if(this.selectedCell.date==null)return"";const match=this.cachedCalendarCellsByDate.get(this.selectedCell.date);return match?this.localize("heatmapSelectedCellLabel",void 0,{cell:this.calendarCellText({week:match.week,weekday:match.weekday,date:match.date})}):""}const{row,col}=this.selectedCell;return row==null||col==null||row<0||row>=this.matrixRowLabels.length||col<0||col>=this.matrixColLabels.length?"":this.localize("heatmapSelectedCellLabel",void 0,{cell:this.matrixCellText({row,col})})}computeValueRange(){const pinned=this.domain;if(pinned){const[lo,hi]=pinned;if(Number.isFinite(lo)&&Number.isFinite(hi)&&lo!==hi)return lo<hi?[lo,hi]:[hi,lo]}const source=this.effectiveMode==="calendar"?this.cachedCalendarGrid.cells.map(cell=>cell.value):this.matrixValues.flat();return minMax(source.filter(v=>!this.isNoData(v)))}localizedValueLabel(){return this.valueLabel===void 0?this.localize("heatmapValueLabel"):this.valueLabel}formatNumericValue(value){return getNumberFormat(this.effectiveLocale||void 0).format(value)}updated(changed){if(super.updated(changed),this.hoverCell&&this.effectiveStickyLabels!=="none"&&this.scheduleAfterUpdate(()=>this.measureTooltip(),"heatmap-tooltip-metrics"),["data","cellSize","maxCellSize","minCellSize","valueLabel","scale","domain","midpoint","fitToWidth","rowLabelWidth","colLabelHeight","colLabelRotation","bucketCount","annotations","focusedCell","colorSteps","cellColor","selectedCell","legendStops","accessibleCells","accessibleTargetSizePx","locale","stickyLabels"].some(name=>changed.has(name))){if(changed.has("focusedCell")&&[...changed.keys()].every(key=>key==="focusedCell"||key==="liveText")&&this.repaintFocusRing(changed.get("focusedCell")))return;this.requestDraw()}const pending=this.pendingAccessibleFocus;if(pending===void 0)return;this.pendingAccessibleFocus=void 0;const origin=this.pendingAccessibleFocusOrigin;this.pendingAccessibleFocusOrigin=void 0;const generation=this.accessibleFocusGeneration;this.scheduleAfterUpdate(()=>{try{if(generation!==this.accessibleFocusGeneration||!this.isConnected)return;if(origin){const internalActive=activeElementIn(this.shadowRoot),documentActive=activeElementIn(this.ownerDocument),focusStayedAtOrigin=internalActive===origin,originWasRemovedWithoutReplacement=internalActive===null&&(documentActive===null||documentActive===this||documentActive===this.ownerDocument.body);if(!focusStayedAtOrigin&&!originWasRemovedWithoutReplacement)return}if(pending==="base"){this.shadowRoot?.querySelector('[part="base"]')?.focus();return}if(pending==="canvas"){this.shadowRoot?.querySelector('[part="canvas"]')?.focus();return}const identity=this.accessibleCellIdentity(pending);[...this.shadowRoot?.querySelectorAll('[part="cell"]')??[]].find(candidate=>candidate.dataset.cellIdentity===identity)?.focus()}finally{this.restoringAccessibleFocus=!1}},"heatmap-accessible-focus")}refreshTheme(){this.cachedRamp=null,this.refreshAccessibleTargetSize()||this.requestDraw()}refreshAccessibleTargetSize(){const raw=this.ownerDocument.defaultView?.getComputedStyle(this).getPropertyValue("--lr-icon-button-size").trim()??"",resolved=resolveCssLength(raw,{host:this}),next=resolved!==void 0&&Number.isFinite(resolved)&&resolved>0?resolved:DEFAULT_ACCESSIBLE_TARGET_SIZE_PX;return next===this.accessibleTargetSizePx?!1:(this.accessibleTargetSizePx=next,!0)}scaleEndpoints(cs){const lo=cs.getPropertyValue("--lr-heatmap-scale-lo").trim()||cs.getPropertyValue("--_lr-heatmap-scale-lo").trim()||FALLBACK_SCALE_LO,hi=cs.getPropertyValue("--lr-heatmap-scale-hi").trim()||cs.getPropertyValue("--_lr-heatmap-scale-hi").trim()||FALLBACK_SCALE_HI;return[lo,hi]}labelColor(cs){return cs.getPropertyValue("--lr-color-text-quiet").trim()||"#6b7280"}labelFont(cs){return cs.getPropertyValue("--lr-heatmap-label-font").trim()||cs.getPropertyValue("--_lr-heatmap-label-font").trim()||FALLBACK_LABEL_FONT}stickyLabelBg(cs){const raw=cs.getPropertyValue("--lr-heatmap-sticky-label-bg").trim()||cs.getPropertyValue("--_lr-heatmap-sticky-label-bg").trim()||FALLBACK_STICKY_LABEL_BG;return formatRgb(resolveRgb(raw,FALLBACK_STICKY_LABEL_BG,this.ownerDocument))}noDataFill(cs){return cs.getPropertyValue("--lr-heatmap-no-data-fill").trim()||cs.getPropertyValue("--_lr-heatmap-no-data-fill").trim()||FALLBACK_NO_DATA_FILL}focusRingColor(cs){return cs.getPropertyValue("--lr-heatmap-focus-ring-color").trim()||cs.getPropertyValue("--_lr-heatmap-focus-ring-color").trim()||FALLBACK_FOCUS_RING_COLOR}annotationColor(cs){return cs.getPropertyValue("--lr-heatmap-annotation-color").trim()||cs.getPropertyValue("--_lr-heatmap-annotation-color").trim()||FALLBACK_ANNOTATION_COLOR}selectedColor(cs){return cs.getPropertyValue("--lr-heatmap-selected-color").trim()||cs.getPropertyValue("--_lr-heatmap-selected-color").trim()||FALLBACK_SELECTED_COLOR}strokeCellState(ctx,x,y,size,state2,color){const inset=Math.min(state2==="annotation"?.5:state2==="selected"?3.5:6.5,Math.max(.5,(size-RING_LINE_WIDTH-1)/2)),extent=Math.max(1,size-inset*2);ctx.lineWidth=RING_LINE_WIDTH,ctx.strokeStyle=color,ctx.setLineDash?.(state2==="annotation"?[]:state2==="selected"?[4,2]:[1,2]),ctx.strokeRect(x+inset,y+inset,extent,extent),ctx.setLineDash?.([])}isSelectedPos(pos){return this.selectedCell?"week"in pos?this.selectedCell.date==null?!1:this.calendarCellAt(pos).date===this.selectedCell.date:this.selectedCell.row===pos.row&&this.selectedCell.col===pos.col:!1}draw(){if(!this.canvasVisible){this.drawDirty=!0;return}this.drawDirty=!1,this.canvasHasContent=!1,this.effectiveMode==="calendar"?this.drawCalendar():this.drawMatrix()}requestDraw(){this.drawDirty=!0,this.canvasVisible&&this.draw()}repaintFocusRing(previous){if(!this.canvasHasContent||!this.canvas)return!1;const current=this.focusedCell;if(this.effectiveMode==="calendar"){if(previous&&!("week"in previous)||current&&!("week"in current))return!1;this.repaintCalendarFocusCell(previous&&"week"in previous?previous:null),current&&(!previous||!this.samePos(previous,current))&&this.repaintCalendarFocusCell(current)}else{if(previous&&!("row"in previous)||current&&!("row"in current))return!1;this.repaintMatrixFocusCell(previous&&"row"in previous?previous:null),current&&(!previous||!this.samePos(previous,current))&&this.repaintMatrixFocusCell(current)}return!0}cancelDrawFrame(){const request=this.drawFrameRequest;request&&request.owner.cancelAnimationFrame(request.handle),this.drawFrameRequest=void 0}resolveColorStep(color,fallback){const safe=sanitizeCssColor(color);if(!safe)return fallback;const scope=this.ownerDocument.createElement("span"),probe=this.ownerDocument.createElement("span");scope.hidden=!0,scope.style.color=fallback,probe.style.color=safe,scope.append(probe),this.renderRoot.append(scope);try{return this.ownerDocument.defaultView?.getComputedStyle(probe).color.trim()||fallback}finally{scope.remove()}}colorRamp(bucketCount,cs){const steps=this.cachedColorSteps;if(steps&&steps.length>=2){const key2=`steps ${steps.join(" ")}`;if(this.cachedRamp?.key===key2)return this.cachedRamp;const resolved=steps.map((color,index)=>this.resolveColorStep(color,index===steps.length-1?FALLBACK_SCALE_HI:FALLBACK_SCALE_LO)),colors2=resolved.map(color=>formatRgb(resolveRgb(color,FALLBACK_SCALE_LO,this.ownerDocument))),loRgb2=resolveRgb(resolved[0],FALLBACK_SCALE_LO,this.ownerDocument),hiRgb2=resolveRgb(resolved[resolved.length-1],FALLBACK_SCALE_HI,this.ownerDocument);return this.cachedRamp={key:key2,colors:colors2,loRgb:loRgb2,hiRgb:hiRgb2},this.cachedRamp}const[scaleLo,scaleHi]=this.scaleEndpoints(cs),normalizedBucketCount=normalizeBucketCount(bucketCount),key=`${scaleLo}\0${scaleHi}\0${normalizedBucketCount}`;if(this.cachedRamp?.key===key)return this.cachedRamp;const loRgb=resolveRgb(scaleLo,FALLBACK_SCALE_LO,this.ownerDocument),hiRgb=resolveRgb(scaleHi,FALLBACK_SCALE_HI,this.ownerDocument),colors=Array.from({length:normalizedBucketCount},(_,i)=>mixRgb(loRgb,hiRgb,i/(normalizedBucketCount-1)));return this.cachedRamp={key,colors,loRgb,hiRgb},this.cachedRamp}calendarCellSize(){const{weekCount}=this.cachedCalendarGrid;let size;if(this.fitToWidth&&weekCount>0){const hostWidth=this.clientWidth||this.calendarPadLeft+weekCount*(this.cellSize+CAL_GAP);size=this.clampFitCellSize((hostWidth-this.calendarPadLeft)/weekCount-CAL_GAP)}else size=this.cellSize;return this.accessibleCells?Math.max(size,this.accessibleTargetSizePx):size}clampFitCellSize(size){const floored=finiteRange(size,FIT_MIN_CELL,Math.max(FIT_MIN_CELL,this.minCellSize??FIT_MIN_CELL));return this.maxCellSize==null?floored:Math.min(floored,this.maxCellSize)}columnXFor(week){return this.calendarColumnPositions()[week]??this.calendarPadLeft}rowYFor(weekday){return this.calendarRowPositions()[weekday]??CAL_LABEL_H}calendarColumnPositions(){const cellSize=this.calendarCellSize(),weekCount=this.cachedCalendarGrid.weekCount,callback=this.calendarColumnX,padLeft=this.calendarPadLeft,cached=this.cachedColumnGeometry;if(cached!==void 0&&cached.callback===callback&&cached.padLeft===padLeft&&cached.cellSize===cellSize&&cached.weekCount===weekCount)return cached.positions;const positions=[];for(let index=0;index<=weekCount;index++){const fallback=index===0?padLeft:positions[index-1]+cellSize+CAL_GAP;let candidate=fallback;if(callback)try{const supplied=callback(index);Number.isFinite(supplied)&&supplied>=0&&(index===0||supplied>=positions[index-1]+cellSize)&&(candidate=supplied)}catch{candidate=fallback}positions.push(candidate)}return this.cachedColumnGeometry={callback,padLeft,cellSize,weekCount,positions},positions}calendarRowPositions(){const cellSize=this.calendarCellSize(),callback=this.calendarRowY,cached=this.cachedRowGeometry;if(cached!==void 0&&cached.callback===callback&&cached.cellSize===cellSize)return cached.positions;const positions=[];for(let index=0;index<=7;index++){const fallback=index===0?CAL_LABEL_H:positions[index-1]+cellSize+CAL_GAP;let candidate=fallback;if(callback)try{const supplied=callback(index);Number.isFinite(supplied)&&supplied>=0&&(index===0||supplied>=positions[index-1]+cellSize)&&(candidate=supplied)}catch{candidate=fallback}positions.push(candidate)}return this.cachedRowGeometry={callback,cellSize,positions},positions}weekAtX(x,weekCount){const positions=this.calendarColumnPositions(),cellSize=this.calendarCellSize();for(let week=0;week<weekCount;week++){const start=positions[week];if(x>=start&&x<start+cellSize)return week}return null}weekdayAtY(y){const positions=this.calendarRowPositions(),cellSize=this.calendarCellSize();for(let weekday=0;weekday<7;weekday++){const start=positions[weekday];if(y>=start&&y<start+cellSize)return weekday}return null}weekdayLabels(firstWeekStart){const formatter=getDateTimeFormat(this.effectiveLocale||void 0,{weekday:"short",timeZone:"UTC"}),labels=["","","","","","",""];for(const weekday of[1,3,5]){const row=(weekday-this.normalizedFirstDayOfWeek+7)%7;labels[row]=this.calendarWeekdayLabelText?.(weekday)??formatter.format(new Date(firstWeekStart.getTime()+row*MS_PER_DAY))}return labels}paintCalendarAxisLabels(ctx,cellSize,cs,firstWeekStart,monthLabels){ctx.fillStyle=this.labelColor(cs),ctx.font=this.labelFont(cs);for(const month of monthLabels)ctx.fillText(month.label,this.columnXFor(month.week),CAL_LABEL_H-4);const available=this.calendarPadLeft-CAL_WEEKDAY_LABEL_INSET*2;this.weekdayLabels(firstWeekStart).forEach((label,weekday)=>{const shown=label?this.ellipsize(ctx,label,available):"";shown&&ctx.fillText(shown,CAL_WEEKDAY_LABEL_INSET,this.rowYFor(weekday)+cellSize-1)})}drawCalendar(){if(!this.canvas)return;const{weekCount,firstWeekStart,monthLabels}=this.cachedCalendarGrid,cs=this.ownerDocument.defaultView?.getComputedStyle(this);if(!cs)return;const previousResolvedWeekdayWidth=this.resolvedCalendarWeekdayLabelWidth;this.calendarWeekdayLabelWidth==="auto"&&(this.resolvedCalendarWeekdayLabelWidth=this.measureCalendarWeekdayLabelWidth(cs,firstWeekStart));const autoGutterChanged=previousResolvedWeekdayWidth!==this.resolvedCalendarWeekdayLabelWidth,cellSize=this.calendarCellSize(),w=this.columnXFor(Math.max(1,weekCount)),h=this.rowYFor(7),dpr=this.ownerDocument.defaultView?.devicePixelRatio||1;this.canvas.width=w*dpr,this.canvas.height=h*dpr,this.canvas.style.width=`${w}px`,this.canvas.style.height=`${h}px`;const ctx=this.canvas.getContext("2d");if(!ctx)return;ctx.scale(dpr,dpr),ctx.clearRect(0,0,w,h);const buckets=normalizeBucketCount(this.bucketCount),ramp=this.colorRamp(buckets,cs).colors,noDataFill=this.noDataFill(cs);this.canvasColorCache.clear();const bounds=this.cachedValueRange,lo=bounds?bounds[0]:0,hi=bounds?bounds[1]:1;for(let week=0;week<weekCount;week++)for(let weekday=0;weekday<7;weekday++){const value=this.calendarValueAt(week,weekday),x=this.columnXFor(week),y=this.rowYFor(weekday),override=this.cellColor?.(this.calendarPos(week,weekday),value);if(override!=null)ctx.fillStyle=this.resolveCanvasColor(override,cs);else if(this.isNoData(value))ctx.fillStyle=noDataFill;else if(this.scale==="sqrt"){const step=sqrtStep(value,hi,ramp.length);ctx.fillStyle=step<0?noDataFill:ramp[step]}else if(this.cachedColorSteps.length>=2){const step=this.rampBucket(value,lo,hi,ramp.length);ctx.fillStyle=ramp[step]}else ctx.fillStyle=ramp[quartileBucket(value,this.cachedCalendarSortedValues,buckets)];ctx.fillRect(x,y,cellSize,cellSize)}if(this.cachedAnnotations.length)for(const ann of this.cachedAnnotations){if(ann.date==null)continue;const match=this.cachedCalendarCellsByDate.get(ann.date);if(!match)continue;const x=this.columnXFor(match.week),y=this.rowYFor(match.weekday);this.strokeCellState(ctx,x,y,cellSize,"annotation",this.annotationColor(cs))}if(this.selectedCell?.date!=null){const match=this.cachedCalendarCellsByDate.get(this.selectedCell.date);if(match){const x=this.columnXFor(match.week),y=this.rowYFor(match.weekday);this.strokeCellState(ctx,x,y,cellSize,"selected",this.selectedColor(cs))}}if(this.focusedCell&&"week"in this.focusedCell){const{week,weekday}=this.focusedCell;if(week<weekCount&&weekday<7){const x=this.columnXFor(week),y=this.rowYFor(weekday);this.strokeCellState(ctx,x,y,cellSize,"focus",this.focusRingColor(cs))}}this.paintCalendarAxisLabels(ctx,cellSize,cs,firstWeekStart,monthLabels),this.canvasHasContent=!0,autoGutterChanged&&this.accessibleCells&&this.scheduleAfterUpdate(()=>this.requestUpdate(),"heatmap-calendar-accessible-geometry")}matrixCellSize(cols){let size;if(this.fitToWidth&&cols>0){const padLeft=this.matrixPadLeft,hostWidth=this.clientWidth||padLeft+cols*this.cellSize;size=this.clampFitCellSize((hostWidth-padLeft)/cols)}else size=this.cellSize;return this.accessibleCells?Math.max(size,this.accessibleTargetSizePx):size}paintMatrixCell(ctx,row,col,cellSize,cs,rampData,noDataFill){const value=this.matrixValues[row]?.[col]??Number.NaN,bounds=this.cachedValueRange,lo=bounds?bounds[0]:0,hi=bounds?bounds[1]:1,override=this.cellColor?.({row,col},value);if(override!=null)ctx.fillStyle=this.resolveCanvasColor(override,cs);else if(this.isNoData(value))ctx.fillStyle=noDataFill;else if(this.scale==="sqrt"){const step=sqrtStep(value,hi,rampData.colors.length);ctx.fillStyle=step<0?noDataFill:rampData.colors[step]}else this.cachedColorSteps.length>=2?ctx.fillStyle=rampData.colors[this.rampBucket(value,lo,hi,rampData.colors.length)]:ctx.fillStyle=mixRgb(rampData.loRgb,rampData.hiRgb,this.rampAlpha(value,lo,hi));ctx.fillRect(this.matrixPadLeft+col*cellSize,this.matrixPadTop+row*cellSize,cellSize-1,cellSize-1)}paintMatrixFocusOverlays(ctx,row,col,cellSize,cs){const x=this.matrixPadLeft+col*cellSize,y=this.matrixPadTop+row*cellSize;this.cachedMatrixAnnotationPositions.has(`${row}:${col}`)&&this.strokeCellState(ctx,x,y,cellSize,"annotation",this.annotationColor(cs)),this.selectedCell?.row===row&&this.selectedCell.col===col&&this.strokeCellState(ctx,x,y,cellSize,"selected",this.selectedColor(cs)),this.focusedCell&&"row"in this.focusedCell&&this.focusedCell.row===row&&this.focusedCell.col===col&&this.strokeCellState(ctx,x,y,cellSize,"focus",this.focusRingColor(cs))}repaintMatrixFocusCell(pos){if(!pos||!this.canvas)return;const rows=this.matrixRowLabels.length,cols=this.matrixColLabels.length;if(pos.row<0||pos.row>=rows||pos.col<0||pos.col>=cols)return;const cellSize=this.matrixCellSize(cols),x=this.matrixPadLeft+pos.col*cellSize,y=this.matrixPadTop+pos.row*cellSize,ctx=this.canvas.getContext("2d");if(!ctx)return;ctx.clearRect(x-RING_LINE_WIDTH-1,y-RING_LINE_WIDTH-1,cellSize+2*(RING_LINE_WIDTH+1),cellSize+2*(RING_LINE_WIDTH+1));const cs=this.ownerDocument.defaultView?.getComputedStyle(this);cs&&(this.paintMatrixCell(ctx,pos.row,pos.col,cellSize,cs,this.colorRamp(RAMP_STEPS,cs),this.noDataFill(cs)),this.paintMatrixFocusOverlays(ctx,pos.row,pos.col,cellSize,cs))}paintCalendarCell(ctx,week,weekday,cellSize,cs,ramp,noDataFill){const value=this.calendarValueAt(week,weekday),bounds=this.cachedValueRange,lo=bounds?bounds[0]:0,hi=bounds?bounds[1]:1,override=this.cellColor?.(this.calendarPos(week,weekday),value);if(override!=null)ctx.fillStyle=this.resolveCanvasColor(override,cs);else if(this.isNoData(value))ctx.fillStyle=noDataFill;else if(this.scale==="sqrt"){const step=sqrtStep(value,hi,ramp.length);ctx.fillStyle=step<0?noDataFill:ramp[step]}else this.cachedColorSteps.length>=2?ctx.fillStyle=ramp[this.rampBucket(value,lo,hi,ramp.length)]:ctx.fillStyle=ramp[quartileBucket(value,this.cachedCalendarSortedValues,ramp.length)];ctx.fillRect(this.columnXFor(week),this.rowYFor(weekday),cellSize,cellSize)}paintCalendarFocusOverlays(ctx,week,weekday,cellSize,cs){const date=this.calendarDateAt(week,weekday),x=this.columnXFor(week),y=this.rowYFor(weekday),matches=candidate=>candidate?.date===date;this.cachedCalendarAnnotationDates.has(date)&&this.strokeCellState(ctx,x,y,cellSize,"annotation",this.annotationColor(cs)),matches(this.selectedCell??void 0)&&this.strokeCellState(ctx,x,y,cellSize,"selected",this.selectedColor(cs)),this.focusedCell&&"week"in this.focusedCell&&this.focusedCell.week===week&&this.focusedCell.weekday===weekday&&this.strokeCellState(ctx,x,y,cellSize,"focus",this.focusRingColor(cs))}repaintCalendarFocusCell(pos){if(!pos||!this.canvas)return;const{weekCount,firstWeekStart}=this.cachedCalendarGrid;if(pos.week<0||pos.week>=weekCount||pos.weekday<0||pos.weekday>=7)return;const cellSize=this.calendarCellSize(),x=this.columnXFor(pos.week),y=this.rowYFor(pos.weekday),ctx=this.canvas.getContext("2d");if(!ctx)return;ctx.clearRect(x-RING_LINE_WIDTH-1,y-RING_LINE_WIDTH-1,cellSize+2*(RING_LINE_WIDTH+1),cellSize+2*(RING_LINE_WIDTH+1));const cs=this.ownerDocument.defaultView?.getComputedStyle(this);if(!cs)return;const ramp=this.colorRamp(normalizeBucketCount(this.bucketCount),cs).colors;this.paintCalendarCell(ctx,pos.week,pos.weekday,cellSize,cs,ramp,this.noDataFill(cs)),this.paintCalendarFocusOverlays(ctx,pos.week,pos.weekday,cellSize,cs),this.paintCalendarAxisLabels(ctx,cellSize,cs,firstWeekStart,this.cachedCalendarGrid.monthLabels)}drawMatrix(){if(!this.canvas)return;const rows=this.matrixRowLabels.length,cols=this.matrixColLabels.length;if(this.rowLabelWidth==="auto"||this.colLabelHeight==="auto"){const measureStyle=getComputedStyle(this);this.rowLabelWidth==="auto"&&(this.resolvedRowLabelWidth=this.measureRowLabelWidth(measureStyle)),this.colLabelHeight==="auto"&&(this.resolvedColLabelHeight=this.measureColLabelHeight(measureStyle))}const padLeft=this.matrixPadLeft,padTop=this.matrixPadTop,cellSize=this.matrixCellSize(cols),previous=this.lastPaintedMatrixGeometry,geometry=previous&&previous.padLeft===padLeft&&previous.padTop===padTop&&previous.cellSize===cellSize?previous:Object.freeze({padLeft,padTop,cellSize});this.lastPaintedMatrixGeometry=geometry;const geometryChanged=geometry!==previous;geometryChanged&&this.emit("lr-matrix-geometry-change",geometry);const w=padLeft+cols*cellSize,h=padTop+rows*cellSize,dpr=this.ownerDocument.defaultView?.devicePixelRatio||1;this.canvas.width=w*dpr,this.canvas.height=h*dpr,this.canvas.style.width=`${w}px`,this.canvas.style.height=`${h}px`;const ctx=this.canvas.getContext("2d");if(!ctx)return;ctx.scale(dpr,dpr),ctx.clearRect(0,0,w,h);const cs=this.ownerDocument.defaultView?.getComputedStyle(this);if(!cs)return;const bounds=this.cachedValueRange,lo=bounds?bounds[0]:0,hi=bounds?bounds[1]:1,rampData=this.colorRamp(RAMP_STEPS,cs),ramp=rampData.colors,{loRgb,hiRgb}=rampData,noDataFill=this.noDataFill(cs);this.canvasColorCache.clear();for(let r=0;r<rows;r++)for(let c=0;c<cols;c++){const v=this.matrixValues[r]?.[c]??Number.NaN,x=padLeft+c*cellSize,y=padTop+r*cellSize,override=this.cellColor?.({row:r,col:c},v);if(override!=null)ctx.fillStyle=this.resolveCanvasColor(override,cs);else if(this.isNoData(v))ctx.fillStyle=noDataFill;else if(this.scale==="sqrt"){const step=sqrtStep(v,hi,ramp.length);ctx.fillStyle=step<0?noDataFill:ramp[step]}else if(this.cachedColorSteps.length>=2){const step=this.rampBucket(v,lo,hi,ramp.length);ctx.fillStyle=ramp[step]}else{const t=this.rampAlpha(v,lo,hi);ctx.fillStyle=mixRgb(loRgb,hiRgb,t)}ctx.fillRect(x,y,cellSize-1,cellSize-1)}if(this.cachedAnnotations.length)for(const ann of this.cachedAnnotations){if(ann.row==null||ann.col==null||ann.row<0||ann.row>=rows||ann.col<0||ann.col>=cols)continue;const x=padLeft+ann.col*cellSize,y=padTop+ann.row*cellSize;this.strokeCellState(ctx,x,y,cellSize,"annotation",this.annotationColor(cs))}if(this.selectedCell?.row!=null&&this.selectedCell.col!=null){const{row,col}=this.selectedCell;if(row>=0&&row<rows&&col>=0&&col<cols){const x=padLeft+col*cellSize,y=padTop+row*cellSize;this.strokeCellState(ctx,x,y,cellSize,"selected",this.selectedColor(cs))}}if(this.focusedCell&&"row"in this.focusedCell){const{row,col}=this.focusedCell;if(row<rows&&col<cols){const x=padLeft+col*cellSize,y=padTop+row*cellSize;this.strokeCellState(ctx,x,y,cellSize,"focus",this.focusRingColor(cs))}}this.paintMatrixRowLabels(ctx,padLeft,padTop,cellSize,cs),this.paintMatrixColLabels(ctx,padLeft,padTop,cellSize,cs),this.paintFrozenLabelBands(padLeft,padTop,cellSize,w,h,dpr,cs),this.canvasHasContent=!0,geometryChanged&&this.accessibleCells&&this.scheduleAfterUpdate(()=>this.requestUpdate(),"heatmap-matrix-accessible-geometry")}paintMatrixRowLabels(ctx,padLeft,padTop,cellSize,cs){ctx.fillStyle=this.labelColor(cs),ctx.font=this.labelFont(cs);const rowLabelSpace=padLeft-ROW_LABEL_INSET*2;this.matrixRowLabels.forEach((label,r)=>{const shown=this.ellipsize(ctx,label,rowLabelSpace);shown&&ctx.fillText(shown,ROW_LABEL_INSET,padTop+r*cellSize+cellSize/2+3)})}paintMatrixColLabels(ctx,padLeft,padTop,cellSize,cs){ctx.fillStyle=this.labelColor(cs),ctx.font=this.labelFont(cs);const colRotation=this.effectiveColLabelRotation;if(colRotation===0){this.matrixColLabels.forEach((label,c)=>{ctx.fillText(label,padLeft+c*cellSize+2,padTop-COL_LABEL_INSET)});return}const radians=colRotation*Math.PI/180,previousAlign=ctx.textAlign;ctx.textAlign="right",this.matrixColLabels.forEach((label,c)=>{ctx.save(),ctx.translate(padLeft+c*cellSize+cellSize/2,padTop-COL_LABEL_INSET),ctx.rotate(radians),ctx.fillText(label,0,0),ctx.restore()}),ctx.textAlign=previousAlign}paintFrozenLabelBands(padLeft,padTop,cellSize,width,height,dpr,cs){if(this.effectiveStickyLabels==="none")return;const backdrop=this.stickyLabelBg(cs),rowBand=this.frozenBandCanvas("row-labels");rowBand&&this.paintFrozenBand(rowBand,padLeft,height,dpr,backdrop,bandCtx=>this.paintMatrixRowLabels(bandCtx,padLeft,padTop,cellSize,cs));const colBand=this.frozenBandCanvas("col-labels");colBand&&this.paintFrozenBand(colBand,width,padTop,dpr,backdrop,bandCtx=>this.paintMatrixColLabels(bandCtx,padLeft,padTop,cellSize,cs))}frozenBandCanvas(part){return this.shadowRoot?.querySelector(`[part="${part}"]`)??null}paintFrozenBand(canvas,width,height,dpr,backdrop,paint){canvas.width=width*dpr,canvas.height=height*dpr,canvas.style.width=`${width}px`,canvas.style.height=`${height}px`;const ctx=canvas.getContext("2d");ctx&&(ctx.scale(dpr,dpr),ctx.clearRect(0,0,width,height),ctx.fillStyle=backdrop,ctx.fillRect(0,0,width,height),paint(ctx))}hitTest(x,y){return this.effectiveMode==="calendar"?this.hitTestCalendar(x,y):this.hitTestMatrix(x,y)}hitTestMatrix(x,y){const rows=this.matrixRowLabels.length,cols=this.matrixColLabels.length;if(rows===0||cols===0)return null;const cellSize=this.matrixCellSize(cols),col=Math.floor((x-this.matrixPadLeft)/cellSize),row=Math.floor((y-this.matrixPadTop)/cellSize);if(row<0||row>=rows||col<0||col>=cols)return null;const pos={row,col};return this.isCellInteractive(pos)?pos:null}firstInteractiveMatrixCell(rows,cols){for(let r=0;r<rows;r++)for(let c=0;c<cols;c++)if(this.isCellInteractive({row:r,col:c}))return{row:r,col:c};return null}nextInteractiveMatrixCell(row,col,dRow,dCol,rows,cols){let r=row,c=col;for(;;){const nr=Math.min(rows-1,Math.max(0,r+dRow)),nc=Math.min(cols-1,Math.max(0,c+dCol));if(nr===r&&nc===c)return{row,col};if(r=nr,c=nc,this.isCellInteractive({row:r,col:c}))return{row:r,col:c}}}firstInteractiveCalendarCell(weekCount){for(let week=0;week<weekCount;week++)for(let weekday=0;weekday<7;weekday++){const pos=this.calendarPos(week,weekday);if(this.isCellInteractive(pos))return pos}return null}nextInteractiveCalendarCell(week,weekday,dWeek,dWeekday,weekCount){let w=week,d=weekday;for(;;){const nw=Math.min(weekCount-1,Math.max(0,w+dWeek)),nd=Math.min(6,Math.max(0,d+dWeekday));if(nw===w&&nd===d)return this.calendarPos(week,weekday);w=nw,d=nd;const pos=this.calendarPos(w,d);if(this.isCellInteractive(pos))return pos}}hitTestCalendar(x,y){const{weekCount}=this.cachedCalendarGrid;if(weekCount===0)return null;const week=this.weekAtX(x,weekCount),weekday=this.weekdayAtY(y);if(week===null||weekday===null)return null;const pos=this.calendarPos(week,weekday);return this.isCellInteractive(pos)?pos:null}calendarCellAt(pos){const match=this.cachedCalendarCellsByPos.get(`${pos.week}:${pos.weekday}`);return match?{date:match.date,value:match.value}:{date:this.calendarDateAt(pos.week,pos.weekday),value:this.calendarValueAt(pos.week,pos.weekday)}}calendarValueAt(week,weekday){const match=this.cachedCalendarCellsByPos.get(`${week}:${weekday}`);return match?match.value:this.signedDomain?Number.NaN:-1}calendarDateAt(week,weekday){const index=week*7+weekday;return this.cachedCalendarDateByPos[index]??isoDateAtOffset(this.cachedCalendarGrid.firstWeekStart,index)}calendarPos(week,weekday){return{week,weekday,date:this.calendarDateAt(week,weekday)}}cellRect(pos){if("week"in pos){const cellSize2=this.calendarCellSize();return{x:this.columnXFor(pos.week),y:this.rowYFor(pos.weekday),w:cellSize2,h:cellSize2}}const cellSize=this.matrixCellSize(this.matrixColLabels.length);return{x:this.matrixPadLeft+pos.col*cellSize,y:this.matrixPadTop+pos.row*cellSize,w:cellSize-1,h:cellSize-1}}accessibleCellRect(pos){if("week"in pos||!this.lastPaintedMatrixGeometry)return this.cellRect(pos);const{padLeft,padTop,cellSize}=this.lastPaintedMatrixGeometry;return{x:padLeft+pos.col*cellSize,y:padTop+pos.row*cellSize,w:cellSize-1,h:cellSize-1}}defaultCellText(pos){return"week"in pos?this.calendarCellText(pos):this.matrixCellText(pos)}matrixCellText(pos){const rowLabel=this.matrixRowLabels[pos.row]??this.localize("heatmapDefaultRowLabel",void 0,{n:this.formatCount(pos.row+1)}),colLabel=this.matrixColLabels[pos.col]??this.localize("heatmapDefaultColLabel",void 0,{n:this.formatCount(pos.col+1)}),v=this.matrixValues[pos.row]?.[pos.col],valueText=v==null||this.isNoData(v)?this.localize("heatmapNoDataValue"):this.formatNumericValue(v);return this.localize("heatmapMatrixCellLabel",void 0,{row:rowLabel,col:colLabel,value:valueText})}calendarCellText(pos){const{date,value}=this.calendarCellAt(pos),label=parseIsoDate(date).toLocaleString(this.effectiveLocale||void 0,{month:"short",day:"numeric",timeZone:"UTC"}),valueText=this.isNoData(value)?this.localize("heatmapNoDataValue"):this.formatNumericValue(value);return this.localize("heatmapCalendarCellLabel",void 0,{date:label,value:valueText})}valueAt(pos){return"week"in pos?this.calendarCellAt(pos).value:this.matrixValues[pos.row]?.[pos.col]??-1}resolveCellText(pos){return this.cellText?this.cellText(pos,this.valueAt(pos)):this.defaultCellText(pos)}isCellInteractive(pos){return this.cellInteractive?.(pos,this.valueAt(pos))??!0}announce(pos){const text=this.resolveCellText(pos),announcement=this.isSelectedPos(pos)?this.localize("heatmapSelectedCellLabel",void 0,{cell:text}):text;this.liveText=announcement,this.announcementSink?.announce(announcement)}emitCellClick(pos){if(this.isCellInteractive(pos))if("week"in pos){const{date,value}=this.calendarCellAt(pos);this.emit("lr-cell-click",{date,value})}else{const value=this.matrixValues[pos.row]?.[pos.col]??-1;this.emit("lr-cell-click",{row:pos.row,col:pos.col,value})}}get gridScrollport(){return this.shadowRoot?.querySelector('[part="grid"]')??null}measureTooltip(){if(!this.gridScrollport)return;const tooltip=this.shadowRoot?.querySelector('[part="tooltip"]');if(!tooltip||tooltip.hidden)return;const view=this.ownerDocument.defaultView,gap=view?Math.abs(finiteNumber(Number.parseFloat(view.getComputedStyle(tooltip).marginBlockStart),0)):0,inline=tooltip.offsetWidth,block=tooltip.offsetHeight+gap;inline===this.tooltipSize.inline&&block===this.tooltipSize.block||(this.tooltipSize={inline,block},this.requestUpdate())}tooltipAnchor(pos){const rect=this.cellRect(pos),center=rect.x+rect.w/2,port=this.gridScrollport;if(!port)return{style:{left:`${center}px`,top:`${rect.y}px`},below:!1};const{inline,block}=this.tooltipSize,windowStart=port.scrollLeft+(this.freezesRowLabels?this.matrixPadLeft:0),windowEnd=port.scrollLeft+port.clientWidth,windowTop=port.scrollTop+(this.freezesColLabels?this.matrixPadTop:0),windowBottom=port.scrollTop+port.clientHeight,below=rect.y-block<windowTop&&rect.y+rect.h+block<=windowBottom;return{style:{left:`${Math.max(windowStart+inline/2,Math.min(center,windowEnd-inline/2))}px`,top:`${below?rect.y+rect.h:rect.y}px`},below}}scrollCellIntoView(pos){const port=this.gridScrollport;if(!port)return;const rect=this.cellRect(pos),bandInline=this.freezesRowLabels?this.matrixPadLeft:0,bandBlock=this.freezesColLabels?this.matrixPadTop:0,left=Math.min(Math.max(port.scrollLeft,rect.x+rect.w-port.clientWidth),rect.x-bandInline),top=Math.min(Math.max(port.scrollTop,rect.y+rect.h-port.clientHeight),rect.y-bandBlock);left!==port.scrollLeft&&(port.scrollLeft=left),top!==port.scrollTop&&(port.scrollTop=top)}samePos(a,b){return a===b?!0:!a||!b?!1:"week"in a&&"week"in b?a.week===b.week&&a.weekday===b.weekday:"row"in a&&"row"in b?a.row===b.row&&a.col===b.col:!1}onMatrixKeyDown(e){const rows=this.matrixRowLabels.length,cols=this.matrixColLabels.length;if(rows===0||cols===0)return;if(e.key==="Enter"||e.key===" "){e.preventDefault(),this.focusedCell&&this.emitCellClick(this.focusedCell);return}if(!ARROW_KEYS.has(e.key))return;if(e.preventDefault(),!this.focusedCell||!("row"in this.focusedCell)){const next2=this.firstInteractiveMatrixCell(rows,cols);if(!next2)return;this.focusedCell=next2,this.announce(next2),this.scrollCellIntoView(next2);return}const{row,col}=this.focusedCell;let dRow=0,dCol=0;e.key==="ArrowUp"?dRow=-1:e.key==="ArrowDown"?dRow=1:e.key==="ArrowLeft"?dCol=-1:e.key==="ArrowRight"&&(dCol=1);const next=this.nextInteractiveMatrixCell(row,col,dRow,dCol,rows,cols);this.focusedCell=next,this.announce(next),this.scrollCellIntoView(next)}onCalendarKeyDown(e){const{weekCount}=this.cachedCalendarGrid;if(weekCount===0)return;if(e.key==="Enter"||e.key===" "){e.preventDefault(),this.focusedCell&&this.emitCellClick(this.focusedCell);return}if(!ARROW_KEYS.has(e.key))return;if(e.preventDefault(),!this.focusedCell||!("week"in this.focusedCell)){const next2=this.firstInteractiveCalendarCell(weekCount);if(!next2)return;this.focusedCell=next2,this.announce(next2);return}const{week,weekday}=this.focusedCell;let dWeek=0,dWeekday=0;e.key==="ArrowUp"?dWeekday=-1:e.key==="ArrowDown"?dWeekday=1:e.key==="ArrowLeft"?dWeek=-1:e.key==="ArrowRight"&&(dWeek=1);const next=this.nextInteractiveCalendarCell(week,weekday,dWeek,dWeekday,weekCount);this.focusedCell=next,this.announce(next)}resolveCanvasColor(value,cs){const cached=this.canvasColorCache.get(value);if(cached!==void 0)return cached;const fallback=this.noDataFill(cs);let candidate=value;if(value.includes("var(")){if(this.colorProbe||(this.colorProbe=this.ownerDocument.createElement("span"),this.colorProbe.style.cssText="position:absolute;width:0;height:0;overflow:hidden;visibility:hidden;pointer-events:none;",this.shadowRoot.appendChild(this.colorProbe)),this.colorProbe.style.color="",this.colorProbe.style.color=value,!this.colorProbe.style.color)return this.canvasColorCache.set(value,fallback),fallback;candidate=this.ownerDocument.defaultView?.getComputedStyle(this.colorProbe).color||fallback}const ctx=getScratchCtx(this.ownerDocument);if(!ctx)return fallback;ctx.fillStyle="rgb(1, 2, 3)";const firstSentinel=ctx.fillStyle;ctx.fillStyle=candidate;let resolved=ctx.fillStyle;if(resolved===firstSentinel){ctx.fillStyle="rgb(4, 5, 6)";const secondSentinel=ctx.fillStyle;ctx.fillStyle=candidate,resolved=ctx.fillStyle,resolved===secondSentinel&&(resolved=fallback)}return this.canvasColorCache.set(value,resolved),resolved}rebuildAccessiblePositions(){const positions=[];if(this.effectiveMode==="calendar"){const{weekCount}=this.cachedCalendarGrid;for(let week=0;week<weekCount;week++)for(let weekday=0;weekday<7;weekday++){const pos=this.calendarPos(week,weekday);this.isCellInteractive(pos)&&positions.push(pos)}}else for(let row=0;row<this.matrixRowLabels.length;row++)for(let col=0;col<this.matrixColLabels.length;col++){const pos={row,col};this.isCellInteractive(pos)&&positions.push(pos)}this.cachedAccessiblePositions=positions,this.cachedAccessiblePositionsByKey=new Map(positions.map(position=>[this.accessibleCellKey(position),position])),this.cachedAccessiblePositionIndexByKey=new Map(positions.map((position,index)=>[this.accessibleCellKey(position),index]))}accessibleCellPositions(){return this.cachedAccessiblePositions}accessibleCellKey(pos){return"week"in pos?`calendar-${pos.week}-${pos.weekday}`:`matrix-${pos.row}-${pos.col}`}accessibleCellIdentity(pos){return"week"in pos?pos.date:this.accessibleCellKey(pos)}accessibleCellAtKey(key){return this.cachedAccessiblePositionsByKey.get(key)??null}focusAccessibleCell(pos){pos&&this.updateComplete.then(()=>{[...this.shadowRoot?.querySelectorAll('[part="cell"]')??[]].find(candidate=>candidate.dataset.cellKey===this.accessibleCellKey(pos))?.focus()})}renderAccessibleCells(){if(!this.accessibleCells)return html``;const positions=this.accessibleCellPositions(),tabStop=this.focusedCell??positions[0]??null,focusIndex=tabStop?this.cachedAccessiblePositionIndexByKey.get(this.accessibleCellKey(tabStop))??0:0,start=Math.max(0,Math.min(Math.max(0,positions.length-MAX_ACCESSIBLE_HEATMAP_CELLS),focusIndex-Math.floor(MAX_ACCESSIBLE_HEATMAP_CELLS/2))),renderedPositions=positions.slice(start,start+MAX_ACCESSIBLE_HEATMAP_CELLS),renderedRows=new Map;for(const pos of renderedPositions){const rowIndex="week"in pos?pos.weekday+1:pos.row+1,row=renderedRows.get(rowIndex);row?row.push(pos):renderedRows.set(rowIndex,[pos])}const rowCount=this.effectiveMode==="calendar"?7:this.matrixRowLabels.length,colCount=this.effectiveMode==="calendar"?this.cachedCalendarGrid.weekCount:this.matrixColLabels.length;return html`
1
+ var __decorate=function(decorators,target,key,desc){var c=arguments.length,r=c<3?target:desc===null?desc=Object.getOwnPropertyDescriptor(target,key):desc,d;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")r=Reflect.decorate(decorators,target,key,desc);else for(var i=decorators.length-1;i>=0;i--)(d=decorators[i])&&(r=(c<3?d(r):c>3?d(target,key,r):d(target,key))||r);return c>3&&r&&Object.defineProperty(target,key,r),r};import{html,nothing}from"lit";import{property,query,state}from"lit/decorators.js";import{styleMap}from"lit/directives/style-map.js";import{LyraElement}from"../../../internal/lyra-element.js";import{srOnly}from"../../../internal/a11y.js";import{finiteInteger,finiteNumber,finiteRange}from"../../../internal/numbers.js";import{getScratchCtx}from"../../../internal/canvas.js";import{resolveCssLength}from"../../../internal/css-length.js";import{ThemeWatcher}from"../../../internal/theme-watcher.js";import{activeElementIn}from"../../../internal/active-element.js";import{linearAlpha,linearBucket,midpointAlpha,midpointBucket,minMax,sqrtStep}from"./heatmap-scale.js";import{styles}from"./heatmap.styles.js";import{buildCalendarGrid,parseIsoDate,quartileBucket}from"./calendar-grid.js";import{getDateTimeFormat,getNumberFormat}from"../../../internal/intl-cache.js";import{sanitizeCssColor}from"../../../internal/safe-css.js";import{literalSetConverter}from"../../../internal/converters.js";import{devWarnOnce}from"../../../internal/dev-mode-attribute-warning.js";import{acquireAnnouncementSink}from"../../../internal/announcer.js";import{LYRA_DEFAULT_heatmapCalendarCellLabel,LYRA_DEFAULT_heatmapCalendarLabel,LYRA_DEFAULT_heatmapDecorationLimit,LYRA_DEFAULT_heatmapDefaultColLabel,LYRA_DEFAULT_heatmapDefaultRowLabel,LYRA_DEFAULT_heatmapMatrixCellLabel,LYRA_DEFAULT_heatmapMatrixLabel,LYRA_DEFAULT_heatmapNoDataValue,LYRA_DEFAULT_heatmapProjectionLimit,LYRA_DEFAULT_heatmapSelectedCellLabel,LYRA_DEFAULT_heatmapValueLabel}from"../../../internal/default-strings.generated.js";const PAD_LEFT=60,PAD_TOP=20,ROW_LABEL_INSET=4,MAX_ROW_LABEL_FRACTION=.4,MAX_COL_LABEL_HEIGHT=240,COL_LABEL_INSET=6,labelExtentConverter={fromAttribute:value=>{if(value===null)return;const trimmed=value.trim();if(trimmed.toLowerCase()==="auto")return"auto";const parsed=Number.parseFloat(trimmed);return Number.isFinite(parsed)&&parsed>=0?parsed:void 0},toAttribute:value=>value===void 0?null:String(value)},STICKY_LABELS=literalSetConverter(["none","rows","cols","both"],"none"),FALLBACK_NO_DATA_FILL="rgba(128,128,128,0.25)",FALLBACK_STICKY_LABEL_BG="#ffffff",RAMP_STEPS=7,FALLBACK_SCALE_LO="#cde2fb",FALLBACK_SCALE_HI="#0969da",FALLBACK_LABEL_FONT="10px system-ui, sans-serif",CAL_PAD_LEFT=28,CAL_WEEKDAY_LABEL_INSET=2,CAL_LABEL_H=16,CAL_CELL=11,CAL_GAP=2,DEFAULT_MATRIX_CELL_SIZE=22,DEFAULT_ACCESSIBLE_TARGET_SIZE_PX=40,DEFAULT_BUCKET_COUNT=5,FIT_MIN_CELL=4,MAX_BUCKET_COUNT=256,MAX_HEATMAP_CELLS=1e4,MAX_HEATMAP_DECORATIONS=256,MAX_ACCESSIBLE_HEATMAP_CELLS=400,RING_LINE_WIDTH=2,FALLBACK_FOCUS_RING_COLOR="#0969da",FALLBACK_ANNOTATION_COLOR="#cf222e",FALLBACK_SELECTED_COLOR="#1a7f37",ARROW_KEYS=new Set(["ArrowUp","ArrowDown","ArrowLeft","ArrowRight"]),MS_PER_DAY=864e5;function isoDateAtOffset(firstWeekStart,dayOffset){return new Date(firstWeekStart.getTime()+dayOffset*MS_PER_DAY).toISOString().slice(0,10)}function legendStopsChanged(value,previous){if(Object.is(value,previous))return!1;if(!Array.isArray(value)||!Array.isArray(previous)||value.length!==previous.length)return!0;for(let index=0;index<value.length;index+=1){if(Object.hasOwn(value,index)!==Object.hasOwn(previous,index))return!0;const next=value[index],before=previous[index];if(!next||!before){if(!Object.is(next,before))return!0;continue}if(!Object.is(next.value,before.value)||!Object.is(next.color,before.color)||!Object.is(next.label,before.label)||!Object.is(next.partOfRamp,before.partOfRamp))return!0}return!1}const HEX_RE=/^([0-9a-f]{3,4}|[0-9a-f]{6}|[0-9a-f]{8})$/i,RGB_RE=/^rgba?\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)(?:\s*,\s*([\d.]+))?\s*\)/i;function hexToRgb(hex){const clean=hex.trim().replace("#","");if(!HEX_RE.test(clean))return null;const hasAlpha=clean.length===4||clean.length===8,full=clean.length<=4?clean.split("").map(c=>c+c).join(""):clean,num=Number.parseInt(full,16);return hasAlpha?[num>>>24&255,num>>>16&255,num>>>8&255,(num&255)/255]:[num>>16&255,num>>8&255,num&255,1]}function parseRgbString(value){const match=RGB_RE.exec(value);if(!match)return null;const a=match[4]===void 0?1:Number(match[4]);return[Number(match[1]),Number(match[2]),Number(match[3]),a]}function resolveViaPixelReadback(ctx){try{ctx.clearRect(0,0,1,1),ctx.fillRect(0,0,1,1);const[r=0,g=0,b=0,a=0]=ctx.getImageData(0,0,1,1).data;return[r,g,b,a/255]}catch{return null}}function formatRgb([r,g,b,a]){const alpha=Math.min(1,Math.max(0,a));return alpha>=1?`rgb(${r}, ${g}, ${b})`:`rgba(${r}, ${g}, ${b}, ${Math.round(alpha*1e3)/1e3})`}function warnInvalidColor(color){devWarnOnce(`heatmap-invalid-color:${color}`,`<lr-heatmap> could not parse "${color}" (set via --lr-heatmap-scale-lo/-hi) as a CSS color; falling back to the default ramp endpoint.`)}let warnedNoCanvasContext=!1;function warnNoCanvasContext(){warnedNoCanvasContext||(warnedNoCanvasContext=!0,console.warn("<lr-heatmap>: no 2D canvas context is available in this environment; color resolution for non-hex/non-rgb values (e.g. oklch(), color(srgb ...), named colors) will fall back to the given default instead of resolving the requested color."))}function normalizeBucketCount(bucketCount){return finiteInteger(bucketCount,DEFAULT_BUCKET_COUNT,2,MAX_BUCKET_COUNT)}const optionalCellSizeConverter={fromAttribute(value){if(value===null||value.trim()==="")return;const parsed=Number(value);return Number.isFinite(parsed)?parsed:void 0}},DEFAULT_MATRIX_DATA=Object.freeze({kind:"matrix",rowLabels:Object.freeze([]),colLabels:Object.freeze([]),values:Object.freeze([])});function normalizeCellSizeClamp(value){if(!(value==null||!Number.isFinite(value)))return finiteRange(value,FIT_MIN_CELL,FIT_MIN_CELL)}const bucketCountConverter={fromAttribute(value){return value===null?DEFAULT_BUCKET_COUNT:normalizeBucketCount(Number(value))}};function resolveRgb(color,fallbackHex,ownerDocument){const fallback=hexToRgb(fallbackHex)??[0,0,0,1],direct=hexToRgb(color);if(direct)return direct;const ctx=getScratchCtx(ownerDocument);if(!ctx)return warnNoCanvasContext(),fallback;const sentinel="rgb(1, 2, 3)";ctx.fillStyle=sentinel;const sentinelNormalized=ctx.fillStyle;if(ctx.fillStyle=color,ctx.fillStyle===sentinelNormalized&&color.trim()!==sentinel)return warnInvalidColor(color),fallback;const normalized=ctx.fillStyle;return hexToRgb(normalized)??parseRgbString(normalized)??resolveViaPixelReadback(ctx)??fallback}function mixRgb(from,to,t){const clamped=Math.min(1,Math.max(0,t)),r=Math.round(from[0]+(to[0]-from[0])*clamped),g=Math.round(from[1]+(to[1]-from[1])*clamped),b=Math.round(from[2]+(to[2]-from[2])*clamped),a=from[3]+(to[3]-from[3])*clamped;return formatRgb([r,g,b,a])}class LyraHeatmap extends LyraElement{static{this.defaultStrings={...super.defaultStrings,heatmapCalendarCellLabel:LYRA_DEFAULT_heatmapCalendarCellLabel,heatmapCalendarLabel:LYRA_DEFAULT_heatmapCalendarLabel,heatmapDecorationLimit:LYRA_DEFAULT_heatmapDecorationLimit,heatmapDefaultColLabel:LYRA_DEFAULT_heatmapDefaultColLabel,heatmapDefaultRowLabel:LYRA_DEFAULT_heatmapDefaultRowLabel,heatmapMatrixCellLabel:LYRA_DEFAULT_heatmapMatrixCellLabel,heatmapMatrixLabel:LYRA_DEFAULT_heatmapMatrixLabel,heatmapNoDataValue:LYRA_DEFAULT_heatmapNoDataValue,heatmapProjectionLimit:LYRA_DEFAULT_heatmapProjectionLimit,heatmapSelectedCellLabel:LYRA_DEFAULT_heatmapSelectedCellLabel,heatmapValueLabel:LYRA_DEFAULT_heatmapValueLabel}}static{this.ownedCollectionProperties=Object.freeze(["data","annotations","legendStops","colorSteps"])}static{this.identityCollectionObjectProperties=Object.freeze(["data"])}static{this.styles=[LyraElement.styles,styles,srOnly]}static get observedAttributes(){return[...new Set([...super.observedAttributes,"role"])]}get effectiveMode(){return this.data.kind}get stickyLabels(){return this._stickyLabels}set stickyLabels(next){const normalized=STICKY_LABELS.normalizeReflected(this,"sticky-labels",next),old=this._stickyLabels;old!==normalized&&(this._stickyLabels=normalized,this.requestUpdate("stickyLabels",old))}get effectiveStickyLabels(){return this.effectiveMode==="matrix"?this._stickyLabels:"none"}get freezesRowLabels(){const sticky=this.effectiveStickyLabels;return sticky==="rows"||sticky==="both"}get freezesColLabels(){const sticky=this.effectiveStickyLabels;return sticky==="cols"||sticky==="both"}get effectiveColLabelRotation(){if(typeof this.colLabelRotation!="number")return 0;const degrees=finiteNumber(this.colLabelRotation,0);return Math.min(90,Math.max(0,degrees))}get matrixPadLeft(){if(this.rowLabelWidth==="auto")return this.resolvedRowLabelWidth;if(typeof this.rowLabelWidth!="number")return PAD_LEFT;const resolved=finiteNumber(this.rowLabelWidth,PAD_LEFT);return resolved>=0?resolved:PAD_LEFT}get matrixGeometry(){if(this.effectiveMode==="matrix")return this.lastPaintedMatrixGeometry}get matrixPadTop(){if(this.colLabelHeight==="auto")return this.resolvedColLabelHeight;if(typeof this.colLabelHeight!="number")return PAD_TOP;const resolved=finiteNumber(this.colLabelHeight,PAD_TOP);return resolved>=0?resolved:PAD_TOP}measureColLabelHeight(cs){const labels=this.matrixColLabels;if(labels.length===0)return PAD_TOP;const ctx=getScratchCtx(this.ownerDocument);if(!ctx)return PAD_TOP;ctx.font=this.labelFont(cs);let widest=0;for(const label of labels)widest=Math.max(widest,ctx.measureText(label).width);const radians=this.effectiveColLabelRotation*Math.PI/180,projected=widest*Math.sin(radians);return Math.max(PAD_TOP,Math.min(Math.ceil(projected)+COL_LABEL_INSET,MAX_COL_LABEL_HEIGHT))}measureRowLabelWidth(cs){const labels=this.matrixRowLabels;if(labels.length===0)return PAD_LEFT;const ctx=getScratchCtx(this.ownerDocument);if(!ctx)return PAD_LEFT;ctx.font=this.labelFont(cs);let widest=0;for(const label of labels)widest=Math.max(widest,ctx.measureText(label).width);const hostWidth=this.clientWidth||0,cap=hostWidth>0?hostWidth*MAX_ROW_LABEL_FRACTION:Number.POSITIVE_INFINITY;return Math.min(Math.max(PAD_LEFT,Math.ceil(widest)+ROW_LABEL_INSET*2),cap)}ellipsize(ctx,label,maxWidth){if(maxWidth<=0)return"";if(ctx.measureText(label).width<=maxWidth)return label;const characters=[...label];let kept=characters.length-1;for(;kept>0;){const candidate=`${characters.slice(0,kept).join("")}…`;if(ctx.measureText(candidate).width<=maxWidth)return candidate;kept-=1}return ctx.measureText("…").width<=maxWidth?"…":""}get calendarPadLeft(){const requested=this.calendarWeekdayLabelWidth;return requested==="auto"?this.resolvedCalendarWeekdayLabelWidth:requested??CAL_PAD_LEFT}measureCalendarWeekdayLabelWidth(cs,firstWeekStart){const ctx=getScratchCtx(this.ownerDocument);if(!ctx)return CAL_PAD_LEFT;ctx.font=this.labelFont(cs);let widest=0;for(const label of this.weekdayLabels(firstWeekStart))label&&(widest=Math.max(widest,ctx.measureText(label).width));const hostWidth=this.clientWidth||0,cap=hostWidth>0?Math.max(CAL_PAD_LEFT,hostWidth*MAX_ROW_LABEL_FRACTION):Number.POSITIVE_INFINITY;return Math.min(Math.max(CAL_PAD_LEFT,Math.ceil(widest)+CAL_WEEKDAY_LABEL_INSET*2),cap)}get matrixRowLabels(){return this.cachedMatrixData.rowLabels}get matrixColLabels(){return this.cachedMatrixData.colLabels}get matrixValues(){return this.cachedMatrixData.values}get calendarDays(){return this.data.kind==="calendar"?this.data.days:[]}get calendarData(){return this.data.kind==="calendar"?this.data:void 0}get cellSize(){return this._cellSize??(this.effectiveMode==="calendar"?CAL_CELL:DEFAULT_MATRIX_CELL_SIZE)}set cellSize(value){const oldValue=this._cellSize;this._cellSize=value==null?void 0:finiteRange(value,this.effectiveMode==="calendar"?CAL_CELL:DEFAULT_MATRIX_CELL_SIZE,1),this.requestUpdate("cellSize",oldValue)}get signedDomain(){return this.domain!==void 0||this.midpoint!==void 0}rampAlpha(value,lo,hi){const anchor=this.midpoint;return anchor===void 0?linearAlpha(value,lo,hi):midpointAlpha(value,lo,hi,anchor)}rampBucket(value,lo,hi,steps){const anchor=this.midpoint;return anchor===void 0?linearBucket(value,lo,hi,steps):midpointBucket(value,lo,hi,anchor,steps)}isNoData(value){return Number.isFinite(value)?value<0&&!this.signedDomain:!0}get maxCellSize(){return this._maxCellSize}set maxCellSize(value){const oldValue=this._maxCellSize;this._maxCellSize=normalizeCellSizeClamp(value),this.requestUpdate("maxCellSize",oldValue)}get minCellSize(){return this._minCellSize}set minCellSize(value){const oldValue=this._minCellSize;this._minCellSize=normalizeCellSizeClamp(value),this.requestUpdate("minCellSize",oldValue)}get normalizedFirstDayOfWeek(){return(finiteInteger(this.calendarData?.firstDayOfWeek??0,0)%7+7)%7}get bucketCount(){return this._bucketCount}set bucketCount(value){const oldValue=this._bucketCount;this._bucketCount=normalizeBucketCount(value),this.requestUpdate("bucketCount",oldValue)}get calendarWeekdayLabelText(){return this.calendarData?.weekdayLabelText}get calendarWeekdayLabelWidth(){const value=this.calendarData?.weekdayLabelWidth;if(value==="auto")return value;if(typeof value!="number")return;const resolved=finiteNumber(value,CAL_PAD_LEFT);return resolved>=0?resolved:void 0}get calendarMonthLabelText(){return this.calendarData?.monthLabelText}get calendarColumnX(){return this.calendarData?.columnX}get calendarRowY(){return this.calendarData?.rowY}constructor(){super(),this.data=DEFAULT_MATRIX_DATA,this._stickyLabels="none",this.resolvedColLabelHeight=PAD_TOP,this.resolvedRowLabelWidth=PAD_LEFT,this.resolvedCalendarWeekdayLabelWidth=CAL_PAD_LEFT,this.scale="linear",this.fitToWidth=!1,this._bucketCount=DEFAULT_BUCKET_COUNT,this.annotations=[],this.selectedCell=null,this.accessibleCells=!1,this.cachedValueRange=null,this.cachedMatrixData={rowLabels:[],colLabels:[],values:[],truncated:!1},this.cachedCalendarGrid=buildCalendarGrid(this.calendarDays),this.cachedCalendarSortedValues=[],this.cachedCalendarCellsByPos=new Map,this.cachedCalendarCellsByDate=new Map,this.cachedAnnotations=[],this.cachedLegendStops=[],this.cachedColorSteps=[],this.cachedCalendarAnnotationDates=new Set,this.cachedMatrixAnnotationPositions=new Set,this.decorationProjectionTruncated=!1,this.cachedCalendarDateByPos=[],this.cachedAccessiblePositions=[],this.cachedAccessiblePositionsByKey=new Map,this.cachedAccessiblePositionIndexByKey=new Map,this.cachedRamp=null,this.canvasHasContent=!1,this.canvasVisible=!0,this.drawDirty=!1,this.hoverCell=null,this.focusedCell=null,this.liveText="",this.accessibleTargetSizePx=DEFAULT_ACCESSIBLE_TARGET_SIZE_PX,this.restoringAccessibleFocus=!1,this.accessibleFocusGeneration=0,this.authorRole=null,this.authorAriaLabel=null,this.generatedAriaLabel="",this.syncingGeneratedSemantics=!1,this.onDprChange=()=>{this.watchDpr(),this.requestDraw()},this.scheduleDraw=()=>{if(this.drawFrameRequest)return;const owner=this.ownerDocument.defaultView;if(!owner||!this.isConnected)return;const request={owner,handle:0};request.handle=owner.requestAnimationFrame(()=>{this.drawFrameRequest===request&&(this.drawFrameRequest=void 0,this.isConnected&&this.ownerDocument.defaultView===owner&&this.requestDraw())}),this.drawFrameRequest=request},this.tooltipSize={inline:0,block:0},this.onPointerMove=e=>{const next=this.hitTest(e.offsetX,e.offsetY);this.samePos(this.hoverCell,next)||(this.hoverCell=next)},this.onPointerLeave=()=>{this.hoverCell=null},this.onCanvasClick=e=>{const pos=this.hitTest(e.offsetX,e.offsetY);pos&&(this.focusedCell=pos,this.announce(pos),this.emitCellClick(pos))},this.onKeyDown=e=>{this.effectiveMode==="calendar"?this.onCalendarKeyDown(e):this.onMatrixKeyDown(e)},this.canvasColorCache=new Map,this.onAccessibleCellFocus=e=>{if(this.restoringAccessibleFocus)return;const key=e.currentTarget.dataset.cellKey,pos=key?this.accessibleCellAtKey(key):null;pos&&(this.focusedCell=pos,this.announce(pos))},this.onAccessibleCellClick=e=>{const key=e.currentTarget.dataset.cellKey,pos=key?this.accessibleCellAtKey(key):null;pos&&(this.focusedCell=pos,this.announce(pos),this.emitCellClick(pos))},this.onAccessibleCellKeyDown=e=>{if(!ARROW_KEYS.has(e.key))return;const key=e.currentTarget.dataset.cellKey,pos=key?this.accessibleCellAtKey(key):null;pos&&(e.preventDefault(),this.focusedCell=pos,this.onKeyDown(e),this.focusAccessibleCell(this.focusedCell))},new ThemeWatcher(this,()=>this.refreshTheme())}warnOnLegendRampMismatch(){const rampColors=this.cachedColorSteps.map(color=>sanitizeCssColor(color)??color);if(rampColors.length===0)return;const legendColors=this.cachedLegendStops.filter(stop=>!!stop.color&&stop.partOfRamp!==!1).map(stop=>sanitizeCssColor(stop.color??"")??stop.color??"");legendColors.length===0||legendColors.length===rampColors.length&&legendColors.every((color,index)=>color===rampColors[index])||devWarnOnce("lyra-heatmap-legend-ramp-mismatch",`<${this.localName}>: legendStops describes ${legendColors.length} colour(s) that do not match the ${rampColors.length} colorSteps the cells are painted from, so the legend may misdescribe the ramp. Supply legendStops built from the same array as colorSteps, or omit it to keep the built-in gradient key.`)}attributeChangedCallback(name,oldValue,value){super.attributeChangedCallback(name,oldValue,value),!(oldValue===value||this.syncingGeneratedSemantics)&&(name==="role"&&(this.authorRole=value),name==="aria-label"&&(this.authorAriaLabel=value))}connectedCallback(){super.connectedCallback(),this.syncAnnouncementSink(),this.refreshAccessibleTargetSize();const owner=this.ownerDocument.defaultView,ResizeObserverCtor=owner?.ResizeObserver;if(owner&&ResizeObserverCtor){let observer;observer=new ResizeObserverCtor(()=>{!this.isConnected||this.ownerDocument.defaultView!==owner||this.resizeObserver!==observer||this.scheduleDraw()}),this.resizeObserver=observer,observer.observe(this)}const IntersectionObserverCtor=owner?.IntersectionObserver;if(this.canvasVisible=!0,owner&&IntersectionObserverCtor){let observer;observer=new IntersectionObserverCtor(entries=>{if(!this.isConnected||this.ownerDocument.defaultView!==owner||this.intersectionObserver!==observer)return;const entry=entries.find(candidate=>candidate.target===this);!entry||entry.isIntersecting===this.canvasVisible||(this.canvasVisible=entry.isIntersecting,this.canvasVisible&&this.drawDirty&&this.scheduleDraw())}),this.intersectionObserver=observer,observer.observe(this)}this.cachedRamp=null,this.canvasColorCache.clear(),this.watchDpr()}disconnectedCallback(){super.disconnectedCallback(),this.accessibleFocusGeneration++,this.pendingAccessibleFocus=void 0,this.pendingAccessibleFocusOrigin=void 0,this.restoringAccessibleFocus=!1,this.releaseAnnouncementSink(),this.hoverCell=null,this.focusedCell=null,this.liveText="",this.canvasHasContent=!1,this.drawDirty=!0,this.resizeObserver?.disconnect(),this.resizeObserver=void 0,this.intersectionObserver?.disconnect(),this.intersectionObserver=void 0,this.canvasVisible=!0,this.clearDprWatcher(),this.cancelDrawFrame()}releaseAnnouncementSink(){this.announcementSink?.release(),this.announcementSink=void 0}syncAnnouncementSink(){if(!this.isConnected){this.releaseAnnouncementSink();return}this.announcementSink?.element.ownerDocument!==this.ownerDocument&&(this.releaseAnnouncementSink(),this.announcementSink=acquireAnnouncementSink("polite",{document:this.ownerDocument,source:this}))}watchDpr(){this.clearDprWatcher();const owner=this.ownerDocument.defaultView;if(!owner||typeof owner.matchMedia!="function")return;const query2=owner.matchMedia(`(resolution: ${owner.devicePixelRatio}dppx)`),listener=()=>{!this.isConnected||this.ownerDocument.defaultView!==owner||this.dprQuery!==query2||this.onDprChange()};this.dprQuery=query2,this.dprChangeListener=listener,query2.addEventListener("change",listener)}clearDprWatcher(){this.dprQuery&&this.dprChangeListener&&this.dprQuery.removeEventListener("change",this.dprChangeListener),this.dprQuery=void 0,this.dprChangeListener=void 0}willUpdate(changed){super.willUpdate(changed),(changed.has("data")||changed.has("domain")||changed.has("midpoint")||!this.hasUpdated)&&this.rebuildCanonicalMatrixData(),(changed.has("annotations")||changed.has("legendStops")||changed.has("colorSteps")||!this.hasUpdated)&&this.rebuildBoundedDecorations();const accessibleModeChanged=changed.has("accessibleCells")&&this.hasUpdated,collectionChanged=changed.has("data")||changed.has("cellInteractive"),activeRenderedControl=collectionChanged||accessibleModeChanged?activeElementIn(this.shadowRoot):null,activeAccessibleCell=activeRenderedControl?.matches('[part="cell"]')?activeRenderedControl:null,renderedAccessibleCells=activeAccessibleCell?.matches('[part="cell"]')?[...this.shadowRoot?.querySelectorAll('[part="cell"]')??[]]:[],accessibleFocusSnapshot=activeAccessibleCell?.matches('[part="cell"]')?{identity:activeAccessibleCell.dataset.cellIdentity,index:renderedAccessibleCells.indexOf(activeAccessibleCell)}:void 0;if(collectionChanged&&(this.focusedCell=null,this.hoverCell=null,this.liveText=""),changed.has("data")||changed.has("locale")||!this.hasUpdated){this.cachedCalendarGrid=buildCalendarGrid(this.calendarDays,this.normalizedFirstDayOfWeek,this.calendarMonthLabelText,this.effectiveLocale),this.cachedCalendarSortedValues=this.cachedCalendarGrid.cells.map(cell=>cell.value).filter(value=>!this.isNoData(value)).sort((a,b)=>a-b),this.cachedCalendarCellsByPos=new Map(this.cachedCalendarGrid.cells.map(cell=>[`${cell.week}:${cell.weekday}`,cell])),this.cachedCalendarCellsByDate=new Map(this.cachedCalendarGrid.cells.map(cell=>[cell.date,cell]));const{firstWeekStart,weekCount}=this.cachedCalendarGrid;this.cachedCalendarDateByPos=Array.from({length:weekCount*7},(_,index)=>isoDateAtOffset(firstWeekStart,index))}if(changed.has("colorSteps")||!this.hasUpdated){const colorSteps=this.cachedColorSteps.map(sanitizeCssColor);colorSteps.length>=2&&colorSteps.every(color=>color!==void 0)?this.style.setProperty("--lr-heatmap-color-steps-gradient",`linear-gradient(to right, ${colorSteps.join(", ")})`):this.style.removeProperty("--lr-heatmap-color-steps-gradient")}if((changed.has("data")||changed.has("domain")||changed.has("midpoint")||!this.hasUpdated)&&(this.cachedValueRange=this.computeValueRange()),(collectionChanged||!this.hasUpdated)&&this.rebuildAccessiblePositions(),accessibleFocusSnapshot){const positions=this.accessibleCellPositions(),target=(accessibleFocusSnapshot.identity==null?void 0:positions.find(pos=>this.accessibleCellIdentity(pos)===accessibleFocusSnapshot.identity))??positions[Math.min(Math.max(accessibleFocusSnapshot.index,0),positions.length-1)]??null;this.focusedCell=target,this.liveText=target?this.resolveCellText(target):"",this.pendingAccessibleFocus=target??"base",this.pendingAccessibleFocusOrigin=activeAccessibleCell??void 0,this.restoringAccessibleFocus=!0,this.accessibleFocusGeneration++}if(accessibleModeChanged){const previouslyAccessible=changed.get("accessibleCells")===!0;if(previouslyAccessible&&!this.accessibleCells&&activeAccessibleCell){const key=activeAccessibleCell.dataset.cellKey,target=key?this.accessibleCellAtKey(key):null;target&&(this.focusedCell=target,this.liveText=this.resolveCellText(target)),this.pendingAccessibleFocus="canvas",this.pendingAccessibleFocusOrigin=activeAccessibleCell,this.restoringAccessibleFocus=!0,this.accessibleFocusGeneration++}else if(!previouslyAccessible&&this.accessibleCells&&activeRenderedControl?.matches('[part="canvas"]')){const positions=this.accessibleCellPositions(),target=this.focusedCell?positions.find(pos=>this.samePos(pos,this.focusedCell))??positions[0]??null:positions[0]??null;this.focusedCell=target,this.liveText=target?this.resolveCellText(target):"",this.pendingAccessibleFocus=target??"base",this.pendingAccessibleFocusOrigin=activeRenderedControl,this.restoringAccessibleFocus=!0,this.accessibleFocusGeneration++}}const bounds=this.cachedValueRange,range=bounds?`${this.formatNumericValue(bounds[0])}–${this.formatNumericValue(bounds[1])}`:this.localize("heatmapNoDataValue"),valueLabel=this.localizedValueLabel();let label;if(this.effectiveMode==="calendar")label=this.localize("heatmapCalendarLabel",void 0,{days:this.formatCount(this.cachedCalendarGrid.cells.length),label:valueLabel,range});else{const rows=this.matrixRowLabels.length,cols=this.matrixColLabels.length;label=this.localize("heatmapMatrixLabel",void 0,{rows:this.formatCount(rows),cols:this.formatCount(cols),label:valueLabel,range})}const selectedText=this.selectedCellDescription(),generatedAriaLabel=[label,selectedText,this.projectionDescription()].filter(Boolean).join(" ");this.generatedAriaLabel=generatedAriaLabel,this.syncingGeneratedSemantics=!0;try{this.authorRole===null&&this.setAttribute("role","group"),this.authorAriaLabel===null&&this.setAttribute("aria-label",generatedAriaLabel)}finally{this.syncingGeneratedSemantics=!1}}rebuildBoundedDecorations(){this.cachedAnnotations=this.annotations.slice(0,MAX_HEATMAP_DECORATIONS).map(entry=>({...entry})),this.cachedLegendStops=(this.legendStops??[]).slice(0,MAX_HEATMAP_DECORATIONS).map(entry=>({...entry})),this.cachedColorSteps=(this.colorSteps??[]).slice(0,MAX_HEATMAP_DECORATIONS),this.warnOnLegendRampMismatch(),this.cachedCalendarAnnotationDates=new Set(this.cachedAnnotations.flatMap(annotation=>annotation.date==null?[]:[annotation.date])),this.cachedMatrixAnnotationPositions=new Set(this.cachedAnnotations.flatMap(annotation=>annotation.row==null||annotation.col==null?[]:[`${annotation.row}:${annotation.col}`])),this.decorationProjectionTruncated=this.annotations.length>MAX_HEATMAP_DECORATIONS||(this.legendStops?.length??0)>MAX_HEATMAP_DECORATIONS||(this.colorSteps?.length??0)>MAX_HEATMAP_DECORATIONS}get projectionTruncated(){return this.decorationProjectionTruncated||(this.effectiveMode==="calendar"?this.cachedCalendarGrid.truncated:this.cachedMatrixData.truncated)}get cellProjectionTruncated(){return this.effectiveMode==="calendar"?this.cachedCalendarGrid.truncated:this.cachedMatrixData.truncated}projectedCellCount(){return this.effectiveMode==="calendar"?this.cachedCalendarGrid.weekCount*7:this.matrixRowLabels.length*this.matrixColLabels.length}projectionDescription(){const messages=[];return this.cellProjectionTruncated&&messages.push(this.localize("heatmapProjectionLimit",void 0,{count:this.formatCount(this.projectedCellCount())})),this.decorationProjectionTruncated&&messages.push(this.localize("heatmapDecorationLimit",void 0,{count:this.formatCount(MAX_HEATMAP_DECORATIONS)})),messages.join(" ")}rebuildCanonicalMatrixData(){if(this.data.kind!=="matrix"){this.cachedMatrixData={rowLabels:[],colLabels:[],values:[],truncated:!1};return}const colCount=Math.min(this.data.colLabels.length,MAX_HEATMAP_CELLS),rowLimit=colCount===0?Math.min(this.data.rowLabels.length,MAX_HEATMAP_CELLS):Math.floor(MAX_HEATMAP_CELLS/colCount),rowCount=Math.min(this.data.rowLabels.length,rowLimit),rowLabels=this.data.rowLabels.slice(0,rowCount).map(String),colLabels=this.data.colLabels.slice(0,colCount).map(String),source=this.data,values=Array.from({length:rowCount},(_,row)=>Array.from({length:colCount},(_2,col)=>source.values[row]?.[col]??(this.signedDomain?Number.NaN:-1)));this.cachedMatrixData={rowLabels,colLabels,values,truncated:rowCount!==this.data.rowLabels.length||colCount!==this.data.colLabels.length||this.data.values.some((row,index)=>index>=rowCount||row.length>colCount)}}selectedCellDescription(){if(!this.selectedCell)return"";if(this.effectiveMode==="calendar"){if(this.selectedCell.date==null)return"";const match=this.cachedCalendarCellsByDate.get(this.selectedCell.date);return match?this.localize("heatmapSelectedCellLabel",void 0,{cell:this.calendarCellText({week:match.week,weekday:match.weekday,date:match.date})}):""}const{row,col}=this.selectedCell;return row==null||col==null||row<0||row>=this.matrixRowLabels.length||col<0||col>=this.matrixColLabels.length?"":this.localize("heatmapSelectedCellLabel",void 0,{cell:this.matrixCellText({row,col})})}computeValueRange(){const pinned=this.domain;if(pinned){const[lo,hi]=pinned;if(Number.isFinite(lo)&&Number.isFinite(hi)&&lo!==hi)return lo<hi?[lo,hi]:[hi,lo]}const source=this.effectiveMode==="calendar"?this.cachedCalendarGrid.cells.map(cell=>cell.value):this.matrixValues.flat();return minMax(source.filter(v=>!this.isNoData(v)))}localizedValueLabel(){return this.valueLabel===void 0?this.localize("heatmapValueLabel"):this.valueLabel}formatNumericValue(value){return getNumberFormat(this.effectiveLocale||void 0).format(value)}updated(changed){if(super.updated(changed),this.hoverCell&&this.effectiveStickyLabels!=="none"&&this.scheduleAfterUpdate(()=>this.measureTooltip(),"heatmap-tooltip-metrics"),["data","cellSize","maxCellSize","minCellSize","valueLabel","scale","domain","midpoint","fitToWidth","rowLabelWidth","colLabelHeight","colLabelRotation","bucketCount","annotations","focusedCell","colorSteps","cellColor","selectedCell","legendStops","accessibleCells","accessibleTargetSizePx","locale","stickyLabels"].some(name=>changed.has(name))){if(changed.has("focusedCell")&&[...changed.keys()].every(key=>key==="focusedCell"||key==="liveText")&&this.repaintFocusRing(changed.get("focusedCell")))return;this.requestDraw()}const pending=this.pendingAccessibleFocus;if(pending===void 0)return;this.pendingAccessibleFocus=void 0;const origin=this.pendingAccessibleFocusOrigin;this.pendingAccessibleFocusOrigin=void 0;const generation=this.accessibleFocusGeneration;this.scheduleAfterUpdate(()=>{try{if(generation!==this.accessibleFocusGeneration||!this.isConnected)return;if(origin){const internalActive=activeElementIn(this.shadowRoot),documentActive=activeElementIn(this.ownerDocument),focusStayedAtOrigin=internalActive===origin,originWasRemovedWithoutReplacement=internalActive===null&&(documentActive===null||documentActive===this||documentActive===this.ownerDocument.body);if(!focusStayedAtOrigin&&!originWasRemovedWithoutReplacement)return}if(pending==="base"){this.shadowRoot?.querySelector('[part="base"]')?.focus();return}if(pending==="canvas"){this.shadowRoot?.querySelector('[part="canvas"]')?.focus();return}const identity=this.accessibleCellIdentity(pending);[...this.shadowRoot?.querySelectorAll('[part="cell"]')??[]].find(candidate=>candidate.dataset.cellIdentity===identity)?.focus()}finally{this.restoringAccessibleFocus=!1}},"heatmap-accessible-focus")}refreshTheme(){this.cachedRamp=null,this.refreshAccessibleTargetSize()||this.requestDraw()}refreshAccessibleTargetSize(){const raw=this.ownerDocument.defaultView?.getComputedStyle(this).getPropertyValue("--lr-icon-button-size").trim()??"",resolved=resolveCssLength(raw,{host:this}),next=resolved!==void 0&&Number.isFinite(resolved)&&resolved>0?resolved:DEFAULT_ACCESSIBLE_TARGET_SIZE_PX;return next===this.accessibleTargetSizePx?!1:(this.accessibleTargetSizePx=next,!0)}scaleEndpoints(cs){const lo=cs.getPropertyValue("--lr-heatmap-scale-lo").trim()||cs.getPropertyValue("--_lr-heatmap-scale-lo").trim()||FALLBACK_SCALE_LO,hi=cs.getPropertyValue("--lr-heatmap-scale-hi").trim()||cs.getPropertyValue("--_lr-heatmap-scale-hi").trim()||FALLBACK_SCALE_HI;return[lo,hi]}labelColor(cs){return cs.getPropertyValue("--lr-color-text-quiet").trim()||"#6b7280"}labelFont(cs){return cs.getPropertyValue("--lr-heatmap-label-font").trim()||cs.getPropertyValue("--_lr-heatmap-label-font").trim()||FALLBACK_LABEL_FONT}stickyLabelBg(cs){const raw=cs.getPropertyValue("--lr-heatmap-sticky-label-bg").trim()||cs.getPropertyValue("--_lr-heatmap-sticky-label-bg").trim()||FALLBACK_STICKY_LABEL_BG;return formatRgb(resolveRgb(raw,FALLBACK_STICKY_LABEL_BG,this.ownerDocument))}noDataFill(cs){return cs.getPropertyValue("--lr-heatmap-no-data-fill").trim()||cs.getPropertyValue("--_lr-heatmap-no-data-fill").trim()||FALLBACK_NO_DATA_FILL}focusRingColor(cs){return cs.getPropertyValue("--lr-heatmap-focus-ring-color").trim()||cs.getPropertyValue("--_lr-heatmap-focus-ring-color").trim()||FALLBACK_FOCUS_RING_COLOR}annotationColor(cs){return cs.getPropertyValue("--lr-heatmap-annotation-color").trim()||cs.getPropertyValue("--_lr-heatmap-annotation-color").trim()||FALLBACK_ANNOTATION_COLOR}selectedColor(cs){return cs.getPropertyValue("--lr-heatmap-selected-color").trim()||cs.getPropertyValue("--_lr-heatmap-selected-color").trim()||FALLBACK_SELECTED_COLOR}strokeCellState(ctx,x,y,size,state2,color){const inset=Math.min(state2==="annotation"?.5:state2==="selected"?3.5:6.5,Math.max(.5,(size-RING_LINE_WIDTH-1)/2)),extent=Math.max(1,size-inset*2);ctx.lineWidth=RING_LINE_WIDTH,ctx.strokeStyle=color,ctx.setLineDash?.(state2==="annotation"?[]:state2==="selected"?[4,2]:[1,2]),ctx.strokeRect(x+inset,y+inset,extent,extent),ctx.setLineDash?.([])}isSelectedPos(pos){return this.selectedCell?"week"in pos?this.selectedCell.date==null?!1:this.calendarCellAt(pos).date===this.selectedCell.date:this.selectedCell.row===pos.row&&this.selectedCell.col===pos.col:!1}draw(){if(!this.canvasVisible){this.drawDirty=!0;return}this.drawDirty=!1,this.canvasHasContent=!1,this.effectiveMode==="calendar"?this.drawCalendar():this.drawMatrix()}requestDraw(){this.drawDirty=!0,this.canvasVisible&&this.draw()}repaintFocusRing(previous){if(!this.canvasHasContent||!this.canvas)return!1;const current=this.focusedCell;if(this.effectiveMode==="calendar"){if(previous&&!("week"in previous)||current&&!("week"in current))return!1;this.repaintCalendarFocusCell(previous&&"week"in previous?previous:null),current&&(!previous||!this.samePos(previous,current))&&this.repaintCalendarFocusCell(current)}else{if(previous&&!("row"in previous)||current&&!("row"in current))return!1;this.repaintMatrixFocusCell(previous&&"row"in previous?previous:null),current&&(!previous||!this.samePos(previous,current))&&this.repaintMatrixFocusCell(current)}return!0}cancelDrawFrame(){const request=this.drawFrameRequest;request&&request.owner.cancelAnimationFrame(request.handle),this.drawFrameRequest=void 0}resolveColorStep(color,fallback){const safe=sanitizeCssColor(color);if(!safe)return fallback;const scope=this.ownerDocument.createElement("span"),probe=this.ownerDocument.createElement("span");scope.hidden=!0,scope.style.color=fallback,probe.style.color=safe,scope.append(probe),this.renderRoot.append(scope);try{return this.ownerDocument.defaultView?.getComputedStyle(probe).color.trim()||fallback}finally{scope.remove()}}colorRamp(bucketCount,cs){const steps=this.cachedColorSteps;if(steps&&steps.length>=2){const key2=`steps ${steps.join(" ")}`;if(this.cachedRamp?.key===key2)return this.cachedRamp;const resolved=steps.map((color,index)=>this.resolveColorStep(color,index===steps.length-1?FALLBACK_SCALE_HI:FALLBACK_SCALE_LO)),colors2=resolved.map(color=>formatRgb(resolveRgb(color,FALLBACK_SCALE_LO,this.ownerDocument))),loRgb2=resolveRgb(resolved[0],FALLBACK_SCALE_LO,this.ownerDocument),hiRgb2=resolveRgb(resolved[resolved.length-1],FALLBACK_SCALE_HI,this.ownerDocument);return this.cachedRamp={key:key2,colors:colors2,loRgb:loRgb2,hiRgb:hiRgb2},this.cachedRamp}const[scaleLo,scaleHi]=this.scaleEndpoints(cs),normalizedBucketCount=normalizeBucketCount(bucketCount),key=`${scaleLo}\0${scaleHi}\0${normalizedBucketCount}`;if(this.cachedRamp?.key===key)return this.cachedRamp;const loRgb=resolveRgb(scaleLo,FALLBACK_SCALE_LO,this.ownerDocument),hiRgb=resolveRgb(scaleHi,FALLBACK_SCALE_HI,this.ownerDocument),colors=Array.from({length:normalizedBucketCount},(_,i)=>mixRgb(loRgb,hiRgb,i/(normalizedBucketCount-1)));return this.cachedRamp={key,colors,loRgb,hiRgb},this.cachedRamp}calendarCellSize(){const{weekCount}=this.cachedCalendarGrid;let size;if(this.fitToWidth&&weekCount>0){const hostWidth=this.clientWidth||this.calendarPadLeft+weekCount*(this.cellSize+CAL_GAP);size=this.clampFitCellSize((hostWidth-this.calendarPadLeft)/weekCount-CAL_GAP)}else size=this.cellSize;return this.accessibleCells?Math.max(size,this.accessibleTargetSizePx):size}clampFitCellSize(size){const floored=finiteRange(size,FIT_MIN_CELL,Math.max(FIT_MIN_CELL,this.minCellSize??FIT_MIN_CELL));return this.maxCellSize==null?floored:Math.min(floored,this.maxCellSize)}columnXFor(week){return this.calendarColumnPositions()[week]??this.calendarPadLeft}rowYFor(weekday){return this.calendarRowPositions()[weekday]??CAL_LABEL_H}calendarColumnPositions(){const cellSize=this.calendarCellSize(),weekCount=this.cachedCalendarGrid.weekCount,callback=this.calendarColumnX,padLeft=this.calendarPadLeft,cached=this.cachedColumnGeometry;if(cached!==void 0&&cached.callback===callback&&cached.padLeft===padLeft&&cached.cellSize===cellSize&&cached.weekCount===weekCount)return cached.positions;const positions=[];for(let index=0;index<=weekCount;index++){const fallback=index===0?padLeft:positions[index-1]+cellSize+CAL_GAP;let candidate=fallback;if(callback)try{const supplied=callback(index);Number.isFinite(supplied)&&supplied>=0&&(index===0||supplied>=positions[index-1]+cellSize)&&(candidate=supplied)}catch{candidate=fallback}positions.push(candidate)}return this.cachedColumnGeometry={callback,padLeft,cellSize,weekCount,positions},positions}calendarRowPositions(){const cellSize=this.calendarCellSize(),callback=this.calendarRowY,cached=this.cachedRowGeometry;if(cached!==void 0&&cached.callback===callback&&cached.cellSize===cellSize)return cached.positions;const positions=[];for(let index=0;index<=7;index++){const fallback=index===0?CAL_LABEL_H:positions[index-1]+cellSize+CAL_GAP;let candidate=fallback;if(callback)try{const supplied=callback(index);Number.isFinite(supplied)&&supplied>=0&&(index===0||supplied>=positions[index-1]+cellSize)&&(candidate=supplied)}catch{candidate=fallback}positions.push(candidate)}return this.cachedRowGeometry={callback,cellSize,positions},positions}weekAtX(x,weekCount){const positions=this.calendarColumnPositions(),cellSize=this.calendarCellSize();for(let week=0;week<weekCount;week++){const start=positions[week];if(x>=start&&x<start+cellSize)return week}return null}weekdayAtY(y){const positions=this.calendarRowPositions(),cellSize=this.calendarCellSize();for(let weekday=0;weekday<7;weekday++){const start=positions[weekday];if(y>=start&&y<start+cellSize)return weekday}return null}weekdayLabels(firstWeekStart){const formatter=getDateTimeFormat(this.effectiveLocale||void 0,{weekday:"short",timeZone:"UTC"}),labels=["","","","","","",""];for(const weekday of[1,3,5]){const row=(weekday-this.normalizedFirstDayOfWeek+7)%7;labels[row]=this.calendarWeekdayLabelText?.(weekday)??formatter.format(new Date(firstWeekStart.getTime()+row*MS_PER_DAY))}return labels}paintCalendarAxisLabels(ctx,cellSize,cs,firstWeekStart,monthLabels){ctx.fillStyle=this.labelColor(cs),ctx.font=this.labelFont(cs);for(const month of monthLabels)ctx.fillText(month.label,this.columnXFor(month.week),CAL_LABEL_H-4);const available=this.calendarPadLeft-CAL_WEEKDAY_LABEL_INSET*2;this.weekdayLabels(firstWeekStart).forEach((label,weekday)=>{const shown=label?this.ellipsize(ctx,label,available):"";shown&&ctx.fillText(shown,CAL_WEEKDAY_LABEL_INSET,this.rowYFor(weekday)+cellSize-1)})}drawCalendar(){if(!this.canvas)return;const{weekCount,firstWeekStart,monthLabels}=this.cachedCalendarGrid,cs=this.ownerDocument.defaultView?.getComputedStyle(this);if(!cs)return;const previousResolvedWeekdayWidth=this.resolvedCalendarWeekdayLabelWidth;this.calendarWeekdayLabelWidth==="auto"&&(this.resolvedCalendarWeekdayLabelWidth=this.measureCalendarWeekdayLabelWidth(cs,firstWeekStart));const autoGutterChanged=previousResolvedWeekdayWidth!==this.resolvedCalendarWeekdayLabelWidth,cellSize=this.calendarCellSize(),w=this.columnXFor(Math.max(1,weekCount)),h=this.rowYFor(7),dpr=this.ownerDocument.defaultView?.devicePixelRatio||1;this.canvas.width=w*dpr,this.canvas.height=h*dpr,this.canvas.style.width=`${w}px`,this.canvas.style.height=`${h}px`;const ctx=this.canvas.getContext("2d");if(!ctx)return;ctx.scale(dpr,dpr),ctx.clearRect(0,0,w,h);const buckets=normalizeBucketCount(this.bucketCount),ramp=this.colorRamp(buckets,cs).colors,noDataFill=this.noDataFill(cs);this.canvasColorCache.clear();const bounds=this.cachedValueRange,lo=bounds?bounds[0]:0,hi=bounds?bounds[1]:1;for(let week=0;week<weekCount;week++)for(let weekday=0;weekday<7;weekday++){const value=this.calendarValueAt(week,weekday),x=this.columnXFor(week),y=this.rowYFor(weekday),override=this.cellColor?.(this.calendarPos(week,weekday),value);if(override!=null)ctx.fillStyle=this.resolveCanvasColor(override,cs);else if(this.isNoData(value))ctx.fillStyle=noDataFill;else if(this.scale==="sqrt"){const step=sqrtStep(value,hi,ramp.length);ctx.fillStyle=step<0?noDataFill:ramp[step]}else if(this.cachedColorSteps.length>=2){const step=this.rampBucket(value,lo,hi,ramp.length);ctx.fillStyle=ramp[step]}else ctx.fillStyle=ramp[quartileBucket(value,this.cachedCalendarSortedValues,buckets)];ctx.fillRect(x,y,cellSize,cellSize)}if(this.cachedAnnotations.length)for(const ann of this.cachedAnnotations){if(ann.date==null)continue;const match=this.cachedCalendarCellsByDate.get(ann.date);if(!match)continue;const x=this.columnXFor(match.week),y=this.rowYFor(match.weekday);this.strokeCellState(ctx,x,y,cellSize,"annotation",this.annotationColor(cs))}if(this.selectedCell?.date!=null){const match=this.cachedCalendarCellsByDate.get(this.selectedCell.date);if(match){const x=this.columnXFor(match.week),y=this.rowYFor(match.weekday);this.strokeCellState(ctx,x,y,cellSize,"selected",this.selectedColor(cs))}}if(this.focusedCell&&"week"in this.focusedCell){const{week,weekday}=this.focusedCell;if(week<weekCount&&weekday<7){const x=this.columnXFor(week),y=this.rowYFor(weekday);this.strokeCellState(ctx,x,y,cellSize,"focus",this.focusRingColor(cs))}}this.paintCalendarAxisLabels(ctx,cellSize,cs,firstWeekStart,monthLabels),this.canvasHasContent=!0,autoGutterChanged&&this.accessibleCells&&this.scheduleAfterUpdate(()=>this.requestUpdate(),"heatmap-calendar-accessible-geometry")}matrixCellSize(cols){let size;if(this.fitToWidth&&cols>0){const padLeft=this.matrixPadLeft,hostWidth=this.clientWidth||padLeft+cols*this.cellSize;size=this.clampFitCellSize((hostWidth-padLeft)/cols)}else size=this.cellSize;return this.accessibleCells?Math.max(size,this.accessibleTargetSizePx):size}paintMatrixCell(ctx,row,col,cellSize,cs,rampData,noDataFill){const value=this.matrixValues[row]?.[col]??Number.NaN,bounds=this.cachedValueRange,lo=bounds?bounds[0]:0,hi=bounds?bounds[1]:1,override=this.cellColor?.({row,col},value);if(override!=null)ctx.fillStyle=this.resolveCanvasColor(override,cs);else if(this.isNoData(value))ctx.fillStyle=noDataFill;else if(this.scale==="sqrt"){const step=sqrtStep(value,hi,rampData.colors.length);ctx.fillStyle=step<0?noDataFill:rampData.colors[step]}else this.cachedColorSteps.length>=2?ctx.fillStyle=rampData.colors[this.rampBucket(value,lo,hi,rampData.colors.length)]:ctx.fillStyle=mixRgb(rampData.loRgb,rampData.hiRgb,this.rampAlpha(value,lo,hi));ctx.fillRect(this.matrixPadLeft+col*cellSize,this.matrixPadTop+row*cellSize,cellSize-1,cellSize-1)}paintMatrixFocusOverlays(ctx,row,col,cellSize,cs,state2){const x=this.matrixPadLeft+col*cellSize,y=this.matrixPadTop+row*cellSize;state2==="annotation"&&this.cachedMatrixAnnotationPositions.has(`${row}:${col}`)&&this.strokeCellState(ctx,x,y,cellSize,"annotation",this.annotationColor(cs)),state2==="selected"&&this.selectedCell?.row===row&&this.selectedCell.col===col&&this.strokeCellState(ctx,x,y,cellSize,"selected",this.selectedColor(cs)),state2==="focus"&&this.focusedCell&&"row"in this.focusedCell&&this.focusedCell.row===row&&this.focusedCell.col===col&&this.strokeCellState(ctx,x,y,cellSize,"focus",this.focusRingColor(cs))}focusRepaintBounds(ctx,x,y,cellSize){const padding=RING_LINE_WIDTH+1,dpr=ctx.getTransform().a,left=Math.floor((x-padding)*dpr)/dpr,top=Math.floor((y-padding)*dpr)/dpr,right=Math.ceil((x+cellSize+padding)*dpr)/dpr,bottom=Math.ceil((y+cellSize+padding)*dpr)/dpr;return{left,top,width:right-left,height:bottom-top,radius:Math.ceil((2*padding+1/dpr)/cellSize)}}repaintMatrixFocusCell(pos){if(!pos||!this.canvas)return;const rows=this.matrixRowLabels.length,cols=this.matrixColLabels.length;if(pos.row<0||pos.row>=rows||pos.col<0||pos.col>=cols)return;const cellSize=this.matrixCellSize(cols),x=this.matrixPadLeft+pos.col*cellSize,y=this.matrixPadTop+pos.row*cellSize,ctx=this.canvas.getContext("2d");if(!ctx)return;const cs=this.ownerDocument.defaultView?.getComputedStyle(this);if(!cs)return;const{left,top,width,height,radius}=this.focusRepaintBounds(ctx,x,y,cellSize),firstRow=Math.max(0,pos.row-radius),lastRow=Math.min(rows-1,pos.row+radius),firstCol=Math.max(0,pos.col-radius),lastCol=Math.min(cols-1,pos.col+radius),ramp=this.colorRamp(RAMP_STEPS,cs),noData=this.noDataFill(cs);ctx.save();try{ctx.beginPath(),ctx.rect(left,top,width,height),ctx.clip(),ctx.clearRect(left,top,width,height);for(let row=firstRow;row<=lastRow;row++)for(let col=firstCol;col<=lastCol;col++)this.paintMatrixCell(ctx,row,col,cellSize,cs,ramp,noData);for(const state2 of["annotation","selected","focus"])for(let row=firstRow;row<=lastRow;row++)for(let col=firstCol;col<=lastCol;col++)this.paintMatrixFocusOverlays(ctx,row,col,cellSize,cs,state2)}finally{ctx.restore()}}paintCalendarCell(ctx,week,weekday,cellSize,cs,ramp,noDataFill){const value=this.calendarValueAt(week,weekday),bounds=this.cachedValueRange,lo=bounds?bounds[0]:0,hi=bounds?bounds[1]:1,override=this.cellColor?.(this.calendarPos(week,weekday),value);if(override!=null)ctx.fillStyle=this.resolveCanvasColor(override,cs);else if(this.isNoData(value))ctx.fillStyle=noDataFill;else if(this.scale==="sqrt"){const step=sqrtStep(value,hi,ramp.length);ctx.fillStyle=step<0?noDataFill:ramp[step]}else this.cachedColorSteps.length>=2?ctx.fillStyle=ramp[this.rampBucket(value,lo,hi,ramp.length)]:ctx.fillStyle=ramp[quartileBucket(value,this.cachedCalendarSortedValues,ramp.length)];ctx.fillRect(this.columnXFor(week),this.rowYFor(weekday),cellSize,cellSize)}paintCalendarFocusOverlays(ctx,week,weekday,cellSize,cs,state2){const date=this.calendarDateAt(week,weekday),x=this.columnXFor(week),y=this.rowYFor(weekday),matches=candidate=>candidate?.date===date;state2==="annotation"&&this.cachedCalendarCellsByDate.has(date)&&this.cachedCalendarAnnotationDates.has(date)&&this.strokeCellState(ctx,x,y,cellSize,"annotation",this.annotationColor(cs)),state2==="selected"&&this.cachedCalendarCellsByDate.has(date)&&matches(this.selectedCell??void 0)&&this.strokeCellState(ctx,x,y,cellSize,"selected",this.selectedColor(cs)),state2==="focus"&&this.focusedCell&&"week"in this.focusedCell&&this.focusedCell.week===week&&this.focusedCell.weekday===weekday&&this.strokeCellState(ctx,x,y,cellSize,"focus",this.focusRingColor(cs))}repaintCalendarFocusCell(pos){if(!pos||!this.canvas)return;const{weekCount,firstWeekStart}=this.cachedCalendarGrid;if(pos.week<0||pos.week>=weekCount||pos.weekday<0||pos.weekday>=7)return;const cellSize=this.calendarCellSize(),x=this.columnXFor(pos.week),y=this.rowYFor(pos.weekday),ctx=this.canvas.getContext("2d");if(!ctx)return;const cs=this.ownerDocument.defaultView?.getComputedStyle(this);if(!cs)return;const{left,top,width,height,radius}=this.focusRepaintBounds(ctx,x,y,cellSize),firstWeek=Math.max(0,pos.week-radius),lastWeek=Math.min(weekCount-1,pos.week+radius),firstDay=Math.max(0,pos.weekday-radius),lastDay=Math.min(6,pos.weekday+radius),ramp=this.colorRamp(normalizeBucketCount(this.bucketCount),cs).colors,noData=this.noDataFill(cs);ctx.save();try{ctx.beginPath(),ctx.rect(left,top,width,height),ctx.clip(),ctx.clearRect(left,top,width,height);for(let week=firstWeek;week<=lastWeek;week++)for(let day=firstDay;day<=lastDay;day++)this.paintCalendarCell(ctx,week,day,cellSize,cs,ramp,noData);for(const state2 of["annotation","selected","focus"])for(let week=firstWeek;week<=lastWeek;week++)for(let day=firstDay;day<=lastDay;day++)this.paintCalendarFocusOverlays(ctx,week,day,cellSize,cs,state2);this.paintCalendarAxisLabels(ctx,cellSize,cs,firstWeekStart,this.cachedCalendarGrid.monthLabels)}finally{ctx.restore()}}drawMatrix(){if(!this.canvas)return;const rows=this.matrixRowLabels.length,cols=this.matrixColLabels.length;if(this.rowLabelWidth==="auto"||this.colLabelHeight==="auto"){const measureStyle=getComputedStyle(this);this.rowLabelWidth==="auto"&&(this.resolvedRowLabelWidth=this.measureRowLabelWidth(measureStyle)),this.colLabelHeight==="auto"&&(this.resolvedColLabelHeight=this.measureColLabelHeight(measureStyle))}const padLeft=this.matrixPadLeft,padTop=this.matrixPadTop,cellSize=this.matrixCellSize(cols),previous=this.lastPaintedMatrixGeometry,geometry=previous&&previous.padLeft===padLeft&&previous.padTop===padTop&&previous.cellSize===cellSize?previous:Object.freeze({padLeft,padTop,cellSize});this.lastPaintedMatrixGeometry=geometry;const geometryChanged=geometry!==previous;geometryChanged&&this.emit("lr-matrix-geometry-change",geometry);const w=padLeft+cols*cellSize,h=padTop+rows*cellSize,dpr=this.ownerDocument.defaultView?.devicePixelRatio||1;this.canvas.width=w*dpr,this.canvas.height=h*dpr,this.canvas.style.width=`${w}px`,this.canvas.style.height=`${h}px`;const ctx=this.canvas.getContext("2d");if(!ctx)return;ctx.scale(dpr,dpr),ctx.clearRect(0,0,w,h);const cs=this.ownerDocument.defaultView?.getComputedStyle(this);if(!cs)return;const bounds=this.cachedValueRange,lo=bounds?bounds[0]:0,hi=bounds?bounds[1]:1,rampData=this.colorRamp(RAMP_STEPS,cs),ramp=rampData.colors,{loRgb,hiRgb}=rampData,noDataFill=this.noDataFill(cs);this.canvasColorCache.clear();for(let r=0;r<rows;r++)for(let c=0;c<cols;c++){const v=this.matrixValues[r]?.[c]??Number.NaN,x=padLeft+c*cellSize,y=padTop+r*cellSize,override=this.cellColor?.({row:r,col:c},v);if(override!=null)ctx.fillStyle=this.resolveCanvasColor(override,cs);else if(this.isNoData(v))ctx.fillStyle=noDataFill;else if(this.scale==="sqrt"){const step=sqrtStep(v,hi,ramp.length);ctx.fillStyle=step<0?noDataFill:ramp[step]}else if(this.cachedColorSteps.length>=2){const step=this.rampBucket(v,lo,hi,ramp.length);ctx.fillStyle=ramp[step]}else{const t=this.rampAlpha(v,lo,hi);ctx.fillStyle=mixRgb(loRgb,hiRgb,t)}ctx.fillRect(x,y,cellSize-1,cellSize-1)}if(this.cachedAnnotations.length)for(const ann of this.cachedAnnotations){if(ann.row==null||ann.col==null||ann.row<0||ann.row>=rows||ann.col<0||ann.col>=cols)continue;const x=padLeft+ann.col*cellSize,y=padTop+ann.row*cellSize;this.strokeCellState(ctx,x,y,cellSize,"annotation",this.annotationColor(cs))}if(this.selectedCell?.row!=null&&this.selectedCell.col!=null){const{row,col}=this.selectedCell;if(row>=0&&row<rows&&col>=0&&col<cols){const x=padLeft+col*cellSize,y=padTop+row*cellSize;this.strokeCellState(ctx,x,y,cellSize,"selected",this.selectedColor(cs))}}if(this.focusedCell&&"row"in this.focusedCell){const{row,col}=this.focusedCell;if(row<rows&&col<cols){const x=padLeft+col*cellSize,y=padTop+row*cellSize;this.strokeCellState(ctx,x,y,cellSize,"focus",this.focusRingColor(cs))}}this.paintMatrixRowLabels(ctx,padLeft,padTop,cellSize,cs),this.paintMatrixColLabels(ctx,padLeft,padTop,cellSize,cs),this.paintFrozenLabelBands(padLeft,padTop,cellSize,w,h,dpr,cs),this.canvasHasContent=!0,geometryChanged&&this.accessibleCells&&this.scheduleAfterUpdate(()=>this.requestUpdate(),"heatmap-matrix-accessible-geometry")}paintMatrixRowLabels(ctx,padLeft,padTop,cellSize,cs){ctx.fillStyle=this.labelColor(cs),ctx.font=this.labelFont(cs);const rowLabelSpace=padLeft-ROW_LABEL_INSET*2;this.matrixRowLabels.forEach((label,r)=>{const shown=this.ellipsize(ctx,label,rowLabelSpace);shown&&ctx.fillText(shown,ROW_LABEL_INSET,padTop+r*cellSize+cellSize/2+3)})}paintMatrixColLabels(ctx,padLeft,padTop,cellSize,cs){ctx.fillStyle=this.labelColor(cs),ctx.font=this.labelFont(cs);const colRotation=this.effectiveColLabelRotation;if(colRotation===0){this.matrixColLabels.forEach((label,c)=>{ctx.fillText(label,padLeft+c*cellSize+2,padTop-COL_LABEL_INSET)});return}const radians=colRotation*Math.PI/180,previousAlign=ctx.textAlign;ctx.textAlign="right",this.matrixColLabels.forEach((label,c)=>{ctx.save(),ctx.translate(padLeft+c*cellSize+cellSize/2,padTop-COL_LABEL_INSET),ctx.rotate(radians),ctx.fillText(label,0,0),ctx.restore()}),ctx.textAlign=previousAlign}paintFrozenLabelBands(padLeft,padTop,cellSize,width,height,dpr,cs){if(this.effectiveStickyLabels==="none")return;const backdrop=this.stickyLabelBg(cs),rowBand=this.frozenBandCanvas("row-labels");rowBand&&this.paintFrozenBand(rowBand,padLeft,height,dpr,backdrop,bandCtx=>this.paintMatrixRowLabels(bandCtx,padLeft,padTop,cellSize,cs));const colBand=this.frozenBandCanvas("col-labels");colBand&&this.paintFrozenBand(colBand,width,padTop,dpr,backdrop,bandCtx=>this.paintMatrixColLabels(bandCtx,padLeft,padTop,cellSize,cs))}frozenBandCanvas(part){return this.shadowRoot?.querySelector(`[part="${part}"]`)??null}paintFrozenBand(canvas,width,height,dpr,backdrop,paint){canvas.width=width*dpr,canvas.height=height*dpr,canvas.style.width=`${width}px`,canvas.style.height=`${height}px`;const ctx=canvas.getContext("2d");ctx&&(ctx.scale(dpr,dpr),ctx.clearRect(0,0,width,height),ctx.fillStyle=backdrop,ctx.fillRect(0,0,width,height),paint(ctx))}hitTest(x,y){return this.effectiveMode==="calendar"?this.hitTestCalendar(x,y):this.hitTestMatrix(x,y)}hitTestMatrix(x,y){const rows=this.matrixRowLabels.length,cols=this.matrixColLabels.length;if(rows===0||cols===0)return null;const cellSize=this.matrixCellSize(cols),col=Math.floor((x-this.matrixPadLeft)/cellSize),row=Math.floor((y-this.matrixPadTop)/cellSize);if(row<0||row>=rows||col<0||col>=cols)return null;const pos={row,col};return this.isCellInteractive(pos)?pos:null}firstInteractiveMatrixCell(rows,cols){for(let r=0;r<rows;r++)for(let c=0;c<cols;c++)if(this.isCellInteractive({row:r,col:c}))return{row:r,col:c};return null}nextInteractiveMatrixCell(row,col,dRow,dCol,rows,cols){let r=row,c=col;for(;;){const nr=Math.min(rows-1,Math.max(0,r+dRow)),nc=Math.min(cols-1,Math.max(0,c+dCol));if(nr===r&&nc===c)return{row,col};if(r=nr,c=nc,this.isCellInteractive({row:r,col:c}))return{row:r,col:c}}}firstInteractiveCalendarCell(weekCount){for(let week=0;week<weekCount;week++)for(let weekday=0;weekday<7;weekday++){const pos=this.calendarPos(week,weekday);if(this.isCellInteractive(pos))return pos}return null}nextInteractiveCalendarCell(week,weekday,dWeek,dWeekday,weekCount){let w=week,d=weekday;for(;;){const nw=Math.min(weekCount-1,Math.max(0,w+dWeek)),nd=Math.min(6,Math.max(0,d+dWeekday));if(nw===w&&nd===d)return this.calendarPos(week,weekday);w=nw,d=nd;const pos=this.calendarPos(w,d);if(this.isCellInteractive(pos))return pos}}hitTestCalendar(x,y){const{weekCount}=this.cachedCalendarGrid;if(weekCount===0)return null;const week=this.weekAtX(x,weekCount),weekday=this.weekdayAtY(y);if(week===null||weekday===null)return null;const pos=this.calendarPos(week,weekday);return this.isCellInteractive(pos)?pos:null}calendarCellAt(pos){const match=this.cachedCalendarCellsByPos.get(`${pos.week}:${pos.weekday}`);return match?{date:match.date,value:match.value}:{date:this.calendarDateAt(pos.week,pos.weekday),value:this.calendarValueAt(pos.week,pos.weekday)}}calendarValueAt(week,weekday){const match=this.cachedCalendarCellsByPos.get(`${week}:${weekday}`);return match?match.value:this.signedDomain?Number.NaN:-1}calendarDateAt(week,weekday){const index=week*7+weekday;return this.cachedCalendarDateByPos[index]??isoDateAtOffset(this.cachedCalendarGrid.firstWeekStart,index)}calendarPos(week,weekday){return{week,weekday,date:this.calendarDateAt(week,weekday)}}cellRect(pos){if("week"in pos){const cellSize2=this.calendarCellSize();return{x:this.columnXFor(pos.week),y:this.rowYFor(pos.weekday),w:cellSize2,h:cellSize2}}const cellSize=this.matrixCellSize(this.matrixColLabels.length);return{x:this.matrixPadLeft+pos.col*cellSize,y:this.matrixPadTop+pos.row*cellSize,w:cellSize-1,h:cellSize-1}}accessibleCellRect(pos){if("week"in pos||!this.lastPaintedMatrixGeometry)return this.cellRect(pos);const{padLeft,padTop,cellSize}=this.lastPaintedMatrixGeometry;return{x:padLeft+pos.col*cellSize,y:padTop+pos.row*cellSize,w:cellSize-1,h:cellSize-1}}defaultCellText(pos){return"week"in pos?this.calendarCellText(pos):this.matrixCellText(pos)}matrixCellText(pos){const rowLabel=this.matrixRowLabels[pos.row]??this.localize("heatmapDefaultRowLabel",void 0,{n:this.formatCount(pos.row+1)}),colLabel=this.matrixColLabels[pos.col]??this.localize("heatmapDefaultColLabel",void 0,{n:this.formatCount(pos.col+1)}),v=this.matrixValues[pos.row]?.[pos.col],valueText=v==null||this.isNoData(v)?this.localize("heatmapNoDataValue"):this.formatNumericValue(v);return this.localize("heatmapMatrixCellLabel",void 0,{row:rowLabel,col:colLabel,value:valueText})}calendarCellText(pos){const{date,value}=this.calendarCellAt(pos),label=parseIsoDate(date).toLocaleString(this.effectiveLocale||void 0,{month:"short",day:"numeric",timeZone:"UTC"}),valueText=this.isNoData(value)?this.localize("heatmapNoDataValue"):this.formatNumericValue(value);return this.localize("heatmapCalendarCellLabel",void 0,{date:label,value:valueText})}valueAt(pos){return"week"in pos?this.calendarCellAt(pos).value:this.matrixValues[pos.row]?.[pos.col]??-1}resolveCellText(pos){return this.cellText?this.cellText(pos,this.valueAt(pos)):this.defaultCellText(pos)}isCellInteractive(pos){return this.cellInteractive?.(pos,this.valueAt(pos))??!0}announce(pos){const text=this.resolveCellText(pos),announcement=this.isSelectedPos(pos)?this.localize("heatmapSelectedCellLabel",void 0,{cell:text}):text;this.liveText=announcement,this.announcementSink?.announce(announcement)}emitCellClick(pos){if(this.isCellInteractive(pos))if("week"in pos){const{date,value}=this.calendarCellAt(pos);this.emit("lr-cell-click",{date,value})}else{const value=this.matrixValues[pos.row]?.[pos.col]??-1;this.emit("lr-cell-click",{row:pos.row,col:pos.col,value})}}get gridScrollport(){return this.shadowRoot?.querySelector('[part="grid"]')??null}measureTooltip(){if(!this.gridScrollport)return;const tooltip=this.shadowRoot?.querySelector('[part="tooltip"]');if(!tooltip||tooltip.hidden)return;const view=this.ownerDocument.defaultView,gap=view?Math.abs(finiteNumber(Number.parseFloat(view.getComputedStyle(tooltip).marginBlockStart),0)):0,inline=tooltip.offsetWidth,block=tooltip.offsetHeight+gap;inline===this.tooltipSize.inline&&block===this.tooltipSize.block||(this.tooltipSize={inline,block},this.requestUpdate())}tooltipAnchor(pos){const rect=this.cellRect(pos),center=rect.x+rect.w/2,port=this.gridScrollport;if(!port)return{style:{left:`${center}px`,top:`${rect.y}px`},below:!1};const{inline,block}=this.tooltipSize,windowStart=port.scrollLeft+(this.freezesRowLabels?this.matrixPadLeft:0),windowEnd=port.scrollLeft+port.clientWidth,windowTop=port.scrollTop+(this.freezesColLabels?this.matrixPadTop:0),windowBottom=port.scrollTop+port.clientHeight,below=rect.y-block<windowTop&&rect.y+rect.h+block<=windowBottom;return{style:{left:`${Math.max(windowStart+inline/2,Math.min(center,windowEnd-inline/2))}px`,top:`${below?rect.y+rect.h:rect.y}px`},below}}scrollCellIntoView(pos){const port=this.gridScrollport;if(!port)return;const rect=this.cellRect(pos),bandInline=this.freezesRowLabels?this.matrixPadLeft:0,bandBlock=this.freezesColLabels?this.matrixPadTop:0,left=Math.min(Math.max(port.scrollLeft,rect.x+rect.w-port.clientWidth),rect.x-bandInline),top=Math.min(Math.max(port.scrollTop,rect.y+rect.h-port.clientHeight),rect.y-bandBlock);left!==port.scrollLeft&&(port.scrollLeft=left),top!==port.scrollTop&&(port.scrollTop=top)}samePos(a,b){return a===b?!0:!a||!b?!1:"week"in a&&"week"in b?a.week===b.week&&a.weekday===b.weekday:"row"in a&&"row"in b?a.row===b.row&&a.col===b.col:!1}onMatrixKeyDown(e){const rows=this.matrixRowLabels.length,cols=this.matrixColLabels.length;if(rows===0||cols===0)return;if(e.key==="Enter"||e.key===" "){e.preventDefault(),this.focusedCell&&this.emitCellClick(this.focusedCell);return}if(!ARROW_KEYS.has(e.key))return;if(e.preventDefault(),!this.focusedCell||!("row"in this.focusedCell)){const next2=this.firstInteractiveMatrixCell(rows,cols);if(!next2)return;this.focusedCell=next2,this.announce(next2),this.scrollCellIntoView(next2);return}const{row,col}=this.focusedCell;let dRow=0,dCol=0;e.key==="ArrowUp"?dRow=-1:e.key==="ArrowDown"?dRow=1:e.key==="ArrowLeft"?dCol=-1:e.key==="ArrowRight"&&(dCol=1);const next=this.nextInteractiveMatrixCell(row,col,dRow,dCol,rows,cols);this.focusedCell=next,this.announce(next),this.scrollCellIntoView(next)}onCalendarKeyDown(e){const{weekCount}=this.cachedCalendarGrid;if(weekCount===0)return;if(e.key==="Enter"||e.key===" "){e.preventDefault(),this.focusedCell&&this.emitCellClick(this.focusedCell);return}if(!ARROW_KEYS.has(e.key))return;if(e.preventDefault(),!this.focusedCell||!("week"in this.focusedCell)){const next2=this.firstInteractiveCalendarCell(weekCount);if(!next2)return;this.focusedCell=next2,this.announce(next2);return}const{week,weekday}=this.focusedCell;let dWeek=0,dWeekday=0;e.key==="ArrowUp"?dWeekday=-1:e.key==="ArrowDown"?dWeekday=1:e.key==="ArrowLeft"?dWeek=-1:e.key==="ArrowRight"&&(dWeek=1);const next=this.nextInteractiveCalendarCell(week,weekday,dWeek,dWeekday,weekCount);this.focusedCell=next,this.announce(next)}resolveCanvasColor(value,cs){const cached=this.canvasColorCache.get(value);if(cached!==void 0)return cached;const fallback=this.noDataFill(cs);let candidate=value;if(value.includes("var(")){if(this.colorProbe||(this.colorProbe=this.ownerDocument.createElement("span"),this.colorProbe.style.cssText="position:absolute;width:0;height:0;overflow:hidden;visibility:hidden;pointer-events:none;",this.shadowRoot.appendChild(this.colorProbe)),this.colorProbe.style.color="",this.colorProbe.style.color=value,!this.colorProbe.style.color)return this.canvasColorCache.set(value,fallback),fallback;candidate=this.ownerDocument.defaultView?.getComputedStyle(this.colorProbe).color||fallback}const ctx=getScratchCtx(this.ownerDocument);if(!ctx)return fallback;ctx.fillStyle="rgb(1, 2, 3)";const firstSentinel=ctx.fillStyle;ctx.fillStyle=candidate;let resolved=ctx.fillStyle;if(resolved===firstSentinel){ctx.fillStyle="rgb(4, 5, 6)";const secondSentinel=ctx.fillStyle;ctx.fillStyle=candidate,resolved=ctx.fillStyle,resolved===secondSentinel&&(resolved=fallback)}return this.canvasColorCache.set(value,resolved),resolved}rebuildAccessiblePositions(){const positions=[];if(this.effectiveMode==="calendar"){const{weekCount}=this.cachedCalendarGrid;for(let week=0;week<weekCount;week++)for(let weekday=0;weekday<7;weekday++){const pos=this.calendarPos(week,weekday);this.isCellInteractive(pos)&&positions.push(pos)}}else for(let row=0;row<this.matrixRowLabels.length;row++)for(let col=0;col<this.matrixColLabels.length;col++){const pos={row,col};this.isCellInteractive(pos)&&positions.push(pos)}this.cachedAccessiblePositions=positions,this.cachedAccessiblePositionsByKey=new Map(positions.map(position=>[this.accessibleCellKey(position),position])),this.cachedAccessiblePositionIndexByKey=new Map(positions.map((position,index)=>[this.accessibleCellKey(position),index]))}accessibleCellPositions(){return this.cachedAccessiblePositions}accessibleCellKey(pos){return"week"in pos?`calendar-${pos.week}-${pos.weekday}`:`matrix-${pos.row}-${pos.col}`}accessibleCellIdentity(pos){return"week"in pos?pos.date:this.accessibleCellKey(pos)}accessibleCellAtKey(key){return this.cachedAccessiblePositionsByKey.get(key)??null}focusAccessibleCell(pos){pos&&this.updateComplete.then(()=>{[...this.shadowRoot?.querySelectorAll('[part="cell"]')??[]].find(candidate=>candidate.dataset.cellKey===this.accessibleCellKey(pos))?.focus()})}renderAccessibleCells(){if(!this.accessibleCells)return html``;const positions=this.accessibleCellPositions(),tabStop=this.focusedCell??positions[0]??null,focusIndex=tabStop?this.cachedAccessiblePositionIndexByKey.get(this.accessibleCellKey(tabStop))??0:0,start=Math.max(0,Math.min(Math.max(0,positions.length-MAX_ACCESSIBLE_HEATMAP_CELLS),focusIndex-Math.floor(MAX_ACCESSIBLE_HEATMAP_CELLS/2))),renderedPositions=positions.slice(start,start+MAX_ACCESSIBLE_HEATMAP_CELLS),renderedRows=new Map;for(const pos of renderedPositions){const rowIndex="week"in pos?pos.weekday+1:pos.row+1,row=renderedRows.get(rowIndex);row?row.push(pos):renderedRows.set(rowIndex,[pos])}const rowCount=this.effectiveMode==="calendar"?7:this.matrixRowLabels.length,colCount=this.effectiveMode==="calendar"?this.cachedCalendarGrid.weekCount:this.matrixColLabels.length;return html`
2
2
  <div
3
3
  part="cells"
4
4
  role="grid"
@@ -28,7 +28,8 @@ export declare class LyraSparkline extends LyraElement{static styles:import("lit
28
28
  appearance:LyraSparklineAppearance;
29
29
  /** Interpolation used to connect adjacent samples. */
30
30
  curve:LyraSparklineCurve;
31
- /** Space-separated finite numeric samples. At least two are required. */
31
+ /** Space-separated finite numeric samples. At least two are required. An empty or removed
32
+ * data attribute uses values instead; removal retains null property readback. */
32
33
  data:string;
33
34
  /** Accessible label applied verbatim to the SVG. */
34
35
  label:string;
@@ -1,4 +1,4 @@
1
- var __decorate=function(decorators,target,key,desc){var c=arguments.length,r=c<3?target:desc===null?desc=Object.getOwnPropertyDescriptor(target,key):desc,d;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")r=Reflect.decorate(decorators,target,key,desc);else for(var i=decorators.length-1;i>=0;i--)(d=decorators[i])&&(r=(c<3?d(r):c>3?d(target,key,r):d(target,key))||r);return c>3&&r&&Object.defineProperty(target,key,r),r};import{html,nothing,svg}from"lit";import{property}from"lit/decorators.js";import{nextId}from"../../../internal/a11y.js";import{LyraElement}from"../../../internal/lyra-element.js";import{getNumberFormat}from"../../../internal/intl-cache.js";import{finiteNumber,finiteRatio}from"../../../internal/numbers.js";import{styles}from"./sparkline.styles.js";import{LYRA_DEFAULT_noData,LYRA_DEFAULT_trendOf}from"../../../internal/default-strings.generated.js";const VIEW=100,MAX_POINTS=500;function decimate(arr,max){if(arr.length<=max)return[...arr];const step=(arr.length-1)/(max-1);return Array.from({length:max},(_,i)=>arr[Math.round(i*step)])}function finiteData(value){const source=value.trim();return source?source.split(/\s+/u).map(Number).filter(item=>Number.isFinite(item)):[]}function normalizeAppearance(value){return value==="gradient"||value==="line"||value==="solid"?value:"solid"}function normalizeCurve(value){return value==="natural"||value==="step"||value==="linear"?value:"linear"}class LyraSparkline extends LyraElement{constructor(){super(...arguments),this.appearance="solid",this.curve="linear",this.data="",this.label="",this.accessibleLabel=null,this.values=[],this._mark="line",this.gradientId=nextId("sparkline-gradient")}static{this.defaultStrings={...super.defaultStrings,noData:LYRA_DEFAULT_noData,trendOf:LYRA_DEFAULT_trendOf}}static{this.styles=[LyraElement.styles,styles]}get mark(){return this._mark}set mark(value){const normalized=value==="bar"?"bar":"line",previous=this._mark;if(previous===normalized){value!==normalized&&this.requestUpdate("mark",previous);return}this._mark=normalized,this.requestUpdate("mark",previous)}plotValues(){if(this.data.trim()){const parsed=finiteData(this.data);return parsed.length>=2?parsed:[]}return Array.isArray(this.values)?this.values.filter(item=>Number.isFinite(item)):[]}points(values=this.plotValues()){let autoLo=values[0]??0,autoHi=values[0]??0;if(!Number.isFinite(this.min)||!Number.isFinite(this.max))for(const value of values)value<autoLo&&(autoLo=value),value>autoHi&&(autoHi=value);let lo=finiteNumber(this.min??autoLo,autoLo),hi=finiteNumber(this.max??autoHi,autoHi);lo>hi&&([lo,hi]=[hi,lo]);const samples=values.length>MAX_POINTS?decimate(values,MAX_POINTS):[...values];return samples.map((value,index)=>{const forwardX=samples.length>1?index/(samples.length-1)*VIEW:VIEW/2,x=this.effectiveDirection==="rtl"?VIEW-forwardX:forwardX,y=lo===hi?VIEW/2:VIEW-finiteRatio(value,lo,hi)*VIEW;return[x,y]})}linePath(points){const first=points[0];if(!first)return"";if(points.length===1)return`M${first[0]},${first[1]} L${first[0]},${first[1]}`;const curve=normalizeCurve(this.curve);if(curve==="step")return points.slice(1).reduce((path,point)=>`${path} H${point[0]} V${point[1]}`,`M${first[0]},${first[1]}`);if(curve==="natural"){let path=`M${first[0]},${first[1]}`;for(let index=0;index<points.length-1;index++){const before=points[Math.max(0,index-1)],start=points[index],end=points[index+1],after=points[Math.min(points.length-1,index+2)],c1x=start[0]+(end[0]-before[0])/6,c1y=start[1]+(end[1]-before[1])/6,c2x=end[0]-(after[0]-start[0])/6,c2y=end[1]-(after[1]-start[1])/6;path+=` C${c1x},${c1y} ${c2x},${c2y} ${end[0]},${end[1]}`}return path}return points.map(([x,y],index)=>`${index?"L":"M"}${x},${y}`).join(" ")}accessibleName(values){const hostLabel=this.getAttribute("aria-label");if(hostLabel!==null)return hostLabel;if(this.label)return this.label;if(typeof this.accessibleLabel=="string"&&this.accessibleLabel.length>0)return this.accessibleLabel;const last=values.at(-1);return last===void 0?this.localize("noData"):this.localize("trendOf",void 0,{count:getNumberFormat(this.effectiveLocale).format(values.length),value:getNumberFormat(this.effectiveLocale,{maximumFractionDigits:2}).format(last)})}renderBars(points){const slot=VIEW/Math.max(1,points.length),barWidth=Math.min(4,Math.max(1,slot*.7));return html`${points.map(([x,y])=>{const barY=Math.min(VIEW,Math.max(0,y));return svg`<rect
1
+ var __decorate=function(decorators,target,key,desc){var c=arguments.length,r=c<3?target:desc===null?desc=Object.getOwnPropertyDescriptor(target,key):desc,d;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")r=Reflect.decorate(decorators,target,key,desc);else for(var i=decorators.length-1;i>=0;i--)(d=decorators[i])&&(r=(c<3?d(r):c>3?d(target,key,r):d(target,key))||r);return c>3&&r&&Object.defineProperty(target,key,r),r};import{html,nothing,svg}from"lit";import{property}from"lit/decorators.js";import{nextId}from"../../../internal/a11y.js";import{LyraElement}from"../../../internal/lyra-element.js";import{getNumberFormat}from"../../../internal/intl-cache.js";import{finiteNumber,finiteRatio}from"../../../internal/numbers.js";import{styles}from"./sparkline.styles.js";import{LYRA_DEFAULT_noData,LYRA_DEFAULT_trendOf}from"../../../internal/default-strings.generated.js";const VIEW=100,MAX_POINTS=500;function decimate(arr,max){if(arr.length<=max)return[...arr];const step=(arr.length-1)/(max-1);return Array.from({length:max},(_,i)=>arr[Math.round(i*step)])}function finiteData(value){const source=value.trim();return source?source.split(/\s+/u).map(Number).filter(item=>Number.isFinite(item)):[]}function normalizeAppearance(value){return value==="gradient"||value==="line"||value==="solid"?value:"solid"}function normalizeCurve(value){return value==="natural"||value==="step"||value==="linear"?value:"linear"}class LyraSparkline extends LyraElement{constructor(){super(...arguments),this.appearance="solid",this.curve="linear",this.data="",this.label="",this.accessibleLabel=null,this.values=[],this._mark="line",this.gradientId=nextId("sparkline-gradient")}static{this.defaultStrings={...super.defaultStrings,noData:LYRA_DEFAULT_noData,trendOf:LYRA_DEFAULT_trendOf}}static{this.styles=[LyraElement.styles,styles]}get mark(){return this._mark}set mark(value){const normalized=value==="bar"?"bar":"line",previous=this._mark;if(previous===normalized){value!==normalized&&this.requestUpdate("mark",previous);return}this._mark=normalized,this.requestUpdate("mark",previous)}plotValues(){if((this.data??"").trim()){const parsed=finiteData(this.data);return parsed.length>=2?parsed:[]}return Array.isArray(this.values)?this.values.filter(item=>Number.isFinite(item)):[]}points(values=this.plotValues()){let autoLo=values[0]??0,autoHi=values[0]??0;if(!Number.isFinite(this.min)||!Number.isFinite(this.max))for(const value of values)value<autoLo&&(autoLo=value),value>autoHi&&(autoHi=value);let lo=finiteNumber(this.min??autoLo,autoLo),hi=finiteNumber(this.max??autoHi,autoHi);lo>hi&&([lo,hi]=[hi,lo]);const samples=values.length>MAX_POINTS?decimate(values,MAX_POINTS):[...values];return samples.map((value,index)=>{const forwardX=samples.length>1?index/(samples.length-1)*VIEW:VIEW/2,x=this.effectiveDirection==="rtl"?VIEW-forwardX:forwardX,y=lo===hi?VIEW/2:VIEW-finiteRatio(value,lo,hi)*VIEW;return[x,y]})}linePath(points){const first=points[0];if(!first)return"";if(points.length===1)return`M${first[0]},${first[1]} L${first[0]},${first[1]}`;const curve=normalizeCurve(this.curve);if(curve==="step")return points.slice(1).reduce((path,point)=>`${path} H${point[0]} V${point[1]}`,`M${first[0]},${first[1]}`);if(curve==="natural"){let path=`M${first[0]},${first[1]}`;for(let index=0;index<points.length-1;index++){const before=points[Math.max(0,index-1)],start=points[index],end=points[index+1],after=points[Math.min(points.length-1,index+2)],c1x=start[0]+(end[0]-before[0])/6,c1y=start[1]+(end[1]-before[1])/6,c2x=end[0]-(after[0]-start[0])/6,c2y=end[1]-(after[1]-start[1])/6;path+=` C${c1x},${c1y} ${c2x},${c2y} ${end[0]},${end[1]}`}return path}return points.map(([x,y],index)=>`${index?"L":"M"}${x},${y}`).join(" ")}accessibleName(values){const hostLabel=this.getAttribute("aria-label");if(hostLabel!==null)return hostLabel;if(this.label)return this.label;if(typeof this.accessibleLabel=="string"&&this.accessibleLabel.length>0)return this.accessibleLabel;const last=values.at(-1);return last===void 0?this.localize("noData"):this.localize("trendOf",void 0,{count:getNumberFormat(this.effectiveLocale).format(values.length),value:getNumberFormat(this.effectiveLocale,{maximumFractionDigits:2}).format(last)})}renderBars(points){const slot=VIEW/Math.max(1,points.length),barWidth=Math.min(4,Math.max(1,slot*.7));return html`${points.map(([x,y])=>{const barY=Math.min(VIEW,Math.max(0,y));return svg`<rect
2
2
  part="bar"
3
3
  x="${x-barWidth/2}"
4
4
  y="${barY}"
@@ -15,7 +15,8 @@ readonly exactValue?:string;}
15
15
  * visual. `lr-stat` only reserves the slot; it doesn't render one itself.
16
16
  * @slot sub - Rich sub-line content (overrides the `sub` attribute).
17
17
  * When linked, every consumer slot remains a sibling of the stretched anchor so an interactive
18
- * slotted descendant is never nested inside the whole-card link.
18
+ * slotted descendant is never nested inside the whole-card link. Passive slotted content forwards
19
+ * pointer modifiers; the platform primary modifier and Shift preserve new-context activation.
19
20
  * @csspart base - The component's root wrapper (`<div>`, or a stretched real `<a>` when `href` is safe).
20
21
  * @csspart icon - Container for the leading icon slot.
21
22
  * @csspart label - The label text. Hidden (and collapsed) whenever `label` is empty, so a
@@ -78,7 +79,9 @@ href?:string;
78
79
  target?:string;private _deltaPercent;
79
80
  /** Percentage delta for the trend pill. Null (the JSON-safe default) hides the pill;
80
81
  * non-finite input normalizes to null and finite numbers remain unclamped. */
81
- get deltaPercent():number|null;set deltaPercent(value:number|null);caption:string;
82
+ get deltaPercent():number|null;set deltaPercent(value:number|null);
83
+ /** Caption fallback. Removing the attribute omits it without hiding assigned caption content. */
84
+ caption:string;
82
85
  /** Which trend direction counts as "good" — inverts arrow/color polarity for
83
86
  * cost/latency/error-rate-style metrics where a decrease is the win. */
84
87
  goodDirection:StatGoodDirection;private _rows;
@@ -96,6 +99,7 @@ emphasis:boolean;
96
99
  exactValue:string;
97
100
  /** A secondary line distinct from `caption` (e.g. a comparison-period label), rendered between the
98
101
  * trend pill and the caption. */
102
+ /** Sub-line fallback. Removing the attribute omits it without hiding assigned sub content. */
99
103
  sub:string;
100
104
  /** Renders `value` as smaller/lighter prose (e.g. a loading/status message) instead of the bold
101
105
  * numeric headline style, and hides `unit`. */
@@ -1,4 +1,4 @@
1
- var __decorate=function(decorators,target,key,desc){var c=arguments.length,r=c<3?target:desc===null?desc=Object.getOwnPropertyDescriptor(target,key):desc,d;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")r=Reflect.decorate(decorators,target,key,desc);else for(var i=decorators.length-1;i>=0;i--)(d=decorators[i])&&(r=(c<3?d(r):c>3?d(target,key,r):d(target,key))||r);return c>3&&r&&Object.defineProperty(target,key,r),r};import{html,nothing}from"lit";import{property,state}from"lit/decorators.js";import{LyraElement}from"../../../internal/lyra-element.js";import{chevronIcon}from"../../../internal/icons.js";import{nextId,srOnly}from"../../../internal/a11y.js";import{finiteNumber}from"../../../internal/numbers.js";import{safeLinkHref}from"../../../internal/safe-url.js";import{getNumberFormat}from"../../../internal/intl-cache.js";import{styles}from"./stat.styles.js";import{LYRA_DEFAULT_statTrendAnnouncement,LYRA_DEFAULT_statTrendBad,LYRA_DEFAULT_statTrendDecreased,LYRA_DEFAULT_statTrendGood,LYRA_DEFAULT_statTrendIncreased,LYRA_DEFAULT_trendUnchanged}from"../../../internal/default-strings.generated.js";const MAX_STAT_ROWS=1e4,NESTED_CONTROL_SELECTOR=["a[href]","button","input","select","textarea","summary","audio[controls]","video[controls]","label",'[contenteditable]:not([contenteditable="false"])','[tabindex]:not([tabindex="-1"])','[role="button"]','[role="link"]','[role="checkbox"]','[role="switch"]','[role="radio"]','[role="menuitem"]','[role="option"]','[role="tab"]','[role="textbox"]','[role="slider"]','[role="spinbutton"]'].join(",");function isElementNode(value){return typeof value=="object"&&value!==null&&value.nodeType===1&&typeof value.matches=="function"}class LyraStat extends LyraElement{constructor(){super(...arguments),this.label="",this.accessibleLabel=null,this.value="",this.unit="",this.variant="neutral",this._deltaPercent=null,this.caption="",this.goodDirection="up",this._rows=[],this.emphasis=!1,this.exactValue="",this.sub="",this.prose=!1,this.compact=!1,this.frame="card",this.orientation="vertical",this.hasIcon=!1,this.hasCaptionSlot=!1,this.hasSparkSlot=!1,this.hasSubSlot=!1,this.labelId=nextId("stat-label"),this.valueId=`${this.labelId}-value`,this.unitId=`${this.labelId}-unit`,this.rowLabelIds=[],this.onIconSlotChange=()=>{const startSlot=this.renderRoot.querySelector('slot[name="start"]'),defaultSlot=this.renderRoot.querySelector("slot:not([name])");this.hasIcon=!!(startSlot?.assignedElements({flatten:!0}).length||defaultSlot?.assignedElements({flatten:!0}).length)},this.onCaptionSlotChange=e=>{this.hasCaptionSlot=e.target.assignedElements({flatten:!0}).length>0},this.onSparkSlotChange=e=>{this.hasSparkSlot=e.target.assignedElements({flatten:!0}).length>0},this.onSubSlotChange=e=>{this.hasSubSlot=e.target.assignedElements({flatten:!0}).length>0},this.onLinkedContentClick=event=>{for(const node of event.composedPath()){if(node===event.currentTarget)break;if(isElementNode(node)&&node.matches(NESTED_CONTROL_SELECTOR))return}this.shadowRoot?.querySelector('[part="base"][href]')?.click()}}static{this.defaultStrings={...super.defaultStrings,statTrendAnnouncement:LYRA_DEFAULT_statTrendAnnouncement,statTrendBad:LYRA_DEFAULT_statTrendBad,statTrendDecreased:LYRA_DEFAULT_statTrendDecreased,statTrendGood:LYRA_DEFAULT_statTrendGood,statTrendIncreased:LYRA_DEFAULT_statTrendIncreased,trendUnchanged:LYRA_DEFAULT_trendUnchanged}}static{this.styles=[LyraElement.styles,styles,srOnly]}get deltaPercent(){return this._deltaPercent}set deltaPercent(value){const old=this._deltaPercent;this._deltaPercent=value!=null&&Number.isFinite(value)?finiteNumber(value,0):null,this.requestUpdate("deltaPercent",old)}get rows(){return this._rows}set rows(value){const previous=this._rows,snapshot=[];if(Array.isArray(value))for(const row of value.slice(0,MAX_STAT_ROWS))try{snapshot.push(Object.freeze({label:typeof row?.label=="string"?row.label:"",value:typeof row?.value=="string"?row.value:"",...typeof row?.exactValue=="string"?{exactValue:row.exactValue}:{}}))}catch{}this._rows=Object.freeze(snapshot),this.requestUpdate("rows",previous)}willUpdate(changed){if(super.willUpdate(changed),!this.hasUpdated){const lightChildren=Array.from(this.children??[]);this.hasIcon=lightChildren.some(el=>{const slotName=el.getAttribute("slot");return slotName===null||slotName==="start"}),this.hasCaptionSlot=lightChildren.some(el=>el.getAttribute("slot")==="caption"),this.hasSparkSlot=lightChildren.some(el=>el.getAttribute("slot")==="spark"),this.hasSubSlot=lightChildren.some(el=>el.getAttribute("slot")==="sub")}changed.has("rows")&&(this.rowLabelIds=this.rows.map(()=>nextId("stat-row-label")))}click(){const anchor=this.shadowRoot?.querySelector('[part="base"][href]');anchor?anchor.click():super.click()}render(){const href=safeLinkHref(this.href),linked=!!href,hasTrend=this.deltaPercent!==null,effectiveDelta=this.deltaPercent??0,rawDirection=effectiveDelta>0?"up":effectiveDelta<0?"down":"flat",isGood=rawDirection==="flat"?null:rawDirection===this.goodDirection,arrow=rawDirection==="flat"?"–":chevronIcon(),hasCaption=this.hasCaptionSlot||this.caption.length>0,hasSub=this.hasSubSlot||this.sub.length>0,formattedTrend=getNumberFormat(this.effectiveLocale,{style:"percent",maximumFractionDigits:20}).format(Math.abs(effectiveDelta)/100),trendAnnouncement=rawDirection==="flat"?this.localize("trendUnchanged"):this.localize("statTrendAnnouncement",void 0,{trend:this.localize(rawDirection==="up"?"statTrendIncreased":"statTrendDecreased",void 0,{value:formattedTrend}),polarity:this.localize(isGood?"statTrendGood":"statTrendBad")}),content=html`
1
+ var __decorate=function(decorators,target,key,desc){var c=arguments.length,r=c<3?target:desc===null?desc=Object.getOwnPropertyDescriptor(target,key):desc,d;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")r=Reflect.decorate(decorators,target,key,desc);else for(var i=decorators.length-1;i>=0;i--)(d=decorators[i])&&(r=(c<3?d(r):c>3?d(target,key,r):d(target,key))||r);return c>3&&r&&Object.defineProperty(target,key,r),r};import{html,nothing}from"lit";import{property,state}from"lit/decorators.js";import{LyraElement}from"../../../internal/lyra-element.js";import{chevronIcon}from"../../../internal/icons.js";import{nextId,srOnly}from"../../../internal/a11y.js";import{finiteNumber}from"../../../internal/numbers.js";import{safeLinkHref}from"../../../internal/safe-url.js";import{detectPlatform}from"../../../internal/platform.js";import{getNumberFormat}from"../../../internal/intl-cache.js";import{styles}from"./stat.styles.js";import{LYRA_DEFAULT_statTrendAnnouncement,LYRA_DEFAULT_statTrendBad,LYRA_DEFAULT_statTrendDecreased,LYRA_DEFAULT_statTrendGood,LYRA_DEFAULT_statTrendIncreased,LYRA_DEFAULT_trendUnchanged}from"../../../internal/default-strings.generated.js";const MAX_STAT_ROWS=1e4,NESTED_CONTROL_SELECTOR=["a[href]","button","input","select","textarea","summary","audio[controls]","video[controls]","label",'[contenteditable]:not([contenteditable="false"])','[tabindex]:not([tabindex="-1"])','[role="button"]','[role="link"]','[role="checkbox"]','[role="switch"]','[role="radio"]','[role="menuitem"]','[role="option"]','[role="tab"]','[role="textbox"]','[role="slider"]','[role="spinbutton"]'].join(",");function isElementNode(value){return typeof value=="object"&&value!==null&&value.nodeType===1&&typeof value.matches=="function"}class LyraStat extends LyraElement{constructor(){super(...arguments),this.label="",this.accessibleLabel=null,this.value="",this.unit="",this.variant="neutral",this._deltaPercent=null,this.caption="",this.goodDirection="up",this._rows=[],this.emphasis=!1,this.exactValue="",this.sub="",this.prose=!1,this.compact=!1,this.frame="card",this.orientation="vertical",this.hasIcon=!1,this.hasCaptionSlot=!1,this.hasSparkSlot=!1,this.hasSubSlot=!1,this.labelId=nextId("stat-label"),this.valueId=`${this.labelId}-value`,this.unitId=`${this.labelId}-unit`,this.rowLabelIds=[],this.onIconSlotChange=()=>{const startSlot=this.renderRoot.querySelector('slot[name="start"]'),defaultSlot=this.renderRoot.querySelector("slot:not([name])");this.hasIcon=!!(startSlot?.assignedElements({flatten:!0}).length||defaultSlot?.assignedElements({flatten:!0}).length)},this.onCaptionSlotChange=e=>{this.hasCaptionSlot=e.target.assignedElements({flatten:!0}).length>0},this.onSparkSlotChange=e=>{this.hasSparkSlot=e.target.assignedElements({flatten:!0}).length>0},this.onSubSlotChange=e=>{this.hasSubSlot=e.target.assignedElements({flatten:!0}).length>0},this.onLinkedContentClick=event=>{for(const node of event.composedPath()){if(node===event.currentTarget)break;if(isElementNode(node)&&node.matches(NESTED_CONTROL_SELECTOR))return}if(event.defaultPrevented)return;const anchor=this.shadowRoot?.querySelector('[part="base"][href]'),MouseEventConstructor=this.ownerDocument.defaultView?.MouseEvent;if(anchor)if(MouseEventConstructor&&event instanceof MouseEventConstructor){const platform=detectPlatform(this.ownerDocument.defaultView?.navigator),newContext=event.shiftKey||(platform==="mac"?event.metaKey:event.ctrlKey),previousTarget=anchor.getAttribute("target"),previousRel=anchor.getAttribute("rel");newContext&&(anchor.target="_blank",anchor.rel="noopener noreferrer");try{anchor.dispatchEvent(new MouseEventConstructor("click",{bubbles:!0,cancelable:!0,composed:!0,view:event.view,detail:event.detail,button:event.button,buttons:event.buttons,clientX:event.clientX,clientY:event.clientY,screenX:event.screenX,screenY:event.screenY,ctrlKey:event.ctrlKey,metaKey:event.metaKey,shiftKey:event.shiftKey,altKey:event.altKey}))}finally{newContext&&(anchor.getAttribute("target")==="_blank"&&(previousTarget===null?anchor.removeAttribute("target"):anchor.setAttribute("target",previousTarget)),anchor.getAttribute("rel")==="noopener noreferrer"&&(previousRel===null?anchor.removeAttribute("rel"):anchor.setAttribute("rel",previousRel)))}}else anchor.click()}}static{this.defaultStrings={...super.defaultStrings,statTrendAnnouncement:LYRA_DEFAULT_statTrendAnnouncement,statTrendBad:LYRA_DEFAULT_statTrendBad,statTrendDecreased:LYRA_DEFAULT_statTrendDecreased,statTrendGood:LYRA_DEFAULT_statTrendGood,statTrendIncreased:LYRA_DEFAULT_statTrendIncreased,trendUnchanged:LYRA_DEFAULT_trendUnchanged}}static{this.styles=[LyraElement.styles,styles,srOnly]}get deltaPercent(){return this._deltaPercent}set deltaPercent(value){const old=this._deltaPercent;this._deltaPercent=value!=null&&Number.isFinite(value)?finiteNumber(value,0):null,this.requestUpdate("deltaPercent",old)}get rows(){return this._rows}set rows(value){const previous=this._rows,snapshot=[];if(Array.isArray(value))for(const row of value.slice(0,MAX_STAT_ROWS))try{snapshot.push(Object.freeze({label:typeof row?.label=="string"?row.label:"",value:typeof row?.value=="string"?row.value:"",...typeof row?.exactValue=="string"?{exactValue:row.exactValue}:{}}))}catch{}this._rows=Object.freeze(snapshot),this.requestUpdate("rows",previous)}willUpdate(changed){if(super.willUpdate(changed),!this.hasUpdated){const lightChildren=Array.from(this.children??[]);this.hasIcon=lightChildren.some(el=>{const slotName=el.getAttribute("slot");return slotName===null||slotName==="start"}),this.hasCaptionSlot=lightChildren.some(el=>el.getAttribute("slot")==="caption"),this.hasSparkSlot=lightChildren.some(el=>el.getAttribute("slot")==="spark"),this.hasSubSlot=lightChildren.some(el=>el.getAttribute("slot")==="sub")}changed.has("rows")&&(this.rowLabelIds=this.rows.map(()=>nextId("stat-row-label")))}click(){const anchor=this.shadowRoot?.querySelector('[part="base"][href]');anchor?anchor.click():super.click()}render(){const href=safeLinkHref(this.href),linked=!!href,hasTrend=this.deltaPercent!==null,effectiveDelta=this.deltaPercent??0,rawDirection=effectiveDelta>0?"up":effectiveDelta<0?"down":"flat",isGood=rawDirection==="flat"?null:rawDirection===this.goodDirection,arrow=rawDirection==="flat"?"–":chevronIcon(),hasCaption=this.hasCaptionSlot||(this.caption??"").length>0,hasSub=this.hasSubSlot||(this.sub??"").length>0,formattedTrend=getNumberFormat(this.effectiveLocale,{style:"percent",maximumFractionDigits:20}).format(Math.abs(effectiveDelta)/100),trendAnnouncement=rawDirection==="flat"?this.localize("trendUnchanged"):this.localize("statTrendAnnouncement",void 0,{trend:this.localize(rawDirection==="up"?"statTrendIncreased":"statTrendDecreased",void 0,{value:formattedTrend}),polarity:this.localize(isGood?"statTrendGood":"statTrendBad")}),content=html`
2
2
  <span part="icon" ?hidden=${!this.hasIcon}
3
3
  ><slot name="start" @slotchange=${this.onIconSlotChange}
4
4
  ><slot @slotchange=${this.onIconSlotChange}></slot></slot
@@ -162,7 +162,10 @@ editType?:'text'|'number';cell:(row:T)=>unknown;}export interface LyraTableEvent
162
162
  * `activateRow()`). When controlled rows or columns replace the focused
163
163
  * member, focus follows the same stable key when it survives and otherwise
164
164
  * clamps to the nearest surviving index; an update never reclaims focus once
165
- * the user has moved it outside the table.
165
+ * the user has moved it outside the table. Effective locale changes use the same current
166
+ * page identity for activation, editing, and direct row-focus restoration.
167
+ * Priority-hidden columns hide their header, body, and footer cells together; revealing
168
+ * priority columns restores all three bands.
166
169
  * Blank and later-duplicate column keys are omitted first-wins at assignment. Rows retain their
167
170
  * caller-owned records, then one canonical `rowKey` projection omits blank and later-duplicate
168
171
  * identities before filtering, counts, pagination, focus, actions, and events.
@@ -628,7 +631,7 @@ private editorHadFocusBeforeUpdate;
628
631
  * to put focus on the already-correct `tabindex="0"` owner. */
629
632
  private rovingFocusSnapshot;private resizedColumnWidths;private resizeState?;
630
633
  /** Window that owns the active resize gesture's global pointer listeners. */
631
- private resizeEventWindow?;private rowsByKey;private columnsByKey;
634
+ private resizeEventWindow?;private rowsByKey;private rowsLocale?;private columnsByKey;
632
635
  /** Watches `[part='base']`'s own inline-size — the `@container` query
633
636
  * container table.styles.ts's priority-hide rules react to — so a
634
637
  * `priority` column flipping hidden/visible from an *external* width
@@ -11,7 +11,7 @@ var __decorate=function(decorators,target,key,desc){var c=arguments.length,r=c<3
11
11
  aria-valuemax=${Number.isFinite(maxWidth)?Math.round(maxWidth):UNBOUNDED_RESIZE_ARIA_MAX}
12
12
  @pointerdown=${this.onResizePointerDown}
13
13
  @keydown=${this.onResizeKeyDown}
14
- ></span>`}syncResizeHandleValues(){for(const handle of this.renderRoot.querySelectorAll('[part="resize-handle"]')){const key=handle.dataset.colKey;if(!key)continue;const column=this.columnsByKey.get(key);if(!column||this.resizedColumnWidths.has(key)||this.parsePixelLength(column.width)!==void 0)continue;const rendered=handle.closest("th[data-col-key]")?.getBoundingClientRect().width;if(rendered&&rendered>0){const width=Math.round(rendered);handle.setAttribute("aria-valuenow",String(width)),handle.setAttribute("aria-valuetext",this.resizeValueText(width))}}}detachResizePointerListeners(){const resizeEventWindow=this.resizeEventWindow;resizeEventWindow&&(resizeEventWindow.removeEventListener("pointermove",this.onResizePointerMove),resizeEventWindow.removeEventListener("pointerup",this.onResizePointerEnd),resizeEventWindow.removeEventListener("pointercancel",this.onResizePointerEnd),resizeEventWindow.removeEventListener("lostpointercapture",this.onResizePointerEnd),this.resizeEventWindow=void 0)}rollbackResizePreview(state2){const reverted=new Map(this.resizedColumnWidths);state2.previousWidth===void 0?reverted.delete(state2.key):reverted.set(state2.key,state2.previousWidth),this.resizedColumnWidths=reverted}cancelResizeGesture(){const state2=this.resizeState;if(this.resizeState=void 0,this.detachResizePointerListeners(),!!state2){state2.handle.removeAttribute("data-resizing");try{state2.handle.releasePointerCapture?.(state2.pointerId)}catch{}this.rollbackResizePreview(state2)}}firstUpdated(changed){super.firstUpdated(changed),!this.accessibleLabel&&!this.hasAttribute("aria-label")&&!this.caption&&devWarnOnce(MISSING_ACCESSIBLE_NAME_WARNING,"<lr-table> has no accessible name: set `accessibleLabel`, a host `aria-label`, or `caption` so assistive technology can identify the grid.")}connectedCallback(){super.connectedCallback(),this.syncAnnouncementSink();const owner=this.ownerDocument.defaultView,ResizeObserverCtor=owner?.ResizeObserver;let observer;ResizeObserverCtor&&(observer=new ResizeObserverCtor(()=>{!this.isConnected||this.ownerDocument.defaultView!==owner||this.resizeObserver!==observer||this.scheduleLayoutSync()})),this.resizeObserver=observer;const base=this.renderRoot?.querySelector('[part="base"]');base&&(this.observeBase(base),this.observeTable(this.renderRoot.querySelector('[part="table"]')??void 0),this.observeHeaders())}disconnectedCallback(){super.disconnectedCallback(),this.releaseAnnouncementSink(),this.cancelResizeGesture(),this.resizeObserver?.disconnect(),this.resizeObserver=void 0;const frame=this.layoutFrame;frame&&frame.owner.cancelAnimationFrame(frame.handle),this.layoutFrame=null,this.observedBase=void 0,this.observedTable=void 0,this.observedHeaders.clear()}releaseAnnouncementSink(){this.announcementSink?.release(),this.announcementSink=void 0}syncAnnouncementSink(){if(!this.isConnected){this.releaseAnnouncementSink();return}this.announcementSink?.element.ownerDocument!==this.ownerDocument&&(this.releaseAnnouncementSink(),this.announcementSink=acquireAnnouncementSink("polite",{document:this.ownerDocument,source:this}))}localizedOverride(key,override){return override??this.localize(key)}loadingText(){return this.localizedOverride("tableLoading",this.loadingLabel)}observeBase(base){this.observedBase!==base&&(this.observedBase&&this.resizeObserver?.unobserve(this.observedBase),this.resizeObserver?.observe(base),this.observedBase=base)}observeTable(table){this.observedTable!==table&&(this.observedTable&&this.resizeObserver?.unobserve(this.observedTable),table&&this.resizeObserver?.observe(table),this.observedTable=table)}syncAutoScrollMode(){const base=this.renderRoot.querySelector('[part="base"]');if(!base)return;const overflows=this.scrollMode==="auto"&&base.scrollWidth-base.clientWidth>TABLE_SCROLL_OVERFLOW_TOLERANCE_PX;base.toggleAttribute("data-scroll-overflow",overflows)}observeHeaders(){const headers=new Set(this.columns.some(column=>column.sticky||column.resizable)?this.renderRoot.querySelectorAll("th[data-col-key]"):[]);for(const header of this.observedHeaders)headers.has(header)||(this.resizeObserver?.unobserve(header),this.observedHeaders.delete(header));for(const header of headers)this.observedHeaders.has(header)||(this.observedHeaders.add(header),this.resizeObserver?.observe(header))}recomputeHiddenPriorityColumns(){const hasPriorityColumns=this.columns.some(col=>col.priority),anyPriorityHidden=hasPriorityColumns&&[...this.renderRoot.querySelectorAll("th[data-priority]")].some(el=>el.offsetParent===null),inlineSize=this.renderRoot.querySelector('[part="base"]')?.clientWidth??0,wouldHideAtAllocation=hasPriorityColumns&&inlineSize>0&&this.columns.some(column=>column.priority==="low"&&inlineSize<=LOW_PRIORITY_MAX_INLINE_SIZE||column.priority==="medium"&&inlineSize<=MEDIUM_PRIORITY_MAX_INLINE_SIZE),toggleAvailable=anyPriorityHidden||this.priorityColumnsVisible&&wouldHideAtAllocation;this.rehomeFocusedColumn(),this.priorityColumnsToggleAvailable!==toggleAvailable&&(this.priorityColumnsToggleAvailable=toggleAvailable),this.hasHiddenPriorityColumns!==anyPriorityHidden&&(this.hasHiddenPriorityColumns=anyPriorityHidden)}rehomeFocusedColumn(){const visible=this.visibleHeaders();visible.length===0||this.activeColKey===null||visible.some(header=>header.dataset.colKey===this.activeColKey)||(this.activeColKey=visible[0].dataset.colKey??null)}keyOf(row,index){try{const key=this.rowKey?this.rowKey(row):index;return typeof key=="string"?key.trim().length===0?void 0:key:typeof key=="number"?key:void 0}catch{return}}canonicalRowEntries(){const inputs=this.canonicalRowEntriesInputs;if(this.cachedCanonicalRowEntries!==null&&inputs?.rows===this.rows&&inputs.rowKey===this.rowKey)return this.cachedCanonicalRowEntries;const entries=[],seen=new Set;return this.rows.forEach((row,index)=>{const key=this.keyOf(row,index);if(key===void 0)return;const encoded=encodeKey(key);seen.has(encoded)||(seen.add(encoded),entries.push({row,index,key}))}),this.canonicalRowEntriesInputs={rows:this.rows,rowKey:this.rowKey},this.cachedCanonicalRowEntries=entries,entries}matchingEntries(){const text=this.filterText.trim(),locale=text===""?"":this.effectiveLocale,canonicalEntries=this.canonicalRowEntries(),inputs=this.matchingEntriesInputs;if(this.cachedMatchingEntries!==null&&inputs!==null&&inputs.entries===canonicalEntries&&inputs.filter===this.filter&&inputs.text===text&&inputs.locale===locale)return this.cachedMatchingEntries;let entries;if(text==="")entries=canonicalEntries;else{const intlLocale=this.effectiveLocale,normalized=text.toLocaleLowerCase(intlLocale);entries=canonicalEntries.filter(({row})=>this.filter?this.filter(row,text):safeStringifyForFilter(row).toLocaleLowerCase(intlLocale).includes(normalized))}return this.matchingEntriesInputs={entries:canonicalEntries,filter:this.filter,text,locale},this.cachedMatchingEntries=entries,entries}get normalizedPageSize(){return finiteInteger(this.pageSize,DEFAULT_PAGE_SIZE,1,MAX_PAGE_SIZE)}get effectiveSkeletonRows(){const explicit=finiteCount(this.skeletonRows,0,MAX_SKELETON_ROWS);if(explicit>0)return explicit;const pageSize=this.normalizedPageSize;return pageSize===DEFAULT_PAGE_SIZE?DEFAULT_SKELETON_ROWS:Math.min(pageSize,MAX_SKELETON_ROWS)}get matchingTotalItems(){const totalItems=finiteInteger(this.totalItems,-1);return totalItems>=0?totalItems:this.matchingEntries().length}get pageCount(){const pageSize=this.normalizedPageSize;return pageSize>0?Math.ceil(this.matchingTotalItems/pageSize):0}get appliedPage(){return this.pageCount===0?1:finiteInteger(this.page,1,1,this.pageCount)}sortedEntries(){const entries=this.matchingEntries();if(this.sortMode!=="client"||this.sortKey==="")return entries;const col=this.columnsByKey.get(this.sortKey);if(!col?.sortable)return entries;const locale=this.effectiveLocale,inputs=this.sortedEntriesInputs;if(this.cachedSortedEntries!==null&&inputs!==null&&inputs.entries===entries&&inputs.columns===this.columns&&inputs.mode===this.sortMode&&inputs.key===this.sortKey&&inputs.dir===this.sortDir&&inputs.locale===locale&&inputs.groupBy===this.groupBy)return this.cachedSortedEntries;const collator=getCollator(locale,{numeric:!0}),dir=this.sortDir==="desc"?-1:1,decorated=entries.map(entry=>{const raw=typeof col.sortValue=="function"?col.sortValue(entry.row):typeof col.cell=="function"?String(col.cell(entry.row)??""):"";return{entry,value:typeof raw=="number"&&!Number.isFinite(raw)?null:raw}}),compare=(a,b)=>{const av=a.value,bv=b.value;return av==null&&bv==null?0:av==null?1:bv==null?-1:typeof av=="number"&&typeof bv=="number"?(av-bv)*dir:collator.compare(String(av),String(bv))*dir};let sorted;const groupBy=this.groupBy;if(groupBy===void 0)decorated.sort(compare),sorted=decorated.map(decoration=>decoration.entry);else{const buckets=new Map;for(const decoration of decorated){const groupKey=groupBy(decoration.entry.row),bucket=buckets.get(groupKey);bucket===void 0?buckets.set(groupKey,[decoration]):bucket.push(decoration)}const ordered=[...buckets.values()],constantWithinEveryGroup=ordered.every(bucket=>bucket.every(decoration=>compare(decoration,bucket[0])===0));constantWithinEveryGroup&&ordered.sort((a,b)=>compare(a[0],b[0])),sorted=[];for(const bucket of ordered){constantWithinEveryGroup||bucket.sort(compare);for(const decoration of bucket)sorted.push(decoration.entry)}}return this.sortedEntriesInputs={entries,columns:this.columns,mode:this.sortMode,key:this.sortKey,dir:this.sortDir,locale,groupBy},this.cachedSortedEntries=sorted,sorted}renderedEntries(){const entries=this.sortedEntries();if(this.paginationMode==="server")return entries.slice(0,this.normalizedPageSize);const start=(this.appliedPage-1)*this.normalizedPageSize;return entries.slice(start,start+this.normalizedPageSize)}focusedColKey(){const visible=this.visibleHeaders(),visibleKeys=new Set(visible.map(el=>el.dataset.colKey).filter(key=>key!==void 0&&this.columnsByKey.has(key)));return this.activeColKey!==null&&this.columnsByKey.has(this.activeColKey)&&(visibleKeys.size===0||visibleKeys.has(this.activeColKey))?this.activeColKey:visible.find(el=>el.dataset.colKey!==void 0&&this.columnsByKey.has(el.dataset.colKey))?.dataset.colKey??this.columns[0]?.key??null}focusedRowKey(){if(this.activeRowKey!==null&&this.rowsByKey.has(this.activeRowKey))return this.activeRowKey;const selectedKey=this._selectedKeys.values().next().value;if(selectedKey!==void 0){const selected=encodeKey(selectedKey);if(this.rowsByKey.has(selected))return selected}const first=this.renderedEntries()[0];return first?encodeKey(first.key):null}rowsAffectingRovingFocusChanged(changed){return changed.has("rows")||changed.has("rowKey")||changed.has("filterText")||changed.has("filter")||changed.has("page")||changed.has("pageSize")||changed.has("paginationMode")||changed.has("totalItems")||changed.has("columns")||changed.has("sortKey")||changed.has("sortDir")||changed.has("sortMode")||changed.has("groupBy")}captureRovingFocus(changed){this.rovingFocusSnapshot=null;const active=activeElementIn(this.shadowRoot),HTMLElementCtor=this.ownerDocument?.defaultView?.HTMLElement;if(!(!HTMLElementCtor||!(active instanceof HTMLElementCtor))){if(changed.has("columns")&&active.matches("th[data-col-key]")){const headers=this.visibleHeaders(),key=active.dataset.colKey,index=headers.indexOf(active);key!==void 0&&index>=0&&(this.rovingFocusSnapshot={kind:"header",key,index,targetKey:null,element:active});return}if(this.rowsAffectingRovingFocusChanged(changed)&&active.matches("tr[data-row-key]")){const renderedRows=[...this.renderRoot.querySelectorAll("tbody tr[data-row-key]")],key=active.dataset.rowKey,index=renderedRows.indexOf(active);key!==void 0&&index>=0&&(this.rovingFocusSnapshot={kind:"row",key,index,targetKey:null,element:active})}}}resolveRovingFocusTarget(){const snapshot=this.rovingFocusSnapshot;if(snapshot===null)return;const keys=snapshot.kind==="header"?this.columns.map(column=>column.key):[...this.rowsByKey.keys()];snapshot.targetKey=keys.includes(snapshot.key)?snapshot.key:keys[Math.min(snapshot.index,keys.length-1)]??null,snapshot.kind==="header"?this.activeColKey=snapshot.targetKey:this.activeRowKey=snapshot.targetKey}willUpdate(changed){if(super.willUpdate(changed),this.captureRovingFocus(changed),this.selectionMode==="single"&&this._selectedKeys.size>1&&(changed.has("selectionMode")||changed.has("selectedRowKeys"))){const first=this._selectedKeys.values().next().value;if(this.selectedRowKeys=first===void 0?new Set:new Set([first]),this.hasUpdated){const rowKeys=Object.freeze(first===void 0?[]:[first]);this.emit("lr-selection-change",Object.freeze({rowKeys}))}}if(!this.hasUpdated){const parsed=readPersistedState(this.storageFullKey,v=>typeof v=="object"&&v!==null);parsed&&typeof parsed.priorityColumnsVisible=="boolean"&&(this.priorityColumnsVisible=parsed.priorityColumnsVisible)}if(changed.has("columns")&&(this.columnsByKey=new Map(this.columns.map(c=>[c.key,c]))),(changed.has("rows")||changed.has("rowKey")||changed.has("filterText")||changed.has("filter")||changed.has("page")||changed.has("pageSize")||changed.has("paginationMode")||changed.has("totalItems")||changed.has("columns")||changed.has("sortKey")||changed.has("sortDir")||changed.has("sortMode")||changed.has("groupBy"))&&(this.rowsByKey=new Map(this.renderedEntries().map(entry=>[encodeKey(entry.key),entry]))),this.resolveRovingFocusTarget(),this.editingCell!==null){const column=this.columnsByKey.get(this.editingCell.columnKey);(!this.rowsByKey.has(this.editingCell.rowKey)||normalizedEditTrigger(column?.editTrigger)!=="double-click")&&(this.editingCell=null)}this.editorHadFocusBeforeUpdate=this.focusedEditorCell!==null&&activeElementIn(this.shadowRoot)===this.editorElementFor(this.focusedEditorCell.rowKey,this.focusedEditorCell.columnKey)}stickyOffsets(){const offsets=new Map,headerWidths=new Map;for(const el of this.renderRoot.querySelectorAll("th[data-col-key]")){const key=el.dataset.colKey;key!==void 0&&!headerWidths.has(key)&&headerWidths.set(key,el.offsetWidth)}const headerWidth=key=>headerWidths.get(key)??0;let runningStart=0;for(const col of this.columns)stickyDirection(col.sticky)==="start"&&(offsets.set(col.key,runningStart),runningStart+=headerWidth(col.key));let runningEnd=0;for(let i=this.columns.length-1;i>=0;i--){const col=this.columns[i];col&&stickyDirection(col.sticky)==="end"&&(offsets.set(col.key,runningEnd),runningEnd+=headerWidth(col.key))}return offsets}computeHeatDomain(hasHeatTint){if(!hasHeatTint)return null;const values=[];for(const entry of this.matchingEntries())for(const col of this.columns){const v=col.heatValue?.(entry.row);v!=null&&Number.isFinite(v)&&values.push(v)}const auto=minMax(values),lo=this.heatTintScale?.min??auto?.[0],hi=this.heatTintScale?.max??auto?.[1];return lo===void 0||hi===void 0?null:[lo,hi]}heatShare(col,row,domain){if(!col.heatValue||!domain)return null;const v=col.heatValue(row);if(v==null||!Number.isFinite(v))return null;const[lo,hi]=domain;return`${(finiteRatio(v,lo,hi)*100).toFixed(2)}%`}applyStickyOffsets(){if(!this.columns.some(c=>c.sticky))return;const offsets=this.stickyOffsets();this.renderRoot.querySelectorAll("[data-col-key]").forEach(el=>{const key=el.dataset.colKey;key!==void 0&&offsets.has(key)&&el.style.setProperty("--lr-table-sticky-offset",`${offsets.get(key)}px`)})}updated(changed){super.updated(changed),this.loadingAnnouncementsReady&&changed.has("loading")&&this.loading&&this.announcementSink?.announce(this.loadingText()),this.loadingAnnouncementsReady=!0,this.persistReady&&changed.has("priorityColumnsVisible")&&writePersistedState(this.storageFullKey,{priorityColumnsVisible:this.priorityColumnsVisible}),this.persistReady=!0,(changed.has("columns")||changed.has("rows")||changed.has("rowKey"))&&this.applyStickyOffsets(),this.syncResizeHandleValues();const base=this.renderRoot.querySelector('[part="base"]');if(base&&this.observeBase(base),this.observeTable(this.renderRoot.querySelector('[part="table"]')??void 0),this.syncAutoScrollMode(),this.observeHeaders(),this.restoreRovingFocus(),this.hasAlwaysOnEditors&&this.restoreAlwaysOnEditorFocus(),changed.has("editingCell")&&this.editingCell){const{rowKey,columnKey}=this.editingCell;queueMicrotask(()=>this.editorElementFor(rowKey,columnKey)?.focus())}queueMicrotask(()=>this.recomputeHiddenPriorityColumns())}restoreRovingFocus(){const snapshot=this.rovingFocusSnapshot;if(this.rovingFocusSnapshot=null,snapshot===null)return;const internalActive=activeElementIn(this.shadowRoot);if(internalActive!==null&&internalActive!==snapshot.element)return;const documentActive=activeElementIn(this.ownerDocument);if(documentActive!==null&&documentActive!==this&&documentActive!==this.ownerDocument.body)return;const candidates=snapshot.kind==="header"?this.visibleHeaders():[...this.renderRoot.querySelectorAll("tbody tr[data-row-key]")],target=candidates.find(candidate=>snapshot.kind==="header"?candidate.dataset.colKey===snapshot.targetKey:candidate.dataset.rowKey===snapshot.targetKey)??candidates[Math.min(snapshot.index,candidates.length-1)]??null;snapshot.kind==="header"?this.focusHeader(target):this.focusRow(target)}activateColumn(key){this.activeColKey=key;const col=this.columnsByKey.get(key);if(!col?.sortable)return;const sortDir=this.sortKey===key?this.sortDir==="asc"?"desc":"asc":this.defaultSortDir,request=Object.freeze({phase:"request",sortKey:col.key,sortDir});this.emit("lr-sort-request",request,{cancelable:!0}).defaultPrevented||(this.sortMode==="client"&&(this.sortKey=col.key,this.sortDir=sortDir),this.emit("lr-sort",Object.freeze({phase:"commit",sortKey:col.key,sortDir})))}activateRow(key){this.activeRowKey=key;const entry=this.rowsByKey.get(key);if(entry===void 0)return;const{row,key:selectedKey}=entry;if(this.emit("lr-row-click",Object.freeze({row})),this.selectionMode==="single"){this.selectedRowKeys=new Set([selectedKey]);const rowKeys=Object.freeze([selectedKey]);this.emit("lr-selection-change",Object.freeze({rowKeys}))}else if(this.selectionMode==="multiple"){const rawKey=selectedKey,next=new Set(this._selectedKeys);next.has(rawKey)?next.delete(rawKey):next.add(rawKey),this.selectedRowKeys=next;const rowKeys=Object.freeze([...next]);this.emit("lr-selection-change",Object.freeze({rowKeys}))}}get hasAlwaysOnEditors(){return this.columns.some(col=>normalizedEditTrigger(col.editTrigger)==="always")}editorValue(row,column){const value=column.editValue?.(row)??row[column.key]??"";return String(value)}startEditing(rowKey,columnKey){const column=this.columnsByKey.get(columnKey);normalizedEditTrigger(column?.editTrigger)!=="double-click"||!this.rowsByKey.has(rowKey)||(this.editingCell={rowKey,columnKey})}commitEdit(event,rowKey,columnKey){event.stopPropagation();const input=event.currentTarget,entry=this.rowsByKey.get(rowKey),column=this.columnsByKey.get(columnKey),isTransient=this.editingCell?.rowKey===rowKey&&this.editingCell.columnKey===columnKey;if(!entry||!column||normalizedEditTrigger(column.editTrigger)===void 0){isTransient&&(this.editingCell=null);return}const value=column.editType==="number"&&input.value!==""?Number(input.value):input.value;this.emit("lr-cell-edit",Object.freeze({row:entry.row,columnKey,value})),isTransient&&(this.editingCell=null)}editorElementFor(rowKey,columnKey){const row=[...this.renderRoot.querySelectorAll("[data-row-key]")].find(el=>el.dataset.rowKey===rowKey);return(row?[...row.querySelectorAll("td[data-col-key]")].find(el=>el.dataset.colKey===columnKey):void 0)?.querySelector('[part="cell-editor"]')??null}restoreAlwaysOnEditorFocus(){const cell=this.focusedEditorCell;if(cell===null)return;const editor=this.editorElementFor(cell.rowKey,cell.columnKey);editor===null?this.focusedEditorCell=null:this.editorHadFocusBeforeUpdate&&activeElementIn(this.shadowRoot)!==editor&&editor.focus(),this.editorHadFocusBeforeUpdate=!1}activateExpandToggle(key){const entry=this.rowsByKey.get(encodeKey(key));entry!==void 0&&this.emit("lr-row-expand-toggle",Object.freeze({row:entry.row,rowKey:key}))}visibleHeaders(){return[...this.renderRoot?.querySelectorAll("th[data-col-key]")??[]].filter(el=>el.offsetParent!==null)}focusHeader(el){el?.dataset.colKey&&(this.activeColKey=el.dataset.colKey,el.focus())}focusRow(el){el?.dataset.rowKey&&(this.activeRowKey=el.dataset.rowKey,el.focus())}onHeaderKeyDown(e,th){if(e.key==="Enter"||e.key===" "){e.preventDefault(),this.activateColumn(th.dataset.colKey);return}const headers=this.visibleHeaders(),index=headers.indexOf(th);if(index<0)return;const rtl=isRtl(this);switch(e.key){case"ArrowLeft":e.preventDefault(),this.focusHeader(headers[rtl?Math.min(headers.length-1,index+1):Math.max(0,index-1)]??null);return;case"ArrowRight":e.preventDefault(),this.focusHeader(headers[rtl?Math.max(0,index-1):Math.min(headers.length-1,index+1)]??null);return;case"Home":e.preventDefault(),this.focusHeader(headers[0]??null);return;case"End":e.preventDefault(),this.focusHeader(headers[headers.length-1]??null);return;case"ArrowDown":{e.preventDefault();const rows=[...this.renderRoot.querySelectorAll("[data-row-key]")],key=this.focusedRowKey();this.focusRow(rows.find(r=>r.dataset.rowKey===key)??rows[0]??null);return}default:return}}onRowKeyDown(e,tr){if(e.key==="Enter"||e.key===" "){e.preventDefault(),this.activateRow(tr.dataset.rowKey);return}const bodyRows=[...this.renderRoot.querySelectorAll("[data-row-key]")],index=bodyRows.indexOf(tr);if(!(index<0))switch(e.key){case"ArrowDown":e.preventDefault(),this.focusRow(bodyRows[Math.min(bodyRows.length-1,index+1)]??null);return;case"ArrowUp":if(e.preventDefault(),index===0){const headers=this.visibleHeaders(),key=this.focusedColKey();this.focusHeader(headers.find(h=>h.dataset.colKey===key)??headers[0]??null)}else this.focusRow(bodyRows[index-1]??null);return;case"Home":e.preventDefault(),this.focusRow(bodyRows[0]??null);return;case"End":e.preventDefault(),this.focusRow(bodyRows[bodyRows.length-1]??null);return;default:return}}renderCellValue(col,row){return typeof col.cell=="function"?col.cell(row):(devWarnOnce(MISSING_CELL_RENDERER_WARNING,"<lr-table>: a column has no required `cell` renderer, so its cells render empty. Supply a `cell` callback for every column."),nothing)}renderCellEditor(row,col,rowKey,alwaysOn){const type=col.editType??"text",isText=type==="text",value=this.editorValue(row,col),label=this.localize("tableEditCell",void 0,{column:col.label}),spellcheck=isText?this.spellcheck:nothing,autocapitalize=isText?this.autocapitalize||nothing:nothing,autocorrect=isText?this.autoCorrect||nothing:nothing,onChange=event=>this.commitEdit(event,rowKey,col.key),onKeyDown=event=>this.onEditorKeyDown(event,rowKey,col.key);return alwaysOn?html`<input
14
+ ></span>`}syncResizeHandleValues(){for(const handle of this.renderRoot.querySelectorAll('[part="resize-handle"]')){const key=handle.dataset.colKey;if(!key)continue;const column=this.columnsByKey.get(key);if(!column||this.resizedColumnWidths.has(key)||this.parsePixelLength(column.width)!==void 0)continue;const rendered=handle.closest("th[data-col-key]")?.getBoundingClientRect().width;if(rendered&&rendered>0){const width=Math.round(rendered);handle.setAttribute("aria-valuenow",String(width)),handle.setAttribute("aria-valuetext",this.resizeValueText(width))}}}detachResizePointerListeners(){const resizeEventWindow=this.resizeEventWindow;resizeEventWindow&&(resizeEventWindow.removeEventListener("pointermove",this.onResizePointerMove),resizeEventWindow.removeEventListener("pointerup",this.onResizePointerEnd),resizeEventWindow.removeEventListener("pointercancel",this.onResizePointerEnd),resizeEventWindow.removeEventListener("lostpointercapture",this.onResizePointerEnd),this.resizeEventWindow=void 0)}rollbackResizePreview(state2){const reverted=new Map(this.resizedColumnWidths);state2.previousWidth===void 0?reverted.delete(state2.key):reverted.set(state2.key,state2.previousWidth),this.resizedColumnWidths=reverted}cancelResizeGesture(){const state2=this.resizeState;if(this.resizeState=void 0,this.detachResizePointerListeners(),!!state2){state2.handle.removeAttribute("data-resizing");try{state2.handle.releasePointerCapture?.(state2.pointerId)}catch{}this.rollbackResizePreview(state2)}}firstUpdated(changed){super.firstUpdated(changed),!this.accessibleLabel&&!this.hasAttribute("aria-label")&&!this.caption&&devWarnOnce(MISSING_ACCESSIBLE_NAME_WARNING,"<lr-table> has no accessible name: set `accessibleLabel`, a host `aria-label`, or `caption` so assistive technology can identify the grid.")}connectedCallback(){super.connectedCallback(),this.syncAnnouncementSink();const owner=this.ownerDocument.defaultView,ResizeObserverCtor=owner?.ResizeObserver;let observer;ResizeObserverCtor&&(observer=new ResizeObserverCtor(()=>{!this.isConnected||this.ownerDocument.defaultView!==owner||this.resizeObserver!==observer||this.scheduleLayoutSync()})),this.resizeObserver=observer;const base=this.renderRoot?.querySelector('[part="base"]');base&&(this.observeBase(base),this.observeTable(this.renderRoot.querySelector('[part="table"]')??void 0),this.observeHeaders())}disconnectedCallback(){super.disconnectedCallback(),this.releaseAnnouncementSink(),this.cancelResizeGesture(),this.resizeObserver?.disconnect(),this.resizeObserver=void 0;const frame=this.layoutFrame;frame&&frame.owner.cancelAnimationFrame(frame.handle),this.layoutFrame=null,this.observedBase=void 0,this.observedTable=void 0,this.observedHeaders.clear()}releaseAnnouncementSink(){this.announcementSink?.release(),this.announcementSink=void 0}syncAnnouncementSink(){if(!this.isConnected){this.releaseAnnouncementSink();return}this.announcementSink?.element.ownerDocument!==this.ownerDocument&&(this.releaseAnnouncementSink(),this.announcementSink=acquireAnnouncementSink("polite",{document:this.ownerDocument,source:this}))}localizedOverride(key,override){return override??this.localize(key)}loadingText(){return this.localizedOverride("tableLoading",this.loadingLabel)}observeBase(base){this.observedBase!==base&&(this.observedBase&&this.resizeObserver?.unobserve(this.observedBase),this.resizeObserver?.observe(base),this.observedBase=base)}observeTable(table){this.observedTable!==table&&(this.observedTable&&this.resizeObserver?.unobserve(this.observedTable),table&&this.resizeObserver?.observe(table),this.observedTable=table)}syncAutoScrollMode(){const base=this.renderRoot.querySelector('[part="base"]');if(!base)return;const overflows=this.scrollMode==="auto"&&base.scrollWidth-base.clientWidth>TABLE_SCROLL_OVERFLOW_TOLERANCE_PX;base.toggleAttribute("data-scroll-overflow",overflows)}observeHeaders(){const headers=new Set(this.columns.some(column=>column.sticky||column.resizable)?this.renderRoot.querySelectorAll("th[data-col-key]"):[]);for(const header of this.observedHeaders)headers.has(header)||(this.resizeObserver?.unobserve(header),this.observedHeaders.delete(header));for(const header of headers)this.observedHeaders.has(header)||(this.observedHeaders.add(header),this.resizeObserver?.observe(header))}recomputeHiddenPriorityColumns(){const hasPriorityColumns=this.columns.some(col=>col.priority),anyPriorityHidden=hasPriorityColumns&&[...this.renderRoot.querySelectorAll("th[data-priority]")].some(el=>el.offsetParent===null),inlineSize=this.renderRoot.querySelector('[part="base"]')?.clientWidth??0,wouldHideAtAllocation=hasPriorityColumns&&inlineSize>0&&this.columns.some(column=>column.priority==="low"&&inlineSize<=LOW_PRIORITY_MAX_INLINE_SIZE||column.priority==="medium"&&inlineSize<=MEDIUM_PRIORITY_MAX_INLINE_SIZE),toggleAvailable=anyPriorityHidden||this.priorityColumnsVisible&&wouldHideAtAllocation;this.rehomeFocusedColumn(),this.priorityColumnsToggleAvailable!==toggleAvailable&&(this.priorityColumnsToggleAvailable=toggleAvailable),this.hasHiddenPriorityColumns!==anyPriorityHidden&&(this.hasHiddenPriorityColumns=anyPriorityHidden)}rehomeFocusedColumn(){const visible=this.visibleHeaders();visible.length===0||this.activeColKey===null||visible.some(header=>header.dataset.colKey===this.activeColKey)||(this.activeColKey=visible[0].dataset.colKey??null)}keyOf(row,index){try{const key=this.rowKey?this.rowKey(row):index;return typeof key=="string"?key.trim().length===0?void 0:key:typeof key=="number"?key:void 0}catch{return}}canonicalRowEntries(){const inputs=this.canonicalRowEntriesInputs;if(this.cachedCanonicalRowEntries!==null&&inputs?.rows===this.rows&&inputs.rowKey===this.rowKey)return this.cachedCanonicalRowEntries;const entries=[],seen=new Set;return this.rows.forEach((row,index)=>{const key=this.keyOf(row,index);if(key===void 0)return;const encoded=encodeKey(key);seen.has(encoded)||(seen.add(encoded),entries.push({row,index,key}))}),this.canonicalRowEntriesInputs={rows:this.rows,rowKey:this.rowKey},this.cachedCanonicalRowEntries=entries,entries}matchingEntries(){const text=(this.filterText??"").trim(),locale=text===""?"":this.effectiveLocale,canonicalEntries=this.canonicalRowEntries(),inputs=this.matchingEntriesInputs;if(this.cachedMatchingEntries!==null&&inputs!==null&&inputs.entries===canonicalEntries&&inputs.filter===this.filter&&inputs.text===text&&inputs.locale===locale)return this.cachedMatchingEntries;let entries;if(text==="")entries=canonicalEntries;else{const intlLocale=this.effectiveLocale,normalized=text.toLocaleLowerCase(intlLocale);entries=canonicalEntries.filter(({row})=>this.filter?this.filter(row,text):safeStringifyForFilter(row).toLocaleLowerCase(intlLocale).includes(normalized))}return this.matchingEntriesInputs={entries:canonicalEntries,filter:this.filter,text,locale},this.cachedMatchingEntries=entries,entries}get normalizedPageSize(){return finiteInteger(this.pageSize,DEFAULT_PAGE_SIZE,1,MAX_PAGE_SIZE)}get effectiveSkeletonRows(){const explicit=finiteCount(this.skeletonRows,0,MAX_SKELETON_ROWS);if(explicit>0)return explicit;const pageSize=this.normalizedPageSize;return pageSize===DEFAULT_PAGE_SIZE?DEFAULT_SKELETON_ROWS:Math.min(pageSize,MAX_SKELETON_ROWS)}get matchingTotalItems(){const totalItems=finiteInteger(this.totalItems,-1);return totalItems>=0?totalItems:this.matchingEntries().length}get pageCount(){const pageSize=this.normalizedPageSize;return pageSize>0?Math.ceil(this.matchingTotalItems/pageSize):0}get appliedPage(){return this.pageCount===0?1:finiteInteger(this.page,1,1,this.pageCount)}sortedEntries(){const entries=this.matchingEntries();if(this.sortMode!=="client"||this.sortKey==="")return entries;const col=this.columnsByKey.get(this.sortKey);if(!col?.sortable)return entries;const locale=this.effectiveLocale,inputs=this.sortedEntriesInputs;if(this.cachedSortedEntries!==null&&inputs!==null&&inputs.entries===entries&&inputs.columns===this.columns&&inputs.mode===this.sortMode&&inputs.key===this.sortKey&&inputs.dir===this.sortDir&&inputs.locale===locale&&inputs.groupBy===this.groupBy)return this.cachedSortedEntries;const collator=getCollator(locale,{numeric:!0}),dir=this.sortDir==="desc"?-1:1,decorated=entries.map(entry=>{const raw=typeof col.sortValue=="function"?col.sortValue(entry.row):typeof col.cell=="function"?String(col.cell(entry.row)??""):"";return{entry,value:typeof raw=="number"&&!Number.isFinite(raw)?null:raw}}),compare=(a,b)=>{const av=a.value,bv=b.value;return av==null&&bv==null?0:av==null?1:bv==null?-1:typeof av=="number"&&typeof bv=="number"?(av-bv)*dir:collator.compare(String(av),String(bv))*dir};let sorted;const groupBy=this.groupBy;if(groupBy===void 0)decorated.sort(compare),sorted=decorated.map(decoration=>decoration.entry);else{const buckets=new Map;for(const decoration of decorated){const groupKey=groupBy(decoration.entry.row),bucket=buckets.get(groupKey);bucket===void 0?buckets.set(groupKey,[decoration]):bucket.push(decoration)}const ordered=[...buckets.values()],constantWithinEveryGroup=ordered.every(bucket=>bucket.every(decoration=>compare(decoration,bucket[0])===0));constantWithinEveryGroup&&ordered.sort((a,b)=>compare(a[0],b[0])),sorted=[];for(const bucket of ordered){constantWithinEveryGroup||bucket.sort(compare);for(const decoration of bucket)sorted.push(decoration.entry)}}return this.sortedEntriesInputs={entries,columns:this.columns,mode:this.sortMode,key:this.sortKey,dir:this.sortDir,locale,groupBy},this.cachedSortedEntries=sorted,sorted}renderedEntries(){const entries=this.sortedEntries();if(this.paginationMode==="server")return entries.slice(0,this.normalizedPageSize);const start=(this.appliedPage-1)*this.normalizedPageSize;return entries.slice(start,start+this.normalizedPageSize)}focusedColKey(){const visible=this.visibleHeaders(),visibleKeys=new Set(visible.map(el=>el.dataset.colKey).filter(key=>key!==void 0&&this.columnsByKey.has(key)));return this.activeColKey!==null&&this.columnsByKey.has(this.activeColKey)&&(visibleKeys.size===0||visibleKeys.has(this.activeColKey))?this.activeColKey:visible.find(el=>el.dataset.colKey!==void 0&&this.columnsByKey.has(el.dataset.colKey))?.dataset.colKey??this.columns[0]?.key??null}focusedRowKey(){if(this.activeRowKey!==null&&this.rowsByKey.has(this.activeRowKey))return this.activeRowKey;const selectedKey=this._selectedKeys.values().next().value;if(selectedKey!==void 0){const selected=encodeKey(selectedKey);if(this.rowsByKey.has(selected))return selected}const first=this.renderedEntries()[0];return first?encodeKey(first.key):null}rowsAffectingRovingFocusChanged(changed){return changed.has("rows")||changed.has("rowKey")||changed.has("filterText")||changed.has("filter")||changed.has("page")||changed.has("pageSize")||changed.has("paginationMode")||changed.has("totalItems")||changed.has("columns")||changed.has("sortKey")||changed.has("sortDir")||changed.has("sortMode")||changed.has("groupBy")||this.rowsLocale!==this.effectiveLocale}captureRovingFocus(changed){this.rovingFocusSnapshot=null;const active=activeElementIn(this.shadowRoot),HTMLElementCtor=this.ownerDocument?.defaultView?.HTMLElement;if(!(!HTMLElementCtor||!(active instanceof HTMLElementCtor))){if(changed.has("columns")&&active.matches("th[data-col-key]")){const headers=this.visibleHeaders(),key=active.dataset.colKey,index=headers.indexOf(active);key!==void 0&&index>=0&&(this.rovingFocusSnapshot={kind:"header",key,index,targetKey:null,element:active});return}if(this.rowsAffectingRovingFocusChanged(changed)&&active.matches("tr[data-row-key]")){const renderedRows=[...this.renderRoot.querySelectorAll("tbody tr[data-row-key]")],key=active.dataset.rowKey,index=renderedRows.indexOf(active);key!==void 0&&index>=0&&(this.rovingFocusSnapshot={kind:"row",key,index,targetKey:null,element:active})}}}resolveRovingFocusTarget(){const snapshot=this.rovingFocusSnapshot;if(snapshot===null)return;const keys=snapshot.kind==="header"?this.columns.map(column=>column.key):[...this.rowsByKey.keys()];snapshot.targetKey=keys.includes(snapshot.key)?snapshot.key:keys[Math.min(snapshot.index,keys.length-1)]??null,snapshot.kind==="header"?this.activeColKey=snapshot.targetKey:this.activeRowKey=snapshot.targetKey}willUpdate(changed){if(super.willUpdate(changed),this.captureRovingFocus(changed),this.selectionMode==="single"&&this._selectedKeys.size>1&&(changed.has("selectionMode")||changed.has("selectedRowKeys"))){const first=this._selectedKeys.values().next().value;if(this.selectedRowKeys=first===void 0?new Set:new Set([first]),this.hasUpdated){const rowKeys=Object.freeze(first===void 0?[]:[first]);this.emit("lr-selection-change",Object.freeze({rowKeys}))}}if(!this.hasUpdated){const parsed=readPersistedState(this.storageFullKey,v=>typeof v=="object"&&v!==null);parsed&&typeof parsed.priorityColumnsVisible=="boolean"&&(this.priorityColumnsVisible=parsed.priorityColumnsVisible)}if(changed.has("columns")&&(this.columnsByKey=new Map(this.columns.map(c=>[c.key,c]))),this.rowsAffectingRovingFocusChanged(changed)&&(this.rowsByKey=new Map(this.renderedEntries().map(entry=>[encodeKey(entry.key),entry])),this.rowsLocale=this.effectiveLocale),this.resolveRovingFocusTarget(),this.editingCell!==null){const column=this.columnsByKey.get(this.editingCell.columnKey);(!this.rowsByKey.has(this.editingCell.rowKey)||normalizedEditTrigger(column?.editTrigger)!=="double-click")&&(this.editingCell=null)}this.editorHadFocusBeforeUpdate=this.focusedEditorCell!==null&&activeElementIn(this.shadowRoot)===this.editorElementFor(this.focusedEditorCell.rowKey,this.focusedEditorCell.columnKey)}stickyOffsets(){const offsets=new Map,headerWidths=new Map;for(const el of this.renderRoot.querySelectorAll("th[data-col-key]")){const key=el.dataset.colKey;key!==void 0&&!headerWidths.has(key)&&headerWidths.set(key,el.offsetWidth)}const headerWidth=key=>headerWidths.get(key)??0;let runningStart=0;for(const col of this.columns)stickyDirection(col.sticky)==="start"&&(offsets.set(col.key,runningStart),runningStart+=headerWidth(col.key));let runningEnd=0;for(let i=this.columns.length-1;i>=0;i--){const col=this.columns[i];col&&stickyDirection(col.sticky)==="end"&&(offsets.set(col.key,runningEnd),runningEnd+=headerWidth(col.key))}return offsets}computeHeatDomain(hasHeatTint){if(!hasHeatTint)return null;const values=[];for(const entry of this.matchingEntries())for(const col of this.columns){const v=col.heatValue?.(entry.row);v!=null&&Number.isFinite(v)&&values.push(v)}const auto=minMax(values),lo=this.heatTintScale?.min??auto?.[0],hi=this.heatTintScale?.max??auto?.[1];return lo===void 0||hi===void 0?null:[lo,hi]}heatShare(col,row,domain){if(!col.heatValue||!domain)return null;const v=col.heatValue(row);if(v==null||!Number.isFinite(v))return null;const[lo,hi]=domain;return`${(finiteRatio(v,lo,hi)*100).toFixed(2)}%`}applyStickyOffsets(){if(!this.columns.some(c=>c.sticky))return;const offsets=this.stickyOffsets();this.renderRoot.querySelectorAll("[data-col-key]").forEach(el=>{const key=el.dataset.colKey;key!==void 0&&offsets.has(key)&&el.style.setProperty("--lr-table-sticky-offset",`${offsets.get(key)}px`)})}updated(changed){super.updated(changed),this.loadingAnnouncementsReady&&changed.has("loading")&&this.loading&&this.announcementSink?.announce(this.loadingText()),this.loadingAnnouncementsReady=!0,this.persistReady&&changed.has("priorityColumnsVisible")&&writePersistedState(this.storageFullKey,{priorityColumnsVisible:this.priorityColumnsVisible}),this.persistReady=!0,(changed.has("columns")||changed.has("rows")||changed.has("rowKey"))&&this.applyStickyOffsets(),this.syncResizeHandleValues();const base=this.renderRoot.querySelector('[part="base"]');if(base&&this.observeBase(base),this.observeTable(this.renderRoot.querySelector('[part="table"]')??void 0),this.syncAutoScrollMode(),this.observeHeaders(),this.restoreRovingFocus(),this.hasAlwaysOnEditors&&this.restoreAlwaysOnEditorFocus(),changed.has("editingCell")&&this.editingCell){const{rowKey,columnKey}=this.editingCell;queueMicrotask(()=>this.editorElementFor(rowKey,columnKey)?.focus())}queueMicrotask(()=>this.recomputeHiddenPriorityColumns())}restoreRovingFocus(){const snapshot=this.rovingFocusSnapshot;if(this.rovingFocusSnapshot=null,snapshot===null)return;const internalActive=activeElementIn(this.shadowRoot);if(internalActive!==null&&internalActive!==snapshot.element)return;const documentActive=activeElementIn(this.ownerDocument);if(documentActive!==null&&documentActive!==this&&documentActive!==this.ownerDocument.body)return;const candidates=snapshot.kind==="header"?this.visibleHeaders():[...this.renderRoot.querySelectorAll("tbody tr[data-row-key]")],target=candidates.find(candidate=>snapshot.kind==="header"?candidate.dataset.colKey===snapshot.targetKey:candidate.dataset.rowKey===snapshot.targetKey)??candidates[Math.min(snapshot.index,candidates.length-1)]??null;snapshot.kind==="header"?this.focusHeader(target):this.focusRow(target)}activateColumn(key){this.activeColKey=key;const col=this.columnsByKey.get(key);if(!col?.sortable)return;const sortDir=this.sortKey===key?this.sortDir==="asc"?"desc":"asc":this.defaultSortDir,request=Object.freeze({phase:"request",sortKey:col.key,sortDir});this.emit("lr-sort-request",request,{cancelable:!0}).defaultPrevented||(this.sortMode==="client"&&(this.sortKey=col.key,this.sortDir=sortDir),this.emit("lr-sort",Object.freeze({phase:"commit",sortKey:col.key,sortDir})))}activateRow(key){this.activeRowKey=key;const entry=this.rowsByKey.get(key);if(entry===void 0)return;const{row,key:selectedKey}=entry;if(this.emit("lr-row-click",Object.freeze({row})),this.selectionMode==="single"){this.selectedRowKeys=new Set([selectedKey]);const rowKeys=Object.freeze([selectedKey]);this.emit("lr-selection-change",Object.freeze({rowKeys}))}else if(this.selectionMode==="multiple"){const rawKey=selectedKey,next=new Set(this._selectedKeys);next.has(rawKey)?next.delete(rawKey):next.add(rawKey),this.selectedRowKeys=next;const rowKeys=Object.freeze([...next]);this.emit("lr-selection-change",Object.freeze({rowKeys}))}}get hasAlwaysOnEditors(){return this.columns.some(col=>normalizedEditTrigger(col.editTrigger)==="always")}editorValue(row,column){const value=column.editValue?.(row)??row[column.key]??"";return String(value)}startEditing(rowKey,columnKey){const column=this.columnsByKey.get(columnKey);normalizedEditTrigger(column?.editTrigger)!=="double-click"||!this.rowsByKey.has(rowKey)||(this.editingCell={rowKey,columnKey})}commitEdit(event,rowKey,columnKey){event.stopPropagation();const input=event.currentTarget,entry=this.rowsByKey.get(rowKey),column=this.columnsByKey.get(columnKey),isTransient=this.editingCell?.rowKey===rowKey&&this.editingCell.columnKey===columnKey;if(!entry||!column||normalizedEditTrigger(column.editTrigger)===void 0){isTransient&&(this.editingCell=null);return}const value=column.editType==="number"&&input.value!==""?Number(input.value):input.value;this.emit("lr-cell-edit",Object.freeze({row:entry.row,columnKey,value})),isTransient&&(this.editingCell=null)}editorElementFor(rowKey,columnKey){const row=[...this.renderRoot.querySelectorAll("[data-row-key]")].find(el=>el.dataset.rowKey===rowKey);return(row?[...row.querySelectorAll("td[data-col-key]")].find(el=>el.dataset.colKey===columnKey):void 0)?.querySelector('[part="cell-editor"]')??null}restoreAlwaysOnEditorFocus(){const cell=this.focusedEditorCell;if(cell===null)return;const editor=this.editorElementFor(cell.rowKey,cell.columnKey);editor===null?this.focusedEditorCell=null:this.editorHadFocusBeforeUpdate&&activeElementIn(this.shadowRoot)!==editor&&editor.focus(),this.editorHadFocusBeforeUpdate=!1}activateExpandToggle(key){const entry=this.rowsByKey.get(encodeKey(key));entry!==void 0&&this.emit("lr-row-expand-toggle",Object.freeze({row:entry.row,rowKey:key}))}visibleHeaders(){return[...this.renderRoot?.querySelectorAll("th[data-col-key]")??[]].filter(el=>el.offsetParent!==null)}focusHeader(el){el?.dataset.colKey&&(this.activeColKey=el.dataset.colKey,el.focus())}focusRow(el){el?.dataset.rowKey&&(this.activeRowKey=el.dataset.rowKey,el.focus())}onHeaderKeyDown(e,th){if(e.key==="Enter"||e.key===" "){e.preventDefault(),this.activateColumn(th.dataset.colKey);return}const headers=this.visibleHeaders(),index=headers.indexOf(th);if(index<0)return;const rtl=isRtl(this);switch(e.key){case"ArrowLeft":e.preventDefault(),this.focusHeader(headers[rtl?Math.min(headers.length-1,index+1):Math.max(0,index-1)]??null);return;case"ArrowRight":e.preventDefault(),this.focusHeader(headers[rtl?Math.max(0,index-1):Math.min(headers.length-1,index+1)]??null);return;case"Home":e.preventDefault(),this.focusHeader(headers[0]??null);return;case"End":e.preventDefault(),this.focusHeader(headers[headers.length-1]??null);return;case"ArrowDown":{e.preventDefault();const rows=[...this.renderRoot.querySelectorAll("[data-row-key]")],key=this.focusedRowKey();this.focusRow(rows.find(r=>r.dataset.rowKey===key)??rows[0]??null);return}default:return}}onRowKeyDown(e,tr){if(e.key==="Enter"||e.key===" "){e.preventDefault(),this.activateRow(tr.dataset.rowKey);return}const bodyRows=[...this.renderRoot.querySelectorAll("[data-row-key]")],index=bodyRows.indexOf(tr);if(!(index<0))switch(e.key){case"ArrowDown":e.preventDefault(),this.focusRow(bodyRows[Math.min(bodyRows.length-1,index+1)]??null);return;case"ArrowUp":if(e.preventDefault(),index===0){const headers=this.visibleHeaders(),key=this.focusedColKey();this.focusHeader(headers.find(h=>h.dataset.colKey===key)??headers[0]??null)}else this.focusRow(bodyRows[index-1]??null);return;case"Home":e.preventDefault(),this.focusRow(bodyRows[0]??null);return;case"End":e.preventDefault(),this.focusRow(bodyRows[bodyRows.length-1]??null);return;default:return}}renderCellValue(col,row){return typeof col.cell=="function"?col.cell(row):(devWarnOnce(MISSING_CELL_RENDERER_WARNING,"<lr-table>: a column has no required `cell` renderer, so its cells render empty. Supply a `cell` callback for every column."),nothing)}renderCellEditor(row,col,rowKey,alwaysOn){const type=col.editType??"text",isText=type==="text",value=this.editorValue(row,col),label=this.localize("tableEditCell",void 0,{column:col.label}),spellcheck=isText?this.spellcheck:nothing,autocapitalize=isText?this.autocapitalize||nothing:nothing,autocorrect=isText?this.autoCorrect||nothing:nothing,onChange=event=>this.commitEdit(event,rowKey,col.key),onKeyDown=event=>this.onEditorKeyDown(event,rowKey,col.key);return alwaysOn?html`<input
15
15
  part="cell-editor"
16
16
  type=${type}
17
17
  value=${value}
@@ -168,7 +168,7 @@ var __decorate=function(decorators,target,key,desc){var c=arguments.length,r=c<3
168
168
  ${this.columns.some(c=>c.footer)?html`<tfoot part="foot">
169
169
  <tr part="footer-row">
170
170
  ${hasExpand?html`<td part="footer-cell" aria-hidden="true"></td>`:nothing}
171
- ${this.columns.map(col=>html`<td part="footer-cell" data-col-key=${col.key} data-align=${col.align??"start"}>
171
+ ${this.columns.map(col=>html`<td part="footer-cell" data-col-key=${col.key} data-priority=${col.priority??nothing} data-align=${col.align??"start"}>
172
172
  ${col.footer?.(matchingEntries.map(entry=>entry.row))??""}
173
173
  </td>`)}
174
174
  ${hasRowTotal?html`<td part="footer-cell" data-align="end">