@prismora/elements 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (393) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +21 -2
  3. package/components.json +15600 -0
  4. package/custom-elements.json +56320 -0
  5. package/dist/base.d.ts +42 -0
  6. package/dist/base.js +62 -0
  7. package/dist/catalog.d.ts +33 -0
  8. package/dist/catalog.js +803 -0
  9. package/dist/components/accordion.d.ts +31 -0
  10. package/dist/components/accordion.js +63 -0
  11. package/dist/components/alert.d.ts +27 -0
  12. package/dist/components/alert.js +40 -0
  13. package/dist/components/avatar-group.d.ts +23 -0
  14. package/dist/components/avatar-group.js +43 -0
  15. package/dist/components/avatar.d.ts +24 -0
  16. package/dist/components/avatar.js +43 -0
  17. package/dist/components/back-to-top.d.ts +32 -0
  18. package/dist/components/back-to-top.js +50 -0
  19. package/dist/components/badge.d.ts +17 -0
  20. package/dist/components/badge.js +20 -0
  21. package/dist/components/banner.d.ts +34 -0
  22. package/dist/components/banner.js +54 -0
  23. package/dist/components/breadcrumb.d.ts +42 -0
  24. package/dist/components/breadcrumb.js +63 -0
  25. package/dist/components/button-group.d.ts +14 -0
  26. package/dist/components/button-group.js +28 -0
  27. package/dist/components/button.d.ts +59 -0
  28. package/dist/components/button.js +162 -0
  29. package/dist/components/calendar.d.ts +48 -0
  30. package/dist/components/calendar.js +296 -0
  31. package/dist/components/card.d.ts +23 -0
  32. package/dist/components/card.js +44 -0
  33. package/dist/components/carousel.d.ts +41 -0
  34. package/dist/components/carousel.js +156 -0
  35. package/dist/components/cascader.d.ts +70 -0
  36. package/dist/components/cascader.js +220 -0
  37. package/dist/components/chart.d.ts +59 -0
  38. package/dist/components/chart.js +267 -0
  39. package/dist/components/chat.d.ts +98 -0
  40. package/dist/components/chat.js +134 -0
  41. package/dist/components/checkbox-group.d.ts +48 -0
  42. package/dist/components/checkbox-group.js +111 -0
  43. package/dist/components/checkbox.d.ts +23 -0
  44. package/dist/components/checkbox.js +70 -0
  45. package/dist/components/code-block.d.ts +46 -0
  46. package/dist/components/code-block.js +86 -0
  47. package/dist/components/color-picker.d.ts +46 -0
  48. package/dist/components/color-picker.js +292 -0
  49. package/dist/components/combobox.d.ts +89 -0
  50. package/dist/components/combobox.js +384 -0
  51. package/dist/components/command.d.ts +96 -0
  52. package/dist/components/command.js +289 -0
  53. package/dist/components/context-menu.d.ts +23 -0
  54. package/dist/components/context-menu.js +110 -0
  55. package/dist/components/copy-button.d.ts +33 -0
  56. package/dist/components/copy-button.js +62 -0
  57. package/dist/components/countdown.d.ts +36 -0
  58. package/dist/components/countdown.js +56 -0
  59. package/dist/components/data-table.d.ts +180 -0
  60. package/dist/components/data-table.js +1060 -0
  61. package/dist/components/date-picker.d.ts +47 -0
  62. package/dist/components/date-picker.js +267 -0
  63. package/dist/components/description-list.d.ts +38 -0
  64. package/dist/components/description-list.js +41 -0
  65. package/dist/components/dialog.d.ts +47 -0
  66. package/dist/components/dialog.js +189 -0
  67. package/dist/components/divider.d.ts +16 -0
  68. package/dist/components/divider.js +23 -0
  69. package/dist/components/drawer.d.ts +19 -0
  70. package/dist/components/drawer.js +27 -0
  71. package/dist/components/editor.d.ts +50 -0
  72. package/dist/components/editor.js +474 -0
  73. package/dist/components/empty-state.d.ts +24 -0
  74. package/dist/components/empty-state.js +27 -0
  75. package/dist/components/file-upload.d.ts +56 -0
  76. package/dist/components/file-upload.js +176 -0
  77. package/dist/components/form-control.d.ts +69 -0
  78. package/dist/components/form-control.js +134 -0
  79. package/dist/components/form.d.ts +38 -0
  80. package/dist/components/form.js +161 -0
  81. package/dist/components/format-number.d.ts +37 -0
  82. package/dist/components/format-number.js +86 -0
  83. package/dist/components/icon.d.ts +34 -0
  84. package/dist/components/icon.js +47 -0
  85. package/dist/components/image.d.ts +44 -0
  86. package/dist/components/image.js +53 -0
  87. package/dist/components/indicator.d.ts +41 -0
  88. package/dist/components/indicator.js +65 -0
  89. package/dist/components/inline-edit.d.ts +45 -0
  90. package/dist/components/inline-edit.js +129 -0
  91. package/dist/components/input.d.ts +55 -0
  92. package/dist/components/input.js +186 -0
  93. package/dist/components/kbd.d.ts +15 -0
  94. package/dist/components/kbd.js +18 -0
  95. package/dist/components/list.d.ts +68 -0
  96. package/dist/components/list.js +180 -0
  97. package/dist/components/menu.d.ts +22 -0
  98. package/dist/components/menu.js +182 -0
  99. package/dist/components/menubar.d.ts +20 -0
  100. package/dist/components/menubar.js +120 -0
  101. package/dist/components/meter.d.ts +38 -0
  102. package/dist/components/meter.js +48 -0
  103. package/dist/components/nav.d.ts +91 -0
  104. package/dist/components/nav.js +228 -0
  105. package/dist/components/number-input.d.ts +26 -0
  106. package/dist/components/number-input.js +70 -0
  107. package/dist/components/pagination.d.ts +44 -0
  108. package/dist/components/pagination.js +94 -0
  109. package/dist/components/pin-input.d.ts +25 -0
  110. package/dist/components/pin-input.js +128 -0
  111. package/dist/components/popover.d.ts +23 -0
  112. package/dist/components/popover.js +140 -0
  113. package/dist/components/progress.d.ts +26 -0
  114. package/dist/components/progress.js +66 -0
  115. package/dist/components/pull-refresh.d.ts +41 -0
  116. package/dist/components/pull-refresh.js +101 -0
  117. package/dist/components/qr-code.d.ts +33 -0
  118. package/dist/components/qr-code.js +54 -0
  119. package/dist/components/radio-group.d.ts +37 -0
  120. package/dist/components/radio-group.js +82 -0
  121. package/dist/components/range-slider.d.ts +46 -0
  122. package/dist/components/range-slider.js +95 -0
  123. package/dist/components/rating.d.ts +38 -0
  124. package/dist/components/rating.js +80 -0
  125. package/dist/components/relative-time.d.ts +31 -0
  126. package/dist/components/relative-time.js +51 -0
  127. package/dist/components/scheduler.d.ts +84 -0
  128. package/dist/components/scheduler.js +187 -0
  129. package/dist/components/segmented.d.ts +58 -0
  130. package/dist/components/segmented.js +129 -0
  131. package/dist/components/select.d.ts +62 -0
  132. package/dist/components/select.js +140 -0
  133. package/dist/components/share-button.d.ts +37 -0
  134. package/dist/components/share-button.js +60 -0
  135. package/dist/components/signature.d.ts +54 -0
  136. package/dist/components/signature.js +152 -0
  137. package/dist/components/skeleton.d.ts +21 -0
  138. package/dist/components/skeleton.js +26 -0
  139. package/dist/components/slider.d.ts +31 -0
  140. package/dist/components/slider.js +80 -0
  141. package/dist/components/sortable.d.ts +22 -0
  142. package/dist/components/sortable.js +196 -0
  143. package/dist/components/sparkline.d.ts +28 -0
  144. package/dist/components/sparkline.js +46 -0
  145. package/dist/components/spinner.d.ts +16 -0
  146. package/dist/components/spinner.js +22 -0
  147. package/dist/components/splitter.d.ts +28 -0
  148. package/dist/components/splitter.js +89 -0
  149. package/dist/components/stat.d.ts +28 -0
  150. package/dist/components/stat.js +33 -0
  151. package/dist/components/steps.d.ts +53 -0
  152. package/dist/components/steps.js +91 -0
  153. package/dist/components/switch.d.ts +12 -0
  154. package/dist/components/switch.js +18 -0
  155. package/dist/components/table.d.ts +58 -0
  156. package/dist/components/table.js +96 -0
  157. package/dist/components/tabs.d.ts +62 -0
  158. package/dist/components/tabs.js +310 -0
  159. package/dist/components/tag.d.ts +32 -0
  160. package/dist/components/tag.js +58 -0
  161. package/dist/components/textarea.d.ts +25 -0
  162. package/dist/components/textarea.js +56 -0
  163. package/dist/components/theme-switch.d.ts +51 -0
  164. package/dist/components/theme-switch.js +85 -0
  165. package/dist/components/time-picker.d.ts +39 -0
  166. package/dist/components/time-picker.js +257 -0
  167. package/dist/components/timeline.d.ts +38 -0
  168. package/dist/components/timeline.js +56 -0
  169. package/dist/components/toaster.d.ts +25 -0
  170. package/dist/components/toaster.js +44 -0
  171. package/dist/components/toggle-group.d.ts +70 -0
  172. package/dist/components/toggle-group.js +172 -0
  173. package/dist/components/toolbar.d.ts +23 -0
  174. package/dist/components/toolbar.js +81 -0
  175. package/dist/components/tooltip.d.ts +18 -0
  176. package/dist/components/tooltip.js +92 -0
  177. package/dist/components/tour.d.ts +41 -0
  178. package/dist/components/tour.js +197 -0
  179. package/dist/components/transfer.d.ts +57 -0
  180. package/dist/components/transfer.js +161 -0
  181. package/dist/components/tree-select.d.ts +66 -0
  182. package/dist/components/tree-select.js +282 -0
  183. package/dist/components/tree.d.ts +129 -0
  184. package/dist/components/tree.js +427 -0
  185. package/dist/components/virtual-list.d.ts +41 -0
  186. package/dist/components/virtual-list.js +77 -0
  187. package/dist/confirm.d.ts +21 -0
  188. package/dist/confirm.js +69 -0
  189. package/dist/count.d.ts +5 -0
  190. package/dist/count.js +12 -0
  191. package/dist/data-table/icons.d.ts +8 -0
  192. package/dist/data-table/icons.js +10 -0
  193. package/dist/data-table/logic.d.ts +33 -0
  194. package/dist/data-table/logic.js +141 -0
  195. package/dist/data-table/strings.d.ts +37 -0
  196. package/dist/data-table/strings.js +36 -0
  197. package/dist/data-table/types.d.ts +76 -0
  198. package/dist/data-table/types.js +1 -0
  199. package/dist/define.d.ts +2 -0
  200. package/dist/define.js +2 -0
  201. package/dist/field-validity.d.ts +42 -0
  202. package/dist/field-validity.js +58 -0
  203. package/dist/floating.d.ts +13 -0
  204. package/dist/floating.js +65 -0
  205. package/dist/highlight.d.ts +11 -0
  206. package/dist/highlight.js +103 -0
  207. package/dist/id.d.ts +2 -0
  208. package/dist/id.js +3 -0
  209. package/dist/index.d.ts +102 -0
  210. package/dist/index.js +102 -0
  211. package/dist/manifest.d.ts +51 -0
  212. package/dist/manifest.js +11 -0
  213. package/dist/named-icon.d.ts +8 -0
  214. package/dist/named-icon.js +8 -0
  215. package/dist/patterns/account.d.ts +6 -0
  216. package/dist/patterns/account.js +137 -0
  217. package/dist/patterns/app.d.ts +7 -0
  218. package/dist/patterns/app.js +351 -0
  219. package/dist/patterns/commerce.d.ts +4 -0
  220. package/dist/patterns/commerce.js +200 -0
  221. package/dist/patterns/flows.d.ts +3 -0
  222. package/dist/patterns/flows.js +100 -0
  223. package/dist/patterns/index.d.ts +9 -0
  224. package/dist/patterns/index.js +29 -0
  225. package/dist/patterns/marketing.d.ts +4 -0
  226. package/dist/patterns/marketing.js +173 -0
  227. package/dist/patterns/more.d.ts +15 -0
  228. package/dist/patterns/more.js +581 -0
  229. package/dist/patterns/shell.d.ts +9 -0
  230. package/dist/patterns/shell.js +48 -0
  231. package/dist/patterns/types.d.ts +19 -0
  232. package/dist/patterns/types.js +1 -0
  233. package/dist/position.d.ts +2 -0
  234. package/dist/position.js +33 -0
  235. package/dist/prismora.standalone.js +5222 -0
  236. package/dist/prismora.standalone.js.map +199 -0
  237. package/dist/qr.d.ts +14 -0
  238. package/dist/qr.js +258 -0
  239. package/dist/register.d.ts +8 -0
  240. package/dist/register.js +21 -0
  241. package/dist/registry.d.ts +203 -0
  242. package/dist/registry.js +203 -0
  243. package/dist/remote.d.ts +58 -0
  244. package/dist/remote.js +130 -0
  245. package/dist/sheet.d.ts +34 -0
  246. package/dist/sheet.js +153 -0
  247. package/dist/styles/accordion.d.ts +2 -0
  248. package/dist/styles/accordion.js +3 -0
  249. package/dist/styles/alert.d.ts +2 -0
  250. package/dist/styles/alert.js +3 -0
  251. package/dist/styles/avatar.d.ts +2 -0
  252. package/dist/styles/avatar.js +3 -0
  253. package/dist/styles/badge.d.ts +2 -0
  254. package/dist/styles/badge.js +3 -0
  255. package/dist/styles/banner.d.ts +2 -0
  256. package/dist/styles/banner.js +3 -0
  257. package/dist/styles/breadcrumb.d.ts +2 -0
  258. package/dist/styles/breadcrumb.js +3 -0
  259. package/dist/styles/button.d.ts +2 -0
  260. package/dist/styles/button.js +3 -0
  261. package/dist/styles/calendar.d.ts +2 -0
  262. package/dist/styles/calendar.js +3 -0
  263. package/dist/styles/card.d.ts +2 -0
  264. package/dist/styles/card.js +3 -0
  265. package/dist/styles/carousel.d.ts +2 -0
  266. package/dist/styles/carousel.js +3 -0
  267. package/dist/styles/chart.d.ts +2 -0
  268. package/dist/styles/chart.js +3 -0
  269. package/dist/styles/chat.d.ts +2 -0
  270. package/dist/styles/chat.js +3 -0
  271. package/dist/styles/checkbox.d.ts +2 -0
  272. package/dist/styles/checkbox.js +3 -0
  273. package/dist/styles/color-picker.d.ts +2 -0
  274. package/dist/styles/color-picker.js +3 -0
  275. package/dist/styles/combobox.d.ts +2 -0
  276. package/dist/styles/combobox.js +3 -0
  277. package/dist/styles/command.d.ts +2 -0
  278. package/dist/styles/command.js +3 -0
  279. package/dist/styles/data-table.d.ts +2 -0
  280. package/dist/styles/data-table.js +3 -0
  281. package/dist/styles/description-list.d.ts +2 -0
  282. package/dist/styles/description-list.js +3 -0
  283. package/dist/styles/dialog.d.ts +2 -0
  284. package/dist/styles/dialog.js +3 -0
  285. package/dist/styles/drawer.d.ts +2 -0
  286. package/dist/styles/drawer.js +3 -0
  287. package/dist/styles/editor.d.ts +2 -0
  288. package/dist/styles/editor.js +3 -0
  289. package/dist/styles/empty-state.d.ts +2 -0
  290. package/dist/styles/empty-state.js +3 -0
  291. package/dist/styles/extras.d.ts +2 -0
  292. package/dist/styles/extras.js +3 -0
  293. package/dist/styles/field.d.ts +2 -0
  294. package/dist/styles/field.js +3 -0
  295. package/dist/styles/file-upload.d.ts +2 -0
  296. package/dist/styles/file-upload.js +3 -0
  297. package/dist/styles/foundation.d.ts +2 -0
  298. package/dist/styles/foundation.js +3 -0
  299. package/dist/styles/helpers.d.ts +2 -0
  300. package/dist/styles/helpers.js +3 -0
  301. package/dist/styles/icon.d.ts +2 -0
  302. package/dist/styles/icon.js +3 -0
  303. package/dist/styles/image.d.ts +2 -0
  304. package/dist/styles/image.js +3 -0
  305. package/dist/styles/indicator.d.ts +2 -0
  306. package/dist/styles/indicator.js +3 -0
  307. package/dist/styles/input.d.ts +2 -0
  308. package/dist/styles/input.js +3 -0
  309. package/dist/styles/kbd.d.ts +2 -0
  310. package/dist/styles/kbd.js +3 -0
  311. package/dist/styles/list.d.ts +2 -0
  312. package/dist/styles/list.js +3 -0
  313. package/dist/styles/listbox.d.ts +2 -0
  314. package/dist/styles/listbox.js +3 -0
  315. package/dist/styles/meter.d.ts +2 -0
  316. package/dist/styles/meter.js +3 -0
  317. package/dist/styles/nav.d.ts +2 -0
  318. package/dist/styles/nav.js +3 -0
  319. package/dist/styles/number-input.d.ts +2 -0
  320. package/dist/styles/number-input.js +3 -0
  321. package/dist/styles/overlay.d.ts +2 -0
  322. package/dist/styles/overlay.js +3 -0
  323. package/dist/styles/pagination.d.ts +2 -0
  324. package/dist/styles/pagination.js +3 -0
  325. package/dist/styles/pickers.d.ts +2 -0
  326. package/dist/styles/pickers.js +3 -0
  327. package/dist/styles/pin-input.d.ts +2 -0
  328. package/dist/styles/pin-input.js +3 -0
  329. package/dist/styles/popover.d.ts +2 -0
  330. package/dist/styles/popover.js +3 -0
  331. package/dist/styles/progress.d.ts +2 -0
  332. package/dist/styles/progress.js +3 -0
  333. package/dist/styles/pull-refresh.d.ts +2 -0
  334. package/dist/styles/pull-refresh.js +3 -0
  335. package/dist/styles/range-slider.d.ts +2 -0
  336. package/dist/styles/range-slider.js +3 -0
  337. package/dist/styles/rating.d.ts +2 -0
  338. package/dist/styles/rating.js +3 -0
  339. package/dist/styles/scheduler.d.ts +2 -0
  340. package/dist/styles/scheduler.js +3 -0
  341. package/dist/styles/segmented.d.ts +2 -0
  342. package/dist/styles/segmented.js +3 -0
  343. package/dist/styles/select.d.ts +2 -0
  344. package/dist/styles/select.js +3 -0
  345. package/dist/styles/separator.d.ts +2 -0
  346. package/dist/styles/separator.js +3 -0
  347. package/dist/styles/sheet.d.ts +2 -0
  348. package/dist/styles/sheet.js +3 -0
  349. package/dist/styles/skeleton.d.ts +2 -0
  350. package/dist/styles/skeleton.js +3 -0
  351. package/dist/styles/slider.d.ts +2 -0
  352. package/dist/styles/slider.js +3 -0
  353. package/dist/styles/sortable.d.ts +2 -0
  354. package/dist/styles/sortable.js +3 -0
  355. package/dist/styles/spinner.d.ts +2 -0
  356. package/dist/styles/spinner.js +3 -0
  357. package/dist/styles/splitter.d.ts +2 -0
  358. package/dist/styles/splitter.js +3 -0
  359. package/dist/styles/stat.d.ts +2 -0
  360. package/dist/styles/stat.js +3 -0
  361. package/dist/styles/steps.d.ts +2 -0
  362. package/dist/styles/steps.js +3 -0
  363. package/dist/styles/surface.d.ts +2 -0
  364. package/dist/styles/surface.js +3 -0
  365. package/dist/styles/switch.d.ts +2 -0
  366. package/dist/styles/switch.js +3 -0
  367. package/dist/styles/table.d.ts +2 -0
  368. package/dist/styles/table.js +3 -0
  369. package/dist/styles/tabs.d.ts +2 -0
  370. package/dist/styles/tabs.js +3 -0
  371. package/dist/styles/tag.d.ts +2 -0
  372. package/dist/styles/tag.js +3 -0
  373. package/dist/styles/time-picker.d.ts +2 -0
  374. package/dist/styles/time-picker.js +3 -0
  375. package/dist/styles/timeline.d.ts +2 -0
  376. package/dist/styles/timeline.js +3 -0
  377. package/dist/styles/toast.d.ts +2 -0
  378. package/dist/styles/toast.js +3 -0
  379. package/dist/styles/toggle.d.ts +2 -0
  380. package/dist/styles/toggle.js +3 -0
  381. package/dist/styles/toolbar.d.ts +2 -0
  382. package/dist/styles/toolbar.js +3 -0
  383. package/dist/styles/tooltip.d.ts +2 -0
  384. package/dist/styles/tooltip.js +3 -0
  385. package/dist/styles/tree.d.ts +2 -0
  386. package/dist/styles/tree.js +3 -0
  387. package/dist/table-core.d.ts +75 -0
  388. package/dist/table-core.js +205 -0
  389. package/dist/toast.d.ts +42 -0
  390. package/dist/toast.js +206 -0
  391. package/dist/top-layer.d.ts +4 -0
  392. package/dist/top-layer.js +33 -0
  393. package/package.json +101 -4
@@ -0,0 +1,1060 @@
1
+ import { css, html, nothing } from 'lit';
2
+ import { PmElement, defineElement } from '../base.js';
3
+ import checkboxCss from '../styles/checkbox.js';
4
+ import dataTableCss from '../styles/data-table.js';
5
+ import skeletonCss from '../styles/skeleton.js';
6
+ import tableCss from '../styles/table.js';
7
+ import badgeCss from '../styles/badge.js';
8
+ import { SORT_ICON, alignOf, cellClassOf, cellContent, compare, nameCustomHeaders, watchTemplates, formatValue, headerContent, isNumeric, noWrap, parseArray, sortRows, } from '../table-core.js';
9
+ import { ICON } from '../data-table/icons.js';
10
+ import { aggregateValue, groupItems, matchNumber, mergeSpans, queryParams, toCsv } from '../data-table/logic.js';
11
+ import { RemoteRequest, buildUrl, fetchJson, pick } from '../remote.js';
12
+ import { DATA_TABLE_STRINGS, fillString } from '../data-table/strings.js';
13
+ import './pagination.js';
14
+ export { DATA_TABLE_STRINGS };
15
+ const FOCUSABLE = 'a[href], button:not([disabled]), input:not([disabled]), select, textarea, [tabindex]:not([tabindex="-1"])';
16
+ /**
17
+ * Advanced data table for business apps: search, filters, sorting, frozen columns, selection, grouping, editing
18
+ * and export.
19
+ *
20
+ * Everything is optional and driven by column definitions:
21
+ * - **Find**: global search box (`searchable`), per-column filters (text, select, number ranges), multi-column sort
22
+ * (Shift+click adds a sort level).
23
+ * - **Columns**: freeze (`pin: 'start' | 'end'`), resize (drag or keyboard), reorder (drag headers or the column
24
+ * menu), show/hide (`column-picker`), header groups (`group`), and a per-column actions menu.
25
+ * - **Rows**: single or multi selection (Shift+click for ranges, "select all N" across pages), pinned rows that stay
26
+ * on top (`pinned-rows`), expandable detail rows (`expandable` + `renderDetail`), grouping with counts
27
+ * (`group-by`), merged cells (`merge` → rowspan, `colSpan` → colspan), inline editing.
28
+ * - **Data**: client-side paging or `manual` for server-side (events carry the full query), footer aggregates
29
+ * (sum/avg/min/max/count), Intl formatting by `type`, CSV export (`exportable` / `toCsv()`), infinite loading
30
+ * (`pm-end-reached`), saved views (`state`, `persist`).
31
+ * - **Use**: spreadsheet-style keyboard grid (arrows, Home/End, PageUp/Down, Enter/F2 to edit, Space to select),
32
+ * sticky header and footer, loading bar, labelled cards in narrow containers, every UI string replaceable.
33
+ * - **Content**: per column `render(row)` (text, DOM node or Lit template), light-DOM `<template data-cell="key">`
34
+ * with escaped `{{field}}` placeholders, `format(value, row)`, or Intl formatting by `type` (number, currency,
35
+ * percent, bytes, date, datetime, time, boolean) with `formatOptions` and `prefix`/`suffix`. Headers the same way:
36
+ * `renderHeader(col)` or `<template data-header="key">`; `label` stays the accessible and CSV name.
37
+ *
38
+ * Server-side data: set `src` to a URL (`src="/api/orders"`; the query goes in as `q`, `page`, `pageSize`, `sort`,
39
+ * `order`, `sorts` and `filter[key]` parameters, or as `{placeholders}` in the URL) and say where the rows and the
40
+ * total are in the JSON (`rows-path="data"`, `total-path="meta.total"`), or set the `loader` property to your own
41
+ * `async (query, { signal }) => ({ rows, total })`. `mapRow` formats each server row. Searching, sorting, filtering
42
+ * and paging then reload from the server (search debounced by `debounce`), superseded requests are cancelled, and
43
+ * loading and error (with Retry) states show. `reload()` fetches the current page again.
44
+ *
45
+ * Columns and rows can be properties or JSON attributes (`columns='[{"key":"name","label":"Name","sortable":true}]'`).
46
+ * For a light table without these features use `<pm-table>`.
47
+ * @tag pm-data-table
48
+ * @slot empty - Content when there are no rows.
49
+ * @slot toolbar - Extra content in the toolbar (filters, bulk actions).
50
+ * @fires pm-sort - detail: { key, direction, sorts }
51
+ * @fires pm-filter - Search or column filters changed. detail: { filter, filters }
52
+ * @fires pm-selection-change - detail: { keys, rows }
53
+ * @fires pm-page - detail: { page, pageSize }
54
+ * @fires pm-row-click - detail: { row, key }
55
+ * @fires pm-expand - detail: { row, key, expanded }
56
+ * @fires pm-cell-edit - Cancelable (call preventDefault to reject). detail: { row, key, value, previous }
57
+ * @fires pm-state-change - Column layout, sort or filters changed. detail: DataTableState
58
+ * @fires pm-load - Server rows arrived. detail: { query, rows, total }
59
+ * @fires pm-load-error - A server request failed. detail: { query, error }
60
+ * @fires pm-end-reached - Scrolled near the bottom (load more rows). detail: { rows }
61
+ * @example <pm-data-table label="Invoices" page-size="10" selectable searchable column-picker exportable></pm-data-table>
62
+ */
63
+ export class PmDataTable extends PmElement {
64
+ static { this.componentName = 'data-table'; }
65
+ static { this.styles = [...PmElement.styles, tableCss, badgeCss, checkboxCss, skeletonCss, dataTableCss, css `/* Tables fill their container: the card layout uses a size container, which has no natural width of its own. */
66
+ :host { display: block; inline-size: 100%; min-inline-size: 0; } :host([hidden]) { display: none; }
67
+ tr[data-clickable] { cursor: pointer; } .count { font-variant-numeric: tabular-nums; }`]; }
68
+ static { this.properties = {
69
+ columns: { type: Array }, rows: { type: Array }, label: {}, rowKey: { attribute: 'row-key' }, stack: {},
70
+ selectable: { type: Boolean }, selection: {}, selected: { attribute: false }, sorts: { attribute: false }, filter: {}, filters: { attribute: false },
71
+ pageSize: { type: Number, attribute: 'page-size' }, page: { type: Number, reflect: true }, total: { type: Number },
72
+ manual: { type: Boolean }, loading: { type: Boolean, reflect: true }, striped: { type: Boolean }, emptyText: { attribute: 'empty-text' },
73
+ rowClickable: { type: Boolean, attribute: 'row-clickable' }, searchable: { type: Boolean }, columnPicker: { type: Boolean, attribute: 'column-picker' },
74
+ exportable: { type: Boolean }, columnMenu: { attribute: 'column-menu', converter: { fromAttribute: (v) => v !== 'false' && v !== 'off' } },
75
+ groupBy: { attribute: 'group-by' }, expandable: { type: Boolean }, renderDetail: { attribute: false }, pinnedRows: { type: Array, attribute: 'pinned-rows' },
76
+ locale: {}, maxHeight: { attribute: 'max-height' }, persist: {}, strings: { attribute: false }, pageSizes: { type: Array, attribute: 'page-sizes' },
77
+ src: {}, loader: { attribute: false }, mapRow: { attribute: false }, rowsPath: { attribute: 'rows-path' }, totalPath: { attribute: 'total-path' },
78
+ debounce: { type: Number },
79
+ }; }
80
+ #index = new WeakMap();
81
+ #remote = new RemoteRequest(this, {
82
+ debounce: () => this.debounce,
83
+ run: async (query, ctx) => {
84
+ const data = this.loader ? await this.loader(query, ctx) : await fetchJson(buildUrl(this.src, queryParams(query), true), ctx.signal);
85
+ const list = this.rowsPath ? pick(data, this.rowsPath) : Array.isArray(data) ? data : pick(data, 'rows') ?? pick(data, 'data') ?? pick(data, 'items');
86
+ if (!Array.isArray(list))
87
+ throw new Error(`Expected rows${this.rowsPath ? ` at "${this.rowsPath}"` : ''} in the server response`);
88
+ const total = Number(this.totalPath ? pick(data, this.totalPath) : Array.isArray(data) ? undefined : pick(data, 'total') ?? pick(data, 'count'));
89
+ return { rows: list.map((item) => (this.mapRow ? this.mapRow(item) : item)), total: Number.isFinite(total) ? total : undefined };
90
+ },
91
+ done: ({ rows, total }, query) => {
92
+ this.rows = rows;
93
+ this.total = total;
94
+ this.emit('pm-load', { query, rows, total });
95
+ },
96
+ failed: (error, query) => this.emit('pm-load-error', { query, error }),
97
+ });
98
+ #remoteLoaded = false;
99
+ get #isRemote() { return !!(this.loader || this.src); }
100
+ get #busy() { return this.loading || this.#remote.pending; }
101
+ /** The current server query (page, search, column filters, sorts). */
102
+ get query() {
103
+ return { page: this.page, pageSize: this.pageSize, filter: this.filter ?? '', filters: { ...this.filters }, sorts: [...this.sorts] };
104
+ }
105
+ /** Fetch the current page from the server again (with `src` / `loader`). */
106
+ reload() { if (this.#isRemote)
107
+ this.#remote.request(this.query, true); }
108
+ #order;
109
+ #vis = new Map();
110
+ #pins = new Map();
111
+ #widths = new Map();
112
+ #collapsed = new Set();
113
+ #expanded = new Set();
114
+ #anchor;
115
+ #editing;
116
+ #menuCol;
117
+ #dragCol;
118
+ #resizing = false;
119
+ #endAt = -1;
120
+ #startKeys = [];
121
+ #endKeys = [];
122
+ #ro;
123
+ #focusAfter;
124
+ constructor() {
125
+ super();
126
+ this.columns = [];
127
+ this.rows = [];
128
+ this.rowKey = 'id';
129
+ this.selectable = false;
130
+ this.selected = new Set();
131
+ this.sorts = [];
132
+ this.filters = {};
133
+ this.pageSize = 0;
134
+ this.page = 1;
135
+ this.manual = false;
136
+ this.loading = false;
137
+ this.debounce = 300;
138
+ this.striped = false;
139
+ this.rowClickable = false;
140
+ this.searchable = false;
141
+ this.columnPicker = false;
142
+ this.exportable = false;
143
+ this.columnMenu = true;
144
+ this.expandable = false;
145
+ this.pinnedRows = [];
146
+ this.strings = {};
147
+ }
148
+ /** First sort level (kept for single-sort code). */
149
+ get sort() { return this.sorts[0]; }
150
+ set sort(v) { this.sorts = v ? [v] : []; }
151
+ #t(k, v = {}) {
152
+ const base = k === 'empty' ? this.emptyText ?? this.strings.empty ?? DATA_TABLE_STRINGS.empty : this.strings[k] ?? DATA_TABLE_STRINGS[k];
153
+ return fillString(base, v);
154
+ }
155
+ #key(row) {
156
+ const k = row[this.rowKey];
157
+ return k == null ? String(this.#index.get(row) ?? this.rows.indexOf(row)) : String(k);
158
+ }
159
+ #pinOf(c) { const p = this.#pins.get(c.key); return p === undefined ? c.pin : p ?? undefined; }
160
+ #hidden(c) { return this.#vis.has(c.key) ? !this.#vis.get(c.key) : !!c.hidden; }
161
+ /** Visible columns in display order (start-pinned, then free, then end-pinned). */
162
+ get visibleColumns() {
163
+ const by = new Map(this.columns.map((c) => [c.key, c]));
164
+ const order = (this.#order ?? []).filter((k) => by.has(k));
165
+ for (const c of this.columns)
166
+ if (!order.includes(c.key))
167
+ order.push(c.key);
168
+ const list = order.map((k) => by.get(k)).filter((c) => !this.#hidden(c));
169
+ return [...list.filter((c) => this.#pinOf(c) === 'start'), ...list.filter((c) => !this.#pinOf(c)), ...list.filter((c) => this.#pinOf(c) === 'end')];
170
+ }
171
+ #text(c, r) {
172
+ const v = r[c.key];
173
+ const f = formatValue(v, c, r, this.locale);
174
+ return v == null ? '' : `${String(v)} ${typeof f === 'string' || typeof f === 'number' ? f : ''}`;
175
+ }
176
+ #match(c, r, q) {
177
+ if (c.filterFn)
178
+ return c.filterFn(r, q);
179
+ const v = r[c.key];
180
+ if (c.filter === 'select')
181
+ return String(v ?? '') === q;
182
+ if (c.filter === 'number' || isNumeric(c))
183
+ return matchNumber(v, q);
184
+ return this.#text(c, r).toLowerCase().includes(q.toLowerCase());
185
+ }
186
+ /** Filtered and sorted rows (all pages; grouping order applied). */
187
+ get processedRows() {
188
+ if (this.manual)
189
+ return this.rows;
190
+ let out = this.rows;
191
+ const q = this.filter?.trim().toLowerCase();
192
+ if (q) {
193
+ const cols = this.columns.filter((c) => !this.#hidden(c));
194
+ out = out.filter((r) => cols.some((c) => this.#text(c, r).toLowerCase().includes(q)));
195
+ }
196
+ for (const [k, v] of Object.entries(this.filters)) {
197
+ const c = this.columns.find((x) => x.key === k);
198
+ if (c && v?.trim())
199
+ out = out.filter((r) => this.#match(c, r, v.trim()));
200
+ }
201
+ const g = this.groupBy;
202
+ return sortRows(out, this.sorts, this.columns, g ? (a, b) => compare(a[g], b[g]) : undefined);
203
+ }
204
+ #items(rows) { return groupItems(rows, this.groupBy, this.#collapsed); }
205
+ get #pageCount() {
206
+ const n = this.manual ? (this.total ?? this.rows.length) : this.#items(this.#mainRows(this.processedRows)).length;
207
+ return this.pageSize ? Math.max(1, Math.ceil(n / this.pageSize)) : 1;
208
+ }
209
+ #mainRows(rows) {
210
+ if (!this.pinnedRows.length || this.manual)
211
+ return rows;
212
+ const pin = new Set(this.pinnedRows.map(String));
213
+ return rows.filter((r) => !pin.has(this.#key(r)));
214
+ }
215
+ /* ---------------- State ---------------- */
216
+ /** The user's current view; assign a saved one to restore it. */
217
+ get state() {
218
+ return {
219
+ sorts: this.sorts.map((s) => ({ ...s })), filters: { ...this.filters }, filter: this.filter ?? '',
220
+ hidden: this.columns.filter((c) => this.#hidden(c)).map((c) => c.key),
221
+ pins: Object.fromEntries(this.#pins), widths: Object.fromEntries(this.#widths),
222
+ order: this.#order ? [...this.#order] : this.columns.map((c) => c.key), groupBy: this.groupBy, pageSize: this.pageSize,
223
+ };
224
+ }
225
+ set state(s) {
226
+ if (s.sorts)
227
+ this.sorts = s.sorts;
228
+ if (s.filters)
229
+ this.filters = s.filters;
230
+ if (s.filter !== undefined)
231
+ this.filter = s.filter;
232
+ if (s.hidden) {
233
+ this.#vis.clear();
234
+ for (const c of this.columns)
235
+ this.#vis.set(c.key, !s.hidden.includes(c.key));
236
+ for (const k of s.hidden)
237
+ this.#vis.set(k, false);
238
+ }
239
+ if (s.pins)
240
+ this.#pins = new Map(Object.entries(s.pins));
241
+ if (s.widths)
242
+ this.#widths = new Map(Object.entries(s.widths));
243
+ if (s.order)
244
+ this.#order = [...s.order];
245
+ if ('groupBy' in s)
246
+ this.groupBy = s.groupBy;
247
+ if (s.pageSize !== undefined)
248
+ this.pageSize = s.pageSize;
249
+ this.requestUpdate();
250
+ }
251
+ /** Back to the column definitions (order, visibility, pins and widths). */
252
+ resetColumns() {
253
+ this.#order = undefined;
254
+ this.#vis.clear();
255
+ this.#pins.clear();
256
+ this.#widths.clear();
257
+ this.#changed();
258
+ }
259
+ #changed() {
260
+ this.requestUpdate();
261
+ const s = this.state;
262
+ if (this.persist) {
263
+ try {
264
+ localStorage.setItem(`pm-data-table:${this.persist}`, JSON.stringify(s));
265
+ }
266
+ catch { /* storage full or blocked */ }
267
+ }
268
+ this.emit('pm-state-change', s);
269
+ }
270
+ #tplObserver;
271
+ connectedCallback() {
272
+ super.connectedCallback();
273
+ this.#tplObserver ??= watchTemplates(this);
274
+ if (this.persist) {
275
+ try {
276
+ const raw = localStorage.getItem(`pm-data-table:${this.persist}`);
277
+ if (raw)
278
+ this.state = JSON.parse(raw);
279
+ }
280
+ catch { /* ignore */ }
281
+ }
282
+ }
283
+ disconnectedCallback() { super.disconnectedCallback(); this.#ro?.disconnect(); this.#ro = undefined; this.#tplObserver?.disconnect(); this.#tplObserver = undefined; }
284
+ willUpdate(changed) {
285
+ if (this.#isRemote)
286
+ this.manual = true;
287
+ if (!Array.isArray(this.columns))
288
+ this.columns = parseArray(this.columns);
289
+ if (!Array.isArray(this.rows))
290
+ this.rows = parseArray(this.rows);
291
+ if (!Array.isArray(this.pinnedRows))
292
+ this.pinnedRows = parseArray(this.pinnedRows);
293
+ if (changed.has('rows')) {
294
+ this.#index = new WeakMap();
295
+ this.rows.forEach((r, i) => this.#index.set(r, i));
296
+ }
297
+ if ((changed.has('filter') && changed.get('filter') !== undefined) || changed.has('filters') || changed.has('groupBy')) {
298
+ if (this.hasUpdated)
299
+ this.page = 1;
300
+ }
301
+ if (this.page > this.#pageCount)
302
+ this.page = this.#pageCount;
303
+ if (this.page < 1)
304
+ this.page = 1;
305
+ }
306
+ /* ---------------- Sorting, filtering, paging ---------------- */
307
+ #toggleSort(c, add, force) {
308
+ const cur = this.sorts.find((s) => s.key === c.key)?.direction;
309
+ const next = force !== undefined ? force ?? undefined : cur === 'asc' ? 'desc' : cur === 'desc' ? undefined : 'asc';
310
+ const sorts = add ? this.sorts.filter((s) => s.key !== c.key) : [];
311
+ if (next) {
312
+ const i = add ? this.sorts.findIndex((s) => s.key === c.key) : -1;
313
+ if (i >= 0)
314
+ sorts.splice(i, 0, { key: c.key, direction: next });
315
+ else
316
+ sorts.push({ key: c.key, direction: next });
317
+ }
318
+ this.sorts = sorts;
319
+ this.page = 1;
320
+ this.emit('pm-sort', { key: c.key, direction: next, sorts });
321
+ this.#changed();
322
+ }
323
+ #setFilter(key, value) {
324
+ if (key === null)
325
+ this.filter = value;
326
+ else
327
+ this.filters = { ...this.filters, [key]: value };
328
+ this.page = 1;
329
+ this.emit('pm-filter', { filter: this.filter ?? '', filters: this.filters });
330
+ this.#changed();
331
+ }
332
+ #goTo(page) { this.page = page; this.emit('pm-page', { page, pageSize: this.pageSize }); }
333
+ /* ---------------- Selection ---------------- */
334
+ #setSelected(next) {
335
+ this.selected = next;
336
+ this.emit('pm-selection-change', { keys: [...next], rows: this.rows.filter((r) => next.has(this.#key(r))) });
337
+ }
338
+ #onSelect(k, i, keys, e) {
339
+ if (this.selection === 'single') {
340
+ this.#setSelected(new Set([k]));
341
+ this.#anchor = i;
342
+ return;
343
+ }
344
+ const on = !this.selected.has(k);
345
+ const n = new Set(this.selected);
346
+ if (e.shiftKey && this.#anchor !== undefined) {
347
+ const [a, b] = [Math.min(this.#anchor, i), Math.max(this.#anchor, i)];
348
+ for (let j = a; j <= b; j++)
349
+ on ? n.add(keys[j]) : n.delete(keys[j]);
350
+ }
351
+ else
352
+ on ? n.add(k) : n.delete(k);
353
+ this.#anchor = i;
354
+ this.#setSelected(n);
355
+ }
356
+ /** Select every row that matches the current search and filters (all pages). */
357
+ selectAllMatching() { this.#setSelected(new Set(this.processedRows.map((r) => this.#key(r)))); }
358
+ clearSelection() { this.#setSelected(new Set()); }
359
+ /* ---------------- Columns ---------------- */
360
+ #fullOrder() { const o = (this.#order ?? []).filter((k) => this.columns.some((c) => c.key === k)); for (const c of this.columns)
361
+ if (!o.includes(c.key))
362
+ o.push(c.key); return o; }
363
+ /** Move a column before (or after) another one. */
364
+ moveColumn(key, to, after = false) {
365
+ if (key === to)
366
+ return;
367
+ const o = this.#fullOrder().filter((k) => k !== key);
368
+ o.splice(o.indexOf(to) + (after ? 1 : 0), 0, key);
369
+ this.#order = o;
370
+ const target = this.columns.find((c) => c.key === to);
371
+ const src = this.columns.find((c) => c.key === key);
372
+ if (target && src && this.#pinOf(target) !== this.#pinOf(src))
373
+ this.#pins.set(key, this.#pinOf(target) ?? null);
374
+ this.#changed();
375
+ }
376
+ #shift(c, dir) {
377
+ const vis = this.visibleColumns;
378
+ const i = vis.indexOf(c);
379
+ const other = vis[i + dir];
380
+ if (other && this.#pinOf(other) === this.#pinOf(c))
381
+ this.moveColumn(c.key, other.key, dir > 0);
382
+ }
383
+ /** Freeze a column at an edge (`null` unpins). */
384
+ pinColumn(key, side) { this.#pins.set(key, side); this.#changed(); }
385
+ /** Show or hide a column. */
386
+ setColumnVisible(key, visible) {
387
+ if (!visible && this.visibleColumns.length <= 1)
388
+ return;
389
+ this.#vis.set(key, visible);
390
+ this.#changed();
391
+ }
392
+ /** Pin or unpin a row at the top. */
393
+ pinRow(key, pinned = true) {
394
+ const set = this.pinnedRows.map(String).filter((k) => k !== key);
395
+ this.pinnedRows = pinned ? [...set, key] : set;
396
+ }
397
+ /** Expand or collapse a row's detail. */
398
+ toggleRow(key, open = !this.#expanded.has(key)) {
399
+ open ? this.#expanded.add(key) : this.#expanded.delete(key);
400
+ const row = this.rows.find((r) => this.#key(r) === key);
401
+ this.emit('pm-expand', { row, key, expanded: open });
402
+ this.requestUpdate();
403
+ }
404
+ #startResize(e, c) {
405
+ if (e.button !== 0)
406
+ return;
407
+ e.preventDefault();
408
+ e.stopPropagation();
409
+ const handle = e.currentTarget;
410
+ const th = handle.closest('th');
411
+ this.#freezeWidths();
412
+ const startX = e.clientX;
413
+ const startW = this.#widths.get(c.key) ?? th.getBoundingClientRect().width;
414
+ const rtl = getComputedStyle(this).direction === 'rtl' ? -1 : 1;
415
+ this.#resizing = true;
416
+ handle.setPointerCapture(e.pointerId);
417
+ const move = (ev) => { this.#widths.set(c.key, Math.max(c.minWidth ?? 56, Math.round(startW + (ev.clientX - startX) * rtl))); this.requestUpdate(); };
418
+ const up = () => {
419
+ handle.removeEventListener('pointermove', move);
420
+ handle.removeEventListener('pointerup', up);
421
+ handle.removeEventListener('pointercancel', up);
422
+ this.#resizing = false;
423
+ this.emit('pm-column-resize', { key: c.key, width: this.#widths.get(c.key) });
424
+ this.#changed();
425
+ };
426
+ handle.addEventListener('pointermove', move);
427
+ handle.addEventListener('pointerup', up);
428
+ handle.addEventListener('pointercancel', up);
429
+ }
430
+ #resizeKey(e, c) {
431
+ const step = e.shiftKey ? 48 : 16;
432
+ const rtl = getComputedStyle(this).direction === 'rtl' ? -1 : 1;
433
+ const d = e.key === 'ArrowRight' ? step * rtl : e.key === 'ArrowLeft' ? -step * rtl : 0;
434
+ if (e.key === 'Enter') {
435
+ e.preventDefault();
436
+ this.#autosize(c);
437
+ return;
438
+ }
439
+ if (!d)
440
+ return;
441
+ e.preventDefault();
442
+ this.#freezeWidths();
443
+ this.#widths.set(c.key, Math.max(c.minWidth ?? 56, (this.#widths.get(c.key) ?? 120) + d));
444
+ this.#changed();
445
+ }
446
+ /** Fit a column to its widest cell. */
447
+ #autosize(c) {
448
+ const cells = [...this.renderRoot.querySelectorAll(`[data-col="${CSS.escape(c.key)}"]`)];
449
+ this.#freezeWidths();
450
+ const prev = this.#widths.get(c.key);
451
+ this.#widths.set(c.key, 9999);
452
+ this.requestUpdate();
453
+ void this.updateComplete.then(() => {
454
+ const w = Math.max(c.minWidth ?? 56, ...cells.filter((x) => x.isConnected).map((x) => Math.ceil(x.scrollWidth) + 2));
455
+ this.#widths.set(c.key, Number.isFinite(w) ? Math.min(w, 640) : prev ?? 120);
456
+ this.#changed();
457
+ });
458
+ }
459
+ /** Switch to fixed layout using the widths columns have right now (so resizing one doesn't reflow the rest). */
460
+ #freezeWidths() {
461
+ if (this.#widths.size)
462
+ return;
463
+ for (const th of this.renderRoot.querySelectorAll('thead th[data-col]')) {
464
+ const k = th.dataset.col;
465
+ if (!k.startsWith('__'))
466
+ this.#widths.set(k, Math.ceil(th.getBoundingClientRect().width));
467
+ }
468
+ }
469
+ /* ---------------- Popovers (column menu, column picker) ---------------- */
470
+ #place(pop, anchor) {
471
+ const a = anchor.getBoundingClientRect();
472
+ const p = pop.getBoundingClientRect();
473
+ let top = a.bottom + 4;
474
+ if (top + p.height > innerHeight - 8)
475
+ top = Math.max(8, a.top - p.height - 4);
476
+ const left = Math.max(8, Math.min(a.right - p.width, innerWidth - p.width - 8));
477
+ Object.assign(pop.style, { top: `${top}px`, left: `${left}px` });
478
+ }
479
+ async #openMenu(c, btn) {
480
+ this.#menuCol = c.key;
481
+ this.requestUpdate();
482
+ await this.updateComplete;
483
+ const pop = this.renderRoot.querySelector('#col-menu');
484
+ try {
485
+ pop.showPopover.call(pop, { source: btn });
486
+ }
487
+ catch {
488
+ pop.showPopover();
489
+ }
490
+ this.#place(pop, btn);
491
+ pop.querySelector('[role="menuitem"]:not([disabled])')?.focus();
492
+ }
493
+ #menuKey = (e) => {
494
+ const items = [...e.currentTarget.querySelectorAll('[role="menuitem"]:not([disabled])')];
495
+ const i = items.indexOf(e.target);
496
+ const go = (j) => { e.preventDefault(); items[(j + items.length) % items.length]?.focus(); };
497
+ if (e.key === 'ArrowDown')
498
+ go(i + 1);
499
+ else if (e.key === 'ArrowUp')
500
+ go(i - 1);
501
+ else if (e.key === 'Home')
502
+ go(0);
503
+ else if (e.key === 'End')
504
+ go(items.length - 1);
505
+ else if (e.key === 'Tab')
506
+ e.currentTarget.hidePopover();
507
+ };
508
+ #menuAction(fn) {
509
+ const pop = this.renderRoot.querySelector('#col-menu');
510
+ const key = this.#menuCol;
511
+ pop?.hidePopover();
512
+ fn();
513
+ void this.updateComplete.then(() => this.renderRoot.querySelector(`th[data-col="${CSS.escape(key ?? '')}"] .pm-dt-colmenu`)?.focus());
514
+ }
515
+ /* ---------------- Keyboard grid ---------------- */
516
+ #rowsNav() { return [...this.renderRoot.querySelectorAll('tr[data-nav]')]; }
517
+ #cellsOf(tr) { return [...tr.querySelectorAll(':scope > td[data-c]:not([data-merged])')]; }
518
+ #cellAt(rows, ri, c) {
519
+ if (ri < 0 || ri >= rows.length)
520
+ return null;
521
+ for (let j = ri; j >= 0; j--) {
522
+ const td = rows[j].querySelector(`:scope > td[data-c="${c}"]`);
523
+ if (td && !td.hasAttribute('data-merged'))
524
+ return td;
525
+ if (!td) {
526
+ // Covered by a colspan to the left.
527
+ const cells = this.#cellsOf(rows[j]).filter((x) => Number(x.dataset.c) <= c);
528
+ if (cells.length)
529
+ return cells[cells.length - 1];
530
+ }
531
+ }
532
+ return null;
533
+ }
534
+ #focusCell(td) {
535
+ if (!td)
536
+ return;
537
+ for (const x of this.renderRoot.querySelectorAll('td[data-c][tabindex="0"]'))
538
+ if (x !== td)
539
+ x.tabIndex = -1;
540
+ td.tabIndex = 0;
541
+ td.focus({ preventScroll: false });
542
+ td.scrollIntoView?.({ block: 'nearest', inline: 'nearest' });
543
+ }
544
+ #onGridKey = (e) => {
545
+ const origin = e.composedPath()[0];
546
+ const td = origin.closest?.('td[data-c]');
547
+ if (!td || !td.closest('tbody') || this.#editing)
548
+ return;
549
+ if (origin !== td) {
550
+ if (e.key === 'Escape' || e.key === 'F2') {
551
+ e.preventDefault();
552
+ td.focus();
553
+ }
554
+ return;
555
+ }
556
+ const tr = td.parentElement;
557
+ const rows = this.#rowsNav();
558
+ const ri = rows.indexOf(tr);
559
+ const c = Number(td.dataset.c);
560
+ const cells = this.#cellsOf(tr);
561
+ const ci = cells.indexOf(td);
562
+ let target;
563
+ switch (e.key) {
564
+ case 'ArrowRight':
565
+ target = cells[ci + (getComputedStyle(this).direction === 'rtl' ? -1 : 1)];
566
+ break;
567
+ case 'ArrowLeft':
568
+ target = cells[ci + (getComputedStyle(this).direction === 'rtl' ? 1 : -1)];
569
+ break;
570
+ case 'ArrowDown':
571
+ target = this.#cellAt(rows, ri + td.rowSpan, c);
572
+ break;
573
+ case 'ArrowUp':
574
+ target = this.#cellAt(rows, ri - 1, c);
575
+ break;
576
+ case 'PageDown':
577
+ target = this.#cellAt(rows, Math.min(rows.length - 1, ri + 10), c);
578
+ break;
579
+ case 'PageUp':
580
+ target = this.#cellAt(rows, Math.max(0, ri - 10), c);
581
+ break;
582
+ case 'Home':
583
+ target = e.ctrlKey || e.metaKey ? this.#cellsOf(rows[0])[0] : cells[0];
584
+ break;
585
+ case 'End': {
586
+ const last = rows[rows.length - 1];
587
+ const lc = this.#cellsOf(e.ctrlKey || e.metaKey ? last : tr);
588
+ target = lc[lc.length - 1];
589
+ break;
590
+ }
591
+ case 'Enter':
592
+ case 'F2': {
593
+ e.preventDefault();
594
+ const col = td.dataset.col;
595
+ const key = tr.dataset.key;
596
+ if (col && key && this.#canEdit(col, key)) {
597
+ void this.#startEdit(key, col);
598
+ return;
599
+ }
600
+ td.querySelector(FOCUSABLE)?.focus();
601
+ return;
602
+ }
603
+ case ' ': {
604
+ if (!this.selectable || !tr.dataset.key)
605
+ return;
606
+ e.preventDefault();
607
+ const keys = this.#pageKeys;
608
+ this.#onSelect(tr.dataset.key, keys.indexOf(tr.dataset.key), keys, e);
609
+ return;
610
+ }
611
+ default: return;
612
+ }
613
+ if (target) {
614
+ e.preventDefault();
615
+ this.#focusCell(target);
616
+ }
617
+ };
618
+ #pageKeys = [];
619
+ /* ---------------- Editing ---------------- */
620
+ #canEdit(col, key) {
621
+ const c = this.columns.find((x) => x.key === col);
622
+ const r = this.rows.find((x) => this.#key(x) === key);
623
+ if (!c || !r || !c.editable)
624
+ return false;
625
+ return typeof c.editable === 'function' ? c.editable(r) : true;
626
+ }
627
+ async #startEdit(key, col) {
628
+ this.#editing = { key, col };
629
+ this.requestUpdate();
630
+ await this.updateComplete;
631
+ const ed = this.renderRoot.querySelector('.pm-dt-editor');
632
+ ed?.focus();
633
+ if (ed instanceof HTMLInputElement)
634
+ ed.select();
635
+ }
636
+ #commit(raw) {
637
+ const ed = this.#editing;
638
+ if (!ed)
639
+ return;
640
+ this.#editing = undefined;
641
+ const c = this.columns.find((x) => x.key === ed.col);
642
+ const row = this.rows.find((x) => this.#key(x) === ed.key);
643
+ if (raw !== null && c && row) {
644
+ const previous = row[c.key];
645
+ const value = isNumeric(c) ? (raw === '' ? null : Number(raw)) : c.type === 'boolean' ? raw === 'true' : raw;
646
+ if (value !== previous && !(typeof value === 'number' && Number.isNaN(value))) {
647
+ const ok = this.emit('pm-cell-edit', { row, key: c.key, value, previous }, { cancelable: true });
648
+ if (ok)
649
+ row[c.key] = value;
650
+ }
651
+ }
652
+ this.#focusAfter = ed;
653
+ this.requestUpdate();
654
+ }
655
+ /* ---------------- Export ---------------- */
656
+ /** CSV of the visible columns for all filtered rows (or only selected ones). Formula-like text is neutralised. */
657
+ toCsv(opts = {}) {
658
+ const rows = this.processedRows;
659
+ return toCsv(this.visibleColumns, opts.selectedOnly ? rows.filter((r) => this.selected.has(this.#key(r))) : rows);
660
+ }
661
+ /** Download `toCsv()` as a file. */
662
+ exportCsv(filename = `${(this.label ?? 'table').replace(/[^\w.-]+/g, '-').toLowerCase()}.csv`, opts = {}) {
663
+ const url = URL.createObjectURL(new Blob(['', this.toCsv(opts)], { type: 'text/csv;charset=utf-8' }));
664
+ const a = document.createElement('a');
665
+ a.href = url;
666
+ a.download = filename;
667
+ a.click();
668
+ setTimeout(() => URL.revokeObjectURL(url), 1000);
669
+ }
670
+ /* ---------------- Layout measurement (frozen columns, pinned rows) ---------------- */
671
+ #measure = () => {
672
+ const table = this.renderRoot.querySelector('table.pm-table');
673
+ if (!table)
674
+ return;
675
+ const th = (k) => table.querySelector(`thead th[data-col="${CSS.escape(k)}"]`);
676
+ let acc = 0;
677
+ this.#startKeys.forEach((k, i) => { table.style.setProperty(`--ps${i}`, `${acc}px`); acc += th(k)?.getBoundingClientRect().width ?? 0; });
678
+ acc = 0;
679
+ this.#endKeys.forEach((k, i) => { table.style.setProperty(`--pe${i}`, `${acc}px`); acc += th(k)?.getBoundingClientRect().width ?? 0; });
680
+ for (const h of table.querySelectorAll('thead th[data-col] > .pm-dt-resizer'))
681
+ h.setAttribute('aria-valuenow', String(Math.round(h.parentElement.getBoundingClientRect().width)));
682
+ let top = table.tHead?.getBoundingClientRect().height ?? 0;
683
+ for (const tr of table.querySelectorAll('tbody.pm-dt-pinned > tr')) {
684
+ tr.style.setProperty('--_top', `${top}px`);
685
+ top += tr.getBoundingClientRect().height;
686
+ }
687
+ };
688
+ updated(changed) {
689
+ super.updated(changed);
690
+ if (this.#isRemote) {
691
+ // Typing in search or filters waits for the debounce; everything else (sort, page, page size, source) loads now.
692
+ const now = !this.#remoteLoaded || ['src', 'loader', 'sorts', 'page', 'pageSize'].some((k) => changed.has(k));
693
+ const typed = changed.has('filter') || changed.has('filters');
694
+ if (now || typed) {
695
+ this.#remoteLoaded = true;
696
+ this.#remote.request(this.query, now);
697
+ }
698
+ }
699
+ this.#measure();
700
+ nameCustomHeaders(this.renderRoot);
701
+ const table = this.renderRoot.querySelector('table');
702
+ if (table && !this.#ro && typeof ResizeObserver !== 'undefined') {
703
+ this.#ro = new ResizeObserver(() => this.#measure());
704
+ this.#ro.observe(table);
705
+ }
706
+ // Exactly one body cell is in the tab order (roving tabindex).
707
+ const body = this.renderRoot.querySelectorAll('tbody td[data-c]:not([data-merged])');
708
+ if (body.length && ![...body].some((x) => x.tabIndex === 0))
709
+ body[0].tabIndex = 0;
710
+ if (this.#focusAfter) {
711
+ const { key, col } = this.#focusAfter;
712
+ this.#focusAfter = undefined;
713
+ this.#focusCell(this.renderRoot.querySelector(`tr[data-key="${CSS.escape(key)}"] > td[data-col="${CSS.escape(col)}"]`));
714
+ }
715
+ }
716
+ #onScroll = (e) => {
717
+ const el = e.currentTarget;
718
+ if (this.#busy || el.scrollTop + el.clientHeight < el.scrollHeight - 160)
719
+ return;
720
+ if (this.#endAt === this.rows.length)
721
+ return;
722
+ this.#endAt = this.rows.length;
723
+ this.emit('pm-end-reached', { rows: this.rows.length });
724
+ };
725
+ /* ---------------- Render ---------------- */
726
+ #pinAttrs(key) {
727
+ const s = this.#startKeys.indexOf(key);
728
+ if (s >= 0)
729
+ return { pin: 'start', style: `inset-inline-start:var(--ps${s},0px);`, edge: s === this.#startKeys.length - 1 };
730
+ const e = this.#endKeys.indexOf(key);
731
+ if (e >= 0)
732
+ return { pin: 'end', style: `inset-inline-end:var(--pe${e},0px);`, edge: e === this.#endKeys.length - 1 };
733
+ return { style: '', edge: false };
734
+ }
735
+ #filterControl(c) {
736
+ const label = this.#t('filter', { label: c.label });
737
+ const v = this.filters[c.key] ?? '';
738
+ if (c.filter === 'select') {
739
+ const opts = c.options ?? [...new Set(this.rows.map((r) => r[c.key]).filter((x) => x != null && x !== '').map(String))].sort((a, b) => compare(a, b)).slice(0, 200);
740
+ return html `<select class="pm-dt-input" aria-label=${label} .value=${v} @change=${(e) => this.#setFilter(c.key, e.target.value)}>
741
+ <option value="">${this.#t('all')}</option>
742
+ ${opts.map((o) => { const [val, text] = typeof o === 'string' ? [o, o] : [o.value, o.label]; return html `<option value=${val} ?selected=${val === v}>${text}</option>`; })}
743
+ </select>`;
744
+ }
745
+ return html `<input class="pm-dt-input" type="search" aria-label=${label} placeholder=${c.filter === 'number' || isNumeric(c) ? '>, <, a..b' : '…'}
746
+ inputmode=${c.filter === 'number' || isNumeric(c) ? 'text' : nothing} .value=${v} @input=${(e) => this.#setFilter(c.key, e.target.value)} />`;
747
+ }
748
+ #headerCell(c, rowspan) {
749
+ const dir = this.sorts.find((s) => s.key === c.key)?.direction;
750
+ const level = this.sorts.length > 1 ? this.sorts.findIndex((s) => s.key === c.key) + 1 : 0;
751
+ const p = this.#pinAttrs(c.key);
752
+ const w = this.#widths.get(c.key);
753
+ const style = p.style + (w ? `inline-size:${w}px;min-inline-size:${w}px;max-inline-size:${w}px;` : c.width ? `inline-size:${c.width};` : '');
754
+ const resizable = c.resizable !== false;
755
+ const head = headerContent(c, this);
756
+ // Custom header content (icons, badges…) keeps `label` as the accessible name.
757
+ const custom = head !== c.label;
758
+ return html `<th scope="col" class=${c.headerClass ?? nothing} data-custom-head=${custom && !c.sortable ? c.label : nothing} data-col=${c.key} data-align=${alignOf(c) ?? nothing} data-pin=${p.pin ?? nothing} ?data-pin-edge=${p.edge}
759
+ rowspan=${rowspan > 1 ? rowspan : nothing} style=${style || nothing} draggable=${this.columnMenu ? 'true' : 'false'}
760
+ aria-sort=${dir === 'asc' ? 'ascending' : dir === 'desc' ? 'descending' : c.sortable ? 'none' : nothing}
761
+ @dragstart=${(e) => {
762
+ if (this.#resizing || e.composedPath()[0].closest?.('.pm-dt-resizer')) {
763
+ e.preventDefault();
764
+ return;
765
+ }
766
+ this.#dragCol = c.key;
767
+ e.dataTransfer?.setData('text/plain', c.key);
768
+ if (e.dataTransfer)
769
+ e.dataTransfer.effectAllowed = 'move';
770
+ }}
771
+ @dragover=${(e) => {
772
+ if (!this.#dragCol || this.#dragCol === c.key)
773
+ return;
774
+ e.preventDefault();
775
+ const th = e.currentTarget;
776
+ const r = th.getBoundingClientRect();
777
+ th.dataset.drop = (e.clientX - r.left > r.width / 2) !== (getComputedStyle(this).direction === 'rtl') ? 'after' : 'before';
778
+ }}
779
+ @dragleave=${(e) => { delete e.currentTarget.dataset.drop; }}
780
+ @drop=${(e) => {
781
+ e.preventDefault();
782
+ const th = e.currentTarget;
783
+ const after = th.dataset.drop === 'after';
784
+ delete th.dataset.drop;
785
+ if (this.#dragCol)
786
+ this.moveColumn(this.#dragCol, c.key, after);
787
+ this.#dragCol = undefined;
788
+ }}
789
+ @dragend=${() => { this.#dragCol = undefined; }}>
790
+ <div class="pm-dt-th">
791
+ ${c.sortable
792
+ ? html `<button type="button" class="pm-sort" data-dir=${dir ?? nothing} title=${level ? `${level}` : nothing} data-custom-head=${custom ? c.label : nothing} @click=${(e) => this.#toggleSort(c, e.shiftKey)}><span class="pm-dt-label">${head}</span>${SORT_ICON(dir)}${level && dir ? html `<span class="pm-dt-level">${level}</span>` : nothing}</button>`
793
+ : html `<span class="pm-dt-label">${head}</span>`}
794
+ ${p.pin ? html `<span class="pm-dt-pinmark" title=${p.pin === 'start' ? this.#t('pinStart') : this.#t('pinEnd')}>${ICON.pin}</span>` : nothing}
795
+ ${this.columnMenu ? html `<button type="button" class="pm-dt-icon pm-dt-colmenu" aria-haspopup="menu" aria-label=${this.#t('columnActions', { label: c.label })}
796
+ @click=${(e) => void this.#openMenu(c, e.currentTarget)}>${ICON.dots}</button>` : nothing}
797
+ </div>
798
+ ${resizable ? html `<span class="pm-dt-resizer" role="separator" aria-orientation="vertical" tabindex="0" aria-label=${this.#t('resize', { label: c.label })}
799
+ aria-valuemin=${c.minWidth ?? 56} aria-valuemax="2000"
800
+ @pointerdown=${(e) => this.#startResize(e, c)} @keydown=${(e) => this.#resizeKey(e, c)}
801
+ @dblclick=${() => this.#autosize(c)} @click=${(e) => e.stopPropagation()}></span>` : nothing}
802
+ </th>`;
803
+ }
804
+ #menu() {
805
+ const c = this.columns.find((x) => x.key === this.#menuCol);
806
+ const item = (label, fn, opts = {}) => html `<button type="button" role="menuitem" class="pm-dt-menuitem" ?disabled=${opts.disabled} aria-current=${opts.checked ? 'true' : nothing} @click=${() => this.#menuAction(fn)}>${label}</button>`;
807
+ const vis = this.visibleColumns;
808
+ const i = c ? vis.indexOf(c) : -1;
809
+ const pin = c ? this.#pinOf(c) : undefined;
810
+ const dir = c ? this.sorts.find((s) => s.key === c.key)?.direction : undefined;
811
+ return html `<div id="col-menu" popover="auto" role="menu" class="pm-dt-pop" aria-label=${c ? this.#t('columnActions', { label: c.label }) : 'Column actions'} @keydown=${this.#menuKey}>
812
+ ${c ? html `
813
+ ${c.sortable ? html `
814
+ ${item(this.#t('sortAsc'), () => this.#toggleSort(c, false, 'asc'), { checked: dir === 'asc' })}
815
+ ${item(this.#t('sortDesc'), () => this.#toggleSort(c, false, 'desc'), { checked: dir === 'desc' })}
816
+ ${dir ? item(this.#t('clearSort'), () => this.#toggleSort(c, true, null)) : nothing}
817
+ <hr />` : nothing}
818
+ ${pin !== 'start' ? item(this.#t('pinStart'), () => this.pinColumn(c.key, 'start')) : nothing}
819
+ ${pin !== 'end' ? item(this.#t('pinEnd'), () => this.pinColumn(c.key, 'end')) : nothing}
820
+ ${pin ? item(this.#t('unpin'), () => this.pinColumn(c.key, null)) : nothing}
821
+ <hr />
822
+ ${item(this.#t('moveLeft'), () => this.#shift(c, -1), { disabled: i <= 0 || this.#pinOf(vis[i - 1]) !== pin })}
823
+ ${item(this.#t('moveRight'), () => this.#shift(c, 1), { disabled: i >= vis.length - 1 || this.#pinOf(vis[i + 1]) !== pin })}
824
+ ${this.groupBy === c.key ? item(this.#t('ungroup'), () => { this.groupBy = undefined; this.#changed(); }) : item(this.#t('groupBy'), () => { this.groupBy = c.key; this.#collapsed.clear(); this.#changed(); })}
825
+ ${c.hideable !== false ? item(this.#t('hide'), () => this.setColumnVisible(c.key, false), { disabled: vis.length <= 1 }) : nothing}
826
+ ` : nothing}
827
+ </div>`;
828
+ }
829
+ #picker() {
830
+ return html `<div id="col-picker" popover="auto" class="pm-dt-pop" role="dialog" aria-label=${this.#t('columns')}
831
+ @toggle=${(e) => { if (e.newState === 'open')
832
+ this.#place(e.currentTarget, this.renderRoot.querySelector('[popovertarget="col-picker"]')); }}>
833
+ <fieldset class="pm-dt-picker"><legend class="pm-visually-hidden">${this.#t('columns')}</legend>
834
+ ${this.#fullOrder().map((k) => this.columns.find((c) => c.key === k)).map((c) => html `<label class="pm-dt-check">
835
+ <input type="checkbox" class="pm-checkbox" .checked=${!this.#hidden(c)} ?disabled=${c.hideable === false || (!this.#hidden(c) && this.visibleColumns.length <= 1)}
836
+ @change=${(e) => this.setColumnVisible(c.key, e.target.checked)} />${c.label}</label>`)}
837
+ </fieldset>
838
+ <button type="button" class="pm-dt-btn" @click=${() => this.resetColumns()}>${this.#t('resetColumns')}</button>
839
+ </div>`;
840
+ }
841
+ #mergeSpans(cols, items) {
842
+ return mergeSpans(cols, items, (row) => this.#expanded.has(this.#key(row)));
843
+ }
844
+ #row(r, i, idx, cols, spans, keys, ctx) {
845
+ const k = this.#key(r);
846
+ const on = this.selected.has(k);
847
+ const open = this.#expanded.has(k);
848
+ const single = this.selection === 'single';
849
+ const out = [];
850
+ let skip = 0;
851
+ let c0 = 0;
852
+ const cells = [];
853
+ if (this.selectable) {
854
+ const p = this.#pinAttrs('__select');
855
+ cells.push(html `<td class="pm-select-cell" data-c=${c0++} data-pin=${p.pin ?? nothing} ?data-pin-edge=${p.edge} style=${p.style || nothing} tabindex="-1">
856
+ <input type=${single ? 'radio' : 'checkbox'} class=${single ? 'pm-radio' : 'pm-checkbox'} name=${single ? 'pm-dt-row' : nothing} tabindex="-1"
857
+ aria-label=${this.#t('selectRow')} .checked=${on} @click=${(e) => { e.stopPropagation(); this.#onSelect(k, i, keys, e); }} /></td>`);
858
+ }
859
+ if (this.expandable) {
860
+ const p = this.#pinAttrs('__expand');
861
+ cells.push(html `<td class="pm-dt-expand-cell" data-c=${c0++} data-pin=${p.pin ?? nothing} ?data-pin-edge=${p.edge} style=${p.style || nothing} tabindex="-1">
862
+ <button type="button" class="pm-dt-icon pm-dt-expand" tabindex="-1" aria-expanded=${String(open)} aria-label=${this.#t('expand')}
863
+ @click=${(e) => { e.stopPropagation(); this.toggleRow(k); }}>${ICON.chev}</button></td>`);
864
+ }
865
+ cols.forEach((c, ci) => {
866
+ const p = this.#pinAttrs(c.key);
867
+ const rs = spans.get(c.key)?.[idx] ?? 1;
868
+ const merged = skip > 0 || rs === 0;
869
+ const content = this.#editing?.key === k && this.#editing.col === c.key ? this.#editor(c, r) : cellContent(c, r, this.locale, this);
870
+ let cs = 1;
871
+ if (!merged && c.colSpan)
872
+ cs = Math.max(1, Math.min(cols.length - ci, Math.floor(c.colSpan(r) || 1)));
873
+ const editable = !!c.editable && (typeof c.editable !== 'function' || c.editable(r));
874
+ cells.push(html `<td class=${cellClassOf(c, r) ?? nothing} data-c=${c0 + ci} data-col=${c.key} data-align=${alignOf(c) ?? nothing} ?data-nowrap=${noWrap(c)} data-label=${c.label} data-pin=${p.pin ?? nothing}
875
+ ?data-pin-edge=${p.edge} ?data-merged=${merged} ?data-editable=${editable} style=${p.style || nothing}
876
+ rowspan=${rs > 1 ? rs : nothing} colspan=${cs > 1 ? cs : nothing} tabindex="-1"
877
+ @dblclick=${editable ? () => void this.#startEdit(k, c.key) : nothing}>${content}</td>`);
878
+ if (skip > 0)
879
+ skip--;
880
+ if (cs > 1)
881
+ skip = cs - 1;
882
+ });
883
+ out.push(html `<tr data-nav data-key=${k} aria-rowindex=${ctx.aria} aria-selected=${this.selectable ? String(on) : nothing}
884
+ ?data-pinned=${ctx.pinned} ?data-clickable=${this.rowClickable}
885
+ @click=${(e) => { if (this.rowClickable && !e.target.closest('input,button,a,select,textarea'))
886
+ this.emit('pm-row-click', { row: r, key: k }); }}>${cells}</tr>`);
887
+ if (this.expandable && open) {
888
+ out.push(html `<tr class="pm-dt-detail"><td colspan=${cols.length + c0}><div class="pm-dt-detail-body">${this.renderDetail ? this.renderDetail(r) : nothing}</div></td></tr>`);
889
+ }
890
+ return out;
891
+ }
892
+ #editor(c, r) {
893
+ const v = r[c.key];
894
+ const keydown = (e) => {
895
+ e.stopPropagation();
896
+ if (e.key === 'Enter') {
897
+ e.preventDefault();
898
+ this.#commit(e.target.value);
899
+ }
900
+ else if (e.key === 'Escape') {
901
+ e.preventDefault();
902
+ this.#commit(null);
903
+ }
904
+ };
905
+ const blur = (e) => this.#commit(e.target.value);
906
+ if (c.options || c.type === 'boolean') {
907
+ const opts = c.options ?? ['true', 'false'];
908
+ return html `<select class="pm-dt-input pm-dt-editor" aria-label=${c.label} @keydown=${keydown} @blur=${blur}>
909
+ ${opts.map((o) => { const [val, text] = typeof o === 'string' ? [o, o] : [o.value, o.label]; return html `<option value=${val} ?selected=${String(v) === val}>${text}</option>`; })}</select>`;
910
+ }
911
+ const type = isNumeric(c) ? 'number' : c.type === 'date' ? 'date' : 'text';
912
+ const val = c.type === 'date' && v ? new Date(v).toISOString().slice(0, 10) : String(v ?? '');
913
+ return html `<input class="pm-dt-input pm-dt-editor" type=${type} step=${type === 'number' ? 'any' : nothing} aria-label=${c.label} .value=${val} @keydown=${keydown} @blur=${blur} />`;
914
+ }
915
+ #aggregate(c, rows) {
916
+ const v = aggregateValue(c, rows);
917
+ if (v === undefined)
918
+ return '';
919
+ if (typeof c.aggregate === 'function')
920
+ return v;
921
+ if (c.aggregate === 'count')
922
+ return new Intl.NumberFormat(this.locale).format(v);
923
+ return formatValue(v, isNumeric(c) ? c : { ...c, type: 'number' }, rows[0], this.locale);
924
+ }
925
+ render() {
926
+ const cols = this.visibleColumns;
927
+ const util = [...(this.selectable ? ['__select'] : []), ...(this.expandable ? ['__expand'] : [])];
928
+ this.#startKeys = [...util, ...cols.filter((c) => this.#pinOf(c) === 'start').map((c) => c.key)];
929
+ this.#endKeys = cols.filter((c) => this.#pinOf(c) === 'end').map((c) => c.key).reverse();
930
+ const span = util.length + cols.length;
931
+ const processed = this.processedRows;
932
+ const pinned = this.manual ? [] : this.pinnedRows.map((k) => this.rows.find((r) => this.#key(r) === String(k))).filter((r) => !!r);
933
+ const main = this.#mainRows(processed);
934
+ const items = this.#items(main);
935
+ const paged = !this.manual && this.pageSize > 0;
936
+ const start = paged ? (this.page - 1) * this.pageSize : 0;
937
+ const pageItems = paged ? items.slice(start, start + this.pageSize) : items;
938
+ const pageRows = pageItems.flatMap((it) => (it.type === 'row' ? [it.row] : []));
939
+ const keys = pageRows.map((r) => this.#key(r));
940
+ this.#pageKeys = keys;
941
+ const selCount = keys.filter((k) => this.selected.has(k)).length;
942
+ const allOn = keys.length > 0 && selCount === keys.length;
943
+ const someOn = selCount > 0 && !allOn;
944
+ const totalItems = this.manual ? (this.total ?? this.rows.length) : items.length;
945
+ const matching = this.manual ? (this.total ?? this.rows.length) : processed.length;
946
+ const grouped = cols.some((c) => c.group);
947
+ const headRows = grouped ? 2 : 1;
948
+ const hasFilters = cols.some((c) => c.filter);
949
+ const hasFoot = cols.some((c) => c.aggregate);
950
+ const spans = this.#mergeSpans(cols, pageItems);
951
+ const fixed = this.#widths.size > 0;
952
+ const widthOf = (k) => this.#widths.get(k) ?? (k === '__select' || k === '__expand' ? 44 : 160);
953
+ const tableStyle = fixed ? `table-layout:fixed;inline-size:${[...util, ...cols.map((c) => c.key)].reduce((s, k) => s + widthOf(k), 0)}px;min-inline-size:100%` : '';
954
+ const utilHead = (k, rowspan) => {
955
+ const p = this.#pinAttrs(k);
956
+ return k === '__select'
957
+ ? html `<th class="pm-select-cell" scope="col" data-col="__select" data-pin=${p.pin ?? nothing} ?data-pin-edge=${p.edge} style=${p.style || nothing} rowspan=${rowspan > 1 ? rowspan : nothing}>
958
+ ${this.selection === 'single' ? html `<span class="pm-visually-hidden">${this.#t('selectRow')}</span>` : html `<input type="checkbox" class="pm-checkbox" aria-label=${this.#t('selectAll')}
959
+ .checked=${allOn} .indeterminate=${someOn} ?disabled=${!keys.length}
960
+ @change=${() => { const n = new Set(this.selected); for (const k2 of keys)
961
+ allOn ? n.delete(k2) : n.add(k2); this.#setSelected(n); }} />`}</th>`
962
+ : html `<th class="pm-dt-expand-cell" scope="col" data-col="__expand" data-pin=${p.pin ?? nothing} ?data-pin-edge=${p.edge} style=${p.style || nothing} rowspan=${rowspan > 1 ? rowspan : nothing}><span class="pm-visually-hidden">${this.#t('expand')}</span></th>`;
963
+ };
964
+ // Header group row (merged header cells).
965
+ const groupRow = () => {
966
+ const cells = util.map((k) => utilHead(k, headRows));
967
+ for (let i = 0; i < cols.length;) {
968
+ const c = cols[i];
969
+ if (!c.group) {
970
+ cells.push(this.#headerCell(c, 2));
971
+ i++;
972
+ continue;
973
+ }
974
+ let j = i + 1;
975
+ while (j < cols.length && cols[j].group === c.group)
976
+ j++;
977
+ const allPinned = cols.slice(i, j).every((x) => this.#pinOf(x) === 'start');
978
+ const p = allPinned ? this.#pinAttrs(c.key) : { style: '', pin: undefined, edge: false };
979
+ cells.push(html `<th scope="colgroup" colspan=${j - i} class="pm-dt-group-head" data-pin=${p.pin ?? nothing} style=${p.style || nothing}>${c.group}</th>`);
980
+ i = j;
981
+ }
982
+ return html `<tr>${cells}</tr>`;
983
+ };
984
+ const leafRow = () => html `<tr>${grouped ? nothing : util.map((k) => utilHead(k, 1))}${cols.filter((c) => !grouped || c.group).map((c) => this.#headerCell(c, 1))}</tr>`;
985
+ const toolbar = this.searchable || this.columnPicker || this.exportable || this.querySelector('[slot="toolbar"]') || this.selected.size > 0;
986
+ let aria = headRows + (hasFilters ? 1 : 0) + 1 + start;
987
+ let rowIdx = 0;
988
+ return html `<div class="pm-data-table pm-table-wrap" part="base" data-stack=${this.stack ?? 'auto'}>
989
+ ${toolbar ? html `<div class="pm-data-table-bar" part="toolbar">
990
+ <div class="pm-dt-bar-start">
991
+ ${this.searchable ? html `<label class="pm-dt-search">${ICON.search}<input class="pm-dt-input" type="search" placeholder=${this.#t('search')} aria-label=${this.#t('search')}
992
+ .value=${this.filter ?? ''} @input=${(e) => this.#setFilter(null, e.target.value)} /></label>` : nothing}
993
+ <slot name="toolbar"></slot>
994
+ </div>
995
+ <div class="pm-dt-bar-end">
996
+ ${this.selected.size ? html `<span class="count" aria-live="polite">${this.#t('selected', { n: this.selected.size })}</span>
997
+ ${this.selection !== 'single' && allOn && matching > this.selected.size ? html `<button type="button" class="pm-dt-btn" data-variant="link" @click=${() => this.selectAllMatching()}>${this.#t('selectAllMatching', { n: matching })}</button>` : nothing}
998
+ <button type="button" class="pm-dt-btn" data-variant="link" @click=${() => this.clearSelection()}>${this.#t('clearSelection')}</button>` : nothing}
999
+ ${this.columnPicker ? html `<button type="button" class="pm-dt-btn" popovertarget="col-picker">${ICON.columns}<span>${this.#t('columns')}</span></button>` : nothing}
1000
+ ${this.exportable ? html `<button type="button" class="pm-dt-btn" @click=${() => this.exportCsv(undefined, { selectedOnly: this.selected.size > 0 })}>${ICON.download}<span>${this.#t('exportCsv')}</span></button>` : nothing}
1001
+ </div>
1002
+ </div>` : nothing}
1003
+ ${this.#busy && pageRows.length ? html `<div class="pm-dt-progress" role="progressbar" aria-label="Loading"></div>` : nothing}
1004
+ ${this.#remote.error && !this.#busy ? html `<div class="pm-dt-alert" role="alert" part="error">${this.#t('loadError')}
1005
+ <button type="button" class="pm-dt-btn" @click=${() => this.#remote.retry()}>${this.#t('retry')}</button></div>` : nothing}
1006
+ <div class="pm-data-table-scroll pm-table-scroll" part="scroll" role="region" aria-label=${this.label ?? 'Table'}
1007
+ style=${this.maxHeight ? `max-block-size:${this.maxHeight}` : nothing} @scroll=${this.#onScroll}>
1008
+ <table class="pm-table" role="grid" ?data-striped=${this.striped} data-hover ?data-fixed=${fixed} aria-busy=${this.#busy ? 'true' : 'false'}
1009
+ aria-rowcount=${this.groupBy ? nothing : matching + headRows + (hasFilters ? 1 : 0)} aria-colcount=${span}
1010
+ aria-multiselectable=${this.selectable && this.selection !== 'single' ? 'true' : nothing}
1011
+ style=${tableStyle || nothing} @keydown=${this.#onGridKey}>
1012
+ ${this.label ? html `<caption class="pm-visually-hidden">${this.label}</caption>` : nothing}
1013
+ ${fixed ? html `<colgroup>${[...util, ...cols.map((c) => c.key)].map((k) => html `<col style=${`inline-size:${widthOf(k)}px`} />`)}</colgroup>` : nothing}
1014
+ <thead>
1015
+ ${grouped ? groupRow() : nothing}
1016
+ ${leafRow()}
1017
+ ${hasFilters ? html `<tr class="pm-dt-filters">${util.map((k) => { const p = this.#pinAttrs(k); return html `<td data-pin=${p.pin ?? nothing} style=${p.style || nothing}></td>`; })}
1018
+ ${cols.map((c) => { const p = this.#pinAttrs(c.key); return html `<td data-pin=${p.pin ?? nothing} ?data-pin-edge=${p.edge} style=${p.style || nothing}>${c.filter ? this.#filterControl(c) : nothing}</td>`; })}</tr>` : nothing}
1019
+ </thead>
1020
+ ${pinned.length ? html `<tbody class="pm-dt-pinned">${pinned.map((r) => this.#row(r, -1, -1, cols, new Map(), keys, { pinned: true, aria: aria++ }))}</tbody>` : nothing}
1021
+ <tbody>
1022
+ ${this.#busy && !pageRows.length
1023
+ ? Array.from({ length: Math.min(this.pageSize || 5, 8) }, () => html `<tr>${Array.from({ length: span }, () => html `<td><span class="pm-skeleton" style="display:block;block-size:0.9em;inline-size:70%"></span></td>`)}</tr>`)
1024
+ : pageItems.length
1025
+ ? pageItems.map((it, idx) => {
1026
+ if (it.type === 'group') {
1027
+ const gc = this.columns.find((c) => c.key === this.groupBy);
1028
+ const shown = gc ? formatValue(it.first[gc.key], gc, it.first, this.locale) : it.value;
1029
+ const open = !this.#collapsed.has(it.value);
1030
+ return html `<tr class="pm-dt-group"><td colspan=${span}><div class="pm-dt-group-inner">
1031
+ <button type="button" class="pm-dt-group-toggle" aria-expanded=${String(open)}
1032
+ @click=${() => { open ? this.#collapsed.add(it.value) : this.#collapsed.delete(it.value); this.requestUpdate(); }}>${ICON.chev}
1033
+ <span class="pm-dt-group-label">${gc?.label ?? this.groupBy}:</span> <strong>${shown === '' ? '—' : shown}</strong>
1034
+ <span class="pm-dt-group-count">${it.count}</span></button>
1035
+ ${cols.filter((c) => c.aggregate).map((c) => html `<span class="pm-dt-group-agg">${c.label}: <strong>${this.#aggregate(c, it.rows)}</strong></span>`)}
1036
+ </div></td></tr>`;
1037
+ }
1038
+ return this.#row(it.row, rowIdx++, idx, cols, spans, keys, { aria: aria++ });
1039
+ })
1040
+ : html `<tr><td colspan=${span} class="pm-table-empty"><slot name="empty">${this.#t('empty')}</slot></td></tr>`}
1041
+ </tbody>
1042
+ ${hasFoot ? html `<tfoot><tr>${util.map((k) => { const p = this.#pinAttrs(k); return html `<td data-pin=${p.pin ?? nothing} style=${p.style || nothing}></td>`; })}
1043
+ ${cols.map((c, i) => { const p = this.#pinAttrs(c.key); return html `<td data-align=${alignOf(c) ?? (c.aggregate ? 'end' : nothing)} data-label=${c.aggregate ? c.label : nothing} data-pin=${p.pin ?? nothing} ?data-pin-edge=${p.edge} style=${p.style || nothing}>${c.aggregate ? this.#aggregate(c, processed) : i === 0 ? this.#t('total') : nothing}</td>`; })}</tr></tfoot>` : nothing}
1044
+ </table>
1045
+ </div>
1046
+ ${this.pageSize && (totalItems > this.pageSize || this.pageSizes?.length) ? html `<div class="pm-data-table-bar" part="footer">
1047
+ <span class="count" aria-live="polite">${this.#t('range', { from: totalItems ? start + 1 : 0, to: Math.min(start + this.pageSize, totalItems), total: totalItems })}</span>
1048
+ <div class="pm-dt-bar-end">
1049
+ ${this.pageSizes?.length ? html `<select class="pm-dt-input pm-dt-pagesize" aria-label="Rows per page" @change=${(e) => { this.pageSize = Number(e.target.value); this.page = 1; this.emit('pm-page', { page: 1, pageSize: this.pageSize }); this.#changed(); }}>
1050
+ ${this.pageSizes.map((n) => html `<option value=${n} ?selected=${n === this.pageSize}>${n} / page</option>`)}</select>` : nothing}
1051
+ ${totalItems > this.pageSize ? html `<pm-pagination .page=${this.page} .pages=${this.#pageCount} label=${this.#t('pages', { label: this.label ?? 'Table' })}
1052
+ @pm-change=${(e) => { e.stopPropagation(); this.#goTo(e.detail.page); }}></pm-pagination>` : nothing}
1053
+ </div>
1054
+ </div>` : nothing}
1055
+ ${this.columnMenu ? this.#menu() : nothing}
1056
+ ${this.columnPicker ? this.#picker() : nothing}
1057
+ </div>`;
1058
+ }
1059
+ }
1060
+ defineElement('pm-data-table', PmDataTable);