@protobase/ui 0.115.0 → 0.115.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 (207) hide show
  1. package/dist/account/messages.d.ts +2 -2
  2. package/dist/app/change-confirm/messages.d.ts +2 -2
  3. package/dist/app/charts/messages.d.ts +2 -2
  4. package/dist/app/comments/messages.d.ts +2 -2
  5. package/dist/app/confirm-sign-in-messages.d.ts +2 -2
  6. package/dist/app/conversation/messages.d.ts +2 -2
  7. package/dist/app/create/messages.d.ts +2 -2
  8. package/dist/app/custom-section.d.ts +1 -1
  9. package/dist/app/delete/messages.d.ts +2 -2
  10. package/dist/app/displays/list-cards.d.ts +1 -1
  11. package/dist/app/displays/messages.d.ts +2 -2
  12. package/dist/app/embedded-list/messages.d.ts +2 -2
  13. package/dist/app/export/messages.d.ts +2 -2
  14. package/dist/app/field-messages.d.ts +2 -2
  15. package/dist/app/field-types/runner-install/messages.d.ts +2 -2
  16. package/dist/app/field-types/widget-part.d.ts +1 -1
  17. package/dist/app/field-types/workflow/messages.d.ts +2 -2
  18. package/dist/app/field-types/workflow-page/messages.d.ts +2 -2
  19. package/dist/app/field-types/workflow-run/messages.d.ts +2 -2
  20. package/dist/app/file-viewers/messages.d.ts +2 -2
  21. package/dist/app/focus/messages.d.ts +2 -2
  22. package/dist/app/gallery/gallery-layout.d.ts +2 -2
  23. package/dist/app/gallery/messages.d.ts +2 -2
  24. package/dist/app/hand-order/messages.d.ts +2 -2
  25. package/dist/app/history/messages.d.ts +2 -2
  26. package/dist/app/import/messages.d.ts +2 -2
  27. package/dist/app/list-messages.d.ts +2 -2
  28. package/dist/app/messages.d.ts +2 -2
  29. package/dist/app/pages/custom-boundary.d.ts +1 -1
  30. package/dist/app/pages/custom-chosen.d.ts +1 -1
  31. package/dist/app/pages/messages.d.ts +2 -2
  32. package/dist/app/record-chart/messages.d.ts +2 -2
  33. package/dist/app/record-messages.d.ts +2 -2
  34. package/dist/app/record-row/messages.d.ts +2 -2
  35. package/dist/app/related-cards/messages.d.ts +2 -2
  36. package/dist/app/runtime/messages.d.ts +2 -2
  37. package/dist/app/saved/messages.d.ts +2 -2
  38. package/dist/app/saved/saved-list.d.ts +1 -1
  39. package/dist/app/search/messages.d.ts +2 -2
  40. package/dist/app/searches/messages.d.ts +2 -2
  41. package/dist/app-shell/messages.d.ts +2 -2
  42. package/dist/assistant-dock/messages.d.ts +2 -2
  43. package/dist/auth/auth-provider.d.ts +3 -2
  44. package/dist/auth/auth-provider.js +8 -5
  45. package/dist/auth/messages.d.ts +2 -2
  46. package/dist/auth/native-sign-in.d.ts +11 -0
  47. package/dist/auth/native-sign-in.js +11 -0
  48. package/dist/calls/messages.d.ts +2 -2
  49. package/dist/chat/messages.d.ts +2 -2
  50. package/dist/compact-table/messages.d.ts +2 -2
  51. package/dist/data-grid/messages.d.ts +2 -2
  52. package/dist/filter-panel/messages.d.ts +2 -2
  53. package/dist/invitations/messages.d.ts +2 -2
  54. package/dist/live/messages.d.ts +2 -2
  55. package/dist/mailbox/messages.d.ts +2 -2
  56. package/dist/mentions/messages.d.ts +2 -2
  57. package/dist/mocks/orders.d.ts +2 -2
  58. package/dist/notifications/bell/messages.d.ts +2 -2
  59. package/dist/organizations/messages.d.ts +2 -2
  60. package/dist/package.js +1 -1
  61. package/dist/plugins/before-sign-in.d.ts +1 -1
  62. package/dist/plugins/messages.d.ts +2 -2
  63. package/dist/record-view/messages.d.ts +2 -2
  64. package/dist/shell/assets/{account-page-XnRBgIm3.js → account-page-ZqwlW9hk.js} +2 -2
  65. package/dist/shell/assets/app-B62bQR9g.js +34 -0
  66. package/dist/shell/assets/{assistant-shell-B0UOjO9j.js → assistant-shell-B7BpQefx.js} +2 -2
  67. package/dist/shell/assets/{board-display-82tI8eop.js → board-display-DkUlCdNw.js} +2 -2
  68. package/dist/shell/assets/{calendar-display-DdVa8wHA.js → calendar-display-BCHxv33y.js} +2 -2
  69. package/dist/shell/assets/{call-rings-CtUeFpjU.js → call-rings-DAUYubKB.js} +2 -2
  70. package/dist/shell/assets/{calls-Joul8uMN.js → calls-BgQWuG_K.js} +2 -2
  71. package/dist/shell/assets/{circle-alert-CKfEY2eG.js → circle-alert-GOsvVcfy.js} +2 -2
  72. package/dist/shell/assets/{composed-page-BRTMBrpL.js → composed-page-BaecAyUt.js} +2 -2
  73. package/dist/shell/assets/{composer-section-DAIjBfXV.js → composer-section-f4ZiGN6b.js} +2 -2
  74. package/dist/shell/assets/{connect-route-DApl7e0e.js → connect-route-DBl0vKRP.js} +2 -2
  75. package/dist/shell/assets/{copy-field-BHZX0DSt.js → copy-field-DyW5ue6m.js} +2 -2
  76. package/dist/shell/assets/{create-route-V5JNc_Kq.js → create-route-C-2_HhMU.js} +2 -2
  77. package/dist/shell/assets/{custom-step-container-field-DC27oiuQ.js → custom-step-container-field-51YbUUBp.js} +2 -2
  78. package/dist/shell/assets/{embedded-list-DAjlopsR.js → embedded-list-BBrpHnq2.js} +3 -3
  79. package/dist/shell/assets/{export-dialog-Co7gghJ9.js → export-dialog-Da8MFuqi.js} +2 -2
  80. package/dist/shell/assets/{graph-view-D7yvxu1M.js → graph-view-d6QFVrkz.js} +2 -2
  81. package/dist/shell/assets/{group-donut-BrffJgvP.js → group-donut-yTquvFkE.js} +2 -2
  82. package/dist/shell/assets/{guest-call-page-B0thHXzD.js → guest-call-page-CZRLRnx2.js} +3 -3
  83. package/dist/shell/assets/{html-viewer-BbtenCM5.js → html-viewer-DBmUOsJ3.js} +2 -2
  84. package/dist/shell/assets/{import-dialog-Q-qqFWmI.js → import-dialog-ggSlUxm7.js} +2 -2
  85. package/dist/shell/assets/{import-table-dialog-CEDYy6gW.js → import-table-dialog-B_LVBAyn.js} +2 -2
  86. package/dist/shell/assets/{index-ygoGHYZq.js → index-BAGIbxUE.js} +1 -1
  87. package/dist/shell/assets/{invitations-page-DZ_oGyRY.js → invitations-page-CdI3jnMc.js} +2 -2
  88. package/dist/shell/assets/{layout-grid-DV6ebMSb.js → layout-grid-Dn4qEC5I.js} +2 -2
  89. package/dist/shell/assets/{legend-item-ClY5HSFP.js → legend-item-CjJUgSsw.js} +2 -2
  90. package/dist/shell/assets/{list-page-CxylG_Bi.js → list-page-DjCEQgcK.js} +4 -4
  91. package/dist/shell/assets/{maplibre-BIJVsLGQ.js → maplibre-CaDAFMUv.js} +2 -2
  92. package/dist/shell/assets/{markdown-content-B-r0DBG0.js → markdown-content-DX4_Buag.js} +2 -2
  93. package/dist/shell/assets/{members-page-UU96y7EQ.js → members-page-DbhRf_Ir.js} +2 -2
  94. package/dist/shell/assets/{messages-03zmq2oA.js → messages-Ct70wtYc.js} +2 -2
  95. package/dist/shell/assets/{organization-page-Bj3c9EW9.js → organization-page-BzqYb0dI.js} +2 -2
  96. package/dist/shell/assets/{organizations-page-Cwn2LlFj.js → organizations-page-Pkf_qkKQ.js} +2 -2
  97. package/dist/shell/assets/{pending-invitation-row-JzQ9tOn_.js → pending-invitation-row-BO7g_HOR.js} +2 -2
  98. package/dist/shell/assets/{period-chart-CWBy03F7.js → period-chart-DuwFRt6t.js} +2 -2
  99. package/dist/shell/assets/{person-row-BJP4ag6H.js → person-row-BEVXbR43.js} +2 -2
  100. package/dist/shell/assets/{public-form-page-Ct45rBwR.js → public-form-page-BB1S8Xz-.js} +2 -2
  101. package/dist/shell/assets/{record-lines-DCs-txvG.js → record-lines-DH2WXKw7.js} +2 -2
  102. package/dist/shell/assets/{record-map-BMZTdCJn.js → record-map-ysuwoP8e.js} +2 -2
  103. package/dist/shell/assets/{record-opens-DQrqEFru.js → record-opens-DLhF2J0q.js} +2 -2
  104. package/dist/shell/assets/{record-page-C6tevfpa.js → record-page-BVYzIF9Z.js} +3 -3
  105. package/dist/shell/assets/{record-preview-Bqm2whUV.js → record-preview-DWMs-hhQ.js} +2 -2
  106. package/dist/shell/assets/{records-map-Dq1fZ0Ll.js → records-map-D_rSUmg1.js} +2 -2
  107. package/dist/shell/assets/{render-node-DQMrGelM.js → render-node-BAePC3l_.js} +3 -3
  108. package/dist/shell/assets/{reorder-button-C8G3bjeB.js → reorder-button-C3r76tJu.js} +2 -2
  109. package/dist/shell/assets/{run-trace-view-BoSTWwYy.js → run-trace-view-ygx54CFl.js} +2 -2
  110. package/dist/shell/assets/{runner-install-field-BcduhfGA.js → runner-install-field-CqATImuc.js} +2 -2
  111. package/dist/shell/assets/{runtime-update-BRoaUFOx.js → runtime-update-Db162XI2.js} +2 -2
  112. package/dist/shell/assets/{shared-protobase-ui-Ck4mYbeU.js → shared-protobase-ui-BSmHN3g_.js} +1 -1
  113. package/dist/shell/assets/{sheet-source-RncsoczT.js → sheet-source-Dm00KLZc.js} +2 -2
  114. package/dist/shell/assets/{sign-in-policy-page-azN2k0xv.js → sign-in-policy-page-C2uInopq.js} +2 -2
  115. package/dist/shell/assets/{start-block-queries-kp3ICAXt.js → start-block-queries-jNww7Vs5.js} +2 -2
  116. package/dist/shell/assets/{step-catalog-QFTLEUUW.js → step-catalog-Dv2NgEcj.js} +2 -2
  117. package/dist/shell/assets/{step-panel-CcBoYcad.js → step-panel-gkiXwLZN.js} +2 -2
  118. package/dist/shell/assets/{timeline-display-Cr61_SZU.js → timeline-display-DRsyatGd.js} +2 -2
  119. package/dist/shell/assets/{trash-Bb3IsZeK.js → trash-DfUQvtnQ.js} +2 -2
  120. package/dist/shell/assets/{update-set-D8rImCxw.js → update-set-CXnC4u8b.js} +2 -2
  121. package/dist/shell/assets/{use-calendar-move-DP_MzXTz.js → use-calendar-move-BEV_Fhxn.js} +2 -2
  122. package/dist/shell/assets/{use-display-rows-3xQM1gvv.js → use-display-rows-DgbmFYc7.js} +2 -2
  123. package/dist/shell/assets/{use-paged-search-DcNUhIL9.js → use-paged-search-DfHM-bt_.js} +2 -2
  124. package/dist/shell/assets/{use-run-trace-B9v2XkVL.js → use-run-trace-Boc0Dt3j.js} +2 -2
  125. package/dist/shell/assets/{use-workflow-page-DZZERjMt.js → use-workflow-page-BtLkA5E8.js} +2 -2
  126. package/dist/shell/assets/{use-workflow-types-BRe2O0QF.js → use-workflow-types-CeXlzawJ.js} +2 -2
  127. package/dist/shell/assets/{workflow-canvas-Be_DnY83.js → workflow-canvas-Pq3WUUPt.js} +2 -2
  128. package/dist/shell/assets/{workflow-field-D3BW-Lvk.js → workflow-field-ApOGZcSb.js} +3 -3
  129. package/dist/shell/assets/{workflow-graph-editor-J0pJUxAk.js → workflow-graph-editor-s14bAl5F.js} +2 -2
  130. package/dist/shell/assets/{workflow-run-field-DCoSJYVl.js → workflow-run-field-CxEHxP9x.js} +3 -3
  131. package/dist/shell/assets/{workflow-status-field-btxWS0rc.js → workflow-status-field-DXe1sQIj.js} +2 -2
  132. package/dist/shell/assets/{workflow-workbench-lBJ6-WBD.js → workflow-workbench-PmFBx_IG.js} +2 -2
  133. package/dist/shell/index.html +3 -3
  134. package/dist/shell/protobase.shell.json +2 -2
  135. package/dist/shell/protobase.sw.js +2 -2
  136. package/dist/shell-source-maps/assets/{account-page-XnRBgIm3.js.map → account-page-ZqwlW9hk.js.map} +1 -1
  137. package/dist/shell-source-maps/assets/app-B62bQR9g.js.map +1 -0
  138. package/dist/shell-source-maps/assets/{assistant-shell-B0UOjO9j.js.map → assistant-shell-B7BpQefx.js.map} +1 -1
  139. package/dist/shell-source-maps/assets/{board-display-82tI8eop.js.map → board-display-DkUlCdNw.js.map} +1 -1
  140. package/dist/shell-source-maps/assets/{calendar-display-DdVa8wHA.js.map → calendar-display-BCHxv33y.js.map} +1 -1
  141. package/dist/shell-source-maps/assets/{call-rings-CtUeFpjU.js.map → call-rings-DAUYubKB.js.map} +1 -1
  142. package/dist/shell-source-maps/assets/{calls-Joul8uMN.js.map → calls-BgQWuG_K.js.map} +1 -1
  143. package/dist/shell-source-maps/assets/{circle-alert-CKfEY2eG.js.map → circle-alert-GOsvVcfy.js.map} +1 -1
  144. package/dist/shell-source-maps/assets/{composed-page-BRTMBrpL.js.map → composed-page-BaecAyUt.js.map} +1 -1
  145. package/dist/shell-source-maps/assets/{composer-section-DAIjBfXV.js.map → composer-section-f4ZiGN6b.js.map} +1 -1
  146. package/dist/shell-source-maps/assets/{connect-route-DApl7e0e.js.map → connect-route-DBl0vKRP.js.map} +1 -1
  147. package/dist/shell-source-maps/assets/{copy-field-BHZX0DSt.js.map → copy-field-DyW5ue6m.js.map} +1 -1
  148. package/dist/shell-source-maps/assets/{create-route-V5JNc_Kq.js.map → create-route-C-2_HhMU.js.map} +1 -1
  149. package/dist/shell-source-maps/assets/{custom-step-container-field-DC27oiuQ.js.map → custom-step-container-field-51YbUUBp.js.map} +1 -1
  150. package/dist/shell-source-maps/assets/{embedded-list-DAjlopsR.js.map → embedded-list-BBrpHnq2.js.map} +1 -1
  151. package/dist/shell-source-maps/assets/{export-dialog-Co7gghJ9.js.map → export-dialog-Da8MFuqi.js.map} +1 -1
  152. package/dist/shell-source-maps/assets/{graph-view-D7yvxu1M.js.map → graph-view-d6QFVrkz.js.map} +1 -1
  153. package/dist/shell-source-maps/assets/{group-donut-BrffJgvP.js.map → group-donut-yTquvFkE.js.map} +1 -1
  154. package/dist/shell-source-maps/assets/{guest-call-page-B0thHXzD.js.map → guest-call-page-CZRLRnx2.js.map} +1 -1
  155. package/dist/shell-source-maps/assets/{html-viewer-BbtenCM5.js.map → html-viewer-DBmUOsJ3.js.map} +1 -1
  156. package/dist/shell-source-maps/assets/{import-dialog-Q-qqFWmI.js.map → import-dialog-ggSlUxm7.js.map} +1 -1
  157. package/dist/shell-source-maps/assets/{import-table-dialog-CEDYy6gW.js.map → import-table-dialog-B_LVBAyn.js.map} +1 -1
  158. package/dist/shell-source-maps/assets/{invitations-page-DZ_oGyRY.js.map → invitations-page-CdI3jnMc.js.map} +1 -1
  159. package/dist/shell-source-maps/assets/{layout-grid-DV6ebMSb.js.map → layout-grid-Dn4qEC5I.js.map} +1 -1
  160. package/dist/shell-source-maps/assets/{legend-item-ClY5HSFP.js.map → legend-item-CjJUgSsw.js.map} +1 -1
  161. package/dist/shell-source-maps/assets/{list-page-CxylG_Bi.js.map → list-page-DjCEQgcK.js.map} +1 -1
  162. package/dist/shell-source-maps/assets/{maplibre-BIJVsLGQ.js.map → maplibre-CaDAFMUv.js.map} +1 -1
  163. package/dist/shell-source-maps/assets/{markdown-content-B-r0DBG0.js.map → markdown-content-DX4_Buag.js.map} +1 -1
  164. package/dist/shell-source-maps/assets/{members-page-UU96y7EQ.js.map → members-page-DbhRf_Ir.js.map} +1 -1
  165. package/dist/shell-source-maps/assets/{messages-03zmq2oA.js.map → messages-Ct70wtYc.js.map} +1 -1
  166. package/dist/shell-source-maps/assets/{organization-page-Bj3c9EW9.js.map → organization-page-BzqYb0dI.js.map} +1 -1
  167. package/dist/shell-source-maps/assets/{organizations-page-Cwn2LlFj.js.map → organizations-page-Pkf_qkKQ.js.map} +1 -1
  168. package/dist/shell-source-maps/assets/{pending-invitation-row-JzQ9tOn_.js.map → pending-invitation-row-BO7g_HOR.js.map} +1 -1
  169. package/dist/shell-source-maps/assets/{period-chart-CWBy03F7.js.map → period-chart-DuwFRt6t.js.map} +1 -1
  170. package/dist/shell-source-maps/assets/{person-row-BJP4ag6H.js.map → person-row-BEVXbR43.js.map} +1 -1
  171. package/dist/shell-source-maps/assets/{public-form-page-Ct45rBwR.js.map → public-form-page-BB1S8Xz-.js.map} +1 -1
  172. package/dist/shell-source-maps/assets/{record-lines-DCs-txvG.js.map → record-lines-DH2WXKw7.js.map} +1 -1
  173. package/dist/shell-source-maps/assets/{record-map-BMZTdCJn.js.map → record-map-ysuwoP8e.js.map} +1 -1
  174. package/dist/shell-source-maps/assets/{record-opens-DQrqEFru.js.map → record-opens-DLhF2J0q.js.map} +1 -1
  175. package/dist/shell-source-maps/assets/{record-page-C6tevfpa.js.map → record-page-BVYzIF9Z.js.map} +1 -1
  176. package/dist/shell-source-maps/assets/{record-preview-Bqm2whUV.js.map → record-preview-DWMs-hhQ.js.map} +1 -1
  177. package/dist/shell-source-maps/assets/{records-map-Dq1fZ0Ll.js.map → records-map-D_rSUmg1.js.map} +1 -1
  178. package/dist/shell-source-maps/assets/{render-node-DQMrGelM.js.map → render-node-BAePC3l_.js.map} +1 -1
  179. package/dist/shell-source-maps/assets/{reorder-button-C8G3bjeB.js.map → reorder-button-C3r76tJu.js.map} +1 -1
  180. package/dist/shell-source-maps/assets/{run-trace-view-BoSTWwYy.js.map → run-trace-view-ygx54CFl.js.map} +1 -1
  181. package/dist/shell-source-maps/assets/{runner-install-field-BcduhfGA.js.map → runner-install-field-CqATImuc.js.map} +1 -1
  182. package/dist/shell-source-maps/assets/{runtime-update-BRoaUFOx.js.map → runtime-update-Db162XI2.js.map} +1 -1
  183. package/dist/shell-source-maps/assets/{sheet-source-RncsoczT.js.map → sheet-source-Dm00KLZc.js.map} +1 -1
  184. package/dist/shell-source-maps/assets/{sign-in-policy-page-azN2k0xv.js.map → sign-in-policy-page-C2uInopq.js.map} +1 -1
  185. package/dist/shell-source-maps/assets/{start-block-queries-kp3ICAXt.js.map → start-block-queries-jNww7Vs5.js.map} +1 -1
  186. package/dist/shell-source-maps/assets/{step-catalog-QFTLEUUW.js.map → step-catalog-Dv2NgEcj.js.map} +1 -1
  187. package/dist/shell-source-maps/assets/{step-panel-CcBoYcad.js.map → step-panel-gkiXwLZN.js.map} +1 -1
  188. package/dist/shell-source-maps/assets/{timeline-display-Cr61_SZU.js.map → timeline-display-DRsyatGd.js.map} +1 -1
  189. package/dist/shell-source-maps/assets/{trash-Bb3IsZeK.js.map → trash-DfUQvtnQ.js.map} +1 -1
  190. package/dist/shell-source-maps/assets/{update-set-D8rImCxw.js.map → update-set-CXnC4u8b.js.map} +1 -1
  191. package/dist/shell-source-maps/assets/{use-calendar-move-DP_MzXTz.js.map → use-calendar-move-BEV_Fhxn.js.map} +1 -1
  192. package/dist/shell-source-maps/assets/{use-display-rows-3xQM1gvv.js.map → use-display-rows-DgbmFYc7.js.map} +1 -1
  193. package/dist/shell-source-maps/assets/{use-paged-search-DcNUhIL9.js.map → use-paged-search-DfHM-bt_.js.map} +1 -1
  194. package/dist/shell-source-maps/assets/{use-run-trace-B9v2XkVL.js.map → use-run-trace-Boc0Dt3j.js.map} +1 -1
  195. package/dist/shell-source-maps/assets/{use-workflow-page-DZZERjMt.js.map → use-workflow-page-BtLkA5E8.js.map} +1 -1
  196. package/dist/shell-source-maps/assets/{use-workflow-types-BRe2O0QF.js.map → use-workflow-types-CeXlzawJ.js.map} +1 -1
  197. package/dist/shell-source-maps/assets/{workflow-canvas-Be_DnY83.js.map → workflow-canvas-Pq3WUUPt.js.map} +1 -1
  198. package/dist/shell-source-maps/assets/{workflow-field-D3BW-Lvk.js.map → workflow-field-ApOGZcSb.js.map} +1 -1
  199. package/dist/shell-source-maps/assets/{workflow-graph-editor-J0pJUxAk.js.map → workflow-graph-editor-s14bAl5F.js.map} +1 -1
  200. package/dist/shell-source-maps/assets/{workflow-run-field-DCoSJYVl.js.map → workflow-run-field-CxEHxP9x.js.map} +1 -1
  201. package/dist/shell-source-maps/assets/{workflow-status-field-btxWS0rc.js.map → workflow-status-field-DXe1sQIj.js.map} +1 -1
  202. package/dist/shell-source-maps/assets/{workflow-workbench-lBJ6-WBD.js.map → workflow-workbench-PmFBx_IG.js.map} +1 -1
  203. package/dist/status/messages.d.ts +2 -2
  204. package/dist/users/messages.d.ts +2 -2
  205. package/package.json +5 -5
  206. package/dist/shell/assets/app-p7iRIIoG.js +0 -34
  207. package/dist/shell-source-maps/assets/app-p7iRIIoG.js.map +0 -1
@@ -1 +1 @@
1
- {"version":3,"mappings":";o7EASA,IAAMA,GAAa,CACjB,KAAM,aACN,KAAM,GACN,KAAM,CACJ,CAAC,OAAQ,CAAE,EAAG,WAAY,IAAK,QAAS,CAAC,EACzC,CAAC,OAAQ,CAAE,EAAG,iBAAkB,IAAK,QAAS,CAAC,CACjD,CACF,EACAA,GAAW,KACX,IAAMC,GAAYC,EAAiBF,EAAU,ECTvCA,GAAa,CACjB,KAAM,cACN,KAAM,GACN,KAAM,CACJ,CAAC,OAAQ,CAAE,EAAG,WAAY,IA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Columns3","GripVertical","List","Map","SquareKanban","text","messages","MailboxConnect","signInProviders","useOptionalAuth","busy","setBusy","useState","error","setError","expired","problem","names","offers","offer","signInName","entry","provider","providerName","connect","onConnect","id","failure","AuthError","authMessage","import_jsx_runtime","ActionCard","link","again","codes","mailboxProblem","isApiError","code","mailboxOffers","named","links","linked","useMailboxOffers","auth","wanted","check","setLinked","account","import_react","shown","mail","providers","useActionMailbox","action","offered","ownBoxes","held","input","record","box","checklistBoxes","records","answersFor","values","name","value","inputs","ChecklistInput","describedBy","invalid","useFieldControl","boxes","toggle","onChange","on","ticked","label","Checkbox","masked","SecretInput","Input","event","mask","secretAnswers","covered","hidden","secret","secrets","at","maskSecrets","index","maskedFailure","escaped","ApiError","maskedMessages","message","fieldTypes","inputField","base","option","inputHints","startingAnswers","toDraft","answerOf","isChosen","toPatchValue","answeredValues","all","draft","shownInputs","decimal","date","refusal","left","refusedAnswers","reason","InputEditor","useAdminMeta","useProjectUi","Custom","components","target","resources","FieldEditor","views","ActionInputsDialog","setDraft","errors","setErrors","setFailure","running","setRunning","formId","useId","mailbox","submit","refused","onSubmit","inputErrors","change","_","rest","current","ResponsiveDialog","onCancel","_Fragment","Button","danger","ErrorBanner","Field","next","ConfirmAction","Dialog","onConfirm","isDanger","asksFirst","ActionPrompt","useMailboxToastAction","toast","useToast","actionApplies","condition","parseCondition","evaluateCondition","fillHref","fillText","href","valueText","recordValueAt","path","webUrl","url","linkTarget","field","hrefField","openLink","hostOf","holdsAll","actionFor","run","resourceField","to","fillAddress","hostPlaceholder","runEach","verdicts","verdict","outcome","quoted","title","useActionRunner","handlers","permissions","usePermissions","resource","client","useClient","handlerClient","useResourceClient","mailboxAction","refresh","useRefreshResource","useAppAddress","titleOf","useRecordTitle","actions","scope","blockedOn","kind","can","custom","blocked","refusedOn","execute","go","updateValues","perform","afterRun","appliesOn","verdictOn","answers","skipped","description","useRunAction","runner","where","createWhere","slot","colorOf","key","color","valueColor","hints","labelOf","group","enumLabel","groupFilter","own","printFilter","filter","measured","measure","valueSlices","groups","periodPoints","measureText","formatTag","decimals","labelFieldOf","chartAggregate","model","groupBy","dated","splitField","splitBy","splitLabel","split","params","viewerZone","sum","average","filteredListAddress","view","GroupBars","largest","slices","slice","share","AppLink","PeriodChart","lazyComponent","__vitePreload","module","Skeleton","compact","GroupDonut","noise","splitPoints","series","splits","missing","partOf","part","candidate","points","parts","entries","point","measureOf","ChartView","result","useAggregate","empty","chartType","type","granularity","snapRowGap","snapItemWidth","snapItemSize","arrowClass","SnapRow","size","scroll","ChevronLeft","ChevronRight","list","watch","same","a","b","useSnapScroll","setList","scrolled","setScrolled","read","latest","useRef","changed","observer","gap","direction","cutOffNote","total","estimated","prefix","embeddedDisplayKey","place","readPickedDisplay","guarded","storage","writePickedDisplay","display","embeddedDisplay","displayChoices","choice","picked","defaultDisplay","xs","preferred","viewAllAddress","changedList","listDefaults","plannedCount","planned","isEmpty","httpsUrl","plainValue","followableFilter","models","parsed","parseFilter","checkFilter","rowButtonFor","rowButtonChoices","button","rowButtonChoiceFields","displayValue","rowButtonTarget","filterField","bareFilterFields","RowButtonLink","style","cn","buttonClass","ExternalLink","features","tableFeatures","helper","createColumnHelper","buildColumns","specs","spec","row","context","renderCell","offeredBulkActions","rows","selected","runBulkAction","open","kept","oneBulkRunAtATime","GridFooter","className","formatApproxRows","selectedCount","formatInt","bulkActions","availableActions","RowMenu","usePopoverMenu","setOpen","MoreHorizontal","createPortal","menu","itemClass","RouteLink","gutterWidthFor","desktopMinScale","minWidthOf","minScale","columnTemplate","gridTemplate","gutter","trailing","gridMinWidth","useHorizontalScroll","ref","edges","setEdges","useCallback","element","child","pinnedStorageKey","userId","readPinned","raw","writePinned","pinned","usePinnedColumns","chosen","setChosen","storageKey","update","initial","defaultPins","sizesOf","fitKey","columns","minWidth","maxWidth","useFittedColumns","fitted","setFitted","fitColumns","sizes","useMemo","resizedWidth","start","delta","withResizedWidths","widths","measuredWidths","header","cell","useColumnResize","setWidths","startWidths","startX","onMove","move","onEnd","rootFontSize","useRootFontSize","useSyncExternalStore","compactRow","below","footer","gridHeights","rem","withBelow","isRightAligned","unsortableText","HeaderMenu","sortable","onTogglePin","ResizeHandle","width","resize","SortIcon","sorted","ChevronsUpDown","HeaderLabel","GridHeader","lastPinned","selectable","onClearSelection","cells","pins","onSort","frameStyle","frame","cellClass","pinStyle","Gutter","onToggle","edge","dragStyle","dragY","openUnlessLink","onOpen","DataRow","rowRef","dragging","transition","handle","props","editable","editing","content","skeletonWidths","SkeletonRow","column","maxContentHeight","gridGeometry","trueHeight","rowHeight","contentHeight","viewportHeight","topFromScroll","geometry","position","scrollFromTop","top","rowOffset","offset","rowsInView","first","overscan","last","height","scrollParent","page","parent","isPage","scroller","scrollEvents","padding","visibleArea","viewRows","useVirtualRows","setView","options","area","before","after","onScroll","sameRows","begin","initialIndex","events","scrollTo","started","drawn","settle","isMoveKey","movedCell","nextEditable","from","placeId","useCellEditing","active","setActive","setEditing","refocus","pressedChosen","container","editor","editableAt","rowAt","choose","edit","close","focused","reachable","onOpenRow","ReorderRows","sensors","useSensors","useSensor","MouseSensor","TouchSensor","KeyboardSensor","sortableKeyboardCoordinates","ids","reorder","DndContext","closestCenter","over","SortableContext","verticalListSortingStrategy","SortableRow","useSortable","setActivatorNodeRef","attributes","listeners","setNodeRef","transform","isDragging","DataGrid","given","controlledSort","selecting","headerHeight","footerHeight","narrow","useIsDesktop","pinsByDefault","defaultPinned","setPinned","pinKey","pinnedIds","source","localSorting","setLocalSorting","naturalSort","sorting","setSorting","updater","onSortChange","rowSelection","setRowSelection","tableColumns","sort","reverse","sourceRowAt","startIndex","initialScrollIndex","virtualRows","firstIndex","lastIndex","onScrollIndex","rowNumbers","getRow","usePagedRows","patchedRow","patch","rowPatches","loaded","data","headerRef","sized","table","useTable","tableRows","selectedRows","rowActions","horizontal","onBodyScroll","setPins","togglePin","headerCells","gridRef","cellEditing","cellEditor","linkColumn","fit","tableRow","chosenRow","rowLink","stacked","body","done","chipClass","FilterChipList","chips","chip","InlineFilterChips","chipsText","defaultDatePresets","knownPresets","datePresetLabel","emptyFilterState","toggleFacetValue","state","toggleFlag","setRange","others","facetLabel","activeChips","facetChips","config","rangeChips","span","range","dateChips","toggleChips","removeChip","matchesSearch","query","w","relative","iso","ms","periodStart","today","dayIn","now","zone","year","month","day","preset","calendarPresets","dayLiteral","startOfDayIn","instant","span$1","dateClauses","stateToClauses","facets","ranges","toggles","clausesToText","clauses","stateToText","extras","flatten","expr","fieldName","isTrue","flagsChosen","clause","fields","groupOf","literalText","presetOf","v","d","amount","unit","textToState","facetIds","flagGroupOf","toggleIds","rangeIds","bounds","dateClause","todayEnd","flags","numberTypes","isNumber","rangeOf","widget","secondaryOf","emptyRange","widgetFields","widgets","rangeHistogram","rangeFormat","suffix","currency","formatMoney","chosenRelations","namedConfig","humanize","skeleton","labels","filterChips","facetNames","unseenFilter","seenAt","isUnseen","useFilterChips","queryClient","useQueryClient","useQueries","keys","fetchLabels","RelationTitleText","useRelationTitle","relationValue","savedRecordsOf","encodeKey","recordKey","savedFor","saved","withSaved","withoutSaved","savedScope","savedRecordsKey","useSavedRecords","useQuery","enabled","pageToken","useFavorite","meta","favorite","usable","prompt","cacheKey","useMutation","existing","FavoriteButton","prompting","setPrompting","Heart","SignInPrompt","placeCard","dot","card","viewport","dotCard","cards","displaysOf","status","__","___","relatedColumnLoads","shownFields","dotsSummary","statuses","counts","singular","plural","dotBox","dotMark","dotsLine","hideMs","cardWidth","DotCardPopover","setPlace","onEnter","onLeave","Card","RelatedDots","displayRow","setShown","hideTimer","pointer","statusText","titleField","recordTitleField","summary","cancelHide","hideSoon","show","hide","outside","tap","blur","shownRow","wrap","toneDots","valueTone","DotsRoom","count","lines","CardDotsRoom","dots","CardDots","cardDotsLines","CardPhoto","image","shownImage","FileImage","CardImageFrame","CardImage","maxCardDots","cardPhotoList","coverUri","isStoredFile","cover","photos","photo","CardCarousel","carousel","useCarousel","picture","CarouselTrack","children","CarouselControls","MetaValue","Icon","namedIcon","icon","RecordCard","cardFields","isMarkdown","markdownExcerpt","jsonSummary","linkTextOf","seedRecord","useSeedRecord","shownValue","shownWidget","WidgetPart","subtitleValue","Markdown","metaValue","ValueBadge","amountValue","amountParts","badge","raised","shownAmount","filledAmount","shownCode","filledCode","footing","filledMeta","pictured","builtIn","subtitle","CodeBlock","rawCode","Badge","mark","CustomBoundary","rowCardGap","rowWindow","step","scrollLeft","placesAround","rowPlaces","end","rowSpan","Spacer","RecordRow","places","isNew","scoped","recordRowRead","loadedFields","defaultOrderBy","rowDisplay","Loading","RecordRowBody","showChips","useIsXs","useLiveRows","limit","note","viewAll","savedSearchesKey","useSavedSearches","useSearchRow","of","stored","unseen","markSeen","newCount","countQuery","targetView","DisplayState","loading","DisplayFooter","grid","CardsDisplay","CustomDisplay","Component","ListDisplayProvider","unmarkFieldRefs","Problem","worldArea","maxZoom","down","degrees","up","wrapped","longitude","boundsFilter","latitude","west","east","areaFilter","inside","listFilter","requestZoom","zoom","boundsAround","corners","buckets","bucket","corner","numeric","recordPosition","earthRadius","circleCorners","isApproximate","circleArea","distance","metres","center","bearing","isPosition","isLine","least","isPolygon","ring","isLines","line","areaGeometry","coordinates","positionArea","radius","mapPoints","groupPoints","near","keptSelection","selection","present","stepSelection","useMapRecords","orderBy","keepPreviousData","listLabels","listPhotos","withLabels","withPhotos","RecordsMap","lazy","settleMs","arrow","MapDisplay","maps","setArea","settled","useDebounced","fitting","setFitting","mapCards","approximate","markerLabel","bucketLabel","overlay","setCovered","flush","Suspense","X","inView","BoardDisplay","CalendarDisplay","TimelineDisplay","icons","Table2","LayoutGrid","Calendar","MapIcon","DisplaySwitch","choices","MenuSelect","Segmented","directions","SortMenu","parseSort","sortFields","word","labelCharWidth","buttonFrame","outsideMark","rowButtonMaxWidth","recordOf","rowButton","rowButtonWidth","rowButtonColumn","withRowButton","opensTo","relatedOpens","item","candidates","relationTarget","singularOf","embeddedRowTargets","farName","opens","far","other","address","openOwn","linkTo","canUpdate","rowAllows","actionLink","rowRecord","useListActions","app","asking","setAsking","listed","available","embeddedRowsQuery","seedTitleRows","recordId","useEmbeddedRows","request","plannedEmbeddedRows","isPending","EmbeddedDisplaySwitch","EmbeddedList","initialOrder","setOrderBy","embeddedFields","bulk","phoneColumns","gridColumns","fromPlan","plannedRows","shownDisplay","allLink","withPrompt","nothing","targets","keyOf","rowTarget","rowTo","chosenKey","sortToOrderBy"],"ignoreList":[0,1,2,3,4,5,6,7,8,9],"sources":["../../../../../node_modules/.bun/lucide-react@1.52.0+0ac650c021fb1b59/node_modules/lucide-react/dist/esm/icons/arrow-down.mjs","../../../../../node_modules/.bun/lucide-react@1.52.0+0ac650c021fb1b59/node_modules/lucide-react/dist/esm/icons/arrow-right.mjs","../../../../../node_modules/.bun/lucide-react@1.52.0+0ac650c021fb1b59/node_modules/lucide-react/dist/esm/icons/arrow-up.mjs","../../../../../node_modules/.bun/lucide-react@1.52.0+0ac650c021fb1b59/node_modules/lucide-react/dist/esm/icons/chart-gantt.mjs","../../../../../node_modules/.bun/lucide-react@1.52.0+0ac650c021fb1b59/node_modules/lucide-react/dist/esm/icons/circle-dashed.mjs","../../../../../node_modules/.bun/lucide-react@1.52.0+0ac650c021fb1b59/node_modules/lucide-react/dist/esm/icons/columns-3.mjs","../../../../../node_modules/.bun/lucide-react@1.52.0+0ac650c021fb1b59/node_modules/lucide-react/dist/esm/icons/grip-vertical.mjs","../../../../../node_modules/.bun/lucide-react@1.52.0+0ac650c021fb1b59/node_modules/lucide-react/dist/esm/icons/list.mjs","../../../../../node_modules/.bun/lucide-react@1.52.0+0ac650c021fb1b59/node_modules/lucide-react/dist/esm/icons/map.mjs","../../../../../node_modules/.bun/lucide-react@1.52.0+0ac650c021fb1b59/node_modules/lucide-react/dist/esm/icons/square-kanban.mjs","../../../src/mailbox/messages.ts","../../../src/mailbox/mailbox-connect.tsx","../../../src/mailbox/mailbox-problem.ts","../../../src/mailbox/mailbox-offers.ts","../../../src/mailbox/use-mailbox-offers.ts","../../../src/mailbox/use-action-mailbox.tsx","../../../src/app/pages/action-inputs/checklist-boxes.ts","../../../src/app/pages/action-inputs/checklist-input.tsx","../../../src/app/pages/action-inputs/secret-input.tsx","../../../src/app/pages/action-inputs/secret-mask.ts","../../../src/app/pages/action-inputs/input-answers.ts","../../../src/app/pages/action-inputs/action-inputs-dialog.tsx","../../../src/app/pages/confirm-action.tsx","../../../src/app/pages/action-prompt.tsx","../../../src/mailbox/use-mailbox-toast-action.ts","../../../src/app/pages/action-when.ts","../../../src/app/pages/action-href.ts","../../../src/app/pages/run-each.ts","../../../src/app/pages/use-run-action.ts","../../../src/app/list-messages.ts","../../../src/app/charts/messages.ts","../../../src/app/charts/chart-groups.ts","../../../src/app/charts/chart-params.ts","../../../src/app/list-link.ts","../../../src/app/charts/group-bars.tsx","../../../src/app/charts/lazy-charts.tsx","../../../src/app/charts/split-points.ts","../../../src/app/charts/chart-view.tsx","../../../src/primitives/snap-row-width.ts","../../../src/primitives/snap-row.tsx","../../../src/primitives/use-snap-scroll.ts","../../../src/app/embedded-list/messages.ts","../../../src/app/embedded-list/cut-off-note.ts","../../../src/app/embedded-list/embedded-display.ts","../../../src/app/pages/planned-count.ts","../../../src/app/row-button/row-button-for.ts","../../../src/app/row-button/row-button-link.tsx","../../../src/data-grid/columns.ts","../../../src/data-grid/bulk-actions.ts","../../../src/data-grid/grid-footer.tsx","../../../src/data-grid/row-menu.tsx","../../../src/data-grid/grid-template.ts","../../../src/data-grid/use-horizontal-scroll.ts","../../../src/data-grid/pinned-storage.ts","../../../src/data-grid/use-pinned-columns.ts","../../../src/data-grid/default-pins.ts","../../../src/data-grid/use-fitted-columns.ts","../../../src/data-grid/column-resize.ts","../../../src/data-grid/use-column-resize.ts","../../../src/lib/use-root-font-size.ts","../../../src/data-grid/grid-heights.ts","../../../src/data-grid/column-spec.ts","../../../src/data-grid/header-menu.tsx","../../../src/data-grid/resize-handle.tsx","../../../src/data-grid/grid-header.tsx","../../../src/data-grid/grid-row.tsx","../../../src/data-grid/geometry.ts","../../../src/data-grid/scroll-parent.ts","../../../src/data-grid/use-virtual-rows.ts","../../../src/data-grid/cell-moves.ts","../../../src/data-grid/use-cell-editing.tsx","../../../src/data-grid/row-reorder.tsx","../../../src/data-grid/data-grid.tsx","../../../src/app/searches/messages.ts","../../../src/app/searches/filter-chip-list.tsx","../../../src/filter-panel/messages.ts","../../../src/filter-panel/filter-config.ts","../../../src/filter-panel/filter-state.ts","../../../src/live/filter-string.ts","../../../src/live/view-fields.ts","../../../src/app/searches/saved-search.ts","../../../src/app/searches/use-filter-chips.ts","../../../src/app/titles/relation-title-text.tsx","../../../src/app/saved/saved-records.ts","../../../src/app/saved/use-saved-records.ts","../../../src/app/saved/messages.ts","../../../src/app/saved/use-favorite.ts","../../../src/app/saved/favorite-button.tsx","../../../src/app/related-dots/card-place.ts","../../../src/app/related-dots/dot-card.ts","../../../src/app/related-dots/messages.ts","../../../src/app/related-dots/dots-summary.ts","../../../src/app/related-dots/related-dots.tsx","../../../src/app/related-dots/card-dots.tsx","../../../src/app/related-dots/card-dots-lines.ts","../../../src/app/displays/card-image.tsx","../../../src/app/displays/card-photos.ts","../../../src/app/displays/card-carousel.tsx","../../../src/app/displays/record-card.tsx","../../../src/app/record-row/row-window.ts","../../../src/app/record-row/messages.ts","../../../src/app/record-row/record-row.tsx","../../../src/app/record-row/record-row-read.ts","../../../src/app/record-row/record-row-body.tsx","../../../src/app/searches/use-saved-searches.ts","../../../src/app/searches/use-search-row.ts","../../../src/app/displays/display-frame.tsx","../../../src/app/displays/cards-display.tsx","../../../src/app/displays/custom-display.tsx","../../../src/app/map/map-area.ts","../../../src/app/map/record-position.ts","../../../src/app/map/approximate-position.ts","../../../src/app/displays/map-groups.ts","../../../src/app/displays/use-map-records.ts","../../../src/app/displays/map-display.tsx","../../../src/app/displays/lazy-displays.tsx","../../../src/app/displays/display-controls.tsx","../../../src/app/row-button/row-button-column.tsx","../../../src/app/related-opens.ts","../../../src/app/embedded-list/embedded-row-targets.ts","../../../src/app/pages/action-link.ts","../../../src/app/list-actions/row-record.ts","../../../src/app/list-actions/use-list-actions.tsx","../../../src/app/embedded-list/use-embedded-rows.ts","../../../src/app/embedded-list/planned-embedded-rows.ts","../../../src/app/embedded-list/embedded-list.tsx"],"sourcesContent":["/**\n * @license lucide-react v1.52.0 - ISC\n *\n * This source code is licensed under the ISC license.\n * See the LICENSE file in the root directory of this source tree.\n */\n\nimport createLucideIcon from '../createLucideIcon.mjs';\n\nconst __iconData = {\n name: \"arrow-down\",\n size: 24,\n node: [\n [\"path\", { d: \"M12 5v14\", key: \"s699le\" }],\n [\"path\", { d: \"m19 12-7 7-7-7\", key: \"1idqje\" }]\n ]\n};\n__iconData.node;\nconst ArrowDown = createLucideIcon(__iconData);\n\nexport { __iconData, ArrowDown as default };\n//# sourceMappingURL=arrow-down.mjs.map\n","/**\n * @license lucide-react v1.52.0 - ISC\n *\n * This source code is licensed under the ISC license.\n * See the LICENSE file in the root directory of this source tree.\n */\n\nimport createLucideIcon from '../createLucideIcon.mjs';\n\nconst __iconData = {\n name: \"arrow-right\",\n size: 24,\n node: [\n [\"path\", { d: \"M5 12h14\", key: \"1ays0h\" }],\n [\"path\", { d: \"m12 5 7 7-7 7\", key: \"xquz4c\" }]\n ]\n};\n__iconData.node;\nconst ArrowRight = createLucideIcon(__iconData);\n\nexport { __iconData, ArrowRight as default };\n//# sourceMappingURL=arrow-right.mjs.map\n","/**\n * @license lucide-react v1.52.0 - ISC\n *\n * This source code is licensed under the ISC license.\n * See the LICENSE file in the root directory of this source tree.\n */\n\nimport createLucideIcon from '../createLucideIcon.mjs';\n\nconst __iconData = {\n name: \"arrow-up\",\n size: 24,\n node: [\n [\"path\", { d: \"m5 12 7-7 7 7\", key: \"hav0vg\" }],\n [\"path\", { d: \"M12 19V5\", key: \"x0mq9r\" }]\n ]\n};\n__iconData.node;\nconst ArrowUp = createLucideIcon(__iconData);\n\nexport { __iconData, ArrowUp as default };\n//# sourceMappingURL=arrow-up.mjs.map\n","/**\n * @license lucide-react v1.52.0 - ISC\n *\n * This source code is licensed under the ISC license.\n * See the LICENSE file in the root directory of this source tree.\n */\n\nimport createLucideIcon from '../createLucideIcon.mjs';\n\nconst __iconData = {\n name: \"chart-gantt\",\n size: 24,\n node: [\n [\"path\", { d: \"M10 6h8\", key: \"zvc2xc\" }],\n [\"path\", { d: \"M12 16h6\", key: \"yi5mkt\" }],\n [\"path\", { d: \"M3 3v16a2 2 0 0 0 2 2h16\", key: \"c24i48\" }],\n [\"path\", { d: \"M8 11h7\", key: \"wz2hg0\" }]\n ]\n};\n__iconData.node;\nconst ChartGantt = createLucideIcon(__iconData);\n\nexport { __iconData, ChartGantt as default };\n//# sourceMappingURL=chart-gantt.mjs.map\n","/**\n * @license lucide-react v1.52.0 - ISC\n *\n * This source code is licensed under the ISC license.\n * See the LICENSE file in the root directory of this source tree.\n */\n\nimport createLucideIcon from '../createLucideIcon.mjs';\n\nconst __iconData = {\n name: \"circle-dashed\",\n size: 24,\n node: [\n [\"path\", { d: \"M10.1 2.182a10 10 0 0 1 3.8 0\", key: \"5ilxe3\" }],\n [\"path\", { d: \"M13.9 21.818a10 10 0 0 1-3.8 0\", key: \"11zvb9\" }],\n [\"path\", { d: \"M17.609 3.721a10 10 0 0 1 2.69 2.7\", key: \"1iw5b2\" }],\n [\"path\", { d: \"M2.182 13.9a10 10 0 0 1 0-3.8\", key: \"c0bmvh\" }],\n [\"path\", { d: \"M20.279 17.609a10 10 0 0 1-2.7 2.69\", key: \"1ruxm7\" }],\n [\"path\", { d: \"M21.818 10.1a10 10 0 0 1 0 3.8\", key: \"qkgqxc\" }],\n [\"path\", { d: \"M3.721 6.391a10 10 0 0 1 2.7-2.69\", key: \"1mcia2\" }],\n [\"path\", { d: \"M6.391 20.279a10 10 0 0 1-2.69-2.7\", key: \"1fvljs\" }]\n ]\n};\n__iconData.node;\nconst CircleDashed = createLucideIcon(__iconData);\n\nexport { __iconData, CircleDashed as default };\n//# sourceMappingURL=circle-dashed.mjs.map\n","/**\n * @license lucide-react v1.52.0 - ISC\n *\n * This source code is licensed under the ISC license.\n * See the LICENSE file in the root directory of this source tree.\n */\n\nimport createLucideIcon from '../createLucideIcon.mjs';\n\nconst __iconData = {\n name: \"columns-3\",\n size: 24,\n node: [\n [\"rect\", { width: \"18\", height: \"18\", x: \"3\", y: \"3\", rx: \"2\", key: \"afitv7\" }],\n [\"path\", { d: \"M9 3v18\", key: \"fh3hqa\" }],\n [\"path\", { d: \"M15 3v18\", key: \"14nvp0\" }]\n ],\n aliases: [\"panels-left-right\"]\n};\n__iconData.node;\nconst Columns3 = createLucideIcon(__iconData);\n\nexport { __iconData, Columns3 as default };\n//# sourceMappingURL=columns-3.mjs.map\n","/**\n * @license lucide-react v1.52.0 - ISC\n *\n * This source code is licensed under the ISC license.\n * See the LICENSE file in the root directory of this source tree.\n */\n\nimport createLucideIcon from '../createLucideIcon.mjs';\n\nconst __iconData = {\n name: \"grip-vertical\",\n size: 24,\n node: [\n [\"circle\", { cx: \"9\", cy: \"12\", r: \"1\", key: \"1vctgf\" }],\n [\"circle\", { cx: \"9\", cy: \"5\", r: \"1\", key: \"hp0tcf\" }],\n [\"circle\", { cx: \"9\", cy: \"19\", r: \"1\", key: \"fkjjf6\" }],\n [\"circle\", { cx: \"15\", cy: \"12\", r: \"1\", key: \"1tmaij\" }],\n [\"circle\", { cx: \"15\", cy: \"5\", r: \"1\", key: \"19l28e\" }],\n [\"circle\", { cx: \"15\", cy: \"19\", r: \"1\", key: \"f4zoj3\" }]\n ]\n};\n__iconData.node;\nconst GripVertical = createLucideIcon(__iconData);\n\nexport { __iconData, GripVertical as default };\n//# sourceMappingURL=grip-vertical.mjs.map\n","/**\n * @license lucide-react v1.52.0 - ISC\n *\n * This source code is licensed under the ISC license.\n * See the LICENSE file in the root directory of this source tree.\n */\n\nimport createLucideIcon from '../createLucideIcon.mjs';\n\nconst __iconData = {\n name: \"list\",\n size: 24,\n node: [\n [\"path\", { d: \"M3 5h.01\", key: \"18ugdj\" }],\n [\"path\", { d: \"M3 12h.01\", key: \"nlz23k\" }],\n [\"path\", { d: \"M3 19h.01\", key: \"noohij\" }],\n [\"path\", { d: \"M8 5h13\", key: \"1pao27\" }],\n [\"path\", { d: \"M8 12h13\", key: \"1za7za\" }],\n [\"path\", { d: \"M8 19h13\", key: \"m83p4d\" }]\n ]\n};\n__iconData.node;\nconst List = createLucideIcon(__iconData);\n\nexport { __iconData, List as default };\n//# sourceMappingURL=list.mjs.map\n","/**\n * @license lucide-react v1.52.0 - ISC\n *\n * This source code is licensed under the ISC license.\n * See the LICENSE file in the root directory of this source tree.\n */\n\nimport createLucideIcon from '../createLucideIcon.mjs';\n\nconst __iconData = {\n name: \"map\",\n size: 24,\n node: [\n [\n \"path\",\n {\n d: \"M14.106 5.553a2 2 0 0 0 1.788 0l3.659-1.83A1 1 0 0 1 21 4.619v12.764a1 1 0 0 1-.553.894l-4.553 2.277a2 2 0 0 1-1.788 0l-4.212-2.106a2 2 0 0 0-1.788 0l-3.659 1.83A1 1 0 0 1 3 19.381V6.618a1 1 0 0 1 .553-.894l4.553-2.277a2 2 0 0 1 1.788 0z\",\n key: \"169xi5\"\n }\n ],\n [\"path\", { d: \"M15 5.764v15\", key: \"1pn4in\" }],\n [\"path\", { d: \"M9 3.236v15\", key: \"1uimfh\" }]\n ]\n};\n__iconData.node;\nconst Map = createLucideIcon(__iconData);\n\nexport { __iconData, Map as default };\n//# sourceMappingURL=map.mjs.map\n","/**\n * @license lucide-react v1.52.0 - ISC\n *\n * This source code is licensed under the ISC license.\n * See the LICENSE file in the root directory of this source tree.\n */\n\nimport createLucideIcon from '../createLucideIcon.mjs';\n\nconst __iconData = {\n name: \"square-kanban\",\n size: 24,\n node: [\n [\"rect\", { width: \"18\", height: \"18\", x: \"3\", y: \"3\", rx: \"2\", key: \"afitv7\" }],\n [\"path\", { d: \"M8 7v7\", key: \"1x2jlm\" }],\n [\"path\", { d: \"M12 7v4\", key: \"xawao1\" }],\n [\"path\", { d: \"M16 7v9\", key: \"1hp2iy\" }]\n ],\n aliases: [\"kanban-square\"]\n};\n__iconData.node;\nconst SquareKanban = createLucideIcon(__iconData);\n\nexport { __iconData, SquareKanban as default };\n//# sourceMappingURL=square-kanban.mjs.map\n","import { messages } from '../locale/messages'\n\nexport const text = messages('mailbox')\n","import { useState } from 'react'\nimport { AuthError } from '@protobase/client'\nimport { ActionCard } from '../action-card/action-card'\nimport { authMessage } from '../auth/auth-messages'\nimport { useOptionalAuth } from '../auth/auth-provider'\nimport { providerName } from '../auth/provider-link'\nimport type { MailboxOffer } from './mailbox-offers'\nimport type { MailboxProblem } from './mailbox-problem'\nimport { text } from './messages'\n\ntype MailboxConnectProps = {\n offers: MailboxOffer[]\n /** Why the send failed; none when it has not run yet, as no mailbox is linked. */\n problem?: MailboxProblem\n onConnect: (offer: MailboxOffer) => Promise<void>\n}\n\n/**\n * Why mail cannot go out from the person's own mailbox, with a button to connect each mailbox the app offers: it starts\n * the same sign-in as the account page's, which comes back to this page. A sign-in through the mailbox's provider that\n * did not allow sending mail is named, so it is not taken for a mailbox.\n */\nexport const MailboxConnect = ({ offers, problem, onConnect }: MailboxConnectProps) => {\n const signInProviders = useOptionalAuth()?.signInProviders ?? []\n const [busy, setBusy] = useState(false)\n const [error, setError] = useState<string>()\n const expired = problem?.code === 'link_expired'\n const names = offers.map((offer) => offer.link.name)\n const signInName = (provider: string) => signInProviders.find((entry) => entry.id === provider)?.name ?? providerName(provider)\n\n const connect = async (id: string) => {\n setBusy(true)\n setError(undefined)\n try {\n await onConnect(offers.find((offer) => offer.link.id === id)!)\n } catch (failure) {\n if (!(failure instanceof AuthError)) throw failure\n setError(authMessage(failure))\n setBusy(false)\n }\n }\n\n return (\n <ActionCard\n title={text(expired ? 'expiredTitle' : 'missingTitle')}\n tone=\"warning\"\n actions={offers.map(({ link, again }) => ({ id: link.id, label: text(again ? 'connectAgain' : 'connect', { name: link.name }), style: 'primary', disabled: busy }))}\n onAction={(id) => void connect(id)}\n >\n <div className=\"space-y-1 text-body\">\n <p>{text(expired ? 'expired' : 'missing', { names: names.join(', ') })}</p>\n {offers\n .filter((offer) => offer.signInOnly)\n .map(({ link }) => (\n <p key={link.id}>{text('signInOnly', { provider: signInName(link.provider), name: link.name })}</p>\n ))}\n {error && (\n <p role=\"alert\" className=\"font-medium text-danger-text\">\n {error}\n </p>\n )}\n </div>\n </ActionCard>\n )\n}\n","import { isApiError } from '@protobase/client'\n\n/** Why a message could not go out from the person's own mailbox, and the mail provider at fault when the server names one. */\nexport type MailboxProblem = { code: 'not_linked' | 'link_expired'; provider?: string }\n\nconst codes = new Map<string, MailboxProblem['code']>([\n ['personal-mail-not-linked', 'not_linked'],\n ['personal-mail-link-expired', 'link_expired'],\n])\n\n/** The mailbox problem a failed call answered with, as the server's personal mail reports it; none for any other failure. */\nexport const mailboxProblem = (error: unknown): MailboxProblem | undefined => {\n if (!isApiError(error)) return\n const code = codes.get(error.slug)\n if (!code) return\n const { provider } = error.problem\n return { code, ...(typeof provider === 'string' && { provider }) }\n}\n","import type { PersonalMailLink } from '@protobase/client'\nimport type { MailboxProblem } from './mailbox-problem'\n\n/**\n * A mailbox the person can connect: `again` when they linked it before and the link needs renewing, and `signInOnly`\n * when they sign in with its provider, such as Google, without having allowed it to send mail.\n */\nexport type MailboxOffer = { link: PersonalMailLink; again: boolean; signInOnly: boolean }\n\n/** What the person's account holds: the mail providers linked with leave to send (`mail`), and the sign-in providers linked (`providers`). */\nexport type LinkedAccounts = { mail: string[]; providers: string[] }\n\n/**\n * The mailboxes to offer for `problem`, or before a send while none is linked (no `problem`): an expired link offers its\n * provider's mailbox again, or every one when the server named none; a missing one offers each the app has.\n */\nexport const mailboxOffers = (links: PersonalMailLink[], linked: LinkedAccounts, problem?: MailboxProblem): MailboxOffer[] => {\n if (problem?.code === 'link_expired') {\n const named = links.filter((link) => link.id === problem.provider)\n return (named.length > 0 ? named : links).map((link) => ({ link, again: true, signInOnly: false }))\n }\n if (!problem && linked.mail.length > 0) return []\n return links.map((link) => {\n const again = linked.mail.includes(link.id)\n return { link, again, signInOnly: !again && linked.providers.includes(link.provider) }\n })\n}\n","import { useEffect, useState } from 'react'\nimport { AuthError } from '@protobase/client'\nimport { authMessage } from '../auth/auth-messages'\nimport { useOptionalAuth } from '../auth/auth-provider'\nimport { mailboxOffers, type LinkedAccounts, type MailboxOffer } from './mailbox-offers'\nimport type { MailboxProblem } from './mailbox-problem'\n\n/**\n * The mailboxes to offer the signed-in person for `problem`, or, with `check`, before a send while none is linked:\n * `undefined` while their linked accounts are read, none in an app without personal mail. `error` says why they could\n * not be read; `connect` leaves to link one, coming back to this page.\n */\nexport const useMailboxOffers = (problem: MailboxProblem | undefined, check: boolean) => {\n const auth = useOptionalAuth()\n const links = auth?.personalMail ?? []\n const wanted = auth !== null && links.length > 0 && (check || problem !== undefined)\n const [linked, setLinked] = useState<LinkedAccounts>()\n const [error, setError] = useState<string>()\n const account = auth?.session.account\n\n useEffect(() => {\n if (!wanted || !account) return\n let shown = true\n Promise.all([account.linkedPersonalMail(links), account.linkedProviders()]).then(\n ([mail, providers]) => {\n if (shown) setLinked({ mail, providers })\n },\n (failure: unknown) => {\n if (!(failure instanceof AuthError)) throw failure\n if (shown) setError(authMessage(failure))\n },\n )\n return () => {\n shown = false\n }\n }, [wanted, account, links])\n\n const connect = (offer: MailboxOffer) => auth!.linkPersonalMail(offer.link)\n if (!wanted) return { offers: [] as MailboxOffer[], connect }\n if (error) return { offers: [] as MailboxOffer[], error, connect }\n return { offers: linked && mailboxOffers(links, linked, problem), connect }\n}\n","import type { ActionModel } from '@protobase/schema'\nimport { MailboxConnect } from './mailbox-connect'\nimport { mailboxProblem } from './mailbox-problem'\nimport { useMailboxOffers } from './use-mailbox-offers'\n\n/**\n * The mailbox part of an action's dialog: for an action that sends from the person's own mailbox (`mailbox: true`),\n * an offer to connect one while none is linked; for any action whose run failed for want of a mailbox, or as its link\n * expired, the same offer for that. `notice` is the offer, which stands in for the failure's banner (`explained`), and\n * `blocked` keeps the action from running while the mailbox is checked or still needs connecting.\n */\nexport const useActionMailbox = (action: ActionModel, failure: unknown) => {\n const problem = mailboxProblem(failure)\n const check = action.mailbox === true\n const { offers, error, connect } = useMailboxOffers(problem, check)\n const offered = offers !== undefined && offers.length > 0\n const notice = offered ? (\n <MailboxConnect offers={offers} problem={problem} onConnect={connect} />\n ) : error ? (\n <p role=\"alert\" className=\"text-body font-medium text-danger-text\">\n {error}\n </p>\n ) : undefined\n return { notice, explained: problem !== undefined && offered, blocked: offered || (check && offers === undefined) }\n}\n","import type { ActionInputModel } from '@protobase/schema'\n\ntype Fields = Record<string, unknown>\n\n// The texts a record holds in a checklist's `from` field; anything but a list of texts holds none.\nconst ownBoxes = (input: ActionInputModel, record: Fields | undefined) => {\n const held = input.from === undefined ? undefined : record?.[input.from]\n return Array.isArray(held) ? held.filter((box): box is string => typeof box === 'string') : []\n}\n\n/** The boxes a checklist shows for the records an action runs on: its `items`, or each box their `from` field holds, once, in order. */\nexport const checklistBoxes = (input: ActionInputModel, records: Fields[]) => {\n if (input.items) return input.items\n return [...new Set(records.flatMap((record) => ownBoxes(input, record)))]\n}\n\n/**\n * The answers as `record` gets them: each checklist that shows answers the boxes this record holds, its `items` or its\n * own `from` boxes, every one ticked before the action runs.\n */\nexport const answersFor = (inputs: ActionInputModel[], values: Record<string, unknown>, record: Fields | undefined) =>\n Object.fromEntries(\n Object.entries(values).map(([name, value]) => {\n const input = inputs.find((entry) => entry.name === name)\n if (input?.kind !== 'checklist') return [name, value]\n return [name, input.items ?? ownBoxes(input, record)]\n }),\n )\n","import { Checkbox } from '../../../primitives/checkbox'\nimport { useFieldControl } from '../../../primitives/field-control'\nimport { text } from '../messages'\n\ntype ChecklistInputProps = { label: string; boxes: string[]; ticked: string[]; onChange: (ticked: string[]) => void }\n\n/**\n * A checklist's boxes, each ticked by its checkbox or its text, as a group named by its label and described by the help\n * and error of the `Field` around it; or a line saying there is nothing to tick.\n */\nexport const ChecklistInput = ({ label, boxes, ticked, onChange }: ChecklistInputProps) => {\n const { id, 'aria-describedby': describedBy, 'aria-invalid': invalid } = useFieldControl()\n if (boxes.length === 0) return <p className=\"text-sm text-muted-foreground\">{text('nothingToTick')}</p>\n const toggle = (box: string, on: boolean) => onChange(on ? [...ticked, box] : ticked.filter((entry) => entry !== box))\n return (\n <div id={id} role=\"group\" aria-label={label} aria-describedby={describedBy} aria-invalid={invalid}>\n <ul className=\"flex flex-col gap-1\">\n {boxes.map((box) => (\n <li key={box}>\n <label className=\"flex cursor-pointer items-start gap-3 rounded py-1.5 text-sm active:opacity-70\">\n <Checkbox checked={ticked.includes(box)} onChange={(on) => toggle(box, on)} className=\"mt-0.5\" />\n <span>{box}</span>\n </label>\n </li>\n ))}\n </ul>\n </div>\n )\n}\n","import type { CSSProperties } from 'react'\nimport { Input } from '../../../primitives/input'\n\n// csstype has no key for it; every current browser engine draws it.\nconst masked: CSSProperties & { WebkitTextSecurity: 'disc' } = { WebkitTextSecurity: 'disc' }\n\ntype SecretInputProps = { name: string; value: string; invalid: boolean; onChange: (value: string) => void }\n\n/**\n * A secret input's field. Not a password input: browsers offer to save the value of any password input, and some to\n * generate one. Instead a text input drawn as discs, so the value never shows on screen. `autocomplete=\"off\"` keeps it\n * out of the browser's form history and saved session, which keep a text input's value as they never do a password's.\n * Its type never changes at runtime, so no show/hide toggle: a browser may treat an input that was ever a password as\n * one. The data attributes ask password managers and writing assistants, in each one's documented words, to skip the\n * field, and the autocorrect ones keep keyboards out.\n */\nexport const SecretInput = ({ name, value, invalid, onChange }: SecretInputProps) => (\n <Input\n type=\"text\"\n name={name}\n autoComplete=\"off\"\n style={masked}\n autoCorrect=\"off\"\n autoCapitalize=\"off\"\n spellCheck={false}\n data-1p-ignore\n data-lpignore=\"true\"\n data-bwignore\n data-form-type=\"other\"\n data-gramm=\"false\"\n data-gramm_editor=\"false\"\n data-enable-grammarly=\"false\"\n value={value}\n invalid={invalid}\n onChange={(event) => onChange(event.target.value)}\n />\n)\n","import { ApiError, isApiError } from '@protobase/client'\nimport type { ActionInputModel } from '@protobase/schema'\n\nconst mask = '••••••'\n\n/** The answers of the secret inputs among `values`, those not empty. */\nexport const secretAnswers = (inputs: ActionInputModel[], values: Record<string, unknown>) =>\n inputs.flatMap((input) => {\n const value = values[input.name]\n return input.kind === 'secret' && typeof value === 'string' && value !== '' ? [value] : []\n })\n\n// Which characters of `text` belong to an occurrence of a secret, every occurrence found in the text as it is, overlaps included.\nconst covered = (text: string, secrets: string[]) => {\n const hidden = new Array<boolean>(text.length).fill(false)\n for (const secret of secrets) {\n for (let at = text.indexOf(secret); at !== -1; at = text.indexOf(secret, at + 1)) hidden.fill(true, at, at + secret.length)\n }\n return hidden\n}\n\n/** `text` with each run of characters that belongs to one of `secrets` replaced by discs, so overlapping secrets leave none of either showing. */\nexport const maskSecrets = (text: string, secrets: string[]) => {\n const hidden = covered(text, secrets.filter((secret) => secret !== ''))\n let masked = ''\n for (let index = 0; index < text.length; index++) {\n if (!hidden[index]) masked += text[index]\n else if (index === 0 || !hidden[index - 1]) masked += mask\n }\n return masked\n}\n\n/**\n * A failure as the dialog may show it: one whose message or problem holds a secret answer comes back with each masked,\n * so a handler that echoes the value never draws it on screen.\n */\nexport const maskedFailure = (error: unknown, secrets: string[]) => {\n if (secrets.length === 0) return error\n if (isApiError(error)) {\n // The problem is masked as JSON, where a secret appears in its escaped form.\n const escaped = secrets.map((secret) => JSON.stringify(secret).slice(1, -1))\n return new ApiError(JSON.parse(maskSecrets(JSON.stringify(error.problem), escaped)))\n }\n if (!(error instanceof Error)) return error\n const masked = new Error(maskSecrets(error.message, secrets))\n masked.name = error.name\n return masked\n}\n\n/** Messages by input name, each with the secret answers masked. */\nexport const maskedMessages = (messages: Record<string, string>, secrets: string[]) =>\n Object.fromEntries(Object.entries(messages).map(([name, message]) => [name, maskSecrets(message, secrets)]))\n","import { shownInputs } from '@protobase/schema/internal'\nimport type { ActionInputModel, FieldModel, FieldType, FieldViewModel } from '@protobase/schema'\nimport { toDraft, toPatchValue } from '../../../live/field-values'\nimport { isChosen, type Draft } from '../../create/create-values'\nimport { text } from '../messages'\n\nconst fieldTypes: Record<Exclude<ActionInputModel['kind'], 'choice' | 'checklist' | 'custom'>, FieldType> = { text: 'text', integer: 'integer', decimal: 'decimal', boolean: 'boolean', date: 'date', secret: 'text' }\n\n/** The field an input is edited as, so the create form's editors edit it: a choice of options is an enum, of records a relation. */\nexport const inputField = (input: ActionInputModel): FieldModel => {\n const base = { name: input.name, column: input.name, nullable: true, readOnly: false, filterable: false, sortable: false, aliases: [] }\n if (input.kind === 'custom' || input.kind === 'checklist') return { ...base, type: 'json' }\n if (input.kind !== 'choice') return { ...base, type: fieldTypes[input.kind] }\n if (input.resource !== undefined) return { ...base, type: 'relation', relation: { resource: input.resource, columns: [input.name] } }\n return { ...base, type: 'enum', enumValues: (input.options ?? []).map((option) => option.value) }\n}\n\n/** The view hints an input's editor reads: its label, a box that grows for a multiline text, a choice's labels. */\nexport const inputHints = (input: ActionInputModel): FieldViewModel => ({\n label: input.label,\n ...(input.multiline && { multiline: true }),\n ...(input.options && { valueLabels: Object.fromEntries(input.options.map((option) => [option.value, option.label])) }),\n})\n\n/** What each input holds when the dialog opens: its default, as its editor holds it. */\nexport const startingAnswers = (inputs: ActionInputModel[]): Draft =>\n Object.fromEntries(\n inputs.map((input) => {\n if (input.kind === 'custom') return [input.name, input.default ?? null]\n if (input.kind === 'checklist') return [input.name, []]\n if (input.kind === 'boolean') return [input.name, Boolean(input.default)]\n return [input.name, toDraft(input.default)]\n }),\n )\n\n// An answer as the handler gets it: null when empty, a number for an integer, a chosen record's key, a checklist's ticked boxes, a secret as typed.\nconst answerOf = (input: ActionInputModel, held: unknown) => {\n if (input.kind === 'custom') return held ?? null\n if (input.kind === 'checklist') return Array.isArray(held) ? held : []\n // A secret goes to the handler exactly as typed, never trimmed.\n if (input.kind === 'secret') return typeof held === 'string' && held !== '' ? held : null\n if (isChosen(held)) return held.key\n // A record's key given as the default, before anything is picked.\n if (input.resource !== undefined) return String(held ?? '') === '' ? null : String(held)\n return toPatchValue(inputField(input), held)\n}\n\n/** The answers of the inputs that show, as the handler gets them in `values`, and the names of those that show. */\nexport const answeredValues = (inputs: ActionInputModel[], draft: Draft) => {\n const all = Object.fromEntries(inputs.map((input) => [input.name, answerOf(input, draft[input.name])]))\n const shown = shownInputs(inputs, all)\n return { shown, values: Object.fromEntries(Object.entries(all).filter(([name]) => shown.has(name))) }\n}\n\nconst decimal = /^-?\\d+(\\.\\d+)?$/\nconst date = /^\\d{4}-\\d{2}-\\d{2}$/\n\n// Why an answer is refused before the action runs, if it is; a checklist's while one of its `boxes` is not ticked.\nconst refusal = (input: ActionInputModel, value: unknown, boxes: string[]) => {\n if (input.kind === 'checklist') {\n const left = boxes.filter((box) => !(Array.isArray(value) && value.includes(box))).length\n return left === 0 ? undefined : text('tickEvery', { count: left })\n }\n if (value === null || value === '') return input.required ? text('required') : undefined\n if (input.kind === 'integer' && !Number.isInteger(value)) return text('wholeNumber')\n if (input.kind === 'decimal' && !decimal.test(String(value))) return text('number')\n if (input.kind === 'date' && !date.test(String(value))) return text('dateFormat')\n if (input.max !== undefined && String(value).length > input.max) return text('atMost', { max: input.max })\n return undefined\n}\n\n/**\n * What is wrong with the answers that show, by input name: one left empty that is required, a number that is none, a\n * text too long, a checklist with a box of `boxes` (by input name) left unticked.\n */\nexport const refusedAnswers = (inputs: ActionInputModel[], values: Record<string, unknown>, boxes: Record<string, string[]> = {}) =>\n Object.fromEntries(\n inputs.flatMap((input) => {\n if (!Object.hasOwn(values, input.name)) return []\n const reason = refusal(input, values[input.name], boxes[input.name] ?? [])\n return reason ? [[input.name, reason]] : []\n }),\n )\n","import { useId, useState, type ComponentType } from 'react'\nimport type { ActionInputModel, ActionModel, JsonValue } from '@protobase/schema'\nimport { Button } from '../../../primitives/button'\nimport { ResponsiveDialog } from '../../../primitives/responsive-dialog'\nimport { Field } from '../../../record-view'\nimport { isChosen, type Draft } from '../../create/create-values'\nimport { ErrorBanner } from '../../error-banner'\nimport { FieldEditor } from '../../field-editor'\nimport { useAdminMeta } from '../../meta-gate'\nimport { useActionMailbox } from '../../../mailbox/use-action-mailbox'\nimport { useProjectUi } from '../project-ui'\nimport { checklistBoxes } from './checklist-boxes'\nimport { ChecklistInput } from './checklist-input'\nimport { SecretInput } from './secret-input'\nimport { maskedFailure, maskedMessages, secretAnswers } from './secret-mask'\nimport { answeredValues, inputField, inputHints, refusedAnswers, startingAnswers } from './input-answers'\nimport { inputErrors } from './input-errors'\nimport { text } from '../messages'\n\n/** What a custom input's component gets, as a field type's editor does: the answer, a way to set it, whether it is refused, and `props`. */\nexport type ActionInputProps<V = unknown, P = Record<string, JsonValue>> = {\n /** The input, as the action declares it. */\n input: ActionInputModel\n value: V | null\n onChange: (value: V | null) => void\n invalid: boolean\n /** What the input gives in `props`; `{}` without. */\n props: P\n}\n\ntype InputEditorProps = { input: ActionInputModel; held: unknown; invalid: boolean; onChange: (value: unknown) => void; boxes: string[] }\n\nconst InputEditor = ({ input, held, invalid, onChange, boxes }: InputEditorProps) => {\n const { resources, views } = useAdminMeta()\n const { components } = useProjectUi()\n if (input.kind === 'custom') {\n const Custom = components?.[input.component ?? ''] as ComponentType<ActionInputProps> | undefined\n if (!Custom) throw new Error(`Input \"${input.name}\": the app has no component \"${input.component}\"`)\n return <Custom input={input} value={held ?? null} onChange={onChange} invalid={invalid} props={input.props ?? {}} />\n }\n if (input.kind === 'checklist') return <ChecklistInput label={input.label} boxes={boxes} ticked={Array.isArray(held) ? (held as string[]) : []} onChange={onChange} />\n if (input.kind === 'secret') return <SecretInput name={input.name} value={typeof held === 'string' ? held : ''} invalid={invalid} onChange={onChange} />\n const target = input.resource === undefined ? undefined : resources[input.resource]\n return (\n <FieldEditor\n field={inputField(input)}\n hints={inputHints(input)}\n value={isChosen(held) ? held.key : held}\n stored={undefined}\n relationLabel={isChosen(held) ? held.label : undefined}\n relationPicker={target ? { target, view: views[target.name] } : undefined}\n invalid={invalid}\n onChange={onChange}\n />\n )\n}\n\ntype ActionInputsDialogProps = {\n action: ActionModel & { inputs: ActionInputModel[] }\n label: string\n danger?: boolean\n /** The records it runs on, whose `from` fields hold a checklist's boxes. */\n records?: Array<Record<string, unknown>>\n /** The titles of the records, named above the inputs when it runs on several. */\n names?: string[]\n onCancel: () => void\n /** Runs the action with the answers; a failure it throws keeps the dialog open, its messages under their inputs. */\n onSubmit: (values: Record<string, unknown>) => Promise<void>\n}\n\n/** The dialog an action with inputs opens: the inputs that show, edited as on the create form, and the action's button. */\nexport const ActionInputsDialog = ({ action, label, danger, records = [], names = [], onCancel, onSubmit }: ActionInputsDialogProps) => {\n const [draft, setDraft] = useState<Draft>(() => startingAnswers(action.inputs))\n const [errors, setErrors] = useState<Record<string, string>>({})\n const [failure, setFailure] = useState<unknown>()\n const [running, setRunning] = useState(false)\n const formId = useId()\n const { shown, values } = answeredValues(action.inputs, draft)\n const mailbox = useActionMailbox(action, failure)\n const boxes = Object.fromEntries(action.inputs.filter((input) => input.kind === 'checklist').map((input) => [input.name, checklistBoxes(input, records)]))\n\n const submit = async () => {\n const refused = refusedAnswers(action.inputs, values, boxes)\n setErrors(refused)\n setFailure(undefined)\n if (Object.keys(refused).length > 0 || mailbox.blocked) return\n setRunning(true)\n // A handler that echoes a secret answer in its failure has it masked before the dialog draws it.\n const secrets = secretAnswers(action.inputs, values)\n await onSubmit(values).catch((error: unknown) => {\n setErrors(maskedMessages(inputErrors(error, action.inputs), secrets))\n setFailure(maskedFailure(error, secrets))\n })\n setRunning(false)\n }\n\n const change = (name: string, value: unknown) => {\n setErrors(({ [name]: _, ...rest }) => rest)\n setDraft((current) => ({ ...current, [name]: value }))\n }\n\n return (\n <ResponsiveDialog\n title={label}\n description={action.confirm}\n open\n onClose={onCancel}\n actions={\n <>\n <Button onClick={onCancel}>{text('cancel')}</Button>\n <Button variant={danger ? 'danger' : 'primary'} type=\"submit\" form={formId} loading={running} disabled={mailbox.blocked}>\n {label}\n </Button>\n </>\n }\n >\n <form\n id={formId}\n className=\"flex flex-col gap-4\"\n onSubmit={(event) => {\n event.preventDefault()\n void submit()\n }}\n >\n {failure !== undefined && Object.keys(errors).length === 0 && !mailbox.explained && <ErrorBanner title={text('failed', { label })} error={failure} />}\n {mailbox.notice}\n {names.length > 1 && <p className=\"text-sm\">{text('forRecords', { records: names.join(', ') })}</p>}\n {action.inputs\n .filter((input) => shown.has(input.name))\n .map((input) => (\n <Field key={input.name} label={input.label} required={input.required} help={input.help} error={errors[input.name]}>\n <InputEditor input={input} held={draft[input.name]} invalid={Boolean(errors[input.name])} onChange={(next) => change(input.name, next)} boxes={boxes[input.name] ?? []} />\n </Field>\n ))}\n </form>\n </ResponsiveDialog>\n )\n}\n","import type { ActionModel } from '@protobase/schema'\nimport { Button } from '../../primitives/button'\nimport { Dialog } from '../../primitives/dialog'\nimport { useActionMailbox } from '../../mailbox/use-action-mailbox'\nimport { text } from './messages'\n\n/** The question an action with `confirm` asks before it runs; one that sends from the person's mailbox offers to connect it first while none is linked. */\nexport const ConfirmAction = ({ action, label, danger, onCancel, onConfirm }: { action: ActionModel; label: string; danger?: boolean; onCancel: () => void; onConfirm: () => void }) => {\n const mailbox = useActionMailbox(action, undefined)\n return (\n <Dialog\n title={`${label}?`}\n description={action.confirm}\n onClose={onCancel}\n actions={\n <>\n <Button onClick={onCancel}>{text('cancel')}</Button>\n <Button variant={danger ? 'danger' : 'primary'} disabled={mailbox.blocked} onClick={onConfirm}>\n {label}\n </Button>\n </>\n }\n >\n {mailbox.notice}\n </Dialog>\n )\n}\n","import type { ActionModel } from '@protobase/schema'\nimport { ActionInputsDialog } from './action-inputs/action-inputs-dialog'\nimport { ConfirmAction } from './confirm-action'\n\n/** Whether the action is drawn in red, as one that destroys or interrupts something: a delete, or one with `variant: 'danger'`. */\nexport const isDanger = (action: ActionModel) => action.variant === 'danger' || action.run?.kind === 'delete'\n\n/** Whether pressing the action's button opens a dialog first: to ask its question, or for its inputs. */\nexport const asksFirst = (action: ActionModel) => Boolean(action.confirm || action.inputs?.length)\n\ntype ActionPromptProps = {\n action: ActionModel\n label: string\n danger?: boolean\n /** The records it runs on, whose fields a checklist may take its boxes from. */\n records?: Array<Record<string, unknown>>\n /** Their titles, which a dialog for several names. */\n names?: string[]\n onCancel: () => void\n /** Runs an action without inputs once its question is answered. */\n onConfirm: () => void\n /** Runs it with the answers to its inputs, throwing its failure for the dialog to show. */\n onSubmit: (values: Record<string, unknown>) => Promise<void>\n}\n\n/** The dialog an action that asks first opens: its inputs, or else its question. */\nexport const ActionPrompt = ({ action, label, danger, records, names, onCancel, onConfirm, onSubmit }: ActionPromptProps) => {\n const { inputs } = action\n if (inputs?.length) return <ActionInputsDialog action={{ ...action, inputs }} label={label} danger={danger} records={records} names={names} onCancel={onCancel} onSubmit={onSubmit} />\n return <ConfirmAction action={action} label={label} danger={danger} onCancel={onCancel} onConfirm={onConfirm} />\n}\n","import { AuthError } from '@protobase/client'\nimport { authMessage } from '../auth/auth-messages'\nimport { useOptionalAuth } from '../auth/auth-provider'\nimport { useToast, type ToastAction } from '../toasts'\nimport { mailboxProblem } from './mailbox-problem'\nimport { text } from './messages'\n\n/**\n * For the toast of a failure: a button that connects the mailbox when the failure was for want of one, or as its link\n * expired, starting the same sign-in as the account page's, which comes back to this page. None for any other failure,\n * or when the app has no mailbox the failure points at.\n */\nexport const useMailboxToastAction = () => {\n const auth = useOptionalAuth()\n const toast = useToast()\n return (error: unknown): ToastAction | undefined => {\n const problem = mailboxProblem(error)\n const links = auth?.personalMail ?? []\n if (!auth || !problem) return\n const link = links.find((entry) => entry.id === problem.provider) ?? (links.length === 1 ? links[0] : undefined)\n if (!link) return\n const connect = async () => {\n try {\n await auth.linkPersonalMail(link)\n } catch (failure) {\n if (!(failure instanceof AuthError)) throw failure\n toast.show({ state: 'error', title: text('connect', { name: link.name }), description: authMessage(failure) })\n }\n }\n return { label: text(problem.code === 'link_expired' ? 'connectAgain' : 'connect', { name: link.name }), onClick: () => void connect() }\n }\n}\n","import { evaluateCondition, parseCondition } from '@protobase/layout'\nimport type { ActionModel } from '@protobase/schema'\n\n/**\n * Whether `action` applies to `record`: always without a `when`, else when its condition holds for the record's own\n * fields. With a `when` there is nothing to apply to without a record, and a condition that does not parse never holds.\n */\nexport const actionApplies = (action: ActionModel, record: Record<string, unknown> | undefined) => {\n if (action.when === undefined) return true\n if (!record) return false\n const condition = parseCondition(action.when)\n return condition.ok && evaluateCondition(condition, record)\n}\n","import type { ActionModel } from '@protobase/schema'\nimport { fillAddress, fillText, hostPlaceholder, hrefField, recordValueAt, resourceField, valueText } from '@protobase/schema/internal'\nimport { actionApplies } from './action-when'\n\n/** `href` with every `{{path}}` replaced by the record's value, percent-encoded; a missing value becomes empty. */\nexport const fillHref = (href: string, record: Record<string, unknown> = {}) => fillText(href, (path) => encodeURIComponent(valueText(recordValueAt(record, path))))\n\nconst webUrl = (value: unknown) => {\n if (typeof value !== 'string' || !URL.canParse(value)) return undefined\n const url = new URL(value)\n return url.protocol === 'https:' || url.protocol === 'http:' ? url.href : undefined\n}\n\n/**\n * Where a link action's `href` goes from `record`: an href that is only `{field}` is the record's value as it is, when\n * that is an `https:` or `http:` URL, and nothing otherwise; any other href is filled by `fillHref`.\n */\nexport const linkTarget = (href: string, record: Record<string, unknown> = {}) => {\n const field = hrefField(href)\n return field === undefined ? fillHref(href, record) : webUrl(recordValueAt(record, field))\n}\n\n/**\n * Opens a link's target: an `https:` or `http:` page in a new tab that gets neither the app's window nor its address,\n * anything else (`mailto:`) in place. A link without a target does nothing.\n */\nexport const openLink = (target: string | undefined) => {\n if (target === undefined) return\n if (/^https?:/i.test(target)) window.open(target, '_blank', 'noopener,noreferrer')\n else window.location.assign(target)\n}\n\nconst hostOf = (target: string) => (URL.canParse(target) ? new URL(target).hostname.replace(/^www\\./, '') : '')\n\n// An update sets values the record may hold already, as `paid: true` on a paid order.\nconst holdsAll = (record: Record<string, unknown>, values: Record<string, unknown>) => Object.entries(values).every(([name, value]) => Object.is(record[name], value))\n\n/**\n * `action` as it shows for `record`: one whose `when` does not hold there is left out, or shown as it is when it\n * disables instead; an update that would change nothing there, a link whose `href` has no target there, and a link\n * whose resource the record names but `resources` (the caller's, from `/meta`) lacks, are left out, and `{{host}}` in a\n * link's label becomes the host its target opens, without `www.`.\n */\nexport const actionFor = (action: ActionModel, record: Record<string, unknown> | undefined, resources: Readonly<Record<string, unknown>> = {}): ActionModel | undefined => {\n if (!actionApplies(action, record)) return action.otherwise === 'disable' ? action : undefined\n const run = action.run\n if (run?.kind === 'update') return record && !action.inputs?.length && holdsAll(record, run.values as Record<string, unknown>) ? undefined : action\n if (run?.kind === 'link' && 'to' in run && resourceField(run.to) !== undefined) {\n const to = fillAddress(run.to, record)\n return to.kind !== 'page' && Object.hasOwn(resources, to.resource) ? action : undefined\n }\n if (run?.kind !== 'link' || !('href' in run)) return action\n const target = linkTarget(run.href, record)\n if (target === undefined) return undefined\n return action.label.includes(hostPlaceholder) ? { ...action, label: action.label.replaceAll(hostPlaceholder, hostOf(target)) } : action\n}\n","/** What a run over several records does with one: runs on it, skips it as one it does not apply to, or refuses it as one the person may not change. */\nexport type EachVerdict = 'run' | 'skip' | 'refuse'\n\n/**\n * How a run over several records went: how many it ran on, skipped as not applying and failed on, with the first\n * failure, and the records it refused, before running or because the run was refused.\n */\nexport type EachOutcome<T> = { done: number; skipped: number; failed: number; refused: T[]; error?: unknown }\n\n/**\n * Runs `run` on each of `records` its `verdict` runs, one after another, so a failure on one leaves the others to run:\n * a failure `refusal` says is a refusal joins the refused records, any other is counted and the first kept for the\n * caller to show.\n */\nexport const runEach = async <T>(records: T[], verdict: (record: T) => EachVerdict, run: (record: T) => Promise<void>, refusal: (error: unknown) => boolean): Promise<EachOutcome<T>> => {\n const verdicts = records.map((record) => ({ record, verdict: verdict(record) }))\n const outcome: EachOutcome<T> = {\n done: 0,\n skipped: verdicts.filter((entry) => entry.verdict === 'skip').length,\n failed: 0,\n refused: verdicts.flatMap((entry) => (entry.verdict === 'refuse' ? [entry.record] : [])),\n }\n for (const { record } of verdicts.filter((entry) => entry.verdict === 'run')) {\n const failure = await run(record).then(\n () => undefined,\n (error: unknown) => ({ error }),\n )\n if (!failure) outcome.done += 1\n else if (refusal(failure.error)) outcome.refused.push(record)\n else {\n outcome.failed += 1\n if (outcome.failed === 1) outcome.error = failure.error\n }\n }\n return outcome\n}\n","import { useState } from 'react'\nimport { ApiError } from '@protobase/client'\nimport type { ActionModel } from '@protobase/schema'\nimport { fillAddress, updateValues } from '@protobase/schema/internal'\nimport { useClient, useResourceClient } from '../../data/api-provider'\nimport { useMailboxToastAction } from '../../mailbox/use-mailbox-toast-action'\nimport { useToast } from '../../toasts'\nimport { useAdminMeta, usePermissions } from '../meta-gate'\nimport { can } from '../permissions'\nimport { useAppAddress } from '../use-app-address'\nimport { actionFor, linkTarget, openLink } from './action-href'\nimport { actionApplies } from './action-when'\nimport { useProjectUi } from './project-ui'\nimport type { LayoutRecord } from './record-scope'\nimport { runEach, type EachVerdict } from './run-each'\nimport { answersFor } from './action-inputs/checklist-boxes'\nimport { maskSecrets, secretAnswers } from './action-inputs/secret-mask'\nimport { useRecordTitle } from '../titles/record-titles'\nimport { useRefreshResource } from './use-layout-data'\nimport { text } from './messages'\n\n/** A record's title, quoted, to name it inside a sentence. */\nexport const quoted = (title: string) => `“${title}”`\n\nconst message = (error: unknown) => (error instanceof Error ? error.message : text('somethingWrong'))\n\n/**\n * The named actions of `resource`'s view, ready to run on `scope` (the record they act on): built-in behaviour first\n * (`update`, `delete`, `link`, and `ai`, which the server runs), else the handler the project registered under the\n * action's name. One whose `when` does not hold for the record is left out, or blocked with its `reason`; an update\n * whose values the record holds already is left out, and so is a link to a URL the record holds while it holds none.\n * `blocked` says why one cannot run; `afterRun` hears about every action that succeeded.\n * `submit` runs one with the answers to its inputs (a handler gets them, an update writes them) and throws its failure, for the dialog to show.\n * `runEach` runs one on each of several records it applies to, as a list's selection does, with the answers to its inputs\n * as each record gets them, and says how that went, naming the records the person may not change; it resolves to its outcome.\n */\nexport const useActionRunner = (resource: string, scope: LayoutRecord | undefined, afterRun?: (action: ActionModel) => void) => {\n const { views, resources } = useAdminMeta()\n const { actions: handlers, components } = useProjectUi()\n const permissions = usePermissions(resource)\n const client = useClient()\n // A handler works on the API that serves the resource, functions included: a source's for one drawn from it.\n const handlerClient = useResourceClient(resource)\n const toast = useToast()\n const mailboxAction = useMailboxToastAction()\n const refresh = useRefreshResource()\n const { go } = useAppAddress()\n const titleOf = useRecordTitle()\n const [running, setRunning] = useState<string>()\n // An update shows only while it would change the record, a link to a URL the record holds only while it holds one, its label naming the URL's host\n const actions = (views[resource]?.actions ?? []).flatMap((action) => actionFor(action, scope?.record, resources) ?? [])\n\n // Why `action` cannot run on `on`, the record it would act on.\n const blockedOn = (action: ActionModel, on: LayoutRecord | undefined) => {\n const kind = action.run?.kind\n if ((kind === 'update' || kind === 'delete' || kind === 'ai') && !on) return text('needsRecord')\n if (!actionApplies(action, on?.record)) return action.reason ?? text('doesNotApply')\n if ((kind === 'update' || kind === 'ai') && (!can(permissions, 'update') || on?.permissions?.update === false)) return text('cannotChange')\n if (action.run?.kind === 'ai' && on?.permissions?.fields?.[action.run.writes] === 'read') return text('cannotChange')\n if (kind === 'delete' && (!can(permissions, 'delete') || on?.permissions?.delete === false)) return text('cannotDelete')\n if (!action.run && !handlers?.[action.name]) return text('noHandler', { name: action.name })\n const custom = action.inputs?.find((input) => input.kind === 'custom' && !components?.[input.component ?? ''])\n if (custom) return text('noInputComponent', { component: String(custom.component), input: custom.name })\n return undefined\n }\n const blocked = (action: ActionModel) => blockedOn(action, scope)\n\n // Whether the person may change this record, though they may change others of the resource: its own permissions say no.\n const refusedOn = (action: ActionModel, on: LayoutRecord) => {\n const { run } = action\n const kind = run?.kind\n if (kind === 'update' || kind === 'ai') return can(permissions, 'update') && (on.permissions?.update === false || (run?.kind === 'ai' && on.permissions?.fields?.[run.writes] === 'read'))\n if (kind === 'delete') return can(permissions, 'delete') && on.permissions?.delete === false\n return false\n }\n\n // Runs the action on `on`, without telling the user how it went.\n const execute = async (action: ActionModel, on: LayoutRecord | undefined, values?: Record<string, unknown>) => {\n const { run } = action\n if (run?.kind === 'link') {\n if ('to' in run) go(fillAddress(run.to, on?.record))\n else openLink(linkTarget(run.href, on?.record))\n return\n }\n if (run?.kind === 'update') await client.update(resource, on!.key, updateValues(run.values as Record<string, unknown>, values ?? {}), on!.etag ?? '*')\n else if (run?.kind === 'delete') await client.remove(resource, on!.key, { etag: on!.etag })\n else if (run?.kind === 'ai') await client.generate(resource, on!.key, action.name)\n else await handlers![action.name]!({ resource, record: on?.record, recordKey: on?.key, etag: on?.etag, client: handlerClient, navigate: go, ...(values && { values }) })\n }\n\n const perform = async (action: ActionModel, on: LayoutRecord | undefined, values?: Record<string, unknown>) => {\n await execute(action, on, values)\n if (action.run?.kind === 'link') return\n await refresh(resource)\n toast.show({ state: 'success', title: text('done', { label: action.label }) })\n afterRun?.(action)\n }\n\n // `on` is another record than the scope's, such as a list's row. A failure for want of a mailbox offers to connect one.\n const run = async (action: ActionModel, on = scope) => {\n if (blockedOn(action, on)) return\n setRunning(action.name)\n await perform(action, on).catch((error: unknown) => {\n const connect = mailboxAction(error)\n toast.show({ state: 'error', title: text('failed', { label: action.label }), description: message(error), ...(connect && { action: connect }) })\n })\n setRunning(undefined)\n }\n\n // An action with inputs runs from its dialog, which shows a failure under the inputs it is about instead of a toast.\n const submit = async (action: ActionModel, values: Record<string, unknown>) => {\n if (blocked(action)) return\n setRunning(action.name)\n await perform(action, scope, answersFor(action.inputs ?? [], values, scope?.record)).finally(() => setRunning(undefined))\n }\n\n /** Whether `action` shows and can run on `on`. */\n const appliesOn = (action: ActionModel, on: LayoutRecord) => actionFor(action, on.record, resources) !== undefined && !blockedOn(action, on)\n\n /** What a run over several records does with `on`: runs on it, refuses it as one the person may not change, or skips it. */\n const verdictOn = (action: ActionModel, on: LayoutRecord): EachVerdict => {\n if (appliesOn(action, on)) return 'run'\n const shows = actionFor(action, on.record, resources) !== undefined && actionApplies(action, on.record)\n return shows && refusedOn(action, on) ? 'refuse' : 'skip'\n }\n\n // A failure on one record leaves the others to run; the toast counts them, with the first failure's message, its secret answers masked, and\n // the records the caller left out already as not applying (`skipped`), and names those the person may not change,\n // refused here or by the API.\n const runOnEach = async (action: ActionModel, records: LayoutRecord[], skipped = 0, values?: Record<string, unknown>) => {\n setRunning(action.name)\n const answers = (on: LayoutRecord) => (values ? answersFor(action.inputs ?? [], values, on.record) : undefined)\n const refusal = (error: unknown) => error instanceof ApiError && error.status === 403\n const outcome = await runEach(records, (on) => verdictOn(action, on), (on) => execute(action, on, answers(on)), refusal)\n setRunning(undefined)\n await refresh(resource)\n const refused = outcome.refused.map((on) => quoted(titleOf(on.model, views[resource], on.record, on.key)))\n const title = text('doneOn', { label: action.label, done: outcome.done, skipped: outcome.skipped + skipped, failed: outcome.failed, refused: refused.length })\n const description = [refused.length > 0 && text('refusedOn', { records: refused.join(', '), count: refused.length }), outcome.failed > 0 && maskSecrets(message(outcome.error), secretAnswers(action.inputs ?? [], values ?? {}))].filter(Boolean).join(' ')\n toast.show({ state: outcome.failed > 0 || refused.length > 0 ? 'error' : 'success', title, ...(description && { description }) })\n if (outcome.done > 0) afterRun?.(action)\n return outcome\n }\n\n return { actions, blocked, blockedOn, appliesOn, verdictOn, running, run, submit, runEach: runOnEach }\n}\n\n/** One named action of `resource`'s view, for a button; `afterRun` hears when it succeeded. */\nexport const useRunAction = (resource: string, name: string, scope: LayoutRecord | undefined, afterRun?: (action: ActionModel) => void) => {\n const runner = useActionRunner(resource, scope, afterRun)\n const action = runner.actions.find((entry) => entry.name === name)\n return {\n action,\n /** The record it acts on, when it acts on one. */\n record: scope?.record,\n blocked: action ? runner.blocked(action) : text('noAction', { name }),\n running: runner.running === name,\n run: () => (action ? runner.run(action) : Promise.resolve()),\n submit: (values: Record<string, unknown>) => (action ? runner.submit(action, values) : Promise.resolve()),\n }\n}\n","import { messages } from '../locale/messages'\n\nexport const text = messages('app/list')\n","import { messages } from '../../locale/messages'\n\nexport const text = messages('app/charts')\n","import type { AggregateGroup } from '@protobase/client'\nimport { createWhere, enumLabel, printFilter, type FieldModel, type FieldViewModel } from '@protobase/schema'\nimport { formatTag } from '../../locale/active-locale'\nimport { valueColor } from '../../live/value-color'\nimport { text as message } from './messages'\n\nconst where = createWhere()\n\n/** How many fixed colours a chart has, `--chart-1` to `--chart-8`; more values than that share a neutral one. */\nexport const seriesColors = 8\n\n/** What a chart adds up per group: how many records, or the sum, average or maximum of a numeric field. */\nexport type ChartMeasure = { kind: 'count' } | { kind: 'sum' | 'average' | 'maximum'; field: FieldModel; hints?: FieldViewModel }\n\n/** One group as a chart draws it: its name, its number, its colour, and the filter that lists its records. */\nexport type ChartSlice = { key: string; label: string; value: number | null; count: number; color: string; filter: string }\n\nconst slot = (index: number) => (index >= 0 && index < seriesColors ? `var(--chart-${index + 1})` : 'var(--faint-foreground)')\n\n// A colour follows its value, never its rank: an enum's by its place among the values, a boolean's by true and false.\n// Other values have no fixed order, so they take the colours in the order the groups come.\nexport const colorOf = (field: FieldModel, hints: FieldViewModel | undefined, value: AggregateGroup['value'], index: number) => {\n const key = String(value)\n if (value === null) return 'var(--faint-foreground)'\n const color = valueColor(hints?.valueColors, value)\n if (color !== undefined) return color\n if (field.type === 'enum') return slot(field.enumValues?.indexOf(key) ?? -1)\n if (field.type === 'boolean') return slot(value ? 0 : 1)\n return slot(index)\n}\n\nexport const labelOf = (field: FieldModel, hints: FieldViewModel | undefined, group: Pick<AggregateGroup, 'value' | 'label'>) => {\n if (group.value === null) return message('notSet')\n if (field.type === 'enum') return enumLabel(String(group.value), hints?.valueLabels)\n if (field.type === 'boolean') return group.value ? message('yes') : message('no')\n return group.label ?? String(group.value)\n}\n\n/** The records of one group: the chart's own filter and the group's value. */\nexport const groupFilter = (field: FieldModel, value: AggregateGroup['value'], filter = '') => {\n const own = printFilter(value === null ? where.isNull(field.name) : where.eq(field.name, value as never))\n return filter.trim() ? `(${filter}) AND ${own}` : own\n}\n\nconst measured = (group: AggregateGroup, measure: ChartMeasure) => (measure.kind === 'count' ? group.count : (group[measure.kind] ?? null))\n\n/** The groups of a field of values as slices, in the order the API ranks them. */\nexport const valueSlices = (groups: AggregateGroup[], field: FieldModel, hints: FieldViewModel | undefined, measure: ChartMeasure, filter = ''): ChartSlice[] =>\n groups.map((group, index) => ({\n key: String(group.value),\n label: labelOf(field, hints, group),\n value: measured(group, measure),\n count: group.count,\n color: colorOf(field, hints, group.value, index),\n filter: groupFilter(field, group.value, filter),\n }))\n\n/** A date field's buckets as points in time, the bucket's start read as UTC as the list's chart reads it. */\nexport const periodPoints = (groups: AggregateGroup[], measure: ChartMeasure) =>\n groups.map((group) => ({ at: Date.parse(`${String(group.value)}Z`), value: measured(group, measure), count: group.count }))\n\n/** A measured number as text: a count whole, a sum, average or maximum with the field's decimals, prefix and suffix. */\nexport const measureText = (value: number | null, measure: ChartMeasure) => {\n if (value === null) return '—'\n if (measure.kind === 'count') return value.toLocaleString(formatTag())\n const decimals = measure.hints?.decimals ?? (Number.isInteger(value) ? 0 : 2)\n const text = value.toLocaleString(formatTag(), { minimumFractionDigits: decimals, maximumFractionDigits: decimals })\n return `${measure.hints?.prefix ?? ''}${text}${measure.hints?.suffix ?? ''}`\n}\n","import type { AggregateParams } from '@protobase/client'\nimport type { ChartProps } from '@protobase/layout'\nimport type { FieldModel, ResourceModel, ViewModel } from '@protobase/schema'\nimport { viewerZone } from '../../format/zone'\nimport { labelFieldOf } from '../../live/model-helpers'\nimport { seriesColors } from './chart-groups'\n\n// For a relation to a single-key resource: the field of that resource that names each of its records\nconst labelOf = (field: FieldModel | undefined, resources: Record<string, ResourceModel>, views: Record<string, ViewModel>) => {\n const target = field?.type === 'relation' && field.relation ? resources[field.relation.resource] : undefined\n return target && target.primaryKey.length === 1 ? labelFieldOf(target, views[target.name]) : undefined\n}\n\ntype ChartAsked = { model: ResourceModel } & Pick<ChartProps, 'groupBy' | 'splitBy' | 'sum' | 'average' | 'filter' | 'granularity' | 'range' | 'limit'>\n\n/**\n * The `:aggregate` a chart reads: a date field's buckets in the viewer's time zone, split by `splitBy`, or a field's\n * first `limit` values, named by the records a relation points at; `undefined` for a field the model lacks.\n */\nexport const chartAggregate = ({ model, groupBy, splitBy, sum, average, filter = '', granularity = 'day', range = '30d', limit = 10 }: ChartAsked, resources: Record<string, ResourceModel>, views: Record<string, ViewModel>): AggregateParams | undefined => {\n const field = model.fields[groupBy]\n if (!field) return\n const dated = field.type === 'date' || field.type === 'timestamp'\n const label = labelOf(field, resources, views)\n const splitField = dated && splitBy !== undefined ? model.fields[splitBy] : undefined\n const splitLabel = labelOf(splitField, resources, views)\n // A timestamp's buckets are the viewer's days, hours and months; a date's are its own\n const split = splitField ? { splitBy: splitField.name, splitLimit: seriesColors, ...(splitLabel && { splitLabel }) } : {}\n const params = dated ? { granularity, range, timeZone: viewerZone(), ...split } : { limit, ...(label && { label }) }\n return { groupBy, filter, ...(sum && { sum }), ...(average && { average }), ...params }\n}\n","import type { AppAddress, ViewModel } from '@protobase/schema'\n\n/**\n * The list of `resource` opened on exactly the records `filter` counted or showed: with no filter, an empty one when\n * the view's list opens on a default filter, so the link does not narrow what it counted; otherwise a clean path.\n */\nexport const filteredListAddress = (view: ViewModel | undefined, resource: string, filter: string | undefined): AppAddress => {\n if (filter) return { kind: 'list', resource, filter }\n if (view?.list?.filter) return { kind: 'list', resource, filter: '' }\n return { kind: 'list', resource }\n}\n","import type { ViewModel } from '@protobase/schema'\nimport { filteredListAddress } from '../list-link'\nimport { AppLink } from '../use-app-address'\nimport { measureText, type ChartMeasure, type ChartSlice } from './chart-groups'\nimport { text } from './messages'\n\n/**\n * A ranked list of a field's values, each a bar as long as its number and a link to its records. Bars in rows read on\n * a phone as well as on a desk, and carry their label and value as text, so no colour has to say what a bar is.\n */\nexport const GroupBars = ({ resource, view, slices, measure }: { resource: string; view: ViewModel | undefined; slices: ChartSlice[]; measure: ChartMeasure }) => {\n const largest = Math.max(0, ...slices.map((slice) => slice.value ?? 0))\n return (\n <ul className=\"flex flex-col gap-1\">\n {slices.map((slice) => {\n const share = largest > 0 && slice.value !== null ? Math.max(0, slice.value) / largest : 0\n return (\n <li key={slice.key}>\n <AppLink\n to={filteredListAddress(view, resource, slice.filter)}\n className=\"group grid grid-cols-[minmax(6rem,35%)_1fr_auto] items-center gap-3 rounded-md px-1 py-1 hover:bg-muted\"\n title={measure.kind === 'count' ? undefined : text('records', { count: measureText(slice.count, { kind: 'count' }) })}\n >\n <span className=\"truncate group-hover:text-primary-text\">{slice.label}</span>\n <span className=\"h-3 rounded-r bg-muted\" aria-hidden>\n <span className=\"block h-full rounded-r\" style={{ width: `${share * 100}%`, background: 'var(--chart-1)' }} />\n </span>\n <span className=\"text-right font-medium tabular-nums\">{measureText(slice.value, measure)}</span>\n </AppLink>\n </li>\n )\n })}\n </ul>\n )\n}\n","import { Skeleton } from '../../primitives/skeleton'\nimport { lazyComponent } from '../lazy-component'\n\n// The charts' drawing, the charting library and all, loads with the first chart shown, in a skeleton of its size.\n\nexport const PeriodChart = lazyComponent(\n () => import('./period-chart').then((module) => module.PeriodChart),\n ({ compact }) => <Skeleton className={compact ? 'h-24 w-full' : 'h-40 w-full'} />,\n)\n\nexport const GroupDonut = lazyComponent(\n () => import('./group-donut').then((module) => module.GroupDonut),\n () => <Skeleton className=\"size-36 rounded-full\" />,\n)\n","import type { Aggregate, AggregateGroup } from '@protobase/client'\nimport type { FieldModel, FieldViewModel } from '@protobase/schema'\nimport { colorOf, groupFilter, labelOf, periodPoints, type ChartMeasure } from './chart-groups'\nimport { text } from './messages'\n\n/**\n * One part of a split bucket as a chart draws it: the key of its number in a point, its name and colour, its records,\n * and how its number reads when it is not the chart's.\n */\nexport type ChartSeries = { key: string; label: string; color: string; filter?: string; measure?: ChartMeasure }\n\nexport type SplitPoint = ReturnType<typeof periodPoints>[number] & Record<string, number | null>\n\n// Sums of decimals carry float noise; what is left under this is no remainder\nconst noise = 1e-6\n\n/**\n * A date field's buckets with each split into one part per value of another field, in the order the API ranks them.\n * A bucket where a value has no records holds 0 of a count and no value of a sum or average. For a count or a sum, what\n * the kept values leave of the bucket's total is \"Other\", a series of its own when some bucket has any; an average\n * has no remainder.\n */\nexport const splitPoints = (\n groups: AggregateGroup[],\n splits: NonNullable<Aggregate['splits']>,\n field: FieldModel,\n hints: FieldViewModel | undefined,\n measure: ChartMeasure,\n filter = '',\n): { series: ChartSeries[]; points: SplitPoint[] } => {\n const series: ChartSeries[] = splits.map((split, index) => ({\n key: `s${index}`,\n label: labelOf(field, hints, split),\n color: colorOf(field, hints, split.value, index),\n filter: groupFilter(field, split.value, filter),\n }))\n const missing = measure.kind === 'count' ? 0 : null\n const partOf = (group: AggregateGroup, value: AggregateGroup['value']) => {\n const part = group.splits?.find((candidate) => candidate.value === value)\n if (!part) return missing\n return measure.kind === 'count' ? part.count : (part[measure.kind] ?? null)\n }\n const points = periodPoints(groups, measure).map((point, at): SplitPoint => {\n const group = groups[at]!\n const parts = splits.map((split) => partOf(group, split.value))\n const entries = Object.fromEntries(parts.map((part, index) => [`s${index}`, part]))\n if (measure.kind === 'average') return { ...point, ...entries }\n const rest = point.value === null ? null : point.value - parts.reduce<number>((all, part) => all + (part ?? 0), 0)\n return { ...point, ...entries, other: rest === null ? null : rest < noise ? 0 : rest }\n })\n const hasOther = measure.kind !== 'average' && points.some((point) => (point.other ?? 0) > 0)\n if (!hasOther) return { series, points: points.map(({ other, ...point }) => point as SplitPoint) }\n return { series: [...series, { key: 'other', label: text('other'), color: 'var(--border-strong)' }], points }\n}\n","import type { ChartBucket, ChartType } from '@protobase/layout'\nimport type { ResourceModel, ViewModel } from '@protobase/schema'\nimport { useAggregate } from '../../data/use-aggregates'\nimport { Skeleton } from '../../primitives/skeleton'\nimport { useAdminMeta } from '../meta-gate'\nimport { periodPoints, valueSlices, type ChartMeasure } from './chart-groups'\nimport { chartAggregate } from './chart-params'\nimport { GroupBars } from './group-bars'\nimport { GroupDonut, PeriodChart } from './lazy-charts'\nimport { splitPoints } from './split-points'\nimport { text } from './messages'\n\n/** What a chart shows: the records of `model` matching `filter`, grouped by `groupBy` and added up. */\nexport type ChartRequest = {\n model: ResourceModel\n view: ViewModel | undefined\n groupBy: string\n /** With a dated `groupBy`: a field of values that splits each bucket. */\n splitBy?: string\n type?: ChartType\n sum?: string\n average?: string\n filter?: string\n granularity?: ChartBucket\n range?: '7d' | '30d' | '90d' | '1y' | 'all'\n limit?: number\n empty?: string\n}\n\nconst measureOf = (model: ResourceModel, view: ViewModel | undefined, sum?: string, average?: string): ChartMeasure => {\n const name = sum ?? average\n const field = name === undefined ? undefined : model.fields[name]\n if (!field || name === undefined) return { kind: 'count' }\n return { kind: sum !== undefined ? 'sum' : 'average', field, hints: view?.fields[name] }\n}\n\n/**\n * Loads a chart's groups through `:aggregate` and draws them: a date field's buckets as bars or a line, a field's\n * values as ranked bars or a donut, each value linking to its records. The server checked the chart at startup.\n */\nexport const ChartView = ({ model, view, groupBy, splitBy, type = 'bar', sum, average, filter = '', granularity = 'day', range = '30d', limit = 10, empty = text('nothingYet') }: ChartRequest) => {\n const { resources, views } = useAdminMeta()\n const field = model.fields[groupBy]\n const dated = field?.type === 'date' || field?.type === 'timestamp'\n const splitField = dated && splitBy !== undefined ? model.fields[splitBy] : undefined\n const params = chartAggregate({ model, groupBy, splitBy, sum, average, filter, granularity, range, limit }, resources, views)\n const result = useAggregate(model.name, params ?? { groupBy }, params !== undefined)\n const measure = measureOf(model, view, sum, average)\n if (!field) return null\n if (result.isPending) return <Skeleton className=\"h-36 w-full\" />\n if (result.error) return <p className=\"text-danger-text\">{text('couldNotLoad')}</p>\n const { groups } = result.data\n if (groups.every((group) => group.count === 0)) return <p className=\"text-muted-foreground\">{empty}</p>\n const chartType = type === 'line' ? 'line' : 'bar'\n if (dated && splitField && result.data.splits) {\n const { series, points } = splitPoints(groups, result.data.splits, splitField, view?.fields[splitField.name], measure, filter)\n return <PeriodChart points={points} measure={measure} bucket={granularity} type={chartType} series={series} resource={model.name} view={view} />\n }\n if (dated) return <PeriodChart points={periodPoints(groups, measure)} measure={measure} bucket={granularity} type={chartType} />\n const slices = valueSlices(groups, field, view?.fields[groupBy], measure, filter)\n return type === 'donut' ? <GroupDonut resource={model.name} view={view} slices={slices} measure={measure} /> : <GroupBars resource={model.name} view={view} slices={slices} measure={measure} />\n}\n","/** The space between the items of a `SnapRow`, Tailwind's `gap-3`. */\nexport const snapRowGap = '0.75rem'\n\n/** How wide an item of a `SnapRow` is when no share sizes it, in pixels. */\nexport const snapCardWidth = 256\n\n/**\n * How wide an item of a row is at `share` of the row's width, the gaps taken off so that `1 / share` items fill it\n * exactly: a third leaves room for three items and the two gaps between them.\n */\nexport const snapItemWidth = (share: number) => {\n if (!(share > 0 && share <= 1)) throw new Error(`An item's share of a row is above 0 and at most 1, not ${share}`)\n return `calc((100% + ${snapRowGap}) * ${share} - ${snapRowGap})`\n}\n\n/**\n * The width and least width of an item of a `SnapRow`: at `share` of the row, but never narrower than 12rem or the\n * row, so narrow shares stay readable on a phone; without one `snapCardWidth`, but never wider than the row, so a very\n * narrow phone does not cut a card off.\n */\nexport const snapItemSize = (share: number | undefined) =>\n share === undefined ? { width: `min(${snapCardWidth}px, 100%)`, minWidth: '0px' } : { width: snapItemWidth(share), minWidth: 'min(100%, 12rem)' }\n","import type { CSSProperties, ReactNode } from 'react'\nimport { ChevronLeft, ChevronRight } from 'lucide-react'\nimport { snapItemSize, snapRowGap } from './snap-row-width'\nimport type { SnapScroll } from './use-snap-scroll'\nimport { text } from './messages'\n\nexport type SnapRowProps = {\n /** The row's scroll, from `useSnapScroll`. */\n scroll: SnapScroll\n /** What the items are, such as \"Homes\": the list's label, and the arrows' as \"Next homes\". */\n label: string\n /** How wide each item is, as a share of the row's width, such as `2 / 3` so the next one peeks in; 256px when omitted. */\n share?: number\n /** The row's items, each an `<li>`. */\n children: ReactNode\n}\n\nconst arrowClass = 'absolute top-1/2 z-10 hidden size-8 -translate-y-1/2 items-center justify-center rounded-full border border-border-strong bg-background shadow-pop hover:bg-muted sm:flex'\n\n/**\n * A list laid out as one row that scrolls sideways, by touch, trackpad, wheel or its scrollbar, and with a pointer by its\n * arrow buttons, snapping each item to its left edge. Each item is `share` of the row wide, but never narrower than 12rem\n * or the row, else 256px but never wider than the row (`snapItemSize`). The row scrolls on its own because the page\n * cannot scroll sideways, and only sideways: it is as tall as its tallest item. A swipe past its last item stops there.\n */\nexport const SnapRow = ({ scroll, label, share, children }: SnapRowProps) => {\n const size = snapItemSize(share)\n return (\n <div className=\"relative min-w-0\">\n <ul\n ref={scroll.ref}\n aria-label={label}\n className=\"relative flex snap-x snap-mandatory overflow-x-auto overflow-y-hidden overscroll-x-contain pb-1 *:w-(--snap-item-width) *:min-w-(--snap-item-min-width) *:shrink-0 *:snap-start\"\n style={{ gap: snapRowGap, scrollbarWidth: 'thin', '--snap-item-width': size.width, '--snap-item-min-width': size.minWidth } as CSSProperties}\n >\n {children}\n </ul>\n {scroll.back && (\n <button type=\"button\" aria-label={text('previous', { label: label.toLowerCase() })} onClick={() => scroll.page(-1)} className={`${arrowClass} -left-3`}>\n <ChevronLeft className=\"size-4\" aria-hidden />\n </button>\n )}\n {scroll.on && (\n <button type=\"button\" aria-label={text('next', { label: label.toLowerCase() })} onClick={() => scroll.page(1)} className={`${arrowClass} -right-3`}>\n <ChevronRight className=\"size-4\" aria-hidden />\n </button>\n )}\n </div>\n )\n}\n","import { useLayoutEffect, useRef, useState } from 'react'\n\n/** The part of a row in view: how far it is scrolled and how wide the view is, in pixels. */\nexport type SnapView = { left: number; width: number }\n\ntype Scrolled = SnapView & { back: boolean; on: boolean; watched: string }\n\nconst measure = (list: HTMLUListElement, watch: (view: SnapView) => string): Scrolled => {\n const view = { left: list.scrollLeft, width: list.clientWidth }\n return { ...view, back: view.left > 0, on: view.left + view.width < list.scrollWidth - 1, watched: watch(view) }\n}\n\nconst same = (a: Scrolled, b: Scrolled) => a.width === b.width && a.back === b.back && a.on === b.on && a.watched === b.watched\n\n/**\n * A `SnapRow`'s sideways scroll: `ref` goes on its list. Gives the part of the row in `view`, whether it can scroll\n * `back` or `on`, and `page`, which scrolls a view's width either way. It draws again only when the view's width, an end\n * reached or what `watch` makes of the view changes, such as the cards a windowed row draws.\n */\nexport const useSnapScroll = (watch: (view: SnapView) => string = () => '') => {\n const [list, setList] = useState<HTMLUListElement | null>(null)\n const [scrolled, setScrolled] = useState<Scrolled>({ left: 0, width: 0, back: false, on: false, watched: '' })\n const read = () => {\n if (!list) return\n const next = measure(list, watch)\n setScrolled((current) => (same(current, next) ? current : next))\n }\n\n // After every draw, since the row's content may have grown without a scroll or resize\n const latest = useRef(read)\n useLayoutEffect(() => {\n latest.current = read\n read()\n })\n useLayoutEffect(() => {\n if (!list) return\n const changed = () => latest.current()\n const observer = new ResizeObserver(changed)\n observer.observe(list)\n list.addEventListener('scroll', changed, { passive: true })\n return () => {\n observer.disconnect()\n list.removeEventListener('scroll', changed)\n }\n }, [list])\n\n const page = (direction: 1 | -1) => {\n if (!list) return\n const gap = parseFloat(getComputedStyle(list).columnGap) || 0\n list.scrollBy({ left: direction * Math.max(1, list.clientWidth - gap), behavior: 'smooth' })\n }\n return { ref: setList, view: { left: scrolled.left, width: scrolled.width }, back: scrolled.back, on: scrolled.on, page }\n}\n\nexport type SnapScroll = ReturnType<typeof useSnapScroll>\n","import { messages } from '../../locale/messages'\n\nexport const text = messages('app/embedded-list')\n","import { formatTag } from '../../locale/active-locale'\nimport { text } from './messages'\n\n/**\n * What a list that shows only its first `shown` of `total` records says about the rest, as \"The first 10 of 37.\";\n * nothing when it shows them all. An `estimated` total is the planner's, so it reads \"about\".\n */\nexport const cutOffNote = (shown: number, total: number, estimated: boolean) => {\n if (shown >= total) return undefined\n return (estimated ? text('firstOfAbout', { shown, total: total.toLocaleString(formatTag()) }) : text('firstOf', { shown, total: total.toLocaleString(formatTag()) }))\n}\n","import type { ResourceModel, ViewModel } from '@protobase/schema'\nimport { guarded } from '../../lib/guarded'\nimport { changedList, listDefaults } from '../current-address'\nimport { defaultDisplay, displayChoices } from '../displays/list-displays'\n\nconst prefix = 'protobase:embedded-display:'\n\n/** Where a viewer's pick of display is kept for one embedded list, named by the place it is shown. */\nexport const embeddedDisplayKey = (place: string) => `${prefix}${place}`\n\nexport const readPickedDisplay = (storage: Pick<Storage, 'getItem'>, key: string) => guarded(() => storage.getItem(key) ?? undefined, undefined)\n\nexport const writePickedDisplay = (storage: Pick<Storage, 'setItem'>, key: string, display: string) => guarded(() => storage.setItem(key, display), undefined)\n\n/**\n * The display an embedded list shows: the viewer's pick while the view still has it, else what the list opens in for\n * the screen, with the display the page names in place of the view's default (with neither, below `sm`, a cards\n * display when the view has one).\n */\nexport const embeddedDisplay = (view: ViewModel | undefined, xs: boolean, { picked, preferred }: { picked?: string; preferred?: string }) => {\n const names = displayChoices(view).map((choice) => choice.name)\n if (picked !== undefined && names.includes(picked)) return picked\n return defaultDisplay(view, xs, preferred !== undefined && names.includes(preferred) ? preferred : undefined)\n}\n\n/**\n * The resource's list with the embedded list's filter, order and display, leaving out what the list does by default (an\n * embedded list's own default display among it, so a phone opens the list in its rows rather than the table), and\n * the saved search whose results it shows, if any. `resource` names another list of the same records, such as the\n * favorites that list a user's saved listings.\n */\nexport const viewAllAddress = (\n model: ResourceModel,\n view: ViewModel | undefined,\n xs: boolean,\n { resource = model.name, ...list }: { filter: string; orderBy: string; display: string; savedSearch?: string; resource?: string },\n) => changedList({ kind: 'list', resource }, list, { ...listDefaults(model, view, xs), display: defaultDisplay(view, xs) })\n","import type { Planned } from './planned'\n\n/** A planned count: the total of its read, or inside a repeated record the count of that record's group, 0 without one. */\nexport const plannedCount = (planned: Planned) => planned.total ?? Number(planned.rows[0]?.count ?? 0)\n","import { checkFilter, parseFilter, type AppAddress, type ResourceModel, type RowButtonModel, type ViewModel } from '@protobase/schema'\nimport { bareFilterFields, fillAddress, fillText, filterField, hrefField, rowButtonChoiceFields, rowButtonChoices, rowButtonTarget } from '@protobase/schema/internal'\nimport { displayValue } from '../../live/display-value'\n\nconst isEmpty = (value: unknown) => value === null || value === undefined || value === ''\n\n// Only an https page opens from a row, so a field holding another scheme, such as `javascript:`, leads nowhere.\nconst httpsUrl = (value: unknown) => (typeof value === 'string' && URL.canParse(value) && new URL(value).protocol === 'https:' ? new URL(value).href : undefined)\n\n// A value a filter takes outside quotes is a number or a boolean, so a row's text cannot change what the filter says.\nconst plainValue = (value: unknown) => typeof value === 'number' || typeof value === 'boolean' || (typeof value === 'string' && /^(-?\\d+(\\.\\d+)?|true|false)$/.test(value))\n\n// A filter the row holds whole leads somewhere only when it parses and checks against the list's resource as the caller sees it.\nconst followableFilter = (to: AppAddress, models: Record<string, ResourceModel>) => {\n if (to.kind !== 'list' || to.filter === undefined) return false\n const target = Object.hasOwn(models, to.resource) ? models[to.resource] : undefined\n if (!target) return false\n const parsed = parseFilter(to.filter)\n if (!parsed.ok || !parsed.ast) return false\n return checkFilter(target, parsed.ast).ok\n}\n\n/**\n * The button `button` draws on `record`, a row of `model`: its first choice whose fields the row holds, its label with\n * each `{{field}}` as the record page shows the value (an enum value by its label), and its address filled from the row,\n * or the `https:` URL its href field holds. None when no choice has its fields, or the chosen one leads nowhere: an\n * href field without an `https:` URL, a value outside quotes in a filter that is not a number or a boolean, or a filter\n * the row holds whole, `'{{field}}'`, that does not parse or check against `models`, the caller's resources.\n */\nexport const rowButtonFor = (button: RowButtonModel, model: ResourceModel, view: ViewModel | undefined, record: Record<string, unknown>, models: Record<string, ResourceModel>): { label: string; to: AppAddress } | { label: string; href: string } | undefined => {\n const choice = rowButtonChoices(button).find((option) => !rowButtonChoiceFields(option).some((name) => isEmpty(record[name])))\n if (!choice) return\n const shown = (name: string) => {\n const field = model.fields[name]\n return field ? displayValue(field, record[name], view?.fields[name]) : String(record[name])\n }\n const label = fillText(choice.label, shown)\n const target = rowButtonTarget(choice)\n if ('href' in target) {\n const href = httpsUrl(record[hrefField(target.href) ?? ''])\n return href === undefined ? undefined : { label, href }\n }\n if (filterField(target.to) !== undefined) {\n const to = fillAddress(target.to, record)\n return followableFilter(to, models) ? { label, to } : undefined\n }\n if (!bareFilterFields(target.to).every((name) => plainValue(record[name]))) return\n return { label, to: fillAddress(target.to, record) }\n}\n","import { ExternalLink } from 'lucide-react'\nimport type { ResourceModel, RowButtonModel, ViewModel } from '@protobase/schema'\nimport { cn } from '../../lib/cn'\nimport { buttonClass } from '../../primitives/button'\nimport { text } from '../messages'\nimport { AppLink } from '../use-app-address'\nimport { rowButtonFor } from './row-button-for'\n\ntype RowButtonLinkProps = { button: RowButtonModel; model: ResourceModel; view: ViewModel | undefined; record: Record<string, unknown>; models: Record<string, ResourceModel> }\n\n/**\n * A row's button: a link to the address its fields name, looking like a button, or to the outside page a field holds,\n * in a new tab with the outside-link mark, which a screen reader hears as text; nothing on a row without them.\n */\nexport const RowButtonLink = ({ button, model, view, record, models }: RowButtonLinkProps) => {\n const shown = rowButtonFor(button, model, view, record, models)\n if (!shown) return null\n // A label longer than its column has shortens inside the button, which stays whole and names it whole on hover\n const style = cn(buttonClass({ variant: 'secondary', size: 'sm' }), 'min-w-0 max-w-full shrink')\n const label = <span className=\"truncate\">{shown.label}</span>\n if ('href' in shown) {\n return (\n <a href={shown.href} target=\"_blank\" rel=\"noreferrer\" title={shown.label} className={style}>\n {label}\n <span className=\"sr-only\"> {text('opensNewTab')}</span>\n <ExternalLink aria-hidden className=\"size-3.5 shrink-0\" />\n </a>\n )\n }\n return (\n <AppLink to={shown.to} title={shown.label} className={style}>\n {label}\n </AppLink>\n )\n}\n","import { createColumnHelper, rowSelectionFeature, rowSortingFeature, tableFeatures } from '@tanstack/react-table'\nimport { renderCell } from './cells'\nimport type { ColumnSpec, GridRow } from './column-spec'\n\nexport const features = tableFeatures({ rowSortingFeature, rowSelectionFeature })\n\nconst helper = createColumnHelper<typeof features, GridRow>()\n\nexport const buildColumns = (specs: ColumnSpec[]) =>\n helper.columns(\n specs.map((spec) =>\n helper.accessor((row) => (spec.value ? spec.value(row) : row[spec.id]), {\n id: spec.id,\n header: spec.header,\n enableSorting: spec.sortable ?? false,\n cell: (context) => (spec.render ? spec.render(context.row.original) : renderCell(spec, context.getValue(), context.row.original)),\n }),\n ),\n )\n","import type { GridRow } from './column-spec'\n\n/**\n * What can be done with the selected rows. `available` narrows them to those the action applies to: it is offered\n * while one of them does, `label` counts those, and `onRun` gets them with how many selected rows it skips. One that asks\n * first returns a promise of the rows still open once it ends, such as those it was refused: all of them when its dialog\n * is cancelled.\n */\nexport type BulkAction = { label: (count: number) => string; destructive?: boolean; available?: (row: GridRow) => boolean; onRun: (rows: GridRow[], skipped: number) => void | Promise<GridRow[]> }\n\n/** The actions offered for `selected`, each with the rows it runs on and how many it skips. */\nexport const offeredBulkActions = (actions: BulkAction[], selected: GridRow[]) =>\n actions.flatMap((action) => {\n const rows = action.available ? selected.filter(action.available) : selected\n return rows.length === 0 ? [] : [{ action, rows, skipped: selected.length - rows.length }]\n })\n\n/** Runs `action` on `rows` and resolves to those it is done with, to deselect: all of them unless its promise names some still open. */\nexport const runBulkAction = async (action: BulkAction, rows: GridRow[], skipped: number) => {\n const open = await action.onRun(rows, skipped)\n if (!open) return rows\n const kept = new Set(open.map((row) => row.id))\n return rows.filter((row) => !kept.has(row.id))\n}\n\n/** A `runBulkAction` that starts no second run while one is in flight: a press meanwhile resolves to nothing. */\nexport const oneBulkRunAtATime = () => {\n let running = false\n return async (action: BulkAction, rows: GridRow[], skipped: number) => {\n if (running) return\n running = true\n try {\n return await runBulkAction(action, rows, skipped)\n } finally {\n running = false\n }\n }\n}\n","import { formatApproxRows, formatInt } from '../format/number'\nimport { cn } from '../lib/cn'\nimport { text } from './messages'\n\nexport type GridFooterProps = {\n total: number\n selectedCount: number\n bulkActions?: Array<{ label: string; destructive?: boolean; onRun: () => void }>\n className?: string\n}\n\n/** How many rows match and, with rows selected, how many and what can be done with them. */\nexport const GridFooter = ({ total, selectedCount, bulkActions = [], className }: GridFooterProps) => (\n <div className={cn('flex h-9 shrink-0 items-center border-t bg-surface px-3 text-xs text-muted-foreground', className)}>\n <span className=\"flex items-center tabular-nums\">\n {formatApproxRows(total)}\n {selectedCount > 0 && <span className=\"ml-3 font-medium text-primary-text\">{text('selected', { count: formatInt(selectedCount) })}</span>}\n {selectedCount > 0 &&\n bulkActions.map((action) => (\n <button\n key={action.label}\n type=\"button\"\n onClick={action.onRun}\n className={cn('ml-3 rounded border bg-background px-2 py-0.5 font-medium hover:bg-muted', action.destructive ? 'border-danger/40 text-danger-text' : 'text-foreground')}\n >\n {action.label}\n </button>\n ))}\n </span>\n </div>\n)\n","import { MoreHorizontal } from 'lucide-react'\nimport { createPortal } from 'react-dom'\nimport { cn } from '../lib/cn'\nimport { usePopoverMenu } from '../primitives/popover-menu'\nimport { RouteLink, type RouteTarget } from '../primitives/route-link'\nimport type { GridRow } from './column-spec'\nimport { text } from './messages'\n\n/**\n * `label` may name the row's own text. `available` hides the action for rows it does not apply to, for example a delete\n * the server will refuse; `blocked` shows it disabled, with why as its tooltip.\n */\ntype RowActionBase = { label: string | ((row: GridRow) => string); destructive?: boolean; available?: (row: GridRow) => boolean; blocked?: (row: GridRow) => string | undefined }\n/** `link` makes the item an ordinary link to where it goes, as every navigation is, unless it is `blocked`; `onSelect` runs anything else. */\nexport type RowAction = RowActionBase & ({ onSelect: (row: GridRow) => void; link?: never } | { link: (row: GridRow) => RouteTarget; onSelect?: never })\n\nconst labelOf = (action: RowAction, row: GridRow) => (typeof action.label === 'string' ? action.label : action.label(row))\n\n/** The actions that apply to a row; a row with none gets no menu at all. */\nexport const availableActions = (actions: RowAction[], row: GridRow) => actions.filter((action) => action.available?.(row) ?? true)\n\n/**\n * The \"...\" button at the end of a row, with a small menu of the row's actions. The menu is portalled to the body:\n * every grid row is its own stacking context and the grid body clips, so a menu inside the row would sit under the\n * rows below it.\n */\nexport const RowMenu = ({ row, actions }: { row: GridRow; actions: RowAction[] }) => {\n const { open, setOpen, place, button, menu } = usePopoverMenu()\n\n return (\n <div className=\"relative flex justify-center bg-inherit\" onClick={(event) => event.stopPropagation()}>\n <button ref={button} type=\"button\" aria-label={text('rowActions')} aria-haspopup=\"menu\" aria-expanded={open} onClick={() => setOpen(!open)} className=\"inline-flex items-center justify-center rounded p-1 text-faint-foreground hover:bg-muted hover:text-foreground pointer-coarse:size-11\">\n <MoreHorizontal className=\"size-4\" />\n </button>\n {open &&\n createPortal(\n <ul ref={menu} role=\"menu\" onClick={(event) => event.stopPropagation()} style={place ?? { visibility: 'hidden' }} className=\"fixed z-50 min-w-36 rounded-md border bg-background py-1 shadow-pop\">\n {actions.map((action, index) => {\n const label = labelOf(action, row)\n const blocked = action.blocked?.(row)\n const itemClass = cn('block w-full px-3 py-1.5 text-left hover:bg-muted disabled:cursor-default disabled:opacity-60 disabled:hover:bg-transparent', action.destructive && 'text-danger-text')\n return (\n <li key={index} role=\"none\">\n {action.link && blocked === undefined ? (\n <RouteLink role=\"menuitem\" to={action.link(row)} onClick={() => setOpen(false)} className={itemClass}>\n {label}\n </RouteLink>\n ) : (\n <button\n type=\"button\"\n role=\"menuitem\"\n disabled={blocked !== undefined}\n title={blocked}\n className={itemClass}\n onClick={() => {\n setOpen(false)\n action.onSelect?.(row)\n }}\n >\n {label}\n </button>\n )}\n </li>\n )\n })}\n </ul>,\n document.body,\n )}\n </div>\n )\n}\n","import type { ColumnSpec } from './column-spec'\n\n/** Wide enough for the checkbox plus the largest row number, with thousands separators. */\nexport const gutterWidthFor = (total: number) => 52 + Math.ceil(String(total).length * 1.33) * 7\n\nexport const rowMenuWidth = 40\n\n/** On phones the gutter holds only the checkbox, leaving room for the columns. */\nexport const compactGutter = 40\n\n/** Columns may shrink to this share of their width on desktop; on narrow screens they keep it whole and the grid scrolls. */\nexport const desktopMinScale = 0.6\n\nconst minWidthOf = (spec: ColumnSpec, minScale: number) => Math.max(spec.minWidth ?? 0, spec.width * minScale)\n\nconst columnTemplate = (spec: ColumnSpec, minScale: number) =>\n spec.fixed ? `${Math.max(spec.minWidth ?? 0, spec.width)}px` : `minmax(${minWidthOf(spec, minScale)}px, ${spec.width}fr)`\n\nexport const gridTemplate = (specs: ColumnSpec[], gutter: number, trailing = 0, minScale = desktopMinScale) =>\n `${gutter}px ${specs.map((spec) => columnTemplate(spec, minScale)).join(' ')}${trailing > 0 ? ` ${trailing}px` : ''}`\n\n/** The narrowest the grid can be before it has to scroll sideways. */\nexport const gridMinWidth = (specs: ColumnSpec[], gutter: number, trailing = 0, minScale = desktopMinScale) =>\n gutter + trailing + specs.reduce((sum, spec) => sum + (spec.fixed ? Math.max(spec.minWidth ?? 0, spec.width) : minWidthOf(spec, minScale)), 0)\n","import { useCallback, useRef, useState } from 'react'\n\n/** Tracks whether the grid is scrolled sideways (`scrolled`) and whether more lies to the right (`more`). */\nexport const useHorizontalScroll = () => {\n const ref = useRef<HTMLDivElement | null>(null)\n const observer = useRef<ResizeObserver | null>(null)\n const [edges, setEdges] = useState({ scrolled: false, more: false })\n\n const measure = useCallback(() => {\n const element = ref.current\n if (!element) return\n const next = { scrolled: element.scrollLeft > 1, more: element.scrollLeft + element.clientWidth < element.scrollWidth - 1 }\n setEdges((current) => (current.scrolled === next.scrolled && current.more === next.more ? current : next))\n }, [])\n\n // Observe once per mounted element rather than on every render: re-subscribing each render made the observer's\n // initial callback schedule another render, which re-subscribed again, looping until React bailed out.\n const attach = useCallback(\n (element: HTMLDivElement | null) => {\n observer.current?.disconnect()\n observer.current = null\n ref.current = element\n if (!element) return\n const next = new ResizeObserver(measure)\n next.observe(element)\n for (const child of Array.from(element.children)) next.observe(child)\n observer.current = next\n measure()\n },\n [measure],\n )\n\n return { ref, attach, onScroll: measure, ...edges }\n}\n","import { guarded } from '../lib/guarded'\n\nconst prefix = 'protobase:pinned:'\n\nexport const pinnedStorageKey = (userId: string, resource: string) => `${prefix}${userId}:${resource}`\n\nexport const readPinned = (storage: Pick<Storage, 'getItem'>, key: string): string[] | undefined =>\n guarded(() => {\n const raw = storage.getItem(key)\n if (raw === null) return undefined\n const parsed: unknown = JSON.parse(raw)\n return Array.isArray(parsed) && parsed.every((entry) => typeof entry === 'string') ? parsed : undefined\n }, undefined)\n\n/** Keeps an empty list too, so a column pinned by default and then unpinned stays unpinned. */\nexport const writePinned = (storage: Pick<Storage, 'setItem'>, key: string, pinned: string[]) => guarded(() => storage.setItem(key, JSON.stringify(pinned)), undefined)\n","import { useCallback, useState } from 'react'\nimport { readPinned, writePinned } from './pinned-storage'\n\n/**\n * The ids of the columns pinned to the left, in pin order. With a `storageKey` the choice is kept in local storage\n * (per user and resource); `initial` applies until the user has chosen, as it is on each render.\n */\nexport const usePinnedColumns = (storageKey: string | undefined, initial: string[] = []) => {\n const [chosen, setChosen] = useState(() => (storageKey ? readPinned(localStorage, storageKey) : undefined))\n const update = useCallback(\n (next: string[]) => {\n setChosen(next)\n if (storageKey) writePinned(localStorage, storageKey, next)\n },\n [storageKey],\n )\n return [chosen ?? initial, update] as const\n}\n","import type { ColumnSpec } from './column-spec'\n\n/**\n * The columns pinned until the user chooses: the leading columns through the title column, when it is first or second.\n * Pinned columns move to the front, so a title further right stays unpinned rather than reorder the list; pins only\n * take effect once the grid is too wide and scrolls sideways.\n */\nexport const defaultPins = (specs: ColumnSpec[]) => {\n const index = specs.findIndex((spec) => spec.title)\n if (index < 0 || index > 1) return []\n return specs.slice(0, index + 1).map((spec) => spec.id)\n}\n","import { useMemo, useState } from 'react'\nimport type { ColumnSpec, GridRow } from './column-spec'\nimport { fitColumns } from './content-widths'\n\ntype Size = Pick<ColumnSpec, 'width' | 'minWidth' | 'fixed'>\n\ntype Fitted = { key: string; sizes: Record<string, Size> }\n\nconst sizesOf = (specs: ColumnSpec[]) => Object.fromEntries(specs.map(({ id, width, minWidth, fixed }) => [id, { width, minWidth, fixed }]))\n\n/** What a fit depends on besides the rows: each column with the bounds its width is clamped to. */\nexport const fitKey = (columns: ColumnSpec[]) =>\n columns\n .map(({ id, minWidth, maxWidth }) => `${id}:${minWidth ?? ''}:${maxWidth ?? ''}`)\n .sort()\n .join(' ')\n\n/**\n * `columns` sized by the first rows shown, fitted once per set of columns and their bounds: later pages, filters and\n * sorts keep those widths, so columns never jump while scrolling, and a longer value later on is cut, with the whole of\n * it on hover.\n */\nexport const useFittedColumns = (columns: ColumnSpec[], rows: GridRow[]) => {\n const key = fitKey(columns)\n const [fitted, setFitted] = useState<Fitted>()\n const current = fitted?.key === key ? fitted : undefined\n // Fitting is stored while rendering, the way React keeps state derived from earlier renders, so no frame shows the old widths\n if (!current && rows.length > 0) setFitted({ key, sizes: sizesOf(fitColumns(columns, rows)) })\n const sizes = current?.sizes\n return useMemo(() => (sizes ? columns.map((spec) => ({ ...spec, ...sizes[spec.id] })) : columns), [columns, sizes])\n}\n","import type { ColumnSpec } from './column-spec'\n\n/** The narrowest a column can be dragged: room for a few letters of its header and its menu button. */\nexport const minColumnWidth = 64\n\n/** Pixels an arrow key moves a column's edge. */\nexport const resizeStep = 16\n\n/**\n * The width a column dragged `delta` pixels from `start` takes, never below `minColumnWidth`, or below `start` for a\n * column the app made narrower than that, such as one of check marks.\n */\nexport const resizedWidth = (start: number, delta: number) => Math.max(Math.min(minColumnWidth, start), Math.round(start + delta))\n\n/**\n * `specs` with the widths a resize set them to: those columns take that width whole, even below the minimum width the\n * app gave them, as `resizedWidth` keeps them usable.\n */\nexport const withResizedWidths = (specs: ColumnSpec[], widths: Record<string, number>) =>\n specs.map((spec) => (spec.id in widths ? { ...spec, fixed: true, width: widths[spec.id]!, minWidth: undefined } : spec))\n","import { useState, type KeyboardEvent, type PointerEvent, type RefObject } from 'react'\nimport { resizeStep, resizedWidth } from './column-resize'\n\n/** The widths every header cell has now, by column id, so that resizing one column leaves the others as they are. */\nconst measuredWidths = (header: HTMLElement) =>\n Object.fromEntries([...header.querySelectorAll<HTMLElement>('[data-col-id]')].map((cell) => [cell.dataset.colId!, cell.offsetWidth]))\n\n/**\n * Column widths the user sets by dragging a header cell's edge, or with the arrow keys on it, by column id. They live\n * as long as the grid does: a reload or another page shows the app's widths again.\n */\nexport const useColumnResize = (header: RefObject<HTMLElement | null>) => {\n const [widths, setWidths] = useState<Record<string, number>>({})\n\n // The first resize fixes every column at the width it has, so that only the one being dragged changes\n const startWidths = () => ({ ...(header.current ? measuredWidths(header.current) : {}), ...widths })\n\n const onPointerDown = (id: string, event: PointerEvent<HTMLElement>) => {\n if (event.button !== 0) return\n event.preventDefault()\n const start = startWidths()\n const startX = event.clientX\n // Followed on the window, so the drag goes on wherever the pointer goes and ends wherever it is let go\n const onMove = (move: globalThis.PointerEvent) => setWidths({ ...start, [id]: resizedWidth(start[id] ?? 0, move.clientX - startX) })\n const onEnd = () => {\n window.removeEventListener('pointermove', onMove)\n window.removeEventListener('pointerup', onEnd)\n window.removeEventListener('pointercancel', onEnd)\n }\n window.addEventListener('pointermove', onMove)\n window.addEventListener('pointerup', onEnd)\n window.addEventListener('pointercancel', onEnd)\n }\n\n const onKeyDown = (id: string, event: KeyboardEvent<HTMLElement>) => {\n const delta = event.key === 'ArrowRight' ? resizeStep : event.key === 'ArrowLeft' ? -resizeStep : 0\n if (delta === 0) return\n event.preventDefault()\n const start = startWidths()\n setWidths({ ...start, [id]: resizedWidth(start[id] ?? 0, delta) })\n }\n\n return { widths, onPointerDown, onKeyDown }\n}\n","import { useSyncExternalStore } from 'react'\n\nconst rootFontSize = () => parseFloat(getComputedStyle(document.documentElement).fontSize)\n\n/** The root text size in pixels, what `1rem` is, read again on a resize of the window such as a zoom. */\nexport const useRootFontSize = () =>\n useSyncExternalStore(\n (onChange) => {\n window.addEventListener('resize', onChange)\n return () => window.removeEventListener('resize', onChange)\n },\n rootFontSize,\n () => 16,\n )\n","// In rem, as the header's `h-8`, the footer's `h-9` and the cells' text and buttons are\nconst header = 2\nconst row = 2.25\nconst compactRow = 1.75\n// A small button's height and the gap above it, for a column with something `below` its cells\nconst below = 2\nconst footer = 2.25\n\n/** The grid's heights in pixels, which rows are placed and virtualized by, for a root text size of `rem` pixels. */\nexport const gridHeights = (rem: number, { compact, withBelow }: { compact: boolean; withBelow: boolean }) => ({\n header: header * rem,\n row: ((compact ? compactRow : row) + (withBelow ? below : 0)) * rem,\n footer: footer * rem,\n})\n","import type { ReactNode } from 'react'\nimport type { BadgeTone } from '../primitives/badge'\nimport type { ContactFormat } from '../live/contact-links'\n\nexport type ColumnKind =\n | 'text' | 'id' | 'money' | 'date' | 'datetime' | 'status' | 'relation'\n | 'boolean' | 'number' | 'signed' | 'percent' | 'user' | 'file'\n\n/** A person a `user` column shows for an id. */\nexport type CellUser = { name: string; initials: string; hue: number }\n\nexport type GridRow = { id: string } & Record<string, unknown>\n\nexport type ColumnSpec = {\n id: string\n header: string\n kind: ColumnKind\n /** Relative width in px; columns grow proportionally to fill the grid. */\n width: number\n /** Pixels the column never shrinks below, for values that must stay whole such as identifiers. */\n minWidth?: number\n /** Pixels the column never grows past when it is sized by `fit`. */\n maxWidth?: number\n /** For a column drawn by its own `render`: the pixels a row's cell needs, so the column takes its widest row's width. */\n fit?: (row: GridRow) => number\n /** A fixed pixel width instead of a share of the leftover space, for values of known length such as timestamps. */\n fixed?: boolean\n sortable?: boolean\n /** The record's title column: it gets the largest share of the width and is pinned by default. */\n title?: boolean\n /** Tints the column to mark it as new. */\n highlight?: boolean\n /** For a `datetime` column: shows how long ago each value is, its exact time on hover. */\n relative?: boolean\n /** The ISO 4217 code of a `money` column's currency, which it needs. */\n currency?: string\n /** Decimals a `money` column shows instead of the currency's usual ones. */\n decimals?: number\n /** Text before a number, such as a currency sign, for `number` and `signed` columns. */\n prefix?: string\n /** Text after a number, such as a unit, for `number`, `signed` and `money` columns. */\n suffix?: string\n /** Badge tone per value, for `status` columns. */\n tones?: Record<string, BadgeTone>\n /** A hex colour per value that fills its badge instead of its tone, for `status` columns; a tone name is no colour. */\n colors?: Record<string, string>\n /** The shape of a `status` column's badges. */\n shape?: 'arrow'\n /** Badge text per value, for `status` columns; a value without one reads as itself in words. */\n labels?: Record<string, string>\n /** For a `text` column of addresses: each value a link that writes to, calls or opens it. */\n link?: ContactFormat\n /** For a `link` column: the text a row's link shows instead of the address; the address when it gives none. */\n linkText?: (row: GridRow) => string | undefined\n /** For a `user` column: the person behind an id; an id it does not know shows as itself. */\n users?: (id: string) => CellUser | undefined\n /** Reads the cell value; defaults to `row[id]`. */\n value?: (row: GridRow) => unknown\n /** Draws the cell instead of its kind, such as a field type's cell. */\n render?: (row: GridRow) => ReactNode\n /** Drawn under the cell's content, outside the link a title cell is; every row of the grid grows to hold it. */\n below?: (row: GridRow) => ReactNode\n}\n\nexport const isRightAligned = (kind: ColumnKind) => kind === 'money' || kind === 'number' || kind === 'signed' || kind === 'percent'\n","import { MoreHorizontal } from 'lucide-react'\nimport { createPortal } from 'react-dom'\nimport { usePopoverMenu } from '../primitives/popover-menu'\nimport { text } from './messages'\n\nexport type HeaderMenuProps = { header: string; pinned: boolean; sortable: boolean; onTogglePin: () => void }\n\n/** Why a column header does nothing when pressed: a list sorts only on the columns its view makes sortable. */\nexport const unsortableText = () => text('unsortable')\n\n/**\n * The \"...\" in a column header: pinning the column to the left edge, and saying so when the list can't sort by it. The\n * menu is portalled to the body, as the row menu is: the header row clips, so a menu inside it would be cut off at the\n * header's bottom edge, with the rows showing where it should be.\n */\nexport const HeaderMenu = ({ header, pinned, sortable, onTogglePin }: HeaderMenuProps) => {\n const { open, setOpen, place, button, menu } = usePopoverMenu()\n\n return (\n <div className=\"relative ml-auto shrink-0\">\n <button\n ref={button}\n type=\"button\"\n aria-label={text('columnMenu', { header })}\n aria-haspopup=\"menu\"\n aria-expanded={open}\n onClick={() => setOpen(!open)}\n className=\"relative inline-flex size-5 items-center justify-center rounded text-faint-foreground hover:bg-muted hover:text-foreground focus-visible:opacity-100 after:absolute after:-inset-2 after:content-[''] md:opacity-0 md:group-hover/cell:opacity-100 aria-expanded:opacity-100\"\n >\n <MoreHorizontal className=\"size-3.5\" />\n </button>\n {open &&\n createPortal(\n <ul ref={menu} role=\"menu\" style={place ?? { visibility: 'hidden' }} className=\"fixed z-50 min-w-32 rounded-md border bg-background py-1 text-body font-normal text-foreground shadow-pop\">\n {!sortable && (\n <li role=\"none\">\n <span role=\"menuitem\" aria-disabled=\"true\" className=\"block min-h-9 whitespace-nowrap px-3 py-1.5 text-muted-foreground\">\n {unsortableText()}\n </span>\n </li>\n )}\n <li role=\"none\">\n <button\n type=\"button\"\n role=\"menuitem\"\n className=\"block min-h-9 w-full whitespace-nowrap px-3 py-1.5 text-left hover:bg-muted\"\n onClick={() => {\n setOpen(false)\n onTogglePin()\n }}\n >\n {pinned ? text('unpin') : text('pinToLeft')}\n </button>\n </li>\n </ul>,\n document.body,\n )}\n </div>\n )\n}\n","import type { KeyboardEvent, PointerEvent } from 'react'\nimport { minColumnWidth } from './column-resize'\nimport { text } from './messages'\n\nexport type ColumnResize = {\n onPointerDown: (id: string, event: PointerEvent<HTMLElement>) => void\n onKeyDown: (id: string, event: KeyboardEvent<HTMLElement>) => void\n}\n\n/**\n * The right edge of a header cell, dragged to make its column wider or narrower. It sits beside the sort button rather\n * than in it, so a drag never sorts.\n */\nexport const ResizeHandle = ({ id, header, width, resize }: { id: string; header: string; width?: number; resize: ColumnResize }) => (\n <div\n role=\"separator\"\n aria-orientation=\"vertical\"\n aria-label={text('resizeColumn', { header })}\n aria-valuemin={minColumnWidth}\n aria-valuenow={width}\n tabIndex={0}\n onPointerDown={(event) => resize.onPointerDown(id, event)}\n onKeyDown={(event) => resize.onKeyDown(id, event)}\n className=\"group/resize absolute inset-y-0 right-0 z-10 flex w-2 cursor-col-resize touch-none justify-end outline-none\"\n >\n <div className=\"h-full w-0.5 bg-transparent group-hover/resize:bg-primary group-focus-visible/resize:bg-primary group-active/resize:bg-primary\" />\n </div>\n)\n","import { ArrowDown, ArrowUp, ChevronsUpDown } from 'lucide-react'\nimport { Checkbox } from '../primitives/checkbox'\nimport { cn } from '../lib/cn'\nimport { isRightAligned, type ColumnSpec } from './column-spec'\nimport { HeaderMenu, unsortableText } from './header-menu'\nimport { compactGutter, gridTemplate } from './grid-template'\nimport { text } from './messages'\nimport { ResizeHandle, type ColumnResize } from './resize-handle'\n\nexport type HeaderCell = { spec: ColumnSpec; sorted: 'asc' | 'desc' | false; onSort: (event: unknown) => void }\n\nexport type GridHeaderProps = {\n cells: HeaderCell[]\n specs: ColumnSpec[]\n gutter: number\n selectedCount: number\n selectable: boolean\n trailing?: number\n minScale?: number\n /** Left offsets of the pinned columns, by id. */\n pins?: Record<string, number>\n /** The pinned column next to the scrolling ones: it gets the edge shadow once the grid scrolls sideways. */\n lastPinned?: string\n scrolled?: boolean\n onTogglePin: (id: string) => void\n /** Lets each column be resized by dragging its header's right edge. */\n resize?: ColumnResize\n /** The widths columns were resized to, by id. */\n widths?: Record<string, number>\n onClearSelection: () => void\n}\n\nconst SortIcon = ({ sorted }: { sorted: HeaderCell['sorted'] }) => {\n if (sorted === 'asc') return <ArrowUp className=\"size-3 text-foreground\" />\n if (sorted === 'desc') return <ArrowDown className=\"size-3 text-foreground\" />\n return <ChevronsUpDown className=\"size-3 opacity-0 group-hover/head:opacity-100\" />\n}\n\nconst HeaderLabel = ({ spec }: { spec: ColumnSpec }) => (\n <>\n <span className=\"truncate\">{spec.header}</span>\n {spec.highlight && <span className=\"rounded bg-primary px-1 text-[0.625rem] font-semibold uppercase leading-4 text-primary-foreground\">{text('new')}</span>}\n </>\n)\n\nexport const GridHeader = ({ cells, specs, gutter, selectedCount, selectable, trailing, minScale, pins = {}, lastPinned, scrolled, onTogglePin, resize, widths = {}, onClearSelection }: GridHeaderProps) => (\n <div className=\"grid h-8 shrink-0 items-center border-b bg-surface text-body font-medium text-muted-foreground\" style={{ gridTemplateColumns: gridTemplate(specs, gutter, trailing, minScale) }} role=\"row\">\n <div className={cn('sticky left-0 z-10 flex h-full items-center gap-2 bg-inherit pl-3', scrolled && !lastPinned && 'shadow-[1px_0_0_var(--border),4px_0_6px_-2px_rgb(0_0_0/0.12)]')} style={{ width: gutter }}>\n {/* It only clears a selection, so with none it says so and cannot be pressed */}\n {selectable && <Checkbox checked={false} indeterminate={selectedCount > 0} label={selectedCount > 0 ? text('clearSelection') : text('noRowsSelected')} disabled={selectedCount === 0} onChange={onClearSelection} className={cn(selectedCount === 0 && 'opacity-60')} />}\n {gutter > compactGutter && <span className=\"w-6 text-right text-faint-foreground\">#</span>}\n </div>\n {cells.map(({ spec, sorted, onSort }) => {\n const pinned = spec.id in pins\n return (\n <div\n key={spec.id}\n data-col-id={spec.id}\n style={pinned ? { left: pins[spec.id] } : undefined}\n className={cn(\n 'group/cell flex h-full min-w-0 items-center',\n pinned ? 'sticky z-10 bg-inherit' : 'relative',\n pinned && scrolled && spec.id === lastPinned && 'shadow-[1px_0_0_var(--border),4px_0_6px_-2px_rgb(0_0_0/0.12)]',\n spec.highlight && 'bg-primary-soft text-primary-text',\n )}\n >\n {spec.sortable ? (\n <button\n type=\"button\"\n onClick={onSort}\n className={cn('group/head flex h-full min-w-0 flex-1 items-center gap-1 pl-3 pr-1 text-left', isRightAligned(spec.kind) && 'justify-end', 'hover:text-foreground', sorted && 'text-foreground')}\n >\n <HeaderLabel spec={spec} />\n <SortIcon sorted={sorted} />\n </button>\n ) : (\n // Not a button: nothing happens on a press, and a disabled button would not show its tooltip\n <div title={unsortableText()} className={cn('flex h-full min-w-0 flex-1 items-center gap-1 pl-3 pr-1 text-left', isRightAligned(spec.kind) && 'justify-end')}>\n <HeaderLabel spec={spec} />\n </div>\n )}\n <div className=\"pr-1.5\">\n <HeaderMenu header={spec.header} pinned={pinned} sortable={Boolean(spec.sortable)} onTogglePin={() => onTogglePin(spec.id)} />\n </div>\n {resize && <ResizeHandle id={spec.id} header={spec.header} width={widths[spec.id]} resize={resize} />}\n </div>\n )\n })}\n {trailing ? <div className=\"sticky right-0 z-10 h-full bg-inherit\" /> : null}\n </div>\n)\n","import type { HTMLAttributes, MouseEvent, ReactNode, Ref } from 'react'\nimport { formatInt } from '../format/number'\nimport { Checkbox } from '../primitives/checkbox'\nimport { Skeleton } from '../primitives/skeleton'\nimport { cn } from '../lib/cn'\nimport { isRightAligned, type ColumnSpec } from './column-spec'\nimport { compactGutter, gridTemplate } from './grid-template'\nimport { text } from './messages'\n\ntype RowFrame = { specs: ColumnSpec[]; gutter: number; index: number; offset: number; height: number; selectable: boolean; trailing?: number; minScale?: number; scrolled?: boolean; pins?: Record<string, number>; lastPinned?: string }\n\nconst frameStyle = (frame: RowFrame) => ({\n gridTemplateColumns: gridTemplate(frame.specs, frame.gutter, frame.trailing, frame.minScale),\n height: frame.height,\n transform: `translateY(${frame.offset}px)`,\n})\n\n/** Pinned cells need a solid background; `bg-inherit` takes the row's, so hover and selection still show. */\nconst cellClass = (spec: ColumnSpec, frame: Pick<RowFrame, 'pins' | 'lastPinned' | 'scrolled'>) =>\n cn(\n 'flex h-full min-w-0 items-center overflow-hidden whitespace-nowrap px-3',\n isRightAligned(spec.kind) && 'justify-end',\n spec.highlight && 'bg-primary-soft/60',\n frame.pins && spec.id in frame.pins && 'sticky z-10 bg-inherit',\n frame.scrolled && spec.id === frame.lastPinned && 'shadow-[1px_0_0_var(--border),4px_0_6px_-2px_rgb(0_0_0/0.12)]',\n )\n\nconst pinStyle = (spec: ColumnSpec, pins?: Record<string, number>) => (pins && spec.id in pins ? { left: pins[spec.id] } : undefined)\n\n/**\n * The selection column never scrolls away, so rows can be selected from anywhere in a wide grid.\n * The whole cell toggles the row instead of opening it; the checkbox's own click bubbles up to it.\n */\nconst Gutter = ({ width, index, selectable, selected, onToggle, edge }: { width: number; index: number; selectable: boolean; selected?: boolean; onToggle?: () => void; edge?: boolean }) => (\n <div\n onClick={selectable ? (event) => { event.stopPropagation(); onToggle?.() } : undefined}\n className={cn('sticky left-0 z-10 flex h-full items-center gap-2 bg-inherit pl-3', selectable && 'cursor-default', edge && 'shadow-[1px_0_0_var(--border),4px_0_6px_-2px_rgb(0_0_0/0.12)]')}\n style={{ width }}\n >\n {selectable && <Checkbox checked={Boolean(selected)} label={text('selectRow', { row: index + 1 })} />}\n {width > compactGutter && <span className=\"min-w-6 text-right text-[0.6875rem] tabular-nums text-faint-foreground\">{formatInt(index + 1)}</span>}\n </div>\n)\n\n/**\n * A cell of a row: its column and content and, in a grid whose cells are edited in place, its handlers and whether it\n * is the chosen cell, is being edited, or can be.\n */\nexport type RowCell = { spec: ColumnSpec; content: ReactNode; props?: HTMLAttributes<HTMLDivElement>; chosen?: boolean; editing?: boolean; editable?: boolean }\n\nexport type DataRowProps = RowFrame & {\n cells: RowCell[]\n selected: boolean\n /** The row the page shows the details of, marked `aria-current` and looking selected. */\n current?: boolean\n onToggle: () => void\n onOpen?: () => void\n menu?: ReactNode\n /**\n * A drag handle in the checkbox's place, for a row moved by hand, with the row's element, how far it is dragged and\n * its move back. Such a row is placed by `top`, since the drag library measures rows without their transforms.\n */\n handle?: ReactNode\n rowRef?: Ref<HTMLDivElement>\n dragY?: number\n transition?: string\n dragging?: boolean\n}\n\nconst dragStyle = (frame: RowFrame, dragY: number, transition: string | undefined) => ({\n gridTemplateColumns: gridTemplate(frame.specs, frame.gutter, frame.trailing, frame.minScale),\n height: frame.height,\n top: frame.offset,\n transform: dragY === 0 ? undefined : `translateY(${dragY}px)`,\n transition,\n})\n\n// A link in the row, such as its title, goes where it points itself: a Cmd-click opening it in a new tab leaves this one.\nconst openUnlessLink = (onOpen: () => void) => (event: MouseEvent) => {\n if ((event.target as Element).closest('a')) return\n onOpen()\n}\n\nexport const DataRow = ({ cells, selected, current = false, onToggle, onOpen, menu, handle, rowRef, dragY, transition, dragging, ...frame }: DataRowProps) => (\n <div\n ref={rowRef}\n role=\"row\"\n aria-current={current || undefined}\n data-pressable={onOpen ? '' : undefined}\n onClick={onOpen && openUnlessLink(onOpen)}\n className={cn('absolute inset-x-0 top-0 grid items-center border-b', selected || current ? 'bg-primary-soft' : 'bg-background hover:bg-surface', onOpen && 'cursor-pointer', dragging && 'z-30 bg-surface shadow-pop')}\n style={dragY === undefined ? frameStyle(frame) : dragStyle(frame, dragY, transition)}\n >\n {handle ? (\n <div className={cn('sticky left-0 z-10 flex h-full items-center bg-inherit pl-1.5', frame.scrolled && !frame.lastPinned && 'shadow-[1px_0_0_var(--border),4px_0_6px_-2px_rgb(0_0_0/0.12)]')} style={{ width: frame.gutter }}>\n {handle}\n </div>\n ) : (\n <Gutter width={frame.gutter} index={frame.index} selectable={frame.selectable} selected={selected} onToggle={onToggle} edge={frame.scrolled && !frame.lastPinned} />\n )}\n {cells.map(({ spec, content, props, chosen, editing, editable }) => (\n <div\n key={spec.id}\n role={props ? 'gridcell' : 'cell'}\n {...props}\n className={cn(\n cellClass(spec, frame),\n props && 'scroll-mb-[calc(var(--pb-sticky-bottom,0px)+3rem)] scroll-mt-[calc(var(--pb-sticky-top,0px)+2rem)] outline-none',\n editable && !editing && 'cursor-default',\n chosen && 'shadow-[inset_0_0_0_2px_var(--primary)]',\n editing && 'z-30 overflow-visible bg-background px-1',\n )}\n style={pinStyle(spec, frame.pins)}\n >\n {content}\n </div>\n ))}\n {/* The menu stays at the right edge while the row scrolls sideways */}\n {menu && <div className=\"sticky right-0 z-10 flex h-full items-center justify-center bg-inherit\">{menu}</div>}\n </div>\n)\n\nconst skeletonWidths = ['w-3/4', 'w-1/2', 'w-2/3', 'w-5/6', 'w-2/5']\n\nexport const SkeletonRow = (frame: RowFrame) => (\n <div role=\"row\" aria-busy className=\"absolute inset-x-0 top-0 grid items-center border-b bg-background\" style={frameStyle(frame)}>\n <Gutter width={frame.gutter} index={frame.index} selectable={false} edge={frame.scrolled && !frame.lastPinned} />\n {frame.specs.map((spec, column) => (\n <div key={spec.id} className={cellClass(spec, frame)} style={pinStyle(spec, frame.pins)}>\n <Skeleton className={cn('h-2.5', skeletonWidths[(frame.index + column) % skeletonWidths.length], isRightAligned(spec.kind) && 'ml-auto')} />\n </div>\n ))}\n </div>\n)\n","/** Browsers cap element height (about 17M px in the strictest); stay well below it. */\nexport const maxContentHeight = 10_000_000\n\nexport type Geometry = ReturnType<typeof gridGeometry>\n\n/** The list's height in the page, `contentHeight`: its true height, or the cap when the rows need more. */\nexport const gridGeometry = (total: number, rowHeight: number, viewportHeight: number) => {\n const trueHeight = total * rowHeight\n const contentHeight = Math.min(trueHeight, maxContentHeight)\n return {\n rowHeight,\n trueHeight,\n contentHeight,\n scaled: trueHeight > contentHeight,\n maxTop: Math.max(0, trueHeight - viewportHeight),\n maxScroll: Math.max(0, contentHeight - viewportHeight),\n }\n}\n\n/**\n * The offset into the rows (the virtual offset) shown at `position`, how far the top of the view is into the list.\n * They are the same unless the list is capped: then the capped range maps onto all the rows, and a position before or\n * after it moves one to one.\n */\nexport const topFromScroll = (geometry: Geometry, position: number) => {\n if (!geometry.scaled || position <= 0) return position\n if (position >= geometry.maxScroll) return geometry.maxTop + position - geometry.maxScroll\n return (position / geometry.maxScroll) * geometry.maxTop\n}\n\nexport const scrollFromTop = (geometry: Geometry, top: number) => {\n if (!geometry.scaled || top <= 0) return top\n if (top >= geometry.maxTop) return geometry.maxScroll + top - geometry.maxTop\n return (top / geometry.maxTop) * geometry.maxScroll\n}\n\n/**\n * Where row `index` is drawn in the list when the view at `position` shows the rows from `top`: its own place, or in a\n * capped list its place relative to the view, so that it scrolls with the page until the next draw.\n */\nexport const rowOffset = (geometry: Geometry, index: number, top: number, position: number) => {\n const offset = index * geometry.rowHeight\n return geometry.scaled ? offset - top + position : offset\n}\n\n/** The rows drawn for a scroll offset: those in a viewport of `height`, and `overscan` more on each side. */\nexport const rowsInView = (total: number, top: number, rowHeight: number, height: number, overscan: number) => {\n const first = Math.min(total, Math.max(0, Math.floor(top / rowHeight) - overscan))\n const last = Math.min(total - 1, Math.floor((top + height) / rowHeight) + overscan)\n return { first, last: Math.max(first - 1, last) }\n}\n","/**\n * The element that scrolls `element` up and down: its nearest ancestor that scrolls vertically, or the page's\n * scrolling element when none does.\n */\nexport const scrollParent = (element: HTMLElement) => {\n const page = document.scrollingElement ?? document.documentElement\n for (let parent = element.parentElement; parent && parent !== page && parent !== document.body; parent = parent.parentElement) {\n if (/auto|scroll/.test(getComputedStyle(parent).overflowY)) return parent\n }\n return page as HTMLElement\n}\n\nconst isPage = (scroller: HTMLElement) => scroller === (document.scrollingElement ?? document.documentElement)\n\n/** Where scroll events of `scroller` are sent: the window for the page. */\nexport const scrollEvents = (scroller: HTMLElement): EventTarget => (isPage(scroller) ? window : scroller)\n\nconst padding = (value: string) => Number.parseFloat(value) || 0\n\n/**\n * The part of `scroller` content shows in, in viewport coordinates: its box less its scroll padding, which is where\n * sticky bars over it say they are.\n */\nexport const visibleArea = (scroller: HTMLElement) => {\n const style = getComputedStyle(scroller)\n const box = isPage(scroller) ? { top: 0, height: scroller.clientHeight } : { top: scroller.getBoundingClientRect().top + scroller.clientTop, height: scroller.clientHeight }\n const top = padding(style.scrollPaddingTop)\n return { top: box.top + top, height: Math.max(0, box.height - top - padding(style.scrollPaddingBottom)) }\n}\n","import { useCallback, useLayoutEffect, useRef, useState } from 'react'\nimport { gridGeometry, rowOffset, rowsInView, scrollFromTop, topFromScroll } from './geometry'\nimport { scrollEvents, scrollParent, visibleArea } from './scroll-parent'\n\nexport type VirtualRowsOptions = {\n total: number\n rowHeight: number\n /** The row to start at, read when the list is ready to start; a fraction starts that far into the row. */\n initialIndex: number\n /** Height over the top of the rows that hides them, such as a sticky header, besides the scroller's scroll padding. */\n inset?: number\n /**\n * The offset to draw at for the scroll offset: after a layout change, where it moves to before the scroller has\n * caught up, so no row of the wrong place is drawn or loaded in between.\n */\n settle?: (top: number) => number\n /** Whether `rowHeight` is the rows' own, such as once they are measured: the list starts at `initialIndex` then. */\n ready?: boolean\n /**\n * Called with the offset into the rows at the top of the view, never below 0, whenever the view moves once the list\n * has started, so the list can come back to it with `initialIndex`.\n */\n onScroll?: (top: number) => void\n}\n\nconst overscan = 6\n\n/** How far the top of the view is into the list, and how tall the view is below the scroller's bars. */\ntype View = { position: number; height: number }\n\nconst viewRows = (view: View, total: number, rowHeight: number) => {\n const geometry = gridGeometry(total, rowHeight, view.height)\n const top = topFromScroll(geometry, view.position)\n return { geometry, top, topIndex: Math.floor(Math.max(0, top) / rowHeight), ...rowsInView(total, top, rowHeight, view.height, overscan) }\n}\n\n/**\n * Rows of a fixed height in a list as tall as all of them, scrolled natively by whatever scrolls it: the nearest\n * scrolling ancestor, or the page. Only the rows in view, and `overscan` more on each side, are drawn: `ref` goes on the\n * list's element, `geometry.contentHeight` tall, and each drawn row sits at `offset` from its top. Nothing listens for\n * wheel or touch: the list follows the scroll position, and draws again only when other rows come into view.\n * `first` and `last` are the indexes of the drawn rows, overscan included; `started` says whether the list has started\n * at `initialIndex`, read after the list's layout effects.\n */\nexport const useVirtualRows = <T extends HTMLElement>({ total, rowHeight, initialIndex, inset = 0, settle, ready = true, onScroll }: VirtualRowsOptions) => {\n const ref = useRef<T>(null)\n const scroller = useRef<HTMLElement | null>(null)\n const [view, setView] = useState<View>({ position: 0, height: 0 })\n const options = useRef({ total, rowHeight, initialIndex, inset, ready, onScroll })\n options.current = { total, rowHeight, initialIndex, inset, ready, onScroll }\n\n const read = useCallback((): View | undefined => {\n const content = ref.current\n if (!content || !scroller.current) return undefined\n const area = visibleArea(scroller.current)\n const hidden = options.current.inset\n return { position: area.top + hidden - content.getBoundingClientRect().top, height: Math.max(0, area.height - hidden) }\n }, [])\n\n // The list starts once, when its rows are ready and it has been laid out: at `initialIndex`, or at the top of its\n // scroller when that is the first row and the scroller is past it, as after a list scrolled down before. The first\n // resize observation comes after every effect of the commit that mounted the list, such as the page's sticky bars\n // saying how tall they are, and before it is painted. Until then the view is not where the list will be, so it is\n // not reported.\n const start = useRef({ pending: true, laidOut: false })\n\n // In a list that is not capped the drawn rows scroll with the page by themselves, so a scroll only draws again when\n // it brings other rows into view\n const shown = useRef(view)\n shown.current = view\n const measure = useCallback(() => {\n const next = read()\n if (!next) return\n const current = shown.current\n const { total, rowHeight, onScroll } = options.current\n const before = viewRows(current, total, rowHeight)\n const after = viewRows(next, total, rowHeight)\n if (!start.current.pending) onScroll?.(Math.max(0, after.top))\n const sameRows = !after.geometry.scaled && before.first === after.first && before.last === after.last && before.topIndex === after.topIndex\n if (current.height === next.height && (current.position === next.position || sameRows)) return\n shown.current = next\n setView(next)\n }, [read])\n\n const begin = useCallback(() => {\n if (!start.current.pending || !start.current.laidOut || !options.current.ready) return\n const view = read()\n const parent = scroller.current\n if (!view || !parent) return\n start.current.pending = false\n const { total, rowHeight, initialIndex } = options.current\n if (initialIndex > 0) parent.scrollTop += scrollFromTop(gridGeometry(total, rowHeight, view.height), initialIndex * rowHeight) - view.position\n else if (view.position > 0) parent.scrollTop = 0\n }, [read])\n\n useLayoutEffect(() => {\n const content = ref.current\n if (!content) return\n const parent = scrollParent(content)\n scroller.current = parent\n const events = scrollEvents(parent)\n events.addEventListener('scroll', measure, { passive: true })\n window.addEventListener('resize', measure, { passive: true })\n const observer = new ResizeObserver(() => {\n start.current.laidOut = true\n begin()\n measure()\n })\n observer.observe(parent)\n observer.observe(content)\n measure()\n return () => {\n events.removeEventListener('scroll', measure)\n window.removeEventListener('resize', measure)\n observer.disconnect()\n scroller.current = null\n }\n }, [measure, begin])\n\n // Anything above the list that changes height moves it in the page without a scroll\n useLayoutEffect(() => {\n begin()\n measure()\n })\n\n /** Scrolls to a virtual offset, for a layout change that keeps a row in view. */\n const scrollTo = useCallback(\n (top: number) => {\n const current = read()\n if (!current || !scroller.current) return\n const geometry = gridGeometry(options.current.total, options.current.rowHeight, current.height)\n scroller.current.scrollTop += scrollFromTop(geometry, top) - current.position\n measure()\n },\n [read, measure],\n )\n\n const started = useCallback(() => !start.current.pending, [])\n\n const drawn = viewRows(view, total, rowHeight)\n const top = settle ? settle(drawn.top) : drawn.top\n const { first, last } = settle ? rowsInView(total, top, rowHeight, view.height, overscan) : drawn\n const rows = Array.from({ length: last - first + 1 }, (_, offset) => ({ index: first + offset, offset: rowOffset(drawn.geometry, first + offset, top, view.position) }))\n return { ref, height: view.height, top, geometry: drawn.geometry, rows, first, last, scrollTo, started }\n}\n","/** A cell of the grid: its row's index among all rows, and its column. */\nexport type CellPlace = { index: number; column: string }\n\nexport type MoveKey = 'ArrowUp' | 'ArrowDown' | 'ArrowLeft' | 'ArrowRight'\n\nexport const isMoveKey = (key: string): key is MoveKey => key === 'ArrowUp' || key === 'ArrowDown' || key === 'ArrowLeft' || key === 'ArrowRight'\n\n/** The cell an arrow key moves to from `at` among `total` rows of `columns`, or undefined at the grid's edge. */\nexport const movedCell = (at: CellPlace, key: MoveKey, columns: readonly string[], total: number): CellPlace | undefined => {\n const column = columns.indexOf(at.column)\n if (key === 'ArrowUp') return at.index > 0 ? { ...at, index: at.index - 1 } : undefined\n if (key === 'ArrowDown') return at.index < total - 1 ? { ...at, index: at.index + 1 } : undefined\n const next = columns[key === 'ArrowLeft' ? column - 1 : column + 1]\n return column >= 0 && next !== undefined ? { ...at, column: next } : undefined\n}\n\n/** The editable column after (`1`) or before (`-1`) `column` in its row, or undefined when there is none. */\nexport const nextEditable = (column: string, columns: readonly string[], editable: (column: string) => boolean, direction: 1 | -1) => {\n const from = columns.indexOf(column)\n const after = direction === 1 ? columns.slice(from + 1) : columns.slice(0, Math.max(0, from)).reverse()\n return after.find(editable)\n}\n","import { useEffect, useRef, useState, type KeyboardEvent, type ReactNode, type RefObject } from 'react'\nimport type { GridRow } from './column-spec'\nimport { isMoveKey, movedCell, nextEditable, type CellPlace } from './cell-moves'\n\n/** Cells edited in place: a double-click, a click on the chosen cell, Enter or F2 opens the cell's editor. */\nexport type CellEditor = {\n /** Whether this row's cell of `column` is edited in place. */\n editable: (row: GridRow, column: string) => boolean\n /**\n * The editor in the cell. It calls `close` once it saved or gave up, with `move` to go on to the next (`1`) or the\n * previous (`-1`) editable cell of the row.\n */\n render: (row: GridRow, column: string, close: (move?: 1 | -1) => void) => ReactNode\n}\n\ntype Options = {\n editor: CellEditor | undefined\n columns: readonly string[]\n total: number\n /** The loaded row at an index, undefined while it loads. */\n rowAt: (index: number) => GridRow | undefined\n onOpenRow?: (row: GridRow) => void\n container: RefObject<HTMLElement | null>\n}\n\nconst placeId = (place: CellPlace) => `${place.index}:${place.column}`\n\n/**\n * The chosen cell and the one being edited, of a grid with an editor. The arrow keys, and Tab and Shift+Tab within a\n * row, move between cells; Enter opens the editor of an editable cell and the row of any other; Escape lets go of the\n * cell. A cell's mouse and keyboard handlers come from `cell`.\n */\nexport const useCellEditing = ({ editor, columns, total, rowAt, onOpenRow, container }: Options) => {\n const [active, setActive] = useState<CellPlace>()\n const [editing, setEditing] = useState(false)\n // A move by key or a closed editor brings the focus to the chosen cell; a scroll or a load does not take it.\n const refocus = useRef(false)\n // Whether the cell was already chosen when the pointer went down on it, before the focus chose it\n const pressedChosen = useRef(false)\n\n useEffect(() => {\n if (!active || editing || !refocus.current) return\n refocus.current = false\n const cell = container.current?.querySelector<HTMLElement>(`[data-cell=\"${placeId(active)}\"]`)\n if (!cell) return\n cell.focus({ preventScroll: true })\n cell.scrollIntoView({ block: 'nearest', inline: 'nearest' })\n }, [active, editing, container])\n\n if (!editor) return undefined\n\n const editableAt = (place: CellPlace) => {\n const row = rowAt(place.index)\n return row !== undefined && editor.editable(row, place.column)\n }\n const choose = (place: CellPlace, edit = false) => {\n refocus.current = true\n setActive(place)\n setEditing(edit && editableAt(place))\n }\n const close = (move?: 1 | -1) => {\n if (!active) return\n const row = rowAt(active.index)\n const next = move && row ? nextEditable(active.column, columns, (column) => editor.editable(row, column), move) : undefined\n // An editor closed by a click elsewhere leaves the focus where the click put it\n const focused = Boolean(container.current?.contains(document.activeElement))\n choose(next ? { ...active, column: next } : active, next !== undefined)\n refocus.current = focused\n }\n\n const onKeyDown = (event: KeyboardEvent) => {\n if (editing || !active || !(event.target instanceof HTMLElement) || event.target.dataset.cell !== placeId(active)) return\n const key = event.key === 'Tab' ? (event.shiftKey ? 'ArrowLeft' : 'ArrowRight') : event.key\n if (isMoveKey(key)) {\n const next = movedCell(active, key, columns, total)\n // Tab leaves the grid at the end of the row; an arrow stays on the edge, and on a row still loading\n if (!next && event.key === 'Tab') return\n event.preventDefault()\n if (next && rowAt(next.index)) choose(next)\n return\n }\n if (event.key === 'Enter' || event.key === 'F2') {\n event.preventDefault()\n const row = rowAt(active.index)\n if (editableAt(active)) choose(active, true)\n else if (event.key === 'Enter' && row) onOpenRow?.(row)\n return\n }\n if (event.key === 'Escape') setActive(undefined)\n }\n\n /** What a cell of the grid needs: its content, its handlers, and whether it is chosen or being edited. */\n const cell = (index: number, row: GridRow, column: string, content: ReactNode) => {\n const place = { index, column }\n const chosen = active?.index === index && active.column === column\n const editable = editor.editable(row, column)\n // The chosen cell takes Tab into the grid; without one, the first cell of the first row does\n const reachable = chosen || (!active && index === 0 && column === columns[0])\n return {\n content: chosen && editing ? editor.render(row, column, close) : content,\n chosen,\n editing: chosen && editing,\n editable,\n props: {\n 'data-cell': placeId(place),\n tabIndex: reachable ? 0 : -1,\n 'aria-selected': chosen,\n onMouseDown: () => {\n pressedChosen.current = chosen\n },\n onFocus: (event: { target: EventTarget; currentTarget: EventTarget }) => {\n if (event.target === event.currentTarget && !chosen) setActive(place)\n },\n // An editable cell is chosen by a click instead of opening its row, and edited by a second one\n onClick: (event: { stopPropagation: () => void }) => {\n if (!editable) return\n event.stopPropagation()\n if (pressedChosen.current && !editing) choose(place, true)\n },\n onDoubleClick: (event: { stopPropagation: () => void }) => {\n if (!editable) return\n event.stopPropagation()\n if (!(chosen && editing)) choose(place, true)\n },\n },\n }\n }\n\n return { cell, onKeyDown }\n}\n","import { DndContext, KeyboardSensor, MouseSensor, TouchSensor, closestCenter, useSensor, useSensors, type Announcements, type DragEndEvent } from '@dnd-kit/core'\nimport { SortableContext, sortableKeyboardCoordinates, useSortable, verticalListSortingStrategy } from '@dnd-kit/sortable'\nimport { GripVertical } from 'lucide-react'\nimport type { ReactNode } from 'react'\nimport type { GridRow } from './column-spec'\nimport { DataRow, type DataRowProps } from './grid-row'\nimport { text } from './messages'\n\n/** Rows moved by a drag handle in place of their checkbox: `onMove` gets the row's index and the index it is dropped at. */\nexport type RowReorder = {\n onMove: (from: number, to: number) => void\n /** How a row reads to a screen reader, such as its title. */\n label: (row: GridRow) => string\n}\n\n/** The rows of a grid that are moved by hand, `ids` in their order, each loaded or not, so the drop's index is the row's place in the whole list. */\nexport const ReorderRows = ({ ids, rowAt, reorder, children }: { ids: string[]; rowAt: (index: number) => GridRow | undefined; reorder: RowReorder; children: ReactNode }) => {\n // A mouse starts dragging after a few pixels; a finger only after a short press, so the page still scrolls\n const sensors = useSensors(\n useSensor(MouseSensor, { activationConstraint: { distance: 4 } }),\n useSensor(TouchSensor, { activationConstraint: { delay: 250, tolerance: 5 } }),\n useSensor(KeyboardSensor, { coordinateGetter: sortableKeyboardCoordinates }),\n )\n const place = (id: string | number | undefined) => ids.indexOf(String(id))\n const name = (id: string | number) => {\n const row = rowAt(place(id))\n return row ? reorder.label(row) : text('row')\n }\n const announcements: Announcements = {\n onDragStart: ({ active }) => text('pickedUp', { name: name(active.id), row: place(active.id) + 1, rows: ids.length }),\n onDragOver: ({ active, over }) => (over ? text('isOver', { name: name(active.id), row: place(over.id) + 1, rows: ids.length }) : undefined),\n onDragEnd: ({ active, over }) => (over ? text('droppedAt', { name: name(active.id), row: place(over.id) + 1, rows: ids.length }) : text('putBack', { name: name(active.id) })),\n onDragCancel: ({ active }) => text('cancelled', { name: name(active.id), row: place(active.id) + 1 }),\n }\n const end = ({ active, over }: DragEndEvent) => {\n if (!over || active.id === over.id) return\n reorder.onMove(place(active.id), place(over.id))\n }\n return (\n <DndContext sensors={sensors} collisionDetection={closestCenter} onDragEnd={end} accessibility={{ announcements, screenReaderInstructions: { draggable: text('reorderInstructions') } }}>\n <SortableContext items={ids} strategy={verticalListSortingStrategy}>\n {children}\n </SortableContext>\n </DndContext>\n )\n}\n\n/** A row moved by its handle, which takes the checkbox's place; it follows the pointer up and down only. */\nexport const SortableRow = ({ row, label, ...props }: Omit<DataRowProps, 'handle' | 'rowRef' | 'dragY' | 'transition' | 'dragging'> & { row: GridRow; label: string }) => {\n const { attributes, listeners, setNodeRef, setActivatorNodeRef, transform, transition, isDragging } = useSortable({ id: row.id })\n const handle = (\n <button\n ref={setActivatorNodeRef}\n type=\"button\"\n aria-label={text('move', { label })}\n {...attributes}\n {...listeners}\n // The row opens its record on a click, which the handle is not\n onClick={(event) => event.stopPropagation()}\n style={{ touchAction: 'none' }}\n className=\"flex size-7 cursor-grab items-center justify-center rounded text-faint-foreground hover:bg-muted hover:text-foreground focus-visible:text-foreground active:cursor-grabbing pointer-coarse:size-9\"\n >\n <GripVertical className=\"size-4\" />\n </button>\n )\n return <DataRow {...props} rowRef={setNodeRef} handle={handle} dragY={transform?.y ?? 0} transition={transition} dragging={isDragging} />\n}\n","import { useTable, type SortingState } from '@tanstack/react-table'\nimport { useCallback, useLayoutEffect, useMemo, useRef, useState } from 'react'\nimport { cn } from '../lib/cn'\nimport type { ColumnSpec, GridRow } from './column-spec'\nimport { buildColumns, features } from './columns'\nimport { offeredBulkActions, oneBulkRunAtATime, type BulkAction } from './bulk-actions'\nimport { GridFooter } from './grid-footer'\nimport { RowMenu, availableActions, type RowAction } from './row-menu'\nimport { compactGutter, desktopMinScale, gridMinWidth, gutterWidthFor, rowMenuWidth } from './grid-template'\nimport { useHorizontalScroll } from './use-horizontal-scroll'\nimport { usePinnedColumns } from './use-pinned-columns'\nimport { defaultPins } from './default-pins'\nimport { useFittedColumns } from './use-fitted-columns'\nimport { withResizedWidths } from './column-resize'\nimport { useColumnResize } from './use-column-resize'\nimport { useIsDesktop } from '../lib/use-media-query'\nimport { useRootFontSize } from '../lib/use-root-font-size'\nimport { gridHeights } from './grid-heights'\nimport { GridHeader } from './grid-header'\nimport { DataRow, SkeletonRow } from './grid-row'\nimport type { RowSource } from './row-source'\nimport { usePagedRows } from './use-paged-rows'\nimport { useVirtualRows } from './use-virtual-rows'\nimport { useCellEditing, type CellEditor } from './use-cell-editing'\nimport { ReorderRows, SortableRow, type RowReorder } from './row-reorder'\nimport { RouteLink, type RouteTarget } from '../primitives/route-link'\n\nexport type DataGridProps = {\n columns: ColumnSpec[]\n source: RowSource\n /** The order in which `source` yields rows; sorting the other way flips the index mapping. */\n naturalSort?: { columnId: string; direction: 'asc' | 'desc' }\n /** The row to start at; a fraction starts that far into the row. */\n initialScrollIndex?: number\n /** Called with the row at the top of the view, and how far into it, as the view moves, to come back to it with `initialScrollIndex`. */\n onScrollIndex?: (index: number) => void\n /** Simulated page load time for mock sources. 0 loads synchronously. */\n latencyMs?: number\n /** Controlled sorting, for sources that sort on the server. Without it, sorting flips the mock source. */\n sort?: { columnId: string; direction: 'asc' | 'desc' }\n onSortChange?: (sort: { columnId: string; direction: 'asc' | 'desc' }) => void\n onOpenRow?: (row: GridRow) => void\n /**\n * Where a row's record is: its title cell (the `title` column, else the first) links there, so it opens in a new tab\n * or is copied as any link is. A cell edited in place is no link, since a click there chooses it.\n */\n rowLink?: (row: GridRow) => RouteTarget\n /** The id of the row the page shows the details of, such as the row chosen in its address; it looks selected. */\n chosenRow?: string\n /** Entries of the \"...\" menu at the end of each row; a row none apply to gets no menu, but keeps the column. */\n rowActions?: RowAction[]\n /** Cells edited in place, between which the arrow keys and Tab move. */\n cellEditor?: CellEditor\n /** Values to show over the loaded rows', by row id, such as those of edits saving or saved since the rows loaded. */\n rowPatches?: ReadonlyMap<string, Partial<GridRow>>\n /** Buttons shown next to the selection count, run on the selected rows. */\n bulkActions?: BulkAction[]\n /** Where to remember pinned columns in local storage, for example one key per user and resource. */\n pinKey?: string\n /** Show the row number next to the checkbox; without it the selection column is a narrow strip. */\n rowNumbers?: boolean\n /** Columns pinned until the user chooses otherwise. */\n defaultPinned?: string[]\n compact?: boolean\n selectable?: boolean\n /** Rows moved by a drag handle in place of the checkbox, every row of `source` loaded; nothing is selected meanwhile. */\n reorder?: RowReorder\n /** Sized to show every row of `source` without scrolling, for a few rows shown whole, without the footer unless it offers `bulkActions` for selected rows. */\n fit?: boolean\n /**\n * What scrolls the rows: `own`, a scroller of the grid's own in the height it is given, or `parent`, the nearest\n * scrolling ancestor or else the page, the grid as tall as all its rows with its header and footer sticky in it.\n */\n scroll?: 'own' | 'parent'\n className?: string\n}\n\nexport const DataGrid = ({ columns: given, source, naturalSort, initialScrollIndex = 0, onScrollIndex, latencyMs = 150, sort: controlledSort, onSortChange, onOpenRow, rowLink, chosenRow, rowActions, cellEditor, rowPatches, bulkActions, pinKey, defaultPinned, rowNumbers = true, compact = false, selectable: selecting = true, reorder, fit = false, scroll = 'own', className }: DataGridProps) => {\n const selectable = selecting && !reorder\n const { header: headerHeight, row: rowHeight, footer: footerHeight } = gridHeights(useRootFontSize(), { compact, withBelow: given.some((spec) => spec.below) })\n const narrow = !useIsDesktop()\n // A phone keeps every column whole, so pinning there could leave nothing to scroll\n const pinsByDefault = (defaultPinned ?? (narrow ? [] : defaultPins(given))).join(' ')\n // Kept while the ids are the same: a new list of pins reorders the columns, which draws every cell anew\n const initialPins = useMemo(() => (pinsByDefault ? pinsByDefault.split(' ') : []), [pinsByDefault])\n const [pinned, setPinned] = usePinnedColumns(pinKey, initialPins)\n const columns = useMemo(() => {\n const first = pinned.flatMap((id) => given.find((spec) => spec.id === id) ?? [])\n return [...first, ...given.filter((spec) => !pinned.includes(spec.id))]\n }, [given, pinned])\n const pinnedIds = columns.slice(0, columns.filter((spec) => pinned.includes(spec.id)).length).map((spec) => spec.id)\n const { total } = source\n const [localSorting, setLocalSorting] = useState<SortingState>(naturalSort ? [{ id: naturalSort.columnId, desc: naturalSort.direction === 'desc' }] : [])\n const sorting: SortingState = controlledSort ? [{ id: controlledSort.columnId, desc: controlledSort.direction === 'desc' }] : localSorting\n const setSorting = (updater: SortingState | ((current: SortingState) => SortingState)) => {\n const next = typeof updater === 'function' ? updater(sorting) : updater\n const first = next[0]\n if (onSortChange && first) onSortChange({ columnId: first.id, direction: first.desc ? 'desc' : 'asc' })\n if (!controlledSort) setLocalSorting(next)\n }\n const [rowSelection, setRowSelection] = useState({})\n const tableColumns = useMemo(() => buildColumns(columns), [columns])\n\n const sort = sorting[0]\n const reverse = Boolean(!controlledSort && naturalSort && sort && sort.id === naturalSort.columnId && (sort.desc ? 'desc' : 'asc') !== naturalSort.direction)\n const sourceRowAt = source.rowAt\n const rowAt = useCallback((index: number) => sourceRowAt!(reverse ? total - 1 - index : index), [sourceRowAt, reverse, total])\n\n const [startIndex] = useState(initialScrollIndex)\n const onScroll = onScrollIndex && ((offset: number) => onScrollIndex(offset / rowHeight))\n const { ref, geometry, rows: virtualRows, first: firstIndex, last: lastIndex } = useVirtualRows<HTMLDivElement>({ total, rowHeight, initialIndex: startIndex, inset: headerHeight, onScroll })\n const gutter = narrow || !rowNumbers ? compactGutter : gutterWidthFor(total)\n const getRow = usePagedRows({ total, rowAt: sourceRowAt ? rowAt : undefined, loadRows: source.loadRows, cachedRows: source.cachedRows, revision: source.revision, latencyMs }, firstIndex, lastIndex)\n\n const patchedRow = useCallback((index: number) => {\n const row = getRow(index)\n const patch = row && rowPatches?.get(row.id)\n return patch ? { ...row, ...patch } : row\n }, [getRow, rowPatches])\n const loaded = virtualRows.map(({ index, offset }) => ({ index, offset, row: patchedRow(index) }))\n const data = useMemo(() => loaded.flatMap(({ row }) => (row ? [row] : [])), [patchedRow, firstIndex, lastIndex])\n // The header scrolls sideways with the rows, outside them so that it can stick to the top of a page\n const headerRef = useRef<HTMLDivElement>(null)\n const resize = useColumnResize(headerRef)\n const fitted = useFittedColumns(columns, data)\n const sized = useMemo(() => withResizedWidths(fitted, resize.widths), [fitted, resize.widths])\n const table = useTable({\n features,\n columns: tableColumns,\n data,\n state: { sorting, rowSelection },\n onSortingChange: setSorting,\n onRowSelectionChange: setRowSelection,\n manualSorting: true,\n enableMultiSort: false,\n enableSortingRemoval: false,\n getRowId: (row) => row.id,\n })\n const tableRows = new Map(table.getRowModel().rows.map((row) => [row.id, row]))\n const selectedCount = Object.keys(rowSelection).length\n const selectedRows = useRef(new Map<string, GridRow>())\n const [runBulkAction] = useState(oneBulkRunAtATime)\n for (const row of table.getRowModel().rows) if (row.getIsSelected()) selectedRows.current.set(row.id, row.original)\n const trailing = rowActions && rowActions.length > 0 ? rowMenuWidth : 0\n const minScale = narrow ? 1 : desktopMinScale\n const horizontal = useHorizontalScroll()\n const onBodyScroll = () => {\n horizontal.onScroll()\n if (headerRef.current && horizontal.ref.current) headerRef.current.scrollLeft = horizontal.ref.current.scrollLeft\n }\n const [pins, setPins] = useState<Record<string, number>>({})\n useLayoutEffect(() => {\n const header = headerRef.current?.querySelector('[role=row]')\n if (!header) return\n let left = gutter\n const next: Record<string, number> = {}\n for (const id of pinnedIds) {\n next[id] = left\n left += header.querySelector<HTMLElement>(`[data-col-id=\"${id}\"]`)?.offsetWidth ?? 0\n }\n if (JSON.stringify(pins) !== JSON.stringify(next)) setPins(next)\n })\n const lastPinned = pinnedIds.at(-1)\n const togglePin = (id: string) => setPinned(pinned.includes(id) ? pinned.filter((entry) => entry !== id) : [...pinned, id])\n\n const headerCells = table.getHeaderGroups().flatMap((group) =>\n group.headers.map((header) => ({\n spec: columns.find((spec) => spec.id === header.column.id)!,\n sorted: header.column.getIsSorted(),\n onSort: (event: unknown) => header.column.getToggleSortingHandler()?.(event),\n })),\n )\n\n const gridRef = useRef<HTMLDivElement>(null)\n const columnIds = useMemo(() => columns.map((spec) => spec.id), [columns])\n const cellEditing = useCellEditing({ editor: cellEditor, columns: columnIds, total, rowAt: patchedRow, onOpenRow, container: gridRef })\n const linkColumn = (columns.find((spec) => spec.title) ?? columns[0])?.id\n\n const minWidth = gridMinWidth(sized, gutter, trailing, minScale)\n const own = scroll === 'own'\n // A grid sized to its rows has no footer, unless its rows can be selected for bulk actions, which it offers\n const footer = !fit || (selectable && Boolean(bulkActions?.length))\n const header = (\n <div ref={headerRef} className={cn('sticky z-20 shrink-0 overflow-hidden', own ? 'top-0' : 'top-[var(--pb-sticky-top,0px)]')}>\n <div style={{ minWidth }}>\n <GridHeader cells={headerCells} specs={sized} gutter={gutter} trailing={trailing} minScale={minScale} pins={pins} lastPinned={lastPinned} scrolled={horizontal.scrolled} onTogglePin={togglePin} resize={resize} widths={resize.widths} selectable={selectable} selectedCount={selectedCount} onClearSelection={() => setRowSelection({})} />\n </div>\n </div>\n )\n const rowsInView = loaded.map(({ index, offset, row }) => {\n const frame = { specs: sized, gutter, index, offset, height: rowHeight, selectable, trailing, minScale, scrolled: horizontal.scrolled, pins, lastPinned }\n const tableRow = row ? tableRows.get(row.id) : undefined\n if (!tableRow || !row) return <SkeletonRow key={`skeleton-${index}`} {...frame} />\n const actions = trailing ? availableActions(rowActions!, row) : []\n const props = {\n ...frame,\n selected: tableRow.getIsSelected(),\n current: row.id === chosenRow,\n onToggle: () => tableRow.toggleSelected(),\n onOpen: onOpenRow ? () => onOpenRow(row) : undefined,\n menu: actions.length > 0 ? <RowMenu row={row} actions={actions} /> : undefined,\n cells: tableRow.getAllCells().map((cell) => {\n const spec = columns.find((column) => column.id === cell.column.id)!\n const content = <table.FlexRender cell={cell} />\n const editable = Boolean(cellEditor?.editable(row, cell.column.id))\n const linked = rowLink && cell.column.id === linkColumn && !editable ? <RouteLink to={rowLink(row)} className=\"flex min-w-0 items-center hover:underline\">{content}</RouteLink> : content\n const stacked = spec.below ? <div className=\"flex min-w-0 flex-col items-start gap-1\">{linked}{spec.below(row)}</div> : linked\n return { spec, ...(cellEditing ? cellEditing.cell(index, row, cell.column.id, stacked) : { content: stacked }) }\n }),\n }\n return reorder ? <SortableRow key={row.id} {...props} row={row} label={reorder.label(row)} /> : <DataRow key={row.id} {...props} />\n })\n const body = (\n <div ref={horizontal.attach} onScroll={onBodyScroll} className=\"overflow-x-auto overflow-y-hidden overscroll-x-contain [-webkit-overflow-scrolling:touch]\">\n <div ref={ref} className=\"relative\" style={{ minWidth, height: geometry.contentHeight }}>\n {reorder ? (\n <ReorderRows ids={Array.from({ length: total }, (_, index) => patchedRow(index)?.id ?? `missing-${index}`)} rowAt={patchedRow} reorder={reorder}>\n {rowsInView}\n </ReorderRows>\n ) : (\n rowsInView\n )}\n </div>\n </div>\n )\n\n return (\n <div\n ref={gridRef}\n role=\"grid\"\n aria-rowcount={total}\n onKeyDown={cellEditing?.onKeyDown}\n className={cn('flex flex-col rounded-lg border bg-background', own ? 'min-h-0 overflow-hidden' : 'overflow-clip', className)}\n style={fit && own ? { height: headerHeight + total * rowHeight + (footer ? footerHeight : 0) + 2 } : undefined}\n >\n <div className={cn('relative', own && 'flex min-h-0 flex-1 flex-col')}>\n {own ? (\n <div className=\"min-h-0 flex-1 overflow-y-auto overflow-x-hidden\">\n {header}\n {body}\n </div>\n ) : (\n <>\n {header}\n {body}\n </>\n )}\n {horizontal.more && <div aria-hidden className=\"pointer-events-none absolute inset-y-0 right-0 z-20 w-8 bg-gradient-to-l from-backdrop/15 to-transparent\" />}\n </div>\n {footer && (\n <GridFooter\n total={total}\n className={own ? undefined : 'sticky bottom-[var(--pb-sticky-bottom,0px)] z-20'}\n selectedCount={selectedCount}\n bulkActions={offeredBulkActions(bulkActions ?? [], Object.keys(rowSelection).flatMap((id) => selectedRows.current.get(id) ?? [])).map(({ action, rows, skipped }) => ({\n label: action.label(rows.length),\n destructive: action.destructive,\n // The selection stays while the action asks first, and keeps the rows it leaves open, such as refused ones\n onRun: () =>\n void runBulkAction(action, rows, skipped).then((done) => {\n if (!done) return\n const ids = new Set(done.map((row) => row.id))\n setRowSelection((current) => Object.fromEntries(Object.entries(current).filter(([id]) => !ids.has(id))))\n for (const id of ids) selectedRows.current.delete(id)\n }),\n }))}\n />\n )}\n </div>\n )\n}\n","import { messages } from '../../locale/messages'\n\nexport const text = messages('app/searches')\n","import type { FilterChip } from '../../filter-panel'\nimport { cn } from '../../lib/cn'\nimport { text } from './messages'\n\nconst chipClass = 'inline-flex h-6 items-center rounded-full border border-primary-border bg-primary-soft px-2.5 text-xs font-medium text-primary-text'\n\n/** What a filter filters on, concisely: its chips as a list labelled \"Filters\". */\nexport const FilterChipList = ({ chips, className }: { chips: readonly FilterChip[]; className?: string }) => (\n <ul className={cn('flex flex-wrap gap-1.5', className)} aria-label={text('filters')}>\n {chips.map((chip) => (\n <li key={chip.key} className={chipClass}>\n {chip.label}\n </li>\n ))}\n </ul>\n)\n\n/** A filter's chips inside a heading or a link, where a list cannot go: read out one after the other. */\nexport const InlineFilterChips = ({ chips }: { chips: readonly FilterChip[] }) => (\n <span className=\"flex flex-wrap gap-1.5\">\n {chips.map((chip, index) => (\n <span key={chip.key} className={chipClass}>\n {index > 0 && <span className=\"sr-only\">, </span>}\n {chip.label}\n </span>\n ))}\n </span>\n)\n\n/** A search without a name as words, for a label or a question: its chips one after the other. */\nexport const chipsText = (chips: readonly FilterChip[]) => chips.map((chip) => chip.label).join(', ')\n","import { messages } from '../locale/messages'\n\nexport const text = messages('filter-panel')\n","import type { DatePreset } from '@protobase/schema'\nimport { text } from './messages'\n\n/** `count` is left out when it is not known, such as for a record found by a search. */\nexport type FacetOption = { value: string; label: string; count?: number }\n\nexport type FacetGroupConfig = {\n id: string\n label: string\n options: FacetOption[]\n searchable?: boolean\n /** A dropdown that searches as you type and holds several choices, instead of a list of checkboxes. */\n combobox?: boolean\n /** Names of chosen values that are not among `options`, such as those picked from an earlier search. */\n labels?: Record<string, string>\n /** Called as the search text changes, the options then being the matches; without it the options are filtered here. */\n onSearch?: (text: string) => void\n /** The options are boolean fields by name, and a record shows when any chosen one is true. */\n flags?: boolean\n /** Behind the bar's \"More filters\" menu until picked there or set. */\n secondary?: boolean\n}\n\nexport type RangeConfig = {\n id: string\n label: string\n min: number\n max: number\n step: number\n /** Bar heights (counts) of the histogram drawn behind the slider. */\n histogram: number[]\n format: (value: number) => string\n /** Behind the bar's \"More filters\" menu until picked there or set. */\n secondary?: boolean\n}\n\nexport type DatePresetId = DatePreset\n\nexport type ToggleConfig = {\n id: string\n label: string\n /** Behind the bar's \"More filters\" menu until picked there or set. */\n secondary?: boolean\n}\n\nexport type FilterConfig = {\n facets: FacetGroupConfig[]\n ranges?: RangeConfig[]\n /** `true` shows the default presets; a list shows exactly those. */\n datePresets?: boolean | DatePresetId[]\n /** The field the date presets filter on, for configs that talk to a server. */\n dateField?: string\n /** Whether `dateField` holds dates or timestamps; calendar presets are printed as that literal. */\n dateKind?: 'date' | 'timestamp'\n /** The date presets are behind the bar's \"More filters\" menu until picked there or set. */\n dateSecondary?: boolean\n toggles?: ToggleConfig[]\n}\n\nexport type FilterState = {\n facets: Record<string, string[]>\n /** The selected span of each range, by its id; a range without one is not filtered on. */\n ranges?: Record<string, [number, number]>\n date?: DatePresetId\n toggles: string[]\n}\n\nexport const defaultDatePresets: DatePresetId[] = ['today', '7d', '30d', 'year']\n\nconst knownPresets = new Set<string>(['today', 'yesterday', '24h', '7d', '30d', '90d', 'month', 'quarter', 'year'] satisfies DatePresetId[])\n\n/** A date preset's label in the screens' language; undefined for one the server offers that this UI does not know. */\nexport const datePresetLabel = (id: DatePresetId) => (knownPresets.has(id) ? text(id) : undefined)\n","import { datePresetLabel, type FacetGroupConfig, type FilterConfig, type FilterState } from './filter-config'\n\nexport const emptyFilterState: FilterState = { facets: {}, toggles: [] }\n\nexport type FilterChip = { key: string; label: string }\n\nexport const toggleFacetValue = (state: FilterState, group: string, value: string): FilterState => {\n const current = state.facets[group] ?? []\n const next = current.includes(value) ? current.filter((entry) => entry !== value) : [...current, value]\n return { ...state, facets: { ...state.facets, [group]: next } }\n}\n\nexport const toggleFlag = (state: FilterState, id: string): FilterState => ({\n ...state,\n toggles: state.toggles.includes(id) ? state.toggles.filter((entry) => entry !== id) : [...state.toggles, id],\n})\n\n/** Sets or, with `undefined`, clears the span of one range. */\nexport const setRange = (state: FilterState, id: string, value: [number, number] | undefined): FilterState => {\n const { [id]: _, ...others } = state.ranges ?? {}\n return { ...state, ranges: value ? { ...others, [id]: value } : others }\n}\n\n/** A facet value's name: its option's label, else a name the group knows for it, else the value itself. */\nexport const facetLabel = (group: FacetGroupConfig, value: string) =>\n group.options.find((option) => option.value === value)?.label ?? group.labels?.[value] ?? value\n\nexport const activeChips = (config: FilterConfig, state: FilterState): FilterChip[] => {\n const facetChips = config.facets.flatMap((group) =>\n (state.facets[group.id] ?? []).map((value) => ({ key: `facet:${group.id}:${value}`, label: `${group.label}: ${facetLabel(group, value)}` })),\n )\n const rangeChips = (config.ranges ?? []).flatMap((range) => {\n const span = state.ranges?.[range.id]\n return span ? [{ key: `range:${range.id}`, label: `${range.label}: ${range.format(span[0])} – ${range.format(span[1])}` }] : []\n })\n const dateChips = state.date ? [{ key: 'date', label: datePresetLabel(state.date) ?? state.date }] : []\n const toggleChips = state.toggles.map((id) => ({ key: `toggle:${id}`, label: config.toggles?.find((toggle) => toggle.id === id)?.label ?? id }))\n return [...facetChips, ...rangeChips, ...dateChips, ...toggleChips]\n}\n\nexport const removeChip = (state: FilterState, key: string): FilterState => {\n if (key === 'date') return { ...state, date: undefined }\n const [kind, group, value] = key.split(':')\n if (kind === 'range') return setRange(state, group!, undefined)\n if (kind === 'toggle') return toggleFlag(state, group!)\n if (kind === 'facet') return toggleFacetValue(state, group!, value!)\n throw new Error(`Unknown filter chip key: ${key}`)\n}\n\nexport const matchesSearch = (label: string, query: string) => label.toLowerCase().includes(query.trim().toLowerCase())\n","import { createWhere, parseFilter, printFilter, type FilterError, type FilterExpr } from '@protobase/schema'\nimport type { DatePresetId, FilterConfig, FilterState } from '../filter-panel'\nimport { dayIn, startOfDayIn, viewerZone } from '../format/zone'\n\nconst w = createWhere()\nconst span = { start: 0, end: 0 }\n\n/** The widgets a `FilterConfig` talks to, by field name. */\ntype Fields = Pick<FilterConfig, 'facets' | 'ranges' | 'dateField' | 'dateKind' | 'toggles'>\n\nconst relative = { '24h': { amount: 24, unit: 'h' }, '7d': { amount: 7, unit: 'd' }, '30d': { amount: 30, unit: 'd' }, '90d': { amount: 90, unit: 'd' } } as const\n\nconst iso = (ms: number) => new Date(ms).toISOString().replace('.000Z', 'Z')\n\n/** The first day of the period a calendar preset starts at, as `YYYY-MM-DD` on the clock of `zone`. */\nexport const periodStart = (preset: DatePresetId, now: Date, zone: string) => {\n const today = dayIn(now.getTime(), zone)\n const [year, month] = [Number(today.slice(0, 4)), Number(today.slice(5, 7)) - 1]\n const day = (ms: number) => new Date(ms).toISOString().slice(0, 10)\n if (preset === 'year') return day(Date.UTC(year, 0, 1))\n if (preset === 'quarter') return day(Date.UTC(year, Math.floor(month / 3) * 3, 1))\n if (preset === 'month') return day(Date.UTC(year, month, 1))\n if (preset === 'yesterday') return day(Date.parse(`${today}T00:00:00Z`) - 86_400_000)\n return today\n}\n\nconst calendarPresets: DatePresetId[] = ['year', 'quarter', 'month', 'yesterday', 'today']\n\n/** The literal a day starts at: the plain date for a date field, its first instant in `zone` for a timestamp field. */\nconst dayLiteral = (day: string, kind: Fields['dateKind'], zone: string) => (kind === 'date' ? day : iso(startOfDayIn(day, zone)))\n\nconst instant = (day: string, kind: Fields['dateKind'], zone: string) =>\n kind === 'date' ? { kind: 'string' as const, value: dayLiteral(day, kind, zone), span } : { kind: 'timestamp' as const, value: dayLiteral(day, kind, zone), span }\n\nconst dateClauses = (field: string, preset: DatePresetId, now: Date, kind: Fields['dateKind'], zone: string): FilterExpr[] => {\n if (preset in relative) return [w.gte(field, w.ago(preset))]\n const from = w.gte(field, instant(periodStart(preset, now, zone), kind, zone))\n return preset === 'yesterday' ? [from, w.lt(field, instant(periodStart('today', now, zone), kind, zone))] : [from]\n}\n\n/** The panel's state as filter clauses, in a fixed order so the text is stable; calendar presets start at midnight in `zone`. */\nexport const stateToClauses = (config: Fields, state: FilterState, now = new Date(), zone = viewerZone()): FilterExpr[] => {\n const facets = config.facets.flatMap((group) => {\n const values = state.facets[group.id] ?? []\n if (values.length === 0) return []\n if (group.flags) {\n const chosen = group.options.filter((option) => values.includes(option.value)).map((option) => w.eq(option.value, true))\n return chosen.length === 0 ? [] : [chosen.length === 1 ? chosen[0]! : w.or(...chosen)]\n }\n return [values.length === 1 ? w.eq(group.id, values[0]!) : w.in(group.id, values)]\n })\n const ranges = (config.ranges ?? []).flatMap((range) => {\n const span = state.ranges?.[range.id]\n return span ? [w.gte(range.id, span[0]), w.lte(range.id, span[1])] : []\n })\n const date = config.dateField && state.date ? dateClauses(config.dateField, state.date, now, config.dateKind, zone) : []\n const toggles = (config.toggles ?? []).filter((toggle) => state.toggles.includes(toggle.id)).map((toggle) => w.eq(toggle.id, true))\n return [...facets, ...ranges, ...date, ...toggles]\n}\n\nexport const clausesToText = (clauses: FilterExpr[]) => (clauses.length === 0 ? '' : printFilter(w.and(...clauses)))\n\nexport const stateToText = (config: Fields, state: FilterState, extras: FilterExpr[] = [], now = new Date(), zone = viewerZone()) =>\n clausesToText([...stateToClauses(config, state, now, zone), ...extras])\n\nconst flatten = (expr: FilterExpr): FilterExpr[] => (expr.kind === 'and' ? expr.args.flatMap(flatten) : [expr])\n\nconst fieldName = (expr: { field: { path: string[] } }) => expr.field.path.join('.')\n\nconst isTrue = (expr: FilterExpr): expr is FilterExpr & { kind: 'compare' } => expr.kind === 'compare' && expr.op === '=' && expr.value.kind === 'boolean' && expr.value.value\n\n// The flags group a clause chooses from, with the fields it chooses: `field = true`, or such clauses ORed in one group.\nconst flagsChosen = (clause: FilterExpr, groupOf: Map<string, string>) => {\n const parts = clause.kind === 'or' ? clause.args : [clause]\n if (!parts.every(isTrue)) return undefined\n const fields = parts.map(fieldName)\n const group = groupOf.get(fields[0]!)\n return group !== undefined && fields.every((field) => groupOf.get(field) === group) ? { group, fields } : undefined\n}\n\nconst literalText = (value: { kind: string; value?: unknown; raw?: string }) => (value.kind === 'number' ? String(value.raw) : value.kind === 'string' ? String(value.value) : undefined)\n\nconst presetOf = (clause: FilterExpr & { kind: 'compare' }, now: Date, zone: string): DatePresetId | undefined => {\n const v = clause.value\n if (v.kind === 'now' && v.offset?.sign === '-') {\n const { amount, unit } = v.offset.duration\n return (Object.entries(relative) as Array<[DatePresetId, { amount: number; unit: string }]>).find(([, d]) => d.amount === amount && d.unit === unit)?.[0]\n }\n if (v.kind === 'timestamp') return calendarPresets.find((preset) => dayLiteral(periodStart(preset, now, zone), 'timestamp', zone) === v.value)\n if (v.kind === 'string') return calendarPresets.find((preset) => periodStart(preset, now, zone) === v.value)\n return undefined\n}\n\nexport type ParsedFilter = { ok: true; state: FilterState; extras: FilterExpr[] } | { ok: false; errors: FilterError[] }\n\n/**\n * The inverse of `stateToText`: clauses that match a widget fill the panel state, everything else\n * (search text, hand-written conditions) is returned as `extras` and survives the round trip.\n */\nexport const textToState = (config: Fields, text: string, now = new Date(), zone = viewerZone()): ParsedFilter => {\n const parsed = parseFilter(text)\n if (!parsed.ok) return { ok: false, errors: parsed.errors }\n const state: FilterState = { facets: {}, toggles: [] }\n const extras: FilterExpr[] = []\n const facetIds = new Set(config.facets.filter((group) => !group.flags).map((group) => group.id))\n const flagGroupOf = new Map(config.facets.filter((group) => group.flags).flatMap((group) => group.options.map((option) => [option.value, group.id] as const)))\n const toggleIds = new Set((config.toggles ?? []).map((toggle) => toggle.id))\n const rangeIds = new Set((config.ranges ?? []).map((range) => range.id))\n const bounds = new Map<string, { low?: number; high?: number; clauses: FilterExpr[] }>()\n let dateClause: FilterExpr | undefined\n let todayEnd: FilterExpr | undefined\n\n for (const clause of parsed.ast ? flatten(parsed.ast) : []) {\n const flags = flagsChosen(clause, flagGroupOf)\n if (flags && !state.facets[flags.group]) {\n state.facets[flags.group] = flags.fields\n } else if (clause.kind === 'compare' && facetIds.has(fieldName(clause)) && clause.op === '=' && literalText(clause.value) !== undefined) {\n state.facets[fieldName(clause)] = [...(state.facets[fieldName(clause)] ?? []), literalText(clause.value)!]\n } else if (clause.kind === 'in' && facetIds.has(fieldName(clause)) && clause.values.every((value) => literalText(value) !== undefined)) {\n state.facets[fieldName(clause)] = [...(state.facets[fieldName(clause)] ?? []), ...clause.values.map((value) => literalText(value)!)]\n } else if (clause.kind === 'compare' && config.dateField === fieldName(clause) && clause.op === '>=' && presetOf(clause, now, zone) && !state.date) {\n state.date = presetOf(clause, now, zone)\n dateClause = clause\n } else if (clause.kind === 'compare' && config.dateField === fieldName(clause) && clause.op === '<' && (clause.value.kind === 'timestamp' || clause.value.kind === 'string') && clause.value.value === dayLiteral(periodStart('today', now, zone), clause.value.kind === 'string' ? 'date' : 'timestamp', zone)) {\n todayEnd = clause\n } else if (clause.kind === 'compare' && toggleIds.has(fieldName(clause)) && clause.op === '=' && clause.value.kind === 'boolean' && clause.value.value) {\n state.toggles.push(fieldName(clause))\n } else if (clause.kind === 'compare' && rangeIds.has(fieldName(clause)) && (clause.op === '>=' || clause.op === '<=') && clause.value.kind === 'number') {\n const range = bounds.get(fieldName(clause)) ?? { clauses: [] }\n if (clause.op === '>=') range.low = clause.value.value\n else range.high = clause.value.value\n range.clauses.push(clause)\n bounds.set(fieldName(clause), range)\n } else {\n extras.push(clause)\n }\n }\n\n if (state.date === 'yesterday' && !todayEnd) {\n extras.push(dateClause!)\n state.date = undefined\n }\n if (todayEnd && state.date !== 'yesterday') extras.push(todayEnd)\n // A range takes a lower and an upper bound; one of them alone is a hand-written condition\n for (const [id, range] of bounds) {\n if (range.low !== undefined && range.high !== undefined) state.ranges = { ...state.ranges, [id]: [range.low, range.high] }\n else extras.push(...range.clauses)\n }\n return { ok: true, state, extras }\n}\n","import type { FieldType, FilterWidgetModel, ResourceModel, ViewModel } from '@protobase/schema'\nimport type { FacetGroupConfig, FilterConfig, RangeConfig } from '../filter-panel'\nimport { formatMoney } from '../format/money'\n\nconst numberTypes: FieldType[] = ['integer', 'bigint', 'decimal']\n\nconst isNumber = (model: ResourceModel | undefined, field: string) => {\n const type = model?.fields[field]?.type\n return type !== undefined && numberTypes.includes(type)\n}\n\n/** A filter on a number field is a range slider, whichever widget the view asked for. */\nconst rangeOf = (widget: FilterWidgetModel, model: ResourceModel | undefined) =>\n widget.kind === 'range' || (widget.kind === 'facets' && isNumber(model, widget.field))\n\nconst secondaryOf = (widget: FilterWidgetModel) => (widget.secondary ? { secondary: true } : {})\n\nconst emptyRange = (widget: FilterWidgetModel & { field: string }): RangeConfig => ({\n id: widget.field,\n label: widget.field,\n min: 0,\n max: 0,\n step: 1,\n histogram: [],\n format: String,\n ...secondaryOf(widget),\n})\n\n/**\n * The widgets of a view in the shape `filter-string` talks to; options and counts are filled in later. Facets on a\n * reference to another resource's records are a combobox, which searches those records.\n */\nexport const widgetFields = (view: ViewModel | undefined, model?: ResourceModel): Pick<FilterConfig, 'facets' | 'ranges' | 'dateField' | 'dateKind' | 'dateSecondary' | 'datePresets' | 'toggles'> => {\n const widgets = view?.filters ?? []\n const date = widgets.find((widget) => widget.kind === 'dateRange')\n return {\n facets: widgets.flatMap((widget): FacetGroupConfig[] => {\n if (widget.kind === 'facets' && !rangeOf(widget, model)) {\n return [{ id: widget.field, label: widget.field, options: [], searchable: widget.search, ...(model?.fields[widget.field]?.type === 'relation' && { combobox: true }), ...secondaryOf(widget) }]\n }\n if (widget.kind === 'flags') return [{ id: widget.fields.join('|'), label: widget.label, options: widget.fields.map((field) => ({ value: field, label: field, count: 0 })), flags: true, ...secondaryOf(widget) }]\n return []\n }),\n ranges: widgets.flatMap((widget) => (widget.kind !== 'flags' && rangeOf(widget, model) ? [emptyRange(widget)] : [])),\n ...(date && { dateField: date.field, ...(date.secondary && { dateSecondary: true }), dateKind: model?.fields[date.field]?.type === 'date' ? ('date' as const) : ('timestamp' as const), ...(date.presets.length > 0 && { datePresets: date.presets }) }),\n toggles: widgets.flatMap((widget) => (widget.kind === 'toggle' ? [{ id: widget.field, label: widget.field, ...secondaryOf(widget) }] : [])),\n }\n}\n\n/** Whether a range draws its histogram: only a `range` widget that asks for one. */\nexport const rangeHistogram = (view: ViewModel | undefined, field: string) =>\n (view?.filters ?? []).some((widget) => widget.kind === 'range' && widget.field === field && widget.histogram)\n\n/** How a range's values read: money in the view's currency, \"€450,000\", else with its prefix and suffix, \"85 m²\". */\nexport const rangeFormat = (view: ViewModel | undefined, field: string) => {\n const hints = view?.fields[field]\n const suffix = hints?.suffix ?? ''\n const currency = hints?.currency\n if (currency !== undefined) return (value: number) => `${formatMoney(value * 100, currency).replace('.00', '')}${suffix}`\n return (value: number) => `${hints?.prefix ?? ''}${value}${suffix}`\n}\n","import { createWhere, enumLabel, parseFilter, printFilter, type ResourceModel, type ViewModel } from '@protobase/schema'\nimport { activeChips, type FilterChip, type FilterConfig } from '../../filter-panel'\nimport { textToState } from '../../live/filter-string'\nimport { humanize } from '../../live/naming'\nimport { rangeFormat, widgetFields } from '../../live/view-fields'\nimport { text as message } from './messages'\n\nconst where = createWhere()\nconst span = { start: 0, end: 0 }\n\n/** Names of relation values, by field and then by value, such as `{ place_id: { '1': 'Amsterdam' } }`. */\nexport type ValueNames = Record<string, Record<string, string>>\n\n/** The relation fields a filter chooses values of through its facets, each with the values it chooses. */\nexport const chosenRelations = (model: ResourceModel, view: ViewModel | undefined, text: string): Record<string, string[]> => {\n const parsed = textToState(widgetFields(view, model), text)\n if (!parsed.ok) return {}\n return Object.fromEntries(Object.entries(parsed.state.facets).filter(([field, values]) => model.fields[field]?.type === 'relation' && values.length > 0))\n}\n\n/**\n * The panel's widgets named as the list page names them, without counts: what reading a saved filter back into chips\n * needs. Enum values take the view's value labels, relation values the names in `names`.\n */\nconst namedConfig = (model: ResourceModel, view: ViewModel | undefined, names: ValueNames): FilterConfig => {\n const label = (name: string) => view?.fields[name]?.label ?? humanize(name)\n const skeleton = widgetFields(view, model)\n return {\n ...skeleton,\n facets: skeleton.facets.map((group) => {\n if (group.flags) return { ...group, options: group.options.map((option) => ({ ...option, label: label(option.value) })) }\n const values = model.fields[group.id]?.enumValues ?? []\n const labels = model.fields[group.id]?.type === 'enum' ? Object.fromEntries(values.map((value) => [value, enumLabel(value, view?.fields[group.id]?.valueLabels)])) : (names[group.id] ?? {})\n return { ...group, label: label(group.id), labels }\n }),\n ranges: (skeleton.ranges ?? []).map((range) => ({ ...range, label: label(range.id), format: rangeFormat(view, range.id) })),\n toggles: skeleton.toggles?.map((toggle) => ({ ...toggle, label: label(toggle.id) })),\n }\n}\n\n/**\n * A saved filter as the chips the list page shows for it, then a chip per condition no widget holds: the search text\n * in quotes, or the condition as written. One chip saying so when the filter cannot be read.\n */\nexport const filterChips = (model: ResourceModel, view: ViewModel | undefined, text: string, names: ValueNames = {}): FilterChip[] => {\n const config = namedConfig(model, view, names)\n const parsed = textToState(config, text)\n if (!parsed.ok) return [{ key: 'unreadable', label: message('unreadableFilter') }]\n const extras = parsed.extras.map((clause, index) => ({ key: `extra:${index}`, label: clause.kind === 'search' ? `\"${clause.text}\"` : printFilter(clause) }))\n return [...activeChips(config, parsed.state), ...extras]\n}\n\n/** The names the list page's panel knows for its facets' values, to name a search saved from it. */\nexport const facetNames = (config: FilterConfig): ValueNames =>\n Object.fromEntries(config.facets.filter((group) => !group.flags).map((group) => [group.id, { ...group.labels, ...Object.fromEntries(group.options.map((option) => [option.value, option.label])) }]))\n\n/**\n * The search's filter narrowed to the records new since the user last opened its results: those whose `field` is after\n * `seenAt`. Without a `seenAt` every record is new.\n */\nexport const unseenFilter = (text: string, field: string, seenAt: unknown) => {\n if (typeof seenAt !== 'string' || seenAt === '') return text\n const after = where.gt(field, { kind: 'timestamp', value: new Date(seenAt).toISOString(), span })\n const parsed = parseFilter(text)\n if (!parsed.ok) throw new Error(`The saved filter cannot be read: ${parsed.errors.map((error) => error.message).join('; ')}`)\n return printFilter(parsed.ast ? where.and(parsed.ast, after) : after)\n}\n\n/** Whether a record whose `field` holds `value` is new to the user, as `unseenFilter` finds it: after `seenAt`, or any. */\nexport const isUnseen = (value: unknown, seenAt: unknown) => {\n if (typeof seenAt !== 'string' || seenAt === '') return true\n if (typeof value !== 'string' || value === '') return false\n return new Date(value).getTime() > new Date(seenAt).getTime()\n}\n","import { useQueries, useQueryClient } from '@tanstack/react-query'\nimport type { ResourceModel } from '@protobase/schema'\nimport { useClient } from '../../data/api-provider'\nimport { keys } from '../../data/query-keys'\nimport { fetchLabels } from '../../live/relation-labels'\nimport { useAdminMeta } from '../meta-gate'\nimport { chosenRelations, filterChips, type ValueNames } from './saved-search'\n\n/** A saved filter of `model`'s list as chips, with the records its relation facets choose named once they have loaded. */\nexport const useFilterChips = (model: ResourceModel, text: string) => {\n const client = useClient()\n const queryClient = useQueryClient()\n const { resources, views } = useAdminMeta()\n const view = views[model.name]\n const chosen = Object.entries(chosenRelations(model, view, text))\n const named = useQueries({\n queries: chosen.map(([field, ids]) => {\n const target = resources[model.fields[field]!.relation!.resource]\n return {\n queryKey: keys.labels(`chips:${model.name}.${field}`, ids.join(',')),\n enabled: target !== undefined,\n queryFn: async () => Object.fromEntries(await fetchLabels(queryClient, client, target!, ids, views[target!.name])),\n }\n }),\n })\n const names: ValueNames = Object.fromEntries(chosen.flatMap(([field], index) => (named[index]?.data ? [[field, named[index].data]] : [])))\n return filterChips(model, view, text, names)\n}\n","import type { ResourceModel } from '@protobase/schema'\nimport { useRelationTitle } from './use-relation-title'\n\n/** The name of the record `id` of `target` a relation points at, for the reader; its key while the name loads. */\nexport const RelationTitleText = ({ target, id }: { target: ResourceModel; id: string }) => <>{useRelationTitle(target, id) ?? id}</>\n","import { createWhere, type FilterExpr, type KeyValue, type ResourceModel } from '@protobase/schema'\nimport { encodeKey } from '@protobase/schema/internal'\nimport { recordKey } from '../../live/model-helpers'\n\nconst where = createWhere()\n\n/** The most saved records one request lists; the user's own are loaded page by page until there are no more. */\nexport const savedPageSize = 500\n\n/** One of the user's saved records: its own key, and the key of the record its relation points at. */\nexport type SavedRecord = {\n /** The saved record's key, in the text form the record API takes. */\n key: string\n /** The value of its relation, the key of the record it saves. */\n target: KeyValue\n}\n\n// A relation's value is the key it points at; labelled, it comes as `{ id, name }`.\nconst relationValue = (value: unknown): KeyValue | undefined => {\n if (typeof value === 'string' || typeof value === 'number') return value\n if (value && typeof value === 'object' && 'id' in value) return relationValue((value as { id: unknown }).id)\n return undefined\n}\n\n/** The saved records among listed rows of `model`, by the relation `field`; rows without a value are left out. */\nexport const savedRecordsOf = (model: ResourceModel, field: string, rows: readonly Record<string, unknown>[]): SavedRecord[] =>\n rows.flatMap((row) => {\n const target = relationValue(row[field])\n return target === undefined ? [] : [{ key: encodeKey(recordKey(model, row)), target }]\n })\n\n/** The saved record of the record with this key, the text form the record API takes, if it is saved. */\nexport const savedFor = (saved: readonly SavedRecord[], key: string) => saved.find((entry) => encodeKey(entry.target) === key)\n\n/** The saved records with one more, until the server answers with its key. */\nexport const withSaved = (saved: readonly SavedRecord[], target: KeyValue): SavedRecord[] => [...saved, { key: '', target }]\n\n/** The saved records without the one of the record with this key. */\nexport const withoutSaved = (saved: readonly SavedRecord[], key: string): SavedRecord[] => saved.filter((entry) => encodeKey(entry.target) !== key)\n\n/**\n * The filter of the records the saved ones point at, on the target's single-column key; undefined when there are none,\n * as `in()` needs at least one value.\n */\nexport const savedScope = (target: ResourceModel, saved: readonly SavedRecord[]): FilterExpr | undefined => {\n const [key] = target.primaryKey\n if (target.primaryKey.length !== 1 || key === undefined) throw new Error(`${target.name} has a composite key, so its saved records cannot be listed`)\n const values = [...new Set(saved.map((entry) => entry.target))]\n return values.length === 0 ? undefined : where.in(key, values as never[])\n}\n","import { useQuery } from '@tanstack/react-query'\nimport { useClient } from '../../data/api-provider'\nimport { keys } from '../../data/query-keys'\nimport { useAdminMeta } from '../meta-gate'\nimport { savedPageSize, savedRecordsOf, type SavedRecord } from './saved-records'\n\n/** Where the user's saved records of `resource` by `field` are cached; a list key, so a write to the resource refreshes it. */\nexport const savedRecordsKey = (resource: string, field: string) => keys.list(resource, '', '', savedPageSize, `saved:${field}`)\n\n/**\n * The signed-in user's saved records of `resource`, each with the key its relation `field` points at: every one, page\n * by page, as the API lists only a user's own records of a resource with an owner. Loads only while `enabled`.\n */\nexport const useSavedRecords = (resource: string, field: string, enabled: boolean) => {\n const client = useClient()\n const model = useAdminMeta().resources[resource]\n return useQuery({\n queryKey: savedRecordsKey(resource, field),\n enabled: enabled && model !== undefined,\n queryFn: async (): Promise<SavedRecord[]> => {\n const rows: Record<string, unknown>[] = []\n let pageToken: string | undefined\n do {\n const page = await client.list(resource, { pageSize: savedPageSize, fields: [...model!.primaryKey, field], ...(pageToken && { pageToken }) })\n rows.push(...(page.items as Record<string, unknown>[]))\n pageToken = page.nextPageToken || undefined\n } while (pageToken)\n return savedRecordsOf(model!, field, rows)\n },\n })\n}\n","import { messages } from '../../locale/messages'\n\nexport const text = messages('app/saved')\n","import { useMutation, useQueryClient } from '@tanstack/react-query'\nimport type { CardFavoriteModel, KeyValue } from '@protobase/schema'\nimport { useClient } from '../../data/api-provider'\nimport { useToast } from '../../toasts'\nimport { useAdminMeta } from '../meta-gate'\nimport { useRefreshResource } from '../pages/use-layout-data'\nimport { can } from '../permissions'\nimport { savedFor, withoutSaved, withSaved, type SavedRecord } from './saved-records'\nimport { savedRecordsKey, useSavedRecords } from './use-saved-records'\nimport { text } from './messages'\n\nconst message = (error: unknown) => (error instanceof Error ? error.message : text('somethingWrong'))\n\n/**\n * A card's favorite button: `save` for someone who can list, create and delete the saved records, `sign-in` for a\n * visitor the saved records' resource asks to sign in (`prompt`), nothing otherwise. A press saves the card's record,\n * or takes it off, at once on screen; a refused write puts it back and says why.\n */\nexport const useFavorite = (favorite: CardFavoriteModel, key: string, target: KeyValue) => {\n const meta = useAdminMeta()\n const client = useClient()\n const queryClient = useQueryClient()\n const toast = useToast()\n const refresh = useRefreshResource()\n const { resource, field } = favorite\n const permissions = meta.permissions[resource]\n const usable = meta.resources[resource] !== undefined && permissions !== undefined && can(permissions, 'create') && can(permissions, 'delete')\n const prompt = meta.signIn?.[resource]?.signIn\n const saved = useSavedRecords(resource, field, usable)\n const current = saved.data && savedFor(saved.data, key)\n const cacheKey = savedRecordsKey(resource, field)\n\n const toggle = useMutation({\n mutationFn: async (existing: SavedRecord | undefined) => {\n if (existing) await client.remove(resource, existing.key)\n else await client.create(resource, { [field]: target })\n },\n onMutate: async (existing) => {\n await queryClient.cancelQueries({ queryKey: cacheKey, exact: true })\n const before = queryClient.getQueryData<SavedRecord[]>(cacheKey)\n queryClient.setQueryData<SavedRecord[]>(cacheKey, (list = []) => (existing ? withoutSaved(list, key) : withSaved(list, target)))\n return { before }\n },\n onError: (error, existing, context) => {\n queryClient.setQueryData(cacheKey, context?.before)\n toast.show({ state: 'error', title: existing ? text('couldNotTakeOff') : text('couldNotSave'), description: message(error) })\n },\n onSettled: () => refresh(resource),\n })\n\n return {\n mode: usable ? ('save' as const) : prompt ? ('sign-in' as const) : undefined,\n prompt,\n saved: current !== undefined,\n // Until the saved records are known, and while a press is on its way, another press would not know what to do\n ready: saved.data !== undefined && !toggle.isPending,\n toggle: () => toggle.mutate(current),\n }\n}\n","import { Heart } from 'lucide-react'\nimport { useState } from 'react'\nimport type { CardFavoriteModel, KeyValue } from '@protobase/schema'\nimport { SignInPrompt } from '../../auth/sign-in-prompt'\nimport { cn } from '../../lib/cn'\nimport { useFavorite } from './use-favorite'\nimport { text } from './messages'\n\ntype FavoriteButtonProps = {\n favorite: CardFavoriteModel\n /** The card's record key, in the text form the record API takes. */\n recordKey: string\n /** The card's record key as the saved record's relation holds it. */\n target: KeyValue\n className?: string\n}\n\n/**\n * A heart that saves the card's record for the signed-in user, pressed while it is saved, or, for a visitor, opens the\n * sign-in prompt of the saved records' resource. It sits over the card's link, beside it in the document, so pressing\n * it does not open the record; the card's list item must be `relative`.\n */\nexport const FavoriteButton = ({ favorite, recordKey, target, className }: FavoriteButtonProps) => {\n const state = useFavorite(favorite, recordKey, target)\n const [prompting, setPrompting] = useState(false)\n if (!state.mode) return null\n const label = favorite.label ?? text('favorite')\n const base = cn(\n 'absolute right-2 top-2 flex size-8 items-center justify-center rounded-full bg-background/85 text-foreground shadow-sm transition-colors hover:bg-background focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/30',\n className,\n )\n if (state.mode === 'sign-in') {\n return (\n <>\n <button type=\"button\" aria-label={label} aria-haspopup=\"dialog\" className={base} onClick={() => setPrompting(true)}>\n <Heart className=\"size-4\" aria-hidden />\n </button>\n <SignInPrompt as=\"dialog\" prompt={state.prompt!} open={prompting} onClose={() => setPrompting(false)} />\n </>\n )\n }\n return (\n <button type=\"button\" aria-label={label} aria-pressed={state.saved} aria-disabled={!state.ready} className={base} onClick={() => state.ready && state.toggle()}>\n <Heart className={cn('size-4', state.saved && 'fill-current text-danger')} aria-hidden />\n </button>\n )\n}\n","const gap = 6\n\ntype Box = { top: number; bottom: number; left: number; width: number }\n\n/**\n * Where a card of `card`'s size goes for the dot at `dot`, in viewport pixels: below it, or above it when the viewport\n * has no room underneath, starting at its left edge and kept inside the viewport's sides.\n */\nexport const placeCard = (dot: Box, card: { width: number; height: number }, viewport: { width: number; height: number }) => {\n const below = dot.bottom + gap\n const top = below + card.height > viewport.height - gap ? Math.max(gap, dot.top - gap - card.height) : below\n const left = Math.max(gap, Math.min(dot.left, viewport.width - gap - card.width))\n return { top, left }\n}\n","import type { ListDisplayModel, ResourceModel, ViewModel } from '@protobase/schema'\nimport type { RelatedColumnLoad } from '../../live/related-column-rows'\nimport { displaysOf, shownFields } from '../displays/list-displays'\n\ntype CardsDisplayModel = Extract<ListDisplayModel, { kind: 'cards' }>\n\n/**\n * The card a dot shows of its record: the first cards display of the record's view, without the photos, favorite\n * button and dots a small card has no room for, else the record's title with its status as the badge.\n */\nexport const dotCard = (view: ViewModel | undefined, status: string): CardsDisplayModel => {\n const cards = displaysOf(view).find((display): display is CardsDisplayModel => display.kind === 'cards')\n if (!cards) return { kind: 'cards', name: 'dot', badge: status }\n const { photos: _, favorite: __, dots: ___, ...card } = cards\n return card\n}\n\n/** What the list loads for the related columns of its view among `columns`: each with the fields its dots' cards show. */\nexport const relatedColumnLoads = (view: ViewModel | undefined, resources: Record<string, ResourceModel>, views: Record<string, ViewModel>, columns: string[]): RelatedColumnLoad[] =>\n (view?.list?.relatedColumns ?? [])\n .filter((column) => columns.includes(column.name))\n .flatMap((column) => {\n const target = resources[column.resource]\n return target ? [{ column, fields: shownFields(target, views[target.name], dotCard(views[target.name], column.status)) }] : []\n })\n","import { messages } from '../../locale/messages'\n\nexport const text = messages('app/related-dots')\n","import { text } from './messages'\ntype SummaryOptions = {\n /** The status field's values, in the order the summary counts them. */\n values: readonly string[]\n /** How a value reads, as the record's badge shows it. */\n label: (value: string) => string\n /** What one record and several are called, such as \"task\" and \"tasks\". */\n singular: string\n plural: string\n}\n\n/**\n * What a related column's dots say, as text: how many records there are, then how many have each status, in the order\n * of the status's values, such as \"4 tasks: 1 To do, 3 Done\". \"No tasks\" without any.\n */\nexport const dotsSummary = (statuses: readonly unknown[], { values, label, singular, plural }: SummaryOptions) => {\n if (statuses.length === 0) return text('none', { plural })\n const counts = new Map<string, number>()\n for (const status of statuses) if (status !== null && status !== undefined) counts.set(String(status), (counts.get(String(status)) ?? 0) + 1)\n const order = [...values, ...[...counts.keys()].filter((value) => !values.includes(value))]\n const parts = order.filter((value) => counts.has(value)).map((value) => `${counts.get(value)} ${label(value)}`)\n const total = `${statuses.length} ${statuses.length === 1 ? singular : plural}`\n return parts.length === 0 ? total : `${total}: ${parts.join(', ')}`\n}\n","import { useEffect, useLayoutEffect, useMemo, useRef, useState, type ComponentType, type FocusEvent, type MouseEvent, type PointerEvent } from 'react'\nimport { createPortal } from 'react-dom'\nimport type { ListDisplayModel, RelatedColumnModel, ResourceModel, ViewModel } from '@protobase/schema'\nimport { cn } from '../../lib/cn'\nimport { displayValue } from '../../live/display-value'\nimport { recordTitleField } from '../../live/model-helpers'\nimport { humanize } from '../../live/naming'\nimport { valueColor, valueTone } from '../../live/value-color'\nimport { toneDots } from '../../primitives/badge'\nimport { displayRow, type ListDisplayRow } from '../displays/list-displays'\nimport { AppLink } from '../use-app-address'\nimport { placeCard } from './card-place'\nimport { dotCard } from './dot-card'\nimport { dotsSummary } from './dots-summary'\n\ntype RelatedDotsProps = {\n column: RelatedColumnModel\n /** The records of `target` the column shows for the row, in its order, as the list loaded them. */\n records: Array<Record<string, unknown>>\n target: ResourceModel\n view: ViewModel | undefined\n /** Whether the dots wrap onto more lines, as a card's do, over a card whose link takes the pointer between them. */\n wrap?: boolean\n /** Draws the card a dot shows: `RecordCard`, passed in because a card draws dots too. */\n Card: DotCardComponent\n}\n\n/** A record's card as `RecordCard` draws it. */\nexport type DotCardComponent = ComponentType<{ model: ResourceModel; view: ViewModel | undefined; display: Extract<ListDisplayModel, { kind: 'cards' }>; row: ListDisplayRow }>\n\n/** A dot's box and its mark, which a card's room for its dots (`DotsRoom`) takes the size of. */\nconst dotBox = 'flex shrink-0 items-center justify-center rounded-full p-0.5 pointer-coarse:p-1.5'\nconst dotMark = 'size-2.5 rounded-full'\nconst dotsLine = 'flex min-w-0 items-center gap-0.5'\n\n// How long the card stays after the pointer leaves its dot, so it can move onto the card. A touch shows it on a tap\n// instead, and keyboard focus as it reaches the dot\nconst hideMs = 150\n\nconst cardWidth = 288\n\ntype Shown = { key: string; dot: DOMRect }\n\n/**\n * The card of the dot that is hovered, focused or tapped, portalled to the body: every grid row is its own stacking\n * context and the grid body clips, so a card inside the row would sit under the rows below it.\n */\nconst DotCardPopover = ({ shown, row, target, view, column, Card, onEnter, onLeave }: { shown: Shown; row: ListDisplayRow; target: ResourceModel; view: ViewModel | undefined; column: RelatedColumnModel; Card: DotCardComponent; onEnter: () => void; onLeave: () => void }) => {\n const card = useRef<HTMLDivElement>(null)\n const [place, setPlace] = useState<{ top: number; left: number }>()\n useLayoutEffect(() => {\n if (!card.current) return\n setPlace(placeCard(shown.dot, { width: cardWidth, height: card.current.offsetHeight }, { width: window.innerWidth, height: window.innerHeight }))\n }, [shown])\n return createPortal(\n <div ref={card} data-dot-card onMouseEnter={onEnter} onMouseLeave={onLeave} style={{ width: cardWidth, ...(place ?? { visibility: 'hidden', top: 0, left: 0 }) }} className=\"fixed z-50 rounded-lg shadow-pop\">\n <Card model={target} view={view} display={dotCard(view, column.status)} row={row} />\n </div>,\n document.body,\n )\n}\n\n/**\n * A related column's cell: a dot per record in the colour its status has in its view, each a link to the record. Hovering\n * or focusing a dot shows the record's card; on a touch screen the first tap shows it, and the card opens the record.\n * The dots say how many records have each status to a screen reader.\n */\nexport const RelatedDots = ({ column, records, target, view, wrap = false, Card }: RelatedDotsProps) => {\n const rows = useMemo(() => records.map((record) => displayRow(target, record)), [records, target])\n const [shown, setShown] = useState<Shown>()\n const hideTimer = useRef<number>(undefined)\n const pointer = useRef<string>('mouse')\n const box = useRef<HTMLDivElement>(null)\n\n const status = target.fields[column.status]\n const hints = view?.fields[column.status]\n const statusText = (row: ListDisplayRow) => (status ? displayValue(status, row.record[column.status], hints) : '')\n const titleField = recordTitleField(target, view)\n const title = (row: ListDisplayRow) => row.labels[titleField] ?? String(row.record[titleField] ?? row.key)\n const singular = (view?.names?.singular ?? humanize(target.name)).toLowerCase()\n const plural = (view?.names?.plural ?? humanize(target.name)).toLowerCase()\n const summary = dotsSummary(\n rows.map((row) => row.record[column.status]),\n { values: status?.enumValues ?? [], label: (value) => (status ? displayValue(status, value, hints) : value), singular, plural },\n )\n\n const cancelHide = () => window.clearTimeout(hideTimer.current)\n const hideSoon = () => {\n cancelHide()\n hideTimer.current = window.setTimeout(() => setShown(undefined), hideMs)\n }\n const show = (key: string, dot: Element) => {\n cancelHide()\n setShown({ key, dot: dot.getBoundingClientRect() })\n }\n useEffect(() => cancelHide, [])\n\n // The card stays where it was drawn, so scrolling or resizing closes it, and so do Escape and a tap elsewhere\n useEffect(() => {\n if (!shown) return\n const hide = () => setShown(undefined)\n const key = (event: KeyboardEvent) => event.key === 'Escape' && hide()\n const outside = (event: Event) => {\n const target = event.target as Element | null\n if (!box.current?.contains(target) && !target?.closest?.('[data-dot-card]')) hide()\n }\n document.addEventListener('keydown', key)\n document.addEventListener('pointerdown', outside)\n document.addEventListener('scroll', hide, true)\n window.addEventListener('resize', hide)\n return () => {\n document.removeEventListener('keydown', key)\n document.removeEventListener('pointerdown', outside)\n document.removeEventListener('scroll', hide, true)\n window.removeEventListener('resize', hide)\n }\n }, [shown])\n\n // A tap on a dot whose card is not open shows the card instead of following the link\n const tap = (key: string) => (event: MouseEvent<HTMLAnchorElement>) => {\n if (pointer.current !== 'touch' || shown?.key === key) return\n event.preventDefault()\n show(key, event.currentTarget)\n }\n const blur = (event: FocusEvent) => {\n if (!(event.relatedTarget as Element | null)?.closest?.('[data-dot-card]')) hideSoon()\n }\n const shownRow = shown && rows.find((row) => row.key === shown.key)\n\n return (\n // A click on a dot or its card stays out of the row, which opens its own record\n <div ref={box} className={cn(dotsLine, wrap && 'pointer-events-none flex-wrap')} onClick={(event) => event.stopPropagation()} onPointerDown={(event: PointerEvent) => (pointer.current = event.pointerType)}>\n <span className=\"sr-only\">{summary}</span>\n {rows.map((row) => {\n const value = row.record[column.status]\n const color = valueColor(hints?.valueColors, value)\n return (\n <AppLink\n key={row.key}\n to={{ kind: 'record', resource: target.name, key: row.key }}\n aria-label={`${title(row)}, ${statusText(row)}`}\n onPointerEnter={(event) => event.pointerType !== 'touch' && show(row.key, event.currentTarget)}\n onPointerLeave={(event) => event.pointerType !== 'touch' && hideSoon()}\n onFocus={(event) => event.currentTarget.matches(':focus-visible') && show(row.key, event.currentTarget)}\n onBlur={blur}\n onClick={tap(row.key)}\n className={cn(dotBox, 'pointer-events-auto focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/40')}\n >\n <span aria-hidden style={color === undefined ? undefined : { backgroundColor: color }} className={cn(dotMark, color === undefined && toneDots[valueTone(hints?.valueColors, value)], shown?.key === row.key && 'ring-2 ring-foreground/30')} />\n </AppLink>\n )\n })}\n {shown && shownRow && <DotCardPopover shown={shown} row={shownRow} target={target} view={view} column={column} Card={Card} onEnter={cancelHide} onLeave={hideSoon} />}\n </div>\n )\n}\n\n/** Room for `count` dots that wrap as `RelatedDots` with `wrap` does, for a card to hold the dots drawn over it. */\nexport const DotsRoom = ({ count }: { count: number }) => (\n <span aria-hidden className={cn(dotsLine, 'invisible flex-wrap')}>\n {Array.from({ length: count }, (_, index) => (\n <span key={index} className={dotBox}>\n <span className={dotMark} />\n </span>\n ))}\n </span>\n)\n","import { useAdminMeta } from '../meta-gate'\nimport type { CardDotsLine } from './card-dots-lines'\nimport { DotsRoom, RelatedDots, type DotCardComponent } from './related-dots'\n\nconst lines = 'flex flex-col gap-1.5'\n\n/** The room a card's lines of dots take at its bottom, which the dots are drawn over. */\nexport const CardDotsRoom = ({ dots }: { dots: CardDotsLine[] }) => (\n <span className={lines}>\n {dots.map(({ column, records }) => (\n <DotsRoom key={column.name} count={records.length} />\n ))}\n </span>\n)\n\n/**\n * A card's lines of dots, over the room the card holds for them at its bottom, inside its border and padding: beside\n * the card in the document, so a dot is a link of its own and the pointer between the dots reaches the card's link.\n * The card's list item must be `relative`.\n */\nexport const CardDots = ({ dots, Card }: { dots: CardDotsLine[]; Card: DotCardComponent }) => {\n const { resources, views } = useAdminMeta()\n return (\n <div className={`pointer-events-none absolute inset-x-[calc(0.75rem+1px)] bottom-[calc(0.75rem+1px)] ${lines}`}>\n {dots.map(({ column, records }) => {\n const target = resources[column.resource]\n return target && <RelatedDots key={column.name} column={column} records={records} target={target} view={views[target.name]} Card={Card} wrap />\n })}\n </div>\n )\n}\n","import type { ListDisplayModel, RelatedColumnModel, ViewModel } from '@protobase/schema'\nimport type { ListDisplayRow } from '../displays/list-displays'\n\n/** A line of dots a card shows: a related column of the list and the records the list loaded with the row for it. */\nexport type CardDotsLine = { column: RelatedColumnModel; records: Array<Record<string, unknown>> }\n\n/**\n * The lines of dots a card of `display` shows for a row, in the order it names their columns: those of the list's\n * related columns that were loaded with the row and hold a record. A row loaded without them, as a map's or a saved\n * search's, shows none.\n */\nexport const cardDotsLines = (view: ViewModel | undefined, display: Extract<ListDisplayModel, { kind: 'cards' }>, row: ListDisplayRow): CardDotsLine[] =>\n (display.dots ?? []).flatMap((name) => {\n const column = view?.list?.relatedColumns?.find((candidate) => candidate.name === name)\n const records = row.record[name]\n return column && Array.isArray(records) && records.length > 0 ? [{ column, records: records as CardDotsLine['records'] }] : []\n })\n","import type { ReactNode } from 'react'\nimport { FileImage } from '../../live/file-image'\nimport { shownImage } from '../../live/file-values'\n\n/** A raster image filling its frame; nothing for any other value. */\nexport const CardPhoto = ({ value }: { value: unknown }) => {\n const image = shownImage(value, { width: 320, height: 240 })\n return image ? <FileImage image={image} loading=\"lazy\" className=\"size-full object-cover\" /> : null\n}\n\n/** The frame across a card's top, from the edge of the card in, holding its picture. */\nexport const CardImageFrame = ({ children }: { children: ReactNode }) => (\n <span className=\"-mx-3 -mt-3 mb-1.5 block aspect-[4/3] overflow-hidden rounded-t-lg border-b border-border bg-muted\">{children}</span>\n)\n\n/** A picture across the card's top: a raster image only, an empty frame otherwise. */\nexport const CardImage = ({ value }: { value: unknown }) => (\n <CardImageFrame>\n <CardPhoto value={value} />\n </CardImageFrame>\n)\n","import { cardPhotoLimit } from '@protobase/schema/internal'\nimport { isStoredFile } from '../../live/file-values'\n\n/** The most photos a card steps through, its own image among them, each marked by a dot. */\nexport const maxCardDots = cardPhotoLimit\n\n/**\n * The files a card steps through: its own image first, then its photos less that same file, at most `maxCardDots`;\n * empty values are left out.\n */\nexport const cardPhotoList = (cover: unknown, photos: readonly unknown[]): unknown[] => {\n const coverUri = isStoredFile(cover) ? cover.uri : undefined\n const rest = photos.filter((photo) => isStoredFile(photo) && photo.uri !== coverUri)\n return (coverUri === undefined ? rest : [cover, ...rest]).slice(0, maxCardDots)\n}\n","import type { ReactNode } from 'react'\nimport { CarouselControls } from '../../carousel/carousel-controls'\nimport { CarouselTrack } from '../../carousel/carousel-track'\nimport { useCarousel } from '../../carousel/use-carousel'\nimport { CardImageFrame, CardPhoto } from './card-image'\nimport { cardPhotoList } from './card-photos'\n\ntype CardCarouselProps = {\n /** The record's photos, as its list loaded them. */\n photos: readonly unknown[]\n /** The card's own image, shown first. */\n cover: unknown\n /** Whether a swipe steps through the photos; off, it scrolls what the card sits in, such as a row that scrolls sideways. */\n swipe?: boolean\n /** The card, drawn with the picture across its top. */\n children: (picture: ReactNode) => ReactNode\n}\n\n/**\n * A card whose picture steps through its photos, the card's own image first: a track that snaps photo by photo, swiped\n * on a touch screen or moved by arrows, with dots marking the one in view. The photos come with the card's row, in the\n * same answer as the list, so the dots mark its own image from the start. The card puts the track in a link of its own,\n * so a tap opens the record and a swipe does not; the arrows sit over it, beside the card in the document, so pressing\n * one does not open the record either. The card's list item must be `relative group/card`.\n */\nexport const CardCarousel = ({ photos, cover, swipe = true, children }: CardCarouselProps) => {\n const list = cardPhotoList(cover, photos)\n const carousel = useCarousel(list.length)\n\n const picture = (\n <CardImageFrame>\n <CarouselTrack data-card-photos carousel={carousel} swipe={swipe} slides={list.map((photo) => <CardPhoto value={photo} />)} />\n </CardImageFrame>\n )\n\n return (\n <>\n {children(picture)}\n <CarouselControls\n carousel={carousel}\n count={list.length}\n swipe={swipe}\n reveal=\"group-has-[[data-card-photos]:hover]/card:opacity-100\"\n className=\"inset-x-px top-px aspect-[4/3]\"\n />\n </>\n )\n}\n","import type { ReactNode } from 'react'\nimport type { KeyValue, ListDisplayModel, ResourceModel, ViewModel } from '@protobase/schema'\nimport { displayValue } from '../../live/display-value'\nimport { jsonSummary } from '../../live/json-summary'\nimport { linkTextOf } from '../../live/link-text'\nimport { recordKey } from '../../live/model-helpers'\nimport { humanize } from '../../live/naming'\nimport { Badge } from '../../primitives/badge'\nimport { CodeBlock } from '../../primitives/code-block'\nimport { AppLink } from '../use-app-address'\nimport { useSeedRecord } from '../record-preview'\nimport { shownWidget } from '../field-types/shown-widget'\nimport { WidgetPart } from '../field-types/widget-part'\nimport { namedIcon } from '../named-icon'\nimport { useAdminMeta } from '../meta-gate'\nimport { RelationTitleText } from '../titles/relation-title-text'\nimport { CustomBoundary } from '../pages/custom-boundary'\nimport { FavoriteButton } from '../saved/favorite-button'\nimport { useProjectUi } from '../pages/project-ui'\nimport { ValueBadge } from '../value-badge'\nimport { CardDots, CardDotsRoom } from '../related-dots/card-dots'\nimport { cardDotsLines } from '../related-dots/card-dots-lines'\nimport { CardCarousel } from './card-carousel'\nimport { CardImage } from './card-image'\nimport { Markdown } from '../../markdown/markdown'\nimport { markdownExcerpt } from '../../markdown/markdown-excerpt'\nimport { isMarkdown } from '../../markdown/markdown-hint'\nimport { amountParts, cardFields, filledAmount, filledCode, filledMeta, rawCode, type ListDisplayRow } from './list-displays'\nimport { text as message } from './messages'\n\ntype RecordCardProps = {\n model: ResourceModel\n view: ViewModel | undefined\n display: Extract<ListDisplayModel, { kind: 'cards' }>\n row: ListDisplayRow\n /** Whether a swipe steps through the card's photos; off in a row that scrolls sideways, which the swipe scrolls instead. */\n swipe?: boolean\n /** A word marked in the card's top left corner, such as \"New\": over its picture, or above its title without one. */\n mark?: string\n}\n\n// A meta field's value after the icon its view names.\nconst MetaValue = ({ icon, children }: { icon: string | undefined; children: ReactNode }) => {\n const Icon = namedIcon(icon)\n return (\n <dd className=\"flex items-center gap-1 tabular-nums\">\n {Icon && <Icon className=\"size-3.5 shrink-0\" aria-hidden />}\n {children}\n </dd>\n )\n}\n\n/**\n * A record's card of a cards display, opening its page: its image across the top, swiped or stepped through its photos\n * when the display names them, the title over the subtitle, the badge beside it, the first amount with a value in bold,\n * small meta fields below, those with a value, the labels of its flags that are true, the footer's fields with a\n * value, joined by bullets, and a line of dots for each related column of the list it names; or, with a `card`\n * component, what it draws of the row, the built-in content again when it is missing or throws. With a favorite button, a heart in the top right corner saves the record.\n */\nexport const RecordCard = ({ model, view, display, row, swipe = true, mark }: RecordCardProps) => {\n const { image, title, subtitle, amount, badge, code, meta, footer, flags } = cardFields(model, view, display)\n const label = (name: string) => view?.fields[name]?.label ?? humanize(name)\n const { resources, views } = useAdminMeta()\n const text = (name: string): ReactNode => {\n const field = model.fields[name]\n if (!field) return ''\n const value = row.record[name]\n // A relation to a resource whose view derives its titles names its record for the reader\n const target = field.type === 'relation' && field.relation ? resources[field.relation.resource] : undefined\n if (target && views[target.name]?.titleFrom && value != null) return <RelationTitleText target={target} id={String(value)} />\n // Markdown reads as its text on a card's one-line parts\n if (row.labels[name] === undefined && isMarkdown(field, view?.fields[name]) && typeof value === 'string' && value !== '') return markdownExcerpt(value)\n // JSON reads as its summary there, as in a table cell\n if (field.type === 'json' && value != null) return jsonSummary(value)\n // A url reads as its link text, when the view gives one, as the address alone says little\n if (view?.fields[name]?.format === 'url' && typeof value === 'string' && value !== '') return linkTextOf(model, view, name, row.record) ?? value\n return row.labels[name] ?? displayValue(field, value, view?.fields[name])\n }\n // A field the view shows with a field type draws its display\n const { fields: fieldTypes, components } = useProjectUi()\n const seedRecord = useSeedRecord(model)\n const Card = display.card === undefined ? undefined : components?.[display.card]\n const shownValue = (name: string) => {\n const field = model.fields[name]\n const shown = field && shownWidget(fieldTypes, field, view?.fields[name])\n return shown ? <WidgetPart shown={shown} part=\"display\" field={field} value={row.record[name]} fallback={text(name)} /> : text(name)\n }\n // A markdown subtitle shows rendered, its links as text inside the card's own link\n const subtitleValue = (name: string) => {\n const field = model.fields[name]\n const value = row.record[name]\n if (!field || !isMarkdown(field, view?.fields[name]) || shownWidget(fieldTypes, field, view?.fields[name]) || typeof value !== 'string' || value === '') return shownValue(name)\n return <Markdown source={value} inLink />\n }\n // A meta field the view formats as a badge shows as one, unless a field type draws it\n const metaValue = (name: string) => {\n const field = model.fields[name]\n const hints = view?.fields[name]\n const value = row.record[name]\n if (!field || hints?.format !== 'badge' || shownWidget(fieldTypes, field, hints) || value === null || value === undefined || value === '') return shownValue(name)\n return (\n <ValueBadge value={value} hints={hints}>\n {text(name)}\n </ValueBadge>\n )\n }\n // The amount in bold, its suffix such as ` /month` not; a relation's name or a field type's display in bold whole\n const amountValue = (name: string) => {\n const field = model.fields[name]\n if (!field) return undefined\n if (row.labels[name] !== undefined || shownWidget(fieldTypes, field, view?.fields[name])) return <strong className=\"font-semibold text-foreground\">{shownValue(name)}</strong>\n const parts = amountParts(field, row.record[name], view?.fields[name])\n return (\n <>\n <strong className=\"font-semibold text-foreground\">{parts.amount}</strong>\n {parts.suffix}\n </>\n )\n }\n // A card component draws its own content, so only the built-in card steps through photos\n const photos = Card ? undefined : display.photos\n const status = badge === undefined ? undefined : row.record[badge]\n const raised = flags.filter((name) => row.record[name] === true)\n const cover = image === undefined ? undefined : row.record[image]\n const shownAmount = filledAmount(row, amount)\n const shownCode = filledCode(row, code)\n const footing = filledMeta(row, footer)\n const pictured = image !== undefined || photos !== undefined\n // The heart sits over the picture, or beside the title, which leaves it room\n const favorite = display.favorite\n // A card component draws its own content, so only the built-in card shows the list's dots\n const dots = Card ? [] : cardDotsLines(view, display, row)\n // The card's one link is its title, stretched over the whole card, so a screen reader reads the card as one link named\n // by its title and the rest as text\n const link = (className: string, children: ReactNode) => (\n <AppLink\n to={{ kind: 'record', resource: model.name, key: row.key }}\n onClick={() => seedRecord(row.record)}\n data-card-link\n className={`${className} after:absolute after:inset-0 after:rounded-lg after:content-[''] focus-visible:outline-hidden`}\n >\n {children}\n </AppLink>\n )\n const builtIn = (picture: ReactNode, linked: boolean) => (\n <>\n {pictured && picture}\n <span className={`flex items-start justify-between gap-2 ${favorite && !pictured ? 'pr-8' : ''}`}>\n {linked ? link('min-w-0 truncate font-medium', shownValue(title)) : <span className=\"min-w-0 truncate font-medium\">{shownValue(title)}</span>}\n {badge !== undefined && status !== null && status !== undefined && (\n <ValueBadge value={status} hints={view?.fields[badge]}>\n {text(badge)}\n </ValueBadge>\n )}\n </span>\n {subtitle !== undefined && (\n // A text of several lines keeps its first three, line breaks and all, and markdown its first three rendered\n <span className={view?.fields[subtitle]?.markdown ? 'line-clamp-3 break-words text-muted-foreground' : view?.fields[subtitle]?.multiline ? 'line-clamp-3 whitespace-pre-line break-words text-muted-foreground' : 'truncate text-muted-foreground'}>{subtitleValue(subtitle)}</span>\n )}\n {shownAmount !== undefined && <span className=\"truncate tabular-nums text-muted-foreground\">{amountValue(shownAmount)}</span>}\n {shownCode !== undefined && <CodeBlock>{rawCode(model.fields[shownCode], row.record[shownCode]) ?? text(shownCode)}</CodeBlock>}\n {meta.length > 0 && (\n <dl className=\"mt-auto flex flex-wrap items-center gap-x-3 gap-y-0.5 pt-1 text-xs text-muted-foreground\">\n {filledMeta(row, meta).map((name) => (\n <div key={name} className=\"flex gap-1\">\n <dt className=\"sr-only\">{label(name)}</dt>\n <MetaValue icon={view?.fields[name]?.icon}>{metaValue(name)}</MetaValue>\n </div>\n ))}\n </dl>\n )}\n {raised.length > 0 && (\n <ul className=\"flex flex-wrap gap-1\" aria-label={message('features')}>\n {raised.map((name) => (\n <li key={name}>\n <Badge dot={false}>{label(name)}</Badge>\n </li>\n ))}\n </ul>\n )}\n {footing.length > 0 && (\n <span className={`truncate text-xs text-muted-foreground ${meta.length > 0 ? '' : 'mt-auto'}`}>\n {footing.map((name, index) => (\n <span key={name}>\n {index > 0 && <span aria-hidden> • </span>}\n {shownValue(name)}\n </span>\n ))}\n </span>\n )}\n {dots.length > 0 && <CardDotsRoom dots={dots} />}\n </>\n )\n // Isolated, so what sits beside the card in the document, such as the photo arrows and the heart, stays over its link\n const card = (picture: ReactNode) => (\n <div className=\"relative isolate flex h-full flex-col gap-1.5 rounded-lg border border-border bg-background p-3 hover:border-border-strong hover:bg-surface has-[[data-card-link]:focus-visible]:ring-2 has-[[data-card-link]:focus-visible]:ring-primary/30\">\n {mark && !pictured && (\n <Badge tone=\"blue\" className=\"self-start\">\n {mark}\n </Badge>\n )}\n {Card ? (\n <>\n {/* A drawn card's content is not known to hold the title, so the link over it is named by the title unseen */}\n {link('absolute inset-0', <span className=\"sr-only\">{shownValue(title)}</span>)}\n <CustomBoundary name={display.card!} fallback={builtIn(picture, false)}>\n <Card row={row} />\n </CustomBoundary>\n </>\n ) : (\n builtIn(picture, true)\n )}\n </div>\n )\n return (\n <div className={photos ? 'group/card relative h-full' : favorite || mark || dots.length > 0 ? 'relative h-full' : 'h-full'}>\n {photos ? (\n // A card drawn for another record, as the map's chosen card is, starts again at that record's first photo\n <CardCarousel key={row.key} photos={row.photos ?? []} cover={cover} swipe={swipe}>\n {(picture) =>\n card(\n // The photos sit over the title's link, so a swipe moves them; a tap opens the record through a link of their\n // own, which a screen reader skips as the title's says the same\n <AppLink to={{ kind: 'record', resource: model.name, key: row.key }} onClick={() => seedRecord(row.record)} tabIndex={-1} aria-hidden className=\"relative z-[1] block\">\n {picture}\n </AppLink>,\n )\n }\n </CardCarousel>\n ) : (\n card(<CardImage value={cover} />)\n )}\n {mark && pictured && (\n <Badge tone=\"blue\" className=\"pointer-events-none absolute top-2 left-2 shadow-sm\">\n {mark}\n </Badge>\n )}\n {dots.length > 0 && <CardDots dots={dots} Card={RecordCard} />}\n {favorite && <FavoriteButton favorite={favorite} recordKey={row.key} target={recordKey(model, row.record) as KeyValue} className={pictured ? undefined : 'right-1.5 top-1.5'} />}\n </div>\n )\n}\n","import { snapCardWidth, snapRowGap } from '../../primitives/snap-row-width'\n\n/** The gap after a card of a record row, in pixels. */\nconst rowCardGap = 12\n\n/** How many cards beyond each edge of the view are drawn, so a short scroll shows cards already there. */\nconst overscan = 3\n\n/**\n * The cards of a row of `total` to draw when it is scrolled `scrollLeft` into a view `width` wide: from `start` up to\n * `end` (not included), the ones in view and `overscan` more on each side, none past either end. A card is 256px wide,\n * or the view's width when that is narrower, as a `SnapRow` sizes it.\n */\nexport const rowWindow = (scrollLeft: number, width: number, total: number) => {\n const step = Math.max(1, Math.min(snapCardWidth, width)) + rowCardGap\n const first = Math.floor(Math.max(0, scrollLeft) / step)\n const last = Math.ceil((Math.max(0, scrollLeft) + width) / step)\n return { start: Math.max(0, first - overscan), end: Math.min(total, last + overscan) }\n}\n\n/** How many cards beyond the drawn ones keep a place of their own, which a swipe snaps to before it is drawn. */\nconst placesAround = 50\n\n/**\n * The cards of a row of `total` that have a place of their own while `start` up to `end` are drawn: those and\n * `placesAround` more on each side. The rest stand together in one spacer at each end (`rowSpan`), so a row of a hundred\n * thousand records draws a few hundred elements, not one for each.\n */\nexport const rowPlaces = (start: number, end: number, total: number) => ({ from: Math.max(0, start - placesAround), to: Math.min(total, end + placesAround) })\n\n/** The width of `count` cards of a row and the gaps between them, as a `SnapRow` sizes its cards, for a spacer that stands in for them. */\nexport const rowSpan = (count: number) => `calc(${count} * (min(${snapCardWidth}px, 100%) + ${snapRowGap}) - ${snapRowGap})`\n","import { messages } from '../../locale/messages'\n\nexport const text = messages('app/record-row')\n","import type { ListDisplayModel, ResourceModel, ViewModel } from '@protobase/schema'\nimport type { RowSource } from '../../data-grid'\nimport { usePagedRows } from '../../data-grid/use-paged-rows'\nimport { Skeleton } from '../../primitives/skeleton'\nimport { SnapRow } from '../../primitives/snap-row'\nimport { useSnapScroll } from '../../primitives/use-snap-scroll'\nimport { displayRow, type ListDisplayRow } from '../displays/list-displays'\nimport { RecordCard } from '../displays/record-card'\nimport { rowPlaces, rowSpan, rowWindow } from './row-window'\nimport { text } from './messages'\n\ntype CardsDisplayModel = Extract<ListDisplayModel, { kind: 'cards' }>\n\ntype RecordRowProps = {\n model: ResourceModel\n view: ViewModel | undefined\n display: CardsDisplayModel\n source: RowSource\n /** What the cards are, such as \"Homes\", for the list's label. */\n label: string\n /** Whether a record is new to the user, marked \"New\" in its card's top left corner. */\n isNew?: (row: ListDisplayRow) => boolean\n}\n\n// The cards far from the view, as wide as they are together: the row keeps its length, and a swipe does not stop in it\nconst Spacer = ({ count }: { count: number }) => <li aria-hidden style={{ width: rowSpan(count), minWidth: 0, scrollSnapAlign: 'none' }} />\n\n/**\n * Records as the cards of their list, in a `SnapRow`: only the cards near the view are drawn, and the records are loaded\n * through the list API in pages as the row scrolls to them. Each card links to its record. Every record near the view has\n * its place, an empty one until it is drawn, so the row snaps to a card a fast swipe reaches before it is drawn; the\n * records further away stand together in a spacer at each end, so a row of a large list draws a few hundred elements.\n */\nexport const RecordRow = ({ model, view, display, source, label, isNew }: RecordRowProps) => {\n const { total } = source\n const shown = (scrolled: { left: number; width: number }) => rowWindow(scrolled.left, scrolled.width, total)\n const scroll = useSnapScroll((scrolled) => {\n const { start, end } = shown(scrolled)\n return `${start}-${end}`\n })\n const { start, end } = shown(scroll.view)\n const places = rowPlaces(start, end, total)\n const getRow = usePagedRows({ total, rowAt: source.rowAt, loadRows: source.loadRows, cachedRows: source.cachedRows, revision: source.revision, latencyMs: 0 }, start, Math.max(start, end - 1))\n return (\n <SnapRow scroll={scroll} label={label}>\n {places.from > 0 && <Spacer count={places.from} />}\n {Array.from({ length: places.to - places.from }, (_, offset) => {\n const index = places.from + offset\n if (index < start || index >= end) return <li key={`place-${index}`} aria-hidden />\n const loaded = getRow(index)\n if (!loaded) {\n return (\n <li key={`skeleton-${index}`} aria-hidden>\n <Skeleton className=\"h-full min-h-24 rounded-lg\" />\n </li>\n )\n }\n const row = displayRow(model, loaded)\n return (\n <li key={row.key} aria-posinset={index + 1} aria-setsize={total} className=\"grid grid-cols-[minmax(0,1fr)]\">\n <RecordCard model={model} view={view} display={display} row={row} swipe={false} mark={isNew?.(row) ? text('new') : undefined} />\n </li>\n )\n })}\n {places.to < total && <Spacer count={total - places.to} />}\n </SnapRow>\n )\n}\n","import { createWhere, parseFilter, printFilter, type FilterExpr, type ResourceModel, type ViewModel } from '@protobase/schema'\nimport { loadedFields } from '../displays/list-displays'\nimport { defaultOrderBy } from '../list-order'\n\nconst where = createWhere()\n\n// The filter a row loads with: its own, narrowed to `scope`\nconst scoped = (filter: string, scope: FilterExpr | undefined) => {\n if (!scope) return filter\n const parsed = parseFilter(filter)\n if (!parsed.ok) throw new Error(`The filter cannot be read: ${parsed.errors.map((error) => error.message).join('; ')}`)\n return printFilter(parsed.ast ? where.and(parsed.ast, scope) : scope)\n}\n\n/** What a record row loads its records with: the fields its view's displays show, its filter narrowed to `scope`, and its order, the list's when `sort` is empty. */\nexport const recordRowRead = (model: ResourceModel, view: ViewModel | undefined, { filter, sort, scope }: { filter: string; sort: string; scope?: FilterExpr }) => ({\n columns: loadedFields(model, view, []),\n filter: scoped(filter, scope),\n orderBy: sort || defaultOrderBy(model, view),\n})\n","import { ArrowRight } from 'lucide-react'\nimport { useMemo, type ReactNode } from 'react'\nimport type { FilterExpr, ListDisplayModel, ResourceModel, ViewModel } from '@protobase/schema'\nimport { useIsXs } from '../../lib/use-media-query'\nimport { humanize } from '../../live/naming'\nimport { useLiveRows } from '../../live/use-live-rows'\nimport { Skeleton } from '../../primitives/skeleton'\nimport { displaysOf, type ListDisplayRow } from '../displays/list-displays'\nimport { viewAllAddress } from '../embedded-list/embedded-display'\nimport { ErrorBanner } from '../error-banner'\nimport { useAdminMeta } from '../meta-gate'\nimport { FilterChipList } from '../searches/filter-chip-list'\nimport { useFilterChips } from '../searches/use-filter-chips'\nimport { AppLink } from '../use-app-address'\nimport { RecordRow } from './record-row'\nimport { recordRowRead } from './record-row-read'\nimport { formatTag } from '../../locale/active-locale'\nimport { text } from './messages'\n\ntype CardsDisplayModel = Extract<ListDisplayModel, { kind: 'cards' }>\n\nexport type RecordRowBodyProps = {\n model: ResourceModel\n view: ViewModel | undefined\n /** The records shown: those matching `filter` (AIP-160) in `sort` order (AIP-132), the list's order when empty. */\n filter: string\n sort?: string\n /** The cards display of the view whose cards it draws; its first when omitted, the title alone without one. */\n display?: string\n /** How many records it shows at most; every one that matches when omitted. */\n limit?: number\n /** Whether it shows what the filter filters on, as chips. */\n chips?: boolean\n empty?: string\n /** A line about the records beside the count, such as that none are new. */\n note?: ReactNode\n isNew?: (row: ListDisplayRow) => boolean\n /** \"View all\"'s label, and the saved search whose results it opens, calling `onOpen` first. */\n viewAll?: { label?: string; savedSearch?: string; onOpen?: () => void }\n /** A filter every load adds to `filter`, which the chips and \"View all\" leave out: the records among the user's saved ones. */\n scope?: FilterExpr\n /** The resource whose list \"View all\" opens, the records' own by default: the saved records' list for a `scope`. */\n list?: string\n}\n\n/** The display a row draws its cards with: the one named, else the view's first cards display, else a card of the title. */\nconst rowDisplay = (view: ViewModel | undefined, name: string | undefined): CardsDisplayModel => {\n const cards = displaysOf(view).filter((display): display is CardsDisplayModel => display.kind === 'cards')\n return cards.find((display) => display.name === name) ?? cards[0] ?? { kind: 'cards', name: 'cards' }\n}\n\n// Three cards' worth, each as wide as a card (`rowCardWidth`)\nconst Loading = () => (\n <div className=\"flex gap-3 overflow-hidden\">\n {Array.from({ length: 3 }, (_, index) => (\n <Skeleton key={index} className=\"h-24 w-64 shrink-0\" />\n ))}\n </div>\n)\n\n/**\n * What a filter finds, in a card's body: its filters as chips, how many records match, the records in a row of their\n * list's cards that scrolls sideways (`RecordRow`), and \"View all\", which opens the list with the filter.\n */\nexport const RecordRowBody = ({ model, view, filter, sort = '', display: named, limit, chips: showChips = true, empty, note, isNew, viewAll, scope, list }: RecordRowBodyProps) => {\n const { resources, views } = useAdminMeta()\n const xs = useIsXs()\n const display = rowDisplay(view, named)\n const read = useMemo(() => recordRowRead(model, view, { filter, sort, scope }), [model, view, filter, sort, scope])\n const { orderBy } = read\n const rows = useLiveRows({ resources, views, model, ...read })\n const chips = useFilterChips(model, filter)\n const singular = (view?.names?.singular ?? humanize(model.name)).toLowerCase()\n const plural = view?.names?.plural ?? humanize(model.name)\n const total = rows.source?.total\n const source = useMemo(() => rows.source && { ...rows.source, total: Math.min(rows.source.total, limit ?? Infinity) }, [rows.source, limit])\n\n return (\n <div className=\"flex min-w-0 flex-col gap-3\">\n {(showChips && chips.length > 0) || total !== undefined || note ? (\n <div className=\"flex flex-wrap items-center justify-between gap-2\">\n {showChips && chips.length > 0 ? <FilterChipList chips={chips} /> : <span />}\n <p className=\"flex flex-wrap gap-x-3 text-muted-foreground\">\n {note && <span>{note}</span>}\n {total !== undefined && <span className=\"tabular-nums\">{`${total.toLocaleString(formatTag())} ${total === 1 ? singular : plural.toLowerCase()}`}</span>}\n </p>\n </div>\n ) : null}\n {rows.isLoading ? (\n <Loading />\n ) : rows.error ? (\n <ErrorBanner title={text('couldNotLoad')} error={rows.error} />\n ) : !source || source.total === 0 ? (\n <p className=\"text-muted-foreground\">{empty ?? text('noneMatch', { plural: plural.toLowerCase() })}</p>\n ) : (\n <RecordRow model={model} view={view} display={display} source={source} label={plural} isNew={isNew} />\n )}\n <AppLink\n to={viewAllAddress(model, view, xs, { filter, orderBy, display: display.name, savedSearch: viewAll?.savedSearch, resource: list })}\n onClick={viewAll?.onOpen}\n className=\"flex items-center gap-1 self-end font-medium text-primary-text hover:underline\"\n >\n {viewAll?.label ?? <>{text('viewAll')} <span className=\"sr-only\">{plural.toLowerCase()}</span></>}\n <ArrowRight className=\"size-3.5\" aria-hidden />\n </AppLink>\n </div>\n )\n}\n","import { useQuery } from '@tanstack/react-query'\nimport { useClient } from '../../data/api-provider'\nimport { keys } from '../../data/query-keys'\nimport { useAdminMeta } from '../meta-gate'\nimport { defaultOrderBy } from '../list-order'\nimport { savedPageSize } from '../saved/saved-records'\n\n/** One of the user's saved searches as the list API gives it: its fields, and its ETag to change it with. */\nexport type SavedSearchRow = Record<string, unknown> & { etag?: string }\n\n/** Where the user's saved searches of `resource` are cached; a list key, so a write to the resource refreshes it. */\nexport const savedSearchesKey = (resource: string) => keys.list(resource, '', '', savedPageSize, 'saved-searches')\n\n/**\n * The signed-in user's saved searches, in the order of their view's list: every one, page by page, as the API lists only\n * a user's own records of a resource with an owner. Loads only while `enabled`.\n */\nexport const useSavedSearches = (resource: string, enabled: boolean) => {\n const client = useClient()\n const { resources, views } = useAdminMeta()\n const model = resources[resource]\n return useQuery({\n queryKey: savedSearchesKey(resource),\n enabled: enabled && model !== undefined,\n queryFn: async (): Promise<SavedSearchRow[]> => {\n const rows: SavedSearchRow[] = []\n let pageToken: string | undefined\n do {\n const page = await client.list(resource, { pageSize: savedPageSize, orderBy: defaultOrderBy(model!, views[resource]), ...(pageToken && { pageToken }) })\n rows.push(...(page.items as SavedSearchRow[]))\n pageToken = page.nextPageToken || undefined\n } while (pageToken)\n return rows\n },\n })\n}\n","import { useMutation, useQuery } from '@tanstack/react-query'\nimport type { ResourceModel, SearchesOfModel, ViewModel } from '@protobase/schema'\nimport { useClient } from '../../data/api-provider'\nimport { humanize } from '../../live/naming'\nimport { countQuery, useRefreshResource } from '../pages/use-layout-data'\nimport type { RecordRowBodyProps } from '../record-row/record-row-body'\nimport { chipsText } from './filter-chip-list'\nimport { isUnseen, unseenFilter } from './saved-search'\nimport { useFilterChips } from './use-filter-chips'\nimport type { SavedSearchRow } from './use-saved-searches'\nimport { text } from './messages'\n\ntype SearchRowInput = {\n /** The saved searches' resource, whose view's `searchesOf` is `of`. */\n model: ResourceModel\n of: SearchesOfModel\n /** The resource searched and its view. */\n target: ResourceModel\n targetView: ViewModel | undefined\n row: SavedSearchRow\n /** The search's key, in the text form the record API takes. */\n recordKey: string\n}\n\n/**\n * One saved search as a row of what it finds: its name, if it has one, its filters as chips, its title (the name, or\n * the chips as words), and the `RecordRowBody` of its records: with `unseen` newest first, those new to the user marked\n * \"New\", saying so when none are, and \"View all results\", which opens the list from the search and counts as having\n * seen them.\n */\nexport const useSearchRow = ({ model, of, target, targetView, row, recordKey }: SearchRowInput) => {\n const client = useClient()\n const refresh = useRefreshResource()\n const filter = String(row[of.filter] ?? '')\n const chips = useFilterChips(target, filter)\n const stored = of.name === undefined ? undefined : row[of.name]\n const name = typeof stored === 'string' && stored !== '' ? stored : undefined\n const unseen = of.unseen\n const markSeen = useMutation({\n mutationFn: (seenAt: string) => client.update(model.name, recordKey, { [unseen!.seenAt]: seenAt }, row.etag ?? '*'),\n onSettled: () => refresh(model.name),\n })\n // How many of its records are new, to say when none are; every record is new to a search never seen\n const newCount = useQuery({ ...countQuery(client, target, unseen ? unseenFilter(filter, unseen.field, row[unseen.seenAt]) : ''), enabled: unseen !== undefined })\n const plural = (targetView?.names?.plural ?? humanize(target.name)).toLowerCase()\n const body: RecordRowBodyProps = {\n model: target,\n view: targetView,\n filter,\n sort: unseen ? `${unseen.field} desc` : undefined,\n limit: of.limit,\n chips: name !== undefined,\n empty: text('noneMatch', { plural }),\n note: unseen && newCount.data === 0 && text('noNew', { plural }),\n isNew: unseen && ((record) => isUnseen(record.record[unseen.field], row[unseen.seenAt])),\n viewAll: { label: text('viewAll'), savedSearch: recordKey, ...(unseen && { onOpen: () => markSeen.mutate(new Date().toISOString()) }) },\n }\n return { name, chips, title: name ?? chipsText(chips), body }\n}\n","import type { ReactNode } from 'react'\nimport { Button } from '../../primitives/button'\nimport { ErrorBanner } from '../error-banner'\nimport type { ListDisplay } from './display-context'\nimport { formatTag } from '../../locale/active-locale'\nimport { text } from './messages'\n\n/** A display's scrolling area: while loading, on an error or with no rows it says so instead of drawing them. */\nexport const DisplayState = ({ list, empty, loading, children }: { list: ListDisplay; empty: string; loading: ReactNode; children: ReactNode }) => (\n <div className=\"min-h-0 flex-1 overflow-y-auto\">\n {list.loading ? loading : list.error ? <ErrorBanner title={text('couldNotLoadRows')} error={list.error} /> : list.rows.length === 0 ? <p className=\"py-8 text-center text-muted-foreground\">{empty}</p> : children}\n </div>\n)\n\n/** How many of the matching records are shown, and a button for the next page while there is one. */\nexport const DisplayFooter = ({ list }: { list: ListDisplay }) => (\n <div className=\"flex items-center justify-between gap-3 py-3 text-xs text-muted-foreground\">\n <span>\n {list.rows.length.toLocaleString(formatTag())} of {list.total.toLocaleString(formatTag())}\n </span>\n {list.more && (\n <Button size=\"sm\" onClick={list.loadMore}>\n {text('showMore')}\n </Button>\n )}\n </div>\n)\n","import type { ListDisplayModel, ResourceModel, ViewModel } from '@protobase/schema'\nimport { cn } from '../../lib/cn'\nimport { humanize } from '../../live/naming'\nimport { Skeleton } from '../../primitives/skeleton'\nimport type { ListDisplay } from './display-context'\nimport { DisplayFooter, DisplayState } from './display-frame'\nimport { RecordCard } from './record-card'\nimport { text } from './messages'\n\ntype CardsProps = {\n model: ResourceModel\n view: ViewModel | undefined\n display: Extract<ListDisplayModel, { kind: 'cards' }>\n list: ListDisplay\n /** The cards in one row that scrolls sideways, card by card, instead of a grid, as an embedded list shows them on a phone. */\n row?: boolean\n /** How many are shown and a button for more, under the cards; an embedded list, which links to the list instead, leaves it out. */\n footer?: boolean\n}\n\nconst grid = 'grid grid-cols-[repeat(auto-fill,minmax(15rem,1fr))] gap-3'\n// Positioned, so the cards' screen-reader labels scroll inside it instead of widening the page\nconst scroller = 'relative flex snap-x snap-mandatory gap-3 overflow-x-auto pb-1'\n\n/** A card per record (see `RecordCard`), in a grid or a row, with how many match and a button for more below. */\nexport const CardsDisplay = ({ model, view, display, list, row = false, footer = true }: CardsProps) => {\n const plural = (view?.names?.plural ?? humanize(model.name)).toLowerCase()\n return (\n <DisplayState list={list} empty={text('noneMatch', { plural })} loading={<div className={grid}>{Array.from({ length: 6 }, (_, index) => <Skeleton key={index} className=\"h-24\" />)}</div>}>\n <ul className={row ? scroller : grid} aria-label={view?.names?.plural ?? humanize(model.name)}>\n {list.rows.map((record) => (\n <li key={record.key} className={cn(row && 'w-64 shrink-0 snap-start')}>\n <RecordCard model={model} view={view} display={display} row={record} swipe={!row} />\n </li>\n ))}\n </ul>\n {footer && <DisplayFooter list={list} />}\n </DisplayState>\n )\n}\n","import type { ListDisplayModel } from '@protobase/schema'\nimport { unmarkFieldRefs } from '@protobase/schema/internal'\nimport { CustomBoundary } from '../pages/custom-boundary'\nimport { Problem } from '../pages/problem'\nimport { useProjectUi } from '../pages/project-ui'\nimport { ListDisplayProvider, type ListDisplay } from './display-context'\nimport { text } from './messages'\n\n/**\n * A display the project draws: the component registered under its name gets the display's props, field references\n * as the names they reference, and reads the list page's rows with `useListDisplay()`.\n */\nexport const CustomDisplay = ({ display, list }: { display: Extract<ListDisplayModel, { kind: 'custom' }>; list: ListDisplay }) => {\n const { components } = useProjectUi()\n const Component = components?.[display.component]\n if (!Component) return <Problem>{text.rich('noComponent', { component: display.component })}</Problem>\n return (\n <ListDisplayProvider value={list}>\n {/* As tall as what it draws, scrolling with the page; a wide one, such as a board, scrolls sideways; positioned, so what it places absolutely scrolls inside it instead of widening the page */}\n <div className=\"relative min-w-0 flex-1 overflow-x-auto\">\n <CustomBoundary name={display.component}>\n <Component {...unmarkFieldRefs(display.props ?? {})} />\n </CustomBoundary>\n </div>\n </ListDisplayProvider>\n )\n}\n","import { createWhere, printFilter, type FilterExpr } from '@protobase/schema'\nimport type { MapBounds, MapBucket } from '@protobase/client'\nimport type { Position } from './record-position'\n\nconst where = createWhere()\n\n/** What a map shows: the bounds of its view, in decimal degrees, and its zoom. */\nexport type MapArea = { bounds: MapBounds; zoom: number }\n\n/** The whole world from as far out as a map goes: what a map asks for before it knows where its records are. */\nexport const worldArea: MapArea = { bounds: { south: -90, west: -180, north: 90, east: 180 }, zoom: 0 }\n\n// MapLibre's zoom levels, from the whole world at 0 to a building at 22.\nconst maxZoom = 22\n\n// Six decimals of a degree are about ten centimetres; rounding outwards keeps every record in view inside the box.\nconst down = (degrees: number) => Math.floor(degrees * 1e6) / 1e6\nconst up = (degrees: number) => Math.ceil(degrees * 1e6) / 1e6\n\n// MapLibre counts on past the antimeridian when the map shows it, such as 190 for -170.\nconst wrapped = (longitude: number) => ((((longitude + 180) % 360) + 360) % 360) - 180\n\n/**\n * The AIP-160 filter for the records inside `bounds`: between its latitudes, and between its longitudes on the globe.\n * A view across the antimeridian takes the longitudes on both sides of it, and one around the whole world takes them all.\n */\nexport const boundsFilter = (fields: { latitude: string; longitude: string }, bounds: MapBounds): FilterExpr => {\n const latitude = [where.gte(fields.latitude, down(Math.max(bounds.south, -90))), where.lte(fields.latitude, up(Math.min(bounds.north, 90)))]\n if (bounds.east - bounds.west >= 360) return where.and(...latitude)\n const west = where.gte(fields.longitude, down(wrapped(bounds.west)))\n const east = where.lte(fields.longitude, up(wrapped(bounds.east)))\n return wrapped(bounds.west) <= wrapped(bounds.east) ? where.and(...latitude, west, east) : where.and(...latitude, where.or(west, east))\n}\n\n/** The list's filter, its search included, narrowed to the records inside the map's bounds. */\nexport const areaFilter = (listFilter: string, fields: { latitude: string; longitude: string }, bounds: MapBounds) => {\n const inside = printFilter(boundsFilter(fields, bounds))\n return listFilter.trim() === '' ? inside : `(${listFilter}) AND ${inside}`\n}\n\n/** The zoom the records are asked for at: the whole zoom level the map is at. */\nexport const requestZoom = (zoom: number) => Math.min(Math.max(Math.floor(zoom), 0), maxZoom)\n\n/** The bounds around the records and the buckets, or none without either. */\nexport const boundsAround = (points: Position[], buckets: MapBucket[]): MapBounds | undefined => {\n const corners = [\n ...points.map((point) => ({ south: point.latitude, west: point.longitude, north: point.latitude, east: point.longitude })),\n ...buckets.map((bucket) => bucket.bounds),\n ]\n if (corners.length === 0) return undefined\n return {\n south: Math.min(...corners.map((corner) => corner.south)),\n west: Math.min(...corners.map((corner) => corner.west)),\n north: Math.max(...corners.map((corner) => corner.north)),\n east: Math.max(...corners.map((corner) => corner.east)),\n }\n}\n","/** A point in decimal degrees (WGS84), as a map is centred on it. */\nexport type Position = { latitude: number; longitude: number }\n\n/** A number field's value: it comes as a number, or as text for a decimal or bigint; anything else, or an empty value, is none. */\nexport const numeric = (value: unknown) => {\n if (typeof value === 'number') return value\n if (typeof value !== 'string' || value.trim() === '') return undefined\n return Number(value)\n}\n\n/** The record's position from its two fields, when both hold degrees on the globe; none otherwise, so no map is drawn. */\nexport const recordPosition = (record: Record<string, unknown>, fields: { latitude: string; longitude: string }): Position | undefined => {\n const latitude = numeric(record[fields.latitude])\n const longitude = numeric(record[fields.longitude])\n if (latitude === undefined || longitude === undefined) return undefined\n if (!(Math.abs(latitude) <= 90 && Math.abs(longitude) <= 180)) return undefined\n return { latitude, longitude }\n}\n","import { numeric, type Position } from './record-position'\n\n/** The fields of a map display that say how exact a record's position is, and the circle it draws without one of its own. */\nexport type ApproximateFields = { approximate?: string; exact?: string; radius?: string; defaultRadius?: number; area?: string }\n\ntype Ring = [number, number][]\n\n/** What a map draws around an approximate position: GeoJSON polygons, or lines such as a street, in longitude and latitude. */\nexport type AreaGeometry =\n | { type: 'Polygon'; coordinates: Ring[] }\n | { type: 'MultiPolygon'; coordinates: Ring[][] }\n | { type: 'LineString'; coordinates: Ring }\n | { type: 'MultiLineString'; coordinates: Ring[] }\n\n// The mean radius of the Earth, in metres, as GeoJSON's WGS84 positions are measured on it.\nconst earthRadius = 6_371_008.8\n// Corners of the polygon a circle is drawn as: round at any size it is drawn at.\nconst circleCorners = 64\n\n/** Whether the record's position is approximate, as its field states; without one, or a value that says neither, it is not. */\nexport const isApproximate = (record: Record<string, unknown>, fields: ApproximateFields) => {\n if (fields.approximate !== undefined) return record[fields.approximate] === true\n if (fields.exact !== undefined) return record[fields.exact] === false\n return false\n}\n\n/** The polygon of `metres` around `center`, its corners as far from it along the globe. */\nexport const circleArea = (center: Position, metres: number): AreaGeometry => {\n const distance = metres / earthRadius\n const latitude = (center.latitude * Math.PI) / 180\n const longitude = (center.longitude * Math.PI) / 180\n const ring: Ring = Array.from({ length: circleCorners + 1 }, (_, index) => {\n const bearing = ((index % circleCorners) / circleCorners) * 2 * Math.PI\n const to = Math.asin(Math.sin(latitude) * Math.cos(distance) + Math.cos(latitude) * Math.sin(distance) * Math.cos(bearing))\n const across = longitude + Math.atan2(Math.sin(bearing) * Math.sin(distance) * Math.cos(latitude), Math.cos(distance) - Math.sin(latitude) * Math.sin(to))\n return [(across * 180) / Math.PI, (to * 180) / Math.PI]\n })\n return { type: 'Polygon', coordinates: [ring] }\n}\n\nconst isPosition = (value: unknown): value is [number, number] =>\n Array.isArray(value) && value.length >= 2 && typeof value[0] === 'number' && typeof value[1] === 'number' && Math.abs(value[0]) <= 180 && Math.abs(value[1]) <= 90\n\nconst isLine = (value: unknown, least: number): value is Ring => Array.isArray(value) && value.length >= least && value.every(isPosition)\nconst isPolygon = (value: unknown): value is Ring[] => Array.isArray(value) && value.length > 0 && value.every((ring) => isLine(ring, 4))\nconst isLines = (value: unknown): value is Ring[] => Array.isArray(value) && value.length > 0 && value.every((line) => isLine(line, 2))\n\n// GeoJSON comes as data from a json field, or as its text from a text field.\nconst parsed = (value: unknown): unknown => {\n if (typeof value !== 'string') return value\n try {\n return JSON.parse(value)\n } catch (error) {\n if (error instanceof SyntaxError) return undefined\n throw error\n }\n}\n\n/** The GeoJSON polygon or line a value holds, as a geometry or a feature of one; none for anything else, such as a point or text that is no GeoJSON. */\nexport const areaGeometry = (value: unknown): AreaGeometry | undefined => {\n const data = parsed(value)\n if (typeof data !== 'object' || data === null) return undefined\n const geometry = (data as { type?: unknown }).type === 'Feature' ? (data as { geometry?: unknown }).geometry : data\n if (typeof geometry !== 'object' || geometry === null) return undefined\n const { type, coordinates } = geometry as { type?: unknown; coordinates?: unknown }\n if (type === 'Polygon' && isPolygon(coordinates)) return { type, coordinates }\n if (type === 'MultiPolygon' && Array.isArray(coordinates) && coordinates.length > 0 && coordinates.every(isPolygon)) return { type, coordinates }\n if (type === 'LineString' && isLine(coordinates, 2)) return { type, coordinates }\n if (type === 'MultiLineString' && isLines(coordinates)) return { type, coordinates }\n return undefined\n}\n\n/**\n * What the map draws around the record's approximate position: the area its field holds, else a circle of the radius\n * its field holds, else one of the display's default radius. An exact position, or one whose record states none of\n * them on a display without a default, has none.\n */\nexport const positionArea = (record: Record<string, unknown>, fields: ApproximateFields, position: Position): AreaGeometry | undefined => {\n if (!isApproximate(record, fields)) return undefined\n const area = fields.area === undefined ? undefined : areaGeometry(record[fields.area])\n if (area) return area\n const radius = fields.radius === undefined ? undefined : numeric(record[fields.radius])\n if (radius !== undefined && Number.isFinite(radius) && radius > 0) return circleArea(position, radius)\n return fields.defaultRadius === undefined ? undefined : circleArea(position, fields.defaultRadius)\n}\n","import { isApproximate, positionArea, type ApproximateFields, type AreaGeometry } from '../map/approximate-position'\nimport { recordPosition, type Position } from '../map/record-position'\nimport type { ListDisplayRow } from './list-displays'\n\n/** A record on a map display: its key, its position, whether that is approximate, and the area drawn around it if so. */\nexport type MapPoint = Position & { key: string; approximate?: true; area?: AreaGeometry }\n\n/** A point as the map draws it, in pixels from the map's corner. */\nexport type ScreenPoint = { key: string; x: number; y: number }\n\n/** The records a map marker stands for, by their keys, at the position of the first. */\nexport type MapGroup = { keys: string[]; at: string }\n\n/** The rows with a position, in their order, approximate ones marked with their area; a row without one is not on the map. */\nexport const mapPoints = (rows: ListDisplayRow[], fields: { latitude: string; longitude: string } & ApproximateFields): MapPoint[] =>\n rows.flatMap((row) => {\n const position = recordPosition(row.record, fields)\n if (!position) return []\n if (!isApproximate(row.record, fields)) return [{ key: row.key, ...position }]\n const area = positionArea(row.record, fields, position)\n return [{ key: row.key, ...position, approximate: true as const, ...(area && { area }) }]\n })\n\n/**\n * The markers for the points as the map draws them: in order, each point joins the first marker within `radius` pixels\n * of it, else starts its own. A marker is at its first point, so markers do not move as others join them.\n */\nexport const groupPoints = (points: ScreenPoint[], radius: number): MapGroup[] => {\n const groups: { at: ScreenPoint; keys: string[] }[] = []\n for (const point of points) {\n const near = groups.find((group) => Math.hypot(group.at.x - point.x, group.at.y - point.y) <= radius)\n if (near) near.keys.push(point.key)\n else groups.push({ at: point, keys: [point.key] })\n }\n return groups.map((group) => ({ keys: group.keys, at: group.at.key }))\n}\n\n/** A choice of records on the map, and which of them shows its card; none once the list no longer has any of them. */\nexport type MapSelection = { keys: string[]; index: number }\n\n/** The selection kept to the records the list still has, its card the same record when it is still there. */\nexport const keptSelection = (selection: MapSelection | undefined, rows: ListDisplayRow[]): MapSelection | undefined => {\n if (!selection) return undefined\n const present = new Set(rows.map((row) => row.key))\n const keys = selection.keys.filter((key) => present.has(key))\n if (keys.length === 0) return undefined\n const index = keys.indexOf(selection.keys[selection.index]!)\n return { keys, index: Math.max(index, 0) }\n}\n\n/** The selection moved by `step` records, round from the last to the first. */\nexport const stepSelection = (selection: MapSelection, step: number): MapSelection => ({\n keys: selection.keys,\n index: (((selection.index + step) % selection.keys.length) + selection.keys.length) % selection.keys.length,\n})\n","import { keepPreviousData, useQuery } from '@tanstack/react-query'\nimport type { ListDisplayModel, ResourceModel, ViewModel } from '@protobase/schema'\nimport { useClient } from '../../data/api-provider'\nimport { keys } from '../../data/query-keys'\nimport { listLabels, withLabels } from '../../live/relation-labels'\nimport { listPhotos, withPhotos } from '../../live/row-photos'\nimport { areaFilter, requestZoom, type MapArea } from '../map/map-area'\nimport { useAdminMeta } from '../meta-gate'\nimport { displayRow } from './list-displays'\n\nexport type MapRecordsParams = {\n model: ResourceModel\n /** The view whose list shows the map; its displays say which photos the records carry. */\n view: ViewModel | undefined\n display: Extract<ListDisplayModel, { kind: 'map' }>\n /** The fields the records' relations are labelled for, those the card shows among them. */\n fields: string[]\n /** The list's filter, its search included, and its order, as the list API takes them. */\n filter: string\n orderBy: string\n /** What the map shows; nothing is asked for without it. */\n area: MapArea | undefined\n}\n\n/**\n * The records in the map's area through the list API's `:map`, labelled for the card and with its photos, or buckets of them when it holds\n * many. A new area or filter keeps the previous answer until its own arrives, and an answer for an area the map has\n * left is never shown.\n */\nexport const useMapRecords = ({ model, view, display, fields, filter, orderBy, area }: MapRecordsParams) => {\n const client = useClient()\n const { resources, views } = useAdminMeta()\n const position = { latitude: display.latitude, longitude: display.longitude }\n const inside = area ? areaFilter(filter, position, area.bounds) : ''\n const zoom = area ? requestZoom(area.zoom) : 0\n return useQuery({\n queryKey: keys.map(model.name, `${position.latitude},${position.longitude}`, zoom, inside, orderBy),\n enabled: area !== undefined,\n placeholderData: keepPreviousData,\n queryFn: async () => {\n const result = await client.map(model.name, { ...position, zoom, filter: inside, orderBy, labels: listLabels(resources, views, model, fields), photos: listPhotos(view) })\n const labelled = withLabels(resources, model, fields, withPhotos(model, result.items, result.photos), result.labels)\n return { rows: labelled.map((record) => displayRow(model, record)), buckets: result.buckets, total: result.totalSize }\n },\n })\n}\n","import { lazy, Suspense, useLayoutEffect, useRef, useState } from 'react'\nimport { ChevronLeft, ChevronRight, CircleDashed, X } from 'lucide-react'\nimport type { ListDisplayModel, MapView, ResourceModel, ViewModel } from '@protobase/schema'\nimport { useDebounced } from '../../lib/use-debounced'\nimport { humanize } from '../../live/naming'\nimport { cn } from '../../lib/cn'\nimport { Button } from '../../primitives/button'\nimport { ErrorBanner } from '../error-banner'\nimport { boundsAround, worldArea, type MapArea } from '../map/map-area'\nimport { useAdminMeta } from '../meta-gate'\nimport { Problem } from '../pages/problem'\nimport { mapCards } from './list-displays'\nimport { keptSelection, mapPoints, stepSelection, type MapSelection } from './map-groups'\nimport { RecordCard } from './record-card'\nimport { useMapRecords } from './use-map-records'\nimport { formatTag } from '../../locale/active-locale'\nimport { text } from './messages'\n\n// MapLibre loads with the first map drawn, so a list that never shows one never loads it.\nconst RecordsMap = lazy(() => import('../map/records-map').then((module) => ({ default: module.RecordsMap })))\n\n// How long the map stays put before the records where it rests are asked for, so a run of zooms asks once.\nconst settleMs = 250\n\ntype MapProps = {\n model: ResourceModel\n view: ViewModel | undefined\n display: Extract<ListDisplayModel, { kind: 'map' }>\n /** The list's filter, its search included, and its order, as the list API takes them. */\n filter: string\n orderBy: string\n /** The fields the records' relations are labelled for, those the card shows among them. */\n fields: string[]\n /** Where the map looks when it opens; without it, it fits every matching record. */\n at?: MapView\n /** Where the map came to rest, for the list's address. */\n onMove?: (view: MapView) => void\n /** How many records are in view, under the map at desktop width; an embedded list, which links to the list instead, leaves it out. */\n footer?: boolean\n /** Below desktop width, fills the page's sides and bottom edge to edge, with no frame. */\n flush?: boolean\n}\n\nconst arrow = 'flex size-8 items-center justify-center rounded-full border border-border bg-background hover:bg-surface focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/30'\n\n/**\n * The matching records in the map's view, drawn with the map style `/meta` names: the records themselves when few are\n * in view or the map is close, else a count for each part of it, which zooms in when chosen. The map asks again as it\n * pans and zooms. Without a view of its own it first fits every matching record. Choosing a marker shows the card of\n * its record at the map's bottom, with arrows through the records the marker stands for; closing it or choosing the map\n * elsewhere clears it. A marker and a card whose record's position is approximate say so.\n */\nexport const MapDisplay = ({ model, view, display, filter, orderBy, fields, at, onMove, footer = true, flush = false }: MapProps) => {\n const maps = useAdminMeta().maps\n const style = maps?.style\n const [chosen, setChosen] = useState<MapSelection>()\n const [area, setArea] = useState<MapArea>()\n const settled = useDebounced(area, settleMs)\n // Without a view, the whole world is asked for, and the map fits what it holds\n const [fitting, setFitting] = useState(at === undefined)\n const records = useMapRecords({ model, view, display, fields, filter, orderBy, area: fitting ? worldArea : settled })\n const loaded = records.isPlaceholderData ? undefined : records.data\n const rows = records.data?.rows ?? []\n const buckets = records.data?.buckets ?? []\n const points = mapPoints(rows, display)\n const fit = fitting && loaded ? boundsAround(mapPoints(loaded.rows, display), loaded.buckets) : undefined\n\n const cards = mapCards(view, display)\n const plural = (view?.names?.plural ?? humanize(model.name)).toLowerCase()\n const singular = (view?.names?.singular ?? humanize(model.name)).toLowerCase()\n const selection = keptSelection(chosen, rows)\n const row = selection && rows.find((candidate) => candidate.key === selection.keys[selection.index])\n const approximate = new Set(points.filter((point) => point.approximate).map((point) => point.key))\n const markerLabel = (keys: string[]) => {\n const near = keys.filter((key) => approximate.has(key)).length\n if (keys.length === 1) return near === 1 ? text('showOneApproximate', { singular }) : text('showOne', { singular })\n if (near === 0) return text('showMany', { count: keys.length, plural })\n return near === keys.length ? text('showManyApproximate', { count: keys.length, plural }) : text('showManySomeApproximate', { count: keys.length, plural, near })\n }\n const bucketLabel = (count: number) => text('zoomIn', { count: count.toLocaleString(formatTag()), noun: count === 1 ? singular : plural })\n // How much of the map's bottom the card and its arrows cover, so the map keeps the chosen marker above them\n const overlay = useRef<HTMLDivElement>(null)\n const [covered, setCovered] = useState(0)\n useLayoutEffect(() => setCovered(overlay.current?.offsetHeight ?? 0), [row?.key])\n\n if (!style) return <Problem>{text('needsStyle')}</Problem>\n const empty = loaded?.total === 0\n return (\n <div className={cn('flex h-full min-h-[36rem] flex-1 flex-col sm:min-h-[28rem]', flush && 'max-md:-mx-5 max-md:-mb-4 max-md:min-h-0')}>\n <div className={cn('relative min-h-0 flex-1 overflow-hidden rounded-lg border border-border bg-muted', flush && 'max-md:rounded-none max-md:border-0')}>\n <Suspense fallback={null}>\n <RecordsMap\n style={style}\n layers={maps?.layers}\n initial={at}\n points={points}\n buckets={buckets}\n fit={fit}\n onFitted={() => setFitting(false)}\n onMove={(next, center) => {\n setArea(next)\n onMove?.(center)\n }}\n selected={selection?.keys}\n covered={selection ? covered : 0}\n onSelect={(keys) => setChosen({ keys, index: 0 })}\n onClear={() => setChosen(undefined)}\n markerLabel={markerLabel}\n bucketLabel={bucketLabel}\n />\n </Suspense>\n {records.error && (\n <div className=\"absolute inset-x-3 top-3 z-10\">\n <ErrorBanner title={text('couldNotLoadRows')} error={records.error} />\n </div>\n )}\n {empty && (\n <div className=\"pointer-events-none absolute inset-x-3 top-3 z-10 flex justify-center\">\n <p className=\"pointer-events-auto flex items-center gap-3 rounded-full border border-border bg-background px-4 py-1.5 text-muted-foreground shadow\" role=\"status\">\n {fitting ? text('noneMatch', { plural }) : text('noneHere', { plural })}\n {!fitting && (\n <Button size=\"sm\" onClick={() => setFitting(true)}>\n {text('showAll')}\n </Button>\n )}\n </p>\n </div>\n )}\n {selection && row && (\n <div ref={overlay} className=\"pointer-events-none absolute inset-x-3 bottom-3 z-10 flex justify-center\">\n <div className=\"pointer-events-auto flex w-full max-w-[16rem] flex-col gap-2 sm:max-w-xs\" role=\"group\" aria-label={text('chosen', { singular })}>\n <div className=\"flex items-center justify-end gap-1.5\">\n {approximate.has(row.key) && (\n <span className=\"mr-auto flex items-center gap-1 rounded-full border border-border bg-background px-2 py-1 text-xs\">\n <CircleDashed className=\"size-3.5\" aria-hidden />\n {text('approximatePosition')}\n </span>\n )}\n {selection.keys.length > 1 && (\n <>\n <button type=\"button\" aria-label={text('previous')} className={arrow} onClick={() => setChosen(stepSelection(selection, -1))}>\n <ChevronLeft className=\"size-4\" aria-hidden />\n </button>\n <span className=\"rounded-full border border-border bg-background px-2 py-1 text-xs tabular-nums\" aria-live=\"polite\">\n {selection.index + 1} / {selection.keys.length}\n </span>\n <button type=\"button\" aria-label={text('next')} className={arrow} onClick={() => setChosen(stepSelection(selection, 1))}>\n <ChevronRight className=\"size-4\" aria-hidden />\n </button>\n </>\n )}\n <button type=\"button\" aria-label={text('close')} className={arrow} onClick={() => setChosen(undefined)}>\n <X className=\"size-4\" aria-hidden />\n </button>\n </div>\n <div className=\"shadow-lg\">\n <RecordCard model={model} view={view} display={cards} row={row} />\n </div>\n </div>\n </div>\n )}\n </div>\n {footer && <p className=\"hidden py-3 text-xs text-muted-foreground md:block\">{inView(records.data, plural)}</p>}\n </div>\n )\n}\n\n/** How many of the matching records are in view, and how many the map shows when it cannot show them all. */\nconst inView = (data: { rows: unknown[]; buckets: unknown[]; total: number } | undefined, plural: string) => {\n if (!data) return ' '\n const total = data.total.toLocaleString(formatTag())\n if (data.buckets.length === 0 && data.rows.length < data.total) return `${data.rows.length.toLocaleString(formatTag())} of ${total} ${plural} in view`\n return `${total} ${plural} in view`\n}\n","import { Skeleton } from '../../primitives/skeleton'\nimport { lazyComponent } from '../lazy-component'\n\n// The list displays that draw with libraries of their own, such as the board's dragging, load with the first one shown.\n\nconst area = () => <Skeleton className=\"min-h-60 flex-1 rounded-lg\" />\n\nexport const BoardDisplay = lazyComponent(() => import('./board-display').then((module) => module.BoardDisplay), area)\nexport const CalendarDisplay = lazyComponent(() => import('./calendar-display').then((module) => module.CalendarDisplay), area)\nexport const TimelineDisplay = lazyComponent(() => import('./timeline-display').then((module) => module.TimelineDisplay), area)\n","import { Calendar, ChartGantt, Columns3, LayoutGrid, List, Map as MapIcon, SquareKanban, Table2, type LucideIcon } from 'lucide-react'\nimport type { ListDisplayModel, ResourceModel, ViewModel } from '@protobase/schema'\nimport { cn } from '../../lib/cn'\nimport { humanize } from '../../live/naming'\nimport { MenuSelect } from '../../primitives/menu-select'\nimport { Segmented } from '../../primitives/segmented'\nimport { parseSort } from '../list-order'\nimport { displayChoices, sortFields, type DisplayChoice } from './list-displays'\nimport { text } from './messages'\n\n/** The icons a display's `icon` may name; another name shows the label alone. */\nconst icons: Record<string, LucideIcon> = { table: Table2, cards: LayoutGrid, kanban: SquareKanban, board: Columns3, list: List, calendar: Calendar, timeline: ChartGantt, map: MapIcon }\n\n/**\n * The list page's switch between the table and the view's displays, or `choices`, as buttons or, on a phone, as a menu;\n * nothing for a list with only its table.\n */\nexport const DisplaySwitch = ({ view, value, onChange, menu = false, choices = displayChoices(view) }: { view: ViewModel | undefined; value: string; onChange: (display: string) => void; menu?: boolean; choices?: DisplayChoice[] }) => {\n if (choices.length < 2) return null\n const options = choices.map((choice) => ({ value: choice.name, label: choice.label, icon: choice.icon === undefined ? undefined : icons[choice.icon] }))\n if (menu) return <MenuSelect label={text('display')} value={value} onChange={onChange} options={options} />\n return <Segmented label={text('display')} size=\"md\" value={value} onChange={onChange} options={options} />\n}\n\nconst directions = [\n ['asc', 'ascending'],\n ['desc', 'descending'],\n] as const\n\n/** The order of a display without column headers, over the sortable fields it shows and the order the list has now. */\nexport const SortMenu = ({ model, view, display, orderBy, onChange, className }: { model: ResourceModel; view: ViewModel | undefined; display: ListDisplayModel; orderBy: string; onChange: (orderBy: string) => void; className?: string }) => {\n const current = parseSort(orderBy)\n const fields = sortFields(model, view, display)\n const names = fields.includes(current.columnId) ? fields : [current.columnId, ...fields]\n const label = (name: string) => view?.fields[name]?.label ?? humanize(name)\n return (\n <select\n aria-label={text('sort')}\n value={`${current.columnId} ${current.direction}`}\n onChange={(event) => onChange(event.target.value)}\n className={cn('h-8 rounded-md border border-border-strong bg-background px-2.5 shadow-sm focus:border-primary focus:outline-none focus:ring-2 focus:ring-primary/20', className)}\n >\n {names.flatMap((name) =>\n directions.map(([direction, word]) => (\n <option key={`${name} ${direction}`} value={`${name} ${direction}`}>\n {label(name)}, {text(word)}\n </option>\n )),\n )}\n </select>\n )\n}\n","import type { ResourceModel, RowButtonModel, ViewModel } from '@protobase/schema'\nimport type { ColumnSpec, GridRow } from '../../data-grid'\nimport { cellPadding } from '../../data-grid/content-widths'\nimport { displayRow } from '../displays/list-displays'\nimport { RowButtonLink } from './row-button-link'\nimport { rowButtonFor } from './row-button-for'\n\n// Widths are estimated from character counts, as the grid's other columns are: a small button's medium-weight label\n// per character, its padding and border, and the outside-link mark with its gap\nconst labelCharWidth = 8\nconst buttonFrame = 22\nconst outsideMark = 20\n\n/** The widest a row's button grows before its label shortens, on a wide screen and on a narrow one. */\nexport const rowButtonMaxWidth = { wide: 288, narrow: 192 }\n\nconst recordOf = (model: ResourceModel, row: GridRow) => displayRow(model, row).record\n\ntype Models = Record<string, ResourceModel>\n\nconst rowButton = (model: ResourceModel, view: ViewModel | undefined, button: RowButtonModel, models: Models) => (row: GridRow) => (\n <RowButtonLink button={button} model={model} view={view} record={recordOf(model, row)} models={models} />\n)\n\n/** The pixels a row's button cell needs to show its label whole; none for a row without a button. */\nconst rowButtonWidth = (model: ResourceModel, view: ViewModel | undefined, button: RowButtonModel, models: Models) => (row: GridRow) => {\n const shown = rowButtonFor(button, model, view, recordOf(model, row), models)\n if (!shown) return 0\n return Math.ceil(shown.label.length * labelCharWidth) + buttonFrame + ('href' in shown ? outsideMark : 0) + cellPadding\n}\n\n/**\n * A table's last column, with the row's button in each row, as wide as its longest label up to `maxWidth`, past which\n * a label shortens and shows whole on hover; its header is empty, as the buttons say what they do. `models` are the\n * caller's resources, which a filter a row holds whole is checked against.\n */\nexport const rowButtonColumn = (model: ResourceModel, view: ViewModel | undefined, button: RowButtonModel, models: Models, maxWidth: number): ColumnSpec => ({\n id: '_row_button',\n header: '',\n kind: 'text',\n // Until rows load: room for a short label with the outside-link mark, such as \"Error report\"\n width: 152,\n minWidth: 96,\n maxWidth,\n sortable: false,\n render: rowButton(model, view, button, models),\n fit: rowButtonWidth(model, view, button, models),\n})\n\n/**\n * A table's columns with the row's button: its last column, or on a narrow screen, where the table scrolls sideways\n * and a last column starts off-screen, under the first cell's text when there is one.\n */\nexport const withRowButton = (specs: ColumnSpec[], model: ResourceModel, view: ViewModel | undefined, button: RowButtonModel, models: Models, narrow: boolean): ColumnSpec[] => {\n if (!narrow) return [...specs, rowButtonColumn(model, view, button, models, rowButtonMaxWidth.wide)]\n const [first, ...rest] = specs\n // Without a first cell to sit under, the button keeps its own column\n if (!first) return [rowButtonColumn(model, view, button, models, rowButtonMaxWidth.narrow)]\n return [{ ...first, below: rowButton(model, view, button, models) }, ...rest]\n}\n","import type { RelatedModel, ResourceModel } from '@protobase/schema'\n\n// A relation whose records can be opened: one to a resource the caller can see, with a single-column key\nconst opensTo = (model: ResourceModel, name: string, resources: Record<string, ResourceModel>) => {\n const field = Object.hasOwn(model.fields, name) ? model.fields[name]! : undefined\n return field?.type === 'relation' && field.relation !== undefined && resources[field.relation.resource]?.primaryKey.length === 1\n}\n\n/**\n * The relation field whose record a related section's row opens: `item.open`, else the one relation in the listed\n * resource's primary key besides `item.field`, when there is exactly one; none when the rows are records in their own right.\n */\nexport const relatedOpens = (item: RelatedModel, model: ResourceModel, resources: Record<string, ResourceModel>): string | undefined => {\n if (item.open !== undefined) return item.open !== item.field && opensTo(model, item.open, resources) ? item.open : undefined\n const candidates = model.primaryKey.filter((name) => name !== item.field && name !== model.tenant && opensTo(model, name, resources))\n return candidates.length === 1 ? candidates[0] : undefined\n}\n\n/** The key of the record a row's relation `name` points at; a list row holds a shown relation as `{ id, name }`. Undefined when empty. */\nexport const relationTarget = (row: Record<string, unknown>, name: string): string | number | undefined => {\n const value = row[name]\n const id = typeof value === 'object' && value !== null && 'id' in value ? value.id : value\n return typeof id === 'string' || typeof id === 'number' ? id : undefined\n}\n","import type { AppAddress, ResourceModel, ViewModel } from '@protobase/schema'\nimport type { GridRow, RowAction } from '../../data-grid'\nimport { recordKey } from '../../live/model-helpers'\nimport { humanize } from '../../live/naming'\nimport type { RouteTarget } from '../../primitives/route-link'\nimport { rowAllows } from '../permissions'\nimport { relationTarget } from '../related-opens'\nimport { text } from './messages'\n\ntype Targets = {\n model: ResourceModel\n view: ViewModel | undefined\n /** The relation whose record a row opens instead of its own. */\n opens: string | undefined\n resources: Record<string, ResourceModel>\n views: Record<string, ViewModel>\n /** Whether the user may update the rows' own records. */\n canUpdate: boolean\n}\n\nconst singularOf = (model: ResourceModel, view: ViewModel | undefined) => (view?.names?.singular ?? humanize(model.name)).toLowerCase()\n\n/**\n * Where a table row of an embedded list leads, and its menu's items. A row opens its own record, or with `opens` the\n * record that relation points at when it holds one; its menu then opens that record and edits, or for a user who may\n * not, opens the row's own.\n */\nexport const embeddedRowTargets = ({ model, view, opens, resources, views, canUpdate }: Targets) => {\n const own = (row: GridRow): AppAddress => ({ kind: 'record', resource: model.name, key: recordKey(model, row) })\n const farName = opens && model.fields[opens]?.relation?.resource\n const far = farName ? resources[farName] : undefined\n const other = (row: GridRow): AppAddress | undefined => {\n const key = opens && far ? relationTarget(row, opens) : undefined\n return far && key !== undefined ? { kind: 'record', resource: far.name, key } : undefined\n }\n const address = (row: GridRow) => other(row) ?? own(row)\n const singular = singularOf(model, view)\n\n const actions = (linkTo: (to: AppAddress) => RouteTarget): RowAction[] => {\n const openOwn: RowAction = { label: text('open', { singular }), link: (row) => linkTo(own(row)) }\n if (!far) return [openOwn]\n const editable = (row: GridRow) => canUpdate && rowAllows(row, 'update')\n return [\n { label: text('open', { singular: singularOf(far, views[far.name]) }), available: (row) => other(row) !== undefined, link: (row) => linkTo(other(row)!) },\n { label: text('edit', { singular }), available: editable, link: (row) => linkTo({ kind: 'record', resource: model.name, key: recordKey(model, row), edit: true }) },\n { ...openOwn, available: (row) => !editable(row) },\n ]\n }\n return { address, actions }\n}\n","import type { ActionRun, AppAddress } from '@protobase/schema'\nimport { fillAddress } from '@protobase/schema/internal'\nimport type { RouteTarget } from '../../primitives/route-link'\nimport { linkTarget } from './action-href'\n\ntype LinkRun = Extract<ActionRun, { kind: 'link' }>\n\n/** How the app writes and follows an address, as `useAppAddress` gives them. */\ntype Addresses = { href: (to: AppAddress) => string; go: (to: AppAddress) => void }\n\n/**\n * A link action on `record` as a link: an address in the app is followed in place, a page outside it, an `https:` or\n * `http:` one in a new tab, is left to the browser. A link whose `href` has no target on the record is never shown\n * (`actionFor` leaves it out), so asking for it is a mistake.\n */\nexport const actionLink = (run: LinkRun, record: Record<string, unknown> | undefined, { href, go }: Addresses): RouteTarget => {\n if ('to' in run) {\n const to = fillAddress(run.to, record)\n return { href: href(to), onFollow: () => go(to) }\n }\n const target = linkTarget(run.href, record)\n if (target === undefined) throw new Error('A link action without a target on the record is not shown')\n return { href: target, newTab: /^https?:/i.test(target) }\n}\n","import type { RecordPermissions } from '@protobase/client'\nimport type { ResourceModel } from '@protobase/schema'\nimport type { GridRow } from '../../data-grid'\nimport { displayRow } from '../displays/list-displays'\nimport type { LayoutRecord } from '../pages/record-scope'\n\n/**\n * A list's row as the record a named action acts on: its fields as the API gives them, without what the list loads\n * beside them, with its key, ETag and permissions.\n */\nexport const rowRecord = (model: ResourceModel, row: GridRow): LayoutRecord => ({\n model,\n record: Object.fromEntries(Object.entries(displayRow(model, row).record).filter(([name]) => Object.hasOwn(model.fields, name))),\n key: row.id,\n ...(typeof row.etag === 'string' && { etag: row.etag }),\n ...(typeof row.permissions === 'object' && row.permissions !== null && { permissions: row.permissions as RecordPermissions }),\n})\n","import { useState } from 'react'\nimport type { ActionModel, ResourceModel } from '@protobase/schema'\nimport type { BulkAction, GridRow, RowAction } from '../../data-grid'\nimport { actionFor } from '../pages/action-href'\nimport { actionLink } from '../pages/action-link'\nimport { ActionPrompt, isDanger } from '../pages/action-prompt'\nimport type { LayoutRecord } from '../pages/record-scope'\nimport { quoted, useActionRunner } from '../pages/use-run-action'\nimport { useRecordTitle } from '../titles/record-titles'\nimport { useAdminMeta } from '../meta-gate'\nimport { useAppAddress } from '../use-app-address'\nimport { text } from '../list-messages'\nimport { rowRecord } from './row-record'\n\n// What runs once the action's question is answered: the action on one row, or on each of a selection.\ntype Run = { action: ActionModel; row: LayoutRecord } | { action: ActionModel; selection: LayoutRecord[]; skipped: number }\n// A run whose dialog is open, with how to report the records it leaves open once it ends.\ntype Asking = Run & { settle: (open: LayoutRecord[] | Promise<LayoutRecord[]>) => void }\n\n/**\n * The named actions of `model`'s view for its list: those without inputs each in the row menu of the rows it shows for,\n * disabled with its reason where `when` disables it, and in red when it is a delete or a danger action; a link is a link\n * there, and a disabled one a disabled item without one. Updates and handlers marked `bulk` are offered for a selection\n * while one selected row applies, ask their question or inputs once, and run on those that do, refusing and naming\n * those the person may not change, which stay selected. `prompt` is the dialog one opens before it runs.\n */\nexport const useListActions = (model: ResourceModel) => {\n const { views, resources } = useAdminMeta()\n const runner = useActionRunner(model.name, undefined)\n const app = useAppAddress()\n const titleOf = useRecordTitle()\n const [asking, setAsking] = useState<Asking>()\n const named = views[model.name]?.actions ?? []\n const listed = named.filter((action) => !action.inputs?.length)\n // Resolves to the records the run leaves open, those it was refused on\n const perform = async (run: Run, values?: Record<string, unknown>) => {\n if ('row' in run) {\n await runner.run(run.action, run.row)\n return []\n }\n const outcome = await runner.runEach(run.action, run.selection, run.skipped, values)\n return outcome.refused\n }\n // Resolves once the run ended to the records it leaves open: all of them when its dialog is cancelled\n const start = (run: Run) =>\n new Promise<LayoutRecord[]>((settle) => {\n if (run.action.confirm || run.action.inputs?.length) setAsking({ ...run, settle })\n else settle(perform(run))\n })\n\n const rowActions = listed.map((action): RowAction => {\n const shown = (row: GridRow) => actionFor(action, rowRecord(model, row).record, resources)\n const base = { label: (row: GridRow) => shown(row)?.label ?? action.label, destructive: isDanger(action) }\n const run = action.run\n const blocked = (row: GridRow) => runner.blockedOn(action, rowRecord(model, row))\n const available = (row: GridRow) => shown(row) !== undefined\n if (run?.kind === 'link') return { ...base, available, blocked, link: (row) => actionLink(run, rowRecord(model, row).record, app) }\n return { ...base, available, blocked, onSelect: (row) => void start({ action, row: rowRecord(model, row) }) }\n })\n\n const bulkActions = named\n .filter((action) => action.bulk && action.run?.kind !== 'link')\n .map((action): BulkAction => ({\n label: (count) => text('actionCount', { label: action.label, count }),\n destructive: isDanger(action),\n available: (row) => runner.verdictOn(action, rowRecord(model, row)) !== 'skip',\n onRun: async (rows, skipped) => {\n const selection = rows.map((row) => rowRecord(model, row))\n const open = await start({ action, selection, skipped })\n return rows.filter((_, index) => open.includes(selection[index]!))\n },\n }))\n\n const prompt = asking && (\n <ActionPrompt\n action={asking.action}\n label={'row' in asking ? asking.action.label : text('actionCount', { label: asking.action.label, count: asking.selection.length })}\n danger={isDanger(asking.action)}\n records={'row' in asking ? [asking.row.record] : asking.selection.map((on) => on.record)}\n names={'row' in asking ? [] : asking.selection.map((on) => quoted(titleOf(model, views[model.name], on.record, on.key)))}\n onCancel={() => {\n setAsking(undefined)\n asking.settle('row' in asking ? [asking.row] : asking.selection)\n }}\n onConfirm={() => {\n setAsking(undefined)\n asking.settle(perform(asking))\n }}\n onSubmit={async (values) => {\n setAsking(undefined)\n const running = perform(asking, values)\n asking.settle(running)\n await running\n }}\n />\n )\n return { rowActions, bulkActions, prompt }\n}\n","import { keepPreviousData, useQuery, useQueryClient, type QueryClient } from '@tanstack/react-query'\nimport type { Client } from '@protobase/client'\nimport type { ResourceModel, ViewModel } from '@protobase/schema'\nimport { useClient } from '../../data/api-provider'\nimport { keys } from '../../data/query-keys'\nimport type { GridRow } from '../../data-grid'\nimport { recordId } from '../../live/model-helpers'\nimport { listLabels, withLabels } from '../../live/relation-labels'\nimport { listPhotos, withPhotos } from '../../live/row-photos'\nimport { seedTitleRows } from '../../live/title-rows'\nimport { useAdminMeta } from '../meta-gate'\n\nexport type EmbeddedRowsRequest = {\n model: ResourceModel\n filter: string\n orderBy: string\n limit: number\n /** The fields its relations are labelled and its relations' titles read for. */\n fields: string[]\n /** The fields each record is read with, from `embeddedReadFields`; `undefined` reads whole records. */\n read: string[] | undefined\n}\n\n/** What `embeddedRowsQuery` reads with beside the request: the API, the query cache its titles are seeded into, and the app's models. */\ntype Reader = { client: Client; queryClient: QueryClient; resources: Record<string, ResourceModel>; views: Record<string, ViewModel> }\n\n/**\n * The first `limit` records in `orderBy` order, with the fields `read` names, as the list page's table and displays get them: relations among\n * `fields` as `{ id, name }`, named in the same call, with the photos of its cards, and how many records match in all,\n * counted in the same call: `estimated` when more than the server counts exactly match; the fields the derived titles\n * of the records its relations point at read, in one more call per resource. A filter through a join\n * resource may hold hundreds of keys, so it goes in a JSON body.\n */\nexport const embeddedRowsQuery = ({ client, queryClient, resources, views }: Reader, { model, filter, orderBy, limit, fields, read }: EmbeddedRowsRequest) => ({\n queryKey: [...keys.list(model.name, filter, orderBy, limit, 'embedded'), fields.join(','), read?.join(',') ?? '*'],\n queryFn: async (): Promise<{ rows: GridRow[]; total: number; estimated: boolean }> => {\n const labels = listLabels(resources, views, model, fields)\n const photos = listPhotos(views[model.name])\n const page = await client.search(model.name, { filter: filter || undefined, orderBy: orderBy || undefined, pageSize: limit, count: 'exact', labels, photos, fields: read })\n await seedTitleRows(queryClient, client, resources, views, model, fields, page.items)\n const labelled = withLabels(resources, model, fields, withPhotos(model, page.items, page.photos), page.labels)\n const rows = labelled.map((row, index) => ({ ...row, id: recordId(model, page.items[index]!) }))\n // The last page holds them all\n if (page.nextPageToken === '') return { rows, total: rows.length, estimated: false }\n return { rows, total: page.totalSize ?? page.totalSizeEstimate, estimated: page.totalSize === undefined }\n },\n})\n\n/** The rows of `embeddedRowsQuery`, the page before staying while the next loads; nothing is read while not `enabled`. */\nexport const useEmbeddedRows = (request: EmbeddedRowsRequest, enabled = true) => {\n const { resources, views } = useAdminMeta()\n return useQuery({ ...embeddedRowsQuery({ client: useClient(), queryClient: useQueryClient(), resources, views }, request), placeholderData: keepPreviousData, enabled })\n}\n","import type { ResourceModel } from '@protobase/schema'\nimport type { GridRow } from '../../data-grid'\nimport { recordId } from '../../live/model-helpers'\nimport { withLabels } from '../../live/relation-labels'\nimport { withPhotos } from '../../live/row-photos'\nimport type { Planned } from '../pages/planned'\nimport { plannedCount } from '../pages/planned-count'\n\n/** A list's first page from the page's planned read, and how many records match in all, from its total read. */\nexport type PlannedList = { rows: Planned; total: Planned | undefined }\n\n/**\n * The rows of `planned` as `useEmbeddedRows` gives its own: relations among `fields` named, photos beside them, and\n * the total its total read counts, its rows' count without one.\n */\nexport const plannedEmbeddedRows = (resources: Record<string, ResourceModel>, model: ResourceModel, fields: string[], { rows, total }: PlannedList) => {\n const isPending = rows.isPending || Boolean(total?.isPending)\n const error = rows.error ?? total?.error ?? null\n if (isPending || error) return { isPending, error, data: undefined }\n const labelled = withLabels(resources, model, fields, withPhotos(model, rows.rows, rows.photos), rows.labels)\n const listed: GridRow[] = labelled.map((row, index) => ({ ...row, id: recordId(model, rows.rows[index]!) }))\n return { isPending, error, data: { rows: listed, total: total ? plannedCount(total) : listed.length, estimated: false } }\n}\n","import { ArrowRight } from 'lucide-react'\nimport { useMemo, useState, type ReactNode } from 'react'\nimport type { AppAddress, ResourceModel, RowButtonModel, ViewModel } from '@protobase/schema'\nimport { encodeKey } from '@protobase/schema/internal'\nimport { DataGrid, type ColumnSpec, type GridRow } from '../../data-grid'\nimport { useIsDesktop, useIsXs } from '../../lib/use-media-query'\nimport { recordKey } from '../../live/model-helpers'\nimport { humanize } from '../../live/naming'\nimport type { RouteTarget } from '../../primitives/route-link'\nimport { Skeleton } from '../../primitives/skeleton'\nimport { CardsDisplay } from '../displays/cards-display'\nimport { CustomDisplay } from '../displays/custom-display'\nimport { MapDisplay } from '../displays/map-display'\nimport { BoardDisplay, CalendarDisplay, TimelineDisplay } from '../displays/lazy-displays'\nimport { DisplaySwitch } from '../displays/display-controls'\nimport type { ListDisplay } from '../displays/display-context'\nimport { displayRow, shownDisplay } from '../displays/list-displays'\nimport { ErrorBanner } from '../error-banner'\nimport { useProjectUi } from '../pages/project-ui'\nimport { defaultOrderBy, parseSort, sortToOrderBy } from '../list-order'\nimport { useAdminMeta, usePermissions } from '../meta-gate'\nimport { can } from '../permissions'\nimport { withRowButton } from '../row-button/row-button-column'\nimport { AppLink, useAppAddress } from '../use-app-address'\nimport { viewAllAddress } from './embedded-display'\nimport { cutOffNote } from './cut-off-note'\nimport { embeddedFields } from './embedded-fields'\nimport { embeddedRowTargets } from './embedded-row-targets'\nimport { useListActions } from '../list-actions/use-list-actions'\nimport { useEmbeddedRows } from './use-embedded-rows'\nimport { plannedEmbeddedRows, type PlannedList } from './planned-embedded-rows'\nimport { text } from './messages'\n\nexport type EmbeddedListProps = {\n model: ResourceModel\n view: ViewModel | undefined\n filter: string\n /** The order to start in, the list's own when empty; the table's headers change it. */\n sort: string\n /** The table's columns, through relations too (`unit_id.property_id`); the list's columns by default. */\n columns?: string[]\n limit: number\n /** The display shown, from `useEmbeddedDisplay`. */\n display: string\n empty?: string\n /** The cards in one row that scrolls sideways on every screen, not only on a phone. */\n row?: boolean\n /**\n * Where \"View all\" leads instead of the same list: the list with this filter, opened from the saved search\n * `savedSearch`, under this label, calling `onOpen` first.\n */\n viewAll?: { filter: string; label: string; savedSearch?: string; onOpen?: () => void }\n /** Whether it ends with the link to the whole list. */\n link?: boolean\n /** The relation whose record a table row opens instead of its own, for rows that link this record to another; the row's menu then also opens or edits the row's own record. */\n opens?: string\n /** A button on each row of the table, as its last column or on a narrow screen under the first cell, to an address the row's fields name. */\n button?: RowButtonModel\n /** The table's rows can be selected, and the view's `bulk` actions run on the selected rows. */\n bulk?: boolean\n /** Picks the table's columns a phone shows; every column when omitted. */\n phoneColumns?: (specs: ColumnSpec[]) => ColumnSpec[]\n /** Where a table row leads instead of its record, by the row's key as text, such as the page with that row chosen; its menu still opens the record. */\n rowTo?: (key: string) => RouteTarget\n /** The key, as text, of the row the page shows the details of, which the table marks as chosen. */\n chosenKey?: string\n /** Its rows and total from the page's planned reads, drawn until a header sorts it another way, which it reads itself. */\n planned?: PlannedList\n}\n\n/** The switch between the table and the view's displays, for an embedded list's heading; nothing with only a table. */\nexport const EmbeddedDisplaySwitch = ({ view, value, onChange }: { view: ViewModel | undefined; value: string; onChange: (display: string) => void }) => (\n <DisplaySwitch view={view} value={value} onChange={onChange} menu={!useIsDesktop()} />\n)\n\nconst Loading = () => <div className=\"flex flex-col gap-2\">{Array.from({ length: 3 }, (_, index) => <Skeleton key={index} className=\"h-4 w-full\" />)}</div>\n\n/**\n * The first `limit` records of a list, drawn by the list page's own table (sized to its rows) or display, and a link\n * to the whole list with the same filter, order and display, beside a note such as \"The first 10 of 37.\" when there are\n * more. On a phone a cards display is one row that scrolls sideways.\n */\nexport const EmbeddedList = ({ model, view, filter, sort, columns, limit, display, empty, row = false, viewAll, link = true, opens, button, bulk = false, phoneColumns, rowTo, chosenKey, planned }: EmbeddedListProps) => {\n const { resources, views } = useAdminMeta()\n const canUpdate = can(usePermissions(model.name), 'update')\n const { fields: fieldTypes } = useProjectUi()\n const { go, href } = useAppAddress()\n const xs = useIsXs()\n const narrow = !useIsDesktop()\n const initialOrder = sort || defaultOrderBy(model, view)\n const [orderBy, setOrderBy] = useState(initialOrder)\n const { specs, fields, read } = useMemo(\n () => embeddedFields({ model, view, resources, views, fieldTypes, columns, button, opens, bulk, phoneColumns, xs }),\n [model, view, resources, views, fieldTypes, columns?.join(','), button, opens, bulk, phoneColumns, xs],\n )\n const gridColumns = useMemo(() => (button ? withRowButton(specs, model, view, button, resources, narrow) : specs), [specs, model, view, button, resources, narrow])\n const fromPlan = planned !== undefined && orderBy === initialOrder\n const own = useEmbeddedRows({ model, filter, orderBy, limit, fields, read }, !fromPlan)\n const plannedRows = useMemo(() => planned && plannedEmbeddedRows(resources, model, fields, planned), [planned, resources, model, fields])\n const rows = fromPlan ? plannedRows! : own\n const named = useListActions(model)\n const loaded = rows.data?.rows\n const source = useMemo(() => loaded && { total: loaded.length, rowAt: (index: number) => loaded[index]! }, [loaded])\n const shown = shownDisplay(view, display)\n\n const plural = view?.names?.plural ?? humanize(model.name)\n const allLink = link && (\n <AppLink\n to={viewAllAddress(model, view, xs, viewAll ? { filter: viewAll.filter, orderBy: defaultOrderBy(model, view), display, savedSearch: viewAll.savedSearch } : { filter, orderBy, display })}\n onClick={viewAll?.onOpen}\n className=\"flex items-center gap-1 self-end font-medium text-primary-text hover:underline\"\n >\n {viewAll ? viewAll.label : <>{text('viewAll')} <span className=\"sr-only\">{plural.toLowerCase()}</span></>}\n <ArrowRight className=\"size-3.5\" aria-hidden />\n </AppLink>\n )\n\n // The open dialog stays while a refetch loads, fails or leaves no rows, so cancelling it still clears it\n const withPrompt = (body: ReactNode) => <>{body}{named.prompt}</>\n if (rows.isPending) return withPrompt(<Loading />)\n if (rows.error) return withPrompt(<ErrorBanner title={text('couldNotLoad')} error={rows.error} />)\n // A link of its own still leads somewhere when nothing here matches\n const data = rows.data\n if (!data || !source || source.total === 0) {\n const nothing = <p className=\"text-muted-foreground\">{empty ?? text('nothingYet')}</p>\n return withPrompt(viewAll && link ? <div className=\"flex flex-col gap-3\">{nothing}{allLink}</div> : nothing)\n }\n\n const list: ListDisplay = {\n resource: model.name,\n rows: data.rows.map((row) => displayRow(model, row)),\n total: data.total,\n loading: false,\n error: null,\n more: false,\n loadMore: () => undefined,\n }\n const targets = embeddedRowTargets({ model, view, opens, resources, views, canUpdate })\n const linkTo = (to: AppAddress): RouteTarget => ({ href: href(to), onFollow: () => go(to) })\n const keyOf = (row: GridRow) => encodeKey(recordKey(model, row))\n const rowTarget = (row: GridRow) => (rowTo ? rowTo(keyOf(row)) : linkTo(targets.address(row)))\n const chosenRow = chosenKey === undefined ? undefined : data.rows.find((row) => keyOf(row) === chosenKey)?.id\n const note = cutOffNote(source.total, data.total, data.estimated)\n return (\n <div className=\"flex flex-col gap-3\">\n {!shown ? (\n <DataGrid\n fit\n columns={gridColumns}\n source={source}\n latencyMs={0}\n sort={parseSort(orderBy)}\n onSortChange={(next) => setOrderBy(sortToOrderBy(next))}\n onOpenRow={(row) => rowTarget(row).onFollow?.()}\n rowLink={rowTarget}\n chosenRow={chosenRow}\n rowActions={targets.actions(linkTo)}\n rowNumbers={false}\n selectable={bulk}\n {...(bulk && { bulkActions: named.bulkActions })}\n />\n ) : shown.kind === 'cards' ? (\n <CardsDisplay model={model} view={view} display={shown} list={list} row={row || xs} footer={false} />\n ) : shown.kind === 'map' ? (\n <MapDisplay model={model} view={view} display={shown} filter={filter} orderBy={orderBy} fields={fields} footer={false} />\n ) : shown.kind === 'board' ? (\n <BoardDisplay model={model} view={view} display={shown} fields={fields} filter={filter} orderBy={orderBy} limit={limit} />\n ) : shown.kind === 'calendar' ? (\n <CalendarDisplay model={model} view={view} display={shown} fields={fields} filter={filter} />\n ) : shown.kind === 'timeline' ? (\n <TimelineDisplay model={model} view={view} display={shown} fields={fields} filter={filter} />\n ) : (\n <CustomDisplay display={shown} list={list} />\n )}\n {named.prompt}\n {note && link ? (\n <div className=\"flex flex-wrap items-center justify-between gap-2\">\n <p className=\"text-xs text-muted-foreground\">{note}</p>\n {allLink}\n </div>\n ) : (\n allLink\n )}\n </div>\n )\n}\n"],"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AC,CAAC,WAAW,EAC9C,QAASktB,EACE,aACX,WAAYF,GAAQ,QAAQhC,EAAM,EAClC,WAAY,GACZ,WAAYuB,EACZ,GAAKA,GAAQ,CAAE,YAAaphC,EAAM,WAAY,CAC/C,GAcFA,EAAM,OACNm3B,IAAQ13B,GACP,EAAAF,EAAA,MAAC,MAAD,CAAK,UAAU,oDAAf,WACE,EAAAA,EAAA,KAAC,IAAD,CAAG,UAAU,gCAAiC,SAAA43B,EAAQ,GACrDuK,EACE,CAEL,GAAAA,EAEC,GAET","names":["__iconData","ArrowDown","createLucideIcon","ArrowRight","ArrowUp","ChartGantt","CircleDashed","Columns3","GripVertical","List","Map","SquareKanban","text","messages","MailboxConnect","signInProviders","useOptionalAuth","busy","setBusy","useState","error","setError","expired","problem","names","offers","offer","signInName","entry","provider","providerName","connect","onConnect","id","failure","AuthError","authMessage","import_jsx_runtime","ActionCard","link","again","codes","mailboxProblem","isApiError","code","mailboxOffers","named","links","linked","useMailboxOffers","auth","wanted","check","setLinked","account","import_react","shown","mail","providers","useActionMailbox","action","offered","ownBoxes","held","input","record","box","checklistBoxes","records","answersFor","values","name","value","inputs","ChecklistInput","describedBy","invalid","useFieldControl","boxes","toggle","onChange","on","ticked","label","Checkbox","masked","SecretInput","Input","event","mask","secretAnswers","covered","hidden","secret","secrets","at","maskSecrets","index","maskedFailure","escaped","ApiError","maskedMessages","message","fieldTypes","inputField","base","option","inputHints","startingAnswers","toDraft","answerOf","isChosen","toPatchValue","answeredValues","all","draft","shownInputs","decimal","date","refusal","left","refusedAnswers","reason","InputEditor","useAdminMeta","useProjectUi","Custom","components","target","resources","FieldEditor","views","ActionInputsDialog","setDraft","errors","setErrors","setFailure","running","setRunning","formId","useId","mailbox","submit","refused","onSubmit","inputErrors","change","_","rest","current","ResponsiveDialog","onCancel","_Fragment","Button","danger","ErrorBanner","Field","next","ConfirmAction","Dialog","onConfirm","isDanger","asksFirst","ActionPrompt","useMailboxToastAction","toast","useToast","actionApplies","condition","parseCondition","evaluateCondition","fillHref","fillText","href","valueText","recordValueAt","path","webUrl","url","linkTarget","field","hrefField","openLink","hostOf","holdsAll","actionFor","run","resourceField","to","fillAddress","hostPlaceholder","runEach","verdicts","verdict","outcome","quoted","title","useActionRunner","handlers","permissions","usePermissions","resource","client","useClient","handlerClient","useResourceClient","mailboxAction","refresh","useRefreshResource","useAppAddress","titleOf","useRecordTitle","actions","scope","blockedOn","kind","can","custom","blocked","refusedOn","execute","go","updateValues","perform","afterRun","appliesOn","verdictOn","answers","skipped","description","useRunAction","runner","where","createWhere","slot","colorOf","key","color","valueColor","hints","labelOf","group","enumLabel","groupFilter","own","printFilter","filter","measured","measure","valueSlices","groups","periodPoints","measureText","formatTag","decimals","labelFieldOf","chartAggregate","model","groupBy","dated","splitField","splitBy","splitLabel","split","params","viewerZone","sum","average","filteredListAddress","view","GroupBars","largest","slices","slice","share","AppLink","PeriodChart","lazyComponent","__vitePreload","module","Skeleton","compact","GroupDonut","noise","splitPoints","series","splits","missing","partOf","part","candidate","points","parts","entries","point","measureOf","ChartView","result","useAggregate","empty","chartType","type","granularity","snapRowGap","snapItemWidth","snapItemSize","arrowClass","SnapRow","size","scroll","ChevronLeft","ChevronRight","list","watch","same","a","b","useSnapScroll","setList","scrolled","setScrolled","read","latest","useRef","changed","observer","gap","direction","cutOffNote","total","estimated","prefix","embeddedDisplayKey","place","readPickedDisplay","guarded","storage","writePickedDisplay","display","embeddedDisplay","displayChoices","choice","picked","defaultDisplay","xs","preferred","viewAllAddress","changedList","listDefaults","plannedCount","planned","isEmpty","httpsUrl","plainValue","followableFilter","models","parsed","parseFilter","checkFilter","rowButtonFor","rowButtonChoices","button","rowButtonChoiceFields","displayValue","rowButtonTarget","filterField","bareFilterFields","RowButtonLink","style","cn","buttonClass","ExternalLink","features","tableFeatures","helper","createColumnHelper","buildColumns","specs","spec","row","context","renderCell","offeredBulkActions","rows","selected","runBulkAction","open","kept","oneBulkRunAtATime","GridFooter","className","formatApproxRows","selectedCount","formatInt","bulkActions","availableActions","RowMenu","usePopoverMenu","setOpen","MoreHorizontal","createPortal","menu","itemClass","RouteLink","gutterWidthFor","desktopMinScale","minWidthOf","minScale","columnTemplate","gridTemplate","gutter","trailing","gridMinWidth","useHorizontalScroll","ref","edges","setEdges","useCallback","element","child","pinnedStorageKey","userId","readPinned","raw","writePinned","pinned","usePinnedColumns","chosen","setChosen","storageKey","update","initial","defaultPins","sizesOf","fitKey","columns","minWidth","maxWidth","useFittedColumns","fitted","setFitted","fitColumns","sizes","useMemo","resizedWidth","start","delta","withResizedWidths","widths","measuredWidths","header","cell","useColumnResize","setWidths","startWidths","startX","onMove","move","onEnd","rootFontSize","useRootFontSize","useSyncExternalStore","compactRow","below","footer","gridHeights","rem","withBelow","isRightAligned","unsortableText","HeaderMenu","sortable","onTogglePin","ResizeHandle","width","resize","SortIcon","sorted","ChevronsUpDown","HeaderLabel","GridHeader","lastPinned","selectable","onClearSelection","cells","pins","onSort","frameStyle","frame","cellClass","pinStyle","Gutter","onToggle","edge","dragStyle","dragY","openUnlessLink","onOpen","DataRow","rowRef","dragging","transition","handle","props","editable","editing","content","skeletonWidths","SkeletonRow","column","maxContentHeight","gridGeometry","trueHeight","rowHeight","contentHeight","viewportHeight","topFromScroll","geometry","position","scrollFromTop","top","rowOffset","offset","rowsInView","first","overscan","last","height","scrollParent","page","parent","isPage","scroller","scrollEvents","padding","visibleArea","viewRows","useVirtualRows","setView","options","area","before","after","onScroll","sameRows","begin","initialIndex","events","scrollTo","started","drawn","settle","isMoveKey","movedCell","nextEditable","from","placeId","useCellEditing","active","setActive","setEditing","refocus","pressedChosen","container","editor","editableAt","rowAt","choose","edit","close","focused","reachable","onOpenRow","ReorderRows","sensors","useSensors","useSensor","MouseSensor","TouchSensor","KeyboardSensor","sortableKeyboardCoordinates","ids","reorder","DndContext","closestCenter","over","SortableContext","verticalListSortingStrategy","SortableRow","useSortable","setActivatorNodeRef","attributes","listeners","setNodeRef","transform","isDragging","DataGrid","given","controlledSort","selecting","headerHeight","footerHeight","narrow","useIsDesktop","pinsByDefault","defaultPinned","setPinned","pinKey","pinnedIds","source","localSorting","setLocalSorting","naturalSort","sorting","setSorting","updater","onSortChange","rowSelection","setRowSelection","tableColumns","sort","reverse","sourceRowAt","startIndex","initialScrollIndex","virtualRows","firstIndex","lastIndex","onScrollIndex","rowNumbers","getRow","usePagedRows","patchedRow","patch","rowPatches","loaded","data","headerRef","sized","table","useTable","tableRows","selectedRows","rowActions","horizontal","onBodyScroll","setPins","togglePin","headerCells","gridRef","cellEditing","cellEditor","linkColumn","fit","tableRow","chosenRow","rowLink","stacked","body","done","chipClass","FilterChipList","chips","chip","InlineFilterChips","chipsText","defaultDatePresets","knownPresets","datePresetLabel","emptyFilterState","toggleFacetValue","state","toggleFlag","setRange","others","facetLabel","activeChips","facetChips","config","rangeChips","span","range","dateChips","toggleChips","removeChip","matchesSearch","query","w","relative","iso","ms","periodStart","today","dayIn","now","zone","year","month","day","preset","calendarPresets","dayLiteral","startOfDayIn","instant","span$1","dateClauses","stateToClauses","facets","ranges","toggles","clausesToText","clauses","stateToText","extras","flatten","expr","fieldName","isTrue","flagsChosen","clause","fields","groupOf","literalText","presetOf","v","d","amount","unit","textToState","facetIds","flagGroupOf","toggleIds","rangeIds","bounds","dateClause","todayEnd","flags","numberTypes","isNumber","rangeOf","widget","secondaryOf","emptyRange","widgetFields","widgets","rangeHistogram","rangeFormat","suffix","currency","formatMoney","chosenRelations","namedConfig","humanize","skeleton","labels","filterChips","facetNames","unseenFilter","seenAt","isUnseen","useFilterChips","queryClient","useQueryClient","useQueries","keys","fetchLabels","RelationTitleText","useRelationTitle","relationValue","savedRecordsOf","encodeKey","recordKey","savedFor","saved","withSaved","withoutSaved","savedScope","savedRecordsKey","useSavedRecords","useQuery","enabled","pageToken","useFavorite","meta","favorite","usable","prompt","cacheKey","useMutation","existing","FavoriteButton","prompting","setPrompting","Heart","SignInPrompt","placeCard","dot","card","viewport","dotCard","cards","displaysOf","status","__","___","relatedColumnLoads","shownFields","dotsSummary","statuses","counts","singular","plural","dotBox","dotMark","dotsLine","hideMs","cardWidth","DotCardPopover","setPlace","onEnter","onLeave","Card","RelatedDots","displayRow","setShown","hideTimer","pointer","statusText","titleField","recordTitleField","summary","cancelHide","hideSoon","show","hide","outside","tap","blur","shownRow","wrap","toneDots","valueTone","DotsRoom","count","lines","CardDotsRoom","dots","CardDots","cardDotsLines","CardPhoto","image","shownImage","FileImage","CardImageFrame","CardImage","maxCardDots","cardPhotoList","coverUri","isStoredFile","cover","photos","photo","CardCarousel","carousel","useCarousel","picture","CarouselTrack","children","CarouselControls","MetaValue","Icon","namedIcon","icon","RecordCard","cardFields","isMarkdown","markdownExcerpt","jsonSummary","linkTextOf","seedRecord","useSeedRecord","shownValue","shownWidget","WidgetPart","subtitleValue","Markdown","metaValue","ValueBadge","amountValue","amountParts","badge","raised","shownAmount","filledAmount","shownCode","filledCode","footing","filledMeta","pictured","builtIn","subtitle","CodeBlock","rawCode","Badge","mark","CustomBoundary","rowCardGap","rowWindow","step","scrollLeft","placesAround","rowPlaces","end","rowSpan","Spacer","RecordRow","places","isNew","scoped","recordRowRead","loadedFields","defaultOrderBy","rowDisplay","Loading","RecordRowBody","showChips","useIsXs","useLiveRows","limit","note","viewAll","savedSearchesKey","useSavedSearches","useSearchRow","of","stored","unseen","markSeen","newCount","countQuery","targetView","DisplayState","loading","DisplayFooter","grid","CardsDisplay","CustomDisplay","Component","ListDisplayProvider","unmarkFieldRefs","Problem","worldArea","maxZoom","down","degrees","up","wrapped","longitude","boundsFilter","latitude","west","east","areaFilter","inside","listFilter","requestZoom","zoom","boundsAround","corners","buckets","bucket","corner","numeric","recordPosition","earthRadius","circleCorners","isApproximate","circleArea","distance","metres","center","bearing","isPosition","isLine","least","isPolygon","ring","isLines","line","areaGeometry","coordinates","positionArea","radius","mapPoints","groupPoints","near","keptSelection","selection","present","stepSelection","useMapRecords","orderBy","keepPreviousData","listLabels","listPhotos","withLabels","withPhotos","RecordsMap","lazy","settleMs","arrow","MapDisplay","maps","setArea","settled","useDebounced","fitting","setFitting","mapCards","approximate","markerLabel","bucketLabel","overlay","setCovered","flush","Suspense","X","inView","BoardDisplay","CalendarDisplay","TimelineDisplay","icons","Table2","LayoutGrid","Calendar","MapIcon","DisplaySwitch","choices","MenuSelect","Segmented","directions","SortMenu","parseSort","sortFields","word","labelCharWidth","buttonFrame","outsideMark","rowButtonMaxWidth","recordOf","rowButton","rowButtonWidth","rowButtonColumn","withRowButton","opensTo","relatedOpens","item","candidates","relationTarget","singularOf","embeddedRowTargets","farName","opens","far","other","address","openOwn","linkTo","canUpdate","rowAllows","actionLink","rowRecord","useListActions","app","asking","setAsking","listed","available","embeddedRowsQuery","seedTitleRows","recordId","useEmbeddedRows","request","plannedEmbeddedRows","isPending","EmbeddedDisplaySwitch","EmbeddedList","initialOrder","setOrderBy","embeddedFields","bulk","phoneColumns","gridColumns","fromPlan","plannedRows","shownDisplay","allLink","withPrompt","nothing","targets","keyOf","rowTarget","rowTo","chosenKey","sortToOrderBy"],"ignoreList":[0,1,2,3,4,5,6,7,8,9],"sources":["../../../../../node_modules/.bun/lucide-react@1.52.0+0ac650c021fb1b59/node_modules/lucide-react/dist/esm/icons/arrow-down.mjs","../../../../../node_modules/.bun/lucide-react@1.52.0+0ac650c021fb1b59/node_modules/lucide-react/dist/esm/icons/arrow-right.mjs","../../../../../node_modules/.bun/lucide-react@1.52.0+0ac650c021fb1b59/node_modules/lucide-react/dist/esm/icons/arrow-up.mjs","../../../../../node_modules/.bun/lucide-react@1.52.0+0ac650c021fb1b59/node_modules/lucide-react/dist/esm/icons/chart-gantt.mjs","../../../../../node_modules/.bun/lucide-react@1.52.0+0ac650c021fb1b59/node_modules/lucide-react/dist/esm/icons/circle-dashed.mjs","../../../../../node_modules/.bun/lucide-react@1.52.0+0ac650c021fb1b59/node_modules/lucide-react/dist/esm/icons/columns-3.mjs","../../../../../node_modules/.bun/lucide-react@1.52.0+0ac650c021fb1b59/node_modules/lucide-react/dist/esm/icons/grip-vertical.mjs","../../../../../node_modules/.bun/lucide-react@1.52.0+0ac650c021fb1b59/node_modules/lucide-react/dist/esm/icons/list.mjs","../../../../../node_modules/.bun/lucide-react@1.52.0+0ac650c021fb1b59/node_modules/lucide-react/dist/esm/icons/map.mjs","../../../../../node_modules/.bun/lucide-react@1.52.0+0ac650c021fb1b59/node_modules/lucide-react/dist/esm/icons/square-kanban.mjs","../../../src/mailbox/messages.ts","../../../src/mailbox/mailbox-connect.tsx","../../../src/mailbox/mailbox-problem.ts","../../../src/mailbox/mailbox-offers.ts","../../../src/mailbox/use-mailbox-offers.ts","../../../src/mailbox/use-action-mailbox.tsx","../../../src/app/pages/action-inputs/checklist-boxes.ts","../../../src/app/pages/action-inputs/checklist-input.tsx","../../../src/app/pages/action-inputs/secret-input.tsx","../../../src/app/pages/action-inputs/secret-mask.ts","../../../src/app/pages/action-inputs/input-answers.ts","../../../src/app/pages/action-inputs/action-inputs-dialog.tsx","../../../src/app/pages/confirm-action.tsx","../../../src/app/pages/action-prompt.tsx","../../../src/mailbox/use-mailbox-toast-action.ts","../../../src/app/pages/action-when.ts","../../../src/app/pages/action-href.ts","../../../src/app/pages/run-each.ts","../../../src/app/pages/use-run-action.ts","../../../src/app/list-messages.ts","../../../src/app/charts/messages.ts","../../../src/app/charts/chart-groups.ts","../../../src/app/charts/chart-params.ts","../../../src/app/list-link.ts","../../../src/app/charts/group-bars.tsx","../../../src/app/charts/lazy-charts.tsx","../../../src/app/charts/split-points.ts","../../../src/app/charts/chart-view.tsx","../../../src/primitives/snap-row-width.ts","../../../src/primitives/snap-row.tsx","../../../src/primitives/use-snap-scroll.ts","../../../src/app/embedded-list/messages.ts","../../../src/app/embedded-list/cut-off-note.ts","../../../src/app/embedded-list/embedded-display.ts","../../../src/app/pages/planned-count.ts","../../../src/app/row-button/row-button-for.ts","../../../src/app/row-button/row-button-link.tsx","../../../src/data-grid/columns.ts","../../../src/data-grid/bulk-actions.ts","../../../src/data-grid/grid-footer.tsx","../../../src/data-grid/row-menu.tsx","../../../src/data-grid/grid-template.ts","../../../src/data-grid/use-horizontal-scroll.ts","../../../src/data-grid/pinned-storage.ts","../../../src/data-grid/use-pinned-columns.ts","../../../src/data-grid/default-pins.ts","../../../src/data-grid/use-fitted-columns.ts","../../../src/data-grid/column-resize.ts","../../../src/data-grid/use-column-resize.ts","../../../src/lib/use-root-font-size.ts","../../../src/data-grid/grid-heights.ts","../../../src/data-grid/column-spec.ts","../../../src/data-grid/header-menu.tsx","../../../src/data-grid/resize-handle.tsx","../../../src/data-grid/grid-header.tsx","../../../src/data-grid/grid-row.tsx","../../../src/data-grid/geometry.ts","../../../src/data-grid/scroll-parent.ts","../../../src/data-grid/use-virtual-rows.ts","../../../src/data-grid/cell-moves.ts","../../../src/data-grid/use-cell-editing.tsx","../../../src/data-grid/row-reorder.tsx","../../../src/data-grid/data-grid.tsx","../../../src/app/searches/messages.ts","../../../src/app/searches/filter-chip-list.tsx","../../../src/filter-panel/messages.ts","../../../src/filter-panel/filter-config.ts","../../../src/filter-panel/filter-state.ts","../../../src/live/filter-string.ts","../../../src/live/view-fields.ts","../../../src/app/searches/saved-search.ts","../../../src/app/searches/use-filter-chips.ts","../../../src/app/titles/relation-title-text.tsx","../../../src/app/saved/saved-records.ts","../../../src/app/saved/use-saved-records.ts","../../../src/app/saved/messages.ts","../../../src/app/saved/use-favorite.ts","../../../src/app/saved/favorite-button.tsx","../../../src/app/related-dots/card-place.ts","../../../src/app/related-dots/dot-card.ts","../../../src/app/related-dots/messages.ts","../../../src/app/related-dots/dots-summary.ts","../../../src/app/related-dots/related-dots.tsx","../../../src/app/related-dots/card-dots.tsx","../../../src/app/related-dots/card-dots-lines.ts","../../../src/app/displays/card-image.tsx","../../../src/app/displays/card-photos.ts","../../../src/app/displays/card-carousel.tsx","../../../src/app/displays/record-card.tsx","../../../src/app/record-row/row-window.ts","../../../src/app/record-row/messages.ts","../../../src/app/record-row/record-row.tsx","../../../src/app/record-row/record-row-read.ts","../../../src/app/record-row/record-row-body.tsx","../../../src/app/searches/use-saved-searches.ts","../../../src/app/searches/use-search-row.ts","../../../src/app/displays/display-frame.tsx","../../../src/app/displays/cards-display.tsx","../../../src/app/displays/custom-display.tsx","../../../src/app/map/map-area.ts","../../../src/app/map/record-position.ts","../../../src/app/map/approximate-position.ts","../../../src/app/displays/map-groups.ts","../../../src/app/displays/use-map-records.ts","../../../src/app/displays/map-display.tsx","../../../src/app/displays/lazy-displays.tsx","../../../src/app/displays/display-controls.tsx","../../../src/app/row-button/row-button-column.tsx","../../../src/app/related-opens.ts","../../../src/app/embedded-list/embedded-row-targets.ts","../../../src/app/pages/action-link.ts","../../../src/app/list-actions/row-record.ts","../../../src/app/list-actions/use-list-actions.tsx","../../../src/app/embedded-list/use-embedded-rows.ts","../../../src/app/embedded-list/planned-embedded-rows.ts","../../../src/app/embedded-list/embedded-list.tsx"],"sourcesContent":["/**\n * @license lucide-react v1.52.0 - ISC\n *\n * This source code is licensed under the ISC license.\n * See the LICENSE file in the root directory of this source tree.\n */\n\nimport createLucideIcon from '../createLucideIcon.mjs';\n\nconst __iconData = {\n name: \"arrow-down\",\n size: 24,\n node: [\n [\"path\", { d: \"M12 5v14\", key: \"s699le\" }],\n [\"path\", { d: \"m19 12-7 7-7-7\", key: \"1idqje\" }]\n ]\n};\n__iconData.node;\nconst ArrowDown = createLucideIcon(__iconData);\n\nexport { __iconData, ArrowDown as default };\n//# sourceMappingURL=arrow-down.mjs.map\n","/**\n * @license lucide-react v1.52.0 - ISC\n *\n * This source code is licensed under the ISC license.\n * See the LICENSE file in the root directory of this source tree.\n */\n\nimport createLucideIcon from '../createLucideIcon.mjs';\n\nconst __iconData = {\n name: \"arrow-right\",\n size: 24,\n node: [\n [\"path\", { d: \"M5 12h14\", key: \"1ays0h\" }],\n [\"path\", { d: \"m12 5 7 7-7 7\", key: \"xquz4c\" }]\n ]\n};\n__iconData.node;\nconst ArrowRight = createLucideIcon(__iconData);\n\nexport { __iconData, ArrowRight as default };\n//# sourceMappingURL=arrow-right.mjs.map\n","/**\n * @license lucide-react v1.52.0 - ISC\n *\n * This source code is licensed under the ISC license.\n * See the LICENSE file in the root directory of this source tree.\n */\n\nimport createLucideIcon from '../createLucideIcon.mjs';\n\nconst __iconData = {\n name: \"arrow-up\",\n size: 24,\n node: [\n [\"path\", { d: \"m5 12 7-7 7 7\", key: \"hav0vg\" }],\n [\"path\", { d: \"M12 19V5\", key: \"x0mq9r\" }]\n ]\n};\n__iconData.node;\nconst ArrowUp = createLucideIcon(__iconData);\n\nexport { __iconData, ArrowUp as default };\n//# sourceMappingURL=arrow-up.mjs.map\n","/**\n * @license lucide-react v1.52.0 - ISC\n *\n * This source code is licensed under the ISC license.\n * See the LICENSE file in the root directory of this source tree.\n */\n\nimport createLucideIcon from '../createLucideIcon.mjs';\n\nconst __iconData = {\n name: \"chart-gantt\",\n size: 24,\n node: [\n [\"path\", { d: \"M10 6h8\", key: \"zvc2xc\" }],\n [\"path\", { d: \"M12 16h6\", key: \"yi5mkt\" }],\n [\"path\", { d: \"M3 3v16a2 2 0 0 0 2 2h16\", key: \"c24i48\" }],\n [\"path\", { d: \"M8 11h7\", key: \"wz2hg0\" }]\n ]\n};\n__iconData.node;\nconst ChartGantt = createLucideIcon(__iconData);\n\nexport { __iconData, ChartGantt as default };\n//# sourceMappingURL=chart-gantt.mjs.map\n","/**\n * @license lucide-react v1.52.0 - ISC\n *\n * This source code is licensed under the ISC license.\n * See the LICENSE file in the root directory of this source tree.\n */\n\nimport createLucideIcon from '../createLucideIcon.mjs';\n\nconst __iconData = {\n name: \"circle-dashed\",\n size: 24,\n node: [\n [\"path\", { d: \"M10.1 2.182a10 10 0 0 1 3.8 0\", key: \"5ilxe3\" }],\n [\"path\", { d: \"M13.9 21.818a10 10 0 0 1-3.8 0\", key: \"11zvb9\" }],\n [\"path\", { d: \"M17.609 3.721a10 10 0 0 1 2.69 2.7\", key: \"1iw5b2\" }],\n [\"path\", { d: \"M2.182 13.9a10 10 0 0 1 0-3.8\", key: \"c0bmvh\" }],\n [\"path\", { d: \"M20.279 17.609a10 10 0 0 1-2.7 2.69\", key: \"1ruxm7\" }],\n [\"path\", { d: \"M21.818 10.1a10 10 0 0 1 0 3.8\", key: \"qkgqxc\" }],\n [\"path\", { d: \"M3.721 6.391a10 10 0 0 1 2.7-2.69\", key: \"1mcia2\" }],\n [\"path\", { d: \"M6.391 20.279a10 10 0 0 1-2.69-2.7\", key: \"1fvljs\" }]\n ]\n};\n__iconData.node;\nconst CircleDashed = createLucideIcon(__iconData);\n\nexport { __iconData, CircleDashed as default };\n//# sourceMappingURL=circle-dashed.mjs.map\n","/**\n * @license lucide-react v1.52.0 - ISC\n *\n * This source code is licensed under the ISC license.\n * See the LICENSE file in the root directory of this source tree.\n */\n\nimport createLucideIcon from '../createLucideIcon.mjs';\n\nconst __iconData = {\n name: \"columns-3\",\n size: 24,\n node: [\n [\"rect\", { width: \"18\", height: \"18\", x: \"3\", y: \"3\", rx: \"2\", key: \"afitv7\" }],\n [\"path\", { d: \"M9 3v18\", key: \"fh3hqa\" }],\n [\"path\", { d: \"M15 3v18\", key: \"14nvp0\" }]\n ],\n aliases: [\"panels-left-right\"]\n};\n__iconData.node;\nconst Columns3 = createLucideIcon(__iconData);\n\nexport { __iconData, Columns3 as default };\n//# sourceMappingURL=columns-3.mjs.map\n","/**\n * @license lucide-react v1.52.0 - ISC\n *\n * This source code is licensed under the ISC license.\n * See the LICENSE file in the root directory of this source tree.\n */\n\nimport createLucideIcon from '../createLucideIcon.mjs';\n\nconst __iconData = {\n name: \"grip-vertical\",\n size: 24,\n node: [\n [\"circle\", { cx: \"9\", cy: \"12\", r: \"1\", key: \"1vctgf\" }],\n [\"circle\", { cx: \"9\", cy: \"5\", r: \"1\", key: \"hp0tcf\" }],\n [\"circle\", { cx: \"9\", cy: \"19\", r: \"1\", key: \"fkjjf6\" }],\n [\"circle\", { cx: \"15\", cy: \"12\", r: \"1\", key: \"1tmaij\" }],\n [\"circle\", { cx: \"15\", cy: \"5\", r: \"1\", key: \"19l28e\" }],\n [\"circle\", { cx: \"15\", cy: \"19\", r: \"1\", key: \"f4zoj3\" }]\n ]\n};\n__iconData.node;\nconst GripVertical = createLucideIcon(__iconData);\n\nexport { __iconData, GripVertical as default };\n//# sourceMappingURL=grip-vertical.mjs.map\n","/**\n * @license lucide-react v1.52.0 - ISC\n *\n * This source code is licensed under the ISC license.\n * See the LICENSE file in the root directory of this source tree.\n */\n\nimport createLucideIcon from '../createLucideIcon.mjs';\n\nconst __iconData = {\n name: \"list\",\n size: 24,\n node: [\n [\"path\", { d: \"M3 5h.01\", key: \"18ugdj\" }],\n [\"path\", { d: \"M3 12h.01\", key: \"nlz23k\" }],\n [\"path\", { d: \"M3 19h.01\", key: \"noohij\" }],\n [\"path\", { d: \"M8 5h13\", key: \"1pao27\" }],\n [\"path\", { d: \"M8 12h13\", key: \"1za7za\" }],\n [\"path\", { d: \"M8 19h13\", key: \"m83p4d\" }]\n ]\n};\n__iconData.node;\nconst List = createLucideIcon(__iconData);\n\nexport { __iconData, List as default };\n//# sourceMappingURL=list.mjs.map\n","/**\n * @license lucide-react v1.52.0 - ISC\n *\n * This source code is licensed under the ISC license.\n * See the LICENSE file in the root directory of this source tree.\n */\n\nimport createLucideIcon from '../createLucideIcon.mjs';\n\nconst __iconData = {\n name: \"map\",\n size: 24,\n node: [\n [\n \"path\",\n {\n d: \"M14.106 5.553a2 2 0 0 0 1.788 0l3.659-1.83A1 1 0 0 1 21 4.619v12.764a1 1 0 0 1-.553.894l-4.553 2.277a2 2 0 0 1-1.788 0l-4.212-2.106a2 2 0 0 0-1.788 0l-3.659 1.83A1 1 0 0 1 3 19.381V6.618a1 1 0 0 1 .553-.894l4.553-2.277a2 2 0 0 1 1.788 0z\",\n key: \"169xi5\"\n }\n ],\n [\"path\", { d: \"M15 5.764v15\", key: \"1pn4in\" }],\n [\"path\", { d: \"M9 3.236v15\", key: \"1uimfh\" }]\n ]\n};\n__iconData.node;\nconst Map = createLucideIcon(__iconData);\n\nexport { __iconData, Map as default };\n//# sourceMappingURL=map.mjs.map\n","/**\n * @license lucide-react v1.52.0 - ISC\n *\n * This source code is licensed under the ISC license.\n * See the LICENSE file in the root directory of this source tree.\n */\n\nimport createLucideIcon from '../createLucideIcon.mjs';\n\nconst __iconData = {\n name: \"square-kanban\",\n size: 24,\n node: [\n [\"rect\", { width: \"18\", height: \"18\", x: \"3\", y: \"3\", rx: \"2\", key: \"afitv7\" }],\n [\"path\", { d: \"M8 7v7\", key: \"1x2jlm\" }],\n [\"path\", { d: \"M12 7v4\", key: \"xawao1\" }],\n [\"path\", { d: \"M16 7v9\", key: \"1hp2iy\" }]\n ],\n aliases: [\"kanban-square\"]\n};\n__iconData.node;\nconst SquareKanban = createLucideIcon(__iconData);\n\nexport { __iconData, SquareKanban as default };\n//# sourceMappingURL=square-kanban.mjs.map\n","import { messages } from '../locale/messages'\n\nexport const text = messages('mailbox')\n","import { useState } from 'react'\nimport { AuthError } from '@protobase/client'\nimport { ActionCard } from '../action-card/action-card'\nimport { authMessage } from '../auth/auth-messages'\nimport { useOptionalAuth } from '../auth/auth-provider'\nimport { providerName } from '../auth/provider-link'\nimport type { MailboxOffer } from './mailbox-offers'\nimport type { MailboxProblem } from './mailbox-problem'\nimport { text } from './messages'\n\ntype MailboxConnectProps = {\n offers: MailboxOffer[]\n /** Why the send failed; none when it has not run yet, as no mailbox is linked. */\n problem?: MailboxProblem\n onConnect: (offer: MailboxOffer) => Promise<void>\n}\n\n/**\n * Why mail cannot go out from the person's own mailbox, with a button to connect each mailbox the app offers: it starts\n * the same sign-in as the account page's, which comes back to this page. A sign-in through the mailbox's provider that\n * did not allow sending mail is named, so it is not taken for a mailbox.\n */\nexport const MailboxConnect = ({ offers, problem, onConnect }: MailboxConnectProps) => {\n const signInProviders = useOptionalAuth()?.signInProviders ?? []\n const [busy, setBusy] = useState(false)\n const [error, setError] = useState<string>()\n const expired = problem?.code === 'link_expired'\n const names = offers.map((offer) => offer.link.name)\n const signInName = (provider: string) => signInProviders.find((entry) => entry.id === provider)?.name ?? providerName(provider)\n\n const connect = async (id: string) => {\n setBusy(true)\n setError(undefined)\n try {\n await onConnect(offers.find((offer) => offer.link.id === id)!)\n } catch (failure) {\n if (!(failure instanceof AuthError)) throw failure\n setError(authMessage(failure))\n setBusy(false)\n }\n }\n\n return (\n <ActionCard\n title={text(expired ? 'expiredTitle' : 'missingTitle')}\n tone=\"warning\"\n actions={offers.map(({ link, again }) => ({ id: link.id, label: text(again ? 'connectAgain' : 'connect', { name: link.name }), style: 'primary', disabled: busy }))}\n onAction={(id) => void connect(id)}\n >\n <div className=\"space-y-1 text-body\">\n <p>{text(expired ? 'expired' : 'missing', { names: names.join(', ') })}</p>\n {offers\n .filter((offer) => offer.signInOnly)\n .map(({ link }) => (\n <p key={link.id}>{text('signInOnly', { provider: signInName(link.provider), name: link.name })}</p>\n ))}\n {error && (\n <p role=\"alert\" className=\"font-medium text-danger-text\">\n {error}\n </p>\n )}\n </div>\n </ActionCard>\n )\n}\n","import { isApiError } from '@protobase/client'\n\n/** Why a message could not go out from the person's own mailbox, and the mail provider at fault when the server names one. */\nexport type MailboxProblem = { code: 'not_linked' | 'link_expired'; provider?: string }\n\nconst codes = new Map<string, MailboxProblem['code']>([\n ['personal-mail-not-linked', 'not_linked'],\n ['personal-mail-link-expired', 'link_expired'],\n])\n\n/** The mailbox problem a failed call answered with, as the server's personal mail reports it; none for any other failure. */\nexport const mailboxProblem = (error: unknown): MailboxProblem | undefined => {\n if (!isApiError(error)) return\n const code = codes.get(error.slug)\n if (!code) return\n const { provider } = error.problem\n return { code, ...(typeof provider === 'string' && { provider }) }\n}\n","import type { PersonalMailLink } from '@protobase/client'\nimport type { MailboxProblem } from './mailbox-problem'\n\n/**\n * A mailbox the person can connect: `again` when they linked it before and the link needs renewing, and `signInOnly`\n * when they sign in with its provider, such as Google, without having allowed it to send mail.\n */\nexport type MailboxOffer = { link: PersonalMailLink; again: boolean; signInOnly: boolean }\n\n/** What the person's account holds: the mail providers linked with leave to send (`mail`), and the sign-in providers linked (`providers`). */\nexport type LinkedAccounts = { mail: string[]; providers: string[] }\n\n/**\n * The mailboxes to offer for `problem`, or before a send while none is linked (no `problem`): an expired link offers its\n * provider's mailbox again, or every one when the server named none; a missing one offers each the app has.\n */\nexport const mailboxOffers = (links: PersonalMailLink[], linked: LinkedAccounts, problem?: MailboxProblem): MailboxOffer[] => {\n if (problem?.code === 'link_expired') {\n const named = links.filter((link) => link.id === problem.provider)\n return (named.length > 0 ? named : links).map((link) => ({ link, again: true, signInOnly: false }))\n }\n if (!problem && linked.mail.length > 0) return []\n return links.map((link) => {\n const again = linked.mail.includes(link.id)\n return { link, again, signInOnly: !again && linked.providers.includes(link.provider) }\n })\n}\n","import { useEffect, useState } from 'react'\nimport { AuthError } from '@protobase/client'\nimport { authMessage } from '../auth/auth-messages'\nimport { useOptionalAuth } from '../auth/auth-provider'\nimport { mailboxOffers, type LinkedAccounts, type MailboxOffer } from './mailbox-offers'\nimport type { MailboxProblem } from './mailbox-problem'\n\n/**\n * The mailboxes to offer the signed-in person for `problem`, or, with `check`, before a send while none is linked:\n * `undefined` while their linked accounts are read, none in an app without personal mail. `error` says why they could\n * not be read; `connect` leaves to link one, coming back to this page.\n */\nexport const useMailboxOffers = (problem: MailboxProblem | undefined, check: boolean) => {\n const auth = useOptionalAuth()\n const links = auth?.personalMail ?? []\n const wanted = auth !== null && links.length > 0 && (check || problem !== undefined)\n const [linked, setLinked] = useState<LinkedAccounts>()\n const [error, setError] = useState<string>()\n const account = auth?.session.account\n\n useEffect(() => {\n if (!wanted || !account) return\n let shown = true\n Promise.all([account.linkedPersonalMail(links), account.linkedProviders()]).then(\n ([mail, providers]) => {\n if (shown) setLinked({ mail, providers })\n },\n (failure: unknown) => {\n if (!(failure instanceof AuthError)) throw failure\n if (shown) setError(authMessage(failure))\n },\n )\n return () => {\n shown = false\n }\n }, [wanted, account, links])\n\n const connect = (offer: MailboxOffer) => auth!.linkPersonalMail(offer.link)\n if (!wanted) return { offers: [] as MailboxOffer[], connect }\n if (error) return { offers: [] as MailboxOffer[], error, connect }\n return { offers: linked && mailboxOffers(links, linked, problem), connect }\n}\n","import type { ActionModel } from '@protobase/schema'\nimport { MailboxConnect } from './mailbox-connect'\nimport { mailboxProblem } from './mailbox-problem'\nimport { useMailboxOffers } from './use-mailbox-offers'\n\n/**\n * The mailbox part of an action's dialog: for an action that sends from the person's own mailbox (`mailbox: true`),\n * an offer to connect one while none is linked; for any action whose run failed for want of a mailbox, or as its link\n * expired, the same offer for that. `notice` is the offer, which stands in for the failure's banner (`explained`), and\n * `blocked` keeps the action from running while the mailbox is checked or still needs connecting.\n */\nexport const useActionMailbox = (action: ActionModel, failure: unknown) => {\n const problem = mailboxProblem(failure)\n const check = action.mailbox === true\n const { offers, error, connect } = useMailboxOffers(problem, check)\n const offered = offers !== undefined && offers.length > 0\n const notice = offered ? (\n <MailboxConnect offers={offers} problem={problem} onConnect={connect} />\n ) : error ? (\n <p role=\"alert\" className=\"text-body font-medium text-danger-text\">\n {error}\n </p>\n ) : undefined\n return { notice, explained: problem !== undefined && offered, blocked: offered || (check && offers === undefined) }\n}\n","import type { ActionInputModel } from '@protobase/schema'\n\ntype Fields = Record<string, unknown>\n\n// The texts a record holds in a checklist's `from` field; anything but a list of texts holds none.\nconst ownBoxes = (input: ActionInputModel, record: Fields | undefined) => {\n const held = input.from === undefined ? undefined : record?.[input.from]\n return Array.isArray(held) ? held.filter((box): box is string => typeof box === 'string') : []\n}\n\n/** The boxes a checklist shows for the records an action runs on: its `items`, or each box their `from` field holds, once, in order. */\nexport const checklistBoxes = (input: ActionInputModel, records: Fields[]) => {\n if (input.items) return input.items\n return [...new Set(records.flatMap((record) => ownBoxes(input, record)))]\n}\n\n/**\n * The answers as `record` gets them: each checklist that shows answers the boxes this record holds, its `items` or its\n * own `from` boxes, every one ticked before the action runs.\n */\nexport const answersFor = (inputs: ActionInputModel[], values: Record<string, unknown>, record: Fields | undefined) =>\n Object.fromEntries(\n Object.entries(values).map(([name, value]) => {\n const input = inputs.find((entry) => entry.name === name)\n if (input?.kind !== 'checklist') return [name, value]\n return [name, input.items ?? ownBoxes(input, record)]\n }),\n )\n","import { Checkbox } from '../../../primitives/checkbox'\nimport { useFieldControl } from '../../../primitives/field-control'\nimport { text } from '../messages'\n\ntype ChecklistInputProps = { label: string; boxes: string[]; ticked: string[]; onChange: (ticked: string[]) => void }\n\n/**\n * A checklist's boxes, each ticked by its checkbox or its text, as a group named by its label and described by the help\n * and error of the `Field` around it; or a line saying there is nothing to tick.\n */\nexport const ChecklistInput = ({ label, boxes, ticked, onChange }: ChecklistInputProps) => {\n const { id, 'aria-describedby': describedBy, 'aria-invalid': invalid } = useFieldControl()\n if (boxes.length === 0) return <p className=\"text-sm text-muted-foreground\">{text('nothingToTick')}</p>\n const toggle = (box: string, on: boolean) => onChange(on ? [...ticked, box] : ticked.filter((entry) => entry !== box))\n return (\n <div id={id} role=\"group\" aria-label={label} aria-describedby={describedBy} aria-invalid={invalid}>\n <ul className=\"flex flex-col gap-1\">\n {boxes.map((box) => (\n <li key={box}>\n <label className=\"flex cursor-pointer items-start gap-3 rounded py-1.5 text-sm active:opacity-70\">\n <Checkbox checked={ticked.includes(box)} onChange={(on) => toggle(box, on)} className=\"mt-0.5\" />\n <span>{box}</span>\n </label>\n </li>\n ))}\n </ul>\n </div>\n )\n}\n","import type { CSSProperties } from 'react'\nimport { Input } from '../../../primitives/input'\n\n// csstype has no key for it; every current browser engine draws it.\nconst masked: CSSProperties & { WebkitTextSecurity: 'disc' } = { WebkitTextSecurity: 'disc' }\n\ntype SecretInputProps = { name: string; value: string; invalid: boolean; onChange: (value: string) => void }\n\n/**\n * A secret input's field. Not a password input: browsers offer to save the value of any password input, and some to\n * generate one. Instead a text input drawn as discs, so the value never shows on screen. `autocomplete=\"off\"` keeps it\n * out of the browser's form history and saved session, which keep a text input's value as they never do a password's.\n * Its type never changes at runtime, so no show/hide toggle: a browser may treat an input that was ever a password as\n * one. The data attributes ask password managers and writing assistants, in each one's documented words, to skip the\n * field, and the autocorrect ones keep keyboards out.\n */\nexport const SecretInput = ({ name, value, invalid, onChange }: SecretInputProps) => (\n <Input\n type=\"text\"\n name={name}\n autoComplete=\"off\"\n style={masked}\n autoCorrect=\"off\"\n autoCapitalize=\"off\"\n spellCheck={false}\n data-1p-ignore\n data-lpignore=\"true\"\n data-bwignore\n data-form-type=\"other\"\n data-gramm=\"false\"\n data-gramm_editor=\"false\"\n data-enable-grammarly=\"false\"\n value={value}\n invalid={invalid}\n onChange={(event) => onChange(event.target.value)}\n />\n)\n","import { ApiError, isApiError } from '@protobase/client'\nimport type { ActionInputModel } from '@protobase/schema'\n\nconst mask = '••••••'\n\n/** The answers of the secret inputs among `values`, those not empty. */\nexport const secretAnswers = (inputs: ActionInputModel[], values: Record<string, unknown>) =>\n inputs.flatMap((input) => {\n const value = values[input.name]\n return input.kind === 'secret' && typeof value === 'string' && value !== '' ? [value] : []\n })\n\n// Which characters of `text` belong to an occurrence of a secret, every occurrence found in the text as it is, overlaps included.\nconst covered = (text: string, secrets: string[]) => {\n const hidden = new Array<boolean>(text.length).fill(false)\n for (const secret of secrets) {\n for (let at = text.indexOf(secret); at !== -1; at = text.indexOf(secret, at + 1)) hidden.fill(true, at, at + secret.length)\n }\n return hidden\n}\n\n/** `text` with each run of characters that belongs to one of `secrets` replaced by discs, so overlapping secrets leave none of either showing. */\nexport const maskSecrets = (text: string, secrets: string[]) => {\n const hidden = covered(text, secrets.filter((secret) => secret !== ''))\n let masked = ''\n for (let index = 0; index < text.length; index++) {\n if (!hidden[index]) masked += text[index]\n else if (index === 0 || !hidden[index - 1]) masked += mask\n }\n return masked\n}\n\n/**\n * A failure as the dialog may show it: one whose message or problem holds a secret answer comes back with each masked,\n * so a handler that echoes the value never draws it on screen.\n */\nexport const maskedFailure = (error: unknown, secrets: string[]) => {\n if (secrets.length === 0) return error\n if (isApiError(error)) {\n // The problem is masked as JSON, where a secret appears in its escaped form.\n const escaped = secrets.map((secret) => JSON.stringify(secret).slice(1, -1))\n return new ApiError(JSON.parse(maskSecrets(JSON.stringify(error.problem), escaped)))\n }\n if (!(error instanceof Error)) return error\n const masked = new Error(maskSecrets(error.message, secrets))\n masked.name = error.name\n return masked\n}\n\n/** Messages by input name, each with the secret answers masked. */\nexport const maskedMessages = (messages: Record<string, string>, secrets: string[]) =>\n Object.fromEntries(Object.entries(messages).map(([name, message]) => [name, maskSecrets(message, secrets)]))\n","import { shownInputs } from '@protobase/schema/internal'\nimport type { ActionInputModel, FieldModel, FieldType, FieldViewModel } from '@protobase/schema'\nimport { toDraft, toPatchValue } from '../../../live/field-values'\nimport { isChosen, type Draft } from '../../create/create-values'\nimport { text } from '../messages'\n\nconst fieldTypes: Record<Exclude<ActionInputModel['kind'], 'choice' | 'checklist' | 'custom'>, FieldType> = { text: 'text', integer: 'integer', decimal: 'decimal', boolean: 'boolean', date: 'date', secret: 'text' }\n\n/** The field an input is edited as, so the create form's editors edit it: a choice of options is an enum, of records a relation. */\nexport const inputField = (input: ActionInputModel): FieldModel => {\n const base = { name: input.name, column: input.name, nullable: true, readOnly: false, filterable: false, sortable: false, aliases: [] }\n if (input.kind === 'custom' || input.kind === 'checklist') return { ...base, type: 'json' }\n if (input.kind !== 'choice') return { ...base, type: fieldTypes[input.kind] }\n if (input.resource !== undefined) return { ...base, type: 'relation', relation: { resource: input.resource, columns: [input.name] } }\n return { ...base, type: 'enum', enumValues: (input.options ?? []).map((option) => option.value) }\n}\n\n/** The view hints an input's editor reads: its label, a box that grows for a multiline text, a choice's labels. */\nexport const inputHints = (input: ActionInputModel): FieldViewModel => ({\n label: input.label,\n ...(input.multiline && { multiline: true }),\n ...(input.options && { valueLabels: Object.fromEntries(input.options.map((option) => [option.value, option.label])) }),\n})\n\n/** What each input holds when the dialog opens: its default, as its editor holds it. */\nexport const startingAnswers = (inputs: ActionInputModel[]): Draft =>\n Object.fromEntries(\n inputs.map((input) => {\n if (input.kind === 'custom') return [input.name, input.default ?? null]\n if (input.kind === 'checklist') return [input.name, []]\n if (input.kind === 'boolean') return [input.name, Boolean(input.default)]\n return [input.name, toDraft(input.default)]\n }),\n )\n\n// An answer as the handler gets it: null when empty, a number for an integer, a chosen record's key, a checklist's ticked boxes, a secret as typed.\nconst answerOf = (input: ActionInputModel, held: unknown) => {\n if (input.kind === 'custom') return held ?? null\n if (input.kind === 'checklist') return Array.isArray(held) ? held : []\n // A secret goes to the handler exactly as typed, never trimmed.\n if (input.kind === 'secret') return typeof held === 'string' && held !== '' ? held : null\n if (isChosen(held)) return held.key\n // A record's key given as the default, before anything is picked.\n if (input.resource !== undefined) return String(held ?? '') === '' ? null : String(held)\n return toPatchValue(inputField(input), held)\n}\n\n/** The answers of the inputs that show, as the handler gets them in `values`, and the names of those that show. */\nexport const answeredValues = (inputs: ActionInputModel[], draft: Draft) => {\n const all = Object.fromEntries(inputs.map((input) => [input.name, answerOf(input, draft[input.name])]))\n const shown = shownInputs(inputs, all)\n return { shown, values: Object.fromEntries(Object.entries(all).filter(([name]) => shown.has(name))) }\n}\n\nconst decimal = /^-?\\d+(\\.\\d+)?$/\nconst date = /^\\d{4}-\\d{2}-\\d{2}$/\n\n// Why an answer is refused before the action runs, if it is; a checklist's while one of its `boxes` is not ticked.\nconst refusal = (input: ActionInputModel, value: unknown, boxes: string[]) => {\n if (input.kind === 'checklist') {\n const left = boxes.filter((box) => !(Array.isArray(value) && value.includes(box))).length\n return left === 0 ? undefined : text('tickEvery', { count: left })\n }\n if (value === null || value === '') return input.required ? text('required') : undefined\n if (input.kind === 'integer' && !Number.isInteger(value)) return text('wholeNumber')\n if (input.kind === 'decimal' && !decimal.test(String(value))) return text('number')\n if (input.kind === 'date' && !date.test(String(value))) return text('dateFormat')\n if (input.max !== undefined && String(value).length > input.max) return text('atMost', { max: input.max })\n return undefined\n}\n\n/**\n * What is wrong with the answers that show, by input name: one left empty that is required, a number that is none, a\n * text too long, a checklist with a box of `boxes` (by input name) left unticked.\n */\nexport const refusedAnswers = (inputs: ActionInputModel[], values: Record<string, unknown>, boxes: Record<string, string[]> = {}) =>\n Object.fromEntries(\n inputs.flatMap((input) => {\n if (!Object.hasOwn(values, input.name)) return []\n const reason = refusal(input, values[input.name], boxes[input.name] ?? [])\n return reason ? [[input.name, reason]] : []\n }),\n )\n","import { useId, useState, type ComponentType } from 'react'\nimport type { ActionInputModel, ActionModel, JsonValue } from '@protobase/schema'\nimport { Button } from '../../../primitives/button'\nimport { ResponsiveDialog } from '../../../primitives/responsive-dialog'\nimport { Field } from '../../../record-view'\nimport { isChosen, type Draft } from '../../create/create-values'\nimport { ErrorBanner } from '../../error-banner'\nimport { FieldEditor } from '../../field-editor'\nimport { useAdminMeta } from '../../meta-gate'\nimport { useActionMailbox } from '../../../mailbox/use-action-mailbox'\nimport { useProjectUi } from '../project-ui'\nimport { checklistBoxes } from './checklist-boxes'\nimport { ChecklistInput } from './checklist-input'\nimport { SecretInput } from './secret-input'\nimport { maskedFailure, maskedMessages, secretAnswers } from './secret-mask'\nimport { answeredValues, inputField, inputHints, refusedAnswers, startingAnswers } from './input-answers'\nimport { inputErrors } from './input-errors'\nimport { text } from '../messages'\n\n/** What a custom input's component gets, as a field type's editor does: the answer, a way to set it, whether it is refused, and `props`. */\nexport type ActionInputProps<V = unknown, P = Record<string, JsonValue>> = {\n /** The input, as the action declares it. */\n input: ActionInputModel\n value: V | null\n onChange: (value: V | null) => void\n invalid: boolean\n /** What the input gives in `props`; `{}` without. */\n props: P\n}\n\ntype InputEditorProps = { input: ActionInputModel; held: unknown; invalid: boolean; onChange: (value: unknown) => void; boxes: string[] }\n\nconst InputEditor = ({ input, held, invalid, onChange, boxes }: InputEditorProps) => {\n const { resources, views } = useAdminMeta()\n const { components } = useProjectUi()\n if (input.kind === 'custom') {\n const Custom = components?.[input.component ?? ''] as ComponentType<ActionInputProps> | undefined\n if (!Custom) throw new Error(`Input \"${input.name}\": the app has no component \"${input.component}\"`)\n return <Custom input={input} value={held ?? null} onChange={onChange} invalid={invalid} props={input.props ?? {}} />\n }\n if (input.kind === 'checklist') return <ChecklistInput label={input.label} boxes={boxes} ticked={Array.isArray(held) ? (held as string[]) : []} onChange={onChange} />\n if (input.kind === 'secret') return <SecretInput name={input.name} value={typeof held === 'string' ? held : ''} invalid={invalid} onChange={onChange} />\n const target = input.resource === undefined ? undefined : resources[input.resource]\n return (\n <FieldEditor\n field={inputField(input)}\n hints={inputHints(input)}\n value={isChosen(held) ? held.key : held}\n stored={undefined}\n relationLabel={isChosen(held) ? held.label : undefined}\n relationPicker={target ? { target, view: views[target.name] } : undefined}\n invalid={invalid}\n onChange={onChange}\n />\n )\n}\n\ntype ActionInputsDialogProps = {\n action: ActionModel & { inputs: ActionInputModel[] }\n label: string\n danger?: boolean\n /** The records it runs on, whose `from` fields hold a checklist's boxes. */\n records?: Array<Record<string, unknown>>\n /** The titles of the records, named above the inputs when it runs on several. */\n names?: string[]\n onCancel: () => void\n /** Runs the action with the answers; a failure it throws keeps the dialog open, its messages under their inputs. */\n onSubmit: (values: Record<string, unknown>) => Promise<void>\n}\n\n/** The dialog an action with inputs opens: the inputs that show, edited as on the create form, and the action's button. */\nexport const ActionInputsDialog = ({ action, label, danger, records = [], names = [], onCancel, onSubmit }: ActionInputsDialogProps) => {\n const [draft, setDraft] = useState<Draft>(() => startingAnswers(action.inputs))\n const [errors, setErrors] = useState<Record<string, string>>({})\n const [failure, setFailure] = useState<unknown>()\n const [running, setRunning] = useState(false)\n const formId = useId()\n const { shown, values } = answeredValues(action.inputs, draft)\n const mailbox = useActionMailbox(action, failure)\n const boxes = Object.fromEntries(action.inputs.filter((input) => input.kind === 'checklist').map((input) => [input.name, checklistBoxes(input, records)]))\n\n const submit = async () => {\n const refused = refusedAnswers(action.inputs, values, boxes)\n setErrors(refused)\n setFailure(undefined)\n if (Object.keys(refused).length > 0 || mailbox.blocked) return\n setRunning(true)\n // A handler that echoes a secret answer in its failure has it masked before the dialog draws it.\n const secrets = secretAnswers(action.inputs, values)\n await onSubmit(values).catch((error: unknown) => {\n setErrors(maskedMessages(inputErrors(error, action.inputs), secrets))\n setFailure(maskedFailure(error, secrets))\n })\n setRunning(false)\n }\n\n const change = (name: string, value: unknown) => {\n setErrors(({ [name]: _, ...rest }) => rest)\n setDraft((current) => ({ ...current, [name]: value }))\n }\n\n return (\n <ResponsiveDialog\n title={label}\n description={action.confirm}\n open\n onClose={onCancel}\n actions={\n <>\n <Button onClick={onCancel}>{text('cancel')}</Button>\n <Button variant={danger ? 'danger' : 'primary'} type=\"submit\" form={formId} loading={running} disabled={mailbox.blocked}>\n {label}\n </Button>\n </>\n }\n >\n <form\n id={formId}\n className=\"flex flex-col gap-4\"\n onSubmit={(event) => {\n event.preventDefault()\n void submit()\n }}\n >\n {failure !== undefined && Object.keys(errors).length === 0 && !mailbox.explained && <ErrorBanner title={text('failed', { label })} error={failure} />}\n {mailbox.notice}\n {names.length > 1 && <p className=\"text-sm\">{text('forRecords', { records: names.join(', ') })}</p>}\n {action.inputs\n .filter((input) => shown.has(input.name))\n .map((input) => (\n <Field key={input.name} label={input.label} required={input.required} help={input.help} error={errors[input.name]}>\n <InputEditor input={input} held={draft[input.name]} invalid={Boolean(errors[input.name])} onChange={(next) => change(input.name, next)} boxes={boxes[input.name] ?? []} />\n </Field>\n ))}\n </form>\n </ResponsiveDialog>\n )\n}\n","import type { ActionModel } from '@protobase/schema'\nimport { Button } from '../../primitives/button'\nimport { Dialog } from '../../primitives/dialog'\nimport { useActionMailbox } from '../../mailbox/use-action-mailbox'\nimport { text } from './messages'\n\n/** The question an action with `confirm` asks before it runs; one that sends from the person's mailbox offers to connect it first while none is linked. */\nexport const ConfirmAction = ({ action, label, danger, onCancel, onConfirm }: { action: ActionModel; label: string; danger?: boolean; onCancel: () => void; onConfirm: () => void }) => {\n const mailbox = useActionMailbox(action, undefined)\n return (\n <Dialog\n title={`${label}?`}\n description={action.confirm}\n onClose={onCancel}\n actions={\n <>\n <Button onClick={onCancel}>{text('cancel')}</Button>\n <Button variant={danger ? 'danger' : 'primary'} disabled={mailbox.blocked} onClick={onConfirm}>\n {label}\n </Button>\n </>\n }\n >\n {mailbox.notice}\n </Dialog>\n )\n}\n","import type { ActionModel } from '@protobase/schema'\nimport { ActionInputsDialog } from './action-inputs/action-inputs-dialog'\nimport { ConfirmAction } from './confirm-action'\n\n/** Whether the action is drawn in red, as one that destroys or interrupts something: a delete, or one with `variant: 'danger'`. */\nexport const isDanger = (action: ActionModel) => action.variant === 'danger' || action.run?.kind === 'delete'\n\n/** Whether pressing the action's button opens a dialog first: to ask its question, or for its inputs. */\nexport const asksFirst = (action: ActionModel) => Boolean(action.confirm || action.inputs?.length)\n\ntype ActionPromptProps = {\n action: ActionModel\n label: string\n danger?: boolean\n /** The records it runs on, whose fields a checklist may take its boxes from. */\n records?: Array<Record<string, unknown>>\n /** Their titles, which a dialog for several names. */\n names?: string[]\n onCancel: () => void\n /** Runs an action without inputs once its question is answered. */\n onConfirm: () => void\n /** Runs it with the answers to its inputs, throwing its failure for the dialog to show. */\n onSubmit: (values: Record<string, unknown>) => Promise<void>\n}\n\n/** The dialog an action that asks first opens: its inputs, or else its question. */\nexport const ActionPrompt = ({ action, label, danger, records, names, onCancel, onConfirm, onSubmit }: ActionPromptProps) => {\n const { inputs } = action\n if (inputs?.length) return <ActionInputsDialog action={{ ...action, inputs }} label={label} danger={danger} records={records} names={names} onCancel={onCancel} onSubmit={onSubmit} />\n return <ConfirmAction action={action} label={label} danger={danger} onCancel={onCancel} onConfirm={onConfirm} />\n}\n","import { AuthError } from '@protobase/client'\nimport { authMessage } from '../auth/auth-messages'\nimport { useOptionalAuth } from '../auth/auth-provider'\nimport { useToast, type ToastAction } from '../toasts'\nimport { mailboxProblem } from './mailbox-problem'\nimport { text } from './messages'\n\n/**\n * For the toast of a failure: a button that connects the mailbox when the failure was for want of one, or as its link\n * expired, starting the same sign-in as the account page's, which comes back to this page. None for any other failure,\n * or when the app has no mailbox the failure points at.\n */\nexport const useMailboxToastAction = () => {\n const auth = useOptionalAuth()\n const toast = useToast()\n return (error: unknown): ToastAction | undefined => {\n const problem = mailboxProblem(error)\n const links = auth?.personalMail ?? []\n if (!auth || !problem) return\n const link = links.find((entry) => entry.id === problem.provider) ?? (links.length === 1 ? links[0] : undefined)\n if (!link) return\n const connect = async () => {\n try {\n await auth.linkPersonalMail(link)\n } catch (failure) {\n if (!(failure instanceof AuthError)) throw failure\n toast.show({ state: 'error', title: text('connect', { name: link.name }), description: authMessage(failure) })\n }\n }\n return { label: text(problem.code === 'link_expired' ? 'connectAgain' : 'connect', { name: link.name }), onClick: () => void connect() }\n }\n}\n","import { evaluateCondition, parseCondition } from '@protobase/layout'\nimport type { ActionModel } from '@protobase/schema'\n\n/**\n * Whether `action` applies to `record`: always without a `when`, else when its condition holds for the record's own\n * fields. With a `when` there is nothing to apply to without a record, and a condition that does not parse never holds.\n */\nexport const actionApplies = (action: ActionModel, record: Record<string, unknown> | undefined) => {\n if (action.when === undefined) return true\n if (!record) return false\n const condition = parseCondition(action.when)\n return condition.ok && evaluateCondition(condition, record)\n}\n","import type { ActionModel } from '@protobase/schema'\nimport { fillAddress, fillText, hostPlaceholder, hrefField, recordValueAt, resourceField, valueText } from '@protobase/schema/internal'\nimport { actionApplies } from './action-when'\n\n/** `href` with every `{{path}}` replaced by the record's value, percent-encoded; a missing value becomes empty. */\nexport const fillHref = (href: string, record: Record<string, unknown> = {}) => fillText(href, (path) => encodeURIComponent(valueText(recordValueAt(record, path))))\n\nconst webUrl = (value: unknown) => {\n if (typeof value !== 'string' || !URL.canParse(value)) return undefined\n const url = new URL(value)\n return url.protocol === 'https:' || url.protocol === 'http:' ? url.href : undefined\n}\n\n/**\n * Where a link action's `href` goes from `record`: an href that is only `{field}` is the record's value as it is, when\n * that is an `https:` or `http:` URL, and nothing otherwise; any other href is filled by `fillHref`.\n */\nexport const linkTarget = (href: string, record: Record<string, unknown> = {}) => {\n const field = hrefField(href)\n return field === undefined ? fillHref(href, record) : webUrl(recordValueAt(record, field))\n}\n\n/**\n * Opens a link's target: an `https:` or `http:` page in a new tab that gets neither the app's window nor its address,\n * anything else (`mailto:`) in place. A link without a target does nothing.\n */\nexport const openLink = (target: string | undefined) => {\n if (target === undefined) return\n if (/^https?:/i.test(target)) window.open(target, '_blank', 'noopener,noreferrer')\n else window.location.assign(target)\n}\n\nconst hostOf = (target: string) => (URL.canParse(target) ? new URL(target).hostname.replace(/^www\\./, '') : '')\n\n// An update sets values the record may hold already, as `paid: true` on a paid order.\nconst holdsAll = (record: Record<string, unknown>, values: Record<string, unknown>) => Object.entries(values).every(([name, value]) => Object.is(record[name], value))\n\n/**\n * `action` as it shows for `record`: one whose `when` does not hold there is left out, or shown as it is when it\n * disables instead; an update that would change nothing there, a link whose `href` has no target there, and a link\n * whose resource the record names but `resources` (the caller's, from `/meta`) lacks, are left out, and `{{host}}` in a\n * link's label becomes the host its target opens, without `www.`.\n */\nexport const actionFor = (action: ActionModel, record: Record<string, unknown> | undefined, resources: Readonly<Record<string, unknown>> = {}): ActionModel | undefined => {\n if (!actionApplies(action, record)) return action.otherwise === 'disable' ? action : undefined\n const run = action.run\n if (run?.kind === 'update') return record && !action.inputs?.length && holdsAll(record, run.values as Record<string, unknown>) ? undefined : action\n if (run?.kind === 'link' && 'to' in run && resourceField(run.to) !== undefined) {\n const to = fillAddress(run.to, record)\n return to.kind !== 'page' && Object.hasOwn(resources, to.resource) ? action : undefined\n }\n if (run?.kind !== 'link' || !('href' in run)) return action\n const target = linkTarget(run.href, record)\n if (target === undefined) return undefined\n return action.label.includes(hostPlaceholder) ? { ...action, label: action.label.replaceAll(hostPlaceholder, hostOf(target)) } : action\n}\n","/** What a run over several records does with one: runs on it, skips it as one it does not apply to, or refuses it as one the person may not change. */\nexport type EachVerdict = 'run' | 'skip' | 'refuse'\n\n/**\n * How a run over several records went: how many it ran on, skipped as not applying and failed on, with the first\n * failure, and the records it refused, before running or because the run was refused.\n */\nexport type EachOutcome<T> = { done: number; skipped: number; failed: number; refused: T[]; error?: unknown }\n\n/**\n * Runs `run` on each of `records` its `verdict` runs, one after another, so a failure on one leaves the others to run:\n * a failure `refusal` says is a refusal joins the refused records, any other is counted and the first kept for the\n * caller to show.\n */\nexport const runEach = async <T>(records: T[], verdict: (record: T) => EachVerdict, run: (record: T) => Promise<void>, refusal: (error: unknown) => boolean): Promise<EachOutcome<T>> => {\n const verdicts = records.map((record) => ({ record, verdict: verdict(record) }))\n const outcome: EachOutcome<T> = {\n done: 0,\n skipped: verdicts.filter((entry) => entry.verdict === 'skip').length,\n failed: 0,\n refused: verdicts.flatMap((entry) => (entry.verdict === 'refuse' ? [entry.record] : [])),\n }\n for (const { record } of verdicts.filter((entry) => entry.verdict === 'run')) {\n const failure = await run(record).then(\n () => undefined,\n (error: unknown) => ({ error }),\n )\n if (!failure) outcome.done += 1\n else if (refusal(failure.error)) outcome.refused.push(record)\n else {\n outcome.failed += 1\n if (outcome.failed === 1) outcome.error = failure.error\n }\n }\n return outcome\n}\n","import { useState } from 'react'\nimport { ApiError } from '@protobase/client'\nimport type { ActionModel } from '@protobase/schema'\nimport { fillAddress, updateValues } from '@protobase/schema/internal'\nimport { useClient, useResourceClient } from '../../data/api-provider'\nimport { useMailboxToastAction } from '../../mailbox/use-mailbox-toast-action'\nimport { useToast } from '../../toasts'\nimport { useAdminMeta, usePermissions } from '../meta-gate'\nimport { can } from '../permissions'\nimport { useAppAddress } from '../use-app-address'\nimport { actionFor, linkTarget, openLink } from './action-href'\nimport { actionApplies } from './action-when'\nimport { useProjectUi } from './project-ui'\nimport type { LayoutRecord } from './record-scope'\nimport { runEach, type EachVerdict } from './run-each'\nimport { answersFor } from './action-inputs/checklist-boxes'\nimport { maskSecrets, secretAnswers } from './action-inputs/secret-mask'\nimport { useRecordTitle } from '../titles/record-titles'\nimport { useRefreshResource } from './use-layout-data'\nimport { text } from './messages'\n\n/** A record's title, quoted, to name it inside a sentence. */\nexport const quoted = (title: string) => `“${title}”`\n\nconst message = (error: unknown) => (error instanceof Error ? error.message : text('somethingWrong'))\n\n/**\n * The named actions of `resource`'s view, ready to run on `scope` (the record they act on): built-in behaviour first\n * (`update`, `delete`, `link`, and `ai`, which the server runs), else the handler the project registered under the\n * action's name. One whose `when` does not hold for the record is left out, or blocked with its `reason`; an update\n * whose values the record holds already is left out, and so is a link to a URL the record holds while it holds none.\n * `blocked` says why one cannot run; `afterRun` hears about every action that succeeded.\n * `submit` runs one with the answers to its inputs (a handler gets them, an update writes them) and throws its failure, for the dialog to show.\n * `runEach` runs one on each of several records it applies to, as a list's selection does, with the answers to its inputs\n * as each record gets them, and says how that went, naming the records the person may not change; it resolves to its outcome.\n */\nexport const useActionRunner = (resource: string, scope: LayoutRecord | undefined, afterRun?: (action: ActionModel) => void) => {\n const { views, resources } = useAdminMeta()\n const { actions: handlers, components } = useProjectUi()\n const permissions = usePermissions(resource)\n const client = useClient()\n // A handler works on the API that serves the resource, functions included: a source's for one drawn from it.\n const handlerClient = useResourceClient(resource)\n const toast = useToast()\n const mailboxAction = useMailboxToastAction()\n const refresh = useRefreshResource()\n const { go } = useAppAddress()\n const titleOf = useRecordTitle()\n const [running, setRunning] = useState<string>()\n // An update shows only while it would change the record, a link to a URL the record holds only while it holds one, its label naming the URL's host\n const actions = (views[resource]?.actions ?? []).flatMap((action) => actionFor(action, scope?.record, resources) ?? [])\n\n // Why `action` cannot run on `on`, the record it would act on.\n const blockedOn = (action: ActionModel, on: LayoutRecord | undefined) => {\n const kind = action.run?.kind\n if ((kind === 'update' || kind === 'delete' || kind === 'ai') && !on) return text('needsRecord')\n if (!actionApplies(action, on?.record)) return action.reason ?? text('doesNotApply')\n if ((kind === 'update' || kind === 'ai') && (!can(permissions, 'update') || on?.permissions?.update === false)) return text('cannotChange')\n if (action.run?.kind === 'ai' && on?.permissions?.fields?.[action.run.writes] === 'read') return text('cannotChange')\n if (kind === 'delete' && (!can(permissions, 'delete') || on?.permissions?.delete === false)) return text('cannotDelete')\n if (!action.run && !handlers?.[action.name]) return text('noHandler', { name: action.name })\n const custom = action.inputs?.find((input) => input.kind === 'custom' && !components?.[input.component ?? ''])\n if (custom) return text('noInputComponent', { component: String(custom.component), input: custom.name })\n return undefined\n }\n const blocked = (action: ActionModel) => blockedOn(action, scope)\n\n // Whether the person may change this record, though they may change others of the resource: its own permissions say no.\n const refusedOn = (action: ActionModel, on: LayoutRecord) => {\n const { run } = action\n const kind = run?.kind\n if (kind === 'update' || kind === 'ai') return can(permissions, 'update') && (on.permissions?.update === false || (run?.kind === 'ai' && on.permissions?.fields?.[run.writes] === 'read'))\n if (kind === 'delete') return can(permissions, 'delete') && on.permissions?.delete === false\n return false\n }\n\n // Runs the action on `on`, without telling the user how it went.\n const execute = async (action: ActionModel, on: LayoutRecord | undefined, values?: Record<string, unknown>) => {\n const { run } = action\n if (run?.kind === 'link') {\n if ('to' in run) go(fillAddress(run.to, on?.record))\n else openLink(linkTarget(run.href, on?.record))\n return\n }\n if (run?.kind === 'update') await client.update(resource, on!.key, updateValues(run.values as Record<string, unknown>, values ?? {}), on!.etag ?? '*')\n else if (run?.kind === 'delete') await client.remove(resource, on!.key, { etag: on!.etag })\n else if (run?.kind === 'ai') await client.generate(resource, on!.key, action.name)\n else await handlers![action.name]!({ resource, record: on?.record, recordKey: on?.key, etag: on?.etag, client: handlerClient, navigate: go, ...(values && { values }) })\n }\n\n const perform = async (action: ActionModel, on: LayoutRecord | undefined, values?: Record<string, unknown>) => {\n await execute(action, on, values)\n if (action.run?.kind === 'link') return\n await refresh(resource)\n toast.show({ state: 'success', title: text('done', { label: action.label }) })\n afterRun?.(action)\n }\n\n // `on` is another record than the scope's, such as a list's row. A failure for want of a mailbox offers to connect one.\n const run = async (action: ActionModel, on = scope) => {\n if (blockedOn(action, on)) return\n setRunning(action.name)\n await perform(action, on).catch((error: unknown) => {\n const connect = mailboxAction(error)\n toast.show({ state: 'error', title: text('failed', { label: action.label }), description: message(error), ...(connect && { action: connect }) })\n })\n setRunning(undefined)\n }\n\n // An action with inputs runs from its dialog, which shows a failure under the inputs it is about instead of a toast.\n const submit = async (action: ActionModel, values: Record<string, unknown>) => {\n if (blocked(action)) return\n setRunning(action.name)\n await perform(action, scope, answersFor(action.inputs ?? [], values, scope?.record)).finally(() => setRunning(undefined))\n }\n\n /** Whether `action` shows and can run on `on`. */\n const appliesOn = (action: ActionModel, on: LayoutRecord) => actionFor(action, on.record, resources) !== undefined && !blockedOn(action, on)\n\n /** What a run over several records does with `on`: runs on it, refuses it as one the person may not change, or skips it. */\n const verdictOn = (action: ActionModel, on: LayoutRecord): EachVerdict => {\n if (appliesOn(action, on)) return 'run'\n const shows = actionFor(action, on.record, resources) !== undefined && actionApplies(action, on.record)\n return shows && refusedOn(action, on) ? 'refuse' : 'skip'\n }\n\n // A failure on one record leaves the others to run; the toast counts them, with the first failure's message, its secret answers masked, and\n // the records the caller left out already as not applying (`skipped`), and names those the person may not change,\n // refused here or by the API.\n const runOnEach = async (action: ActionModel, records: LayoutRecord[], skipped = 0, values?: Record<string, unknown>) => {\n setRunning(action.name)\n const answers = (on: LayoutRecord) => (values ? answersFor(action.inputs ?? [], values, on.record) : undefined)\n const refusal = (error: unknown) => error instanceof ApiError && error.status === 403\n const outcome = await runEach(records, (on) => verdictOn(action, on), (on) => execute(action, on, answers(on)), refusal)\n setRunning(undefined)\n await refresh(resource)\n const refused = outcome.refused.map((on) => quoted(titleOf(on.model, views[resource], on.record, on.key)))\n const title = text('doneOn', { label: action.label, done: outcome.done, skipped: outcome.skipped + skipped, failed: outcome.failed, refused: refused.length })\n const description = [refused.length > 0 && text('refusedOn', { records: refused.join(', '), count: refused.length }), outcome.failed > 0 && maskSecrets(message(outcome.error), secretAnswers(action.inputs ?? [], values ?? {}))].filter(Boolean).join(' ')\n toast.show({ state: outcome.failed > 0 || refused.length > 0 ? 'error' : 'success', title, ...(description && { description }) })\n if (outcome.done > 0) afterRun?.(action)\n return outcome\n }\n\n return { actions, blocked, blockedOn, appliesOn, verdictOn, running, run, submit, runEach: runOnEach }\n}\n\n/** One named action of `resource`'s view, for a button; `afterRun` hears when it succeeded. */\nexport const useRunAction = (resource: string, name: string, scope: LayoutRecord | undefined, afterRun?: (action: ActionModel) => void) => {\n const runner = useActionRunner(resource, scope, afterRun)\n const action = runner.actions.find((entry) => entry.name === name)\n return {\n action,\n /** The record it acts on, when it acts on one. */\n record: scope?.record,\n blocked: action ? runner.blocked(action) : text('noAction', { name }),\n running: runner.running === name,\n run: () => (action ? runner.run(action) : Promise.resolve()),\n submit: (values: Record<string, unknown>) => (action ? runner.submit(action, values) : Promise.resolve()),\n }\n}\n","import { messages } from '../locale/messages'\n\nexport const text = messages('app/list')\n","import { messages } from '../../locale/messages'\n\nexport const text = messages('app/charts')\n","import type { AggregateGroup } from '@protobase/client'\nimport { createWhere, enumLabel, printFilter, type FieldModel, type FieldViewModel } from '@protobase/schema'\nimport { formatTag } from '../../locale/active-locale'\nimport { valueColor } from '../../live/value-color'\nimport { text as message } from './messages'\n\nconst where = createWhere()\n\n/** How many fixed colours a chart has, `--chart-1` to `--chart-8`; more values than that share a neutral one. */\nexport const seriesColors = 8\n\n/** What a chart adds up per group: how many records, or the sum, average or maximum of a numeric field. */\nexport type ChartMeasure = { kind: 'count' } | { kind: 'sum' | 'average' | 'maximum'; field: FieldModel; hints?: FieldViewModel }\n\n/** One group as a chart draws it: its name, its number, its colour, and the filter that lists its records. */\nexport type ChartSlice = { key: string; label: string; value: number | null; count: number; color: string; filter: string }\n\nconst slot = (index: number) => (index >= 0 && index < seriesColors ? `var(--chart-${index + 1})` : 'var(--faint-foreground)')\n\n// A colour follows its value, never its rank: an enum's by its place among the values, a boolean's by true and false.\n// Other values have no fixed order, so they take the colours in the order the groups come.\nexport const colorOf = (field: FieldModel, hints: FieldViewModel | undefined, value: AggregateGroup['value'], index: number) => {\n const key = String(value)\n if (value === null) return 'var(--faint-foreground)'\n const color = valueColor(hints?.valueColors, value)\n if (color !== undefined) return color\n if (field.type === 'enum') return slot(field.enumValues?.indexOf(key) ?? -1)\n if (field.type === 'boolean') return slot(value ? 0 : 1)\n return slot(index)\n}\n\nexport const labelOf = (field: FieldModel, hints: FieldViewModel | undefined, group: Pick<AggregateGroup, 'value' | 'label'>) => {\n if (group.value === null) return message('notSet')\n if (field.type === 'enum') return enumLabel(String(group.value), hints?.valueLabels)\n if (field.type === 'boolean') return group.value ? message('yes') : message('no')\n return group.label ?? String(group.value)\n}\n\n/** The records of one group: the chart's own filter and the group's value. */\nexport const groupFilter = (field: FieldModel, value: AggregateGroup['value'], filter = '') => {\n const own = printFilter(value === null ? where.isNull(field.name) : where.eq(field.name, value as never))\n return filter.trim() ? `(${filter}) AND ${own}` : own\n}\n\nconst measured = (group: AggregateGroup, measure: ChartMeasure) => (measure.kind === 'count' ? group.count : (group[measure.kind] ?? null))\n\n/** The groups of a field of values as slices, in the order the API ranks them. */\nexport const valueSlices = (groups: AggregateGroup[], field: FieldModel, hints: FieldViewModel | undefined, measure: ChartMeasure, filter = ''): ChartSlice[] =>\n groups.map((group, index) => ({\n key: String(group.value),\n label: labelOf(field, hints, group),\n value: measured(group, measure),\n count: group.count,\n color: colorOf(field, hints, group.value, index),\n filter: groupFilter(field, group.value, filter),\n }))\n\n/** A date field's buckets as points in time, the bucket's start read as UTC as the list's chart reads it. */\nexport const periodPoints = (groups: AggregateGroup[], measure: ChartMeasure) =>\n groups.map((group) => ({ at: Date.parse(`${String(group.value)}Z`), value: measured(group, measure), count: group.count }))\n\n/** A measured number as text: a count whole, a sum, average or maximum with the field's decimals, prefix and suffix. */\nexport const measureText = (value: number | null, measure: ChartMeasure) => {\n if (value === null) return '—'\n if (measure.kind === 'count') return value.toLocaleString(formatTag())\n const decimals = measure.hints?.decimals ?? (Number.isInteger(value) ? 0 : 2)\n const text = value.toLocaleString(formatTag(), { minimumFractionDigits: decimals, maximumFractionDigits: decimals })\n return `${measure.hints?.prefix ?? ''}${text}${measure.hints?.suffix ?? ''}`\n}\n","import type { AggregateParams } from '@protobase/client'\nimport type { ChartProps } from '@protobase/layout'\nimport type { FieldModel, ResourceModel, ViewModel } from '@protobase/schema'\nimport { viewerZone } from '../../format/zone'\nimport { labelFieldOf } from '../../live/model-helpers'\nimport { seriesColors } from './chart-groups'\n\n// For a relation to a single-key resource: the field of that resource that names each of its records\nconst labelOf = (field: FieldModel | undefined, resources: Record<string, ResourceModel>, views: Record<string, ViewModel>) => {\n const target = field?.type === 'relation' && field.relation ? resources[field.relation.resource] : undefined\n return target && target.primaryKey.length === 1 ? labelFieldOf(target, views[target.name]) : undefined\n}\n\ntype ChartAsked = { model: ResourceModel } & Pick<ChartProps, 'groupBy' | 'splitBy' | 'sum' | 'average' | 'filter' | 'granularity' | 'range' | 'limit'>\n\n/**\n * The `:aggregate` a chart reads: a date field's buckets in the viewer's time zone, split by `splitBy`, or a field's\n * first `limit` values, named by the records a relation points at; `undefined` for a field the model lacks.\n */\nexport const chartAggregate = ({ model, groupBy, splitBy, sum, average, filter = '', granularity = 'day', range = '30d', limit = 10 }: ChartAsked, resources: Record<string, ResourceModel>, views: Record<string, ViewModel>): AggregateParams | undefined => {\n const field = model.fields[groupBy]\n if (!field) return\n const dated = field.type === 'date' || field.type === 'timestamp'\n const label = labelOf(field, resources, views)\n const splitField = dated && splitBy !== undefined ? model.fields[splitBy] : undefined\n const splitLabel = labelOf(splitField, resources, views)\n // A timestamp's buckets are the viewer's days, hours and months; a date's are its own\n const split = splitField ? { splitBy: splitField.name, splitLimit: seriesColors, ...(splitLabel && { splitLabel }) } : {}\n const params = dated ? { granularity, range, timeZone: viewerZone(), ...split } : { limit, ...(label && { label }) }\n return { groupBy, filter, ...(sum && { sum }), ...(average && { average }), ...params }\n}\n","import type { AppAddress, ViewModel } from '@protobase/schema'\n\n/**\n * The list of `resource` opened on exactly the records `filter` counted or showed: with no filter, an empty one when\n * the view's list opens on a default filter, so the link does not narrow what it counted; otherwise a clean path.\n */\nexport const filteredListAddress = (view: ViewModel | undefined, resource: string, filter: string | undefined): AppAddress => {\n if (filter) return { kind: 'list', resource, filter }\n if (view?.list?.filter) return { kind: 'list', resource, filter: '' }\n return { kind: 'list', resource }\n}\n","import type { ViewModel } from '@protobase/schema'\nimport { filteredListAddress } from '../list-link'\nimport { AppLink } from '../use-app-address'\nimport { measureText, type ChartMeasure, type ChartSlice } from './chart-groups'\nimport { text } from './messages'\n\n/**\n * A ranked list of a field's values, each a bar as long as its number and a link to its records. Bars in rows read on\n * a phone as well as on a desk, and carry their label and value as text, so no colour has to say what a bar is.\n */\nexport const GroupBars = ({ resource, view, slices, measure }: { resource: string; view: ViewModel | undefined; slices: ChartSlice[]; measure: ChartMeasure }) => {\n const largest = Math.max(0, ...slices.map((slice) => slice.value ?? 0))\n return (\n <ul className=\"flex flex-col gap-1\">\n {slices.map((slice) => {\n const share = largest > 0 && slice.value !== null ? Math.max(0, slice.value) / largest : 0\n return (\n <li key={slice.key}>\n <AppLink\n to={filteredListAddress(view, resource, slice.filter)}\n className=\"group grid grid-cols-[minmax(6rem,35%)_1fr_auto] items-center gap-3 rounded-md px-1 py-1 hover:bg-muted\"\n title={measure.kind === 'count' ? undefined : text('records', { count: measureText(slice.count, { kind: 'count' }) })}\n >\n <span className=\"truncate group-hover:text-primary-text\">{slice.label}</span>\n <span className=\"h-3 rounded-r bg-muted\" aria-hidden>\n <span className=\"block h-full rounded-r\" style={{ width: `${share * 100}%`, background: 'var(--chart-1)' }} />\n </span>\n <span className=\"text-right font-medium tabular-nums\">{measureText(slice.value, measure)}</span>\n </AppLink>\n </li>\n )\n })}\n </ul>\n )\n}\n","import { Skeleton } from '../../primitives/skeleton'\nimport { lazyComponent } from '../lazy-component'\n\n// The charts' drawing, the charting library and all, loads with the first chart shown, in a skeleton of its size.\n\nexport const PeriodChart = lazyComponent(\n () => import('./period-chart').then((module) => module.PeriodChart),\n ({ compact }) => <Skeleton className={compact ? 'h-24 w-full' : 'h-40 w-full'} />,\n)\n\nexport const GroupDonut = lazyComponent(\n () => import('./group-donut').then((module) => module.GroupDonut),\n () => <Skeleton className=\"size-36 rounded-full\" />,\n)\n","import type { Aggregate, AggregateGroup } from '@protobase/client'\nimport type { FieldModel, FieldViewModel } from '@protobase/schema'\nimport { colorOf, groupFilter, labelOf, periodPoints, type ChartMeasure } from './chart-groups'\nimport { text } from './messages'\n\n/**\n * One part of a split bucket as a chart draws it: the key of its number in a point, its name and colour, its records,\n * and how its number reads when it is not the chart's.\n */\nexport type ChartSeries = { key: string; label: string; color: string; filter?: string; measure?: ChartMeasure }\n\nexport type SplitPoint = ReturnType<typeof periodPoints>[number] & Record<string, number | null>\n\n// Sums of decimals carry float noise; what is left under this is no remainder\nconst noise = 1e-6\n\n/**\n * A date field's buckets with each split into one part per value of another field, in the order the API ranks them.\n * A bucket where a value has no records holds 0 of a count and no value of a sum or average. For a count or a sum, what\n * the kept values leave of the bucket's total is \"Other\", a series of its own when some bucket has any; an average\n * has no remainder.\n */\nexport const splitPoints = (\n groups: AggregateGroup[],\n splits: NonNullable<Aggregate['splits']>,\n field: FieldModel,\n hints: FieldViewModel | undefined,\n measure: ChartMeasure,\n filter = '',\n): { series: ChartSeries[]; points: SplitPoint[] } => {\n const series: ChartSeries[] = splits.map((split, index) => ({\n key: `s${index}`,\n label: labelOf(field, hints, split),\n color: colorOf(field, hints, split.value, index),\n filter: groupFilter(field, split.value, filter),\n }))\n const missing = measure.kind === 'count' ? 0 : null\n const partOf = (group: AggregateGroup, value: AggregateGroup['value']) => {\n const part = group.splits?.find((candidate) => candidate.value === value)\n if (!part) return missing\n return measure.kind === 'count' ? part.count : (part[measure.kind] ?? null)\n }\n const points = periodPoints(groups, measure).map((point, at): SplitPoint => {\n const group = groups[at]!\n const parts = splits.map((split) => partOf(group, split.value))\n const entries = Object.fromEntries(parts.map((part, index) => [`s${index}`, part]))\n if (measure.kind === 'average') return { ...point, ...entries }\n const rest = point.value === null ? null : point.value - parts.reduce<number>((all, part) => all + (part ?? 0), 0)\n return { ...point, ...entries, other: rest === null ? null : rest < noise ? 0 : rest }\n })\n const hasOther = measure.kind !== 'average' && points.some((point) => (point.other ?? 0) > 0)\n if (!hasOther) return { series, points: points.map(({ other, ...point }) => point as SplitPoint) }\n return { series: [...series, { key: 'other', label: text('other'), color: 'var(--border-strong)' }], points }\n}\n","import type { ChartBucket, ChartType } from '@protobase/layout'\nimport type { ResourceModel, ViewModel } from '@protobase/schema'\nimport { useAggregate } from '../../data/use-aggregates'\nimport { Skeleton } from '../../primitives/skeleton'\nimport { useAdminMeta } from '../meta-gate'\nimport { periodPoints, valueSlices, type ChartMeasure } from './chart-groups'\nimport { chartAggregate } from './chart-params'\nimport { GroupBars } from './group-bars'\nimport { GroupDonut, PeriodChart } from './lazy-charts'\nimport { splitPoints } from './split-points'\nimport { text } from './messages'\n\n/** What a chart shows: the records of `model` matching `filter`, grouped by `groupBy` and added up. */\nexport type ChartRequest = {\n model: ResourceModel\n view: ViewModel | undefined\n groupBy: string\n /** With a dated `groupBy`: a field of values that splits each bucket. */\n splitBy?: string\n type?: ChartType\n sum?: string\n average?: string\n filter?: string\n granularity?: ChartBucket\n range?: '7d' | '30d' | '90d' | '1y' | 'all'\n limit?: number\n empty?: string\n}\n\nconst measureOf = (model: ResourceModel, view: ViewModel | undefined, sum?: string, average?: string): ChartMeasure => {\n const name = sum ?? average\n const field = name === undefined ? undefined : model.fields[name]\n if (!field || name === undefined) return { kind: 'count' }\n return { kind: sum !== undefined ? 'sum' : 'average', field, hints: view?.fields[name] }\n}\n\n/**\n * Loads a chart's groups through `:aggregate` and draws them: a date field's buckets as bars or a line, a field's\n * values as ranked bars or a donut, each value linking to its records. The server checked the chart at startup.\n */\nexport const ChartView = ({ model, view, groupBy, splitBy, type = 'bar', sum, average, filter = '', granularity = 'day', range = '30d', limit = 10, empty = text('nothingYet') }: ChartRequest) => {\n const { resources, views } = useAdminMeta()\n const field = model.fields[groupBy]\n const dated = field?.type === 'date' || field?.type === 'timestamp'\n const splitField = dated && splitBy !== undefined ? model.fields[splitBy] : undefined\n const params = chartAggregate({ model, groupBy, splitBy, sum, average, filter, granularity, range, limit }, resources, views)\n const result = useAggregate(model.name, params ?? { groupBy }, params !== undefined)\n const measure = measureOf(model, view, sum, average)\n if (!field) return null\n if (result.isPending) return <Skeleton className=\"h-36 w-full\" />\n if (result.error) return <p className=\"text-danger-text\">{text('couldNotLoad')}</p>\n const { groups } = result.data\n if (groups.every((group) => group.count === 0)) return <p className=\"text-muted-foreground\">{empty}</p>\n const chartType = type === 'line' ? 'line' : 'bar'\n if (dated && splitField && result.data.splits) {\n const { series, points } = splitPoints(groups, result.data.splits, splitField, view?.fields[splitField.name], measure, filter)\n return <PeriodChart points={points} measure={measure} bucket={granularity} type={chartType} series={series} resource={model.name} view={view} />\n }\n if (dated) return <PeriodChart points={periodPoints(groups, measure)} measure={measure} bucket={granularity} type={chartType} />\n const slices = valueSlices(groups, field, view?.fields[groupBy], measure, filter)\n return type === 'donut' ? <GroupDonut resource={model.name} view={view} slices={slices} measure={measure} /> : <GroupBars resource={model.name} view={view} slices={slices} measure={measure} />\n}\n","/** The space between the items of a `SnapRow`, Tailwind's `gap-3`. */\nexport const snapRowGap = '0.75rem'\n\n/** How wide an item of a `SnapRow` is when no share sizes it, in pixels. */\nexport const snapCardWidth = 256\n\n/**\n * How wide an item of a row is at `share` of the row's width, the gaps taken off so that `1 / share` items fill it\n * exactly: a third leaves room for three items and the two gaps between them.\n */\nexport const snapItemWidth = (share: number) => {\n if (!(share > 0 && share <= 1)) throw new Error(`An item's share of a row is above 0 and at most 1, not ${share}`)\n return `calc((100% + ${snapRowGap}) * ${share} - ${snapRowGap})`\n}\n\n/**\n * The width and least width of an item of a `SnapRow`: at `share` of the row, but never narrower than 12rem or the\n * row, so narrow shares stay readable on a phone; without one `snapCardWidth`, but never wider than the row, so a very\n * narrow phone does not cut a card off.\n */\nexport const snapItemSize = (share: number | undefined) =>\n share === undefined ? { width: `min(${snapCardWidth}px, 100%)`, minWidth: '0px' } : { width: snapItemWidth(share), minWidth: 'min(100%, 12rem)' }\n","import type { CSSProperties, ReactNode } from 'react'\nimport { ChevronLeft, ChevronRight } from 'lucide-react'\nimport { snapItemSize, snapRowGap } from './snap-row-width'\nimport type { SnapScroll } from './use-snap-scroll'\nimport { text } from './messages'\n\nexport type SnapRowProps = {\n /** The row's scroll, from `useSnapScroll`. */\n scroll: SnapScroll\n /** What the items are, such as \"Homes\": the list's label, and the arrows' as \"Next homes\". */\n label: string\n /** How wide each item is, as a share of the row's width, such as `2 / 3` so the next one peeks in; 256px when omitted. */\n share?: number\n /** The row's items, each an `<li>`. */\n children: ReactNode\n}\n\nconst arrowClass = 'absolute top-1/2 z-10 hidden size-8 -translate-y-1/2 items-center justify-center rounded-full border border-border-strong bg-background shadow-pop hover:bg-muted sm:flex'\n\n/**\n * A list laid out as one row that scrolls sideways, by touch, trackpad, wheel or its scrollbar, and with a pointer by its\n * arrow buttons, snapping each item to its left edge. Each item is `share` of the row wide, but never narrower than 12rem\n * or the row, else 256px but never wider than the row (`snapItemSize`). The row scrolls on its own because the page\n * cannot scroll sideways, and only sideways: it is as tall as its tallest item. A swipe past its last item stops there.\n */\nexport const SnapRow = ({ scroll, label, share, children }: SnapRowProps) => {\n const size = snapItemSize(share)\n return (\n <div className=\"relative min-w-0\">\n <ul\n ref={scroll.ref}\n aria-label={label}\n className=\"relative flex snap-x snap-mandatory overflow-x-auto overflow-y-hidden overscroll-x-contain pb-1 *:w-(--snap-item-width) *:min-w-(--snap-item-min-width) *:shrink-0 *:snap-start\"\n style={{ gap: snapRowGap, scrollbarWidth: 'thin', '--snap-item-width': size.width, '--snap-item-min-width': size.minWidth } as CSSProperties}\n >\n {children}\n </ul>\n {scroll.back && (\n <button type=\"button\" aria-label={text('previous', { label: label.toLowerCase() })} onClick={() => scroll.page(-1)} className={`${arrowClass} -left-3`}>\n <ChevronLeft className=\"size-4\" aria-hidden />\n </button>\n )}\n {scroll.on && (\n <button type=\"button\" aria-label={text('next', { label: label.toLowerCase() })} onClick={() => scroll.page(1)} className={`${arrowClass} -right-3`}>\n <ChevronRight className=\"size-4\" aria-hidden />\n </button>\n )}\n </div>\n )\n}\n","import { useLayoutEffect, useRef, useState } from 'react'\n\n/** The part of a row in view: how far it is scrolled and how wide the view is, in pixels. */\nexport type SnapView = { left: number; width: number }\n\ntype Scrolled = SnapView & { back: boolean; on: boolean; watched: string }\n\nconst measure = (list: HTMLUListElement, watch: (view: SnapView) => string): Scrolled => {\n const view = { left: list.scrollLeft, width: list.clientWidth }\n return { ...view, back: view.left > 0, on: view.left + view.width < list.scrollWidth - 1, watched: watch(view) }\n}\n\nconst same = (a: Scrolled, b: Scrolled) => a.width === b.width && a.back === b.back && a.on === b.on && a.watched === b.watched\n\n/**\n * A `SnapRow`'s sideways scroll: `ref` goes on its list. Gives the part of the row in `view`, whether it can scroll\n * `back` or `on`, and `page`, which scrolls a view's width either way. It draws again only when the view's width, an end\n * reached or what `watch` makes of the view changes, such as the cards a windowed row draws.\n */\nexport const useSnapScroll = (watch: (view: SnapView) => string = () => '') => {\n const [list, setList] = useState<HTMLUListElement | null>(null)\n const [scrolled, setScrolled] = useState<Scrolled>({ left: 0, width: 0, back: false, on: false, watched: '' })\n const read = () => {\n if (!list) return\n const next = measure(list, watch)\n setScrolled((current) => (same(current, next) ? current : next))\n }\n\n // After every draw, since the row's content may have grown without a scroll or resize\n const latest = useRef(read)\n useLayoutEffect(() => {\n latest.current = read\n read()\n })\n useLayoutEffect(() => {\n if (!list) return\n const changed = () => latest.current()\n const observer = new ResizeObserver(changed)\n observer.observe(list)\n list.addEventListener('scroll', changed, { passive: true })\n return () => {\n observer.disconnect()\n list.removeEventListener('scroll', changed)\n }\n }, [list])\n\n const page = (direction: 1 | -1) => {\n if (!list) return\n const gap = parseFloat(getComputedStyle(list).columnGap) || 0\n list.scrollBy({ left: direction * Math.max(1, list.clientWidth - gap), behavior: 'smooth' })\n }\n return { ref: setList, view: { left: scrolled.left, width: scrolled.width }, back: scrolled.back, on: scrolled.on, page }\n}\n\nexport type SnapScroll = ReturnType<typeof useSnapScroll>\n","import { messages } from '../../locale/messages'\n\nexport const text = messages('app/embedded-list')\n","import { formatTag } from '../../locale/active-locale'\nimport { text } from './messages'\n\n/**\n * What a list that shows only its first `shown` of `total` records says about the rest, as \"The first 10 of 37.\";\n * nothing when it shows them all. An `estimated` total is the planner's, so it reads \"about\".\n */\nexport const cutOffNote = (shown: number, total: number, estimated: boolean) => {\n if (shown >= total) return undefined\n return (estimated ? text('firstOfAbout', { shown, total: total.toLocaleString(formatTag()) }) : text('firstOf', { shown, total: total.toLocaleString(formatTag()) }))\n}\n","import type { ResourceModel, ViewModel } from '@protobase/schema'\nimport { guarded } from '../../lib/guarded'\nimport { changedList, listDefaults } from '../current-address'\nimport { defaultDisplay, displayChoices } from '../displays/list-displays'\n\nconst prefix = 'protobase:embedded-display:'\n\n/** Where a viewer's pick of display is kept for one embedded list, named by the place it is shown. */\nexport const embeddedDisplayKey = (place: string) => `${prefix}${place}`\n\nexport const readPickedDisplay = (storage: Pick<Storage, 'getItem'>, key: string) => guarded(() => storage.getItem(key) ?? undefined, undefined)\n\nexport const writePickedDisplay = (storage: Pick<Storage, 'setItem'>, key: string, display: string) => guarded(() => storage.setItem(key, display), undefined)\n\n/**\n * The display an embedded list shows: the viewer's pick while the view still has it, else what the list opens in for\n * the screen, with the display the page names in place of the view's default (with neither, below `sm`, a cards\n * display when the view has one).\n */\nexport const embeddedDisplay = (view: ViewModel | undefined, xs: boolean, { picked, preferred }: { picked?: string; preferred?: string }) => {\n const names = displayChoices(view).map((choice) => choice.name)\n if (picked !== undefined && names.includes(picked)) return picked\n return defaultDisplay(view, xs, preferred !== undefined && names.includes(preferred) ? preferred : undefined)\n}\n\n/**\n * The resource's list with the embedded list's filter, order and display, leaving out what the list does by default (an\n * embedded list's own default display among it, so a phone opens the list in its rows rather than the table), and\n * the saved search whose results it shows, if any. `resource` names another list of the same records, such as the\n * favorites that list a user's saved listings.\n */\nexport const viewAllAddress = (\n model: ResourceModel,\n view: ViewModel | undefined,\n xs: boolean,\n { resource = model.name, ...list }: { filter: string; orderBy: string; display: string; savedSearch?: string; resource?: string },\n) => changedList({ kind: 'list', resource }, list, { ...listDefaults(model, view, xs), display: defaultDisplay(view, xs) })\n","import type { Planned } from './planned'\n\n/** A planned count: the total of its read, or inside a repeated record the count of that record's group, 0 without one. */\nexport const plannedCount = (planned: Planned) => planned.total ?? Number(planned.rows[0]?.count ?? 0)\n","import { checkFilter, parseFilter, type AppAddress, type ResourceModel, type RowButtonModel, type ViewModel } from '@protobase/schema'\nimport { bareFilterFields, fillAddress, fillText, filterField, hrefField, rowButtonChoiceFields, rowButtonChoices, rowButtonTarget } from '@protobase/schema/internal'\nimport { displayValue } from '../../live/display-value'\n\nconst isEmpty = (value: unknown) => value === null || value === undefined || value === ''\n\n// Only an https page opens from a row, so a field holding another scheme, such as `javascript:`, leads nowhere.\nconst httpsUrl = (value: unknown) => (typeof value === 'string' && URL.canParse(value) && new URL(value).protocol === 'https:' ? new URL(value).href : undefined)\n\n// A value a filter takes outside quotes is a number or a boolean, so a row's text cannot change what the filter says.\nconst plainValue = (value: unknown) => typeof value === 'number' || typeof value === 'boolean' || (typeof value === 'string' && /^(-?\\d+(\\.\\d+)?|true|false)$/.test(value))\n\n// A filter the row holds whole leads somewhere only when it parses and checks against the list's resource as the caller sees it.\nconst followableFilter = (to: AppAddress, models: Record<string, ResourceModel>) => {\n if (to.kind !== 'list' || to.filter === undefined) return false\n const target = Object.hasOwn(models, to.resource) ? models[to.resource] : undefined\n if (!target) return false\n const parsed = parseFilter(to.filter)\n if (!parsed.ok || !parsed.ast) return false\n return checkFilter(target, parsed.ast).ok\n}\n\n/**\n * The button `button` draws on `record`, a row of `model`: its first choice whose fields the row holds, its label with\n * each `{{field}}` as the record page shows the value (an enum value by its label), and its address filled from the row,\n * or the `https:` URL its href field holds. None when no choice has its fields, or the chosen one leads nowhere: an\n * href field without an `https:` URL, a value outside quotes in a filter that is not a number or a boolean, or a filter\n * the row holds whole, `'{{field}}'`, that does not parse or check against `models`, the caller's resources.\n */\nexport const rowButtonFor = (button: RowButtonModel, model: ResourceModel, view: ViewModel | undefined, record: Record<string, unknown>, models: Record<string, ResourceModel>): { label: string; to: AppAddress } | { label: string; href: string } | undefined => {\n const choice = rowButtonChoices(button).find((option) => !rowButtonChoiceFields(option).some((name) => isEmpty(record[name])))\n if (!choice) return\n const shown = (name: string) => {\n const field = model.fields[name]\n return field ? displayValue(field, record[name], view?.fields[name]) : String(record[name])\n }\n const label = fillText(choice.label, shown)\n const target = rowButtonTarget(choice)\n if ('href' in target) {\n const href = httpsUrl(record[hrefField(target.href) ?? ''])\n return href === undefined ? undefined : { label, href }\n }\n if (filterField(target.to) !== undefined) {\n const to = fillAddress(target.to, record)\n return followableFilter(to, models) ? { label, to } : undefined\n }\n if (!bareFilterFields(target.to).every((name) => plainValue(record[name]))) return\n return { label, to: fillAddress(target.to, record) }\n}\n","import { ExternalLink } from 'lucide-react'\nimport type { ResourceModel, RowButtonModel, ViewModel } from '@protobase/schema'\nimport { cn } from '../../lib/cn'\nimport { buttonClass } from '../../primitives/button'\nimport { text } from '../messages'\nimport { AppLink } from '../use-app-address'\nimport { rowButtonFor } from './row-button-for'\n\ntype RowButtonLinkProps = { button: RowButtonModel; model: ResourceModel; view: ViewModel | undefined; record: Record<string, unknown>; models: Record<string, ResourceModel> }\n\n/**\n * A row's button: a link to the address its fields name, looking like a button, or to the outside page a field holds,\n * in a new tab with the outside-link mark, which a screen reader hears as text; nothing on a row without them.\n */\nexport const RowButtonLink = ({ button, model, view, record, models }: RowButtonLinkProps) => {\n const shown = rowButtonFor(button, model, view, record, models)\n if (!shown) return null\n // A label longer than its column has shortens inside the button, which stays whole and names it whole on hover\n const style = cn(buttonClass({ variant: 'secondary', size: 'sm' }), 'min-w-0 max-w-full shrink')\n const label = <span className=\"truncate\">{shown.label}</span>\n if ('href' in shown) {\n return (\n <a href={shown.href} target=\"_blank\" rel=\"noreferrer\" title={shown.label} className={style}>\n {label}\n <span className=\"sr-only\"> {text('opensNewTab')}</span>\n <ExternalLink aria-hidden className=\"size-3.5 shrink-0\" />\n </a>\n )\n }\n return (\n <AppLink to={shown.to} title={shown.label} className={style}>\n {label}\n </AppLink>\n )\n}\n","import { createColumnHelper, rowSelectionFeature, rowSortingFeature, tableFeatures } from '@tanstack/react-table'\nimport { renderCell } from './cells'\nimport type { ColumnSpec, GridRow } from './column-spec'\n\nexport const features = tableFeatures({ rowSortingFeature, rowSelectionFeature })\n\nconst helper = createColumnHelper<typeof features, GridRow>()\n\nexport const buildColumns = (specs: ColumnSpec[]) =>\n helper.columns(\n specs.map((spec) =>\n helper.accessor((row) => (spec.value ? spec.value(row) : row[spec.id]), {\n id: spec.id,\n header: spec.header,\n enableSorting: spec.sortable ?? false,\n cell: (context) => (spec.render ? spec.render(context.row.original) : renderCell(spec, context.getValue(), context.row.original)),\n }),\n ),\n )\n","import type { GridRow } from './column-spec'\n\n/**\n * What can be done with the selected rows. `available` narrows them to those the action applies to: it is offered\n * while one of them does, `label` counts those, and `onRun` gets them with how many selected rows it skips. One that asks\n * first returns a promise of the rows still open once it ends, such as those it was refused: all of them when its dialog\n * is cancelled.\n */\nexport type BulkAction = { label: (count: number) => string; destructive?: boolean; available?: (row: GridRow) => boolean; onRun: (rows: GridRow[], skipped: number) => void | Promise<GridRow[]> }\n\n/** The actions offered for `selected`, each with the rows it runs on and how many it skips. */\nexport const offeredBulkActions = (actions: BulkAction[], selected: GridRow[]) =>\n actions.flatMap((action) => {\n const rows = action.available ? selected.filter(action.available) : selected\n return rows.length === 0 ? [] : [{ action, rows, skipped: selected.length - rows.length }]\n })\n\n/** Runs `action` on `rows` and resolves to those it is done with, to deselect: all of them unless its promise names some still open. */\nexport const runBulkAction = async (action: BulkAction, rows: GridRow[], skipped: number) => {\n const open = await action.onRun(rows, skipped)\n if (!open) return rows\n const kept = new Set(open.map((row) => row.id))\n return rows.filter((row) => !kept.has(row.id))\n}\n\n/** A `runBulkAction` that starts no second run while one is in flight: a press meanwhile resolves to nothing. */\nexport const oneBulkRunAtATime = () => {\n let running = false\n return async (action: BulkAction, rows: GridRow[], skipped: number) => {\n if (running) return\n running = true\n try {\n return await runBulkAction(action, rows, skipped)\n } finally {\n running = false\n }\n }\n}\n","import { formatApproxRows, formatInt } from '../format/number'\nimport { cn } from '../lib/cn'\nimport { text } from './messages'\n\nexport type GridFooterProps = {\n total: number\n selectedCount: number\n bulkActions?: Array<{ label: string; destructive?: boolean; onRun: () => void }>\n className?: string\n}\n\n/** How many rows match and, with rows selected, how many and what can be done with them. */\nexport const GridFooter = ({ total, selectedCount, bulkActions = [], className }: GridFooterProps) => (\n <div className={cn('flex h-9 shrink-0 items-center border-t bg-surface px-3 text-xs text-muted-foreground', className)}>\n <span className=\"flex items-center tabular-nums\">\n {formatApproxRows(total)}\n {selectedCount > 0 && <span className=\"ml-3 font-medium text-primary-text\">{text('selected', { count: formatInt(selectedCount) })}</span>}\n {selectedCount > 0 &&\n bulkActions.map((action) => (\n <button\n key={action.label}\n type=\"button\"\n onClick={action.onRun}\n className={cn('ml-3 rounded border bg-background px-2 py-0.5 font-medium hover:bg-muted', action.destructive ? 'border-danger/40 text-danger-text' : 'text-foreground')}\n >\n {action.label}\n </button>\n ))}\n </span>\n </div>\n)\n","import { MoreHorizontal } from 'lucide-react'\nimport { createPortal } from 'react-dom'\nimport { cn } from '../lib/cn'\nimport { usePopoverMenu } from '../primitives/popover-menu'\nimport { RouteLink, type RouteTarget } from '../primitives/route-link'\nimport type { GridRow } from './column-spec'\nimport { text } from './messages'\n\n/**\n * `label` may name the row's own text. `available` hides the action for rows it does not apply to, for example a delete\n * the server will refuse; `blocked` shows it disabled, with why as its tooltip.\n */\ntype RowActionBase = { label: string | ((row: GridRow) => string); destructive?: boolean; available?: (row: GridRow) => boolean; blocked?: (row: GridRow) => string | undefined }\n/** `link` makes the item an ordinary link to where it goes, as every navigation is, unless it is `blocked`; `onSelect` runs anything else. */\nexport type RowAction = RowActionBase & ({ onSelect: (row: GridRow) => void; link?: never } | { link: (row: GridRow) => RouteTarget; onSelect?: never })\n\nconst labelOf = (action: RowAction, row: GridRow) => (typeof action.label === 'string' ? action.label : action.label(row))\n\n/** The actions that apply to a row; a row with none gets no menu at all. */\nexport const availableActions = (actions: RowAction[], row: GridRow) => actions.filter((action) => action.available?.(row) ?? true)\n\n/**\n * The \"...\" button at the end of a row, with a small menu of the row's actions. The menu is portalled to the body:\n * every grid row is its own stacking context and the grid body clips, so a menu inside the row would sit under the\n * rows below it.\n */\nexport const RowMenu = ({ row, actions }: { row: GridRow; actions: RowAction[] }) => {\n const { open, setOpen, place, button, menu } = usePopoverMenu()\n\n return (\n <div className=\"relative flex justify-center bg-inherit\" onClick={(event) => event.stopPropagation()}>\n <button ref={button} type=\"button\" aria-label={text('rowActions')} aria-haspopup=\"menu\" aria-expanded={open} onClick={() => setOpen(!open)} className=\"inline-flex items-center justify-center rounded p-1 text-faint-foreground hover:bg-muted hover:text-foreground pointer-coarse:size-11\">\n <MoreHorizontal className=\"size-4\" />\n </button>\n {open &&\n createPortal(\n <ul ref={menu} role=\"menu\" onClick={(event) => event.stopPropagation()} style={place ?? { visibility: 'hidden' }} className=\"fixed z-50 min-w-36 rounded-md border bg-background py-1 shadow-pop\">\n {actions.map((action, index) => {\n const label = labelOf(action, row)\n const blocked = action.blocked?.(row)\n const itemClass = cn('block w-full px-3 py-1.5 text-left hover:bg-muted disabled:cursor-default disabled:opacity-60 disabled:hover:bg-transparent', action.destructive && 'text-danger-text')\n return (\n <li key={index} role=\"none\">\n {action.link && blocked === undefined ? (\n <RouteLink role=\"menuitem\" to={action.link(row)} onClick={() => setOpen(false)} className={itemClass}>\n {label}\n </RouteLink>\n ) : (\n <button\n type=\"button\"\n role=\"menuitem\"\n disabled={blocked !== undefined}\n title={blocked}\n className={itemClass}\n onClick={() => {\n setOpen(false)\n action.onSelect?.(row)\n }}\n >\n {label}\n </button>\n )}\n </li>\n )\n })}\n </ul>,\n document.body,\n )}\n </div>\n )\n}\n","import type { ColumnSpec } from './column-spec'\n\n/** Wide enough for the checkbox plus the largest row number, with thousands separators. */\nexport const gutterWidthFor = (total: number) => 52 + Math.ceil(String(total).length * 1.33) * 7\n\nexport const rowMenuWidth = 40\n\n/** On phones the gutter holds only the checkbox, leaving room for the columns. */\nexport const compactGutter = 40\n\n/** Columns may shrink to this share of their width on desktop; on narrow screens they keep it whole and the grid scrolls. */\nexport const desktopMinScale = 0.6\n\nconst minWidthOf = (spec: ColumnSpec, minScale: number) => Math.max(spec.minWidth ?? 0, spec.width * minScale)\n\nconst columnTemplate = (spec: ColumnSpec, minScale: number) =>\n spec.fixed ? `${Math.max(spec.minWidth ?? 0, spec.width)}px` : `minmax(${minWidthOf(spec, minScale)}px, ${spec.width}fr)`\n\nexport const gridTemplate = (specs: ColumnSpec[], gutter: number, trailing = 0, minScale = desktopMinScale) =>\n `${gutter}px ${specs.map((spec) => columnTemplate(spec, minScale)).join(' ')}${trailing > 0 ? ` ${trailing}px` : ''}`\n\n/** The narrowest the grid can be before it has to scroll sideways. */\nexport const gridMinWidth = (specs: ColumnSpec[], gutter: number, trailing = 0, minScale = desktopMinScale) =>\n gutter + trailing + specs.reduce((sum, spec) => sum + (spec.fixed ? Math.max(spec.minWidth ?? 0, spec.width) : minWidthOf(spec, minScale)), 0)\n","import { useCallback, useRef, useState } from 'react'\n\n/** Tracks whether the grid is scrolled sideways (`scrolled`) and whether more lies to the right (`more`). */\nexport const useHorizontalScroll = () => {\n const ref = useRef<HTMLDivElement | null>(null)\n const observer = useRef<ResizeObserver | null>(null)\n const [edges, setEdges] = useState({ scrolled: false, more: false })\n\n const measure = useCallback(() => {\n const element = ref.current\n if (!element) return\n const next = { scrolled: element.scrollLeft > 1, more: element.scrollLeft + element.clientWidth < element.scrollWidth - 1 }\n setEdges((current) => (current.scrolled === next.scrolled && current.more === next.more ? current : next))\n }, [])\n\n // Observe once per mounted element rather than on every render: re-subscribing each render made the observer's\n // initial callback schedule another render, which re-subscribed again, looping until React bailed out.\n const attach = useCallback(\n (element: HTMLDivElement | null) => {\n observer.current?.disconnect()\n observer.current = null\n ref.current = element\n if (!element) return\n const next = new ResizeObserver(measure)\n next.observe(element)\n for (const child of Array.from(element.children)) next.observe(child)\n observer.current = next\n measure()\n },\n [measure],\n )\n\n return { ref, attach, onScroll: measure, ...edges }\n}\n","import { guarded } from '../lib/guarded'\n\nconst prefix = 'protobase:pinned:'\n\nexport const pinnedStorageKey = (userId: string, resource: string) => `${prefix}${userId}:${resource}`\n\nexport const readPinned = (storage: Pick<Storage, 'getItem'>, key: string): string[] | undefined =>\n guarded(() => {\n const raw = storage.getItem(key)\n if (raw === null) return undefined\n const parsed: unknown = JSON.parse(raw)\n return Array.isArray(parsed) && parsed.every((entry) => typeof entry === 'string') ? parsed : undefined\n }, undefined)\n\n/** Keeps an empty list too, so a column pinned by default and then unpinned stays unpinned. */\nexport const writePinned = (storage: Pick<Storage, 'setItem'>, key: string, pinned: string[]) => guarded(() => storage.setItem(key, JSON.stringify(pinned)), undefined)\n","import { useCallback, useState } from 'react'\nimport { readPinned, writePinned } from './pinned-storage'\n\n/**\n * The ids of the columns pinned to the left, in pin order. With a `storageKey` the choice is kept in local storage\n * (per user and resource); `initial` applies until the user has chosen, as it is on each render.\n */\nexport const usePinnedColumns = (storageKey: string | undefined, initial: string[] = []) => {\n const [chosen, setChosen] = useState(() => (storageKey ? readPinned(localStorage, storageKey) : undefined))\n const update = useCallback(\n (next: string[]) => {\n setChosen(next)\n if (storageKey) writePinned(localStorage, storageKey, next)\n },\n [storageKey],\n )\n return [chosen ?? initial, update] as const\n}\n","import type { ColumnSpec } from './column-spec'\n\n/**\n * The columns pinned until the user chooses: the leading columns through the title column, when it is first or second.\n * Pinned columns move to the front, so a title further right stays unpinned rather than reorder the list; pins only\n * take effect once the grid is too wide and scrolls sideways.\n */\nexport const defaultPins = (specs: ColumnSpec[]) => {\n const index = specs.findIndex((spec) => spec.title)\n if (index < 0 || index > 1) return []\n return specs.slice(0, index + 1).map((spec) => spec.id)\n}\n","import { useMemo, useState } from 'react'\nimport type { ColumnSpec, GridRow } from './column-spec'\nimport { fitColumns } from './content-widths'\n\ntype Size = Pick<ColumnSpec, 'width' | 'minWidth' | 'fixed'>\n\ntype Fitted = { key: string; sizes: Record<string, Size> }\n\nconst sizesOf = (specs: ColumnSpec[]) => Object.fromEntries(specs.map(({ id, width, minWidth, fixed }) => [id, { width, minWidth, fixed }]))\n\n/** What a fit depends on besides the rows: each column with the bounds its width is clamped to. */\nexport const fitKey = (columns: ColumnSpec[]) =>\n columns\n .map(({ id, minWidth, maxWidth }) => `${id}:${minWidth ?? ''}:${maxWidth ?? ''}`)\n .sort()\n .join(' ')\n\n/**\n * `columns` sized by the first rows shown, fitted once per set of columns and their bounds: later pages, filters and\n * sorts keep those widths, so columns never jump while scrolling, and a longer value later on is cut, with the whole of\n * it on hover.\n */\nexport const useFittedColumns = (columns: ColumnSpec[], rows: GridRow[]) => {\n const key = fitKey(columns)\n const [fitted, setFitted] = useState<Fitted>()\n const current = fitted?.key === key ? fitted : undefined\n // Fitting is stored while rendering, the way React keeps state derived from earlier renders, so no frame shows the old widths\n if (!current && rows.length > 0) setFitted({ key, sizes: sizesOf(fitColumns(columns, rows)) })\n const sizes = current?.sizes\n return useMemo(() => (sizes ? columns.map((spec) => ({ ...spec, ...sizes[spec.id] })) : columns), [columns, sizes])\n}\n","import type { ColumnSpec } from './column-spec'\n\n/** The narrowest a column can be dragged: room for a few letters of its header and its menu button. */\nexport const minColumnWidth = 64\n\n/** Pixels an arrow key moves a column's edge. */\nexport const resizeStep = 16\n\n/**\n * The width a column dragged `delta` pixels from `start` takes, never below `minColumnWidth`, or below `start` for a\n * column the app made narrower than that, such as one of check marks.\n */\nexport const resizedWidth = (start: number, delta: number) => Math.max(Math.min(minColumnWidth, start), Math.round(start + delta))\n\n/**\n * `specs` with the widths a resize set them to: those columns take that width whole, even below the minimum width the\n * app gave them, as `resizedWidth` keeps them usable.\n */\nexport const withResizedWidths = (specs: ColumnSpec[], widths: Record<string, number>) =>\n specs.map((spec) => (spec.id in widths ? { ...spec, fixed: true, width: widths[spec.id]!, minWidth: undefined } : spec))\n","import { useState, type KeyboardEvent, type PointerEvent, type RefObject } from 'react'\nimport { resizeStep, resizedWidth } from './column-resize'\n\n/** The widths every header cell has now, by column id, so that resizing one column leaves the others as they are. */\nconst measuredWidths = (header: HTMLElement) =>\n Object.fromEntries([...header.querySelectorAll<HTMLElement>('[data-col-id]')].map((cell) => [cell.dataset.colId!, cell.offsetWidth]))\n\n/**\n * Column widths the user sets by dragging a header cell's edge, or with the arrow keys on it, by column id. They live\n * as long as the grid does: a reload or another page shows the app's widths again.\n */\nexport const useColumnResize = (header: RefObject<HTMLElement | null>) => {\n const [widths, setWidths] = useState<Record<string, number>>({})\n\n // The first resize fixes every column at the width it has, so that only the one being dragged changes\n const startWidths = () => ({ ...(header.current ? measuredWidths(header.current) : {}), ...widths })\n\n const onPointerDown = (id: string, event: PointerEvent<HTMLElement>) => {\n if (event.button !== 0) return\n event.preventDefault()\n const start = startWidths()\n const startX = event.clientX\n // Followed on the window, so the drag goes on wherever the pointer goes and ends wherever it is let go\n const onMove = (move: globalThis.PointerEvent) => setWidths({ ...start, [id]: resizedWidth(start[id] ?? 0, move.clientX - startX) })\n const onEnd = () => {\n window.removeEventListener('pointermove', onMove)\n window.removeEventListener('pointerup', onEnd)\n window.removeEventListener('pointercancel', onEnd)\n }\n window.addEventListener('pointermove', onMove)\n window.addEventListener('pointerup', onEnd)\n window.addEventListener('pointercancel', onEnd)\n }\n\n const onKeyDown = (id: string, event: KeyboardEvent<HTMLElement>) => {\n const delta = event.key === 'ArrowRight' ? resizeStep : event.key === 'ArrowLeft' ? -resizeStep : 0\n if (delta === 0) return\n event.preventDefault()\n const start = startWidths()\n setWidths({ ...start, [id]: resizedWidth(start[id] ?? 0, delta) })\n }\n\n return { widths, onPointerDown, onKeyDown }\n}\n","import { useSyncExternalStore } from 'react'\n\nconst rootFontSize = () => parseFloat(getComputedStyle(document.documentElement).fontSize)\n\n/** The root text size in pixels, what `1rem` is, read again on a resize of the window such as a zoom. */\nexport const useRootFontSize = () =>\n useSyncExternalStore(\n (onChange) => {\n window.addEventListener('resize', onChange)\n return () => window.removeEventListener('resize', onChange)\n },\n rootFontSize,\n () => 16,\n )\n","// In rem, as the header's `h-8`, the footer's `h-9` and the cells' text and buttons are\nconst header = 2\nconst row = 2.25\nconst compactRow = 1.75\n// A small button's height and the gap above it, for a column with something `below` its cells\nconst below = 2\nconst footer = 2.25\n\n/** The grid's heights in pixels, which rows are placed and virtualized by, for a root text size of `rem` pixels. */\nexport const gridHeights = (rem: number, { compact, withBelow }: { compact: boolean; withBelow: boolean }) => ({\n header: header * rem,\n row: ((compact ? compactRow : row) + (withBelow ? below : 0)) * rem,\n footer: footer * rem,\n})\n","import type { ReactNode } from 'react'\nimport type { BadgeTone } from '../primitives/badge'\nimport type { ContactFormat } from '../live/contact-links'\n\nexport type ColumnKind =\n | 'text' | 'id' | 'money' | 'date' | 'datetime' | 'status' | 'relation'\n | 'boolean' | 'number' | 'signed' | 'percent' | 'user' | 'file'\n\n/** A person a `user` column shows for an id. */\nexport type CellUser = { name: string; initials: string; hue: number }\n\nexport type GridRow = { id: string } & Record<string, unknown>\n\nexport type ColumnSpec = {\n id: string\n header: string\n kind: ColumnKind\n /** Relative width in px; columns grow proportionally to fill the grid. */\n width: number\n /** Pixels the column never shrinks below, for values that must stay whole such as identifiers. */\n minWidth?: number\n /** Pixels the column never grows past when it is sized by `fit`. */\n maxWidth?: number\n /** For a column drawn by its own `render`: the pixels a row's cell needs, so the column takes its widest row's width. */\n fit?: (row: GridRow) => number\n /** A fixed pixel width instead of a share of the leftover space, for values of known length such as timestamps. */\n fixed?: boolean\n sortable?: boolean\n /** The record's title column: it gets the largest share of the width and is pinned by default. */\n title?: boolean\n /** Tints the column to mark it as new. */\n highlight?: boolean\n /** For a `datetime` column: shows how long ago each value is, its exact time on hover. */\n relative?: boolean\n /** The ISO 4217 code of a `money` column's currency, which it needs. */\n currency?: string\n /** Decimals a `money` column shows instead of the currency's usual ones. */\n decimals?: number\n /** Text before a number, such as a currency sign, for `number` and `signed` columns. */\n prefix?: string\n /** Text after a number, such as a unit, for `number`, `signed` and `money` columns. */\n suffix?: string\n /** Badge tone per value, for `status` columns. */\n tones?: Record<string, BadgeTone>\n /** A hex colour per value that fills its badge instead of its tone, for `status` columns; a tone name is no colour. */\n colors?: Record<string, string>\n /** The shape of a `status` column's badges. */\n shape?: 'arrow'\n /** Badge text per value, for `status` columns; a value without one reads as itself in words. */\n labels?: Record<string, string>\n /** For a `text` column of addresses: each value a link that writes to, calls or opens it. */\n link?: ContactFormat\n /** For a `link` column: the text a row's link shows instead of the address; the address when it gives none. */\n linkText?: (row: GridRow) => string | undefined\n /** For a `user` column: the person behind an id; an id it does not know shows as itself. */\n users?: (id: string) => CellUser | undefined\n /** Reads the cell value; defaults to `row[id]`. */\n value?: (row: GridRow) => unknown\n /** Draws the cell instead of its kind, such as a field type's cell. */\n render?: (row: GridRow) => ReactNode\n /** Drawn under the cell's content, outside the link a title cell is; every row of the grid grows to hold it. */\n below?: (row: GridRow) => ReactNode\n}\n\nexport const isRightAligned = (kind: ColumnKind) => kind === 'money' || kind === 'number' || kind === 'signed' || kind === 'percent'\n","import { MoreHorizontal } from 'lucide-react'\nimport { createPortal } from 'react-dom'\nimport { usePopoverMenu } from '../primitives/popover-menu'\nimport { text } from './messages'\n\nexport type HeaderMenuProps = { header: string; pinned: boolean; sortable: boolean; onTogglePin: () => void }\n\n/** Why a column header does nothing when pressed: a list sorts only on the columns its view makes sortable. */\nexport const unsortableText = () => text('unsortable')\n\n/**\n * The \"...\" in a column header: pinning the column to the left edge, and saying so when the list can't sort by it. The\n * menu is portalled to the body, as the row menu is: the header row clips, so a menu inside it would be cut off at the\n * header's bottom edge, with the rows showing where it should be.\n */\nexport const HeaderMenu = ({ header, pinned, sortable, onTogglePin }: HeaderMenuProps) => {\n const { open, setOpen, place, button, menu } = usePopoverMenu()\n\n return (\n <div className=\"relative ml-auto shrink-0\">\n <button\n ref={button}\n type=\"button\"\n aria-label={text('columnMenu', { header })}\n aria-haspopup=\"menu\"\n aria-expanded={open}\n onClick={() => setOpen(!open)}\n className=\"relative inline-flex size-5 items-center justify-center rounded text-faint-foreground hover:bg-muted hover:text-foreground focus-visible:opacity-100 after:absolute after:-inset-2 after:content-[''] md:opacity-0 md:group-hover/cell:opacity-100 aria-expanded:opacity-100\"\n >\n <MoreHorizontal className=\"size-3.5\" />\n </button>\n {open &&\n createPortal(\n <ul ref={menu} role=\"menu\" style={place ?? { visibility: 'hidden' }} className=\"fixed z-50 min-w-32 rounded-md border bg-background py-1 text-body font-normal text-foreground shadow-pop\">\n {!sortable && (\n <li role=\"none\">\n <span role=\"menuitem\" aria-disabled=\"true\" className=\"block min-h-9 whitespace-nowrap px-3 py-1.5 text-muted-foreground\">\n {unsortableText()}\n </span>\n </li>\n )}\n <li role=\"none\">\n <button\n type=\"button\"\n role=\"menuitem\"\n className=\"block min-h-9 w-full whitespace-nowrap px-3 py-1.5 text-left hover:bg-muted\"\n onClick={() => {\n setOpen(false)\n onTogglePin()\n }}\n >\n {pinned ? text('unpin') : text('pinToLeft')}\n </button>\n </li>\n </ul>,\n document.body,\n )}\n </div>\n )\n}\n","import type { KeyboardEvent, PointerEvent } from 'react'\nimport { minColumnWidth } from './column-resize'\nimport { text } from './messages'\n\nexport type ColumnResize = {\n onPointerDown: (id: string, event: PointerEvent<HTMLElement>) => void\n onKeyDown: (id: string, event: KeyboardEvent<HTMLElement>) => void\n}\n\n/**\n * The right edge of a header cell, dragged to make its column wider or narrower. It sits beside the sort button rather\n * than in it, so a drag never sorts.\n */\nexport const ResizeHandle = ({ id, header, width, resize }: { id: string; header: string; width?: number; resize: ColumnResize }) => (\n <div\n role=\"separator\"\n aria-orientation=\"vertical\"\n aria-label={text('resizeColumn', { header })}\n aria-valuemin={minColumnWidth}\n aria-valuenow={width}\n tabIndex={0}\n onPointerDown={(event) => resize.onPointerDown(id, event)}\n onKeyDown={(event) => resize.onKeyDown(id, event)}\n className=\"group/resize absolute inset-y-0 right-0 z-10 flex w-2 cursor-col-resize touch-none justify-end outline-none\"\n >\n <div className=\"h-full w-0.5 bg-transparent group-hover/resize:bg-primary group-focus-visible/resize:bg-primary group-active/resize:bg-primary\" />\n </div>\n)\n","import { ArrowDown, ArrowUp, ChevronsUpDown } from 'lucide-react'\nimport { Checkbox } from '../primitives/checkbox'\nimport { cn } from '../lib/cn'\nimport { isRightAligned, type ColumnSpec } from './column-spec'\nimport { HeaderMenu, unsortableText } from './header-menu'\nimport { compactGutter, gridTemplate } from './grid-template'\nimport { text } from './messages'\nimport { ResizeHandle, type ColumnResize } from './resize-handle'\n\nexport type HeaderCell = { spec: ColumnSpec; sorted: 'asc' | 'desc' | false; onSort: (event: unknown) => void }\n\nexport type GridHeaderProps = {\n cells: HeaderCell[]\n specs: ColumnSpec[]\n gutter: number\n selectedCount: number\n selectable: boolean\n trailing?: number\n minScale?: number\n /** Left offsets of the pinned columns, by id. */\n pins?: Record<string, number>\n /** The pinned column next to the scrolling ones: it gets the edge shadow once the grid scrolls sideways. */\n lastPinned?: string\n scrolled?: boolean\n onTogglePin: (id: string) => void\n /** Lets each column be resized by dragging its header's right edge. */\n resize?: ColumnResize\n /** The widths columns were resized to, by id. */\n widths?: Record<string, number>\n onClearSelection: () => void\n}\n\nconst SortIcon = ({ sorted }: { sorted: HeaderCell['sorted'] }) => {\n if (sorted === 'asc') return <ArrowUp className=\"size-3 text-foreground\" />\n if (sorted === 'desc') return <ArrowDown className=\"size-3 text-foreground\" />\n return <ChevronsUpDown className=\"size-3 opacity-0 group-hover/head:opacity-100\" />\n}\n\nconst HeaderLabel = ({ spec }: { spec: ColumnSpec }) => (\n <>\n <span className=\"truncate\">{spec.header}</span>\n {spec.highlight && <span className=\"rounded bg-primary px-1 text-[0.625rem] font-semibold uppercase leading-4 text-primary-foreground\">{text('new')}</span>}\n </>\n)\n\nexport const GridHeader = ({ cells, specs, gutter, selectedCount, selectable, trailing, minScale, pins = {}, lastPinned, scrolled, onTogglePin, resize, widths = {}, onClearSelection }: GridHeaderProps) => (\n <div className=\"grid h-8 shrink-0 items-center border-b bg-surface text-body font-medium text-muted-foreground\" style={{ gridTemplateColumns: gridTemplate(specs, gutter, trailing, minScale) }} role=\"row\">\n <div className={cn('sticky left-0 z-10 flex h-full items-center gap-2 bg-inherit pl-3', scrolled && !lastPinned && 'shadow-[1px_0_0_var(--border),4px_0_6px_-2px_rgb(0_0_0/0.12)]')} style={{ width: gutter }}>\n {/* It only clears a selection, so with none it says so and cannot be pressed */}\n {selectable && <Checkbox checked={false} indeterminate={selectedCount > 0} label={selectedCount > 0 ? text('clearSelection') : text('noRowsSelected')} disabled={selectedCount === 0} onChange={onClearSelection} className={cn(selectedCount === 0 && 'opacity-60')} />}\n {gutter > compactGutter && <span className=\"w-6 text-right text-faint-foreground\">#</span>}\n </div>\n {cells.map(({ spec, sorted, onSort }) => {\n const pinned = spec.id in pins\n return (\n <div\n key={spec.id}\n data-col-id={spec.id}\n style={pinned ? { left: pins[spec.id] } : undefined}\n className={cn(\n 'group/cell flex h-full min-w-0 items-center',\n pinned ? 'sticky z-10 bg-inherit' : 'relative',\n pinned && scrolled && spec.id === lastPinned && 'shadow-[1px_0_0_var(--border),4px_0_6px_-2px_rgb(0_0_0/0.12)]',\n spec.highlight && 'bg-primary-soft text-primary-text',\n )}\n >\n {spec.sortable ? (\n <button\n type=\"button\"\n onClick={onSort}\n className={cn('group/head flex h-full min-w-0 flex-1 items-center gap-1 pl-3 pr-1 text-left', isRightAligned(spec.kind) && 'justify-end', 'hover:text-foreground', sorted && 'text-foreground')}\n >\n <HeaderLabel spec={spec} />\n <SortIcon sorted={sorted} />\n </button>\n ) : (\n // Not a button: nothing happens on a press, and a disabled button would not show its tooltip\n <div title={unsortableText()} className={cn('flex h-full min-w-0 flex-1 items-center gap-1 pl-3 pr-1 text-left', isRightAligned(spec.kind) && 'justify-end')}>\n <HeaderLabel spec={spec} />\n </div>\n )}\n <div className=\"pr-1.5\">\n <HeaderMenu header={spec.header} pinned={pinned} sortable={Boolean(spec.sortable)} onTogglePin={() => onTogglePin(spec.id)} />\n </div>\n {resize && <ResizeHandle id={spec.id} header={spec.header} width={widths[spec.id]} resize={resize} />}\n </div>\n )\n })}\n {trailing ? <div className=\"sticky right-0 z-10 h-full bg-inherit\" /> : null}\n </div>\n)\n","import type { HTMLAttributes, MouseEvent, ReactNode, Ref } from 'react'\nimport { formatInt } from '../format/number'\nimport { Checkbox } from '../primitives/checkbox'\nimport { Skeleton } from '../primitives/skeleton'\nimport { cn } from '../lib/cn'\nimport { isRightAligned, type ColumnSpec } from './column-spec'\nimport { compactGutter, gridTemplate } from './grid-template'\nimport { text } from './messages'\n\ntype RowFrame = { specs: ColumnSpec[]; gutter: number; index: number; offset: number; height: number; selectable: boolean; trailing?: number; minScale?: number; scrolled?: boolean; pins?: Record<string, number>; lastPinned?: string }\n\nconst frameStyle = (frame: RowFrame) => ({\n gridTemplateColumns: gridTemplate(frame.specs, frame.gutter, frame.trailing, frame.minScale),\n height: frame.height,\n transform: `translateY(${frame.offset}px)`,\n})\n\n/** Pinned cells need a solid background; `bg-inherit` takes the row's, so hover and selection still show. */\nconst cellClass = (spec: ColumnSpec, frame: Pick<RowFrame, 'pins' | 'lastPinned' | 'scrolled'>) =>\n cn(\n 'flex h-full min-w-0 items-center overflow-hidden whitespace-nowrap px-3',\n isRightAligned(spec.kind) && 'justify-end',\n spec.highlight && 'bg-primary-soft/60',\n frame.pins && spec.id in frame.pins && 'sticky z-10 bg-inherit',\n frame.scrolled && spec.id === frame.lastPinned && 'shadow-[1px_0_0_var(--border),4px_0_6px_-2px_rgb(0_0_0/0.12)]',\n )\n\nconst pinStyle = (spec: ColumnSpec, pins?: Record<string, number>) => (pins && spec.id in pins ? { left: pins[spec.id] } : undefined)\n\n/**\n * The selection column never scrolls away, so rows can be selected from anywhere in a wide grid.\n * The whole cell toggles the row instead of opening it; the checkbox's own click bubbles up to it.\n */\nconst Gutter = ({ width, index, selectable, selected, onToggle, edge }: { width: number; index: number; selectable: boolean; selected?: boolean; onToggle?: () => void; edge?: boolean }) => (\n <div\n onClick={selectable ? (event) => { event.stopPropagation(); onToggle?.() } : undefined}\n className={cn('sticky left-0 z-10 flex h-full items-center gap-2 bg-inherit pl-3', selectable && 'cursor-default', edge && 'shadow-[1px_0_0_var(--border),4px_0_6px_-2px_rgb(0_0_0/0.12)]')}\n style={{ width }}\n >\n {selectable && <Checkbox checked={Boolean(selected)} label={text('selectRow', { row: index + 1 })} />}\n {width > compactGutter && <span className=\"min-w-6 text-right text-[0.6875rem] tabular-nums text-faint-foreground\">{formatInt(index + 1)}</span>}\n </div>\n)\n\n/**\n * A cell of a row: its column and content and, in a grid whose cells are edited in place, its handlers and whether it\n * is the chosen cell, is being edited, or can be.\n */\nexport type RowCell = { spec: ColumnSpec; content: ReactNode; props?: HTMLAttributes<HTMLDivElement>; chosen?: boolean; editing?: boolean; editable?: boolean }\n\nexport type DataRowProps = RowFrame & {\n cells: RowCell[]\n selected: boolean\n /** The row the page shows the details of, marked `aria-current` and looking selected. */\n current?: boolean\n onToggle: () => void\n onOpen?: () => void\n menu?: ReactNode\n /**\n * A drag handle in the checkbox's place, for a row moved by hand, with the row's element, how far it is dragged and\n * its move back. Such a row is placed by `top`, since the drag library measures rows without their transforms.\n */\n handle?: ReactNode\n rowRef?: Ref<HTMLDivElement>\n dragY?: number\n transition?: string\n dragging?: boolean\n}\n\nconst dragStyle = (frame: RowFrame, dragY: number, transition: string | undefined) => ({\n gridTemplateColumns: gridTemplate(frame.specs, frame.gutter, frame.trailing, frame.minScale),\n height: frame.height,\n top: frame.offset,\n transform: dragY === 0 ? undefined : `translateY(${dragY}px)`,\n transition,\n})\n\n// A link in the row, such as its title, goes where it points itself: a Cmd-click opening it in a new tab leaves this one.\nconst openUnlessLink = (onOpen: () => void) => (event: MouseEvent) => {\n if ((event.target as Element).closest('a')) return\n onOpen()\n}\n\nexport const DataRow = ({ cells, selected, current = false, onToggle, onOpen, menu, handle, rowRef, dragY, transition, dragging, ...frame }: DataRowProps) => (\n <div\n ref={rowRef}\n role=\"row\"\n aria-current={current || undefined}\n data-pressable={onOpen ? '' : undefined}\n onClick={onOpen && openUnlessLink(onOpen)}\n className={cn('absolute inset-x-0 top-0 grid items-center border-b', selected || current ? 'bg-primary-soft' : 'bg-background hover:bg-surface', onOpen && 'cursor-pointer', dragging && 'z-30 bg-surface shadow-pop')}\n style={dragY === undefined ? frameStyle(frame) : dragStyle(frame, dragY, transition)}\n >\n {handle ? (\n <div className={cn('sticky left-0 z-10 flex h-full items-center bg-inherit pl-1.5', frame.scrolled && !frame.lastPinned && 'shadow-[1px_0_0_var(--border),4px_0_6px_-2px_rgb(0_0_0/0.12)]')} style={{ width: frame.gutter }}>\n {handle}\n </div>\n ) : (\n <Gutter width={frame.gutter} index={frame.index} selectable={frame.selectable} selected={selected} onToggle={onToggle} edge={frame.scrolled && !frame.lastPinned} />\n )}\n {cells.map(({ spec, content, props, chosen, editing, editable }) => (\n <div\n key={spec.id}\n role={props ? 'gridcell' : 'cell'}\n {...props}\n className={cn(\n cellClass(spec, frame),\n props && 'scroll-mb-[calc(var(--pb-sticky-bottom,0px)+3rem)] scroll-mt-[calc(var(--pb-sticky-top,0px)+2rem)] outline-none',\n editable && !editing && 'cursor-default',\n chosen && 'shadow-[inset_0_0_0_2px_var(--primary)]',\n editing && 'z-30 overflow-visible bg-background px-1',\n )}\n style={pinStyle(spec, frame.pins)}\n >\n {content}\n </div>\n ))}\n {/* The menu stays at the right edge while the row scrolls sideways */}\n {menu && <div className=\"sticky right-0 z-10 flex h-full items-center justify-center bg-inherit\">{menu}</div>}\n </div>\n)\n\nconst skeletonWidths = ['w-3/4', 'w-1/2', 'w-2/3', 'w-5/6', 'w-2/5']\n\nexport const SkeletonRow = (frame: RowFrame) => (\n <div role=\"row\" aria-busy className=\"absolute inset-x-0 top-0 grid items-center border-b bg-background\" style={frameStyle(frame)}>\n <Gutter width={frame.gutter} index={frame.index} selectable={false} edge={frame.scrolled && !frame.lastPinned} />\n {frame.specs.map((spec, column) => (\n <div key={spec.id} className={cellClass(spec, frame)} style={pinStyle(spec, frame.pins)}>\n <Skeleton className={cn('h-2.5', skeletonWidths[(frame.index + column) % skeletonWidths.length], isRightAligned(spec.kind) && 'ml-auto')} />\n </div>\n ))}\n </div>\n)\n","/** Browsers cap element height (about 17M px in the strictest); stay well below it. */\nexport const maxContentHeight = 10_000_000\n\nexport type Geometry = ReturnType<typeof gridGeometry>\n\n/** The list's height in the page, `contentHeight`: its true height, or the cap when the rows need more. */\nexport const gridGeometry = (total: number, rowHeight: number, viewportHeight: number) => {\n const trueHeight = total * rowHeight\n const contentHeight = Math.min(trueHeight, maxContentHeight)\n return {\n rowHeight,\n trueHeight,\n contentHeight,\n scaled: trueHeight > contentHeight,\n maxTop: Math.max(0, trueHeight - viewportHeight),\n maxScroll: Math.max(0, contentHeight - viewportHeight),\n }\n}\n\n/**\n * The offset into the rows (the virtual offset) shown at `position`, how far the top of the view is into the list.\n * They are the same unless the list is capped: then the capped range maps onto all the rows, and a position before or\n * after it moves one to one.\n */\nexport const topFromScroll = (geometry: Geometry, position: number) => {\n if (!geometry.scaled || position <= 0) return position\n if (position >= geometry.maxScroll) return geometry.maxTop + position - geometry.maxScroll\n return (position / geometry.maxScroll) * geometry.maxTop\n}\n\nexport const scrollFromTop = (geometry: Geometry, top: number) => {\n if (!geometry.scaled || top <= 0) return top\n if (top >= geometry.maxTop) return geometry.maxScroll + top - geometry.maxTop\n return (top / geometry.maxTop) * geometry.maxScroll\n}\n\n/**\n * Where row `index` is drawn in the list when the view at `position` shows the rows from `top`: its own place, or in a\n * capped list its place relative to the view, so that it scrolls with the page until the next draw.\n */\nexport const rowOffset = (geometry: Geometry, index: number, top: number, position: number) => {\n const offset = index * geometry.rowHeight\n return geometry.scaled ? offset - top + position : offset\n}\n\n/** The rows drawn for a scroll offset: those in a viewport of `height`, and `overscan` more on each side. */\nexport const rowsInView = (total: number, top: number, rowHeight: number, height: number, overscan: number) => {\n const first = Math.min(total, Math.max(0, Math.floor(top / rowHeight) - overscan))\n const last = Math.min(total - 1, Math.floor((top + height) / rowHeight) + overscan)\n return { first, last: Math.max(first - 1, last) }\n}\n","/**\n * The element that scrolls `element` up and down: its nearest ancestor that scrolls vertically, or the page's\n * scrolling element when none does.\n */\nexport const scrollParent = (element: HTMLElement) => {\n const page = document.scrollingElement ?? document.documentElement\n for (let parent = element.parentElement; parent && parent !== page && parent !== document.body; parent = parent.parentElement) {\n if (/auto|scroll/.test(getComputedStyle(parent).overflowY)) return parent\n }\n return page as HTMLElement\n}\n\nconst isPage = (scroller: HTMLElement) => scroller === (document.scrollingElement ?? document.documentElement)\n\n/** Where scroll events of `scroller` are sent: the window for the page. */\nexport const scrollEvents = (scroller: HTMLElement): EventTarget => (isPage(scroller) ? window : scroller)\n\nconst padding = (value: string) => Number.parseFloat(value) || 0\n\n/**\n * The part of `scroller` content shows in, in viewport coordinates: its box less its scroll padding, which is where\n * sticky bars over it say they are.\n */\nexport const visibleArea = (scroller: HTMLElement) => {\n const style = getComputedStyle(scroller)\n const box = isPage(scroller) ? { top: 0, height: scroller.clientHeight } : { top: scroller.getBoundingClientRect().top + scroller.clientTop, height: scroller.clientHeight }\n const top = padding(style.scrollPaddingTop)\n return { top: box.top + top, height: Math.max(0, box.height - top - padding(style.scrollPaddingBottom)) }\n}\n","import { useCallback, useLayoutEffect, useRef, useState } from 'react'\nimport { gridGeometry, rowOffset, rowsInView, scrollFromTop, topFromScroll } from './geometry'\nimport { scrollEvents, scrollParent, visibleArea } from './scroll-parent'\n\nexport type VirtualRowsOptions = {\n total: number\n rowHeight: number\n /** The row to start at, read when the list is ready to start; a fraction starts that far into the row. */\n initialIndex: number\n /** Height over the top of the rows that hides them, such as a sticky header, besides the scroller's scroll padding. */\n inset?: number\n /**\n * The offset to draw at for the scroll offset: after a layout change, where it moves to before the scroller has\n * caught up, so no row of the wrong place is drawn or loaded in between.\n */\n settle?: (top: number) => number\n /** Whether `rowHeight` is the rows' own, such as once they are measured: the list starts at `initialIndex` then. */\n ready?: boolean\n /**\n * Called with the offset into the rows at the top of the view, never below 0, whenever the view moves once the list\n * has started, so the list can come back to it with `initialIndex`.\n */\n onScroll?: (top: number) => void\n}\n\nconst overscan = 6\n\n/** How far the top of the view is into the list, and how tall the view is below the scroller's bars. */\ntype View = { position: number; height: number }\n\nconst viewRows = (view: View, total: number, rowHeight: number) => {\n const geometry = gridGeometry(total, rowHeight, view.height)\n const top = topFromScroll(geometry, view.position)\n return { geometry, top, topIndex: Math.floor(Math.max(0, top) / rowHeight), ...rowsInView(total, top, rowHeight, view.height, overscan) }\n}\n\n/**\n * Rows of a fixed height in a list as tall as all of them, scrolled natively by whatever scrolls it: the nearest\n * scrolling ancestor, or the page. Only the rows in view, and `overscan` more on each side, are drawn: `ref` goes on the\n * list's element, `geometry.contentHeight` tall, and each drawn row sits at `offset` from its top. Nothing listens for\n * wheel or touch: the list follows the scroll position, and draws again only when other rows come into view.\n * `first` and `last` are the indexes of the drawn rows, overscan included; `started` says whether the list has started\n * at `initialIndex`, read after the list's layout effects.\n */\nexport const useVirtualRows = <T extends HTMLElement>({ total, rowHeight, initialIndex, inset = 0, settle, ready = true, onScroll }: VirtualRowsOptions) => {\n const ref = useRef<T>(null)\n const scroller = useRef<HTMLElement | null>(null)\n const [view, setView] = useState<View>({ position: 0, height: 0 })\n const options = useRef({ total, rowHeight, initialIndex, inset, ready, onScroll })\n options.current = { total, rowHeight, initialIndex, inset, ready, onScroll }\n\n const read = useCallback((): View | undefined => {\n const content = ref.current\n if (!content || !scroller.current) return undefined\n const area = visibleArea(scroller.current)\n const hidden = options.current.inset\n return { position: area.top + hidden - content.getBoundingClientRect().top, height: Math.max(0, area.height - hidden) }\n }, [])\n\n // The list starts once, when its rows are ready and it has been laid out: at `initialIndex`, or at the top of its\n // scroller when that is the first row and the scroller is past it, as after a list scrolled down before. The first\n // resize observation comes after every effect of the commit that mounted the list, such as the page's sticky bars\n // saying how tall they are, and before it is painted. Until then the view is not where the list will be, so it is\n // not reported.\n const start = useRef({ pending: true, laidOut: false })\n\n // In a list that is not capped the drawn rows scroll with the page by themselves, so a scroll only draws again when\n // it brings other rows into view\n const shown = useRef(view)\n shown.current = view\n const measure = useCallback(() => {\n const next = read()\n if (!next) return\n const current = shown.current\n const { total, rowHeight, onScroll } = options.current\n const before = viewRows(current, total, rowHeight)\n const after = viewRows(next, total, rowHeight)\n if (!start.current.pending) onScroll?.(Math.max(0, after.top))\n const sameRows = !after.geometry.scaled && before.first === after.first && before.last === after.last && before.topIndex === after.topIndex\n if (current.height === next.height && (current.position === next.position || sameRows)) return\n shown.current = next\n setView(next)\n }, [read])\n\n const begin = useCallback(() => {\n if (!start.current.pending || !start.current.laidOut || !options.current.ready) return\n const view = read()\n const parent = scroller.current\n if (!view || !parent) return\n start.current.pending = false\n const { total, rowHeight, initialIndex } = options.current\n if (initialIndex > 0) parent.scrollTop += scrollFromTop(gridGeometry(total, rowHeight, view.height), initialIndex * rowHeight) - view.position\n else if (view.position > 0) parent.scrollTop = 0\n }, [read])\n\n useLayoutEffect(() => {\n const content = ref.current\n if (!content) return\n const parent = scrollParent(content)\n scroller.current = parent\n const events = scrollEvents(parent)\n events.addEventListener('scroll', measure, { passive: true })\n window.addEventListener('resize', measure, { passive: true })\n const observer = new ResizeObserver(() => {\n start.current.laidOut = true\n begin()\n measure()\n })\n observer.observe(parent)\n observer.observe(content)\n measure()\n return () => {\n events.removeEventListener('scroll', measure)\n window.removeEventListener('resize', measure)\n observer.disconnect()\n scroller.current = null\n }\n }, [measure, begin])\n\n // Anything above the list that changes height moves it in the page without a scroll\n useLayoutEffect(() => {\n begin()\n measure()\n })\n\n /** Scrolls to a virtual offset, for a layout change that keeps a row in view. */\n const scrollTo = useCallback(\n (top: number) => {\n const current = read()\n if (!current || !scroller.current) return\n const geometry = gridGeometry(options.current.total, options.current.rowHeight, current.height)\n scroller.current.scrollTop += scrollFromTop(geometry, top) - current.position\n measure()\n },\n [read, measure],\n )\n\n const started = useCallback(() => !start.current.pending, [])\n\n const drawn = viewRows(view, total, rowHeight)\n const top = settle ? settle(drawn.top) : drawn.top\n const { first, last } = settle ? rowsInView(total, top, rowHeight, view.height, overscan) : drawn\n const rows = Array.from({ length: last - first + 1 }, (_, offset) => ({ index: first + offset, offset: rowOffset(drawn.geometry, first + offset, top, view.position) }))\n return { ref, height: view.height, top, geometry: drawn.geometry, rows, first, last, scrollTo, started }\n}\n","/** A cell of the grid: its row's index among all rows, and its column. */\nexport type CellPlace = { index: number; column: string }\n\nexport type MoveKey = 'ArrowUp' | 'ArrowDown' | 'ArrowLeft' | 'ArrowRight'\n\nexport const isMoveKey = (key: string): key is MoveKey => key === 'ArrowUp' || key === 'ArrowDown' || key === 'ArrowLeft' || key === 'ArrowRight'\n\n/** The cell an arrow key moves to from `at` among `total` rows of `columns`, or undefined at the grid's edge. */\nexport const movedCell = (at: CellPlace, key: MoveKey, columns: readonly string[], total: number): CellPlace | undefined => {\n const column = columns.indexOf(at.column)\n if (key === 'ArrowUp') return at.index > 0 ? { ...at, index: at.index - 1 } : undefined\n if (key === 'ArrowDown') return at.index < total - 1 ? { ...at, index: at.index + 1 } : undefined\n const next = columns[key === 'ArrowLeft' ? column - 1 : column + 1]\n return column >= 0 && next !== undefined ? { ...at, column: next } : undefined\n}\n\n/** The editable column after (`1`) or before (`-1`) `column` in its row, or undefined when there is none. */\nexport const nextEditable = (column: string, columns: readonly string[], editable: (column: string) => boolean, direction: 1 | -1) => {\n const from = columns.indexOf(column)\n const after = direction === 1 ? columns.slice(from + 1) : columns.slice(0, Math.max(0, from)).reverse()\n return after.find(editable)\n}\n","import { useEffect, useRef, useState, type KeyboardEvent, type ReactNode, type RefObject } from 'react'\nimport type { GridRow } from './column-spec'\nimport { isMoveKey, movedCell, nextEditable, type CellPlace } from './cell-moves'\n\n/** Cells edited in place: a double-click, a click on the chosen cell, Enter or F2 opens the cell's editor. */\nexport type CellEditor = {\n /** Whether this row's cell of `column` is edited in place. */\n editable: (row: GridRow, column: string) => boolean\n /**\n * The editor in the cell. It calls `close` once it saved or gave up, with `move` to go on to the next (`1`) or the\n * previous (`-1`) editable cell of the row.\n */\n render: (row: GridRow, column: string, close: (move?: 1 | -1) => void) => ReactNode\n}\n\ntype Options = {\n editor: CellEditor | undefined\n columns: readonly string[]\n total: number\n /** The loaded row at an index, undefined while it loads. */\n rowAt: (index: number) => GridRow | undefined\n onOpenRow?: (row: GridRow) => void\n container: RefObject<HTMLElement | null>\n}\n\nconst placeId = (place: CellPlace) => `${place.index}:${place.column}`\n\n/**\n * The chosen cell and the one being edited, of a grid with an editor. The arrow keys, and Tab and Shift+Tab within a\n * row, move between cells; Enter opens the editor of an editable cell and the row of any other; Escape lets go of the\n * cell. A cell's mouse and keyboard handlers come from `cell`.\n */\nexport const useCellEditing = ({ editor, columns, total, rowAt, onOpenRow, container }: Options) => {\n const [active, setActive] = useState<CellPlace>()\n const [editing, setEditing] = useState(false)\n // A move by key or a closed editor brings the focus to the chosen cell; a scroll or a load does not take it.\n const refocus = useRef(false)\n // Whether the cell was already chosen when the pointer went down on it, before the focus chose it\n const pressedChosen = useRef(false)\n\n useEffect(() => {\n if (!active || editing || !refocus.current) return\n refocus.current = false\n const cell = container.current?.querySelector<HTMLElement>(`[data-cell=\"${placeId(active)}\"]`)\n if (!cell) return\n cell.focus({ preventScroll: true })\n cell.scrollIntoView({ block: 'nearest', inline: 'nearest' })\n }, [active, editing, container])\n\n if (!editor) return undefined\n\n const editableAt = (place: CellPlace) => {\n const row = rowAt(place.index)\n return row !== undefined && editor.editable(row, place.column)\n }\n const choose = (place: CellPlace, edit = false) => {\n refocus.current = true\n setActive(place)\n setEditing(edit && editableAt(place))\n }\n const close = (move?: 1 | -1) => {\n if (!active) return\n const row = rowAt(active.index)\n const next = move && row ? nextEditable(active.column, columns, (column) => editor.editable(row, column), move) : undefined\n // An editor closed by a click elsewhere leaves the focus where the click put it\n const focused = Boolean(container.current?.contains(document.activeElement))\n choose(next ? { ...active, column: next } : active, next !== undefined)\n refocus.current = focused\n }\n\n const onKeyDown = (event: KeyboardEvent) => {\n if (editing || !active || !(event.target instanceof HTMLElement) || event.target.dataset.cell !== placeId(active)) return\n const key = event.key === 'Tab' ? (event.shiftKey ? 'ArrowLeft' : 'ArrowRight') : event.key\n if (isMoveKey(key)) {\n const next = movedCell(active, key, columns, total)\n // Tab leaves the grid at the end of the row; an arrow stays on the edge, and on a row still loading\n if (!next && event.key === 'Tab') return\n event.preventDefault()\n if (next && rowAt(next.index)) choose(next)\n return\n }\n if (event.key === 'Enter' || event.key === 'F2') {\n event.preventDefault()\n const row = rowAt(active.index)\n if (editableAt(active)) choose(active, true)\n else if (event.key === 'Enter' && row) onOpenRow?.(row)\n return\n }\n if (event.key === 'Escape') setActive(undefined)\n }\n\n /** What a cell of the grid needs: its content, its handlers, and whether it is chosen or being edited. */\n const cell = (index: number, row: GridRow, column: string, content: ReactNode) => {\n const place = { index, column }\n const chosen = active?.index === index && active.column === column\n const editable = editor.editable(row, column)\n // The chosen cell takes Tab into the grid; without one, the first cell of the first row does\n const reachable = chosen || (!active && index === 0 && column === columns[0])\n return {\n content: chosen && editing ? editor.render(row, column, close) : content,\n chosen,\n editing: chosen && editing,\n editable,\n props: {\n 'data-cell': placeId(place),\n tabIndex: reachable ? 0 : -1,\n 'aria-selected': chosen,\n onMouseDown: () => {\n pressedChosen.current = chosen\n },\n onFocus: (event: { target: EventTarget; currentTarget: EventTarget }) => {\n if (event.target === event.currentTarget && !chosen) setActive(place)\n },\n // An editable cell is chosen by a click instead of opening its row, and edited by a second one\n onClick: (event: { stopPropagation: () => void }) => {\n if (!editable) return\n event.stopPropagation()\n if (pressedChosen.current && !editing) choose(place, true)\n },\n onDoubleClick: (event: { stopPropagation: () => void }) => {\n if (!editable) return\n event.stopPropagation()\n if (!(chosen && editing)) choose(place, true)\n },\n },\n }\n }\n\n return { cell, onKeyDown }\n}\n","import { DndContext, KeyboardSensor, MouseSensor, TouchSensor, closestCenter, useSensor, useSensors, type Announcements, type DragEndEvent } from '@dnd-kit/core'\nimport { SortableContext, sortableKeyboardCoordinates, useSortable, verticalListSortingStrategy } from '@dnd-kit/sortable'\nimport { GripVertical } from 'lucide-react'\nimport type { ReactNode } from 'react'\nimport type { GridRow } from './column-spec'\nimport { DataRow, type DataRowProps } from './grid-row'\nimport { text } from './messages'\n\n/** Rows moved by a drag handle in place of their checkbox: `onMove` gets the row's index and the index it is dropped at. */\nexport type RowReorder = {\n onMove: (from: number, to: number) => void\n /** How a row reads to a screen reader, such as its title. */\n label: (row: GridRow) => string\n}\n\n/** The rows of a grid that are moved by hand, `ids` in their order, each loaded or not, so the drop's index is the row's place in the whole list. */\nexport const ReorderRows = ({ ids, rowAt, reorder, children }: { ids: string[]; rowAt: (index: number) => GridRow | undefined; reorder: RowReorder; children: ReactNode }) => {\n // A mouse starts dragging after a few pixels; a finger only after a short press, so the page still scrolls\n const sensors = useSensors(\n useSensor(MouseSensor, { activationConstraint: { distance: 4 } }),\n useSensor(TouchSensor, { activationConstraint: { delay: 250, tolerance: 5 } }),\n useSensor(KeyboardSensor, { coordinateGetter: sortableKeyboardCoordinates }),\n )\n const place = (id: string | number | undefined) => ids.indexOf(String(id))\n const name = (id: string | number) => {\n const row = rowAt(place(id))\n return row ? reorder.label(row) : text('row')\n }\n const announcements: Announcements = {\n onDragStart: ({ active }) => text('pickedUp', { name: name(active.id), row: place(active.id) + 1, rows: ids.length }),\n onDragOver: ({ active, over }) => (over ? text('isOver', { name: name(active.id), row: place(over.id) + 1, rows: ids.length }) : undefined),\n onDragEnd: ({ active, over }) => (over ? text('droppedAt', { name: name(active.id), row: place(over.id) + 1, rows: ids.length }) : text('putBack', { name: name(active.id) })),\n onDragCancel: ({ active }) => text('cancelled', { name: name(active.id), row: place(active.id) + 1 }),\n }\n const end = ({ active, over }: DragEndEvent) => {\n if (!over || active.id === over.id) return\n reorder.onMove(place(active.id), place(over.id))\n }\n return (\n <DndContext sensors={sensors} collisionDetection={closestCenter} onDragEnd={end} accessibility={{ announcements, screenReaderInstructions: { draggable: text('reorderInstructions') } }}>\n <SortableContext items={ids} strategy={verticalListSortingStrategy}>\n {children}\n </SortableContext>\n </DndContext>\n )\n}\n\n/** A row moved by its handle, which takes the checkbox's place; it follows the pointer up and down only. */\nexport const SortableRow = ({ row, label, ...props }: Omit<DataRowProps, 'handle' | 'rowRef' | 'dragY' | 'transition' | 'dragging'> & { row: GridRow; label: string }) => {\n const { attributes, listeners, setNodeRef, setActivatorNodeRef, transform, transition, isDragging } = useSortable({ id: row.id })\n const handle = (\n <button\n ref={setActivatorNodeRef}\n type=\"button\"\n aria-label={text('move', { label })}\n {...attributes}\n {...listeners}\n // The row opens its record on a click, which the handle is not\n onClick={(event) => event.stopPropagation()}\n style={{ touchAction: 'none' }}\n className=\"flex size-7 cursor-grab items-center justify-center rounded text-faint-foreground hover:bg-muted hover:text-foreground focus-visible:text-foreground active:cursor-grabbing pointer-coarse:size-9\"\n >\n <GripVertical className=\"size-4\" />\n </button>\n )\n return <DataRow {...props} rowRef={setNodeRef} handle={handle} dragY={transform?.y ?? 0} transition={transition} dragging={isDragging} />\n}\n","import { useTable, type SortingState } from '@tanstack/react-table'\nimport { useCallback, useLayoutEffect, useMemo, useRef, useState } from 'react'\nimport { cn } from '../lib/cn'\nimport type { ColumnSpec, GridRow } from './column-spec'\nimport { buildColumns, features } from './columns'\nimport { offeredBulkActions, oneBulkRunAtATime, type BulkAction } from './bulk-actions'\nimport { GridFooter } from './grid-footer'\nimport { RowMenu, availableActions, type RowAction } from './row-menu'\nimport { compactGutter, desktopMinScale, gridMinWidth, gutterWidthFor, rowMenuWidth } from './grid-template'\nimport { useHorizontalScroll } from './use-horizontal-scroll'\nimport { usePinnedColumns } from './use-pinned-columns'\nimport { defaultPins } from './default-pins'\nimport { useFittedColumns } from './use-fitted-columns'\nimport { withResizedWidths } from './column-resize'\nimport { useColumnResize } from './use-column-resize'\nimport { useIsDesktop } from '../lib/use-media-query'\nimport { useRootFontSize } from '../lib/use-root-font-size'\nimport { gridHeights } from './grid-heights'\nimport { GridHeader } from './grid-header'\nimport { DataRow, SkeletonRow } from './grid-row'\nimport type { RowSource } from './row-source'\nimport { usePagedRows } from './use-paged-rows'\nimport { useVirtualRows } from './use-virtual-rows'\nimport { useCellEditing, type CellEditor } from './use-cell-editing'\nimport { ReorderRows, SortableRow, type RowReorder } from './row-reorder'\nimport { RouteLink, type RouteTarget } from '../primitives/route-link'\n\nexport type DataGridProps = {\n columns: ColumnSpec[]\n source: RowSource\n /** The order in which `source` yields rows; sorting the other way flips the index mapping. */\n naturalSort?: { columnId: string; direction: 'asc' | 'desc' }\n /** The row to start at; a fraction starts that far into the row. */\n initialScrollIndex?: number\n /** Called with the row at the top of the view, and how far into it, as the view moves, to come back to it with `initialScrollIndex`. */\n onScrollIndex?: (index: number) => void\n /** Simulated page load time for mock sources. 0 loads synchronously. */\n latencyMs?: number\n /** Controlled sorting, for sources that sort on the server. Without it, sorting flips the mock source. */\n sort?: { columnId: string; direction: 'asc' | 'desc' }\n onSortChange?: (sort: { columnId: string; direction: 'asc' | 'desc' }) => void\n onOpenRow?: (row: GridRow) => void\n /**\n * Where a row's record is: its title cell (the `title` column, else the first) links there, so it opens in a new tab\n * or is copied as any link is. A cell edited in place is no link, since a click there chooses it.\n */\n rowLink?: (row: GridRow) => RouteTarget\n /** The id of the row the page shows the details of, such as the row chosen in its address; it looks selected. */\n chosenRow?: string\n /** Entries of the \"...\" menu at the end of each row; a row none apply to gets no menu, but keeps the column. */\n rowActions?: RowAction[]\n /** Cells edited in place, between which the arrow keys and Tab move. */\n cellEditor?: CellEditor\n /** Values to show over the loaded rows', by row id, such as those of edits saving or saved since the rows loaded. */\n rowPatches?: ReadonlyMap<string, Partial<GridRow>>\n /** Buttons shown next to the selection count, run on the selected rows. */\n bulkActions?: BulkAction[]\n /** Where to remember pinned columns in local storage, for example one key per user and resource. */\n pinKey?: string\n /** Show the row number next to the checkbox; without it the selection column is a narrow strip. */\n rowNumbers?: boolean\n /** Columns pinned until the user chooses otherwise. */\n defaultPinned?: string[]\n compact?: boolean\n selectable?: boolean\n /** Rows moved by a drag handle in place of the checkbox, every row of `source` loaded; nothing is selected meanwhile. */\n reorder?: RowReorder\n /** Sized to show every row of `source` without scrolling, for a few rows shown whole, without the footer unless it offers `bulkActions` for selected rows. */\n fit?: boolean\n /**\n * What scrolls the rows: `own`, a scroller of the grid's own in the height it is given, or `parent`, the nearest\n * scrolling ancestor or else the page, the grid as tall as all its rows with its header and footer sticky in it.\n */\n scroll?: 'own' | 'parent'\n className?: string\n}\n\nexport const DataGrid = ({ columns: given, source, naturalSort, initialScrollIndex = 0, onScrollIndex, latencyMs = 150, sort: controlledSort, onSortChange, onOpenRow, rowLink, chosenRow, rowActions, cellEditor, rowPatches, bulkActions, pinKey, defaultPinned, rowNumbers = true, compact = false, selectable: selecting = true, reorder, fit = false, scroll = 'own', className }: DataGridProps) => {\n const selectable = selecting && !reorder\n const { header: headerHeight, row: rowHeight, footer: footerHeight } = gridHeights(useRootFontSize(), { compact, withBelow: given.some((spec) => spec.below) })\n const narrow = !useIsDesktop()\n // A phone keeps every column whole, so pinning there could leave nothing to scroll\n const pinsByDefault = (defaultPinned ?? (narrow ? [] : defaultPins(given))).join(' ')\n // Kept while the ids are the same: a new list of pins reorders the columns, which draws every cell anew\n const initialPins = useMemo(() => (pinsByDefault ? pinsByDefault.split(' ') : []), [pinsByDefault])\n const [pinned, setPinned] = usePinnedColumns(pinKey, initialPins)\n const columns = useMemo(() => {\n const first = pinned.flatMap((id) => given.find((spec) => spec.id === id) ?? [])\n return [...first, ...given.filter((spec) => !pinned.includes(spec.id))]\n }, [given, pinned])\n const pinnedIds = columns.slice(0, columns.filter((spec) => pinned.includes(spec.id)).length).map((spec) => spec.id)\n const { total } = source\n const [localSorting, setLocalSorting] = useState<SortingState>(naturalSort ? [{ id: naturalSort.columnId, desc: naturalSort.direction === 'desc' }] : [])\n const sorting: SortingState = controlledSort ? [{ id: controlledSort.columnId, desc: controlledSort.direction === 'desc' }] : localSorting\n const setSorting = (updater: SortingState | ((current: SortingState) => SortingState)) => {\n const next = typeof updater === 'function' ? updater(sorting) : updater\n const first = next[0]\n if (onSortChange && first) onSortChange({ columnId: first.id, direction: first.desc ? 'desc' : 'asc' })\n if (!controlledSort) setLocalSorting(next)\n }\n const [rowSelection, setRowSelection] = useState({})\n const tableColumns = useMemo(() => buildColumns(columns), [columns])\n\n const sort = sorting[0]\n const reverse = Boolean(!controlledSort && naturalSort && sort && sort.id === naturalSort.columnId && (sort.desc ? 'desc' : 'asc') !== naturalSort.direction)\n const sourceRowAt = source.rowAt\n const rowAt = useCallback((index: number) => sourceRowAt!(reverse ? total - 1 - index : index), [sourceRowAt, reverse, total])\n\n const [startIndex] = useState(initialScrollIndex)\n const onScroll = onScrollIndex && ((offset: number) => onScrollIndex(offset / rowHeight))\n const { ref, geometry, rows: virtualRows, first: firstIndex, last: lastIndex } = useVirtualRows<HTMLDivElement>({ total, rowHeight, initialIndex: startIndex, inset: headerHeight, onScroll })\n const gutter = narrow || !rowNumbers ? compactGutter : gutterWidthFor(total)\n const getRow = usePagedRows({ total, rowAt: sourceRowAt ? rowAt : undefined, loadRows: source.loadRows, cachedRows: source.cachedRows, revision: source.revision, latencyMs }, firstIndex, lastIndex)\n\n const patchedRow = useCallback((index: number) => {\n const row = getRow(index)\n const patch = row && rowPatches?.get(row.id)\n return patch ? { ...row, ...patch } : row\n }, [getRow, rowPatches])\n const loaded = virtualRows.map(({ index, offset }) => ({ index, offset, row: patchedRow(index) }))\n const data = useMemo(() => loaded.flatMap(({ row }) => (row ? [row] : [])), [patchedRow, firstIndex, lastIndex])\n // The header scrolls sideways with the rows, outside them so that it can stick to the top of a page\n const headerRef = useRef<HTMLDivElement>(null)\n const resize = useColumnResize(headerRef)\n const fitted = useFittedColumns(columns, data)\n const sized = useMemo(() => withResizedWidths(fitted, resize.widths), [fitted, resize.widths])\n const table = useTable({\n features,\n columns: tableColumns,\n data,\n state: { sorting, rowSelection },\n onSortingChange: setSorting,\n onRowSelectionChange: setRowSelection,\n manualSorting: true,\n enableMultiSort: false,\n enableSortingRemoval: false,\n getRowId: (row) => row.id,\n })\n const tableRows = new Map(table.getRowModel().rows.map((row) => [row.id, row]))\n const selectedCount = Object.keys(rowSelection).length\n const selectedRows = useRef(new Map<string, GridRow>())\n const [runBulkAction] = useState(oneBulkRunAtATime)\n for (const row of table.getRowModel().rows) if (row.getIsSelected()) selectedRows.current.set(row.id, row.original)\n const trailing = rowActions && rowActions.length > 0 ? rowMenuWidth : 0\n const minScale = narrow ? 1 : desktopMinScale\n const horizontal = useHorizontalScroll()\n const onBodyScroll = () => {\n horizontal.onScroll()\n if (headerRef.current && horizontal.ref.current) headerRef.current.scrollLeft = horizontal.ref.current.scrollLeft\n }\n const [pins, setPins] = useState<Record<string, number>>({})\n useLayoutEffect(() => {\n const header = headerRef.current?.querySelector('[role=row]')\n if (!header) return\n let left = gutter\n const next: Record<string, number> = {}\n for (const id of pinnedIds) {\n next[id] = left\n left += header.querySelector<HTMLElement>(`[data-col-id=\"${id}\"]`)?.offsetWidth ?? 0\n }\n if (JSON.stringify(pins) !== JSON.stringify(next)) setPins(next)\n })\n const lastPinned = pinnedIds.at(-1)\n const togglePin = (id: string) => setPinned(pinned.includes(id) ? pinned.filter((entry) => entry !== id) : [...pinned, id])\n\n const headerCells = table.getHeaderGroups().flatMap((group) =>\n group.headers.map((header) => ({\n spec: columns.find((spec) => spec.id === header.column.id)!,\n sorted: header.column.getIsSorted(),\n onSort: (event: unknown) => header.column.getToggleSortingHandler()?.(event),\n })),\n )\n\n const gridRef = useRef<HTMLDivElement>(null)\n const columnIds = useMemo(() => columns.map((spec) => spec.id), [columns])\n const cellEditing = useCellEditing({ editor: cellEditor, columns: columnIds, total, rowAt: patchedRow, onOpenRow, container: gridRef })\n const linkColumn = (columns.find((spec) => spec.title) ?? columns[0])?.id\n\n const minWidth = gridMinWidth(sized, gutter, trailing, minScale)\n const own = scroll === 'own'\n // A grid sized to its rows has no footer, unless its rows can be selected for bulk actions, which it offers\n const footer = !fit || (selectable && Boolean(bulkActions?.length))\n const header = (\n <div ref={headerRef} className={cn('sticky z-20 shrink-0 overflow-hidden', own ? 'top-0' : 'top-[var(--pb-sticky-top,0px)]')}>\n <div style={{ minWidth }}>\n <GridHeader cells={headerCells} specs={sized} gutter={gutter} trailing={trailing} minScale={minScale} pins={pins} lastPinned={lastPinned} scrolled={horizontal.scrolled} onTogglePin={togglePin} resize={resize} widths={resize.widths} selectable={selectable} selectedCount={selectedCount} onClearSelection={() => setRowSelection({})} />\n </div>\n </div>\n )\n const rowsInView = loaded.map(({ index, offset, row }) => {\n const frame = { specs: sized, gutter, index, offset, height: rowHeight, selectable, trailing, minScale, scrolled: horizontal.scrolled, pins, lastPinned }\n const tableRow = row ? tableRows.get(row.id) : undefined\n if (!tableRow || !row) return <SkeletonRow key={`skeleton-${index}`} {...frame} />\n const actions = trailing ? availableActions(rowActions!, row) : []\n const props = {\n ...frame,\n selected: tableRow.getIsSelected(),\n current: row.id === chosenRow,\n onToggle: () => tableRow.toggleSelected(),\n onOpen: onOpenRow ? () => onOpenRow(row) : undefined,\n menu: actions.length > 0 ? <RowMenu row={row} actions={actions} /> : undefined,\n cells: tableRow.getAllCells().map((cell) => {\n const spec = columns.find((column) => column.id === cell.column.id)!\n const content = <table.FlexRender cell={cell} />\n const editable = Boolean(cellEditor?.editable(row, cell.column.id))\n const linked = rowLink && cell.column.id === linkColumn && !editable ? <RouteLink to={rowLink(row)} className=\"flex min-w-0 items-center hover:underline\">{content}</RouteLink> : content\n const stacked = spec.below ? <div className=\"flex min-w-0 flex-col items-start gap-1\">{linked}{spec.below(row)}</div> : linked\n return { spec, ...(cellEditing ? cellEditing.cell(index, row, cell.column.id, stacked) : { content: stacked }) }\n }),\n }\n return reorder ? <SortableRow key={row.id} {...props} row={row} label={reorder.label(row)} /> : <DataRow key={row.id} {...props} />\n })\n const body = (\n <div ref={horizontal.attach} onScroll={onBodyScroll} className=\"overflow-x-auto overflow-y-hidden overscroll-x-contain [-webkit-overflow-scrolling:touch]\">\n <div ref={ref} className=\"relative\" style={{ minWidth, height: geometry.contentHeight }}>\n {reorder ? (\n <ReorderRows ids={Array.from({ length: total }, (_, index) => patchedRow(index)?.id ?? `missing-${index}`)} rowAt={patchedRow} reorder={reorder}>\n {rowsInView}\n </ReorderRows>\n ) : (\n rowsInView\n )}\n </div>\n </div>\n )\n\n return (\n <div\n ref={gridRef}\n role=\"grid\"\n aria-rowcount={total}\n onKeyDown={cellEditing?.onKeyDown}\n className={cn('flex flex-col rounded-lg border bg-background', own ? 'min-h-0 overflow-hidden' : 'overflow-clip', className)}\n style={fit && own ? { height: headerHeight + total * rowHeight + (footer ? footerHeight : 0) + 2 } : undefined}\n >\n <div className={cn('relative', own && 'flex min-h-0 flex-1 flex-col')}>\n {own ? (\n <div className=\"min-h-0 flex-1 overflow-y-auto overflow-x-hidden\">\n {header}\n {body}\n </div>\n ) : (\n <>\n {header}\n {body}\n </>\n )}\n {horizontal.more && <div aria-hidden className=\"pointer-events-none absolute inset-y-0 right-0 z-20 w-8 bg-gradient-to-l from-backdrop/15 to-transparent\" />}\n </div>\n {footer && (\n <GridFooter\n total={total}\n className={own ? undefined : 'sticky bottom-[var(--pb-sticky-bottom,0px)] z-20'}\n selectedCount={selectedCount}\n bulkActions={offeredBulkActions(bulkActions ?? [], Object.keys(rowSelection).flatMap((id) => selectedRows.current.get(id) ?? [])).map(({ action, rows, skipped }) => ({\n label: action.label(rows.length),\n destructive: action.destructive,\n // The selection stays while the action asks first, and keeps the rows it leaves open, such as refused ones\n onRun: () =>\n void runBulkAction(action, rows, skipped).then((done) => {\n if (!done) return\n const ids = new Set(done.map((row) => row.id))\n setRowSelection((current) => Object.fromEntries(Object.entries(current).filter(([id]) => !ids.has(id))))\n for (const id of ids) selectedRows.current.delete(id)\n }),\n }))}\n />\n )}\n </div>\n )\n}\n","import { messages } from '../../locale/messages'\n\nexport const text = messages('app/searches')\n","import type { FilterChip } from '../../filter-panel'\nimport { cn } from '../../lib/cn'\nimport { text } from './messages'\n\nconst chipClass = 'inline-flex h-6 items-center rounded-full border border-primary-border bg-primary-soft px-2.5 text-xs font-medium text-primary-text'\n\n/** What a filter filters on, concisely: its chips as a list labelled \"Filters\". */\nexport const FilterChipList = ({ chips, className }: { chips: readonly FilterChip[]; className?: string }) => (\n <ul className={cn('flex flex-wrap gap-1.5', className)} aria-label={text('filters')}>\n {chips.map((chip) => (\n <li key={chip.key} className={chipClass}>\n {chip.label}\n </li>\n ))}\n </ul>\n)\n\n/** A filter's chips inside a heading or a link, where a list cannot go: read out one after the other. */\nexport const InlineFilterChips = ({ chips }: { chips: readonly FilterChip[] }) => (\n <span className=\"flex flex-wrap gap-1.5\">\n {chips.map((chip, index) => (\n <span key={chip.key} className={chipClass}>\n {index > 0 && <span className=\"sr-only\">, </span>}\n {chip.label}\n </span>\n ))}\n </span>\n)\n\n/** A search without a name as words, for a label or a question: its chips one after the other. */\nexport const chipsText = (chips: readonly FilterChip[]) => chips.map((chip) => chip.label).join(', ')\n","import { messages } from '../locale/messages'\n\nexport const text = messages('filter-panel')\n","import type { DatePreset } from '@protobase/schema'\nimport { text } from './messages'\n\n/** `count` is left out when it is not known, such as for a record found by a search. */\nexport type FacetOption = { value: string; label: string; count?: number }\n\nexport type FacetGroupConfig = {\n id: string\n label: string\n options: FacetOption[]\n searchable?: boolean\n /** A dropdown that searches as you type and holds several choices, instead of a list of checkboxes. */\n combobox?: boolean\n /** Names of chosen values that are not among `options`, such as those picked from an earlier search. */\n labels?: Record<string, string>\n /** Called as the search text changes, the options then being the matches; without it the options are filtered here. */\n onSearch?: (text: string) => void\n /** The options are boolean fields by name, and a record shows when any chosen one is true. */\n flags?: boolean\n /** Behind the bar's \"More filters\" menu until picked there or set. */\n secondary?: boolean\n}\n\nexport type RangeConfig = {\n id: string\n label: string\n min: number\n max: number\n step: number\n /** Bar heights (counts) of the histogram drawn behind the slider. */\n histogram: number[]\n format: (value: number) => string\n /** Behind the bar's \"More filters\" menu until picked there or set. */\n secondary?: boolean\n}\n\nexport type DatePresetId = DatePreset\n\nexport type ToggleConfig = {\n id: string\n label: string\n /** Behind the bar's \"More filters\" menu until picked there or set. */\n secondary?: boolean\n}\n\nexport type FilterConfig = {\n facets: FacetGroupConfig[]\n ranges?: RangeConfig[]\n /** `true` shows the default presets; a list shows exactly those. */\n datePresets?: boolean | DatePresetId[]\n /** The field the date presets filter on, for configs that talk to a server. */\n dateField?: string\n /** Whether `dateField` holds dates or timestamps; calendar presets are printed as that literal. */\n dateKind?: 'date' | 'timestamp'\n /** The date presets are behind the bar's \"More filters\" menu until picked there or set. */\n dateSecondary?: boolean\n toggles?: ToggleConfig[]\n}\n\nexport type FilterState = {\n facets: Record<string, string[]>\n /** The selected span of each range, by its id; a range without one is not filtered on. */\n ranges?: Record<string, [number, number]>\n date?: DatePresetId\n toggles: string[]\n}\n\nexport const defaultDatePresets: DatePresetId[] = ['today', '7d', '30d', 'year']\n\nconst knownPresets = new Set<string>(['today', 'yesterday', '24h', '7d', '30d', '90d', 'month', 'quarter', 'year'] satisfies DatePresetId[])\n\n/** A date preset's label in the screens' language; undefined for one the server offers that this UI does not know. */\nexport const datePresetLabel = (id: DatePresetId) => (knownPresets.has(id) ? text(id) : undefined)\n","import { datePresetLabel, type FacetGroupConfig, type FilterConfig, type FilterState } from './filter-config'\n\nexport const emptyFilterState: FilterState = { facets: {}, toggles: [] }\n\nexport type FilterChip = { key: string; label: string }\n\nexport const toggleFacetValue = (state: FilterState, group: string, value: string): FilterState => {\n const current = state.facets[group] ?? []\n const next = current.includes(value) ? current.filter((entry) => entry !== value) : [...current, value]\n return { ...state, facets: { ...state.facets, [group]: next } }\n}\n\nexport const toggleFlag = (state: FilterState, id: string): FilterState => ({\n ...state,\n toggles: state.toggles.includes(id) ? state.toggles.filter((entry) => entry !== id) : [...state.toggles, id],\n})\n\n/** Sets or, with `undefined`, clears the span of one range. */\nexport const setRange = (state: FilterState, id: string, value: [number, number] | undefined): FilterState => {\n const { [id]: _, ...others } = state.ranges ?? {}\n return { ...state, ranges: value ? { ...others, [id]: value } : others }\n}\n\n/** A facet value's name: its option's label, else a name the group knows for it, else the value itself. */\nexport const facetLabel = (group: FacetGroupConfig, value: string) =>\n group.options.find((option) => option.value === value)?.label ?? group.labels?.[value] ?? value\n\nexport const activeChips = (config: FilterConfig, state: FilterState): FilterChip[] => {\n const facetChips = config.facets.flatMap((group) =>\n (state.facets[group.id] ?? []).map((value) => ({ key: `facet:${group.id}:${value}`, label: `${group.label}: ${facetLabel(group, value)}` })),\n )\n const rangeChips = (config.ranges ?? []).flatMap((range) => {\n const span = state.ranges?.[range.id]\n return span ? [{ key: `range:${range.id}`, label: `${range.label}: ${range.format(span[0])} – ${range.format(span[1])}` }] : []\n })\n const dateChips = state.date ? [{ key: 'date', label: datePresetLabel(state.date) ?? state.date }] : []\n const toggleChips = state.toggles.map((id) => ({ key: `toggle:${id}`, label: config.toggles?.find((toggle) => toggle.id === id)?.label ?? id }))\n return [...facetChips, ...rangeChips, ...dateChips, ...toggleChips]\n}\n\nexport const removeChip = (state: FilterState, key: string): FilterState => {\n if (key === 'date') return { ...state, date: undefined }\n const [kind, group, value] = key.split(':')\n if (kind === 'range') return setRange(state, group!, undefined)\n if (kind === 'toggle') return toggleFlag(state, group!)\n if (kind === 'facet') return toggleFacetValue(state, group!, value!)\n throw new Error(`Unknown filter chip key: ${key}`)\n}\n\nexport const matchesSearch = (label: string, query: string) => label.toLowerCase().includes(query.trim().toLowerCase())\n","import { createWhere, parseFilter, printFilter, type FilterError, type FilterExpr } from '@protobase/schema'\nimport type { DatePresetId, FilterConfig, FilterState } from '../filter-panel'\nimport { dayIn, startOfDayIn, viewerZone } from '../format/zone'\n\nconst w = createWhere()\nconst span = { start: 0, end: 0 }\n\n/** The widgets a `FilterConfig` talks to, by field name. */\ntype Fields = Pick<FilterConfig, 'facets' | 'ranges' | 'dateField' | 'dateKind' | 'toggles'>\n\nconst relative = { '24h': { amount: 24, unit: 'h' }, '7d': { amount: 7, unit: 'd' }, '30d': { amount: 30, unit: 'd' }, '90d': { amount: 90, unit: 'd' } } as const\n\nconst iso = (ms: number) => new Date(ms).toISOString().replace('.000Z', 'Z')\n\n/** The first day of the period a calendar preset starts at, as `YYYY-MM-DD` on the clock of `zone`. */\nexport const periodStart = (preset: DatePresetId, now: Date, zone: string) => {\n const today = dayIn(now.getTime(), zone)\n const [year, month] = [Number(today.slice(0, 4)), Number(today.slice(5, 7)) - 1]\n const day = (ms: number) => new Date(ms).toISOString().slice(0, 10)\n if (preset === 'year') return day(Date.UTC(year, 0, 1))\n if (preset === 'quarter') return day(Date.UTC(year, Math.floor(month / 3) * 3, 1))\n if (preset === 'month') return day(Date.UTC(year, month, 1))\n if (preset === 'yesterday') return day(Date.parse(`${today}T00:00:00Z`) - 86_400_000)\n return today\n}\n\nconst calendarPresets: DatePresetId[] = ['year', 'quarter', 'month', 'yesterday', 'today']\n\n/** The literal a day starts at: the plain date for a date field, its first instant in `zone` for a timestamp field. */\nconst dayLiteral = (day: string, kind: Fields['dateKind'], zone: string) => (kind === 'date' ? day : iso(startOfDayIn(day, zone)))\n\nconst instant = (day: string, kind: Fields['dateKind'], zone: string) =>\n kind === 'date' ? { kind: 'string' as const, value: dayLiteral(day, kind, zone), span } : { kind: 'timestamp' as const, value: dayLiteral(day, kind, zone), span }\n\nconst dateClauses = (field: string, preset: DatePresetId, now: Date, kind: Fields['dateKind'], zone: string): FilterExpr[] => {\n if (preset in relative) return [w.gte(field, w.ago(preset))]\n const from = w.gte(field, instant(periodStart(preset, now, zone), kind, zone))\n return preset === 'yesterday' ? [from, w.lt(field, instant(periodStart('today', now, zone), kind, zone))] : [from]\n}\n\n/** The panel's state as filter clauses, in a fixed order so the text is stable; calendar presets start at midnight in `zone`. */\nexport const stateToClauses = (config: Fields, state: FilterState, now = new Date(), zone = viewerZone()): FilterExpr[] => {\n const facets = config.facets.flatMap((group) => {\n const values = state.facets[group.id] ?? []\n if (values.length === 0) return []\n if (group.flags) {\n const chosen = group.options.filter((option) => values.includes(option.value)).map((option) => w.eq(option.value, true))\n return chosen.length === 0 ? [] : [chosen.length === 1 ? chosen[0]! : w.or(...chosen)]\n }\n return [values.length === 1 ? w.eq(group.id, values[0]!) : w.in(group.id, values)]\n })\n const ranges = (config.ranges ?? []).flatMap((range) => {\n const span = state.ranges?.[range.id]\n return span ? [w.gte(range.id, span[0]), w.lte(range.id, span[1])] : []\n })\n const date = config.dateField && state.date ? dateClauses(config.dateField, state.date, now, config.dateKind, zone) : []\n const toggles = (config.toggles ?? []).filter((toggle) => state.toggles.includes(toggle.id)).map((toggle) => w.eq(toggle.id, true))\n return [...facets, ...ranges, ...date, ...toggles]\n}\n\nexport const clausesToText = (clauses: FilterExpr[]) => (clauses.length === 0 ? '' : printFilter(w.and(...clauses)))\n\nexport const stateToText = (config: Fields, state: FilterState, extras: FilterExpr[] = [], now = new Date(), zone = viewerZone()) =>\n clausesToText([...stateToClauses(config, state, now, zone), ...extras])\n\nconst flatten = (expr: FilterExpr): FilterExpr[] => (expr.kind === 'and' ? expr.args.flatMap(flatten) : [expr])\n\nconst fieldName = (expr: { field: { path: string[] } }) => expr.field.path.join('.')\n\nconst isTrue = (expr: FilterExpr): expr is FilterExpr & { kind: 'compare' } => expr.kind === 'compare' && expr.op === '=' && expr.value.kind === 'boolean' && expr.value.value\n\n// The flags group a clause chooses from, with the fields it chooses: `field = true`, or such clauses ORed in one group.\nconst flagsChosen = (clause: FilterExpr, groupOf: Map<string, string>) => {\n const parts = clause.kind === 'or' ? clause.args : [clause]\n if (!parts.every(isTrue)) return undefined\n const fields = parts.map(fieldName)\n const group = groupOf.get(fields[0]!)\n return group !== undefined && fields.every((field) => groupOf.get(field) === group) ? { group, fields } : undefined\n}\n\nconst literalText = (value: { kind: string; value?: unknown; raw?: string }) => (value.kind === 'number' ? String(value.raw) : value.kind === 'string' ? String(value.value) : undefined)\n\nconst presetOf = (clause: FilterExpr & { kind: 'compare' }, now: Date, zone: string): DatePresetId | undefined => {\n const v = clause.value\n if (v.kind === 'now' && v.offset?.sign === '-') {\n const { amount, unit } = v.offset.duration\n return (Object.entries(relative) as Array<[DatePresetId, { amount: number; unit: string }]>).find(([, d]) => d.amount === amount && d.unit === unit)?.[0]\n }\n if (v.kind === 'timestamp') return calendarPresets.find((preset) => dayLiteral(periodStart(preset, now, zone), 'timestamp', zone) === v.value)\n if (v.kind === 'string') return calendarPresets.find((preset) => periodStart(preset, now, zone) === v.value)\n return undefined\n}\n\nexport type ParsedFilter = { ok: true; state: FilterState; extras: FilterExpr[] } | { ok: false; errors: FilterError[] }\n\n/**\n * The inverse of `stateToText`: clauses that match a widget fill the panel state, everything else\n * (search text, hand-written conditions) is returned as `extras` and survives the round trip.\n */\nexport const textToState = (config: Fields, text: string, now = new Date(), zone = viewerZone()): ParsedFilter => {\n const parsed = parseFilter(text)\n if (!parsed.ok) return { ok: false, errors: parsed.errors }\n const state: FilterState = { facets: {}, toggles: [] }\n const extras: FilterExpr[] = []\n const facetIds = new Set(config.facets.filter((group) => !group.flags).map((group) => group.id))\n const flagGroupOf = new Map(config.facets.filter((group) => group.flags).flatMap((group) => group.options.map((option) => [option.value, group.id] as const)))\n const toggleIds = new Set((config.toggles ?? []).map((toggle) => toggle.id))\n const rangeIds = new Set((config.ranges ?? []).map((range) => range.id))\n const bounds = new Map<string, { low?: number; high?: number; clauses: FilterExpr[] }>()\n let dateClause: FilterExpr | undefined\n let todayEnd: FilterExpr | undefined\n\n for (const clause of parsed.ast ? flatten(parsed.ast) : []) {\n const flags = flagsChosen(clause, flagGroupOf)\n if (flags && !state.facets[flags.group]) {\n state.facets[flags.group] = flags.fields\n } else if (clause.kind === 'compare' && facetIds.has(fieldName(clause)) && clause.op === '=' && literalText(clause.value) !== undefined) {\n state.facets[fieldName(clause)] = [...(state.facets[fieldName(clause)] ?? []), literalText(clause.value)!]\n } else if (clause.kind === 'in' && facetIds.has(fieldName(clause)) && clause.values.every((value) => literalText(value) !== undefined)) {\n state.facets[fieldName(clause)] = [...(state.facets[fieldName(clause)] ?? []), ...clause.values.map((value) => literalText(value)!)]\n } else if (clause.kind === 'compare' && config.dateField === fieldName(clause) && clause.op === '>=' && presetOf(clause, now, zone) && !state.date) {\n state.date = presetOf(clause, now, zone)\n dateClause = clause\n } else if (clause.kind === 'compare' && config.dateField === fieldName(clause) && clause.op === '<' && (clause.value.kind === 'timestamp' || clause.value.kind === 'string') && clause.value.value === dayLiteral(periodStart('today', now, zone), clause.value.kind === 'string' ? 'date' : 'timestamp', zone)) {\n todayEnd = clause\n } else if (clause.kind === 'compare' && toggleIds.has(fieldName(clause)) && clause.op === '=' && clause.value.kind === 'boolean' && clause.value.value) {\n state.toggles.push(fieldName(clause))\n } else if (clause.kind === 'compare' && rangeIds.has(fieldName(clause)) && (clause.op === '>=' || clause.op === '<=') && clause.value.kind === 'number') {\n const range = bounds.get(fieldName(clause)) ?? { clauses: [] }\n if (clause.op === '>=') range.low = clause.value.value\n else range.high = clause.value.value\n range.clauses.push(clause)\n bounds.set(fieldName(clause), range)\n } else {\n extras.push(clause)\n }\n }\n\n if (state.date === 'yesterday' && !todayEnd) {\n extras.push(dateClause!)\n state.date = undefined\n }\n if (todayEnd && state.date !== 'yesterday') extras.push(todayEnd)\n // A range takes a lower and an upper bound; one of them alone is a hand-written condition\n for (const [id, range] of bounds) {\n if (range.low !== undefined && range.high !== undefined) state.ranges = { ...state.ranges, [id]: [range.low, range.high] }\n else extras.push(...range.clauses)\n }\n return { ok: true, state, extras }\n}\n","import type { FieldType, FilterWidgetModel, ResourceModel, ViewModel } from '@protobase/schema'\nimport type { FacetGroupConfig, FilterConfig, RangeConfig } from '../filter-panel'\nimport { formatMoney } from '../format/money'\n\nconst numberTypes: FieldType[] = ['integer', 'bigint', 'decimal']\n\nconst isNumber = (model: ResourceModel | undefined, field: string) => {\n const type = model?.fields[field]?.type\n return type !== undefined && numberTypes.includes(type)\n}\n\n/** A filter on a number field is a range slider, whichever widget the view asked for. */\nconst rangeOf = (widget: FilterWidgetModel, model: ResourceModel | undefined) =>\n widget.kind === 'range' || (widget.kind === 'facets' && isNumber(model, widget.field))\n\nconst secondaryOf = (widget: FilterWidgetModel) => (widget.secondary ? { secondary: true } : {})\n\nconst emptyRange = (widget: FilterWidgetModel & { field: string }): RangeConfig => ({\n id: widget.field,\n label: widget.field,\n min: 0,\n max: 0,\n step: 1,\n histogram: [],\n format: String,\n ...secondaryOf(widget),\n})\n\n/**\n * The widgets of a view in the shape `filter-string` talks to; options and counts are filled in later. Facets on a\n * reference to another resource's records are a combobox, which searches those records.\n */\nexport const widgetFields = (view: ViewModel | undefined, model?: ResourceModel): Pick<FilterConfig, 'facets' | 'ranges' | 'dateField' | 'dateKind' | 'dateSecondary' | 'datePresets' | 'toggles'> => {\n const widgets = view?.filters ?? []\n const date = widgets.find((widget) => widget.kind === 'dateRange')\n return {\n facets: widgets.flatMap((widget): FacetGroupConfig[] => {\n if (widget.kind === 'facets' && !rangeOf(widget, model)) {\n return [{ id: widget.field, label: widget.field, options: [], searchable: widget.search, ...(model?.fields[widget.field]?.type === 'relation' && { combobox: true }), ...secondaryOf(widget) }]\n }\n if (widget.kind === 'flags') return [{ id: widget.fields.join('|'), label: widget.label, options: widget.fields.map((field) => ({ value: field, label: field, count: 0 })), flags: true, ...secondaryOf(widget) }]\n return []\n }),\n ranges: widgets.flatMap((widget) => (widget.kind !== 'flags' && rangeOf(widget, model) ? [emptyRange(widget)] : [])),\n ...(date && { dateField: date.field, ...(date.secondary && { dateSecondary: true }), dateKind: model?.fields[date.field]?.type === 'date' ? ('date' as const) : ('timestamp' as const), ...(date.presets.length > 0 && { datePresets: date.presets }) }),\n toggles: widgets.flatMap((widget) => (widget.kind === 'toggle' ? [{ id: widget.field, label: widget.field, ...secondaryOf(widget) }] : [])),\n }\n}\n\n/** Whether a range draws its histogram: only a `range` widget that asks for one. */\nexport const rangeHistogram = (view: ViewModel | undefined, field: string) =>\n (view?.filters ?? []).some((widget) => widget.kind === 'range' && widget.field === field && widget.histogram)\n\n/** How a range's values read: money in the view's currency, \"€450,000\", else with its prefix and suffix, \"85 m²\". */\nexport const rangeFormat = (view: ViewModel | undefined, field: string) => {\n const hints = view?.fields[field]\n const suffix = hints?.suffix ?? ''\n const currency = hints?.currency\n if (currency !== undefined) return (value: number) => `${formatMoney(value * 100, currency).replace('.00', '')}${suffix}`\n return (value: number) => `${hints?.prefix ?? ''}${value}${suffix}`\n}\n","import { createWhere, enumLabel, parseFilter, printFilter, type ResourceModel, type ViewModel } from '@protobase/schema'\nimport { activeChips, type FilterChip, type FilterConfig } from '../../filter-panel'\nimport { textToState } from '../../live/filter-string'\nimport { humanize } from '../../live/naming'\nimport { rangeFormat, widgetFields } from '../../live/view-fields'\nimport { text as message } from './messages'\n\nconst where = createWhere()\nconst span = { start: 0, end: 0 }\n\n/** Names of relation values, by field and then by value, such as `{ place_id: { '1': 'Amsterdam' } }`. */\nexport type ValueNames = Record<string, Record<string, string>>\n\n/** The relation fields a filter chooses values of through its facets, each with the values it chooses. */\nexport const chosenRelations = (model: ResourceModel, view: ViewModel | undefined, text: string): Record<string, string[]> => {\n const parsed = textToState(widgetFields(view, model), text)\n if (!parsed.ok) return {}\n return Object.fromEntries(Object.entries(parsed.state.facets).filter(([field, values]) => model.fields[field]?.type === 'relation' && values.length > 0))\n}\n\n/**\n * The panel's widgets named as the list page names them, without counts: what reading a saved filter back into chips\n * needs. Enum values take the view's value labels, relation values the names in `names`.\n */\nconst namedConfig = (model: ResourceModel, view: ViewModel | undefined, names: ValueNames): FilterConfig => {\n const label = (name: string) => view?.fields[name]?.label ?? humanize(name)\n const skeleton = widgetFields(view, model)\n return {\n ...skeleton,\n facets: skeleton.facets.map((group) => {\n if (group.flags) return { ...group, options: group.options.map((option) => ({ ...option, label: label(option.value) })) }\n const values = model.fields[group.id]?.enumValues ?? []\n const labels = model.fields[group.id]?.type === 'enum' ? Object.fromEntries(values.map((value) => [value, enumLabel(value, view?.fields[group.id]?.valueLabels)])) : (names[group.id] ?? {})\n return { ...group, label: label(group.id), labels }\n }),\n ranges: (skeleton.ranges ?? []).map((range) => ({ ...range, label: label(range.id), format: rangeFormat(view, range.id) })),\n toggles: skeleton.toggles?.map((toggle) => ({ ...toggle, label: label(toggle.id) })),\n }\n}\n\n/**\n * A saved filter as the chips the list page shows for it, then a chip per condition no widget holds: the search text\n * in quotes, or the condition as written. One chip saying so when the filter cannot be read.\n */\nexport const filterChips = (model: ResourceModel, view: ViewModel | undefined, text: string, names: ValueNames = {}): FilterChip[] => {\n const config = namedConfig(model, view, names)\n const parsed = textToState(config, text)\n if (!parsed.ok) return [{ key: 'unreadable', label: message('unreadableFilter') }]\n const extras = parsed.extras.map((clause, index) => ({ key: `extra:${index}`, label: clause.kind === 'search' ? `\"${clause.text}\"` : printFilter(clause) }))\n return [...activeChips(config, parsed.state), ...extras]\n}\n\n/** The names the list page's panel knows for its facets' values, to name a search saved from it. */\nexport const facetNames = (config: FilterConfig): ValueNames =>\n Object.fromEntries(config.facets.filter((group) => !group.flags).map((group) => [group.id, { ...group.labels, ...Object.fromEntries(group.options.map((option) => [option.value, option.label])) }]))\n\n/**\n * The search's filter narrowed to the records new since the user last opened its results: those whose `field` is after\n * `seenAt`. Without a `seenAt` every record is new.\n */\nexport const unseenFilter = (text: string, field: string, seenAt: unknown) => {\n if (typeof seenAt !== 'string' || seenAt === '') return text\n const after = where.gt(field, { kind: 'timestamp', value: new Date(seenAt).toISOString(), span })\n const parsed = parseFilter(text)\n if (!parsed.ok) throw new Error(`The saved filter cannot be read: ${parsed.errors.map((error) => error.message).join('; ')}`)\n return printFilter(parsed.ast ? where.and(parsed.ast, after) : after)\n}\n\n/** Whether a record whose `field` holds `value` is new to the user, as `unseenFilter` finds it: after `seenAt`, or any. */\nexport const isUnseen = (value: unknown, seenAt: unknown) => {\n if (typeof seenAt !== 'string' || seenAt === '') return true\n if (typeof value !== 'string' || value === '') return false\n return new Date(value).getTime() > new Date(seenAt).getTime()\n}\n","import { useQueries, useQueryClient } from '@tanstack/react-query'\nimport type { ResourceModel } from '@protobase/schema'\nimport { useClient } from '../../data/api-provider'\nimport { keys } from '../../data/query-keys'\nimport { fetchLabels } from '../../live/relation-labels'\nimport { useAdminMeta } from '../meta-gate'\nimport { chosenRelations, filterChips, type ValueNames } from './saved-search'\n\n/** A saved filter of `model`'s list as chips, with the records its relation facets choose named once they have loaded. */\nexport const useFilterChips = (model: ResourceModel, text: string) => {\n const client = useClient()\n const queryClient = useQueryClient()\n const { resources, views } = useAdminMeta()\n const view = views[model.name]\n const chosen = Object.entries(chosenRelations(model, view, text))\n const named = useQueries({\n queries: chosen.map(([field, ids]) => {\n const target = resources[model.fields[field]!.relation!.resource]\n return {\n queryKey: keys.labels(`chips:${model.name}.${field}`, ids.join(',')),\n enabled: target !== undefined,\n queryFn: async () => Object.fromEntries(await fetchLabels(queryClient, client, target!, ids, views[target!.name])),\n }\n }),\n })\n const names: ValueNames = Object.fromEntries(chosen.flatMap(([field], index) => (named[index]?.data ? [[field, named[index].data]] : [])))\n return filterChips(model, view, text, names)\n}\n","import type { ResourceModel } from '@protobase/schema'\nimport { useRelationTitle } from './use-relation-title'\n\n/** The name of the record `id` of `target` a relation points at, for the reader; its key while the name loads. */\nexport const RelationTitleText = ({ target, id }: { target: ResourceModel; id: string }) => <>{useRelationTitle(target, id) ?? id}</>\n","import { createWhere, type FilterExpr, type KeyValue, type ResourceModel } from '@protobase/schema'\nimport { encodeKey } from '@protobase/schema/internal'\nimport { recordKey } from '../../live/model-helpers'\n\nconst where = createWhere()\n\n/** The most saved records one request lists; the user's own are loaded page by page until there are no more. */\nexport const savedPageSize = 500\n\n/** One of the user's saved records: its own key, and the key of the record its relation points at. */\nexport type SavedRecord = {\n /** The saved record's key, in the text form the record API takes. */\n key: string\n /** The value of its relation, the key of the record it saves. */\n target: KeyValue\n}\n\n// A relation's value is the key it points at; labelled, it comes as `{ id, name }`.\nconst relationValue = (value: unknown): KeyValue | undefined => {\n if (typeof value === 'string' || typeof value === 'number') return value\n if (value && typeof value === 'object' && 'id' in value) return relationValue((value as { id: unknown }).id)\n return undefined\n}\n\n/** The saved records among listed rows of `model`, by the relation `field`; rows without a value are left out. */\nexport const savedRecordsOf = (model: ResourceModel, field: string, rows: readonly Record<string, unknown>[]): SavedRecord[] =>\n rows.flatMap((row) => {\n const target = relationValue(row[field])\n return target === undefined ? [] : [{ key: encodeKey(recordKey(model, row)), target }]\n })\n\n/** The saved record of the record with this key, the text form the record API takes, if it is saved. */\nexport const savedFor = (saved: readonly SavedRecord[], key: string) => saved.find((entry) => encodeKey(entry.target) === key)\n\n/** The saved records with one more, until the server answers with its key. */\nexport const withSaved = (saved: readonly SavedRecord[], target: KeyValue): SavedRecord[] => [...saved, { key: '', target }]\n\n/** The saved records without the one of the record with this key. */\nexport const withoutSaved = (saved: readonly SavedRecord[], key: string): SavedRecord[] => saved.filter((entry) => encodeKey(entry.target) !== key)\n\n/**\n * The filter of the records the saved ones point at, on the target's single-column key; undefined when there are none,\n * as `in()` needs at least one value.\n */\nexport const savedScope = (target: ResourceModel, saved: readonly SavedRecord[]): FilterExpr | undefined => {\n const [key] = target.primaryKey\n if (target.primaryKey.length !== 1 || key === undefined) throw new Error(`${target.name} has a composite key, so its saved records cannot be listed`)\n const values = [...new Set(saved.map((entry) => entry.target))]\n return values.length === 0 ? undefined : where.in(key, values as never[])\n}\n","import { useQuery } from '@tanstack/react-query'\nimport { useClient } from '../../data/api-provider'\nimport { keys } from '../../data/query-keys'\nimport { useAdminMeta } from '../meta-gate'\nimport { savedPageSize, savedRecordsOf, type SavedRecord } from './saved-records'\n\n/** Where the user's saved records of `resource` by `field` are cached; a list key, so a write to the resource refreshes it. */\nexport const savedRecordsKey = (resource: string, field: string) => keys.list(resource, '', '', savedPageSize, `saved:${field}`)\n\n/**\n * The signed-in user's saved records of `resource`, each with the key its relation `field` points at: every one, page\n * by page, as the API lists only a user's own records of a resource with an owner. Loads only while `enabled`.\n */\nexport const useSavedRecords = (resource: string, field: string, enabled: boolean) => {\n const client = useClient()\n const model = useAdminMeta().resources[resource]\n return useQuery({\n queryKey: savedRecordsKey(resource, field),\n enabled: enabled && model !== undefined,\n queryFn: async (): Promise<SavedRecord[]> => {\n const rows: Record<string, unknown>[] = []\n let pageToken: string | undefined\n do {\n const page = await client.list(resource, { pageSize: savedPageSize, fields: [...model!.primaryKey, field], ...(pageToken && { pageToken }) })\n rows.push(...(page.items as Record<string, unknown>[]))\n pageToken = page.nextPageToken || undefined\n } while (pageToken)\n return savedRecordsOf(model!, field, rows)\n },\n })\n}\n","import { messages } from '../../locale/messages'\n\nexport const text = messages('app/saved')\n","import { useMutation, useQueryClient } from '@tanstack/react-query'\nimport type { CardFavoriteModel, KeyValue } from '@protobase/schema'\nimport { useClient } from '../../data/api-provider'\nimport { useToast } from '../../toasts'\nimport { useAdminMeta } from '../meta-gate'\nimport { useRefreshResource } from '../pages/use-layout-data'\nimport { can } from '../permissions'\nimport { savedFor, withoutSaved, withSaved, type SavedRecord } from './saved-records'\nimport { savedRecordsKey, useSavedRecords } from './use-saved-records'\nimport { text } from './messages'\n\nconst message = (error: unknown) => (error instanceof Error ? error.message : text('somethingWrong'))\n\n/**\n * A card's favorite button: `save` for someone who can list, create and delete the saved records, `sign-in` for a\n * visitor the saved records' resource asks to sign in (`prompt`), nothing otherwise. A press saves the card's record,\n * or takes it off, at once on screen; a refused write puts it back and says why.\n */\nexport const useFavorite = (favorite: CardFavoriteModel, key: string, target: KeyValue) => {\n const meta = useAdminMeta()\n const client = useClient()\n const queryClient = useQueryClient()\n const toast = useToast()\n const refresh = useRefreshResource()\n const { resource, field } = favorite\n const permissions = meta.permissions[resource]\n const usable = meta.resources[resource] !== undefined && permissions !== undefined && can(permissions, 'create') && can(permissions, 'delete')\n const prompt = meta.signIn?.[resource]?.signIn\n const saved = useSavedRecords(resource, field, usable)\n const current = saved.data && savedFor(saved.data, key)\n const cacheKey = savedRecordsKey(resource, field)\n\n const toggle = useMutation({\n mutationFn: async (existing: SavedRecord | undefined) => {\n if (existing) await client.remove(resource, existing.key)\n else await client.create(resource, { [field]: target })\n },\n onMutate: async (existing) => {\n await queryClient.cancelQueries({ queryKey: cacheKey, exact: true })\n const before = queryClient.getQueryData<SavedRecord[]>(cacheKey)\n queryClient.setQueryData<SavedRecord[]>(cacheKey, (list = []) => (existing ? withoutSaved(list, key) : withSaved(list, target)))\n return { before }\n },\n onError: (error, existing, context) => {\n queryClient.setQueryData(cacheKey, context?.before)\n toast.show({ state: 'error', title: existing ? text('couldNotTakeOff') : text('couldNotSave'), description: message(error) })\n },\n onSettled: () => refresh(resource),\n })\n\n return {\n mode: usable ? ('save' as const) : prompt ? ('sign-in' as const) : undefined,\n prompt,\n saved: current !== undefined,\n // Until the saved records are known, and while a press is on its way, another press would not know what to do\n ready: saved.data !== undefined && !toggle.isPending,\n toggle: () => toggle.mutate(current),\n }\n}\n","import { Heart } from 'lucide-react'\nimport { useState } from 'react'\nimport type { CardFavoriteModel, KeyValue } from '@protobase/schema'\nimport { SignInPrompt } from '../../auth/sign-in-prompt'\nimport { cn } from '../../lib/cn'\nimport { useFavorite } from './use-favorite'\nimport { text } from './messages'\n\ntype FavoriteButtonProps = {\n favorite: CardFavoriteModel\n /** The card's record key, in the text form the record API takes. */\n recordKey: string\n /** The card's record key as the saved record's relation holds it. */\n target: KeyValue\n className?: string\n}\n\n/**\n * A heart that saves the card's record for the signed-in user, pressed while it is saved, or, for a visitor, opens the\n * sign-in prompt of the saved records' resource. It sits over the card's link, beside it in the document, so pressing\n * it does not open the record; the card's list item must be `relative`.\n */\nexport const FavoriteButton = ({ favorite, recordKey, target, className }: FavoriteButtonProps) => {\n const state = useFavorite(favorite, recordKey, target)\n const [prompting, setPrompting] = useState(false)\n if (!state.mode) return null\n const label = favorite.label ?? text('favorite')\n const base = cn(\n 'absolute right-2 top-2 flex size-8 items-center justify-center rounded-full bg-background/85 text-foreground shadow-sm transition-colors hover:bg-background focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/30',\n className,\n )\n if (state.mode === 'sign-in') {\n return (\n <>\n <button type=\"button\" aria-label={label} aria-haspopup=\"dialog\" className={base} onClick={() => setPrompting(true)}>\n <Heart className=\"size-4\" aria-hidden />\n </button>\n <SignInPrompt as=\"dialog\" prompt={state.prompt!} open={prompting} onClose={() => setPrompting(false)} />\n </>\n )\n }\n return (\n <button type=\"button\" aria-label={label} aria-pressed={state.saved} aria-disabled={!state.ready} className={base} onClick={() => state.ready && state.toggle()}>\n <Heart className={cn('size-4', state.saved && 'fill-current text-danger')} aria-hidden />\n </button>\n )\n}\n","const gap = 6\n\ntype Box = { top: number; bottom: number; left: number; width: number }\n\n/**\n * Where a card of `card`'s size goes for the dot at `dot`, in viewport pixels: below it, or above it when the viewport\n * has no room underneath, starting at its left edge and kept inside the viewport's sides.\n */\nexport const placeCard = (dot: Box, card: { width: number; height: number }, viewport: { width: number; height: number }) => {\n const below = dot.bottom + gap\n const top = below + card.height > viewport.height - gap ? Math.max(gap, dot.top - gap - card.height) : below\n const left = Math.max(gap, Math.min(dot.left, viewport.width - gap - card.width))\n return { top, left }\n}\n","import type { ListDisplayModel, ResourceModel, ViewModel } from '@protobase/schema'\nimport type { RelatedColumnLoad } from '../../live/related-column-rows'\nimport { displaysOf, shownFields } from '../displays/list-displays'\n\ntype CardsDisplayModel = Extract<ListDisplayModel, { kind: 'cards' }>\n\n/**\n * The card a dot shows of its record: the first cards display of the record's view, without the photos, favorite\n * button and dots a small card has no room for, else the record's title with its status as the badge.\n */\nexport const dotCard = (view: ViewModel | undefined, status: string): CardsDisplayModel => {\n const cards = displaysOf(view).find((display): display is CardsDisplayModel => display.kind === 'cards')\n if (!cards) return { kind: 'cards', name: 'dot', badge: status }\n const { photos: _, favorite: __, dots: ___, ...card } = cards\n return card\n}\n\n/** What the list loads for the related columns of its view among `columns`: each with the fields its dots' cards show. */\nexport const relatedColumnLoads = (view: ViewModel | undefined, resources: Record<string, ResourceModel>, views: Record<string, ViewModel>, columns: string[]): RelatedColumnLoad[] =>\n (view?.list?.relatedColumns ?? [])\n .filter((column) => columns.includes(column.name))\n .flatMap((column) => {\n const target = resources[column.resource]\n return target ? [{ column, fields: shownFields(target, views[target.name], dotCard(views[target.name], column.status)) }] : []\n })\n","import { messages } from '../../locale/messages'\n\nexport const text = messages('app/related-dots')\n","import { text } from './messages'\ntype SummaryOptions = {\n /** The status field's values, in the order the summary counts them. */\n values: readonly string[]\n /** How a value reads, as the record's badge shows it. */\n label: (value: string) => string\n /** What one record and several are called, such as \"task\" and \"tasks\". */\n singular: string\n plural: string\n}\n\n/**\n * What a related column's dots say, as text: how many records there are, then how many have each status, in the order\n * of the status's values, such as \"4 tasks: 1 To do, 3 Done\". \"No tasks\" without any.\n */\nexport const dotsSummary = (statuses: readonly unknown[], { values, label, singular, plural }: SummaryOptions) => {\n if (statuses.length === 0) return text('none', { plural })\n const counts = new Map<string, number>()\n for (const status of statuses) if (status !== null && status !== undefined) counts.set(String(status), (counts.get(String(status)) ?? 0) + 1)\n const order = [...values, ...[...counts.keys()].filter((value) => !values.includes(value))]\n const parts = order.filter((value) => counts.has(value)).map((value) => `${counts.get(value)} ${label(value)}`)\n const total = `${statuses.length} ${statuses.length === 1 ? singular : plural}`\n return parts.length === 0 ? total : `${total}: ${parts.join(', ')}`\n}\n","import { useEffect, useLayoutEffect, useMemo, useRef, useState, type ComponentType, type FocusEvent, type MouseEvent, type PointerEvent } from 'react'\nimport { createPortal } from 'react-dom'\nimport type { ListDisplayModel, RelatedColumnModel, ResourceModel, ViewModel } from '@protobase/schema'\nimport { cn } from '../../lib/cn'\nimport { displayValue } from '../../live/display-value'\nimport { recordTitleField } from '../../live/model-helpers'\nimport { humanize } from '../../live/naming'\nimport { valueColor, valueTone } from '../../live/value-color'\nimport { toneDots } from '../../primitives/badge'\nimport { displayRow, type ListDisplayRow } from '../displays/list-displays'\nimport { AppLink } from '../use-app-address'\nimport { placeCard } from './card-place'\nimport { dotCard } from './dot-card'\nimport { dotsSummary } from './dots-summary'\n\ntype RelatedDotsProps = {\n column: RelatedColumnModel\n /** The records of `target` the column shows for the row, in its order, as the list loaded them. */\n records: Array<Record<string, unknown>>\n target: ResourceModel\n view: ViewModel | undefined\n /** Whether the dots wrap onto more lines, as a card's do, over a card whose link takes the pointer between them. */\n wrap?: boolean\n /** Draws the card a dot shows: `RecordCard`, passed in because a card draws dots too. */\n Card: DotCardComponent\n}\n\n/** A record's card as `RecordCard` draws it. */\nexport type DotCardComponent = ComponentType<{ model: ResourceModel; view: ViewModel | undefined; display: Extract<ListDisplayModel, { kind: 'cards' }>; row: ListDisplayRow }>\n\n/** A dot's box and its mark, which a card's room for its dots (`DotsRoom`) takes the size of. */\nconst dotBox = 'flex shrink-0 items-center justify-center rounded-full p-0.5 pointer-coarse:p-1.5'\nconst dotMark = 'size-2.5 rounded-full'\nconst dotsLine = 'flex min-w-0 items-center gap-0.5'\n\n// How long the card stays after the pointer leaves its dot, so it can move onto the card. A touch shows it on a tap\n// instead, and keyboard focus as it reaches the dot\nconst hideMs = 150\n\nconst cardWidth = 288\n\ntype Shown = { key: string; dot: DOMRect }\n\n/**\n * The card of the dot that is hovered, focused or tapped, portalled to the body: every grid row is its own stacking\n * context and the grid body clips, so a card inside the row would sit under the rows below it.\n */\nconst DotCardPopover = ({ shown, row, target, view, column, Card, onEnter, onLeave }: { shown: Shown; row: ListDisplayRow; target: ResourceModel; view: ViewModel | undefined; column: RelatedColumnModel; Card: DotCardComponent; onEnter: () => void; onLeave: () => void }) => {\n const card = useRef<HTMLDivElement>(null)\n const [place, setPlace] = useState<{ top: number; left: number }>()\n useLayoutEffect(() => {\n if (!card.current) return\n setPlace(placeCard(shown.dot, { width: cardWidth, height: card.current.offsetHeight }, { width: window.innerWidth, height: window.innerHeight }))\n }, [shown])\n return createPortal(\n <div ref={card} data-dot-card onMouseEnter={onEnter} onMouseLeave={onLeave} style={{ width: cardWidth, ...(place ?? { visibility: 'hidden', top: 0, left: 0 }) }} className=\"fixed z-50 rounded-lg shadow-pop\">\n <Card model={target} view={view} display={dotCard(view, column.status)} row={row} />\n </div>,\n document.body,\n )\n}\n\n/**\n * A related column's cell: a dot per record in the colour its status has in its view, each a link to the record. Hovering\n * or focusing a dot shows the record's card; on a touch screen the first tap shows it, and the card opens the record.\n * The dots say how many records have each status to a screen reader.\n */\nexport const RelatedDots = ({ column, records, target, view, wrap = false, Card }: RelatedDotsProps) => {\n const rows = useMemo(() => records.map((record) => displayRow(target, record)), [records, target])\n const [shown, setShown] = useState<Shown>()\n const hideTimer = useRef<number>(undefined)\n const pointer = useRef<string>('mouse')\n const box = useRef<HTMLDivElement>(null)\n\n const status = target.fields[column.status]\n const hints = view?.fields[column.status]\n const statusText = (row: ListDisplayRow) => (status ? displayValue(status, row.record[column.status], hints) : '')\n const titleField = recordTitleField(target, view)\n const title = (row: ListDisplayRow) => row.labels[titleField] ?? String(row.record[titleField] ?? row.key)\n const singular = (view?.names?.singular ?? humanize(target.name)).toLowerCase()\n const plural = (view?.names?.plural ?? humanize(target.name)).toLowerCase()\n const summary = dotsSummary(\n rows.map((row) => row.record[column.status]),\n { values: status?.enumValues ?? [], label: (value) => (status ? displayValue(status, value, hints) : value), singular, plural },\n )\n\n const cancelHide = () => window.clearTimeout(hideTimer.current)\n const hideSoon = () => {\n cancelHide()\n hideTimer.current = window.setTimeout(() => setShown(undefined), hideMs)\n }\n const show = (key: string, dot: Element) => {\n cancelHide()\n setShown({ key, dot: dot.getBoundingClientRect() })\n }\n useEffect(() => cancelHide, [])\n\n // The card stays where it was drawn, so scrolling or resizing closes it, and so do Escape and a tap elsewhere\n useEffect(() => {\n if (!shown) return\n const hide = () => setShown(undefined)\n const key = (event: KeyboardEvent) => event.key === 'Escape' && hide()\n const outside = (event: Event) => {\n const target = event.target as Element | null\n if (!box.current?.contains(target) && !target?.closest?.('[data-dot-card]')) hide()\n }\n document.addEventListener('keydown', key)\n document.addEventListener('pointerdown', outside)\n document.addEventListener('scroll', hide, true)\n window.addEventListener('resize', hide)\n return () => {\n document.removeEventListener('keydown', key)\n document.removeEventListener('pointerdown', outside)\n document.removeEventListener('scroll', hide, true)\n window.removeEventListener('resize', hide)\n }\n }, [shown])\n\n // A tap on a dot whose card is not open shows the card instead of following the link\n const tap = (key: string) => (event: MouseEvent<HTMLAnchorElement>) => {\n if (pointer.current !== 'touch' || shown?.key === key) return\n event.preventDefault()\n show(key, event.currentTarget)\n }\n const blur = (event: FocusEvent) => {\n if (!(event.relatedTarget as Element | null)?.closest?.('[data-dot-card]')) hideSoon()\n }\n const shownRow = shown && rows.find((row) => row.key === shown.key)\n\n return (\n // A click on a dot or its card stays out of the row, which opens its own record\n <div ref={box} className={cn(dotsLine, wrap && 'pointer-events-none flex-wrap')} onClick={(event) => event.stopPropagation()} onPointerDown={(event: PointerEvent) => (pointer.current = event.pointerType)}>\n <span className=\"sr-only\">{summary}</span>\n {rows.map((row) => {\n const value = row.record[column.status]\n const color = valueColor(hints?.valueColors, value)\n return (\n <AppLink\n key={row.key}\n to={{ kind: 'record', resource: target.name, key: row.key }}\n aria-label={`${title(row)}, ${statusText(row)}`}\n onPointerEnter={(event) => event.pointerType !== 'touch' && show(row.key, event.currentTarget)}\n onPointerLeave={(event) => event.pointerType !== 'touch' && hideSoon()}\n onFocus={(event) => event.currentTarget.matches(':focus-visible') && show(row.key, event.currentTarget)}\n onBlur={blur}\n onClick={tap(row.key)}\n className={cn(dotBox, 'pointer-events-auto focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/40')}\n >\n <span aria-hidden style={color === undefined ? undefined : { backgroundColor: color }} className={cn(dotMark, color === undefined && toneDots[valueTone(hints?.valueColors, value)], shown?.key === row.key && 'ring-2 ring-foreground/30')} />\n </AppLink>\n )\n })}\n {shown && shownRow && <DotCardPopover shown={shown} row={shownRow} target={target} view={view} column={column} Card={Card} onEnter={cancelHide} onLeave={hideSoon} />}\n </div>\n )\n}\n\n/** Room for `count` dots that wrap as `RelatedDots` with `wrap` does, for a card to hold the dots drawn over it. */\nexport const DotsRoom = ({ count }: { count: number }) => (\n <span aria-hidden className={cn(dotsLine, 'invisible flex-wrap')}>\n {Array.from({ length: count }, (_, index) => (\n <span key={index} className={dotBox}>\n <span className={dotMark} />\n </span>\n ))}\n </span>\n)\n","import { useAdminMeta } from '../meta-gate'\nimport type { CardDotsLine } from './card-dots-lines'\nimport { DotsRoom, RelatedDots, type DotCardComponent } from './related-dots'\n\nconst lines = 'flex flex-col gap-1.5'\n\n/** The room a card's lines of dots take at its bottom, which the dots are drawn over. */\nexport const CardDotsRoom = ({ dots }: { dots: CardDotsLine[] }) => (\n <span className={lines}>\n {dots.map(({ column, records }) => (\n <DotsRoom key={column.name} count={records.length} />\n ))}\n </span>\n)\n\n/**\n * A card's lines of dots, over the room the card holds for them at its bottom, inside its border and padding: beside\n * the card in the document, so a dot is a link of its own and the pointer between the dots reaches the card's link.\n * The card's list item must be `relative`.\n */\nexport const CardDots = ({ dots, Card }: { dots: CardDotsLine[]; Card: DotCardComponent }) => {\n const { resources, views } = useAdminMeta()\n return (\n <div className={`pointer-events-none absolute inset-x-[calc(0.75rem+1px)] bottom-[calc(0.75rem+1px)] ${lines}`}>\n {dots.map(({ column, records }) => {\n const target = resources[column.resource]\n return target && <RelatedDots key={column.name} column={column} records={records} target={target} view={views[target.name]} Card={Card} wrap />\n })}\n </div>\n )\n}\n","import type { ListDisplayModel, RelatedColumnModel, ViewModel } from '@protobase/schema'\nimport type { ListDisplayRow } from '../displays/list-displays'\n\n/** A line of dots a card shows: a related column of the list and the records the list loaded with the row for it. */\nexport type CardDotsLine = { column: RelatedColumnModel; records: Array<Record<string, unknown>> }\n\n/**\n * The lines of dots a card of `display` shows for a row, in the order it names their columns: those of the list's\n * related columns that were loaded with the row and hold a record. A row loaded without them, as a map's or a saved\n * search's, shows none.\n */\nexport const cardDotsLines = (view: ViewModel | undefined, display: Extract<ListDisplayModel, { kind: 'cards' }>, row: ListDisplayRow): CardDotsLine[] =>\n (display.dots ?? []).flatMap((name) => {\n const column = view?.list?.relatedColumns?.find((candidate) => candidate.name === name)\n const records = row.record[name]\n return column && Array.isArray(records) && records.length > 0 ? [{ column, records: records as CardDotsLine['records'] }] : []\n })\n","import type { ReactNode } from 'react'\nimport { FileImage } from '../../live/file-image'\nimport { shownImage } from '../../live/file-values'\n\n/** A raster image filling its frame; nothing for any other value. */\nexport const CardPhoto = ({ value }: { value: unknown }) => {\n const image = shownImage(value, { width: 320, height: 240 })\n return image ? <FileImage image={image} loading=\"lazy\" className=\"size-full object-cover\" /> : null\n}\n\n/** The frame across a card's top, from the edge of the card in, holding its picture. */\nexport const CardImageFrame = ({ children }: { children: ReactNode }) => (\n <span className=\"-mx-3 -mt-3 mb-1.5 block aspect-[4/3] overflow-hidden rounded-t-lg border-b border-border bg-muted\">{children}</span>\n)\n\n/** A picture across the card's top: a raster image only, an empty frame otherwise. */\nexport const CardImage = ({ value }: { value: unknown }) => (\n <CardImageFrame>\n <CardPhoto value={value} />\n </CardImageFrame>\n)\n","import { cardPhotoLimit } from '@protobase/schema/internal'\nimport { isStoredFile } from '../../live/file-values'\n\n/** The most photos a card steps through, its own image among them, each marked by a dot. */\nexport const maxCardDots = cardPhotoLimit\n\n/**\n * The files a card steps through: its own image first, then its photos less that same file, at most `maxCardDots`;\n * empty values are left out.\n */\nexport const cardPhotoList = (cover: unknown, photos: readonly unknown[]): unknown[] => {\n const coverUri = isStoredFile(cover) ? cover.uri : undefined\n const rest = photos.filter((photo) => isStoredFile(photo) && photo.uri !== coverUri)\n return (coverUri === undefined ? rest : [cover, ...rest]).slice(0, maxCardDots)\n}\n","import type { ReactNode } from 'react'\nimport { CarouselControls } from '../../carousel/carousel-controls'\nimport { CarouselTrack } from '../../carousel/carousel-track'\nimport { useCarousel } from '../../carousel/use-carousel'\nimport { CardImageFrame, CardPhoto } from './card-image'\nimport { cardPhotoList } from './card-photos'\n\ntype CardCarouselProps = {\n /** The record's photos, as its list loaded them. */\n photos: readonly unknown[]\n /** The card's own image, shown first. */\n cover: unknown\n /** Whether a swipe steps through the photos; off, it scrolls what the card sits in, such as a row that scrolls sideways. */\n swipe?: boolean\n /** The card, drawn with the picture across its top. */\n children: (picture: ReactNode) => ReactNode\n}\n\n/**\n * A card whose picture steps through its photos, the card's own image first: a track that snaps photo by photo, swiped\n * on a touch screen or moved by arrows, with dots marking the one in view. The photos come with the card's row, in the\n * same answer as the list, so the dots mark its own image from the start. The card puts the track in a link of its own,\n * so a tap opens the record and a swipe does not; the arrows sit over it, beside the card in the document, so pressing\n * one does not open the record either. The card's list item must be `relative group/card`.\n */\nexport const CardCarousel = ({ photos, cover, swipe = true, children }: CardCarouselProps) => {\n const list = cardPhotoList(cover, photos)\n const carousel = useCarousel(list.length)\n\n const picture = (\n <CardImageFrame>\n <CarouselTrack data-card-photos carousel={carousel} swipe={swipe} slides={list.map((photo) => <CardPhoto value={photo} />)} />\n </CardImageFrame>\n )\n\n return (\n <>\n {children(picture)}\n <CarouselControls\n carousel={carousel}\n count={list.length}\n swipe={swipe}\n reveal=\"group-has-[[data-card-photos]:hover]/card:opacity-100\"\n className=\"inset-x-px top-px aspect-[4/3]\"\n />\n </>\n )\n}\n","import type { ReactNode } from 'react'\nimport type { KeyValue, ListDisplayModel, ResourceModel, ViewModel } from '@protobase/schema'\nimport { displayValue } from '../../live/display-value'\nimport { jsonSummary } from '../../live/json-summary'\nimport { linkTextOf } from '../../live/link-text'\nimport { recordKey } from '../../live/model-helpers'\nimport { humanize } from '../../live/naming'\nimport { Badge } from '../../primitives/badge'\nimport { CodeBlock } from '../../primitives/code-block'\nimport { AppLink } from '../use-app-address'\nimport { useSeedRecord } from '../record-preview'\nimport { shownWidget } from '../field-types/shown-widget'\nimport { WidgetPart } from '../field-types/widget-part'\nimport { namedIcon } from '../named-icon'\nimport { useAdminMeta } from '../meta-gate'\nimport { RelationTitleText } from '../titles/relation-title-text'\nimport { CustomBoundary } from '../pages/custom-boundary'\nimport { FavoriteButton } from '../saved/favorite-button'\nimport { useProjectUi } from '../pages/project-ui'\nimport { ValueBadge } from '../value-badge'\nimport { CardDots, CardDotsRoom } from '../related-dots/card-dots'\nimport { cardDotsLines } from '../related-dots/card-dots-lines'\nimport { CardCarousel } from './card-carousel'\nimport { CardImage } from './card-image'\nimport { Markdown } from '../../markdown/markdown'\nimport { markdownExcerpt } from '../../markdown/markdown-excerpt'\nimport { isMarkdown } from '../../markdown/markdown-hint'\nimport { amountParts, cardFields, filledAmount, filledCode, filledMeta, rawCode, type ListDisplayRow } from './list-displays'\nimport { text as message } from './messages'\n\ntype RecordCardProps = {\n model: ResourceModel\n view: ViewModel | undefined\n display: Extract<ListDisplayModel, { kind: 'cards' }>\n row: ListDisplayRow\n /** Whether a swipe steps through the card's photos; off in a row that scrolls sideways, which the swipe scrolls instead. */\n swipe?: boolean\n /** A word marked in the card's top left corner, such as \"New\": over its picture, or above its title without one. */\n mark?: string\n}\n\n// A meta field's value after the icon its view names.\nconst MetaValue = ({ icon, children }: { icon: string | undefined; children: ReactNode }) => {\n const Icon = namedIcon(icon)\n return (\n <dd className=\"flex items-center gap-1 tabular-nums\">\n {Icon && <Icon className=\"size-3.5 shrink-0\" aria-hidden />}\n {children}\n </dd>\n )\n}\n\n/**\n * A record's card of a cards display, opening its page: its image across the top, swiped or stepped through its photos\n * when the display names them, the title over the subtitle, the badge beside it, the first amount with a value in bold,\n * small meta fields below, those with a value, the labels of its flags that are true, the footer's fields with a\n * value, joined by bullets, and a line of dots for each related column of the list it names; or, with a `card`\n * component, what it draws of the row, the built-in content again when it is missing or throws. With a favorite button, a heart in the top right corner saves the record.\n */\nexport const RecordCard = ({ model, view, display, row, swipe = true, mark }: RecordCardProps) => {\n const { image, title, subtitle, amount, badge, code, meta, footer, flags } = cardFields(model, view, display)\n const label = (name: string) => view?.fields[name]?.label ?? humanize(name)\n const { resources, views } = useAdminMeta()\n const text = (name: string): ReactNode => {\n const field = model.fields[name]\n if (!field) return ''\n const value = row.record[name]\n // A relation to a resource whose view derives its titles names its record for the reader\n const target = field.type === 'relation' && field.relation ? resources[field.relation.resource] : undefined\n if (target && views[target.name]?.titleFrom && value != null) return <RelationTitleText target={target} id={String(value)} />\n // Markdown reads as its text on a card's one-line parts\n if (row.labels[name] === undefined && isMarkdown(field, view?.fields[name]) && typeof value === 'string' && value !== '') return markdownExcerpt(value)\n // JSON reads as its summary there, as in a table cell\n if (field.type === 'json' && value != null) return jsonSummary(value)\n // A url reads as its link text, when the view gives one, as the address alone says little\n if (view?.fields[name]?.format === 'url' && typeof value === 'string' && value !== '') return linkTextOf(model, view, name, row.record) ?? value\n return row.labels[name] ?? displayValue(field, value, view?.fields[name])\n }\n // A field the view shows with a field type draws its display\n const { fields: fieldTypes, components } = useProjectUi()\n const seedRecord = useSeedRecord(model)\n const Card = display.card === undefined ? undefined : components?.[display.card]\n const shownValue = (name: string) => {\n const field = model.fields[name]\n const shown = field && shownWidget(fieldTypes, field, view?.fields[name])\n return shown ? <WidgetPart shown={shown} part=\"display\" field={field} value={row.record[name]} fallback={text(name)} /> : text(name)\n }\n // A markdown subtitle shows rendered, its links as text inside the card's own link\n const subtitleValue = (name: string) => {\n const field = model.fields[name]\n const value = row.record[name]\n if (!field || !isMarkdown(field, view?.fields[name]) || shownWidget(fieldTypes, field, view?.fields[name]) || typeof value !== 'string' || value === '') return shownValue(name)\n return <Markdown source={value} inLink />\n }\n // A meta field the view formats as a badge shows as one, unless a field type draws it\n const metaValue = (name: string) => {\n const field = model.fields[name]\n const hints = view?.fields[name]\n const value = row.record[name]\n if (!field || hints?.format !== 'badge' || shownWidget(fieldTypes, field, hints) || value === null || value === undefined || value === '') return shownValue(name)\n return (\n <ValueBadge value={value} hints={hints}>\n {text(name)}\n </ValueBadge>\n )\n }\n // The amount in bold, its suffix such as ` /month` not; a relation's name or a field type's display in bold whole\n const amountValue = (name: string) => {\n const field = model.fields[name]\n if (!field) return undefined\n if (row.labels[name] !== undefined || shownWidget(fieldTypes, field, view?.fields[name])) return <strong className=\"font-semibold text-foreground\">{shownValue(name)}</strong>\n const parts = amountParts(field, row.record[name], view?.fields[name])\n return (\n <>\n <strong className=\"font-semibold text-foreground\">{parts.amount}</strong>\n {parts.suffix}\n </>\n )\n }\n // A card component draws its own content, so only the built-in card steps through photos\n const photos = Card ? undefined : display.photos\n const status = badge === undefined ? undefined : row.record[badge]\n const raised = flags.filter((name) => row.record[name] === true)\n const cover = image === undefined ? undefined : row.record[image]\n const shownAmount = filledAmount(row, amount)\n const shownCode = filledCode(row, code)\n const footing = filledMeta(row, footer)\n const pictured = image !== undefined || photos !== undefined\n // The heart sits over the picture, or beside the title, which leaves it room\n const favorite = display.favorite\n // A card component draws its own content, so only the built-in card shows the list's dots\n const dots = Card ? [] : cardDotsLines(view, display, row)\n // The card's one link is its title, stretched over the whole card, so a screen reader reads the card as one link named\n // by its title and the rest as text\n const link = (className: string, children: ReactNode) => (\n <AppLink\n to={{ kind: 'record', resource: model.name, key: row.key }}\n onClick={() => seedRecord(row.record)}\n data-card-link\n className={`${className} after:absolute after:inset-0 after:rounded-lg after:content-[''] focus-visible:outline-hidden`}\n >\n {children}\n </AppLink>\n )\n const builtIn = (picture: ReactNode, linked: boolean) => (\n <>\n {pictured && picture}\n <span className={`flex items-start justify-between gap-2 ${favorite && !pictured ? 'pr-8' : ''}`}>\n {linked ? link('min-w-0 truncate font-medium', shownValue(title)) : <span className=\"min-w-0 truncate font-medium\">{shownValue(title)}</span>}\n {badge !== undefined && status !== null && status !== undefined && (\n <ValueBadge value={status} hints={view?.fields[badge]}>\n {text(badge)}\n </ValueBadge>\n )}\n </span>\n {subtitle !== undefined && (\n // A text of several lines keeps its first three, line breaks and all, and markdown its first three rendered\n <span className={view?.fields[subtitle]?.markdown ? 'line-clamp-3 break-words text-muted-foreground' : view?.fields[subtitle]?.multiline ? 'line-clamp-3 whitespace-pre-line break-words text-muted-foreground' : 'truncate text-muted-foreground'}>{subtitleValue(subtitle)}</span>\n )}\n {shownAmount !== undefined && <span className=\"truncate tabular-nums text-muted-foreground\">{amountValue(shownAmount)}</span>}\n {shownCode !== undefined && <CodeBlock>{rawCode(model.fields[shownCode], row.record[shownCode]) ?? text(shownCode)}</CodeBlock>}\n {meta.length > 0 && (\n <dl className=\"mt-auto flex flex-wrap items-center gap-x-3 gap-y-0.5 pt-1 text-xs text-muted-foreground\">\n {filledMeta(row, meta).map((name) => (\n <div key={name} className=\"flex gap-1\">\n <dt className=\"sr-only\">{label(name)}</dt>\n <MetaValue icon={view?.fields[name]?.icon}>{metaValue(name)}</MetaValue>\n </div>\n ))}\n </dl>\n )}\n {raised.length > 0 && (\n <ul className=\"flex flex-wrap gap-1\" aria-label={message('features')}>\n {raised.map((name) => (\n <li key={name}>\n <Badge dot={false}>{label(name)}</Badge>\n </li>\n ))}\n </ul>\n )}\n {footing.length > 0 && (\n <span className={`truncate text-xs text-muted-foreground ${meta.length > 0 ? '' : 'mt-auto'}`}>\n {footing.map((name, index) => (\n <span key={name}>\n {index > 0 && <span aria-hidden> • </span>}\n {shownValue(name)}\n </span>\n ))}\n </span>\n )}\n {dots.length > 0 && <CardDotsRoom dots={dots} />}\n </>\n )\n // Isolated, so what sits beside the card in the document, such as the photo arrows and the heart, stays over its link\n const card = (picture: ReactNode) => (\n <div className=\"relative isolate flex h-full flex-col gap-1.5 rounded-lg border border-border bg-background p-3 hover:border-border-strong hover:bg-surface has-[[data-card-link]:focus-visible]:ring-2 has-[[data-card-link]:focus-visible]:ring-primary/30\">\n {mark && !pictured && (\n <Badge tone=\"blue\" className=\"self-start\">\n {mark}\n </Badge>\n )}\n {Card ? (\n <>\n {/* A drawn card's content is not known to hold the title, so the link over it is named by the title unseen */}\n {link('absolute inset-0', <span className=\"sr-only\">{shownValue(title)}</span>)}\n <CustomBoundary name={display.card!} fallback={builtIn(picture, false)}>\n <Card row={row} />\n </CustomBoundary>\n </>\n ) : (\n builtIn(picture, true)\n )}\n </div>\n )\n return (\n <div className={photos ? 'group/card relative h-full' : favorite || mark || dots.length > 0 ? 'relative h-full' : 'h-full'}>\n {photos ? (\n // A card drawn for another record, as the map's chosen card is, starts again at that record's first photo\n <CardCarousel key={row.key} photos={row.photos ?? []} cover={cover} swipe={swipe}>\n {(picture) =>\n card(\n // The photos sit over the title's link, so a swipe moves them; a tap opens the record through a link of their\n // own, which a screen reader skips as the title's says the same\n <AppLink to={{ kind: 'record', resource: model.name, key: row.key }} onClick={() => seedRecord(row.record)} tabIndex={-1} aria-hidden className=\"relative z-[1] block\">\n {picture}\n </AppLink>,\n )\n }\n </CardCarousel>\n ) : (\n card(<CardImage value={cover} />)\n )}\n {mark && pictured && (\n <Badge tone=\"blue\" className=\"pointer-events-none absolute top-2 left-2 shadow-sm\">\n {mark}\n </Badge>\n )}\n {dots.length > 0 && <CardDots dots={dots} Card={RecordCard} />}\n {favorite && <FavoriteButton favorite={favorite} recordKey={row.key} target={recordKey(model, row.record) as KeyValue} className={pictured ? undefined : 'right-1.5 top-1.5'} />}\n </div>\n )\n}\n","import { snapCardWidth, snapRowGap } from '../../primitives/snap-row-width'\n\n/** The gap after a card of a record row, in pixels. */\nconst rowCardGap = 12\n\n/** How many cards beyond each edge of the view are drawn, so a short scroll shows cards already there. */\nconst overscan = 3\n\n/**\n * The cards of a row of `total` to draw when it is scrolled `scrollLeft` into a view `width` wide: from `start` up to\n * `end` (not included), the ones in view and `overscan` more on each side, none past either end. A card is 256px wide,\n * or the view's width when that is narrower, as a `SnapRow` sizes it.\n */\nexport const rowWindow = (scrollLeft: number, width: number, total: number) => {\n const step = Math.max(1, Math.min(snapCardWidth, width)) + rowCardGap\n const first = Math.floor(Math.max(0, scrollLeft) / step)\n const last = Math.ceil((Math.max(0, scrollLeft) + width) / step)\n return { start: Math.max(0, first - overscan), end: Math.min(total, last + overscan) }\n}\n\n/** How many cards beyond the drawn ones keep a place of their own, which a swipe snaps to before it is drawn. */\nconst placesAround = 50\n\n/**\n * The cards of a row of `total` that have a place of their own while `start` up to `end` are drawn: those and\n * `placesAround` more on each side. The rest stand together in one spacer at each end (`rowSpan`), so a row of a hundred\n * thousand records draws a few hundred elements, not one for each.\n */\nexport const rowPlaces = (start: number, end: number, total: number) => ({ from: Math.max(0, start - placesAround), to: Math.min(total, end + placesAround) })\n\n/** The width of `count` cards of a row and the gaps between them, as a `SnapRow` sizes its cards, for a spacer that stands in for them. */\nexport const rowSpan = (count: number) => `calc(${count} * (min(${snapCardWidth}px, 100%) + ${snapRowGap}) - ${snapRowGap})`\n","import { messages } from '../../locale/messages'\n\nexport const text = messages('app/record-row')\n","import type { ListDisplayModel, ResourceModel, ViewModel } from '@protobase/schema'\nimport type { RowSource } from '../../data-grid'\nimport { usePagedRows } from '../../data-grid/use-paged-rows'\nimport { Skeleton } from '../../primitives/skeleton'\nimport { SnapRow } from '../../primitives/snap-row'\nimport { useSnapScroll } from '../../primitives/use-snap-scroll'\nimport { displayRow, type ListDisplayRow } from '../displays/list-displays'\nimport { RecordCard } from '../displays/record-card'\nimport { rowPlaces, rowSpan, rowWindow } from './row-window'\nimport { text } from './messages'\n\ntype CardsDisplayModel = Extract<ListDisplayModel, { kind: 'cards' }>\n\ntype RecordRowProps = {\n model: ResourceModel\n view: ViewModel | undefined\n display: CardsDisplayModel\n source: RowSource\n /** What the cards are, such as \"Homes\", for the list's label. */\n label: string\n /** Whether a record is new to the user, marked \"New\" in its card's top left corner. */\n isNew?: (row: ListDisplayRow) => boolean\n}\n\n// The cards far from the view, as wide as they are together: the row keeps its length, and a swipe does not stop in it\nconst Spacer = ({ count }: { count: number }) => <li aria-hidden style={{ width: rowSpan(count), minWidth: 0, scrollSnapAlign: 'none' }} />\n\n/**\n * Records as the cards of their list, in a `SnapRow`: only the cards near the view are drawn, and the records are loaded\n * through the list API in pages as the row scrolls to them. Each card links to its record. Every record near the view has\n * its place, an empty one until it is drawn, so the row snaps to a card a fast swipe reaches before it is drawn; the\n * records further away stand together in a spacer at each end, so a row of a large list draws a few hundred elements.\n */\nexport const RecordRow = ({ model, view, display, source, label, isNew }: RecordRowProps) => {\n const { total } = source\n const shown = (scrolled: { left: number; width: number }) => rowWindow(scrolled.left, scrolled.width, total)\n const scroll = useSnapScroll((scrolled) => {\n const { start, end } = shown(scrolled)\n return `${start}-${end}`\n })\n const { start, end } = shown(scroll.view)\n const places = rowPlaces(start, end, total)\n const getRow = usePagedRows({ total, rowAt: source.rowAt, loadRows: source.loadRows, cachedRows: source.cachedRows, revision: source.revision, latencyMs: 0 }, start, Math.max(start, end - 1))\n return (\n <SnapRow scroll={scroll} label={label}>\n {places.from > 0 && <Spacer count={places.from} />}\n {Array.from({ length: places.to - places.from }, (_, offset) => {\n const index = places.from + offset\n if (index < start || index >= end) return <li key={`place-${index}`} aria-hidden />\n const loaded = getRow(index)\n if (!loaded) {\n return (\n <li key={`skeleton-${index}`} aria-hidden>\n <Skeleton className=\"h-full min-h-24 rounded-lg\" />\n </li>\n )\n }\n const row = displayRow(model, loaded)\n return (\n <li key={row.key} aria-posinset={index + 1} aria-setsize={total} className=\"grid grid-cols-[minmax(0,1fr)]\">\n <RecordCard model={model} view={view} display={display} row={row} swipe={false} mark={isNew?.(row) ? text('new') : undefined} />\n </li>\n )\n })}\n {places.to < total && <Spacer count={total - places.to} />}\n </SnapRow>\n )\n}\n","import { createWhere, parseFilter, printFilter, type FilterExpr, type ResourceModel, type ViewModel } from '@protobase/schema'\nimport { loadedFields } from '../displays/list-displays'\nimport { defaultOrderBy } from '../list-order'\n\nconst where = createWhere()\n\n// The filter a row loads with: its own, narrowed to `scope`\nconst scoped = (filter: string, scope: FilterExpr | undefined) => {\n if (!scope) return filter\n const parsed = parseFilter(filter)\n if (!parsed.ok) throw new Error(`The filter cannot be read: ${parsed.errors.map((error) => error.message).join('; ')}`)\n return printFilter(parsed.ast ? where.and(parsed.ast, scope) : scope)\n}\n\n/** What a record row loads its records with: the fields its view's displays show, its filter narrowed to `scope`, and its order, the list's when `sort` is empty. */\nexport const recordRowRead = (model: ResourceModel, view: ViewModel | undefined, { filter, sort, scope }: { filter: string; sort: string; scope?: FilterExpr }) => ({\n columns: loadedFields(model, view, []),\n filter: scoped(filter, scope),\n orderBy: sort || defaultOrderBy(model, view),\n})\n","import { ArrowRight } from 'lucide-react'\nimport { useMemo, type ReactNode } from 'react'\nimport type { FilterExpr, ListDisplayModel, ResourceModel, ViewModel } from '@protobase/schema'\nimport { useIsXs } from '../../lib/use-media-query'\nimport { humanize } from '../../live/naming'\nimport { useLiveRows } from '../../live/use-live-rows'\nimport { Skeleton } from '../../primitives/skeleton'\nimport { displaysOf, type ListDisplayRow } from '../displays/list-displays'\nimport { viewAllAddress } from '../embedded-list/embedded-display'\nimport { ErrorBanner } from '../error-banner'\nimport { useAdminMeta } from '../meta-gate'\nimport { FilterChipList } from '../searches/filter-chip-list'\nimport { useFilterChips } from '../searches/use-filter-chips'\nimport { AppLink } from '../use-app-address'\nimport { RecordRow } from './record-row'\nimport { recordRowRead } from './record-row-read'\nimport { formatTag } from '../../locale/active-locale'\nimport { text } from './messages'\n\ntype CardsDisplayModel = Extract<ListDisplayModel, { kind: 'cards' }>\n\nexport type RecordRowBodyProps = {\n model: ResourceModel\n view: ViewModel | undefined\n /** The records shown: those matching `filter` (AIP-160) in `sort` order (AIP-132), the list's order when empty. */\n filter: string\n sort?: string\n /** The cards display of the view whose cards it draws; its first when omitted, the title alone without one. */\n display?: string\n /** How many records it shows at most; every one that matches when omitted. */\n limit?: number\n /** Whether it shows what the filter filters on, as chips. */\n chips?: boolean\n empty?: string\n /** A line about the records beside the count, such as that none are new. */\n note?: ReactNode\n isNew?: (row: ListDisplayRow) => boolean\n /** \"View all\"'s label, and the saved search whose results it opens, calling `onOpen` first. */\n viewAll?: { label?: string; savedSearch?: string; onOpen?: () => void }\n /** A filter every load adds to `filter`, which the chips and \"View all\" leave out: the records among the user's saved ones. */\n scope?: FilterExpr\n /** The resource whose list \"View all\" opens, the records' own by default: the saved records' list for a `scope`. */\n list?: string\n}\n\n/** The display a row draws its cards with: the one named, else the view's first cards display, else a card of the title. */\nconst rowDisplay = (view: ViewModel | undefined, name: string | undefined): CardsDisplayModel => {\n const cards = displaysOf(view).filter((display): display is CardsDisplayModel => display.kind === 'cards')\n return cards.find((display) => display.name === name) ?? cards[0] ?? { kind: 'cards', name: 'cards' }\n}\n\n// Three cards' worth, each as wide as a card (`rowCardWidth`)\nconst Loading = () => (\n <div className=\"flex gap-3 overflow-hidden\">\n {Array.from({ length: 3 }, (_, index) => (\n <Skeleton key={index} className=\"h-24 w-64 shrink-0\" />\n ))}\n </div>\n)\n\n/**\n * What a filter finds, in a card's body: its filters as chips, how many records match, the records in a row of their\n * list's cards that scrolls sideways (`RecordRow`), and \"View all\", which opens the list with the filter.\n */\nexport const RecordRowBody = ({ model, view, filter, sort = '', display: named, limit, chips: showChips = true, empty, note, isNew, viewAll, scope, list }: RecordRowBodyProps) => {\n const { resources, views } = useAdminMeta()\n const xs = useIsXs()\n const display = rowDisplay(view, named)\n const read = useMemo(() => recordRowRead(model, view, { filter, sort, scope }), [model, view, filter, sort, scope])\n const { orderBy } = read\n const rows = useLiveRows({ resources, views, model, ...read })\n const chips = useFilterChips(model, filter)\n const singular = (view?.names?.singular ?? humanize(model.name)).toLowerCase()\n const plural = view?.names?.plural ?? humanize(model.name)\n const total = rows.source?.total\n const source = useMemo(() => rows.source && { ...rows.source, total: Math.min(rows.source.total, limit ?? Infinity) }, [rows.source, limit])\n\n return (\n <div className=\"flex min-w-0 flex-col gap-3\">\n {(showChips && chips.length > 0) || total !== undefined || note ? (\n <div className=\"flex flex-wrap items-center justify-between gap-2\">\n {showChips && chips.length > 0 ? <FilterChipList chips={chips} /> : <span />}\n <p className=\"flex flex-wrap gap-x-3 text-muted-foreground\">\n {note && <span>{note}</span>}\n {total !== undefined && <span className=\"tabular-nums\">{`${total.toLocaleString(formatTag())} ${total === 1 ? singular : plural.toLowerCase()}`}</span>}\n </p>\n </div>\n ) : null}\n {rows.isLoading ? (\n <Loading />\n ) : rows.error ? (\n <ErrorBanner title={text('couldNotLoad')} error={rows.error} />\n ) : !source || source.total === 0 ? (\n <p className=\"text-muted-foreground\">{empty ?? text('noneMatch', { plural: plural.toLowerCase() })}</p>\n ) : (\n <RecordRow model={model} view={view} display={display} source={source} label={plural} isNew={isNew} />\n )}\n <AppLink\n to={viewAllAddress(model, view, xs, { filter, orderBy, display: display.name, savedSearch: viewAll?.savedSearch, resource: list })}\n onClick={viewAll?.onOpen}\n className=\"flex items-center gap-1 self-end font-medium text-primary-text hover:underline\"\n >\n {viewAll?.label ?? <>{text('viewAll')} <span className=\"sr-only\">{plural.toLowerCase()}</span></>}\n <ArrowRight className=\"size-3.5\" aria-hidden />\n </AppLink>\n </div>\n )\n}\n","import { useQuery } from '@tanstack/react-query'\nimport { useClient } from '../../data/api-provider'\nimport { keys } from '../../data/query-keys'\nimport { useAdminMeta } from '../meta-gate'\nimport { defaultOrderBy } from '../list-order'\nimport { savedPageSize } from '../saved/saved-records'\n\n/** One of the user's saved searches as the list API gives it: its fields, and its ETag to change it with. */\nexport type SavedSearchRow = Record<string, unknown> & { etag?: string }\n\n/** Where the user's saved searches of `resource` are cached; a list key, so a write to the resource refreshes it. */\nexport const savedSearchesKey = (resource: string) => keys.list(resource, '', '', savedPageSize, 'saved-searches')\n\n/**\n * The signed-in user's saved searches, in the order of their view's list: every one, page by page, as the API lists only\n * a user's own records of a resource with an owner. Loads only while `enabled`.\n */\nexport const useSavedSearches = (resource: string, enabled: boolean) => {\n const client = useClient()\n const { resources, views } = useAdminMeta()\n const model = resources[resource]\n return useQuery({\n queryKey: savedSearchesKey(resource),\n enabled: enabled && model !== undefined,\n queryFn: async (): Promise<SavedSearchRow[]> => {\n const rows: SavedSearchRow[] = []\n let pageToken: string | undefined\n do {\n const page = await client.list(resource, { pageSize: savedPageSize, orderBy: defaultOrderBy(model!, views[resource]), ...(pageToken && { pageToken }) })\n rows.push(...(page.items as SavedSearchRow[]))\n pageToken = page.nextPageToken || undefined\n } while (pageToken)\n return rows\n },\n })\n}\n","import { useMutation, useQuery } from '@tanstack/react-query'\nimport type { ResourceModel, SearchesOfModel, ViewModel } from '@protobase/schema'\nimport { useClient } from '../../data/api-provider'\nimport { humanize } from '../../live/naming'\nimport { countQuery, useRefreshResource } from '../pages/use-layout-data'\nimport type { RecordRowBodyProps } from '../record-row/record-row-body'\nimport { chipsText } from './filter-chip-list'\nimport { isUnseen, unseenFilter } from './saved-search'\nimport { useFilterChips } from './use-filter-chips'\nimport type { SavedSearchRow } from './use-saved-searches'\nimport { text } from './messages'\n\ntype SearchRowInput = {\n /** The saved searches' resource, whose view's `searchesOf` is `of`. */\n model: ResourceModel\n of: SearchesOfModel\n /** The resource searched and its view. */\n target: ResourceModel\n targetView: ViewModel | undefined\n row: SavedSearchRow\n /** The search's key, in the text form the record API takes. */\n recordKey: string\n}\n\n/**\n * One saved search as a row of what it finds: its name, if it has one, its filters as chips, its title (the name, or\n * the chips as words), and the `RecordRowBody` of its records: with `unseen` newest first, those new to the user marked\n * \"New\", saying so when none are, and \"View all results\", which opens the list from the search and counts as having\n * seen them.\n */\nexport const useSearchRow = ({ model, of, target, targetView, row, recordKey }: SearchRowInput) => {\n const client = useClient()\n const refresh = useRefreshResource()\n const filter = String(row[of.filter] ?? '')\n const chips = useFilterChips(target, filter)\n const stored = of.name === undefined ? undefined : row[of.name]\n const name = typeof stored === 'string' && stored !== '' ? stored : undefined\n const unseen = of.unseen\n const markSeen = useMutation({\n mutationFn: (seenAt: string) => client.update(model.name, recordKey, { [unseen!.seenAt]: seenAt }, row.etag ?? '*'),\n onSettled: () => refresh(model.name),\n })\n // How many of its records are new, to say when none are; every record is new to a search never seen\n const newCount = useQuery({ ...countQuery(client, target, unseen ? unseenFilter(filter, unseen.field, row[unseen.seenAt]) : ''), enabled: unseen !== undefined })\n const plural = (targetView?.names?.plural ?? humanize(target.name)).toLowerCase()\n const body: RecordRowBodyProps = {\n model: target,\n view: targetView,\n filter,\n sort: unseen ? `${unseen.field} desc` : undefined,\n limit: of.limit,\n chips: name !== undefined,\n empty: text('noneMatch', { plural }),\n note: unseen && newCount.data === 0 && text('noNew', { plural }),\n isNew: unseen && ((record) => isUnseen(record.record[unseen.field], row[unseen.seenAt])),\n viewAll: { label: text('viewAll'), savedSearch: recordKey, ...(unseen && { onOpen: () => markSeen.mutate(new Date().toISOString()) }) },\n }\n return { name, chips, title: name ?? chipsText(chips), body }\n}\n","import type { ReactNode } from 'react'\nimport { Button } from '../../primitives/button'\nimport { ErrorBanner } from '../error-banner'\nimport type { ListDisplay } from './display-context'\nimport { formatTag } from '../../locale/active-locale'\nimport { text } from './messages'\n\n/** A display's scrolling area: while loading, on an error or with no rows it says so instead of drawing them. */\nexport const DisplayState = ({ list, empty, loading, children }: { list: ListDisplay; empty: string; loading: ReactNode; children: ReactNode }) => (\n <div className=\"min-h-0 flex-1 overflow-y-auto\">\n {list.loading ? loading : list.error ? <ErrorBanner title={text('couldNotLoadRows')} error={list.error} /> : list.rows.length === 0 ? <p className=\"py-8 text-center text-muted-foreground\">{empty}</p> : children}\n </div>\n)\n\n/** How many of the matching records are shown, and a button for the next page while there is one. */\nexport const DisplayFooter = ({ list }: { list: ListDisplay }) => (\n <div className=\"flex items-center justify-between gap-3 py-3 text-xs text-muted-foreground\">\n <span>\n {list.rows.length.toLocaleString(formatTag())} of {list.total.toLocaleString(formatTag())}\n </span>\n {list.more && (\n <Button size=\"sm\" onClick={list.loadMore}>\n {text('showMore')}\n </Button>\n )}\n </div>\n)\n","import type { ListDisplayModel, ResourceModel, ViewModel } from '@protobase/schema'\nimport { cn } from '../../lib/cn'\nimport { humanize } from '../../live/naming'\nimport { Skeleton } from '../../primitives/skeleton'\nimport type { ListDisplay } from './display-context'\nimport { DisplayFooter, DisplayState } from './display-frame'\nimport { RecordCard } from './record-card'\nimport { text } from './messages'\n\ntype CardsProps = {\n model: ResourceModel\n view: ViewModel | undefined\n display: Extract<ListDisplayModel, { kind: 'cards' }>\n list: ListDisplay\n /** The cards in one row that scrolls sideways, card by card, instead of a grid, as an embedded list shows them on a phone. */\n row?: boolean\n /** How many are shown and a button for more, under the cards; an embedded list, which links to the list instead, leaves it out. */\n footer?: boolean\n}\n\nconst grid = 'grid grid-cols-[repeat(auto-fill,minmax(15rem,1fr))] gap-3'\n// Positioned, so the cards' screen-reader labels scroll inside it instead of widening the page\nconst scroller = 'relative flex snap-x snap-mandatory gap-3 overflow-x-auto pb-1'\n\n/** A card per record (see `RecordCard`), in a grid or a row, with how many match and a button for more below. */\nexport const CardsDisplay = ({ model, view, display, list, row = false, footer = true }: CardsProps) => {\n const plural = (view?.names?.plural ?? humanize(model.name)).toLowerCase()\n return (\n <DisplayState list={list} empty={text('noneMatch', { plural })} loading={<div className={grid}>{Array.from({ length: 6 }, (_, index) => <Skeleton key={index} className=\"h-24\" />)}</div>}>\n <ul className={row ? scroller : grid} aria-label={view?.names?.plural ?? humanize(model.name)}>\n {list.rows.map((record) => (\n <li key={record.key} className={cn(row && 'w-64 shrink-0 snap-start')}>\n <RecordCard model={model} view={view} display={display} row={record} swipe={!row} />\n </li>\n ))}\n </ul>\n {footer && <DisplayFooter list={list} />}\n </DisplayState>\n )\n}\n","import type { ListDisplayModel } from '@protobase/schema'\nimport { unmarkFieldRefs } from '@protobase/schema/internal'\nimport { CustomBoundary } from '../pages/custom-boundary'\nimport { Problem } from '../pages/problem'\nimport { useProjectUi } from '../pages/project-ui'\nimport { ListDisplayProvider, type ListDisplay } from './display-context'\nimport { text } from './messages'\n\n/**\n * A display the project draws: the component registered under its name gets the display's props, field references\n * as the names they reference, and reads the list page's rows with `useListDisplay()`.\n */\nexport const CustomDisplay = ({ display, list }: { display: Extract<ListDisplayModel, { kind: 'custom' }>; list: ListDisplay }) => {\n const { components } = useProjectUi()\n const Component = components?.[display.component]\n if (!Component) return <Problem>{text.rich('noComponent', { component: display.component })}</Problem>\n return (\n <ListDisplayProvider value={list}>\n {/* As tall as what it draws, scrolling with the page; a wide one, such as a board, scrolls sideways; positioned, so what it places absolutely scrolls inside it instead of widening the page */}\n <div className=\"relative min-w-0 flex-1 overflow-x-auto\">\n <CustomBoundary name={display.component}>\n <Component {...unmarkFieldRefs(display.props ?? {})} />\n </CustomBoundary>\n </div>\n </ListDisplayProvider>\n )\n}\n","import { createWhere, printFilter, type FilterExpr } from '@protobase/schema'\nimport type { MapBounds, MapBucket } from '@protobase/client'\nimport type { Position } from './record-position'\n\nconst where = createWhere()\n\n/** What a map shows: the bounds of its view, in decimal degrees, and its zoom. */\nexport type MapArea = { bounds: MapBounds; zoom: number }\n\n/** The whole world from as far out as a map goes: what a map asks for before it knows where its records are. */\nexport const worldArea: MapArea = { bounds: { south: -90, west: -180, north: 90, east: 180 }, zoom: 0 }\n\n// MapLibre's zoom levels, from the whole world at 0 to a building at 22.\nconst maxZoom = 22\n\n// Six decimals of a degree are about ten centimetres; rounding outwards keeps every record in view inside the box.\nconst down = (degrees: number) => Math.floor(degrees * 1e6) / 1e6\nconst up = (degrees: number) => Math.ceil(degrees * 1e6) / 1e6\n\n// MapLibre counts on past the antimeridian when the map shows it, such as 190 for -170.\nconst wrapped = (longitude: number) => ((((longitude + 180) % 360) + 360) % 360) - 180\n\n/**\n * The AIP-160 filter for the records inside `bounds`: between its latitudes, and between its longitudes on the globe.\n * A view across the antimeridian takes the longitudes on both sides of it, and one around the whole world takes them all.\n */\nexport const boundsFilter = (fields: { latitude: string; longitude: string }, bounds: MapBounds): FilterExpr => {\n const latitude = [where.gte(fields.latitude, down(Math.max(bounds.south, -90))), where.lte(fields.latitude, up(Math.min(bounds.north, 90)))]\n if (bounds.east - bounds.west >= 360) return where.and(...latitude)\n const west = where.gte(fields.longitude, down(wrapped(bounds.west)))\n const east = where.lte(fields.longitude, up(wrapped(bounds.east)))\n return wrapped(bounds.west) <= wrapped(bounds.east) ? where.and(...latitude, west, east) : where.and(...latitude, where.or(west, east))\n}\n\n/** The list's filter, its search included, narrowed to the records inside the map's bounds. */\nexport const areaFilter = (listFilter: string, fields: { latitude: string; longitude: string }, bounds: MapBounds) => {\n const inside = printFilter(boundsFilter(fields, bounds))\n return listFilter.trim() === '' ? inside : `(${listFilter}) AND ${inside}`\n}\n\n/** The zoom the records are asked for at: the whole zoom level the map is at. */\nexport const requestZoom = (zoom: number) => Math.min(Math.max(Math.floor(zoom), 0), maxZoom)\n\n/** The bounds around the records and the buckets, or none without either. */\nexport const boundsAround = (points: Position[], buckets: MapBucket[]): MapBounds | undefined => {\n const corners = [\n ...points.map((point) => ({ south: point.latitude, west: point.longitude, north: point.latitude, east: point.longitude })),\n ...buckets.map((bucket) => bucket.bounds),\n ]\n if (corners.length === 0) return undefined\n return {\n south: Math.min(...corners.map((corner) => corner.south)),\n west: Math.min(...corners.map((corner) => corner.west)),\n north: Math.max(...corners.map((corner) => corner.north)),\n east: Math.max(...corners.map((corner) => corner.east)),\n }\n}\n","/** A point in decimal degrees (WGS84), as a map is centred on it. */\nexport type Position = { latitude: number; longitude: number }\n\n/** A number field's value: it comes as a number, or as text for a decimal or bigint; anything else, or an empty value, is none. */\nexport const numeric = (value: unknown) => {\n if (typeof value === 'number') return value\n if (typeof value !== 'string' || value.trim() === '') return undefined\n return Number(value)\n}\n\n/** The record's position from its two fields, when both hold degrees on the globe; none otherwise, so no map is drawn. */\nexport const recordPosition = (record: Record<string, unknown>, fields: { latitude: string; longitude: string }): Position | undefined => {\n const latitude = numeric(record[fields.latitude])\n const longitude = numeric(record[fields.longitude])\n if (latitude === undefined || longitude === undefined) return undefined\n if (!(Math.abs(latitude) <= 90 && Math.abs(longitude) <= 180)) return undefined\n return { latitude, longitude }\n}\n","import { numeric, type Position } from './record-position'\n\n/** The fields of a map display that say how exact a record's position is, and the circle it draws without one of its own. */\nexport type ApproximateFields = { approximate?: string; exact?: string; radius?: string; defaultRadius?: number; area?: string }\n\ntype Ring = [number, number][]\n\n/** What a map draws around an approximate position: GeoJSON polygons, or lines such as a street, in longitude and latitude. */\nexport type AreaGeometry =\n | { type: 'Polygon'; coordinates: Ring[] }\n | { type: 'MultiPolygon'; coordinates: Ring[][] }\n | { type: 'LineString'; coordinates: Ring }\n | { type: 'MultiLineString'; coordinates: Ring[] }\n\n// The mean radius of the Earth, in metres, as GeoJSON's WGS84 positions are measured on it.\nconst earthRadius = 6_371_008.8\n// Corners of the polygon a circle is drawn as: round at any size it is drawn at.\nconst circleCorners = 64\n\n/** Whether the record's position is approximate, as its field states; without one, or a value that says neither, it is not. */\nexport const isApproximate = (record: Record<string, unknown>, fields: ApproximateFields) => {\n if (fields.approximate !== undefined) return record[fields.approximate] === true\n if (fields.exact !== undefined) return record[fields.exact] === false\n return false\n}\n\n/** The polygon of `metres` around `center`, its corners as far from it along the globe. */\nexport const circleArea = (center: Position, metres: number): AreaGeometry => {\n const distance = metres / earthRadius\n const latitude = (center.latitude * Math.PI) / 180\n const longitude = (center.longitude * Math.PI) / 180\n const ring: Ring = Array.from({ length: circleCorners + 1 }, (_, index) => {\n const bearing = ((index % circleCorners) / circleCorners) * 2 * Math.PI\n const to = Math.asin(Math.sin(latitude) * Math.cos(distance) + Math.cos(latitude) * Math.sin(distance) * Math.cos(bearing))\n const across = longitude + Math.atan2(Math.sin(bearing) * Math.sin(distance) * Math.cos(latitude), Math.cos(distance) - Math.sin(latitude) * Math.sin(to))\n return [(across * 180) / Math.PI, (to * 180) / Math.PI]\n })\n return { type: 'Polygon', coordinates: [ring] }\n}\n\nconst isPosition = (value: unknown): value is [number, number] =>\n Array.isArray(value) && value.length >= 2 && typeof value[0] === 'number' && typeof value[1] === 'number' && Math.abs(value[0]) <= 180 && Math.abs(value[1]) <= 90\n\nconst isLine = (value: unknown, least: number): value is Ring => Array.isArray(value) && value.length >= least && value.every(isPosition)\nconst isPolygon = (value: unknown): value is Ring[] => Array.isArray(value) && value.length > 0 && value.every((ring) => isLine(ring, 4))\nconst isLines = (value: unknown): value is Ring[] => Array.isArray(value) && value.length > 0 && value.every((line) => isLine(line, 2))\n\n// GeoJSON comes as data from a json field, or as its text from a text field.\nconst parsed = (value: unknown): unknown => {\n if (typeof value !== 'string') return value\n try {\n return JSON.parse(value)\n } catch (error) {\n if (error instanceof SyntaxError) return undefined\n throw error\n }\n}\n\n/** The GeoJSON polygon or line a value holds, as a geometry or a feature of one; none for anything else, such as a point or text that is no GeoJSON. */\nexport const areaGeometry = (value: unknown): AreaGeometry | undefined => {\n const data = parsed(value)\n if (typeof data !== 'object' || data === null) return undefined\n const geometry = (data as { type?: unknown }).type === 'Feature' ? (data as { geometry?: unknown }).geometry : data\n if (typeof geometry !== 'object' || geometry === null) return undefined\n const { type, coordinates } = geometry as { type?: unknown; coordinates?: unknown }\n if (type === 'Polygon' && isPolygon(coordinates)) return { type, coordinates }\n if (type === 'MultiPolygon' && Array.isArray(coordinates) && coordinates.length > 0 && coordinates.every(isPolygon)) return { type, coordinates }\n if (type === 'LineString' && isLine(coordinates, 2)) return { type, coordinates }\n if (type === 'MultiLineString' && isLines(coordinates)) return { type, coordinates }\n return undefined\n}\n\n/**\n * What the map draws around the record's approximate position: the area its field holds, else a circle of the radius\n * its field holds, else one of the display's default radius. An exact position, or one whose record states none of\n * them on a display without a default, has none.\n */\nexport const positionArea = (record: Record<string, unknown>, fields: ApproximateFields, position: Position): AreaGeometry | undefined => {\n if (!isApproximate(record, fields)) return undefined\n const area = fields.area === undefined ? undefined : areaGeometry(record[fields.area])\n if (area) return area\n const radius = fields.radius === undefined ? undefined : numeric(record[fields.radius])\n if (radius !== undefined && Number.isFinite(radius) && radius > 0) return circleArea(position, radius)\n return fields.defaultRadius === undefined ? undefined : circleArea(position, fields.defaultRadius)\n}\n","import { isApproximate, positionArea, type ApproximateFields, type AreaGeometry } from '../map/approximate-position'\nimport { recordPosition, type Position } from '../map/record-position'\nimport type { ListDisplayRow } from './list-displays'\n\n/** A record on a map display: its key, its position, whether that is approximate, and the area drawn around it if so. */\nexport type MapPoint = Position & { key: string; approximate?: true; area?: AreaGeometry }\n\n/** A point as the map draws it, in pixels from the map's corner. */\nexport type ScreenPoint = { key: string; x: number; y: number }\n\n/** The records a map marker stands for, by their keys, at the position of the first. */\nexport type MapGroup = { keys: string[]; at: string }\n\n/** The rows with a position, in their order, approximate ones marked with their area; a row without one is not on the map. */\nexport const mapPoints = (rows: ListDisplayRow[], fields: { latitude: string; longitude: string } & ApproximateFields): MapPoint[] =>\n rows.flatMap((row) => {\n const position = recordPosition(row.record, fields)\n if (!position) return []\n if (!isApproximate(row.record, fields)) return [{ key: row.key, ...position }]\n const area = positionArea(row.record, fields, position)\n return [{ key: row.key, ...position, approximate: true as const, ...(area && { area }) }]\n })\n\n/**\n * The markers for the points as the map draws them: in order, each point joins the first marker within `radius` pixels\n * of it, else starts its own. A marker is at its first point, so markers do not move as others join them.\n */\nexport const groupPoints = (points: ScreenPoint[], radius: number): MapGroup[] => {\n const groups: { at: ScreenPoint; keys: string[] }[] = []\n for (const point of points) {\n const near = groups.find((group) => Math.hypot(group.at.x - point.x, group.at.y - point.y) <= radius)\n if (near) near.keys.push(point.key)\n else groups.push({ at: point, keys: [point.key] })\n }\n return groups.map((group) => ({ keys: group.keys, at: group.at.key }))\n}\n\n/** A choice of records on the map, and which of them shows its card; none once the list no longer has any of them. */\nexport type MapSelection = { keys: string[]; index: number }\n\n/** The selection kept to the records the list still has, its card the same record when it is still there. */\nexport const keptSelection = (selection: MapSelection | undefined, rows: ListDisplayRow[]): MapSelection | undefined => {\n if (!selection) return undefined\n const present = new Set(rows.map((row) => row.key))\n const keys = selection.keys.filter((key) => present.has(key))\n if (keys.length === 0) return undefined\n const index = keys.indexOf(selection.keys[selection.index]!)\n return { keys, index: Math.max(index, 0) }\n}\n\n/** The selection moved by `step` records, round from the last to the first. */\nexport const stepSelection = (selection: MapSelection, step: number): MapSelection => ({\n keys: selection.keys,\n index: (((selection.index + step) % selection.keys.length) + selection.keys.length) % selection.keys.length,\n})\n","import { keepPreviousData, useQuery } from '@tanstack/react-query'\nimport type { ListDisplayModel, ResourceModel, ViewModel } from '@protobase/schema'\nimport { useClient } from '../../data/api-provider'\nimport { keys } from '../../data/query-keys'\nimport { listLabels, withLabels } from '../../live/relation-labels'\nimport { listPhotos, withPhotos } from '../../live/row-photos'\nimport { areaFilter, requestZoom, type MapArea } from '../map/map-area'\nimport { useAdminMeta } from '../meta-gate'\nimport { displayRow } from './list-displays'\n\nexport type MapRecordsParams = {\n model: ResourceModel\n /** The view whose list shows the map; its displays say which photos the records carry. */\n view: ViewModel | undefined\n display: Extract<ListDisplayModel, { kind: 'map' }>\n /** The fields the records' relations are labelled for, those the card shows among them. */\n fields: string[]\n /** The list's filter, its search included, and its order, as the list API takes them. */\n filter: string\n orderBy: string\n /** What the map shows; nothing is asked for without it. */\n area: MapArea | undefined\n}\n\n/**\n * The records in the map's area through the list API's `:map`, labelled for the card and with its photos, or buckets of them when it holds\n * many. A new area or filter keeps the previous answer until its own arrives, and an answer for an area the map has\n * left is never shown.\n */\nexport const useMapRecords = ({ model, view, display, fields, filter, orderBy, area }: MapRecordsParams) => {\n const client = useClient()\n const { resources, views } = useAdminMeta()\n const position = { latitude: display.latitude, longitude: display.longitude }\n const inside = area ? areaFilter(filter, position, area.bounds) : ''\n const zoom = area ? requestZoom(area.zoom) : 0\n return useQuery({\n queryKey: keys.map(model.name, `${position.latitude},${position.longitude}`, zoom, inside, orderBy),\n enabled: area !== undefined,\n placeholderData: keepPreviousData,\n queryFn: async () => {\n const result = await client.map(model.name, { ...position, zoom, filter: inside, orderBy, labels: listLabels(resources, views, model, fields), photos: listPhotos(view) })\n const labelled = withLabels(resources, model, fields, withPhotos(model, result.items, result.photos), result.labels)\n return { rows: labelled.map((record) => displayRow(model, record)), buckets: result.buckets, total: result.totalSize }\n },\n })\n}\n","import { lazy, Suspense, useLayoutEffect, useRef, useState } from 'react'\nimport { ChevronLeft, ChevronRight, CircleDashed, X } from 'lucide-react'\nimport type { ListDisplayModel, MapView, ResourceModel, ViewModel } from '@protobase/schema'\nimport { useDebounced } from '../../lib/use-debounced'\nimport { humanize } from '../../live/naming'\nimport { cn } from '../../lib/cn'\nimport { Button } from '../../primitives/button'\nimport { ErrorBanner } from '../error-banner'\nimport { boundsAround, worldArea, type MapArea } from '../map/map-area'\nimport { useAdminMeta } from '../meta-gate'\nimport { Problem } from '../pages/problem'\nimport { mapCards } from './list-displays'\nimport { keptSelection, mapPoints, stepSelection, type MapSelection } from './map-groups'\nimport { RecordCard } from './record-card'\nimport { useMapRecords } from './use-map-records'\nimport { formatTag } from '../../locale/active-locale'\nimport { text } from './messages'\n\n// MapLibre loads with the first map drawn, so a list that never shows one never loads it.\nconst RecordsMap = lazy(() => import('../map/records-map').then((module) => ({ default: module.RecordsMap })))\n\n// How long the map stays put before the records where it rests are asked for, so a run of zooms asks once.\nconst settleMs = 250\n\ntype MapProps = {\n model: ResourceModel\n view: ViewModel | undefined\n display: Extract<ListDisplayModel, { kind: 'map' }>\n /** The list's filter, its search included, and its order, as the list API takes them. */\n filter: string\n orderBy: string\n /** The fields the records' relations are labelled for, those the card shows among them. */\n fields: string[]\n /** Where the map looks when it opens; without it, it fits every matching record. */\n at?: MapView\n /** Where the map came to rest, for the list's address. */\n onMove?: (view: MapView) => void\n /** How many records are in view, under the map at desktop width; an embedded list, which links to the list instead, leaves it out. */\n footer?: boolean\n /** Below desktop width, fills the page's sides and bottom edge to edge, with no frame. */\n flush?: boolean\n}\n\nconst arrow = 'flex size-8 items-center justify-center rounded-full border border-border bg-background hover:bg-surface focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/30'\n\n/**\n * The matching records in the map's view, drawn with the map style `/meta` names: the records themselves when few are\n * in view or the map is close, else a count for each part of it, which zooms in when chosen. The map asks again as it\n * pans and zooms. Without a view of its own it first fits every matching record. Choosing a marker shows the card of\n * its record at the map's bottom, with arrows through the records the marker stands for; closing it or choosing the map\n * elsewhere clears it. A marker and a card whose record's position is approximate say so.\n */\nexport const MapDisplay = ({ model, view, display, filter, orderBy, fields, at, onMove, footer = true, flush = false }: MapProps) => {\n const maps = useAdminMeta().maps\n const style = maps?.style\n const [chosen, setChosen] = useState<MapSelection>()\n const [area, setArea] = useState<MapArea>()\n const settled = useDebounced(area, settleMs)\n // Without a view, the whole world is asked for, and the map fits what it holds\n const [fitting, setFitting] = useState(at === undefined)\n const records = useMapRecords({ model, view, display, fields, filter, orderBy, area: fitting ? worldArea : settled })\n const loaded = records.isPlaceholderData ? undefined : records.data\n const rows = records.data?.rows ?? []\n const buckets = records.data?.buckets ?? []\n const points = mapPoints(rows, display)\n const fit = fitting && loaded ? boundsAround(mapPoints(loaded.rows, display), loaded.buckets) : undefined\n\n const cards = mapCards(view, display)\n const plural = (view?.names?.plural ?? humanize(model.name)).toLowerCase()\n const singular = (view?.names?.singular ?? humanize(model.name)).toLowerCase()\n const selection = keptSelection(chosen, rows)\n const row = selection && rows.find((candidate) => candidate.key === selection.keys[selection.index])\n const approximate = new Set(points.filter((point) => point.approximate).map((point) => point.key))\n const markerLabel = (keys: string[]) => {\n const near = keys.filter((key) => approximate.has(key)).length\n if (keys.length === 1) return near === 1 ? text('showOneApproximate', { singular }) : text('showOne', { singular })\n if (near === 0) return text('showMany', { count: keys.length, plural })\n return near === keys.length ? text('showManyApproximate', { count: keys.length, plural }) : text('showManySomeApproximate', { count: keys.length, plural, near })\n }\n const bucketLabel = (count: number) => text('zoomIn', { count: count.toLocaleString(formatTag()), noun: count === 1 ? singular : plural })\n // How much of the map's bottom the card and its arrows cover, so the map keeps the chosen marker above them\n const overlay = useRef<HTMLDivElement>(null)\n const [covered, setCovered] = useState(0)\n useLayoutEffect(() => setCovered(overlay.current?.offsetHeight ?? 0), [row?.key])\n\n if (!style) return <Problem>{text('needsStyle')}</Problem>\n const empty = loaded?.total === 0\n return (\n <div className={cn('flex h-full min-h-[36rem] flex-1 flex-col sm:min-h-[28rem]', flush && 'max-md:-mx-5 max-md:-mb-4 max-md:min-h-0')}>\n <div className={cn('relative min-h-0 flex-1 overflow-hidden rounded-lg border border-border bg-muted', flush && 'max-md:rounded-none max-md:border-0')}>\n <Suspense fallback={null}>\n <RecordsMap\n style={style}\n layers={maps?.layers}\n initial={at}\n points={points}\n buckets={buckets}\n fit={fit}\n onFitted={() => setFitting(false)}\n onMove={(next, center) => {\n setArea(next)\n onMove?.(center)\n }}\n selected={selection?.keys}\n covered={selection ? covered : 0}\n onSelect={(keys) => setChosen({ keys, index: 0 })}\n onClear={() => setChosen(undefined)}\n markerLabel={markerLabel}\n bucketLabel={bucketLabel}\n />\n </Suspense>\n {records.error && (\n <div className=\"absolute inset-x-3 top-3 z-10\">\n <ErrorBanner title={text('couldNotLoadRows')} error={records.error} />\n </div>\n )}\n {empty && (\n <div className=\"pointer-events-none absolute inset-x-3 top-3 z-10 flex justify-center\">\n <p className=\"pointer-events-auto flex items-center gap-3 rounded-full border border-border bg-background px-4 py-1.5 text-muted-foreground shadow\" role=\"status\">\n {fitting ? text('noneMatch', { plural }) : text('noneHere', { plural })}\n {!fitting && (\n <Button size=\"sm\" onClick={() => setFitting(true)}>\n {text('showAll')}\n </Button>\n )}\n </p>\n </div>\n )}\n {selection && row && (\n <div ref={overlay} className=\"pointer-events-none absolute inset-x-3 bottom-3 z-10 flex justify-center\">\n <div className=\"pointer-events-auto flex w-full max-w-[16rem] flex-col gap-2 sm:max-w-xs\" role=\"group\" aria-label={text('chosen', { singular })}>\n <div className=\"flex items-center justify-end gap-1.5\">\n {approximate.has(row.key) && (\n <span className=\"mr-auto flex items-center gap-1 rounded-full border border-border bg-background px-2 py-1 text-xs\">\n <CircleDashed className=\"size-3.5\" aria-hidden />\n {text('approximatePosition')}\n </span>\n )}\n {selection.keys.length > 1 && (\n <>\n <button type=\"button\" aria-label={text('previous')} className={arrow} onClick={() => setChosen(stepSelection(selection, -1))}>\n <ChevronLeft className=\"size-4\" aria-hidden />\n </button>\n <span className=\"rounded-full border border-border bg-background px-2 py-1 text-xs tabular-nums\" aria-live=\"polite\">\n {selection.index + 1} / {selection.keys.length}\n </span>\n <button type=\"button\" aria-label={text('next')} className={arrow} onClick={() => setChosen(stepSelection(selection, 1))}>\n <ChevronRight className=\"size-4\" aria-hidden />\n </button>\n </>\n )}\n <button type=\"button\" aria-label={text('close')} className={arrow} onClick={() => setChosen(undefined)}>\n <X className=\"size-4\" aria-hidden />\n </button>\n </div>\n <div className=\"shadow-lg\">\n <RecordCard model={model} view={view} display={cards} row={row} />\n </div>\n </div>\n </div>\n )}\n </div>\n {footer && <p className=\"hidden py-3 text-xs text-muted-foreground md:block\">{inView(records.data, plural)}</p>}\n </div>\n )\n}\n\n/** How many of the matching records are in view, and how many the map shows when it cannot show them all. */\nconst inView = (data: { rows: unknown[]; buckets: unknown[]; total: number } | undefined, plural: string) => {\n if (!data) return ' '\n const total = data.total.toLocaleString(formatTag())\n if (data.buckets.length === 0 && data.rows.length < data.total) return `${data.rows.length.toLocaleString(formatTag())} of ${total} ${plural} in view`\n return `${total} ${plural} in view`\n}\n","import { Skeleton } from '../../primitives/skeleton'\nimport { lazyComponent } from '../lazy-component'\n\n// The list displays that draw with libraries of their own, such as the board's dragging, load with the first one shown.\n\nconst area = () => <Skeleton className=\"min-h-60 flex-1 rounded-lg\" />\n\nexport const BoardDisplay = lazyComponent(() => import('./board-display').then((module) => module.BoardDisplay), area)\nexport const CalendarDisplay = lazyComponent(() => import('./calendar-display').then((module) => module.CalendarDisplay), area)\nexport const TimelineDisplay = lazyComponent(() => import('./timeline-display').then((module) => module.TimelineDisplay), area)\n","import { Calendar, ChartGantt, Columns3, LayoutGrid, List, Map as MapIcon, SquareKanban, Table2, type LucideIcon } from 'lucide-react'\nimport type { ListDisplayModel, ResourceModel, ViewModel } from '@protobase/schema'\nimport { cn } from '../../lib/cn'\nimport { humanize } from '../../live/naming'\nimport { MenuSelect } from '../../primitives/menu-select'\nimport { Segmented } from '../../primitives/segmented'\nimport { parseSort } from '../list-order'\nimport { displayChoices, sortFields, type DisplayChoice } from './list-displays'\nimport { text } from './messages'\n\n/** The icons a display's `icon` may name; another name shows the label alone. */\nconst icons: Record<string, LucideIcon> = { table: Table2, cards: LayoutGrid, kanban: SquareKanban, board: Columns3, list: List, calendar: Calendar, timeline: ChartGantt, map: MapIcon }\n\n/**\n * The list page's switch between the table and the view's displays, or `choices`, as buttons or, on a phone, as a menu;\n * nothing for a list with only its table.\n */\nexport const DisplaySwitch = ({ view, value, onChange, menu = false, choices = displayChoices(view) }: { view: ViewModel | undefined; value: string; onChange: (display: string) => void; menu?: boolean; choices?: DisplayChoice[] }) => {\n if (choices.length < 2) return null\n const options = choices.map((choice) => ({ value: choice.name, label: choice.label, icon: choice.icon === undefined ? undefined : icons[choice.icon] }))\n if (menu) return <MenuSelect label={text('display')} value={value} onChange={onChange} options={options} />\n return <Segmented label={text('display')} size=\"md\" value={value} onChange={onChange} options={options} />\n}\n\nconst directions = [\n ['asc', 'ascending'],\n ['desc', 'descending'],\n] as const\n\n/** The order of a display without column headers, over the sortable fields it shows and the order the list has now. */\nexport const SortMenu = ({ model, view, display, orderBy, onChange, className }: { model: ResourceModel; view: ViewModel | undefined; display: ListDisplayModel; orderBy: string; onChange: (orderBy: string) => void; className?: string }) => {\n const current = parseSort(orderBy)\n const fields = sortFields(model, view, display)\n const names = fields.includes(current.columnId) ? fields : [current.columnId, ...fields]\n const label = (name: string) => view?.fields[name]?.label ?? humanize(name)\n return (\n <select\n aria-label={text('sort')}\n value={`${current.columnId} ${current.direction}`}\n onChange={(event) => onChange(event.target.value)}\n className={cn('h-8 rounded-md border border-border-strong bg-background px-2.5 shadow-sm focus:border-primary focus:outline-none focus:ring-2 focus:ring-primary/20', className)}\n >\n {names.flatMap((name) =>\n directions.map(([direction, word]) => (\n <option key={`${name} ${direction}`} value={`${name} ${direction}`}>\n {label(name)}, {text(word)}\n </option>\n )),\n )}\n </select>\n )\n}\n","import type { ResourceModel, RowButtonModel, ViewModel } from '@protobase/schema'\nimport type { ColumnSpec, GridRow } from '../../data-grid'\nimport { cellPadding } from '../../data-grid/content-widths'\nimport { displayRow } from '../displays/list-displays'\nimport { RowButtonLink } from './row-button-link'\nimport { rowButtonFor } from './row-button-for'\n\n// Widths are estimated from character counts, as the grid's other columns are: a small button's medium-weight label\n// per character, its padding and border, and the outside-link mark with its gap\nconst labelCharWidth = 8\nconst buttonFrame = 22\nconst outsideMark = 20\n\n/** The widest a row's button grows before its label shortens, on a wide screen and on a narrow one. */\nexport const rowButtonMaxWidth = { wide: 288, narrow: 192 }\n\nconst recordOf = (model: ResourceModel, row: GridRow) => displayRow(model, row).record\n\ntype Models = Record<string, ResourceModel>\n\nconst rowButton = (model: ResourceModel, view: ViewModel | undefined, button: RowButtonModel, models: Models) => (row: GridRow) => (\n <RowButtonLink button={button} model={model} view={view} record={recordOf(model, row)} models={models} />\n)\n\n/** The pixels a row's button cell needs to show its label whole; none for a row without a button. */\nconst rowButtonWidth = (model: ResourceModel, view: ViewModel | undefined, button: RowButtonModel, models: Models) => (row: GridRow) => {\n const shown = rowButtonFor(button, model, view, recordOf(model, row), models)\n if (!shown) return 0\n return Math.ceil(shown.label.length * labelCharWidth) + buttonFrame + ('href' in shown ? outsideMark : 0) + cellPadding\n}\n\n/**\n * A table's last column, with the row's button in each row, as wide as its longest label up to `maxWidth`, past which\n * a label shortens and shows whole on hover; its header is empty, as the buttons say what they do. `models` are the\n * caller's resources, which a filter a row holds whole is checked against.\n */\nexport const rowButtonColumn = (model: ResourceModel, view: ViewModel | undefined, button: RowButtonModel, models: Models, maxWidth: number): ColumnSpec => ({\n id: '_row_button',\n header: '',\n kind: 'text',\n // Until rows load: room for a short label with the outside-link mark, such as \"Error report\"\n width: 152,\n minWidth: 96,\n maxWidth,\n sortable: false,\n render: rowButton(model, view, button, models),\n fit: rowButtonWidth(model, view, button, models),\n})\n\n/**\n * A table's columns with the row's button: its last column, or on a narrow screen, where the table scrolls sideways\n * and a last column starts off-screen, under the first cell's text when there is one.\n */\nexport const withRowButton = (specs: ColumnSpec[], model: ResourceModel, view: ViewModel | undefined, button: RowButtonModel, models: Models, narrow: boolean): ColumnSpec[] => {\n if (!narrow) return [...specs, rowButtonColumn(model, view, button, models, rowButtonMaxWidth.wide)]\n const [first, ...rest] = specs\n // Without a first cell to sit under, the button keeps its own column\n if (!first) return [rowButtonColumn(model, view, button, models, rowButtonMaxWidth.narrow)]\n return [{ ...first, below: rowButton(model, view, button, models) }, ...rest]\n}\n","import type { RelatedModel, ResourceModel } from '@protobase/schema'\n\n// A relation whose records can be opened: one to a resource the caller can see, with a single-column key\nconst opensTo = (model: ResourceModel, name: string, resources: Record<string, ResourceModel>) => {\n const field = Object.hasOwn(model.fields, name) ? model.fields[name]! : undefined\n return field?.type === 'relation' && field.relation !== undefined && resources[field.relation.resource]?.primaryKey.length === 1\n}\n\n/**\n * The relation field whose record a related section's row opens: `item.open`, else the one relation in the listed\n * resource's primary key besides `item.field`, when there is exactly one; none when the rows are records in their own right.\n */\nexport const relatedOpens = (item: RelatedModel, model: ResourceModel, resources: Record<string, ResourceModel>): string | undefined => {\n if (item.open !== undefined) return item.open !== item.field && opensTo(model, item.open, resources) ? item.open : undefined\n const candidates = model.primaryKey.filter((name) => name !== item.field && name !== model.tenant && opensTo(model, name, resources))\n return candidates.length === 1 ? candidates[0] : undefined\n}\n\n/** The key of the record a row's relation `name` points at; a list row holds a shown relation as `{ id, name }`. Undefined when empty. */\nexport const relationTarget = (row: Record<string, unknown>, name: string): string | number | undefined => {\n const value = row[name]\n const id = typeof value === 'object' && value !== null && 'id' in value ? value.id : value\n return typeof id === 'string' || typeof id === 'number' ? id : undefined\n}\n","import type { AppAddress, ResourceModel, ViewModel } from '@protobase/schema'\nimport type { GridRow, RowAction } from '../../data-grid'\nimport { recordKey } from '../../live/model-helpers'\nimport { humanize } from '../../live/naming'\nimport type { RouteTarget } from '../../primitives/route-link'\nimport { rowAllows } from '../permissions'\nimport { relationTarget } from '../related-opens'\nimport { text } from './messages'\n\ntype Targets = {\n model: ResourceModel\n view: ViewModel | undefined\n /** The relation whose record a row opens instead of its own. */\n opens: string | undefined\n resources: Record<string, ResourceModel>\n views: Record<string, ViewModel>\n /** Whether the user may update the rows' own records. */\n canUpdate: boolean\n}\n\nconst singularOf = (model: ResourceModel, view: ViewModel | undefined) => (view?.names?.singular ?? humanize(model.name)).toLowerCase()\n\n/**\n * Where a table row of an embedded list leads, and its menu's items. A row opens its own record, or with `opens` the\n * record that relation points at when it holds one; its menu then opens that record and edits, or for a user who may\n * not, opens the row's own.\n */\nexport const embeddedRowTargets = ({ model, view, opens, resources, views, canUpdate }: Targets) => {\n const own = (row: GridRow): AppAddress => ({ kind: 'record', resource: model.name, key: recordKey(model, row) })\n const farName = opens && model.fields[opens]?.relation?.resource\n const far = farName ? resources[farName] : undefined\n const other = (row: GridRow): AppAddress | undefined => {\n const key = opens && far ? relationTarget(row, opens) : undefined\n return far && key !== undefined ? { kind: 'record', resource: far.name, key } : undefined\n }\n const address = (row: GridRow) => other(row) ?? own(row)\n const singular = singularOf(model, view)\n\n const actions = (linkTo: (to: AppAddress) => RouteTarget): RowAction[] => {\n const openOwn: RowAction = { label: text('open', { singular }), link: (row) => linkTo(own(row)) }\n if (!far) return [openOwn]\n const editable = (row: GridRow) => canUpdate && rowAllows(row, 'update')\n return [\n { label: text('open', { singular: singularOf(far, views[far.name]) }), available: (row) => other(row) !== undefined, link: (row) => linkTo(other(row)!) },\n { label: text('edit', { singular }), available: editable, link: (row) => linkTo({ kind: 'record', resource: model.name, key: recordKey(model, row), edit: true }) },\n { ...openOwn, available: (row) => !editable(row) },\n ]\n }\n return { address, actions }\n}\n","import type { ActionRun, AppAddress } from '@protobase/schema'\nimport { fillAddress } from '@protobase/schema/internal'\nimport type { RouteTarget } from '../../primitives/route-link'\nimport { linkTarget } from './action-href'\n\ntype LinkRun = Extract<ActionRun, { kind: 'link' }>\n\n/** How the app writes and follows an address, as `useAppAddress` gives them. */\ntype Addresses = { href: (to: AppAddress) => string; go: (to: AppAddress) => void }\n\n/**\n * A link action on `record` as a link: an address in the app is followed in place, a page outside it, an `https:` or\n * `http:` one in a new tab, is left to the browser. A link whose `href` has no target on the record is never shown\n * (`actionFor` leaves it out), so asking for it is a mistake.\n */\nexport const actionLink = (run: LinkRun, record: Record<string, unknown> | undefined, { href, go }: Addresses): RouteTarget => {\n if ('to' in run) {\n const to = fillAddress(run.to, record)\n return { href: href(to), onFollow: () => go(to) }\n }\n const target = linkTarget(run.href, record)\n if (target === undefined) throw new Error('A link action without a target on the record is not shown')\n return { href: target, newTab: /^https?:/i.test(target) }\n}\n","import type { RecordPermissions } from '@protobase/client'\nimport type { ResourceModel } from '@protobase/schema'\nimport type { GridRow } from '../../data-grid'\nimport { displayRow } from '../displays/list-displays'\nimport type { LayoutRecord } from '../pages/record-scope'\n\n/**\n * A list's row as the record a named action acts on: its fields as the API gives them, without what the list loads\n * beside them, with its key, ETag and permissions.\n */\nexport const rowRecord = (model: ResourceModel, row: GridRow): LayoutRecord => ({\n model,\n record: Object.fromEntries(Object.entries(displayRow(model, row).record).filter(([name]) => Object.hasOwn(model.fields, name))),\n key: row.id,\n ...(typeof row.etag === 'string' && { etag: row.etag }),\n ...(typeof row.permissions === 'object' && row.permissions !== null && { permissions: row.permissions as RecordPermissions }),\n})\n","import { useState } from 'react'\nimport type { ActionModel, ResourceModel } from '@protobase/schema'\nimport type { BulkAction, GridRow, RowAction } from '../../data-grid'\nimport { actionFor } from '../pages/action-href'\nimport { actionLink } from '../pages/action-link'\nimport { ActionPrompt, isDanger } from '../pages/action-prompt'\nimport type { LayoutRecord } from '../pages/record-scope'\nimport { quoted, useActionRunner } from '../pages/use-run-action'\nimport { useRecordTitle } from '../titles/record-titles'\nimport { useAdminMeta } from '../meta-gate'\nimport { useAppAddress } from '../use-app-address'\nimport { text } from '../list-messages'\nimport { rowRecord } from './row-record'\n\n// What runs once the action's question is answered: the action on one row, or on each of a selection.\ntype Run = { action: ActionModel; row: LayoutRecord } | { action: ActionModel; selection: LayoutRecord[]; skipped: number }\n// A run whose dialog is open, with how to report the records it leaves open once it ends.\ntype Asking = Run & { settle: (open: LayoutRecord[] | Promise<LayoutRecord[]>) => void }\n\n/**\n * The named actions of `model`'s view for its list: those without inputs each in the row menu of the rows it shows for,\n * disabled with its reason where `when` disables it, and in red when it is a delete or a danger action; a link is a link\n * there, and a disabled one a disabled item without one. Updates and handlers marked `bulk` are offered for a selection\n * while one selected row applies, ask their question or inputs once, and run on those that do, refusing and naming\n * those the person may not change, which stay selected. `prompt` is the dialog one opens before it runs.\n */\nexport const useListActions = (model: ResourceModel) => {\n const { views, resources } = useAdminMeta()\n const runner = useActionRunner(model.name, undefined)\n const app = useAppAddress()\n const titleOf = useRecordTitle()\n const [asking, setAsking] = useState<Asking>()\n const named = views[model.name]?.actions ?? []\n const listed = named.filter((action) => !action.inputs?.length)\n // Resolves to the records the run leaves open, those it was refused on\n const perform = async (run: Run, values?: Record<string, unknown>) => {\n if ('row' in run) {\n await runner.run(run.action, run.row)\n return []\n }\n const outcome = await runner.runEach(run.action, run.selection, run.skipped, values)\n return outcome.refused\n }\n // Resolves once the run ended to the records it leaves open: all of them when its dialog is cancelled\n const start = (run: Run) =>\n new Promise<LayoutRecord[]>((settle) => {\n if (run.action.confirm || run.action.inputs?.length) setAsking({ ...run, settle })\n else settle(perform(run))\n })\n\n const rowActions = listed.map((action): RowAction => {\n const shown = (row: GridRow) => actionFor(action, rowRecord(model, row).record, resources)\n const base = { label: (row: GridRow) => shown(row)?.label ?? action.label, destructive: isDanger(action) }\n const run = action.run\n const blocked = (row: GridRow) => runner.blockedOn(action, rowRecord(model, row))\n const available = (row: GridRow) => shown(row) !== undefined\n if (run?.kind === 'link') return { ...base, available, blocked, link: (row) => actionLink(run, rowRecord(model, row).record, app) }\n return { ...base, available, blocked, onSelect: (row) => void start({ action, row: rowRecord(model, row) }) }\n })\n\n const bulkActions = named\n .filter((action) => action.bulk && action.run?.kind !== 'link')\n .map((action): BulkAction => ({\n label: (count) => text('actionCount', { label: action.label, count }),\n destructive: isDanger(action),\n available: (row) => runner.verdictOn(action, rowRecord(model, row)) !== 'skip',\n onRun: async (rows, skipped) => {\n const selection = rows.map((row) => rowRecord(model, row))\n const open = await start({ action, selection, skipped })\n return rows.filter((_, index) => open.includes(selection[index]!))\n },\n }))\n\n const prompt = asking && (\n <ActionPrompt\n action={asking.action}\n label={'row' in asking ? asking.action.label : text('actionCount', { label: asking.action.label, count: asking.selection.length })}\n danger={isDanger(asking.action)}\n records={'row' in asking ? [asking.row.record] : asking.selection.map((on) => on.record)}\n names={'row' in asking ? [] : asking.selection.map((on) => quoted(titleOf(model, views[model.name], on.record, on.key)))}\n onCancel={() => {\n setAsking(undefined)\n asking.settle('row' in asking ? [asking.row] : asking.selection)\n }}\n onConfirm={() => {\n setAsking(undefined)\n asking.settle(perform(asking))\n }}\n onSubmit={async (values) => {\n setAsking(undefined)\n const running = perform(asking, values)\n asking.settle(running)\n await running\n }}\n />\n )\n return { rowActions, bulkActions, prompt }\n}\n","import { keepPreviousData, useQuery, useQueryClient, type QueryClient } from '@tanstack/react-query'\nimport type { Client } from '@protobase/client'\nimport type { ResourceModel, ViewModel } from '@protobase/schema'\nimport { useClient } from '../../data/api-provider'\nimport { keys } from '../../data/query-keys'\nimport type { GridRow } from '../../data-grid'\nimport { recordId } from '../../live/model-helpers'\nimport { listLabels, withLabels } from '../../live/relation-labels'\nimport { listPhotos, withPhotos } from '../../live/row-photos'\nimport { seedTitleRows } from '../../live/title-rows'\nimport { useAdminMeta } from '../meta-gate'\n\nexport type EmbeddedRowsRequest = {\n model: ResourceModel\n filter: string\n orderBy: string\n limit: number\n /** The fields its relations are labelled and its relations' titles read for. */\n fields: string[]\n /** The fields each record is read with, from `embeddedReadFields`; `undefined` reads whole records. */\n read: string[] | undefined\n}\n\n/** What `embeddedRowsQuery` reads with beside the request: the API, the query cache its titles are seeded into, and the app's models. */\ntype Reader = { client: Client; queryClient: QueryClient; resources: Record<string, ResourceModel>; views: Record<string, ViewModel> }\n\n/**\n * The first `limit` records in `orderBy` order, with the fields `read` names, as the list page's table and displays get them: relations among\n * `fields` as `{ id, name }`, named in the same call, with the photos of its cards, and how many records match in all,\n * counted in the same call: `estimated` when more than the server counts exactly match; the fields the derived titles\n * of the records its relations point at read, in one more call per resource. A filter through a join\n * resource may hold hundreds of keys, so it goes in a JSON body.\n */\nexport const embeddedRowsQuery = ({ client, queryClient, resources, views }: Reader, { model, filter, orderBy, limit, fields, read }: EmbeddedRowsRequest) => ({\n queryKey: [...keys.list(model.name, filter, orderBy, limit, 'embedded'), fields.join(','), read?.join(',') ?? '*'],\n queryFn: async (): Promise<{ rows: GridRow[]; total: number; estimated: boolean }> => {\n const labels = listLabels(resources, views, model, fields)\n const photos = listPhotos(views[model.name])\n const page = await client.search(model.name, { filter: filter || undefined, orderBy: orderBy || undefined, pageSize: limit, count: 'exact', labels, photos, fields: read })\n await seedTitleRows(queryClient, client, resources, views, model, fields, page.items)\n const labelled = withLabels(resources, model, fields, withPhotos(model, page.items, page.photos), page.labels)\n const rows = labelled.map((row, index) => ({ ...row, id: recordId(model, page.items[index]!) }))\n // The last page holds them all\n if (page.nextPageToken === '') return { rows, total: rows.length, estimated: false }\n return { rows, total: page.totalSize ?? page.totalSizeEstimate, estimated: page.totalSize === undefined }\n },\n})\n\n/** The rows of `embeddedRowsQuery`, the page before staying while the next loads; nothing is read while not `enabled`. */\nexport const useEmbeddedRows = (request: EmbeddedRowsRequest, enabled = true) => {\n const { resources, views } = useAdminMeta()\n return useQuery({ ...embeddedRowsQuery({ client: useClient(), queryClient: useQueryClient(), resources, views }, request), placeholderData: keepPreviousData, enabled })\n}\n","import type { ResourceModel } from '@protobase/schema'\nimport type { GridRow } from '../../data-grid'\nimport { recordId } from '../../live/model-helpers'\nimport { withLabels } from '../../live/relation-labels'\nimport { withPhotos } from '../../live/row-photos'\nimport type { Planned } from '../pages/planned'\nimport { plannedCount } from '../pages/planned-count'\n\n/** A list's first page from the page's planned read, and how many records match in all, from its total read. */\nexport type PlannedList = { rows: Planned; total: Planned | undefined }\n\n/**\n * The rows of `planned` as `useEmbeddedRows` gives its own: relations among `fields` named, photos beside them, and\n * the total its total read counts, its rows' count without one.\n */\nexport const plannedEmbeddedRows = (resources: Record<string, ResourceModel>, model: ResourceModel, fields: string[], { rows, total }: PlannedList) => {\n const isPending = rows.isPending || Boolean(total?.isPending)\n const error = rows.error ?? total?.error ?? null\n if (isPending || error) return { isPending, error, data: undefined }\n const labelled = withLabels(resources, model, fields, withPhotos(model, rows.rows, rows.photos), rows.labels)\n const listed: GridRow[] = labelled.map((row, index) => ({ ...row, id: recordId(model, rows.rows[index]!) }))\n return { isPending, error, data: { rows: listed, total: total ? plannedCount(total) : listed.length, estimated: false } }\n}\n","import { ArrowRight } from 'lucide-react'\nimport { useMemo, useState, type ReactNode } from 'react'\nimport type { AppAddress, ResourceModel, RowButtonModel, ViewModel } from '@protobase/schema'\nimport { encodeKey } from '@protobase/schema/internal'\nimport { DataGrid, type ColumnSpec, type GridRow } from '../../data-grid'\nimport { useIsDesktop, useIsXs } from '../../lib/use-media-query'\nimport { recordKey } from '../../live/model-helpers'\nimport { humanize } from '../../live/naming'\nimport type { RouteTarget } from '../../primitives/route-link'\nimport { Skeleton } from '../../primitives/skeleton'\nimport { CardsDisplay } from '../displays/cards-display'\nimport { CustomDisplay } from '../displays/custom-display'\nimport { MapDisplay } from '../displays/map-display'\nimport { BoardDisplay, CalendarDisplay, TimelineDisplay } from '../displays/lazy-displays'\nimport { DisplaySwitch } from '../displays/display-controls'\nimport type { ListDisplay } from '../displays/display-context'\nimport { displayRow, shownDisplay } from '../displays/list-displays'\nimport { ErrorBanner } from '../error-banner'\nimport { useProjectUi } from '../pages/project-ui'\nimport { defaultOrderBy, parseSort, sortToOrderBy } from '../list-order'\nimport { useAdminMeta, usePermissions } from '../meta-gate'\nimport { can } from '../permissions'\nimport { withRowButton } from '../row-button/row-button-column'\nimport { AppLink, useAppAddress } from '../use-app-address'\nimport { viewAllAddress } from './embedded-display'\nimport { cutOffNote } from './cut-off-note'\nimport { embeddedFields } from './embedded-fields'\nimport { embeddedRowTargets } from './embedded-row-targets'\nimport { useListActions } from '../list-actions/use-list-actions'\nimport { useEmbeddedRows } from './use-embedded-rows'\nimport { plannedEmbeddedRows, type PlannedList } from './planned-embedded-rows'\nimport { text } from './messages'\n\nexport type EmbeddedListProps = {\n model: ResourceModel\n view: ViewModel | undefined\n filter: string\n /** The order to start in, the list's own when empty; the table's headers change it. */\n sort: string\n /** The table's columns, through relations too (`unit_id.property_id`); the list's columns by default. */\n columns?: string[]\n limit: number\n /** The display shown, from `useEmbeddedDisplay`. */\n display: string\n empty?: string\n /** The cards in one row that scrolls sideways on every screen, not only on a phone. */\n row?: boolean\n /**\n * Where \"View all\" leads instead of the same list: the list with this filter, opened from the saved search\n * `savedSearch`, under this label, calling `onOpen` first.\n */\n viewAll?: { filter: string; label: string; savedSearch?: string; onOpen?: () => void }\n /** Whether it ends with the link to the whole list. */\n link?: boolean\n /** The relation whose record a table row opens instead of its own, for rows that link this record to another; the row's menu then also opens or edits the row's own record. */\n opens?: string\n /** A button on each row of the table, as its last column or on a narrow screen under the first cell, to an address the row's fields name. */\n button?: RowButtonModel\n /** The table's rows can be selected, and the view's `bulk` actions run on the selected rows. */\n bulk?: boolean\n /** Picks the table's columns a phone shows; every column when omitted. */\n phoneColumns?: (specs: ColumnSpec[]) => ColumnSpec[]\n /** Where a table row leads instead of its record, by the row's key as text, such as the page with that row chosen; its menu still opens the record. */\n rowTo?: (key: string) => RouteTarget\n /** The key, as text, of the row the page shows the details of, which the table marks as chosen. */\n chosenKey?: string\n /** Its rows and total from the page's planned reads, drawn until a header sorts it another way, which it reads itself. */\n planned?: PlannedList\n}\n\n/** The switch between the table and the view's displays, for an embedded list's heading; nothing with only a table. */\nexport const EmbeddedDisplaySwitch = ({ view, value, onChange }: { view: ViewModel | undefined; value: string; onChange: (display: string) => void }) => (\n <DisplaySwitch view={view} value={value} onChange={onChange} menu={!useIsDesktop()} />\n)\n\nconst Loading = () => <div className=\"flex flex-col gap-2\">{Array.from({ length: 3 }, (_, index) => <Skeleton key={index} className=\"h-4 w-full\" />)}</div>\n\n/**\n * The first `limit` records of a list, drawn by the list page's own table (sized to its rows) or display, and a link\n * to the whole list with the same filter, order and display, beside a note such as \"The first 10 of 37.\" when there are\n * more. On a phone a cards display is one row that scrolls sideways.\n */\nexport const EmbeddedList = ({ model, view, filter, sort, columns, limit, display, empty, row = false, viewAll, link = true, opens, button, bulk = false, phoneColumns, rowTo, chosenKey, planned }: EmbeddedListProps) => {\n const { resources, views } = useAdminMeta()\n const canUpdate = can(usePermissions(model.name), 'update')\n const { fields: fieldTypes } = useProjectUi()\n const { go, href } = useAppAddress()\n const xs = useIsXs()\n const narrow = !useIsDesktop()\n const initialOrder = sort || defaultOrderBy(model, view)\n const [orderBy, setOrderBy] = useState(initialOrder)\n const { specs, fields, read } = useMemo(\n () => embeddedFields({ model, view, resources, views, fieldTypes, columns, button, opens, bulk, phoneColumns, xs }),\n [model, view, resources, views, fieldTypes, columns?.join(','), button, opens, bulk, phoneColumns, xs],\n )\n const gridColumns = useMemo(() => (button ? withRowButton(specs, model, view, button, resources, narrow) : specs), [specs, model, view, button, resources, narrow])\n const fromPlan = planned !== undefined && orderBy === initialOrder\n const own = useEmbeddedRows({ model, filter, orderBy, limit, fields, read }, !fromPlan)\n const plannedRows = useMemo(() => planned && plannedEmbeddedRows(resources, model, fields, planned), [planned, resources, model, fields])\n const rows = fromPlan ? plannedRows! : own\n const named = useListActions(model)\n const loaded = rows.data?.rows\n const source = useMemo(() => loaded && { total: loaded.length, rowAt: (index: number) => loaded[index]! }, [loaded])\n const shown = shownDisplay(view, display)\n\n const plural = view?.names?.plural ?? humanize(model.name)\n const allLink = link && (\n <AppLink\n to={viewAllAddress(model, view, xs, viewAll ? { filter: viewAll.filter, orderBy: defaultOrderBy(model, view), display, savedSearch: viewAll.savedSearch } : { filter, orderBy, display })}\n onClick={viewAll?.onOpen}\n className=\"flex items-center gap-1 self-end font-medium text-primary-text hover:underline\"\n >\n {viewAll ? viewAll.label : <>{text('viewAll')} <span className=\"sr-only\">{plural.toLowerCase()}</span></>}\n <ArrowRight className=\"size-3.5\" aria-hidden />\n </AppLink>\n )\n\n // The open dialog stays while a refetch loads, fails or leaves no rows, so cancelling it still clears it\n const withPrompt = (body: ReactNode) => <>{body}{named.prompt}</>\n if (rows.isPending) return withPrompt(<Loading />)\n if (rows.error) return withPrompt(<ErrorBanner title={text('couldNotLoad')} error={rows.error} />)\n // A link of its own still leads somewhere when nothing here matches\n const data = rows.data\n if (!data || !source || source.total === 0) {\n const nothing = <p className=\"text-muted-foreground\">{empty ?? text('nothingYet')}</p>\n return withPrompt(viewAll && link ? <div className=\"flex flex-col gap-3\">{nothing}{allLink}</div> : nothing)\n }\n\n const list: ListDisplay = {\n resource: model.name,\n rows: data.rows.map((row) => displayRow(model, row)),\n total: data.total,\n loading: false,\n error: null,\n more: false,\n loadMore: () => undefined,\n }\n const targets = embeddedRowTargets({ model, view, opens, resources, views, canUpdate })\n const linkTo = (to: AppAddress): RouteTarget => ({ href: href(to), onFollow: () => go(to) })\n const keyOf = (row: GridRow) => encodeKey(recordKey(model, row))\n const rowTarget = (row: GridRow) => (rowTo ? rowTo(keyOf(row)) : linkTo(targets.address(row)))\n const chosenRow = chosenKey === undefined ? undefined : data.rows.find((row) => keyOf(row) === chosenKey)?.id\n const note = cutOffNote(source.total, data.total, data.estimated)\n return (\n <div className=\"flex flex-col gap-3\">\n {!shown ? (\n <DataGrid\n fit\n columns={gridColumns}\n source={source}\n latencyMs={0}\n sort={parseSort(orderBy)}\n onSortChange={(next) => setOrderBy(sortToOrderBy(next))}\n onOpenRow={(row) => rowTarget(row).onFollow?.()}\n rowLink={rowTarget}\n chosenRow={chosenRow}\n rowActions={targets.actions(linkTo)}\n rowNumbers={false}\n selectable={bulk}\n {...(bulk && { bulkActions: named.bulkActions })}\n />\n ) : shown.kind === 'cards' ? (\n <CardsDisplay model={model} view={view} display={shown} list={list} row={row || xs} footer={false} />\n ) : shown.kind === 'map' ? (\n <MapDisplay model={model} view={view} display={shown} filter={filter} orderBy={orderBy} fields={fields} footer={false} />\n ) : shown.kind === 'board' ? (\n <BoardDisplay model={model} view={view} display={shown} fields={fields} filter={filter} orderBy={orderBy} limit={limit} />\n ) : shown.kind === 'calendar' ? (\n <CalendarDisplay model={model} view={view} display={shown} fields={fields} filter={filter} />\n ) : shown.kind === 'timeline' ? (\n <TimelineDisplay model={model} view={view} display={shown} fields={fields} filter={filter} />\n ) : (\n <CustomDisplay display={shown} list={list} />\n )}\n {named.prompt}\n {note && link ? (\n <div className=\"flex flex-wrap items-center justify-between gap-2\">\n <p className=\"text-xs text-muted-foreground\">{note}</p>\n {allLink}\n </div>\n ) : (\n allLink\n )}\n </div>\n )\n}\n"],"file":"embedded-list-BBrpHnq2.js","debugId":"41ae91e7-ab63-4a0c-a822-d259ff44ba9c"}