@protobase/ui 0.117.5 → 0.117.6

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 (196) hide show
  1. package/dist/account/messages.d.ts +2 -2
  2. package/dist/app/charts/messages.d.ts +2 -2
  3. package/dist/app/comments/messages.d.ts +2 -2
  4. package/dist/app/confirm-sign-in-messages.d.ts +2 -2
  5. package/dist/app/conversation/thread-state.d.ts +1 -1
  6. package/dist/app/create/messages.d.ts +2 -2
  7. package/dist/app/delete/messages.d.ts +2 -2
  8. package/dist/app/displays/messages.d.ts +2 -2
  9. package/dist/app/export/messages.d.ts +2 -2
  10. package/dist/app/field-types/custom-step-container/messages.d.ts +2 -2
  11. package/dist/app/field-types/json/messages.d.ts +2 -2
  12. package/dist/app/field-types/runner-install/messages.d.ts +2 -2
  13. package/dist/app/field-types/workflow/messages.d.ts +2 -2
  14. package/dist/app/field-types/workflow-page/messages.d.ts +2 -2
  15. package/dist/app/field-types/workflow-run/messages.d.ts +2 -2
  16. package/dist/app/field-types/workflow-status/messages.d.ts +2 -2
  17. package/dist/app/file-viewers/messages.d.ts +2 -2
  18. package/dist/app/focus/messages.d.ts +2 -2
  19. package/dist/app/gallery/messages.d.ts +2 -2
  20. package/dist/app/hand-order/messages.d.ts +2 -2
  21. package/dist/app/import/messages.d.ts +2 -2
  22. package/dist/app/list-messages.d.ts +2 -2
  23. package/dist/app/messages.d.ts +2 -2
  24. package/dist/app/meta-gate-messages.d.ts +2 -2
  25. package/dist/app/new-version/messages.d.ts +2 -2
  26. package/dist/app/pages/messages.d.ts +2 -2
  27. package/dist/app/record-chart/messages.d.ts +2 -2
  28. package/dist/app/record-messages.d.ts +2 -2
  29. package/dist/app/record-row/messages.d.ts +2 -2
  30. package/dist/app/related-cards/messages.d.ts +2 -2
  31. package/dist/app/runtime/messages.d.ts +2 -2
  32. package/dist/app/saved/messages.d.ts +2 -2
  33. package/dist/app/saved/use-favorite.d.ts +1 -1
  34. package/dist/app/searches/messages.d.ts +2 -2
  35. package/dist/app/searches/use-save-search.d.ts +1 -1
  36. package/dist/app-shell/messages.d.ts +2 -2
  37. package/dist/assistant-dock/messages.d.ts +2 -2
  38. package/dist/auth/messages.d.ts +2 -2
  39. package/dist/calls/messages.d.ts +2 -2
  40. package/dist/data-grid/messages.d.ts +2 -2
  41. package/dist/filter-panel/messages.d.ts +2 -2
  42. package/dist/format/messages.d.ts +2 -2
  43. package/dist/forms/messages.d.ts +2 -2
  44. package/dist/invitations/messages.d.ts +2 -2
  45. package/dist/mailbox/messages.d.ts +2 -2
  46. package/dist/mocks/invoices.d.ts +1 -1
  47. package/dist/mocks/orders.d.ts +1 -1
  48. package/dist/mocks/stockMoves.d.ts +1 -1
  49. package/dist/notifications/bell/messages.d.ts +2 -2
  50. package/dist/organizations/messages.d.ts +2 -2
  51. package/dist/package.js +1 -1
  52. package/dist/plugins/messages.d.ts +2 -2
  53. package/dist/primitives/messages.d.ts +2 -2
  54. package/dist/record-view/messages.d.ts +2 -2
  55. package/dist/shell/assets/{account-page-BPtyska2.js → account-page-Bqb6zGSu.js} +2 -2
  56. package/dist/shell/assets/{app-DKn-6fgf.js → app-DzYUvsKN.js} +5 -5
  57. package/dist/shell/assets/{assistant-shell-BW59by36.js → assistant-shell-DOwiIEWE.js} +2 -2
  58. package/dist/shell/assets/{board-display-uC4sMccF.js → board-display-BmqzVMBI.js} +2 -2
  59. package/dist/shell/assets/{calendar-display-BZhTapxV.js → calendar-display-CigAD33q.js} +2 -2
  60. package/dist/shell/assets/{call-rings-DwyQO_zl.js → call-rings-CTIiSB__.js} +2 -2
  61. package/dist/shell/assets/{calls-DeHPxZSF.js → calls-D7-msX2f.js} +2 -2
  62. package/dist/shell/assets/{circle-alert-mtPRl_1e.js → circle-alert-BBrhHhh-.js} +2 -2
  63. package/dist/shell/assets/{composed-page-CqjAO9Zv.js → composed-page-CnajGi9M.js} +2 -2
  64. package/dist/shell/assets/{composer-section-D16PrwJe.js → composer-section-CEiUZctQ.js} +2 -2
  65. package/dist/shell/assets/{connect-route-BHjM-n0c.js → connect-route-B1pwUNo5.js} +2 -2
  66. package/dist/shell/assets/{copy-field-C7SgGBWe.js → copy-field-DSicODbK.js} +2 -2
  67. package/dist/shell/assets/{create-route-CV6sScUu.js → create-route-IrF4K8-E.js} +2 -2
  68. package/dist/shell/assets/{custom-step-container-field-DbXZzPJp.js → custom-step-container-field-DGBCh3aW.js} +2 -2
  69. package/dist/shell/assets/{embedded-list-CG1SyUtd.js → embedded-list-y9Zllidc.js} +3 -3
  70. package/dist/shell/assets/{export-dialog-CMPyzZa3.js → export-dialog-C7aFNN_I.js} +2 -2
  71. package/dist/shell/assets/{graph-view-CfO5HJXO.js → graph-view-DIEwXkMm.js} +2 -2
  72. package/dist/shell/assets/{group-donut-UrNllcKD.js → group-donut-No1GKRrh.js} +2 -2
  73. package/dist/shell/assets/{guest-call-page-CgISSPNH.js → guest-call-page-C0GElAN6.js} +3 -3
  74. package/dist/shell/assets/{html-viewer-GgauWEUE.js → html-viewer-C3HC5LlC.js} +2 -2
  75. package/dist/shell/assets/{import-dialog-BppJUUoF.js → import-dialog-e6K5QITR.js} +2 -2
  76. package/dist/shell/assets/{import-table-dialog-cfWZMJfg.js → import-table-dialog-BGu9aIO6.js} +2 -2
  77. package/dist/shell/assets/{index-C6CE4Yqt.js → index-B_wfA6Kh.js} +1 -1
  78. package/dist/shell/assets/{invitations-page-Cx960zfb.js → invitations-page-Dc_YyiPd.js} +2 -2
  79. package/dist/shell/assets/{layout-grid-IdJUsNk6.js → layout-grid-hthVLoXp.js} +2 -2
  80. package/dist/shell/assets/{legend-item-FRGENXpR.js → legend-item-D545faKl.js} +2 -2
  81. package/dist/shell/assets/{list-page-Di8ApAmU.js → list-page-LW7JjE8M.js} +4 -4
  82. package/dist/shell/assets/{maplibre-B0oPa_5e.js → maplibre-BlAV3xhB.js} +2 -2
  83. package/dist/shell/assets/{markdown-content-CA74ofB3.js → markdown-content-D5FzgqvR.js} +2 -2
  84. package/dist/shell/assets/{members-page-UO-o4WSG.js → members-page-BacI69K5.js} +2 -2
  85. package/dist/shell/assets/{messages-CjRWJI05.js → messages-xzaxaGR2.js} +2 -2
  86. package/dist/shell/assets/{organization-page-DaGSJbur.js → organization-page-DdeKAkoY.js} +2 -2
  87. package/dist/shell/assets/{organizations-page-C5oK_zsd.js → organizations-page-CIm5yo6I.js} +2 -2
  88. package/dist/shell/assets/{pending-invitation-row-BEvgmW-N.js → pending-invitation-row-kfzdAW1e.js} +2 -2
  89. package/dist/shell/assets/{period-chart-CW2NUL07.js → period-chart-CaH4lnzr.js} +2 -2
  90. package/dist/shell/assets/{person-row-5VQjyq5t.js → person-row-CR5zNgI0.js} +2 -2
  91. package/dist/shell/assets/{public-form-page-CqU7Cg33.js → public-form-page-DMT_-q3R.js} +2 -2
  92. package/dist/shell/assets/{record-lines-CJgNIVFS.js → record-lines-BbEMwyZz.js} +2 -2
  93. package/dist/shell/assets/{record-map-DHkY7hYE.js → record-map-Bgjc6l6v.js} +2 -2
  94. package/dist/shell/assets/{record-opens-B0MlYjrH.js → record-opens-BDYrsPg7.js} +2 -2
  95. package/dist/shell/assets/{record-page-whDNzf71.js → record-page-CTlLVFMY.js} +3 -3
  96. package/dist/shell/assets/{record-preview-BUnzkT7g.js → record-preview-D69nznsk.js} +2 -2
  97. package/dist/shell/assets/{records-map-DjcDdJBM.js → records-map-Cjs4-0-T.js} +2 -2
  98. package/dist/shell/assets/{render-node-DGmdm-wr.js → render-node-p5OrHoJa.js} +3 -3
  99. package/dist/shell/assets/{reorder-button-q4oqy3UR.js → reorder-button-D6e3M-BK.js} +2 -2
  100. package/dist/shell/assets/{run-trace-view-DjtMSojN.js → run-trace-view-CZkpU6FK.js} +2 -2
  101. package/dist/shell/assets/{runner-install-field-Ddxc9XB0.js → runner-install-field-Bg2frYus.js} +2 -2
  102. package/dist/shell/assets/{runtime-update-CKEA5P-k.js → runtime-update-bb8Mych_.js} +2 -2
  103. package/dist/shell/assets/{shared-protobase-ui-tTqz9hwW.js → shared-protobase-ui-CDq17YBF.js} +1 -1
  104. package/dist/shell/assets/{sheet-source-CAIVzfnw.js → sheet-source-Cn2x0B7b.js} +2 -2
  105. package/dist/shell/assets/{sign-in-policy-page-CdTIudi-.js → sign-in-policy-page-B5opy3S1.js} +2 -2
  106. package/dist/shell/assets/{start-block-queries-DjQjQ2Ef.js → start-block-queries-DoDAw6-T.js} +2 -2
  107. package/dist/shell/assets/{step-catalog-Dit0IJvs.js → step-catalog-CtopLqDZ.js} +2 -2
  108. package/dist/shell/assets/{step-panel-9kx6xfm1.js → step-panel-BPHKL3JP.js} +2 -2
  109. package/dist/shell/assets/{timeline-display-CoQETrmW.js → timeline-display-Df0FwDTq.js} +2 -2
  110. package/dist/shell/assets/{trash-DJwJPifF.js → trash-DvIkRk0v.js} +2 -2
  111. package/dist/shell/assets/{update-set-DPSGWrcI.js → update-set-C6scM9Py.js} +2 -2
  112. package/dist/shell/assets/{use-calendar-move-CgXeokRh.js → use-calendar-move-DcZxW6eO.js} +2 -2
  113. package/dist/shell/assets/{use-display-rows-DFSNvNWx.js → use-display-rows-9Pz57Zus.js} +2 -2
  114. package/dist/shell/assets/{use-paged-search-B52iaj1D.js → use-paged-search-CHxoPbgl.js} +2 -2
  115. package/dist/shell/assets/{use-run-trace-KAufJAqD.js → use-run-trace-DdUrSC__.js} +2 -2
  116. package/dist/shell/assets/{use-workflow-page-171SXJ7G.js → use-workflow-page-BqleruNg.js} +2 -2
  117. package/dist/shell/assets/{use-workflow-types-ZGEaDrEJ.js → use-workflow-types-DUEWsZgC.js} +2 -2
  118. package/dist/shell/assets/{workflow-canvas-CCu4twlF.js → workflow-canvas-cQ7U4Mgc.js} +2 -2
  119. package/dist/shell/assets/{workflow-field-BFNHwCjK.js → workflow-field-c0IiPQaY.js} +3 -3
  120. package/dist/shell/assets/{workflow-graph-editor-DTSyabCd.js → workflow-graph-editor-BAwGZFkg.js} +2 -2
  121. package/dist/shell/assets/{workflow-run-field-D2fpm1Vk.js → workflow-run-field-Y49d5OnF.js} +3 -3
  122. package/dist/shell/assets/{workflow-status-field-D_4-8JIF.js → workflow-status-field-fYllRt7c.js} +2 -2
  123. package/dist/shell/assets/{workflow-workbench-CN5-OYpd.js → workflow-workbench-Bvx_2IBB.js} +2 -2
  124. package/dist/shell/index.html +3 -3
  125. package/dist/shell/protobase.shell.json +3 -3
  126. package/dist/shell/protobase.sw.js +2 -2
  127. package/dist/shell-source-maps/assets/{account-page-BPtyska2.js.map → account-page-Bqb6zGSu.js.map} +1 -1
  128. package/dist/shell-source-maps/assets/{app-DKn-6fgf.js.map → app-DzYUvsKN.js.map} +1 -1
  129. package/dist/shell-source-maps/assets/{assistant-shell-BW59by36.js.map → assistant-shell-DOwiIEWE.js.map} +1 -1
  130. package/dist/shell-source-maps/assets/{board-display-uC4sMccF.js.map → board-display-BmqzVMBI.js.map} +1 -1
  131. package/dist/shell-source-maps/assets/{calendar-display-BZhTapxV.js.map → calendar-display-CigAD33q.js.map} +1 -1
  132. package/dist/shell-source-maps/assets/{call-rings-DwyQO_zl.js.map → call-rings-CTIiSB__.js.map} +1 -1
  133. package/dist/shell-source-maps/assets/{calls-DeHPxZSF.js.map → calls-D7-msX2f.js.map} +1 -1
  134. package/dist/shell-source-maps/assets/{circle-alert-mtPRl_1e.js.map → circle-alert-BBrhHhh-.js.map} +1 -1
  135. package/dist/shell-source-maps/assets/{composed-page-CqjAO9Zv.js.map → composed-page-CnajGi9M.js.map} +1 -1
  136. package/dist/shell-source-maps/assets/{composer-section-D16PrwJe.js.map → composer-section-CEiUZctQ.js.map} +1 -1
  137. package/dist/shell-source-maps/assets/{connect-route-BHjM-n0c.js.map → connect-route-B1pwUNo5.js.map} +1 -1
  138. package/dist/shell-source-maps/assets/{copy-field-C7SgGBWe.js.map → copy-field-DSicODbK.js.map} +1 -1
  139. package/dist/shell-source-maps/assets/{create-route-CV6sScUu.js.map → create-route-IrF4K8-E.js.map} +1 -1
  140. package/dist/shell-source-maps/assets/{custom-step-container-field-DbXZzPJp.js.map → custom-step-container-field-DGBCh3aW.js.map} +1 -1
  141. package/dist/shell-source-maps/assets/{embedded-list-CG1SyUtd.js.map → embedded-list-y9Zllidc.js.map} +1 -1
  142. package/dist/shell-source-maps/assets/{export-dialog-CMPyzZa3.js.map → export-dialog-C7aFNN_I.js.map} +1 -1
  143. package/dist/shell-source-maps/assets/{graph-view-CfO5HJXO.js.map → graph-view-DIEwXkMm.js.map} +1 -1
  144. package/dist/shell-source-maps/assets/{group-donut-UrNllcKD.js.map → group-donut-No1GKRrh.js.map} +1 -1
  145. package/dist/shell-source-maps/assets/{guest-call-page-CgISSPNH.js.map → guest-call-page-C0GElAN6.js.map} +1 -1
  146. package/dist/shell-source-maps/assets/{html-viewer-GgauWEUE.js.map → html-viewer-C3HC5LlC.js.map} +1 -1
  147. package/dist/shell-source-maps/assets/{import-dialog-BppJUUoF.js.map → import-dialog-e6K5QITR.js.map} +1 -1
  148. package/dist/shell-source-maps/assets/{import-table-dialog-cfWZMJfg.js.map → import-table-dialog-BGu9aIO6.js.map} +1 -1
  149. package/dist/shell-source-maps/assets/{invitations-page-Cx960zfb.js.map → invitations-page-Dc_YyiPd.js.map} +1 -1
  150. package/dist/shell-source-maps/assets/{layout-grid-IdJUsNk6.js.map → layout-grid-hthVLoXp.js.map} +1 -1
  151. package/dist/shell-source-maps/assets/{legend-item-FRGENXpR.js.map → legend-item-D545faKl.js.map} +1 -1
  152. package/dist/shell-source-maps/assets/{list-page-Di8ApAmU.js.map → list-page-LW7JjE8M.js.map} +1 -1
  153. package/dist/shell-source-maps/assets/{maplibre-B0oPa_5e.js.map → maplibre-BlAV3xhB.js.map} +1 -1
  154. package/dist/shell-source-maps/assets/{markdown-content-CA74ofB3.js.map → markdown-content-D5FzgqvR.js.map} +1 -1
  155. package/dist/shell-source-maps/assets/{members-page-UO-o4WSG.js.map → members-page-BacI69K5.js.map} +1 -1
  156. package/dist/shell-source-maps/assets/{messages-CjRWJI05.js.map → messages-xzaxaGR2.js.map} +1 -1
  157. package/dist/shell-source-maps/assets/{organization-page-DaGSJbur.js.map → organization-page-DdeKAkoY.js.map} +1 -1
  158. package/dist/shell-source-maps/assets/{organizations-page-C5oK_zsd.js.map → organizations-page-CIm5yo6I.js.map} +1 -1
  159. package/dist/shell-source-maps/assets/{pending-invitation-row-BEvgmW-N.js.map → pending-invitation-row-kfzdAW1e.js.map} +1 -1
  160. package/dist/shell-source-maps/assets/{period-chart-CW2NUL07.js.map → period-chart-CaH4lnzr.js.map} +1 -1
  161. package/dist/shell-source-maps/assets/{person-row-5VQjyq5t.js.map → person-row-CR5zNgI0.js.map} +1 -1
  162. package/dist/shell-source-maps/assets/{public-form-page-CqU7Cg33.js.map → public-form-page-DMT_-q3R.js.map} +1 -1
  163. package/dist/shell-source-maps/assets/{record-lines-CJgNIVFS.js.map → record-lines-BbEMwyZz.js.map} +1 -1
  164. package/dist/shell-source-maps/assets/{record-map-DHkY7hYE.js.map → record-map-Bgjc6l6v.js.map} +1 -1
  165. package/dist/shell-source-maps/assets/{record-opens-B0MlYjrH.js.map → record-opens-BDYrsPg7.js.map} +1 -1
  166. package/dist/shell-source-maps/assets/{record-page-whDNzf71.js.map → record-page-CTlLVFMY.js.map} +1 -1
  167. package/dist/shell-source-maps/assets/{record-preview-BUnzkT7g.js.map → record-preview-D69nznsk.js.map} +1 -1
  168. package/dist/shell-source-maps/assets/{records-map-DjcDdJBM.js.map → records-map-Cjs4-0-T.js.map} +1 -1
  169. package/dist/shell-source-maps/assets/{render-node-DGmdm-wr.js.map → render-node-p5OrHoJa.js.map} +1 -1
  170. package/dist/shell-source-maps/assets/{reorder-button-q4oqy3UR.js.map → reorder-button-D6e3M-BK.js.map} +1 -1
  171. package/dist/shell-source-maps/assets/{run-trace-view-DjtMSojN.js.map → run-trace-view-CZkpU6FK.js.map} +1 -1
  172. package/dist/shell-source-maps/assets/{runner-install-field-Ddxc9XB0.js.map → runner-install-field-Bg2frYus.js.map} +1 -1
  173. package/dist/shell-source-maps/assets/{runtime-update-CKEA5P-k.js.map → runtime-update-bb8Mych_.js.map} +1 -1
  174. package/dist/shell-source-maps/assets/{sheet-source-CAIVzfnw.js.map → sheet-source-Cn2x0B7b.js.map} +1 -1
  175. package/dist/shell-source-maps/assets/{sign-in-policy-page-CdTIudi-.js.map → sign-in-policy-page-B5opy3S1.js.map} +1 -1
  176. package/dist/shell-source-maps/assets/{start-block-queries-DjQjQ2Ef.js.map → start-block-queries-DoDAw6-T.js.map} +1 -1
  177. package/dist/shell-source-maps/assets/{step-catalog-Dit0IJvs.js.map → step-catalog-CtopLqDZ.js.map} +1 -1
  178. package/dist/shell-source-maps/assets/{step-panel-9kx6xfm1.js.map → step-panel-BPHKL3JP.js.map} +1 -1
  179. package/dist/shell-source-maps/assets/{timeline-display-CoQETrmW.js.map → timeline-display-Df0FwDTq.js.map} +1 -1
  180. package/dist/shell-source-maps/assets/{trash-DJwJPifF.js.map → trash-DvIkRk0v.js.map} +1 -1
  181. package/dist/shell-source-maps/assets/{update-set-DPSGWrcI.js.map → update-set-C6scM9Py.js.map} +1 -1
  182. package/dist/shell-source-maps/assets/{use-calendar-move-CgXeokRh.js.map → use-calendar-move-DcZxW6eO.js.map} +1 -1
  183. package/dist/shell-source-maps/assets/{use-display-rows-DFSNvNWx.js.map → use-display-rows-9Pz57Zus.js.map} +1 -1
  184. package/dist/shell-source-maps/assets/{use-paged-search-B52iaj1D.js.map → use-paged-search-CHxoPbgl.js.map} +1 -1
  185. package/dist/shell-source-maps/assets/{use-run-trace-KAufJAqD.js.map → use-run-trace-DdUrSC__.js.map} +1 -1
  186. package/dist/shell-source-maps/assets/{use-workflow-page-171SXJ7G.js.map → use-workflow-page-BqleruNg.js.map} +1 -1
  187. package/dist/shell-source-maps/assets/{use-workflow-types-ZGEaDrEJ.js.map → use-workflow-types-DUEWsZgC.js.map} +1 -1
  188. package/dist/shell-source-maps/assets/{workflow-canvas-CCu4twlF.js.map → workflow-canvas-cQ7U4Mgc.js.map} +1 -1
  189. package/dist/shell-source-maps/assets/{workflow-field-BFNHwCjK.js.map → workflow-field-c0IiPQaY.js.map} +1 -1
  190. package/dist/shell-source-maps/assets/{workflow-graph-editor-DTSyabCd.js.map → workflow-graph-editor-BAwGZFkg.js.map} +1 -1
  191. package/dist/shell-source-maps/assets/{workflow-run-field-D2fpm1Vk.js.map → workflow-run-field-Y49d5OnF.js.map} +1 -1
  192. package/dist/shell-source-maps/assets/{workflow-status-field-D_4-8JIF.js.map → workflow-status-field-fYllRt7c.js.map} +1 -1
  193. package/dist/shell-source-maps/assets/{workflow-workbench-CN5-OYpd.js.map → workflow-workbench-Bvx_2IBB.js.map} +1 -1
  194. package/dist/status/messages.d.ts +2 -2
  195. package/dist/users/messages.d.ts +2 -2
  196. package/package.json +5 -5
@@ -1 +1 @@
1
- {"version":3,"mappings":";s4FASA,IAAMA,GAAa,CACjB,KAAM,UACN,KAAM,GACN,KAAM,CACJ,CAAC,SAAU,CAAE,GAAI,KAAM,GAAI,KAAM,EAAG,IAAK,IAAK,QAAS,CAAC,EACxD,CAAC,OAAQ,CAAE,EAAG,2CAA4C,IAAK,QAAS,CAAC,CAC3E,CACF,EACAA,GAAW,KACX,IAAMC,GAASC,EAAiBF,EAAU,ECTpCA,GAAa,CACjB,KAAM,MACN,KAAM,GACN,KAAM,CACJ,CAAC,OAAQ,CAAE,EAAG,YAAa,IAAK,QAAS,CAAC,EAC1C,CAAC,OAAQ,CAAE,MAAO,KAAM,OAAQ,KAAM,EAAG,IAAK,EAAG,IAAK,GAAI,IAAK,IAAK,QAAS,CAAC,EAC9E,CAAC,OAAQ,CAAE,EAAG,UAAW,IAAK,QAAS,CAAC,EACxC,CAAC,OAAQ,CAAE,EAAG,WAAY,IAAK,QAAS,CAAC,EACzC,CAAC,OAAQ,CAAE,EAAG,WAAY,IAAK,QAAS,CAAC,EACzC,CAAC,OAAQ,CAAE,EAAG,UAAW,IAAK,QAAS,CAAC,CAC1C,CACF,EACAA,GA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K,eAAgB,CAAE,KAAMsB,EAAK,IAAK,CAAC,CAAW,GACrF,IAAMO,EAAY,OAAOP,EAAK,MAAM,WAAc,SAAWA,EAAK,MAAM,UAAY,OAC9E4K,EAAWpH,GAAOxD,EAAK,SAAUiB,EAAI,UAAU,EAE/C24B,GACJ,EAAA96B,EAAA,KAAC66B,EAAD,CAAa,OAAU,KAAI,MAAOjB,GAAY14B,EAAMiB,CAAE,EAAc,YACjE,SAAAjB,EAAK,OAAS,QAAUA,EAAK,OAAS,QAAUA,EAAK,OAAS,UAAYk4B,GAAattB,CAAQ,EAAIytB,GAAer4B,EAAK,OAAS,SAAW4K,EAAS,QAAQ,CAAE,WAAY,OAAOtQ,GAAU,QAAQ,EAAIsQ,CAAQ,CAC3M,GAEHivB,EAAUt5B,IAAc,QAAao3B,GAAW,IAAI33B,EAAK,IAAI,EAAI45B,GAAQ,EAAA96B,EAAA,KAAC,MAAD,CAAgB,YAAY,SAAA86B,CAAW,GAGtH,OADK55B,EAAK,UAER,EAAAlB,EAAA,KAAC04B,EAAD,CAAgB,KAAMx3B,EAAK,KAAM,SAAUA,EAAM,UAAU,EAAAlB,EAAA,KAAAC,WAAA,UAAGs5B,GAAe70B,GAAOxD,EAAK,SAAUiB,EAAI,UAAU,CAAC,CAAI,GACnH,SAAA44B,CACa,GAJSA,CAO7B","names":["__iconData","AtSign","createLucideIcon","Bot","KeySquare","Laptop","PlugZap","ShieldUser","Smartphone","Tablet","toolCallStates","defineBlock","inlineFieldTypes","isInlineField","child","isInlineChild","isEmptyFieldValue","type","value","textFieldText","numberFieldText","number","locales","locale","options","dateFieldText","date","props","input","showDate","showTime","dateOptions","booleanFieldText","words","safeSchemes","safeFieldUrl","read","scheme","cardsLayoutOf","layout","cardWidth","keyText","byText","a","b","graphShape","byKey","groups","row","nodes","id","key","fields","group","linked","edges","parts","edgeKey","name","source","target","ListActionButton","useAdminMeta","runner","useActionRunner","model","titleOf","useRecordTitle","asking","setAsking","useState","action","views","entry","records","items","scopeOf","item","on","record","skipped","shown","text","label","run","values","import_jsx_runtime","_Fragment","Button","variant","asksFirst","ActionPrompt","isDanger","quoted","ActionButton","scope","useLayoutRecord","useRunAction","resource","onRun","ran","about","ActionBlock","propsOf","node","list","useLayoutList","CardBlock","CardFrame","slots","cn","className","RecordsEach","Fragment","planned","index","wrap","RecordScope","RecordsIteratorBlock","LoadedCardRow","usePlanned","at","own","useListPage","limit","page","rows","Skeleton","ErrorBanner","Quiet","empty","LayoutListScope","CardRowBlock","ChartBlock","_actions","_span","_className","chart","resources","ChartView","ChosenRecord","useFirstRecord","query","body","timeOf","ms","keyOf","share","span","from","groupOf","lanes","start","given","end","now","lane","bar","pack","bars","placed","timelineShape","grouped","times","time","to","barKey","segments","segment","withinBar","minute","hour","day","tickSteps","year","stepsIn","toOffset","step","fromOffset","axisTicks","offset","offsetOf","endOffset","candidate","ticks","local","barIdOf","barIn","shape","offsetAt","zone","part","anchor","left","TimelineAxis","dated","viewerZone","tick","daily","formatDayShort","formatTime","segmentPaint","striped","hints","declared","isBadgeTone","toneDots","colorOf","field","paintStyle","paint","SegmentFill","width","formatDate","formatDateTime","rangeText","open","segmentText","displayValue","view","barText","known","barLook","BarMark","useRelationTitle","point","style","choose","chosen","RouteLink","TimelineLanes","laneField","FieldValue","Swatch","TimelineLegend","TimelineReadout","pageSize","timelineRowsQuery","keys","filter","sort","pageToken","client","useTimelineRows","request","useQuery","useClient","keepPreviousData","LoadedTimeline","defaultTimelineLimit","hovered","setHovered","focused","setFocused","idOf","readSort","cut","details","barValue","SelectTimeline","usePageParams","select","barTo","linkTo","GuardedParams","groupFilter","TimelineBlock","_children","loaded","timelineReadSort","timelineSort","CustomChosen","selection","selectOf","params","usePageParamsIfAny","children","GraphView","lazy","module","loading","Spinner","GraphBlock","reads","useElementReads","useMemo","status","signature","error","param","Suspense","messages","MessageComposer","refresh","useRefreshResource","permissions","usePermissions","sending","setSending","failure","setFailure","can","Composer","sent","message","ComposerBlock","DetailsBlock","SummaryBlock","DiffBlock","useScopedPathValue","emptyText","files","parsePatch","DiffView","file","plainText","fieldLabel","viewLabel","path","humanize","FieldBlock","columns","statColumns","spans","isStat","GridBlock","count","childNodes","stats","element","FixedImage","alt","imageQuery","asked","space","height","imageRefetch","isPicture","answer","useObjectUrl","url","setUrl","import_react","blob","next","useBroken","broken","setBroken","FunctionImage","useTheme","ref","useElementWidth","picture","markBroken","size","ImageBlock","inlineField","show","labelled","enumLabel","TextFieldBlock","NumberFieldBlock","formatTag","DateFieldBlock","formatRelativeTime","BooleanFieldBlock","TrueMark","UrlFieldBlock","safe","ChipFieldBlock","ValueBadge","linkStyle","LinkBlock","valueScopeOf","useScopeStack","usePageParamValues","buttonClass","content","fillAddressFrom","scopeLookup","AppLink","appPath","href","startingDraft","stored","toDraft","fallback","editBody","draft","isChosen","differs","toPatchValue","ModalFormDialog","toast","useToast","setDraft","errors","setErrors","rejections","setRejections","formRef","useFocusFirstInvalid","saving","setSaving","touched","setTouched","useNavigationGuard","submit","mode","createBody","title","onClose","found","fieldErrors","Dialog","event","problem","Field","fieldMessage","FieldEditor","_","rest","current","KeyedRecord","recordKey","ModalFormBlock","setOpen","button","PageBlock","PageHeader","description","useAmount","stack","amount","frameFor","usePathValue","ProgressBlock","total","max","LoadedRecordCard","plannedRecord","scoped","actions","RecordCardBlock","Clamped","useRef","taller","setTaller","box","measure","observer","isEmpty","RelatedField","clamped","CompactCard","buttons","tone","ToneEdge","RowButtonLink","onActed","RelatedCard","enabled","control","firstControl","card","nextFocus","before","gone","stays","after","headingOf","heading","root","useLeavingFocus","pending","announcement","setAnnouncement","settle","acted","previous","CardsSkeleton","compact","RelatedCards","xs","useIsXs","scroll","useSnapScroll","plural","orderBy","defaultOrderBy","ownCount","useCount","plannedCount","scopes","leaving","cards","note","cutOffNote","carousel","SnapRow","viewAllAddress","embeddedDisplay","display","listText","ArrowRight","shares","RecordCardsBlock","usePlannedReads","SectionContent","listColumnNames","cardActions","SavedRecordRow","listed","listedResource","saved","useSavedRecords","savedScope","RecordRowBody","SearchRowItem","encodeKey","useSearchRow","InlineFilterChips","SavedSearchRows","of","useSavedSearches","RecordRowBlock","savesAtOnce","SettingsForm","setStored","queue","latest","defaults","writable","typed","unsaved","write","changes","created","save","change","LoadedSettings","SettingsBlock","useConditions","useStackConditions","whens","parsed","parseCondition","isField","frame","paths","condition","counted","countedResource","fieldPaths","countedModels","sources","usePathValues","counts","useQueries","countQuery","evaluateCondition","fallbackOf","ShowBlock","when","drawn","matchConditions","fillProps","SwitchBlock","held","holds","MatchBlock","big","Count","filteredListAddress","RecordValue","StatBlock","useEmbeddedDisplay","embeddedDisplayKey","place","picked","setPicked","readPickedDisplay","pick","useCallback","writePickedDisplay","LoadedListTable","fieldTypes","useProjectUi","canUpdate","useAppAddress","narrow","useIsDesktop","names","columnName","all","embeddedColumns","specs","phoneSpecs","gridColumns","withRowButton","recordId","targets","embeddedRowTargets","go","DataGrid","ListTable","LoadedTable","tableDisplay","phoneColumns","EmbeddedDisplaySwitch","EmbeddedList","TableBlock","SelectTable","rowTo","TabsBlock","named","usePageTabsRoute","useRouter","tabs","tabsOf","shownPageTab","pathOf","navigate","tab","Link","Problem","TabBlock","mergeByTime","oldest","cutoff","first","second","merged","MessageStatus","mark","Check","valueTone","CircleAlert","Value","jsonOf","notJson","CodeBlock","JsonBlock","Part","ToolCallItem","useId","call","statusHints","opens","ChevronRight","messageRows","authorOf","threadItems","newestFirst","sameDay","sameChatDay","chatDayLabel","author","sender","state","stateOf","textOf","callKey","toolCallOf","result","threadListOf","reading","expanded","plannedList","expand","useThreadList","setExpanded","useList","pages","hasNextPage","isFetchingNextPage","fetchNextPage","useToolCalls","calls","threadSort","threadState","emptyLine","lines","showsErrorAbove","retryOf","loadEarlier","each","lists","MessageThread","auth","useOptionalAuth","reader","senders","labels","listLabels","callList","withLabels","markdown","isMarkdown","ChatThread","ChatDivider","ChatMessage","Markdown","ThreadBox","ThreadBlock","busy","working","plannedCalls","callsModel","BoxBlock","RowBlock","ColumnBlock","TextBlock","Tag","ArrayFieldBlock","scopeValue","SelectInputBlock","choices","MenuSelect","choice","defaultValue","relatedListOf","perPage","loadMore","more","useRelatedList","ReferenceManyFieldBlock","lookup","RelatedList","referenceManyRead","ListBody","ReferenceArrayFieldBlock","referenceArrayRead","LoadedReference","recordTitle","link","ReferenceFieldBlock","reference","roleNames","roleLabel","roles","AppInvitations","useAuth","selected","setSelected","invitations","setInvitations","load","session","InviteForm","AppRolesPicker","role","AccountSection","PendingInvitationRow","invitation","CreateUserForm","email","setEmail","setName","password","setPassword","useAction","create","onCreated","incomplete","SectionError","Input","UserRow","initial","user","setUser","setRoles","setError","setBlocked","blocked","PersonRow","Badge","self","UserList","setQuery","search","term","version","usePagedSearch","selfId","PagedSearchList","useUserRoles","AuthError","authMessage","UsersBlock","setVersion","MailSenderDialog","address","setAddress","setSignature","isDefault","setDefault","onSave","Switch","Textarea","detailsOf","MailSendersSection","setBusy","editing","setEditing","inFlight","close","attempt","onUpdate","added","onAdd","Plus","onRemove","signInOnlyNotes","mailboxOffers","links","offer","mailboxText","providerNames","Mailboxes","linkError","takeLinkError","mail","providers","account","useAccountData","data","SignInProvidersSection","signInProviders","provider","providerName","linkPersonalMail","providerMessage","reload","AccountLoading","PersonalMailBlock","personalMail","nameOf","clientName","app","accessOf","organization","ConnectedAppsSection","disconnecting","setDisconnecting","disconnect","onDisconnect","apps","publisher","clientPublisher","connectorDialogUrl","dialog","appName","McpAddressSection","CopyField","ExternalLink","Apps","clientId","Mcp","ConnectedAppsBlock","mcp","lifetimes","lifetimeLabels","dateOf","iso","expiryOf","expiresAt","token","PersonalAccessTokensSection","lifetime","setLifetime","confirming","setConfirming","days","onCreate","tokens","Select","option","ConfirmSignIn","onRevoke","Tokens","PersonalAccessTokensBlock","disconnected","wholeGrant","connection","ConnectionsSection","returned","setChosen","notice","setNotice","work","SectionNotice","connections","onConnect","RecordLink","workflow","ConnectionsBlock","connectAccount","deletionMessage","DeleteAccountDialog","formId","confirm","onDelete","hasPassword","DeleteAccountSection","staff","DeleteAccountBlock","methods","deleteAccount","browsers","systems","find","pattern","userAgent","deviceOf","linkName","operator","browser","system","iconOf","ordered","sessions","what","descriptionOf","DevicesSection","others","onSignOut","onSignOutLink","onSignOutOthers","signOut","Icon","DevicesBlock","deviceLinks","staffSignIn","descriptions","PasskeysSection","keepLast","rule","passkeys","KeyRound","passkey","onRename","PasskeysBlock","passwordMessage","draftProblem","repeat","PasswordChangeDialog","setCurrent","setNext","setRepeat","filled","PasswordSection","setSaved","canEdit","onChange","onSet","PasswordBlock","ChangeEmailDialog","sentTo","setSentTo","code","setCode","newEmail","send","complete","onDone","OtpInput","ProfileSection","changingEmail","setChangingEmail","rename","emailChange","onEmailChanged","ProfileBlock","changeEmail","PasswordDialog","onConfirm","needsPassword","danger","confirmLabel","offDescriptions","TwoFactorSection","authenticatorApp","TwoFactorSetup","onChanged","onTurnOff","onNewBackupCodes","BackupCodes","TwoFactorBlock","Replacement","CustomOrFallback","registered","CustomBoundary","blocks","ConnectedAccountsBlock","ownClasses","steps","pointerOf","FilledText","fillText","valueText","textChild","renderInline","position","RenderNode","renderChildren","runs","last","isElements","isLayoutNode","renderSlots","slotted","isObject","transChildren","components","tags","tag","chunks","formatted","formatMessage","texts","written","useAppTexts","withPropTexts","Custom","ComponentElement","unmarkFieldRefs","Block","block","classed"],"ignoreList":[0,1,2,3,4,5,6,7],"sources":["../../../../../node_modules/.bun/lucide-react@1.52.0+0ac650c021fb1b59/node_modules/lucide-react/dist/esm/icons/at-sign.mjs","../../../../../node_modules/.bun/lucide-react@1.52.0+0ac650c021fb1b59/node_modules/lucide-react/dist/esm/icons/bot.mjs","../../../../../node_modules/.bun/lucide-react@1.52.0+0ac650c021fb1b59/node_modules/lucide-react/dist/esm/icons/key-square.mjs","../../../../../node_modules/.bun/lucide-react@1.52.0+0ac650c021fb1b59/node_modules/lucide-react/dist/esm/icons/laptop.mjs","../../../../../node_modules/.bun/lucide-react@1.52.0+0ac650c021fb1b59/node_modules/lucide-react/dist/esm/icons/plug-zap.mjs","../../../../../node_modules/.bun/lucide-react@1.52.0+0ac650c021fb1b59/node_modules/lucide-react/dist/esm/icons/shield-user.mjs","../../../../../node_modules/.bun/lucide-react@1.52.0+0ac650c021fb1b59/node_modules/lucide-react/dist/esm/icons/smartphone.mjs","../../../../../node_modules/.bun/lucide-react@1.52.0+0ac650c021fb1b59/node_modules/lucide-react/dist/esm/icons/tablet.mjs","../../../../layout/src/check-tool-calls.ts","../../../../layout/src/inline-fields.ts","../../../../layout/src/field-format.ts","../../../../layout/src/cards-layout.ts","../../../../layout/src/graph-shape.ts","../../../src/app/pages/blocks/list-action.tsx","../../../src/app/pages/blocks/action.tsx","../../../src/app/pages/blocks/card.tsx","../../../src/app/pages/blocks/records-iterator.tsx","../../../src/app/pages/blocks/card-row.tsx","../../../src/app/pages/blocks/chart.tsx","../../../src/app/pages/blocks/chosen-record.tsx","../../../src/app/pages/blocks/timeline/timeline-layout.ts","../../../src/app/pages/blocks/timeline/bar-identity.ts","../../../src/app/pages/blocks/timeline/timeline-axis.tsx","../../../src/app/pages/blocks/timeline/timeline-paint.ts","../../../src/app/pages/blocks/timeline/segment-fill.tsx","../../../src/app/pages/blocks/timeline/timeline-text.ts","../../../src/app/pages/blocks/timeline/timeline-lanes.tsx","../../../src/app/pages/blocks/timeline/timeline-readout.tsx","../../../src/app/pages/blocks/timeline/use-timeline-rows.ts","../../../src/app/pages/blocks/timeline/timeline.tsx","../../../src/app/pages/custom-chosen.tsx","../../../src/app/pages/blocks/graph/graph-block.tsx","../../../src/app/conversation/messages.ts","../../../src/app/conversation/message-composer.tsx","../../../src/app/pages/blocks/composer.tsx","../../../src/app/pages/blocks/details.tsx","../../../src/app/pages/blocks/diff.tsx","../../../src/app/pages/blocks/plain-value.ts","../../../src/app/pages/blocks/field.tsx","../../../src/app/pages/blocks/grid.tsx","../../../src/app/pages/blocks/fixed-image.tsx","../../../src/app/pages/blocks/image-query.ts","../../../src/app/pages/blocks/image.tsx","../../../src/app/pages/blocks/inline-field.tsx","../../../src/app/pages/blocks/link.tsx","../../../src/app/pages/blocks/form-draft.ts","../../../src/app/pages/blocks/modal-form.tsx","../../../src/app/pages/blocks/page-block.tsx","../../../src/app/pages/blocks/progress.tsx","../../../src/app/pages/blocks/record-card.tsx","../../../src/app/related-cards/messages.ts","../../../src/app/related-cards/clamped.tsx","../../../src/app/related-cards/related-field.tsx","../../../src/app/related-cards/compact-card.tsx","../../../src/app/related-cards/related-card.tsx","../../../src/app/related-cards/first-control.ts","../../../src/app/related-cards/next-focus.ts","../../../src/app/related-cards/use-leaving-focus.ts","../../../src/app/related-cards/related-cards.tsx","../../../src/app/pages/blocks/record-cards.tsx","../../../src/app/record-row/saved-record-row.tsx","../../../src/app/searches/saved-search-rows.tsx","../../../src/app/pages/blocks/record-row.tsx","../../../src/app/pages/blocks/settings.tsx","../../../src/app/pages/use-conditions.ts","../../../src/app/pages/blocks/show.tsx","../../../src/app/pages/blocks/switch.tsx","../../../src/app/pages/blocks/stat.tsx","../../../src/app/embedded-list/use-embedded-display.ts","../../../src/app/pages/blocks/list-table.tsx","../../../src/app/pages/blocks/table.tsx","../../../src/app/pages/blocks/tabs.tsx","../../../src/app/conversation/merge-by-time.ts","../../../src/app/conversation/message-status.tsx","../../../src/app/conversation/tool-call-item.tsx","../../../src/app/conversation/thread-items.ts","../../../src/app/conversation/tool-calls.ts","../../../src/app/conversation/planned-thread-list.ts","../../../src/app/conversation/use-thread-list.ts","../../../src/app/conversation/use-tool-calls.ts","../../../src/app/conversation/thread-state.ts","../../../src/app/conversation/message-thread.tsx","../../../src/app/conversation/thread-box.tsx","../../../src/app/pages/blocks/thread.tsx","../../../src/app/pages/blocks/plain.tsx","../../../src/app/pages/blocks/array-field.tsx","../../../src/app/pages/blocks/select-input.tsx","../../../src/app/pages/related-list-of.ts","../../../src/app/pages/use-related-list.ts","../../../src/app/pages/blocks/reference-many-field.tsx","../../../src/app/pages/blocks/reference-array-field.tsx","../../../src/app/pages/blocks/reference-field.tsx","../../../src/users/role-names.ts","../../../src/users/messages.ts","../../../src/users/app-invitations.tsx","../../../src/users/create-user-form.tsx","../../../src/users/user-row.tsx","../../../src/users/user-list.tsx","../../../src/users/use-user-roles.ts","../../../src/users/users-block.tsx","../../../src/account/mail-sender-dialog.tsx","../../../src/account/mail-senders-section.tsx","../../../src/account/blocks/personal-mail-block.tsx","../../../src/account/connected-apps-section.tsx","../../../src/account/connector-dialog.ts","../../../src/account/mcp-address-section.tsx","../../../src/account/blocks/connected-apps-block.tsx","../../../src/account/personal-access-tokens-section.tsx","../../../src/account/blocks/personal-access-tokens-block.tsx","../../../src/account/connections-section.tsx","../../../src/account/blocks/connections-block.tsx","../../../src/account/delete-account-dialog.tsx","../../../src/account/delete-account-section.tsx","../../../src/account/blocks/delete-account-block.tsx","../../../src/account/device-name.ts","../../../src/account/devices-section.tsx","../../../src/account/blocks/devices-block.tsx","../../../src/account/passkeys-section.tsx","../../../src/account/blocks/passkeys-block.tsx","../../../src/account/password-change-dialog.tsx","../../../src/account/password-section.tsx","../../../src/account/blocks/password-block.tsx","../../../src/account/change-email-dialog.tsx","../../../src/account/profile-section.tsx","../../../src/account/blocks/profile-block.tsx","../../../src/account/password-dialog.tsx","../../../src/account/two-factor-section.tsx","../../../src/account/blocks/two-factor-block.tsx","../../../src/app/pages/custom-or-fallback.tsx","../../../src/app/pages/render-node.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: \"at-sign\",\n size: 24,\n node: [\n [\"circle\", { cx: \"12\", cy: \"12\", r: \"4\", key: \"4exip2\" }],\n [\"path\", { d: \"M16 8v5a3 3 0 0 0 6 0v-1a10 10 0 1 0-4 8\", key: \"7n84p3\" }]\n ]\n};\n__iconData.node;\nconst AtSign = createLucideIcon(__iconData);\n\nexport { __iconData, AtSign as default };\n//# sourceMappingURL=at-sign.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: \"bot\",\n size: 24,\n node: [\n [\"path\", { d: \"M12 8V4H8\", key: \"hb8ula\" }],\n [\"rect\", { width: \"16\", height: \"12\", x: \"4\", y: \"8\", rx: \"2\", key: \"enze0r\" }],\n [\"path\", { d: \"M2 14h2\", key: \"vft8re\" }],\n [\"path\", { d: \"M20 14h2\", key: \"4cs60a\" }],\n [\"path\", { d: \"M15 13v2\", key: \"1xurst\" }],\n [\"path\", { d: \"M9 13v2\", key: \"rq6x2g\" }]\n ]\n};\n__iconData.node;\nconst Bot = createLucideIcon(__iconData);\n\nexport { __iconData, Bot as default };\n//# sourceMappingURL=bot.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: \"key-square\",\n size: 24,\n node: [\n [\n \"path\",\n {\n d: \"M12.4 2.7a2.5 2.5 0 0 1 3.4 0l5.5 5.5a2.5 2.5 0 0 1 0 3.4l-3.7 3.7a2.5 2.5 0 0 1-3.4 0L8.7 9.8a2.5 2.5 0 0 1 0-3.4z\",\n key: \"165ttr\"\n }\n ],\n [\"path\", { d: \"m14 7 3 3\", key: \"1r5n42\" }],\n [\n \"path\",\n {\n d: \"m9.4 10.6-6.814 6.814A2 2 0 0 0 2 18.828V21a1 1 0 0 0 1 1h3a1 1 0 0 0 1-1v-1a1 1 0 0 1 1-1h1a1 1 0 0 0 1-1v-1a1 1 0 0 1 1-1h.172a2 2 0 0 0 1.414-.586l.814-.814\",\n key: \"1ubxi2\"\n }\n ]\n ]\n};\n__iconData.node;\nconst KeySquare = createLucideIcon(__iconData);\n\nexport { __iconData, KeySquare as default };\n//# sourceMappingURL=key-square.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: \"laptop\",\n size: 24,\n node: [\n [\n \"path\",\n {\n d: \"M18 5a2 2 0 0 1 2 2v8.526a2 2 0 0 0 .212.897l1.068 2.127a1 1 0 0 1-.9 1.45H3.62a1 1 0 0 1-.9-1.45l1.068-2.127A2 2 0 0 0 4 15.526V7a2 2 0 0 1 2-2z\",\n key: \"1pdavp\"\n }\n ],\n [\"path\", { d: \"M20.054 15.987H3.946\", key: \"14rxg9\" }]\n ]\n};\n__iconData.node;\nconst Laptop = createLucideIcon(__iconData);\n\nexport { __iconData, Laptop as default };\n//# sourceMappingURL=laptop.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: \"plug-zap\",\n size: 24,\n node: [\n [\n \"path\",\n { d: \"M6.3 20.3a2.4 2.4 0 0 0 3.4 0L12 18l-6-6-2.3 2.3a2.4 2.4 0 0 0 0 3.4Z\", key: \"goz73y\" }\n ],\n [\"path\", { d: \"m2 22 3-3\", key: \"19mgm9\" }],\n [\"path\", { d: \"M7.5 13.5 10 11\", key: \"7xgeeb\" }],\n [\"path\", { d: \"M10.5 16.5 13 14\", key: \"10btkg\" }],\n [\"path\", { d: \"m18 3-4 4h6l-4 4\", key: \"16psg9\" }]\n ],\n aliases: [\"plug-zap-2\"]\n};\n__iconData.node;\nconst PlugZap = createLucideIcon(__iconData);\n\nexport { __iconData, PlugZap as default };\n//# sourceMappingURL=plug-zap.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: \"shield-user\",\n size: 24,\n node: [\n [\n \"path\",\n {\n d: \"M20 13c0 5-3.5 7.5-7.66 8.95a1 1 0 0 1-.67-.01C7.5 20.5 4 18 4 13V6a1 1 0 0 1 1-1c2 0 4.5-1.2 6.24-2.72a1.17 1.17 0 0 1 1.52 0C14.51 3.81 17 5 19 5a1 1 0 0 1 1 1z\",\n key: \"oel41y\"\n }\n ],\n [\"path\", { d: \"M6.376 18.91a6 6 0 0 1 11.249.003\", key: \"hnjrf2\" }],\n [\"circle\", { cx: \"12\", cy: \"11\", r: \"4\", key: \"1gt34v\" }]\n ]\n};\n__iconData.node;\nconst ShieldUser = createLucideIcon(__iconData);\n\nexport { __iconData, ShieldUser as default };\n//# sourceMappingURL=shield-user.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: \"smartphone\",\n size: 24,\n node: [\n [\"rect\", { width: \"14\", height: \"20\", x: \"5\", y: \"2\", rx: \"2\", ry: \"2\", key: \"1yt0o3\" }],\n [\"path\", { d: \"M12 18h.01\", key: \"mhygvu\" }]\n ]\n};\n__iconData.node;\nconst Smartphone = createLucideIcon(__iconData);\n\nexport { __iconData, Smartphone as default };\n//# sourceMappingURL=smartphone.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: \"tablet\",\n size: 24,\n node: [\n [\"rect\", { width: \"16\", height: \"20\", x: \"4\", y: \"2\", rx: \"2\", ry: \"2\", key: \"76otgf\" }],\n [\"line\", { x1: \"12\", x2: \"12.01\", y1: \"18\", y2: \"18\", key: \"1dp563\" }]\n ]\n};\n__iconData.node;\nconst Tablet = createLucideIcon(__iconData);\n\nexport { __iconData, Tablet as default };\n//# sourceMappingURL=tablet.mjs.map\n","import type { ResourceModel, ToolCallFields } from '@protobase/schema'\nimport { choiceFilterProblems } from './check-param-filters'\nimport { pathFindings, type PathCheckInput } from './check-paths'\nimport { timeProblems } from './check-time'\nimport type { SelectInputProps } from './page-params'\nimport { sampledFilterErrors } from './sampled-filter'\nimport type { Scope } from './walk'\n\n/** The tool calls a thread draws between its messages: records of `resource`, by the fields it reads of each, narrowed by `filter` on a page. */\nexport type ToolCallSource = ToolCallFields & { resource: string; filter?: string }\n\n/** The values of a tool call's `status` that give it a mark; any other value, or none, draws no mark. */\nexport const toolCallStates = ['done', 'error', 'running'] as const\n\nexport type ToolCallState = (typeof toolCallStates)[number]\n\nconst required = ['name', 'time', 'status'] as const\nconst shown = ['input', 'result', 'error'] as const\n\nconst fieldOf = (model: ResourceModel, name: string) => (Object.hasOwn(model.fields, name) ? model.fields[name] : undefined)\n\n/** The fields of `source` that name a field, the ones each call needs first. */\nconst namedFields = (source: ToolCallSource) => [...required, ...shown].flatMap((prop) => (source[prop] === undefined ? [] : [[prop, source[prop]] as const]))\n\n// The name and the error read as text, the status as one of the states; the input and result show as JSON whatever their type\nconst typeProblems = (source: ToolCallSource, model: ResourceModel): string[] => {\n const name = fieldOf(model, source.name)!\n const status = fieldOf(model, source.status)!\n const error = source.error === undefined ? undefined : fieldOf(model, source.error)!\n return [\n ...(name.type === 'text' ? [] : [`name: \"${source.name}\" is ${name.type}; a tool call's name is a text field`]),\n ...(['text', 'enum'].includes(status.type) ? [] : [`status: \"${source.status}\" is ${status.type}; a tool call's status is a text or enum field`]),\n ...(error === undefined || error.type === 'text' ? [] : [`error: \"${source.error}\" is ${error.type}; a tool call's error is a text field`]),\n ]\n}\n\n/** Where on a page a thread sits: the records around it, its page parameters and their inputs, and where a warning goes. */\nexport type ToolCallsPage = PathCheckInput & { scope: Scope; inputs: ReadonlyMap<string, SelectInputProps>; warn: (warning: string) => void }\n\nconst sampledProblems = (filter: string, model: ResourceModel) => {\n const errors = sampledFilterErrors(model, filter)\n return errors.length === 0 ? [] : [`filter: ${errors.join('; ')}`]\n}\n\n// A filter is checked as a block's own filter is: its `{{path}}` slots through the records around the thread, then with\n// each value of the page parameters it reads, or else with a stand-in for each slot, such as `task_id = {{@root.id}}`\nconst filterProblems = (filter: string | undefined, model: ResourceModel, page: ToolCallsPage | undefined): string[] => {\n if (filter === undefined) return []\n if (!page) return sampledProblems(filter, model)\n const placed = pathFindings({ type: 'Thread', props: { filter }, children: [] }, page.scope, page)\n placed.warnings.forEach(page.warn)\n return [...placed.problems, ...(choiceFilterProblems(model, filter, page.inputs) ?? sampledProblems(filter, model))]\n}\n\n/**\n * What a thread's tool calls name that their resource does not have, cannot order them by, or cannot show as their\n * name, status or error; on a `page`, also what their filter reads that the records around the thread do not have.\n */\nexport const toolCallsProblems = (source: ToolCallSource, models: Record<string, ResourceModel>, page?: ToolCallsPage): string[] => {\n const model = Object.hasOwn(models, source.resource) ? models[source.resource] : undefined\n if (!model) return [`unknown resource \"${source.resource}\"`]\n const unknown = namedFields(source).flatMap(([prop, name]) => (fieldOf(model, name) ? [] : [`${prop}: unknown field \"${name}\" on ${model.name}`]))\n if (unknown.length > 0) return unknown\n return [...timeProblems(source.time, model, 'tool calls'), ...typeProblems(source, model), ...filterProblems(source.filter, model, page)]\n}\n\n/**\n * A thread's tool calls as a caller may see them: gone when they cannot read the calls or the name, time and status of\n * each, and without the input, result or error they cannot read.\n */\nexport const pruneToolCalls = <S extends ToolCallSource>(source: S, models: Record<string, ResourceModel>): S | undefined => {\n const { input, result, error, ...core } = source\n if (toolCallsProblems(core, models).length > 0) return\n const model = models[source.resource]!\n const keeps = (name: string | undefined) => name !== undefined && fieldOf(model, name) !== undefined\n return { ...core, ...(keeps(input) && { input }), ...(keeps(result) && { result }), ...(keeps(error) && { error }) } as S\n}\n","import { defineBlock } from './create-node'\nimport type { Styled } from './blocks'\nimport type { LayoutChild } from './node'\n\n// React-admin's field components (https://marmelab.com/react-admin/Fields.html): one value of the record around them,\n// read by `source` and drawn inline, so they sit in a `Text`, a `Link` or a `Summary` like a word of the sentence.\n\n/** What every field component takes, as react-admin's `FieldProps`: the path of its value, and the text shown when it has none. */\nexport type InlineFieldProps = Styled & {\n /** A field of the records around it, looked up as `{{path}}` is: `title`, `plan.name`, `../title`. */\n source: string\n /** Shown when the value is empty; nothing is shown without it. */\n emptyText?: string\n}\n\n/** Intl options, as `Intl.NumberFormat` or `Intl.DateTimeFormat` take them: names to strings, numbers and booleans. */\nexport type IntlOptions = Record<string, string | number | boolean>\n\n/** The value as text. https://marmelab.com/react-admin/TextField.html */\nexport type TextFieldProps = InlineFieldProps\n/** A number in the reader's locale, or `locales`, formatted by `Intl.NumberFormat` with `options`. https://marmelab.com/react-admin/NumberField.html */\nexport type NumberFieldProps = InlineFieldProps & { locales?: string | string[]; options?: IntlOptions }\n/**\n * A date, a time or both in the reader's locale, or `locales`, formatted by `Intl.DateTimeFormat` with `options`.\n * `format=\"relative\"`, which react-admin does not have, shows how long ago or ahead it is, such as \"3 hours ago\".\n * https://marmelab.com/react-admin/DateField.html\n */\nexport type DateFieldProps = InlineFieldProps & { showDate?: boolean; showTime?: boolean; locales?: string | string[]; options?: IntlOptions; format?: 'relative' }\n/** A mark for true and for false, with `valueLabelTrue` and `valueLabelFalse` as its words. https://marmelab.com/react-admin/BooleanField.html */\nexport type BooleanFieldProps = InlineFieldProps & { valueLabelTrue?: string; valueLabelFalse?: string }\n/** A link to the address the value holds, showing `content` or the address. https://marmelab.com/react-admin/UrlField.html */\nexport type UrlFieldProps = InlineFieldProps & { content?: string }\n/** The value as a chip. https://marmelab.com/react-admin/ChipField.html */\nexport type ChipFieldProps = InlineFieldProps\n\nexport const TextField = defineBlock<TextFieldProps>('TextField', false)\nexport const NumberField = defineBlock<NumberFieldProps>('NumberField', false)\nexport const DateField = defineBlock<DateFieldProps>('DateField', false)\nexport const BooleanField = defineBlock<BooleanFieldProps>('BooleanField', false)\nexport const UrlField = defineBlock<UrlFieldProps>('UrlField', false)\nexport const ChipField = defineBlock<ChipFieldProps>('ChipField', false)\n\n/** The field components' block types. */\nexport const inlineFieldTypes: ReadonlySet<string> = new Set(['TextField', 'NumberField', 'DateField', 'BooleanField', 'UrlField', 'ChipField'])\n\nexport const isInlineField = (child: LayoutChild) => typeof child !== 'string' && !child.custom && inlineFieldTypes.has(child.type)\n\n/** What runs on in a line of text: text, links, a `Text as=\"span\"` and the field components. */\nexport const isInlineChild = (child: LayoutChild) => typeof child === 'string' || isInlineField(child) || (!child.custom && (child.type === 'Link' || child.type === 'Trans' || (child.type === 'Text' && ['span', 'strong', 'em'].includes(String(child.props.as)))))\n","import type { BooleanFieldProps, DateFieldProps, NumberFieldProps } from './inline-fields'\n\n// How the field components turn a value into text, as react-admin's do (packages/ra-ui-materialui/src/field), shared\n// by the web and the text form so both read the same.\n\n/** Whether a field component shows its `emptyText` for `value`: as react-admin tests it, per component. */\nexport const isEmptyFieldValue = (type: string, value: unknown) => {\n if (type === 'BooleanField') return value !== true && value !== false\n if (type === 'NumberField' || type === 'UrlField') return value === null || value === undefined\n return value === null || value === undefined || value === ''\n}\n\n/** A value as `TextField` shows it: text as it is, anything else as its string; an object as JSON. */\nexport const textFieldText = (value: unknown) => (typeof value === 'object' && value !== null ? JSON.stringify(value) : String(value))\n\n/** A number as `NumberField` shows it, a numeric string read as its number first. */\nexport const numberFieldText = (value: unknown, { locales, options }: Pick<NumberFieldProps, 'locales' | 'options'>, locale?: string) => {\n const number = typeof value === 'string' && value !== '' && !Number.isNaN(Number(value)) ? Number(value) : value\n return typeof number === 'number' ? number.toLocaleString(locales ?? locale, options) : String(number)\n}\n\nexport type DateTextInput = {\n /** The reader's locale, used where the component names no `locales`; the runtime's default when omitted. */\n locale?: string\n /** Now, in milliseconds, which `format=\"relative\"` counts from. */\n now: number\n /** How long ago a moment was, in seconds (negative for one to come), as the client words it. */\n relative: (seconds: number) => string\n}\n\n/** A date as `DateField` shows it: a date-only value such as `2026-02-15` in UTC, so no time zone moves its day. */\nexport const dateFieldText = (value: unknown, props: Pick<DateFieldProps, 'showDate' | 'showTime' | 'locales' | 'options' | 'format'>, input: DateTextInput) => {\n const date = value instanceof Date ? value : typeof value === 'string' || typeof value === 'number' ? new Date(value) : undefined\n // An unparseable value, such as `'soon'`, gives an invalid date, which no formatter takes\n if (!date || Number.isNaN(date.getTime())) return ''\n if (props.format === 'relative') return input.relative(Math.round((input.now - date.getTime()) / 1000))\n const { showDate = true, showTime = false, options } = props\n const locales = props.locales ?? input.locale\n if (showDate && showTime) return date.toLocaleString(locales, options)\n if (showTime) return date.toLocaleTimeString(locales, options)\n const dateOptions = options ?? (typeof value === 'string' && value.length <= 10 ? { timeZone: 'UTC' } : undefined)\n return date.toLocaleDateString(locales, dateOptions)\n}\n\n/** The word for a boolean, as `BooleanField` labels its mark: `valueLabelTrue` or `valueLabelFalse`, else the client's yes or no. */\nexport const booleanFieldText = (value: boolean, props: Pick<BooleanFieldProps, 'valueLabelTrue' | 'valueLabelFalse'>, words: { yes: string; no: string }) =>\n value ? (props.valueLabelTrue ?? words.yes) : (props.valueLabelFalse ?? words.no)\n\n// The schemes a link may follow; another, such as javascript: or data:, could run code, so its address shows as text.\nconst safeSchemes = new Set(['http:', 'https:', 'mailto:', 'tel:'])\n\n/**\n * The address `UrlField` links to: one with an `http:`, `https:`, `mailto:` or `tel:` scheme, or a path on the app's\n * own origin; `undefined` for any other, which then shows as text.\n */\nexport const safeFieldUrl = (value: string): string | undefined => {\n // Browsers drop leading control characters and spaces, and tabs and newlines anywhere, before reading the scheme\n // eslint-disable-next-line no-control-regex\n const read = value.replace(/^[\\u0000- ]+/, '').replace(/[\\t\\n\\r]/g, '')\n const scheme = /^([A-Za-z][A-Za-z0-9+.-]*):/.exec(read)?.[1]\n if (scheme === undefined) return read.startsWith('/') || !read.includes(':') ? value : undefined\n return safeSchemes.has(`${scheme.toLowerCase()}:`) ? value : undefined\n}\n","import type { CardsLayout, CardWidth, RecordCardsProps } from './blocks'\n\n/** How a `RecordCards` lays out its cards, its props' defaults filled in: stacked, and two thirds wide in a carousel. */\nexport const cardsLayoutOf = ({ layout, cardWidth }: Pick<RecordCardsProps, 'layout' | 'cardWidth'>): { layout: CardsLayout; cardWidth: CardWidth } => ({\n layout: layout ?? 'stack',\n cardWidth: cardWidth ?? '2/3',\n})\n","type Row = Record<string, unknown>\n\n/** The fields a graph reads: a node's `label`, `group` and `status`, and the node keys an edge's `source` and `target` hold. */\nexport type GraphFields = { label: string; group?: string; status?: string; source: string; target: string }\n\nexport type ShapeNode = { id: string; row: Row; group?: string }\nexport type ShapeGroup = { id: string; value: unknown }\nexport type ShapeEdge = { id: string; source: string; target: string; row: Row }\n\n/** What a graph shows: its groups, its nodes, each in its group, and the edges between them, each in one fixed order. */\nexport type GraphShape = { groups: ShapeGroup[]; nodes: ShapeNode[]; edges: ShapeEdge[] }\n\nconst keyText = (value: unknown) => (value === null || value === undefined || value === '' ? undefined : String(value))\n\nconst byText = (a: string, b: string) => (a < b ? -1 : a > b ? 1 : 0)\n\n/**\n * The graph `nodes` and `edges` make: a node per record by its `key` field, an edge by its `edgeKey` fields, in the group its `group` value names, and\n * an edge per record whose `source` and `target` are both among the nodes; one pointing elsewhere is left out. Groups,\n * nodes and edges are each sorted by key, so the same records make the same graph whatever order they come in.\n */\nexport const graphShape = ({ nodes, edges, key, edgeKey, fields }: { nodes: Row[]; edges: Row[]; key: string; edgeKey: readonly string[]; fields: GraphFields }): GraphShape => {\n const byKey = new Map<string, ShapeNode>()\n const groups = new Map<string, ShapeGroup>()\n for (const row of nodes) {\n const id = keyText(row[key])\n if (id === undefined || byKey.has(id)) continue\n const value = fields.group === undefined ? undefined : row[fields.group]\n const group = keyText(value)\n if (group !== undefined && !groups.has(group)) groups.set(group, { id: group, value })\n byKey.set(id, { id, row, ...(group !== undefined && { group }) })\n }\n const linked = edges.flatMap((row) => {\n const parts = edgeKey.map((name) => keyText(row[name]))\n // A JSON list keeps the parts apart, so `['a,b', 'c']` and `['a', 'b,c']` stay two edges\n const id = parts.includes(undefined) ? undefined : parts.length === 1 ? parts[0] : JSON.stringify(parts)\n const source = keyText(row[fields.source])\n const target = keyText(row[fields.target])\n if (id === undefined || source === undefined || target === undefined || !byKey.has(source) || !byKey.has(target)) return []\n return [{ id, source, target, row }]\n })\n return {\n groups: [...groups.values()].sort((a, b) => byText(a.id, b.id)),\n nodes: [...byKey.values()].sort((a, b) => byText(a.id, b.id)),\n edges: linked.sort((a, b) => byText(a.source, b.source) || byText(a.target, b.target) || byText(a.id, b.id)),\n }\n}\n","import { useState } from 'react'\nimport type { ActionProps } from '@protobase/layout'\nimport type { ResourceModel } from '@protobase/schema'\nimport { Button } from '../../../primitives/button'\nimport { text } from '../../list-messages'\nimport { useAdminMeta } from '../../meta-gate'\nimport { useRecordTitle } from '../../titles/record-titles'\nimport { ActionPrompt, asksFirst, isDanger } from '../action-prompt'\nimport { scopeOf } from '../use-layout-data'\nimport { quoted, useActionRunner } from '../use-run-action'\n\ntype ListActionProps = Omit<ActionProps, 'resource'> & { model: ResourceModel; items: readonly unknown[]; className?: string }\n\n/**\n * A button for a named action of `model`'s view that runs on each record of the list it sits in, as a list's selection\n * does: on those it applies to, counted in its label (\"Approve (3)\"), asking its question or inputs once, a checklist's\n * boxes shared by several records once, and refusing and naming those the person may not change. Nothing when the view\n * has no such action, when it is a link, or when it applies to none of the records.\n */\nexport const ListActionButton = ({ model, items, name, label, variant, className }: ListActionProps) => {\n const { views } = useAdminMeta()\n const runner = useActionRunner(model.name, undefined)\n const titleOf = useRecordTitle()\n const [asking, setAsking] = useState(false)\n const action = views[model.name]?.actions?.find((entry) => entry.name === name)\n if (!action || action.run?.kind === 'link') return null\n const records = items.map((item) => scopeOf(model, item as Record<string, unknown>))\n const on = records.filter((record) => runner.verdictOn(action, record) !== 'skip')\n if (on.length === 0) return null\n const skipped = records.length - on.length\n const shown = text('actionCount', { label: label ?? action.label, count: on.length })\n const run = (values?: Record<string, unknown>) => runner.runEach(action, on, skipped, values)\n const start = () => (asksFirst(action) ? setAsking(true) : void run())\n return (\n <>\n <Button size=\"sm\" variant={variant ?? action.variant ?? 'secondary'} className={className} loading={runner.running === name} onClick={start}>\n {shown}\n </Button>\n {asking && (\n <ActionPrompt\n action={action}\n label={shown}\n danger={variant === 'danger' || (variant === undefined && isDanger(action))}\n records={on.map((record) => record.record)}\n names={on.map((record) => quoted(titleOf(model, views[model.name], record.record, record.key)))}\n onCancel={() => setAsking(false)}\n onConfirm={() => {\n setAsking(false)\n void run()\n }}\n onSubmit={async (values) => {\n setAsking(false)\n await run(values)\n }}\n />\n )}\n </>\n )\n}\n","import { useState } from 'react'\nimport type { ActionProps } from '@protobase/layout'\nimport { Button } from '../../../primitives/button'\nimport { ActionPrompt, asksFirst } from '../action-prompt'\nimport { useLayoutList } from '../layout-list'\nimport { useLayoutRecord } from '../record-scope'\nimport { useRunAction } from '../use-run-action'\nimport { propsOf, type BlockProps } from './block-props'\nimport { ListActionButton } from './list-action'\n\n/**\n * A button for a named action of `resource`'s view, by default of the record around it, on that record, asking first\n * when the action has `confirm` or `inputs`; nothing when the view has no such action for the user, or none for the\n * record. It is drawn as the action's `variant` unless the block names its own. `about` names the record in the\n * button's accessible name after its label, as \"Mark clear: <title>\", where the same button repeats for several records.\n * `onRun` hears the label it shows once the action succeeded.\n */\nexport const ActionButton = ({ name, resource, label, variant, className, about, onRun }: ActionProps & { className?: string; about?: string; onRun?: (label: string) => void }) => {\n const scope = useLayoutRecord()\n const action = useRunAction(resource ?? scope?.model.name ?? '', name, resource === undefined || resource === scope?.model.name ? scope : undefined, (ran) => onRun?.(label ?? ran.label))\n const [asking, setAsking] = useState(false)\n if (!action.action) return null\n const text = label ?? action.action.label\n // The block's own variant wins over the action's\n const shown = variant ?? action.action.variant ?? 'secondary'\n const start = () => (asksFirst(action.action!) ? setAsking(true) : void action.run())\n return (\n <>\n <Button size=\"sm\" variant={shown} className={className} loading={action.running} disabled={Boolean(action.blocked)} title={action.blocked} aria-label={about === undefined ? undefined : `${text}: ${about}`} onClick={start}>\n {text}\n </Button>\n {asking && (\n <ActionPrompt\n action={action.action}\n label={text}\n danger={shown === 'danger'}\n records={action.record ? [action.record] : []}\n onCancel={() => setAsking(false)}\n onConfirm={() => {\n setAsking(false)\n void action.run()\n }}\n onSubmit={async (values) => {\n await action.submit(values)\n setAsking(false)\n }}\n />\n )}\n </>\n )\n}\n\n/**\n * An Action block: its button, on the record around it, or, directly in a list of records and naming no other resource,\n * on each record of that list.\n */\nexport const ActionBlock = ({ node, className }: BlockProps) => {\n const props = propsOf<ActionProps>(node)\n const list = useLayoutList()\n const model = list?.model\n if (model && (props.resource === undefined || props.resource === model.name)) return <ListActionButton {...props} model={model} items={list.items} className={className} />\n return <ActionButton {...props} className={className} />\n}\n","import type { CardProps } from '@protobase/layout'\nimport { cn } from '../../../lib/cn'\nimport { propsOf, type BlockProps } from './block-props'\nimport { CardFrame } from './card-frame'\n\nexport const CardBlock = ({ node, children, slots, className }: BlockProps) => {\n const { title, description } = propsOf<CardProps>(node)\n return (\n <CardFrame title={title} description={description} actions={slots.actions} className={cn('h-full', className)}>\n <div className=\"flex flex-col gap-3\">{children}</div>\n </CardFrame>\n )\n}\n","import { Fragment, type ReactNode } from 'react'\nimport { RecordScope, type ItemFrame, type LayoutRecord } from '../record-scope'\nimport { useLayoutList } from '../layout-list'\nimport { scopeOf } from '../use-layout-data'\nimport type { BlockProps } from './block-props'\n\ntype EachProps = {\n children: ReactNode\n /** What each entry is drawn in, such as a card of a row; nothing when omitted. */\n wrap?: (entry: ReactNode, key: string | number) => ReactNode\n}\n\n/**\n * `children` once per entry of the list around it, each in the record it is, or the item of a JSON list, which\n * `@index`, `@first` and `@last` count; the list ends there, so a list inside them is one of their own.\n */\nexport const RecordsEach = ({ children, wrap = (entry, key) => <Fragment key={key}>{entry}</Fragment> }: EachProps) => {\n const list = useLayoutList()\n if (!list) return null\n const { model, items, planned } = list\n return items.map((item, index) => {\n const value: LayoutRecord | ItemFrame = model ? { ...scopeOf(model, item as Record<string, unknown>), ...(planned && { planned }) } : { item }\n const key = 'key' in value ? value.key : index\n return wrap(\n <RecordScope value={value} row={{ index, count: items.length }}>\n {children}\n </RecordScope>,\n key,\n )\n })\n}\n\n/** Its children once per entry of the list around it, with nothing drawn around them, as react-admin's RecordsIterator. */\nexport const RecordsIteratorBlock = ({ children }: BlockProps) => <RecordsEach>{children}</RecordsEach>\n","import type { ReactNode } from 'react'\nimport type { CardRowProps } from '@protobase/layout'\nimport type { ResourceModel } from '@protobase/schema'\nimport { Skeleton } from '../../../primitives/skeleton'\nimport { ErrorBanner } from '../../error-banner'\nimport { useAdminMeta } from '../../meta-gate'\nimport { LayoutListScope } from '../layout-list'\nimport { usePlanned } from '../plan-reads'\nimport { useListPage } from '../use-layout-data'\nimport { propsOf, type BlockProps } from './block-props'\nimport { CardFrame, Quiet } from './card-frame'\nimport { RecordsEach } from './records-iterator'\nimport { text } from '../messages'\n\ntype LoadedProps = Omit<CardRowProps, 'resource' | 'actions' | 'children'> & { model: ResourceModel; at?: string; actions: ReactNode; children: ReactNode[]; className?: string }\n\n// A list of its records, from the page's planned read or one of its own, drawn as a RecordsIterator draws one, each in a\n// small card of the row\nconst LoadedCardRow = ({ model, at, filter, sort, limit = 12, title, description, empty, actions, children, className }: LoadedProps) => {\n const planned = usePlanned(at)\n const own = useListPage(model, { filter, sort, pageSize: limit, enabled: !planned })\n const page = planned ?? own\n const rows = planned ? planned.rows : (own.data?.items ?? [])\n return (\n <CardFrame title={title} description={description} actions={actions} className={className}>\n {page.isPending ? (\n <div className=\"flex gap-3\">{Array.from({ length: 3 }, (_, index) => <Skeleton key={index} className=\"h-24 w-56\" />)}</div>\n ) : page.error ? (\n <ErrorBanner title={text('couldNotLoad')} error={page.error} />\n ) : rows.length === 0 ? (\n <Quiet>{empty ?? text('nothingYet')}</Quiet>\n ) : (\n <ul className=\"relative -mx-4 flex snap-x gap-3 overflow-x-auto px-4 pb-1\">\n <LayoutListScope value={{ model, items: rows, ...(planned && { planned: true }) }}>\n <RecordsEach\n wrap={(entry, key) => (\n <li key={key} className=\"flex w-60 shrink-0 snap-start flex-col gap-2 rounded-lg border border-border bg-surface p-3\">\n {entry}\n </li>\n )}\n >\n {children}\n </RecordsEach>\n </LayoutListScope>\n </ul>\n )}\n </CardFrame>\n )\n}\n\n/** Up to `limit` records side by side, each a small card made from the children, with their own actions. */\nexport const CardRowBlock = ({ node, at, children, slots }: BlockProps) => {\n const { resource, ...props } = propsOf<CardRowProps>(node)\n const model = useAdminMeta().resources[resource]\n if (!model) return null\n return (\n <LoadedCardRow {...props} model={model} {...(at !== undefined && { at })} actions={slots.actions}>\n {children}\n </LoadedCardRow>\n )\n}\n","import type { ChartProps, Styled } from '@protobase/layout'\nimport { ChartView } from '../../charts/chart-view'\nimport { useAdminMeta } from '../../meta-gate'\nimport { cn } from '../../../lib/cn'\nimport { propsOf, type BlockProps } from './block-props'\nimport { CardFrame } from './card-frame'\n\n/** Counts, sums or averages of the records that match, per value or date bucket of a field, in a card. */\nexport const ChartBlock = ({ node, slots, className }: BlockProps) => {\n const { resource, title, description, actions: _actions, span: _span, className: _className, ...chart } = propsOf<ChartProps & Styled>(node)\n const { resources, views } = useAdminMeta()\n const model = resources[resource]\n if (!model) return null\n return (\n <CardFrame title={title} description={description} actions={slots.actions} className={cn('h-full', className)}>\n <ChartView model={model} view={views[resource]} {...chart} />\n </CardFrame>\n )\n}\n","import type { ReactNode } from 'react'\nimport type { ResourceModel } from '@protobase/schema'\nimport { Skeleton } from '../../../primitives/skeleton'\nimport { ErrorBanner } from '../../error-banner'\nimport { RecordScope } from '../record-scope'\nimport { useFirstRecord } from '../use-layout-data'\nimport { Quiet } from './card-frame'\nimport { text } from '../messages'\n\n/** Which record a `select` chose: by its key as text, or the first that matches a filter in a sort's order. */\nexport type ChosenQuery = { key: string } | { filter: string; sort: string }\n\n/** The record a block's `select` chose, with its children drawn inside it, under a rule unless `className` places it otherwise. */\nexport const ChosenRecord = ({ model, query, className = 'mt-4 border-t pt-4', children }: { model: ResourceModel; query: ChosenQuery; className?: string; children: ReactNode }) => {\n const record = useFirstRecord(model, query)\n const body = record.isPending ? (\n <div className=\"flex flex-col gap-2\">\n <Skeleton className=\"h-4 w-1/2\" />\n <Skeleton className=\"h-4 w-1/3\" />\n </div>\n ) : record.error ? (\n <ErrorBanner title={text('couldNotLoad')} error={record.error} />\n ) : record.data ? (\n <RecordScope value={record.data}>\n <div className=\"flex flex-col gap-3\">{children}</div>\n </RecordScope>\n ) : (\n <Quiet>{text('nothingYet')}</Quiet>\n )\n return <div className={className}>{body}</div>\n}\n","// Where a timeline draws each record: a lane per `lane` value in the order they first start, a bar per `bar` value\n// in its lane, and a segment per record from `start` to `end`, all placed as a share of the time from the earliest\n// start to the latest end, so the axis always fits the width it has. A record without an end runs to now.\n\ntype Row = Record<string, unknown>\n\n/** The fields a timeline reads of each record, by their roles. */\nexport type TimelineFields = { lane: string; bar: string; start: string; end: string; color: string }\n\n/** One record as a part of its bar: its colour value, its time in ms, `open` when it has no end, and where it sits in %. */\nexport type TimelineSegment = { record: Row; value: unknown; start: number; end: number; open: boolean; left: number; width: number }\n\n/** The records of one `bar` value in a lane, from its first start to its last end, placed in %. */\nexport type TimelineBar = { key: string; value: unknown; lane: unknown; start: number; end: number; left: number; width: number; segments: TimelineSegment[] }\n\n/** One lane: its value, and its bars packed into rows so none overlap another in time. */\nexport type TimelineLane = { key: string; value: unknown; rows: TimelineBar[][] }\n\n/** What a timeline draws: its lanes, and the time its axis runs over. */\nexport type TimelineShape = { lanes: TimelineLane[]; from: number; to: number }\n\nconst timeOf = (value: unknown) => {\n if (typeof value !== 'string' && typeof value !== 'number') return\n const ms = typeof value === 'number' ? value : Date.parse(value)\n return Number.isNaN(ms) ? undefined : ms\n}\n\n/** The key a lane or bar value is grouped by. */\nexport const keyOf = (value: unknown) => (value === null || value === undefined ? '' : String(value))\n\nconst share = (ms: number, from: number, span: number) => (span === 0 ? 0 : ((ms - from) / span) * 100)\n\ntype Grouped = { value: unknown; bars: Map<string, { value: unknown; records: Array<{ record: Row; start: number; end: number; open: boolean }> }> }\n\n// Records grouped into lanes and bars, each with its time; one without a start cannot be placed and is left out\nconst groupOf = (rows: Row[], fields: TimelineFields, now: number) => {\n const lanes = new Map<string, Grouped>()\n for (const record of rows) {\n const start = timeOf(record[fields.start])\n if (start === undefined) continue\n const given = timeOf(record[fields.end])\n const end = Math.max(start, given ?? now)\n const lane = lanes.get(keyOf(record[fields.lane])) ?? { value: record[fields.lane], bars: new Map() }\n lanes.set(keyOf(record[fields.lane]), lane)\n const bar = lane.bars.get(keyOf(record[fields.bar])) ?? { value: record[fields.bar], records: [] }\n lane.bars.set(keyOf(record[fields.bar]), bar)\n bar.records.push({ record, start, end, open: given === undefined })\n }\n return lanes\n}\n\n// Each bar goes in the first row of its lane whose last bar ended by the time it starts, or a new row\nconst pack = (bars: TimelineBar[]) => {\n const rows: TimelineBar[][] = []\n for (const bar of [...bars].sort((a, b) => a.start - b.start)) {\n const row = rows.find((placed) => placed.at(-1)!.end <= bar.start)\n if (row) row.push(bar)\n else rows.push([bar])\n }\n return rows\n}\n\n/** Lanes, bars and segments of `rows`, placed between the earliest start and the latest end, an open end at `now`. */\nexport const timelineShape = (rows: Row[], fields: TimelineFields, now: number): TimelineShape => {\n const grouped = groupOf(rows, fields, now)\n const times = [...grouped.values()].flatMap((lane) => [...lane.bars.values()].flatMap((bar) => bar.records))\n if (times.length === 0) return { lanes: [], from: now, to: now }\n const from = Math.min(...times.map((time) => time.start))\n const to = Math.max(...times.map((time) => time.end))\n const span = to - from\n const lanes = [...grouped.entries()].map(([key, lane]): TimelineLane => {\n const bars = [...lane.bars.entries()].map(([barKey, bar]): TimelineBar => {\n const segments = bar.records\n .sort((a, b) => a.start - b.start)\n .map(({ record, start, end, open }) => ({ record, value: record[fields.color], start, end, open, left: share(start, from, span), width: share(end, from, span) - share(start, from, span) }))\n const start = segments[0]!.start\n const end = Math.max(...segments.map((segment) => segment.end))\n return { key: barKey, value: bar.value, lane: lane.value, start, end, left: share(start, from, span), width: share(end, from, span) - share(start, from, span), segments }\n })\n return { key, value: lane.value, rows: pack(bars) }\n })\n return { lanes, from, to }\n}\n\n/** A segment's place within its bar, in % of the bar's width, for drawing it inside the bar. */\nexport const withinBar = (bar: TimelineBar, segment: TimelineSegment) => {\n const span = bar.end - bar.start\n return { left: share(segment.start, bar.start, span), width: span === 0 ? 100 : ((segment.end - segment.start) / span) * 100 }\n}\n\nconst minute = 60_000\nconst hour = 60 * minute\nconst day = 24 * hour\n\n/** The steps an axis ticks at, the shortest first. */\nexport const tickSteps = [5 * minute, 15 * minute, 30 * minute, hour, 3 * hour, 6 * hour, 12 * hour, day, 2 * day, 7 * day, 14 * day, 30 * day, 90 * day, 365 * day]\n\n/** How many ticks an axis shows at most, so their labels fit a phone's width. */\nexport const maxTicks = 6\n\nconst year = 365 * day\n\n// How many whole local steps lie from `from` to `to`, both included, on a clock `fromOffset` ms ahead of UTC at `from` and `toOffset` at `to`\nconst stepsIn = (from: number, to: number, step: number, fromOffset: number, toOffset: number) => Math.floor((to + toOffset) / step) - Math.ceil((from + fromOffset) / step) + 1\n\n/**\n * The ticks of an axis from `from` to `to`: the shortest step that gives at most `maxTicks`, past the last of\n * `tickSteps` whole years, each on a whole step of the clock `offsetOf` gives at a moment, its ms ahead of UTC there,\n * so a tick stays on its local hour or midnight when the offset changes within the range, and a local time the clock\n * skips gets none. Each is placed in %;\n * `daily` when the step is a day or more, so they read as dates.\n */\nexport const axisTicks = (from: number, to: number, offsetOf: (ms: number) => number = () => 0) => {\n const span = to - from\n if (span <= 0) return { daily: false, ticks: [] }\n const offset = offsetOf(from)\n const endOffset = offsetOf(to)\n const step = tickSteps.find((candidate) => stepsIn(from, to, candidate, offset, endOffset) <= maxTicks) ?? Math.ceil(span / (maxTicks - 1) / year) * year\n const ticks: Array<{ at: number; left: number }> = []\n for (let local = Math.ceil((from + offset) / step) * step; local <= to + endOffset; local += step) {\n // The local step's moment, by the offset in force near it; a step the clock skips, as it springs forward, has none\n const at = local - offsetOf(local - offset)\n if (at + offsetOf(at) !== local) continue\n if (at >= from && at <= to) ticks.push({ at, left: share(at, from, span) })\n }\n return { daily: step >= day, ticks }\n}\n","import { keyOf, type TimelineBar, type TimelineShape } from './timeline-layout'\n\n/** Which bar of a timeline one is, by its lane's key and its own, so it is found again in a newer shape. */\nexport type BarId = { lane: string; bar: string }\n\nexport const barIdOf = (bar: TimelineBar): BarId => ({ lane: keyOf(bar.lane), bar: bar.key })\n\n/** The bar `id` names in `shape`, as the current data places it, or `null` when it is no longer there. */\nexport const barIn = (shape: TimelineShape, id: BarId | null) => {\n if (!id) return null\n const lane = shape.lanes.find((candidate) => candidate.key === id.lane)\n return lane?.rows.flat().find((bar) => bar.key === id.bar) ?? null\n}\n","import { formatDayShort, formatTime } from '../../../../format/date'\nimport { viewerZone } from '../../../../format/zone'\nimport { axisTicks } from './timeline-layout'\n\n// How far the viewer's clock is ahead of UTC at `ms`, so ticks fall on their whole hours and days\nconst offsetAt = (ms: number, zone: string) => {\n const parts = Object.fromEntries(new Intl.DateTimeFormat('en-US', { timeZone: zone, hourCycle: 'h23', year: 'numeric', month: 'numeric', day: 'numeric', hour: 'numeric', minute: 'numeric' }).formatToParts(ms).map((part) => [part.type, part.value]))\n const local = Date.UTC(Number(parts.year), Number(parts.month) - 1, Number(parts.day), Number(parts.hour), Number(parts.minute))\n return local - Math.floor(ms / 60_000) * 60_000\n}\n\n// A label near an edge stays inside the axis, so it never widens the page\nconst anchor = (left: number) => (left < 8 ? 'translate-x-0' : left > 92 ? '-translate-x-full' : '-translate-x-1/2')\n\n/**\n * The time from `from` to `to` as a few ticks, as dates from a day apart, as times below: on the viewer's clock, or for\n * `dated` fields, whose days are kept in UTC as their bars are, on UTC's.\n */\nexport const TimelineAxis = ({ from, to, dated }: { from: number; to: number; dated: boolean }) => {\n const zone = dated ? 'UTC' : viewerZone()\n const offsetOf = (ms: number) => (dated ? 0 : offsetAt(ms, zone))\n const { daily, ticks } = axisTicks(from, to, offsetOf)\n return (\n <div aria-hidden=\"true\" className=\"relative h-5 min-w-0 flex-1 border-b border-border text-xs text-muted-foreground tabular-nums\">\n {ticks.map((tick) => (\n <span key={tick.at} className={`absolute bottom-1 whitespace-nowrap ${anchor(tick.left)}`} style={{ left: `${tick.left}%` }}>\n {/* A day is kept in UTC, so the viewer's day is their midnight moved by the offset there */}\n {daily ? formatDayShort(tick.at + offsetOf(tick.at)) : formatTime(tick.at, zone)}\n </span>\n ))}\n </div>\n )\n}\n","import { isBadgeTone, type FieldModel, type FieldViewModel } from '@protobase/schema'\nimport { toneDots } from '../../../../primitives/badge'\nimport { colorOf } from '../../../charts/chart-groups'\n\n/** How a segment is filled: a tone's class or a colour, striped while its value waits. */\nexport type SegmentPaint = { className?: string; color?: string; striped: boolean }\n\n// A wait reads apart from work at a glance, in any colour: the background shows through every other stripe\nexport const stripes = 'repeating-linear-gradient(-45deg, transparent 0 4px, color-mix(in srgb, var(--background) 55%, transparent) 4px 6px)'\n\n/**\n * A segment's fill by its `color` value: the tone or hex colour its view's `valueColors` gives it, else the chart\n * colour of its place among the enum's values, as a chart colours it; striped when the view marks it waiting.\n */\nexport const segmentPaint = (field: FieldModel, hints: FieldViewModel | undefined, value: unknown): SegmentPaint => {\n const key = String(value)\n const striped = hints?.waitingValues?.includes(key) ?? false\n const declared = hints?.valueColors && Object.hasOwn(hints.valueColors, key) ? hints.valueColors[key] : undefined\n if (declared !== undefined && isBadgeTone(declared)) return { className: toneDots[declared], striped }\n return { color: colorOf(field, hints, value === undefined ? null : (value as string | null), -1), striped }\n}\n","import type { FieldModel, FieldViewModel } from '@protobase/schema'\nimport { cn } from '../../../../lib/cn'\nimport { withinBar, type TimelineBar } from './timeline-layout'\nimport { segmentPaint, stripes, type SegmentPaint } from './timeline-paint'\n\n/** A swatch or segment's fill: its tone's class or colour, with stripes while it waits. */\nexport const paintStyle = (paint: SegmentPaint) => ({ ...(paint.color !== undefined && { backgroundColor: paint.color }), ...(paint.striped && { backgroundImage: stripes }) })\n\n/** A bar's segments, each where its time falls in the bar and filled as its `color` value says. */\nexport const SegmentFill = ({ bar, field, hints }: { bar: TimelineBar; field: FieldModel; hints: FieldViewModel | undefined }) =>\n bar.segments.map((segment, index) => {\n const paint = segmentPaint(field, hints, segment.value)\n const { left, width } = withinBar(bar, segment)\n return <span key={index} aria-hidden=\"true\" className={cn('absolute inset-y-0', paint.className)} style={{ left: `${left}%`, width: `${width}%`, ...paintStyle(paint) }} />\n })\n","import type { ResourceModel, ViewModel } from '@protobase/schema'\nimport { formatDate, formatDateTime } from '../../../../format/date'\nimport { displayValue } from '../../../../live/display-value'\nimport { text } from '../../messages'\nimport type { TimelineBar, TimelineFields, TimelineSegment } from './timeline-layout'\n\nconst timeOf = (ms: number, dated: boolean) => (dated ? formatDate(ms) : formatDateTime(ms))\n\n/** \"14 Nov 2026, 09:00 – 14 Nov 2026, 11:30\", or \"… – now\" while it runs: from `start` to `end`, in the type of `fields.start`. */\nexport const rangeText = (model: ResourceModel, fields: TimelineFields, start: number, end: number, open: boolean) => {\n const dated = model.fields[fields.start]?.type === 'date'\n return text('timelineRange', { from: timeOf(start, dated), to: open ? text('timelineNow') : timeOf(end, dated) })\n}\n\n/** A segment's value and times, as one line. */\nexport const segmentText = (segment: TimelineSegment, model: ResourceModel, view: ViewModel | undefined, fields: TimelineFields) =>\n `${displayValue(model.fields[fields.color]!, segment.value, view?.fields[fields.color])}: ${rangeText(model, fields, segment.start, segment.end, segment.open)}`\n\n/** What a bar reads as to a screen reader: its name, its value as shown without one, and times, then each segment's. */\nexport const barText = (bar: TimelineBar, model: ResourceModel, view: ViewModel | undefined, fields: TimelineFields, known?: string) => {\n const open = bar.segments.some((segment) => segment.open && segment.end === bar.end)\n const name = known ?? displayValue(model.fields[fields.bar]!, bar.value, view?.fields[fields.bar])\n return [`${name}: ${rangeText(model, fields, bar.start, bar.end, open)}`, ...bar.segments.map((segment) => segmentText(segment, model, view, fields))].join('; ')\n}\n","import type { ResourceModel, ViewModel } from '@protobase/schema'\nimport { cn } from '../../../../lib/cn'\nimport { RouteLink, type RouteTarget } from '../../../../primitives/route-link'\nimport { FieldValue } from '../../field-value'\nimport { useAdminMeta } from '../../../meta-gate'\nimport { useRelationTitle } from '../../../titles/use-relation-title'\nimport type { TimelineBar, TimelineFields, TimelineShape } from './timeline-layout'\nimport { TimelineAxis } from './timeline-axis'\nimport { SegmentFill } from './segment-fill'\nimport { barText } from './timeline-text'\n\n/** What the lanes draw with: the resource and its view, the fields by role, and what pointing at and choosing a bar do. */\nexport type LanesProps = {\n shape: TimelineShape\n model: ResourceModel\n view: ViewModel | undefined\n fields: TimelineFields\n /** What pointing at a bar and moving focus to it do; `null` when the pointer or focus leaves it. */\n point: { hover: (bar: TimelineBar | null) => void; focus: (bar: TimelineBar | null) => void }\n /** With `select`: where a bar leads, and the key of the bar chosen. */\n choose?: { barTo: (key: string) => RouteTarget; chosen: string | undefined }\n}\n\nconst barLook = 'absolute inset-y-0 flex overflow-hidden rounded-sm ring-offset-1 ring-offset-background outline-none hover:ring-2 hover:ring-border-strong focus-visible:ring-2 focus-visible:ring-primary'\n\n// One bar: its segments side by side within it, a link to the page with it chosen under `select`, else a mark that\n// can take focus, so a keyboard and a screen reader reach its times too\nconst BarMark = ({ bar, model, view, fields, point: on, choose }: Omit<LanesProps, 'shape'> & { bar: TimelineBar }) => {\n // A bar of a relation is named by the record it points at, as its readout shows it\n const target = useAdminMeta().resources[model.fields[fields.bar]?.relation?.resource ?? '']\n const name = useRelationTitle(target ?? model, bar.key, target !== undefined)\n const label = barText(bar, model, view, fields, target ? name : undefined)\n const point = { onMouseEnter: () => on.hover(bar), onMouseLeave: () => on.hover(null), onFocus: () => on.focus(bar), onBlur: () => on.focus(null) }\n const style = { left: `${bar.left}%`, width: `max(${bar.width}%, 4px)` }\n const segments = <SegmentFill bar={bar} field={model.fields[fields.color]!} hints={view?.fields[fields.color]} />\n if (!choose) {\n return (\n <span role=\"img\" tabIndex={0} aria-label={label} style={style} className={barLook} {...point}>\n {segments}\n </span>\n )\n }\n const chosen = choose.chosen === bar.key\n return (\n <RouteLink to={choose.barTo(bar.key)} aria-label={label} aria-current={chosen ? 'true' : undefined} style={style} className={cn(barLook, chosen && 'ring-2 ring-foreground')} {...point}>\n {segments}\n </RouteLink>\n )\n}\n\n/**\n * A lane per value of `lane`, its name beside its bars from a phone's width up and above them on a phone, its bars in\n * as many rows as keep them apart in time, under an axis of the whole time. The bars are placed as a share of the\n * width, so the timeline always fits the page and never scrolls sideways.\n */\nexport const TimelineLanes = ({ shape, ...props }: LanesProps) => {\n const { model, fields } = props\n const laneField = model.fields[fields.lane]!\n return (\n <div className=\"flex flex-col gap-2\">\n <div className=\"flex sm:pl-40\">\n <TimelineAxis from={shape.from} to={shape.to} dated={model.fields[fields.start]?.type === 'date'} />\n </div>\n <ul className=\"flex flex-col gap-3 sm:gap-2\">\n {shape.lanes.map((lane) => (\n <li key={lane.key} className=\"flex flex-col gap-1 sm:flex-row sm:items-center\">\n <div className=\"min-w-0 truncate text-sm font-medium sm:w-40 sm:shrink-0 sm:pr-3\">\n <FieldValue model={model} field={laneField} value={lane.value} />\n </div>\n <div className=\"flex min-w-0 flex-1 flex-col gap-1 border-l border-border pl-px\">\n {lane.rows.map((row, index) => (\n <div key={index} className=\"relative h-6 overflow-x-clip\">\n {row.map((bar) => (\n <BarMark key={bar.key} bar={bar} {...props} />\n ))}\n </div>\n ))}\n </div>\n </li>\n ))}\n </ul>\n </div>\n )\n}\n","import type { ResourceModel, ViewModel } from '@protobase/schema'\nimport { displayValue } from '../../../../live/display-value'\nimport { FieldValue } from '../../field-value'\nimport { text } from '../../messages'\nimport { paintStyle } from './segment-fill'\nimport type { TimelineBar, TimelineFields } from './timeline-layout'\nimport { segmentPaint } from './timeline-paint'\nimport { rangeText } from './timeline-text'\nimport { cn } from '../../../../lib/cn'\n\ntype ReadoutProps = { bar: TimelineBar | null; model: ResourceModel; view: ViewModel | undefined; fields: TimelineFields }\n\n/** A value's colour, as a small square beside its name. */\nconst Swatch = ({ model, view, fields, value }: Omit<ReadoutProps, 'bar'> & { value: unknown }) => {\n const paint = segmentPaint(model.fields[fields.color]!, view?.fields[fields.color], value)\n return <span aria-hidden=\"true\" className={cn('inline-block size-3 shrink-0 rounded-sm', paint.className)} style={paintStyle(paint)} />\n}\n\n/** What each colour of a bar means: the `color` field's values the bars hold, in the enum's order, the waits striped. */\nexport const TimelineLegend = ({ values, ...props }: Omit<ReadoutProps, 'bar'> & { values: ReadonlySet<string> }) => {\n const field = props.model.fields[props.fields.color]!\n const shown = (field.enumValues ?? []).filter((value) => values.has(value))\n return (\n <ul className=\"flex flex-wrap gap-x-4 gap-y-1.5 text-xs text-muted-foreground\">\n {shown.map((value) => (\n <li key={value} className=\"flex items-center gap-1.5\">\n <Swatch {...props} value={value} />\n {displayValue(field, value, props.view?.fields[props.fields.color])}\n </li>\n ))}\n </ul>\n )\n}\n\n/** The bar pointed at: its value and times, then each segment's value and times; a hint while none is. */\nexport const TimelineReadout = ({ bar, ...props }: ReadoutProps) => {\n const { model, view, fields } = props\n if (!bar) return <p className=\"text-sm text-muted-foreground\">{text('timelinePoint')}</p>\n const open = bar.segments.some((segment) => segment.open && segment.end === bar.end)\n return (\n <div className=\"flex flex-col gap-1 text-sm\">\n <p className=\"flex flex-wrap items-baseline gap-x-2\">\n <span className=\"font-medium\">\n <FieldValue model={model} field={model.fields[fields.bar]!} value={bar.value} />\n </span>\n <span className=\"text-muted-foreground tabular-nums\">{rangeText(model, fields, bar.start, bar.end, open)}</span>\n </p>\n <ul className=\"flex flex-col gap-0.5 text-xs text-muted-foreground\">\n {bar.segments.map((segment, index) => (\n <li key={index} className=\"flex items-center gap-1.5 tabular-nums\">\n <Swatch {...props} value={segment.value} />\n {displayValue(model.fields[fields.color]!, segment.value, view?.fields[fields.color])}: {rangeText(model, fields, segment.start, segment.end, segment.open)}\n </li>\n ))}\n </ul>\n </div>\n )\n}\n","import { keepPreviousData, useQuery } from '@tanstack/react-query'\nimport type { Client } from '@protobase/client'\nimport type { ResourceModel } from '@protobase/schema'\nimport { useClient } from '../../../../data/api-provider'\nimport { keys } from '../../../../data/query-keys'\n\n// The list API's largest page\nconst pageSize = 500\n\ntype Row = Record<string, unknown>\n\nexport type TimelineRowsRequest = { filter?: string; sort: string; fields: string[]; limit: number }\n\n/** A timeline's records, as many as `limit`, and whether more match than that. */\nexport type TimelineRows = { rows: Row[]; cut: boolean }\n\n/**\n * Every record that matches `filter`, page after page in `sort` order up to `limit`, then the earliest first; `cut`\n * when more remain. It reads only the fields the timeline draws, and no ETags.\n */\nexport const timelineRowsQuery = (client: Client, model: ResourceModel, { filter = '', sort, fields, limit }: TimelineRowsRequest) => ({\n queryKey: [...keys.list(model.name, filter, sort, limit, 'timeline'), fields.join(',')],\n queryFn: async (): Promise<TimelineRows> => {\n const rows: Row[] = []\n let pageToken: string | undefined\n do {\n const page = await client.list(model.name, { filter: filter || undefined, orderBy: sort, pageSize: Math.min(pageSize, limit - rows.length), fields, etag: false, ...(pageToken && { pageToken }) })\n rows.push(...(page.items as Row[]))\n pageToken = page.nextPageToken || undefined\n } while (pageToken && rows.length < limit)\n return { rows: rows.toReversed(), cut: pageToken !== undefined }\n },\n})\n\n/** A timeline's records, as `timelineRowsQuery` reads them; the records before stay on screen while newer ones load. */\nexport const useTimelineRows = (model: ResourceModel, { enabled = true, ...request }: TimelineRowsRequest & { enabled?: boolean }) =>\n useQuery({ ...timelineRowsQuery(useClient(), model, request), enabled, placeholderData: keepPreviousData })\n","import { useState, type ReactNode } from 'react'\nimport { defaultTimelineLimit, timelineReadSort, timelineSort, type Styled, type TimelineProps } from '@protobase/layout'\nimport type { FieldModel, ResourceModel, ViewModel } from '@protobase/schema'\nimport { Skeleton } from '../../../../primitives/skeleton'\nimport { ErrorBanner } from '../../../error-banner'\nimport { GuardedParams } from '../../../guarded-params'\nimport { useAdminMeta } from '../../../meta-gate'\nimport { cn } from '../../../../lib/cn'\nimport { groupFilter } from '../../../charts/chart-groups'\nimport { text } from '../../messages'\nimport { usePageParams } from '../../page-params'\nimport { usePlanned } from '../../plan-reads'\nimport { propsOf, type BlockProps } from '../block-props'\nimport { CardFrame, Quiet } from '../card-frame'\nimport { ChosenRecord } from '../chosen-record'\nimport { barIdOf, barIn, type BarId } from './bar-identity'\nimport { timelineShape, type TimelineBar, type TimelineFields } from './timeline-layout'\nimport { TimelineLanes, type LanesProps } from './timeline-lanes'\nimport { TimelineLegend, TimelineReadout } from './timeline-readout'\nimport { useTimelineRows } from './use-timeline-rows'\n\ntype LoadedProps = Omit<TimelineProps, 'resource' | 'actions' | 'children' | 'select' | 'lane' | 'bar' | 'start' | 'end' | 'color'> & {\n model: ResourceModel\n view: ViewModel | undefined\n fields: TimelineFields\n /** The order it reads its records in, the latest first, so a limit leaves out the oldest. */\n readSort: string\n /** The order the chosen bar's first record is found in. */\n sort: string\n at?: string\n actions: ReactNode\n className?: string\n choose?: LanesProps['choose']\n details?: ReactNode\n}\n\n// Its records from the page's planned read, or a read of its own page after page up to its limit, drawn as lanes with\n// what the bar pointed at holds under them; a limit that leaves records out says how many it shows\nconst LoadedTimeline = ({ model, view, fields, readSort, at, filter, limit = defaultTimelineLimit, title, description, empty, actions, className, choose, details }: LoadedProps) => {\n // The bar under the pointer shows over the one with focus, which shows again once the pointer leaves; each is kept\n // by its identity and found in the current data, so the readout follows a refresh and drops a bar that is gone\n const [hovered, setHovered] = useState<BarId | null>(null)\n const [focused, setFocused] = useState<BarId | null>(null)\n const idOf = (bar: TimelineBar | null) => (bar ? barIdOf(bar) : null)\n const point = { hover: (bar: TimelineBar | null) => setHovered(idOf(bar)), focus: (bar: TimelineBar | null) => setFocused(idOf(bar)) }\n const planned = usePlanned(at)\n const own = useTimelineRows(model, { filter, sort: readSort, fields: [...new Set([...Object.values(fields), ...model.primaryKey])], limit, enabled: !planned })\n const page = planned ?? own\n const rows = planned ? planned.rows : (own.data?.rows ?? [])\n const cut = !planned && own.data?.cut === true\n const shape = timelineShape(rows, fields, Date.now())\n const body = () => {\n if (page.isPending) return <div className=\"flex flex-col gap-2\">{Array.from({ length: 3 }, (_, index) => <Skeleton key={index} className=\"h-6\" />)}</div>\n if (page.error) return <ErrorBanner title={text('couldNotLoad')} error={page.error} />\n if (shape.lanes.length === 0) return <Quiet>{empty ?? text('nothingYet')}</Quiet>\n const values = new Set(rows.map((row) => String(row[fields.color])))\n return (\n <div className=\"flex flex-col gap-4\">\n <TimelineLegend model={model} view={view} fields={fields} values={values} />\n <TimelineLanes shape={shape} model={model} view={view} fields={fields} point={point} {...(choose && { choose })} />\n {cut && <Quiet>{text('timelineCut', { count: rows.length })}</Quiet>}\n <div aria-live=\"polite\">\n <TimelineReadout bar={barIn(shape, hovered) ?? barIn(shape, focused)} model={model} view={view} fields={fields} />\n </div>\n </div>\n )\n }\n return (\n <CardFrame title={title} description={description} actions={actions} className={cn('h-full', className)}>\n {body()}\n {details}\n </CardFrame>\n )\n}\n\n// The bar a key names, as its `bar` field holds it: a number for an integer field, the text otherwise, as the API\n// gives a bigint or decimal, whose digits a number would round\nconst barValue = (field: FieldModel, key: string) => (field.type === 'integer' ? Number(key) : key)\n\n/** A timeline whose bars each link to the page with that bar's value in the parameter `select`, and the chosen bar's children under it. */\nconst SelectTimeline = ({ select, children, ...props }: LoadedProps & { select: string; children: ReactNode[] }) => {\n const { given, linkTo } = usePageParams()\n const key = given[select]\n const barTo = (barKey: string) => linkTo({ [select]: barKey })\n const field = props.model.fields[props.fields.bar]!\n // The chosen bar's first record among those the timeline shows; a form under it asks before another bar replaces it\n const details =\n key === undefined ? null : (\n <GuardedParams name={select}>\n <ChosenRecord key={key} model={props.model} query={{ filter: groupFilter(field, barValue(field, key), props.filter), sort: props.sort }}>\n {children}\n </ChosenRecord>\n </GuardedParams>\n )\n return <LoadedTimeline {...props} choose={{ barTo, chosen: key }} details={details} />\n}\n\n/**\n * Records as a timeline: a lane per `lane` value, a bar per `bar` value in it, each record a segment from `start` to\n * `end` coloured by its `color` value, the bar pointed at with its times under them. With `select`, a bar leads to the\n * page with it chosen, and the chosen bar's first record draws the children under the timeline.\n */\nexport const TimelineBlock = ({ node, at, slots, children, className }: BlockProps) => {\n const { className: _className, resource, select, lane, bar, start, end, color, children: _children, ...props } = propsOf<TimelineProps & Styled>(node)\n const { resources, views } = useAdminMeta()\n const model = resources[resource]\n if (!model) return null\n const loaded = { ...props, model, view: views[model.name], fields: { lane, bar, start, end, color }, readSort: timelineReadSort(node), sort: timelineSort(node), ...(at !== undefined && { at }), actions: slots.actions, className }\n if (select === undefined) return <LoadedTimeline {...loaded} />\n return (\n <SelectTimeline {...loaded} select={select}>\n {children}\n </SelectTimeline>\n )\n}\n","import type { ReactNode } from 'react'\nimport { selectOf, type LayoutNode } from '@protobase/layout'\nimport { GuardedParams } from '../guarded-params'\nimport { useAdminMeta } from '../meta-gate'\nimport { ChosenRecord } from './blocks/chosen-record'\nimport { usePageParamsIfAny } from './page-params'\n\n/**\n * A custom component's children inside the record its `select` chose, read by the key the page's address holds;\n * nothing while none is chosen. Without `select`, its children as they are.\n */\nexport const CustomChosen = ({ node, children }: { node: LayoutNode; children: ReactNode }) => {\n const selection = selectOf(node)\n const params = usePageParamsIfAny()\n const { resources } = useAdminMeta()\n if (!selection || !params) return children\n const key = params.given[selection.param]\n const model = selection.resource === undefined ? undefined : resources[selection.resource]\n if (key === undefined || !model) return null\n // A form under it asks before another choice replaces it\n return (\n <GuardedParams name={selection.param}>\n <ChosenRecord key={key} model={model} query={{ key }} className=\"\">\n {children}\n </ChosenRecord>\n </GuardedParams>\n )\n}\n","import { graphShape, type GraphFields, type GraphProps } from '@protobase/layout'\nimport { lazy, Suspense, useMemo } from 'react'\nimport { cn } from '../../../../lib/cn'\nimport { Spinner } from '../../../../primitives/spinner'\nimport { ErrorBanner } from '../../../error-banner'\nimport { useElementReads, type ComponentSelect } from '../../component-reads'\nimport { CustomChosen } from '../../custom-chosen'\nimport { text } from '../../messages'\nimport { usePageParamsIfAny } from '../../page-params'\nimport { propsOf, type BlockProps } from '../block-props'\nimport { Quiet } from '../card-frame'\n\n// The drawing library is a chunk of its own, which loads only when a graph draws\nconst GraphView = lazy(() => import('./graph-view').then((module) => ({ default: module.GraphView })))\n\nconst loading = (\n <div className=\"flex h-64 w-full items-center justify-center\">\n <Spinner />\n </div>\n)\n\n/**\n * The `Graph` block: the records of `nodes` as boxes, each in the region of its `group` and coloured by its `status`,\n * drawing `node` inside its record where the graph has one, and the records of `edges` as arrows between them, from the\n * reads the page's plan made. With `select`, each node links to the page with it chosen, and the children draw beside\n * the graph, inside the chosen node's record, or under it on a narrow screen. A read that fails draws its fallback.\n */\nexport const GraphBlock = ({ node, at, slots, children, className }: BlockProps) => {\n const props = propsOf<GraphProps>(node)\n const reads = useElementReads(node, at)\n const params = usePageParamsIfAny()\n const nodes = reads.nodes\n const edges = reads.edges\n const { label, group, status, source, target } = props\n const fields: GraphFields = useMemo(() => ({ label, source, target, ...(group !== undefined && { group }), ...(status !== undefined && { status }) }), [label, source, target, group, status])\n // The rows are new arrays on each render; the same records make the same shape, laid out once\n const signature = JSON.stringify([nodes?.rows, edges?.rows, fields])\n const shape = useMemo(() => nodes && edges && graphShape({ nodes: nodes.rows, edges: edges.rows, key: nodes.model.primaryKey[0]!, edgeKey: edges.model.primaryKey, fields }), [signature])\n if (!nodes || !edges || !shape) return null\n const error = nodes.error ?? edges.error\n // Its fallback stands in where it declares one, as for a component that throws\n if (error && node.fallback) throw error\n if (error) return <ErrorBanner title={text('couldNotLoad')} error={error} />\n if (nodes.isPending || edges.isPending) return loading\n if (shape.nodes.length === 0) return <Quiet>{props.empty ?? text('nothingYet')}</Quiet>\n const param = props.select\n const select: ComponentSelect | undefined = param !== undefined && params ? { chosen: params.given[param], linkTo: (key) => params.linkTo({ [param]: key }) } : undefined\n return (\n <div className={cn('flex flex-col gap-4 lg:flex-row', className)}>\n <div className=\"min-w-0 flex-1\">\n <Suspense fallback={loading}>\n <GraphView shape={shape} nodes={nodes} edges={edges} fields={fields} props={props} {...(select && { select })} {...(props.node !== undefined && { content: slots.node })} />\n </Suspense>\n </div>\n {/* The children draw once a node is chosen, inside its record */}\n {children.length > 0 && select?.chosen !== undefined && (\n <div className=\"min-w-0 lg:w-80 lg:shrink-0\">\n <CustomChosen node={node}>{children}</CustomChosen>\n </div>\n )}\n </div>\n )\n}\n","import { messages } from '../../locale/messages'\n\nexport const text = messages('app/conversation')\n","import { useState } from 'react'\nimport { Composer } from '../../chat'\nimport { useClient } from '../../data/api-provider'\nimport { ErrorBanner } from '../error-banner'\nimport { useAdminMeta, usePermissions } from '../meta-gate'\nimport { can } from '../permissions'\nimport { useRefreshResource } from '../pages/use-layout-data'\nimport { text } from './messages'\n\nexport type MessageComposerProps = {\n resource: string\n /** The text field the message goes in. */\n field: string\n /** Values sent with every message, such as the record's key in its relation. */\n values?: Record<string, unknown>\n placeholder?: string\n}\n\n/** A box that sends a message: each send creates a record of `resource` with the text in `field` and the `values`, for a user who may create one. */\nexport const MessageComposer = ({ resource, field, values, placeholder }: MessageComposerProps) => {\n const { resources } = useAdminMeta()\n const client = useClient()\n const refresh = useRefreshResource()\n const permissions = usePermissions(resource)\n const [sending, setSending] = useState(false)\n const [failure, setFailure] = useState<unknown>()\n if (!resources[resource] || !can(permissions, 'create')) return null\n\n // The text stays in the box until the server took it, so a refused message can be sent again\n const send = async (message: string) => {\n setSending(true)\n setFailure(undefined)\n const sent = await client.create(resource, { ...values, [field]: message }).then(\n () => true,\n (error: unknown) => {\n setFailure(error)\n return false\n },\n )\n setSending(false)\n if (sent) void refresh(resource)\n return sent\n }\n\n return (\n <div className=\"flex flex-col gap-2\">\n {failure !== undefined && <ErrorBanner title={text('notSent')} error={failure} />}\n <Composer onSend={send} busy={sending} placeholder={placeholder} />\n </div>\n )\n}\n","import type { ComposerProps } from '@protobase/layout'\nimport { MessageComposer } from '../../conversation/message-composer'\nimport { propsOf, type BlockProps } from './block-props'\n\n/** A box that sends a message: each send creates a record of `resource` with the text in `field` and the `values`. */\nexport const ComposerBlock = ({ node }: BlockProps) => {\n const { resource, field, values, placeholder } = propsOf<ComposerProps>(node)\n return <MessageComposer resource={resource} field={field} values={values} placeholder={placeholder} />\n}\n","import type { DetailsProps } from '@protobase/layout'\nimport { cn } from '../../../lib/cn'\nimport { propsOf, type BlockProps } from './block-props'\n\n/** HTML's <details>: the browser opens and closes it on a click of its summary, with no script. */\nexport const DetailsBlock = ({ node, children, className }: BlockProps) => {\n const { open } = propsOf<DetailsProps>(node)\n return (\n <details open={open} className={cn('[&[open]>summary]:mb-2', className)}>\n {children}\n </details>\n )\n}\n\n/** The line of a `Details` that is always shown, which opens and closes it. */\nexport const SummaryBlock = ({ children, className }: BlockProps) => <summary className={cn('cursor-pointer font-medium', className)}>{children}</summary>\n","import type { DiffProps } from '@protobase/layout'\nimport { DiffView } from '../../../diff-view/diff-view'\nimport { parsePatch } from '../../../diff-view/patch'\nimport { cn } from '../../../lib/cn'\nimport { Skeleton } from '../../../primitives/skeleton'\nimport { useScopedPathValue } from '../use-path-value'\nimport { propsOf, type BlockProps } from './block-props'\n\n/** A stored unified patch, each file drawn by `DiffView`; text that is no patch as it is, `emptyText` for an empty field. */\nexport const DiffBlock = ({ node, className }: BlockProps) => {\n const { source, emptyText } = propsOf<DiffProps>(node)\n const read = useScopedPathValue(source)\n if (read.state === 'missing') return null\n if (read.state === 'loading') return <Skeleton className={cn('h-24 w-full', className)} />\n if (read.value === null || read.value === undefined || read.value === '') return emptyText ? <p className={cn('text-sm text-muted-foreground', className)}>{emptyText}</p> : null\n const text = String(read.value)\n const files = parsePatch(text)\n if (!files) return <pre className={cn('overflow-x-auto whitespace-pre-wrap break-words rounded-md border border-border bg-background p-3 font-mono text-[0.6875rem] leading-[18px]', className)}>{text}</pre>\n return (\n <div className={cn('flex flex-col gap-3', className)}>\n {files.map((file, index) => (\n <DiffView key={`${index}-${file.path}`} source={file.lines} path={file.path} split className=\"rounded-md border border-border\" />\n ))}\n </div>\n )\n}\n","/** An `ArrayField` item's value as text, which no field describes: a list or object as JSON, nothing for none. */\nexport const plainText = (value: unknown) => (value === null || value === undefined ? '' : typeof value === 'object' ? JSON.stringify(value) : String(value))\n","import type { FieldProps } from '@protobase/layout'\nimport { humanize } from '../../../live/naming'\nimport { Skeleton } from '../../../primitives/skeleton'\nimport { useAdminMeta } from '../../meta-gate'\nimport { FieldValue } from '../field-value'\nimport { useScopedPathValue } from '../use-path-value'\nimport { cn } from '../../../lib/cn'\nimport { plainText } from './plain-value'\nimport { propsOf, type BlockProps } from './block-props'\n\n/** The view's label for the field at the end of the path, else the path in words: `companyId.city` is \"Company city\". */\nexport const fieldLabel = (path: string, viewLabel: string | undefined) => {\n if (viewLabel) return viewLabel\n const words = path.split('.').map((part) => humanize(part).toLowerCase()).join(' ')\n return words[0]!.toUpperCase() + words.slice(1)\n}\n\n/** A label over a value of the record around it; `label={false}` shows the value alone. */\nexport const FieldBlock = ({ node, className }: BlockProps) => {\n const { source, label, format } = propsOf<FieldProps>(node)\n const { views } = useAdminMeta()\n const value = useScopedPathValue(source)\n if (value.state === 'missing') return null\n const shown =\n value.state === 'loading' ? <Skeleton className=\"h-4 w-24\" /> : value.state === 'plain' ? plainText(value.value) : <FieldValue model={value.model} field={value.field} value={value.value} format={format} />\n if (label === false) return <div className={className}>{shown}</div>\n const text = label ?? fieldLabel(source, value.state === 'ready' ? views[value.model.name]?.fields[value.field.name]?.label : undefined)\n return (\n <div className={cn('min-w-0', className)}>\n <div className=\"text-body text-muted-foreground\">{text}</div>\n <div className=\"mt-0.5 truncate\">{shown}</div>\n </div>\n )\n}\n","import type { GridProps, GridSpan, LayoutChild } from '@protobase/layout'\nimport { cn } from '../../../lib/cn'\nimport { propsOf, type BlockProps } from './block-props'\n\nconst columns = { 1: '', 2: 'md:grid-cols-2', 3: 'md:grid-cols-2 xl:grid-cols-3', 4: 'sm:grid-cols-2 xl:grid-cols-4' }\n// Numbers are small enough to sit two to a row on a phone; an odd last one sits alone at half width.\nconst statColumns = { 1: '', 2: 'grid-cols-2', 3: 'grid-cols-2 xl:grid-cols-3', 4: 'grid-cols-2 xl:grid-cols-4' }\nconst spans: Record<GridSpan, string> = { 1: '', 2: 'md:col-span-2', 3: 'md:col-span-2 xl:col-span-3', 4: 'sm:col-span-2 md:col-span-2 xl:col-span-4' }\n\nconst isStat = (child: LayoutChild) => typeof child === 'object' && !child.custom && child.type === 'Stat'\n\n/** Columns that collapse to one on a phone, or two when it holds only `Stat`s; a child's `span` makes it wider. */\nexport const GridBlock = ({ node, children, className }: BlockProps) => {\n const { columns: count = 2 } = propsOf<GridProps>(node)\n const childNodes = node.children\n const stats = childNodes.length > 0 && childNodes.every(isStat)\n return (\n <div className={cn('grid grid-cols-1 gap-4', stats ? statColumns[count] : columns[count], className)}>\n {children.map((child, index) => {\n const element = childNodes[index]\n const span = typeof element === 'object' ? (element.props.span as GridSpan | undefined) : undefined\n return (\n <div key={index} className={cn('min-w-0', span && spans[span])}>\n {child}\n </div>\n )\n })}\n </div>\n )\n}\n","/** A fixed picture at `src`, as a plain `<img>` carrying the block's classes, at its `width` and `height` when given. */\nexport const FixedImage = ({ src, alt, width, height, className }: { src: string; alt?: string; width?: number; height?: number; className?: string }) => (\n <img src={src} alt={alt ?? ''} width={width} height={height} className={className ?? 'max-w-full'} />\n)\n","import type { Theme } from '../../../theme/theme-preference'\n\n/** How far apart the widths a block without its own `width` asks for are, so resizing the window refetches only now and then. */\nexport const widthStep = 100\n\n/**\n * The query an `Image` asks its function with: its own `width`, or the space it has rounded up to the next step, its\n * `height` when it has one, and the theme it is drawn in. `undefined` until the space it has is measured.\n */\nexport const imageQuery = ({ width, height, space, theme }: { width?: number; height?: number; space: number; theme: Theme }) => {\n const asked = width ?? Math.ceil(space / widthStep) * widthStep\n if (asked === 0) return\n return { width: String(asked), ...(height !== undefined && { height: String(height) }), theme }\n}\n\n/**\n * When the picture is asked for again: every `refresh` seconds, and never because the window regains focus or the block\n * mounts again, so without `refresh` each query is asked for once.\n */\nexport const imageRefetch = (refresh?: number) => ({\n staleTime: Infinity,\n refetchOnWindowFocus: false,\n ...(refresh !== undefined && { refetchInterval: refresh * 1000 }),\n})\n\n/** Whether a function's answer is a picture an `<img>` can draw: a `Blob` of an `image/*` type. */\nexport const isPicture = (answer: unknown): answer is Blob => answer instanceof Blob && answer.type.startsWith('image/')\n","import { keepPreviousData, useQuery } from '@tanstack/react-query'\nimport { useEffect, useState } from 'react'\nimport type { ImageProps } from '@protobase/layout'\nimport { useClient } from '../../../data/api-provider'\nimport { keys } from '../../../data/query-keys'\nimport { useElementWidth } from '../../../focus-page/use-element-width'\nimport { Skeleton } from '../../../primitives/skeleton'\nimport { useTheme } from '../../../theme/theme-provider'\nimport { cn } from '../../../lib/cn'\nimport { propsOf, type BlockProps } from './block-props'\nimport { FixedImage } from './fixed-image'\nimport { imageQuery, imageRefetch, isPicture } from './image-query'\n\n/** A URL the `<img>` loads a fetched picture from, given back to the browser once another replaces it or the block goes. */\nconst useObjectUrl = (blob: Blob | undefined) => {\n const [url, setUrl] = useState<string>()\n useEffect(() => {\n if (!blob) return setUrl(undefined)\n const next = URL.createObjectURL(blob)\n setUrl(next)\n return () => URL.revokeObjectURL(next)\n }, [blob])\n return url\n}\n\n/** Whether the browser failed to draw the picture at `url`, such as a damaged file; a new `url` is tried again. */\nconst useBroken = (url: string | undefined) => {\n const [broken, setBroken] = useState<string>()\n return [broken !== undefined && broken === url, () => setBroken(url)] as const\n}\n\n/**\n * The picture an API function draws, fetched with the reader's token at the block's size, or the width it has, and the\n * page's theme, again every `refresh` seconds. The previous picture stays while the next loads. A function that refuses\n * or answers no picture, also on a later request, or a picture the browser cannot draw, leaves its `alt`, or nothing.\n */\nconst FunctionImage = ({ name, alt, width, height, refresh, className }: { name: string; alt?: string; width?: number; height?: number; refresh?: number; className?: string }) => {\n const client = useClient()\n const { theme } = useTheme()\n const [ref, space] = useElementWidth()\n const query = imageQuery({ width, height, space, theme })\n const picture = useQuery({\n queryKey: keys.image(name, query ?? {}),\n enabled: query !== undefined,\n placeholderData: keepPreviousData,\n ...imageRefetch(refresh),\n queryFn: async () => {\n // The picture is the caller's own: the browser's HTTP cache keeps it from no later user of the browser.\n const answer = await client.invoke(name, { query, cache: 'no-store' })\n if (!isPicture(answer)) throw new Error(`The function \"${name}\" answered no picture`)\n return answer\n },\n })\n const url = useObjectUrl(picture.data)\n const [broken, markBroken] = useBroken(url)\n const size = { ...(width !== undefined && { width }), ...(height !== undefined && { height }) }\n return (\n <div ref={ref} className={cn('min-w-0', className)}>\n {picture.isError || broken ? (\n alt && <p className=\"text-muted-foreground\">{alt}</p>\n ) : url ? (\n <img src={url} alt={alt ?? ''} onError={markBroken} style={size} className={width === undefined ? 'w-full max-w-full object-contain' : 'max-w-full object-contain'} />\n ) : (\n <Skeleton className=\"w-full max-w-full\" style={{ height: height ?? 160, ...(width !== undefined && { width }) }} />\n )}\n </div>\n )\n}\n\n/** A fixed picture at `src`, or the one an API function draws. */\nexport const ImageBlock = ({ node, className }: BlockProps) => {\n const props = propsOf<ImageProps>(node)\n if (props.src !== undefined) return <FixedImage src={props.src} alt={props.alt} width={props.width} height={props.height} className={className} />\n return <FunctionImage name={props.function} alt={props.alt} width={props.width} height={props.height} refresh={props.refresh} className={className} />\n}\n","import type { ReactNode } from 'react'\nimport { booleanFieldText, dateFieldText, isEmptyFieldValue, numberFieldText, safeFieldUrl, textFieldText, type BooleanFieldProps, type DateFieldProps, type InlineFieldProps, type NumberFieldProps, type UrlFieldProps } from '@protobase/layout'\nimport { enumLabel, type FieldModel, type FieldViewModel } from '@protobase/schema'\nimport { formatRelativeTime } from '../../../format/date'\nimport { formatTag } from '../../../locale/active-locale'\nimport { text as message } from '../../../live/messages'\nimport { Skeleton } from '../../../primitives/skeleton'\nimport { TrueMark } from '../../../primitives/true-mark'\nimport { useAdminMeta } from '../../meta-gate'\nimport { ValueBadge } from '../../value-badge'\nimport { useScopedPathValue } from '../use-path-value'\nimport { propsOf, type BlockProps } from './block-props'\n\n// React-admin's field components: one value of the records around them, inline, formatted as react-admin formats it.\n\n// `field` is missing for an item of a JSON list, which no model describes\ntype Shown = { value: unknown; field: FieldModel | undefined; hints: FieldViewModel | undefined; props: InlineFieldProps }\n\n/** A field component: its value drawn by `show`, `emptyText` when empty, and nothing while there is no value to read. */\nconst inlineField = (show: (shown: Shown) => ReactNode) =>\n function InlineFieldBlock({ node, className }: BlockProps) {\n const props = propsOf<InlineFieldProps>(node)\n const { views } = useAdminMeta()\n const read = useScopedPathValue(props.source)\n if (read.state === 'missing') return null\n if (read.state === 'loading') return <Skeleton className=\"inline-block h-3 w-16 align-middle\" />\n if (isEmptyFieldValue(node.type, read.value)) return props.emptyText ? <span className={className}>{props.emptyText}</span> : null\n if (read.state === 'plain') return <span className={className}>{show({ value: read.value, field: undefined, hints: undefined, props })}</span>\n return <span className={className}>{show({ value: read.value, field: read.field, hints: views[read.model.name]?.fields[read.field.name], props })}</span>\n }\n\n// An enum's value as its label, as everywhere else it is shown\nconst labelled = ({ value, field, hints }: Shown) => (field?.type === 'enum' && typeof value === 'string' ? enumLabel(value, hints?.valueLabels) : textFieldText(value))\n\nexport const TextFieldBlock = inlineField(labelled)\n\nexport const NumberFieldBlock = inlineField(({ value, props }) => <span className=\"tabular-nums\">{numberFieldText(value, props as NumberFieldProps, formatTag())}</span>)\n\nexport const DateFieldBlock = inlineField(({ value, props }) => {\n const shown = dateFieldText(value, props as DateFieldProps, { locale: formatTag(), now: Date.now(), relative: formatRelativeTime })\n return <time dateTime={String(value)}>{shown}</time>\n})\n\nexport const BooleanFieldBlock = inlineField(({ value, props }) => {\n const words = booleanFieldText(value as boolean, props as BooleanFieldProps, { yes: message('yes'), no: message('no') })\n return value ? <TrueMark label={words} className=\"align-middle\" /> : <span className=\"text-faint-foreground\">{words}</span>\n})\n\n// An address that could run code shows as text, not as a link\nexport const UrlFieldBlock = inlineField(({ value, props }) => {\n const url = String(value)\n const shown = (props as UrlFieldProps).content ?? url\n const safe = safeFieldUrl(url)\n if (safe === undefined) return shown\n return (\n <a href={safe} className=\"font-medium text-primary-text hover:underline\" {...(/^https?:/i.test(safe) && { target: '_blank', rel: 'noreferrer' })}>\n {shown}\n </a>\n )\n})\n\nexport const ChipFieldBlock = inlineField((shown) => (\n <ValueBadge value={shown.value} hints={shown.hints}>\n {labelled(shown)}\n </ValueBadge>\n))\n","import type { LinkProps } from '@protobase/layout'\nimport { appPath } from '@protobase/schema'\nimport { scopeLookup } from '@protobase/layout'\nimport { fillAddressFrom } from '@protobase/schema/internal'\nimport { AppLink } from '../../use-app-address'\nimport { usePageParamValues } from '../page-params'\nimport { useScopeStack, valueScopeOf } from '../record-scope'\nimport { cn } from '../../../lib/cn'\nimport { buttonClass } from '../../../primitives/button'\nimport { propsOf, type BlockProps } from './block-props'\n\nconst linkStyle = 'font-medium text-primary-text hover:underline'\n\n/**\n * `to` an address in the app, through the router, its `{{path}}`s filled from the records around it and the page's\n * parameters; an `href` (`mailto:`, `https:`) is an ordinary anchor. It shows its children, text and spans inline, else where it leads.\n */\nexport const LinkBlock = ({ node, children, className }: BlockProps) => {\n const props = propsOf<LinkProps>(node)\n const scope = { ...valueScopeOf(useScopeStack()), params: usePageParamValues() }\n // A button's look, to which classes add; otherwise classes of its own replace the link's look\n const style = props.variant ? cn(buttonClass({ variant: props.variant }), className) : (className ?? linkStyle)\n // Children that are only blank text show nothing, so the link shows where it leads instead\n const content = node.children.some((child) => typeof child !== 'string' || child.trim() !== '') ? children : undefined\n if (props.to) {\n const to = fillAddressFrom(props.to, scopeLookup(scope))\n return <AppLink to={to} className={style}>{content ?? appPath(to)}</AppLink>\n }\n const href = props.href ?? ''\n return <a href={href} className={style} {...(href.startsWith('http') && { target: '_blank', rel: 'noreferrer' })}>{content ?? href}</a>\n}\n","import type { ResourceModel } from '@protobase/schema'\nimport { differs, toDraft, toPatchValue } from '../../../live/field-values'\nimport { isChosen, type Draft } from '../../create/create-values'\n\ntype Row = Record<string, unknown>\n\n/** The literal defaults of new records, or the stored record's values; relations as `{ key, label }` once chosen. */\nexport const startingDraft = (model: ResourceModel, fields: string[], stored: Row | undefined): Draft =>\n Object.fromEntries(\n fields.map((name) => {\n const field = model.fields[name]!\n if (field.type === 'file') return [name, stored?.[name] ?? null]\n if (stored) return [name, field.type === 'boolean' ? Boolean(stored[name]) : toDraft(stored[name])]\n const fallback = field.default && 'value' in field.default ? field.default.value : undefined\n return [name, field.type === 'boolean' ? Boolean(fallback) : toDraft(fallback)]\n }),\n )\n\n/** Changed fields only; a chosen relation sends its key. */\nexport const editBody = (model: ResourceModel, draft: Draft, stored: Row) =>\n Object.fromEntries(\n Object.entries(draft).flatMap(([name, value]) => {\n const field = model.fields[name]!\n if (isChosen(value)) return value.key === toDraft(stored[name]) ? [] : [[name, field.type === 'integer' ? Number(value.key) : value.key]]\n return differs(field, value, stored[name]) ? [[name, toPatchValue(field, value)]] : []\n }),\n )\n","import { useState, type ReactNode } from 'react'\nimport type { ProblemError } from '@protobase/client'\nimport type { ModalFormProps } from '@protobase/layout'\nimport type { ResourceModel } from '@protobase/schema'\nimport { useClient } from '../../../data/api-provider'\nimport { humanize } from '../../../live/naming'\nimport { Button } from '../../../primitives/button'\nimport { Dialog } from '../../../primitives/dialog'\nimport { Field } from '../../../record-view'\nimport { useToast } from '../../../toasts'\nimport { createBody, isChosen } from '../../create/create-values'\nimport { ErrorBanner } from '../../error-banner'\nimport { fieldErrors, fieldMessage } from '../../field-errors'\nimport { useFocusFirstInvalid } from '../../use-focus-first-invalid'\nimport { FieldEditor } from '../../field-editor'\nimport { useAdminMeta, usePermissions } from '../../meta-gate'\nimport { can } from '../../permissions'\nimport { useNavigationGuard } from '../../router'\nimport { useLayoutRecord, type LayoutRecord } from '../record-scope'\nimport { useFirstRecord, useRefreshResource } from '../use-layout-data'\nimport { propsOf, type BlockProps } from './block-props'\nimport { editBody, startingDraft } from './form-draft'\nimport { text } from '../messages'\n\ntype FormProps = Omit<ModalFormProps, 'resource' | 'recordKey'> & { model: ResourceModel; record: LayoutRecord | undefined; onClose: () => void }\n\nconst ModalFormDialog = ({ model, record, mode, label, title, fields, values, onClose }: FormProps) => {\n const { resources, views } = useAdminMeta()\n const client = useClient()\n const toast = useToast()\n const refresh = useRefreshResource()\n const view = views[model.name]\n const [draft, setDraft] = useState(() => startingDraft(model, fields, record?.record))\n const [errors, setErrors] = useState<Record<string, ProblemError>>({})\n // How many saves the server turned down for their fields\n const [rejections, setRejections] = useState(0)\n const formRef = useFocusFirstInvalid<HTMLFormElement>(rejections)\n const [failure, setFailure] = useState<unknown>()\n const [saving, setSaving] = useState(false)\n // What is typed in the dialog, or being saved, is gone when the page is left\n const [touched, setTouched] = useState(false)\n useNavigationGuard(touched || saving, 'input-lost')\n\n const submit = async () => {\n setSaving(true)\n setFailure(undefined)\n const saved =\n mode === 'create'\n ? client.create(model.name, { ...createBody(model, resources, draft), ...values })\n : client.update(model.name, record!.key, editBody(model, draft, record!.record), record!.etag ?? '*')\n await saved.then(\n async () => {\n await refresh(model.name)\n toast.show({ state: 'success', title: text('saved', { label: title ?? label }) })\n onClose()\n },\n (error: unknown) => {\n const found = fieldErrors(error)\n setErrors(found)\n if (Object.keys(found).length > 0) setRejections((count) => count + 1)\n setFailure(error)\n },\n )\n setSaving(false)\n }\n\n return (\n <Dialog\n title={title ?? label}\n onClose={onClose}\n actions={\n <>\n <Button onClick={onClose}>{text('cancel')}</Button>\n <Button variant=\"primary\" loading={saving} onClick={() => void submit()}>\n {mode === 'create' ? text('create') : text('save')}\n </Button>\n </>\n }\n >\n <form\n ref={formRef}\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 && <ErrorBanner title={text('notSaved')} error={failure} />}\n {fields.map((name) => {\n const field = model.fields[name]!\n const value = draft[name]\n const target = field.relation ? resources[field.relation.resource] : undefined\n const label = view?.fields[name]?.label ?? humanize(name)\n const problem = errors[name]\n return (\n <Field key={name} name={name} label={label} help={view?.fields[name]?.help} error={problem && fieldMessage(field, label, problem)}>\n <FieldEditor\n field={field}\n hints={view?.fields[name]}\n value={isChosen(value) ? value.key : value}\n stored={record?.record[name]}\n relationLabel={isChosen(value) ? value.label : undefined}\n relationPicker={target ? { target, view: views[target.name] } : undefined}\n invalid={Boolean(errors[name])}\n resource={model.name}\n onChange={(next) => {\n setErrors(({ [name]: _, ...rest }) => rest)\n setTouched(true)\n setDraft((current) => ({ ...current, [name]: next }))\n }}\n />\n </Field>\n )\n })}\n </form>\n </Dialog>\n )\n}\n\nconst KeyedRecord = ({ model, recordKey, children }: { model: ResourceModel; recordKey: string; children: (record: LayoutRecord | undefined) => ReactNode }) => {\n const record = useFirstRecord(model, { key: recordKey })\n return <>{children(record.data ?? undefined)}</>\n}\n\n/** A button that opens a form in a dialog: a new record of `resource`, or the record around it (or `recordKey`) to edit. */\nexport const ModalFormBlock = ({ node }: BlockProps) => {\n const props = propsOf<ModalFormProps>(node)\n const scope = useLayoutRecord()\n const { resources } = useAdminMeta()\n const model = resources[props.resource ?? scope?.model.name ?? '']\n const permissions = usePermissions(model?.name ?? '')\n const [open, setOpen] = useState(false)\n if (!model) return null\n const allowed = props.mode === 'create' ? can(permissions, 'create') : can(permissions, 'update') && scope?.permissions?.update !== false\n if (!allowed) return null\n const button = (record: LayoutRecord | undefined) => (\n <>\n <Button size=\"sm\" variant={props.variant ?? 'secondary'} disabled={props.mode === 'edit' && !record} onClick={() => setOpen(true)}>\n {props.label}\n </Button>\n {open && <ModalFormDialog {...props} model={model} record={props.mode === 'edit' ? record : undefined} onClose={() => setOpen(false)} />}\n </>\n )\n if (props.mode === 'edit' && props.recordKey !== undefined) return <KeyedRecord model={model} recordKey={props.recordKey}>{button}</KeyedRecord>\n return button(props.mode === 'edit' ? scope : undefined)\n}\n","import type { PageProps } from '@protobase/layout'\nimport { PageHeader } from '../../../app-shell'\nimport { cn } from '../../../lib/cn'\nimport { propsOf, type BlockProps } from './block-props'\n\nexport const PageBlock = ({ node, children, slots, className }: BlockProps) => {\n const { title, description, width } = propsOf<PageProps>(node)\n return (\n <div className={cn('flex-1', className)}>\n <div className={cn('flex flex-col gap-6 px-4 pb-16 pt-6 md:px-10 md:py-8', width !== 'full' && 'mx-auto max-w-[1200px]')}>\n <PageHeader title={title} subtitle={description} actions={slots.actions} />\n {children}\n </div>\n </div>\n )\n}\n","import type { ProgressProps } from '@protobase/layout'\nimport { Skeleton } from '../../../primitives/skeleton'\nimport { frameFor, useScopeStack } from '../record-scope'\nimport { usePathValue } from '../use-path-value'\nimport { cn } from '../../../lib/cn'\nimport { propsOf, type BlockProps } from './block-props'\nimport { formatTag } from '../../../locale/active-locale'\n\n/** A number as given, or the number in a field of the records around it. */\nconst useAmount = (amount: number | string | undefined, fallback: number) => {\n const stack = useScopeStack()\n const at = typeof amount === 'string' ? frameFor(stack, amount) : undefined\n const value = usePathValue(at && 'frame' in at ? at.frame : undefined, at && 'path' in at ? at.path : '')\n if (typeof amount === 'number') return amount\n if (amount === undefined) return fallback\n if (at && 'item' in at) return Number(at.item)\n if (value.state === 'ready') return Number(value.value)\n return value.state === 'loading' ? undefined : Number.NaN\n}\n\n/** A bar for `value` out of `max` (100 by default), with the numbers beside the label. */\nexport const ProgressBlock = ({ node, className }: BlockProps) => {\n const { value, max, label } = propsOf<ProgressProps>(node)\n const current = useAmount(value, 0)\n const total = useAmount(max, 100)\n if (current === undefined || total === undefined) return <Skeleton className=\"h-6 w-full\" />\n if (!Number.isFinite(current) || !Number.isFinite(total)) return null\n const share = total > 0 ? Math.min(1, Math.max(0, current / total)) : 0\n return (\n <div className={cn('min-w-0', className)}>\n <div className=\"flex items-baseline justify-between gap-2 text-body\">\n <span className=\"text-muted-foreground\">{label}</span>\n <span className=\"tabular-nums\">\n {current.toLocaleString(formatTag())} / {total.toLocaleString(formatTag())}\n </span>\n </div>\n <div role=\"progressbar\" aria-label={label} aria-valuenow={current} aria-valuemin={0} aria-valuemax={total} className=\"mt-1.5 h-2 overflow-hidden rounded-full bg-muted\">\n <div className={share >= 0.9 ? 'h-full rounded-full bg-warning' : 'h-full rounded-full bg-primary'} style={{ width: `${share * 100}%` }} />\n </div>\n </div>\n )\n}\n","import type { ReactNode } from 'react'\nimport type { RecordCardProps } from '@protobase/layout'\nimport type { ResourceModel } from '@protobase/schema'\nimport { Skeleton } from '../../../primitives/skeleton'\nimport { ErrorBanner } from '../../error-banner'\nimport { useAdminMeta } from '../../meta-gate'\nimport { RecordScope } from '../record-scope'\nimport { usePlanned } from '../plan-reads'\nimport { plannedRecord, useFirstRecord } from '../use-layout-data'\nimport { cn } from '../../../lib/cn'\nimport { propsOf, type BlockProps } from './block-props'\nimport { CardFrame, Quiet } from './card-frame'\nimport { text } from '../messages'\n\ntype LoadedProps = Omit<RecordCardProps, 'resource' | 'actions' | 'children'> & { model: ResourceModel; at?: string; actions: ReactNode; children: ReactNode[]; className?: string }\n\nconst LoadedRecordCard = ({ model, at, filter, sort, recordKey, title, description, empty, actions, children, className }: LoadedProps) => {\n const planned = usePlanned(at)\n const own = useFirstRecord(model, { filter, sort, key: recordKey, enabled: !planned })\n const record = planned ? plannedRecord(model, planned) : own\n const scoped = (content: ReactNode) => (record.data ? <RecordScope value={record.data}>{content}</RecordScope> : undefined)\n const body = record.isPending ? (\n <div className=\"flex flex-col gap-2\">\n <Skeleton className=\"h-4 w-1/2\" />\n <Skeleton className=\"h-4 w-1/3\" />\n </div>\n ) : record.error ? (\n <ErrorBanner title={text('couldNotLoad')} error={record.error} />\n ) : record.data ? (\n scoped(<div className=\"flex flex-col gap-3\">{children}</div>)\n ) : (\n <Quiet>{empty ?? text('nothingYet')}</Quiet>\n )\n return (\n <CardFrame title={title} description={description} actions={actions ? scoped(actions) : undefined} className={cn('h-full', className)}>\n {body}\n </CardFrame>\n )\n}\n\n/** One record, the one `recordKey` names or the first match: its Fields, Actions and forms inside, actions in the header. */\nexport const RecordCardBlock = ({ node, at, children, slots, className }: BlockProps) => {\n const { resource, filter, sort, recordKey, title, description, empty } = propsOf<RecordCardProps>(node)\n const model = useAdminMeta().resources[resource]\n if (!model) return null\n return (\n <LoadedRecordCard model={model} {...(at !== undefined && { at })} filter={filter} sort={sort} recordKey={recordKey} title={title} description={description} empty={empty} actions={slots.actions} className={className}>\n {children}\n </LoadedRecordCard>\n )\n}\n","import { messages } from '../../locale/messages'\n\nexport const text = messages('app/related-cards')\n","import { useLayoutEffect, useRef, useState, type ReactNode } from 'react'\nimport { Button } from '../../primitives/button'\nimport { cn } from '../../lib/cn'\nimport { text } from './messages'\n\n/**\n * Its content cut off at a few lines' height with \"Show more\" under it when it is taller, which shows it all; the cut\n * hides the rest rather than scrolling it, so the page keeps its one scrollbar.\n */\nexport const Clamped = ({ children }: { children: ReactNode }) => {\n const content = useRef<HTMLDivElement>(null)\n const [open, setOpen] = useState(false)\n const [taller, setTaller] = useState(false)\n // Markdown renders once its renderer loads, so the height is measured again whenever the content resizes, and on closing\n useLayoutEffect(() => {\n const box = content.current\n if (!box) return\n const measure = () => setTaller(box.scrollHeight > box.parentElement!.clientHeight + 1)\n measure()\n const observer = new ResizeObserver(measure)\n observer.observe(box)\n return () => observer.disconnect()\n }, [open])\n return (\n <div className=\"flex flex-col items-start gap-1\">\n <div className={cn('w-full min-w-0', !open && 'max-h-40 overflow-hidden')}>\n <div ref={content}>{children}</div>\n </div>\n {(taller || open) && (\n <Button size=\"sm\" variant=\"ghost\" className=\"-ml-2\" aria-expanded={open} onClick={() => setOpen(!open)}>\n {open ? text('showLess') : text('showMore')}\n </Button>\n )}\n </div>\n )\n}\n","import { Skeleton } from '../../primitives/skeleton'\nimport { useAdminMeta } from '../meta-gate'\nimport { fieldLabel } from '../pages/blocks/field'\nimport { FieldValue } from '../pages/field-value'\nimport type { LayoutRecord } from '../pages/record-scope'\nimport { usePathValue } from '../pages/use-path-value'\nimport { Clamped } from './clamped'\n\nconst isEmpty = (value: unknown) => value === null || value === undefined || value === ''\n\n/**\n * A field of a related record, through relations too, under its label unless `labelled` is false; `clamped` shows a\n * long value's first lines. A field without a value is left off, so only what the record says shows.\n */\nexport const RelatedField = ({ scope, path, labelled = true, clamped = false }: { scope: LayoutRecord; path: string; labelled?: boolean; clamped?: boolean }) => {\n const { views } = useAdminMeta()\n const value = usePathValue(scope, path)\n if (value.state === 'missing') return null\n if (value.state === 'ready' && isEmpty(value.value)) return null\n const shown = value.state === 'loading' ? <Skeleton className=\"h-4 w-24\" /> : <FieldValue model={value.model} field={value.field} value={value.value} />\n const body = clamped ? <Clamped>{shown}</Clamped> : shown\n if (!labelled) return <div className=\"min-w-0\">{body}</div>\n const label = fieldLabel(path, value.state === 'ready' ? views[value.model.name]?.fields[value.field.name]?.label : undefined)\n return (\n <div className=\"min-w-0\">\n <dt className=\"text-body text-muted-foreground\">{label}</dt>\n <dd className=\"mt-0.5\">{body}</dd>\n </div>\n )\n}\n","import type { RowButtonModel, ViewModel } from '@protobase/schema'\nimport { recordKey } from '../../live/model-helpers'\nimport { cn } from '../../lib/cn'\nimport { ActionButton } from '../pages/blocks/action'\nimport { RecordScope, type LayoutRecord } from '../pages/record-scope'\nimport { useRecordTitle } from '../titles/record-titles'\nimport { useAdminMeta } from '../meta-gate'\nimport { RowButtonLink } from '../row-button/row-button-link'\nimport { AppLink } from '../use-app-address'\nimport { RelatedField } from './related-field'\nimport { ToneEdge } from './tone-edge'\n\ntype CompactCardProps = {\n scope: LayoutRecord\n view: ViewModel | undefined\n /** The values on the second line, inline without labels. */\n fields: string[]\n /** The date or timestamp field beside the title. */\n time?: string\n /** The enum field whose value colours the card's left edge. */\n tone?: string\n actions: string[]\n button?: RowButtonModel\n /** Hears an action that ran on the card, by its label, with the card's title. */\n onActed?: (action: string, title: string) => void\n}\n\n/**\n * A related record as a card of one or two lines: its title linking to its page and its `time` on the first, its\n * `fields` inline without labels, a dot between them, on the second, and its buttons beside both, or beside the second\n * where the card is narrow, as on a phone; its `tone` field colours its left edge.\n */\nexport const CompactCard = ({ scope, view, fields, time, tone, actions, button, onActed }: CompactCardProps) => {\n const titleOf = useRecordTitle()\n const { resources } = useAdminMeta()\n const title = titleOf(scope.model, view, scope.record, scope.key)\n const buttons = actions.length > 0 || button !== undefined\n // Without buttons the card is one column: a second, auto-sized one would take the values beside the title and squeeze it\n return (\n <li data-card={scope.key} className={cn('relative grid min-w-0 items-center gap-x-4 gap-y-1 rounded-lg border border-border bg-surface px-4 py-2.5', buttons ? 'grid-cols-[minmax(0,1fr)_auto]' : 'grid-cols-[minmax(0,1fr)]')}>\n {tone && <ToneEdge view={view} field={tone} record={scope.record} />}\n <div className={cn('flex min-w-0 items-baseline gap-2', buttons && 'col-span-2 sm:col-span-1')}>\n <AppLink to={{ kind: 'record', resource: scope.model.name, key: recordKey(scope.model, scope.record) }} className=\"line-clamp-2 min-w-0 font-medium [overflow-wrap:anywhere] text-primary-text hover:underline\">\n {title}\n </AppLink>\n {time && (\n <div className=\"ml-auto shrink-0 text-body whitespace-nowrap text-muted-foreground empty:hidden\">\n <RelatedField scope={scope} path={time} labelled={false} />\n </div>\n )}\n </div>\n {fields.length > 0 && (\n <div className=\"flex min-w-0 flex-wrap items-center gap-y-0.5 text-body text-muted-foreground\">\n {fields.map((path) => (\n <div key={path} className=\"flex max-w-full min-w-0 items-center whitespace-nowrap empty:hidden [&>div]:truncate [:not(:empty)~&]:before:mx-2 [:not(:empty)~&]:before:content-['·'_/_'']\">\n <RelatedField scope={scope} path={path} labelled={false} />\n </div>\n ))}\n </div>\n )}\n {buttons && (\n <RecordScope value={scope}>\n <div className=\"col-start-2 flex flex-wrap items-center justify-end gap-2 sm:row-span-2 sm:row-start-1\">\n {button && <RowButtonLink button={button} model={scope.model} view={view} record={scope.record} models={resources} />}\n {actions.map((name) => <ActionButton key={name} name={name} about={title} onRun={(label) => onActed?.(label, title)} />)}\n </div>\n </RecordScope>\n )}\n </li>\n )\n}\n","import type { RowButtonModel, ViewModel } from '@protobase/schema'\nimport { recordKey } from '../../live/model-helpers'\nimport { ActionButton } from '../pages/blocks/action'\nimport { RecordScope, type LayoutRecord } from '../pages/record-scope'\nimport { useRecordTitle } from '../titles/record-titles'\nimport { useAdminMeta } from '../meta-gate'\nimport { RowButtonLink } from '../row-button/row-button-link'\nimport { AppLink } from '../use-app-address'\nimport { RelatedField } from './related-field'\nimport { ToneEdge } from './tone-edge'\n\n/**\n * A related record as a card: its title linking to its page, its `fields` under their labels, the buttons of its\n * view's `actions`, run on it as everywhere else, and `button`, a link to the address its fields name; its `tone`\n * field colours its left edge. `onActed` hears an action that ran on it, by its label, with its title.\n */\nexport const RelatedCard = ({ scope, view, fields, tone, actions, button, onActed }: { scope: LayoutRecord; view: ViewModel | undefined; fields: string[]; tone?: string; actions: string[]; button?: RowButtonModel; onActed?: (action: string, title: string) => void }) => {\n const titleOf = useRecordTitle()\n const { resources } = useAdminMeta()\n const title = titleOf(scope.model, view, scope.record, scope.key)\n return (\n <li data-card={scope.key} className=\"relative flex min-w-0 flex-col gap-3 rounded-lg border border-border bg-surface p-4\">\n {tone && <ToneEdge view={view} field={tone} record={scope.record} />}\n <AppLink to={{ kind: 'record', resource: scope.model.name, key: recordKey(scope.model, scope.record) }} className=\"self-start font-medium text-primary-text hover:underline\">\n {title}\n </AppLink>\n {fields.length > 0 && (\n <dl className=\"flex flex-col gap-3\">\n {fields.map((path) => <RelatedField key={path} scope={scope} path={path} clamped />)}\n </dl>\n )}\n {(actions.length > 0 || button) && (\n <RecordScope value={scope}>\n <div className=\"flex flex-wrap items-center gap-2\">\n {button && <RowButtonLink button={button} model={scope.model} view={view} record={scope.record} models={resources} />}\n {actions.map((name) => <ActionButton key={name} name={name} about={title} onRun={(label) => onActed?.(label, title)} />)}\n </div>\n </RecordScope>\n )}\n </li>\n )\n}\n","type Control = { disabled?: boolean; getAttribute: (name: string) => string | null }\ntype Card<T extends Control> = { querySelectorAll: (selectors: string) => Iterable<T>; querySelector: (selectors: string) => T | null }\n\nconst enabled = (control: Control) => !control.disabled && control.getAttribute('aria-disabled') !== 'true'\n\n// A card's first action it can take, else its title's link: a disabled button takes no focus\nexport const firstControl = <T extends Control>(card: Card<T>) =>\n [...card.querySelectorAll('button')].find(enabled) ?? card.querySelector('a')\n","/**\n * The card to focus when the card `gone` has left a list of cards, the keys `before` and `after` in their order: the\n * first after it that is still there, else the last before it that is; none when no card is left.\n */\nexport const nextFocus = (before: string[], after: string[], gone: string) => {\n const at = before.indexOf(gone)\n const stays = (key: string) => after.includes(key)\n return before.slice(at + 1).find(stays) ?? before.slice(0, Math.max(at, 0)).findLast(stays)\n}\n","import { useEffect, useRef, useState } from 'react'\nimport { firstControl } from './first-control'\nimport { nextFocus } from './next-focus'\nimport { text } from './messages'\n\ntype Acted = { key: string; action: string; title: string }\n\n// The heading of the section the cards are in, focusable by script\nconst headingOf = (root: HTMLElement) => {\n const heading = root.closest('section')?.querySelector<HTMLElement>('h2')\n if (heading && !heading.hasAttribute('tabindex')) heading.tabIndex = -1\n return heading\n}\n\n/**\n * Where focus goes when an action takes its card out of the list, the cards' `keys` in their order: to the next card's\n * first enabled action, else the previous card's, else the section's heading, while the focus fell to the page with the\n * card; `announcement` then says it left. Cards carry their key in `data-card`, inside `root`; each tells `acted` once one of\n * its actions ran. A card that stays keeps the focus where it is. `keys` is a new list only when the cards reload.\n */\nexport const useLeavingFocus = (keys: string[]) => {\n const root = useRef<HTMLDivElement>(null)\n const shown = useRef({ current: keys, previous: keys })\n const pending = useRef<Acted>(undefined)\n const [announcement, setAnnouncement] = useState('')\n\n const settle = (acted: Acted, before: string[], after: string[]) => {\n pending.current = undefined\n if (after.includes(acted.key) || !root.current) return\n setAnnouncement(text('left', { action: acted.action, title: acted.title }))\n // Focus the person moved on with stays where it is\n if (document.activeElement && document.activeElement !== document.body) return\n const key = nextFocus(before, after, acted.key)\n const card = key === undefined ? undefined : root.current.querySelector(`[data-card=\"${CSS.escape(key)}\"]`)\n const target = card ? firstControl<HTMLElement>(card) : headingOf(root.current)\n target?.focus()\n }\n\n // The list reloads after the action ran, mostly once it told; the list it left is then the one before\n useEffect(() => {\n const before = shown.current.current\n shown.current = { current: keys, previous: before }\n if (pending.current) settle(pending.current, before, keys)\n }, [keys])\n\n const acted = (key: string, action: string, title: string) => {\n const { current, previous } = shown.current\n if (current.includes(key)) {\n pending.current = { key, action, title }\n return\n }\n settle({ key, action, title }, previous, current)\n }\n\n return { root, acted, announcement }\n}\n","import { ArrowRight } from 'lucide-react'\nimport { useMemo } from 'react'\nimport type { ResourceModel, RowButtonModel, ViewModel } from '@protobase/schema'\nimport { useIsXs } from '../../lib/use-media-query'\nimport { humanize } from '../../live/naming'\nimport { Skeleton } from '../../primitives/skeleton'\nimport { SnapRow } from '../../primitives/snap-row'\nimport { useSnapScroll } from '../../primitives/use-snap-scroll'\nimport { cutOffNote } from '../embedded-list/cut-off-note'\nimport { embeddedDisplay, viewAllAddress } from '../embedded-list/embedded-display'\nimport { text as listText } from '../embedded-list/messages'\nimport { ErrorBanner } from '../error-banner'\nimport { defaultOrderBy } from '../list-order'\nimport type { PlannedList } from '../embedded-list/planned-embedded-rows'\nimport { plannedCount } from '../pages/planned-count'\nimport { scopeOf, useCount, useListPage } from '../pages/use-layout-data'\nimport { AppLink } from '../use-app-address'\nimport { CompactCard } from './compact-card'\nimport { RelatedCard } from './related-card'\nimport { text } from './messages'\nimport { useLeavingFocus } from './use-leaving-focus'\n\ntype RelatedCardsProps = {\n model: ResourceModel\n view: ViewModel | undefined\n filter: string\n /** The order of the cards, the list's own when empty. */\n sort: string\n /** The fields each card shows. */\n fields: string[]\n /** The named actions of the view each card has buttons for. */\n actions: string[]\n /** A button on each card to an address the record's fields name. */\n button?: RowButtonModel\n limit: number\n /** The display of the list \"View all\" opens. */\n display: string | undefined\n empty?: string\n /** Each card's share of the width in one row that scrolls sideways, snapping each card to its left edge; stacked when omitted. */\n carousel?: number\n /** Cards of one or two lines, with this date or timestamp field beside the title, or `{}` for none. */\n compact?: { time?: string }\n /** The enum field whose value colours each card's left edge. */\n tone?: string\n /** Its records and how many match in all, from the page's planned reads, inside the records of another block. */\n planned?: PlannedList\n}\n\n// Compact cards are two lines high, a long title taking a third on a phone; three of them hold the room a\n// short list takes, so the page below barely moves when they load\nconst CardsSkeleton = ({ compact, limit }: { compact: boolean; limit: number }) => (\n <div className={compact ? 'flex flex-col gap-2' : 'flex flex-col gap-3'}>\n {Array.from({ length: compact ? Math.min(limit, 3) : 2 }, (_, index) => <Skeleton key={index} className={compact ? 'h-17.5 w-full max-sm:h-24' : 'h-24 w-full'} />)}\n </div>\n)\n\n/**\n * The first `limit` records of a list as cards stacked full width or in a `carousel`, each with its fields, its\n * actions' buttons and its row button, and a link to the whole list beside a note such as \"The first 10 of 37.\" when there are more.\n */\nexport const RelatedCards = ({ model, view, filter, sort, fields, actions, button, limit, display, empty, carousel, compact, tone, planned }: RelatedCardsProps) => {\n const xs = useIsXs()\n const scroll = useSnapScroll()\n const plural = view?.names?.plural ?? humanize(model.name)\n const orderBy = sort || defaultOrderBy(model, view)\n const own = useListPage(model, { filter, sort: orderBy, pageSize: limit, enabled: !planned })\n const ownCount = useCount(model, filter, !planned)\n const page = planned ? planned.rows : { isPending: own.isPending, error: own.error }\n const items = planned ? planned.rows.rows : own.data?.items\n const count = planned ? { data: planned.total && !planned.total.isPending && !planned.total.error ? plannedCount(planned.total) : undefined } : ownCount\n const scopes = useMemo(() => (items ?? []).map((row) => scopeOf(model, row)), [model, items])\n const keys = useMemo(() => scopes.map((scope) => scope.key), [scopes])\n const leaving = useLeavingFocus(keys)\n const content = () => {\n if (page.isPending) return <CardsSkeleton compact={Boolean(compact)} limit={limit} />\n if (page.error) return <ErrorBanner title={text('couldNotLoad')} error={page.error} />\n if (scopes.length === 0) return <p className=\"text-muted-foreground\">{empty ?? text('nothingYet')}</p>\n const cards = scopes.map((scope) => {\n const acted = (action: string, title: string) => leaving.acted(scope.key, action, title)\n if (compact) return <CompactCard key={scope.key} scope={scope} view={view} fields={fields} time={compact.time} tone={tone} actions={actions} button={button} onActed={acted} />\n return <RelatedCard key={scope.key} scope={scope} view={view} fields={fields} tone={tone} actions={actions} button={button} onActed={acted} />\n })\n const note = count.data === undefined ? undefined : cutOffNote(scopes.length, count.data, false)\n return (\n <div className=\"flex flex-col gap-3\">\n {carousel === undefined ? <ul className={compact ? 'flex flex-col gap-2' : 'flex flex-col gap-3'}>{cards}</ul> : (\n <SnapRow scroll={scroll} label={plural} share={carousel}>\n {cards}\n </SnapRow>\n )}\n <div className=\"flex flex-wrap items-center justify-between gap-2\">\n <p className=\"text-xs text-muted-foreground\">{note}</p>\n <AppLink to={viewAllAddress(model, view, xs, { filter, orderBy, display: embeddedDisplay(view, xs, { preferred: display }) })} className=\"flex items-center gap-1 font-medium text-primary-text hover:underline\">\n {listText('viewAll')} <span className=\"sr-only\">{plural.toLowerCase()}</span>\n <ArrowRight className=\"size-3.5\" aria-hidden />\n </AppLink>\n </div>\n </div>\n )\n }\n // The toast says an action is done; only the cards know when it took its card out of the list\n return (\n <div ref={leaving.root}>\n {content()}\n <p role=\"status\" className=\"sr-only\">{leaving.announcement}</p>\n </div>\n )\n}\n","import { useMemo } from 'react'\nimport { cardsLayoutOf, type CardWidth, type RecordCardsProps } from '@protobase/layout'\nimport { listColumnNames } from '../../../live/columns-from-model'\nimport { SectionContent } from '../../../record-view/section'\nimport { useAdminMeta } from '../../meta-gate'\nimport { RelatedCards } from '../../related-cards/related-cards'\nimport { cn } from '../../../lib/cn'\nimport { usePlannedReads } from '../plan-reads'\nimport { propsOf, type BlockProps } from './block-props'\n\nconst shares: Record<CardWidth, number> = { '1/4': 1 / 4, '1/3': 1 / 3, '1/2': 1 / 2, '2/3': 2 / 3 }\n\n/**\n * What a filter finds as the record page's related cards, stacked full width or in a row that scrolls sideways, under\n * a heading like a record page section's, with no card frame around them, so no card sits in another. Inside the\n * records of another block, its records and total per record come from the page's planned reads.\n */\nexport const RecordCardsBlock = ({ node, at, slots, className }: BlockProps) => {\n const props = propsOf<RecordCardsProps>(node)\n const { resource, filter = '', sort = '', fields, cardActions = [], limit = 10, display, title, description, empty } = props\n const { layout, cardWidth } = cardsLayoutOf(props)\n const { resources, views } = useAdminMeta()\n const [rows, total] = usePlannedReads([at, at === undefined ? undefined : `${at}#total`])\n const planned = useMemo(() => rows && { rows, total }, [rows, total])\n const model = resources[resource]\n if (!model) return null\n const view = views[model.name]\n return (\n <section className={cn('min-w-0', className)} aria-label={title}>\n <SectionContent title={title} help={description} actions={slots.actions}>\n <RelatedCards model={model} view={view} filter={filter} sort={sort} fields={fields ?? listColumnNames(model, view)} actions={cardActions} limit={limit} display={display} empty={empty} carousel={layout === 'carousel' ? shares[cardWidth] : undefined} {...(planned && { planned })} />\n </SectionContent>\n </section>\n )\n}\n","import type { ResourceModel, ViewModel } from '@protobase/schema'\nimport { humanize } from '../../live/naming'\nimport { Skeleton } from '../../primitives/skeleton'\nimport { listedResource } from '../current-address'\nimport { ErrorBanner } from '../error-banner'\nimport { useAdminMeta } from '../meta-gate'\nimport { savedScope } from '../saved/saved-records'\nimport { useSavedRecords } from '../saved/use-saved-records'\nimport { RecordRowBody, type RecordRowBodyProps } from './record-row-body'\nimport { text } from './messages'\n\ntype SavedRecordRowProps = Omit<RecordRowBodyProps, 'model' | 'view' | 'filter' | 'sort' | 'scope' | 'list'> & {\n /** The saved records' resource, such as favorites, and its view, whose `listOf` names what they point at. */\n model: ResourceModel\n view: ViewModel\n}\n\n/**\n * The records the user's saved ones of a view with `listOf` point at, such as the listings among their favorites, as a\n * row of their own resource's cards, with \"View all\" to the saved records' list. `empty` when there are none.\n */\nexport const SavedRecordRow = ({ model, view, empty, ...props }: SavedRecordRowProps) => {\n const { resources, views } = useAdminMeta()\n const listed = listedResource(resources, views, model.name)\n const saved = useSavedRecords(model.name, view.listOf!, true)\n const plural = (view.names?.plural ?? humanize(model.name)).toLowerCase()\n if (!listed.listOf) return null\n if (saved.error) return <ErrorBanner title={text('couldNotLoadYour', { plural })} error={saved.error} />\n if (!saved.data) return <Skeleton className=\"h-24\" />\n const scope = savedScope(listed.model!, saved.data)\n if (!scope) return <p className=\"text-muted-foreground\">{empty ?? text('noneYet', { plural })}</p>\n return <RecordRowBody {...props} model={listed.model!} view={listed.view} filter=\"\" scope={scope} list={model.name} empty={empty} />\n}\n","import type { ResourceModel, ViewModel } from '@protobase/schema'\nimport { encodeKey } from '@protobase/schema/internal'\nimport { recordKey } from '../../live/model-helpers'\nimport { humanize } from '../../live/naming'\nimport { Skeleton } from '../../primitives/skeleton'\nimport { ErrorBanner } from '../error-banner'\nimport { useAdminMeta } from '../meta-gate'\nimport { RecordRowBody } from '../record-row/record-row-body'\nimport { AppLink } from '../use-app-address'\nimport { InlineFilterChips } from './filter-chip-list'\nimport { useSavedSearches, type SavedSearchRow } from './use-saved-searches'\nimport { useSearchRow } from './use-search-row'\nimport { text } from './messages'\n\ntype SearchRowItemProps = { model: ResourceModel; view: ViewModel; target: ResourceModel; targetView: ViewModel | undefined; row: SavedSearchRow }\n\nconst SearchRowItem = ({ model, view, target, targetView, row }: SearchRowItemProps) => {\n const key = encodeKey(recordKey(model, row))\n const { name, chips, title, body } = useSearchRow({ model, of: view.searchesOf!, target, targetView, row, recordKey: key })\n return (\n <section aria-label={title} className=\"flex flex-col gap-3 py-4 first:pt-0 last:pb-0\">\n <h3 className=\"text-[0.9375rem] font-semibold\">\n <AppLink to={{ kind: 'record', resource: model.name, key }} className=\"hover:underline\">\n {name ?? <InlineFilterChips chips={chips} />}\n </AppLink>\n </h3>\n <RecordRowBody {...body} />\n </section>\n )\n}\n\n/**\n * The user's saved searches of a view with `searchesOf`, for a page: each with its name or filters, linking to it, over\n * the row of what it finds (`useSearchRow`), in the order of their list. `empty` when there are none.\n */\nexport const SavedSearchRows = ({ model, view, empty }: { model: ResourceModel; view: ViewModel; empty?: string }) => {\n const { resources, views } = useAdminMeta()\n const of = view.searchesOf!\n const target = resources[of.resource]\n const saved = useSavedSearches(model.name, true)\n const plural = (view.names?.plural ?? humanize(model.name)).toLowerCase()\n if (!target) return null\n if (saved.error) return <ErrorBanner title={text('couldNotLoadYour', { plural })} error={saved.error} />\n if (!saved.data) return <Skeleton className=\"h-40\" />\n if (saved.data.length === 0) return <p className=\"text-muted-foreground\">{empty ?? text('noneYet', { plural })}</p>\n return (\n <div className=\"flex flex-col divide-y\">\n {saved.data.map((row) => (\n <SearchRowItem key={encodeKey(recordKey(model, row))} model={model} view={view} target={target} targetView={views[of.resource]} row={row} />\n ))}\n </div>\n )\n}\n","import type { RecordRowProps } from '@protobase/layout'\nimport { useAdminMeta } from '../../meta-gate'\nimport { RecordRowBody } from '../../record-row/record-row-body'\nimport { SavedRecordRow } from '../../record-row/saved-record-row'\nimport { SavedSearchRows } from '../../searches/saved-search-rows'\nimport { propsOf, type BlockProps } from './block-props'\nimport { CardFrame } from './card-frame'\n\n/**\n * What a filter finds: its chips, the count, its records as a sideways row of their list's cards, and \"View all\". Of a\n * resource whose view has `listOf`, the records the user's saved ones point at; of one with `searchesOf`, a row per\n * saved search of the user's.\n */\nexport const RecordRowBlock = ({ node, slots, className }: BlockProps) => {\n const { resource, filter = '', sort, limit, display, title, description, empty } = propsOf<RecordRowProps>(node)\n const { resources, views } = useAdminMeta()\n const model = resources[resource]\n if (!model) return null\n const view = views[model.name]\n const body = () => {\n if (view?.searchesOf) return <SavedSearchRows model={model} view={view} empty={empty} />\n if (view?.listOf !== undefined) return <SavedRecordRow model={model} view={view} limit={limit} display={display} empty={empty} />\n return <RecordRowBody model={model} view={view} filter={filter} sort={sort} limit={limit} display={display} empty={empty} />\n }\n return (\n <CardFrame title={title} description={description} actions={slots.actions} className={className}>\n {body()}\n </CardFrame>\n )\n}\n","import { useRef, useState } from 'react'\nimport type { ProblemError } from '@protobase/client'\nimport type { SettingsProps, Styled } from '@protobase/layout'\nimport type { FieldModel, ResourceModel } from '@protobase/schema'\nimport { useClient } from '../../../data/api-provider'\nimport { differs } from '../../../live/field-values'\nimport { humanize } from '../../../live/naming'\nimport { Button } from '../../../primitives/button'\nimport { Skeleton } from '../../../primitives/skeleton'\nimport { Field } from '../../../record-view'\nimport { useToast } from '../../../toasts'\nimport { createBody, type Draft } from '../../create/create-values'\nimport { ErrorBanner } from '../../error-banner'\nimport { fieldErrors, fieldMessage } from '../../field-errors'\nimport { FieldEditor } from '../../field-editor'\nimport { useAdminMeta, usePermissions } from '../../meta-gate'\nimport { can } from '../../permissions'\nimport type { LayoutRecord } from '../record-scope'\nimport { scopeOf, useFirstRecord, useRefreshResource } from '../use-layout-data'\nimport { cn } from '../../../lib/cn'\nimport { propsOf, type BlockProps } from './block-props'\nimport { CardFrame } from './card-frame'\nimport { editBody, startingDraft } from './form-draft'\nimport { text } from '../messages'\n\ntype FormProps = Omit<SettingsProps, 'resource' | 'fields'> & { model: ResourceModel; fields: string[]; stored: LayoutRecord | undefined; className?: string }\n\n/** A switch or a choice saves as soon as it changes; what is typed waits for Save. */\nexport const savesAtOnce = (field: FieldModel) => field.type === 'boolean' || field.type === 'enum'\n\nconst SettingsForm = ({ model, fields, title, description, stored: loaded, className }: FormProps) => {\n const { resources, views } = useAdminMeta()\n const permissions = usePermissions(model.name)\n const client = useClient()\n const toast = useToast()\n const refresh = useRefreshResource()\n const view = views[model.name]\n const [stored, setStored] = useState(loaded)\n const [draft, setDraft] = useState(() => startingDraft(model, fields, loaded?.record))\n const [errors, setErrors] = useState<Record<string, ProblemError>>({})\n const [failure, setFailure] = useState<unknown>()\n const [saving, setSaving] = useState(false)\n // One save at a time, each from the record the one before wrote, so a quick second change updates rather than creates\n const queue = useRef<Promise<unknown>>(Promise.resolve())\n const latest = useRef(loaded)\n\n const defaults = startingDraft(model, fields, undefined)\n const writable = stored ? can(permissions, 'update') && stored.permissions?.update !== false : can(permissions, 'create')\n const typed = fields.filter((name) => !savesAtOnce(model.fields[name]!))\n const unsaved = typed.some((name) => (stored ? differs(model.fields[name]!, draft[name], stored.record[name]) : draft[name] !== defaults[name]))\n\n const write = async (changes: Draft) => {\n const current = latest.current\n if (current) {\n const saved = await client.update(model.name, current.key, editBody(model, changes, current.record), current.etag ?? '*')\n return { ...scopeOf(model, saved.record), etag: saved.etag, permissions: saved.permissions ?? current.permissions }\n }\n // The first save creates the record with every value shown, the server making the caller its owner\n const created = await client.create(model.name, createBody(model, resources, { ...defaults, ...changes }))\n return { ...scopeOf(model, created.record), etag: created.etag }\n }\n\n const save = (changes: Draft) => {\n const run = queue.current.then(async () => {\n setSaving(true)\n setFailure(undefined)\n await write(changes).then(\n async (record) => {\n latest.current = record\n setStored(record)\n setErrors((current) => Object.fromEntries(Object.entries(current).filter(([name]) => !Object.hasOwn(changes, name))))\n await refresh(model.name)\n toast.show({ state: 'success', title: text('saved', { label: title ?? text('settings') }) })\n },\n (error: unknown) => {\n setErrors((current) => ({ ...current, ...fieldErrors(error) }))\n setFailure(error)\n },\n )\n setSaving(false)\n })\n queue.current = run\n }\n\n const change = (name: string, next: unknown) => {\n setDraft((current) => ({ ...current, [name]: next }))\n if (savesAtOnce(model.fields[name]!)) save({ [name]: next })\n }\n\n return (\n <CardFrame title={title} description={description} className={cn('h-full', className)}>\n <form\n className=\"flex flex-col gap-4\"\n onSubmit={(event) => {\n event.preventDefault()\n if (unsaved) save(Object.fromEntries(typed.map((name) => [name, draft[name]])))\n }}\n >\n {failure !== undefined && Object.keys(errors).length === 0 && <ErrorBanner title={text('notSaved')} error={failure} />}\n {fields.map((name) => {\n const field = model.fields[name]!\n const label = view?.fields[name]?.label ?? humanize(name)\n const problem = errors[name]\n return (\n <Field key={name} name={name} label={label} help={view?.fields[name]?.help} error={problem && fieldMessage(field, label, problem)}>\n <FieldEditor\n field={field}\n hints={view?.fields[name]}\n value={draft[name]}\n stored={stored?.record[name] ?? defaults[name]}\n invalid={Boolean(problem)}\n locked={!writable || field.readOnly}\n resource={model.name}\n onChange={(next) => change(name, next)}\n />\n </Field>\n )\n })}\n {writable && unsaved && (\n <div>\n <Button type=\"submit\" variant=\"primary\" size=\"sm\" loading={saving}>\n {text('save')}\n </Button>\n </div>\n )}\n </form>\n </CardFrame>\n )\n}\n\nconst LoadedSettings = (props: FormProps) => {\n const record = useFirstRecord(props.model, {})\n if (record.isPending) {\n return (\n <CardFrame title={props.title} description={props.description} className={props.className}>\n <div className=\"flex flex-col gap-2\">\n <Skeleton className=\"h-4 w-1/2\" />\n <Skeleton className=\"h-4 w-1/3\" />\n </div>\n </CardFrame>\n )\n }\n if (record.error) {\n return (\n <CardFrame title={props.title} description={props.description} className={props.className}>\n <ErrorBanner title={text('couldNotLoad')} error={record.error} />\n </CardFrame>\n )\n }\n return <SettingsForm {...props} stored={record.data ?? undefined} />\n}\n\n/**\n * The signed-in person's own record of a resource as settings: each field as a control, a switch or a choice saving as\n * it changes and typed values with Save, the defaults shown until the first save creates the record. The server keeps\n * every caller to their own record, so the list holds at most theirs.\n */\nexport const SettingsBlock = ({ node, className }: BlockProps) => {\n const { resource, fields = [], className: _className, ...rest } = propsOf<SettingsProps & Styled>(node)\n const model = useAdminMeta().resources[resource]\n if (!model) return null\n return <LoadedSettings {...rest} model={model} fields={fields.filter((name) => Object.hasOwn(model.fields, name))} stored={undefined} className={className} />\n}\n","import { useQueries } from '@tanstack/react-query'\nimport { useMemo } from 'react'\nimport { countedResource, evaluateCondition, parseCondition } from '@protobase/layout'\nimport { useClient } from '../../data/api-provider'\nimport { useAdminMeta } from '../meta-gate'\nimport { frameFor, type LayoutRecord, type ScopeFrame } from './record-scope'\nimport { countQuery } from './use-layout-data'\nimport { usePathValues } from './use-path-value'\n\n/** Whether each condition holds for the record around it (`scope`), as `useStackConditions` says. */\nexport const useConditions = (whens: string[], scope: LayoutRecord | undefined): Array<boolean | undefined> => useStackConditions(whens, scope ? [scope] : [])\n\n/**\n * Whether each condition holds for the records around it (`stack`, outermost first): `undefined` while a value it reads\n * loads, `false` when it does not parse. A name reads from the nearest record that has that field, followed through\n * relations; `<resource>.count` counts records. All conditions share one set of queries, so the hook count never\n * changes with the conditions.\n */\nexport const useStackConditions = (whens: string[], stack: readonly ScopeFrame[]): Array<boolean | undefined> => {\n const { resources } = useAdminMeta()\n const client = useClient()\n const key = JSON.stringify(whens)\n const parsed = useMemo(() => (JSON.parse(key) as string[]).map(parseCondition), [key])\n const isField = (name: string) => stack.some((frame) => ('item' in frame ? typeof frame.item === 'object' && frame.item !== null && Object.hasOwn(frame.item, name) : Object.hasOwn(frame.model.fields, name)))\n const paths = [...new Set(parsed.flatMap((condition) => (condition.ok ? condition.paths : [])))]\n const counted = new Map(paths.flatMap((path) => {\n const resource = countedResource(path, isField)\n return resource === undefined ? [] : [[path, resource] as const]\n }))\n const fieldPaths = paths.filter((path) => !counted.has(path))\n const countedModels = [...new Set(counted.values())].flatMap((resource) => (resources[resource] ? [resources[resource]!] : []))\n const sources = fieldPaths.map((path) => frameFor(stack, path))\n const fields = usePathValues(fieldPaths.map((path, index) => {\n const at = sources[index]\n return at && 'frame' in at ? { scope: at.frame, path: at.path } : { scope: undefined, path }\n }))\n const counts = useQueries({ queries: countedModels.map((model) => countQuery(client, model)) })\n\n return parsed.map((condition) => {\n if (!condition.ok) return false\n const values: Record<string, unknown> = {}\n for (const path of condition.paths) {\n const resource = counted.get(path)\n if (resource === undefined) {\n const index = fieldPaths.indexOf(path)\n const at = sources[index]\n if (at && 'item' in at) {\n values[path] = at.item\n continue\n }\n const value = fields[index]!\n if (value.state === 'loading') return undefined\n if (value.state === 'ready') values[path] = value.value\n continue\n }\n // A resource the caller cannot see has no query and counts as zero.\n const index = countedModels.findIndex((model) => model.name === resource)\n if (index === -1) values[path] = 0\n else if (counts[index]!.isPending) return undefined\n else values[path] = counts[index]!.data ?? 0\n }\n return evaluateCondition(condition, values)\n })\n}\n","import type { ReactNode } from 'react'\nimport { type ShowProps } from '@protobase/layout'\nimport { useScopeStack } from '../record-scope'\nimport { useStackConditions } from '../use-conditions'\nimport { propsOf, type BlockProps } from './block-props'\n\n/** A `fallback` as it draws: text as it is, elements as they were rendered into the slot of that name. */\nexport const fallbackOf = (node: BlockProps['node'], slots: BlockProps['slots']): ReactNode => (typeof node.props.fallback === 'string' ? node.props.fallback : slots.fallback)\n\n/**\n * Its children while `when` holds, else its `fallback`, as SolidJS's `<Show>`: fields of the records around it, and\n * `<resource>.count` for any resource. Nothing while a value the condition reads loads.\n */\nexport const ShowBlock = ({ node, children, slots, className }: BlockProps) => {\n const { when } = propsOf<ShowProps>(node)\n const [shown] = useStackConditions([when], useScopeStack())\n if (shown === undefined) return null\n const drawn = shown ? children : fallbackOf(node, slots)\n if (drawn === undefined || drawn === null) return null\n // Its classes go on an element around what it draws, and on nothing while it draws nothing\n return className === undefined ? <>{drawn}</> : <div className={className}>{drawn}</div>\n}\n","import { fillProps, type LayoutNode } from '@protobase/layout'\nimport { useScopeStack, valueScopeOf, type ScopeFrame } from '../record-scope'\nimport { useStackConditions } from '../use-conditions'\nimport type { BlockProps } from './block-props'\nimport { fallbackOf } from './show'\n\n/**\n * The `when` of each `Match`, its `{{path}}`s filled from the records around the Switch as each Match fills its own when\n * it draws. The structure check lets a Switch hold Matches only, each one rendered child.\n */\nexport const matchConditions = (children: LayoutNode['children'], stack: readonly ScopeFrame[]) =>\n children.flatMap((child) => (typeof child === 'string' ? [] : [String(fillProps(child, valueScopeOf(stack)).props.when)]))\n\n/**\n * Its first `Match` whose `when` holds, else its `fallback`, as SolidJS's `<Switch>`; nothing while a value an earlier\n * `Match` reads loads, so a later one never shows first.\n */\nexport const SwitchBlock = ({ node, children, slots, className }: BlockProps) => {\n const stack = useScopeStack()\n const held = useStackConditions(matchConditions(node.children, stack), stack)\n const drawn = held.findIndex((holds) => holds !== false)\n if (drawn !== -1 && held[drawn] === undefined) return null\n const shown = drawn === -1 ? fallbackOf(node, slots) : children[drawn]\n if (shown === undefined || shown === null) return null\n return className === undefined ? <>{shown}</> : <div className={className}>{shown}</div>\n}\n\n/** One branch of a `Switch`, which decides whether it is drawn. */\nexport const MatchBlock = ({ children }: BlockProps) => <>{children}</>\n","import type { StatProps } from '@protobase/layout'\nimport type { ResourceModel } from '@protobase/schema'\nimport { Skeleton } from '../../../primitives/skeleton'\nimport { useAdminMeta } from '../../meta-gate'\nimport { filteredListAddress } from '../../list-link'\nimport { AppLink } from '../../use-app-address'\nimport { FieldValue } from '../field-value'\nimport { usePlanned } from '../plan-reads'\nimport { plannedCount } from '../planned-count'\nimport { useCount } from '../use-layout-data'\nimport { useScopedPathValue } from '../use-path-value'\nimport { cn } from '../../../lib/cn'\nimport { plainText } from './plain-value'\nimport { propsOf, type BlockProps } from './block-props'\nimport { CardFrame } from './card-frame'\nimport { formatTag } from '../../../locale/active-locale'\nimport { text } from '../messages'\n\nconst big = 'text-2xl font-semibold tracking-tight tabular-nums'\n\nconst Count = ({ model, at, filter }: { model: ResourceModel; at?: string; filter?: string }) => {\n const { views } = useAdminMeta()\n const planned = usePlanned(at)\n const own = useCount(model, filter, !planned)\n const count = planned ?? own\n if (count.isPending) return <Skeleton className=\"h-8 w-16\" />\n if (count.error) return <span className=\"text-danger-text\">{text('couldNotCount')}</span>\n const total = planned ? plannedCount(planned) : own.data!\n return (\n <AppLink to={filteredListAddress(views[model.name], model.name, filter)} className={`${big} hover:text-primary-text after:absolute after:inset-0 after:content-['']`}>\n {total.toLocaleString(formatTag())}\n </AppLink>\n )\n}\n\nconst RecordValue = ({ field, format }: { field: string; format: StatProps['format'] }) => {\n const value = useScopedPathValue(field)\n if (value.state === 'loading') return <Skeleton className=\"h-8 w-16\" />\n if (value.state === 'missing') return null\n if (value.state === 'plain') return <span className={big}>{plainText(value.value)}</span>\n return (\n <span className={big}>\n <FieldValue model={value.model} field={value.field} value={value.value} format={format} />\n </span>\n )\n}\n\n/**\n * One number or value with a label: fixed, a count of matching records (linking to them from anywhere on the card), or\n * a field of the record. A label that wraps pushes nothing out of line: the value sits at the card's bottom.\n */\nexport const StatBlock = ({ node, at, className }: BlockProps) => {\n const { label, value, resource, filter, field, format, description } = propsOf<StatProps>(node)\n const { resources } = useAdminMeta()\n const model = resource === undefined ? undefined : resources[resource]\n return (\n <CardFrame className={cn('relative h-full', className)} bodyClassName=\"flex flex-col\">\n <p className=\"text-muted-foreground break-words\">{label}</p>\n <div className=\"mt-auto pt-1\">\n {value !== undefined && <span className={big}>{value}</span>}\n {model && <Count model={model} {...(at !== undefined && { at })} filter={filter} />}\n {field !== undefined && <RecordValue field={field} format={format} />}\n </div>\n {description && <p className=\"mt-1 text-xs text-muted-foreground\">{description}</p>}\n </CardFrame>\n )\n}\n","import { useCallback, useState } from 'react'\nimport type { ViewModel } from '@protobase/schema'\nimport { useIsXs } from '../../lib/use-media-query'\nimport { embeddedDisplay, embeddedDisplayKey, readPickedDisplay, writePickedDisplay } from './embedded-display'\n\n/**\n * The display an embedded list shows and the way to pick another, which is kept in local storage for the viewer under\n * `place`, the list's place in the app.\n */\nexport const useEmbeddedDisplay = (view: ViewModel | undefined, place: string, preferred?: string) => {\n const xs = useIsXs()\n const key = embeddedDisplayKey(place)\n const [picked, setPicked] = useState(() => readPickedDisplay(localStorage, key))\n const pick = useCallback(\n (display: string) => {\n setPicked(display)\n writePickedDisplay(localStorage, key, display)\n },\n [key],\n )\n return [embeddedDisplay(view, xs, { picked, preferred }), pick] as const\n}\n","import { useMemo, type ReactNode } from 'react'\nimport { columnName, type TableProps } from '@protobase/layout'\nimport type { AppAddress, ResourceModel } from '@protobase/schema'\nimport { DataGrid } from '../../../data-grid'\nimport { useIsDesktop, useIsXs } from '../../../lib/use-media-query'\nimport { listColumnNames } from '../../../live/columns-from-model'\nimport { recordId } from '../../../live/model-helpers'\nimport type { RouteTarget } from '../../../primitives/route-link'\nimport { embeddedColumns } from '../../embedded-list/embedded-columns'\nimport { embeddedRowTargets } from '../../embedded-list/embedded-row-targets'\nimport { useAdminMeta, usePermissions } from '../../meta-gate'\nimport { can } from '../../permissions'\nimport { useProjectUi } from '../project-ui'\nimport { withRowButton } from '../../row-button/row-button-column'\nimport { useAppAddress } from '../../use-app-address'\nimport { useLayoutList } from '../layout-list'\nimport { CardFrame, Quiet } from './card-frame'\nimport { phoneSpecs } from './table-phone-columns'\nimport { text } from '../messages'\n\ntype Props = Pick<TableProps, 'columns' | 'button' | 'title' | 'description' | 'empty'> & { model: ResourceModel; items: readonly unknown[]; actions: ReactNode; className?: string }\n\n// The list page's table over records the list around it read, in the list's order: it reads nothing of its own\nconst LoadedListTable = ({ model, items, columns, button, title, description, empty, actions, className }: Props) => {\n const { resources, views } = useAdminMeta()\n const view = views[model.name]\n const { fields: fieldTypes } = useProjectUi()\n const canUpdate = can(usePermissions(model.name), 'update')\n const { go, href } = useAppAddress()\n const xs = useIsXs()\n const narrow = !useIsDesktop()\n const names = useMemo(() => columns?.map(columnName) ?? listColumnNames(model, view), [columns, model, view])\n const all = useMemo(() => embeddedColumns(model, view, names, { resources, views, fieldTypes }), [model, view, names, resources, views, fieldTypes])\n const specs = useMemo(() => (xs ? phoneSpecs(columns)(all) : all), [xs, columns, all])\n const gridColumns = useMemo(() => (button ? withRowButton(specs, model, view, button, resources, narrow) : specs), [specs, model, view, button, resources, narrow])\n const rows = useMemo(() => items.map((item) => ({ ...(item as Record<string, unknown>), id: recordId(model, item as Record<string, unknown>) })), [items, model])\n const source = useMemo(() => ({ total: rows.length, rowAt: (index: number) => rows[index]! }), [rows])\n const targets = embeddedRowTargets({ model, view, opens: undefined, resources, views, canUpdate })\n const linkTo = (to: AppAddress): RouteTarget => ({ href: href(to), onFollow: () => go(to) })\n return (\n <CardFrame title={title} description={description} actions={actions} className={className}>\n {rows.length === 0 ? (\n <Quiet>{empty ?? text('nothingYet')}</Quiet>\n ) : (\n <DataGrid\n fit\n columns={gridColumns}\n source={source}\n latencyMs={0}\n onOpenRow={(row) => go(targets.address(row))}\n rowLink={(row) => linkTo(targets.address(row))}\n rowActions={targets.actions(linkTo)}\n rowNumbers={false}\n selectable={false}\n />\n )}\n </CardFrame>\n )\n}\n\n/** A `Table` without `resource`: the records of the list around it, as react-admin's DataTable draws its ListContext. */\nexport const ListTable = (props: Omit<Props, 'model' | 'items'>) => {\n const list = useLayoutList()\n if (!list?.model) return null\n return <LoadedListTable {...props} model={list.model} items={list.items} />\n}\n","import { useMemo, type ReactNode } from 'react'\nimport { columnName, type Styled, type TableProps } from '@protobase/layout'\nimport type { ResourceModel, ViewModel } from '@protobase/schema'\nimport { EmbeddedDisplaySwitch, EmbeddedList } from '../../embedded-list/embedded-list'\nimport { useEmbeddedDisplay } from '../../embedded-list/use-embedded-display'\nimport { useAdminMeta } from '../../meta-gate'\nimport { cn } from '../../../lib/cn'\nimport { propsOf, type BlockProps } from './block-props'\nimport { ListTable } from './list-table'\nimport { CardFrame } from './card-frame'\nimport { phoneSpecs } from './table-phone-columns'\nimport { GuardedParams } from '../../guarded-params'\nimport { ChosenRecord } from './chosen-record'\nimport { usePageParams } from '../page-params'\nimport type { RouteTarget } from '../../../primitives/route-link'\nimport { tableDisplay } from '@protobase/schema/internal'\nimport type { PlannedList } from '../../embedded-list/planned-embedded-rows'\nimport { usePlannedReads } from '../plan-reads'\n\ntype LoadedProps = Omit<TableProps, 'resource' | 'actions' | 'children' | 'select'> & {\n model: ResourceModel\n view: ViewModel | undefined\n actions: BlockProps['slots'][string]\n className?: string\n /** With `select`: where a row leads, the chosen row's key, and its children under the table. */\n chosen?: { rowTo: (key: string) => RouteTarget; key: string | undefined; details: ReactNode }\n /** Its rows and total from the page's planned reads, inside the records of another block. */\n planned?: PlannedList\n}\n\nconst LoadedTable = ({ model, view, filter = '', sort = '', columns, button, bulk, limit = 10, display: picked, title, description, empty, actions, className, chosen, planned }: LoadedProps) => {\n const [shown, pick] = useEmbeddedDisplay(view, `page:${model.name}:${title ?? ''}:${filter}`, picked)\n // A row is chosen in the table, so a table with `select` shows no other display\n const display = chosen ? tableDisplay : shown\n const names = useMemo(() => columns?.map(columnName), [columns])\n const phoneColumns = useMemo(() => phoneSpecs(columns), [columns])\n return (\n <CardFrame\n title={title}\n description={description}\n actions={\n <>\n {!chosen && <EmbeddedDisplaySwitch view={view} value={display} onChange={pick} />}\n {actions}\n </>\n }\n className={cn('h-full', className)}\n >\n <EmbeddedList model={model} view={view} filter={filter} sort={sort} columns={names} button={button} bulk={bulk} limit={limit} display={display} empty={empty} phoneColumns={phoneColumns} {...(chosen && { rowTo: chosen.rowTo, chosenKey: chosen.key })} {...(planned && { planned })} />\n {chosen?.details}\n </CardFrame>\n )\n}\n\n/**\n * The first `limit` records in `sort` order, in the list page's table, with its row button and, with `bulk`, the view's\n * bulk actions for the rows selected, or display, with a link to the whole list. A phone shows the columns `phoneSpecs`\n * picks. Without `resource`, the records of the list around it. With `select`, a row leads to the page with it chosen,\n * and the chosen row's children follow the table. Inside the records of another block, its rows and total per record\n * come from the page's planned reads.\n */\nexport const TableBlock = ({ node, at, slots, children, className }: BlockProps) => {\n const { className: _className, resource, select, children: _children, ...props } = propsOf<TableProps & Styled>(node)\n const { resources, views } = useAdminMeta()\n const [rows, total] = usePlannedReads([at, at === undefined ? undefined : `${at}#total`])\n const planned = useMemo(() => rows && { rows, total }, [rows, total])\n if (resource === undefined) return <ListTable {...props} actions={slots.actions} className={className} />\n const model = resources[resource]\n if (!model) return null\n if (select !== undefined) {\n return (\n <SelectTable {...props} model={model} view={views[model.name]} actions={slots.actions} className={className} select={select} {...(planned && { planned })}>\n {children}\n </SelectTable>\n )\n }\n return <LoadedTable {...props} model={model} view={views[model.name]} actions={slots.actions} className={className} {...(planned && { planned })} />\n}\n\n/** A table whose rows each link to the page with that row's key in the parameter `select`, and the chosen row's children under it. */\nconst SelectTable = ({ select, children, ...props }: Omit<LoadedProps, 'chosen'> & { select: string; children: ReactNode[] }) => {\n const { given, linkTo } = usePageParams()\n const rowTo = (key: string) => linkTo({ [select]: key })\n const key = given[select]\n // A form under the chosen row asks before another row replaces it\n const details = key === undefined ? null : <GuardedParams name={select}><ChosenRecord key={key} model={props.model} query={{ key }}>{children}</ChosenRecord></GuardedParams>\n return <LoadedTable {...props} chosen={{ rowTo, key, details }} />\n}\n","import { Fragment } from 'react'\nimport type { BlockProps } from './block-props'\nimport { cn } from '../../../lib/cn'\nimport { Link, useRouter } from '../../router'\nimport { shownPageTab, tabsOf, usePageTabsRoute } from '../page-tabs'\nimport { Problem } from '../problem'\nimport { text } from '../messages'\n\n/**\n * The page's tabs, each a link to its own address, and the shown tab alone (its children are the tabs, one each, in\n * order), so the others load nothing. On a phone they are a select. A name the page has no tab for, such as one the\n * user may not see, says so under the tabs.\n */\nexport const TabsBlock = ({ node, children, className }: BlockProps) => {\n const { tab: named, pathOf } = usePageTabsRoute()\n const { navigate } = useRouter()\n const tabs = tabsOf(node)\n const shown = shownPageTab(tabs, named)\n // The first tab is at the page's own address\n const path = (name: string) => pathOf(name === tabs[0]?.name ? undefined : name)\n return (\n <div className={cn('flex flex-col gap-6', className)}>\n <select aria-label={text('tabs')} value={shown?.name ?? ''} onChange={(event) => navigate(path(event.target.value))} className=\"h-9 rounded-md border border-border-strong bg-background px-2 font-medium md:hidden\">\n {!shown && <option value=\"\" disabled />}\n {tabs.map((tab) => (\n <option key={tab.name} value={tab.name}>\n {tab.label}\n </option>\n ))}\n </select>\n <nav aria-label={text('tabs')} className=\"hidden border-b md:block\">\n <ul className=\"flex gap-1\">\n {tabs.map((tab) => (\n <li key={tab.name}>\n <Link\n to={path(tab.name)}\n aria-current={tab === shown ? 'page' : undefined}\n className={cn('-mb-px inline-flex h-9 items-center whitespace-nowrap border-b-2 px-3 font-medium transition-colors', tab === shown ? 'border-foreground text-foreground' : 'border-transparent text-muted-foreground hover:text-foreground')}\n >\n {tab.label}\n </Link>\n </li>\n ))}\n </ul>\n </nav>\n {shown ? <Fragment key={shown.name}>{children[tabs.indexOf(shown)]}</Fragment> : <Problem>{text('noTab', { name: named ?? '' })}</Problem>}\n </div>\n )\n}\n\n/** One tab's elements, stacked as on the page. */\nexport const TabBlock = ({ children }: BlockProps) => <div className=\"flex flex-col gap-6\">{children}</div>\n","/** A list a thread reads newest first, a page at a time: the items loaded so far, and whether earlier ones are left. */\nexport type TimedList<T> = { items: T[]; more: boolean }\n\n// An item without a time sorts as the newest, as Postgres puts a null first when ordering newest first\nconst timeOf = (time: string | undefined) => (time === undefined ? Infinity : Date.parse(time))\n\n/**\n * Two lists read newest first, such as a thread's messages and its tool calls, as one newest first. Items older than\n * the oldest loaded of a list with earlier ones left are held back until those load, so nothing shows out of order. At\n * the same time, an item of `first` is newer than one of `second`, so the one of `second` shows before it.\n */\nexport const mergeByTime = <A extends { time: string | undefined }, B extends { time: string | undefined }>(first: TimedList<A>, second: TimedList<B>): (A | B)[] => {\n const oldest = (list: TimedList<{ time: string | undefined }>) => (list.more && list.items.length > 0 ? timeOf(list.items.at(-1)!.time) : -Infinity)\n const cutoff = Math.max(oldest(first), oldest(second))\n const merged: (A | B)[] = []\n let a = 0\n let b = 0\n while (a < first.items.length || b < second.items.length) {\n const takeFirst = b >= second.items.length || (a < first.items.length && timeOf(first.items[a]!.time) >= timeOf(second.items[b]!.time))\n const item = takeFirst ? first.items[a++]! : second.items[b++]!\n if (timeOf(item.time) < cutoff) break\n merged.push(item)\n }\n return merged\n}\n","import { Check, CircleAlert } from 'lucide-react'\nimport type { ToolCallState } from '@protobase/layout'\nimport { enumLabel, type FieldViewModel } from '@protobase/schema'\nimport { valueTone } from '../../live/value-color'\nimport { Spinner } from '../../primitives/spinner'\n\n/**\n * A message's or tool call's status in its view's label; a value the view colours `red`, such as a failed send, reads\n * as a problem. A tool call's `mark` draws its state before the label: a check when done, a spinner while running, and\n * an error as a problem.\n */\nexport const MessageStatus = ({ value, hints, mark }: { value: string; hints: FieldViewModel | undefined; mark?: ToolCallState }) => {\n const label = enumLabel(value, hints?.valueLabels)\n if (mark === 'done') {\n return (\n <span className=\"inline-flex items-center gap-1\">\n <Check aria-hidden className=\"size-3.5 shrink-0 text-success-text\" />\n {label}\n </span>\n )\n }\n if (mark === 'running') {\n return (\n <span className=\"inline-flex items-center gap-1\">\n <Spinner hidden className=\"size-3.5 shrink-0\" />\n {label}\n </span>\n )\n }\n if (mark !== 'error' && valueTone(hints?.valueColors, value) !== 'red') return label\n return (\n <span className=\"inline-flex items-center gap-1 text-danger-text\">\n <CircleAlert aria-hidden className=\"size-3.5 shrink-0\" />\n {label}\n </span>\n )\n}\n","import { ChevronRight } from 'lucide-react'\nimport { useId, useState, type ReactNode } from 'react'\nimport type { FieldViewModel } from '@protobase/schema'\nimport { cn } from '../../lib/cn'\nimport { Button } from '../../primitives/button'\nimport { CodeBlock } from '../../primitives/code-block'\nimport { JsonBlock } from '../field-types/json/json-block'\nimport { jsonOf, notJson } from '../field-types/json/json-text'\nimport { MessageStatus } from './message-status'\nimport type { ToolCall } from './tool-calls'\nimport { text } from './messages'\n\n// A value as pretty JSON; a text that holds JSON shows as the value it holds, any other text as written\nconst Value = ({ value }: { value: unknown }) => {\n const parsed = typeof value === 'string' ? jsonOf(value) : value\n return parsed === notJson ? <CodeBlock>{String(value)}</CodeBlock> : <JsonBlock value={parsed} />\n}\n\nconst Part = ({ label, children }: { label: string; children: ReactNode }) => (\n <div className=\"grid gap-1\">\n <p className=\"text-xs font-medium text-muted-foreground\">{label}</p>\n {children}\n </div>\n)\n\n/**\n * A tool call between a thread's messages: its tool's name and its status with its mark, and a toggle, closed at\n * first, that opens to its input and result as pretty JSON and its error.\n */\nexport const ToolCallItem = ({ call, statusHints }: { call: ToolCall; statusHints: FieldViewModel | undefined }) => {\n const [open, setOpen] = useState(false)\n const id = useId()\n const status = call.status !== undefined && <MessageStatus value={call.status} hints={statusHints} mark={call.state} />\n const name = <span className=\"font-mono text-xs text-foreground\">{call.name}</span>\n const opens = call.input !== undefined || call.result !== undefined || call.error !== undefined\n return (\n <div data-tool-call className=\"flex min-w-0 flex-col gap-1 pl-11 text-xs text-muted-foreground\">\n {opens ? (\n <Button size=\"sm\" variant=\"ghost\" className=\"-ml-2.5 self-start\" aria-expanded={open} aria-controls={id} onClick={() => setOpen(!open)}>\n <ChevronRight aria-hidden className={cn('size-3.5 transition-transform', open && 'rotate-90')} />\n {name}\n {status}\n </Button>\n ) : (\n <p className=\"flex items-center gap-1.5\">\n {name}\n {status}\n </p>\n )}\n {open && (\n <div id={id} className=\"grid gap-2\">\n {call.input !== undefined && <Part label={text('callInput')}><Value value={call.input} /></Part>}\n {call.result !== undefined && <Part label={text('callResult')}><Value value={call.result} /></Part>}\n {call.error !== undefined && <Part label={text('callError')}><CodeBlock>{call.error}</CodeBlock></Part>}\n </div>\n )}\n </div>\n )\n}\n","import type { ChatAuthor } from '../../chat'\nimport { chatDayLabel, sameChatDay } from '../../chat/chat-day'\nimport type { ToolCall } from './tool-calls'\n\ntype Row = Record<string, unknown>\n\nexport type ThreadFields = { key: (row: Row) => string; sender?: string; time: string; text: string; status?: string }\n\n/** A message record of a thread with its time, read to order it among the thread's tool calls. */\nexport type MessageRow = { kind: 'message'; row: Row; time: string | undefined }\n\n/** The message records of a thread with the time each was sent, in the order read. */\nexport const messageRows = (rows: Row[], time: string): MessageRow[] => rows.map((row) => ({ kind: 'message', row, time: typeof row[time] === 'string' ? (row[time] as string) : undefined }))\n\n/**\n * One line of a thread: a day's divider, a message under its sender, or with no `author` one author's, `continued`\n * after one of theirs that day, with its status when it has one, or a tool call.\n */\nexport type ThreadItem =\n | { kind: 'day'; key: string; label: string }\n | { kind: 'message'; key: string; author?: ChatAuthor; time: string | undefined; text: string; status?: string; continued: boolean }\n | ToolCall\n\n// A relation comes named as `{ id, name }` (`withLabels`); any other sender is its own name\nconst authorOf = (value: unknown): ChatAuthor => {\n if (typeof value === 'object' && value !== null && 'id' in value) {\n const { id, name } = value as { id: unknown; name?: unknown }\n return { id: String(id), ...(typeof name === 'string' && { name }) }\n }\n return { id: String(value ?? ''), ...(typeof value === 'string' && { name: value }) }\n}\n\n/**\n * The messages and tool calls of a thread, read newest first, as its lines oldest first: a day divider above each day's\n * first item, and a message that follows its sender's on the same day, with no tool call between, drawn as continued.\n */\nexport const threadItems = (newestFirst: (MessageRow | ToolCall)[], { key, sender, text, status }: ThreadFields, now = Date.now()): ThreadItem[] => {\n const items: ThreadItem[] = []\n let previous: { author: string | undefined; time: string | undefined } | undefined\n for (const entry of [...newestFirst].reverse()) {\n const sent = entry.time\n const sameDay = previous?.time !== undefined && sent !== undefined && sameChatDay(previous.time, sent)\n if (sent !== undefined && !sameDay) items.push({ kind: 'day', key: `day:${entry.kind === 'call' ? entry.key : key(entry.row)}`, label: chatDayLabel(sent, now) })\n if (entry.kind === 'call') {\n items.push(entry)\n previous = { author: undefined, time: sent }\n continue\n }\n const { row } = entry\n // A thread without a sender is one author's, whose messages all follow each other\n const author = sender === undefined ? undefined : authorOf(row[sender])\n const id = author?.id ?? ''\n const state = status === undefined || row[status] == null || row[status] === '' ? undefined : String(row[status])\n items.push({ kind: 'message', key: key(row), ...(author && { author }), time: sent, text: row[text] == null ? '' : String(row[text]), ...(state !== undefined && { status: state }), continued: sameDay && previous?.author === id })\n previous = { author: id, time: sent }\n }\n return items\n}\n","import { toolCallStates, type ToolCallState } from '@protobase/layout'\nimport type { ToolCallFields } from '@protobase/schema'\n\ntype Row = Record<string, unknown>\n\n/** A tool call of a thread: its tool's name, when it was called, its status and the mark that status gives, and what opens under it. */\nexport type ToolCall = { kind: 'call'; key: string; name: string; time: string | undefined; status?: string; state?: ToolCallState; input?: unknown; result?: unknown; error?: string }\n\nconst stateOf = (value: string | undefined) => (toolCallStates as readonly string[]).includes(value ?? '') ? (value as ToolCallState) : undefined\n\nconst textOf = (value: unknown) => (value == null || value === '' ? undefined : String(value))\n\n/** A call's React key from its record key; JSON keeps composite keys such as `['a,b']` and `['a', 'b']` apart. */\nexport const callKey = (key: unknown) => `call:${JSON.stringify(key)}`\n\n/** A record of a thread's tool call resource as the call it draws, by the fields the thread reads of it. */\nexport const toolCallOf = (row: Row, key: string, fields: ToolCallFields): ToolCall => {\n const status = textOf(row[fields.status])\n const state = stateOf(status)\n const input = fields.input === undefined ? undefined : row[fields.input]\n const result = fields.result === undefined ? undefined : row[fields.result]\n const error = fields.error === undefined ? undefined : textOf(row[fields.error])\n return {\n kind: 'call',\n key,\n name: String(row[fields.name] ?? ''),\n time: typeof row[fields.time] === 'string' ? (row[fields.time] as string) : undefined,\n ...(status !== undefined && { status }),\n ...(state !== undefined && { state }),\n ...(input != null && { input }),\n ...(result != null && { result }),\n ...(error !== undefined && { error }),\n }\n}\n","import type { Planned } from '../pages/planned'\n\n/** What a thread draws of one of its lists, its messages or its tool calls, as `useList` gives it. */\nexport type ThreadList = {\n items: Record<string, unknown>[]\n labels: Record<string, Record<string, string>>\n hasNextPage: boolean\n isFetchingNextPage: boolean\n isFetchNextPageError: boolean\n isLoading: boolean\n error: Error | null\n fetchNextPage: () => unknown\n refetch: () => unknown\n}\n\ntype State = {\n /** The latest records the page's planned read holds for it, inside the records of another block. */\n planned: Planned | undefined\n /** How many the planned read gives each record at most: as many mean earlier ones may be left. */\n limit: number\n /** Whether earlier records were asked for, so it reads its pages itself from then on. */\n expanded: boolean\n expand: () => void\n /** Its own read, which reads nothing until it is expanded when planned. */\n own: ThreadList & { pages: number }\n}\n\n/**\n * The list a thread draws: the planned latest records until earlier ones are asked for, which its own read then gives\n * from its first page and the one after it, the planned records staying while it reads them or until it reads one\n * after failing; its own read without one.\n */\nexport const threadListOf = ({ planned, limit, expanded, expand, own }: State): ThreadList => {\n if (!planned) return own\n const reading = expanded && !own.error && own.pages < 2 && (own.pages === 0 || own.hasNextPage)\n const plannedList = {\n items: planned.rows,\n labels: planned.labels ?? {},\n hasNextPage: planned.rows.length >= limit,\n isFetchingNextPage: reading,\n isFetchNextPageError: false,\n isLoading: planned.isPending,\n }\n // Its own read failed before its first page: the planned records stay, with its error, and trying again reads it again\n if (expanded && own.error && own.pages === 0) return { ...plannedList, error: own.error, fetchNextPage: own.refetch, refetch: own.refetch }\n if (expanded && !reading) return own\n // A planned read that failed is read again as its own\n return { ...plannedList, error: planned.error, fetchNextPage: expand, refetch: expand }\n}\n","import { useEffect, useState } from 'react'\nimport { useList, type UseListParams } from '../../data/use-list'\nimport type { Planned } from '../pages/planned'\nimport { threadListOf } from './planned-thread-list'\n\n/**\n * One list of a thread, its messages or its tool calls: from the page's planned read when it has one, earlier records\n * read by itself on request, and otherwise read by itself; nothing is read while not `enabled`.\n */\nexport const useThreadList = (resource: string, { pageSize = 50, enabled = true, ...request }: UseListParams, planned: Planned | undefined) => {\n const [expanded, setExpanded] = useState(false)\n const list = useList(resource, { ...request, pageSize, enabled: enabled && (!planned || expanded) })\n const pages = list.data?.pages.length ?? 0\n const { hasNextPage, isFetchingNextPage, fetchNextPage, error } = list\n // Asking a planned thread for earlier records reads its first page and then the one after it\n useEffect(() => {\n if (planned && expanded && !error && pages === 1 && hasNextPage && !isFetchingNextPage) void fetchNextPage()\n }, [planned, expanded, error, pages, hasNextPage, isFetchingNextPage, fetchNextPage])\n return threadListOf({ planned, limit: pageSize, expanded, expand: () => setExpanded(true), own: { ...list, pages } })\n}\n","import { threadSort } from '@protobase/layout'\nimport type { ResourceModel, ToolCallFields } from '@protobase/schema'\nimport { recordKey } from '../../live/model-helpers'\nimport { useAdminMeta } from '../meta-gate'\nimport type { Planned } from '../pages/planned'\nimport { callKey, toolCallOf } from './tool-calls'\nimport { useThreadList } from './use-thread-list'\n\n/**\n * The latest `limit` tool calls of a thread, newest first, from the page's `planned` read when it has one, with earlier\n * ones on request; none without `calls`.\n */\nexport const useToolCalls = (calls: { model: ResourceModel; filter?: string; fields: ToolCallFields } | undefined, limit: number, planned?: Planned) => {\n const { views } = useAdminMeta()\n const name = calls?.model.name ?? ''\n const list = useThreadList(name, { filter: calls?.filter, orderBy: calls && threadSort(calls.fields.time), pageSize: limit, enabled: calls !== undefined }, planned)\n if (!calls) return { calls: [], hasNextPage: false, isFetchingNextPage: false, list, statusHints: undefined }\n return {\n calls: list.items.map((row) => toolCallOf(row, callKey(recordKey(calls.model, row)), calls.fields)),\n hasNextPage: list.hasNextPage,\n isFetchingNextPage: list.isFetchingNextPage,\n list,\n statusHints: views[name]?.fields[calls.fields.status],\n }\n}\n","type ThreadList = { error: unknown; isLoading: boolean; items: unknown[] }\n\n/**\n * What a thread shows of its list: the error only while no message has loaded, so a failed refetch keeps the messages\n * on screen and the reader's place in them; then its loading line until the first page arrives; then the messages.\n */\nexport const threadState = (list: ThreadList) => {\n if (list.items.length > 0) return 'messages'\n if (list.error) return 'error'\n if (list.isLoading) return 'loading'\n return 'messages'\n}\n\n/** What an empty thread says: its loading line while its calls still load, so it never says empty before they arrive. */\nexport const emptyLine = (calls: { isLoading: boolean }, lines: { loading: string; empty: string }) => (calls.isLoading ? lines.loading : lines.empty)\n\n/** Whether a failed refetch or **Load earlier messages** shows its error above the messages that stay loaded. */\nexport const showsErrorAbove = (list: ThreadList) => list.items.length > 0 && Boolean(list.error)\n\ntype RetryableList = { isFetchNextPageError: boolean; fetchNextPage: () => unknown; refetch: () => unknown }\n\n/** What **Try again** runs on a thread's error: the earlier messages when loading them failed, else the thread again. */\nexport const retryOf = (list: RetryableList) => (list.isFetchNextPageError ? () => void list.fetchNextPage() : () => void list.refetch())\n","import { threadSort, type MessageFields } from '@protobase/layout'\nimport type { ResourceModel, ToolCallFields } from '@protobase/schema'\nimport { ChatDivider, ChatMessage, ChatThread } from '../../chat'\nimport { useOptionalAuth } from '../../auth/auth-provider'\nimport { recordKey } from '../../live/model-helpers'\nimport { listLabels, withLabels } from '../../live/relation-labels'\nimport { Markdown } from '../../markdown/markdown'\nimport { isMarkdown } from '../../markdown/markdown-hint'\nimport { Quiet } from '../pages/blocks/card-frame'\nimport { ErrorBanner } from '../error-banner'\nimport { useAdminMeta } from '../meta-gate'\nimport { mergeByTime } from './merge-by-time'\nimport { MessageStatus } from './message-status'\nimport { ToolCallItem } from './tool-call-item'\nimport { messageRows, threadItems } from './thread-items'\nimport { useToolCalls } from './use-tool-calls'\nimport { useThreadList } from './use-thread-list'\nimport type { Planned } from '../pages/planned'\nimport { emptyLine, retryOf, showsErrorAbove, threadState } from './thread-state'\nimport { text } from './messages'\n\n// Each list with earlier items left loads its next page\nconst loadEarlier = (lists: { hasNextPage: boolean; fetchNextPage: () => unknown }[]) => {\n for (const each of lists) if (each.hasNextPage) void each.fetchNextPage()\n}\n\nexport type MessageThreadProps = MessageFields & {\n model: ResourceModel\n /** An AIP-160 filter on the messages, such as the record's key in its relation. */\n filter?: string\n limit?: number\n empty?: string\n /** Whether the other side is writing a reply, which the thread's end says; left out, it never says. */\n working?: boolean\n /** The tool calls drawn between the messages in time order: records of `calls.model` matching `calls.filter`, read by `calls.fields`. */\n calls?: { model: ResourceModel; filter?: string; fields: ToolCallFields }\n /** Its latest messages and tool calls from the page's planned reads, inside the records of another block. */\n planned?: { messages: Planned | undefined; calls: Planned | undefined }\n}\n\n/**\n * The latest `limit` messages of `model` matching `filter`, oldest first, each under its sender's name and time, or its\n * time alone without `sender`, with\n * earlier ones on request, and its `status` under it in the view's enum labels; a text the message resource's view marks\n * `.markdown()` shows rendered. The latest `limit` of its `calls` show between them in time order. Planned, it reads\n * only its earlier ones itself.\n */\nexport const MessageThread = ({ model, filter, sender, time, text: body, status, limit = 50, empty, working, calls, planned }: MessageThreadProps) => {\n const { resources, views } = useAdminMeta()\n const auth = useOptionalAuth()\n const reader = auth?.state.kind === 'signed-in' ? auth.state.user.id : undefined\n const senders = sender === undefined ? [] : [sender]\n const labels = listLabels(resources, views, model, senders)\n const list = useThreadList(model.name, { filter, orderBy: threadSort(time), pageSize: limit, labels }, planned?.messages)\n const callList = useToolCalls(calls, limit, planned?.calls)\n const state = threadState(list)\n if (state === 'error') return <ErrorBanner title={text('couldNotLoad')} error={list.error} onRetry={retryOf(list)} />\n // The live region mounts with the messages it opens on, so a screen reader announces only those that arrive later\n if (state === 'loading') return <div className=\"p-4\"><Quiet>{text('loadingMessages')}</Quiet></div>\n const rows = withLabels(resources, model, senders, list.items, list.labels)\n // A call shows after a message sent at the same time\n const newestFirst = mergeByTime({ items: callList.calls, more: callList.hasNextPage }, { items: messageRows(rows, time), more: list.hasNextPage })\n const items = threadItems(newestFirst, { key: (row) => String(recordKey(model, row)), sender, time, text: body, status })\n const statusHints = status === undefined ? undefined : views[model.name]?.fields[status]\n const markdown = model.fields[body] !== undefined && isMarkdown(model.fields[body], views[model.name]?.fields[body])\n // The reader's own newest message: when one arrives, the thread goes to the end wherever they were\n const own = items.findLast((item) => item.kind === 'message' && item.author !== undefined && item.author.id === reader)\n return (\n <>\n {/* The messages stay, so the reader keeps their place; Try again runs what failed once more */}\n {showsErrorAbove(list) && <div className=\"shrink-0 p-2\"><ErrorBanner title={text('couldNotLoad')} error={list.error} onRetry={retryOf(list)} /></div>}\n {calls && callList.list.error && <div className=\"shrink-0 p-2\"><ErrorBanner title={text('couldNotLoadCalls')} error={callList.list.error} onRetry={retryOf(callList.list)} /></div>}\n <ChatThread\n length={newestFirst.length}\n followKey={own?.key}\n working={working}\n empty={emptyLine(callList.list, { loading: text('loadingMessages'), empty: empty ?? text('noMessages') })}\n onLoadEarlier={list.hasNextPage || callList.hasNextPage ? () => loadEarlier([list, callList.list]) : undefined}\n loadingEarlier={list.isFetchingNextPage || callList.isFetchingNextPage}\n >\n {items.map((item) =>\n item.kind === 'day' ? (\n <ChatDivider key={item.key} label={item.label} />\n ) : item.kind === 'call' ? (\n <ToolCallItem key={item.key} call={item} statusHints={callList.statusHints} />\n ) : (\n <ChatMessage key={item.key} {...(item.author ? { author: item.author } : { alone: true as const })} time={item.time} continued={item.continued} footer={item.status !== undefined && <MessageStatus value={item.status} hints={statusHints} />}>\n {/* A message keeps its line breaks; rendered markdown makes its own */}\n {markdown && item.text !== '' ? <Markdown source={item.text} className=\"whitespace-normal\" /> : item.text}\n </ChatMessage>\n ),\n )}\n </ChatThread>\n </>\n )\n}\n","import type { ReactNode } from 'react'\n\n/**\n * The box a thread scrolls in. It scrolls inside a box of its own, not with the page, so it can open at the newest\n * message and follow the ones that arrive, with what comes after it, such as a composer, in view beneath.\n */\nexport const ThreadBox = ({ children }: { children: ReactNode }) => <div className=\"flex h-[min(36rem,65dvh)] flex-col rounded-lg border border-border bg-background\">{children}</div>\n","import type { ThreadProps } from '@protobase/layout'\nimport { SectionContent } from '../../../record-view/section'\nimport { MessageThread } from '../../conversation/message-thread'\nimport { ThreadBox } from '../../conversation/thread-box'\nimport { useAdminMeta } from '../../meta-gate'\nimport { usePlannedReads } from '../plan-reads'\nimport { useScopeStack } from '../record-scope'\nimport { useStackConditions } from '../use-conditions'\nimport { cn } from '../../../lib/cn'\nimport { propsOf, type BlockProps } from './block-props'\n\n/**\n * The latest messages of a resource, oldest first, under their sender's name and time and over their status, with\n * earlier ones on request, ending in a working indicator while `working` holds for the record around it, with the\n * tool calls of `calls` between them in time order. Inside the records of another block, its latest messages and\n * tool calls come from the page's planned reads.\n */\nexport const ThreadBlock = ({ node, at, slots, className }: BlockProps) => {\n const { title, description, resource, filter, sender, time, text, status, working, calls, limit, empty } = propsOf<ThreadProps>(node)\n const { resources } = useAdminMeta()\n const [busy] = useStackConditions(working === undefined ? [] : [working], useScopeStack())\n const [messages, plannedCalls] = usePlannedReads([at, at === undefined ? undefined : `${at}#calls`])\n const model = resources[resource]\n if (!model) return null\n const callsModel = calls && resources[calls.resource]\n return (\n <section className={cn('flex min-w-0 flex-col', className)} aria-label={title}>\n <SectionContent title={title} help={description} actions={slots.actions}>\n <ThreadBox>\n <MessageThread model={model} filter={filter} sender={sender} time={time} text={text} status={status} calls={calls && callsModel && { model: callsModel, filter: calls.filter, fields: calls }} limit={limit} empty={empty} working={working === undefined ? undefined : busy === true} {...((messages || plannedCalls) && { planned: { messages, calls: plannedCalls } })} />\n </ThreadBox>\n </SectionContent>\n </section>\n )\n}\n","import type { TextProps } from '@protobase/layout'\nimport { cn } from '../../../lib/cn'\nimport { propsOf, type BlockProps } from './block-props'\n\n// The plain elements look like nothing of their own: their classes say how they look.\n\n/** An element of its own, such as a panel or a banner. */\nexport const BoxBlock = ({ children, className }: BlockProps) => <div className={className}>{children}</div>\n\n/** Its children side by side. */\nexport const RowBlock = ({ children, className }: BlockProps) => <div className={cn('flex', className)}>{children}</div>\n\n/** Its children one under another. */\nexport const ColumnBlock = ({ children, className }: BlockProps) => <div className={cn('flex flex-col', className)}>{children}</div>\n\n/** Text and links in it, as a paragraph, a piece of a line or a heading. */\nexport const TextBlock = ({ node, children, className }: BlockProps) => {\n const { as: Tag = 'p' } = propsOf<TextProps>(node)\n return <Tag className={className}>{children}</Tag>\n}\n","import { scopeValue, type ArrayFieldProps } from '@protobase/layout'\nimport { useMemo } from 'react'\nimport { LayoutListScope } from '../layout-list'\nimport { useScopeStack, valueScopeOf } from '../record-scope'\nimport { propsOf, type BlockProps } from './block-props'\n\n/** The items of a JSON list the record around it holds, as a list its children draw, as react-admin's ArrayField. */\nexport const ArrayFieldBlock = ({ node, children }: BlockProps) => {\n const { source } = propsOf<ArrayFieldProps>(node)\n const held = scopeValue(valueScopeOf(useScopeStack()), source)\n const list = useMemo(() => ({ items: Array.isArray(held) ? held : [] }), [held])\n return <LayoutListScope value={list}>{children}</LayoutListScope>\n}\n","import type { SelectInputProps } from '@protobase/layout'\nimport { cn } from '../../../lib/cn'\nimport { MenuSelect } from '../../../primitives/menu-select'\nimport { usePageParams } from '../page-params'\nimport { propsOf, type BlockProps } from './block-props'\n\n/**\n * The page parameter `source` under its label, as react-admin's SelectInput draws a choice: a select whose every choice\n * is a link to the page with it chosen, its default leaving the parameter out. Without choices, the value the address\n * gives, as text.\n */\nexport const SelectInputBlock = ({ node, className }: BlockProps) => {\n const { source, choices, label = source, defaultValue } = propsOf<SelectInputProps>(node)\n const { values, linkTo } = usePageParams()\n const value = values[source]\n return (\n <div className={cn('flex flex-wrap items-center gap-2', className)}>\n <span className=\"font-medium text-muted-foreground\">{label}</span>\n {choices ? (\n <MenuSelect\n label={label}\n value={value ?? ''}\n options={choices.map((choice) => ({ value: String(choice.id), label: choice.name }))}\n link={(id) => linkTo({ [source]: defaultValue !== undefined && id === String(defaultValue) ? undefined : id })}\n />\n ) : (\n <span>{value}</span>\n )}\n </div>\n )\n}\n","import type { ResourceModel } from '@protobase/schema'\nimport type { LayoutList } from './layout-list'\nimport type { Planned } from './planned'\n\n/** Where a list's own read stands: the pages it read so far, their records, and whether one more is there. */\nexport type OwnRead = {\n pages: number\n items: Record<string, unknown>[]\n hasNextPage: boolean\n isFetchingNextPage: boolean\n isPending: boolean\n error: Error | null\n fetchNextPage: () => unknown\n}\n\ntype State = {\n model: ResourceModel\n /** `undefined` when no record can match. */\n filter: string | undefined\n perPage: number\n more: boolean\n planned: Planned | undefined\n /** Whether a planned list's button was clicked, so it reads its pages itself from then on. */\n expanded: boolean\n expand: () => void\n own: OwnRead\n}\n\n/** The list a list block draws and the read it shows the state of, from its planned rows or its own read. */\nexport const relatedListOf = ({ model, filter, perPage, more, planned, expanded, expand, own }: State): { read: { isPending: boolean; error: Error | null }; list: LayoutList } => {\n if (filter === undefined) return { read: { isPending: false, error: null }, list: { model, items: [] } }\n if (planned && !expanded) {\n const items = planned.rows.slice(0, perPage)\n const loadMore = more && items.length === perPage ? expand : undefined\n return { read: planned, list: { model, items, planned: true, ...(loadMore && { loadMore }) } }\n }\n // While a planned list reads its first two pages, its planned rows stay, still planned, the button loading\n if (planned && !own.error && own.pages < 2 && (own.pages === 0 || own.hasNextPage)) {\n return { read: planned, list: { model, items: planned.rows.slice(0, perPage), planned: true, loadMore: () => {}, loadingMore: true } }\n }\n // The rows the list read itself are its own, so the reads planned inside them no longer hold theirs\n const loadMore = more && own.hasNextPage ? () => void own.fetchNextPage() : undefined\n return { read: { isPending: own.isPending, error: own.error }, list: { model, items: own.items, ...(loadMore && { loadMore, loadingMore: own.isFetchingNextPage }) } }\n}\n","import { useEffect, useState } from 'react'\nimport type { ResourceModel } from '@protobase/schema'\nimport { useList } from '../../data/use-list'\nimport type { LayoutList } from './layout-list'\nimport type { Planned } from './planned'\nimport { relatedListOf } from './related-list-of'\n\ntype Request = {\n model: ResourceModel\n /** `undefined` when no record can match, such as when the record around it holds no value to tie the list by. */\n filter: string | undefined\n sort: string\n perPage: number\n /** Whether a button reads the next `perPage` records into the same list. */\n more: boolean\n /** The rows the page's planned read holds for it, which it draws instead of reading them itself. */\n planned?: Planned\n}\n\n/**\n * The first `perPage` records of `model` a list block reads, from the page's planned read or a read of its own, and\n * with `more` each next page added to the same list. Nothing is read when no record can match. A planned list's next\n * pages are a read of the list's own, from its first page, the planned rows staying on screen meanwhile.\n */\nexport const useRelatedList = ({ model, filter, sort, perPage, more, planned }: Request): { read: { isPending: boolean; error: Error | null }; list: LayoutList } => {\n const [expanded, setExpanded] = useState(false)\n const query = useList(model.name, { filter, orderBy: sort, pageSize: perPage, enabled: filter !== undefined && (!planned || expanded) })\n const pages = query.data?.pages.length ?? 0\n const { hasNextPage, isFetchingNextPage, fetchNextPage, error } = query\n // The first click on a planned list reads its first page and then the one after it\n useEffect(() => {\n if (planned && expanded && !error && pages === 1 && hasNextPage && !isFetchingNextPage) void fetchNextPage()\n }, [planned, expanded, error, pages, hasNextPage, isFetchingNextPage, fetchNextPage])\n const own = { pages, items: query.items, hasNextPage, isFetchingNextPage, isPending: query.isPending, error, fetchNextPage }\n return relatedListOf({ model, filter, perPage, more, planned, expanded, expand: () => setExpanded(true), own })\n}\n","import { referenceManyRead, scopeLookup, type ReferenceManyFieldProps } from '@protobase/layout'\nimport { useAdminMeta } from '../../meta-gate'\nimport { ListBody } from '../layout-list'\nimport { useScopeStack, valueScopeOf } from '../record-scope'\nimport { usePlanned } from '../plan-reads'\nimport { useRelatedList } from '../use-related-list'\nimport { propsOf, type BlockProps } from './block-props'\n\n/**\n * The records of `reference` whose `target` holds the record's `source`, as a list its children draw, as react-admin's\n * ReferenceManyField: its key descending unless `sort` says otherwise, `empty` when none match, and with\n * `pagination=\"more\"` a button that reads the next page. On a page, its rows come from the page's planned read.\n */\nexport const ReferenceManyFieldBlock = ({ node, at, children }: BlockProps) => {\n const props = propsOf<ReferenceManyFieldProps>(node)\n const model = useAdminMeta().resources[props.reference]\n const lookup = scopeLookup(valueScopeOf(useScopeStack()))\n const planned = usePlanned(at)\n if (!model) return null\n return (\n <RelatedList model={model} {...referenceManyRead(props, model.primaryKey[0]!, lookup)} more={props.pagination === 'more'} empty={props.empty} {...(planned && { planned })}>\n {children}\n </RelatedList>\n )\n}\n\ntype ListProps = Parameters<typeof useRelatedList>[0] & { empty?: string; children: BlockProps['children'] }\n\n/** A list block's read and what it draws of it. */\nexport const RelatedList = ({ empty, children, ...request }: ListProps) => {\n const { read, list } = useRelatedList(request)\n return (\n <ListBody read={read} list={list} empty={empty}>\n {children}\n </ListBody>\n )\n}\n","import { referenceArrayRead, scopeLookup, type ReferenceArrayFieldProps } from '@protobase/layout'\nimport { useAdminMeta } from '../../meta-gate'\nimport { useScopeStack, valueScopeOf } from '../record-scope'\nimport { usePlanned } from '../plan-reads'\nimport { propsOf, type BlockProps } from './block-props'\nimport { RelatedList } from './reference-many-field'\n\n/**\n * The records of `reference` whose keys the record's `source`, a JSON list, holds, as a list its children draw, as\n * react-admin's ReferenceArrayField: one read with `in()`, its filter and sort, by default its key descending; on a\n * page, the rows of the page's planned read.\n */\nexport const ReferenceArrayFieldBlock = ({ node, at, children }: BlockProps) => {\n const props = propsOf<ReferenceArrayFieldProps>(node)\n const model = useAdminMeta().resources[props.reference]\n const lookup = scopeLookup(valueScopeOf(useScopeStack()))\n const planned = usePlanned(at)\n if (!model) return null\n return (\n <RelatedList model={model} {...referenceArrayRead(props, model.primaryKey[0]!, lookup)} more={false} empty={props.empty} {...(planned && { planned })}>\n {children}\n </RelatedList>\n )\n}\n","import type { ReactNode } from 'react'\nimport { scopeValue, type ReferenceFieldProps } from '@protobase/layout'\nimport type { ResourceModel } from '@protobase/schema'\nimport { recordTitle } from '@protobase/schema/internal'\nimport { Skeleton } from '../../../primitives/skeleton'\nimport { ErrorBanner } from '../../error-banner'\nimport { useAdminMeta } from '../../meta-gate'\nimport { AppLink } from '../../use-app-address'\nimport { RecordScope, useScopeStack, valueScopeOf } from '../record-scope'\nimport { usePlanned } from '../plan-reads'\nimport { plannedRecord, useFirstRecord } from '../use-layout-data'\nimport { propsOf, type BlockProps } from './block-props'\nimport { text } from '../messages'\n\ntype LoadedProps = { model: ResourceModel; at?: string; recordKey: string; link: ReferenceFieldProps['link']; children: ReactNode[]; className?: string }\n\n// The record its key names, from the page's planned read or one of its own, its children inside it or its title, linked\n// to its page unless `link` is false\nconst LoadedReference = ({ model, at, recordKey, link = 'edit', children, className }: LoadedProps) => {\n const { views } = useAdminMeta()\n const planned = usePlanned(at)\n const own = useFirstRecord(model, { key: recordKey, enabled: !planned })\n const record = planned ? plannedRecord(model, planned) : own\n if (record.isPending) return <Skeleton className=\"h-4 w-24\" />\n if (record.error) return <ErrorBanner title={text('couldNotLoad')} error={record.error} />\n if (!record.data) return null\n const shown = children.length > 0 ? (\n <RecordScope value={record.data}>{children}</RecordScope>\n ) : recordTitle(model, views[model.name], record.data.record, recordKey)\n if (link === false) return <span className={className}>{shown}</span>\n return (\n <AppLink to={{ kind: 'record', resource: model.name, key: recordKey }} className={className ?? 'font-medium text-primary-text hover:underline'}>\n {shown}\n </AppLink>\n )\n}\n\n/**\n * The record of `reference` the record's `source` points at, as react-admin's ReferenceField: its children inside that\n * record, or its title, as a link to the record's page; `empty` when the field holds none.\n */\nexport const ReferenceFieldBlock = ({ node, at, children, className }: BlockProps) => {\n const { reference, source, link, empty } = propsOf<ReferenceFieldProps>(node)\n const model = useAdminMeta().resources[reference]\n const value = scopeValue(valueScopeOf(useScopeStack()), source)\n if (!model) return null\n if (value === null || value === undefined || value === '') return empty === undefined ? null : <span className={className}>{empty}</span>\n return (\n <LoadedReference model={model} {...(at !== undefined && { at })} recordKey={String(value)} link={link} className={className}>\n {children}\n </LoadedReference>\n )\n}\n","import type { RoleLabel } from '@protobase/client'\nimport { roleLabel } from '../organizations/organization-paths'\n\n/** The labels of `names`, as the server names the roles, in one line. */\nexport const roleNames = (roles: readonly RoleLabel[], names: readonly string[]) => names.map((name) => roleLabel(roles, name)).join(', ')\n","import { messages } from '../locale/messages'\n\nexport const text = messages('users')\n","import { useCallback, useEffect, useState } from 'react'\nimport type { RoleLabel, UserInvitation } from '@protobase/client'\nimport { AccountSection } from '../account/account-section'\nimport { useAuth } from '../auth/auth-provider'\nimport { InviteForm } from '../invitations/invite-form'\nimport { PendingInvitationRow } from '../invitations/pending-invitation-row'\nimport { AppRolesPicker } from '../organizations/app-roles-picker'\nimport { roleNames } from './role-names'\nimport { text } from './messages'\n\n/** Inviting someone to the app with the roles their account gets, and the invitations not accepted yet. */\nexport const AppInvitations = ({ roles }: { roles: readonly RoleLabel[] }) => {\n const { session } = useAuth()\n const [selected, setSelected] = useState<string[]>([])\n const [invitations, setInvitations] = useState<UserInvitation[]>([])\n const load = useCallback(() => void session.users.invitations().then(setInvitations, () => setInvitations([])), [session])\n useEffect(load, [load])\n const invite = async (email: string) => {\n const sent = await session.users.invite({ email, roles: selected })\n setSelected([])\n load()\n return sent\n }\n return (\n <>\n <InviteForm title={text('inviteSomeone')} description={text('inviteDescription')} onInvite={invite} incomplete={selected.length === 0}>\n <AppRolesPicker roles={roles} selected={selected} grantable={new Set(roles.map((role) => role.name))} onChange={setSelected} />\n </InviteForm>\n <AccountSection title={text('notAcceptedYet')} description={invitations.length > 0 ? text('sendingAgain') : text('nobodyWaiting')}>\n {invitations.length > 0 && (\n <ul className=\"divide-y rounded-md border\">\n {invitations.map((invitation) => (\n <PendingInvitationRow\n key={invitation.id}\n email={invitation.email}\n gives={roleNames(roles, invitation.roles)}\n expiresAt={invitation.expiresAt}\n onResend={async () => {\n const sent = await session.users.invite({ email: invitation.email, roles: invitation.roles })\n load()\n return sent\n }}\n onRevoke={async () => {\n await session.users.revoke(invitation.id)\n load()\n }}\n />\n ))}\n </ul>\n )}\n </AccountSection>\n </>\n )\n}\n","import { useState } from 'react'\nimport type { RoleLabel } from '@protobase/client'\nimport { AccountSection, SectionError } from '../account/account-section'\nimport { useAuth } from '../auth/auth-provider'\nimport { minPasswordLength } from '../auth/reset-password-form'\nimport { AppRolesPicker } from '../organizations/app-roles-picker'\nimport { useAction } from '../organizations/use-action'\nimport { Button } from '../primitives/button'\nimport { Input } from '../primitives/input'\nimport { text } from './messages'\n\n/** Adding an account directly, with its roles and, if wanted, a password; without one the person signs in another way. */\nexport const CreateUserForm = ({ roles, onCreated }: { roles: readonly RoleLabel[]; onCreated: () => void }) => {\n const { session } = useAuth()\n const [email, setEmail] = useState('')\n const [name, setName] = useState('')\n const [password, setPassword] = useState('')\n const [selected, setSelected] = useState<string[]>([])\n const { busy, error, run } = useAction()\n const create = () =>\n run(async () => {\n await session.users.create({ email: email.trim(), name: name.trim(), roles: selected, ...(password && { password }) })\n setEmail('')\n setName('')\n setPassword('')\n setSelected([])\n onCreated()\n })\n const incomplete = !email.trim() || !name.trim() || selected.length === 0 || (password !== '' && password.length < minPasswordLength)\n return (\n <AccountSection title={text('addAnAccount')} description={text('addDescription')}>\n <SectionError message={error} />\n <form className=\"flex flex-col gap-3\" onSubmit={(event) => { event.preventDefault(); void create() }}>\n <div className=\"flex flex-col gap-2 sm:flex-row\">\n <Input aria-label={text('email')} type=\"email\" placeholder=\"name@example.com\" value={email} onChange={(event) => setEmail(event.target.value)} wrapperClassName=\"flex-1\" />\n <Input aria-label={text('name')} placeholder={text('name')} autoComplete=\"off\" value={name} onChange={(event) => setName(event.target.value)} wrapperClassName=\"flex-1\" />\n </div>\n <Input aria-label={text('password')} type=\"password\" autoComplete=\"new-password\" placeholder={text('passwordOptional', { length: minPasswordLength })} value={password} onChange={(event) => setPassword(event.target.value)} />\n <AppRolesPicker roles={roles} selected={selected} grantable={new Set(roles.map((role) => role.name))} onChange={setSelected} />\n <div>\n <Button type=\"submit\" variant=\"primary\" loading={busy} disabled={incomplete}>{text('addAccount')}</Button>\n </div>\n </form>\n </AccountSection>\n )\n}\n","import { useState } from 'react'\nimport type { AppUser, RoleLabel } from '@protobase/client'\nimport { useAuth } from '../auth/auth-provider'\nimport { AppRolesPicker } from '../organizations/app-roles-picker'\nimport { useAction } from '../organizations/use-action'\nimport { PersonRow } from '../people/person-row'\nimport { Badge } from '../primitives/badge'\nimport { Button } from '../primitives/button'\nimport { text } from './messages'\n\n/** Someone who can sign in, with Block or Unblock, and their roles to tick; an admin may give every role. */\nexport const UserRow = ({ user: initial, roles, self }: { user: AppUser; roles: readonly RoleLabel[]; self: boolean }) => {\n const { session } = useAuth()\n const [user, setUser] = useState(initial)\n const { busy, error, run, setError } = useAction()\n const setRoles = (selected: string[]) => {\n if (selected.length === 0) return setError(text('keepOneRole'))\n void run(async () => {\n await session.users.setRoles(user.id, selected)\n setUser({ ...user, roles: selected })\n })\n }\n const setBlocked = (blocked: boolean) =>\n void run(async () => {\n await (blocked ? session.users.block(user.id) : session.users.unblock(user.id))\n setUser({ ...user, blocked })\n })\n return (\n <PersonRow\n name={user.name}\n email={user.email}\n self={self}\n error={error}\n actions={\n <>\n {user.blocked && <Badge tone=\"red\">{text('blocked')}</Badge>}\n {!self && (user.blocked ? <Button size=\"sm\" loading={busy} onClick={() => setBlocked(false)}>{text('unblock')}</Button> : <Button size=\"sm\" variant=\"danger\" loading={busy} onClick={() => setBlocked(true)}>{text('block')}</Button>)}\n </>\n }\n >\n <AppRolesPicker roles={roles} selected={user.roles} grantable={new Set(roles.map((role) => role.name))} disabled={busy} onChange={setRoles} />\n </PersonRow>\n )\n}\n","import { useCallback, useState } from 'react'\nimport type { RoleLabel } from '@protobase/client'\nimport { useAuth } from '../auth/auth-provider'\nimport { PagedSearchList } from '../lists/paged-search-list'\nimport { usePagedSearch } from '../lists/use-paged-search'\nimport { UserRow } from './user-row'\nimport { text } from './messages'\n\n/** Everyone who can sign in, a page at a time, found by address; `version` changes to read them again. */\nexport const UserList = ({ roles, version }: { roles: readonly RoleLabel[]; version: number }) => {\n const { session, state } = useAuth()\n const [query, setQuery] = useState('')\n // A new version is a new search, so the list reads the users again.\n const search = useCallback((term: string, offset: number) => session.users.search(term, offset).then((page) => ({ items: page.users, total: page.total })), [session, version])\n const list = usePagedSearch(search, query)\n const selfId = state.kind === 'signed-in' ? state.user.id : undefined\n return (\n <PagedSearchList\n title={text('people')}\n description={text('peopleDescription')}\n searchLabel={text('findSomeone')}\n placeholder={text('emailAddress')}\n query={query}\n onQuery={setQuery}\n list={list}\n renderRow={(user) => <UserRow key={`${version}/${user.id}`} user={user} roles={roles} self={user.id === selfId} />}\n />\n )\n}\n","import { useEffect, useState } from 'react'\nimport { AuthError, type RoleLabel } from '@protobase/client'\nimport { authMessage } from '../auth/auth-messages'\nimport { useAuth } from '../auth/auth-provider'\nimport { text } from './messages'\n\n/** Every role an admin can give, with its label, read once; `error` says why they could not be read. */\nexport const useUserRoles = () => {\n const { session } = useAuth()\n const [roles, setRoles] = useState<RoleLabel[]>([])\n const [error, setError] = useState<string>()\n useEffect(() => {\n void session.users.roles().then(setRoles, (failure: unknown) => setError(failure instanceof AuthError ? authMessage(failure) : text('couldNotReadRoles')))\n }, [session])\n return { roles, error }\n}\n","import { useState } from 'react'\nimport { SectionError } from '../account/account-section'\nimport { AppInvitations } from './app-invitations'\nimport { CreateUserForm } from './create-user-form'\nimport { UserList } from './user-list'\nimport { useUserRoles } from './use-user-roles'\n\n/** The `Users` block: everyone who can sign in, inviting someone, and adding an account, for admins. */\nexport const UsersBlock = () => {\n const { roles, error } = useUserRoles()\n const [version, setVersion] = useState(0)\n return (\n <div className=\"flex max-w-3xl flex-col gap-4\">\n <SectionError message={error} />\n <UserList roles={roles} version={version} />\n <AppInvitations roles={roles} />\n <CreateUserForm roles={roles} onCreated={() => setVersion((current) => current + 1)} />\n </div>\n )\n}\n","import { useState } from 'react'\nimport type { MailSender } from '@protobase/client'\nimport { Button } from '../primitives/button'\nimport { Dialog } from '../primitives/dialog'\nimport { Input } from '../primitives/input'\nimport { Switch } from '../primitives/switch'\nimport { Textarea } from '../primitives/textarea'\nimport { SectionError } from './account-section'\nimport { text } from './messages'\n\n/** What the dialog asks: the address, when it is a new one, its display name, its own signature, and if it is the default. */\nexport type MailSenderInput = { address: string; name: string; signature: string; isDefault: boolean }\n\ntype MailSenderDialogProps = {\n /** The address to change; without it, the dialog enters a new one. */\n sender?: MailSender\n busy: boolean\n error?: string\n onSave: (input: MailSenderInput) => void\n onClose: () => void\n}\n\n/** Enters a From address, or changes one: its display name, whether it is the default, and its own signature. */\nexport const MailSenderDialog = ({ sender, busy, error, onSave, onClose }: MailSenderDialogProps) => {\n const [address, setAddress] = useState(sender?.address ?? '')\n const [name, setName] = useState(sender?.name ?? '')\n const [signature, setSignature] = useState(sender?.signature ?? '')\n const [isDefault, setDefault] = useState(sender?.isDefault ?? false)\n const save = () => onSave({ address: address.trim(), name: name.trim(), signature, isDefault })\n return (\n <Dialog\n title={sender ? sender.address : text('addFromAddress')}\n description={sender ? text('changeFromAddressDescription') : text('addFromAddressDescription')}\n onClose={onClose}\n actions={\n <>\n <Button onClick={onClose}>{text('cancel')}</Button>\n <Button variant=\"primary\" loading={busy} disabled={!address.trim()} onClick={save}>\n {sender ? text('save') : text('addAddress')}\n </Button>\n </>\n }\n >\n {!sender && (\n <label className=\"flex flex-col gap-1.5 font-medium\">\n {text('fromAddress')}\n <Input autoFocus type=\"email\" value={address} maxLength={254} placeholder={text('fromAddressPlaceholder')} onChange={(event) => setAddress(event.target.value)} />\n </label>\n )}\n <label className=\"mt-3 flex flex-col gap-1.5 font-medium\">\n {text('fromName')}\n <Input value={name} maxLength={100} placeholder={text('fromNamePlaceholder')} onChange={(event) => setName(event.target.value)} />\n </label>\n <label className=\"mt-3 flex cursor-pointer items-center justify-between gap-3\">\n <span>{text('defaultFromAddress')}</span>\n <Switch checked={isDefault} onChange={setDefault} label={text('defaultFromAddress')} />\n </label>\n <label className=\"mt-3 flex flex-col gap-1.5 font-medium\">\n {text('signature')}\n <Textarea value={signature} maxLength={2000} placeholder={text('signaturePlaceholder')} onChange={(event) => setSignature(event.target.value)} />\n </label>\n <SectionError message={error} />\n </Dialog>\n )\n}\n","import { AtSign, Plus } from 'lucide-react'\nimport { useRef, useState } from 'react'\nimport { AuthError, type MailSender, type MailSenderChange, type MailSenders } from '@protobase/client'\nimport { authMessage } from '../auth/auth-messages'\nimport { Badge } from '../primitives/badge'\nimport { Button } from '../primitives/button'\nimport { Dialog } from '../primitives/dialog'\nimport { SectionError } from './account-section'\nimport { MailSenderDialog, type MailSenderInput } from './mail-sender-dialog'\nimport { text } from './messages'\n\nexport type MailSendersSectionProps = {\n senders: MailSenders\n /** Each rejects with `AuthError`, which the section shows. */\n onAdd: (input: { address: string; name?: string; signature?: string }) => Promise<MailSender>\n onUpdate: (id: string, change: MailSenderChange) => Promise<unknown>\n onRemove: (id: string) => Promise<void>\n}\n\ntype Editing = { kind: 'add' } | { kind: 'change'; sender: MailSender } | { kind: 'remove'; sender: MailSender }\n\nconst detailsOf = (sender: MailSender) => (sender.signature ? text('ownSignature') : text('genericSignature'))\n\n/**\n * The From addresses the person's mail goes out from, under their mailbox: its own and those they entered once, such\n * as its send-as addresses, each with its own signature or the generic one; one is the default.\n */\nexport const MailSendersSection = ({ senders: { address, senders }, onAdd, onUpdate, onRemove }: MailSendersSectionProps) => {\n const [busy, setBusy] = useState(false)\n const [error, setError] = useState<string>()\n const [editing, setEditing] = useState<Editing>()\n // Set at once, unlike `busy`, so a second click before the next render changes nothing twice.\n const inFlight = useRef(false)\n const chosen = senders.find((sender) => sender.isDefault)\n\n const close = () => {\n setEditing(undefined)\n setError(undefined)\n }\n\n const attempt = async (action: () => Promise<unknown>) => {\n if (inFlight.current) return\n inFlight.current = true\n setBusy(true)\n setError(undefined)\n try {\n await action()\n setEditing(undefined)\n } catch (failure) {\n // The browser's fetch rejects with a TypeError when the connection fails, before or after the server acted.\n if (failure instanceof TypeError) return setError(text('noAnswerFromServer'))\n if (!(failure instanceof AuthError)) throw failure\n setError(authMessage(failure))\n } finally {\n inFlight.current = false\n setBusy(false)\n }\n }\n\n // An empty name drops the address's name, and an empty signature its own, so the generic one applies.\n const save = (input: MailSenderInput) =>\n attempt(async () => {\n const name = input.name || null\n const signature = input.signature.trim() ? input.signature : null\n if (editing?.kind === 'change') return onUpdate(editing.sender.id, { name, signature, isDefault: input.isDefault })\n const added = await onAdd({ address: input.address, ...(name && { name }), ...(signature && { signature }) })\n if (input.isDefault) await onUpdate(added.id, { isDefault: true })\n })\n\n return (\n <div className=\"mt-5 border-t pt-4\">\n <h3 className=\"font-semibold\">{text('fromAddresses')}</h3>\n <p className=\"mt-1 mb-3 text-muted-foreground\">{text('fromAddressesDescription')}</p>\n <SectionError message={editing ? undefined : error} />\n {(address || senders.length > 0) && (\n <ul className=\"mb-3 divide-y rounded-md border\">\n {address && (\n <li className=\"flex flex-wrap items-center gap-3 px-3 py-2.5\">\n <AtSign className=\"size-4 shrink-0 text-muted-foreground\" />\n <span className=\"min-w-0 flex-1\">\n <bdi className=\"block truncate font-medium\">{address}</bdi>\n <span className=\"block text-xs text-muted-foreground\">{text('mailboxOwnAddress')}</span>\n </span>\n {chosen ? (\n <Button size=\"sm\" variant=\"ghost\" loading={busy} onClick={() => void attempt(() => onUpdate(chosen.id, { isDefault: false }))}>\n {text('makeDefault')}\n </Button>\n ) : (\n <Badge tone=\"blue\">{text('default')}</Badge>\n )}\n </li>\n )}\n {senders.map((sender) => (\n <li key={sender.id} className=\"flex flex-wrap items-center gap-3 px-3 py-2.5\">\n <AtSign className=\"size-4 shrink-0 text-muted-foreground\" />\n <span className=\"min-w-0 flex-1\">\n <bdi className=\"block truncate font-medium\">{sender.address}</bdi>\n {sender.name && <bdi className=\"block truncate\">{sender.name}</bdi>}\n <span className=\"block text-xs text-muted-foreground\">{detailsOf(sender)}</span>\n </span>\n {sender.isDefault && <Badge tone=\"blue\">{text('default')}</Badge>}\n <Button size=\"sm\" variant=\"ghost\" onClick={() => setEditing({ kind: 'change', sender })}>\n {text('edit')}\n </Button>\n <Button size=\"sm\" variant=\"ghost\" onClick={() => setEditing({ kind: 'remove', sender })}>\n {text('remove')}\n </Button>\n </li>\n ))}\n </ul>\n )}\n <Button onClick={() => setEditing({ kind: 'add' })}>\n <Plus className=\"size-3.5\" />\n {text('addFromAddress')}\n </Button>\n {editing?.kind === 'add' && <MailSenderDialog busy={busy} error={error} onSave={(input) => void save(input)} onClose={close} />}\n {editing?.kind === 'change' && <MailSenderDialog key={editing.sender.id} sender={editing.sender} busy={busy} error={error} onSave={(input) => void save(input)} onClose={close} />}\n {editing?.kind === 'remove' && (\n <Dialog\n title={text('removeFromAddress', { address: editing.sender.address })}\n description={text('removeFromAddressDescription')}\n onClose={close}\n actions={\n <>\n <Button onClick={close}>{text('cancel')}</Button>\n <Button variant=\"danger\" loading={busy} onClick={() => void attempt(() => onRemove(editing.sender.id))}>\n {text('remove')}\n </Button>\n </>\n }\n >\n <SectionError message={error} />\n </Dialog>\n )}\n </div>\n )\n}\n","import { useCallback, useState } from 'react'\nimport type { PersonalMailLink } from '@protobase/client'\nimport { providerMessage } from '../../auth/auth-messages'\nimport { useAuth } from '../../auth/auth-provider'\nimport { providerName } from '../../auth/provider-link'\nimport { mailboxOffers, type LinkedAccounts } from '../../mailbox/mailbox-offers'\nimport { text as mailboxText } from '../../mailbox/messages'\nimport { MailSendersSection } from '../mail-senders-section'\nimport { SignInProvidersSection } from '../sign-in-providers-section'\nimport { text } from '../messages'\nimport { AccountLoading } from './account-loading'\nimport { takeLinkError } from './connected-accounts-block'\nimport { useAccountData } from './use-account-data'\n\n// A mailbox not linked whose sign-in provider is, such as Gmail beside a Google sign-in: that sign-in cannot send mail.\nconst signInOnlyNotes = (links: PersonalMailLink[], linked: LinkedAccounts, providerNames: (id: string) => string) =>\n Object.fromEntries(\n mailboxOffers(links, linked, { code: 'not_linked' })\n .filter((offer) => offer.signInOnly)\n .map(({ link }) => [link.id, mailboxText('signInOnly', { provider: providerNames(link.provider), name: link.name })]),\n )\n\nconst Mailboxes = ({ links }: { links: PersonalMailLink[] }) => {\n const { session, linkPersonalMail, signInProviders } = useAuth()\n const { account } = session\n const [linkError] = useState(takeLinkError)\n const load = useCallback(async () => {\n const [mail, providers, senders] = await Promise.all([account.linkedPersonalMail(links), account.linkedProviders(), account.mailSenders()])\n return { mail, providers, senders }\n }, [account, links])\n const { data, error, reload } = useAccountData(load, text('couldNotReadMethods'))\n if (!data) return <AccountLoading error={error} />\n const providerNames = (id: string) => signInProviders.find((provider) => provider.id === id)?.name ?? providerName(id)\n const connect = (id: string) => linkPersonalMail(links.find((link) => link.id === id)!)\n return (\n <SignInProvidersSection\n title={text('mailbox')}\n description={text('mailboxDescription')}\n providers={links.map(({ id, name }) => ({ id, name }))}\n linked={data.mail}\n notes={signInOnlyNotes(links, data, providerNames)}\n reconnect\n onConnect={connect}\n error={linkError && providerMessage(linkError, links.length === 1 ? links[0]!.name : text('theProvider'))}\n >\n {/* Each change reads the list again, so the section shows what the server now has, such as the one default. */}\n <MailSendersSection\n senders={data.senders}\n onAdd={async (input) => {\n const added = await account.addMailSender(input)\n await reload()\n return added\n }}\n onUpdate={async (id, change) => {\n await account.updateMailSender(id, change)\n await reload()\n }}\n onRemove={async (id) => {\n await account.removeMailSender(id)\n await reload()\n }}\n />\n </SignInProvidersSection>\n )\n}\n\n/** The `PersonalMail` block: the mailboxes the signed-in person can link for the app to send mail from, hidden when the app has none. */\nexport const PersonalMailBlock = () => {\n const { personalMail } = useAuth()\n return personalMail.length > 0 ? <Mailboxes links={personalMail} /> : null\n}\n","import { Bot } from 'lucide-react'\nimport { useState } from 'react'\nimport { AuthError, type ConnectedApp } from '@protobase/client'\nimport { authMessage } from '../auth/auth-messages'\nimport { clientName } from '../connect/client-name'\nimport { clientPublisher } from '../connect/client-publisher'\nimport { formatDate } from '../format'\nimport { Button } from '../primitives/button'\nimport { Dialog } from '../primitives/dialog'\nimport { AccountSection, SectionError } from './account-section'\n\nexport type ConnectedAppsSectionProps = {\n apps: ConnectedApp[]\n /** Rejects with `AuthError`, which the section shows. */\n onDisconnect: (clientId: string) => Promise<void>\n}\n\nconst nameOf = (app: ConnectedApp) => clientName(app.name) ?? 'An unnamed app'\n\n// \"as Sales in Acme\", one per role and organization it was allowed with.\nconst accessOf = (app: ConnectedApp) =>\n app.access.map(({ role, organization }) => `as ${role || 'no role'}${organization ? ` in ${organization}` : ''}`).join(', ')\n\n/** The apps, such as MCP clients, the person allowed to act as them, each of which they can disconnect. */\nexport const ConnectedAppsSection = ({ apps, onDisconnect }: ConnectedAppsSectionProps) => {\n const [busy, setBusy] = useState(false)\n const [error, setError] = useState<string>()\n const [disconnecting, setDisconnecting] = useState<ConnectedApp>()\n\n const disconnect = async (app: ConnectedApp) => {\n setBusy(true)\n setError(undefined)\n try {\n await onDisconnect(app.clientId)\n setDisconnecting(undefined)\n } catch (failure) {\n if (!(failure instanceof AuthError)) throw failure\n setError(authMessage(failure))\n }\n setBusy(false)\n }\n\n return (\n <AccountSection title=\"Connected apps\" description=\"AI assistants and other apps you allowed to act as you here. Disconnecting one stops it within 15 minutes; it has to ask you again to come back.\">\n <SectionError message={disconnecting ? undefined : error} />\n {apps.length === 0 ? (\n <p className=\"text-muted-foreground\">No apps are connected. Add this app's MCP address to an AI assistant to connect one.</p>\n ) : (\n <ul className=\"divide-y rounded-md border\">\n {apps.map((app) => {\n const publisher = clientPublisher(app.clientId)\n return (\n <li key={app.clientId} className=\"flex flex-wrap items-center gap-3 px-3 py-2.5\">\n <Bot className=\"size-4 shrink-0 text-muted-foreground\" />\n <span className=\"min-w-0 flex-1\">\n <bdi className=\"block truncate font-medium\">{nameOf(app)}</bdi>\n <span className=\"block text-xs text-muted-foreground\">\n {publisher && `Published by ${publisher} · `}Allowed {formatDate(Date.parse(app.allowedAt))} · {accessOf(app)}\n </span>\n </span>\n <Button size=\"sm\" variant=\"ghost\" onClick={() => setDisconnecting(app)}>\n Disconnect\n </Button>\n </li>\n )\n })}\n </ul>\n )}\n {disconnecting && (\n <Dialog\n title={`Disconnect ${nameOf(disconnecting)}?`}\n description=\"It can no longer read or change anything as you. What it already started may keep working for up to 15 minutes.\"\n onClose={() => setDisconnecting(undefined)}\n actions={\n <>\n <Button onClick={() => setDisconnecting(undefined)}>Cancel</Button>\n <Button variant=\"danger\" loading={busy} onClick={() => void disconnect(disconnecting)}>\n Disconnect\n </Button>\n </>\n }\n >\n {error && <SectionError message={error} />}\n </Dialog>\n )}\n </AccountSection>\n )\n}\n","/**\n * The address of Claude's dialog that adds a custom connector, filled in with the MCP endpoint's `url` and, when the\n * app has one, its name; the person sees both there and confirms.\n */\nexport const connectorDialogUrl = (url: string, appName?: string) => {\n const dialog = new URL('https://claude.ai/customize/connectors')\n dialog.searchParams.set('modal', 'add-custom-connector')\n if (appName) dialog.searchParams.set('connectorName', appName)\n dialog.searchParams.set('connectorUrl', url)\n return dialog.href\n}\n","import { ExternalLink } from 'lucide-react'\nimport { buttonClass } from '../primitives/button'\nimport { AccountSection } from './account-section'\nimport { connectorDialogUrl } from './connector-dialog'\nimport { CopyField } from './copy-field'\nimport { text } from './messages'\n\n/** The address of the app's MCP endpoint, to copy into an AI client or add to Claude, with how connecting goes. */\nexport const McpAddressSection = ({ url, appName }: { url: string; appName?: string }) => (\n <AccountSection title={text('mcpAddress')} description={text('mcpAddressDescription')}>\n <div className=\"flex flex-wrap items-center gap-2\">\n <CopyField value={url} copyLabel={text('copyMcpAddress')} />\n <a href={connectorDialogUrl(url, appName)} target=\"_blank\" rel=\"noreferrer\" className={buttonClass()}>\n <ExternalLink className=\"size-3.5\" />\n {text('addToClaude')}\n </a>\n </div>\n </AccountSection>\n)\n","import { useCallback } from 'react'\nimport { useAuth } from '../../auth/auth-provider'\nimport { useAdminMeta } from '../../app/meta-gate'\nimport { ConnectedAppsSection } from '../connected-apps-section'\nimport { McpAddressSection } from '../mcp-address-section'\nimport { text } from '../messages'\nimport { AccountLoading } from './account-loading'\nimport { useAccountData } from './use-account-data'\n\nconst Apps = () => {\n const { account } = useAuth().session\n const { data: apps, error, reload } = useAccountData(useCallback(() => account.connectedApps(), [account]), text('couldNotReadMethods'))\n if (!apps) return <AccountLoading error={error} />\n return <ConnectedAppsSection apps={apps} onDisconnect={(clientId) => account.disconnectApp(clientId).then(reload)} />\n}\n\nconst Mcp = ({ url }: { url: string }) => (\n <>\n <McpAddressSection url={url} appName={useAdminMeta().appName} />\n <Apps />\n </>\n)\n\n/**\n * The `ConnectedApps` block: the address of the app's MCP endpoint and the apps the signed-in person allowed to act as\n * them, hidden when the app has no MCP.\n */\nexport const ConnectedAppsBlock = () => {\n const { mcp } = useAuth()\n return mcp ? <Mcp url={mcp.url} /> : null\n}\n","import { KeySquare, Plus } from 'lucide-react'\nimport { useRef, useState } from 'react'\nimport { AuthError, type NewPersonalAccessToken, type PersonalAccessToken } from '@protobase/client'\nimport { confirmationMinutes } from '@protobase/schema/internal'\nimport { ConfirmSignIn } from '../app/confirm-sign-in'\nimport { authMessage } from '../auth/auth-messages'\nimport { formatDate } from '../format'\nimport { Button } from '../primitives/button'\nimport { Dialog } from '../primitives/dialog'\nimport { Input } from '../primitives/input'\nimport { Select } from '../primitives/select'\nimport { AccountSection, SectionError } from './account-section'\nimport { CopyField } from './copy-field'\nimport { text } from './messages'\n\nexport type PersonalAccessTokensSectionProps = {\n tokens: PersonalAccessToken[]\n /** Rejects with `AuthError`, which the section shows, or answers by asking the person to confirm it's them. */\n onCreate: (input: { name: string; expiresInDays?: number }) => Promise<NewPersonalAccessToken>\n /** Rejects with `AuthError`, which the section shows. */\n onRevoke: (id: string) => Promise<void>\n}\n\n// The lifetimes offered, in days; `never` makes a token that lasts until it is revoked.\nconst lifetimes = { '30': 30, '90': 90, '365': 365, never: undefined } as const\ntype Lifetime = keyof typeof lifetimes\nconst lifetimeLabels = { '30': 'expiresIn30Days', '90': 'expiresIn90Days', '365': 'expiresInAYear', never: 'neverExpires' } as const\n\nconst dateOf = (iso: string) => formatDate(Date.parse(iso))\n\n// When it expires, or expired: a token past its expiry stays listed until it is revoked.\nconst expiryOf = (expiresAt: string | undefined) => {\n if (!expiresAt) return text('neverExpires')\n return Date.parse(expiresAt) <= Date.now() ? text('expiredOn', { date: dateOf(expiresAt) }) : text('expiresOn', { date: dateOf(expiresAt) })\n}\n\n// \"Created 1 Aug 2026 · Expires 30 Aug 2026 · Last used 2 Aug 2026 · As Sales in Acme\".\nconst detailsOf = (token: PersonalAccessToken) =>\n [\n text('createdOn', { date: dateOf(token.createdAt) }),\n expiryOf(token.expiresAt),\n token.lastUsedAt ? text('lastUsedOn', { date: dateOf(token.lastUsedAt) }) : text('notUsedYet'),\n token.organization ? text('actsAsIn', { role: token.role, organization: token.organization }) : text('actsAs', { role: token.role }),\n ].join(' · ')\n\ntype Editing = { kind: 'create' } | { kind: 'created'; created: NewPersonalAccessToken } | { kind: 'revoke'; token: PersonalAccessToken }\n\n/**\n * The person's personal access tokens, which let a script call the app's API as them: each with when it was made,\n * expires and was last used, and what it acts as, to revoke; and a new one, shown once to copy, since the app keeps\n * only its hash. An older session confirms it's them before a new token, in place.\n */\nexport const PersonalAccessTokensSection = ({ tokens, onCreate, onRevoke }: PersonalAccessTokensSectionProps) => {\n const [busy, setBusy] = useState(false)\n const [error, setError] = useState<string>()\n const [editing, setEditing] = useState<Editing>()\n const [name, setName] = useState('')\n const [lifetime, setLifetime] = useState<Lifetime>('90')\n const [confirming, setConfirming] = useState<'asked' | 'done'>()\n\n const close = () => {\n setEditing(undefined)\n setError(undefined)\n setConfirming(undefined)\n }\n\n // Set at once, unlike `busy`, so a second click before the next render makes no second token.\n const inFlight = useRef(false)\n\n const attempt = async (action: () => Promise<Editing | undefined>) => {\n if (inFlight.current) return\n inFlight.current = true\n setBusy(true)\n setError(undefined)\n try {\n setEditing(await action())\n setConfirming(undefined)\n } catch (failure) {\n // The browser's fetch rejects with a TypeError when the connection fails, before or after the server acted.\n if (failure instanceof TypeError) return setError(text('noAnswerFromServer'))\n if (!(failure instanceof AuthError)) throw failure\n if (failure.code === 'STRONG_SIGN_IN_REQUIRED') setConfirming('asked')\n else setError(authMessage(failure))\n } finally {\n inFlight.current = false\n setBusy(false)\n }\n }\n\n const create = () =>\n attempt(async () => {\n const days = lifetimes[lifetime]\n const created = await onCreate({ name: name.trim(), ...(days !== undefined && { expiresInDays: days }) })\n return { kind: 'created', created }\n })\n\n return (\n <AccountSection title={text('accessTokens')} description={text('accessTokensDescription')}>\n <SectionError message={editing ? undefined : error} />\n {tokens.length === 0 ? (\n <p className=\"mb-3 text-muted-foreground\">{text('noAccessTokens')}</p>\n ) : (\n <ul className=\"mb-3 divide-y rounded-md border\">\n {tokens.map((token) => (\n <li key={token.id} className=\"flex flex-wrap items-center gap-3 px-3 py-2.5\">\n <KeySquare className=\"size-4 shrink-0 text-muted-foreground\" />\n <span className=\"min-w-0 flex-1\">\n <bdi className=\"block truncate font-medium\">{token.name}</bdi>\n <span className=\"block text-xs text-muted-foreground\">{detailsOf(token)}</span>\n </span>\n <Button size=\"sm\" variant=\"ghost\" onClick={() => setEditing({ kind: 'revoke', token })}>\n {text('revoke')}\n </Button>\n </li>\n ))}\n </ul>\n )}\n <Button\n onClick={() => {\n setName('')\n setLifetime('90')\n setEditing({ kind: 'create' })\n }}\n >\n <Plus className=\"size-3.5\" />\n {text('newAccessToken')}\n </Button>\n {editing?.kind === 'create' && (\n <Dialog\n title={text('newAccessToken')}\n description={text('newAccessTokenDescription')}\n onClose={close}\n actions={\n <>\n <Button onClick={close}>{text('cancel')}</Button>\n <Button variant=\"primary\" loading={busy} disabled={!name.trim()} onClick={() => void create()}>\n {text('createAccessToken')}\n </Button>\n </>\n }\n >\n <label className=\"flex flex-col gap-1.5 font-medium\">\n {text('name')}\n <Input autoFocus value={name} maxLength={100} placeholder={text('accessTokenNamePlaceholder')} onChange={(event) => setName(event.target.value)} />\n </label>\n <label className=\"mt-3 flex flex-col gap-1.5 font-medium\">\n {text('accessTokenExpiry')}\n <Select value={lifetime} onChange={(event) => setLifetime(event.target.value as Lifetime)}>\n {(Object.keys(lifetimes) as Lifetime[]).map((option) => (\n <option key={option} value={option}>\n {text(lifetimeLabels[option])}\n </option>\n ))}\n </Select>\n </label>\n {/* Confirming signs the browser in anew or confirms its session; the person then makes the token again. */}\n {confirming === 'asked' && <ConfirmSignIn purpose=\"change\" minutes={confirmationMinutes} onConfirmed={() => setConfirming('done')} />}\n {confirming === 'done' && <p className=\"mt-2 text-muted-foreground\">{text('confirmedCreateAccessToken')}</p>}\n <SectionError message={error} />\n </Dialog>\n )}\n {editing?.kind === 'created' && (\n <Dialog\n title={text('accessTokenCreated', { name: editing.created.personalAccessToken.name })}\n description={text('accessTokenCreatedDescription')}\n onClose={close}\n actions={\n <Button variant=\"primary\" onClick={close}>\n {text('done')}\n </Button>\n }\n >\n <CopyField value={editing.created.token} copyLabel={text('copyAccessToken')} />\n </Dialog>\n )}\n {editing?.kind === 'revoke' && (\n <Dialog\n title={text('revokeAccessToken', { name: editing.token.name })}\n description={text('revokeAccessTokenDescription')}\n onClose={close}\n actions={\n <>\n <Button onClick={close}>{text('cancel')}</Button>\n <Button variant=\"danger\" loading={busy} onClick={() => void attempt(async () => (await onRevoke(editing.token.id), undefined))}>\n {text('revoke')}\n </Button>\n </>\n }\n >\n <SectionError message={error} />\n </Dialog>\n )}\n </AccountSection>\n )\n}\n","import { useCallback } from 'react'\nimport { useAuth } from '../../auth/auth-provider'\nimport { SectionError } from '../account-section'\nimport { PersonalAccessTokensSection } from '../personal-access-tokens-section'\nimport { text } from '../messages'\nimport { AccountLoading } from './account-loading'\nimport { useAccountData } from './use-account-data'\n\nconst Tokens = () => {\n const { account } = useAuth().session\n const { data: tokens, error, reload } = useAccountData(useCallback(() => account.personalAccessTokens(), [account]), text('couldNotReadAccessTokens'))\n if (!tokens) return <AccountLoading error={error} />\n // The list is read again after every change. A new token reaches its dialog at once, to be copied while the list\n // loads; a failed change, whose answer may have been lost after the server made it, waits for the list before the\n // dialog lets the person try again. A list that could not be read again says so above it.\n return (\n <>\n <SectionError message={error} />\n <PersonalAccessTokensSection\n tokens={tokens}\n onCreate={(input) =>\n account.createPersonalAccessToken(input).then(\n (created) => {\n void reload()\n return created\n },\n async (failure: unknown) => {\n await reload()\n throw failure\n },\n )\n }\n onRevoke={(id) => account.revokePersonalAccessToken(id).finally(reload)}\n />\n </>\n )\n}\n\n/** The `PersonalAccessTokens` block: the signed-in person's personal access tokens, hidden when the app has none. */\nexport const PersonalAccessTokensBlock = () => (useAuth().personalAccessTokens ? <Tokens /> : null)\n","import { PlugZap } from 'lucide-react'\nimport { Fragment, useState } from 'react'\nimport { AuthError, type ConnectionRevocation, type WorkflowConnection } from '@protobase/client'\nimport { authMessage } from '../auth/auth-messages'\nimport { RecordLink } from '../app/displays/record-link'\nimport { formatDate } from '../format'\nimport { Badge } from '../primitives/badge'\nimport { Button } from '../primitives/button'\nimport { Dialog } from '../primitives/dialog'\nimport { AccountSection, SectionError, SectionNotice } from './account-section'\nimport { text } from './messages'\n\nexport type ConnectionsSectionProps = {\n connections: WorkflowConnection[]\n /** Leaves for the provider to connect an account; rejects with `AuthError`, which the section shows. */\n onConnect: (connection: WorkflowConnection) => Promise<void>\n /** Answers what became of the account's token, which the section says; rejects with `AuthError`, which it shows. */\n onDisconnect: (accountId: string) => Promise<ConnectionRevocation>\n /** Why the last connect did not go through, as the provider came back with it. */\n error?: string\n}\n\ntype Chosen = { connection: WorkflowConnection; accountId: string }\n\nconst disconnected = { revoked: 'disconnectedRevoked', queued: 'disconnectedQueued', not_revoked: 'disconnectedNotRevoked' } as const satisfies Record<ConnectionRevocation, string>\n\n// Revoking at Google ends every grant the account gave this app, the sign-in and a linked mailbox included.\nconst wholeGrant = (connection: WorkflowConnection) => connection.provider === 'google'\n\n/**\n * The accounts the person connected for their workflows' steps to use, by the connection the app's plugins declare:\n * each one connects an account, again when a trigger waits for it, and disconnects one, which revokes its token and\n * says whether the provider took it. Each account links to the workflows that use it.\n */\nexport const ConnectionsSection = ({ connections, onConnect, onDisconnect, error: returned }: ConnectionsSectionProps) => {\n const [busy, setBusy] = useState<string>()\n const [error, setError] = useState(returned)\n const [chosen, setChosen] = useState<Chosen>()\n const [notice, setNotice] = useState<string>()\n\n const attempt = async (key: string, work: () => Promise<void>) => {\n setBusy(key)\n setError(undefined)\n setNotice(undefined)\n try {\n await work()\n setChosen(undefined)\n } catch (failure) {\n if (!(failure instanceof AuthError)) throw failure\n setError(authMessage(failure))\n } finally {\n setBusy(undefined)\n }\n }\n\n return (\n <AccountSection title={text('connections')} description={text('connectionsDescription')}>\n <SectionError message={chosen ? undefined : error} />\n <SectionNotice message={notice} />\n <ul className=\"divide-y rounded-md border\">\n {connections.map((connection) => (\n <li key={connection.key} className=\"flex flex-col gap-2 px-3 py-2.5\">\n <div className=\"flex flex-wrap items-center gap-3\">\n <PlugZap className=\"size-4 shrink-0 text-muted-foreground\" />\n <span className=\"min-w-0 flex-1 truncate font-medium\">{connection.label}</span>\n <Button size=\"sm\" loading={busy === connection.key} disabled={busy !== undefined} onClick={() => void attempt(connection.key, () => onConnect(connection))}>\n {connection.accounts.length > 0 ? text('connectAgain', { name: connection.label }) : text('connect', { name: connection.label })}\n </Button>\n </div>\n {connection.accounts.map((account) => (\n <Fragment key={account.id}>\n <div className=\"flex flex-wrap items-center gap-3 pl-7 text-sm\">\n <span className=\"min-w-0 flex-1 text-muted-foreground\">\n {text('connectedOn', { date: formatDate(Date.parse(account.created_at)) })} · <code className=\"text-xs\">{account.id}</code>\n </span>\n {account.needs_sign_in ? <Badge tone=\"amber\">{text('connectionNeedsSignIn')}</Badge> : <Badge tone=\"green\">{text('connected')}</Badge>}\n <Button size=\"sm\" variant=\"ghost\" onClick={() => setChosen({ connection, accountId: account.id })}>\n {text('disconnect')}\n </Button>\n </div>\n {account.used_by.length > 0 && (\n <div className=\"flex flex-wrap items-center gap-x-3 gap-y-1 pl-7 text-sm\">\n <span className=\"text-muted-foreground\">{text('connectionUsedBy')}</span>\n {account.used_by.map((workflow) => (\n <RecordLink key={workflow.id} resource=\"workflows\" recordKey={workflow.id} className=\"font-medium text-primary-text hover:underline\">\n {workflow.name}\n </RecordLink>\n ))}\n </div>\n )}\n </Fragment>\n ))}\n </li>\n ))}\n </ul>\n {chosen && (\n <Dialog\n title={text('disconnectTitle', { name: chosen.connection.label })}\n description={wholeGrant(chosen.connection) ? `${text('disconnectDescription')} ${text('disconnectWholeGrant')}` : text('disconnectDescription')}\n onClose={() => setChosen(undefined)}\n actions={\n <>\n <Button onClick={() => setChosen(undefined)}>{text('cancel')}</Button>\n <Button variant=\"danger\" loading={busy === chosen.accountId} onClick={() => void attempt(chosen.accountId, async () => setNotice(text(disconnected[await onDisconnect(chosen.accountId)])))}>\n {text('disconnect')}\n </Button>\n </>\n }\n >\n {error && <SectionError message={error} />}\n </Dialog>\n )}\n </AccountSection>\n )\n}\n","import { useCallback, useState } from 'react'\nimport { providerMessage } from '../../auth/auth-messages'\nimport { useAuth } from '../../auth/auth-provider'\nimport { ConnectionsSection } from '../connections-section'\nimport { text } from '../messages'\nimport { AccountLoading } from './account-loading'\nimport { takeLinkError } from './connected-accounts-block'\nimport { useAccountData } from './use-account-data'\n\n/** The `Connections` block: the accounts the signed-in person connected for their workflows, hidden when the app's plugins declare none. */\nexport const ConnectionsBlock = () => {\n const { session, connectAccount } = useAuth()\n const { account } = session\n const [linkError] = useState(takeLinkError)\n const { data: connections, error, reload } = useAccountData(useCallback(() => account.workflowConnections(), [account]), text('couldNotReadMethods'))\n if (!connections) return <AccountLoading error={error} />\n if (connections.length === 0) return null\n return <ConnectionsSection connections={connections} onConnect={connectAccount} onDisconnect={(id) => account.disconnectAccount(id).finally(reload)} error={linkError && providerMessage(linkError, text('theProvider'))} />\n}\n","import { useId, useState } from 'react'\nimport { AuthError } from '@protobase/client'\nimport { confirmationMinutes } from '@protobase/schema/internal'\nimport { ConfirmSignIn } from '../app/confirm-sign-in'\nimport { authMessage } from '../auth/auth-messages'\nimport { Button } from '../primitives/button'\nimport { Dialog } from '../primitives/dialog'\nimport { Input } from '../primitives/input'\nimport { SectionError } from './account-section'\nimport { text } from './messages'\n\nexport type DeleteAccountDialogProps = {\n /** The account has a password: ask for it. Without one, a session older than a day confirms it's them in place first. */\n hasPassword: boolean\n /** Rejects with `AuthError`, which the dialog shows; resolves once the account is gone. */\n onDelete: (password?: string) => Promise<void>\n onClose: () => void\n}\n\n// The server's refusals of this deletion, in words for the person at the keyboard.\nconst deletionMessage = (error: AuthError) => {\n if (error.code === 'LAST_ADMIN') return text('deleteAccountLastAdmin')\n if (error.code === 'ACCOUNT_LOCKED') return text('deleteAccountLocked')\n return authMessage(error)\n}\n\n/** Asks the person to confirm deleting their own account, with their password when it has one. */\nexport const DeleteAccountDialog = ({ hasPassword, onDelete, onClose }: DeleteAccountDialogProps) => {\n const [password, setPassword] = useState('')\n const [busy, setBusy] = useState(false)\n const [error, setError] = useState<string>()\n const [confirming, setConfirming] = useState(false)\n const formId = useId()\n\n const confirm = async () => {\n setBusy(true)\n setError(undefined)\n setConfirming(false)\n try {\n await onDelete(hasPassword ? password : undefined)\n } catch (failure) {\n if (!(failure instanceof AuthError)) throw failure\n if (failure.code === 'STRONG_SIGN_IN_REQUIRED') setConfirming(true)\n else setError(deletionMessage(failure))\n setBusy(false)\n }\n }\n\n return (\n <Dialog\n title={text('deleteAccountQuestion')}\n description={text('deleteAccountWarning')}\n onClose={onClose}\n actions={\n <>\n <Button onClick={onClose}>{text('cancel')}</Button>\n <Button variant=\"danger\" type=\"submit\" form={formId} loading={busy} disabled={hasPassword && !password}>\n {text('deleteAccountConfirm')}\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 confirm()\n }}\n >\n {hasPassword && (\n <label className=\"flex flex-col gap-1.5 font-medium\">\n {text('deleteAccountPassword')}\n <Input type=\"password\" name=\"current-password\" autoComplete=\"current-password\" autoFocus value={password} invalid={Boolean(error)} onChange={(event) => setPassword(event.target.value)} />\n </label>\n )}\n <SectionError message={error} />\n </form>\n {/* Outside the form, since the confirmation has forms of its own. */}\n {confirming && <ConfirmSignIn purpose=\"change\" minutes={confirmationMinutes} onConfirmed={() => void confirm()} />}\n </Dialog>\n )\n}\n","import { useState } from 'react'\nimport { Button } from '../primitives/button'\nimport { AccountSection } from './account-section'\nimport { DeleteAccountDialog } from './delete-account-dialog'\nimport { text } from './messages'\n\nexport type DeleteAccountSectionProps = {\n hasPassword: boolean\n /** Staff signed in as the person, who may not delete their account: the section only says so. */\n staff: boolean\n /** Rejects with `AuthError`, which the dialog shows; resolves once the account is gone and this device signed out. */\n onDelete: (password?: string) => Promise<void>\n}\n\n/** Deletes the signed-in person's own account, once they confirm it in a dialog. */\nexport const DeleteAccountSection = ({ hasPassword, staff, onDelete }: DeleteAccountSectionProps) => {\n const [confirming, setConfirming] = useState(false)\n return (\n <AccountSection title={text('deleteAccount')} description={staff ? text('deleteAccountStaff') : text('deleteAccountDescription')}>\n {!staff && (\n <Button variant=\"danger\" onClick={() => setConfirming(true)}>\n {text('deleteAccount')}\n </Button>\n )}\n {confirming && <DeleteAccountDialog hasPassword={hasPassword} onDelete={onDelete} onClose={() => setConfirming(false)} />}\n </AccountSection>\n )\n}\n","import { useCallback } from 'react'\nimport { useAuth } from '../../auth/auth-provider'\nimport { DeleteAccountSection } from '../delete-account-section'\nimport { text } from '../messages'\nimport { AccountLoading } from './account-loading'\nimport { useAccountData } from './use-account-data'\n\n/** The `DeleteAccount` block: the signed-in person deletes their own account, which signs them out; staff signed in as them cannot. */\nexport const DeleteAccountBlock = () => {\n const { session, state, deleteAccount } = useAuth()\n const { account } = session\n const { data: methods, error } = useAccountData(useCallback(() => account.signInMethods(), [account]), text('couldNotReadMethods'))\n if (!methods) return <AccountLoading error={error} />\n return <DeleteAccountSection hasPassword={methods.account.password} staff={state.kind === 'signed-in' && Boolean(state.staff)} onDelete={deleteAccount} />\n}\n","// In the order to test them: Edge, Opera and Samsung Internet also say Chrome, and Chrome also says Safari.\nconst browsers: Array<[RegExp, string]> = [\n [/Edg(e|A|iOS)?\\//, 'Edge'],\n [/OPR\\/|Opera/, 'Opera'],\n [/SamsungBrowser\\//, 'Samsung Internet'],\n [/Firefox\\/|FxiOS\\//, 'Firefox'],\n [/Chrome\\/|CriOS\\//, 'Chrome'],\n [/Safari\\//, 'Safari'],\n]\n\n// iPads and Android also say Mac OS X and Linux.\nconst systems: Array<[RegExp, string]> = [\n [/iPhone/, 'iPhone'],\n [/iPad/, 'iPad'],\n [/Android/, 'Android'],\n [/CrOS/, 'ChromeOS'],\n [/Windows/, 'Windows'],\n [/Mac OS X|Macintosh/, 'macOS'],\n [/Linux/, 'Linux'],\n]\n\nconst find = (list: Array<[RegExp, string]>, userAgent: string) => list.find(([pattern]) => pattern.test(userAgent))?.[1]\n\n/** The browser and system a user agent names, such as Chrome and macOS, each `undefined` when it names none we know. */\nexport const deviceOf = (userAgent: string | undefined) => (userAgent ? { browser: find(browsers, userAgent), system: find(systems, userAgent) } : {})\n","import { Laptop, ShieldUser, Smartphone, Tablet } from 'lucide-react'\nimport { useState } from 'react'\nimport { AuthError, type DeviceLink, type DeviceSession } from '@protobase/client'\nimport { authMessage } from '../auth/auth-messages'\nimport { formatDateTime } from '../format'\nimport { Badge } from '../primitives/badge'\nimport { Button } from '../primitives/button'\nimport { Dialog } from '../primitives/dialog'\nimport { AccountSection, SectionError } from './account-section'\nimport { deviceOf } from './device-name'\nimport { text } from './messages'\n\nexport type DevicesSectionProps = {\n sessions: DeviceSession[]\n /** The operator provider's name, which names a staff session; `undefined` when the app has none. */\n operator?: string\n /** The devices the platform links, each listed once with the sessions it began. */\n links?: DeviceLink[]\n /** Each rejects with `AuthError`, which the section shows. */\n onSignOut: (token: string) => Promise<void>\n onSignOutOthers: () => Promise<void>\n /** Signs a linked device out for good. */\n onSignOutLink?: (id: string) => Promise<void>\n}\n\n// A linked device is named by its provider and, when its token gave one, its own name.\nconst linkName = (link: DeviceLink) => (link.device ? text('deviceThrough', { device: link.device, provider: link.name }) : link.name)\n\n// A staff session is named for the operator alone: the person sees that its staff signed in and when, not who.\nconst nameOf = (session: DeviceSession, operator: string | undefined) => {\n if (session.staff) return operator ? text('staffOf', { operator }) : text('staff')\n const { browser, system } = deviceOf(session.userAgent)\n if (browser && system) return text('browserOn', { browser, system })\n if (system) return text('aBrowserOn', { system })\n return browser ?? text('unknownDevice')\n}\n\nconst iconOf = (session: DeviceSession) => {\n if (session.staff) return ShieldUser\n const { system } = deviceOf(session.userAgent)\n if (system === 'iPhone' || system === 'Android') return Smartphone\n if (system === 'iPad') return Tablet\n return Laptop\n}\n\n// This device first, then the newest sign-in.\nconst ordered = (sessions: DeviceSession[]) => [...sessions].sort((a, b) => Number(b.current) - Number(a.current) || b.createdAt.localeCompare(a.createdAt))\n\ntype Confirming = { kind: 'one'; session: DeviceSession } | { kind: 'link'; link: DeviceLink } | { kind: 'others' }\n\nconst titleOf = (what: Confirming, operator: string | undefined) => {\n if (what.kind === 'one') return text('signOutDevice', { name: nameOf(what.session, operator) })\n if (what.kind === 'link') return text('signOutDevice', { name: linkName(what.link) })\n return text('signOutOthersTitle')\n}\n\nconst descriptionOf = (what: Confirming) => text(what.kind === 'one' ? 'signOutDeviceDescription' : what.kind === 'link' ? 'signOutLinkedDeviceDescription' : 'signOutOthersDescription')\n\n/**\n * The devices signed in to the person's account, this one marked, each other one of which they can sign out; and the\n * devices the platform links, each of which they can sign out for good, with the sessions it began.\n */\nexport const DevicesSection = ({ sessions: all, operator, links = [], onSignOut, onSignOutOthers, onSignOutLink }: DevicesSectionProps) => {\n const [busy, setBusy] = useState(false)\n const [error, setError] = useState<string>()\n const [confirming, setConfirming] = useState<Confirming>()\n // A linked device's sessions show as that device.\n const sessions = all.filter((session) => !links.some((link) => link.sessions.includes(session.token)))\n const others = all.filter((session) => !session.current)\n\n const run = (what: Confirming) => {\n if (what.kind === 'one') return onSignOut(what.session.token)\n if (what.kind === 'link') return onSignOutLink!(what.link.id)\n return onSignOutOthers()\n }\n\n const signOut = async (what: Confirming) => {\n setBusy(true)\n setError(undefined)\n try {\n await run(what)\n setConfirming(undefined)\n } catch (failure) {\n if (!(failure instanceof AuthError)) throw failure\n setError(authMessage(failure))\n }\n setBusy(false)\n }\n\n const open = (what: Confirming) => {\n setError(undefined)\n setConfirming(what)\n }\n\n return (\n <AccountSection title={text('devices')} description={text('devicesDescription')}>\n {sessions.length === 0 && links.length === 0 ? (\n <p className=\"text-muted-foreground\">{text('noDevices')}</p>\n ) : (\n <ul className=\"divide-y rounded-md border\">\n {ordered(sessions).map((session) => {\n const Icon = iconOf(session)\n return (\n <li key={session.token} className=\"flex flex-wrap items-center gap-3 px-3 py-2.5\">\n <Icon className=\"size-4 shrink-0 text-muted-foreground\" />\n <span className=\"min-w-0 flex-1\">\n <span className=\"flex flex-wrap items-center gap-2\">\n <bdi className=\"truncate font-medium\">{nameOf(session, operator)}</bdi>\n {session.current && <Badge tone=\"green\">{text('thisDevice')}</Badge>}\n </span>\n <span className=\"block text-xs text-muted-foreground\">\n {text('signedInFromUntil', { from: formatDateTime(Date.parse(session.createdAt)), until: formatDateTime(Date.parse(session.expiresAt)) })}\n {!session.staff && session.ipAddress && ` · ${session.ipAddress}`}\n </span>\n </span>\n {!session.current && (\n <Button size=\"sm\" variant=\"ghost\" onClick={() => open({ kind: 'one', session })}>\n {text('signOut')}\n </Button>\n )}\n </li>\n )\n })}\n {links.map((link) => {\n const current = all.some((session) => session.current && link.sessions.includes(session.token))\n return (\n <li key={link.id} className=\"flex flex-wrap items-center gap-3 px-3 py-2.5\">\n <Smartphone className=\"size-4 shrink-0 text-muted-foreground\" />\n <span className=\"min-w-0 flex-1\">\n <span className=\"flex flex-wrap items-center gap-2\">\n <bdi className=\"truncate font-medium\">{linkName(link)}</bdi>\n {current && <Badge tone=\"green\">{text('thisDevice')}</Badge>}\n </span>\n <span className=\"block text-xs text-muted-foreground\">{text('linkedOn', { date: formatDateTime(Date.parse(link.linkedAt)) })}</span>\n </span>\n {!current && onSignOutLink && (\n <Button size=\"sm\" variant=\"ghost\" onClick={() => open({ kind: 'link', link })}>\n {text('signOut')}\n </Button>\n )}\n </li>\n )\n })}\n </ul>\n )}\n {others.length > 0 && (\n <Button className=\"mt-3\" onClick={() => open({ kind: 'others' })}>\n {text('signOutOthers')}\n </Button>\n )}\n {confirming && (\n <Dialog\n title={titleOf(confirming, operator)}\n description={descriptionOf(confirming)}\n onClose={() => setConfirming(undefined)}\n actions={\n <>\n <Button onClick={() => setConfirming(undefined)}>{text('cancel')}</Button>\n <Button variant=\"danger\" loading={busy} onClick={() => void signOut(confirming)}>\n {text('signOut')}\n </Button>\n </>\n }\n >\n <SectionError message={error} />\n </Dialog>\n )}\n </AccountSection>\n )\n}\n","import { useCallback } from 'react'\nimport { useAuth } from '../../auth/auth-provider'\nimport { DevicesSection } from '../devices-section'\nimport { text } from '../messages'\nimport { AccountLoading } from './account-loading'\nimport { useAccountData } from './use-account-data'\n\n/**\n * The `Devices` block: the browsers and apps signed in as the person, this one marked, the others to sign out; and the\n * devices the platform links, when it links any.\n */\nexport const DevicesBlock = () => {\n const { session, staffSignIn, deviceLinks } = useAuth()\n const { account } = session\n const read = useCallback(async () => {\n const [sessions, links] = await Promise.all([account.sessions(), deviceLinks ? account.deviceLinks() : []])\n return { sessions, links }\n }, [account, deviceLinks])\n const { data, error, reload } = useAccountData(read, text('couldNotReadDevices'))\n if (!data) return <AccountLoading error={error} />\n return (\n <DevicesSection\n sessions={data.sessions}\n links={data.links}\n operator={staffSignIn}\n onSignOut={(token) => account.revokeSession(token).then(reload)}\n onSignOutOthers={() => account.revokeOtherSessions().then(reload)}\n onSignOutLink={(id) => account.signOutDeviceLink(id).then(reload)}\n />\n )\n}\n","import { KeyRound, Plus } from 'lucide-react'\nimport { useState } from 'react'\nimport { AuthError, type Passkey, type SignInRule } from '@protobase/client'\nimport { confirmationMinutes } from '@protobase/schema/internal'\nimport { ConfirmSignIn } from '../app/confirm-sign-in'\nimport { authMessage } from '../auth/auth-messages'\nimport { formatDate } from '../format'\nimport { Badge } from '../primitives/badge'\nimport { Button } from '../primitives/button'\nimport { Dialog } from '../primitives/dialog'\nimport { Input } from '../primitives/input'\nimport { AccountSection, SectionError } from './account-section'\nimport { text } from './messages'\n\nexport type PasskeysSectionProps = {\n /** What the sign-in policy says about passkeys. */\n rule: SignInRule\n passkeys: Passkey[]\n /** Each rejects with `AuthError`, which the section shows. */\n onAdd: () => Promise<void>\n onRename: (id: string, name: string) => Promise<void>\n onRemove: (id: string) => Promise<void>\n}\n\nconst descriptions = { allowed: 'passkeysAllowed', required: 'passkeysRequired', forbidden: 'passkeysForbidden' } as const satisfies Record<SignInRule, string>\n\ntype Editing = { kind: 'rename'; passkey: Passkey } | { kind: 'remove'; passkey: Passkey }\n\nexport const PasskeysSection = ({ rule, passkeys, onAdd, onRename, onRemove }: PasskeysSectionProps) => {\n const [busy, setBusy] = useState(false)\n const [error, setError] = useState<string>()\n const [editing, setEditing] = useState<Editing>()\n const [name, setName] = useState('')\n // A passkey asks an older session to confirm it's them first; a first one, on an account without a second step, may take the password.\n const [confirming, setConfirming] = useState<'asked' | 'done'>()\n const keepLast = rule === 'required' && passkeys.length <= 1\n\n const attempt = async (action: () => Promise<void>) => {\n setBusy(true)\n setError(undefined)\n setConfirming(undefined)\n try {\n await action()\n setEditing(undefined)\n } catch (failure) {\n if (!(failure instanceof AuthError)) throw failure\n if (failure.code === 'STRONG_SIGN_IN_REQUIRED') setConfirming('asked')\n else setError(authMessage(failure))\n }\n setBusy(false)\n }\n\n return (\n <AccountSection title={text('passkeys')} status={rule === 'required' && <Badge tone=\"blue\">{text('required')}</Badge>} description={text(descriptions[rule])}>\n <SectionError message={editing ? undefined : error} />\n {passkeys.length > 0 && (\n <ul className=\"mb-3 divide-y rounded-md border\">\n {passkeys.map((passkey) => (\n <li key={passkey.id} className=\"flex flex-wrap items-center gap-3 px-3 py-2.5\">\n <KeyRound className=\"size-4 shrink-0 text-muted-foreground\" />\n <span className=\"min-w-0 flex-1\">\n <span className=\"block truncate font-medium\">{passkey.name ?? text('passkey')}</span>\n <span className=\"block text-xs text-muted-foreground\">\n {passkey.createdAt ? text('addedOn', { date: formatDate(Date.parse(passkey.createdAt)) }) : text('addedEarlier')} · {passkey.backedUp ? text('synced') : text('oneDevice')}\n </span>\n </span>\n <span className=\"flex gap-1\">\n <Button\n size=\"sm\"\n variant=\"ghost\"\n onClick={() => {\n setName(passkey.name ?? '')\n setEditing({ kind: 'rename', passkey })\n }}\n >\n {text('rename')}\n </Button>\n <Button size=\"sm\" variant=\"ghost\" disabled={keepLast} title={keepLast ? text('keepLastPasskey') : undefined} onClick={() => setEditing({ kind: 'remove', passkey })}>\n {text('remove')}\n </Button>\n </span>\n </li>\n ))}\n </ul>\n )}\n {rule !== 'forbidden' && (\n <Button loading={busy && !editing} onClick={() => void attempt(onAdd)}>\n <Plus className=\"size-3.5\" />\n {text('addPasskey')}\n </Button>\n )}\n {/* The browser asks for the new passkey only on a click, so the person adds it again once confirmed. */}\n {confirming === 'asked' && <ConfirmSignIn purpose=\"change\" withPassword minutes={confirmationMinutes} onConfirmed={() => setConfirming('done')} />}\n {confirming === 'done' && <p className=\"mt-2 text-muted-foreground\">{text('confirmedAddPasskey')}</p>}\n {editing?.kind === 'rename' && (\n <Dialog\n title={text('renamePasskey')}\n description={text('renamePasskeyDescription')}\n onClose={() => setEditing(undefined)}\n actions={\n <>\n <Button onClick={() => setEditing(undefined)}>{text('cancel')}</Button>\n <Button variant=\"primary\" loading={busy} disabled={!name.trim()} onClick={() => void attempt(() => onRename(editing.passkey.id, name.trim()))}>\n {text('save')}\n </Button>\n </>\n }\n >\n <label className=\"flex flex-col gap-1.5 font-medium\">\n {text('name')}\n <Input autoFocus value={name} maxLength={60} onChange={(event) => setName(event.target.value)} />\n </label>\n <SectionError message={error} />\n </Dialog>\n )}\n {editing?.kind === 'remove' && (\n <Dialog\n title={text('removePasskey')}\n description={text('removePasskeyDescription', { name: editing.passkey.name ?? text('thisPasskey') })}\n onClose={() => setEditing(undefined)}\n actions={\n <>\n <Button onClick={() => setEditing(undefined)}>{text('cancel')}</Button>\n <Button variant=\"danger\" loading={busy} onClick={() => void attempt(() => onRemove(editing.passkey.id))}>\n {text('remove')}\n </Button>\n </>\n }\n >\n {error && <SectionError message={error} />}\n </Dialog>\n )}\n </AccountSection>\n )\n}\n","import { useCallback } from 'react'\nimport { useAuth } from '../../auth/auth-provider'\nimport { PasskeysSection } from '../passkeys-section'\nimport { text } from '../messages'\nimport { AccountLoading } from './account-loading'\nimport { useAccountData } from './use-account-data'\n\n/** The `Passkeys` block: the signed-in person's passkeys, within what the sign-in policy allows. */\nexport const PasskeysBlock = () => {\n const { account } = useAuth().session\n const load = useCallback(() => Promise.all([account.signInMethods(), account.passkeys()]), [account])\n const { data, error, reload } = useAccountData(load, text('couldNotReadMethods'))\n if (!data) return <AccountLoading error={error} />\n const [methods, passkeys] = data\n return (\n <PasskeysSection\n rule={methods.policy.passkey}\n passkeys={passkeys}\n onAdd={() => account.addPasskey().then(reload)}\n onRename={(id, name) => account.renamePasskey(id, name).then(reload)}\n onRemove={(id) => account.removePasskey(id).then(reload)}\n />\n )\n}\n","import { useId, useState } from 'react'\nimport { AuthError } from '@protobase/client'\nimport { authMessage } from '../auth/auth-messages'\nimport { minPasswordLength } from '../auth/reset-password-form'\nimport { Button } from '../primitives/button'\nimport { Dialog } from '../primitives/dialog'\nimport { Input } from '../primitives/input'\nimport { SectionError } from './account-section'\nimport { text } from './messages'\n\nexport type PasswordChangeDialogProps = {\n /** The account has a password: ask for it, and say the other devices are signed out. Without one, it sets the first. */\n hasPassword: boolean\n /** Rejects with `AuthError`, which the dialog shows; resolves when the password is saved. */\n onSave: (input: { current: string; next: string }) => Promise<void>\n onClose: () => void\n}\n\n// Better Auth's answers to a new password or a wrong current one, in words for the person at the keyboard.\nconst passwordMessage = (error: AuthError) => {\n if (error.code === 'PASSWORD_TOO_SHORT') return text('useAtLeast', { length: minPasswordLength })\n if (error.code === 'PASSWORD_TOO_LONG') return text('passwordTooLong')\n return authMessage(error)\n}\n\n// Why the new password cannot be sent yet, before the server is asked.\nconst draftProblem = (next: string, repeat: string) => {\n if (next.length < minPasswordLength) return text('useAtLeast', { length: minPasswordLength })\n if (next !== repeat) return text('passwordsDiffer')\n return undefined\n}\n\n/** Changes the account's password with the current one, or sets a first one for an account without. */\nexport const PasswordChangeDialog = ({ hasPassword, onSave, onClose }: PasswordChangeDialogProps) => {\n const [current, setCurrent] = useState('')\n const [next, setNext] = useState('')\n const [repeat, setRepeat] = useState('')\n const [busy, setBusy] = useState(false)\n const [error, setError] = useState<string>()\n const formId = useId()\n const filled = (!hasPassword || current) && next && repeat\n\n const save = async () => {\n const problem = draftProblem(next, repeat)\n setError(problem)\n if (problem) return\n setBusy(true)\n try {\n await onSave({ current, next })\n } catch (failure) {\n if (!(failure instanceof AuthError)) throw failure\n setError(passwordMessage(failure))\n setBusy(false)\n }\n }\n\n return (\n <Dialog\n title={hasPassword ? text('changePassword') : text('setPassword')}\n description={text('atLeast', { length: minPasswordLength })}\n onClose={onClose}\n actions={\n <>\n <Button onClick={onClose}>{text('cancel')}</Button>\n <Button variant=\"primary\" type=\"submit\" form={formId} loading={busy} disabled={!filled}>\n {text('save')}\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 save()\n }}\n >\n {hasPassword && (\n <label className=\"flex flex-col gap-1.5 font-medium\">\n {text('currentPassword')}\n <Input type=\"password\" name=\"current-password\" autoComplete=\"current-password\" autoFocus value={current} onChange={(event) => setCurrent(event.target.value)} />\n </label>\n )}\n <label className=\"flex flex-col gap-1.5 font-medium\">\n {text('newPassword')}\n <Input type=\"password\" name=\"new-password\" autoComplete=\"new-password\" autoFocus={!hasPassword} value={next} invalid={Boolean(error)} onChange={(event) => setNext(event.target.value)} />\n </label>\n <label className=\"flex flex-col gap-1.5 font-medium\">\n {text('repeatPassword')}\n <Input type=\"password\" name=\"repeat-password\" autoComplete=\"new-password\" value={repeat} invalid={Boolean(error)} onChange={(event) => setRepeat(event.target.value)} />\n </label>\n {hasPassword && <p className=\"text-muted-foreground\">{text('changeSignsOutOthers')}</p>}\n <SectionError message={error} />\n </form>\n </Dialog>\n )\n}\n","import { useState } from 'react'\nimport { Button } from '../primitives/button'\nimport { AccountSection, SectionNotice } from './account-section'\nimport { PasswordChangeDialog } from './password-change-dialog'\nimport { text } from './messages'\n\nexport type PasswordSectionProps = {\n /** What the sign-in policy says about passwords: while they are off, the section only says so. */\n rule: 'allowed' | 'forbidden'\n hasPassword: boolean\n /** Staff signed in as the person, who may not change their sign-in: the section only says so. */\n staff: boolean\n /** Each rejects with `AuthError`, which the dialog shows. */\n onChange: (current: string, next: string) => Promise<void>\n onSet: (next: string) => Promise<void>\n}\n\nconst descriptionOf = ({ rule, hasPassword, staff }: Pick<PasswordSectionProps, 'rule' | 'hasPassword' | 'staff'>) => {\n if (staff) return text('passwordStaff')\n if (rule === 'forbidden') return text('passwordForbidden')\n return hasPassword ? text('passwordIsSet') : text('passwordNotSet')\n}\n\n/** The signed-in person's password: change it with the current one, or set a first one without signing anyone out. */\nexport const PasswordSection = ({ rule, hasPassword, staff, onChange, onSet }: PasswordSectionProps) => {\n const [editing, setEditing] = useState(false)\n const [saved, setSaved] = useState(false)\n const canEdit = !staff && rule === 'allowed'\n\n return (\n <AccountSection title={text('password')} description={descriptionOf({ rule, hasPassword, staff })}>\n <SectionNotice message={saved ? text('passwordSaved') : undefined} />\n {canEdit && (\n <Button\n onClick={() => {\n setSaved(false)\n setEditing(true)\n }}\n >\n {hasPassword ? text('changePassword') : text('setPassword')}\n </Button>\n )}\n {editing && (\n <PasswordChangeDialog\n hasPassword={hasPassword}\n onClose={() => setEditing(false)}\n onSave={async ({ current, next }) => {\n await (hasPassword ? onChange(current, next) : onSet(next))\n setEditing(false)\n setSaved(true)\n }}\n />\n )}\n </AccountSection>\n )\n}\n","import { useCallback } from 'react'\nimport { useAuth } from '../../auth/auth-provider'\nimport { PasswordSection } from '../password-section'\nimport { text } from '../messages'\nimport { AccountLoading } from './account-loading'\nimport { useAccountData } from './use-account-data'\n\n/**\n * The `Password` block: the signed-in person changes their password, or sets a first one without signing anyone out,\n * within what the sign-in policy allows; staff signed in as the person cannot.\n */\nexport const PasswordBlock = () => {\n const { session, state } = useAuth()\n const { account } = session\n const { data: methods, error, reload } = useAccountData(useCallback(() => account.signInMethods(), [account]), text('couldNotReadMethods'))\n if (!methods) return <AccountLoading error={error} />\n return (\n <PasswordSection\n rule={methods.policy.password}\n hasPassword={methods.account.password}\n staff={state.kind === 'signed-in' && Boolean(state.staff)}\n onChange={(current, next) => account.changePassword(current, next).then(reload)}\n onSet={(next) => account.setPassword(next).then(reload)}\n />\n )\n}\n","import { useState } from 'react'\nimport { AuthError } from '@protobase/client'\nimport { emailCodeMinutes } from '@protobase/schema/internal'\nimport { authMessage } from '../auth/auth-messages'\nimport { Button } from '../primitives/button'\nimport { Dialog } from '../primitives/dialog'\nimport { Input } from '../primitives/input'\nimport { OtpInput } from '../primitives/otp-input'\nimport { SectionError } from './account-section'\nimport { text } from './messages'\n\n/** Changing the address: a code mailed to the new one, then that code. Each rejects with `AuthError`, which the dialog shows. */\nexport type EmailChange = {\n request: (newEmail: string) => Promise<void>\n confirm: (newEmail: string, code: string) => Promise<void>\n}\n\nexport type ChangeEmailDialogProps = { email: string; change: EmailChange; onDone: () => void; onClose: () => void }\n\n/** Asks for the new address, mails it a code, and moves the account to it once the code is right. */\nexport const ChangeEmailDialog = ({ email, change, onDone, onClose }: ChangeEmailDialogProps) => {\n const [draft, setDraft] = useState('')\n const [sentTo, setSentTo] = useState<string>()\n const [code, setCode] = useState('')\n const [busy, setBusy] = useState(false)\n const [error, setError] = useState<string>()\n\n const run = async (step: () => Promise<void>) => {\n setBusy(true)\n setError(undefined)\n try {\n await step()\n } catch (failure) {\n if (!(failure instanceof AuthError)) throw failure\n setError(authMessage(failure))\n }\n setBusy(false)\n }\n\n const newEmail = draft.trim()\n const send = () =>\n run(async () => {\n await change.request(newEmail)\n setCode('')\n setSentTo(newEmail)\n })\n const confirm = (complete: string) =>\n run(async () => {\n await change.confirm(sentTo!, complete)\n onDone()\n })\n\n if (!sentTo) {\n return (\n <Dialog\n title={text('changeEmail')}\n description={text('changeEmailDescription')}\n onClose={onClose}\n actions={\n <>\n <Button onClick={onClose}>{text('cancel')}</Button>\n <Button variant=\"primary\" loading={busy} disabled={!newEmail || newEmail.toLowerCase() === email.toLowerCase()} onClick={() => void send()}>\n {text('sendCode')}\n </Button>\n </>\n }\n >\n <label className=\"flex flex-col gap-1.5 font-medium\">\n {text('newEmail')}\n <Input type=\"email\" autoComplete=\"email\" autoFocus value={draft} onChange={(event) => setDraft(event.target.value)} />\n </label>\n <SectionError message={error} />\n </Dialog>\n )\n }\n\n return (\n <Dialog\n title={text('changeEmail')}\n description={text('codeSentTo', { email: sentTo, minutes: emailCodeMinutes })}\n onClose={onClose}\n actions={\n <>\n <Button\n variant=\"ghost\"\n onClick={() => {\n setSentTo(undefined)\n setError(undefined)\n }}\n >\n {text('otherAddress')}\n </Button>\n <Button variant=\"primary\" loading={busy} disabled={code.length < 6} onClick={() => void confirm(code)}>\n {text('changeEmail')}\n </Button>\n </>\n }\n >\n <label className=\"flex flex-col gap-1.5 font-medium\">\n {text('code')}\n <OtpInput name=\"code\" required autoFocus value={code} invalid={Boolean(error)} onChange={setCode} onComplete={(complete) => !busy && void confirm(complete)} />\n </label>\n <SectionError message={error} />\n </Dialog>\n )\n}\n","import { useState } from 'react'\nimport { AuthError } from '@protobase/client'\nimport { authMessage } from '../auth/auth-messages'\nimport { Button } from '../primitives/button'\nimport { Dialog } from '../primitives/dialog'\nimport { Input } from '../primitives/input'\nimport { AccountSection, SectionError } from './account-section'\nimport { ChangeEmailDialog, type EmailChange } from './change-email-dialog'\nimport { text } from './messages'\n\nexport type ProfileSectionProps = {\n name: string\n email: string\n /** Rejects with `AuthError`, which the section shows. */\n onRename: (name: string) => Promise<void>\n /** Offers to change the address, when the server can mail the code that confirms it. */\n emailChange?: EmailChange\n /** Called once the address changed, to read it back. */\n onEmailChanged?: () => void\n}\n\n/** The signed-in person's name, which they can change, and the address they sign in with, which they can change with mail. */\nexport const ProfileSection = ({ name, email, onRename, emailChange, onEmailChanged }: ProfileSectionProps) => {\n const [editing, setEditing] = useState(false)\n const [changingEmail, setChangingEmail] = useState(false)\n const [draft, setDraft] = useState('')\n const [busy, setBusy] = useState(false)\n const [error, setError] = useState<string>()\n\n const rename = async () => {\n setBusy(true)\n setError(undefined)\n try {\n await onRename(draft.trim())\n setEditing(false)\n } catch (failure) {\n if (!(failure instanceof AuthError)) throw failure\n setError(authMessage(failure))\n }\n setBusy(false)\n }\n\n return (\n <AccountSection title={text('profile')} description={text('profileDescription')}>\n <dl className=\"mb-3 grid grid-cols-[auto_1fr] gap-x-6 gap-y-1.5\">\n <dt className=\"text-muted-foreground\">{text('name')}</dt>\n <dd className=\"min-w-0 truncate font-medium\">{name}</dd>\n <dt className=\"text-muted-foreground\">{text('email')}</dt>\n <dd className=\"min-w-0 truncate font-medium\">{email}</dd>\n </dl>\n <div className=\"flex flex-wrap gap-2\">\n <Button\n onClick={() => {\n setDraft(name)\n setError(undefined)\n setEditing(true)\n }}\n >\n {text('changeName')}\n </Button>\n {emailChange && <Button onClick={() => setChangingEmail(true)}>{text('changeEmail')}</Button>}\n </div>\n {editing && (\n <Dialog\n title={text('changeName')}\n description={text('changeNameDescription')}\n onClose={() => setEditing(false)}\n actions={\n <>\n <Button onClick={() => setEditing(false)}>{text('cancel')}</Button>\n <Button variant=\"primary\" loading={busy} disabled={!draft.trim() || draft.trim() === name} onClick={() => void rename()}>\n {text('save')}\n </Button>\n </>\n }\n >\n <label className=\"flex flex-col gap-1.5 font-medium\">\n {text('name')}\n <Input autoFocus value={draft} maxLength={100} onChange={(event) => setDraft(event.target.value)} />\n </label>\n <SectionError message={error} />\n </Dialog>\n )}\n {changingEmail && emailChange && (\n <ChangeEmailDialog\n email={email}\n change={emailChange}\n onClose={() => setChangingEmail(false)}\n onDone={() => {\n setChangingEmail(false)\n onEmailChanged?.()\n }}\n />\n )}\n </AccountSection>\n )\n}\n","import { useCallback } from 'react'\nimport { useAuth } from '../../auth/auth-provider'\nimport { ProfileSection } from '../profile-section'\nimport { text } from '../messages'\nimport { AccountLoading } from './account-loading'\nimport { useAccountData } from './use-account-data'\n\n/** The `Profile` block: the signed-in person's name and address, which they can change; the address only with mail. */\nexport const ProfileBlock = () => {\n const { session, changeEmail } = useAuth()\n const { data: user, loaded, error, reload } = useAccountData(useCallback(() => session.session(), [session]), text('couldNotReadProfile'))\n if (!loaded) return <AccountLoading error={error} />\n if (!user) return null\n const emailChange = changeEmail ? { request: session.account.requestEmailChange, confirm: session.account.changeEmail } : undefined\n return <ProfileSection name={user.name} email={user.email} onRename={(name) => session.account.updateName(name).then(reload)} emailChange={emailChange} onEmailChanged={reload} />\n}\n","import { useState } from 'react'\nimport { AuthError } from '@protobase/client'\nimport { confirmationMinutes } from '@protobase/schema/internal'\nimport { ConfirmSignIn } from '../app/confirm-sign-in'\nimport { authMessage } from '../auth/auth-messages'\nimport { Button } from '../primitives/button'\nimport { Dialog } from '../primitives/dialog'\nimport { Input } from '../primitives/input'\nimport { text } from './messages'\n\nexport type PasswordDialogProps = {\n title: string\n description: string\n /** The button that runs `onConfirm`, for example \"Turn off\". */\n confirmLabel: string\n danger?: boolean\n /** Ask for the password, which the change needs when the account has one. */\n needsPassword: boolean\n /** Rejects with `AuthError`, which the dialog shows; resolves when the change is done. */\n onConfirm: (password?: string) => Promise<void>\n onClose: () => void\n}\n\n/**\n * Confirms a change to the account's sign-in, with the password when it has one. Without one, an older session that the\n * change refuses (`STRONG_SIGN_IN_REQUIRED`) confirms it's them in place, and the change runs again.\n */\nexport const PasswordDialog = ({ title, description, confirmLabel, danger, needsPassword, onConfirm, onClose }: PasswordDialogProps) => {\n const [password, setPassword] = useState('')\n const [busy, setBusy] = useState(false)\n const [error, setError] = useState<string>()\n const [confirming, setConfirming] = useState(false)\n\n const confirm = async () => {\n setBusy(true)\n setError(undefined)\n setConfirming(false)\n try {\n await onConfirm(needsPassword ? password : undefined)\n } catch (failure) {\n if (!(failure instanceof AuthError)) throw failure\n if (failure.code === 'STRONG_SIGN_IN_REQUIRED') setConfirming(true)\n else setError(authMessage(failure))\n setBusy(false)\n }\n }\n\n return (\n <Dialog\n title={title}\n description={description}\n onClose={onClose}\n actions={\n <>\n <Button onClick={onClose}>{text('cancel')}</Button>\n <Button variant={danger ? 'danger' : 'primary'} loading={busy} disabled={needsPassword && !password} onClick={() => void confirm()}>\n {confirmLabel}\n </Button>\n </>\n }\n >\n {needsPassword && (\n <label className=\"flex flex-col gap-1.5 font-medium\">\n {text('yourPassword')}\n <Input type=\"password\" autoComplete=\"current-password\" autoFocus value={password} invalid={Boolean(error)} onChange={(event) => setPassword(event.target.value)} onKeyDown={(event) => event.key === 'Enter' && password && void confirm()} />\n </label>\n )}\n {error && (\n <p role=\"alert\" className=\"mt-2 text-body font-medium text-danger-text\">\n {error}\n </p>\n )}\n {confirming && <ConfirmSignIn purpose=\"change\" minutes={confirmationMinutes} onConfirmed={() => void confirm()} />}\n </Dialog>\n )\n}\n","import { useState } from 'react'\nimport type { AuthenticatorSetup, SignInRule } from '@protobase/client'\nimport { Badge } from '../primitives/badge'\nimport { Button } from '../primitives/button'\nimport { Dialog } from '../primitives/dialog'\nimport { AccountSection } from './account-section'\nimport { BackupCodes } from './backup-codes'\nimport { PasswordDialog } from './password-dialog'\nimport { TwoFactorSetup } from './two-factor-setup'\nimport { text } from './messages'\n\nexport type TwoFactorSectionProps = {\n /** What the sign-in policy says about two-factor authentication. */\n rule: SignInRule\n /** The account has it on, with an authenticator app (and backup codes) or with emailed codes only. */\n enabled: boolean\n authenticatorApp: boolean\n /** Mail can be sent, so emailed codes are offered. */\n mail: boolean\n /** The account has a password, which changes here ask for. */\n needsPassword: boolean\n /** Each rejects with `AuthError`, which the section shows. */\n onStartApp: (password?: string) => Promise<AuthenticatorSetup>\n onConfirmApp: (code: string) => Promise<void>\n onEmailedCodes: (password?: string) => Promise<void>\n onTurnOff: (password?: string) => Promise<void>\n onNewBackupCodes: (password?: string) => Promise<string[]>\n /** Something changed: read the account again. */\n onChanged: () => void\n}\n\nconst offDescriptions = { allowed: 'twoFactorAllowed', required: 'twoFactorRequired', forbidden: 'twoFactorForbidden' } as const satisfies Record<SignInRule, string>\n\ntype Open = { kind: 'setup'; appOnly: boolean } | { kind: 'turn-off' } | { kind: 'new-codes' } | { kind: 'codes'; codes: string[] }\n\nexport const TwoFactorSection = (props: TwoFactorSectionProps) => {\n const { rule, enabled, authenticatorApp, mail, needsPassword, onTurnOff, onNewBackupCodes, onChanged } = props\n const [open, setOpen] = useState<Open>()\n const close = () => setOpen(undefined)\n\n const status = enabled ? <Badge tone=\"green\">{text('on')}</Badge> : rule === 'required' ? <Badge tone=\"amber\">{text('required')}</Badge> : <Badge>{text('off')}</Badge>\n const description = !enabled\n ? text(offDescriptions[rule])\n : authenticatorApp\n ? text(mail ? 'twoFactorOnWithAppOrMail' : 'twoFactorOnWithApp')\n : text('twoFactorOnWithMail')\n\n if (open?.kind === 'setup') {\n return (\n <AccountSection title={text('twoFactor')} status={status} description={description}>\n <div className=\"max-w-sm\">\n <TwoFactorSetup\n offerEmailedCodes={mail && !open.appOnly}\n needsPassword={needsPassword}\n onStartApp={props.onStartApp}\n onConfirmApp={props.onConfirmApp}\n onEmailedCodes={props.onEmailedCodes}\n onCancel={close}\n onDone={() => {\n close()\n onChanged()\n }}\n />\n </div>\n </AccountSection>\n )\n }\n\n return (\n <AccountSection title={text('twoFactor')} status={status} description={description}>\n <div className=\"flex flex-wrap gap-2\">\n {!enabled && rule !== 'forbidden' && (\n <Button variant=\"primary\" onClick={() => setOpen({ kind: 'setup', appOnly: false })}>\n {text('turnOn')}\n </Button>\n )}\n {enabled && !authenticatorApp && rule !== 'forbidden' && <Button onClick={() => setOpen({ kind: 'setup', appOnly: true })}>{text('addAuthenticator')}</Button>}\n {enabled && authenticatorApp && <Button onClick={() => setOpen({ kind: 'new-codes' })}>{text('newBackupCodes')}</Button>}\n {enabled && (\n <Button variant=\"danger\" disabled={rule === 'required'} title={rule === 'required' ? text('twoFactorIsRequired') : undefined} onClick={() => setOpen({ kind: 'turn-off' })}>\n {text('turnOff')}\n </Button>\n )}\n </div>\n {open?.kind === 'turn-off' && (\n <PasswordDialog\n title={text('turnOffTitle')}\n description={text('turnOffDescription')}\n confirmLabel={text('turnOff')}\n danger\n needsPassword={needsPassword}\n onClose={close}\n onConfirm={async (password) => {\n await onTurnOff(password)\n close()\n onChanged()\n }}\n />\n )}\n {open?.kind === 'new-codes' && (\n <PasswordDialog\n title={text('newCodesTitle')}\n description={text('newCodesDescription')}\n confirmLabel={text('makeNewCodes')}\n needsPassword={needsPassword}\n onClose={close}\n onConfirm={async (password) => setOpen({ kind: 'codes', codes: await onNewBackupCodes(password) })}\n />\n )}\n {open?.kind === 'codes' && (\n <Dialog\n title={text('yourNewCodes')}\n description={text('keepCodesSafe')}\n onClose={close}\n actions={\n <Button variant=\"primary\" onClick={close}>\n {text('savedCodes')}\n </Button>\n }\n >\n <BackupCodes codes={open.codes} />\n </Dialog>\n )}\n </AccountSection>\n )\n}\n","import { useCallback } from 'react'\nimport { useAuth } from '../../auth/auth-provider'\nimport { TwoFactorSection } from '../two-factor-section'\nimport { text } from '../messages'\nimport { AccountLoading } from './account-loading'\nimport { useAccountData } from './use-account-data'\n\n/** The `TwoFactor` block: the signed-in person's two-factor authentication, within what the sign-in policy allows. */\nexport const TwoFactorBlock = () => {\n const { account } = useAuth().session\n const { data: methods, error, reload } = useAccountData(useCallback(() => account.signInMethods(), [account]), text('couldNotReadMethods'))\n if (!methods) return <AccountLoading error={error} />\n return (\n <TwoFactorSection\n rule={methods.policy.twoFactor}\n enabled={methods.account.twoFactor}\n authenticatorApp={methods.account.authenticatorApp}\n mail={methods.mail}\n needsPassword={methods.account.password}\n onStartApp={(password) => account.startAuthenticatorApp(password)}\n onConfirmApp={(code) => account.confirmAuthenticatorApp(code)}\n onEmailedCodes={(password) => account.turnOnEmailedCodes(password)}\n onTurnOff={(password) => account.turnOffTwoFactor(password)}\n onNewBackupCodes={(password) => account.newBackupCodes(password)}\n onChanged={reload}\n />\n )\n}\n","import type { ReactNode } from 'react'\nimport { CustomBoundary } from './custom-boundary'\nimport { Problem } from './problem'\nimport { text } from './messages'\n\n/** What stands in for a custom component the app cannot draw: its fallback, under the warning in development, or the warning alone without one. */\nconst Replacement = ({ problem, fallback }: { problem: ReactNode; fallback: ReactNode | undefined }) => {\n if (fallback === undefined) return <Problem>{problem}</Problem>\n return (\n <>\n {import.meta.env?.DEV && <Problem>{problem}</Problem>}\n {fallback}\n </>\n )\n}\n\ntype CustomOrFallbackProps = {\n /** The component's registered name. */\n name: string\n /** Whether the app has a component registered under `name`. */\n registered: boolean\n /** The fallback the layout declares, drawn when the component is missing or throws; `undefined` when it declares none. */\n fallback: ReactNode | undefined\n /** The component, drawn when it is registered. */\n children: ReactNode\n}\n\n/** A project's or plugin's layout component, or, when it is missing or throws, the fallback its layout declares. */\nexport const CustomOrFallback = ({ name, registered, fallback, children }: CustomOrFallbackProps) => {\n if (!registered) return <Replacement problem={text.rich('noComponent', { component: name })} fallback={fallback} />\n return (\n <CustomBoundary name={name} fallback={fallback === undefined ? undefined : <Replacement problem={text.rich('couldNotDraw', { name })} fallback={fallback} />}>\n {children}\n </CustomBoundary>\n )\n}\n","import { Fragment, useMemo, type ComponentType } from 'react'\nimport { fillProps, formatMessage, isInlineChild, isLayoutNode, pointerOf, scopeValue, type LayoutChild, type LayoutNode, type LayoutValue, type ReaderTexts } from '@protobase/layout'\nimport { fillText, unmarkFieldRefs, valueText } from '@protobase/schema/internal'\nimport { ActionBlock } from './blocks/action'\nimport type { BlockProps } from './blocks/block-props'\nimport { CardBlock } from './blocks/card'\nimport { CardRowBlock } from './blocks/card-row'\nimport { ChartBlock } from './blocks/chart'\nimport { TimelineBlock } from './blocks/timeline/timeline'\nimport { GraphBlock } from './blocks/graph/graph-block'\nimport { ComposerBlock } from './blocks/composer'\nimport { DetailsBlock, SummaryBlock } from './blocks/details'\nimport { DiffBlock } from './blocks/diff'\nimport { FieldBlock } from './blocks/field'\nimport { GridBlock } from './blocks/grid'\nimport { ImageBlock } from './blocks/image'\nimport { BooleanFieldBlock, ChipFieldBlock, DateFieldBlock, NumberFieldBlock, TextFieldBlock, UrlFieldBlock } from './blocks/inline-field'\nimport { LinkBlock } from './blocks/link'\nimport { ModalFormBlock } from './blocks/modal-form'\nimport { PageBlock } from './blocks/page-block'\nimport { ProgressBlock } from './blocks/progress'\nimport { RecordCardBlock } from './blocks/record-card'\nimport { RecordCardsBlock } from './blocks/record-cards'\nimport { RecordRowBlock } from './blocks/record-row'\nimport { SettingsBlock } from './blocks/settings'\nimport { ShowBlock } from './blocks/show'\nimport { MatchBlock, SwitchBlock } from './blocks/switch'\nimport { StatBlock } from './blocks/stat'\nimport { TableBlock } from './blocks/table'\nimport { TabBlock, TabsBlock } from './blocks/tabs'\nimport { ThreadBlock } from './blocks/thread'\nimport { BoxBlock, ColumnBlock, RowBlock, TextBlock } from './blocks/plain'\nimport { ArrayFieldBlock } from './blocks/array-field'\nimport { RecordsIteratorBlock } from './blocks/records-iterator'\nimport { SelectInputBlock } from './blocks/select-input'\nimport { ReferenceArrayFieldBlock } from './blocks/reference-array-field'\nimport { ReferenceFieldBlock } from './blocks/reference-field'\nimport { ReferenceManyFieldBlock } from './blocks/reference-many-field'\nimport { UsersBlock } from '../../users/users-block'\nimport { ConnectedAccountsBlock } from '../../account/blocks/connected-accounts-block'\nimport { PersonalMailBlock } from '../../account/blocks/personal-mail-block'\nimport { ConnectedAppsBlock } from '../../account/blocks/connected-apps-block'\nimport { PersonalAccessTokensBlock } from '../../account/blocks/personal-access-tokens-block'\nimport { ConnectionsBlock } from '../../account/blocks/connections-block'\nimport { DeleteAccountBlock } from '../../account/blocks/delete-account-block'\nimport { DevicesBlock } from '../../account/blocks/devices-block'\nimport { PasskeysBlock } from '../../account/blocks/passkeys-block'\nimport { PasswordBlock } from '../../account/blocks/password-block'\nimport { ProfileBlock } from '../../account/blocks/profile-block'\nimport { TwoFactorBlock } from '../../account/blocks/two-factor-block'\nimport { ComponentElement } from './component-reads'\nimport { CustomBoundary } from './custom-boundary'\nimport { CustomChosen } from './custom-chosen'\nimport { CustomOrFallback } from './custom-or-fallback'\nimport { Problem } from './problem'\nimport { useProjectUi } from './project-ui'\nimport { usePageParamValues } from './page-params'\nimport { useScopeStack, valueScopeOf } from './record-scope'\nimport { text } from './messages'\nimport { useAppTexts, withPropTexts } from './app-texts'\n\nconst blocks: Record<string, ComponentType<BlockProps>> = {\n Page: PageBlock,\n Grid: GridBlock,\n Card: CardBlock,\n Stat: StatBlock,\n RecordCard: RecordCardBlock,\n Field: FieldBlock,\n Diff: DiffBlock,\n Table: TableBlock,\n CardRow: CardRowBlock,\n RecordRow: RecordRowBlock,\n RecordCards: RecordCardsBlock,\n Chart: ChartBlock,\n Timeline: TimelineBlock,\n Graph: GraphBlock,\n Progress: ProgressBlock,\n Image: ImageBlock,\n ModalForm: ModalFormBlock,\n Thread: ThreadBlock,\n Composer: ComposerBlock,\n Action: ActionBlock,\n Show: ShowBlock,\n Switch: SwitchBlock,\n Match: MatchBlock,\n Link: LinkBlock,\n Settings: SettingsBlock,\n Tabs: TabsBlock,\n Tab: TabBlock,\n Users: UsersBlock,\n Profile: ProfileBlock,\n Password: PasswordBlock,\n Passkeys: PasskeysBlock,\n TwoFactor: TwoFactorBlock,\n ConnectedAccounts: ConnectedAccountsBlock,\n PersonalMail: PersonalMailBlock,\n Connections: ConnectionsBlock,\n Devices: DevicesBlock,\n ConnectedApps: ConnectedAppsBlock,\n PersonalAccessTokens: PersonalAccessTokensBlock,\n DeleteAccount: DeleteAccountBlock,\n Box: BoxBlock,\n Row: RowBlock,\n Column: ColumnBlock,\n Text: TextBlock,\n ReferenceManyField: ReferenceManyFieldBlock,\n ReferenceArrayField: ReferenceArrayFieldBlock,\n ArrayField: ArrayFieldBlock,\n RecordsIterator: RecordsIteratorBlock,\n ReferenceField: ReferenceFieldBlock,\n SelectInput: SelectInputBlock,\n Details: DetailsBlock,\n Summary: SummaryBlock,\n TextField: TextFieldBlock,\n NumberField: NumberFieldBlock,\n DateField: DateFieldBlock,\n BooleanField: BooleanFieldBlock,\n UrlField: UrlFieldBlock,\n ChipField: ChipFieldBlock,\n}\n\n// The blocks that put their classes on an element of their own; the others draw none, or several, and get a <div> for them.\nconst ownClasses = new Set(['Page', 'Grid', 'Card', 'Stat', 'RecordCard', 'Field', 'Diff', 'Table', 'CardRow', 'RecordRow', 'RecordCards', 'Chart', 'Timeline', 'Graph', 'Progress', 'Image', 'Thread', 'Link', 'Tabs', 'Settings', 'Show', 'Switch', 'Action', 'Box', 'Row', 'Column', 'Text', 'ReferenceField', 'SelectInput', 'Details', 'Summary', 'TextField', 'NumberField', 'DateField', 'BooleanField', 'UrlField', 'ChipField'])\n\n/** A child and its place in the page's tree, the JSON Pointer its planned read names it by; none outside a page. */\ntype Placed = { child: LayoutChild; at?: string }\n\nconst placed = (children: LayoutChild[], at: string | undefined, ...steps: string[]): Placed[] =>\n children.map((child, index) => ({ child, ...(at !== undefined && { at: pointerOf(at, ...steps, index) }) }))\n\n/** A text child with its `{{path}}`s filled from the records around it and the page's parameters, as a prop's are. */\nconst FilledText = ({ text }: { text: string }) => {\n const stack = useScopeStack()\n const params = usePageParamValues()\n const scope = { ...valueScopeOf(stack), params }\n return <>{fillText(text, (path) => valueText(scopeValue(scope, path)))}</>\n}\n\nconst textChild = (text: string, key: number) => (text.includes('{{') ? <FilledText key={key} text={text} /> : <Fragment key={key}>{text}</Fragment>)\n\n/** Text and links as they run in one line. */\nconst renderInline = (run: Placed[]) => run.map(({ child, at }, position) => (typeof child === 'string' ? textChild(child, position) : <RenderNode key={position} node={child} at={at} />))\n\n/** Text, links and field components run together as one paragraph, like a sentence with a link in it; other elements stand alone. */\nconst renderChildren = (children: Placed[]) => {\n const runs: Placed[][] = []\n for (const entry of children) {\n const last = runs.at(-1)\n if (isInlineChild(entry.child) && last && isInlineChild(last[0]!.child)) last.push(entry)\n else runs.push([entry])\n }\n return runs.map((run, index) => {\n const [first] = run\n if (!isInlineChild(first!.child)) return <RenderNode key={index} node={first!.child as LayoutNode} at={first!.at} />\n return (\n <p key={index} className=\"leading-6\">\n {renderInline(run)}\n </p>\n )\n })\n}\n\nconst isElements = (value: LayoutValue): value is LayoutNode | LayoutNode[] => isLayoutNode(value) || (Array.isArray(value) && value.length > 0 && value.every(isLayoutNode))\n\n/** Element props (`actions={...}`) rendered like children; the block decides where they go and in which record. */\nconst renderSlots = (node: LayoutNode, at: string | undefined) =>\n Object.fromEntries(Object.entries(node.props).flatMap(([name, value]) => (isElements(value) ? [[name, <>{renderChildren(slotted(value, at, name))}</>]] : [])))\n\n// One element in a prop is at the prop itself, a list of them each at its index\nconst slotted = (value: LayoutNode | LayoutNode[], at: string | undefined, name: string): Placed[] =>\n Array.isArray(value) ? placed(value, at, 'props', name) : [{ child: value, ...(at !== undefined && { at: pointerOf(at, 'props', name) }) }]\n\nconst isObject = (value: unknown): value is Record<string, LayoutValue> => typeof value === 'object' && value !== null && !Array.isArray(value)\n\n// A <Trans> child as the text it runs as: its message in the user's language, each tag the element `components` gives\n// it with the text inside the tag as its children\nconst transChildren = (node: LayoutNode, texts: ReaderTexts | undefined): LayoutChild[] => {\n const components = isObject(node.props.components) ? node.props.components : {}\n const tags = Object.fromEntries(Object.entries(components).flatMap(([tag, element]) => (isLayoutNode(element) ? [[tag, (chunks: unknown[]) => ({ ...element, children: [...element.children, ...(chunks as LayoutChild[])] })]] : [])))\n const formatted = formatMessage<LayoutNode>(texts, String(node.props.i18nKey), isObject(node.props.values) ? node.props.values : {}, tags)\n return Array.isArray(formatted) ? formatted.map((part) => (typeof part === 'string' || isLayoutNode(part) ? part : String(part))) : [formatted]\n}\n\n/**\n * One element of a composed page: a built-in block, or the project's component registered under its name. A block's\n * `{{path}}`s are filled from the records around it and the page's parameters before it draws. `at` is its place in\n * the page's tree, by which a block finds its planned read.\n */\nexport const RenderNode = ({ node: written, at }: { node: LayoutNode; at?: string }) => {\n const { components } = useProjectUi()\n const stack = useScopeStack()\n const params = usePageParamValues()\n const texts = useAppTexts()\n const node = useMemo(() => withPropTexts(fillProps(written, { ...valueScopeOf(stack), params }), texts), [written, stack, params, texts])\n if (node.type === 'Trans' && !node.custom) return <>{renderInline(transChildren(node, texts).map((child) => ({ child })))}</>\n if (node.custom) {\n const Custom = components?.[node.type]\n // Field references reach the component as the names they reference; its children draw in the record its\n // `select` chose, and its declared reads reach it through useComponentReads\n const children = node.children.length > 0 ? <CustomChosen node={node}>{renderChildren(placed(node.children, at, 'children'))}</CustomChosen> : undefined\n return (\n <CustomOrFallback name={node.type} registered={Boolean(Custom)} fallback={node.fallback && <>{renderChildren(placed(node.fallback, at, 'fallback'))}</>}>\n {Custom && (\n <ComponentElement node={node} {...(at !== undefined && { at })}>\n <Custom {...unmarkFieldRefs(node.props)}>{children}</Custom>\n </ComponentElement>\n )}\n </CustomOrFallback>\n )\n }\n const Block = blocks[node.type]\n if (!Block) return <Problem>{text.rich('unknownBlock', { type: node.type })}</Problem>\n const className = typeof node.props.className === 'string' ? node.props.className : undefined\n const children = placed(node.children, at, 'children')\n // A Text and a Summary are one line, and a Link a piece of one: what they hold runs inline, in no paragraph of its own\n const block = (\n <Block node={node} at={at} slots={renderSlots(node, at)} className={className}>\n {node.type === 'Text' || node.type === 'Link' || node.type === 'Summary' ? renderInline(children) : renderChildren(node.type === 'Switch' ? children.filter(({ child }) => typeof child !== 'string') : children)}\n </Block>\n )\n const classed = className === undefined || ownClasses.has(node.type) ? block : <div className={className}>{block}</div>\n // A block with a fallback, such as a Graph's, draws it where the block cannot draw, as a custom component's does\n if (!node.fallback) return classed\n return (\n <CustomBoundary name={node.type} resetKey={node} fallback={<>{renderChildren(placed(node.fallback, at, 'fallback'))}</>}>\n {classed}\n </CustomBoundary>\n )\n\n}\n"],"file":"render-node-DGmdm-wr.js","debugId":"c699d9be-c2be-4f83-9894-b0a90e18756d"}
1
+ {"version":3,"mappings":";s4FASA,IAAMA,GAAa,CACjB,KAAM,UACN,KAAM,GACN,KAAM,CACJ,CAAC,SAAU,CAAE,GAAI,KAAM,GAAI,KAAM,EAAG,IAAK,IAAK,QAAS,CAAC,EACxD,CAAC,OAAQ,CAAE,EA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,UAAU,EAAAlB,EAAA,KAAAC,WAAA,UAAGs5B,GAAe70B,GAAOxD,EAAK,SAAUiB,EAAI,UAAU,CAAC,CAAI,GACnH,SAAA44B,CACa,GAJSA,CAO7B","names":["__iconData","AtSign","createLucideIcon","Bot","KeySquare","Laptop","PlugZap","ShieldUser","Smartphone","Tablet","toolCallStates","defineBlock","inlineFieldTypes","isInlineField","child","isInlineChild","isEmptyFieldValue","type","value","textFieldText","numberFieldText","number","locales","locale","options","dateFieldText","date","props","input","showDate","showTime","dateOptions","booleanFieldText","words","safeSchemes","safeFieldUrl","read","scheme","cardsLayoutOf","layout","cardWidth","keyText","byText","a","b","graphShape","byKey","groups","row","nodes","id","key","fields","group","linked","edges","parts","edgeKey","name","source","target","ListActionButton","useAdminMeta","runner","useActionRunner","model","titleOf","useRecordTitle","asking","setAsking","useState","action","views","entry","records","items","scopeOf","item","on","record","skipped","shown","text","label","run","values","import_jsx_runtime","_Fragment","Button","variant","asksFirst","ActionPrompt","isDanger","quoted","ActionButton","scope","useLayoutRecord","useRunAction","resource","onRun","ran","about","ActionBlock","propsOf","node","list","useLayoutList","CardBlock","CardFrame","slots","cn","className","RecordsEach","Fragment","planned","index","wrap","RecordScope","RecordsIteratorBlock","LoadedCardRow","usePlanned","at","own","useListPage","limit","page","rows","Skeleton","ErrorBanner","Quiet","empty","LayoutListScope","CardRowBlock","ChartBlock","_actions","_span","_className","chart","resources","ChartView","ChosenRecord","useFirstRecord","query","body","timeOf","ms","keyOf","share","span","from","groupOf","lanes","start","given","end","now","lane","bar","pack","bars","placed","timelineShape","grouped","times","time","to","barKey","segments","segment","withinBar","minute","hour","day","tickSteps","year","stepsIn","toOffset","step","fromOffset","axisTicks","offset","offsetOf","endOffset","candidate","ticks","local","barIdOf","barIn","shape","offsetAt","zone","part","anchor","left","TimelineAxis","dated","viewerZone","tick","daily","formatDayShort","formatTime","segmentPaint","striped","hints","declared","isBadgeTone","toneDots","colorOf","field","paintStyle","paint","SegmentFill","width","formatDate","formatDateTime","rangeText","open","segmentText","displayValue","view","barText","known","barLook","BarMark","useRelationTitle","point","style","choose","chosen","RouteLink","TimelineLanes","laneField","FieldValue","Swatch","TimelineLegend","TimelineReadout","pageSize","timelineRowsQuery","keys","filter","sort","pageToken","client","useTimelineRows","request","useQuery","useClient","keepPreviousData","LoadedTimeline","defaultTimelineLimit","hovered","setHovered","focused","setFocused","idOf","readSort","cut","details","barValue","SelectTimeline","usePageParams","select","barTo","linkTo","GuardedParams","groupFilter","TimelineBlock","_children","loaded","timelineReadSort","timelineSort","CustomChosen","selection","selectOf","params","usePageParamsIfAny","children","GraphView","lazy","module","loading","Spinner","GraphBlock","reads","useElementReads","useMemo","status","signature","error","param","Suspense","messages","MessageComposer","refresh","useRefreshResource","permissions","usePermissions","sending","setSending","failure","setFailure","can","Composer","sent","message","ComposerBlock","DetailsBlock","SummaryBlock","DiffBlock","useScopedPathValue","emptyText","files","parsePatch","DiffView","file","plainText","fieldLabel","viewLabel","path","humanize","FieldBlock","columns","statColumns","spans","isStat","GridBlock","count","childNodes","stats","element","FixedImage","alt","imageQuery","asked","space","height","imageRefetch","isPicture","answer","useObjectUrl","url","setUrl","import_react","blob","next","useBroken","broken","setBroken","FunctionImage","useTheme","ref","useElementWidth","picture","markBroken","size","ImageBlock","inlineField","show","labelled","enumLabel","TextFieldBlock","NumberFieldBlock","formatTag","DateFieldBlock","formatRelativeTime","BooleanFieldBlock","TrueMark","UrlFieldBlock","safe","ChipFieldBlock","ValueBadge","linkStyle","LinkBlock","valueScopeOf","useScopeStack","usePageParamValues","buttonClass","content","fillAddressFrom","scopeLookup","AppLink","appPath","href","startingDraft","stored","toDraft","fallback","editBody","draft","isChosen","differs","toPatchValue","ModalFormDialog","toast","useToast","setDraft","errors","setErrors","rejections","setRejections","formRef","useFocusFirstInvalid","saving","setSaving","touched","setTouched","useNavigationGuard","submit","mode","createBody","title","onClose","found","fieldErrors","Dialog","event","problem","Field","fieldMessage","FieldEditor","_","rest","current","KeyedRecord","recordKey","ModalFormBlock","setOpen","button","PageBlock","PageHeader","description","useAmount","stack","amount","frameFor","usePathValue","ProgressBlock","total","max","LoadedRecordCard","plannedRecord","scoped","actions","RecordCardBlock","Clamped","useRef","taller","setTaller","box","measure","observer","isEmpty","RelatedField","clamped","CompactCard","buttons","tone","ToneEdge","RowButtonLink","onActed","RelatedCard","enabled","control","firstControl","card","nextFocus","before","gone","stays","after","headingOf","heading","root","useLeavingFocus","pending","announcement","setAnnouncement","settle","acted","previous","CardsSkeleton","compact","RelatedCards","xs","useIsXs","scroll","useSnapScroll","plural","orderBy","defaultOrderBy","ownCount","useCount","plannedCount","scopes","leaving","cards","note","cutOffNote","carousel","SnapRow","viewAllAddress","embeddedDisplay","display","listText","ArrowRight","shares","RecordCardsBlock","usePlannedReads","SectionContent","listColumnNames","cardActions","SavedRecordRow","listed","listedResource","saved","useSavedRecords","savedScope","RecordRowBody","SearchRowItem","encodeKey","useSearchRow","InlineFilterChips","SavedSearchRows","of","useSavedSearches","RecordRowBlock","savesAtOnce","SettingsForm","setStored","queue","latest","defaults","writable","typed","unsaved","write","changes","created","save","change","LoadedSettings","SettingsBlock","useConditions","useStackConditions","whens","parsed","parseCondition","isField","frame","paths","condition","counted","countedResource","fieldPaths","countedModels","sources","usePathValues","counts","useQueries","countQuery","evaluateCondition","fallbackOf","ShowBlock","when","drawn","matchConditions","fillProps","SwitchBlock","held","holds","MatchBlock","big","Count","filteredListAddress","RecordValue","StatBlock","useEmbeddedDisplay","embeddedDisplayKey","place","picked","setPicked","readPickedDisplay","pick","useCallback","writePickedDisplay","LoadedListTable","fieldTypes","useProjectUi","canUpdate","useAppAddress","narrow","useIsDesktop","names","columnName","all","embeddedColumns","specs","phoneSpecs","gridColumns","withRowButton","recordId","targets","embeddedRowTargets","go","DataGrid","ListTable","LoadedTable","tableDisplay","phoneColumns","EmbeddedDisplaySwitch","EmbeddedList","TableBlock","SelectTable","rowTo","TabsBlock","named","usePageTabsRoute","useRouter","tabs","tabsOf","shownPageTab","pathOf","navigate","tab","Link","Problem","TabBlock","mergeByTime","oldest","cutoff","first","second","merged","MessageStatus","mark","Check","valueTone","CircleAlert","Value","jsonOf","notJson","CodeBlock","JsonBlock","Part","ToolCallItem","useId","call","statusHints","opens","ChevronRight","messageRows","authorOf","threadItems","newestFirst","sameDay","sameChatDay","chatDayLabel","author","sender","state","stateOf","textOf","callKey","toolCallOf","result","threadListOf","reading","expanded","plannedList","expand","useThreadList","setExpanded","useList","pages","hasNextPage","isFetchingNextPage","fetchNextPage","useToolCalls","calls","threadSort","threadState","emptyLine","lines","showsErrorAbove","retryOf","loadEarlier","each","lists","MessageThread","auth","useOptionalAuth","reader","senders","labels","listLabels","callList","withLabels","markdown","isMarkdown","ChatThread","ChatDivider","ChatMessage","Markdown","ThreadBox","ThreadBlock","busy","working","plannedCalls","callsModel","BoxBlock","RowBlock","ColumnBlock","TextBlock","Tag","ArrayFieldBlock","scopeValue","SelectInputBlock","choices","MenuSelect","choice","defaultValue","relatedListOf","perPage","loadMore","more","useRelatedList","ReferenceManyFieldBlock","lookup","RelatedList","referenceManyRead","ListBody","ReferenceArrayFieldBlock","referenceArrayRead","LoadedReference","recordTitle","link","ReferenceFieldBlock","reference","roleNames","roleLabel","roles","AppInvitations","useAuth","selected","setSelected","invitations","setInvitations","load","session","InviteForm","AppRolesPicker","role","AccountSection","PendingInvitationRow","invitation","CreateUserForm","email","setEmail","setName","password","setPassword","useAction","create","onCreated","incomplete","SectionError","Input","UserRow","initial","user","setUser","setRoles","setError","setBlocked","blocked","PersonRow","Badge","self","UserList","setQuery","search","term","version","usePagedSearch","selfId","PagedSearchList","useUserRoles","AuthError","authMessage","UsersBlock","setVersion","MailSenderDialog","address","setAddress","setSignature","isDefault","setDefault","onSave","Switch","Textarea","detailsOf","MailSendersSection","setBusy","editing","setEditing","inFlight","close","attempt","onUpdate","added","onAdd","Plus","onRemove","signInOnlyNotes","mailboxOffers","links","offer","mailboxText","providerNames","Mailboxes","linkError","takeLinkError","mail","providers","account","useAccountData","data","SignInProvidersSection","signInProviders","provider","providerName","linkPersonalMail","providerMessage","reload","AccountLoading","PersonalMailBlock","personalMail","nameOf","clientName","app","accessOf","organization","ConnectedAppsSection","disconnecting","setDisconnecting","disconnect","onDisconnect","apps","publisher","clientPublisher","connectorDialogUrl","dialog","appName","McpAddressSection","CopyField","ExternalLink","Apps","clientId","Mcp","ConnectedAppsBlock","mcp","lifetimes","lifetimeLabels","dateOf","iso","expiryOf","expiresAt","token","PersonalAccessTokensSection","lifetime","setLifetime","confirming","setConfirming","days","onCreate","tokens","Select","option","ConfirmSignIn","onRevoke","Tokens","PersonalAccessTokensBlock","disconnected","wholeGrant","connection","ConnectionsSection","returned","setChosen","notice","setNotice","work","SectionNotice","connections","onConnect","RecordLink","workflow","ConnectionsBlock","connectAccount","deletionMessage","DeleteAccountDialog","formId","confirm","onDelete","hasPassword","DeleteAccountSection","staff","DeleteAccountBlock","methods","deleteAccount","browsers","systems","find","pattern","userAgent","deviceOf","linkName","operator","browser","system","iconOf","ordered","sessions","what","descriptionOf","DevicesSection","others","onSignOut","onSignOutLink","onSignOutOthers","signOut","Icon","DevicesBlock","deviceLinks","staffSignIn","descriptions","PasskeysSection","keepLast","rule","passkeys","KeyRound","passkey","onRename","PasskeysBlock","passwordMessage","draftProblem","repeat","PasswordChangeDialog","setCurrent","setNext","setRepeat","filled","PasswordSection","setSaved","canEdit","onChange","onSet","PasswordBlock","ChangeEmailDialog","sentTo","setSentTo","code","setCode","newEmail","send","complete","onDone","OtpInput","ProfileSection","changingEmail","setChangingEmail","rename","emailChange","onEmailChanged","ProfileBlock","changeEmail","PasswordDialog","onConfirm","needsPassword","danger","confirmLabel","offDescriptions","TwoFactorSection","authenticatorApp","TwoFactorSetup","onChanged","onTurnOff","onNewBackupCodes","BackupCodes","TwoFactorBlock","Replacement","CustomOrFallback","registered","CustomBoundary","blocks","ConnectedAccountsBlock","ownClasses","steps","pointerOf","FilledText","fillText","valueText","textChild","renderInline","position","RenderNode","renderChildren","runs","last","isElements","isLayoutNode","renderSlots","slotted","isObject","transChildren","components","tags","tag","chunks","formatted","formatMessage","texts","written","useAppTexts","withPropTexts","Custom","ComponentElement","unmarkFieldRefs","Block","block","classed"],"ignoreList":[0,1,2,3,4,5,6,7],"sources":["../../../../../node_modules/.bun/lucide-react@1.52.0+0ac650c021fb1b59/node_modules/lucide-react/dist/esm/icons/at-sign.mjs","../../../../../node_modules/.bun/lucide-react@1.52.0+0ac650c021fb1b59/node_modules/lucide-react/dist/esm/icons/bot.mjs","../../../../../node_modules/.bun/lucide-react@1.52.0+0ac650c021fb1b59/node_modules/lucide-react/dist/esm/icons/key-square.mjs","../../../../../node_modules/.bun/lucide-react@1.52.0+0ac650c021fb1b59/node_modules/lucide-react/dist/esm/icons/laptop.mjs","../../../../../node_modules/.bun/lucide-react@1.52.0+0ac650c021fb1b59/node_modules/lucide-react/dist/esm/icons/plug-zap.mjs","../../../../../node_modules/.bun/lucide-react@1.52.0+0ac650c021fb1b59/node_modules/lucide-react/dist/esm/icons/shield-user.mjs","../../../../../node_modules/.bun/lucide-react@1.52.0+0ac650c021fb1b59/node_modules/lucide-react/dist/esm/icons/smartphone.mjs","../../../../../node_modules/.bun/lucide-react@1.52.0+0ac650c021fb1b59/node_modules/lucide-react/dist/esm/icons/tablet.mjs","../../../../layout/src/check-tool-calls.ts","../../../../layout/src/inline-fields.ts","../../../../layout/src/field-format.ts","../../../../layout/src/cards-layout.ts","../../../../layout/src/graph-shape.ts","../../../src/app/pages/blocks/list-action.tsx","../../../src/app/pages/blocks/action.tsx","../../../src/app/pages/blocks/card.tsx","../../../src/app/pages/blocks/records-iterator.tsx","../../../src/app/pages/blocks/card-row.tsx","../../../src/app/pages/blocks/chart.tsx","../../../src/app/pages/blocks/chosen-record.tsx","../../../src/app/pages/blocks/timeline/timeline-layout.ts","../../../src/app/pages/blocks/timeline/bar-identity.ts","../../../src/app/pages/blocks/timeline/timeline-axis.tsx","../../../src/app/pages/blocks/timeline/timeline-paint.ts","../../../src/app/pages/blocks/timeline/segment-fill.tsx","../../../src/app/pages/blocks/timeline/timeline-text.ts","../../../src/app/pages/blocks/timeline/timeline-lanes.tsx","../../../src/app/pages/blocks/timeline/timeline-readout.tsx","../../../src/app/pages/blocks/timeline/use-timeline-rows.ts","../../../src/app/pages/blocks/timeline/timeline.tsx","../../../src/app/pages/custom-chosen.tsx","../../../src/app/pages/blocks/graph/graph-block.tsx","../../../src/app/conversation/messages.ts","../../../src/app/conversation/message-composer.tsx","../../../src/app/pages/blocks/composer.tsx","../../../src/app/pages/blocks/details.tsx","../../../src/app/pages/blocks/diff.tsx","../../../src/app/pages/blocks/plain-value.ts","../../../src/app/pages/blocks/field.tsx","../../../src/app/pages/blocks/grid.tsx","../../../src/app/pages/blocks/fixed-image.tsx","../../../src/app/pages/blocks/image-query.ts","../../../src/app/pages/blocks/image.tsx","../../../src/app/pages/blocks/inline-field.tsx","../../../src/app/pages/blocks/link.tsx","../../../src/app/pages/blocks/form-draft.ts","../../../src/app/pages/blocks/modal-form.tsx","../../../src/app/pages/blocks/page-block.tsx","../../../src/app/pages/blocks/progress.tsx","../../../src/app/pages/blocks/record-card.tsx","../../../src/app/related-cards/messages.ts","../../../src/app/related-cards/clamped.tsx","../../../src/app/related-cards/related-field.tsx","../../../src/app/related-cards/compact-card.tsx","../../../src/app/related-cards/related-card.tsx","../../../src/app/related-cards/first-control.ts","../../../src/app/related-cards/next-focus.ts","../../../src/app/related-cards/use-leaving-focus.ts","../../../src/app/related-cards/related-cards.tsx","../../../src/app/pages/blocks/record-cards.tsx","../../../src/app/record-row/saved-record-row.tsx","../../../src/app/searches/saved-search-rows.tsx","../../../src/app/pages/blocks/record-row.tsx","../../../src/app/pages/blocks/settings.tsx","../../../src/app/pages/use-conditions.ts","../../../src/app/pages/blocks/show.tsx","../../../src/app/pages/blocks/switch.tsx","../../../src/app/pages/blocks/stat.tsx","../../../src/app/embedded-list/use-embedded-display.ts","../../../src/app/pages/blocks/list-table.tsx","../../../src/app/pages/blocks/table.tsx","../../../src/app/pages/blocks/tabs.tsx","../../../src/app/conversation/merge-by-time.ts","../../../src/app/conversation/message-status.tsx","../../../src/app/conversation/tool-call-item.tsx","../../../src/app/conversation/thread-items.ts","../../../src/app/conversation/tool-calls.ts","../../../src/app/conversation/planned-thread-list.ts","../../../src/app/conversation/use-thread-list.ts","../../../src/app/conversation/use-tool-calls.ts","../../../src/app/conversation/thread-state.ts","../../../src/app/conversation/message-thread.tsx","../../../src/app/conversation/thread-box.tsx","../../../src/app/pages/blocks/thread.tsx","../../../src/app/pages/blocks/plain.tsx","../../../src/app/pages/blocks/array-field.tsx","../../../src/app/pages/blocks/select-input.tsx","../../../src/app/pages/related-list-of.ts","../../../src/app/pages/use-related-list.ts","../../../src/app/pages/blocks/reference-many-field.tsx","../../../src/app/pages/blocks/reference-array-field.tsx","../../../src/app/pages/blocks/reference-field.tsx","../../../src/users/role-names.ts","../../../src/users/messages.ts","../../../src/users/app-invitations.tsx","../../../src/users/create-user-form.tsx","../../../src/users/user-row.tsx","../../../src/users/user-list.tsx","../../../src/users/use-user-roles.ts","../../../src/users/users-block.tsx","../../../src/account/mail-sender-dialog.tsx","../../../src/account/mail-senders-section.tsx","../../../src/account/blocks/personal-mail-block.tsx","../../../src/account/connected-apps-section.tsx","../../../src/account/connector-dialog.ts","../../../src/account/mcp-address-section.tsx","../../../src/account/blocks/connected-apps-block.tsx","../../../src/account/personal-access-tokens-section.tsx","../../../src/account/blocks/personal-access-tokens-block.tsx","../../../src/account/connections-section.tsx","../../../src/account/blocks/connections-block.tsx","../../../src/account/delete-account-dialog.tsx","../../../src/account/delete-account-section.tsx","../../../src/account/blocks/delete-account-block.tsx","../../../src/account/device-name.ts","../../../src/account/devices-section.tsx","../../../src/account/blocks/devices-block.tsx","../../../src/account/passkeys-section.tsx","../../../src/account/blocks/passkeys-block.tsx","../../../src/account/password-change-dialog.tsx","../../../src/account/password-section.tsx","../../../src/account/blocks/password-block.tsx","../../../src/account/change-email-dialog.tsx","../../../src/account/profile-section.tsx","../../../src/account/blocks/profile-block.tsx","../../../src/account/password-dialog.tsx","../../../src/account/two-factor-section.tsx","../../../src/account/blocks/two-factor-block.tsx","../../../src/app/pages/custom-or-fallback.tsx","../../../src/app/pages/render-node.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: \"at-sign\",\n size: 24,\n node: [\n [\"circle\", { cx: \"12\", cy: \"12\", r: \"4\", key: \"4exip2\" }],\n [\"path\", { d: \"M16 8v5a3 3 0 0 0 6 0v-1a10 10 0 1 0-4 8\", key: \"7n84p3\" }]\n ]\n};\n__iconData.node;\nconst AtSign = createLucideIcon(__iconData);\n\nexport { __iconData, AtSign as default };\n//# sourceMappingURL=at-sign.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: \"bot\",\n size: 24,\n node: [\n [\"path\", { d: \"M12 8V4H8\", key: \"hb8ula\" }],\n [\"rect\", { width: \"16\", height: \"12\", x: \"4\", y: \"8\", rx: \"2\", key: \"enze0r\" }],\n [\"path\", { d: \"M2 14h2\", key: \"vft8re\" }],\n [\"path\", { d: \"M20 14h2\", key: \"4cs60a\" }],\n [\"path\", { d: \"M15 13v2\", key: \"1xurst\" }],\n [\"path\", { d: \"M9 13v2\", key: \"rq6x2g\" }]\n ]\n};\n__iconData.node;\nconst Bot = createLucideIcon(__iconData);\n\nexport { __iconData, Bot as default };\n//# sourceMappingURL=bot.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: \"key-square\",\n size: 24,\n node: [\n [\n \"path\",\n {\n d: \"M12.4 2.7a2.5 2.5 0 0 1 3.4 0l5.5 5.5a2.5 2.5 0 0 1 0 3.4l-3.7 3.7a2.5 2.5 0 0 1-3.4 0L8.7 9.8a2.5 2.5 0 0 1 0-3.4z\",\n key: \"165ttr\"\n }\n ],\n [\"path\", { d: \"m14 7 3 3\", key: \"1r5n42\" }],\n [\n \"path\",\n {\n d: \"m9.4 10.6-6.814 6.814A2 2 0 0 0 2 18.828V21a1 1 0 0 0 1 1h3a1 1 0 0 0 1-1v-1a1 1 0 0 1 1-1h1a1 1 0 0 0 1-1v-1a1 1 0 0 1 1-1h.172a2 2 0 0 0 1.414-.586l.814-.814\",\n key: \"1ubxi2\"\n }\n ]\n ]\n};\n__iconData.node;\nconst KeySquare = createLucideIcon(__iconData);\n\nexport { __iconData, KeySquare as default };\n//# sourceMappingURL=key-square.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: \"laptop\",\n size: 24,\n node: [\n [\n \"path\",\n {\n d: \"M18 5a2 2 0 0 1 2 2v8.526a2 2 0 0 0 .212.897l1.068 2.127a1 1 0 0 1-.9 1.45H3.62a1 1 0 0 1-.9-1.45l1.068-2.127A2 2 0 0 0 4 15.526V7a2 2 0 0 1 2-2z\",\n key: \"1pdavp\"\n }\n ],\n [\"path\", { d: \"M20.054 15.987H3.946\", key: \"14rxg9\" }]\n ]\n};\n__iconData.node;\nconst Laptop = createLucideIcon(__iconData);\n\nexport { __iconData, Laptop as default };\n//# sourceMappingURL=laptop.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: \"plug-zap\",\n size: 24,\n node: [\n [\n \"path\",\n { d: \"M6.3 20.3a2.4 2.4 0 0 0 3.4 0L12 18l-6-6-2.3 2.3a2.4 2.4 0 0 0 0 3.4Z\", key: \"goz73y\" }\n ],\n [\"path\", { d: \"m2 22 3-3\", key: \"19mgm9\" }],\n [\"path\", { d: \"M7.5 13.5 10 11\", key: \"7xgeeb\" }],\n [\"path\", { d: \"M10.5 16.5 13 14\", key: \"10btkg\" }],\n [\"path\", { d: \"m18 3-4 4h6l-4 4\", key: \"16psg9\" }]\n ],\n aliases: [\"plug-zap-2\"]\n};\n__iconData.node;\nconst PlugZap = createLucideIcon(__iconData);\n\nexport { __iconData, PlugZap as default };\n//# sourceMappingURL=plug-zap.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: \"shield-user\",\n size: 24,\n node: [\n [\n \"path\",\n {\n d: \"M20 13c0 5-3.5 7.5-7.66 8.95a1 1 0 0 1-.67-.01C7.5 20.5 4 18 4 13V6a1 1 0 0 1 1-1c2 0 4.5-1.2 6.24-2.72a1.17 1.17 0 0 1 1.52 0C14.51 3.81 17 5 19 5a1 1 0 0 1 1 1z\",\n key: \"oel41y\"\n }\n ],\n [\"path\", { d: \"M6.376 18.91a6 6 0 0 1 11.249.003\", key: \"hnjrf2\" }],\n [\"circle\", { cx: \"12\", cy: \"11\", r: \"4\", key: \"1gt34v\" }]\n ]\n};\n__iconData.node;\nconst ShieldUser = createLucideIcon(__iconData);\n\nexport { __iconData, ShieldUser as default };\n//# sourceMappingURL=shield-user.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: \"smartphone\",\n size: 24,\n node: [\n [\"rect\", { width: \"14\", height: \"20\", x: \"5\", y: \"2\", rx: \"2\", ry: \"2\", key: \"1yt0o3\" }],\n [\"path\", { d: \"M12 18h.01\", key: \"mhygvu\" }]\n ]\n};\n__iconData.node;\nconst Smartphone = createLucideIcon(__iconData);\n\nexport { __iconData, Smartphone as default };\n//# sourceMappingURL=smartphone.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: \"tablet\",\n size: 24,\n node: [\n [\"rect\", { width: \"16\", height: \"20\", x: \"4\", y: \"2\", rx: \"2\", ry: \"2\", key: \"76otgf\" }],\n [\"line\", { x1: \"12\", x2: \"12.01\", y1: \"18\", y2: \"18\", key: \"1dp563\" }]\n ]\n};\n__iconData.node;\nconst Tablet = createLucideIcon(__iconData);\n\nexport { __iconData, Tablet as default };\n//# sourceMappingURL=tablet.mjs.map\n","import type { ResourceModel, ToolCallFields } from '@protobase/schema'\nimport { choiceFilterProblems } from './check-param-filters'\nimport { pathFindings, type PathCheckInput } from './check-paths'\nimport { timeProblems } from './check-time'\nimport type { SelectInputProps } from './page-params'\nimport { sampledFilterErrors } from './sampled-filter'\nimport type { Scope } from './walk'\n\n/** The tool calls a thread draws between its messages: records of `resource`, by the fields it reads of each, narrowed by `filter` on a page. */\nexport type ToolCallSource = ToolCallFields & { resource: string; filter?: string }\n\n/** The values of a tool call's `status` that give it a mark; any other value, or none, draws no mark. */\nexport const toolCallStates = ['done', 'error', 'running'] as const\n\nexport type ToolCallState = (typeof toolCallStates)[number]\n\nconst required = ['name', 'time', 'status'] as const\nconst shown = ['input', 'result', 'error'] as const\n\nconst fieldOf = (model: ResourceModel, name: string) => (Object.hasOwn(model.fields, name) ? model.fields[name] : undefined)\n\n/** The fields of `source` that name a field, the ones each call needs first. */\nconst namedFields = (source: ToolCallSource) => [...required, ...shown].flatMap((prop) => (source[prop] === undefined ? [] : [[prop, source[prop]] as const]))\n\n// The name and the error read as text, the status as one of the states; the input and result show as JSON whatever their type\nconst typeProblems = (source: ToolCallSource, model: ResourceModel): string[] => {\n const name = fieldOf(model, source.name)!\n const status = fieldOf(model, source.status)!\n const error = source.error === undefined ? undefined : fieldOf(model, source.error)!\n return [\n ...(name.type === 'text' ? [] : [`name: \"${source.name}\" is ${name.type}; a tool call's name is a text field`]),\n ...(['text', 'enum'].includes(status.type) ? [] : [`status: \"${source.status}\" is ${status.type}; a tool call's status is a text or enum field`]),\n ...(error === undefined || error.type === 'text' ? [] : [`error: \"${source.error}\" is ${error.type}; a tool call's error is a text field`]),\n ]\n}\n\n/** Where on a page a thread sits: the records around it, its page parameters and their inputs, and where a warning goes. */\nexport type ToolCallsPage = PathCheckInput & { scope: Scope; inputs: ReadonlyMap<string, SelectInputProps>; warn: (warning: string) => void }\n\nconst sampledProblems = (filter: string, model: ResourceModel) => {\n const errors = sampledFilterErrors(model, filter)\n return errors.length === 0 ? [] : [`filter: ${errors.join('; ')}`]\n}\n\n// A filter is checked as a block's own filter is: its `{{path}}` slots through the records around the thread, then with\n// each value of the page parameters it reads, or else with a stand-in for each slot, such as `task_id = {{@root.id}}`\nconst filterProblems = (filter: string | undefined, model: ResourceModel, page: ToolCallsPage | undefined): string[] => {\n if (filter === undefined) return []\n if (!page) return sampledProblems(filter, model)\n const placed = pathFindings({ type: 'Thread', props: { filter }, children: [] }, page.scope, page)\n placed.warnings.forEach(page.warn)\n return [...placed.problems, ...(choiceFilterProblems(model, filter, page.inputs) ?? sampledProblems(filter, model))]\n}\n\n/**\n * What a thread's tool calls name that their resource does not have, cannot order them by, or cannot show as their\n * name, status or error; on a `page`, also what their filter reads that the records around the thread do not have.\n */\nexport const toolCallsProblems = (source: ToolCallSource, models: Record<string, ResourceModel>, page?: ToolCallsPage): string[] => {\n const model = Object.hasOwn(models, source.resource) ? models[source.resource] : undefined\n if (!model) return [`unknown resource \"${source.resource}\"`]\n const unknown = namedFields(source).flatMap(([prop, name]) => (fieldOf(model, name) ? [] : [`${prop}: unknown field \"${name}\" on ${model.name}`]))\n if (unknown.length > 0) return unknown\n return [...timeProblems(source.time, model, 'tool calls'), ...typeProblems(source, model), ...filterProblems(source.filter, model, page)]\n}\n\n/**\n * A thread's tool calls as a caller may see them: gone when they cannot read the calls or the name, time and status of\n * each, and without the input, result or error they cannot read.\n */\nexport const pruneToolCalls = <S extends ToolCallSource>(source: S, models: Record<string, ResourceModel>): S | undefined => {\n const { input, result, error, ...core } = source\n if (toolCallsProblems(core, models).length > 0) return\n const model = models[source.resource]!\n const keeps = (name: string | undefined) => name !== undefined && fieldOf(model, name) !== undefined\n return { ...core, ...(keeps(input) && { input }), ...(keeps(result) && { result }), ...(keeps(error) && { error }) } as S\n}\n","import { defineBlock } from './create-node'\nimport type { Styled } from './blocks'\nimport type { LayoutChild } from './node'\n\n// React-admin's field components (https://marmelab.com/react-admin/Fields.html): one value of the record around them,\n// read by `source` and drawn inline, so they sit in a `Text`, a `Link` or a `Summary` like a word of the sentence.\n\n/** What every field component takes, as react-admin's `FieldProps`: the path of its value, and the text shown when it has none. */\nexport type InlineFieldProps = Styled & {\n /** A field of the records around it, looked up as `{{path}}` is: `title`, `plan.name`, `../title`. */\n source: string\n /** Shown when the value is empty; nothing is shown without it. */\n emptyText?: string\n}\n\n/** Intl options, as `Intl.NumberFormat` or `Intl.DateTimeFormat` take them: names to strings, numbers and booleans. */\nexport type IntlOptions = Record<string, string | number | boolean>\n\n/** The value as text. https://marmelab.com/react-admin/TextField.html */\nexport type TextFieldProps = InlineFieldProps\n/** A number in the reader's locale, or `locales`, formatted by `Intl.NumberFormat` with `options`. https://marmelab.com/react-admin/NumberField.html */\nexport type NumberFieldProps = InlineFieldProps & { locales?: string | string[]; options?: IntlOptions }\n/**\n * A date, a time or both in the reader's locale, or `locales`, formatted by `Intl.DateTimeFormat` with `options`.\n * `format=\"relative\"`, which react-admin does not have, shows how long ago or ahead it is, such as \"3 hours ago\".\n * https://marmelab.com/react-admin/DateField.html\n */\nexport type DateFieldProps = InlineFieldProps & { showDate?: boolean; showTime?: boolean; locales?: string | string[]; options?: IntlOptions; format?: 'relative' }\n/** A mark for true and for false, with `valueLabelTrue` and `valueLabelFalse` as its words. https://marmelab.com/react-admin/BooleanField.html */\nexport type BooleanFieldProps = InlineFieldProps & { valueLabelTrue?: string; valueLabelFalse?: string }\n/** A link to the address the value holds, showing `content` or the address. https://marmelab.com/react-admin/UrlField.html */\nexport type UrlFieldProps = InlineFieldProps & { content?: string }\n/** The value as a chip. https://marmelab.com/react-admin/ChipField.html */\nexport type ChipFieldProps = InlineFieldProps\n\nexport const TextField = defineBlock<TextFieldProps>('TextField', false)\nexport const NumberField = defineBlock<NumberFieldProps>('NumberField', false)\nexport const DateField = defineBlock<DateFieldProps>('DateField', false)\nexport const BooleanField = defineBlock<BooleanFieldProps>('BooleanField', false)\nexport const UrlField = defineBlock<UrlFieldProps>('UrlField', false)\nexport const ChipField = defineBlock<ChipFieldProps>('ChipField', false)\n\n/** The field components' block types. */\nexport const inlineFieldTypes: ReadonlySet<string> = new Set(['TextField', 'NumberField', 'DateField', 'BooleanField', 'UrlField', 'ChipField'])\n\nexport const isInlineField = (child: LayoutChild) => typeof child !== 'string' && !child.custom && inlineFieldTypes.has(child.type)\n\n/** What runs on in a line of text: text, links, a `Text as=\"span\"` and the field components. */\nexport const isInlineChild = (child: LayoutChild) => typeof child === 'string' || isInlineField(child) || (!child.custom && (child.type === 'Link' || child.type === 'Trans' || (child.type === 'Text' && ['span', 'strong', 'em'].includes(String(child.props.as)))))\n","import type { BooleanFieldProps, DateFieldProps, NumberFieldProps } from './inline-fields'\n\n// How the field components turn a value into text, as react-admin's do (packages/ra-ui-materialui/src/field), shared\n// by the web and the text form so both read the same.\n\n/** Whether a field component shows its `emptyText` for `value`: as react-admin tests it, per component. */\nexport const isEmptyFieldValue = (type: string, value: unknown) => {\n if (type === 'BooleanField') return value !== true && value !== false\n if (type === 'NumberField' || type === 'UrlField') return value === null || value === undefined\n return value === null || value === undefined || value === ''\n}\n\n/** A value as `TextField` shows it: text as it is, anything else as its string; an object as JSON. */\nexport const textFieldText = (value: unknown) => (typeof value === 'object' && value !== null ? JSON.stringify(value) : String(value))\n\n/** A number as `NumberField` shows it, a numeric string read as its number first. */\nexport const numberFieldText = (value: unknown, { locales, options }: Pick<NumberFieldProps, 'locales' | 'options'>, locale?: string) => {\n const number = typeof value === 'string' && value !== '' && !Number.isNaN(Number(value)) ? Number(value) : value\n return typeof number === 'number' ? number.toLocaleString(locales ?? locale, options) : String(number)\n}\n\nexport type DateTextInput = {\n /** The reader's locale, used where the component names no `locales`; the runtime's default when omitted. */\n locale?: string\n /** Now, in milliseconds, which `format=\"relative\"` counts from. */\n now: number\n /** How long ago a moment was, in seconds (negative for one to come), as the client words it. */\n relative: (seconds: number) => string\n}\n\n/** A date as `DateField` shows it: a date-only value such as `2026-02-15` in UTC, so no time zone moves its day. */\nexport const dateFieldText = (value: unknown, props: Pick<DateFieldProps, 'showDate' | 'showTime' | 'locales' | 'options' | 'format'>, input: DateTextInput) => {\n const date = value instanceof Date ? value : typeof value === 'string' || typeof value === 'number' ? new Date(value) : undefined\n // An unparseable value, such as `'soon'`, gives an invalid date, which no formatter takes\n if (!date || Number.isNaN(date.getTime())) return ''\n if (props.format === 'relative') return input.relative(Math.round((input.now - date.getTime()) / 1000))\n const { showDate = true, showTime = false, options } = props\n const locales = props.locales ?? input.locale\n if (showDate && showTime) return date.toLocaleString(locales, options)\n if (showTime) return date.toLocaleTimeString(locales, options)\n const dateOptions = options ?? (typeof value === 'string' && value.length <= 10 ? { timeZone: 'UTC' } : undefined)\n return date.toLocaleDateString(locales, dateOptions)\n}\n\n/** The word for a boolean, as `BooleanField` labels its mark: `valueLabelTrue` or `valueLabelFalse`, else the client's yes or no. */\nexport const booleanFieldText = (value: boolean, props: Pick<BooleanFieldProps, 'valueLabelTrue' | 'valueLabelFalse'>, words: { yes: string; no: string }) =>\n value ? (props.valueLabelTrue ?? words.yes) : (props.valueLabelFalse ?? words.no)\n\n// The schemes a link may follow; another, such as javascript: or data:, could run code, so its address shows as text.\nconst safeSchemes = new Set(['http:', 'https:', 'mailto:', 'tel:'])\n\n/**\n * The address `UrlField` links to: one with an `http:`, `https:`, `mailto:` or `tel:` scheme, or a path on the app's\n * own origin; `undefined` for any other, which then shows as text.\n */\nexport const safeFieldUrl = (value: string): string | undefined => {\n // Browsers drop leading control characters and spaces, and tabs and newlines anywhere, before reading the scheme\n // eslint-disable-next-line no-control-regex\n const read = value.replace(/^[\\u0000- ]+/, '').replace(/[\\t\\n\\r]/g, '')\n const scheme = /^([A-Za-z][A-Za-z0-9+.-]*):/.exec(read)?.[1]\n if (scheme === undefined) return read.startsWith('/') || !read.includes(':') ? value : undefined\n return safeSchemes.has(`${scheme.toLowerCase()}:`) ? value : undefined\n}\n","import type { CardsLayout, CardWidth, RecordCardsProps } from './blocks'\n\n/** How a `RecordCards` lays out its cards, its props' defaults filled in: stacked, and two thirds wide in a carousel. */\nexport const cardsLayoutOf = ({ layout, cardWidth }: Pick<RecordCardsProps, 'layout' | 'cardWidth'>): { layout: CardsLayout; cardWidth: CardWidth } => ({\n layout: layout ?? 'stack',\n cardWidth: cardWidth ?? '2/3',\n})\n","type Row = Record<string, unknown>\n\n/** The fields a graph reads: a node's `label`, `group` and `status`, and the node keys an edge's `source` and `target` hold. */\nexport type GraphFields = { label: string; group?: string; status?: string; source: string; target: string }\n\nexport type ShapeNode = { id: string; row: Row; group?: string }\nexport type ShapeGroup = { id: string; value: unknown }\nexport type ShapeEdge = { id: string; source: string; target: string; row: Row }\n\n/** What a graph shows: its groups, its nodes, each in its group, and the edges between them, each in one fixed order. */\nexport type GraphShape = { groups: ShapeGroup[]; nodes: ShapeNode[]; edges: ShapeEdge[] }\n\nconst keyText = (value: unknown) => (value === null || value === undefined || value === '' ? undefined : String(value))\n\nconst byText = (a: string, b: string) => (a < b ? -1 : a > b ? 1 : 0)\n\n/**\n * The graph `nodes` and `edges` make: a node per record by its `key` field, an edge by its `edgeKey` fields, in the group its `group` value names, and\n * an edge per record whose `source` and `target` are both among the nodes; one pointing elsewhere is left out. Groups,\n * nodes and edges are each sorted by key, so the same records make the same graph whatever order they come in.\n */\nexport const graphShape = ({ nodes, edges, key, edgeKey, fields }: { nodes: Row[]; edges: Row[]; key: string; edgeKey: readonly string[]; fields: GraphFields }): GraphShape => {\n const byKey = new Map<string, ShapeNode>()\n const groups = new Map<string, ShapeGroup>()\n for (const row of nodes) {\n const id = keyText(row[key])\n if (id === undefined || byKey.has(id)) continue\n const value = fields.group === undefined ? undefined : row[fields.group]\n const group = keyText(value)\n if (group !== undefined && !groups.has(group)) groups.set(group, { id: group, value })\n byKey.set(id, { id, row, ...(group !== undefined && { group }) })\n }\n const linked = edges.flatMap((row) => {\n const parts = edgeKey.map((name) => keyText(row[name]))\n // A JSON list keeps the parts apart, so `['a,b', 'c']` and `['a', 'b,c']` stay two edges\n const id = parts.includes(undefined) ? undefined : parts.length === 1 ? parts[0] : JSON.stringify(parts)\n const source = keyText(row[fields.source])\n const target = keyText(row[fields.target])\n if (id === undefined || source === undefined || target === undefined || !byKey.has(source) || !byKey.has(target)) return []\n return [{ id, source, target, row }]\n })\n return {\n groups: [...groups.values()].sort((a, b) => byText(a.id, b.id)),\n nodes: [...byKey.values()].sort((a, b) => byText(a.id, b.id)),\n edges: linked.sort((a, b) => byText(a.source, b.source) || byText(a.target, b.target) || byText(a.id, b.id)),\n }\n}\n","import { useState } from 'react'\nimport type { ActionProps } from '@protobase/layout'\nimport type { ResourceModel } from '@protobase/schema'\nimport { Button } from '../../../primitives/button'\nimport { text } from '../../list-messages'\nimport { useAdminMeta } from '../../meta-gate'\nimport { useRecordTitle } from '../../titles/record-titles'\nimport { ActionPrompt, asksFirst, isDanger } from '../action-prompt'\nimport { scopeOf } from '../use-layout-data'\nimport { quoted, useActionRunner } from '../use-run-action'\n\ntype ListActionProps = Omit<ActionProps, 'resource'> & { model: ResourceModel; items: readonly unknown[]; className?: string }\n\n/**\n * A button for a named action of `model`'s view that runs on each record of the list it sits in, as a list's selection\n * does: on those it applies to, counted in its label (\"Approve (3)\"), asking its question or inputs once, a checklist's\n * boxes shared by several records once, and refusing and naming those the person may not change. Nothing when the view\n * has no such action, when it is a link, or when it applies to none of the records.\n */\nexport const ListActionButton = ({ model, items, name, label, variant, className }: ListActionProps) => {\n const { views } = useAdminMeta()\n const runner = useActionRunner(model.name, undefined)\n const titleOf = useRecordTitle()\n const [asking, setAsking] = useState(false)\n const action = views[model.name]?.actions?.find((entry) => entry.name === name)\n if (!action || action.run?.kind === 'link') return null\n const records = items.map((item) => scopeOf(model, item as Record<string, unknown>))\n const on = records.filter((record) => runner.verdictOn(action, record) !== 'skip')\n if (on.length === 0) return null\n const skipped = records.length - on.length\n const shown = text('actionCount', { label: label ?? action.label, count: on.length })\n const run = (values?: Record<string, unknown>) => runner.runEach(action, on, skipped, values)\n const start = () => (asksFirst(action) ? setAsking(true) : void run())\n return (\n <>\n <Button size=\"sm\" variant={variant ?? action.variant ?? 'secondary'} className={className} loading={runner.running === name} onClick={start}>\n {shown}\n </Button>\n {asking && (\n <ActionPrompt\n action={action}\n label={shown}\n danger={variant === 'danger' || (variant === undefined && isDanger(action))}\n records={on.map((record) => record.record)}\n names={on.map((record) => quoted(titleOf(model, views[model.name], record.record, record.key)))}\n onCancel={() => setAsking(false)}\n onConfirm={() => {\n setAsking(false)\n void run()\n }}\n onSubmit={async (values) => {\n setAsking(false)\n await run(values)\n }}\n />\n )}\n </>\n )\n}\n","import { useState } from 'react'\nimport type { ActionProps } from '@protobase/layout'\nimport { Button } from '../../../primitives/button'\nimport { ActionPrompt, asksFirst } from '../action-prompt'\nimport { useLayoutList } from '../layout-list'\nimport { useLayoutRecord } from '../record-scope'\nimport { useRunAction } from '../use-run-action'\nimport { propsOf, type BlockProps } from './block-props'\nimport { ListActionButton } from './list-action'\n\n/**\n * A button for a named action of `resource`'s view, by default of the record around it, on that record, asking first\n * when the action has `confirm` or `inputs`; nothing when the view has no such action for the user, or none for the\n * record. It is drawn as the action's `variant` unless the block names its own. `about` names the record in the\n * button's accessible name after its label, as \"Mark clear: <title>\", where the same button repeats for several records.\n * `onRun` hears the label it shows once the action succeeded.\n */\nexport const ActionButton = ({ name, resource, label, variant, className, about, onRun }: ActionProps & { className?: string; about?: string; onRun?: (label: string) => void }) => {\n const scope = useLayoutRecord()\n const action = useRunAction(resource ?? scope?.model.name ?? '', name, resource === undefined || resource === scope?.model.name ? scope : undefined, (ran) => onRun?.(label ?? ran.label))\n const [asking, setAsking] = useState(false)\n if (!action.action) return null\n const text = label ?? action.action.label\n // The block's own variant wins over the action's\n const shown = variant ?? action.action.variant ?? 'secondary'\n const start = () => (asksFirst(action.action!) ? setAsking(true) : void action.run())\n return (\n <>\n <Button size=\"sm\" variant={shown} className={className} loading={action.running} disabled={Boolean(action.blocked)} title={action.blocked} aria-label={about === undefined ? undefined : `${text}: ${about}`} onClick={start}>\n {text}\n </Button>\n {asking && (\n <ActionPrompt\n action={action.action}\n label={text}\n danger={shown === 'danger'}\n records={action.record ? [action.record] : []}\n onCancel={() => setAsking(false)}\n onConfirm={() => {\n setAsking(false)\n void action.run()\n }}\n onSubmit={async (values) => {\n await action.submit(values)\n setAsking(false)\n }}\n />\n )}\n </>\n )\n}\n\n/**\n * An Action block: its button, on the record around it, or, directly in a list of records and naming no other resource,\n * on each record of that list.\n */\nexport const ActionBlock = ({ node, className }: BlockProps) => {\n const props = propsOf<ActionProps>(node)\n const list = useLayoutList()\n const model = list?.model\n if (model && (props.resource === undefined || props.resource === model.name)) return <ListActionButton {...props} model={model} items={list.items} className={className} />\n return <ActionButton {...props} className={className} />\n}\n","import type { CardProps } from '@protobase/layout'\nimport { cn } from '../../../lib/cn'\nimport { propsOf, type BlockProps } from './block-props'\nimport { CardFrame } from './card-frame'\n\nexport const CardBlock = ({ node, children, slots, className }: BlockProps) => {\n const { title, description } = propsOf<CardProps>(node)\n return (\n <CardFrame title={title} description={description} actions={slots.actions} className={cn('h-full', className)}>\n <div className=\"flex flex-col gap-3\">{children}</div>\n </CardFrame>\n )\n}\n","import { Fragment, type ReactNode } from 'react'\nimport { RecordScope, type ItemFrame, type LayoutRecord } from '../record-scope'\nimport { useLayoutList } from '../layout-list'\nimport { scopeOf } from '../use-layout-data'\nimport type { BlockProps } from './block-props'\n\ntype EachProps = {\n children: ReactNode\n /** What each entry is drawn in, such as a card of a row; nothing when omitted. */\n wrap?: (entry: ReactNode, key: string | number) => ReactNode\n}\n\n/**\n * `children` once per entry of the list around it, each in the record it is, or the item of a JSON list, which\n * `@index`, `@first` and `@last` count; the list ends there, so a list inside them is one of their own.\n */\nexport const RecordsEach = ({ children, wrap = (entry, key) => <Fragment key={key}>{entry}</Fragment> }: EachProps) => {\n const list = useLayoutList()\n if (!list) return null\n const { model, items, planned } = list\n return items.map((item, index) => {\n const value: LayoutRecord | ItemFrame = model ? { ...scopeOf(model, item as Record<string, unknown>), ...(planned && { planned }) } : { item }\n const key = 'key' in value ? value.key : index\n return wrap(\n <RecordScope value={value} row={{ index, count: items.length }}>\n {children}\n </RecordScope>,\n key,\n )\n })\n}\n\n/** Its children once per entry of the list around it, with nothing drawn around them, as react-admin's RecordsIterator. */\nexport const RecordsIteratorBlock = ({ children }: BlockProps) => <RecordsEach>{children}</RecordsEach>\n","import type { ReactNode } from 'react'\nimport type { CardRowProps } from '@protobase/layout'\nimport type { ResourceModel } from '@protobase/schema'\nimport { Skeleton } from '../../../primitives/skeleton'\nimport { ErrorBanner } from '../../error-banner'\nimport { useAdminMeta } from '../../meta-gate'\nimport { LayoutListScope } from '../layout-list'\nimport { usePlanned } from '../plan-reads'\nimport { useListPage } from '../use-layout-data'\nimport { propsOf, type BlockProps } from './block-props'\nimport { CardFrame, Quiet } from './card-frame'\nimport { RecordsEach } from './records-iterator'\nimport { text } from '../messages'\n\ntype LoadedProps = Omit<CardRowProps, 'resource' | 'actions' | 'children'> & { model: ResourceModel; at?: string; actions: ReactNode; children: ReactNode[]; className?: string }\n\n// A list of its records, from the page's planned read or one of its own, drawn as a RecordsIterator draws one, each in a\n// small card of the row\nconst LoadedCardRow = ({ model, at, filter, sort, limit = 12, title, description, empty, actions, children, className }: LoadedProps) => {\n const planned = usePlanned(at)\n const own = useListPage(model, { filter, sort, pageSize: limit, enabled: !planned })\n const page = planned ?? own\n const rows = planned ? planned.rows : (own.data?.items ?? [])\n return (\n <CardFrame title={title} description={description} actions={actions} className={className}>\n {page.isPending ? (\n <div className=\"flex gap-3\">{Array.from({ length: 3 }, (_, index) => <Skeleton key={index} className=\"h-24 w-56\" />)}</div>\n ) : page.error ? (\n <ErrorBanner title={text('couldNotLoad')} error={page.error} />\n ) : rows.length === 0 ? (\n <Quiet>{empty ?? text('nothingYet')}</Quiet>\n ) : (\n <ul className=\"relative -mx-4 flex snap-x gap-3 overflow-x-auto px-4 pb-1\">\n <LayoutListScope value={{ model, items: rows, ...(planned && { planned: true }) }}>\n <RecordsEach\n wrap={(entry, key) => (\n <li key={key} className=\"flex w-60 shrink-0 snap-start flex-col gap-2 rounded-lg border border-border bg-surface p-3\">\n {entry}\n </li>\n )}\n >\n {children}\n </RecordsEach>\n </LayoutListScope>\n </ul>\n )}\n </CardFrame>\n )\n}\n\n/** Up to `limit` records side by side, each a small card made from the children, with their own actions. */\nexport const CardRowBlock = ({ node, at, children, slots }: BlockProps) => {\n const { resource, ...props } = propsOf<CardRowProps>(node)\n const model = useAdminMeta().resources[resource]\n if (!model) return null\n return (\n <LoadedCardRow {...props} model={model} {...(at !== undefined && { at })} actions={slots.actions}>\n {children}\n </LoadedCardRow>\n )\n}\n","import type { ChartProps, Styled } from '@protobase/layout'\nimport { ChartView } from '../../charts/chart-view'\nimport { useAdminMeta } from '../../meta-gate'\nimport { cn } from '../../../lib/cn'\nimport { propsOf, type BlockProps } from './block-props'\nimport { CardFrame } from './card-frame'\n\n/** Counts, sums or averages of the records that match, per value or date bucket of a field, in a card. */\nexport const ChartBlock = ({ node, slots, className }: BlockProps) => {\n const { resource, title, description, actions: _actions, span: _span, className: _className, ...chart } = propsOf<ChartProps & Styled>(node)\n const { resources, views } = useAdminMeta()\n const model = resources[resource]\n if (!model) return null\n return (\n <CardFrame title={title} description={description} actions={slots.actions} className={cn('h-full', className)}>\n <ChartView model={model} view={views[resource]} {...chart} />\n </CardFrame>\n )\n}\n","import type { ReactNode } from 'react'\nimport type { ResourceModel } from '@protobase/schema'\nimport { Skeleton } from '../../../primitives/skeleton'\nimport { ErrorBanner } from '../../error-banner'\nimport { RecordScope } from '../record-scope'\nimport { useFirstRecord } from '../use-layout-data'\nimport { Quiet } from './card-frame'\nimport { text } from '../messages'\n\n/** Which record a `select` chose: by its key as text, or the first that matches a filter in a sort's order. */\nexport type ChosenQuery = { key: string } | { filter: string; sort: string }\n\n/** The record a block's `select` chose, with its children drawn inside it, under a rule unless `className` places it otherwise. */\nexport const ChosenRecord = ({ model, query, className = 'mt-4 border-t pt-4', children }: { model: ResourceModel; query: ChosenQuery; className?: string; children: ReactNode }) => {\n const record = useFirstRecord(model, query)\n const body = record.isPending ? (\n <div className=\"flex flex-col gap-2\">\n <Skeleton className=\"h-4 w-1/2\" />\n <Skeleton className=\"h-4 w-1/3\" />\n </div>\n ) : record.error ? (\n <ErrorBanner title={text('couldNotLoad')} error={record.error} />\n ) : record.data ? (\n <RecordScope value={record.data}>\n <div className=\"flex flex-col gap-3\">{children}</div>\n </RecordScope>\n ) : (\n <Quiet>{text('nothingYet')}</Quiet>\n )\n return <div className={className}>{body}</div>\n}\n","// Where a timeline draws each record: a lane per `lane` value in the order they first start, a bar per `bar` value\n// in its lane, and a segment per record from `start` to `end`, all placed as a share of the time from the earliest\n// start to the latest end, so the axis always fits the width it has. A record without an end runs to now.\n\ntype Row = Record<string, unknown>\n\n/** The fields a timeline reads of each record, by their roles. */\nexport type TimelineFields = { lane: string; bar: string; start: string; end: string; color: string }\n\n/** One record as a part of its bar: its colour value, its time in ms, `open` when it has no end, and where it sits in %. */\nexport type TimelineSegment = { record: Row; value: unknown; start: number; end: number; open: boolean; left: number; width: number }\n\n/** The records of one `bar` value in a lane, from its first start to its last end, placed in %. */\nexport type TimelineBar = { key: string; value: unknown; lane: unknown; start: number; end: number; left: number; width: number; segments: TimelineSegment[] }\n\n/** One lane: its value, and its bars packed into rows so none overlap another in time. */\nexport type TimelineLane = { key: string; value: unknown; rows: TimelineBar[][] }\n\n/** What a timeline draws: its lanes, and the time its axis runs over. */\nexport type TimelineShape = { lanes: TimelineLane[]; from: number; to: number }\n\nconst timeOf = (value: unknown) => {\n if (typeof value !== 'string' && typeof value !== 'number') return\n const ms = typeof value === 'number' ? value : Date.parse(value)\n return Number.isNaN(ms) ? undefined : ms\n}\n\n/** The key a lane or bar value is grouped by. */\nexport const keyOf = (value: unknown) => (value === null || value === undefined ? '' : String(value))\n\nconst share = (ms: number, from: number, span: number) => (span === 0 ? 0 : ((ms - from) / span) * 100)\n\ntype Grouped = { value: unknown; bars: Map<string, { value: unknown; records: Array<{ record: Row; start: number; end: number; open: boolean }> }> }\n\n// Records grouped into lanes and bars, each with its time; one without a start cannot be placed and is left out\nconst groupOf = (rows: Row[], fields: TimelineFields, now: number) => {\n const lanes = new Map<string, Grouped>()\n for (const record of rows) {\n const start = timeOf(record[fields.start])\n if (start === undefined) continue\n const given = timeOf(record[fields.end])\n const end = Math.max(start, given ?? now)\n const lane = lanes.get(keyOf(record[fields.lane])) ?? { value: record[fields.lane], bars: new Map() }\n lanes.set(keyOf(record[fields.lane]), lane)\n const bar = lane.bars.get(keyOf(record[fields.bar])) ?? { value: record[fields.bar], records: [] }\n lane.bars.set(keyOf(record[fields.bar]), bar)\n bar.records.push({ record, start, end, open: given === undefined })\n }\n return lanes\n}\n\n// Each bar goes in the first row of its lane whose last bar ended by the time it starts, or a new row\nconst pack = (bars: TimelineBar[]) => {\n const rows: TimelineBar[][] = []\n for (const bar of [...bars].sort((a, b) => a.start - b.start)) {\n const row = rows.find((placed) => placed.at(-1)!.end <= bar.start)\n if (row) row.push(bar)\n else rows.push([bar])\n }\n return rows\n}\n\n/** Lanes, bars and segments of `rows`, placed between the earliest start and the latest end, an open end at `now`. */\nexport const timelineShape = (rows: Row[], fields: TimelineFields, now: number): TimelineShape => {\n const grouped = groupOf(rows, fields, now)\n const times = [...grouped.values()].flatMap((lane) => [...lane.bars.values()].flatMap((bar) => bar.records))\n if (times.length === 0) return { lanes: [], from: now, to: now }\n const from = Math.min(...times.map((time) => time.start))\n const to = Math.max(...times.map((time) => time.end))\n const span = to - from\n const lanes = [...grouped.entries()].map(([key, lane]): TimelineLane => {\n const bars = [...lane.bars.entries()].map(([barKey, bar]): TimelineBar => {\n const segments = bar.records\n .sort((a, b) => a.start - b.start)\n .map(({ record, start, end, open }) => ({ record, value: record[fields.color], start, end, open, left: share(start, from, span), width: share(end, from, span) - share(start, from, span) }))\n const start = segments[0]!.start\n const end = Math.max(...segments.map((segment) => segment.end))\n return { key: barKey, value: bar.value, lane: lane.value, start, end, left: share(start, from, span), width: share(end, from, span) - share(start, from, span), segments }\n })\n return { key, value: lane.value, rows: pack(bars) }\n })\n return { lanes, from, to }\n}\n\n/** A segment's place within its bar, in % of the bar's width, for drawing it inside the bar. */\nexport const withinBar = (bar: TimelineBar, segment: TimelineSegment) => {\n const span = bar.end - bar.start\n return { left: share(segment.start, bar.start, span), width: span === 0 ? 100 : ((segment.end - segment.start) / span) * 100 }\n}\n\nconst minute = 60_000\nconst hour = 60 * minute\nconst day = 24 * hour\n\n/** The steps an axis ticks at, the shortest first. */\nexport const tickSteps = [5 * minute, 15 * minute, 30 * minute, hour, 3 * hour, 6 * hour, 12 * hour, day, 2 * day, 7 * day, 14 * day, 30 * day, 90 * day, 365 * day]\n\n/** How many ticks an axis shows at most, so their labels fit a phone's width. */\nexport const maxTicks = 6\n\nconst year = 365 * day\n\n// How many whole local steps lie from `from` to `to`, both included, on a clock `fromOffset` ms ahead of UTC at `from` and `toOffset` at `to`\nconst stepsIn = (from: number, to: number, step: number, fromOffset: number, toOffset: number) => Math.floor((to + toOffset) / step) - Math.ceil((from + fromOffset) / step) + 1\n\n/**\n * The ticks of an axis from `from` to `to`: the shortest step that gives at most `maxTicks`, past the last of\n * `tickSteps` whole years, each on a whole step of the clock `offsetOf` gives at a moment, its ms ahead of UTC there,\n * so a tick stays on its local hour or midnight when the offset changes within the range, and a local time the clock\n * skips gets none. Each is placed in %;\n * `daily` when the step is a day or more, so they read as dates.\n */\nexport const axisTicks = (from: number, to: number, offsetOf: (ms: number) => number = () => 0) => {\n const span = to - from\n if (span <= 0) return { daily: false, ticks: [] }\n const offset = offsetOf(from)\n const endOffset = offsetOf(to)\n const step = tickSteps.find((candidate) => stepsIn(from, to, candidate, offset, endOffset) <= maxTicks) ?? Math.ceil(span / (maxTicks - 1) / year) * year\n const ticks: Array<{ at: number; left: number }> = []\n for (let local = Math.ceil((from + offset) / step) * step; local <= to + endOffset; local += step) {\n // The local step's moment, by the offset in force near it; a step the clock skips, as it springs forward, has none\n const at = local - offsetOf(local - offset)\n if (at + offsetOf(at) !== local) continue\n if (at >= from && at <= to) ticks.push({ at, left: share(at, from, span) })\n }\n return { daily: step >= day, ticks }\n}\n","import { keyOf, type TimelineBar, type TimelineShape } from './timeline-layout'\n\n/** Which bar of a timeline one is, by its lane's key and its own, so it is found again in a newer shape. */\nexport type BarId = { lane: string; bar: string }\n\nexport const barIdOf = (bar: TimelineBar): BarId => ({ lane: keyOf(bar.lane), bar: bar.key })\n\n/** The bar `id` names in `shape`, as the current data places it, or `null` when it is no longer there. */\nexport const barIn = (shape: TimelineShape, id: BarId | null) => {\n if (!id) return null\n const lane = shape.lanes.find((candidate) => candidate.key === id.lane)\n return lane?.rows.flat().find((bar) => bar.key === id.bar) ?? null\n}\n","import { formatDayShort, formatTime } from '../../../../format/date'\nimport { viewerZone } from '../../../../format/zone'\nimport { axisTicks } from './timeline-layout'\n\n// How far the viewer's clock is ahead of UTC at `ms`, so ticks fall on their whole hours and days\nconst offsetAt = (ms: number, zone: string) => {\n const parts = Object.fromEntries(new Intl.DateTimeFormat('en-US', { timeZone: zone, hourCycle: 'h23', year: 'numeric', month: 'numeric', day: 'numeric', hour: 'numeric', minute: 'numeric' }).formatToParts(ms).map((part) => [part.type, part.value]))\n const local = Date.UTC(Number(parts.year), Number(parts.month) - 1, Number(parts.day), Number(parts.hour), Number(parts.minute))\n return local - Math.floor(ms / 60_000) * 60_000\n}\n\n// A label near an edge stays inside the axis, so it never widens the page\nconst anchor = (left: number) => (left < 8 ? 'translate-x-0' : left > 92 ? '-translate-x-full' : '-translate-x-1/2')\n\n/**\n * The time from `from` to `to` as a few ticks, as dates from a day apart, as times below: on the viewer's clock, or for\n * `dated` fields, whose days are kept in UTC as their bars are, on UTC's.\n */\nexport const TimelineAxis = ({ from, to, dated }: { from: number; to: number; dated: boolean }) => {\n const zone = dated ? 'UTC' : viewerZone()\n const offsetOf = (ms: number) => (dated ? 0 : offsetAt(ms, zone))\n const { daily, ticks } = axisTicks(from, to, offsetOf)\n return (\n <div aria-hidden=\"true\" className=\"relative h-5 min-w-0 flex-1 border-b border-border text-xs text-muted-foreground tabular-nums\">\n {ticks.map((tick) => (\n <span key={tick.at} className={`absolute bottom-1 whitespace-nowrap ${anchor(tick.left)}`} style={{ left: `${tick.left}%` }}>\n {/* A day is kept in UTC, so the viewer's day is their midnight moved by the offset there */}\n {daily ? formatDayShort(tick.at + offsetOf(tick.at)) : formatTime(tick.at, zone)}\n </span>\n ))}\n </div>\n )\n}\n","import { isBadgeTone, type FieldModel, type FieldViewModel } from '@protobase/schema'\nimport { toneDots } from '../../../../primitives/badge'\nimport { colorOf } from '../../../charts/chart-groups'\n\n/** How a segment is filled: a tone's class or a colour, striped while its value waits. */\nexport type SegmentPaint = { className?: string; color?: string; striped: boolean }\n\n// A wait reads apart from work at a glance, in any colour: the background shows through every other stripe\nexport const stripes = 'repeating-linear-gradient(-45deg, transparent 0 4px, color-mix(in srgb, var(--background) 55%, transparent) 4px 6px)'\n\n/**\n * A segment's fill by its `color` value: the tone or hex colour its view's `valueColors` gives it, else the chart\n * colour of its place among the enum's values, as a chart colours it; striped when the view marks it waiting.\n */\nexport const segmentPaint = (field: FieldModel, hints: FieldViewModel | undefined, value: unknown): SegmentPaint => {\n const key = String(value)\n const striped = hints?.waitingValues?.includes(key) ?? false\n const declared = hints?.valueColors && Object.hasOwn(hints.valueColors, key) ? hints.valueColors[key] : undefined\n if (declared !== undefined && isBadgeTone(declared)) return { className: toneDots[declared], striped }\n return { color: colorOf(field, hints, value === undefined ? null : (value as string | null), -1), striped }\n}\n","import type { FieldModel, FieldViewModel } from '@protobase/schema'\nimport { cn } from '../../../../lib/cn'\nimport { withinBar, type TimelineBar } from './timeline-layout'\nimport { segmentPaint, stripes, type SegmentPaint } from './timeline-paint'\n\n/** A swatch or segment's fill: its tone's class or colour, with stripes while it waits. */\nexport const paintStyle = (paint: SegmentPaint) => ({ ...(paint.color !== undefined && { backgroundColor: paint.color }), ...(paint.striped && { backgroundImage: stripes }) })\n\n/** A bar's segments, each where its time falls in the bar and filled as its `color` value says. */\nexport const SegmentFill = ({ bar, field, hints }: { bar: TimelineBar; field: FieldModel; hints: FieldViewModel | undefined }) =>\n bar.segments.map((segment, index) => {\n const paint = segmentPaint(field, hints, segment.value)\n const { left, width } = withinBar(bar, segment)\n return <span key={index} aria-hidden=\"true\" className={cn('absolute inset-y-0', paint.className)} style={{ left: `${left}%`, width: `${width}%`, ...paintStyle(paint) }} />\n })\n","import type { ResourceModel, ViewModel } from '@protobase/schema'\nimport { formatDate, formatDateTime } from '../../../../format/date'\nimport { displayValue } from '../../../../live/display-value'\nimport { text } from '../../messages'\nimport type { TimelineBar, TimelineFields, TimelineSegment } from './timeline-layout'\n\nconst timeOf = (ms: number, dated: boolean) => (dated ? formatDate(ms) : formatDateTime(ms))\n\n/** \"14 Nov 2026, 09:00 – 14 Nov 2026, 11:30\", or \"… – now\" while it runs: from `start` to `end`, in the type of `fields.start`. */\nexport const rangeText = (model: ResourceModel, fields: TimelineFields, start: number, end: number, open: boolean) => {\n const dated = model.fields[fields.start]?.type === 'date'\n return text('timelineRange', { from: timeOf(start, dated), to: open ? text('timelineNow') : timeOf(end, dated) })\n}\n\n/** A segment's value and times, as one line. */\nexport const segmentText = (segment: TimelineSegment, model: ResourceModel, view: ViewModel | undefined, fields: TimelineFields) =>\n `${displayValue(model.fields[fields.color]!, segment.value, view?.fields[fields.color])}: ${rangeText(model, fields, segment.start, segment.end, segment.open)}`\n\n/** What a bar reads as to a screen reader: its name, its value as shown without one, and times, then each segment's. */\nexport const barText = (bar: TimelineBar, model: ResourceModel, view: ViewModel | undefined, fields: TimelineFields, known?: string) => {\n const open = bar.segments.some((segment) => segment.open && segment.end === bar.end)\n const name = known ?? displayValue(model.fields[fields.bar]!, bar.value, view?.fields[fields.bar])\n return [`${name}: ${rangeText(model, fields, bar.start, bar.end, open)}`, ...bar.segments.map((segment) => segmentText(segment, model, view, fields))].join('; ')\n}\n","import type { ResourceModel, ViewModel } from '@protobase/schema'\nimport { cn } from '../../../../lib/cn'\nimport { RouteLink, type RouteTarget } from '../../../../primitives/route-link'\nimport { FieldValue } from '../../field-value'\nimport { useAdminMeta } from '../../../meta-gate'\nimport { useRelationTitle } from '../../../titles/use-relation-title'\nimport type { TimelineBar, TimelineFields, TimelineShape } from './timeline-layout'\nimport { TimelineAxis } from './timeline-axis'\nimport { SegmentFill } from './segment-fill'\nimport { barText } from './timeline-text'\n\n/** What the lanes draw with: the resource and its view, the fields by role, and what pointing at and choosing a bar do. */\nexport type LanesProps = {\n shape: TimelineShape\n model: ResourceModel\n view: ViewModel | undefined\n fields: TimelineFields\n /** What pointing at a bar and moving focus to it do; `null` when the pointer or focus leaves it. */\n point: { hover: (bar: TimelineBar | null) => void; focus: (bar: TimelineBar | null) => void }\n /** With `select`: where a bar leads, and the key of the bar chosen. */\n choose?: { barTo: (key: string) => RouteTarget; chosen: string | undefined }\n}\n\nconst barLook = 'absolute inset-y-0 flex overflow-hidden rounded-sm ring-offset-1 ring-offset-background outline-none hover:ring-2 hover:ring-border-strong focus-visible:ring-2 focus-visible:ring-primary'\n\n// One bar: its segments side by side within it, a link to the page with it chosen under `select`, else a mark that\n// can take focus, so a keyboard and a screen reader reach its times too\nconst BarMark = ({ bar, model, view, fields, point: on, choose }: Omit<LanesProps, 'shape'> & { bar: TimelineBar }) => {\n // A bar of a relation is named by the record it points at, as its readout shows it\n const target = useAdminMeta().resources[model.fields[fields.bar]?.relation?.resource ?? '']\n const name = useRelationTitle(target ?? model, bar.key, target !== undefined)\n const label = barText(bar, model, view, fields, target ? name : undefined)\n const point = { onMouseEnter: () => on.hover(bar), onMouseLeave: () => on.hover(null), onFocus: () => on.focus(bar), onBlur: () => on.focus(null) }\n const style = { left: `${bar.left}%`, width: `max(${bar.width}%, 4px)` }\n const segments = <SegmentFill bar={bar} field={model.fields[fields.color]!} hints={view?.fields[fields.color]} />\n if (!choose) {\n return (\n <span role=\"img\" tabIndex={0} aria-label={label} style={style} className={barLook} {...point}>\n {segments}\n </span>\n )\n }\n const chosen = choose.chosen === bar.key\n return (\n <RouteLink to={choose.barTo(bar.key)} aria-label={label} aria-current={chosen ? 'true' : undefined} style={style} className={cn(barLook, chosen && 'ring-2 ring-foreground')} {...point}>\n {segments}\n </RouteLink>\n )\n}\n\n/**\n * A lane per value of `lane`, its name beside its bars from a phone's width up and above them on a phone, its bars in\n * as many rows as keep them apart in time, under an axis of the whole time. The bars are placed as a share of the\n * width, so the timeline always fits the page and never scrolls sideways.\n */\nexport const TimelineLanes = ({ shape, ...props }: LanesProps) => {\n const { model, fields } = props\n const laneField = model.fields[fields.lane]!\n return (\n <div className=\"flex flex-col gap-2\">\n <div className=\"flex sm:pl-40\">\n <TimelineAxis from={shape.from} to={shape.to} dated={model.fields[fields.start]?.type === 'date'} />\n </div>\n <ul className=\"flex flex-col gap-3 sm:gap-2\">\n {shape.lanes.map((lane) => (\n <li key={lane.key} className=\"flex flex-col gap-1 sm:flex-row sm:items-center\">\n <div className=\"min-w-0 truncate text-sm font-medium sm:w-40 sm:shrink-0 sm:pr-3\">\n <FieldValue model={model} field={laneField} value={lane.value} />\n </div>\n <div className=\"flex min-w-0 flex-1 flex-col gap-1 border-l border-border pl-px\">\n {lane.rows.map((row, index) => (\n <div key={index} className=\"relative h-6 overflow-x-clip\">\n {row.map((bar) => (\n <BarMark key={bar.key} bar={bar} {...props} />\n ))}\n </div>\n ))}\n </div>\n </li>\n ))}\n </ul>\n </div>\n )\n}\n","import type { ResourceModel, ViewModel } from '@protobase/schema'\nimport { displayValue } from '../../../../live/display-value'\nimport { FieldValue } from '../../field-value'\nimport { text } from '../../messages'\nimport { paintStyle } from './segment-fill'\nimport type { TimelineBar, TimelineFields } from './timeline-layout'\nimport { segmentPaint } from './timeline-paint'\nimport { rangeText } from './timeline-text'\nimport { cn } from '../../../../lib/cn'\n\ntype ReadoutProps = { bar: TimelineBar | null; model: ResourceModel; view: ViewModel | undefined; fields: TimelineFields }\n\n/** A value's colour, as a small square beside its name. */\nconst Swatch = ({ model, view, fields, value }: Omit<ReadoutProps, 'bar'> & { value: unknown }) => {\n const paint = segmentPaint(model.fields[fields.color]!, view?.fields[fields.color], value)\n return <span aria-hidden=\"true\" className={cn('inline-block size-3 shrink-0 rounded-sm', paint.className)} style={paintStyle(paint)} />\n}\n\n/** What each colour of a bar means: the `color` field's values the bars hold, in the enum's order, the waits striped. */\nexport const TimelineLegend = ({ values, ...props }: Omit<ReadoutProps, 'bar'> & { values: ReadonlySet<string> }) => {\n const field = props.model.fields[props.fields.color]!\n const shown = (field.enumValues ?? []).filter((value) => values.has(value))\n return (\n <ul className=\"flex flex-wrap gap-x-4 gap-y-1.5 text-xs text-muted-foreground\">\n {shown.map((value) => (\n <li key={value} className=\"flex items-center gap-1.5\">\n <Swatch {...props} value={value} />\n {displayValue(field, value, props.view?.fields[props.fields.color])}\n </li>\n ))}\n </ul>\n )\n}\n\n/** The bar pointed at: its value and times, then each segment's value and times; a hint while none is. */\nexport const TimelineReadout = ({ bar, ...props }: ReadoutProps) => {\n const { model, view, fields } = props\n if (!bar) return <p className=\"text-sm text-muted-foreground\">{text('timelinePoint')}</p>\n const open = bar.segments.some((segment) => segment.open && segment.end === bar.end)\n return (\n <div className=\"flex flex-col gap-1 text-sm\">\n <p className=\"flex flex-wrap items-baseline gap-x-2\">\n <span className=\"font-medium\">\n <FieldValue model={model} field={model.fields[fields.bar]!} value={bar.value} />\n </span>\n <span className=\"text-muted-foreground tabular-nums\">{rangeText(model, fields, bar.start, bar.end, open)}</span>\n </p>\n <ul className=\"flex flex-col gap-0.5 text-xs text-muted-foreground\">\n {bar.segments.map((segment, index) => (\n <li key={index} className=\"flex items-center gap-1.5 tabular-nums\">\n <Swatch {...props} value={segment.value} />\n {displayValue(model.fields[fields.color]!, segment.value, view?.fields[fields.color])}: {rangeText(model, fields, segment.start, segment.end, segment.open)}\n </li>\n ))}\n </ul>\n </div>\n )\n}\n","import { keepPreviousData, useQuery } from '@tanstack/react-query'\nimport type { Client } from '@protobase/client'\nimport type { ResourceModel } from '@protobase/schema'\nimport { useClient } from '../../../../data/api-provider'\nimport { keys } from '../../../../data/query-keys'\n\n// The list API's largest page\nconst pageSize = 500\n\ntype Row = Record<string, unknown>\n\nexport type TimelineRowsRequest = { filter?: string; sort: string; fields: string[]; limit: number }\n\n/** A timeline's records, as many as `limit`, and whether more match than that. */\nexport type TimelineRows = { rows: Row[]; cut: boolean }\n\n/**\n * Every record that matches `filter`, page after page in `sort` order up to `limit`, then the earliest first; `cut`\n * when more remain. It reads only the fields the timeline draws, and no ETags.\n */\nexport const timelineRowsQuery = (client: Client, model: ResourceModel, { filter = '', sort, fields, limit }: TimelineRowsRequest) => ({\n queryKey: [...keys.list(model.name, filter, sort, limit, 'timeline'), fields.join(',')],\n queryFn: async (): Promise<TimelineRows> => {\n const rows: Row[] = []\n let pageToken: string | undefined\n do {\n const page = await client.list(model.name, { filter: filter || undefined, orderBy: sort, pageSize: Math.min(pageSize, limit - rows.length), fields, etag: false, ...(pageToken && { pageToken }) })\n rows.push(...(page.items as Row[]))\n pageToken = page.nextPageToken || undefined\n } while (pageToken && rows.length < limit)\n return { rows: rows.toReversed(), cut: pageToken !== undefined }\n },\n})\n\n/** A timeline's records, as `timelineRowsQuery` reads them; the records before stay on screen while newer ones load. */\nexport const useTimelineRows = (model: ResourceModel, { enabled = true, ...request }: TimelineRowsRequest & { enabled?: boolean }) =>\n useQuery({ ...timelineRowsQuery(useClient(), model, request), enabled, placeholderData: keepPreviousData })\n","import { useState, type ReactNode } from 'react'\nimport { defaultTimelineLimit, timelineReadSort, timelineSort, type Styled, type TimelineProps } from '@protobase/layout'\nimport type { FieldModel, ResourceModel, ViewModel } from '@protobase/schema'\nimport { Skeleton } from '../../../../primitives/skeleton'\nimport { ErrorBanner } from '../../../error-banner'\nimport { GuardedParams } from '../../../guarded-params'\nimport { useAdminMeta } from '../../../meta-gate'\nimport { cn } from '../../../../lib/cn'\nimport { groupFilter } from '../../../charts/chart-groups'\nimport { text } from '../../messages'\nimport { usePageParams } from '../../page-params'\nimport { usePlanned } from '../../plan-reads'\nimport { propsOf, type BlockProps } from '../block-props'\nimport { CardFrame, Quiet } from '../card-frame'\nimport { ChosenRecord } from '../chosen-record'\nimport { barIdOf, barIn, type BarId } from './bar-identity'\nimport { timelineShape, type TimelineBar, type TimelineFields } from './timeline-layout'\nimport { TimelineLanes, type LanesProps } from './timeline-lanes'\nimport { TimelineLegend, TimelineReadout } from './timeline-readout'\nimport { useTimelineRows } from './use-timeline-rows'\n\ntype LoadedProps = Omit<TimelineProps, 'resource' | 'actions' | 'children' | 'select' | 'lane' | 'bar' | 'start' | 'end' | 'color'> & {\n model: ResourceModel\n view: ViewModel | undefined\n fields: TimelineFields\n /** The order it reads its records in, the latest first, so a limit leaves out the oldest. */\n readSort: string\n /** The order the chosen bar's first record is found in. */\n sort: string\n at?: string\n actions: ReactNode\n className?: string\n choose?: LanesProps['choose']\n details?: ReactNode\n}\n\n// Its records from the page's planned read, or a read of its own page after page up to its limit, drawn as lanes with\n// what the bar pointed at holds under them; a limit that leaves records out says how many it shows\nconst LoadedTimeline = ({ model, view, fields, readSort, at, filter, limit = defaultTimelineLimit, title, description, empty, actions, className, choose, details }: LoadedProps) => {\n // The bar under the pointer shows over the one with focus, which shows again once the pointer leaves; each is kept\n // by its identity and found in the current data, so the readout follows a refresh and drops a bar that is gone\n const [hovered, setHovered] = useState<BarId | null>(null)\n const [focused, setFocused] = useState<BarId | null>(null)\n const idOf = (bar: TimelineBar | null) => (bar ? barIdOf(bar) : null)\n const point = { hover: (bar: TimelineBar | null) => setHovered(idOf(bar)), focus: (bar: TimelineBar | null) => setFocused(idOf(bar)) }\n const planned = usePlanned(at)\n const own = useTimelineRows(model, { filter, sort: readSort, fields: [...new Set([...Object.values(fields), ...model.primaryKey])], limit, enabled: !planned })\n const page = planned ?? own\n const rows = planned ? planned.rows : (own.data?.rows ?? [])\n const cut = !planned && own.data?.cut === true\n const shape = timelineShape(rows, fields, Date.now())\n const body = () => {\n if (page.isPending) return <div className=\"flex flex-col gap-2\">{Array.from({ length: 3 }, (_, index) => <Skeleton key={index} className=\"h-6\" />)}</div>\n if (page.error) return <ErrorBanner title={text('couldNotLoad')} error={page.error} />\n if (shape.lanes.length === 0) return <Quiet>{empty ?? text('nothingYet')}</Quiet>\n const values = new Set(rows.map((row) => String(row[fields.color])))\n return (\n <div className=\"flex flex-col gap-4\">\n <TimelineLegend model={model} view={view} fields={fields} values={values} />\n <TimelineLanes shape={shape} model={model} view={view} fields={fields} point={point} {...(choose && { choose })} />\n {cut && <Quiet>{text('timelineCut', { count: rows.length })}</Quiet>}\n <div aria-live=\"polite\">\n <TimelineReadout bar={barIn(shape, hovered) ?? barIn(shape, focused)} model={model} view={view} fields={fields} />\n </div>\n </div>\n )\n }\n return (\n <CardFrame title={title} description={description} actions={actions} className={cn('h-full', className)}>\n {body()}\n {details}\n </CardFrame>\n )\n}\n\n// The bar a key names, as its `bar` field holds it: a number for an integer field, the text otherwise, as the API\n// gives a bigint or decimal, whose digits a number would round\nconst barValue = (field: FieldModel, key: string) => (field.type === 'integer' ? Number(key) : key)\n\n/** A timeline whose bars each link to the page with that bar's value in the parameter `select`, and the chosen bar's children under it. */\nconst SelectTimeline = ({ select, children, ...props }: LoadedProps & { select: string; children: ReactNode[] }) => {\n const { given, linkTo } = usePageParams()\n const key = given[select]\n const barTo = (barKey: string) => linkTo({ [select]: barKey })\n const field = props.model.fields[props.fields.bar]!\n // The chosen bar's first record among those the timeline shows; a form under it asks before another bar replaces it\n const details =\n key === undefined ? null : (\n <GuardedParams name={select}>\n <ChosenRecord key={key} model={props.model} query={{ filter: groupFilter(field, barValue(field, key), props.filter), sort: props.sort }}>\n {children}\n </ChosenRecord>\n </GuardedParams>\n )\n return <LoadedTimeline {...props} choose={{ barTo, chosen: key }} details={details} />\n}\n\n/**\n * Records as a timeline: a lane per `lane` value, a bar per `bar` value in it, each record a segment from `start` to\n * `end` coloured by its `color` value, the bar pointed at with its times under them. With `select`, a bar leads to the\n * page with it chosen, and the chosen bar's first record draws the children under the timeline.\n */\nexport const TimelineBlock = ({ node, at, slots, children, className }: BlockProps) => {\n const { className: _className, resource, select, lane, bar, start, end, color, children: _children, ...props } = propsOf<TimelineProps & Styled>(node)\n const { resources, views } = useAdminMeta()\n const model = resources[resource]\n if (!model) return null\n const loaded = { ...props, model, view: views[model.name], fields: { lane, bar, start, end, color }, readSort: timelineReadSort(node), sort: timelineSort(node), ...(at !== undefined && { at }), actions: slots.actions, className }\n if (select === undefined) return <LoadedTimeline {...loaded} />\n return (\n <SelectTimeline {...loaded} select={select}>\n {children}\n </SelectTimeline>\n )\n}\n","import type { ReactNode } from 'react'\nimport { selectOf, type LayoutNode } from '@protobase/layout'\nimport { GuardedParams } from '../guarded-params'\nimport { useAdminMeta } from '../meta-gate'\nimport { ChosenRecord } from './blocks/chosen-record'\nimport { usePageParamsIfAny } from './page-params'\n\n/**\n * A custom component's children inside the record its `select` chose, read by the key the page's address holds;\n * nothing while none is chosen. Without `select`, its children as they are.\n */\nexport const CustomChosen = ({ node, children }: { node: LayoutNode; children: ReactNode }) => {\n const selection = selectOf(node)\n const params = usePageParamsIfAny()\n const { resources } = useAdminMeta()\n if (!selection || !params) return children\n const key = params.given[selection.param]\n const model = selection.resource === undefined ? undefined : resources[selection.resource]\n if (key === undefined || !model) return null\n // A form under it asks before another choice replaces it\n return (\n <GuardedParams name={selection.param}>\n <ChosenRecord key={key} model={model} query={{ key }} className=\"\">\n {children}\n </ChosenRecord>\n </GuardedParams>\n )\n}\n","import { graphShape, type GraphFields, type GraphProps } from '@protobase/layout'\nimport { lazy, Suspense, useMemo } from 'react'\nimport { cn } from '../../../../lib/cn'\nimport { Spinner } from '../../../../primitives/spinner'\nimport { ErrorBanner } from '../../../error-banner'\nimport { useElementReads, type ComponentSelect } from '../../component-reads'\nimport { CustomChosen } from '../../custom-chosen'\nimport { text } from '../../messages'\nimport { usePageParamsIfAny } from '../../page-params'\nimport { propsOf, type BlockProps } from '../block-props'\nimport { Quiet } from '../card-frame'\n\n// The drawing library is a chunk of its own, which loads only when a graph draws\nconst GraphView = lazy(() => import('./graph-view').then((module) => ({ default: module.GraphView })))\n\nconst loading = (\n <div className=\"flex h-64 w-full items-center justify-center\">\n <Spinner />\n </div>\n)\n\n/**\n * The `Graph` block: the records of `nodes` as boxes, each in the region of its `group` and coloured by its `status`,\n * drawing `node` inside its record where the graph has one, and the records of `edges` as arrows between them, from the\n * reads the page's plan made. With `select`, each node links to the page with it chosen, and the children draw beside\n * the graph, inside the chosen node's record, or under it on a narrow screen. A read that fails draws its fallback.\n */\nexport const GraphBlock = ({ node, at, slots, children, className }: BlockProps) => {\n const props = propsOf<GraphProps>(node)\n const reads = useElementReads(node, at)\n const params = usePageParamsIfAny()\n const nodes = reads.nodes\n const edges = reads.edges\n const { label, group, status, source, target } = props\n const fields: GraphFields = useMemo(() => ({ label, source, target, ...(group !== undefined && { group }), ...(status !== undefined && { status }) }), [label, source, target, group, status])\n // The rows are new arrays on each render; the same records make the same shape, laid out once\n const signature = JSON.stringify([nodes?.rows, edges?.rows, fields])\n const shape = useMemo(() => nodes && edges && graphShape({ nodes: nodes.rows, edges: edges.rows, key: nodes.model.primaryKey[0]!, edgeKey: edges.model.primaryKey, fields }), [signature])\n if (!nodes || !edges || !shape) return null\n const error = nodes.error ?? edges.error\n // Its fallback stands in where it declares one, as for a component that throws\n if (error && node.fallback) throw error\n if (error) return <ErrorBanner title={text('couldNotLoad')} error={error} />\n if (nodes.isPending || edges.isPending) return loading\n if (shape.nodes.length === 0) return <Quiet>{props.empty ?? text('nothingYet')}</Quiet>\n const param = props.select\n const select: ComponentSelect | undefined = param !== undefined && params ? { chosen: params.given[param], linkTo: (key) => params.linkTo({ [param]: key }) } : undefined\n return (\n <div className={cn('flex flex-col gap-4 lg:flex-row', className)}>\n <div className=\"min-w-0 flex-1\">\n <Suspense fallback={loading}>\n <GraphView shape={shape} nodes={nodes} edges={edges} fields={fields} props={props} {...(select && { select })} {...(props.node !== undefined && { content: slots.node })} />\n </Suspense>\n </div>\n {/* The children draw once a node is chosen, inside its record */}\n {children.length > 0 && select?.chosen !== undefined && (\n <div className=\"min-w-0 lg:w-80 lg:shrink-0\">\n <CustomChosen node={node}>{children}</CustomChosen>\n </div>\n )}\n </div>\n )\n}\n","import { messages } from '../../locale/messages'\n\nexport const text = messages('app/conversation')\n","import { useState } from 'react'\nimport { Composer } from '../../chat'\nimport { useClient } from '../../data/api-provider'\nimport { ErrorBanner } from '../error-banner'\nimport { useAdminMeta, usePermissions } from '../meta-gate'\nimport { can } from '../permissions'\nimport { useRefreshResource } from '../pages/use-layout-data'\nimport { text } from './messages'\n\nexport type MessageComposerProps = {\n resource: string\n /** The text field the message goes in. */\n field: string\n /** Values sent with every message, such as the record's key in its relation. */\n values?: Record<string, unknown>\n placeholder?: string\n}\n\n/** A box that sends a message: each send creates a record of `resource` with the text in `field` and the `values`, for a user who may create one. */\nexport const MessageComposer = ({ resource, field, values, placeholder }: MessageComposerProps) => {\n const { resources } = useAdminMeta()\n const client = useClient()\n const refresh = useRefreshResource()\n const permissions = usePermissions(resource)\n const [sending, setSending] = useState(false)\n const [failure, setFailure] = useState<unknown>()\n if (!resources[resource] || !can(permissions, 'create')) return null\n\n // The text stays in the box until the server took it, so a refused message can be sent again\n const send = async (message: string) => {\n setSending(true)\n setFailure(undefined)\n const sent = await client.create(resource, { ...values, [field]: message }).then(\n () => true,\n (error: unknown) => {\n setFailure(error)\n return false\n },\n )\n setSending(false)\n if (sent) void refresh(resource)\n return sent\n }\n\n return (\n <div className=\"flex flex-col gap-2\">\n {failure !== undefined && <ErrorBanner title={text('notSent')} error={failure} />}\n <Composer onSend={send} busy={sending} placeholder={placeholder} />\n </div>\n )\n}\n","import type { ComposerProps } from '@protobase/layout'\nimport { MessageComposer } from '../../conversation/message-composer'\nimport { propsOf, type BlockProps } from './block-props'\n\n/** A box that sends a message: each send creates a record of `resource` with the text in `field` and the `values`. */\nexport const ComposerBlock = ({ node }: BlockProps) => {\n const { resource, field, values, placeholder } = propsOf<ComposerProps>(node)\n return <MessageComposer resource={resource} field={field} values={values} placeholder={placeholder} />\n}\n","import type { DetailsProps } from '@protobase/layout'\nimport { cn } from '../../../lib/cn'\nimport { propsOf, type BlockProps } from './block-props'\n\n/** HTML's <details>: the browser opens and closes it on a click of its summary, with no script. */\nexport const DetailsBlock = ({ node, children, className }: BlockProps) => {\n const { open } = propsOf<DetailsProps>(node)\n return (\n <details open={open} className={cn('[&[open]>summary]:mb-2', className)}>\n {children}\n </details>\n )\n}\n\n/** The line of a `Details` that is always shown, which opens and closes it. */\nexport const SummaryBlock = ({ children, className }: BlockProps) => <summary className={cn('cursor-pointer font-medium', className)}>{children}</summary>\n","import type { DiffProps } from '@protobase/layout'\nimport { DiffView } from '../../../diff-view/diff-view'\nimport { parsePatch } from '../../../diff-view/patch'\nimport { cn } from '../../../lib/cn'\nimport { Skeleton } from '../../../primitives/skeleton'\nimport { useScopedPathValue } from '../use-path-value'\nimport { propsOf, type BlockProps } from './block-props'\n\n/** A stored unified patch, each file drawn by `DiffView`; text that is no patch as it is, `emptyText` for an empty field. */\nexport const DiffBlock = ({ node, className }: BlockProps) => {\n const { source, emptyText } = propsOf<DiffProps>(node)\n const read = useScopedPathValue(source)\n if (read.state === 'missing') return null\n if (read.state === 'loading') return <Skeleton className={cn('h-24 w-full', className)} />\n if (read.value === null || read.value === undefined || read.value === '') return emptyText ? <p className={cn('text-sm text-muted-foreground', className)}>{emptyText}</p> : null\n const text = String(read.value)\n const files = parsePatch(text)\n if (!files) return <pre className={cn('overflow-x-auto whitespace-pre-wrap break-words rounded-md border border-border bg-background p-3 font-mono text-[0.6875rem] leading-[18px]', className)}>{text}</pre>\n return (\n <div className={cn('flex flex-col gap-3', className)}>\n {files.map((file, index) => (\n <DiffView key={`${index}-${file.path}`} source={file.lines} path={file.path} split className=\"rounded-md border border-border\" />\n ))}\n </div>\n )\n}\n","/** An `ArrayField` item's value as text, which no field describes: a list or object as JSON, nothing for none. */\nexport const plainText = (value: unknown) => (value === null || value === undefined ? '' : typeof value === 'object' ? JSON.stringify(value) : String(value))\n","import type { FieldProps } from '@protobase/layout'\nimport { humanize } from '../../../live/naming'\nimport { Skeleton } from '../../../primitives/skeleton'\nimport { useAdminMeta } from '../../meta-gate'\nimport { FieldValue } from '../field-value'\nimport { useScopedPathValue } from '../use-path-value'\nimport { cn } from '../../../lib/cn'\nimport { plainText } from './plain-value'\nimport { propsOf, type BlockProps } from './block-props'\n\n/** The view's label for the field at the end of the path, else the path in words: `companyId.city` is \"Company city\". */\nexport const fieldLabel = (path: string, viewLabel: string | undefined) => {\n if (viewLabel) return viewLabel\n const words = path.split('.').map((part) => humanize(part).toLowerCase()).join(' ')\n return words[0]!.toUpperCase() + words.slice(1)\n}\n\n/** A label over a value of the record around it; `label={false}` shows the value alone. */\nexport const FieldBlock = ({ node, className }: BlockProps) => {\n const { source, label, format } = propsOf<FieldProps>(node)\n const { views } = useAdminMeta()\n const value = useScopedPathValue(source)\n if (value.state === 'missing') return null\n const shown =\n value.state === 'loading' ? <Skeleton className=\"h-4 w-24\" /> : value.state === 'plain' ? plainText(value.value) : <FieldValue model={value.model} field={value.field} value={value.value} format={format} />\n if (label === false) return <div className={className}>{shown}</div>\n const text = label ?? fieldLabel(source, value.state === 'ready' ? views[value.model.name]?.fields[value.field.name]?.label : undefined)\n return (\n <div className={cn('min-w-0', className)}>\n <div className=\"text-body text-muted-foreground\">{text}</div>\n <div className=\"mt-0.5 truncate\">{shown}</div>\n </div>\n )\n}\n","import type { GridProps, GridSpan, LayoutChild } from '@protobase/layout'\nimport { cn } from '../../../lib/cn'\nimport { propsOf, type BlockProps } from './block-props'\n\nconst columns = { 1: '', 2: 'md:grid-cols-2', 3: 'md:grid-cols-2 xl:grid-cols-3', 4: 'sm:grid-cols-2 xl:grid-cols-4' }\n// Numbers are small enough to sit two to a row on a phone; an odd last one sits alone at half width.\nconst statColumns = { 1: '', 2: 'grid-cols-2', 3: 'grid-cols-2 xl:grid-cols-3', 4: 'grid-cols-2 xl:grid-cols-4' }\nconst spans: Record<GridSpan, string> = { 1: '', 2: 'md:col-span-2', 3: 'md:col-span-2 xl:col-span-3', 4: 'sm:col-span-2 md:col-span-2 xl:col-span-4' }\n\nconst isStat = (child: LayoutChild) => typeof child === 'object' && !child.custom && child.type === 'Stat'\n\n/** Columns that collapse to one on a phone, or two when it holds only `Stat`s; a child's `span` makes it wider. */\nexport const GridBlock = ({ node, children, className }: BlockProps) => {\n const { columns: count = 2 } = propsOf<GridProps>(node)\n const childNodes = node.children\n const stats = childNodes.length > 0 && childNodes.every(isStat)\n return (\n <div className={cn('grid grid-cols-1 gap-4', stats ? statColumns[count] : columns[count], className)}>\n {children.map((child, index) => {\n const element = childNodes[index]\n const span = typeof element === 'object' ? (element.props.span as GridSpan | undefined) : undefined\n return (\n <div key={index} className={cn('min-w-0', span && spans[span])}>\n {child}\n </div>\n )\n })}\n </div>\n )\n}\n","/** A fixed picture at `src`, as a plain `<img>` carrying the block's classes, at its `width` and `height` when given. */\nexport const FixedImage = ({ src, alt, width, height, className }: { src: string; alt?: string; width?: number; height?: number; className?: string }) => (\n <img src={src} alt={alt ?? ''} width={width} height={height} className={className ?? 'max-w-full'} />\n)\n","import type { Theme } from '../../../theme/theme-preference'\n\n/** How far apart the widths a block without its own `width` asks for are, so resizing the window refetches only now and then. */\nexport const widthStep = 100\n\n/**\n * The query an `Image` asks its function with: its own `width`, or the space it has rounded up to the next step, its\n * `height` when it has one, and the theme it is drawn in. `undefined` until the space it has is measured.\n */\nexport const imageQuery = ({ width, height, space, theme }: { width?: number; height?: number; space: number; theme: Theme }) => {\n const asked = width ?? Math.ceil(space / widthStep) * widthStep\n if (asked === 0) return\n return { width: String(asked), ...(height !== undefined && { height: String(height) }), theme }\n}\n\n/**\n * When the picture is asked for again: every `refresh` seconds, and never because the window regains focus or the block\n * mounts again, so without `refresh` each query is asked for once.\n */\nexport const imageRefetch = (refresh?: number) => ({\n staleTime: Infinity,\n refetchOnWindowFocus: false,\n ...(refresh !== undefined && { refetchInterval: refresh * 1000 }),\n})\n\n/** Whether a function's answer is a picture an `<img>` can draw: a `Blob` of an `image/*` type. */\nexport const isPicture = (answer: unknown): answer is Blob => answer instanceof Blob && answer.type.startsWith('image/')\n","import { keepPreviousData, useQuery } from '@tanstack/react-query'\nimport { useEffect, useState } from 'react'\nimport type { ImageProps } from '@protobase/layout'\nimport { useClient } from '../../../data/api-provider'\nimport { keys } from '../../../data/query-keys'\nimport { useElementWidth } from '../../../focus-page/use-element-width'\nimport { Skeleton } from '../../../primitives/skeleton'\nimport { useTheme } from '../../../theme/theme-provider'\nimport { cn } from '../../../lib/cn'\nimport { propsOf, type BlockProps } from './block-props'\nimport { FixedImage } from './fixed-image'\nimport { imageQuery, imageRefetch, isPicture } from './image-query'\n\n/** A URL the `<img>` loads a fetched picture from, given back to the browser once another replaces it or the block goes. */\nconst useObjectUrl = (blob: Blob | undefined) => {\n const [url, setUrl] = useState<string>()\n useEffect(() => {\n if (!blob) return setUrl(undefined)\n const next = URL.createObjectURL(blob)\n setUrl(next)\n return () => URL.revokeObjectURL(next)\n }, [blob])\n return url\n}\n\n/** Whether the browser failed to draw the picture at `url`, such as a damaged file; a new `url` is tried again. */\nconst useBroken = (url: string | undefined) => {\n const [broken, setBroken] = useState<string>()\n return [broken !== undefined && broken === url, () => setBroken(url)] as const\n}\n\n/**\n * The picture an API function draws, fetched with the reader's token at the block's size, or the width it has, and the\n * page's theme, again every `refresh` seconds. The previous picture stays while the next loads. A function that refuses\n * or answers no picture, also on a later request, or a picture the browser cannot draw, leaves its `alt`, or nothing.\n */\nconst FunctionImage = ({ name, alt, width, height, refresh, className }: { name: string; alt?: string; width?: number; height?: number; refresh?: number; className?: string }) => {\n const client = useClient()\n const { theme } = useTheme()\n const [ref, space] = useElementWidth()\n const query = imageQuery({ width, height, space, theme })\n const picture = useQuery({\n queryKey: keys.image(name, query ?? {}),\n enabled: query !== undefined,\n placeholderData: keepPreviousData,\n ...imageRefetch(refresh),\n queryFn: async () => {\n // The picture is the caller's own: the browser's HTTP cache keeps it from no later user of the browser.\n const answer = await client.invoke(name, { query, cache: 'no-store' })\n if (!isPicture(answer)) throw new Error(`The function \"${name}\" answered no picture`)\n return answer\n },\n })\n const url = useObjectUrl(picture.data)\n const [broken, markBroken] = useBroken(url)\n const size = { ...(width !== undefined && { width }), ...(height !== undefined && { height }) }\n return (\n <div ref={ref} className={cn('min-w-0', className)}>\n {picture.isError || broken ? (\n alt && <p className=\"text-muted-foreground\">{alt}</p>\n ) : url ? (\n <img src={url} alt={alt ?? ''} onError={markBroken} style={size} className={width === undefined ? 'w-full max-w-full object-contain' : 'max-w-full object-contain'} />\n ) : (\n <Skeleton className=\"w-full max-w-full\" style={{ height: height ?? 160, ...(width !== undefined && { width }) }} />\n )}\n </div>\n )\n}\n\n/** A fixed picture at `src`, or the one an API function draws. */\nexport const ImageBlock = ({ node, className }: BlockProps) => {\n const props = propsOf<ImageProps>(node)\n if (props.src !== undefined) return <FixedImage src={props.src} alt={props.alt} width={props.width} height={props.height} className={className} />\n return <FunctionImage name={props.function} alt={props.alt} width={props.width} height={props.height} refresh={props.refresh} className={className} />\n}\n","import type { ReactNode } from 'react'\nimport { booleanFieldText, dateFieldText, isEmptyFieldValue, numberFieldText, safeFieldUrl, textFieldText, type BooleanFieldProps, type DateFieldProps, type InlineFieldProps, type NumberFieldProps, type UrlFieldProps } from '@protobase/layout'\nimport { enumLabel, type FieldModel, type FieldViewModel } from '@protobase/schema'\nimport { formatRelativeTime } from '../../../format/date'\nimport { formatTag } from '../../../locale/active-locale'\nimport { text as message } from '../../../live/messages'\nimport { Skeleton } from '../../../primitives/skeleton'\nimport { TrueMark } from '../../../primitives/true-mark'\nimport { useAdminMeta } from '../../meta-gate'\nimport { ValueBadge } from '../../value-badge'\nimport { useScopedPathValue } from '../use-path-value'\nimport { propsOf, type BlockProps } from './block-props'\n\n// React-admin's field components: one value of the records around them, inline, formatted as react-admin formats it.\n\n// `field` is missing for an item of a JSON list, which no model describes\ntype Shown = { value: unknown; field: FieldModel | undefined; hints: FieldViewModel | undefined; props: InlineFieldProps }\n\n/** A field component: its value drawn by `show`, `emptyText` when empty, and nothing while there is no value to read. */\nconst inlineField = (show: (shown: Shown) => ReactNode) =>\n function InlineFieldBlock({ node, className }: BlockProps) {\n const props = propsOf<InlineFieldProps>(node)\n const { views } = useAdminMeta()\n const read = useScopedPathValue(props.source)\n if (read.state === 'missing') return null\n if (read.state === 'loading') return <Skeleton className=\"inline-block h-3 w-16 align-middle\" />\n if (isEmptyFieldValue(node.type, read.value)) return props.emptyText ? <span className={className}>{props.emptyText}</span> : null\n if (read.state === 'plain') return <span className={className}>{show({ value: read.value, field: undefined, hints: undefined, props })}</span>\n return <span className={className}>{show({ value: read.value, field: read.field, hints: views[read.model.name]?.fields[read.field.name], props })}</span>\n }\n\n// An enum's value as its label, as everywhere else it is shown\nconst labelled = ({ value, field, hints }: Shown) => (field?.type === 'enum' && typeof value === 'string' ? enumLabel(value, hints?.valueLabels) : textFieldText(value))\n\nexport const TextFieldBlock = inlineField(labelled)\n\nexport const NumberFieldBlock = inlineField(({ value, props }) => <span className=\"tabular-nums\">{numberFieldText(value, props as NumberFieldProps, formatTag())}</span>)\n\nexport const DateFieldBlock = inlineField(({ value, props }) => {\n const shown = dateFieldText(value, props as DateFieldProps, { locale: formatTag(), now: Date.now(), relative: formatRelativeTime })\n return <time dateTime={String(value)}>{shown}</time>\n})\n\nexport const BooleanFieldBlock = inlineField(({ value, props }) => {\n const words = booleanFieldText(value as boolean, props as BooleanFieldProps, { yes: message('yes'), no: message('no') })\n return value ? <TrueMark label={words} className=\"align-middle\" /> : <span className=\"text-faint-foreground\">{words}</span>\n})\n\n// An address that could run code shows as text, not as a link\nexport const UrlFieldBlock = inlineField(({ value, props }) => {\n const url = String(value)\n const shown = (props as UrlFieldProps).content ?? url\n const safe = safeFieldUrl(url)\n if (safe === undefined) return shown\n return (\n <a href={safe} className=\"font-medium text-primary-text hover:underline\" {...(/^https?:/i.test(safe) && { target: '_blank', rel: 'noreferrer' })}>\n {shown}\n </a>\n )\n})\n\nexport const ChipFieldBlock = inlineField((shown) => (\n <ValueBadge value={shown.value} hints={shown.hints}>\n {labelled(shown)}\n </ValueBadge>\n))\n","import type { LinkProps } from '@protobase/layout'\nimport { appPath } from '@protobase/schema'\nimport { scopeLookup } from '@protobase/layout'\nimport { fillAddressFrom } from '@protobase/schema/internal'\nimport { AppLink } from '../../use-app-address'\nimport { usePageParamValues } from '../page-params'\nimport { useScopeStack, valueScopeOf } from '../record-scope'\nimport { cn } from '../../../lib/cn'\nimport { buttonClass } from '../../../primitives/button'\nimport { propsOf, type BlockProps } from './block-props'\n\nconst linkStyle = 'font-medium text-primary-text hover:underline'\n\n/**\n * `to` an address in the app, through the router, its `{{path}}`s filled from the records around it and the page's\n * parameters; an `href` (`mailto:`, `https:`) is an ordinary anchor. It shows its children, text and spans inline, else where it leads.\n */\nexport const LinkBlock = ({ node, children, className }: BlockProps) => {\n const props = propsOf<LinkProps>(node)\n const scope = { ...valueScopeOf(useScopeStack()), params: usePageParamValues() }\n // A button's look, to which classes add; otherwise classes of its own replace the link's look\n const style = props.variant ? cn(buttonClass({ variant: props.variant }), className) : (className ?? linkStyle)\n // Children that are only blank text show nothing, so the link shows where it leads instead\n const content = node.children.some((child) => typeof child !== 'string' || child.trim() !== '') ? children : undefined\n if (props.to) {\n const to = fillAddressFrom(props.to, scopeLookup(scope))\n return <AppLink to={to} className={style}>{content ?? appPath(to)}</AppLink>\n }\n const href = props.href ?? ''\n return <a href={href} className={style} {...(href.startsWith('http') && { target: '_blank', rel: 'noreferrer' })}>{content ?? href}</a>\n}\n","import type { ResourceModel } from '@protobase/schema'\nimport { differs, toDraft, toPatchValue } from '../../../live/field-values'\nimport { isChosen, type Draft } from '../../create/create-values'\n\ntype Row = Record<string, unknown>\n\n/** The literal defaults of new records, or the stored record's values; relations as `{ key, label }` once chosen. */\nexport const startingDraft = (model: ResourceModel, fields: string[], stored: Row | undefined): Draft =>\n Object.fromEntries(\n fields.map((name) => {\n const field = model.fields[name]!\n if (field.type === 'file') return [name, stored?.[name] ?? null]\n if (stored) return [name, field.type === 'boolean' ? Boolean(stored[name]) : toDraft(stored[name])]\n const fallback = field.default && 'value' in field.default ? field.default.value : undefined\n return [name, field.type === 'boolean' ? Boolean(fallback) : toDraft(fallback)]\n }),\n )\n\n/** Changed fields only; a chosen relation sends its key. */\nexport const editBody = (model: ResourceModel, draft: Draft, stored: Row) =>\n Object.fromEntries(\n Object.entries(draft).flatMap(([name, value]) => {\n const field = model.fields[name]!\n if (isChosen(value)) return value.key === toDraft(stored[name]) ? [] : [[name, field.type === 'integer' ? Number(value.key) : value.key]]\n return differs(field, value, stored[name]) ? [[name, toPatchValue(field, value)]] : []\n }),\n )\n","import { useState, type ReactNode } from 'react'\nimport type { ProblemError } from '@protobase/client'\nimport type { ModalFormProps } from '@protobase/layout'\nimport type { ResourceModel } from '@protobase/schema'\nimport { useClient } from '../../../data/api-provider'\nimport { humanize } from '../../../live/naming'\nimport { Button } from '../../../primitives/button'\nimport { Dialog } from '../../../primitives/dialog'\nimport { Field } from '../../../record-view'\nimport { useToast } from '../../../toasts'\nimport { createBody, isChosen } from '../../create/create-values'\nimport { ErrorBanner } from '../../error-banner'\nimport { fieldErrors, fieldMessage } from '../../field-errors'\nimport { useFocusFirstInvalid } from '../../use-focus-first-invalid'\nimport { FieldEditor } from '../../field-editor'\nimport { useAdminMeta, usePermissions } from '../../meta-gate'\nimport { can } from '../../permissions'\nimport { useNavigationGuard } from '../../router'\nimport { useLayoutRecord, type LayoutRecord } from '../record-scope'\nimport { useFirstRecord, useRefreshResource } from '../use-layout-data'\nimport { propsOf, type BlockProps } from './block-props'\nimport { editBody, startingDraft } from './form-draft'\nimport { text } from '../messages'\n\ntype FormProps = Omit<ModalFormProps, 'resource' | 'recordKey'> & { model: ResourceModel; record: LayoutRecord | undefined; onClose: () => void }\n\nconst ModalFormDialog = ({ model, record, mode, label, title, fields, values, onClose }: FormProps) => {\n const { resources, views } = useAdminMeta()\n const client = useClient()\n const toast = useToast()\n const refresh = useRefreshResource()\n const view = views[model.name]\n const [draft, setDraft] = useState(() => startingDraft(model, fields, record?.record))\n const [errors, setErrors] = useState<Record<string, ProblemError>>({})\n // How many saves the server turned down for their fields\n const [rejections, setRejections] = useState(0)\n const formRef = useFocusFirstInvalid<HTMLFormElement>(rejections)\n const [failure, setFailure] = useState<unknown>()\n const [saving, setSaving] = useState(false)\n // What is typed in the dialog, or being saved, is gone when the page is left\n const [touched, setTouched] = useState(false)\n useNavigationGuard(touched || saving, 'input-lost')\n\n const submit = async () => {\n setSaving(true)\n setFailure(undefined)\n const saved =\n mode === 'create'\n ? client.create(model.name, { ...createBody(model, resources, draft), ...values })\n : client.update(model.name, record!.key, editBody(model, draft, record!.record), record!.etag ?? '*')\n await saved.then(\n async () => {\n await refresh(model.name)\n toast.show({ state: 'success', title: text('saved', { label: title ?? label }) })\n onClose()\n },\n (error: unknown) => {\n const found = fieldErrors(error)\n setErrors(found)\n if (Object.keys(found).length > 0) setRejections((count) => count + 1)\n setFailure(error)\n },\n )\n setSaving(false)\n }\n\n return (\n <Dialog\n title={title ?? label}\n onClose={onClose}\n actions={\n <>\n <Button onClick={onClose}>{text('cancel')}</Button>\n <Button variant=\"primary\" loading={saving} onClick={() => void submit()}>\n {mode === 'create' ? text('create') : text('save')}\n </Button>\n </>\n }\n >\n <form\n ref={formRef}\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 && <ErrorBanner title={text('notSaved')} error={failure} />}\n {fields.map((name) => {\n const field = model.fields[name]!\n const value = draft[name]\n const target = field.relation ? resources[field.relation.resource] : undefined\n const label = view?.fields[name]?.label ?? humanize(name)\n const problem = errors[name]\n return (\n <Field key={name} name={name} label={label} help={view?.fields[name]?.help} error={problem && fieldMessage(field, label, problem)}>\n <FieldEditor\n field={field}\n hints={view?.fields[name]}\n value={isChosen(value) ? value.key : value}\n stored={record?.record[name]}\n relationLabel={isChosen(value) ? value.label : undefined}\n relationPicker={target ? { target, view: views[target.name] } : undefined}\n invalid={Boolean(errors[name])}\n resource={model.name}\n onChange={(next) => {\n setErrors(({ [name]: _, ...rest }) => rest)\n setTouched(true)\n setDraft((current) => ({ ...current, [name]: next }))\n }}\n />\n </Field>\n )\n })}\n </form>\n </Dialog>\n )\n}\n\nconst KeyedRecord = ({ model, recordKey, children }: { model: ResourceModel; recordKey: string; children: (record: LayoutRecord | undefined) => ReactNode }) => {\n const record = useFirstRecord(model, { key: recordKey })\n return <>{children(record.data ?? undefined)}</>\n}\n\n/** A button that opens a form in a dialog: a new record of `resource`, or the record around it (or `recordKey`) to edit. */\nexport const ModalFormBlock = ({ node }: BlockProps) => {\n const props = propsOf<ModalFormProps>(node)\n const scope = useLayoutRecord()\n const { resources } = useAdminMeta()\n const model = resources[props.resource ?? scope?.model.name ?? '']\n const permissions = usePermissions(model?.name ?? '')\n const [open, setOpen] = useState(false)\n if (!model) return null\n const allowed = props.mode === 'create' ? can(permissions, 'create') : can(permissions, 'update') && scope?.permissions?.update !== false\n if (!allowed) return null\n const button = (record: LayoutRecord | undefined) => (\n <>\n <Button size=\"sm\" variant={props.variant ?? 'secondary'} disabled={props.mode === 'edit' && !record} onClick={() => setOpen(true)}>\n {props.label}\n </Button>\n {open && <ModalFormDialog {...props} model={model} record={props.mode === 'edit' ? record : undefined} onClose={() => setOpen(false)} />}\n </>\n )\n if (props.mode === 'edit' && props.recordKey !== undefined) return <KeyedRecord model={model} recordKey={props.recordKey}>{button}</KeyedRecord>\n return button(props.mode === 'edit' ? scope : undefined)\n}\n","import type { PageProps } from '@protobase/layout'\nimport { PageHeader } from '../../../app-shell'\nimport { cn } from '../../../lib/cn'\nimport { propsOf, type BlockProps } from './block-props'\n\nexport const PageBlock = ({ node, children, slots, className }: BlockProps) => {\n const { title, description, width } = propsOf<PageProps>(node)\n return (\n <div className={cn('flex-1', className)}>\n <div className={cn('flex flex-col gap-6 px-4 pb-16 pt-6 md:px-10 md:py-8', width !== 'full' && 'mx-auto max-w-[1200px]')}>\n <PageHeader title={title} subtitle={description} actions={slots.actions} />\n {children}\n </div>\n </div>\n )\n}\n","import type { ProgressProps } from '@protobase/layout'\nimport { Skeleton } from '../../../primitives/skeleton'\nimport { frameFor, useScopeStack } from '../record-scope'\nimport { usePathValue } from '../use-path-value'\nimport { cn } from '../../../lib/cn'\nimport { propsOf, type BlockProps } from './block-props'\nimport { formatTag } from '../../../locale/active-locale'\n\n/** A number as given, or the number in a field of the records around it. */\nconst useAmount = (amount: number | string | undefined, fallback: number) => {\n const stack = useScopeStack()\n const at = typeof amount === 'string' ? frameFor(stack, amount) : undefined\n const value = usePathValue(at && 'frame' in at ? at.frame : undefined, at && 'path' in at ? at.path : '')\n if (typeof amount === 'number') return amount\n if (amount === undefined) return fallback\n if (at && 'item' in at) return Number(at.item)\n if (value.state === 'ready') return Number(value.value)\n return value.state === 'loading' ? undefined : Number.NaN\n}\n\n/** A bar for `value` out of `max` (100 by default), with the numbers beside the label. */\nexport const ProgressBlock = ({ node, className }: BlockProps) => {\n const { value, max, label } = propsOf<ProgressProps>(node)\n const current = useAmount(value, 0)\n const total = useAmount(max, 100)\n if (current === undefined || total === undefined) return <Skeleton className=\"h-6 w-full\" />\n if (!Number.isFinite(current) || !Number.isFinite(total)) return null\n const share = total > 0 ? Math.min(1, Math.max(0, current / total)) : 0\n return (\n <div className={cn('min-w-0', className)}>\n <div className=\"flex items-baseline justify-between gap-2 text-body\">\n <span className=\"text-muted-foreground\">{label}</span>\n <span className=\"tabular-nums\">\n {current.toLocaleString(formatTag())} / {total.toLocaleString(formatTag())}\n </span>\n </div>\n <div role=\"progressbar\" aria-label={label} aria-valuenow={current} aria-valuemin={0} aria-valuemax={total} className=\"mt-1.5 h-2 overflow-hidden rounded-full bg-muted\">\n <div className={share >= 0.9 ? 'h-full rounded-full bg-warning' : 'h-full rounded-full bg-primary'} style={{ width: `${share * 100}%` }} />\n </div>\n </div>\n )\n}\n","import type { ReactNode } from 'react'\nimport type { RecordCardProps } from '@protobase/layout'\nimport type { ResourceModel } from '@protobase/schema'\nimport { Skeleton } from '../../../primitives/skeleton'\nimport { ErrorBanner } from '../../error-banner'\nimport { useAdminMeta } from '../../meta-gate'\nimport { RecordScope } from '../record-scope'\nimport { usePlanned } from '../plan-reads'\nimport { plannedRecord, useFirstRecord } from '../use-layout-data'\nimport { cn } from '../../../lib/cn'\nimport { propsOf, type BlockProps } from './block-props'\nimport { CardFrame, Quiet } from './card-frame'\nimport { text } from '../messages'\n\ntype LoadedProps = Omit<RecordCardProps, 'resource' | 'actions' | 'children'> & { model: ResourceModel; at?: string; actions: ReactNode; children: ReactNode[]; className?: string }\n\nconst LoadedRecordCard = ({ model, at, filter, sort, recordKey, title, description, empty, actions, children, className }: LoadedProps) => {\n const planned = usePlanned(at)\n const own = useFirstRecord(model, { filter, sort, key: recordKey, enabled: !planned })\n const record = planned ? plannedRecord(model, planned) : own\n const scoped = (content: ReactNode) => (record.data ? <RecordScope value={record.data}>{content}</RecordScope> : undefined)\n const body = record.isPending ? (\n <div className=\"flex flex-col gap-2\">\n <Skeleton className=\"h-4 w-1/2\" />\n <Skeleton className=\"h-4 w-1/3\" />\n </div>\n ) : record.error ? (\n <ErrorBanner title={text('couldNotLoad')} error={record.error} />\n ) : record.data ? (\n scoped(<div className=\"flex flex-col gap-3\">{children}</div>)\n ) : (\n <Quiet>{empty ?? text('nothingYet')}</Quiet>\n )\n return (\n <CardFrame title={title} description={description} actions={actions ? scoped(actions) : undefined} className={cn('h-full', className)}>\n {body}\n </CardFrame>\n )\n}\n\n/** One record, the one `recordKey` names or the first match: its Fields, Actions and forms inside, actions in the header. */\nexport const RecordCardBlock = ({ node, at, children, slots, className }: BlockProps) => {\n const { resource, filter, sort, recordKey, title, description, empty } = propsOf<RecordCardProps>(node)\n const model = useAdminMeta().resources[resource]\n if (!model) return null\n return (\n <LoadedRecordCard model={model} {...(at !== undefined && { at })} filter={filter} sort={sort} recordKey={recordKey} title={title} description={description} empty={empty} actions={slots.actions} className={className}>\n {children}\n </LoadedRecordCard>\n )\n}\n","import { messages } from '../../locale/messages'\n\nexport const text = messages('app/related-cards')\n","import { useLayoutEffect, useRef, useState, type ReactNode } from 'react'\nimport { Button } from '../../primitives/button'\nimport { cn } from '../../lib/cn'\nimport { text } from './messages'\n\n/**\n * Its content cut off at a few lines' height with \"Show more\" under it when it is taller, which shows it all; the cut\n * hides the rest rather than scrolling it, so the page keeps its one scrollbar.\n */\nexport const Clamped = ({ children }: { children: ReactNode }) => {\n const content = useRef<HTMLDivElement>(null)\n const [open, setOpen] = useState(false)\n const [taller, setTaller] = useState(false)\n // Markdown renders once its renderer loads, so the height is measured again whenever the content resizes, and on closing\n useLayoutEffect(() => {\n const box = content.current\n if (!box) return\n const measure = () => setTaller(box.scrollHeight > box.parentElement!.clientHeight + 1)\n measure()\n const observer = new ResizeObserver(measure)\n observer.observe(box)\n return () => observer.disconnect()\n }, [open])\n return (\n <div className=\"flex flex-col items-start gap-1\">\n <div className={cn('w-full min-w-0', !open && 'max-h-40 overflow-hidden')}>\n <div ref={content}>{children}</div>\n </div>\n {(taller || open) && (\n <Button size=\"sm\" variant=\"ghost\" className=\"-ml-2\" aria-expanded={open} onClick={() => setOpen(!open)}>\n {open ? text('showLess') : text('showMore')}\n </Button>\n )}\n </div>\n )\n}\n","import { Skeleton } from '../../primitives/skeleton'\nimport { useAdminMeta } from '../meta-gate'\nimport { fieldLabel } from '../pages/blocks/field'\nimport { FieldValue } from '../pages/field-value'\nimport type { LayoutRecord } from '../pages/record-scope'\nimport { usePathValue } from '../pages/use-path-value'\nimport { Clamped } from './clamped'\n\nconst isEmpty = (value: unknown) => value === null || value === undefined || value === ''\n\n/**\n * A field of a related record, through relations too, under its label unless `labelled` is false; `clamped` shows a\n * long value's first lines. A field without a value is left off, so only what the record says shows.\n */\nexport const RelatedField = ({ scope, path, labelled = true, clamped = false }: { scope: LayoutRecord; path: string; labelled?: boolean; clamped?: boolean }) => {\n const { views } = useAdminMeta()\n const value = usePathValue(scope, path)\n if (value.state === 'missing') return null\n if (value.state === 'ready' && isEmpty(value.value)) return null\n const shown = value.state === 'loading' ? <Skeleton className=\"h-4 w-24\" /> : <FieldValue model={value.model} field={value.field} value={value.value} />\n const body = clamped ? <Clamped>{shown}</Clamped> : shown\n if (!labelled) return <div className=\"min-w-0\">{body}</div>\n const label = fieldLabel(path, value.state === 'ready' ? views[value.model.name]?.fields[value.field.name]?.label : undefined)\n return (\n <div className=\"min-w-0\">\n <dt className=\"text-body text-muted-foreground\">{label}</dt>\n <dd className=\"mt-0.5\">{body}</dd>\n </div>\n )\n}\n","import type { RowButtonModel, ViewModel } from '@protobase/schema'\nimport { recordKey } from '../../live/model-helpers'\nimport { cn } from '../../lib/cn'\nimport { ActionButton } from '../pages/blocks/action'\nimport { RecordScope, type LayoutRecord } from '../pages/record-scope'\nimport { useRecordTitle } from '../titles/record-titles'\nimport { useAdminMeta } from '../meta-gate'\nimport { RowButtonLink } from '../row-button/row-button-link'\nimport { AppLink } from '../use-app-address'\nimport { RelatedField } from './related-field'\nimport { ToneEdge } from './tone-edge'\n\ntype CompactCardProps = {\n scope: LayoutRecord\n view: ViewModel | undefined\n /** The values on the second line, inline without labels. */\n fields: string[]\n /** The date or timestamp field beside the title. */\n time?: string\n /** The enum field whose value colours the card's left edge. */\n tone?: string\n actions: string[]\n button?: RowButtonModel\n /** Hears an action that ran on the card, by its label, with the card's title. */\n onActed?: (action: string, title: string) => void\n}\n\n/**\n * A related record as a card of one or two lines: its title linking to its page and its `time` on the first, its\n * `fields` inline without labels, a dot between them, on the second, and its buttons beside both, or beside the second\n * where the card is narrow, as on a phone; its `tone` field colours its left edge.\n */\nexport const CompactCard = ({ scope, view, fields, time, tone, actions, button, onActed }: CompactCardProps) => {\n const titleOf = useRecordTitle()\n const { resources } = useAdminMeta()\n const title = titleOf(scope.model, view, scope.record, scope.key)\n const buttons = actions.length > 0 || button !== undefined\n // Without buttons the card is one column: a second, auto-sized one would take the values beside the title and squeeze it\n return (\n <li data-card={scope.key} className={cn('relative grid min-w-0 items-center gap-x-4 gap-y-1 rounded-lg border border-border bg-surface px-4 py-2.5', buttons ? 'grid-cols-[minmax(0,1fr)_auto]' : 'grid-cols-[minmax(0,1fr)]')}>\n {tone && <ToneEdge view={view} field={tone} record={scope.record} />}\n <div className={cn('flex min-w-0 items-baseline gap-2', buttons && 'col-span-2 sm:col-span-1')}>\n <AppLink to={{ kind: 'record', resource: scope.model.name, key: recordKey(scope.model, scope.record) }} className=\"line-clamp-2 min-w-0 font-medium [overflow-wrap:anywhere] text-primary-text hover:underline\">\n {title}\n </AppLink>\n {time && (\n <div className=\"ml-auto shrink-0 text-body whitespace-nowrap text-muted-foreground empty:hidden\">\n <RelatedField scope={scope} path={time} labelled={false} />\n </div>\n )}\n </div>\n {fields.length > 0 && (\n <div className=\"flex min-w-0 flex-wrap items-center gap-y-0.5 text-body text-muted-foreground\">\n {fields.map((path) => (\n <div key={path} className=\"flex max-w-full min-w-0 items-center whitespace-nowrap empty:hidden [&>div]:truncate [:not(:empty)~&]:before:mx-2 [:not(:empty)~&]:before:content-['·'_/_'']\">\n <RelatedField scope={scope} path={path} labelled={false} />\n </div>\n ))}\n </div>\n )}\n {buttons && (\n <RecordScope value={scope}>\n <div className=\"col-start-2 flex flex-wrap items-center justify-end gap-2 sm:row-span-2 sm:row-start-1\">\n {button && <RowButtonLink button={button} model={scope.model} view={view} record={scope.record} models={resources} />}\n {actions.map((name) => <ActionButton key={name} name={name} about={title} onRun={(label) => onActed?.(label, title)} />)}\n </div>\n </RecordScope>\n )}\n </li>\n )\n}\n","import type { RowButtonModel, ViewModel } from '@protobase/schema'\nimport { recordKey } from '../../live/model-helpers'\nimport { ActionButton } from '../pages/blocks/action'\nimport { RecordScope, type LayoutRecord } from '../pages/record-scope'\nimport { useRecordTitle } from '../titles/record-titles'\nimport { useAdminMeta } from '../meta-gate'\nimport { RowButtonLink } from '../row-button/row-button-link'\nimport { AppLink } from '../use-app-address'\nimport { RelatedField } from './related-field'\nimport { ToneEdge } from './tone-edge'\n\n/**\n * A related record as a card: its title linking to its page, its `fields` under their labels, the buttons of its\n * view's `actions`, run on it as everywhere else, and `button`, a link to the address its fields name; its `tone`\n * field colours its left edge. `onActed` hears an action that ran on it, by its label, with its title.\n */\nexport const RelatedCard = ({ scope, view, fields, tone, actions, button, onActed }: { scope: LayoutRecord; view: ViewModel | undefined; fields: string[]; tone?: string; actions: string[]; button?: RowButtonModel; onActed?: (action: string, title: string) => void }) => {\n const titleOf = useRecordTitle()\n const { resources } = useAdminMeta()\n const title = titleOf(scope.model, view, scope.record, scope.key)\n return (\n <li data-card={scope.key} className=\"relative flex min-w-0 flex-col gap-3 rounded-lg border border-border bg-surface p-4\">\n {tone && <ToneEdge view={view} field={tone} record={scope.record} />}\n <AppLink to={{ kind: 'record', resource: scope.model.name, key: recordKey(scope.model, scope.record) }} className=\"self-start font-medium text-primary-text hover:underline\">\n {title}\n </AppLink>\n {fields.length > 0 && (\n <dl className=\"flex flex-col gap-3\">\n {fields.map((path) => <RelatedField key={path} scope={scope} path={path} clamped />)}\n </dl>\n )}\n {(actions.length > 0 || button) && (\n <RecordScope value={scope}>\n <div className=\"flex flex-wrap items-center gap-2\">\n {button && <RowButtonLink button={button} model={scope.model} view={view} record={scope.record} models={resources} />}\n {actions.map((name) => <ActionButton key={name} name={name} about={title} onRun={(label) => onActed?.(label, title)} />)}\n </div>\n </RecordScope>\n )}\n </li>\n )\n}\n","type Control = { disabled?: boolean; getAttribute: (name: string) => string | null }\ntype Card<T extends Control> = { querySelectorAll: (selectors: string) => Iterable<T>; querySelector: (selectors: string) => T | null }\n\nconst enabled = (control: Control) => !control.disabled && control.getAttribute('aria-disabled') !== 'true'\n\n// A card's first action it can take, else its title's link: a disabled button takes no focus\nexport const firstControl = <T extends Control>(card: Card<T>) =>\n [...card.querySelectorAll('button')].find(enabled) ?? card.querySelector('a')\n","/**\n * The card to focus when the card `gone` has left a list of cards, the keys `before` and `after` in their order: the\n * first after it that is still there, else the last before it that is; none when no card is left.\n */\nexport const nextFocus = (before: string[], after: string[], gone: string) => {\n const at = before.indexOf(gone)\n const stays = (key: string) => after.includes(key)\n return before.slice(at + 1).find(stays) ?? before.slice(0, Math.max(at, 0)).findLast(stays)\n}\n","import { useEffect, useRef, useState } from 'react'\nimport { firstControl } from './first-control'\nimport { nextFocus } from './next-focus'\nimport { text } from './messages'\n\ntype Acted = { key: string; action: string; title: string }\n\n// The heading of the section the cards are in, focusable by script\nconst headingOf = (root: HTMLElement) => {\n const heading = root.closest('section')?.querySelector<HTMLElement>('h2')\n if (heading && !heading.hasAttribute('tabindex')) heading.tabIndex = -1\n return heading\n}\n\n/**\n * Where focus goes when an action takes its card out of the list, the cards' `keys` in their order: to the next card's\n * first enabled action, else the previous card's, else the section's heading, while the focus fell to the page with the\n * card; `announcement` then says it left. Cards carry their key in `data-card`, inside `root`; each tells `acted` once one of\n * its actions ran. A card that stays keeps the focus where it is. `keys` is a new list only when the cards reload.\n */\nexport const useLeavingFocus = (keys: string[]) => {\n const root = useRef<HTMLDivElement>(null)\n const shown = useRef({ current: keys, previous: keys })\n const pending = useRef<Acted>(undefined)\n const [announcement, setAnnouncement] = useState('')\n\n const settle = (acted: Acted, before: string[], after: string[]) => {\n pending.current = undefined\n if (after.includes(acted.key) || !root.current) return\n setAnnouncement(text('left', { action: acted.action, title: acted.title }))\n // Focus the person moved on with stays where it is\n if (document.activeElement && document.activeElement !== document.body) return\n const key = nextFocus(before, after, acted.key)\n const card = key === undefined ? undefined : root.current.querySelector(`[data-card=\"${CSS.escape(key)}\"]`)\n const target = card ? firstControl<HTMLElement>(card) : headingOf(root.current)\n target?.focus()\n }\n\n // The list reloads after the action ran, mostly once it told; the list it left is then the one before\n useEffect(() => {\n const before = shown.current.current\n shown.current = { current: keys, previous: before }\n if (pending.current) settle(pending.current, before, keys)\n }, [keys])\n\n const acted = (key: string, action: string, title: string) => {\n const { current, previous } = shown.current\n if (current.includes(key)) {\n pending.current = { key, action, title }\n return\n }\n settle({ key, action, title }, previous, current)\n }\n\n return { root, acted, announcement }\n}\n","import { ArrowRight } from 'lucide-react'\nimport { useMemo } from 'react'\nimport type { ResourceModel, RowButtonModel, ViewModel } from '@protobase/schema'\nimport { useIsXs } from '../../lib/use-media-query'\nimport { humanize } from '../../live/naming'\nimport { Skeleton } from '../../primitives/skeleton'\nimport { SnapRow } from '../../primitives/snap-row'\nimport { useSnapScroll } from '../../primitives/use-snap-scroll'\nimport { cutOffNote } from '../embedded-list/cut-off-note'\nimport { embeddedDisplay, viewAllAddress } from '../embedded-list/embedded-display'\nimport { text as listText } from '../embedded-list/messages'\nimport { ErrorBanner } from '../error-banner'\nimport { defaultOrderBy } from '../list-order'\nimport type { PlannedList } from '../embedded-list/planned-embedded-rows'\nimport { plannedCount } from '../pages/planned-count'\nimport { scopeOf, useCount, useListPage } from '../pages/use-layout-data'\nimport { AppLink } from '../use-app-address'\nimport { CompactCard } from './compact-card'\nimport { RelatedCard } from './related-card'\nimport { text } from './messages'\nimport { useLeavingFocus } from './use-leaving-focus'\n\ntype RelatedCardsProps = {\n model: ResourceModel\n view: ViewModel | undefined\n filter: string\n /** The order of the cards, the list's own when empty. */\n sort: string\n /** The fields each card shows. */\n fields: string[]\n /** The named actions of the view each card has buttons for. */\n actions: string[]\n /** A button on each card to an address the record's fields name. */\n button?: RowButtonModel\n limit: number\n /** The display of the list \"View all\" opens. */\n display: string | undefined\n empty?: string\n /** Each card's share of the width in one row that scrolls sideways, snapping each card to its left edge; stacked when omitted. */\n carousel?: number\n /** Cards of one or two lines, with this date or timestamp field beside the title, or `{}` for none. */\n compact?: { time?: string }\n /** The enum field whose value colours each card's left edge. */\n tone?: string\n /** Its records and how many match in all, from the page's planned reads, inside the records of another block. */\n planned?: PlannedList\n}\n\n// Compact cards are two lines high, a long title taking a third on a phone; three of them hold the room a\n// short list takes, so the page below barely moves when they load\nconst CardsSkeleton = ({ compact, limit }: { compact: boolean; limit: number }) => (\n <div className={compact ? 'flex flex-col gap-2' : 'flex flex-col gap-3'}>\n {Array.from({ length: compact ? Math.min(limit, 3) : 2 }, (_, index) => <Skeleton key={index} className={compact ? 'h-17.5 w-full max-sm:h-24' : 'h-24 w-full'} />)}\n </div>\n)\n\n/**\n * The first `limit` records of a list as cards stacked full width or in a `carousel`, each with its fields, its\n * actions' buttons and its row button, and a link to the whole list beside a note such as \"The first 10 of 37.\" when there are more.\n */\nexport const RelatedCards = ({ model, view, filter, sort, fields, actions, button, limit, display, empty, carousel, compact, tone, planned }: RelatedCardsProps) => {\n const xs = useIsXs()\n const scroll = useSnapScroll()\n const plural = view?.names?.plural ?? humanize(model.name)\n const orderBy = sort || defaultOrderBy(model, view)\n const own = useListPage(model, { filter, sort: orderBy, pageSize: limit, enabled: !planned })\n const ownCount = useCount(model, filter, !planned)\n const page = planned ? planned.rows : { isPending: own.isPending, error: own.error }\n const items = planned ? planned.rows.rows : own.data?.items\n const count = planned ? { data: planned.total && !planned.total.isPending && !planned.total.error ? plannedCount(planned.total) : undefined } : ownCount\n const scopes = useMemo(() => (items ?? []).map((row) => scopeOf(model, row)), [model, items])\n const keys = useMemo(() => scopes.map((scope) => scope.key), [scopes])\n const leaving = useLeavingFocus(keys)\n const content = () => {\n if (page.isPending) return <CardsSkeleton compact={Boolean(compact)} limit={limit} />\n if (page.error) return <ErrorBanner title={text('couldNotLoad')} error={page.error} />\n if (scopes.length === 0) return <p className=\"text-muted-foreground\">{empty ?? text('nothingYet')}</p>\n const cards = scopes.map((scope) => {\n const acted = (action: string, title: string) => leaving.acted(scope.key, action, title)\n if (compact) return <CompactCard key={scope.key} scope={scope} view={view} fields={fields} time={compact.time} tone={tone} actions={actions} button={button} onActed={acted} />\n return <RelatedCard key={scope.key} scope={scope} view={view} fields={fields} tone={tone} actions={actions} button={button} onActed={acted} />\n })\n const note = count.data === undefined ? undefined : cutOffNote(scopes.length, count.data, false)\n return (\n <div className=\"flex flex-col gap-3\">\n {carousel === undefined ? <ul className={compact ? 'flex flex-col gap-2' : 'flex flex-col gap-3'}>{cards}</ul> : (\n <SnapRow scroll={scroll} label={plural} share={carousel}>\n {cards}\n </SnapRow>\n )}\n <div className=\"flex flex-wrap items-center justify-between gap-2\">\n <p className=\"text-xs text-muted-foreground\">{note}</p>\n <AppLink to={viewAllAddress(model, view, xs, { filter, orderBy, display: embeddedDisplay(view, xs, { preferred: display }) })} className=\"flex items-center gap-1 font-medium text-primary-text hover:underline\">\n {listText('viewAll')} <span className=\"sr-only\">{plural.toLowerCase()}</span>\n <ArrowRight className=\"size-3.5\" aria-hidden />\n </AppLink>\n </div>\n </div>\n )\n }\n // The toast says an action is done; only the cards know when it took its card out of the list\n return (\n <div ref={leaving.root}>\n {content()}\n <p role=\"status\" className=\"sr-only\">{leaving.announcement}</p>\n </div>\n )\n}\n","import { useMemo } from 'react'\nimport { cardsLayoutOf, type CardWidth, type RecordCardsProps } from '@protobase/layout'\nimport { listColumnNames } from '../../../live/columns-from-model'\nimport { SectionContent } from '../../../record-view/section'\nimport { useAdminMeta } from '../../meta-gate'\nimport { RelatedCards } from '../../related-cards/related-cards'\nimport { cn } from '../../../lib/cn'\nimport { usePlannedReads } from '../plan-reads'\nimport { propsOf, type BlockProps } from './block-props'\n\nconst shares: Record<CardWidth, number> = { '1/4': 1 / 4, '1/3': 1 / 3, '1/2': 1 / 2, '2/3': 2 / 3 }\n\n/**\n * What a filter finds as the record page's related cards, stacked full width or in a row that scrolls sideways, under\n * a heading like a record page section's, with no card frame around them, so no card sits in another. Inside the\n * records of another block, its records and total per record come from the page's planned reads.\n */\nexport const RecordCardsBlock = ({ node, at, slots, className }: BlockProps) => {\n const props = propsOf<RecordCardsProps>(node)\n const { resource, filter = '', sort = '', fields, cardActions = [], limit = 10, display, title, description, empty } = props\n const { layout, cardWidth } = cardsLayoutOf(props)\n const { resources, views } = useAdminMeta()\n const [rows, total] = usePlannedReads([at, at === undefined ? undefined : `${at}#total`])\n const planned = useMemo(() => rows && { rows, total }, [rows, total])\n const model = resources[resource]\n if (!model) return null\n const view = views[model.name]\n return (\n <section className={cn('min-w-0', className)} aria-label={title}>\n <SectionContent title={title} help={description} actions={slots.actions}>\n <RelatedCards model={model} view={view} filter={filter} sort={sort} fields={fields ?? listColumnNames(model, view)} actions={cardActions} limit={limit} display={display} empty={empty} carousel={layout === 'carousel' ? shares[cardWidth] : undefined} {...(planned && { planned })} />\n </SectionContent>\n </section>\n )\n}\n","import type { ResourceModel, ViewModel } from '@protobase/schema'\nimport { humanize } from '../../live/naming'\nimport { Skeleton } from '../../primitives/skeleton'\nimport { listedResource } from '../current-address'\nimport { ErrorBanner } from '../error-banner'\nimport { useAdminMeta } from '../meta-gate'\nimport { savedScope } from '../saved/saved-records'\nimport { useSavedRecords } from '../saved/use-saved-records'\nimport { RecordRowBody, type RecordRowBodyProps } from './record-row-body'\nimport { text } from './messages'\n\ntype SavedRecordRowProps = Omit<RecordRowBodyProps, 'model' | 'view' | 'filter' | 'sort' | 'scope' | 'list'> & {\n /** The saved records' resource, such as favorites, and its view, whose `listOf` names what they point at. */\n model: ResourceModel\n view: ViewModel\n}\n\n/**\n * The records the user's saved ones of a view with `listOf` point at, such as the listings among their favorites, as a\n * row of their own resource's cards, with \"View all\" to the saved records' list. `empty` when there are none.\n */\nexport const SavedRecordRow = ({ model, view, empty, ...props }: SavedRecordRowProps) => {\n const { resources, views } = useAdminMeta()\n const listed = listedResource(resources, views, model.name)\n const saved = useSavedRecords(model.name, view.listOf!, true)\n const plural = (view.names?.plural ?? humanize(model.name)).toLowerCase()\n if (!listed.listOf) return null\n if (saved.error) return <ErrorBanner title={text('couldNotLoadYour', { plural })} error={saved.error} />\n if (!saved.data) return <Skeleton className=\"h-24\" />\n const scope = savedScope(listed.model!, saved.data)\n if (!scope) return <p className=\"text-muted-foreground\">{empty ?? text('noneYet', { plural })}</p>\n return <RecordRowBody {...props} model={listed.model!} view={listed.view} filter=\"\" scope={scope} list={model.name} empty={empty} />\n}\n","import type { ResourceModel, ViewModel } from '@protobase/schema'\nimport { encodeKey } from '@protobase/schema/internal'\nimport { recordKey } from '../../live/model-helpers'\nimport { humanize } from '../../live/naming'\nimport { Skeleton } from '../../primitives/skeleton'\nimport { ErrorBanner } from '../error-banner'\nimport { useAdminMeta } from '../meta-gate'\nimport { RecordRowBody } from '../record-row/record-row-body'\nimport { AppLink } from '../use-app-address'\nimport { InlineFilterChips } from './filter-chip-list'\nimport { useSavedSearches, type SavedSearchRow } from './use-saved-searches'\nimport { useSearchRow } from './use-search-row'\nimport { text } from './messages'\n\ntype SearchRowItemProps = { model: ResourceModel; view: ViewModel; target: ResourceModel; targetView: ViewModel | undefined; row: SavedSearchRow }\n\nconst SearchRowItem = ({ model, view, target, targetView, row }: SearchRowItemProps) => {\n const key = encodeKey(recordKey(model, row))\n const { name, chips, title, body } = useSearchRow({ model, of: view.searchesOf!, target, targetView, row, recordKey: key })\n return (\n <section aria-label={title} className=\"flex flex-col gap-3 py-4 first:pt-0 last:pb-0\">\n <h3 className=\"text-[0.9375rem] font-semibold\">\n <AppLink to={{ kind: 'record', resource: model.name, key }} className=\"hover:underline\">\n {name ?? <InlineFilterChips chips={chips} />}\n </AppLink>\n </h3>\n <RecordRowBody {...body} />\n </section>\n )\n}\n\n/**\n * The user's saved searches of a view with `searchesOf`, for a page: each with its name or filters, linking to it, over\n * the row of what it finds (`useSearchRow`), in the order of their list. `empty` when there are none.\n */\nexport const SavedSearchRows = ({ model, view, empty }: { model: ResourceModel; view: ViewModel; empty?: string }) => {\n const { resources, views } = useAdminMeta()\n const of = view.searchesOf!\n const target = resources[of.resource]\n const saved = useSavedSearches(model.name, true)\n const plural = (view.names?.plural ?? humanize(model.name)).toLowerCase()\n if (!target) return null\n if (saved.error) return <ErrorBanner title={text('couldNotLoadYour', { plural })} error={saved.error} />\n if (!saved.data) return <Skeleton className=\"h-40\" />\n if (saved.data.length === 0) return <p className=\"text-muted-foreground\">{empty ?? text('noneYet', { plural })}</p>\n return (\n <div className=\"flex flex-col divide-y\">\n {saved.data.map((row) => (\n <SearchRowItem key={encodeKey(recordKey(model, row))} model={model} view={view} target={target} targetView={views[of.resource]} row={row} />\n ))}\n </div>\n )\n}\n","import type { RecordRowProps } from '@protobase/layout'\nimport { useAdminMeta } from '../../meta-gate'\nimport { RecordRowBody } from '../../record-row/record-row-body'\nimport { SavedRecordRow } from '../../record-row/saved-record-row'\nimport { SavedSearchRows } from '../../searches/saved-search-rows'\nimport { propsOf, type BlockProps } from './block-props'\nimport { CardFrame } from './card-frame'\n\n/**\n * What a filter finds: its chips, the count, its records as a sideways row of their list's cards, and \"View all\". Of a\n * resource whose view has `listOf`, the records the user's saved ones point at; of one with `searchesOf`, a row per\n * saved search of the user's.\n */\nexport const RecordRowBlock = ({ node, slots, className }: BlockProps) => {\n const { resource, filter = '', sort, limit, display, title, description, empty } = propsOf<RecordRowProps>(node)\n const { resources, views } = useAdminMeta()\n const model = resources[resource]\n if (!model) return null\n const view = views[model.name]\n const body = () => {\n if (view?.searchesOf) return <SavedSearchRows model={model} view={view} empty={empty} />\n if (view?.listOf !== undefined) return <SavedRecordRow model={model} view={view} limit={limit} display={display} empty={empty} />\n return <RecordRowBody model={model} view={view} filter={filter} sort={sort} limit={limit} display={display} empty={empty} />\n }\n return (\n <CardFrame title={title} description={description} actions={slots.actions} className={className}>\n {body()}\n </CardFrame>\n )\n}\n","import { useRef, useState } from 'react'\nimport type { ProblemError } from '@protobase/client'\nimport type { SettingsProps, Styled } from '@protobase/layout'\nimport type { FieldModel, ResourceModel } from '@protobase/schema'\nimport { useClient } from '../../../data/api-provider'\nimport { differs } from '../../../live/field-values'\nimport { humanize } from '../../../live/naming'\nimport { Button } from '../../../primitives/button'\nimport { Skeleton } from '../../../primitives/skeleton'\nimport { Field } from '../../../record-view'\nimport { useToast } from '../../../toasts'\nimport { createBody, type Draft } from '../../create/create-values'\nimport { ErrorBanner } from '../../error-banner'\nimport { fieldErrors, fieldMessage } from '../../field-errors'\nimport { FieldEditor } from '../../field-editor'\nimport { useAdminMeta, usePermissions } from '../../meta-gate'\nimport { can } from '../../permissions'\nimport type { LayoutRecord } from '../record-scope'\nimport { scopeOf, useFirstRecord, useRefreshResource } from '../use-layout-data'\nimport { cn } from '../../../lib/cn'\nimport { propsOf, type BlockProps } from './block-props'\nimport { CardFrame } from './card-frame'\nimport { editBody, startingDraft } from './form-draft'\nimport { text } from '../messages'\n\ntype FormProps = Omit<SettingsProps, 'resource' | 'fields'> & { model: ResourceModel; fields: string[]; stored: LayoutRecord | undefined; className?: string }\n\n/** A switch or a choice saves as soon as it changes; what is typed waits for Save. */\nexport const savesAtOnce = (field: FieldModel) => field.type === 'boolean' || field.type === 'enum'\n\nconst SettingsForm = ({ model, fields, title, description, stored: loaded, className }: FormProps) => {\n const { resources, views } = useAdminMeta()\n const permissions = usePermissions(model.name)\n const client = useClient()\n const toast = useToast()\n const refresh = useRefreshResource()\n const view = views[model.name]\n const [stored, setStored] = useState(loaded)\n const [draft, setDraft] = useState(() => startingDraft(model, fields, loaded?.record))\n const [errors, setErrors] = useState<Record<string, ProblemError>>({})\n const [failure, setFailure] = useState<unknown>()\n const [saving, setSaving] = useState(false)\n // One save at a time, each from the record the one before wrote, so a quick second change updates rather than creates\n const queue = useRef<Promise<unknown>>(Promise.resolve())\n const latest = useRef(loaded)\n\n const defaults = startingDraft(model, fields, undefined)\n const writable = stored ? can(permissions, 'update') && stored.permissions?.update !== false : can(permissions, 'create')\n const typed = fields.filter((name) => !savesAtOnce(model.fields[name]!))\n const unsaved = typed.some((name) => (stored ? differs(model.fields[name]!, draft[name], stored.record[name]) : draft[name] !== defaults[name]))\n\n const write = async (changes: Draft) => {\n const current = latest.current\n if (current) {\n const saved = await client.update(model.name, current.key, editBody(model, changes, current.record), current.etag ?? '*')\n return { ...scopeOf(model, saved.record), etag: saved.etag, permissions: saved.permissions ?? current.permissions }\n }\n // The first save creates the record with every value shown, the server making the caller its owner\n const created = await client.create(model.name, createBody(model, resources, { ...defaults, ...changes }))\n return { ...scopeOf(model, created.record), etag: created.etag }\n }\n\n const save = (changes: Draft) => {\n const run = queue.current.then(async () => {\n setSaving(true)\n setFailure(undefined)\n await write(changes).then(\n async (record) => {\n latest.current = record\n setStored(record)\n setErrors((current) => Object.fromEntries(Object.entries(current).filter(([name]) => !Object.hasOwn(changes, name))))\n await refresh(model.name)\n toast.show({ state: 'success', title: text('saved', { label: title ?? text('settings') }) })\n },\n (error: unknown) => {\n setErrors((current) => ({ ...current, ...fieldErrors(error) }))\n setFailure(error)\n },\n )\n setSaving(false)\n })\n queue.current = run\n }\n\n const change = (name: string, next: unknown) => {\n setDraft((current) => ({ ...current, [name]: next }))\n if (savesAtOnce(model.fields[name]!)) save({ [name]: next })\n }\n\n return (\n <CardFrame title={title} description={description} className={cn('h-full', className)}>\n <form\n className=\"flex flex-col gap-4\"\n onSubmit={(event) => {\n event.preventDefault()\n if (unsaved) save(Object.fromEntries(typed.map((name) => [name, draft[name]])))\n }}\n >\n {failure !== undefined && Object.keys(errors).length === 0 && <ErrorBanner title={text('notSaved')} error={failure} />}\n {fields.map((name) => {\n const field = model.fields[name]!\n const label = view?.fields[name]?.label ?? humanize(name)\n const problem = errors[name]\n return (\n <Field key={name} name={name} label={label} help={view?.fields[name]?.help} error={problem && fieldMessage(field, label, problem)}>\n <FieldEditor\n field={field}\n hints={view?.fields[name]}\n value={draft[name]}\n stored={stored?.record[name] ?? defaults[name]}\n invalid={Boolean(problem)}\n locked={!writable || field.readOnly}\n resource={model.name}\n onChange={(next) => change(name, next)}\n />\n </Field>\n )\n })}\n {writable && unsaved && (\n <div>\n <Button type=\"submit\" variant=\"primary\" size=\"sm\" loading={saving}>\n {text('save')}\n </Button>\n </div>\n )}\n </form>\n </CardFrame>\n )\n}\n\nconst LoadedSettings = (props: FormProps) => {\n const record = useFirstRecord(props.model, {})\n if (record.isPending) {\n return (\n <CardFrame title={props.title} description={props.description} className={props.className}>\n <div className=\"flex flex-col gap-2\">\n <Skeleton className=\"h-4 w-1/2\" />\n <Skeleton className=\"h-4 w-1/3\" />\n </div>\n </CardFrame>\n )\n }\n if (record.error) {\n return (\n <CardFrame title={props.title} description={props.description} className={props.className}>\n <ErrorBanner title={text('couldNotLoad')} error={record.error} />\n </CardFrame>\n )\n }\n return <SettingsForm {...props} stored={record.data ?? undefined} />\n}\n\n/**\n * The signed-in person's own record of a resource as settings: each field as a control, a switch or a choice saving as\n * it changes and typed values with Save, the defaults shown until the first save creates the record. The server keeps\n * every caller to their own record, so the list holds at most theirs.\n */\nexport const SettingsBlock = ({ node, className }: BlockProps) => {\n const { resource, fields = [], className: _className, ...rest } = propsOf<SettingsProps & Styled>(node)\n const model = useAdminMeta().resources[resource]\n if (!model) return null\n return <LoadedSettings {...rest} model={model} fields={fields.filter((name) => Object.hasOwn(model.fields, name))} stored={undefined} className={className} />\n}\n","import { useQueries } from '@tanstack/react-query'\nimport { useMemo } from 'react'\nimport { countedResource, evaluateCondition, parseCondition } from '@protobase/layout'\nimport { useClient } from '../../data/api-provider'\nimport { useAdminMeta } from '../meta-gate'\nimport { frameFor, type LayoutRecord, type ScopeFrame } from './record-scope'\nimport { countQuery } from './use-layout-data'\nimport { usePathValues } from './use-path-value'\n\n/** Whether each condition holds for the record around it (`scope`), as `useStackConditions` says. */\nexport const useConditions = (whens: string[], scope: LayoutRecord | undefined): Array<boolean | undefined> => useStackConditions(whens, scope ? [scope] : [])\n\n/**\n * Whether each condition holds for the records around it (`stack`, outermost first): `undefined` while a value it reads\n * loads, `false` when it does not parse. A name reads from the nearest record that has that field, followed through\n * relations; `<resource>.count` counts records. All conditions share one set of queries, so the hook count never\n * changes with the conditions.\n */\nexport const useStackConditions = (whens: string[], stack: readonly ScopeFrame[]): Array<boolean | undefined> => {\n const { resources } = useAdminMeta()\n const client = useClient()\n const key = JSON.stringify(whens)\n const parsed = useMemo(() => (JSON.parse(key) as string[]).map(parseCondition), [key])\n const isField = (name: string) => stack.some((frame) => ('item' in frame ? typeof frame.item === 'object' && frame.item !== null && Object.hasOwn(frame.item, name) : Object.hasOwn(frame.model.fields, name)))\n const paths = [...new Set(parsed.flatMap((condition) => (condition.ok ? condition.paths : [])))]\n const counted = new Map(paths.flatMap((path) => {\n const resource = countedResource(path, isField)\n return resource === undefined ? [] : [[path, resource] as const]\n }))\n const fieldPaths = paths.filter((path) => !counted.has(path))\n const countedModels = [...new Set(counted.values())].flatMap((resource) => (resources[resource] ? [resources[resource]!] : []))\n const sources = fieldPaths.map((path) => frameFor(stack, path))\n const fields = usePathValues(fieldPaths.map((path, index) => {\n const at = sources[index]\n return at && 'frame' in at ? { scope: at.frame, path: at.path } : { scope: undefined, path }\n }))\n const counts = useQueries({ queries: countedModels.map((model) => countQuery(client, model)) })\n\n return parsed.map((condition) => {\n if (!condition.ok) return false\n const values: Record<string, unknown> = {}\n for (const path of condition.paths) {\n const resource = counted.get(path)\n if (resource === undefined) {\n const index = fieldPaths.indexOf(path)\n const at = sources[index]\n if (at && 'item' in at) {\n values[path] = at.item\n continue\n }\n const value = fields[index]!\n if (value.state === 'loading') return undefined\n if (value.state === 'ready') values[path] = value.value\n continue\n }\n // A resource the caller cannot see has no query and counts as zero.\n const index = countedModels.findIndex((model) => model.name === resource)\n if (index === -1) values[path] = 0\n else if (counts[index]!.isPending) return undefined\n else values[path] = counts[index]!.data ?? 0\n }\n return evaluateCondition(condition, values)\n })\n}\n","import type { ReactNode } from 'react'\nimport { type ShowProps } from '@protobase/layout'\nimport { useScopeStack } from '../record-scope'\nimport { useStackConditions } from '../use-conditions'\nimport { propsOf, type BlockProps } from './block-props'\n\n/** A `fallback` as it draws: text as it is, elements as they were rendered into the slot of that name. */\nexport const fallbackOf = (node: BlockProps['node'], slots: BlockProps['slots']): ReactNode => (typeof node.props.fallback === 'string' ? node.props.fallback : slots.fallback)\n\n/**\n * Its children while `when` holds, else its `fallback`, as SolidJS's `<Show>`: fields of the records around it, and\n * `<resource>.count` for any resource. Nothing while a value the condition reads loads.\n */\nexport const ShowBlock = ({ node, children, slots, className }: BlockProps) => {\n const { when } = propsOf<ShowProps>(node)\n const [shown] = useStackConditions([when], useScopeStack())\n if (shown === undefined) return null\n const drawn = shown ? children : fallbackOf(node, slots)\n if (drawn === undefined || drawn === null) return null\n // Its classes go on an element around what it draws, and on nothing while it draws nothing\n return className === undefined ? <>{drawn}</> : <div className={className}>{drawn}</div>\n}\n","import { fillProps, type LayoutNode } from '@protobase/layout'\nimport { useScopeStack, valueScopeOf, type ScopeFrame } from '../record-scope'\nimport { useStackConditions } from '../use-conditions'\nimport type { BlockProps } from './block-props'\nimport { fallbackOf } from './show'\n\n/**\n * The `when` of each `Match`, its `{{path}}`s filled from the records around the Switch as each Match fills its own when\n * it draws. The structure check lets a Switch hold Matches only, each one rendered child.\n */\nexport const matchConditions = (children: LayoutNode['children'], stack: readonly ScopeFrame[]) =>\n children.flatMap((child) => (typeof child === 'string' ? [] : [String(fillProps(child, valueScopeOf(stack)).props.when)]))\n\n/**\n * Its first `Match` whose `when` holds, else its `fallback`, as SolidJS's `<Switch>`; nothing while a value an earlier\n * `Match` reads loads, so a later one never shows first.\n */\nexport const SwitchBlock = ({ node, children, slots, className }: BlockProps) => {\n const stack = useScopeStack()\n const held = useStackConditions(matchConditions(node.children, stack), stack)\n const drawn = held.findIndex((holds) => holds !== false)\n if (drawn !== -1 && held[drawn] === undefined) return null\n const shown = drawn === -1 ? fallbackOf(node, slots) : children[drawn]\n if (shown === undefined || shown === null) return null\n return className === undefined ? <>{shown}</> : <div className={className}>{shown}</div>\n}\n\n/** One branch of a `Switch`, which decides whether it is drawn. */\nexport const MatchBlock = ({ children }: BlockProps) => <>{children}</>\n","import type { StatProps } from '@protobase/layout'\nimport type { ResourceModel } from '@protobase/schema'\nimport { Skeleton } from '../../../primitives/skeleton'\nimport { useAdminMeta } from '../../meta-gate'\nimport { filteredListAddress } from '../../list-link'\nimport { AppLink } from '../../use-app-address'\nimport { FieldValue } from '../field-value'\nimport { usePlanned } from '../plan-reads'\nimport { plannedCount } from '../planned-count'\nimport { useCount } from '../use-layout-data'\nimport { useScopedPathValue } from '../use-path-value'\nimport { cn } from '../../../lib/cn'\nimport { plainText } from './plain-value'\nimport { propsOf, type BlockProps } from './block-props'\nimport { CardFrame } from './card-frame'\nimport { formatTag } from '../../../locale/active-locale'\nimport { text } from '../messages'\n\nconst big = 'text-2xl font-semibold tracking-tight tabular-nums'\n\nconst Count = ({ model, at, filter }: { model: ResourceModel; at?: string; filter?: string }) => {\n const { views } = useAdminMeta()\n const planned = usePlanned(at)\n const own = useCount(model, filter, !planned)\n const count = planned ?? own\n if (count.isPending) return <Skeleton className=\"h-8 w-16\" />\n if (count.error) return <span className=\"text-danger-text\">{text('couldNotCount')}</span>\n const total = planned ? plannedCount(planned) : own.data!\n return (\n <AppLink to={filteredListAddress(views[model.name], model.name, filter)} className={`${big} hover:text-primary-text after:absolute after:inset-0 after:content-['']`}>\n {total.toLocaleString(formatTag())}\n </AppLink>\n )\n}\n\nconst RecordValue = ({ field, format }: { field: string; format: StatProps['format'] }) => {\n const value = useScopedPathValue(field)\n if (value.state === 'loading') return <Skeleton className=\"h-8 w-16\" />\n if (value.state === 'missing') return null\n if (value.state === 'plain') return <span className={big}>{plainText(value.value)}</span>\n return (\n <span className={big}>\n <FieldValue model={value.model} field={value.field} value={value.value} format={format} />\n </span>\n )\n}\n\n/**\n * One number or value with a label: fixed, a count of matching records (linking to them from anywhere on the card), or\n * a field of the record. A label that wraps pushes nothing out of line: the value sits at the card's bottom.\n */\nexport const StatBlock = ({ node, at, className }: BlockProps) => {\n const { label, value, resource, filter, field, format, description } = propsOf<StatProps>(node)\n const { resources } = useAdminMeta()\n const model = resource === undefined ? undefined : resources[resource]\n return (\n <CardFrame className={cn('relative h-full', className)} bodyClassName=\"flex flex-col\">\n <p className=\"text-muted-foreground break-words\">{label}</p>\n <div className=\"mt-auto pt-1\">\n {value !== undefined && <span className={big}>{value}</span>}\n {model && <Count model={model} {...(at !== undefined && { at })} filter={filter} />}\n {field !== undefined && <RecordValue field={field} format={format} />}\n </div>\n {description && <p className=\"mt-1 text-xs text-muted-foreground\">{description}</p>}\n </CardFrame>\n )\n}\n","import { useCallback, useState } from 'react'\nimport type { ViewModel } from '@protobase/schema'\nimport { useIsXs } from '../../lib/use-media-query'\nimport { embeddedDisplay, embeddedDisplayKey, readPickedDisplay, writePickedDisplay } from './embedded-display'\n\n/**\n * The display an embedded list shows and the way to pick another, which is kept in local storage for the viewer under\n * `place`, the list's place in the app.\n */\nexport const useEmbeddedDisplay = (view: ViewModel | undefined, place: string, preferred?: string) => {\n const xs = useIsXs()\n const key = embeddedDisplayKey(place)\n const [picked, setPicked] = useState(() => readPickedDisplay(localStorage, key))\n const pick = useCallback(\n (display: string) => {\n setPicked(display)\n writePickedDisplay(localStorage, key, display)\n },\n [key],\n )\n return [embeddedDisplay(view, xs, { picked, preferred }), pick] as const\n}\n","import { useMemo, type ReactNode } from 'react'\nimport { columnName, type TableProps } from '@protobase/layout'\nimport type { AppAddress, ResourceModel } from '@protobase/schema'\nimport { DataGrid } from '../../../data-grid'\nimport { useIsDesktop, useIsXs } from '../../../lib/use-media-query'\nimport { listColumnNames } from '../../../live/columns-from-model'\nimport { recordId } from '../../../live/model-helpers'\nimport type { RouteTarget } from '../../../primitives/route-link'\nimport { embeddedColumns } from '../../embedded-list/embedded-columns'\nimport { embeddedRowTargets } from '../../embedded-list/embedded-row-targets'\nimport { useAdminMeta, usePermissions } from '../../meta-gate'\nimport { can } from '../../permissions'\nimport { useProjectUi } from '../project-ui'\nimport { withRowButton } from '../../row-button/row-button-column'\nimport { useAppAddress } from '../../use-app-address'\nimport { useLayoutList } from '../layout-list'\nimport { CardFrame, Quiet } from './card-frame'\nimport { phoneSpecs } from './table-phone-columns'\nimport { text } from '../messages'\n\ntype Props = Pick<TableProps, 'columns' | 'button' | 'title' | 'description' | 'empty'> & { model: ResourceModel; items: readonly unknown[]; actions: ReactNode; className?: string }\n\n// The list page's table over records the list around it read, in the list's order: it reads nothing of its own\nconst LoadedListTable = ({ model, items, columns, button, title, description, empty, actions, className }: Props) => {\n const { resources, views } = useAdminMeta()\n const view = views[model.name]\n const { fields: fieldTypes } = useProjectUi()\n const canUpdate = can(usePermissions(model.name), 'update')\n const { go, href } = useAppAddress()\n const xs = useIsXs()\n const narrow = !useIsDesktop()\n const names = useMemo(() => columns?.map(columnName) ?? listColumnNames(model, view), [columns, model, view])\n const all = useMemo(() => embeddedColumns(model, view, names, { resources, views, fieldTypes }), [model, view, names, resources, views, fieldTypes])\n const specs = useMemo(() => (xs ? phoneSpecs(columns)(all) : all), [xs, columns, all])\n const gridColumns = useMemo(() => (button ? withRowButton(specs, model, view, button, resources, narrow) : specs), [specs, model, view, button, resources, narrow])\n const rows = useMemo(() => items.map((item) => ({ ...(item as Record<string, unknown>), id: recordId(model, item as Record<string, unknown>) })), [items, model])\n const source = useMemo(() => ({ total: rows.length, rowAt: (index: number) => rows[index]! }), [rows])\n const targets = embeddedRowTargets({ model, view, opens: undefined, resources, views, canUpdate })\n const linkTo = (to: AppAddress): RouteTarget => ({ href: href(to), onFollow: () => go(to) })\n return (\n <CardFrame title={title} description={description} actions={actions} className={className}>\n {rows.length === 0 ? (\n <Quiet>{empty ?? text('nothingYet')}</Quiet>\n ) : (\n <DataGrid\n fit\n columns={gridColumns}\n source={source}\n latencyMs={0}\n onOpenRow={(row) => go(targets.address(row))}\n rowLink={(row) => linkTo(targets.address(row))}\n rowActions={targets.actions(linkTo)}\n rowNumbers={false}\n selectable={false}\n />\n )}\n </CardFrame>\n )\n}\n\n/** A `Table` without `resource`: the records of the list around it, as react-admin's DataTable draws its ListContext. */\nexport const ListTable = (props: Omit<Props, 'model' | 'items'>) => {\n const list = useLayoutList()\n if (!list?.model) return null\n return <LoadedListTable {...props} model={list.model} items={list.items} />\n}\n","import { useMemo, type ReactNode } from 'react'\nimport { columnName, type Styled, type TableProps } from '@protobase/layout'\nimport type { ResourceModel, ViewModel } from '@protobase/schema'\nimport { EmbeddedDisplaySwitch, EmbeddedList } from '../../embedded-list/embedded-list'\nimport { useEmbeddedDisplay } from '../../embedded-list/use-embedded-display'\nimport { useAdminMeta } from '../../meta-gate'\nimport { cn } from '../../../lib/cn'\nimport { propsOf, type BlockProps } from './block-props'\nimport { ListTable } from './list-table'\nimport { CardFrame } from './card-frame'\nimport { phoneSpecs } from './table-phone-columns'\nimport { GuardedParams } from '../../guarded-params'\nimport { ChosenRecord } from './chosen-record'\nimport { usePageParams } from '../page-params'\nimport type { RouteTarget } from '../../../primitives/route-link'\nimport { tableDisplay } from '@protobase/schema/internal'\nimport type { PlannedList } from '../../embedded-list/planned-embedded-rows'\nimport { usePlannedReads } from '../plan-reads'\n\ntype LoadedProps = Omit<TableProps, 'resource' | 'actions' | 'children' | 'select'> & {\n model: ResourceModel\n view: ViewModel | undefined\n actions: BlockProps['slots'][string]\n className?: string\n /** With `select`: where a row leads, the chosen row's key, and its children under the table. */\n chosen?: { rowTo: (key: string) => RouteTarget; key: string | undefined; details: ReactNode }\n /** Its rows and total from the page's planned reads, inside the records of another block. */\n planned?: PlannedList\n}\n\nconst LoadedTable = ({ model, view, filter = '', sort = '', columns, button, bulk, limit = 10, display: picked, title, description, empty, actions, className, chosen, planned }: LoadedProps) => {\n const [shown, pick] = useEmbeddedDisplay(view, `page:${model.name}:${title ?? ''}:${filter}`, picked)\n // A row is chosen in the table, so a table with `select` shows no other display\n const display = chosen ? tableDisplay : shown\n const names = useMemo(() => columns?.map(columnName), [columns])\n const phoneColumns = useMemo(() => phoneSpecs(columns), [columns])\n return (\n <CardFrame\n title={title}\n description={description}\n actions={\n <>\n {!chosen && <EmbeddedDisplaySwitch view={view} value={display} onChange={pick} />}\n {actions}\n </>\n }\n className={cn('h-full', className)}\n >\n <EmbeddedList model={model} view={view} filter={filter} sort={sort} columns={names} button={button} bulk={bulk} limit={limit} display={display} empty={empty} phoneColumns={phoneColumns} {...(chosen && { rowTo: chosen.rowTo, chosenKey: chosen.key })} {...(planned && { planned })} />\n {chosen?.details}\n </CardFrame>\n )\n}\n\n/**\n * The first `limit` records in `sort` order, in the list page's table, with its row button and, with `bulk`, the view's\n * bulk actions for the rows selected, or display, with a link to the whole list. A phone shows the columns `phoneSpecs`\n * picks. Without `resource`, the records of the list around it. With `select`, a row leads to the page with it chosen,\n * and the chosen row's children follow the table. Inside the records of another block, its rows and total per record\n * come from the page's planned reads.\n */\nexport const TableBlock = ({ node, at, slots, children, className }: BlockProps) => {\n const { className: _className, resource, select, children: _children, ...props } = propsOf<TableProps & Styled>(node)\n const { resources, views } = useAdminMeta()\n const [rows, total] = usePlannedReads([at, at === undefined ? undefined : `${at}#total`])\n const planned = useMemo(() => rows && { rows, total }, [rows, total])\n if (resource === undefined) return <ListTable {...props} actions={slots.actions} className={className} />\n const model = resources[resource]\n if (!model) return null\n if (select !== undefined) {\n return (\n <SelectTable {...props} model={model} view={views[model.name]} actions={slots.actions} className={className} select={select} {...(planned && { planned })}>\n {children}\n </SelectTable>\n )\n }\n return <LoadedTable {...props} model={model} view={views[model.name]} actions={slots.actions} className={className} {...(planned && { planned })} />\n}\n\n/** A table whose rows each link to the page with that row's key in the parameter `select`, and the chosen row's children under it. */\nconst SelectTable = ({ select, children, ...props }: Omit<LoadedProps, 'chosen'> & { select: string; children: ReactNode[] }) => {\n const { given, linkTo } = usePageParams()\n const rowTo = (key: string) => linkTo({ [select]: key })\n const key = given[select]\n // A form under the chosen row asks before another row replaces it\n const details = key === undefined ? null : <GuardedParams name={select}><ChosenRecord key={key} model={props.model} query={{ key }}>{children}</ChosenRecord></GuardedParams>\n return <LoadedTable {...props} chosen={{ rowTo, key, details }} />\n}\n","import { Fragment } from 'react'\nimport type { BlockProps } from './block-props'\nimport { cn } from '../../../lib/cn'\nimport { Link, useRouter } from '../../router'\nimport { shownPageTab, tabsOf, usePageTabsRoute } from '../page-tabs'\nimport { Problem } from '../problem'\nimport { text } from '../messages'\n\n/**\n * The page's tabs, each a link to its own address, and the shown tab alone (its children are the tabs, one each, in\n * order), so the others load nothing. On a phone they are a select. A name the page has no tab for, such as one the\n * user may not see, says so under the tabs.\n */\nexport const TabsBlock = ({ node, children, className }: BlockProps) => {\n const { tab: named, pathOf } = usePageTabsRoute()\n const { navigate } = useRouter()\n const tabs = tabsOf(node)\n const shown = shownPageTab(tabs, named)\n // The first tab is at the page's own address\n const path = (name: string) => pathOf(name === tabs[0]?.name ? undefined : name)\n return (\n <div className={cn('flex flex-col gap-6', className)}>\n <select aria-label={text('tabs')} value={shown?.name ?? ''} onChange={(event) => navigate(path(event.target.value))} className=\"h-9 rounded-md border border-border-strong bg-background px-2 font-medium md:hidden\">\n {!shown && <option value=\"\" disabled />}\n {tabs.map((tab) => (\n <option key={tab.name} value={tab.name}>\n {tab.label}\n </option>\n ))}\n </select>\n <nav aria-label={text('tabs')} className=\"hidden border-b md:block\">\n <ul className=\"flex gap-1\">\n {tabs.map((tab) => (\n <li key={tab.name}>\n <Link\n to={path(tab.name)}\n aria-current={tab === shown ? 'page' : undefined}\n className={cn('-mb-px inline-flex h-9 items-center whitespace-nowrap border-b-2 px-3 font-medium transition-colors', tab === shown ? 'border-foreground text-foreground' : 'border-transparent text-muted-foreground hover:text-foreground')}\n >\n {tab.label}\n </Link>\n </li>\n ))}\n </ul>\n </nav>\n {shown ? <Fragment key={shown.name}>{children[tabs.indexOf(shown)]}</Fragment> : <Problem>{text('noTab', { name: named ?? '' })}</Problem>}\n </div>\n )\n}\n\n/** One tab's elements, stacked as on the page. */\nexport const TabBlock = ({ children }: BlockProps) => <div className=\"flex flex-col gap-6\">{children}</div>\n","/** A list a thread reads newest first, a page at a time: the items loaded so far, and whether earlier ones are left. */\nexport type TimedList<T> = { items: T[]; more: boolean }\n\n// An item without a time sorts as the newest, as Postgres puts a null first when ordering newest first\nconst timeOf = (time: string | undefined) => (time === undefined ? Infinity : Date.parse(time))\n\n/**\n * Two lists read newest first, such as a thread's messages and its tool calls, as one newest first. Items older than\n * the oldest loaded of a list with earlier ones left are held back until those load, so nothing shows out of order. At\n * the same time, an item of `first` is newer than one of `second`, so the one of `second` shows before it.\n */\nexport const mergeByTime = <A extends { time: string | undefined }, B extends { time: string | undefined }>(first: TimedList<A>, second: TimedList<B>): (A | B)[] => {\n const oldest = (list: TimedList<{ time: string | undefined }>) => (list.more && list.items.length > 0 ? timeOf(list.items.at(-1)!.time) : -Infinity)\n const cutoff = Math.max(oldest(first), oldest(second))\n const merged: (A | B)[] = []\n let a = 0\n let b = 0\n while (a < first.items.length || b < second.items.length) {\n const takeFirst = b >= second.items.length || (a < first.items.length && timeOf(first.items[a]!.time) >= timeOf(second.items[b]!.time))\n const item = takeFirst ? first.items[a++]! : second.items[b++]!\n if (timeOf(item.time) < cutoff) break\n merged.push(item)\n }\n return merged\n}\n","import { Check, CircleAlert } from 'lucide-react'\nimport type { ToolCallState } from '@protobase/layout'\nimport { enumLabel, type FieldViewModel } from '@protobase/schema'\nimport { valueTone } from '../../live/value-color'\nimport { Spinner } from '../../primitives/spinner'\n\n/**\n * A message's or tool call's status in its view's label; a value the view colours `red`, such as a failed send, reads\n * as a problem. A tool call's `mark` draws its state before the label: a check when done, a spinner while running, and\n * an error as a problem.\n */\nexport const MessageStatus = ({ value, hints, mark }: { value: string; hints: FieldViewModel | undefined; mark?: ToolCallState }) => {\n const label = enumLabel(value, hints?.valueLabels)\n if (mark === 'done') {\n return (\n <span className=\"inline-flex items-center gap-1\">\n <Check aria-hidden className=\"size-3.5 shrink-0 text-success-text\" />\n {label}\n </span>\n )\n }\n if (mark === 'running') {\n return (\n <span className=\"inline-flex items-center gap-1\">\n <Spinner hidden className=\"size-3.5 shrink-0\" />\n {label}\n </span>\n )\n }\n if (mark !== 'error' && valueTone(hints?.valueColors, value) !== 'red') return label\n return (\n <span className=\"inline-flex items-center gap-1 text-danger-text\">\n <CircleAlert aria-hidden className=\"size-3.5 shrink-0\" />\n {label}\n </span>\n )\n}\n","import { ChevronRight } from 'lucide-react'\nimport { useId, useState, type ReactNode } from 'react'\nimport type { FieldViewModel } from '@protobase/schema'\nimport { cn } from '../../lib/cn'\nimport { Button } from '../../primitives/button'\nimport { CodeBlock } from '../../primitives/code-block'\nimport { JsonBlock } from '../field-types/json/json-block'\nimport { jsonOf, notJson } from '../field-types/json/json-text'\nimport { MessageStatus } from './message-status'\nimport type { ToolCall } from './tool-calls'\nimport { text } from './messages'\n\n// A value as pretty JSON; a text that holds JSON shows as the value it holds, any other text as written\nconst Value = ({ value }: { value: unknown }) => {\n const parsed = typeof value === 'string' ? jsonOf(value) : value\n return parsed === notJson ? <CodeBlock>{String(value)}</CodeBlock> : <JsonBlock value={parsed} />\n}\n\nconst Part = ({ label, children }: { label: string; children: ReactNode }) => (\n <div className=\"grid gap-1\">\n <p className=\"text-xs font-medium text-muted-foreground\">{label}</p>\n {children}\n </div>\n)\n\n/**\n * A tool call between a thread's messages: its tool's name and its status with its mark, and a toggle, closed at\n * first, that opens to its input and result as pretty JSON and its error.\n */\nexport const ToolCallItem = ({ call, statusHints }: { call: ToolCall; statusHints: FieldViewModel | undefined }) => {\n const [open, setOpen] = useState(false)\n const id = useId()\n const status = call.status !== undefined && <MessageStatus value={call.status} hints={statusHints} mark={call.state} />\n const name = <span className=\"font-mono text-xs text-foreground\">{call.name}</span>\n const opens = call.input !== undefined || call.result !== undefined || call.error !== undefined\n return (\n <div data-tool-call className=\"flex min-w-0 flex-col gap-1 pl-11 text-xs text-muted-foreground\">\n {opens ? (\n <Button size=\"sm\" variant=\"ghost\" className=\"-ml-2.5 self-start\" aria-expanded={open} aria-controls={id} onClick={() => setOpen(!open)}>\n <ChevronRight aria-hidden className={cn('size-3.5 transition-transform', open && 'rotate-90')} />\n {name}\n {status}\n </Button>\n ) : (\n <p className=\"flex items-center gap-1.5\">\n {name}\n {status}\n </p>\n )}\n {open && (\n <div id={id} className=\"grid gap-2\">\n {call.input !== undefined && <Part label={text('callInput')}><Value value={call.input} /></Part>}\n {call.result !== undefined && <Part label={text('callResult')}><Value value={call.result} /></Part>}\n {call.error !== undefined && <Part label={text('callError')}><CodeBlock>{call.error}</CodeBlock></Part>}\n </div>\n )}\n </div>\n )\n}\n","import type { ChatAuthor } from '../../chat'\nimport { chatDayLabel, sameChatDay } from '../../chat/chat-day'\nimport type { ToolCall } from './tool-calls'\n\ntype Row = Record<string, unknown>\n\nexport type ThreadFields = { key: (row: Row) => string; sender?: string; time: string; text: string; status?: string }\n\n/** A message record of a thread with its time, read to order it among the thread's tool calls. */\nexport type MessageRow = { kind: 'message'; row: Row; time: string | undefined }\n\n/** The message records of a thread with the time each was sent, in the order read. */\nexport const messageRows = (rows: Row[], time: string): MessageRow[] => rows.map((row) => ({ kind: 'message', row, time: typeof row[time] === 'string' ? (row[time] as string) : undefined }))\n\n/**\n * One line of a thread: a day's divider, a message under its sender, or with no `author` one author's, `continued`\n * after one of theirs that day, with its status when it has one, or a tool call.\n */\nexport type ThreadItem =\n | { kind: 'day'; key: string; label: string }\n | { kind: 'message'; key: string; author?: ChatAuthor; time: string | undefined; text: string; status?: string; continued: boolean }\n | ToolCall\n\n// A relation comes named as `{ id, name }` (`withLabels`); any other sender is its own name\nconst authorOf = (value: unknown): ChatAuthor => {\n if (typeof value === 'object' && value !== null && 'id' in value) {\n const { id, name } = value as { id: unknown; name?: unknown }\n return { id: String(id), ...(typeof name === 'string' && { name }) }\n }\n return { id: String(value ?? ''), ...(typeof value === 'string' && { name: value }) }\n}\n\n/**\n * The messages and tool calls of a thread, read newest first, as its lines oldest first: a day divider above each day's\n * first item, and a message that follows its sender's on the same day, with no tool call between, drawn as continued.\n */\nexport const threadItems = (newestFirst: (MessageRow | ToolCall)[], { key, sender, text, status }: ThreadFields, now = Date.now()): ThreadItem[] => {\n const items: ThreadItem[] = []\n let previous: { author: string | undefined; time: string | undefined } | undefined\n for (const entry of [...newestFirst].reverse()) {\n const sent = entry.time\n const sameDay = previous?.time !== undefined && sent !== undefined && sameChatDay(previous.time, sent)\n if (sent !== undefined && !sameDay) items.push({ kind: 'day', key: `day:${entry.kind === 'call' ? entry.key : key(entry.row)}`, label: chatDayLabel(sent, now) })\n if (entry.kind === 'call') {\n items.push(entry)\n previous = { author: undefined, time: sent }\n continue\n }\n const { row } = entry\n // A thread without a sender is one author's, whose messages all follow each other\n const author = sender === undefined ? undefined : authorOf(row[sender])\n const id = author?.id ?? ''\n const state = status === undefined || row[status] == null || row[status] === '' ? undefined : String(row[status])\n items.push({ kind: 'message', key: key(row), ...(author && { author }), time: sent, text: row[text] == null ? '' : String(row[text]), ...(state !== undefined && { status: state }), continued: sameDay && previous?.author === id })\n previous = { author: id, time: sent }\n }\n return items\n}\n","import { toolCallStates, type ToolCallState } from '@protobase/layout'\nimport type { ToolCallFields } from '@protobase/schema'\n\ntype Row = Record<string, unknown>\n\n/** A tool call of a thread: its tool's name, when it was called, its status and the mark that status gives, and what opens under it. */\nexport type ToolCall = { kind: 'call'; key: string; name: string; time: string | undefined; status?: string; state?: ToolCallState; input?: unknown; result?: unknown; error?: string }\n\nconst stateOf = (value: string | undefined) => (toolCallStates as readonly string[]).includes(value ?? '') ? (value as ToolCallState) : undefined\n\nconst textOf = (value: unknown) => (value == null || value === '' ? undefined : String(value))\n\n/** A call's React key from its record key; JSON keeps composite keys such as `['a,b']` and `['a', 'b']` apart. */\nexport const callKey = (key: unknown) => `call:${JSON.stringify(key)}`\n\n/** A record of a thread's tool call resource as the call it draws, by the fields the thread reads of it. */\nexport const toolCallOf = (row: Row, key: string, fields: ToolCallFields): ToolCall => {\n const status = textOf(row[fields.status])\n const state = stateOf(status)\n const input = fields.input === undefined ? undefined : row[fields.input]\n const result = fields.result === undefined ? undefined : row[fields.result]\n const error = fields.error === undefined ? undefined : textOf(row[fields.error])\n return {\n kind: 'call',\n key,\n name: String(row[fields.name] ?? ''),\n time: typeof row[fields.time] === 'string' ? (row[fields.time] as string) : undefined,\n ...(status !== undefined && { status }),\n ...(state !== undefined && { state }),\n ...(input != null && { input }),\n ...(result != null && { result }),\n ...(error !== undefined && { error }),\n }\n}\n","import type { Planned } from '../pages/planned'\n\n/** What a thread draws of one of its lists, its messages or its tool calls, as `useList` gives it. */\nexport type ThreadList = {\n items: Record<string, unknown>[]\n labels: Record<string, Record<string, string>>\n hasNextPage: boolean\n isFetchingNextPage: boolean\n isFetchNextPageError: boolean\n isLoading: boolean\n error: Error | null\n fetchNextPage: () => unknown\n refetch: () => unknown\n}\n\ntype State = {\n /** The latest records the page's planned read holds for it, inside the records of another block. */\n planned: Planned | undefined\n /** How many the planned read gives each record at most: as many mean earlier ones may be left. */\n limit: number\n /** Whether earlier records were asked for, so it reads its pages itself from then on. */\n expanded: boolean\n expand: () => void\n /** Its own read, which reads nothing until it is expanded when planned. */\n own: ThreadList & { pages: number }\n}\n\n/**\n * The list a thread draws: the planned latest records until earlier ones are asked for, which its own read then gives\n * from its first page and the one after it, the planned records staying while it reads them or until it reads one\n * after failing; its own read without one.\n */\nexport const threadListOf = ({ planned, limit, expanded, expand, own }: State): ThreadList => {\n if (!planned) return own\n const reading = expanded && !own.error && own.pages < 2 && (own.pages === 0 || own.hasNextPage)\n const plannedList = {\n items: planned.rows,\n labels: planned.labels ?? {},\n hasNextPage: planned.rows.length >= limit,\n isFetchingNextPage: reading,\n isFetchNextPageError: false,\n isLoading: planned.isPending,\n }\n // Its own read failed before its first page: the planned records stay, with its error, and trying again reads it again\n if (expanded && own.error && own.pages === 0) return { ...plannedList, error: own.error, fetchNextPage: own.refetch, refetch: own.refetch }\n if (expanded && !reading) return own\n // A planned read that failed is read again as its own\n return { ...plannedList, error: planned.error, fetchNextPage: expand, refetch: expand }\n}\n","import { useEffect, useState } from 'react'\nimport { useList, type UseListParams } from '../../data/use-list'\nimport type { Planned } from '../pages/planned'\nimport { threadListOf } from './planned-thread-list'\n\n/**\n * One list of a thread, its messages or its tool calls: from the page's planned read when it has one, earlier records\n * read by itself on request, and otherwise read by itself; nothing is read while not `enabled`.\n */\nexport const useThreadList = (resource: string, { pageSize = 50, enabled = true, ...request }: UseListParams, planned: Planned | undefined) => {\n const [expanded, setExpanded] = useState(false)\n const list = useList(resource, { ...request, pageSize, enabled: enabled && (!planned || expanded) })\n const pages = list.data?.pages.length ?? 0\n const { hasNextPage, isFetchingNextPage, fetchNextPage, error } = list\n // Asking a planned thread for earlier records reads its first page and then the one after it\n useEffect(() => {\n if (planned && expanded && !error && pages === 1 && hasNextPage && !isFetchingNextPage) void fetchNextPage()\n }, [planned, expanded, error, pages, hasNextPage, isFetchingNextPage, fetchNextPage])\n return threadListOf({ planned, limit: pageSize, expanded, expand: () => setExpanded(true), own: { ...list, pages } })\n}\n","import { threadSort } from '@protobase/layout'\nimport type { ResourceModel, ToolCallFields } from '@protobase/schema'\nimport { recordKey } from '../../live/model-helpers'\nimport { useAdminMeta } from '../meta-gate'\nimport type { Planned } from '../pages/planned'\nimport { callKey, toolCallOf } from './tool-calls'\nimport { useThreadList } from './use-thread-list'\n\n/**\n * The latest `limit` tool calls of a thread, newest first, from the page's `planned` read when it has one, with earlier\n * ones on request; none without `calls`.\n */\nexport const useToolCalls = (calls: { model: ResourceModel; filter?: string; fields: ToolCallFields } | undefined, limit: number, planned?: Planned) => {\n const { views } = useAdminMeta()\n const name = calls?.model.name ?? ''\n const list = useThreadList(name, { filter: calls?.filter, orderBy: calls && threadSort(calls.fields.time), pageSize: limit, enabled: calls !== undefined }, planned)\n if (!calls) return { calls: [], hasNextPage: false, isFetchingNextPage: false, list, statusHints: undefined }\n return {\n calls: list.items.map((row) => toolCallOf(row, callKey(recordKey(calls.model, row)), calls.fields)),\n hasNextPage: list.hasNextPage,\n isFetchingNextPage: list.isFetchingNextPage,\n list,\n statusHints: views[name]?.fields[calls.fields.status],\n }\n}\n","type ThreadList = { error: unknown; isLoading: boolean; items: unknown[] }\n\n/**\n * What a thread shows of its list: the error only while no message has loaded, so a failed refetch keeps the messages\n * on screen and the reader's place in them; then its loading line until the first page arrives; then the messages.\n */\nexport const threadState = (list: ThreadList) => {\n if (list.items.length > 0) return 'messages'\n if (list.error) return 'error'\n if (list.isLoading) return 'loading'\n return 'messages'\n}\n\n/** What an empty thread says: its loading line while its calls still load, so it never says empty before they arrive. */\nexport const emptyLine = (calls: { isLoading: boolean }, lines: { loading: string; empty: string }) => (calls.isLoading ? lines.loading : lines.empty)\n\n/** Whether a failed refetch or **Load earlier messages** shows its error above the messages that stay loaded. */\nexport const showsErrorAbove = (list: ThreadList) => list.items.length > 0 && Boolean(list.error)\n\ntype RetryableList = { isFetchNextPageError: boolean; fetchNextPage: () => unknown; refetch: () => unknown }\n\n/** What **Try again** runs on a thread's error: the earlier messages when loading them failed, else the thread again. */\nexport const retryOf = (list: RetryableList) => (list.isFetchNextPageError ? () => void list.fetchNextPage() : () => void list.refetch())\n","import { threadSort, type MessageFields } from '@protobase/layout'\nimport type { ResourceModel, ToolCallFields } from '@protobase/schema'\nimport { ChatDivider, ChatMessage, ChatThread } from '../../chat'\nimport { useOptionalAuth } from '../../auth/auth-provider'\nimport { recordKey } from '../../live/model-helpers'\nimport { listLabels, withLabels } from '../../live/relation-labels'\nimport { Markdown } from '../../markdown/markdown'\nimport { isMarkdown } from '../../markdown/markdown-hint'\nimport { Quiet } from '../pages/blocks/card-frame'\nimport { ErrorBanner } from '../error-banner'\nimport { useAdminMeta } from '../meta-gate'\nimport { mergeByTime } from './merge-by-time'\nimport { MessageStatus } from './message-status'\nimport { ToolCallItem } from './tool-call-item'\nimport { messageRows, threadItems } from './thread-items'\nimport { useToolCalls } from './use-tool-calls'\nimport { useThreadList } from './use-thread-list'\nimport type { Planned } from '../pages/planned'\nimport { emptyLine, retryOf, showsErrorAbove, threadState } from './thread-state'\nimport { text } from './messages'\n\n// Each list with earlier items left loads its next page\nconst loadEarlier = (lists: { hasNextPage: boolean; fetchNextPage: () => unknown }[]) => {\n for (const each of lists) if (each.hasNextPage) void each.fetchNextPage()\n}\n\nexport type MessageThreadProps = MessageFields & {\n model: ResourceModel\n /** An AIP-160 filter on the messages, such as the record's key in its relation. */\n filter?: string\n limit?: number\n empty?: string\n /** Whether the other side is writing a reply, which the thread's end says; left out, it never says. */\n working?: boolean\n /** The tool calls drawn between the messages in time order: records of `calls.model` matching `calls.filter`, read by `calls.fields`. */\n calls?: { model: ResourceModel; filter?: string; fields: ToolCallFields }\n /** Its latest messages and tool calls from the page's planned reads, inside the records of another block. */\n planned?: { messages: Planned | undefined; calls: Planned | undefined }\n}\n\n/**\n * The latest `limit` messages of `model` matching `filter`, oldest first, each under its sender's name and time, or its\n * time alone without `sender`, with\n * earlier ones on request, and its `status` under it in the view's enum labels; a text the message resource's view marks\n * `.markdown()` shows rendered. The latest `limit` of its `calls` show between them in time order. Planned, it reads\n * only its earlier ones itself.\n */\nexport const MessageThread = ({ model, filter, sender, time, text: body, status, limit = 50, empty, working, calls, planned }: MessageThreadProps) => {\n const { resources, views } = useAdminMeta()\n const auth = useOptionalAuth()\n const reader = auth?.state.kind === 'signed-in' ? auth.state.user.id : undefined\n const senders = sender === undefined ? [] : [sender]\n const labels = listLabels(resources, views, model, senders)\n const list = useThreadList(model.name, { filter, orderBy: threadSort(time), pageSize: limit, labels }, planned?.messages)\n const callList = useToolCalls(calls, limit, planned?.calls)\n const state = threadState(list)\n if (state === 'error') return <ErrorBanner title={text('couldNotLoad')} error={list.error} onRetry={retryOf(list)} />\n // The live region mounts with the messages it opens on, so a screen reader announces only those that arrive later\n if (state === 'loading') return <div className=\"p-4\"><Quiet>{text('loadingMessages')}</Quiet></div>\n const rows = withLabels(resources, model, senders, list.items, list.labels)\n // A call shows after a message sent at the same time\n const newestFirst = mergeByTime({ items: callList.calls, more: callList.hasNextPage }, { items: messageRows(rows, time), more: list.hasNextPage })\n const items = threadItems(newestFirst, { key: (row) => String(recordKey(model, row)), sender, time, text: body, status })\n const statusHints = status === undefined ? undefined : views[model.name]?.fields[status]\n const markdown = model.fields[body] !== undefined && isMarkdown(model.fields[body], views[model.name]?.fields[body])\n // The reader's own newest message: when one arrives, the thread goes to the end wherever they were\n const own = items.findLast((item) => item.kind === 'message' && item.author !== undefined && item.author.id === reader)\n return (\n <>\n {/* The messages stay, so the reader keeps their place; Try again runs what failed once more */}\n {showsErrorAbove(list) && <div className=\"shrink-0 p-2\"><ErrorBanner title={text('couldNotLoad')} error={list.error} onRetry={retryOf(list)} /></div>}\n {calls && callList.list.error && <div className=\"shrink-0 p-2\"><ErrorBanner title={text('couldNotLoadCalls')} error={callList.list.error} onRetry={retryOf(callList.list)} /></div>}\n <ChatThread\n length={newestFirst.length}\n followKey={own?.key}\n working={working}\n empty={emptyLine(callList.list, { loading: text('loadingMessages'), empty: empty ?? text('noMessages') })}\n onLoadEarlier={list.hasNextPage || callList.hasNextPage ? () => loadEarlier([list, callList.list]) : undefined}\n loadingEarlier={list.isFetchingNextPage || callList.isFetchingNextPage}\n >\n {items.map((item) =>\n item.kind === 'day' ? (\n <ChatDivider key={item.key} label={item.label} />\n ) : item.kind === 'call' ? (\n <ToolCallItem key={item.key} call={item} statusHints={callList.statusHints} />\n ) : (\n <ChatMessage key={item.key} {...(item.author ? { author: item.author } : { alone: true as const })} time={item.time} continued={item.continued} footer={item.status !== undefined && <MessageStatus value={item.status} hints={statusHints} />}>\n {/* A message keeps its line breaks; rendered markdown makes its own */}\n {markdown && item.text !== '' ? <Markdown source={item.text} className=\"whitespace-normal\" /> : item.text}\n </ChatMessage>\n ),\n )}\n </ChatThread>\n </>\n )\n}\n","import type { ReactNode } from 'react'\n\n/**\n * The box a thread scrolls in. It scrolls inside a box of its own, not with the page, so it can open at the newest\n * message and follow the ones that arrive, with what comes after it, such as a composer, in view beneath.\n */\nexport const ThreadBox = ({ children }: { children: ReactNode }) => <div className=\"flex h-[min(36rem,65dvh)] flex-col rounded-lg border border-border bg-background\">{children}</div>\n","import type { ThreadProps } from '@protobase/layout'\nimport { SectionContent } from '../../../record-view/section'\nimport { MessageThread } from '../../conversation/message-thread'\nimport { ThreadBox } from '../../conversation/thread-box'\nimport { useAdminMeta } from '../../meta-gate'\nimport { usePlannedReads } from '../plan-reads'\nimport { useScopeStack } from '../record-scope'\nimport { useStackConditions } from '../use-conditions'\nimport { cn } from '../../../lib/cn'\nimport { propsOf, type BlockProps } from './block-props'\n\n/**\n * The latest messages of a resource, oldest first, under their sender's name and time and over their status, with\n * earlier ones on request, ending in a working indicator while `working` holds for the record around it, with the\n * tool calls of `calls` between them in time order. Inside the records of another block, its latest messages and\n * tool calls come from the page's planned reads.\n */\nexport const ThreadBlock = ({ node, at, slots, className }: BlockProps) => {\n const { title, description, resource, filter, sender, time, text, status, working, calls, limit, empty } = propsOf<ThreadProps>(node)\n const { resources } = useAdminMeta()\n const [busy] = useStackConditions(working === undefined ? [] : [working], useScopeStack())\n const [messages, plannedCalls] = usePlannedReads([at, at === undefined ? undefined : `${at}#calls`])\n const model = resources[resource]\n if (!model) return null\n const callsModel = calls && resources[calls.resource]\n return (\n <section className={cn('flex min-w-0 flex-col', className)} aria-label={title}>\n <SectionContent title={title} help={description} actions={slots.actions}>\n <ThreadBox>\n <MessageThread model={model} filter={filter} sender={sender} time={time} text={text} status={status} calls={calls && callsModel && { model: callsModel, filter: calls.filter, fields: calls }} limit={limit} empty={empty} working={working === undefined ? undefined : busy === true} {...((messages || plannedCalls) && { planned: { messages, calls: plannedCalls } })} />\n </ThreadBox>\n </SectionContent>\n </section>\n )\n}\n","import type { TextProps } from '@protobase/layout'\nimport { cn } from '../../../lib/cn'\nimport { propsOf, type BlockProps } from './block-props'\n\n// The plain elements look like nothing of their own: their classes say how they look.\n\n/** An element of its own, such as a panel or a banner. */\nexport const BoxBlock = ({ children, className }: BlockProps) => <div className={className}>{children}</div>\n\n/** Its children side by side. */\nexport const RowBlock = ({ children, className }: BlockProps) => <div className={cn('flex', className)}>{children}</div>\n\n/** Its children one under another. */\nexport const ColumnBlock = ({ children, className }: BlockProps) => <div className={cn('flex flex-col', className)}>{children}</div>\n\n/** Text and links in it, as a paragraph, a piece of a line or a heading. */\nexport const TextBlock = ({ node, children, className }: BlockProps) => {\n const { as: Tag = 'p' } = propsOf<TextProps>(node)\n return <Tag className={className}>{children}</Tag>\n}\n","import { scopeValue, type ArrayFieldProps } from '@protobase/layout'\nimport { useMemo } from 'react'\nimport { LayoutListScope } from '../layout-list'\nimport { useScopeStack, valueScopeOf } from '../record-scope'\nimport { propsOf, type BlockProps } from './block-props'\n\n/** The items of a JSON list the record around it holds, as a list its children draw, as react-admin's ArrayField. */\nexport const ArrayFieldBlock = ({ node, children }: BlockProps) => {\n const { source } = propsOf<ArrayFieldProps>(node)\n const held = scopeValue(valueScopeOf(useScopeStack()), source)\n const list = useMemo(() => ({ items: Array.isArray(held) ? held : [] }), [held])\n return <LayoutListScope value={list}>{children}</LayoutListScope>\n}\n","import type { SelectInputProps } from '@protobase/layout'\nimport { cn } from '../../../lib/cn'\nimport { MenuSelect } from '../../../primitives/menu-select'\nimport { usePageParams } from '../page-params'\nimport { propsOf, type BlockProps } from './block-props'\n\n/**\n * The page parameter `source` under its label, as react-admin's SelectInput draws a choice: a select whose every choice\n * is a link to the page with it chosen, its default leaving the parameter out. Without choices, the value the address\n * gives, as text.\n */\nexport const SelectInputBlock = ({ node, className }: BlockProps) => {\n const { source, choices, label = source, defaultValue } = propsOf<SelectInputProps>(node)\n const { values, linkTo } = usePageParams()\n const value = values[source]\n return (\n <div className={cn('flex flex-wrap items-center gap-2', className)}>\n <span className=\"font-medium text-muted-foreground\">{label}</span>\n {choices ? (\n <MenuSelect\n label={label}\n value={value ?? ''}\n options={choices.map((choice) => ({ value: String(choice.id), label: choice.name }))}\n link={(id) => linkTo({ [source]: defaultValue !== undefined && id === String(defaultValue) ? undefined : id })}\n />\n ) : (\n <span>{value}</span>\n )}\n </div>\n )\n}\n","import type { ResourceModel } from '@protobase/schema'\nimport type { LayoutList } from './layout-list'\nimport type { Planned } from './planned'\n\n/** Where a list's own read stands: the pages it read so far, their records, and whether one more is there. */\nexport type OwnRead = {\n pages: number\n items: Record<string, unknown>[]\n hasNextPage: boolean\n isFetchingNextPage: boolean\n isPending: boolean\n error: Error | null\n fetchNextPage: () => unknown\n}\n\ntype State = {\n model: ResourceModel\n /** `undefined` when no record can match. */\n filter: string | undefined\n perPage: number\n more: boolean\n planned: Planned | undefined\n /** Whether a planned list's button was clicked, so it reads its pages itself from then on. */\n expanded: boolean\n expand: () => void\n own: OwnRead\n}\n\n/** The list a list block draws and the read it shows the state of, from its planned rows or its own read. */\nexport const relatedListOf = ({ model, filter, perPage, more, planned, expanded, expand, own }: State): { read: { isPending: boolean; error: Error | null }; list: LayoutList } => {\n if (filter === undefined) return { read: { isPending: false, error: null }, list: { model, items: [] } }\n if (planned && !expanded) {\n const items = planned.rows.slice(0, perPage)\n const loadMore = more && items.length === perPage ? expand : undefined\n return { read: planned, list: { model, items, planned: true, ...(loadMore && { loadMore }) } }\n }\n // While a planned list reads its first two pages, its planned rows stay, still planned, the button loading\n if (planned && !own.error && own.pages < 2 && (own.pages === 0 || own.hasNextPage)) {\n return { read: planned, list: { model, items: planned.rows.slice(0, perPage), planned: true, loadMore: () => {}, loadingMore: true } }\n }\n // The rows the list read itself are its own, so the reads planned inside them no longer hold theirs\n const loadMore = more && own.hasNextPage ? () => void own.fetchNextPage() : undefined\n return { read: { isPending: own.isPending, error: own.error }, list: { model, items: own.items, ...(loadMore && { loadMore, loadingMore: own.isFetchingNextPage }) } }\n}\n","import { useEffect, useState } from 'react'\nimport type { ResourceModel } from '@protobase/schema'\nimport { useList } from '../../data/use-list'\nimport type { LayoutList } from './layout-list'\nimport type { Planned } from './planned'\nimport { relatedListOf } from './related-list-of'\n\ntype Request = {\n model: ResourceModel\n /** `undefined` when no record can match, such as when the record around it holds no value to tie the list by. */\n filter: string | undefined\n sort: string\n perPage: number\n /** Whether a button reads the next `perPage` records into the same list. */\n more: boolean\n /** The rows the page's planned read holds for it, which it draws instead of reading them itself. */\n planned?: Planned\n}\n\n/**\n * The first `perPage` records of `model` a list block reads, from the page's planned read or a read of its own, and\n * with `more` each next page added to the same list. Nothing is read when no record can match. A planned list's next\n * pages are a read of the list's own, from its first page, the planned rows staying on screen meanwhile.\n */\nexport const useRelatedList = ({ model, filter, sort, perPage, more, planned }: Request): { read: { isPending: boolean; error: Error | null }; list: LayoutList } => {\n const [expanded, setExpanded] = useState(false)\n const query = useList(model.name, { filter, orderBy: sort, pageSize: perPage, enabled: filter !== undefined && (!planned || expanded) })\n const pages = query.data?.pages.length ?? 0\n const { hasNextPage, isFetchingNextPage, fetchNextPage, error } = query\n // The first click on a planned list reads its first page and then the one after it\n useEffect(() => {\n if (planned && expanded && !error && pages === 1 && hasNextPage && !isFetchingNextPage) void fetchNextPage()\n }, [planned, expanded, error, pages, hasNextPage, isFetchingNextPage, fetchNextPage])\n const own = { pages, items: query.items, hasNextPage, isFetchingNextPage, isPending: query.isPending, error, fetchNextPage }\n return relatedListOf({ model, filter, perPage, more, planned, expanded, expand: () => setExpanded(true), own })\n}\n","import { referenceManyRead, scopeLookup, type ReferenceManyFieldProps } from '@protobase/layout'\nimport { useAdminMeta } from '../../meta-gate'\nimport { ListBody } from '../layout-list'\nimport { useScopeStack, valueScopeOf } from '../record-scope'\nimport { usePlanned } from '../plan-reads'\nimport { useRelatedList } from '../use-related-list'\nimport { propsOf, type BlockProps } from './block-props'\n\n/**\n * The records of `reference` whose `target` holds the record's `source`, as a list its children draw, as react-admin's\n * ReferenceManyField: its key descending unless `sort` says otherwise, `empty` when none match, and with\n * `pagination=\"more\"` a button that reads the next page. On a page, its rows come from the page's planned read.\n */\nexport const ReferenceManyFieldBlock = ({ node, at, children }: BlockProps) => {\n const props = propsOf<ReferenceManyFieldProps>(node)\n const model = useAdminMeta().resources[props.reference]\n const lookup = scopeLookup(valueScopeOf(useScopeStack()))\n const planned = usePlanned(at)\n if (!model) return null\n return (\n <RelatedList model={model} {...referenceManyRead(props, model.primaryKey[0]!, lookup)} more={props.pagination === 'more'} empty={props.empty} {...(planned && { planned })}>\n {children}\n </RelatedList>\n )\n}\n\ntype ListProps = Parameters<typeof useRelatedList>[0] & { empty?: string; children: BlockProps['children'] }\n\n/** A list block's read and what it draws of it. */\nexport const RelatedList = ({ empty, children, ...request }: ListProps) => {\n const { read, list } = useRelatedList(request)\n return (\n <ListBody read={read} list={list} empty={empty}>\n {children}\n </ListBody>\n )\n}\n","import { referenceArrayRead, scopeLookup, type ReferenceArrayFieldProps } from '@protobase/layout'\nimport { useAdminMeta } from '../../meta-gate'\nimport { useScopeStack, valueScopeOf } from '../record-scope'\nimport { usePlanned } from '../plan-reads'\nimport { propsOf, type BlockProps } from './block-props'\nimport { RelatedList } from './reference-many-field'\n\n/**\n * The records of `reference` whose keys the record's `source`, a JSON list, holds, as a list its children draw, as\n * react-admin's ReferenceArrayField: one read with `in()`, its filter and sort, by default its key descending; on a\n * page, the rows of the page's planned read.\n */\nexport const ReferenceArrayFieldBlock = ({ node, at, children }: BlockProps) => {\n const props = propsOf<ReferenceArrayFieldProps>(node)\n const model = useAdminMeta().resources[props.reference]\n const lookup = scopeLookup(valueScopeOf(useScopeStack()))\n const planned = usePlanned(at)\n if (!model) return null\n return (\n <RelatedList model={model} {...referenceArrayRead(props, model.primaryKey[0]!, lookup)} more={false} empty={props.empty} {...(planned && { planned })}>\n {children}\n </RelatedList>\n )\n}\n","import type { ReactNode } from 'react'\nimport { scopeValue, type ReferenceFieldProps } from '@protobase/layout'\nimport type { ResourceModel } from '@protobase/schema'\nimport { recordTitle } from '@protobase/schema/internal'\nimport { Skeleton } from '../../../primitives/skeleton'\nimport { ErrorBanner } from '../../error-banner'\nimport { useAdminMeta } from '../../meta-gate'\nimport { AppLink } from '../../use-app-address'\nimport { RecordScope, useScopeStack, valueScopeOf } from '../record-scope'\nimport { usePlanned } from '../plan-reads'\nimport { plannedRecord, useFirstRecord } from '../use-layout-data'\nimport { propsOf, type BlockProps } from './block-props'\nimport { text } from '../messages'\n\ntype LoadedProps = { model: ResourceModel; at?: string; recordKey: string; link: ReferenceFieldProps['link']; children: ReactNode[]; className?: string }\n\n// The record its key names, from the page's planned read or one of its own, its children inside it or its title, linked\n// to its page unless `link` is false\nconst LoadedReference = ({ model, at, recordKey, link = 'edit', children, className }: LoadedProps) => {\n const { views } = useAdminMeta()\n const planned = usePlanned(at)\n const own = useFirstRecord(model, { key: recordKey, enabled: !planned })\n const record = planned ? plannedRecord(model, planned) : own\n if (record.isPending) return <Skeleton className=\"h-4 w-24\" />\n if (record.error) return <ErrorBanner title={text('couldNotLoad')} error={record.error} />\n if (!record.data) return null\n const shown = children.length > 0 ? (\n <RecordScope value={record.data}>{children}</RecordScope>\n ) : recordTitle(model, views[model.name], record.data.record, recordKey)\n if (link === false) return <span className={className}>{shown}</span>\n return (\n <AppLink to={{ kind: 'record', resource: model.name, key: recordKey }} className={className ?? 'font-medium text-primary-text hover:underline'}>\n {shown}\n </AppLink>\n )\n}\n\n/**\n * The record of `reference` the record's `source` points at, as react-admin's ReferenceField: its children inside that\n * record, or its title, as a link to the record's page; `empty` when the field holds none.\n */\nexport const ReferenceFieldBlock = ({ node, at, children, className }: BlockProps) => {\n const { reference, source, link, empty } = propsOf<ReferenceFieldProps>(node)\n const model = useAdminMeta().resources[reference]\n const value = scopeValue(valueScopeOf(useScopeStack()), source)\n if (!model) return null\n if (value === null || value === undefined || value === '') return empty === undefined ? null : <span className={className}>{empty}</span>\n return (\n <LoadedReference model={model} {...(at !== undefined && { at })} recordKey={String(value)} link={link} className={className}>\n {children}\n </LoadedReference>\n )\n}\n","import type { RoleLabel } from '@protobase/client'\nimport { roleLabel } from '../organizations/organization-paths'\n\n/** The labels of `names`, as the server names the roles, in one line. */\nexport const roleNames = (roles: readonly RoleLabel[], names: readonly string[]) => names.map((name) => roleLabel(roles, name)).join(', ')\n","import { messages } from '../locale/messages'\n\nexport const text = messages('users')\n","import { useCallback, useEffect, useState } from 'react'\nimport type { RoleLabel, UserInvitation } from '@protobase/client'\nimport { AccountSection } from '../account/account-section'\nimport { useAuth } from '../auth/auth-provider'\nimport { InviteForm } from '../invitations/invite-form'\nimport { PendingInvitationRow } from '../invitations/pending-invitation-row'\nimport { AppRolesPicker } from '../organizations/app-roles-picker'\nimport { roleNames } from './role-names'\nimport { text } from './messages'\n\n/** Inviting someone to the app with the roles their account gets, and the invitations not accepted yet. */\nexport const AppInvitations = ({ roles }: { roles: readonly RoleLabel[] }) => {\n const { session } = useAuth()\n const [selected, setSelected] = useState<string[]>([])\n const [invitations, setInvitations] = useState<UserInvitation[]>([])\n const load = useCallback(() => void session.users.invitations().then(setInvitations, () => setInvitations([])), [session])\n useEffect(load, [load])\n const invite = async (email: string) => {\n const sent = await session.users.invite({ email, roles: selected })\n setSelected([])\n load()\n return sent\n }\n return (\n <>\n <InviteForm title={text('inviteSomeone')} description={text('inviteDescription')} onInvite={invite} incomplete={selected.length === 0}>\n <AppRolesPicker roles={roles} selected={selected} grantable={new Set(roles.map((role) => role.name))} onChange={setSelected} />\n </InviteForm>\n <AccountSection title={text('notAcceptedYet')} description={invitations.length > 0 ? text('sendingAgain') : text('nobodyWaiting')}>\n {invitations.length > 0 && (\n <ul className=\"divide-y rounded-md border\">\n {invitations.map((invitation) => (\n <PendingInvitationRow\n key={invitation.id}\n email={invitation.email}\n gives={roleNames(roles, invitation.roles)}\n expiresAt={invitation.expiresAt}\n onResend={async () => {\n const sent = await session.users.invite({ email: invitation.email, roles: invitation.roles })\n load()\n return sent\n }}\n onRevoke={async () => {\n await session.users.revoke(invitation.id)\n load()\n }}\n />\n ))}\n </ul>\n )}\n </AccountSection>\n </>\n )\n}\n","import { useState } from 'react'\nimport type { RoleLabel } from '@protobase/client'\nimport { AccountSection, SectionError } from '../account/account-section'\nimport { useAuth } from '../auth/auth-provider'\nimport { minPasswordLength } from '../auth/reset-password-form'\nimport { AppRolesPicker } from '../organizations/app-roles-picker'\nimport { useAction } from '../organizations/use-action'\nimport { Button } from '../primitives/button'\nimport { Input } from '../primitives/input'\nimport { text } from './messages'\n\n/** Adding an account directly, with its roles and, if wanted, a password; without one the person signs in another way. */\nexport const CreateUserForm = ({ roles, onCreated }: { roles: readonly RoleLabel[]; onCreated: () => void }) => {\n const { session } = useAuth()\n const [email, setEmail] = useState('')\n const [name, setName] = useState('')\n const [password, setPassword] = useState('')\n const [selected, setSelected] = useState<string[]>([])\n const { busy, error, run } = useAction()\n const create = () =>\n run(async () => {\n await session.users.create({ email: email.trim(), name: name.trim(), roles: selected, ...(password && { password }) })\n setEmail('')\n setName('')\n setPassword('')\n setSelected([])\n onCreated()\n })\n const incomplete = !email.trim() || !name.trim() || selected.length === 0 || (password !== '' && password.length < minPasswordLength)\n return (\n <AccountSection title={text('addAnAccount')} description={text('addDescription')}>\n <SectionError message={error} />\n <form className=\"flex flex-col gap-3\" onSubmit={(event) => { event.preventDefault(); void create() }}>\n <div className=\"flex flex-col gap-2 sm:flex-row\">\n <Input aria-label={text('email')} type=\"email\" placeholder=\"name@example.com\" value={email} onChange={(event) => setEmail(event.target.value)} wrapperClassName=\"flex-1\" />\n <Input aria-label={text('name')} placeholder={text('name')} autoComplete=\"off\" value={name} onChange={(event) => setName(event.target.value)} wrapperClassName=\"flex-1\" />\n </div>\n <Input aria-label={text('password')} type=\"password\" autoComplete=\"new-password\" placeholder={text('passwordOptional', { length: minPasswordLength })} value={password} onChange={(event) => setPassword(event.target.value)} />\n <AppRolesPicker roles={roles} selected={selected} grantable={new Set(roles.map((role) => role.name))} onChange={setSelected} />\n <div>\n <Button type=\"submit\" variant=\"primary\" loading={busy} disabled={incomplete}>{text('addAccount')}</Button>\n </div>\n </form>\n </AccountSection>\n )\n}\n","import { useState } from 'react'\nimport type { AppUser, RoleLabel } from '@protobase/client'\nimport { useAuth } from '../auth/auth-provider'\nimport { AppRolesPicker } from '../organizations/app-roles-picker'\nimport { useAction } from '../organizations/use-action'\nimport { PersonRow } from '../people/person-row'\nimport { Badge } from '../primitives/badge'\nimport { Button } from '../primitives/button'\nimport { text } from './messages'\n\n/** Someone who can sign in, with Block or Unblock, and their roles to tick; an admin may give every role. */\nexport const UserRow = ({ user: initial, roles, self }: { user: AppUser; roles: readonly RoleLabel[]; self: boolean }) => {\n const { session } = useAuth()\n const [user, setUser] = useState(initial)\n const { busy, error, run, setError } = useAction()\n const setRoles = (selected: string[]) => {\n if (selected.length === 0) return setError(text('keepOneRole'))\n void run(async () => {\n await session.users.setRoles(user.id, selected)\n setUser({ ...user, roles: selected })\n })\n }\n const setBlocked = (blocked: boolean) =>\n void run(async () => {\n await (blocked ? session.users.block(user.id) : session.users.unblock(user.id))\n setUser({ ...user, blocked })\n })\n return (\n <PersonRow\n name={user.name}\n email={user.email}\n self={self}\n error={error}\n actions={\n <>\n {user.blocked && <Badge tone=\"red\">{text('blocked')}</Badge>}\n {!self && (user.blocked ? <Button size=\"sm\" loading={busy} onClick={() => setBlocked(false)}>{text('unblock')}</Button> : <Button size=\"sm\" variant=\"danger\" loading={busy} onClick={() => setBlocked(true)}>{text('block')}</Button>)}\n </>\n }\n >\n <AppRolesPicker roles={roles} selected={user.roles} grantable={new Set(roles.map((role) => role.name))} disabled={busy} onChange={setRoles} />\n </PersonRow>\n )\n}\n","import { useCallback, useState } from 'react'\nimport type { RoleLabel } from '@protobase/client'\nimport { useAuth } from '../auth/auth-provider'\nimport { PagedSearchList } from '../lists/paged-search-list'\nimport { usePagedSearch } from '../lists/use-paged-search'\nimport { UserRow } from './user-row'\nimport { text } from './messages'\n\n/** Everyone who can sign in, a page at a time, found by address; `version` changes to read them again. */\nexport const UserList = ({ roles, version }: { roles: readonly RoleLabel[]; version: number }) => {\n const { session, state } = useAuth()\n const [query, setQuery] = useState('')\n // A new version is a new search, so the list reads the users again.\n const search = useCallback((term: string, offset: number) => session.users.search(term, offset).then((page) => ({ items: page.users, total: page.total })), [session, version])\n const list = usePagedSearch(search, query)\n const selfId = state.kind === 'signed-in' ? state.user.id : undefined\n return (\n <PagedSearchList\n title={text('people')}\n description={text('peopleDescription')}\n searchLabel={text('findSomeone')}\n placeholder={text('emailAddress')}\n query={query}\n onQuery={setQuery}\n list={list}\n renderRow={(user) => <UserRow key={`${version}/${user.id}`} user={user} roles={roles} self={user.id === selfId} />}\n />\n )\n}\n","import { useEffect, useState } from 'react'\nimport { AuthError, type RoleLabel } from '@protobase/client'\nimport { authMessage } from '../auth/auth-messages'\nimport { useAuth } from '../auth/auth-provider'\nimport { text } from './messages'\n\n/** Every role an admin can give, with its label, read once; `error` says why they could not be read. */\nexport const useUserRoles = () => {\n const { session } = useAuth()\n const [roles, setRoles] = useState<RoleLabel[]>([])\n const [error, setError] = useState<string>()\n useEffect(() => {\n void session.users.roles().then(setRoles, (failure: unknown) => setError(failure instanceof AuthError ? authMessage(failure) : text('couldNotReadRoles')))\n }, [session])\n return { roles, error }\n}\n","import { useState } from 'react'\nimport { SectionError } from '../account/account-section'\nimport { AppInvitations } from './app-invitations'\nimport { CreateUserForm } from './create-user-form'\nimport { UserList } from './user-list'\nimport { useUserRoles } from './use-user-roles'\n\n/** The `Users` block: everyone who can sign in, inviting someone, and adding an account, for admins. */\nexport const UsersBlock = () => {\n const { roles, error } = useUserRoles()\n const [version, setVersion] = useState(0)\n return (\n <div className=\"flex max-w-3xl flex-col gap-4\">\n <SectionError message={error} />\n <UserList roles={roles} version={version} />\n <AppInvitations roles={roles} />\n <CreateUserForm roles={roles} onCreated={() => setVersion((current) => current + 1)} />\n </div>\n )\n}\n","import { useState } from 'react'\nimport type { MailSender } from '@protobase/client'\nimport { Button } from '../primitives/button'\nimport { Dialog } from '../primitives/dialog'\nimport { Input } from '../primitives/input'\nimport { Switch } from '../primitives/switch'\nimport { Textarea } from '../primitives/textarea'\nimport { SectionError } from './account-section'\nimport { text } from './messages'\n\n/** What the dialog asks: the address, when it is a new one, its display name, its own signature, and if it is the default. */\nexport type MailSenderInput = { address: string; name: string; signature: string; isDefault: boolean }\n\ntype MailSenderDialogProps = {\n /** The address to change; without it, the dialog enters a new one. */\n sender?: MailSender\n busy: boolean\n error?: string\n onSave: (input: MailSenderInput) => void\n onClose: () => void\n}\n\n/** Enters a From address, or changes one: its display name, whether it is the default, and its own signature. */\nexport const MailSenderDialog = ({ sender, busy, error, onSave, onClose }: MailSenderDialogProps) => {\n const [address, setAddress] = useState(sender?.address ?? '')\n const [name, setName] = useState(sender?.name ?? '')\n const [signature, setSignature] = useState(sender?.signature ?? '')\n const [isDefault, setDefault] = useState(sender?.isDefault ?? false)\n const save = () => onSave({ address: address.trim(), name: name.trim(), signature, isDefault })\n return (\n <Dialog\n title={sender ? sender.address : text('addFromAddress')}\n description={sender ? text('changeFromAddressDescription') : text('addFromAddressDescription')}\n onClose={onClose}\n actions={\n <>\n <Button onClick={onClose}>{text('cancel')}</Button>\n <Button variant=\"primary\" loading={busy} disabled={!address.trim()} onClick={save}>\n {sender ? text('save') : text('addAddress')}\n </Button>\n </>\n }\n >\n {!sender && (\n <label className=\"flex flex-col gap-1.5 font-medium\">\n {text('fromAddress')}\n <Input autoFocus type=\"email\" value={address} maxLength={254} placeholder={text('fromAddressPlaceholder')} onChange={(event) => setAddress(event.target.value)} />\n </label>\n )}\n <label className=\"mt-3 flex flex-col gap-1.5 font-medium\">\n {text('fromName')}\n <Input value={name} maxLength={100} placeholder={text('fromNamePlaceholder')} onChange={(event) => setName(event.target.value)} />\n </label>\n <label className=\"mt-3 flex cursor-pointer items-center justify-between gap-3\">\n <span>{text('defaultFromAddress')}</span>\n <Switch checked={isDefault} onChange={setDefault} label={text('defaultFromAddress')} />\n </label>\n <label className=\"mt-3 flex flex-col gap-1.5 font-medium\">\n {text('signature')}\n <Textarea value={signature} maxLength={2000} placeholder={text('signaturePlaceholder')} onChange={(event) => setSignature(event.target.value)} />\n </label>\n <SectionError message={error} />\n </Dialog>\n )\n}\n","import { AtSign, Plus } from 'lucide-react'\nimport { useRef, useState } from 'react'\nimport { AuthError, type MailSender, type MailSenderChange, type MailSenders } from '@protobase/client'\nimport { authMessage } from '../auth/auth-messages'\nimport { Badge } from '../primitives/badge'\nimport { Button } from '../primitives/button'\nimport { Dialog } from '../primitives/dialog'\nimport { SectionError } from './account-section'\nimport { MailSenderDialog, type MailSenderInput } from './mail-sender-dialog'\nimport { text } from './messages'\n\nexport type MailSendersSectionProps = {\n senders: MailSenders\n /** Each rejects with `AuthError`, which the section shows. */\n onAdd: (input: { address: string; name?: string; signature?: string }) => Promise<MailSender>\n onUpdate: (id: string, change: MailSenderChange) => Promise<unknown>\n onRemove: (id: string) => Promise<void>\n}\n\ntype Editing = { kind: 'add' } | { kind: 'change'; sender: MailSender } | { kind: 'remove'; sender: MailSender }\n\nconst detailsOf = (sender: MailSender) => (sender.signature ? text('ownSignature') : text('genericSignature'))\n\n/**\n * The From addresses the person's mail goes out from, under their mailbox: its own and those they entered once, such\n * as its send-as addresses, each with its own signature or the generic one; one is the default.\n */\nexport const MailSendersSection = ({ senders: { address, senders }, onAdd, onUpdate, onRemove }: MailSendersSectionProps) => {\n const [busy, setBusy] = useState(false)\n const [error, setError] = useState<string>()\n const [editing, setEditing] = useState<Editing>()\n // Set at once, unlike `busy`, so a second click before the next render changes nothing twice.\n const inFlight = useRef(false)\n const chosen = senders.find((sender) => sender.isDefault)\n\n const close = () => {\n setEditing(undefined)\n setError(undefined)\n }\n\n const attempt = async (action: () => Promise<unknown>) => {\n if (inFlight.current) return\n inFlight.current = true\n setBusy(true)\n setError(undefined)\n try {\n await action()\n setEditing(undefined)\n } catch (failure) {\n // The browser's fetch rejects with a TypeError when the connection fails, before or after the server acted.\n if (failure instanceof TypeError) return setError(text('noAnswerFromServer'))\n if (!(failure instanceof AuthError)) throw failure\n setError(authMessage(failure))\n } finally {\n inFlight.current = false\n setBusy(false)\n }\n }\n\n // An empty name drops the address's name, and an empty signature its own, so the generic one applies.\n const save = (input: MailSenderInput) =>\n attempt(async () => {\n const name = input.name || null\n const signature = input.signature.trim() ? input.signature : null\n if (editing?.kind === 'change') return onUpdate(editing.sender.id, { name, signature, isDefault: input.isDefault })\n const added = await onAdd({ address: input.address, ...(name && { name }), ...(signature && { signature }) })\n if (input.isDefault) await onUpdate(added.id, { isDefault: true })\n })\n\n return (\n <div className=\"mt-5 border-t pt-4\">\n <h3 className=\"font-semibold\">{text('fromAddresses')}</h3>\n <p className=\"mt-1 mb-3 text-muted-foreground\">{text('fromAddressesDescription')}</p>\n <SectionError message={editing ? undefined : error} />\n {(address || senders.length > 0) && (\n <ul className=\"mb-3 divide-y rounded-md border\">\n {address && (\n <li className=\"flex flex-wrap items-center gap-3 px-3 py-2.5\">\n <AtSign className=\"size-4 shrink-0 text-muted-foreground\" />\n <span className=\"min-w-0 flex-1\">\n <bdi className=\"block truncate font-medium\">{address}</bdi>\n <span className=\"block text-xs text-muted-foreground\">{text('mailboxOwnAddress')}</span>\n </span>\n {chosen ? (\n <Button size=\"sm\" variant=\"ghost\" loading={busy} onClick={() => void attempt(() => onUpdate(chosen.id, { isDefault: false }))}>\n {text('makeDefault')}\n </Button>\n ) : (\n <Badge tone=\"blue\">{text('default')}</Badge>\n )}\n </li>\n )}\n {senders.map((sender) => (\n <li key={sender.id} className=\"flex flex-wrap items-center gap-3 px-3 py-2.5\">\n <AtSign className=\"size-4 shrink-0 text-muted-foreground\" />\n <span className=\"min-w-0 flex-1\">\n <bdi className=\"block truncate font-medium\">{sender.address}</bdi>\n {sender.name && <bdi className=\"block truncate\">{sender.name}</bdi>}\n <span className=\"block text-xs text-muted-foreground\">{detailsOf(sender)}</span>\n </span>\n {sender.isDefault && <Badge tone=\"blue\">{text('default')}</Badge>}\n <Button size=\"sm\" variant=\"ghost\" onClick={() => setEditing({ kind: 'change', sender })}>\n {text('edit')}\n </Button>\n <Button size=\"sm\" variant=\"ghost\" onClick={() => setEditing({ kind: 'remove', sender })}>\n {text('remove')}\n </Button>\n </li>\n ))}\n </ul>\n )}\n <Button onClick={() => setEditing({ kind: 'add' })}>\n <Plus className=\"size-3.5\" />\n {text('addFromAddress')}\n </Button>\n {editing?.kind === 'add' && <MailSenderDialog busy={busy} error={error} onSave={(input) => void save(input)} onClose={close} />}\n {editing?.kind === 'change' && <MailSenderDialog key={editing.sender.id} sender={editing.sender} busy={busy} error={error} onSave={(input) => void save(input)} onClose={close} />}\n {editing?.kind === 'remove' && (\n <Dialog\n title={text('removeFromAddress', { address: editing.sender.address })}\n description={text('removeFromAddressDescription')}\n onClose={close}\n actions={\n <>\n <Button onClick={close}>{text('cancel')}</Button>\n <Button variant=\"danger\" loading={busy} onClick={() => void attempt(() => onRemove(editing.sender.id))}>\n {text('remove')}\n </Button>\n </>\n }\n >\n <SectionError message={error} />\n </Dialog>\n )}\n </div>\n )\n}\n","import { useCallback, useState } from 'react'\nimport type { PersonalMailLink } from '@protobase/client'\nimport { providerMessage } from '../../auth/auth-messages'\nimport { useAuth } from '../../auth/auth-provider'\nimport { providerName } from '../../auth/provider-link'\nimport { mailboxOffers, type LinkedAccounts } from '../../mailbox/mailbox-offers'\nimport { text as mailboxText } from '../../mailbox/messages'\nimport { MailSendersSection } from '../mail-senders-section'\nimport { SignInProvidersSection } from '../sign-in-providers-section'\nimport { text } from '../messages'\nimport { AccountLoading } from './account-loading'\nimport { takeLinkError } from './connected-accounts-block'\nimport { useAccountData } from './use-account-data'\n\n// A mailbox not linked whose sign-in provider is, such as Gmail beside a Google sign-in: that sign-in cannot send mail.\nconst signInOnlyNotes = (links: PersonalMailLink[], linked: LinkedAccounts, providerNames: (id: string) => string) =>\n Object.fromEntries(\n mailboxOffers(links, linked, { code: 'not_linked' })\n .filter((offer) => offer.signInOnly)\n .map(({ link }) => [link.id, mailboxText('signInOnly', { provider: providerNames(link.provider), name: link.name })]),\n )\n\nconst Mailboxes = ({ links }: { links: PersonalMailLink[] }) => {\n const { session, linkPersonalMail, signInProviders } = useAuth()\n const { account } = session\n const [linkError] = useState(takeLinkError)\n const load = useCallback(async () => {\n const [mail, providers, senders] = await Promise.all([account.linkedPersonalMail(links), account.linkedProviders(), account.mailSenders()])\n return { mail, providers, senders }\n }, [account, links])\n const { data, error, reload } = useAccountData(load, text('couldNotReadMethods'))\n if (!data) return <AccountLoading error={error} />\n const providerNames = (id: string) => signInProviders.find((provider) => provider.id === id)?.name ?? providerName(id)\n const connect = (id: string) => linkPersonalMail(links.find((link) => link.id === id)!)\n return (\n <SignInProvidersSection\n title={text('mailbox')}\n description={text('mailboxDescription')}\n providers={links.map(({ id, name }) => ({ id, name }))}\n linked={data.mail}\n notes={signInOnlyNotes(links, data, providerNames)}\n reconnect\n onConnect={connect}\n error={linkError && providerMessage(linkError, links.length === 1 ? links[0]!.name : text('theProvider'))}\n >\n {/* Each change reads the list again, so the section shows what the server now has, such as the one default. */}\n <MailSendersSection\n senders={data.senders}\n onAdd={async (input) => {\n const added = await account.addMailSender(input)\n await reload()\n return added\n }}\n onUpdate={async (id, change) => {\n await account.updateMailSender(id, change)\n await reload()\n }}\n onRemove={async (id) => {\n await account.removeMailSender(id)\n await reload()\n }}\n />\n </SignInProvidersSection>\n )\n}\n\n/** The `PersonalMail` block: the mailboxes the signed-in person can link for the app to send mail from, hidden when the app has none. */\nexport const PersonalMailBlock = () => {\n const { personalMail } = useAuth()\n return personalMail.length > 0 ? <Mailboxes links={personalMail} /> : null\n}\n","import { Bot } from 'lucide-react'\nimport { useState } from 'react'\nimport { AuthError, type ConnectedApp } from '@protobase/client'\nimport { authMessage } from '../auth/auth-messages'\nimport { clientName } from '../connect/client-name'\nimport { clientPublisher } from '../connect/client-publisher'\nimport { formatDate } from '../format'\nimport { Button } from '../primitives/button'\nimport { Dialog } from '../primitives/dialog'\nimport { AccountSection, SectionError } from './account-section'\n\nexport type ConnectedAppsSectionProps = {\n apps: ConnectedApp[]\n /** Rejects with `AuthError`, which the section shows. */\n onDisconnect: (clientId: string) => Promise<void>\n}\n\nconst nameOf = (app: ConnectedApp) => clientName(app.name) ?? 'An unnamed app'\n\n// \"as Sales in Acme\", one per role and organization it was allowed with.\nconst accessOf = (app: ConnectedApp) =>\n app.access.map(({ role, organization }) => `as ${role || 'no role'}${organization ? ` in ${organization}` : ''}`).join(', ')\n\n/** The apps, such as MCP clients, the person allowed to act as them, each of which they can disconnect. */\nexport const ConnectedAppsSection = ({ apps, onDisconnect }: ConnectedAppsSectionProps) => {\n const [busy, setBusy] = useState(false)\n const [error, setError] = useState<string>()\n const [disconnecting, setDisconnecting] = useState<ConnectedApp>()\n\n const disconnect = async (app: ConnectedApp) => {\n setBusy(true)\n setError(undefined)\n try {\n await onDisconnect(app.clientId)\n setDisconnecting(undefined)\n } catch (failure) {\n if (!(failure instanceof AuthError)) throw failure\n setError(authMessage(failure))\n }\n setBusy(false)\n }\n\n return (\n <AccountSection title=\"Connected apps\" description=\"AI assistants and other apps you allowed to act as you here. Disconnecting one stops it within 15 minutes; it has to ask you again to come back.\">\n <SectionError message={disconnecting ? undefined : error} />\n {apps.length === 0 ? (\n <p className=\"text-muted-foreground\">No apps are connected. Add this app's MCP address to an AI assistant to connect one.</p>\n ) : (\n <ul className=\"divide-y rounded-md border\">\n {apps.map((app) => {\n const publisher = clientPublisher(app.clientId)\n return (\n <li key={app.clientId} className=\"flex flex-wrap items-center gap-3 px-3 py-2.5\">\n <Bot className=\"size-4 shrink-0 text-muted-foreground\" />\n <span className=\"min-w-0 flex-1\">\n <bdi className=\"block truncate font-medium\">{nameOf(app)}</bdi>\n <span className=\"block text-xs text-muted-foreground\">\n {publisher && `Published by ${publisher} · `}Allowed {formatDate(Date.parse(app.allowedAt))} · {accessOf(app)}\n </span>\n </span>\n <Button size=\"sm\" variant=\"ghost\" onClick={() => setDisconnecting(app)}>\n Disconnect\n </Button>\n </li>\n )\n })}\n </ul>\n )}\n {disconnecting && (\n <Dialog\n title={`Disconnect ${nameOf(disconnecting)}?`}\n description=\"It can no longer read or change anything as you. What it already started may keep working for up to 15 minutes.\"\n onClose={() => setDisconnecting(undefined)}\n actions={\n <>\n <Button onClick={() => setDisconnecting(undefined)}>Cancel</Button>\n <Button variant=\"danger\" loading={busy} onClick={() => void disconnect(disconnecting)}>\n Disconnect\n </Button>\n </>\n }\n >\n {error && <SectionError message={error} />}\n </Dialog>\n )}\n </AccountSection>\n )\n}\n","/**\n * The address of Claude's dialog that adds a custom connector, filled in with the MCP endpoint's `url` and, when the\n * app has one, its name; the person sees both there and confirms.\n */\nexport const connectorDialogUrl = (url: string, appName?: string) => {\n const dialog = new URL('https://claude.ai/customize/connectors')\n dialog.searchParams.set('modal', 'add-custom-connector')\n if (appName) dialog.searchParams.set('connectorName', appName)\n dialog.searchParams.set('connectorUrl', url)\n return dialog.href\n}\n","import { ExternalLink } from 'lucide-react'\nimport { buttonClass } from '../primitives/button'\nimport { AccountSection } from './account-section'\nimport { connectorDialogUrl } from './connector-dialog'\nimport { CopyField } from './copy-field'\nimport { text } from './messages'\n\n/** The address of the app's MCP endpoint, to copy into an AI client or add to Claude, with how connecting goes. */\nexport const McpAddressSection = ({ url, appName }: { url: string; appName?: string }) => (\n <AccountSection title={text('mcpAddress')} description={text('mcpAddressDescription')}>\n <div className=\"flex flex-wrap items-center gap-2\">\n <CopyField value={url} copyLabel={text('copyMcpAddress')} />\n <a href={connectorDialogUrl(url, appName)} target=\"_blank\" rel=\"noreferrer\" className={buttonClass()}>\n <ExternalLink className=\"size-3.5\" />\n {text('addToClaude')}\n </a>\n </div>\n </AccountSection>\n)\n","import { useCallback } from 'react'\nimport { useAuth } from '../../auth/auth-provider'\nimport { useAdminMeta } from '../../app/meta-gate'\nimport { ConnectedAppsSection } from '../connected-apps-section'\nimport { McpAddressSection } from '../mcp-address-section'\nimport { text } from '../messages'\nimport { AccountLoading } from './account-loading'\nimport { useAccountData } from './use-account-data'\n\nconst Apps = () => {\n const { account } = useAuth().session\n const { data: apps, error, reload } = useAccountData(useCallback(() => account.connectedApps(), [account]), text('couldNotReadMethods'))\n if (!apps) return <AccountLoading error={error} />\n return <ConnectedAppsSection apps={apps} onDisconnect={(clientId) => account.disconnectApp(clientId).then(reload)} />\n}\n\nconst Mcp = ({ url }: { url: string }) => (\n <>\n <McpAddressSection url={url} appName={useAdminMeta().appName} />\n <Apps />\n </>\n)\n\n/**\n * The `ConnectedApps` block: the address of the app's MCP endpoint and the apps the signed-in person allowed to act as\n * them, hidden when the app has no MCP.\n */\nexport const ConnectedAppsBlock = () => {\n const { mcp } = useAuth()\n return mcp ? <Mcp url={mcp.url} /> : null\n}\n","import { KeySquare, Plus } from 'lucide-react'\nimport { useRef, useState } from 'react'\nimport { AuthError, type NewPersonalAccessToken, type PersonalAccessToken } from '@protobase/client'\nimport { confirmationMinutes } from '@protobase/schema/internal'\nimport { ConfirmSignIn } from '../app/confirm-sign-in'\nimport { authMessage } from '../auth/auth-messages'\nimport { formatDate } from '../format'\nimport { Button } from '../primitives/button'\nimport { Dialog } from '../primitives/dialog'\nimport { Input } from '../primitives/input'\nimport { Select } from '../primitives/select'\nimport { AccountSection, SectionError } from './account-section'\nimport { CopyField } from './copy-field'\nimport { text } from './messages'\n\nexport type PersonalAccessTokensSectionProps = {\n tokens: PersonalAccessToken[]\n /** Rejects with `AuthError`, which the section shows, or answers by asking the person to confirm it's them. */\n onCreate: (input: { name: string; expiresInDays?: number }) => Promise<NewPersonalAccessToken>\n /** Rejects with `AuthError`, which the section shows. */\n onRevoke: (id: string) => Promise<void>\n}\n\n// The lifetimes offered, in days; `never` makes a token that lasts until it is revoked.\nconst lifetimes = { '30': 30, '90': 90, '365': 365, never: undefined } as const\ntype Lifetime = keyof typeof lifetimes\nconst lifetimeLabels = { '30': 'expiresIn30Days', '90': 'expiresIn90Days', '365': 'expiresInAYear', never: 'neverExpires' } as const\n\nconst dateOf = (iso: string) => formatDate(Date.parse(iso))\n\n// When it expires, or expired: a token past its expiry stays listed until it is revoked.\nconst expiryOf = (expiresAt: string | undefined) => {\n if (!expiresAt) return text('neverExpires')\n return Date.parse(expiresAt) <= Date.now() ? text('expiredOn', { date: dateOf(expiresAt) }) : text('expiresOn', { date: dateOf(expiresAt) })\n}\n\n// \"Created 1 Aug 2026 · Expires 30 Aug 2026 · Last used 2 Aug 2026 · As Sales in Acme\".\nconst detailsOf = (token: PersonalAccessToken) =>\n [\n text('createdOn', { date: dateOf(token.createdAt) }),\n expiryOf(token.expiresAt),\n token.lastUsedAt ? text('lastUsedOn', { date: dateOf(token.lastUsedAt) }) : text('notUsedYet'),\n token.organization ? text('actsAsIn', { role: token.role, organization: token.organization }) : text('actsAs', { role: token.role }),\n ].join(' · ')\n\ntype Editing = { kind: 'create' } | { kind: 'created'; created: NewPersonalAccessToken } | { kind: 'revoke'; token: PersonalAccessToken }\n\n/**\n * The person's personal access tokens, which let a script call the app's API as them: each with when it was made,\n * expires and was last used, and what it acts as, to revoke; and a new one, shown once to copy, since the app keeps\n * only its hash. An older session confirms it's them before a new token, in place.\n */\nexport const PersonalAccessTokensSection = ({ tokens, onCreate, onRevoke }: PersonalAccessTokensSectionProps) => {\n const [busy, setBusy] = useState(false)\n const [error, setError] = useState<string>()\n const [editing, setEditing] = useState<Editing>()\n const [name, setName] = useState('')\n const [lifetime, setLifetime] = useState<Lifetime>('90')\n const [confirming, setConfirming] = useState<'asked' | 'done'>()\n\n const close = () => {\n setEditing(undefined)\n setError(undefined)\n setConfirming(undefined)\n }\n\n // Set at once, unlike `busy`, so a second click before the next render makes no second token.\n const inFlight = useRef(false)\n\n const attempt = async (action: () => Promise<Editing | undefined>) => {\n if (inFlight.current) return\n inFlight.current = true\n setBusy(true)\n setError(undefined)\n try {\n setEditing(await action())\n setConfirming(undefined)\n } catch (failure) {\n // The browser's fetch rejects with a TypeError when the connection fails, before or after the server acted.\n if (failure instanceof TypeError) return setError(text('noAnswerFromServer'))\n if (!(failure instanceof AuthError)) throw failure\n if (failure.code === 'STRONG_SIGN_IN_REQUIRED') setConfirming('asked')\n else setError(authMessage(failure))\n } finally {\n inFlight.current = false\n setBusy(false)\n }\n }\n\n const create = () =>\n attempt(async () => {\n const days = lifetimes[lifetime]\n const created = await onCreate({ name: name.trim(), ...(days !== undefined && { expiresInDays: days }) })\n return { kind: 'created', created }\n })\n\n return (\n <AccountSection title={text('accessTokens')} description={text('accessTokensDescription')}>\n <SectionError message={editing ? undefined : error} />\n {tokens.length === 0 ? (\n <p className=\"mb-3 text-muted-foreground\">{text('noAccessTokens')}</p>\n ) : (\n <ul className=\"mb-3 divide-y rounded-md border\">\n {tokens.map((token) => (\n <li key={token.id} className=\"flex flex-wrap items-center gap-3 px-3 py-2.5\">\n <KeySquare className=\"size-4 shrink-0 text-muted-foreground\" />\n <span className=\"min-w-0 flex-1\">\n <bdi className=\"block truncate font-medium\">{token.name}</bdi>\n <span className=\"block text-xs text-muted-foreground\">{detailsOf(token)}</span>\n </span>\n <Button size=\"sm\" variant=\"ghost\" onClick={() => setEditing({ kind: 'revoke', token })}>\n {text('revoke')}\n </Button>\n </li>\n ))}\n </ul>\n )}\n <Button\n onClick={() => {\n setName('')\n setLifetime('90')\n setEditing({ kind: 'create' })\n }}\n >\n <Plus className=\"size-3.5\" />\n {text('newAccessToken')}\n </Button>\n {editing?.kind === 'create' && (\n <Dialog\n title={text('newAccessToken')}\n description={text('newAccessTokenDescription')}\n onClose={close}\n actions={\n <>\n <Button onClick={close}>{text('cancel')}</Button>\n <Button variant=\"primary\" loading={busy} disabled={!name.trim()} onClick={() => void create()}>\n {text('createAccessToken')}\n </Button>\n </>\n }\n >\n <label className=\"flex flex-col gap-1.5 font-medium\">\n {text('name')}\n <Input autoFocus value={name} maxLength={100} placeholder={text('accessTokenNamePlaceholder')} onChange={(event) => setName(event.target.value)} />\n </label>\n <label className=\"mt-3 flex flex-col gap-1.5 font-medium\">\n {text('accessTokenExpiry')}\n <Select value={lifetime} onChange={(event) => setLifetime(event.target.value as Lifetime)}>\n {(Object.keys(lifetimes) as Lifetime[]).map((option) => (\n <option key={option} value={option}>\n {text(lifetimeLabels[option])}\n </option>\n ))}\n </Select>\n </label>\n {/* Confirming signs the browser in anew or confirms its session; the person then makes the token again. */}\n {confirming === 'asked' && <ConfirmSignIn purpose=\"change\" minutes={confirmationMinutes} onConfirmed={() => setConfirming('done')} />}\n {confirming === 'done' && <p className=\"mt-2 text-muted-foreground\">{text('confirmedCreateAccessToken')}</p>}\n <SectionError message={error} />\n </Dialog>\n )}\n {editing?.kind === 'created' && (\n <Dialog\n title={text('accessTokenCreated', { name: editing.created.personalAccessToken.name })}\n description={text('accessTokenCreatedDescription')}\n onClose={close}\n actions={\n <Button variant=\"primary\" onClick={close}>\n {text('done')}\n </Button>\n }\n >\n <CopyField value={editing.created.token} copyLabel={text('copyAccessToken')} />\n </Dialog>\n )}\n {editing?.kind === 'revoke' && (\n <Dialog\n title={text('revokeAccessToken', { name: editing.token.name })}\n description={text('revokeAccessTokenDescription')}\n onClose={close}\n actions={\n <>\n <Button onClick={close}>{text('cancel')}</Button>\n <Button variant=\"danger\" loading={busy} onClick={() => void attempt(async () => (await onRevoke(editing.token.id), undefined))}>\n {text('revoke')}\n </Button>\n </>\n }\n >\n <SectionError message={error} />\n </Dialog>\n )}\n </AccountSection>\n )\n}\n","import { useCallback } from 'react'\nimport { useAuth } from '../../auth/auth-provider'\nimport { SectionError } from '../account-section'\nimport { PersonalAccessTokensSection } from '../personal-access-tokens-section'\nimport { text } from '../messages'\nimport { AccountLoading } from './account-loading'\nimport { useAccountData } from './use-account-data'\n\nconst Tokens = () => {\n const { account } = useAuth().session\n const { data: tokens, error, reload } = useAccountData(useCallback(() => account.personalAccessTokens(), [account]), text('couldNotReadAccessTokens'))\n if (!tokens) return <AccountLoading error={error} />\n // The list is read again after every change. A new token reaches its dialog at once, to be copied while the list\n // loads; a failed change, whose answer may have been lost after the server made it, waits for the list before the\n // dialog lets the person try again. A list that could not be read again says so above it.\n return (\n <>\n <SectionError message={error} />\n <PersonalAccessTokensSection\n tokens={tokens}\n onCreate={(input) =>\n account.createPersonalAccessToken(input).then(\n (created) => {\n void reload()\n return created\n },\n async (failure: unknown) => {\n await reload()\n throw failure\n },\n )\n }\n onRevoke={(id) => account.revokePersonalAccessToken(id).finally(reload)}\n />\n </>\n )\n}\n\n/** The `PersonalAccessTokens` block: the signed-in person's personal access tokens, hidden when the app has none. */\nexport const PersonalAccessTokensBlock = () => (useAuth().personalAccessTokens ? <Tokens /> : null)\n","import { PlugZap } from 'lucide-react'\nimport { Fragment, useState } from 'react'\nimport { AuthError, type ConnectionRevocation, type WorkflowConnection } from '@protobase/client'\nimport { authMessage } from '../auth/auth-messages'\nimport { RecordLink } from '../app/displays/record-link'\nimport { formatDate } from '../format'\nimport { Badge } from '../primitives/badge'\nimport { Button } from '../primitives/button'\nimport { Dialog } from '../primitives/dialog'\nimport { AccountSection, SectionError, SectionNotice } from './account-section'\nimport { text } from './messages'\n\nexport type ConnectionsSectionProps = {\n connections: WorkflowConnection[]\n /** Leaves for the provider to connect an account; rejects with `AuthError`, which the section shows. */\n onConnect: (connection: WorkflowConnection) => Promise<void>\n /** Answers what became of the account's token, which the section says; rejects with `AuthError`, which it shows. */\n onDisconnect: (accountId: string) => Promise<ConnectionRevocation>\n /** Why the last connect did not go through, as the provider came back with it. */\n error?: string\n}\n\ntype Chosen = { connection: WorkflowConnection; accountId: string }\n\nconst disconnected = { revoked: 'disconnectedRevoked', queued: 'disconnectedQueued', not_revoked: 'disconnectedNotRevoked' } as const satisfies Record<ConnectionRevocation, string>\n\n// Revoking at Google ends every grant the account gave this app, the sign-in and a linked mailbox included.\nconst wholeGrant = (connection: WorkflowConnection) => connection.provider === 'google'\n\n/**\n * The accounts the person connected for their workflows' steps to use, by the connection the app's plugins declare:\n * each one connects an account, again when a trigger waits for it, and disconnects one, which revokes its token and\n * says whether the provider took it. Each account links to the workflows that use it.\n */\nexport const ConnectionsSection = ({ connections, onConnect, onDisconnect, error: returned }: ConnectionsSectionProps) => {\n const [busy, setBusy] = useState<string>()\n const [error, setError] = useState(returned)\n const [chosen, setChosen] = useState<Chosen>()\n const [notice, setNotice] = useState<string>()\n\n const attempt = async (key: string, work: () => Promise<void>) => {\n setBusy(key)\n setError(undefined)\n setNotice(undefined)\n try {\n await work()\n setChosen(undefined)\n } catch (failure) {\n if (!(failure instanceof AuthError)) throw failure\n setError(authMessage(failure))\n } finally {\n setBusy(undefined)\n }\n }\n\n return (\n <AccountSection title={text('connections')} description={text('connectionsDescription')}>\n <SectionError message={chosen ? undefined : error} />\n <SectionNotice message={notice} />\n <ul className=\"divide-y rounded-md border\">\n {connections.map((connection) => (\n <li key={connection.key} className=\"flex flex-col gap-2 px-3 py-2.5\">\n <div className=\"flex flex-wrap items-center gap-3\">\n <PlugZap className=\"size-4 shrink-0 text-muted-foreground\" />\n <span className=\"min-w-0 flex-1 truncate font-medium\">{connection.label}</span>\n <Button size=\"sm\" loading={busy === connection.key} disabled={busy !== undefined} onClick={() => void attempt(connection.key, () => onConnect(connection))}>\n {connection.accounts.length > 0 ? text('connectAgain', { name: connection.label }) : text('connect', { name: connection.label })}\n </Button>\n </div>\n {connection.accounts.map((account) => (\n <Fragment key={account.id}>\n <div className=\"flex flex-wrap items-center gap-3 pl-7 text-sm\">\n <span className=\"min-w-0 flex-1 text-muted-foreground\">\n {text('connectedOn', { date: formatDate(Date.parse(account.created_at)) })} · <code className=\"text-xs\">{account.id}</code>\n </span>\n {account.needs_sign_in ? <Badge tone=\"amber\">{text('connectionNeedsSignIn')}</Badge> : <Badge tone=\"green\">{text('connected')}</Badge>}\n <Button size=\"sm\" variant=\"ghost\" onClick={() => setChosen({ connection, accountId: account.id })}>\n {text('disconnect')}\n </Button>\n </div>\n {account.used_by.length > 0 && (\n <div className=\"flex flex-wrap items-center gap-x-3 gap-y-1 pl-7 text-sm\">\n <span className=\"text-muted-foreground\">{text('connectionUsedBy')}</span>\n {account.used_by.map((workflow) => (\n <RecordLink key={workflow.id} resource=\"workflows\" recordKey={workflow.id} className=\"font-medium text-primary-text hover:underline\">\n {workflow.name}\n </RecordLink>\n ))}\n </div>\n )}\n </Fragment>\n ))}\n </li>\n ))}\n </ul>\n {chosen && (\n <Dialog\n title={text('disconnectTitle', { name: chosen.connection.label })}\n description={wholeGrant(chosen.connection) ? `${text('disconnectDescription')} ${text('disconnectWholeGrant')}` : text('disconnectDescription')}\n onClose={() => setChosen(undefined)}\n actions={\n <>\n <Button onClick={() => setChosen(undefined)}>{text('cancel')}</Button>\n <Button variant=\"danger\" loading={busy === chosen.accountId} onClick={() => void attempt(chosen.accountId, async () => setNotice(text(disconnected[await onDisconnect(chosen.accountId)])))}>\n {text('disconnect')}\n </Button>\n </>\n }\n >\n {error && <SectionError message={error} />}\n </Dialog>\n )}\n </AccountSection>\n )\n}\n","import { useCallback, useState } from 'react'\nimport { providerMessage } from '../../auth/auth-messages'\nimport { useAuth } from '../../auth/auth-provider'\nimport { ConnectionsSection } from '../connections-section'\nimport { text } from '../messages'\nimport { AccountLoading } from './account-loading'\nimport { takeLinkError } from './connected-accounts-block'\nimport { useAccountData } from './use-account-data'\n\n/** The `Connections` block: the accounts the signed-in person connected for their workflows, hidden when the app's plugins declare none. */\nexport const ConnectionsBlock = () => {\n const { session, connectAccount } = useAuth()\n const { account } = session\n const [linkError] = useState(takeLinkError)\n const { data: connections, error, reload } = useAccountData(useCallback(() => account.workflowConnections(), [account]), text('couldNotReadMethods'))\n if (!connections) return <AccountLoading error={error} />\n if (connections.length === 0) return null\n return <ConnectionsSection connections={connections} onConnect={connectAccount} onDisconnect={(id) => account.disconnectAccount(id).finally(reload)} error={linkError && providerMessage(linkError, text('theProvider'))} />\n}\n","import { useId, useState } from 'react'\nimport { AuthError } from '@protobase/client'\nimport { confirmationMinutes } from '@protobase/schema/internal'\nimport { ConfirmSignIn } from '../app/confirm-sign-in'\nimport { authMessage } from '../auth/auth-messages'\nimport { Button } from '../primitives/button'\nimport { Dialog } from '../primitives/dialog'\nimport { Input } from '../primitives/input'\nimport { SectionError } from './account-section'\nimport { text } from './messages'\n\nexport type DeleteAccountDialogProps = {\n /** The account has a password: ask for it. Without one, a session older than a day confirms it's them in place first. */\n hasPassword: boolean\n /** Rejects with `AuthError`, which the dialog shows; resolves once the account is gone. */\n onDelete: (password?: string) => Promise<void>\n onClose: () => void\n}\n\n// The server's refusals of this deletion, in words for the person at the keyboard.\nconst deletionMessage = (error: AuthError) => {\n if (error.code === 'LAST_ADMIN') return text('deleteAccountLastAdmin')\n if (error.code === 'ACCOUNT_LOCKED') return text('deleteAccountLocked')\n return authMessage(error)\n}\n\n/** Asks the person to confirm deleting their own account, with their password when it has one. */\nexport const DeleteAccountDialog = ({ hasPassword, onDelete, onClose }: DeleteAccountDialogProps) => {\n const [password, setPassword] = useState('')\n const [busy, setBusy] = useState(false)\n const [error, setError] = useState<string>()\n const [confirming, setConfirming] = useState(false)\n const formId = useId()\n\n const confirm = async () => {\n setBusy(true)\n setError(undefined)\n setConfirming(false)\n try {\n await onDelete(hasPassword ? password : undefined)\n } catch (failure) {\n if (!(failure instanceof AuthError)) throw failure\n if (failure.code === 'STRONG_SIGN_IN_REQUIRED') setConfirming(true)\n else setError(deletionMessage(failure))\n setBusy(false)\n }\n }\n\n return (\n <Dialog\n title={text('deleteAccountQuestion')}\n description={text('deleteAccountWarning')}\n onClose={onClose}\n actions={\n <>\n <Button onClick={onClose}>{text('cancel')}</Button>\n <Button variant=\"danger\" type=\"submit\" form={formId} loading={busy} disabled={hasPassword && !password}>\n {text('deleteAccountConfirm')}\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 confirm()\n }}\n >\n {hasPassword && (\n <label className=\"flex flex-col gap-1.5 font-medium\">\n {text('deleteAccountPassword')}\n <Input type=\"password\" name=\"current-password\" autoComplete=\"current-password\" autoFocus value={password} invalid={Boolean(error)} onChange={(event) => setPassword(event.target.value)} />\n </label>\n )}\n <SectionError message={error} />\n </form>\n {/* Outside the form, since the confirmation has forms of its own. */}\n {confirming && <ConfirmSignIn purpose=\"change\" minutes={confirmationMinutes} onConfirmed={() => void confirm()} />}\n </Dialog>\n )\n}\n","import { useState } from 'react'\nimport { Button } from '../primitives/button'\nimport { AccountSection } from './account-section'\nimport { DeleteAccountDialog } from './delete-account-dialog'\nimport { text } from './messages'\n\nexport type DeleteAccountSectionProps = {\n hasPassword: boolean\n /** Staff signed in as the person, who may not delete their account: the section only says so. */\n staff: boolean\n /** Rejects with `AuthError`, which the dialog shows; resolves once the account is gone and this device signed out. */\n onDelete: (password?: string) => Promise<void>\n}\n\n/** Deletes the signed-in person's own account, once they confirm it in a dialog. */\nexport const DeleteAccountSection = ({ hasPassword, staff, onDelete }: DeleteAccountSectionProps) => {\n const [confirming, setConfirming] = useState(false)\n return (\n <AccountSection title={text('deleteAccount')} description={staff ? text('deleteAccountStaff') : text('deleteAccountDescription')}>\n {!staff && (\n <Button variant=\"danger\" onClick={() => setConfirming(true)}>\n {text('deleteAccount')}\n </Button>\n )}\n {confirming && <DeleteAccountDialog hasPassword={hasPassword} onDelete={onDelete} onClose={() => setConfirming(false)} />}\n </AccountSection>\n )\n}\n","import { useCallback } from 'react'\nimport { useAuth } from '../../auth/auth-provider'\nimport { DeleteAccountSection } from '../delete-account-section'\nimport { text } from '../messages'\nimport { AccountLoading } from './account-loading'\nimport { useAccountData } from './use-account-data'\n\n/** The `DeleteAccount` block: the signed-in person deletes their own account, which signs them out; staff signed in as them cannot. */\nexport const DeleteAccountBlock = () => {\n const { session, state, deleteAccount } = useAuth()\n const { account } = session\n const { data: methods, error } = useAccountData(useCallback(() => account.signInMethods(), [account]), text('couldNotReadMethods'))\n if (!methods) return <AccountLoading error={error} />\n return <DeleteAccountSection hasPassword={methods.account.password} staff={state.kind === 'signed-in' && Boolean(state.staff)} onDelete={deleteAccount} />\n}\n","// In the order to test them: Edge, Opera and Samsung Internet also say Chrome, and Chrome also says Safari.\nconst browsers: Array<[RegExp, string]> = [\n [/Edg(e|A|iOS)?\\//, 'Edge'],\n [/OPR\\/|Opera/, 'Opera'],\n [/SamsungBrowser\\//, 'Samsung Internet'],\n [/Firefox\\/|FxiOS\\//, 'Firefox'],\n [/Chrome\\/|CriOS\\//, 'Chrome'],\n [/Safari\\//, 'Safari'],\n]\n\n// iPads and Android also say Mac OS X and Linux.\nconst systems: Array<[RegExp, string]> = [\n [/iPhone/, 'iPhone'],\n [/iPad/, 'iPad'],\n [/Android/, 'Android'],\n [/CrOS/, 'ChromeOS'],\n [/Windows/, 'Windows'],\n [/Mac OS X|Macintosh/, 'macOS'],\n [/Linux/, 'Linux'],\n]\n\nconst find = (list: Array<[RegExp, string]>, userAgent: string) => list.find(([pattern]) => pattern.test(userAgent))?.[1]\n\n/** The browser and system a user agent names, such as Chrome and macOS, each `undefined` when it names none we know. */\nexport const deviceOf = (userAgent: string | undefined) => (userAgent ? { browser: find(browsers, userAgent), system: find(systems, userAgent) } : {})\n","import { Laptop, ShieldUser, Smartphone, Tablet } from 'lucide-react'\nimport { useState } from 'react'\nimport { AuthError, type DeviceLink, type DeviceSession } from '@protobase/client'\nimport { authMessage } from '../auth/auth-messages'\nimport { formatDateTime } from '../format'\nimport { Badge } from '../primitives/badge'\nimport { Button } from '../primitives/button'\nimport { Dialog } from '../primitives/dialog'\nimport { AccountSection, SectionError } from './account-section'\nimport { deviceOf } from './device-name'\nimport { text } from './messages'\n\nexport type DevicesSectionProps = {\n sessions: DeviceSession[]\n /** The operator provider's name, which names a staff session; `undefined` when the app has none. */\n operator?: string\n /** The devices the platform links, each listed once with the sessions it began. */\n links?: DeviceLink[]\n /** Each rejects with `AuthError`, which the section shows. */\n onSignOut: (token: string) => Promise<void>\n onSignOutOthers: () => Promise<void>\n /** Signs a linked device out for good. */\n onSignOutLink?: (id: string) => Promise<void>\n}\n\n// A linked device is named by its provider and, when its token gave one, its own name.\nconst linkName = (link: DeviceLink) => (link.device ? text('deviceThrough', { device: link.device, provider: link.name }) : link.name)\n\n// A staff session is named for the operator alone: the person sees that its staff signed in and when, not who.\nconst nameOf = (session: DeviceSession, operator: string | undefined) => {\n if (session.staff) return operator ? text('staffOf', { operator }) : text('staff')\n const { browser, system } = deviceOf(session.userAgent)\n if (browser && system) return text('browserOn', { browser, system })\n if (system) return text('aBrowserOn', { system })\n return browser ?? text('unknownDevice')\n}\n\nconst iconOf = (session: DeviceSession) => {\n if (session.staff) return ShieldUser\n const { system } = deviceOf(session.userAgent)\n if (system === 'iPhone' || system === 'Android') return Smartphone\n if (system === 'iPad') return Tablet\n return Laptop\n}\n\n// This device first, then the newest sign-in.\nconst ordered = (sessions: DeviceSession[]) => [...sessions].sort((a, b) => Number(b.current) - Number(a.current) || b.createdAt.localeCompare(a.createdAt))\n\ntype Confirming = { kind: 'one'; session: DeviceSession } | { kind: 'link'; link: DeviceLink } | { kind: 'others' }\n\nconst titleOf = (what: Confirming, operator: string | undefined) => {\n if (what.kind === 'one') return text('signOutDevice', { name: nameOf(what.session, operator) })\n if (what.kind === 'link') return text('signOutDevice', { name: linkName(what.link) })\n return text('signOutOthersTitle')\n}\n\nconst descriptionOf = (what: Confirming) => text(what.kind === 'one' ? 'signOutDeviceDescription' : what.kind === 'link' ? 'signOutLinkedDeviceDescription' : 'signOutOthersDescription')\n\n/**\n * The devices signed in to the person's account, this one marked, each other one of which they can sign out; and the\n * devices the platform links, each of which they can sign out for good, with the sessions it began.\n */\nexport const DevicesSection = ({ sessions: all, operator, links = [], onSignOut, onSignOutOthers, onSignOutLink }: DevicesSectionProps) => {\n const [busy, setBusy] = useState(false)\n const [error, setError] = useState<string>()\n const [confirming, setConfirming] = useState<Confirming>()\n // A linked device's sessions show as that device.\n const sessions = all.filter((session) => !links.some((link) => link.sessions.includes(session.token)))\n const others = all.filter((session) => !session.current)\n\n const run = (what: Confirming) => {\n if (what.kind === 'one') return onSignOut(what.session.token)\n if (what.kind === 'link') return onSignOutLink!(what.link.id)\n return onSignOutOthers()\n }\n\n const signOut = async (what: Confirming) => {\n setBusy(true)\n setError(undefined)\n try {\n await run(what)\n setConfirming(undefined)\n } catch (failure) {\n if (!(failure instanceof AuthError)) throw failure\n setError(authMessage(failure))\n }\n setBusy(false)\n }\n\n const open = (what: Confirming) => {\n setError(undefined)\n setConfirming(what)\n }\n\n return (\n <AccountSection title={text('devices')} description={text('devicesDescription')}>\n {sessions.length === 0 && links.length === 0 ? (\n <p className=\"text-muted-foreground\">{text('noDevices')}</p>\n ) : (\n <ul className=\"divide-y rounded-md border\">\n {ordered(sessions).map((session) => {\n const Icon = iconOf(session)\n return (\n <li key={session.token} className=\"flex flex-wrap items-center gap-3 px-3 py-2.5\">\n <Icon className=\"size-4 shrink-0 text-muted-foreground\" />\n <span className=\"min-w-0 flex-1\">\n <span className=\"flex flex-wrap items-center gap-2\">\n <bdi className=\"truncate font-medium\">{nameOf(session, operator)}</bdi>\n {session.current && <Badge tone=\"green\">{text('thisDevice')}</Badge>}\n </span>\n <span className=\"block text-xs text-muted-foreground\">\n {text('signedInFromUntil', { from: formatDateTime(Date.parse(session.createdAt)), until: formatDateTime(Date.parse(session.expiresAt)) })}\n {!session.staff && session.ipAddress && ` · ${session.ipAddress}`}\n </span>\n </span>\n {!session.current && (\n <Button size=\"sm\" variant=\"ghost\" onClick={() => open({ kind: 'one', session })}>\n {text('signOut')}\n </Button>\n )}\n </li>\n )\n })}\n {links.map((link) => {\n const current = all.some((session) => session.current && link.sessions.includes(session.token))\n return (\n <li key={link.id} className=\"flex flex-wrap items-center gap-3 px-3 py-2.5\">\n <Smartphone className=\"size-4 shrink-0 text-muted-foreground\" />\n <span className=\"min-w-0 flex-1\">\n <span className=\"flex flex-wrap items-center gap-2\">\n <bdi className=\"truncate font-medium\">{linkName(link)}</bdi>\n {current && <Badge tone=\"green\">{text('thisDevice')}</Badge>}\n </span>\n <span className=\"block text-xs text-muted-foreground\">{text('linkedOn', { date: formatDateTime(Date.parse(link.linkedAt)) })}</span>\n </span>\n {!current && onSignOutLink && (\n <Button size=\"sm\" variant=\"ghost\" onClick={() => open({ kind: 'link', link })}>\n {text('signOut')}\n </Button>\n )}\n </li>\n )\n })}\n </ul>\n )}\n {others.length > 0 && (\n <Button className=\"mt-3\" onClick={() => open({ kind: 'others' })}>\n {text('signOutOthers')}\n </Button>\n )}\n {confirming && (\n <Dialog\n title={titleOf(confirming, operator)}\n description={descriptionOf(confirming)}\n onClose={() => setConfirming(undefined)}\n actions={\n <>\n <Button onClick={() => setConfirming(undefined)}>{text('cancel')}</Button>\n <Button variant=\"danger\" loading={busy} onClick={() => void signOut(confirming)}>\n {text('signOut')}\n </Button>\n </>\n }\n >\n <SectionError message={error} />\n </Dialog>\n )}\n </AccountSection>\n )\n}\n","import { useCallback } from 'react'\nimport { useAuth } from '../../auth/auth-provider'\nimport { DevicesSection } from '../devices-section'\nimport { text } from '../messages'\nimport { AccountLoading } from './account-loading'\nimport { useAccountData } from './use-account-data'\n\n/**\n * The `Devices` block: the browsers and apps signed in as the person, this one marked, the others to sign out; and the\n * devices the platform links, when it links any.\n */\nexport const DevicesBlock = () => {\n const { session, staffSignIn, deviceLinks } = useAuth()\n const { account } = session\n const read = useCallback(async () => {\n const [sessions, links] = await Promise.all([account.sessions(), deviceLinks ? account.deviceLinks() : []])\n return { sessions, links }\n }, [account, deviceLinks])\n const { data, error, reload } = useAccountData(read, text('couldNotReadDevices'))\n if (!data) return <AccountLoading error={error} />\n return (\n <DevicesSection\n sessions={data.sessions}\n links={data.links}\n operator={staffSignIn}\n onSignOut={(token) => account.revokeSession(token).then(reload)}\n onSignOutOthers={() => account.revokeOtherSessions().then(reload)}\n onSignOutLink={(id) => account.signOutDeviceLink(id).then(reload)}\n />\n )\n}\n","import { KeyRound, Plus } from 'lucide-react'\nimport { useState } from 'react'\nimport { AuthError, type Passkey, type SignInRule } from '@protobase/client'\nimport { confirmationMinutes } from '@protobase/schema/internal'\nimport { ConfirmSignIn } from '../app/confirm-sign-in'\nimport { authMessage } from '../auth/auth-messages'\nimport { formatDate } from '../format'\nimport { Badge } from '../primitives/badge'\nimport { Button } from '../primitives/button'\nimport { Dialog } from '../primitives/dialog'\nimport { Input } from '../primitives/input'\nimport { AccountSection, SectionError } from './account-section'\nimport { text } from './messages'\n\nexport type PasskeysSectionProps = {\n /** What the sign-in policy says about passkeys. */\n rule: SignInRule\n passkeys: Passkey[]\n /** Each rejects with `AuthError`, which the section shows. */\n onAdd: () => Promise<void>\n onRename: (id: string, name: string) => Promise<void>\n onRemove: (id: string) => Promise<void>\n}\n\nconst descriptions = { allowed: 'passkeysAllowed', required: 'passkeysRequired', forbidden: 'passkeysForbidden' } as const satisfies Record<SignInRule, string>\n\ntype Editing = { kind: 'rename'; passkey: Passkey } | { kind: 'remove'; passkey: Passkey }\n\nexport const PasskeysSection = ({ rule, passkeys, onAdd, onRename, onRemove }: PasskeysSectionProps) => {\n const [busy, setBusy] = useState(false)\n const [error, setError] = useState<string>()\n const [editing, setEditing] = useState<Editing>()\n const [name, setName] = useState('')\n // A passkey asks an older session to confirm it's them first; a first one, on an account without a second step, may take the password.\n const [confirming, setConfirming] = useState<'asked' | 'done'>()\n const keepLast = rule === 'required' && passkeys.length <= 1\n\n const attempt = async (action: () => Promise<void>) => {\n setBusy(true)\n setError(undefined)\n setConfirming(undefined)\n try {\n await action()\n setEditing(undefined)\n } catch (failure) {\n if (!(failure instanceof AuthError)) throw failure\n if (failure.code === 'STRONG_SIGN_IN_REQUIRED') setConfirming('asked')\n else setError(authMessage(failure))\n }\n setBusy(false)\n }\n\n return (\n <AccountSection title={text('passkeys')} status={rule === 'required' && <Badge tone=\"blue\">{text('required')}</Badge>} description={text(descriptions[rule])}>\n <SectionError message={editing ? undefined : error} />\n {passkeys.length > 0 && (\n <ul className=\"mb-3 divide-y rounded-md border\">\n {passkeys.map((passkey) => (\n <li key={passkey.id} className=\"flex flex-wrap items-center gap-3 px-3 py-2.5\">\n <KeyRound className=\"size-4 shrink-0 text-muted-foreground\" />\n <span className=\"min-w-0 flex-1\">\n <span className=\"block truncate font-medium\">{passkey.name ?? text('passkey')}</span>\n <span className=\"block text-xs text-muted-foreground\">\n {passkey.createdAt ? text('addedOn', { date: formatDate(Date.parse(passkey.createdAt)) }) : text('addedEarlier')} · {passkey.backedUp ? text('synced') : text('oneDevice')}\n </span>\n </span>\n <span className=\"flex gap-1\">\n <Button\n size=\"sm\"\n variant=\"ghost\"\n onClick={() => {\n setName(passkey.name ?? '')\n setEditing({ kind: 'rename', passkey })\n }}\n >\n {text('rename')}\n </Button>\n <Button size=\"sm\" variant=\"ghost\" disabled={keepLast} title={keepLast ? text('keepLastPasskey') : undefined} onClick={() => setEditing({ kind: 'remove', passkey })}>\n {text('remove')}\n </Button>\n </span>\n </li>\n ))}\n </ul>\n )}\n {rule !== 'forbidden' && (\n <Button loading={busy && !editing} onClick={() => void attempt(onAdd)}>\n <Plus className=\"size-3.5\" />\n {text('addPasskey')}\n </Button>\n )}\n {/* The browser asks for the new passkey only on a click, so the person adds it again once confirmed. */}\n {confirming === 'asked' && <ConfirmSignIn purpose=\"change\" withPassword minutes={confirmationMinutes} onConfirmed={() => setConfirming('done')} />}\n {confirming === 'done' && <p className=\"mt-2 text-muted-foreground\">{text('confirmedAddPasskey')}</p>}\n {editing?.kind === 'rename' && (\n <Dialog\n title={text('renamePasskey')}\n description={text('renamePasskeyDescription')}\n onClose={() => setEditing(undefined)}\n actions={\n <>\n <Button onClick={() => setEditing(undefined)}>{text('cancel')}</Button>\n <Button variant=\"primary\" loading={busy} disabled={!name.trim()} onClick={() => void attempt(() => onRename(editing.passkey.id, name.trim()))}>\n {text('save')}\n </Button>\n </>\n }\n >\n <label className=\"flex flex-col gap-1.5 font-medium\">\n {text('name')}\n <Input autoFocus value={name} maxLength={60} onChange={(event) => setName(event.target.value)} />\n </label>\n <SectionError message={error} />\n </Dialog>\n )}\n {editing?.kind === 'remove' && (\n <Dialog\n title={text('removePasskey')}\n description={text('removePasskeyDescription', { name: editing.passkey.name ?? text('thisPasskey') })}\n onClose={() => setEditing(undefined)}\n actions={\n <>\n <Button onClick={() => setEditing(undefined)}>{text('cancel')}</Button>\n <Button variant=\"danger\" loading={busy} onClick={() => void attempt(() => onRemove(editing.passkey.id))}>\n {text('remove')}\n </Button>\n </>\n }\n >\n {error && <SectionError message={error} />}\n </Dialog>\n )}\n </AccountSection>\n )\n}\n","import { useCallback } from 'react'\nimport { useAuth } from '../../auth/auth-provider'\nimport { PasskeysSection } from '../passkeys-section'\nimport { text } from '../messages'\nimport { AccountLoading } from './account-loading'\nimport { useAccountData } from './use-account-data'\n\n/** The `Passkeys` block: the signed-in person's passkeys, within what the sign-in policy allows. */\nexport const PasskeysBlock = () => {\n const { account } = useAuth().session\n const load = useCallback(() => Promise.all([account.signInMethods(), account.passkeys()]), [account])\n const { data, error, reload } = useAccountData(load, text('couldNotReadMethods'))\n if (!data) return <AccountLoading error={error} />\n const [methods, passkeys] = data\n return (\n <PasskeysSection\n rule={methods.policy.passkey}\n passkeys={passkeys}\n onAdd={() => account.addPasskey().then(reload)}\n onRename={(id, name) => account.renamePasskey(id, name).then(reload)}\n onRemove={(id) => account.removePasskey(id).then(reload)}\n />\n )\n}\n","import { useId, useState } from 'react'\nimport { AuthError } from '@protobase/client'\nimport { authMessage } from '../auth/auth-messages'\nimport { minPasswordLength } from '../auth/reset-password-form'\nimport { Button } from '../primitives/button'\nimport { Dialog } from '../primitives/dialog'\nimport { Input } from '../primitives/input'\nimport { SectionError } from './account-section'\nimport { text } from './messages'\n\nexport type PasswordChangeDialogProps = {\n /** The account has a password: ask for it, and say the other devices are signed out. Without one, it sets the first. */\n hasPassword: boolean\n /** Rejects with `AuthError`, which the dialog shows; resolves when the password is saved. */\n onSave: (input: { current: string; next: string }) => Promise<void>\n onClose: () => void\n}\n\n// Better Auth's answers to a new password or a wrong current one, in words for the person at the keyboard.\nconst passwordMessage = (error: AuthError) => {\n if (error.code === 'PASSWORD_TOO_SHORT') return text('useAtLeast', { length: minPasswordLength })\n if (error.code === 'PASSWORD_TOO_LONG') return text('passwordTooLong')\n return authMessage(error)\n}\n\n// Why the new password cannot be sent yet, before the server is asked.\nconst draftProblem = (next: string, repeat: string) => {\n if (next.length < minPasswordLength) return text('useAtLeast', { length: minPasswordLength })\n if (next !== repeat) return text('passwordsDiffer')\n return undefined\n}\n\n/** Changes the account's password with the current one, or sets a first one for an account without. */\nexport const PasswordChangeDialog = ({ hasPassword, onSave, onClose }: PasswordChangeDialogProps) => {\n const [current, setCurrent] = useState('')\n const [next, setNext] = useState('')\n const [repeat, setRepeat] = useState('')\n const [busy, setBusy] = useState(false)\n const [error, setError] = useState<string>()\n const formId = useId()\n const filled = (!hasPassword || current) && next && repeat\n\n const save = async () => {\n const problem = draftProblem(next, repeat)\n setError(problem)\n if (problem) return\n setBusy(true)\n try {\n await onSave({ current, next })\n } catch (failure) {\n if (!(failure instanceof AuthError)) throw failure\n setError(passwordMessage(failure))\n setBusy(false)\n }\n }\n\n return (\n <Dialog\n title={hasPassword ? text('changePassword') : text('setPassword')}\n description={text('atLeast', { length: minPasswordLength })}\n onClose={onClose}\n actions={\n <>\n <Button onClick={onClose}>{text('cancel')}</Button>\n <Button variant=\"primary\" type=\"submit\" form={formId} loading={busy} disabled={!filled}>\n {text('save')}\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 save()\n }}\n >\n {hasPassword && (\n <label className=\"flex flex-col gap-1.5 font-medium\">\n {text('currentPassword')}\n <Input type=\"password\" name=\"current-password\" autoComplete=\"current-password\" autoFocus value={current} onChange={(event) => setCurrent(event.target.value)} />\n </label>\n )}\n <label className=\"flex flex-col gap-1.5 font-medium\">\n {text('newPassword')}\n <Input type=\"password\" name=\"new-password\" autoComplete=\"new-password\" autoFocus={!hasPassword} value={next} invalid={Boolean(error)} onChange={(event) => setNext(event.target.value)} />\n </label>\n <label className=\"flex flex-col gap-1.5 font-medium\">\n {text('repeatPassword')}\n <Input type=\"password\" name=\"repeat-password\" autoComplete=\"new-password\" value={repeat} invalid={Boolean(error)} onChange={(event) => setRepeat(event.target.value)} />\n </label>\n {hasPassword && <p className=\"text-muted-foreground\">{text('changeSignsOutOthers')}</p>}\n <SectionError message={error} />\n </form>\n </Dialog>\n )\n}\n","import { useState } from 'react'\nimport { Button } from '../primitives/button'\nimport { AccountSection, SectionNotice } from './account-section'\nimport { PasswordChangeDialog } from './password-change-dialog'\nimport { text } from './messages'\n\nexport type PasswordSectionProps = {\n /** What the sign-in policy says about passwords: while they are off, the section only says so. */\n rule: 'allowed' | 'forbidden'\n hasPassword: boolean\n /** Staff signed in as the person, who may not change their sign-in: the section only says so. */\n staff: boolean\n /** Each rejects with `AuthError`, which the dialog shows. */\n onChange: (current: string, next: string) => Promise<void>\n onSet: (next: string) => Promise<void>\n}\n\nconst descriptionOf = ({ rule, hasPassword, staff }: Pick<PasswordSectionProps, 'rule' | 'hasPassword' | 'staff'>) => {\n if (staff) return text('passwordStaff')\n if (rule === 'forbidden') return text('passwordForbidden')\n return hasPassword ? text('passwordIsSet') : text('passwordNotSet')\n}\n\n/** The signed-in person's password: change it with the current one, or set a first one without signing anyone out. */\nexport const PasswordSection = ({ rule, hasPassword, staff, onChange, onSet }: PasswordSectionProps) => {\n const [editing, setEditing] = useState(false)\n const [saved, setSaved] = useState(false)\n const canEdit = !staff && rule === 'allowed'\n\n return (\n <AccountSection title={text('password')} description={descriptionOf({ rule, hasPassword, staff })}>\n <SectionNotice message={saved ? text('passwordSaved') : undefined} />\n {canEdit && (\n <Button\n onClick={() => {\n setSaved(false)\n setEditing(true)\n }}\n >\n {hasPassword ? text('changePassword') : text('setPassword')}\n </Button>\n )}\n {editing && (\n <PasswordChangeDialog\n hasPassword={hasPassword}\n onClose={() => setEditing(false)}\n onSave={async ({ current, next }) => {\n await (hasPassword ? onChange(current, next) : onSet(next))\n setEditing(false)\n setSaved(true)\n }}\n />\n )}\n </AccountSection>\n )\n}\n","import { useCallback } from 'react'\nimport { useAuth } from '../../auth/auth-provider'\nimport { PasswordSection } from '../password-section'\nimport { text } from '../messages'\nimport { AccountLoading } from './account-loading'\nimport { useAccountData } from './use-account-data'\n\n/**\n * The `Password` block: the signed-in person changes their password, or sets a first one without signing anyone out,\n * within what the sign-in policy allows; staff signed in as the person cannot.\n */\nexport const PasswordBlock = () => {\n const { session, state } = useAuth()\n const { account } = session\n const { data: methods, error, reload } = useAccountData(useCallback(() => account.signInMethods(), [account]), text('couldNotReadMethods'))\n if (!methods) return <AccountLoading error={error} />\n return (\n <PasswordSection\n rule={methods.policy.password}\n hasPassword={methods.account.password}\n staff={state.kind === 'signed-in' && Boolean(state.staff)}\n onChange={(current, next) => account.changePassword(current, next).then(reload)}\n onSet={(next) => account.setPassword(next).then(reload)}\n />\n )\n}\n","import { useState } from 'react'\nimport { AuthError } from '@protobase/client'\nimport { emailCodeMinutes } from '@protobase/schema/internal'\nimport { authMessage } from '../auth/auth-messages'\nimport { Button } from '../primitives/button'\nimport { Dialog } from '../primitives/dialog'\nimport { Input } from '../primitives/input'\nimport { OtpInput } from '../primitives/otp-input'\nimport { SectionError } from './account-section'\nimport { text } from './messages'\n\n/** Changing the address: a code mailed to the new one, then that code. Each rejects with `AuthError`, which the dialog shows. */\nexport type EmailChange = {\n request: (newEmail: string) => Promise<void>\n confirm: (newEmail: string, code: string) => Promise<void>\n}\n\nexport type ChangeEmailDialogProps = { email: string; change: EmailChange; onDone: () => void; onClose: () => void }\n\n/** Asks for the new address, mails it a code, and moves the account to it once the code is right. */\nexport const ChangeEmailDialog = ({ email, change, onDone, onClose }: ChangeEmailDialogProps) => {\n const [draft, setDraft] = useState('')\n const [sentTo, setSentTo] = useState<string>()\n const [code, setCode] = useState('')\n const [busy, setBusy] = useState(false)\n const [error, setError] = useState<string>()\n\n const run = async (step: () => Promise<void>) => {\n setBusy(true)\n setError(undefined)\n try {\n await step()\n } catch (failure) {\n if (!(failure instanceof AuthError)) throw failure\n setError(authMessage(failure))\n }\n setBusy(false)\n }\n\n const newEmail = draft.trim()\n const send = () =>\n run(async () => {\n await change.request(newEmail)\n setCode('')\n setSentTo(newEmail)\n })\n const confirm = (complete: string) =>\n run(async () => {\n await change.confirm(sentTo!, complete)\n onDone()\n })\n\n if (!sentTo) {\n return (\n <Dialog\n title={text('changeEmail')}\n description={text('changeEmailDescription')}\n onClose={onClose}\n actions={\n <>\n <Button onClick={onClose}>{text('cancel')}</Button>\n <Button variant=\"primary\" loading={busy} disabled={!newEmail || newEmail.toLowerCase() === email.toLowerCase()} onClick={() => void send()}>\n {text('sendCode')}\n </Button>\n </>\n }\n >\n <label className=\"flex flex-col gap-1.5 font-medium\">\n {text('newEmail')}\n <Input type=\"email\" autoComplete=\"email\" autoFocus value={draft} onChange={(event) => setDraft(event.target.value)} />\n </label>\n <SectionError message={error} />\n </Dialog>\n )\n }\n\n return (\n <Dialog\n title={text('changeEmail')}\n description={text('codeSentTo', { email: sentTo, minutes: emailCodeMinutes })}\n onClose={onClose}\n actions={\n <>\n <Button\n variant=\"ghost\"\n onClick={() => {\n setSentTo(undefined)\n setError(undefined)\n }}\n >\n {text('otherAddress')}\n </Button>\n <Button variant=\"primary\" loading={busy} disabled={code.length < 6} onClick={() => void confirm(code)}>\n {text('changeEmail')}\n </Button>\n </>\n }\n >\n <label className=\"flex flex-col gap-1.5 font-medium\">\n {text('code')}\n <OtpInput name=\"code\" required autoFocus value={code} invalid={Boolean(error)} onChange={setCode} onComplete={(complete) => !busy && void confirm(complete)} />\n </label>\n <SectionError message={error} />\n </Dialog>\n )\n}\n","import { useState } from 'react'\nimport { AuthError } from '@protobase/client'\nimport { authMessage } from '../auth/auth-messages'\nimport { Button } from '../primitives/button'\nimport { Dialog } from '../primitives/dialog'\nimport { Input } from '../primitives/input'\nimport { AccountSection, SectionError } from './account-section'\nimport { ChangeEmailDialog, type EmailChange } from './change-email-dialog'\nimport { text } from './messages'\n\nexport type ProfileSectionProps = {\n name: string\n email: string\n /** Rejects with `AuthError`, which the section shows. */\n onRename: (name: string) => Promise<void>\n /** Offers to change the address, when the server can mail the code that confirms it. */\n emailChange?: EmailChange\n /** Called once the address changed, to read it back. */\n onEmailChanged?: () => void\n}\n\n/** The signed-in person's name, which they can change, and the address they sign in with, which they can change with mail. */\nexport const ProfileSection = ({ name, email, onRename, emailChange, onEmailChanged }: ProfileSectionProps) => {\n const [editing, setEditing] = useState(false)\n const [changingEmail, setChangingEmail] = useState(false)\n const [draft, setDraft] = useState('')\n const [busy, setBusy] = useState(false)\n const [error, setError] = useState<string>()\n\n const rename = async () => {\n setBusy(true)\n setError(undefined)\n try {\n await onRename(draft.trim())\n setEditing(false)\n } catch (failure) {\n if (!(failure instanceof AuthError)) throw failure\n setError(authMessage(failure))\n }\n setBusy(false)\n }\n\n return (\n <AccountSection title={text('profile')} description={text('profileDescription')}>\n <dl className=\"mb-3 grid grid-cols-[auto_1fr] gap-x-6 gap-y-1.5\">\n <dt className=\"text-muted-foreground\">{text('name')}</dt>\n <dd className=\"min-w-0 truncate font-medium\">{name}</dd>\n <dt className=\"text-muted-foreground\">{text('email')}</dt>\n <dd className=\"min-w-0 truncate font-medium\">{email}</dd>\n </dl>\n <div className=\"flex flex-wrap gap-2\">\n <Button\n onClick={() => {\n setDraft(name)\n setError(undefined)\n setEditing(true)\n }}\n >\n {text('changeName')}\n </Button>\n {emailChange && <Button onClick={() => setChangingEmail(true)}>{text('changeEmail')}</Button>}\n </div>\n {editing && (\n <Dialog\n title={text('changeName')}\n description={text('changeNameDescription')}\n onClose={() => setEditing(false)}\n actions={\n <>\n <Button onClick={() => setEditing(false)}>{text('cancel')}</Button>\n <Button variant=\"primary\" loading={busy} disabled={!draft.trim() || draft.trim() === name} onClick={() => void rename()}>\n {text('save')}\n </Button>\n </>\n }\n >\n <label className=\"flex flex-col gap-1.5 font-medium\">\n {text('name')}\n <Input autoFocus value={draft} maxLength={100} onChange={(event) => setDraft(event.target.value)} />\n </label>\n <SectionError message={error} />\n </Dialog>\n )}\n {changingEmail && emailChange && (\n <ChangeEmailDialog\n email={email}\n change={emailChange}\n onClose={() => setChangingEmail(false)}\n onDone={() => {\n setChangingEmail(false)\n onEmailChanged?.()\n }}\n />\n )}\n </AccountSection>\n )\n}\n","import { useCallback } from 'react'\nimport { useAuth } from '../../auth/auth-provider'\nimport { ProfileSection } from '../profile-section'\nimport { text } from '../messages'\nimport { AccountLoading } from './account-loading'\nimport { useAccountData } from './use-account-data'\n\n/** The `Profile` block: the signed-in person's name and address, which they can change; the address only with mail. */\nexport const ProfileBlock = () => {\n const { session, changeEmail } = useAuth()\n const { data: user, loaded, error, reload } = useAccountData(useCallback(() => session.session(), [session]), text('couldNotReadProfile'))\n if (!loaded) return <AccountLoading error={error} />\n if (!user) return null\n const emailChange = changeEmail ? { request: session.account.requestEmailChange, confirm: session.account.changeEmail } : undefined\n return <ProfileSection name={user.name} email={user.email} onRename={(name) => session.account.updateName(name).then(reload)} emailChange={emailChange} onEmailChanged={reload} />\n}\n","import { useState } from 'react'\nimport { AuthError } from '@protobase/client'\nimport { confirmationMinutes } from '@protobase/schema/internal'\nimport { ConfirmSignIn } from '../app/confirm-sign-in'\nimport { authMessage } from '../auth/auth-messages'\nimport { Button } from '../primitives/button'\nimport { Dialog } from '../primitives/dialog'\nimport { Input } from '../primitives/input'\nimport { text } from './messages'\n\nexport type PasswordDialogProps = {\n title: string\n description: string\n /** The button that runs `onConfirm`, for example \"Turn off\". */\n confirmLabel: string\n danger?: boolean\n /** Ask for the password, which the change needs when the account has one. */\n needsPassword: boolean\n /** Rejects with `AuthError`, which the dialog shows; resolves when the change is done. */\n onConfirm: (password?: string) => Promise<void>\n onClose: () => void\n}\n\n/**\n * Confirms a change to the account's sign-in, with the password when it has one. Without one, an older session that the\n * change refuses (`STRONG_SIGN_IN_REQUIRED`) confirms it's them in place, and the change runs again.\n */\nexport const PasswordDialog = ({ title, description, confirmLabel, danger, needsPassword, onConfirm, onClose }: PasswordDialogProps) => {\n const [password, setPassword] = useState('')\n const [busy, setBusy] = useState(false)\n const [error, setError] = useState<string>()\n const [confirming, setConfirming] = useState(false)\n\n const confirm = async () => {\n setBusy(true)\n setError(undefined)\n setConfirming(false)\n try {\n await onConfirm(needsPassword ? password : undefined)\n } catch (failure) {\n if (!(failure instanceof AuthError)) throw failure\n if (failure.code === 'STRONG_SIGN_IN_REQUIRED') setConfirming(true)\n else setError(authMessage(failure))\n setBusy(false)\n }\n }\n\n return (\n <Dialog\n title={title}\n description={description}\n onClose={onClose}\n actions={\n <>\n <Button onClick={onClose}>{text('cancel')}</Button>\n <Button variant={danger ? 'danger' : 'primary'} loading={busy} disabled={needsPassword && !password} onClick={() => void confirm()}>\n {confirmLabel}\n </Button>\n </>\n }\n >\n {needsPassword && (\n <label className=\"flex flex-col gap-1.5 font-medium\">\n {text('yourPassword')}\n <Input type=\"password\" autoComplete=\"current-password\" autoFocus value={password} invalid={Boolean(error)} onChange={(event) => setPassword(event.target.value)} onKeyDown={(event) => event.key === 'Enter' && password && void confirm()} />\n </label>\n )}\n {error && (\n <p role=\"alert\" className=\"mt-2 text-body font-medium text-danger-text\">\n {error}\n </p>\n )}\n {confirming && <ConfirmSignIn purpose=\"change\" minutes={confirmationMinutes} onConfirmed={() => void confirm()} />}\n </Dialog>\n )\n}\n","import { useState } from 'react'\nimport type { AuthenticatorSetup, SignInRule } from '@protobase/client'\nimport { Badge } from '../primitives/badge'\nimport { Button } from '../primitives/button'\nimport { Dialog } from '../primitives/dialog'\nimport { AccountSection } from './account-section'\nimport { BackupCodes } from './backup-codes'\nimport { PasswordDialog } from './password-dialog'\nimport { TwoFactorSetup } from './two-factor-setup'\nimport { text } from './messages'\n\nexport type TwoFactorSectionProps = {\n /** What the sign-in policy says about two-factor authentication. */\n rule: SignInRule\n /** The account has it on, with an authenticator app (and backup codes) or with emailed codes only. */\n enabled: boolean\n authenticatorApp: boolean\n /** Mail can be sent, so emailed codes are offered. */\n mail: boolean\n /** The account has a password, which changes here ask for. */\n needsPassword: boolean\n /** Each rejects with `AuthError`, which the section shows. */\n onStartApp: (password?: string) => Promise<AuthenticatorSetup>\n onConfirmApp: (code: string) => Promise<void>\n onEmailedCodes: (password?: string) => Promise<void>\n onTurnOff: (password?: string) => Promise<void>\n onNewBackupCodes: (password?: string) => Promise<string[]>\n /** Something changed: read the account again. */\n onChanged: () => void\n}\n\nconst offDescriptions = { allowed: 'twoFactorAllowed', required: 'twoFactorRequired', forbidden: 'twoFactorForbidden' } as const satisfies Record<SignInRule, string>\n\ntype Open = { kind: 'setup'; appOnly: boolean } | { kind: 'turn-off' } | { kind: 'new-codes' } | { kind: 'codes'; codes: string[] }\n\nexport const TwoFactorSection = (props: TwoFactorSectionProps) => {\n const { rule, enabled, authenticatorApp, mail, needsPassword, onTurnOff, onNewBackupCodes, onChanged } = props\n const [open, setOpen] = useState<Open>()\n const close = () => setOpen(undefined)\n\n const status = enabled ? <Badge tone=\"green\">{text('on')}</Badge> : rule === 'required' ? <Badge tone=\"amber\">{text('required')}</Badge> : <Badge>{text('off')}</Badge>\n const description = !enabled\n ? text(offDescriptions[rule])\n : authenticatorApp\n ? text(mail ? 'twoFactorOnWithAppOrMail' : 'twoFactorOnWithApp')\n : text('twoFactorOnWithMail')\n\n if (open?.kind === 'setup') {\n return (\n <AccountSection title={text('twoFactor')} status={status} description={description}>\n <div className=\"max-w-sm\">\n <TwoFactorSetup\n offerEmailedCodes={mail && !open.appOnly}\n needsPassword={needsPassword}\n onStartApp={props.onStartApp}\n onConfirmApp={props.onConfirmApp}\n onEmailedCodes={props.onEmailedCodes}\n onCancel={close}\n onDone={() => {\n close()\n onChanged()\n }}\n />\n </div>\n </AccountSection>\n )\n }\n\n return (\n <AccountSection title={text('twoFactor')} status={status} description={description}>\n <div className=\"flex flex-wrap gap-2\">\n {!enabled && rule !== 'forbidden' && (\n <Button variant=\"primary\" onClick={() => setOpen({ kind: 'setup', appOnly: false })}>\n {text('turnOn')}\n </Button>\n )}\n {enabled && !authenticatorApp && rule !== 'forbidden' && <Button onClick={() => setOpen({ kind: 'setup', appOnly: true })}>{text('addAuthenticator')}</Button>}\n {enabled && authenticatorApp && <Button onClick={() => setOpen({ kind: 'new-codes' })}>{text('newBackupCodes')}</Button>}\n {enabled && (\n <Button variant=\"danger\" disabled={rule === 'required'} title={rule === 'required' ? text('twoFactorIsRequired') : undefined} onClick={() => setOpen({ kind: 'turn-off' })}>\n {text('turnOff')}\n </Button>\n )}\n </div>\n {open?.kind === 'turn-off' && (\n <PasswordDialog\n title={text('turnOffTitle')}\n description={text('turnOffDescription')}\n confirmLabel={text('turnOff')}\n danger\n needsPassword={needsPassword}\n onClose={close}\n onConfirm={async (password) => {\n await onTurnOff(password)\n close()\n onChanged()\n }}\n />\n )}\n {open?.kind === 'new-codes' && (\n <PasswordDialog\n title={text('newCodesTitle')}\n description={text('newCodesDescription')}\n confirmLabel={text('makeNewCodes')}\n needsPassword={needsPassword}\n onClose={close}\n onConfirm={async (password) => setOpen({ kind: 'codes', codes: await onNewBackupCodes(password) })}\n />\n )}\n {open?.kind === 'codes' && (\n <Dialog\n title={text('yourNewCodes')}\n description={text('keepCodesSafe')}\n onClose={close}\n actions={\n <Button variant=\"primary\" onClick={close}>\n {text('savedCodes')}\n </Button>\n }\n >\n <BackupCodes codes={open.codes} />\n </Dialog>\n )}\n </AccountSection>\n )\n}\n","import { useCallback } from 'react'\nimport { useAuth } from '../../auth/auth-provider'\nimport { TwoFactorSection } from '../two-factor-section'\nimport { text } from '../messages'\nimport { AccountLoading } from './account-loading'\nimport { useAccountData } from './use-account-data'\n\n/** The `TwoFactor` block: the signed-in person's two-factor authentication, within what the sign-in policy allows. */\nexport const TwoFactorBlock = () => {\n const { account } = useAuth().session\n const { data: methods, error, reload } = useAccountData(useCallback(() => account.signInMethods(), [account]), text('couldNotReadMethods'))\n if (!methods) return <AccountLoading error={error} />\n return (\n <TwoFactorSection\n rule={methods.policy.twoFactor}\n enabled={methods.account.twoFactor}\n authenticatorApp={methods.account.authenticatorApp}\n mail={methods.mail}\n needsPassword={methods.account.password}\n onStartApp={(password) => account.startAuthenticatorApp(password)}\n onConfirmApp={(code) => account.confirmAuthenticatorApp(code)}\n onEmailedCodes={(password) => account.turnOnEmailedCodes(password)}\n onTurnOff={(password) => account.turnOffTwoFactor(password)}\n onNewBackupCodes={(password) => account.newBackupCodes(password)}\n onChanged={reload}\n />\n )\n}\n","import type { ReactNode } from 'react'\nimport { CustomBoundary } from './custom-boundary'\nimport { Problem } from './problem'\nimport { text } from './messages'\n\n/** What stands in for a custom component the app cannot draw: its fallback, under the warning in development, or the warning alone without one. */\nconst Replacement = ({ problem, fallback }: { problem: ReactNode; fallback: ReactNode | undefined }) => {\n if (fallback === undefined) return <Problem>{problem}</Problem>\n return (\n <>\n {import.meta.env?.DEV && <Problem>{problem}</Problem>}\n {fallback}\n </>\n )\n}\n\ntype CustomOrFallbackProps = {\n /** The component's registered name. */\n name: string\n /** Whether the app has a component registered under `name`. */\n registered: boolean\n /** The fallback the layout declares, drawn when the component is missing or throws; `undefined` when it declares none. */\n fallback: ReactNode | undefined\n /** The component, drawn when it is registered. */\n children: ReactNode\n}\n\n/** A project's or plugin's layout component, or, when it is missing or throws, the fallback its layout declares. */\nexport const CustomOrFallback = ({ name, registered, fallback, children }: CustomOrFallbackProps) => {\n if (!registered) return <Replacement problem={text.rich('noComponent', { component: name })} fallback={fallback} />\n return (\n <CustomBoundary name={name} fallback={fallback === undefined ? undefined : <Replacement problem={text.rich('couldNotDraw', { name })} fallback={fallback} />}>\n {children}\n </CustomBoundary>\n )\n}\n","import { Fragment, useMemo, type ComponentType } from 'react'\nimport { fillProps, formatMessage, isInlineChild, isLayoutNode, pointerOf, scopeValue, type LayoutChild, type LayoutNode, type LayoutValue, type ReaderTexts } from '@protobase/layout'\nimport { fillText, unmarkFieldRefs, valueText } from '@protobase/schema/internal'\nimport { ActionBlock } from './blocks/action'\nimport type { BlockProps } from './blocks/block-props'\nimport { CardBlock } from './blocks/card'\nimport { CardRowBlock } from './blocks/card-row'\nimport { ChartBlock } from './blocks/chart'\nimport { TimelineBlock } from './blocks/timeline/timeline'\nimport { GraphBlock } from './blocks/graph/graph-block'\nimport { ComposerBlock } from './blocks/composer'\nimport { DetailsBlock, SummaryBlock } from './blocks/details'\nimport { DiffBlock } from './blocks/diff'\nimport { FieldBlock } from './blocks/field'\nimport { GridBlock } from './blocks/grid'\nimport { ImageBlock } from './blocks/image'\nimport { BooleanFieldBlock, ChipFieldBlock, DateFieldBlock, NumberFieldBlock, TextFieldBlock, UrlFieldBlock } from './blocks/inline-field'\nimport { LinkBlock } from './blocks/link'\nimport { ModalFormBlock } from './blocks/modal-form'\nimport { PageBlock } from './blocks/page-block'\nimport { ProgressBlock } from './blocks/progress'\nimport { RecordCardBlock } from './blocks/record-card'\nimport { RecordCardsBlock } from './blocks/record-cards'\nimport { RecordRowBlock } from './blocks/record-row'\nimport { SettingsBlock } from './blocks/settings'\nimport { ShowBlock } from './blocks/show'\nimport { MatchBlock, SwitchBlock } from './blocks/switch'\nimport { StatBlock } from './blocks/stat'\nimport { TableBlock } from './blocks/table'\nimport { TabBlock, TabsBlock } from './blocks/tabs'\nimport { ThreadBlock } from './blocks/thread'\nimport { BoxBlock, ColumnBlock, RowBlock, TextBlock } from './blocks/plain'\nimport { ArrayFieldBlock } from './blocks/array-field'\nimport { RecordsIteratorBlock } from './blocks/records-iterator'\nimport { SelectInputBlock } from './blocks/select-input'\nimport { ReferenceArrayFieldBlock } from './blocks/reference-array-field'\nimport { ReferenceFieldBlock } from './blocks/reference-field'\nimport { ReferenceManyFieldBlock } from './blocks/reference-many-field'\nimport { UsersBlock } from '../../users/users-block'\nimport { ConnectedAccountsBlock } from '../../account/blocks/connected-accounts-block'\nimport { PersonalMailBlock } from '../../account/blocks/personal-mail-block'\nimport { ConnectedAppsBlock } from '../../account/blocks/connected-apps-block'\nimport { PersonalAccessTokensBlock } from '../../account/blocks/personal-access-tokens-block'\nimport { ConnectionsBlock } from '../../account/blocks/connections-block'\nimport { DeleteAccountBlock } from '../../account/blocks/delete-account-block'\nimport { DevicesBlock } from '../../account/blocks/devices-block'\nimport { PasskeysBlock } from '../../account/blocks/passkeys-block'\nimport { PasswordBlock } from '../../account/blocks/password-block'\nimport { ProfileBlock } from '../../account/blocks/profile-block'\nimport { TwoFactorBlock } from '../../account/blocks/two-factor-block'\nimport { ComponentElement } from './component-reads'\nimport { CustomBoundary } from './custom-boundary'\nimport { CustomChosen } from './custom-chosen'\nimport { CustomOrFallback } from './custom-or-fallback'\nimport { Problem } from './problem'\nimport { useProjectUi } from './project-ui'\nimport { usePageParamValues } from './page-params'\nimport { useScopeStack, valueScopeOf } from './record-scope'\nimport { text } from './messages'\nimport { useAppTexts, withPropTexts } from './app-texts'\n\nconst blocks: Record<string, ComponentType<BlockProps>> = {\n Page: PageBlock,\n Grid: GridBlock,\n Card: CardBlock,\n Stat: StatBlock,\n RecordCard: RecordCardBlock,\n Field: FieldBlock,\n Diff: DiffBlock,\n Table: TableBlock,\n CardRow: CardRowBlock,\n RecordRow: RecordRowBlock,\n RecordCards: RecordCardsBlock,\n Chart: ChartBlock,\n Timeline: TimelineBlock,\n Graph: GraphBlock,\n Progress: ProgressBlock,\n Image: ImageBlock,\n ModalForm: ModalFormBlock,\n Thread: ThreadBlock,\n Composer: ComposerBlock,\n Action: ActionBlock,\n Show: ShowBlock,\n Switch: SwitchBlock,\n Match: MatchBlock,\n Link: LinkBlock,\n Settings: SettingsBlock,\n Tabs: TabsBlock,\n Tab: TabBlock,\n Users: UsersBlock,\n Profile: ProfileBlock,\n Password: PasswordBlock,\n Passkeys: PasskeysBlock,\n TwoFactor: TwoFactorBlock,\n ConnectedAccounts: ConnectedAccountsBlock,\n PersonalMail: PersonalMailBlock,\n Connections: ConnectionsBlock,\n Devices: DevicesBlock,\n ConnectedApps: ConnectedAppsBlock,\n PersonalAccessTokens: PersonalAccessTokensBlock,\n DeleteAccount: DeleteAccountBlock,\n Box: BoxBlock,\n Row: RowBlock,\n Column: ColumnBlock,\n Text: TextBlock,\n ReferenceManyField: ReferenceManyFieldBlock,\n ReferenceArrayField: ReferenceArrayFieldBlock,\n ArrayField: ArrayFieldBlock,\n RecordsIterator: RecordsIteratorBlock,\n ReferenceField: ReferenceFieldBlock,\n SelectInput: SelectInputBlock,\n Details: DetailsBlock,\n Summary: SummaryBlock,\n TextField: TextFieldBlock,\n NumberField: NumberFieldBlock,\n DateField: DateFieldBlock,\n BooleanField: BooleanFieldBlock,\n UrlField: UrlFieldBlock,\n ChipField: ChipFieldBlock,\n}\n\n// The blocks that put their classes on an element of their own; the others draw none, or several, and get a <div> for them.\nconst ownClasses = new Set(['Page', 'Grid', 'Card', 'Stat', 'RecordCard', 'Field', 'Diff', 'Table', 'CardRow', 'RecordRow', 'RecordCards', 'Chart', 'Timeline', 'Graph', 'Progress', 'Image', 'Thread', 'Link', 'Tabs', 'Settings', 'Show', 'Switch', 'Action', 'Box', 'Row', 'Column', 'Text', 'ReferenceField', 'SelectInput', 'Details', 'Summary', 'TextField', 'NumberField', 'DateField', 'BooleanField', 'UrlField', 'ChipField'])\n\n/** A child and its place in the page's tree, the JSON Pointer its planned read names it by; none outside a page. */\ntype Placed = { child: LayoutChild; at?: string }\n\nconst placed = (children: LayoutChild[], at: string | undefined, ...steps: string[]): Placed[] =>\n children.map((child, index) => ({ child, ...(at !== undefined && { at: pointerOf(at, ...steps, index) }) }))\n\n/** A text child with its `{{path}}`s filled from the records around it and the page's parameters, as a prop's are. */\nconst FilledText = ({ text }: { text: string }) => {\n const stack = useScopeStack()\n const params = usePageParamValues()\n const scope = { ...valueScopeOf(stack), params }\n return <>{fillText(text, (path) => valueText(scopeValue(scope, path)))}</>\n}\n\nconst textChild = (text: string, key: number) => (text.includes('{{') ? <FilledText key={key} text={text} /> : <Fragment key={key}>{text}</Fragment>)\n\n/** Text and links as they run in one line. */\nconst renderInline = (run: Placed[]) => run.map(({ child, at }, position) => (typeof child === 'string' ? textChild(child, position) : <RenderNode key={position} node={child} at={at} />))\n\n/** Text, links and field components run together as one paragraph, like a sentence with a link in it; other elements stand alone. */\nconst renderChildren = (children: Placed[]) => {\n const runs: Placed[][] = []\n for (const entry of children) {\n const last = runs.at(-1)\n if (isInlineChild(entry.child) && last && isInlineChild(last[0]!.child)) last.push(entry)\n else runs.push([entry])\n }\n return runs.map((run, index) => {\n const [first] = run\n if (!isInlineChild(first!.child)) return <RenderNode key={index} node={first!.child as LayoutNode} at={first!.at} />\n return (\n <p key={index} className=\"leading-6\">\n {renderInline(run)}\n </p>\n )\n })\n}\n\nconst isElements = (value: LayoutValue): value is LayoutNode | LayoutNode[] => isLayoutNode(value) || (Array.isArray(value) && value.length > 0 && value.every(isLayoutNode))\n\n/** Element props (`actions={...}`) rendered like children; the block decides where they go and in which record. */\nconst renderSlots = (node: LayoutNode, at: string | undefined) =>\n Object.fromEntries(Object.entries(node.props).flatMap(([name, value]) => (isElements(value) ? [[name, <>{renderChildren(slotted(value, at, name))}</>]] : [])))\n\n// One element in a prop is at the prop itself, a list of them each at its index\nconst slotted = (value: LayoutNode | LayoutNode[], at: string | undefined, name: string): Placed[] =>\n Array.isArray(value) ? placed(value, at, 'props', name) : [{ child: value, ...(at !== undefined && { at: pointerOf(at, 'props', name) }) }]\n\nconst isObject = (value: unknown): value is Record<string, LayoutValue> => typeof value === 'object' && value !== null && !Array.isArray(value)\n\n// A <Trans> child as the text it runs as: its message in the user's language, each tag the element `components` gives\n// it with the text inside the tag as its children\nconst transChildren = (node: LayoutNode, texts: ReaderTexts | undefined): LayoutChild[] => {\n const components = isObject(node.props.components) ? node.props.components : {}\n const tags = Object.fromEntries(Object.entries(components).flatMap(([tag, element]) => (isLayoutNode(element) ? [[tag, (chunks: unknown[]) => ({ ...element, children: [...element.children, ...(chunks as LayoutChild[])] })]] : [])))\n const formatted = formatMessage<LayoutNode>(texts, String(node.props.i18nKey), isObject(node.props.values) ? node.props.values : {}, tags)\n return Array.isArray(formatted) ? formatted.map((part) => (typeof part === 'string' || isLayoutNode(part) ? part : String(part))) : [formatted]\n}\n\n/**\n * One element of a composed page: a built-in block, or the project's component registered under its name. A block's\n * `{{path}}`s are filled from the records around it and the page's parameters before it draws. `at` is its place in\n * the page's tree, by which a block finds its planned read.\n */\nexport const RenderNode = ({ node: written, at }: { node: LayoutNode; at?: string }) => {\n const { components } = useProjectUi()\n const stack = useScopeStack()\n const params = usePageParamValues()\n const texts = useAppTexts()\n const node = useMemo(() => withPropTexts(fillProps(written, { ...valueScopeOf(stack), params }), texts), [written, stack, params, texts])\n if (node.type === 'Trans' && !node.custom) return <>{renderInline(transChildren(node, texts).map((child) => ({ child })))}</>\n if (node.custom) {\n const Custom = components?.[node.type]\n // Field references reach the component as the names they reference; its children draw in the record its\n // `select` chose, and its declared reads reach it through useComponentReads\n const children = node.children.length > 0 ? <CustomChosen node={node}>{renderChildren(placed(node.children, at, 'children'))}</CustomChosen> : undefined\n return (\n <CustomOrFallback name={node.type} registered={Boolean(Custom)} fallback={node.fallback && <>{renderChildren(placed(node.fallback, at, 'fallback'))}</>}>\n {Custom && (\n <ComponentElement node={node} {...(at !== undefined && { at })}>\n <Custom {...unmarkFieldRefs(node.props)}>{children}</Custom>\n </ComponentElement>\n )}\n </CustomOrFallback>\n )\n }\n const Block = blocks[node.type]\n if (!Block) return <Problem>{text.rich('unknownBlock', { type: node.type })}</Problem>\n const className = typeof node.props.className === 'string' ? node.props.className : undefined\n const children = placed(node.children, at, 'children')\n // A Text and a Summary are one line, and a Link a piece of one: what they hold runs inline, in no paragraph of its own\n const block = (\n <Block node={node} at={at} slots={renderSlots(node, at)} className={className}>\n {node.type === 'Text' || node.type === 'Link' || node.type === 'Summary' ? renderInline(children) : renderChildren(node.type === 'Switch' ? children.filter(({ child }) => typeof child !== 'string') : children)}\n </Block>\n )\n const classed = className === undefined || ownClasses.has(node.type) ? block : <div className={className}>{block}</div>\n // A block with a fallback, such as a Graph's, draws it where the block cannot draw, as a custom component's does\n if (!node.fallback) return classed\n return (\n <CustomBoundary name={node.type} resetKey={node} fallback={<>{renderChildren(placed(node.fallback, at, 'fallback'))}</>}>\n {classed}\n </CustomBoundary>\n )\n\n}\n"],"file":"render-node-p5OrHoJa.js","debugId":"29e4eac7-a096-4dc6-b8a9-191ad8743cbb"}